cc-safety-net 2.0.9 → 2.0.11
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/README.md +34 -36
- package/dist/amp/cc-safety-net/index.ts +42 -42
- package/dist/bin/cc-safety-net.js +103 -105
- package/dist/chunks/index-9dxxkq16.js +62 -0
- package/dist/index.js +1 -1
- package/dist/openclaw/cc-safety-net/index.js +42 -42
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunks/index-tdm5076r.js +0 -62
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import{randomBytes as Op}from"node:crypto";import{closeSync as ji,constants as $n,fstatSync as Ui,fsyncSync as Dp,lstatSync as vt,mkdirSync as bl,openSync as Sl,readdirSync as Vi,readFileSync as Mp,realpathSync as Ot,renameSync as Np,rmdirSync as Lp,statSync as Hi,unlinkSync as qi,writeFileSync as Wp}from"node:fs";import{isAbsolute as vl,join as on,normalize as Fp,parse as Rl,relative as Ki,resolve as Zi,sep as Un}from"node:path";var Gp=Symbol("PolicyFilesystemScope"),zp=Symbol("PolicyFilesystemTarget"),El=$n.O_NOFOLLOW??0;class N extends Error{constructor(e){super(`Unable to access ${e} filesystem safely.`);this.name="PolicyFilesystemError"}}function we(e,t){return{[Gp]:!0,root:Zi(e),label:t}}function Hn(e,t){let n=Fp(t);if(t===""||vl(t)||n===".."||n.startsWith(`..${Un}`))throw new N(e.label);return{[zp]:!0,scope:e,relativePath:n,path:on(e.root,n)}}function ie(e,t){let n=Ki(e.root,Zi(t));return Hn(e,n)}function Br(e,t="rules policy"){let n=Zi(e),r=Rl(n).dir;return Hn(we(r,t),Ki(r,n))}function at(e){try{if(!ae(e,!1).exists)return null;let n=Sl(e.path,$n.O_RDONLY|El);try{let r=Ui(n);if(!r.isFile())throw new N(e.scope.label);let o=Mp(n,"utf-8"),i=vt(e.path);if(!i.isFile()||i.isSymbolicLink()||r.dev!==i.dev||r.ino!==i.ino)throw new N(e.scope.label);return ae(e,!1),o}finally{ji(n)}}catch(t){Rt(e.scope.label,t)}}function xl(e,t,n=384,r){let o=`${e.path}.${Op(8).toString("hex")}.tmp`,i=null;try{Up(e),ae(e,!0),i=Sl(o,$n.O_CREAT|$n.O_EXCL|$n.O_WRONLY|El,n);let s=Ui(i);if(!s.isFile())throw new N(e.scope.label);Wp(i,t,"utf-8"),Dp(i);let a=Ui(i);if(!a.isFile()||a.dev!==s.dev||a.ino!==s.ino)throw new N(e.scope.label);ji(i),i=null,ae(e,!0),jp(e,o,a.dev,a.ino),Np(o,e.path),r?.(e.path),ae(e,!1)}catch(s){if(i!==null)qp(i);Kp(o),Rt(e.scope.label,s)}}function wl(e,t){if(e.path===t.path)return!0;try{if(!ae(e,!1).exists||!ae(t,!1).exists)return!1;return Ot(e.path)===Ot(t.path)}catch(n){if(n instanceof N)throw n;throw new N(e.scope.label)}}function $p(e){try{if(!ae(e,!1,"directory").exists)return null;let n=Vi(e.path);return ae(e,!1,"directory"),n}catch(t){Rt(e.scope.label,t)}}function sP(e){let t=$p(e);if(!t)return null;try{let n=t.map((r)=>{let o=Hn(e.scope,on(e.relativePath,r)),i=vt(o.path);if(i.isSymbolicLink()||!i.isFile()&&!i.isDirectory())throw new N(e.scope.label);return Ur(kl(e.scope),Ot(o.path),e.scope.label),{name:r,kind:i.isDirectory()?"directory":"file"}});return ae(e,!1,"directory"),n}catch(n){Rt(e.scope.label,n)}}function aP(e){try{if(!ae(e,!0).exists)return;qi(e.path),ae(e,!0)}catch(t){Rt(e.scope.label,t)}}function lP(e){try{Al(e,e.relativePath.split(Un))}catch(t){Rt(e.scope.label,t)}}function cP(e){try{if(!Bp(e))return;Pl(e),ae(e,!0,"directory")}catch(t){Rt(e.scope.label,t)}}function Bp(e){try{if(!ae(e,!0,"directory").exists)return!1;return _l(e),!0}catch(t){Rt(e.scope.label,t)}}function ae(e,t,n="file"){let r=Yi(e.scope);if(!r)return{exists:!1};let o=e.relativePath.split(Un);for(let i of o.keys()){let s=on(e.scope.root,...o.slice(0,i+1)),a=Bn(s);if(!a){if(i===o.length-1&&t)return{exists:!1};return{exists:!1}}if(a.isSymbolicLink())throw new N(e.scope.label);if(i<o.length-1&&!a.isDirectory())throw new N(e.scope.label);if(i===o.length-1&&(n==="file"?!a.isFile():!a.isDirectory()))throw new N(e.scope.label);Ur(r,Ot(s),e.scope.label)}return{exists:!0}}function _l(e){for(let t of Vi(e.path)){let n=Hn(e.scope,on(e.relativePath,t)),r=vt(n.path);if(r.isSymbolicLink()||!r.isDirectory()&&!r.isFile())throw new N(e.scope.label);if(r.isDirectory())_l(n)}ae(e,!1,"directory")}function Pl(e){for(let t of Vi(e.path)){let n=Hn(e.scope,on(e.relativePath,t)),r=vt(n.path);if(r.isSymbolicLink())throw new N(e.scope.label);if(r.isDirectory()){Pl(n);continue}if(!r.isFile())throw new N(e.scope.label);qi(n.path)}Lp(e.path)}function Up(e){Al(e,e.relativePath.split(Un).slice(0,-1))}function Al(e,t){Hp(e.scope);let n=kl(e.scope);for(let r of t.keys()){let o=on(e.scope.root,...t.slice(0,r+1));if(!Bn(o))bl(o,{mode:448});let s=vt(o);if(!s.isDirectory()||s.isSymbolicLink())throw new N(e.scope.label);Ur(n,Ot(o),e.scope.label)}}function Hp(e){if(Bn(e.root)){if(!Hi(e.root).isDirectory())throw new N(e.label);return}let t=[],n=e.root;while(!Bn(n)){t.unshift(n);let r=Rl(n).dir;if(r===n)throw new N(e.label);n=r}if(!Hi(n).isDirectory())throw new N(e.label);for(let r of t){bl(r,{mode:448});let o=vt(r);if(!o.isDirectory()||o.isSymbolicLink())throw new N(e.label)}}function Yi(e){if(!Bn(e.root))return null;if(!Hi(e.root).isDirectory())throw new N(e.label);return Ot(e.root)}function kl(e){let t=Yi(e);if(!t)throw new N(e.label);return t}function jp(e,t,n,r){let o=vt(t);if(!o.isFile()||o.isSymbolicLink()||o.dev!==n||o.ino!==r)throw new N(e.scope.label);let i=Yi(e.scope);if(!i)throw new N(e.scope.label);Ur(i,Ot(t),e.scope.label)}function Ur(e,t,n){let r=Ki(e,t);if(r===".."||r.startsWith(`..${Un}`)||vl(r))throw new N(n)}function Bn(e){try{return vt(e)}catch(t){if(Vp(t)&&t.code==="ENOENT")return null;throw t}}function Rt(e,t){if(t instanceof N)throw t;throw new N(e)}function Vp(e){return e instanceof Error&&"code"in e}function qp(e){try{ji(e)}catch{}}function Kp(e){try{qi(e)}catch{}}import{homedir as Qp}from"node:os";import{dirname as Ke,isAbsolute as eg,join as Me,relative as tg,resolve as Ze,sep as ng}from"node:path";var _e=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,Hr="rulebook.json",jr=".cc-safety-net/rules";var Tl=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,Zp=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,Yp=/^[A-Za-z0-9._-]+$/,Xp=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Jp="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Xi=new RegExp(`^${Xp}/(${_e.source.slice(1,-1)})/${Jp}$`);function Il(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function jn(e){if(an(e))try{return sn(e),null}catch(t){return t instanceof Error?t.message:String(t)}return _e.test(e)?null:`Local rulebook sources must be bare names matching ${_e}: ${e}`}function sn(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(Tl);if(!t?.[1]||!t[2]||!t[3])throw Error(`Invalid GitHub rulebook source: ${e}`);let[n,r,...o]=t[3].split("/");if(!n||!Yp.test(n))throw Error(`GitHub rulebook refs must be a single path segment: ${e}`);if(!r||o.length>0||!_e.test(r))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);return{owner:t[1],repo:t[2],ref:n,path:Il(r),name:r}}function Ol(e){return Zp.test(e)}function an(e){return Tl.test(e)}function Ji(e){if(!_e.test(e))throw Error(`Local rulebook sources must be bare names matching ${_e}: ${e}`)}var Ml="rule.json",Vr="policy.json",Nl="rule.lock",rg="config.json",Ll=".cc-safety-net",og="rules",Dl="cache",ig="CC_SAFETY_NET_HOME",Ne="`cc-safety-net rule sync`";function sg(e){return Ze(e??process.cwd(),jr)}function Wl(e){return Me(sg(e),Ml)}function lt(e){return e?.userConfigDir??(e?.userConfigPath?Ke(e.userConfigPath):Me(ag(),og))}function ag(){let e=process.env[ig];return e?Ze(e):Me(Qp(),Ll)}function Fl(e){return Me(lt(e),Ml)}function yP(e){return Me(lt(e),Nl)}function Dt(e){return Me(Ke(e),Nl)}function CP(e={}){return Me(Ke(lt(e)),rg)}function bP(e={}){return Ze(e.cwd??process.cwd(),".safety-net.json")}function Gl(e){let t=e.userConfigPath??Fl(e),n=e.projectConfigPath??Wl(e.cwd),r=zl(t,e),o=$l(n,e);return{userConfigPath:t,projectConfigPath:n,userLockPath:Dt(t),projectLockPath:Dt(n),userScope:r,projectScope:o,userConfigTarget:ie(r,t),projectConfigTarget:ie(o,n),userLockTarget:ie(r,Dt(t)),projectLockTarget:ie(o,Dt(n))}}function SP(e){let t=e.global?e.userConfigPath??Fl(e):e.projectConfigPath??Wl(e.cwd),n=e.global?zl(t,e):$l(t,e),r=Dt(t);return{configDir:Ke(t),configPath:t,lockPath:r,filesystemScope:n,configTarget:ie(n,t),lockTarget:ie(n,r)}}function zl(e,t){let n=t.userConfigPath?Ke(Ke(Ze(t.userConfigPath))):Ke(Ze(t.userConfigDir??lt(t)));return we(n,"user policy")}function $l(e,t){let n=Ze(t.cwd??process.cwd()),r=Ze(e),o=tg(n,r);if(o!==".."&&!o.startsWith(`..${ng}`)&&!eg(o))return we(n,"project policy");return we(Ke(Ke(r)),"project policy")}function Bl(e){if(e.kind==="github"&&e.display_ref)return`${e.owner}/${e.repo}#${e.display_ref}/${e.name}`;return e.spec}function qr(e,t){let n=e.digest.startsWith("sha256:")?e.digest.slice(7):e.digest;return Me(Ul(t),"rulebooks",`${lg(e)}--${n.slice(0,12)}`,Hr)}function vP(e){return Me(Ul(e),"rulebooks")}function Kr(e,t){let n=t;return{cacheConfigDir:e,cwd:t.cwd,global:n.global}}function lg(e){return(e.kind==="github"&&e.display_ref?`${e.owner}/${e.repo}#${e.display_ref}/${e.name}`:e.spec).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"rulebook"}function Ul(e){let t=e?.cacheConfigDir??lt(e),n=e;if(n&&!n.global&&n.cwd&&Ze(t)===Ze(n.cwd))return Me(Ze(n.cwd),Ll,Dl);return Me(Ke(t),Dl)}import{lstatSync as Hl,readdirSync as cg,readFileSync as Kl,rmdirSync as ug,statSync as jl,unlinkSync as dg,utimesSync as mg,writeFileSync as fg}from"node:fs";import{dirname as pg,join as ln}from"node:path";var Zr=30,Qi=1,es=365;function Yr(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var ns=86400000,gg=".last-prune",hg=/^\d{4}-\d{2}$/,yg=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Vl=(e)=>Math.floor(e/ns);function Cg(e){try{let t=ln(pg(lt(e)),Vr),n=JSON.parse(Kl(t,"utf-8"));return Yr(n?.audit?.retention_days)}catch{return Zr}}function Zl(e,t=()=>new Date){try{let n=t().getTime();if(!jl(e,{throwIfNoEntry:!1})?.isDirectory())return;let r=ln(e,gg),o=jl(r,{throwIfNoEntry:!1})?.mtimeMs;if(o!==void 0&&Vl(o)===Vl(n))return;let i=n-Cg()*ns,s=new Date(n).toISOString().slice(0,7);for(let a of ts(e)){if(a.isDirectory()){bg(ln(e,a.name),i,s);continue}if(a.isFile()&&a.name.endsWith(".jsonl"))Sg(ln(e,a.name),i)}fg(r,"",{mode:384}),mg(r,n/1000,n/1000)}catch{}}function bg(e,t,n){for(let r of ts(e)){if(!r.isDirectory()||!hg.test(r.name))continue;let o=ln(e,r.name);for(let i of ts(o)){if(!i.isFile())continue;let s=yg.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+ns;if(!Number.isFinite(a)||a>=t)continue;Yl(ln(o,i.name))}if(r.name!==n)ql(o)}ql(e)}function Sg(e,t){try{let n=Hl(e);if(n.mtimeMs>=t)return;let r=Kl(e,"utf-8").split(`
|
|
2
|
+
`).filter((o)=>o.trim()).map(vg);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(Hl(e).mtimeMs!==n.mtimeMs)return;Yl(e)}catch{}}function vg(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function ts(e){try{return cg(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Yl(e){try{dg(e)}catch{}}function ql(e){try{ug(e)}catch{}}import{randomBytes as _g}from"node:crypto";import{appendFileSync as Pg,mkdirSync as Ag}from"node:fs";import{homedir as kg,userInfo as Tg}from"node:os";import{isAbsolute as Ig,join as rs}from"node:path";var Rg=[/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bglpat-[A-Za-z0-9_-]{20,}\b/g,/\bxox[abeprs]-[A-Za-z0-9-]{20,}\b/g,/\bnpm_[A-Za-z0-9_]{20,}\b/g,/\bpypi-[A-Za-z0-9_-]{20,}\b/g,/\b[rs]k_(?:live|test)_[A-Za-z0-9_]{20,}\b/g,/\bsk-[A-Za-z0-9_-]{20,}\b/g,/\bsk_[A-Za-z0-9]{20,}\b/g,/\bgsk_[A-Za-z0-9]{52,}\b/g,/\bxai-[A-Za-z0-9_-]{80,}\b/g,/\bpplx-[A-Za-z0-9_-]{20,}\b/g,/\bbastn_[A-Za-z0-9]{16,}\b/g,/\btgp_v1_[A-Za-z0-9_-]{43,}\b/g,/\bflp_[A-Za-z0-9]{10,}\b/g,/\bwfr_[A-Za-z0-9]{20,}\b/g,/\bfwp?_[A-Za-z0-9_-]{20,}\b/g,/\btp-[A-Za-z0-9_-]{20,}\b/g,/\bpsk-[A-Za-z0-9_-]{8,}-[A-Za-z0-9_-]{8,}\b/g,/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/g];function ct(e){let t=e.replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_DSN|CONNECTION_STRING)=("[^"]*"|'[^']*'|[^\s]+(?:\s+[A-Z_][A-Z0-9_]*=[^\s]+)*)/gi,"$1=<redacted>").replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_(?:URL|URI|CONNECTION_STRING))=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIALS)[A-Z0-9_]*)=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>");return Xl(t)}function Xl(e){let t=e.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi,"<redacted>").replace(/((?:(['"])(?:authorization|cookie|x-api-key|api-key)\2|(?:authorization|cookie|x-api-key|api-key))\s*:\s*)(['"])(?:\\[^\r\n]|(?!\3)[^\\\r\n])*\3/gi,"$1$3<redacted>$3").replace(/(['"]?\s*(?:authorization|cookie|x-api-key|api-key)\s*:(?!\s*(?:"<redacted>"|'<redacted>'))\s*)([^'"\r\n]+)(['"]?)/gi,"$1<redacted>$3").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s@/]+)@/gi,"$1<redacted>:<redacted>@").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+)@/gi,"$1<redacted>@").replace(/(^|[\s?&;|])((?:x-amz-signature|x-goog-signature|sig|signature)=)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^&#\s'"`;|<>()]*)/gi,"$1$2<redacted>").replace(/(^|\s)((?:-u|--user)(?:\s+|=))([^\s:]+):([^\s]+)/g,"$1$2<redacted>:<redacted>");for(let n of Rg)t=t.replace(n,"<redacted>");return t.replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"<redacted>").replace(/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,"<redacted>")}function Eg(e){return Jl(e).reduceRight((n,r)=>`${n.slice(0,r.valueStart)}<redacted>${n.slice(r.valueEnd)}`,e)}function TP(e){return Xl(Eg(e))}function IP(e){return Jl(e).map((t)=>e.slice(t.valueStart,t.valueEnd))}function OP(e){return/[A-Za-z_][A-Za-z0-9_]*=/.test(e)}function Jl(e){let t=[],n=/[A-Za-z_][A-Za-z0-9_]*=/g;for(let r of e.matchAll(n)){let o=r.index,i=e[o-1];if(o>0&&i&&!/[\s"'([{]/.test(i))continue;let s=o+r[0].length;if(s>=e.length)continue;t.push({valueStart:s,valueEnd:xg(e,s)})}return t}function xg(e,t){if(e.startsWith("$(",t))return wg(e,t);let n=e[t];if(n==='"'||n==="'"){for(let o=t+1;o<e.length;o++)if(n==='"'&&e[o]==="\\")o++;else if(e[o]===n)return o+1}let r=t;while(r<e.length&&!/\s/.test(e[r]??""))r++;return r}function wg(e,t){let n=0,r;for(let o=t;o<e.length;o++){let i=e[o];if(r){if(r==='"'&&i==="\\")o++;else if(i===r)r=void 0;continue}if(i==='"'||i==="'"){r=i;continue}if(i==="$"&&e[o+1]==="("){n++,o++;continue}if(i!==")")continue;if(n--,n===0)return o+1}return e.length}var Og="2.0.11",Dg=1e4,Mg=2000,Ng=256,Lg=32768;function Wg(e){let t=e.trim();if(!t)return null;let n=t.replace(/[^A-Za-z0-9_.-]+/g,"_");if(n=n.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!n||n==="."||n==="..")return null;return n}function Fg(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function os(e,t,n,r,o,i={}){let s=Wg(e);if(!s)return;let a=i.homeDir??Ql();if(!a)return;let l=Gg(a);if(!l)return;try{let c=(i.now??(()=>new Date))().toISOString(),u=Xr(ct(t),i.failureStage?Number.POSITIVE_INFINITY:Dg),m=Xr(ct(n),Mg),f=i.toolName?Xr(ct(i.toolName),Ng):void 0,d=o===null?void 0:Xr(ct(o),Lg),p=rs(l,Fg(d?.value??null),c.slice(0,7));Ag(p,{recursive:!0,mode:448});let g=rs(p,`${c.slice(0,10)}-${s}.jsonl`),y={ts:c,id:(i.createId??(()=>_g(8).toString("hex")))(),v:Og,sessionId:s,decision:i.decision??"deny",agent:i.agent,shape:i.shape,level:i.level,configFallback:i.configFallback,toolName:f?.value,command:u.value,segment:m.value,...u.truncated||m.truncated||f?.truncated||d?.truncated?{truncated:!0}:{},reason:r,ruleId:i.ruleId,intent:i.intent,failureStage:i.failureStage,errorCode:i.errorCode,cwd:d?.value??null};Pg(g,`${JSON.stringify(y)}
|
|
3
|
+
`,{encoding:"utf-8",mode:384}),Zl(l,i.now)}catch{}}function Xr(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function Ql(e=process.env.CC_SAFETY_NET_AUDIT_HOME||process.env.HOME){let t=e||kg()||Tg().homedir;return t&&Ig(t)?t:null}function Gg(e=Ql()){return e?rs(e,".cc-safety-net","logs"):null}function tc(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=ec(e);return{decision:"allow",command:a,segment:a,reason:"allowed",cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{}}}let i=t.decision.evidence.find((a)=>a.kind==="command"),s=i?.command??(r?ec(e):"");return{decision:"deny",command:s,segment:i?.segment??s,reason:t.decision.reason,cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{},ruleId:t.decision.ruleId,intent:t.decision.intent,failureStage:o?.stage,errorCode:o?.errorCode}}function ec(e){return"command"in e?e.command??"":""}function nc(e,t,n){if(!e)return;let r;try{r=t()}catch{return}if(typeof r!=="string"||!r.trim())return;os(r,e.command,e.segment,e.reason,e.cwd,{homeDir:n.homeDir,decision:e.decision,agent:n.agent,shape:n.shape,level:e.level,configFallback:e.configFallback,toolName:e.toolName,ruleId:e.ruleId,intent:e.intent,failureStage:e.failureStage,errorCode:e.errorCode})}function UP(e,t,n){let r;try{r=t()}catch{return}if(typeof r!=="string"||!r.trim())return;os(r,e.command??"",e.segment??e.command??"",e.reason,n.cwd??null,{homeDir:n.homeDir,decision:"deny",agent:n.agent,shape:n.shape,toolName:n.toolName??e.toolName,ruleId:e.ruleId,intent:e.intent})}var Et="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",ut="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",rc="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.",oc="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Jr="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";function sc(e){let{reason:t,command:n,segment:r,toolName:o}=e,i=e.maxLen??200,s=e.redact??((l)=>l),a=`BLOCKED by CC Safety Net
|
|
4
|
+
|
|
5
|
+
Reason: ${s(t)}`;if(e.ruleId)a+=`
|
|
6
|
+
|
|
7
|
+
Rule: ${e.ruleId}`;if(o)a+=`
|
|
8
|
+
|
|
9
|
+
Tool: ${o}`;if(n){let l=s(n);a+=`
|
|
10
|
+
|
|
11
|
+
Command: ${ic(l,i)}`}if(r&&r!==n){let l=s(r);a+=`
|
|
12
|
+
|
|
13
|
+
Segment: ${ic(l,i)}`}if(e.configWarning)a+=`
|
|
14
|
+
|
|
15
|
+
Config warning: ${s(e.configWarning)}`;return a+=`
|
|
16
|
+
|
|
17
|
+
${zg(e.intent??"manual_only")}`,a}function zg(e){switch(e){case"hard_stop":return"Do not retry this operation or attempt any workaround (other tools, flags, or paths). Report the block to the user and continue with the rest of the task.";case"use_alternative":return"Do not retry the blocked form. Continue the task using the safer alternative described above.";case"scope_down":return"Retry with a narrower, explicit target as described above. Escalate to the user if the broad operation is truly required.";case"manual_only":return"If this operation is truly needed, ask the user for explicit permission and have them run the command manually.";case"stop_and_explain":return"Do not brute-force variants. Simplify or restructure the command so it can be analyzed, or report the block to the user."}}function ic(e,t){return e.length>t?`${e.slice(0,t)}...`:e}function YP(e,t){if(e.decision.kind!=="deny")return;let n=t.includeEvidence?e.decision.evidence.find((r)=>r.kind==="command"):void 0;return{reason:e.decision.reason,ruleId:e.decision.ruleId,intent:e.decision.intent,command:n?.command,segment:n?.segment,toolName:t.toolName,...e.configFallback?{configWarning:e.configFallback.reason}:{}}}function XP(e={}){return{reason:Jr,intent:"stop_and_explain",command:e.command,segment:e.segment??e.command,toolName:e.toolName}}function JP(e){return sc({...e,redact:ct})}function QP(e){return ct(e instanceof Error?e.message:String(e))}import{basename as $g,dirname as Bg,join as is}from"node:path";var cn=Object.freeze({maxEnvironmentExpansionDepth:64,maxMissingSuffixComponents:256,maxRealpathAttempts:16384,maxProcessedCandidateBytes:4194304});class le extends Error{name="PathCanonicalizationLimitError";constructor(){super("Path canonicalization work limit exceeded.")}}function Vn(){return{realpathAttempts:0,processedCandidateBytes:0,resolvedPaths:new Map}}function Mt(e){return{...Vn(),environment:e}}var Qr=new Set(["CC_SAFETY_NET_HOME","CLAUDE_CONFIG_DIR","CODEX_HOME","COPILOT_HOME","GEMINI_CLI_HOME","HOME","KIMI_CODE_HOME","KIMI_SHARE_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","ProgramData","TMPDIR","XDG_CONFIG_HOME","XDG_DATA_HOME"]);function eo(e,t){return ss(e,0,t)}function ss(e,t,n){let r="",o=0;while(o<e.length){if(e[o]!=="$"){r+=e[o],o++;continue}if(e[o+1]==="{"){let s=as(e,o+2),a=Ug(e,o,t);if(a===null){if(Qr.has(s))throw new le;r+=e.slice(o);break}let l=e.slice(o,a+1);r+=Hg(l,t,n),o=a+1;continue}let i=as(e,o+1);if(!i){r+="$",o++;continue}r+=ls(i,n)??`$${i}`,o+=i.length+1}return r}function Ug(e,t,n){let r=1;for(let o=t+2;o<e.length;o++){if(e[o]==="\\"){o++;continue}if(e[o]==="$"&&e[o+1]==="{"){if(r++,n+r>cn.maxEnvironmentExpansionDepth)throw new le;o++;continue}if(e[o]!=="}")continue;if(r--,r===0)return o}return null}function Hg(e,t,n){let r=e.slice(2,-1),o=as(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return ls(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(Qr.has(o))throw new le;return e}if(!Qr.has(o))return e;if(s.endsWith("="))throw new le;let a=ls(o,n),l=s.startsWith(":")?a!==null&&a!=="":a!==null;if(s.endsWith("?")&&!l)throw new le;if(s.endsWith("-")||s.endsWith("?"))return l?a??"":ss(i.slice(s.length),t+1,n);return l?ss(i.slice(s.length),t+1,n):""}function as(e,t){if(!/[A-Za-z_]/.test(e[t]??""))return"";let n=t+1;while(/[A-Za-z0-9_]/.test(e[n]??""))n++;return e.slice(t,n)}function U(e,t,n=Vn()){if(!e)return e;let r=n.resolvedPaths.get(e);if(r!==void 0)return r;let o=[],i=e;while(!0){if(n.realpathAttempts++,n.processedCandidateBytes+=Buffer.byteLength(i),n.realpathAttempts>cn.maxRealpathAttempts||n.processedCandidateBytes>cn.maxProcessedCandidateBytes)throw new le;let s=t.realpath(i);if(s!==null){let l=o.length===0?s:is(s,...o.reverse());return n.resolvedPaths.set(e,l),l}let a=Bg(i);if(a===i){let l=o.length===0?i:is(i,...o.reverse());return n.resolvedPaths.set(e,l),l}if(o.length>=cn.maxMissingSuffixComponents){let l=is(i,...o.reverse());return n.resolvedPaths.set(e,l),l}o.push($g(i)),i=a}}function ac(e,t,n){let r=n.resolvedPaths.get(e);if(r!==void 0)return r;if(n.realpathAttempts++,n.processedCandidateBytes+=Buffer.byteLength(e),n.realpathAttempts>cn.maxRealpathAttempts||n.processedCandidateBytes>cn.maxProcessedCandidateBytes)throw new le;let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function ls(e,t){if(!Qr.has(e))return null;if(e==="HOME")return t.env.get("HOME")??t.home;return t.env.get(e)??null}var jg=["git.ssh-env","git.alias-config","git.checkout-force","git.checkout-double-dash","git.checkout-ref-path","git.checkout-pathspec-from-file","git.checkout-ambiguous","git.switch-discard-changes","git.switch-force","git.restore-worktree","git.restore-unstaged","git.reset-hard","git.reset-merge","git.clean-force","git.rm-force","git.push-force","git.push-delete","git.push-mirror","git.branch-force-delete","git.rebase-abort","git.merge-abort","git.tag-delete","git.reflog-delete","git.stash-drop","git.stash-clear","git.worktree-remove-force","rm.recursive-force-root-or-home","rm.git-metadata","rm.recursive-force-dynamic-target","rm.recursive-force-home-cwd","rm.recursive-force-cwd-self","rm.recursive-force-outside-cwd","rm.recursive-force-paranoid","powershell.remove-item-root-or-home","powershell.remove-item-recursive-force-root-or-home","powershell.remove-item-git-metadata","powershell.remove-item-recursive-force-dynamic-target","powershell.remove-item-recursive-force-home-cwd","powershell.remove-item-recursive-force-cwd-self","powershell.remove-item-recursive-force-outside-cwd","powershell.remove-item-recursive-force-paranoid","powershell.remove-item-pipeline-dynamic-target","find.delete","find.delete-git-metadata","find.exec-rm-recursive-force","dd.device-write","mkfs.device","shred.target","interpreter.dangerous-command","interpreter.one-liner-paranoid","awk.system-dynamic","xargs.rm-recursive-force-dynamic","xargs.shell-dynamic","parallel.rm-recursive-force-dynamic","parallel.shell-dynamic","parallel.command-stream-dynamic","shell.dynamic-structure","shell.dynamic-executable","raw-text.dangerous-command"],to=new Set(jg),no=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores after --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"find.delete",category:"Filesystem",label:"find delete",description:"Blocks unsafe find -delete operations.",example:"find . -delete",intent:"scope_down"},{id:"find.delete-git-metadata",category:"Filesystem",label:"find delete Git metadata",description:"Blocks find -delete operations selecting protected Git metadata and hooks.",example:"find .git -delete",intent:"hard_stop",catastrophic:!0},{id:"find.exec-rm-recursive-force",category:"Filesystem",label:"find exec rm -rf",description:"Blocks find -exec rm -rf operations.",example:"find . -exec rm -rf {} +",intent:"scope_down"},{id:"dd.device-write",category:"Filesystem",label:"dd device write",description:"Blocks dd writing to a /dev device.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"mkfs device format",description:"Blocks mkfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],Vg=new Map(no.map((e)=>[e.id,e.intent])),lc=new Set(no.filter((e)=>e.catastrophic).map((e)=>e.id));function b(e,t){return{id:e,reason:t,intent:Vg.get(e)??"manual_only"}}function k(e,t){if(!e)return null;if(lc.has(e.id))return e;if(t?.destructiveCommandProtectionEnabled===!1)return null;let n=t?.effectiveDestructiveCommandRules[e.id];return n&&!n.enabled?null:e}function Q(e,t,n){if(lc.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function cs(e,t){return Object.freeze(Object.fromEntries(no.map((n)=>{let r=n.activationCapability?t[n.activationCapability]:void 0,o=r?.enabled??!0,i=e.destructiveCommandRuleOverrides[n.id],s=n.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...i?{override:i}:{}}:e.destructiveCommandProtectionEnabled?i?{enabled:i==="on",inheritedEnabled:o,changesInherited:i==="on"!==o,source:"rule_override",...n.activationCapability?{activationCapability:n.activationCapability}:{},override:i}:{enabled:o,inheritedEnabled:o,changesInherited:!1,source:r?.source??"built_in_default",...n.activationCapability?{activationCapability:n.activationCapability}:{}}:{enabled:!1,inheritedEnabled:o,changesInherited:!1,source:"master_disabled",...n.activationCapability?{activationCapability:n.activationCapability}:{},...i?{override:i}:{}};return[n.id,Object.freeze(s)]})))}function cc(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:cs(e,t)})}var ro=10,un=20,Nt=/^[a-zA-Z][a-zA-Z0-9_-]*$/,dn=256,ee=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),uc=new Set(["python","python3","python2","node","ruby","perl"]),dc=/^python(?:[23](?:\.\d+)*)?$/,oo=new Set(["echo","printf","cat","head","tail","less","more","grep","rg","ag","ack","sed","awk","cut","tr","sort","uniq","wc","tee","man","help","info","type","which","whereis","whatis","apropos","file","stat","ls","ll","dir","tree","pwd","date","cal","uptime","whoami","id","groups","hostname","uname","env","printenv","set","export","alias","history","jobs","fg","bg","test","true","false","read","return","exit","break","continue","shift","wait","trap","basename","dirname","realpath","readlink","md5sum","sha256sum","base64","xxd","od","hexdump","strings","diff","cmp","comm","join","paste","column","fmt","fold","nl","pr","expand","unexpand","rev","tac","shuf","seq","yes","sleep","logger","write","wall","mesg","notify-send"]);import{types as qg}from"node:util";var Kg=new Set(["applypatch","patch"]),Zg=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),Yg=new Set(["grep","grepsearch","rg"]),Xg=new Set(["find","findbyname","glob"]),Jg=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),Qg=new Set(["command","diff","input","patch","patchtext"]),mc=new TextEncoder,eh=new TextDecoder,th=/\s/,nh=64;class dt extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var qn=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function yc(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function so(e){return Jg.has(yc(e))}function rh(e){let t=yc(e);if(Kg.has(t))return"patch";if(Yg.has(t))return"grep";if(Xg.has(t))return"glob";if(Zg.has(t))return"path";return"unknown"}function Zn(e){if(!e||typeof e!=="object")return;Rc(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)Ye();return}if(t.get||t.set)Ye();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function fs(e,t){return Cc(e,t,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Cc(e,t,n,r){let o=vc(e,n,r);if(!o)return[];let i=o.entries.flatMap(([s,a])=>{let l=Cc(a,t,n,r+1);return typeof a==="string"&&t.has(bc(s))?[a]:l});return n.ancestors.delete(o.object),i}function bc(e){return e.replace(/-/g,"_").toLowerCase()}function ps(e){return Sc(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(ih)}function Sc(e,t,n,r){let o=vc(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>Sc(a,o.array?t:Qg.has(bc(s)),n,r+1));return n.ancestors.delete(o.object),i}function oh(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>qn.maxDepth||t.nodes>qn.maxNodes)Ye();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>qn.maxStringBytes||t.stringBytes>qn.maxAggregateStringBytes)Ye()}function vc(e,t,n){if(oh(e,t,n),!e||typeof e!=="object")return null;let r=Rc(e);if(t.ancestors.has(e))Ye();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>qn.maxKeys)Ye();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)Ye();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function Rc(e){if(qg.isProxy(e))Ye();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)Ye();return t}function Ye(){throw new dt}function ih(e){let t=[],n=e.split(/\r?\n/),r=!1,o=!1,i=null,s=null,a=()=>{o=!1,i=null,s=null};for(let l=0;l<n.length;l++){let c=n[l]??"";if(c==="*** Begin Patch"){r=!0,a();continue}if(c==="*** End Patch"){r=!1,a();continue}if(c.startsWith("@@")){let u=sh(c);if(o=!0,i=u?.oldLines??null,s=u?.newLines??null,i===0&&s===0)a();continue}if(o&&i!==null&&s!==null){let u=c.startsWith(" ")||c.startsWith("-")?1:0,m=c.startsWith(" ")||c.startsWith("+")?1:0;if(i=Math.max(0,i-u),s=Math.max(0,s-m),i===0&&s===0)a();continue}if(c.startsWith("*** ")){a(),t.push(...us(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...us(c));continue}if(c.startsWith("--- ")){let u=n[l+1]??"";if(!u.startsWith("+++ "))continue;t.push(...ms(io(c.slice(4),!0),io(u.slice(4),!0))),l++;continue}if(!r)t.push(...us(c))}return t}function sh(e){let t=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(e);if(!t)return null;return{oldLines:Number(t[1]??1),newLines:Number(t[2]??1)}}function us(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return hc(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return hc(n[1]);if(e.startsWith("diff --git "))return ah(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return gc(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return gc(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return ph(i[1]);return[]}function ah(e){let t=lh(e);if(t.length===2&&t[0]&&t[1])return ms(t[0],t[1]);let n=ch(e);return n?ms(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function lh(e){let t=[],n=0;while(n<e.length&&t.length<2){while(Lt(e[n]))n++;if(n>=e.length)break;let r=e[n]==='"'||e[n]==="'"?e[n]:void 0;if(!r){let i=n;while(n<e.length&&!Lt(e[n]))n++;t.push(e.slice(i,n));continue}let o=Ec(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(Lt(e[n]))n++;return n===e.length?t:[]}function ch(e){let t=0;while(t<e.length&&Lt(e[t]))t++;let n=e.length;while(n>t&&Lt(e[n-1]))n--;let r=0,o=t;while(o<n){if(!Lt(e[o])){o++;continue}let i=o;while(o<n&&Lt(e[o]))o++;if(i===t||o===n)continue;if(r++,r>nh)Ye();if(uh(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function uh(e,t,n,r,o){if(ds(e,t,n,r,o))return!0;let i=fc(e,"/",t,n),s=fc(e,"/",r,o);if(i<=t||s<=r)return!1;if(ds(e,t,i,r,s))return!1;return ds(e,i+1,n,s+1,o)}function ds(e,t,n,r,o){if(n-t!==o-r)return!1;for(let i=0;i<n-t;i++)if(e[t+i]!==e[r+i])return!1;return!0}function fc(e,t,n,r){for(let o=n;o<r;o++)if(e[o]===t)return o;return-1}function Lt(e){return e!==void 0&&th.test(e)}function Ec(e,t,n){let r=[],o=t+1;while(o<e.length){let i=e[o]??"";if(i===n)return{value:eh.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...mc.encode(i)),o++;continue}let s=e.slice(o+1),a=/^[0-7]{1,3}/.exec(s)?.[0];if(a){r.push(Number.parseInt(a,8)),o+=a.length+1;continue}r.push(...mc.encode(dh(s[0]??""))),o+=2}return null}function dh(e){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
18
|
+
`,r:"\r",t:"\t",v:"\v"}[e]??e}function mh(e){return Kn(gh(e))}function ms(e,t){if(e==="/dev/null")return pc(t);if(t==="/dev/null")return pc(e);if(e.startsWith("a/")&&t.startsWith("b/"))return[e.slice(2),t.slice(2)].flatMap(Kn);let n=fh(e,t)??(e===t?xc(e):null);return[e,t,...n?[n]:[]].flatMap(Kn)}function pc(e){let t=xc(e);return[e,...t?[t]:[]].flatMap(Kn)}function xc(e){let t=e.indexOf("/");return t>0&&t<e.length-1?e.slice(t+1):null}function fh(e,t){let n=e.indexOf("/"),r=t.indexOf("/");if(n<1||r<1)return null;if(e.slice(0,n)===t.slice(0,r))return null;let o=e.slice(n+1);return o===t.slice(r+1)?o:null}function gc(e){return mh(io(e,!0))}function ph(e){return Kn(io(e,!1))}function io(e,t){let n=e.trim(),r=n[0]==='"'||n[0]==="'"?n[0]:void 0;if(r){let o=Ec(n,0,r);if(o&&(t||n.slice(o.end).trim()===""))return o.value}return t?n.split("\t",1)[0]?.trim()??"":n}function gh(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function Kn(e){return e===""||e==="/dev/null"?[]:[e]}function hc(e){let t=e.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return t===""||t==="/dev/null"?[]:[t]}import{lstatSync as hh,realpathSync as yh}from"node:fs";import{homedir as Ch,tmpdir as bh}from"node:os";var Pe={realpath:(e)=>{try{return yh(e)}catch{return null}},entryKind:(e)=>{let t=hh(e,{throwIfNoEntry:!1});if(!t)return"missing";return t.isSymbolicLink()?"symlink":"present"}};function Wt(){return process.env.HOME||Ch()}function mt(){return{env:new Map(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),home:Wt(),tmpdir:bh(),paths:Pe}}function ao(){return[]}function lo(){return[]}function co(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Sh(e){return Object.freeze({...e,span:Object.freeze(e.span),words:Object.freeze(e.words),redirections:Object.freeze(e.redirections.map((t)=>Object.freeze({...t,span:Object.freeze(t.span),...t.heredoc?{heredoc:Object.freeze({...t.heredoc,bodySpan:Object.freeze(t.heredoc.bodySpan),terminatorSpan:Object.freeze(t.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(e.nested.map((t)=>de(t)))})}function uo(e,t,n){e.push(n),t.reset()}function vh(e,t,n,r,o){if(r<=n)return;e.push({raw:t.slice(n,r),span:{start:n,end:r},provenance:o})}function mo(e){let t=[];return{parts:t,push:(n,r,o)=>vh(t,e,n,r,o)}}function gs(e){let t=e.parts??[{raw:e.raw,span:e.span,provenance:e.provenance}];return Object.freeze({kind:"word",...e,span:Object.freeze(e.span),parts:Object.freeze(t.map((n)=>Object.freeze({...n,span:Object.freeze(n.span)})))})}function mn(e,t,n,r,o,i,s){return gs({text:r,raw:e.slice(t,n),span:{start:t,end:n},provenance:o,quoted:i,...s?{parts:s}:{}})}function de(e){return Object.freeze({...e,span:Object.freeze(e.span),issues:Object.freeze(e.issues.map((t)=>Object.freeze({...t,span:Object.freeze(t.span)}))),nodes:Object.freeze(e.nodes.map((t)=>{if(t.kind==="command")return Sh(t);if(t.kind==="group"||t.kind==="function")return Object.freeze({...t,span:Object.freeze(t.span),body:de(t.body)});return Object.freeze({...t,span:Object.freeze(t.span)})}))})}function hs(e,t,n){if(t>=n||_c(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!_c(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=wc(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=wc(e,s+1,n,'"');r+=l.text,i||=!l.closed,s=l.next;continue}if(a==="\\"){o=!0;let l=e[s+1];if(!l||l===`
|
|
19
|
+
`||l==="\r"){i=!0;break}r+=l,s+=2;continue}if(a==="`"||e.startsWith("$(",s)||e.startsWith("${",s)||e.startsWith("<(",s)||e.startsWith(">(",s))i=!0;r+=a,s++}return{delimiter:r,quoted:o,next:s,span:{start:t,end:s},ambiguous:i}}function ys(e,t,n,r){let o=[],i=t;for(let s of r){let a=i,l=!1;while(i<n){let c=Rh(e,i,n);if((s.stripTabs?c.text.replace(/^\t+/,""):c.text)===s.delimiter){s.attach({body:s.stripTabs?Eh(e.slice(a,i)):e.slice(a,i),delimiter:s.delimiter,quotedDelimiter:s.quotedDelimiter,bodySpan:{start:a,end:i},terminatorSpan:{start:i,end:c.contentEnd}}),i=c.next,l=!0;break}if(c.next<=i)break;i=c.next}if(l)continue;return o.push({code:"unterminated-heredoc",message:`heredoc delimiter ${s.delimiter} was not found`,span:s.declarationSpan}),{next:n,issues:o,terminated:!1}}return{next:i,issues:o,terminated:!0}}function wc(e,t,n,r){let o="",i=t;while(i<n&&e[i]!==`
|
|
20
|
+
`&&e[i]!=="\r"){let s=e[i]??"";if(s===r)return{text:o,next:i+1,closed:!0};if(r==='"'&&s==="\\"&&e[i+1]){let a=e[i+1]??"";o+=["$","`",'"',"\\"].includes(a)?a:`\\${a}`,i+=2;continue}o+=s,i++}return{text:o,next:i,closed:!1}}function _c(e){return/[\s;&|<>)]/u.test(e)||e==="`"}function Rh(e,t,n){let r=t;while(r<n&&e[r]!==`
|
|
21
|
+
`&&e[r]!=="\r")r++;let o=r>=n?n:e[r]==="\r"&&e[r+1]===`
|
|
22
|
+
`?r+2:r+1;return{text:e.slice(t,r),contentEnd:r,next:o}}function Eh(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Ic=new Set(["&&","||","|","|&"]);function Oc(e,t,n){let r={start:0,end:e.length};if(e.length>n.maxInputLength)return de({kind:"program",dialect:t,source:e,span:r,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${n.maxInputLength} UTF-16 code units`,span:r}],nodes:[]});let o=go(e,0,e.length,t,n,{used:0,max:n.maxWords},0);return de({kind:"program",dialect:t,source:e,span:r,status:Co(o.issues,o.limited),issues:o.issues,nodes:o.nodes})}function go(e,t,n,r,o,i,s,a){let l=ao(),c=lo(),u=co(),m=[],f=()=>{if(u.words.length===0&&u.redirections.length===0)return;let p={start:u.start,end:u.end},g=u.words.map((y)=>y.text);uo(l,u,{kind:"command",dialect:r,source:e.slice(p.start,p.end),span:p,words:u.words,redirections:u.redirections,nested:u.nested,displayText:c.length>0&&l.length===0?e.slice(t,n):g.join(" ")})},d=t;while(d<n){let p=e[d];if(!p)break;if(a&&p===a)return f(),Tc(l,c),{nodes:l,issues:c,next:d+1,closed:!0,limited:!1,pendingHeredocs:m};if(yo(p)){if(p===`
|
|
23
|
+
`||p==="\r"){f();let _=p==="\r"&&e[d+1]===`
|
|
24
|
+
`?d+2:d+1,S=l.at(-1);if(S?.kind!=="connector"||!Ic.has(S.operator))l.push(Object.freeze({kind:"connector",operator:e.slice(d,_),span:Object.freeze({start:d,end:_})}));if(m.length>0){let C=ys(e,_,n,m.splice(0));c.push(...C.issues),d=C.next;continue}d=_;continue}d++;continue}if(p==="#"){while(d<n&&e[d]!==`
|
|
25
|
+
`&&e[d]!=="\r")d++;continue}let g=u.start===-1?Bh(e,d,n):void 0;if(g){if(bs(l,c,d),s>=o.maxDepth)return fn(l,c,d,"depth-limit",o.maxDepth);if(!Cs(i))return fn(l,c,d,"word-limit",o.maxWords);let _=go(e,g.braceIndex+1,n,r,o,i,s+1,"}"),S=_.next,C={start:g.braceIndex+1,end:_.closed?S-1:S},P=Pc(e,r,C,_);if(l.push({kind:"function",name:g.name,span:{start:d,end:S},body:P}),c.push(..._.issues),_.pendingHeredocs.length>0||Xn(_.nodes))c.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely",span:{start:d,end:S}});if(m.push(..._.pendingHeredocs),_.limited)return po(l,c,_.next);if(!_.closed)c.push({code:"unclosed-function-body",message:"function body is not closed",span:{start:g.braceIndex,end:S}});d=S;continue}let y=ho(e,d);if(y){if(f(),!zc(l.at(-1)))c.push({code:"unexpected-connector",message:`connector ${y} has no preceding command`,span:{start:d,end:d+y.length}});l.push(Object.freeze({kind:"connector",operator:y,span:Object.freeze({start:d,end:d+y.length})})),d+=y.length;continue}if(p===")"){f(),c.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis",span:{start:d,end:d+1}}),l.push({kind:"unknown",source:p,span:{start:d,end:d+1}}),d++;continue}if((p==="("||p==="{"&&Th(e,d,n))&&u.start===-1){if(bs(l,c,d),s>=o.maxDepth)return fn(l,c,d,"depth-limit",o.maxDepth);let _=p==="("?")":"}",S=go(e,d+1,n,r,o,i,s+1,_),C=S.next,P={start:d+1,end:S.closed?C-1:C},x=Pc(e,r,P,S);if(l.push({kind:"group",style:p==="("?"subshell":"brace",span:{start:d,end:C},body:x}),c.push(...S.issues),S.pendingHeredocs.length>0||Xn(S.nodes))c.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely",span:{start:d,end:C}});if(m.push(...S.pendingHeredocs),S.limited)return po(l,c,S.next);if(!S.closed)c.push({code:p==="("?"unclosed-subshell":"unclosed-brace-group",message:`${p} group is not closed`,span:{start:d,end:C}});d=C;continue}let h=(p==="<"||p===">")&&e[d+1]!=="("?_h(e,d):null;if(h){let _=u.words.at(-1),S=_&&_.span.end===d&&/^[0-9]+$/.test(_.raw)?Number(_.raw):void 0;if(S!==void 0)u.words.pop();let C=S===void 0?d:_?.span.start??d;u.start=u.start===-1?d:u.start;let P=d+h.length;while(P<n&&/[ \t]/.test(e[P]??""))P++;let x=e[P],T=P>d+h.length&&x==="#",O=!x||yo(x)||!!ho(e,P)||x===a||x===")"||T||(x==="<"||x===">")&&e[P+1]!=="(",D=h==="<<"||h==="<<-"?hs(e,P,n):void 0,F=D?{word:mn(e,P,D.next,D.delimiter,"literal",D.quoted),nested:[],issues:[],next:D.next,limited:!1}:!O?Ss(e,P,n,r,o,i,s):void 0;if(F){if(c.push(...F.issues),F.limited)return po(l,c,F.next);if(!Cs(i))return fn(l,c,F.next,"word-limit",o.maxWords)}let oe=F?.next??d+h.length,xe={kind:"redirection",operator:h,span:{start:C,end:oe},...S===void 0?{}:{fd:S},...F?{target:F.word}:{}};if(u.redirections.push(xe),h==="<<"||h==="<<-")if(!D)c.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word",span:{start:d,end:d+h.length}});else{if(D.ambiguous||D.delimiter.length===0)c.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely",span:D.span});m.push({delimiter:D.delimiter,quotedDelimiter:D.quoted,stripTabs:h==="<<-",declarationSpan:{start:C,end:oe},attach:(w)=>{xe.heredoc=w}})}else if(!F)c.push({code:"missing-redirection-target",message:`redirection ${h} requires a target word`,span:{start:d,end:d+h.length}});if(F)u.nested.push(...F.nested);u.end=oe,d=oe;continue}if(u.start===-1)bs(l,c,d);let R=Ss(e,d,n,r,o,i,s);if(c.push(...R.issues),R.limited)return po(l,c,R.next);let E=Dh(u.words)?Fh(e,R.word,i.max-i.used,o.maxDepth,o.maxInputLength):void 0;if(E?.limitCode)return fn(l,c,R.next,E.limitCode,E.limitCode==="word-limit"?o.maxWords:E.limitCode==="depth-limit"?o.maxDepth:o.maxInputLength);let A=E?.words??[R.word];for(let _ of A){if(!Cs(i))return fn(l,c,R.next,"word-limit",o.maxWords);u.words.push(_)}u.start=u.start===-1?d:u.start,u.end=R.next,u.nested.push(...R.nested),d=R.next>d?R.next:d+1}return f(),Tc(l,c),c.push(...Uh(m)),{nodes:l,issues:c,next:d,closed:a===void 0,limited:!1,pendingHeredocs:[]}}function Pc(e,t,n,r){return{kind:"program",dialect:t,source:e.slice(n.start,n.end),span:n,status:Co(r.issues,r.limited),issues:r.issues,nodes:r.nodes}}function Ss(e,t,n,r,o,i,s){let a="",l=t,c=!1,u="literal",m=[],f=[],d=!1;while(l<n){let p=e[l],g=(p==="<"||p===">")&&e[l+1]==="(";if(!p||yo(p)||(p===";"||p==="|"||p==="&")&&ho(e,l)||(p==="<"||p===">")&&!g)break;if(p===")")break;if(p==="'"){c=!0;let h=e.indexOf("'",l+1);if(h===-1||h>=n){a+=e.slice(l+1,n),f.push({code:"unclosed-single-quote",message:"single-quoted word is not closed",span:{start:l,end:n}}),l=n;break}a+=e.slice(l+1,h),l=h+1;continue}if(p==='"'){c=!0;let h=xh(e,l,n,r,o,i,s);if(a+=h.text,m.push(...h.nested),f.push(...h.issues),d||=h.limited,u=Yn(u,h.provenance),l=h.next,d)break;continue}if(e.startsWith("$'",l)){c=!0;let h=Ph(e,l+2,n);if(a+=h.text,f.push(...h.issues),!h.closed)f.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed",span:{start:l,end:n}});l=h.next;continue}if(p==="\\"){let h=e[l+1];if(!h){f.push({code:"trailing-escape",message:"escape has no following character",span:{start:l,end:l+1}}),l++;break}if(h===`
|
|
26
|
+
`){l+=2;continue}a+=h,l+=2;continue}let y=p==="$"||p==="<"||p===">"||p==="`"?vs(e,l,n,r,o,i,s):null;if(y){let h=Dc(y,m,f);if(d||=h.limited,u=Yn(u,h.provenance),l=h.next,d)break;continue}if(p==="$"){let h=Lc(e,l,n,a,u);a=h.text,u=h.provenance,l=h.next;continue}if(p==="*"||p==="?"||p==="[")u=Yn(u,"glob");a+=p,l++}return{word:mn(e,t,l,a,u,c,u==="literal"?void 0:kh(e,t,l)),nested:m,issues:f,next:l,limited:d}}function xh(e,t,n,r,o,i,s){let a="",l="literal",c=[],u=[],m=!1,f=t+1;while(f<n){let d=e[f];if(d==='"')return{text:a,provenance:l,nested:c,issues:u,next:f+1,limited:m};if(d==="\\"&&e[f+1]){let g=e[f+1]??"";if(g===`
|
|
27
|
+
`){f+=2;continue}if(g==="\r"&&e[f+2]===`
|
|
28
|
+
`){f+=3;continue}a+=["$","`",'"',"\\"].includes(g)?g:`\\${g}`,f+=2;continue}if(e.startsWith("$((",f)){let g=Rs(e,f+3,n,"))"),y=g===-1?n:g+2;if(a+=e.slice(f,y),g===-1)u.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:f,end:y}});f=y;continue}let p=vs(e,f,n,r,o,i,s);if(p){let g=Dc(p,c,u);if(f=g.next,m||=g.limited,l=Yn(l,g.provenance),m)return{text:a,provenance:l,nested:c,issues:u,next:f,limited:m};continue}if(d==="$"){let g=Lc(e,f,n,a,l);a=g.text,l=g.provenance,f=g.next;continue}a+=d??"",f++}return u.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:t,end:n}}),{text:a,provenance:l,nested:c,issues:u,next:n,limited:m}}function vs(e,t,n,r,o,i,s){let a=e.startsWith("$((",t),l=e.startsWith("$(",t)&&!a,c=(e.startsWith("<(",t)||e.startsWith(">(",t))&&!0,u=e[t]==="`";if(!a&&!l&&!c&&!u)return null;let m=a?3:u?1:2,f=a?"))":u?"`":")",d=Rs(e,t+m,n,f),p=d===-1?n:d,g=d===-1?n:d+f.length;if(s>=o.maxDepth)return{program:$h(e,t+m,p,r,"depth-limit"),next:g,provenance:a?"arithmetic":"command-substitution"};if(a){let E=[],A=[],_=!1,S=t+m;while(S<p){let C=vs(e,S,p,r,o,i,s+1);if(!C){S++;continue}if(E.push(...C.program.nodes),A.push(...C.program.issues),_||=C.program.status==="limited",S=C.next,_)break}if(d===-1)A.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:t,end:g}});return{program:de({kind:"program",dialect:r,source:e.slice(t+m,p),span:{start:t+m,end:p},status:Co(A,_),issues:A,nodes:E}),next:g,provenance:"arithmetic"}}let y=go(e,t+m,p,r,o,i,s+1),h=d===-1?[{code:a?"unclosed-arithmetic":"unclosed-command-substitution",message:`${e.slice(t,t+m)} substitution is not closed`,span:{start:t,end:g}}]:[],R=(u||c)&&Xn(y.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions",span:{start:t,end:g}}]:[];return{program:de({kind:"program",dialect:r,source:e.slice(t+m,p),span:{start:t+m,end:p},status:Co([...y.issues,...h,...R],y.limited),issues:[...y.issues,...h,...R],nodes:y.nodes}),next:g,provenance:a?"arithmetic":"command-substitution"}}function Dc(e,t,n){return t.push(e.program),n.push(...e.program.issues),{provenance:e.provenance,next:e.next,limited:e.program.status==="limited"}}function Rs(e,t,n,r){if(r==="`"){for(let a=t;a<n;a++)if(e[a]==="\\")a++;else if(e[a]==="`")return a;return-1}let o=1,i={single:!1,double:!1},s=[];for(let a=t;a<n;a++){let l=e[a];if((l===`
|
|
29
|
+
`||l==="\r")&&s.length>0){let u=l==="\r"&&e[a+1]===`
|
|
30
|
+
`?a+2:a+1,m=ys(e,u,n,s.splice(0));if(!m.terminated)return-1;a=m.next-1;continue}let c=Mc(e,a,t,n,i);if(c!==null){a=c;continue}if(!i.double&&e.startsWith("$((",a)){let u=wh(e,a+3,n);if(u===-1)return-1;a=u+1;continue}if(r===")"&&!i.double&&l==="<"&&e[a+1]==="<"&&e[a+2]!=="<"){let u=e[a+2]==="-",m=a+(u?3:2);while(m<n&&/[ \t]/.test(e[m]??""))m++;let f=hs(e,m,n);if(f){s.push({delimiter:f.delimiter,quotedDelimiter:f.quoted,stripTabs:u,declarationSpan:{start:a,end:f.next},attach:()=>{return}}),a=f.next-1;continue}}if(e.startsWith("$(",a)&&!e.startsWith("$((",a)){o++,a++;continue}if(l==="("&&!i.double)o++;if(l===")"&&!i.double){if(o--,o===0)return r==="))"&&e[a+1]!==")"?-1:a}}return-1}function wh(e,t,n){let r=1,o={single:!1,double:!1};for(let i=t;i<n;i++){let s=e[i],a=Mc(e,i,t,n,o);if(a!==null){i=a;continue}if(e.startsWith("$(",i)&&!e.startsWith("$((",i)){r++,i++;continue}if(s==="("&&!o.double)r++;if(s!==")"||o.double)continue;if(r--,r===0)return e[i+1]===")"?i:-1}return-1}function Mc(e,t,n,r,o){let i=e[t];if(i==="\\"&&!o.single)return t+1;if(!o.double&&i==="'")o.single=!o.single;if(!o.single&&i==='"')o.double=!o.double;if(o.single)return t;if(o.double||i!=="#"||!Hh(e,t,n))return null;let s=t;while(s+1<r&&e[s+1]!==`
|
|
31
|
+
`&&e[s+1]!=="\r")s++;return s}function ho(e,t){let n=e[t];if(n===";")return";";if(n==="&")return e[t+1]==="&"?"&&":"&";if(n==="|")return e[t+1]==="|"?"||":e[t+1]==="&"?"|&":"|";return null}function _h(e,t){let n=e[t];if(n===">"){if(e[t+1]===">")return">>";if(e[t+1]==="&")return">&";return e[t+1]==="|"?">|":">"}if(n!=="<")return null;if(e.startsWith("<<<",t))return"<<<";if(e.startsWith("<<-",t))return"<<-";if(e[t+1]==="<")return"<<";if(e[t+1]==="&")return"<&";if(e[t+1]===">")return"<>";return"<"}function yo(e){let t=e.charCodeAt(0);if(t===32||t>=9&&t<=13)return!0;if(t<128)return!1;return/\s/u.test(e)}function Nc(e,t,n){if(e[t+1]==="{"){let o=e.indexOf("}",t+2);return o===-1||o>=n?n:o+1}let r=t+1;while(r<n&&/[A-Za-z0-9_?@#$!*-]/.test(e[r]??""))r++;return r===t+1?t+1:r}function Ph(e,t,n){let r="",o=[],i=t;while(i<n){let s=e[i];if(s==="'")return{text:r,next:i+1,closed:!0,issues:o};if(s!=="\\"){r+=s??"",i++;continue}let a=Ah(e,i+1,n);if(r+=a.text,a.invalidCodePoint!==void 0)o.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${a.invalidCodePoint}`,span:{start:i,end:a.next}});i=a.next}return{text:r,next:n,closed:!1,issues:o}}function Ah(e,t,n){let r=e[t];if(!r||t>=n)return{text:"\\",next:t};let o=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
|
|
32
|
+
`],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(o.has(r))return{text:o.get(r)??r,next:t+1};if(r==="x")return fo(e,t+1,n,16,2,t+1);if(r==="u")return fo(e,t+1,n,16,4,t+1);if(r==="U")return fo(e,t+1,n,16,8,t+1);if(/[0-7]/.test(r))return fo(e,t,n,8,3,t+1);return{text:r,next:t+1}}function fo(e,t,n,r,o,i){let s=r===16?/[0-9a-fA-F]/:/[0-7]/,a="",l=t;while(l<n&&a.length<o&&s.test(e[l]??""))a+=e[l],l++;if(!a)return{text:e[i-1]??"",next:i};let c=Number.parseInt(a,r);return c>1114111||c>=55296&&c<=57343?{text:"�",next:l,invalidCodePoint:c}:{text:String.fromCodePoint(c),next:l}}function Co(e,t=!1){if(t)return"limited";if(e.some((n)=>n.code==="invalid-ansi-c-code-point"||n.code==="missing-heredoc-delimiter"||n.code==="ambiguous-heredoc-delimiter"||n.code==="unterminated-heredoc"||n.code==="unsupported-heredoc-context"))return"invalid";return e.length>0?"partial":"complete"}function Lc(e,t,n,r,o){let i=Nc(e,t,n);return{text:r+e.slice(t,i),provenance:Yn(o,"variable"),next:i}}function kh(e,t,n){let r=mo(e),o=t,i=!1,s=!1,a=t;while(a<n){let l=e[a];if(l==="\\"&&!i){a+=2;continue}if(!s&&l==="'"){i=!i,a++;continue}if(!i&&l==='"'){s=!s,a++;continue}if(i){a++;continue}let c=e.startsWith("$((",a),u=e.startsWith("$(",a)&&!c,m=!s&&(e.startsWith("<(",a)||e.startsWith(">(",a)),f=l==="`";if(c||u||m||f){let d=c?3:f?1:2,p=c?"))":f?"`":")",g=Rs(e,a+d,n,p),y=g===-1?n:g+p.length;r.push(o,a,"literal"),r.push(a,y,c?"arithmetic":"command-substitution"),a=y,o=y;continue}if(l==="$"){let d=Nc(e,a,n);if(d>a+1){r.push(o,a,"literal"),r.push(a,d,"variable"),a=d,o=d;continue}}if(!s&&(l==="*"||l==="?"||l==="[")){r.push(o,a,"literal"),r.push(a,a+1,"glob"),a++,o=a;continue}a++}return r.push(o,n,"literal"),r.parts}function Yn(e,t){if(t==="command-substitution"||e==="command-substitution")return"command-substitution";if(t==="arithmetic"||e==="arithmetic")return"arithmetic";if(t==="variable"||e==="variable")return"variable";if(t==="glob"||e==="glob")return"glob";return e}function Th(e,t,n){return t+1>=n||yo(e[t+1]??"")||ho(e,t+1)!==null}var Ih=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),Oh=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function Dh(e){let t=0;while(t<=e.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]?.text??""))t++;if(t===e.length)return!0;let n=Mh(e,t);if(n===void 0||n===null)return!1;t=n}return!1}function Mh(e,t){let n=e[t]?.text.toLowerCase();if(n==="command")return Nh(e,t);if(n==="env")return Lh(e,t);if(n==="sudo")return Wh(e,t);return}function Nh(e,t){if(e[t+1]?.text==="-v")return null;for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(r==="-p"||r==="-v"||r==="-V"||/^-[pvV]+$/.test(r))continue;return n}return e.length}function Lh(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(Ih.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-u=")||r.startsWith("--unset=")||r.startsWith("-C")&&r.length>2||r.startsWith("--chdir=")||r.startsWith("-S")&&r.length>2||r.startsWith("--split-string=")||r.startsWith("-P"))continue;if(r.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(r))continue;return n}return e.length}function Wh(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(Oh.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-"))continue;return n}return e.length}function Wc(e,t,n,r){if(e.provenance!=="literal"||!e.raw.includes("{"))return;let o=[e.raw],i=e.raw.length,s=0;while(!0){let l=o.findIndex((p)=>kc(p));if(l===-1)break;if(++s>n)return{limited:!0};let c=o[l]??"",u=kc(c);if(!u||u.kind==="range")return{limited:!0};let m=u.start+c.length-u.end,f=u.alternatives.reduce((p,g)=>p+m+g.length,0);if(i-c.length+f>r||o.length-1+u.alternatives.length>t)return{limited:!0};let d=Fc(c,u);o.splice(l,1,...d),i+=f-c.length}if(s===0)return;let a=o.map((l)=>zh(l,n));if(a.some((l)=>l===null))return{limited:!0};return{words:[...new Set(a.filter((l)=>l!==null&&l!==""))]}}function Fh(e,t,n,r,o){if(t.provenance!=="literal"||t.quoted||t.raw!==t.text||!t.raw.includes("{"))return;let i=[t.text],s=t.text.length,a=0;while(!0){let c=i.findIndex((y)=>Ac(y));if(c===-1)break;if(++a>r)return{limitCode:"depth-limit"};let u=i[c]??"",m=Ac(u);if(!m)break;let f=m.start+u.length-m.end,d=m.alternatives.filter((y)=>f+y.length>0),p=d.reduce((y,h)=>y+f+h.length,0);if(s-u.length+p>o)return{limitCode:"brace-expansion-limit"};if(i.length-1+d.length>n)return{limitCode:"word-limit"};let g=Fc(u,{...m,alternatives:d});i.splice(c,1,...g),s+=p-u.length}let l=i.filter((c)=>c.length>0);if(a===0)return;return{words:l.map((c)=>mn(e,t.span.start,t.span.end,c,"literal",!1))}}function Ac(e){let t=[],n;for(let r=0;r<e.length;r++){let o=e[r];if(o==="{"){t.push({start:r,commas:[]});continue}if(o===","&&t.length>0){t.at(-1)?.commas.push(r);continue}if(o!=="}"||t.length===0)continue;let i=t.pop();if(!i||i.commas.length===0)continue;if(!n||i.start<n.start)n={start:i.start,end:r+1,commas:i.commas}}if(!n)return;return{start:n.start,end:n.end,alternatives:Gc(e,n)}}function kc(e){let t=[],n,r=null,o=!1;for(let i=0;i<e.length;i++){let s=e[i];if(o){o=!1;continue}if(s==="\\"&&r!=="'"){o=!0;continue}if(s===r){r=null;continue}if(r===null&&(s==="'"||s==='"')){r=s;continue}if(r!==null)continue;if(s==="{"){t.push({start:i,commas:[]});continue}if(s===","&&t.length>0){t.at(-1)?.commas.push(i);continue}if(s!=="}"||t.length===0)continue;let a=t.pop();if(!a)continue;let l=a.commas.length>0?{kind:"alternatives",start:a.start,end:i+1,commas:a.commas}:Gh(e.slice(a.start+1,i))?{kind:"range",start:a.start,end:i+1}:void 0;if(l&&(!n||l.start<n.start))n=l}if(!n||n.kind==="range")return n;return{kind:n.kind,start:n.start,end:n.end,alternatives:Gc(e,n)}}function Fc(e,t){return t.alternatives.map((n)=>`${e.slice(0,t.start)}${n}${e.slice(t.end)}`)}function Gc(e,t){let n=[t.start,...t.commas,t.end-1];return n.slice(0,-1).map((r,o)=>e.slice(r+1,n[o+1]))}function Gh(e){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(e)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(e)}function zh(e,t){let n=`x${e}`,r=Ss(n,0,n.length,"posix",{maxInputLength:n.length,maxWords:1,maxDepth:t},{used:0,max:1},0);if(r.limited||r.issues.length>0||r.next!==n.length||r.word.provenance!=="literal")return null;return r.word.text.slice(1)}function $h(e,t,n,r,o){return de({kind:"program",dialect:r,source:e.slice(t,n),span:{start:t,end:n},status:"limited",issues:[{code:o,message:"command structure exceeds parser limit",span:{start:t,end:n}}],nodes:[]})}function fn(e,t,n,r,o){return{nodes:e,issues:[...t,{code:r,message:`command structure exceeds parser limit ${o}`,span:{start:n,end:n}}],next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function po(e,t,n){return{nodes:e,issues:t,next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function Cs(e){return e.used++,e.used<=e.max}function Bh(e,t,n){let r=/^([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(e.slice(t,n)),o=r?.[1];if(!r||!o)return;return{name:o,braceIndex:t+r[0].lastIndexOf("{")}}function Xn(e){return e.some((t)=>{if(t.kind==="command")return t.redirections.some((n)=>n.heredoc)||t.nested.some((n)=>Xn(n.nodes));return(t.kind==="group"||t.kind==="function")&&Xn(t.body.nodes)})}function Uh(e){return e.map((t)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${t.delimiter} was not found`,span:t.declarationSpan}))}function zc(e){return e?.kind==="command"||e?.kind==="group"||e?.kind==="function"}function Tc(e,t){let n=e.at(-1);if(n?.kind!=="connector"||!Ic.has(n.operator))return;t.push({code:"missing-command-after-connector",message:`connector ${n.operator} requires a following command`,span:n.span})}function bs(e,t,n){if(!zc(e.at(-1)))return;t.push({code:"missing-command-connector",message:"adjacent commands require a connector",span:{start:n,end:n+1}})}function Hh(e,t,n){return t===n||/[\s;&|()]/u.test(e[t-1]??"")}var $c=new Set(["remove-item","ri","del","erase","rd","rmdir"]),Bc=["-rec","-for","-path","-literalpath","-whatif"],bo={maxInputLength:131072,maxWords:16384,maxDepth:64};function Uc(e){let t=e.toLowerCase().replaceAll("`","");if(![...$c].some((r)=>t.includes(r))&&!(t.includes("rm")&&Bc.some((r)=>t.includes(r)))&&!t.includes("<#"))return!1;let n=Kh(e);return n.invalidComment||n.commands.some(jh)}function jh(e){let t=e[0]==="&"||e[0]==="."?1:0,n=e[t]?.toLowerCase();if(n&&$c.has(n))return!0;if(n!=="rm")return!1;return e.slice(t+1).some((r)=>{let o=r.toLowerCase().split(":",1)[0]??"";return Bc.some((i)=>o.startsWith(i))})}function Hc(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return de({kind:"program",dialect:"powershell",source:e,span:n,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${t.maxInputLength} UTF-16 code units`,span:n}],nodes:[]});let r=Ps(e,0,e.length,t,0);return de({kind:"program",dialect:"powershell",source:e,span:n,status:Zh(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function Ps(e,t,n,r,o,i=!1){let s=ao(),a=lo(),l=co(),c=0,u=!1,m=()=>{if(l.words.length===0&&l.redirections.length===0)return;let d={start:l.start,end:l.end};uo(s,l,{kind:"command",dialect:"powershell",source:e.slice(d.start,d.end),span:d,words:l.words,redirections:l.redirections,nested:l.nested,displayText:l.words.map((p)=>p.text).join(" ")})},f=t;while(f<n){let d=e[f];if(!d)break;if(i&&d==="}")return m(),{nodes:s,issues:a,next:f+1,closed:!0,words:c,limited:u};let p=qc(e,f,n,r.maxDepth);if(p){if(p.issue)a.push(p.issue);if(p.limited)return m(),{nodes:s,issues:a,next:p.next,closed:!1,words:c,limited:!0};f=p.next;continue}if(/\s/.test(d)){if(d==="\r"||d===`
|
|
33
|
+
`){m();let h=d==="\r"&&e[f+1]===`
|
|
34
|
+
`?f+2:f+1;s.push(Es(e,f,h)),f=h;continue}f++;continue}let g=As(e,f);if(g){m(),s.push(Es(e,f,f+g.length)),f+=g.length;continue}if(d==="{"){if(m(),o>=r.maxDepth)return a.push(Vc(f,r.maxDepth)),{nodes:s,issues:a,next:n,closed:!1,words:c,limited:!0};let h=Ps(e,f+1,n,r,o+1,!0),R=h.closed?h.next-1:h.next,E=de({kind:"program",dialect:"powershell",source:e.slice(f+1,R),span:{start:f+1,end:R},status:h.limited?"limited":h.issues.length>0?"partial":"complete",issues:h.issues,nodes:h.nodes});if(s.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:f,end:h.next}),body:E})),a.push(...h.issues),!h.closed)a.push({code:"unclosed-script-block",message:"PowerShell script block is not closed",span:{start:f,end:h.next}});c+=h.words,u||=h.limited,f=h.next;continue}if(d==="}"){m(),s.push(Es(e,f,f+1)),f++;continue}if(d===">"||d==="<"){l.start=l.start===-1?f:l.start;let h=e[f+1]===d?f+2:f+1,R=h;while(/[ \t]/.test(e[R]??""))R++;let E=R<n?xs(e,R,n,r,o):void 0,A=E?.next??h;if(l.redirections.push(Object.freeze({kind:"redirection",operator:e.slice(f,h),span:Object.freeze({start:f,end:A}),...E?{target:E.word}:{}})),E)a.push(...E.issues),l.nested.push(...E.nested),c+=E.words,u||=E.limited;l.end=A,f=A;continue}if(d===","){l.start=l.start===-1?f:l.start,l.words.push(gs({text:",",raw:",",span:{start:f,end:f+1},provenance:"literal",quoted:!1})),l.end=++f;continue}let y=xs(e,f,n,r,o);if(l.start=l.start===-1?f:l.start,l.end=y.next,l.words.push(y.word),a.push(...y.issues),l.nested.push(...y.nested),c+=1+y.words,u||=y.limited,c>r.maxWords)return a.push({code:"word-limit",message:`command exceeds ${r.maxWords} words`,span:{start:f,end:y.next}}),m(),{nodes:s,issues:a,next:y.next,closed:!1,words:c,limited:!0};f=y.next>f?y.next:f+1}return m(),{nodes:s,issues:a,next:f,closed:!i,words:c,limited:u}}function xs(e,t,n,r,o){let i="",s="literal",a=!1,l=[],c=[],u=0,m=!1,f=(p)=>{let g=Vh(e,p,n,r,o);return i+=e.slice(p,g.next),c.push(g.program),l.push(...g.program.issues),u+=ws(g.program),m||=g.program.status==="limited",s="command-substitution",g.next},d=t;while(d<n){let p=e[d];if(!p||/\s/.test(p)||As(e,d)||p===">"||p==="<"||p==="#")break;if(p===",")break;if(p==="`"){let g=e[d+1];if(!g){l.push({code:"trailing-escape",message:"PowerShell escape has no following character",span:{start:d,end:d+1}}),d++;break}i+=g,d+=2;continue}if(e.startsWith("$(",d)){d=f(d);continue}if(p==="'"){a=!0,d++;let g=!1;while(d<e.length){if(e[d]==="'"&&e[d+1]==="'"){i+="'",d+=2;continue}if(e[d]==="'"){g=!0,d++;break}i+=e[d]??"",d++}if(!g)l.push({code:"unclosed-single-quote",message:"single-quoted word is not closed",span:{start:t,end:e.length}});continue}if(p==='"'){a=!0;let g=d++,y=!1;while(d<n){let h=e[d];if(h==="`"&&e[d+1]){i+=e[d+1],d+=2;continue}if(h==='"'){y=!0,d++;break}if(e.startsWith("$(",d)){d=f(d);continue}if(h==="$")s=e[d+1]==="("?"command-substitution":"variable";i+=h??"",d++}if(!y)l.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:g,end:e.length}});continue}if(p==="$")s=e[d+1]==="("?"command-substitution":"variable";if(p==="@"&&d===t)s="variable";i+=p,d++}return{word:mn(e,t,d,i,s,a,s==="literal"?void 0:qh(e,t,d)),next:d,issues:l,nested:c,words:u,limited:m}}function Vh(e,t,n,r,o){let i=jc(e,t+2,n),s=i===-1?n:i,a=i===-1?n:i+1;if(o>=r.maxDepth)return{program:de({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:"limited",issues:[Vc(t,r.maxDepth)],nodes:[]}),next:a};let l=Ps(e,t+2,s,r,o+1),c=i===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed",span:{start:t,end:a}}]:[];return{program:de({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:l.limited?"limited":l.issues.length+c.length>0?"partial":"complete",issues:[...l.issues,...c],nodes:l.nodes}),next:a}}function jc(e,t,n){let r=1,o=!1,i=!1;for(let s=t;s<n;s++){let a=e[s];if(a==="`"){s++;continue}if(!i&&a==="'"){if(o&&e[s+1]==="'"){s++;continue}o=!o;continue}if(!o&&a==='"'){i=!i;continue}if(o)continue;if(e.startsWith("$(",s)){r++,s++;continue}if(!i&&a==="(")r++;if(a!==")")continue;if(r--,r===0)return s}return-1}function ws(e){let t=0;for(let n of e.nodes){if(n.kind==="group")t+=ws(n.body);if(n.kind==="command"){t+=n.words.length;for(let r of n.nested)t+=ws(r)}}return t}function qh(e,t,n){let r=mo(e),o=t,i=!1,s=t;while(s<n){let a=e[s];if(a==="`"){s+=2;continue}if(a==="'"){if(i&&e[s+1]==="'"){s+=2;continue}i=!i,s++;continue}if(i){s++;continue}if(e.startsWith("$(",s)){let l=jc(e,s+2,n),c=l===-1?n:l+1;r.push(o,s,"literal"),r.push(s,c,"command-substitution"),s=c,o=c;continue}if(a==="$"||a==="@"&&s===t){let l=s+1;if(e[l]==="{"){let c=e.indexOf("}",l+1);l=c===-1||c>=n?n:c+1}else while(l<n&&/[A-Za-z0-9_:?]/.test(e[l]??""))l++;r.push(o,s,"literal"),r.push(s,l,"variable"),s=l,o=l;continue}s++}return r.push(o,n,"literal"),r.parts}function Vc(e,t){return{code:"depth-limit",message:`command structure exceeds parser limit ${t}`,span:{start:e,end:e}}}function Kh(e){let t=[],n=[],r=0,o=0,i=!1,s=()=>{if(n.length>0)t.push(n);n=[]};while(r<e.length&&r<131072&&o<16384){let a=e[r];if(a==="\r"||a===`
|
|
35
|
+
`){s(),r+=a==="\r"&&e[r+1]===`
|
|
36
|
+
`?2:1;continue}if(/\s/.test(a??"")){r++;continue}let l=qc(e,r,Math.min(e.length,bo.maxInputLength),bo.maxDepth);if(l){i||=!!l.issue||l.limited,r=l.next;continue}let c=As(e,r);if(c){s(),r+=c.length;continue}if(a==="{"||a==="}"){s(),r++;continue}let u=xs(e,r,Math.min(e.length,bo.maxInputLength),bo,0);if(u.word.text)n.push(u.word.text);for(let m of u.nested)t.push(..._s(m));o++,r=u.next>r?u.next:r+1}return s(),{commands:t,invalidComment:i}}function _s(e){return e.nodes.flatMap((t)=>{if(t.kind==="group")return _s(t.body);if(t.kind!=="command")return[];return[t.words.map((n)=>n.text),...t.nested.flatMap(_s)]})}function As(e,t){for(let n of["&&","||",";","|"])if(e.startsWith(n,t))return n;return null}function qc(e,t,n,r){if(e[t]==="#"&&e[t+1]!==">"){let s=t+1;while(s<n&&e[s]!=="\r"&&e[s]!==`
|
|
37
|
+
`)s++;return{next:s,limited:!1}}if(!e.startsWith("<#",t))return null;let o=1,i=t+2;while(i<n){if(e.startsWith("<#",i)){if(o++,o>r)return{next:n,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${r}`,span:{start:t,end:i+2}},limited:!0};i+=2;continue}if(e.startsWith("#>",i)){if(o--,i+=2,o===0)return{next:i,limited:!1};continue}i++}return{next:n,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed",span:{start:t,end:n}},limited:!1}}function Zh(e,t){if(t)return"limited";if(e.some((n)=>n.code==="unclosed-block-comment"))return"invalid";return e.length>0?"partial":"complete"}function Es(e,t,n){return Object.freeze({kind:"connector",operator:e.slice(t,n),span:Object.freeze({start:t,end:n})})}var Ft=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Le(e,t="auto",n=Ft){if(t==="powershell"||t==="auto"&&Uc(e.slice(0,n.maxInputLength)))return Hc(e,n);return Oc(e,"posix",n)}function Jn(e,t){if(e!=="powershell")return t[0]?.provenance==="command-substitution";let n=t[0]?.text==="&"||t[0]?.text==="."?1:0,r=t[n]?.provenance;return r!==void 0&&r!=="literal"}var Yh=/^[A-Za-z_][A-Za-z0-9_]*=/;function So(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function vo(e){let t=So(e.words[0],"time")?1:0,n=t===1&&So(e.words[t],"-p")?t+1:t,r=t===1&&So(e.words[n],"--")?n+1:n,o=So(e.words[r],"!")?r+1:r,i=e.words.slice(o).find((s)=>!Yh.test(s.text));return i?.provenance==="literal"?i.text:void 0}function Qn(e,t){if(t.escaped)return t.escaped=!1,!0;if(e==="\\"&&!t.inSingle)return t.escaped=!0,!0;if(e==="'"&&!t.inDouble)return t.inSingle=!t.inSingle,!0;if(e==='"'&&!t.inSingle)return t.inDouble=!t.inDouble,!0;return!1}function pn(e){let t={inSingle:!1,inDouble:!1,escaped:!1};for(let n of Xh(e))Qn(n,t);return t.inSingle||t.inDouble}function Xh(e){let t="",n={inSingle:!1,inDouble:!1,escaped:!1},r=!1,o=!0;for(let i=0;i<e.length;i++){let s=e[i];if(!s)break;if(r){if(s===`
|
|
38
|
+
`||s==="\r")t+=s,r=!1,n.escaped=!1;continue}if(s==="#"&&!n.inSingle&&!n.inDouble&&o){r=!0;continue}if(t+=s,!n.inSingle&&!n.inDouble&&!n.escaped)o=/[\s;&|()<>]/.test(s);Qn(s,n)}return t}var Jh=new Set(["&&","||","|&","|","&",";"]),Qh=new Set(["<<","<<<",">|"]),ey=/[*@#?$!_-]/,ks=Object.freeze([]),ty=Object.freeze([]),ny=256;function Jc(e,t){let n=t.status==="complete"?new Set(Is(t)):new Set,r=[...n].reduce((s,a)=>s.slice(0,a.start)+" ".repeat(a.end-a.start)+s.slice(a.end),e);if(pn(r))return Ro("unclosed-quote",r,ks);let o={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},i=er(t,{source:r,suppressed:n,flags:o,depth:0,functions:new Map});if(o.limited)return Ro("structural-limit",r,ks);if(o.invalid)return Ro("invalid",r,ks);return Ro("complete",r,i,o.assignmentFallbacks)}function Ro(e,t,n,r=ty){return Object.freeze({status:e,source:t,entries:Object.freeze(n),assignmentFallbacks:Object.freeze(r)})}function er(e,t){return e.nodes.flatMap((n,r)=>ry(n,e,r,t)).sort((n,r)=>n.start-r.start).flatMap((n)=>[...n.entries])}function ry(e,t,n,r){if(e.kind==="connector")return[{start:e.span.start,entries:[We(ly(e.operator))]}];if(e.kind==="unknown")return[{start:e.span.start,entries:[We(e.source)]}];if(e.kind==="function")return r.functions.set(e.name,e.body),[];if(e.kind==="group"){let i=e.style!=="subshell",s=r.source[e.span.end-1]===(i?"}":")"),a=i?r:{...r,functions:new Map(r.functions)};return[{start:e.span.start,entries:[i?Eo("{"):We("("),...er(e.body,a),...s?[i?Eo("}"):We(")")]:[]]}]}let o=uy(e,r.functions);if(o){if(r.depth>=Ft.maxDepth||++r.flags.expansions>ny)return r.flags.limited=!0,[];return[{start:e.span.start,entries:[...Kc(e,r),Eo(";"),...er(o,{...r,depth:r.depth+1}),Eo(";")]},...Zc(e,t,n,r)]}return[{start:e.span.start,entries:Kc(e,r)},...Zc(e,t,n,r)]}function Kc(e,t){return[...e.words.map((n)=>({start:n.span.start,entries:eu(n,e,t,!1)})),...e.redirections.map((n)=>({start:n.span.start,entries:oy(n,e,t)}))].sort((n,r)=>n.start-r.start).flatMap((n)=>n.entries)}function oy(e,t,n){let r=e.operator==="<<-"?"<<":e.operator,o=e.target?eu(e.target,t,n,!0):[],i=o[0],s=i?.kind==="word"?i.text:void 0;return[...e.fd===void 0?[]:[Os(String(e.fd))],Object.freeze({kind:"redirection",operator:r,role:cy(r),targetOrder:Qh.has(r)?"legacy-segment":"immediate",...s===void 0?{}:{target:s}}),...s===void 0?o:o.slice(1)]}function Zc(e,t,n,r){let o=e.redirections.filter((i)=>i.operator==="<<"||i.operator==="<<-");return[...o.flatMap((i)=>{let s=i.heredoc;if(!s)return[];let a=[Os(s.delimiter),.../[\r\n]/.test(r.source[s.terminatorSpan.end]??"")?[We(";")]:[]];if(r.suppressed.has(s.bodySpan))return[{start:s.bodySpan.start,entries:a}];return[{start:s.bodySpan.start,entries:[...Qc(r.source.slice(s.bodySpan.start,s.bodySpan.end),r),...a]}]}),...o.some((i)=>!i.heredoc&&i.target)?iy(t,n,r):[]]}function iy(e,t,n){let r=e.nodes.slice(t+1).find((o)=>o.kind==="connector");if(!r||r.span.end>=e.span.end)return[];return[{start:r.span.end,entries:Qc(n.source.slice(r.span.end,e.span.end),n)}]}function Qc(e,t){if(t.depth>=Ft.maxDepth)return t.flags.limited=!0,[];let n=Le(e,"posix");if(n.status==="limited")return t.flags.limited=!0,[];let r={invalid:!1,limited:!1,expansions:t.flags.expansions,assignmentFallbacks:t.flags.assignmentFallbacks},o=er(n,{source:e,suppressed:new Set,flags:r,depth:t.depth+1,functions:new Map});return t.flags.limited||=r.limited,t.flags.expansions=r.expansions,o}function eu(e,t,n,r){let o=[],i={single:!1,double:!1},s="",a=!1,l=()=>{if(a&&!r)o.push(We("glob"));else if(s!==""||e.quoted&&o.length===0)o.push(Os(s));s="",a=!1};for(let c of e.parts){if(c.provenance!=="command-substitution"&&c.provenance!=="arithmetic"){for(let d of Ts(c.raw,i,n.flags)){if(typeof d==="string"){l(),o.push(We(d));continue}s+=d.text,a||=d.glob}continue}if(i.double){let d=n.source.slice(c.span.start,c.span.end);s+=Ts(d,{single:!1,double:!0},n.flags).map((p)=>typeof p==="string"?p:p.text).join("");continue}let u=t.nested.find((d)=>d.span.start>=c.span.start&&d.span.end<=c.span.end),m=u?er(u,n):[];if(c.raw.startsWith("`")){s+="${}",l(),o.push(...m);continue}if(c.raw.startsWith("<(")||c.raw.startsWith(">(")){l(),o.push(c.raw.startsWith("<(")?We("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),...m,...c.raw.endsWith(")")?[We(")")]:[]);continue}let f=c.raw.startsWith("$((")?2:1;s+="${}",l(),o.push(...Array.from({length:f},()=>We("(")),...m,...c.raw.endsWith(")".repeat(f))?Array.from({length:f},()=>We(")")):[])}return l(),o}function Ts(e,t,n){let r=[],o="",i=!1,s=0;while(s<e.length){let a=e[s]??"";if(!t.single&&!t.double&&(a==="("||a===")")){r.push({text:o,glob:i},a),o="",i=!1,s++;continue}if(t.single){if(a==="'")t.single=!1;else o+=a;s++;continue}if(t.double){if(a==='"'){t.double=!1,s++;continue}if(a==="\\"){let l=e[s+1]??"";o+=['"',"\\","$"].includes(l)?l:`\\${l}`,s+=2;continue}if(a==="$"){let l=Yc(e,s,t,n);o+=l.text,s=l.next;continue}o+=a,s++;continue}if(a==="'"||a==='"'){t.single=a==="'",t.double=a==='"',s++;continue}if(a==="\\"){let l=e[s+1]??"";i||=l==="*"||l==="?",o+=l,s+=2;continue}if(a==="$"){let l=Yc(e,s,t,n);o+=l.text,s=l.next;continue}i||=a==="*"||a==="?",o+=a,s++}return[...r,{text:o,glob:i}]}function Yc(e,t,n,r){let o=e[t+1];if(o==="{"){let s=ay(e,t+2);if(s===-1)return r.invalid=!0,{text:"",next:e.length};let a=e.slice(t,s+1);return sy(a,n,r),{text:a,next:s+1}}if(o!==void 0&&ey.test(o))return{text:`\${${o}}`,next:t+2};let i=/^\w*/.exec(e.slice(t+1))?.[0]??"";return{text:`\${${i}}`,next:t+1+i.length}}function sy(e,t,n){let r=e.slice(2,-1),o=/^[A-Za-z_][A-Za-z0-9_]*/.exec(r)?.[0];if(!o)return;let i=r.slice(o.length),s=[":=","="].find((l)=>i.startsWith(l));if(!s)return;let a=Ts(i.slice(s.length),{...t},n);n.assignmentFallbacks.push(...a.flatMap((l)=>typeof l==="string"||!l.text?[]:[l.text]))}function ay(e,t){let n=1,r=t;while(n>0&&r<e.length){if(e[r]==="{"&&e[r-1]==="$")n++;else if(e[r]==="}")n--;r++}return n===0?r-1:-1}function ly(e){return/^[\r\n]+$/.test(e)?";":e}function We(e){return Object.freeze({kind:"operator",operator:e,boundary:Jh.has(e)})}function Eo(e){return Object.freeze({kind:"operator",operator:e,boundary:!0})}function Os(e){return Object.freeze({kind:"word",text:e})}function cy(e){if(e==="<<"||e==="<<<")return"here-data";if(e==="<"||e==="<&")return"file-read";return"file-write"}function Is(e){return e.nodes.flatMap((t,n)=>{if(t.kind==="group"||t.kind==="function")return Is(t.body);if(t.kind!=="command")return[];let r=t.nested.flatMap((s)=>Is(s)),o=e.nodes[n+1];if(o?.kind==="connector"&&(o.operator==="|"||o.operator==="|&")||!my(t))return r;return[...r,...t.redirections.flatMap((s)=>s.heredoc?.quotedDelimiter?[s.heredoc.bodySpan]:[])]})}function uy(e,t){let n=vo(e);return n===void 0?void 0:t.get(n)}function xt(e,t){return e!==void 0&&e.provenance==="literal"&&!e.quoted&&e.raw===e.text&&e.text===t}function dy(e){if(xt(e.words[0],"git"))return xt(e.words[1],"commit");if(!xt(e.words[0],"gh")||!xt(e.words[2],"create"))return!1;return xt(e.words[1],"pr")||xt(e.words[1],"issue")}function my(e){return(xt(e.words[0],"cat")||xt(e.words[0],"tee")||dy(e))&&!e.words.some(Xc)&&!e.redirections.some((n)=>Xc(n.target))}function Xc(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}var tu=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),nu=new Set([...tu,"glob"]),fy=new Set([...nu,"pattern"]),py=[],ru={parseCommand:Le,projectShellSyntax:Jc};class Xe extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function xo(e,t={}){let n=gy({...ru,...t}),r=Zn(e.input),o=[];if((e.route.kind==="command"||e.route.kind==="unknown")&&r)o.push({usage:"input-candidate",source:r});if(e.route.kind==="command"&&"command"in e&&e.command)o.push({usage:"declared-command",source:e.command});let i=o.reduce((s,a)=>{let l=s.findIndex((m)=>m.source===a.source);if(l!==-1){let m=s[l];if(!m)return s;return s[l]={...m,usages:[...m.usages,a.usage]},s}let c=e.route.kind==="command"?e.route.shell:"posix",u=n.getCommandProgram(a.source,c);return s.push({usages:[a.usage],source:a.source,program:u,shell:n.getShellSyntax(a.source,u)}),s},[]);return{invocation:{toolName:e.toolName,route:e.route,context:e.context},commands:i,paths:hy(e),store:n}}function ge(e,t){return e.commands.find((n)=>n.usages.includes(t))}function Je(e){if(!e.includes("$"))return e;return eo(e,mt())}function gy(e={}){let t={...ru,...e},n=new Map,r=new Map,o=new WeakMap,i=(a,l)=>{let c=`${l}\x00${a}`,u=r.get(c);if(u)return u;let m=t.parseCommand(a,l);return r.set(c,m),m};return{getShellSyntax:(a,l)=>{if(l&&l.source!==a)throw TypeError("Shell syntax source does not match command program source.");let c=l??i(a,"posix");if(c.status==="limited"){let f=o.get(c);if(f)return f;let d={status:"structural-limit",source:a,entries:py,assignmentFallbacks:[]};return o.set(c,d),d}let u=n.get(a);if(u)return u;let m=t.projectShellSyntax(a,c);return n.set(a,m),m},getCommandProgram:i}}function hy(e){let t=e.route.kind==="grep"?nu:e.route.kind==="glob"?fy:tu;return[...fs(e.input,t),...e.route.kind==="patch"?ps(e.input):[]]}function Ds(e,t){return{value:e,work:t}}function v(e,t){if(e.work)e.work.units=Math.min(Number.MAX_SAFE_INTEGER,e.work.units+1);return e.value[t]}function X(e){return e.value.length}function tr(e,t,n=1){if(e)e.units=Math.min(Number.MAX_SAFE_INTEGER,e.units+t.length*n)}function he(e,t){tr(e,t)}function Gt(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t===95||t>=97&&t<=122}function j(e){if(!e)return!1;let t=e.charCodeAt(0);return t===9||t===10||t===11||t===12||t===13||t===32||t===160||t===65279||t===5760||t>=8192&&t<=8202||t===8232||t===8233||t===8239||t===8287||t===12288}function Ms(e){return e===`
|
|
39
|
+
`||e==="\r"||e==="\u2028"||e==="\u2029"}function V(e,t,n){if(t+n.length>X(e))return!1;for(let r=0;r<n.length;r++)if(v(e,t+r)!==n[r])return!1;return!0}function ft(e,t,n){return!Gt(v(e,t-1))&&V(e,t,n)&&!Gt(v(e,t+n.length))}function pt(e,t){return Gt(v(e,t-1))!==Gt(v(e,t))}function te(e){return e===`
|
|
40
|
+
`||e===";"||e==="&"||e==="|"}function gn(e){return e==="|"||e===";"}var ye=new Set(["awk","gawk","nawk","mawk"]),yy=new Set(["-e","--source"]),Cy=new Set(["-F","-v","--assign","--field-separator"]),ou=new Set(["-f","--file"]),by=new Set(["print","printf","return"]),iu=[{selector:"-e",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"--source",kind:"inline-code",valueForm:"equals-or-separate"},{selector:"-f",kind:"program-file",valueForm:"attached-or-separate"},{selector:"--file",kind:"program-file",valueForm:"equals-or-separate"}],Sy="Detected awk system(), pipe, or getline command with dynamic command that cannot be safely analyzed. Use a literal command or process the data without system(), pipes, or getline.";function Po(e,t,n){let r=!1;for(let o of vy(e)){let i=Ry(o,n);if(!i)continue;for(let s of i.commands){let a=t(s);if(a)return a;if(s.includes("{}")||/[$`]/.test(s))r=!0}r||=i.dynamic}return r?b("awk.system-dynamic",Sy):null}function Ls(e){let t=[],n=!1,r=!1,o=!0,i=!0;for(let s=1;s<e.length;s++){let a=e[s];if(a===void 0)break;if(o&&a==="--"){o=!1;continue}if(o&&yy.has(a)){n=!0;let l=e[s+1];if(l!==void 0)t.push({tokenIndex:s+1,kind:"inline-code",value:l});else i=!1;s++;continue}if(o&&a.startsWith("--source=")){n=!0,t.push({tokenIndex:s,kind:"inline-code",value:a.slice(9)});continue}if(o&&a.startsWith("-e")&&a.length>2){n=!0,t.push({tokenIndex:s,kind:"inline-code",value:a.slice(2)});continue}if(o&&(Cy.has(a)||ou.has(a))){if(ou.has(a)){r=!0;let l=e[s+1];if(l!==void 0)t.push({tokenIndex:s+1,kind:"program-file",value:l});else i=!1}else if(e[s+1]===void 0)i=!1;s++;continue}if(o&&(a.startsWith("-F")||a.startsWith("-v")&&a.slice(2).includes("=")))continue;if(o&&a.startsWith("-f")&&a.length>2){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(2)});continue}if(o&&(a.startsWith("--assign=")||a.startsWith("--field-separator=")))continue;if(o&&a.startsWith("--file=")){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(7)});continue}if(o&&a.startsWith("-")&&a!=="-")continue;if(o=!1,!n&&!r)t.push({tokenIndex:s,kind:"main-program",value:a});return{sources:t,optionsOpen:!1}}return{sources:i?t:[],optionsOpen:o&&i}}function rr(e){return Ls(e).sources}function vy(e){return rr(e).filter((t)=>t.kind!=="program-file").map((t)=>t.value)}function Ry(e,t){he(t,e);let n=e.includes("system")?Ws(e,t):null,r=Ey(e,t);if(!n&&!r)return null;return{dynamic:!!n?.dynamic||!!r?.dynamic,commands:[...n?.commands??[],...r?.commands??[]]}}function Ws(e,t){he(t,e);let n=[],r=!1,o=!1,i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){i=_o(e,i,s)?.endIndex??i+1;continue}if(s==="#"){i=su(e,i+1);continue}if(s==="/"&&au(e,i)){i=lu(e,i+1)??i+1;continue}if(!e.startsWith("system",i)){i++;continue}let a=i;if(i+=6,nr(e[a-1])||nr(e[i]))continue;let l=wo(e,i);if(e[l]!=="(")continue;l=wo(e,l+1);let c=e[l];if(c!=='"'&&c!=="'"){r=!0,o=!0;continue}let u=_o(e,l,c);if(!u){r=!0,o=!0;continue}if(l=wo(e,u.endIndex),r=!0,e[l]!==")"){o=!0,i=u.endIndex;continue}n.push(u.value),i=l+1}if(!r)return null;return{dynamic:o,commands:n}}function Ey(e,t){he(t,e);let n=[],r=!1,o=!1,i=0,s=0,a=null,l=null,c=0;while(i<e.length){let u=e[i];if(!u)break;if(u==='"'||u==="'"){let d=_o(e,i,u);if(d&&c===s)l={...d,startIndex:i};c=d?.endIndex??i+1,i=d?.endIndex??i+1;continue}if(u==="#"){i=su(e,i+1),s=i,a=null,l=null,c=i;continue}if(u==="/"&&au(e,i)){let d=lu(e,i+1);c=d??i+1,i=d??i+1;continue}if(`;
|
|
41
|
+
{}`.includes(u)){i++,s=i,a=null,l=null,c=i;continue}if(a===null&&(Ns(e,i,"print")||Ns(e,i,"printf")))a=i;if(u!=="|"||e[i-1]==="|"||e[i+1]==="|"){if(!/\s/.test(u))c=i+1;i++;continue}let m=e[i+1]==="&"?i+2:i+1,f=wo(e,m);if(Ns(e,f,"getline")){o=!0;let d=_y(s,l,c);if(d===null)r=!0;else n.push(d);c=m,i=m;continue}if(Ay(s,a)){o=!0;let d=wy(e,f);if(!d){r=!0,c=m,i=m;continue}if(!xy(e,d.endIndex)){r=!0,c=d.endIndex,i=d.endIndex;continue}n.push(d.value),c=d.endIndex,i=d.endIndex;continue}c=m,i++}if(!o)return null;return{dynamic:r,commands:n}}function nr(e){return!!e&&/[A-Za-z0-9_]/.test(e)}function wo(e,t){let n=t;while(/\s/.test(e[n]??""))n++;return n}function xy(e,t){let n=t;while(/[\t\f\v\r ]/.test(e[n]??""))n++;let r=e[n];return!r||`;
|
|
42
|
+
}#`.includes(r)}function _o(e,t,n){let r="",o=!1;for(let i=t+1;i<e.length;i++){let s=e[i];if(!s)break;if(o){let a=Py(e,i);if(!a)return null;r+=a.value,i=a.endIndex,o=!1;continue}if(s==="\\"){o=!0;continue}if(s===n)return{value:r,endIndex:i+1};r+=s}return null}function wy(e,t){let n=e[t];if(n!=='"'&&n!=="'")return null;return _o(e,t,n)}function _y(e,t,n){if(!t)return null;return t.startIndex>=e&&t.endIndex===n?t.value:null}function Py(e,t){let n=e[t];if(!n)return null;if(n==="x"){let o=e.slice(t+1,t+3);if(!/^[0-9A-Fa-f]{2}$/.test(o))return null;return{value:String.fromCharCode(Number.parseInt(o,16)),endIndex:t+2}}if(/[0-7]/.test(n)){let o=/^[0-7]{1,3}/.exec(e.slice(t));if(!o)return null;return{value:String.fromCharCode(Number.parseInt(o[0],8)),endIndex:t+o[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
|
|
43
|
+
`,r:"\r",t:"\t",v:"\v"}[n]??n,endIndex:t}}function Ns(e,t,n){return e.startsWith(n,t)&&!nr(e[t-1])&&!nr(e[t+n.length])}function Ay(e,t){return t!==null&&t>=e}function su(e,t){let n=e.indexOf(`
|
|
44
|
+
`,t);return n===-1?e.length:n+1}function au(e,t){let n=ky(e,t);if(n===-1)return!0;if("{([,;!~=".includes(e[n]??""))return!0;let r=n;while(nr(e[r-1]))r--;return by.has(e.slice(r,n+1))}function ky(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function lu(e,t){let n=!1;for(let r=t;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="/")return r+1}return null}import{existsSync as $s,lstatSync as Gy,readFileSync as Io,realpathSync as sr,statSync as ir}from"node:fs";import{dirname as Bs,isAbsolute as Us,join as Oo,resolve as Do}from"node:path";import{dirname as Ty,isAbsolute as Iy,parse as Oy,sep as Dy}from"node:path";function zt(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function wt(e,t,n){if(zt(t))throw Error("Unsupported Windows namespace path");let r=Iy(t)?Ny(t):"",o=r||e;for(let i of Ly(r?t.slice(r.length):t)){if(i===""||i===".")continue;if(i===".."){o=Ty(o);continue}let s=My(o,i),a=n.entryKind(s),l=a==="symlink"?n.realpath(s):s;if(a==="missing"||l===null)throw Error(`Cannot resolve path component: ${s}`);o=l}return o}function My(e,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${t}`:`${e}${Dy}${t}`}function Ny(e){return Oy(e).root}function Ly(e){let t=process.platform==="win32"?/[\\/]+/:/\/+/;return e.split(t)}var Fs=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],Wy=new Set(Fs);var cu=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),Ao=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),Fy=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function Gs(e){return Wy.has(e)}function or(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function zs(e){return Gs(e)||cu.has(e)||Ao.has(e)||or(e)}function Ae(e,t,n){return n?.has(e)?n.get(e):t.get(e)}function ko(e,t){let n=Ae("GIT_CONFIG_COUNT",e,t);if(n===void 0)return{state:"absent"};if(n==="")return{state:"valid",count:0};if(!/^\d+$/.test(n))return{state:"invalid"};let r=Number(n);return Number.isSafeInteger(r)&&r<=1024?{state:"valid",count:r}:{state:"invalid"}}function To(e,t,n){let o=e.match(Fy)?.[1];if(!o||!zs(o))return null;let i=e.indexOf("=");return{name:o,value:`${Ae(o,t,n)??""}${e.slice(i+1)}`}}function uu(e){return mu(e,Ao)}function du(e){return mu(e,cu)}function mu(e,t){if(!e)return!1;for(let n of e.keys())if(t.has(n))return!0;return!1}var Qe=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]);function gu(e,t){return Fs.some((n)=>t?.has(n)||e.has(n))}function hu(e,t){if(!t)return{gitCwd:null,hasExplicitGitContext:!1};let n;try{n=sr(Do(t))}catch{return{gitCwd:null,hasExplicitGitContext:!1}}if(!bu(n))return{gitCwd:null,hasExplicitGitContext:!1};let r=!1,o=1;while(o<e.length){let i=e[o];if(!i)break;if(i==="--")break;if(!i.startsWith("-"))break;if(i==="-C"){let s=e[o+1];if(!s)return{gitCwd:null,hasExplicitGitContext:r};let a=pu(n,s);if(!a)return{gitCwd:null,hasExplicitGitContext:r};n=a,o+=2;continue}if(i.startsWith("-C")&&i.length>2){let s=pu(n,i.slice(2));if(!s)return{gitCwd:null,hasExplicitGitContext:r};n=s,o++;continue}if(i==="--git-dir"||i==="--work-tree"){r=!0,o+=2;continue}if(i.startsWith("--git-dir=")||i.startsWith("--work-tree=")){r=!0,o++;continue}if(Qe.has(i))o+=2;else if(i.startsWith("-c")&&i.length>2)o++;else o++}return{gitCwd:n,hasExplicitGitContext:r}}function yu(e){let t=Qy(e);if(!t)return!1;try{let n=Gy(t);if(n.isSymbolicLink()||!n.isFile())return!1;let r=Hs(t);if(!r?.commonDir)return!1;if(!By(r.gitDir,t))return!1;return Uy(r.gitDir,Bs(t))}catch{return!1}}function Hs(e){try{let t=zy(e);if(!t)return null;let n=sr(Us(t)?t:Do(Bs(e),t));if(!ir(n).isDirectory())return null;return{gitDir:n,commonDir:$y(n)}}catch{return null}}function zy(e){let t=Io(e,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!t.startsWith("gitdir:"))return null;return t.slice(7).trim()||null}function $y(e){try{let t=Io(Oo(e,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!t)return null;let n=sr(Us(t)?t:Do(e,t));return ir(n).isDirectory()?n:null}catch{return null}}function By(e,t){let n=Hy(e);return n===null?!1:Cu(e,n,t)}function Uy(e,t){let n=jy(e);return n===null?!0:Cu(e,n,t)}function Hy(e){let t=Oo(e,"gitdir");if(!$s(t))return null;let n=Io(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return n===""?null:n}function jy(e){let t=Oo(e,"config.worktree");return $s(t)?Yy(t):null}function Cu(e,t,n){return qy(Vy(e,t),n)}function Vy(e,t){return Us(t)?t:Do(e,t)}function qy(e,t){try{return Ky(e,t)}catch{return!1}}function Ky(e,t){try{let n=ir(e),r=ir(t);if(n.ino!==0&&r.ino!==0&&n.dev===r.dev&&n.ino===r.ino)return!0}catch{}return fu(e)===fu(t)}function fu(e){return Zy(sr.native(e))}function Zy(e){let t=e.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"");if(t=t.replace(/\\/g,"/"),t.length>1&&t.endsWith("/"))t=t.slice(0,-1);return process.platform==="win32"?t.toLowerCase():t}function Yy(e){let t=Io(e,"utf-8"),n=!1,r=null;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i===""||i.startsWith("#")||i.startsWith(";"))continue;if(i.startsWith("[")){n=/^\[core\]$/i.test(i);continue}if(!n)continue;let s=i.match(/^worktree\s*=\s*(.*)$/i);if(s)r=Xy(s[1]??"")}return r}function Xy(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;return Jy(t.slice(1,-1))}function Jy(e){let t="";for(let n=0;n<e.length;n++){let r=e[n];if(r!=="\\"){t+=r;continue}let o=e[n+1];if(o===void 0){t+=r;continue}switch(o){case"\\":case'"':t+=o;break;case"n":t+=`
|
|
45
|
+
`;break;case"t":t+="\t";break;case"b":t+="\b";break;default:t+=`\\${o}`;break}n++}return t}function pu(e,t){try{let n=wt(e,t,Pe);return bu(n)?n:null}catch{return null}}function bu(e){try{return ir(e).isDirectory()}catch{return!1}}function Qy(e){try{return ar(sr(e))}catch{return null}}function ar(e){let t=e;while(!0){let n=Oo(t,".git");if($s(n))return n;let r=Bs(t);if(r===t)return null;t=r}}function Mo(e,t,n){let r=Ds(e,n);if(t==="rm")return eC(r);if(t==="dd")return nC(r);return wu(r,!0)}function No(e,t,n){let r=Ds(e,n);if(t==="rm")return rC(r);if(t==="reset-hard")return Eu(r,"--ha","rd");if(t==="reset-merge")return Eu(r,"--me","rge");if(t==="clean")return aC(r);if(t==="checkout")return cC(r);if(t==="push-force")return uC(r);if(t==="push-refspec")return dC(r);if(t==="push-delete")return mC(r);if(t==="branch")return fC(r);if(t==="tag")return hC(r);if(t==="restore")return yC(r);return wu(r,!1)}function eC(e){let t=!1,n=!1,r=!1,o=-1;for(let i=0;i<=X(e);i++){let s=v(e,i);if(!t){let l=v(e,i+2);if(ft(e,i,"rm")&&j(l)&&l!==`
|
|
46
|
+
`)t=!0,i++;continue}let a=tC(e,i);if(s===`
|
|
47
|
+
`||a!==-1){if(t=!1,n=!1,r=!1,o=-1,a!==-1)i=a-1;continue}if(s===";"||s==="&"||s==="|"||i===X(e)){if(o>=0){let l=Su(e,o,i);n||=l.recursive,r||=l.force}if(n&&r)return!0;t=!1,n=!1,r=!1,o=-1;continue}if(j(s)){if(o>=0){if(V(e,o,"--")&&i-o===2)t=!1,n=!1,r=!1;else{let l=Su(e,o,i);if(n||=l.recursive,r||=l.force,n&&r)return!0}o=-1}continue}if(o<0)o=i}return!1}function tC(e,t){if(v(e,t)!=="\\"||v(e,t-1)==="\\")return-1;if(V(e,t,String.raw`\n`))return t+2;if(V(e,t,String.raw`\x0a`)||V(e,t,String.raw`\x0A`))return t+5;if(V(e,t,String.raw`\u000a`)||V(e,t,String.raw`\u000A`))return t+7;return V(e,t,String.raw`\012`)?t+4:-1}function Su(e,t,n){if(vu(e,t,n,"recursive"))return{recursive:!0,force:!1};if(vu(e,t,n,"force"))return{recursive:!1,force:!0};if(v(e,t)!=="-"||v(e,t+1)==="-")return{recursive:!1,force:!1};let r=!1,o=!1;for(let i=t+1;i<n;i++){let s=v(e,i);r||=s==="r"||s==="R",o||=s==="f"||s==="F"}return{recursive:r,force:o}}function vu(e,t,n,r){let o=n-t-2;if(o<1||o>r.length||!V(e,t,"--"))return!1;for(let i=0;i<o;i++)if(v(e,t+i+2)!==r[i])return!1;return!0}function nC(e){let t=!1;for(let n=0;n<X(e);n++){if(te(v(e,n))){t=!1;continue}if(ft(e,n,"dd")){t=!0,n++;continue}if(!t||!ft(e,n,"of")||!V(e,n,"of=/dev/"))continue;let r=n+8;if(r<X(e)&&!j(v(e,r))&&v(e,r)!=="'"&&v(e,r)!=='"')return!0}return!1}function rC(e){let t=!1,n=!1,r=!1;for(let o=0;o<=X(e);){let i=v(e,o);if(o===X(e)||te(i)){t=!1,n=!1,r=!1,o++;continue}let s=iC(e,o);if(s>=0){if(oC(e,s))return!0;let a=s,l=!1;while(j(v(e,a)))l||=v(e,a)===`
|
|
48
|
+
`,a++;if(l)n=!1,r=!1;t=!0,o=a;continue}if(!t){o++;continue}if(V(e,o,"--")&&(o===0||j(v(e,o-1)))&&(!v(e,o+2)||j(v(e,o+2))||te(v(e,o+2)))){t=!1,n=!1,r=!1,o+=2;continue}if(n||=V(e,o,"--recursive")&&pt(e,o+11)||js(e,o,"recursive"),r||=V(e,o,"--force")&&pt(e,o+7)||js(e,o,"force"),n&&r)return!0;o++}return!1}function js(e,t,n){if(!V(e,t,"--"))return!1;let r=0;while(r<=n.length){let o=v(e,t+r+2);if(!o||j(o)||te(o))break;if(o!==n[r])return!1;r++}return r>0&&pt(e,t+r+2)}function oC(e,t){let n=t,r=!1,o=!1;while(n<X(e)){while(j(v(e,n)))n++;let i=n;while(n<X(e)&&!j(v(e,n)))n++;if(v(e,i)!=="-"||n-i===2&&V(e,i,"--"))return!1;let s=Ru(e,i,"recursive"),a=Ru(e,i,"force");if(r&&a||o&&s)return!0;if(r||=s,o||=a,v(e,i+1)==="-")continue;let l=sC(e,i,n);if(l.combined||r&&l.forceAtBoundary||o&&l.recursiveAtBoundary)return!0;r||=l.recursive,o||=l.force}return!1}function Ru(e,t,n){return V(e,t,`--${n}`)&&pt(e,t+n.length+2)||js(e,t,n)}function iC(e,t){if(t>0&&Gt(v(e,t-1)))return-1;let n=t;if(v(e,n)==="\\")n++;if(v(e,n)!=="r")return-1;if(n++,v(e,n)==="\\")n++;if(v(e,n)!=="m"||!j(v(e,n+1)))return-1;return n+1}function sC(e,t,n){let r=!1,o=!1,i=!1,s=!1,a=!1;if(v(e,t)!=="-")return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a};let l="";for(let c=t+1;c<n;c++){let u=v(e,c)??"",m=(u==="r"||u==="f")&&pt(e,c+1);r||=u==="r",o||=u==="f",i||=u==="r"&&m,s||=u==="f"&&m,a||=(l==="r"&&u==="f"||l==="f"&&u==="r")&&m,l=u}return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a}}function Eu(e,t,n){return cr(e,"reset",gn,!0,(r)=>v(e,r)==="-"&&hn(e,r,t,n)?!0:r)}function aC(e){return cr(e,"clean",gn,!0,(t)=>{if(v(e,t)!=="-")return t;if(hn(e,t,"--fo","rce"))return!0;let n=lr(e,t,gn);for(let r=t+1;r<n;r++)if(v(e,r)==="f")return!0;return n-1})}function Lo(e,t,n){if(!ft(e,t,"git"))return null;let r=t+3;if(!j(v(e,r)))return{commandEnd:-1,next:r};while(j(v(e,r)))r++;while(r<X(e)){if(te(v(e,r)))return{commandEnd:-1,next:r};let o=lr(e,r,te);if(ft(e,r,n))return{commandEnd:r+n.length,next:o};if(v(e,r)!=="-")return{commandEnd:-1,next:o};let i=o-r===2&&V(e,r,"--"),s=lC(e,r,o);r=o;while(j(v(e,r)))r++;if(i)return{commandEnd:ft(e,r,n)?r+n.length:-1,next:lr(e,r,te)};if(!s)continue;if(r>=X(e)||te(v(e,r)))return{commandEnd:-1,next:r};r=lr(e,r,te);while(j(v(e,r)))r++}return{commandEnd:-1,next:r}}function lC(e,t,n){for(let r of Qe)if(n-t===r.length&&V(e,t,r))return!0;return!1}function cC(e){return xu(e,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function uC(e){return cr(e,"push",gn,!0,(t)=>{if(v(e,t)!=="-")return t;if(v(e,t+1)==="f"&&!Gt(v(e,t+2))&&!V(e,t+2,"-with-lease"))return!0;let n=_u(e,t,"--fo","rce");if(n>=0&&!V(e,n,"-with-lease"))return!0;return t})}function dC(e){return cr(e,"push",te,!1,(t)=>{if(j(v(e,t))&&v(e,t+1)==="+"&&t+2<X(e)&&!te(v(e,t+2))&&!j(v(e,t+2)))return!0;if(v(e,t)===":"&&v(e,t+1)==="+")return!0;return t})}function mC(e){return cr(e,"push",te,!1,(t)=>{if(v(e,t)==="-"&&hn(e,t,"--de","lete"))return!0;if(j(v(e,t))&&v(e,t+1)===":"&&t+2<X(e)&&!j(v(e,t+2))&&!te(v(e,t+2)))return!0;return t})}function fC(e){let t=!1,n=!1,r=!1;for(let o=0;o<=X(e);o++){if(o===X(e)||te(v(e,o))){if(n&&r)return!0;t=!1,n=!1,r=!1;continue}if(!t){let a=Lo(e,o,"branch");if(a){t=a.commandEnd>=0,o=Math.max(o,(t?a.commandEnd:a.next)-1);continue}}if(!t||v(e,o)!=="-")continue;let i=lr(e,o,te),s=pC(e,o,i);if(n||=s.deletion,r||=s.force,n&&r)return!0;o=i-1}return!1}function pC(e,t,n){let r=!1,o=!1;for(let i=t;i<n;i++){if(v(e,i)!=="-")continue;if(hn(e,i,"--de","lete"))r=!0;if(hn(e,i,"--fo","rce"))o=!0;if(v(e,i+1)==="-")continue;let s=i+1,a=!1,l=!1,c=!1;while(s<n&&gC(v(e,s))){let u=v(e,s);a||=u==="d"||u==="D",l||=u==="f",c||=u==="D",s++}if(!pt(e,s))continue;r||=a,o||=l||c}return{deletion:r,force:o}}function gC(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function hC(e){return xu(e,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function xu(e,t){let n=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let r=0;r<X(e);r++){let o=v(e,r),i=n[n.length-1];if(!i)return!1;let s=i.escaped;if(i.escaped=!s&&i.quote!=="'"&&o==="\\",!s&&o==="'"&&i.quote!=='"')i.quote=i.quote==="'"?"":"'";if(!s&&o==='"'&&i.quote!=="'")i.quote=i.quote==='"'?"":'"';if(o==="$"&&v(e,r+1)==="("&&(n.length===1||!s&&i.quote!=="'")){n.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),r++;continue}if(!s&&!i.quote&&n.length>1&&o==="("){i.depth++;continue}if(!s&&!i.quote&&n.length>1&&o===")"){if(i.depth--,i.depth===0)n.pop();continue}if(j(o))i.shortActive=!1,i.hasShortFlag=!1;if(!i.outerActive){let a=Lo(e,r,t.command);if(a){i.outerActive=a.commandEnd>=0&&j(v(e,a.commandEnd)),i.shortActive=!1,i.hasShortFlag=!1,r=Math.max(r,(i.outerActive?a.commandEnd:a.next)-1);continue}}if(i.outerActive&&o==="-"){if(hn(e,r,t.longPrefix,t.longOptional))return!0;i.shortActive||=!t.excludedShortStarts.includes(v(e,r+1)??"")}if(i.hasShortFlag||=i.shortActive&&o===t.shortFlag,i.hasShortFlag&&pt(e,r+1))return!0;if(gn(o))i.outerActive=!1}return!1}function cr(e,t,n,r,o){let i=!1;for(let s=0;s<X(e);s++){let a=v(e,s),l=n(a);if(!i&&!l){let c=Lo(e,s,t);if(c){i=c.commandEnd>=0&&(!r||j(v(e,c.commandEnd))),s=Math.max(s,(i?c.commandEnd:c.next)-1);continue}}if(i){let c=o(s);if(c===!0)return!0;for(let u=s;u<=c;u++)if(n(v(e,u)))i=!1;s=c}if(l)i=!1}return!1}function yC(e){let t=!1;for(let n=0;n<X(e);n++){if(Ms(v(e,n))){if(t)return!0;t=!1;continue}if(!t){let r=Lo(e,n,"restore");if(r){t=r.commandEnd>=0,n=Math.max(n,(t?r.commandEnd:r.next)-1);continue}}if(t&&v(e,n)==="-"&&v(e,n+1)==="-"&&(V(e,n+2,"staged")||V(e,n+2,"help")))t=!1}return t}function wu(e,t){let n=!1;for(let r=0;r<X(e);r++){let o=v(e,r),i=t?Ms(o):te(o);if(n&&j(o)&&v(e,r+1)==="-"&&ft(e,r+2,"delete"))return!0;if(i){n=!1;continue}if(ft(e,r,"find"))n=!0,r+=3}return!1}function lr(e,t,n){let r=t;while(r<X(e)&&!j(v(e,r))&&!n(v(e,r)))r++;return r}function _u(e,t,n,r){if(!V(e,t,n))return-1;let o=t+n.length;for(let i=0;i<r.length&&v(e,o)===r[i];i++)o++;return pt(e,o)?o:-1}function hn(e,t,n,r){return _u(e,t,n,r)>=0}function z(e){return M(e).toLowerCase()}function M(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}var $t="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",yn="Interpreter one-liners are blocked by the active safety policy. Write the code to a script file and run it, or run the equivalent shell command directly.",Wo=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),CC=new Set(["-p","--print"]),bC=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),SC=new Map([["python",new Set(["W","X"])],["node",new Set(["C","r"])],["ruby",new Set(["C","E","F","I","r"])],["perl",new Set(["F","I","M","m"])]]),vC=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),RC=new Map([["python",new Set(["m"])]]),EC=new Map([["node",new Set(["--allow-fs-read","--allow-fs-write","--conditions","--cpu-prof-dir","--cpu-prof-interval","--cpu-prof-name","--debug-port","--diagnostic-dir","--disable-proto","--disable-warning","--dns-result-order","--env-file","--env-file-if-exists","--experimental-package-map","--experimental-test-isolation","--experimental-test-tag-filter","--heap-prof-dir","--heap-prof-interval","--heap-prof-name","--heapsnapshot-near-heap-limit","--heapsnapshot-signal","--icu-data-dir","--input-type","--inspect-port","--inspect-publish-uid","--localstorage-file","--max-http-header-size","--max-old-space-size-percentage","--network-family-autoselection-attempt-timeout","--openssl-config","--redirect-warnings","--report-dir","--report-directory","--report-filename","--report-signal","--secure-heap","--secure-heap-min","--test-concurrency","--test-coverage-branches","--test-coverage-exclude","--test-coverage-functions","--test-coverage-include","--test-coverage-lines","--test-global-setup","--test-isolation","--test-name-pattern","--test-random-seed","--test-reporter","--test-reporter-destination","--test-rerun-failures","--test-shard","--test-skip-pattern","--test-timeout","--title","--tls-cipher-list","--tls-keylog","--trace-event-categories","--trace-event-file-pattern","--trace-require-module","--unhandled-rejections","--use-largepages","--v8-pool-size","--watch-kill-signal"])],["python",new Set(["--check-hash-based-pycs"])],["ruby",new Set(["--backtrace-limit","--crash-report","--disable","--enable","--encoding","--external-encoding","--internal-encoding","--parser"])]]),xC=new Set(["always","default","never"]),wC=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),_C=/\\\r?\n/g,PC=new Map([["python",[{selector:"-c",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-m",kind:"module-file",valueForm:"attached-or-separate"}]],["node",[{selector:"-e",kind:"inline-code",valueForm:"separate-only"},{selector:"--eval",kind:"inline-code",valueForm:"equals-or-separate"},{selector:"-p",kind:"inline-code",valueForm:"separate-only"},{selector:"--print",kind:"inline-code",valueForm:"separate-only"},{selector:"-r",kind:"module-file",valueForm:"separate-only"},{selector:"--require",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--import",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--loader",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--experimental-loader",kind:"module-file",valueForm:"equals-or-separate"}]],["ruby",[{selector:"-e",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-r",kind:"module-file",valueForm:"attached-or-separate"}]],["perl",[{selector:"-e",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-E",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-M",kind:"module-file",valueForm:"attached-only"},{selector:"-m",kind:"module-file",valueForm:"attached-only"}]]]);function Fo(e){return zo(e).code}function Go(e){return zo(e).sources}function Au(e){return PC.get(Bo(e))??[]}function zo(e){let t=Bo(e[0]??"");if(!Wo.has(t))return{code:null,sources:[],optionsOpen:!1};let n=[],r=[],o=!0;for(let i=1;i<e.length;i++){let s=e[i];if(s===void 0)break;if(s==="--")return Fe(t,n,r,o,e[i+1]===void 0?void 0:i+1,e[i+1]);if(s===""||s==="-"||!s.startsWith("-"))return Fe(t,n,r,o,i,s);if(t==="node"&&CC.has(s)){let m=e[i+1];if(m===void 0)return Fe(t,n,r,o);if(m.startsWith("-"))continue;n.push({tokenIndex:i+1,value:m}),r.push({tokenIndex:i+1,kind:"inline-code",value:m}),i++;continue}if(kC(t,s)){let m=e[i+1];if(m===void 0)return Fe(t,n,r,o);if(n.push({tokenIndex:i+1,value:m}),r.push({tokenIndex:i+1,kind:"inline-code",value:m}),t==="python")return Fe(t,n,r,o);i++;continue}let a=/^--eval=(.*)$/s.exec(s);if(TC(t)&&a){let m=a[1]??"";n.push({tokenIndex:i,value:m}),r.push({tokenIndex:i,kind:"inline-code",value:m});continue}if(t==="node"){let m=AC(s);if(m){if(m.attached){if(o&&=m.value!=="",m.value!=="")r.push({tokenIndex:i,kind:"module-file",value:m.value});continue}let f=e[i+1];if(f===void 0||f.startsWith("-"))return o=!1,Fe(t,n,r,o);r.push({tokenIndex:i+1,kind:"module-file",value:f}),i++;continue}}if(t==="python"&&s.startsWith("--check-hash-based-pycs=")||t==="node"&&(s==="--conditions="||s==="--diagnostic-dir="||s==="--title=")||t==="ruby"&&(s==="--disable="||s==="--enable="))return Fe(t,n,r,o);if(EC.get(t)?.has(s)){let m=e[i+1];if(m===void 0||m.startsWith("-")&&!(t==="ruby"&&wC.has(s))||t==="python"&&!xC.has(m))return Fe(t,n,r,o);i++;continue}if(s.startsWith("--"))continue;let l,c=!1;for(let m=1;m<s.length;m++){let f=s[m];if(f===void 0)break;if(RC.get(t)?.has(f)){let d=s.slice(m+1),p=d||e[i+1];if(p!==void 0)r.push({tokenIndex:d?i:i+1,kind:"module-file",value:p});return Fe(t,n,r,o)}if(bC.get(t)?.has(f)){l=s.slice(m+1)||e[i+1],c=m+1===s.length;break}if(t==="node"&&f==="r"){if(s==="-r"){let d=e[i+1];if(o&&=d!==void 0&&!d.startsWith("-"),o&&d!==void 0)r.push({tokenIndex:i+1,kind:"module-file",value:d});i++}else o=!1;break}if(t==="ruby"&&f==="r"){let d=s.slice(m+1),p=d||e[i+1];if(o&&=p!==void 0,p!==void 0)r.push({tokenIndex:d?i:i+1,kind:"module-file",value:p});if(!d)i++;break}if(t==="perl"&&(f==="M"||f==="m")){let d=s.slice(m+1);if(d)r.push({tokenIndex:i,kind:"module-file",value:d});else if(o=!1,m+1===s.length)i++;break}if(SC.get(t)?.has(f)){if(m+1===s.length)i++;break}if(vC.get(t)?.has(f)&&m+1<s.length)break}if(l===void 0)continue;let u=c?i+1:i;if(n.push({tokenIndex:u,value:l}),r.push({tokenIndex:u,kind:"inline-code",value:l}),t==="python")return Fe(t,n,r,o);if(c)i++}return Fe(t,n,r,o,void 0,void 0,!0)}function Fe(e,t,n,r,o,i,s=!1){let a=e==="node"?t.slice(-1):t,l=new Set(a.map((u)=>u.tokenIndex)),c=n.filter((u)=>u.kind!=="inline-code"||l.has(u.tokenIndex));if(r&&t.length===0&&o!==void 0&&i!==void 0)c.push({tokenIndex:o,kind:"main-script",value:i});return{code:(e==="node"?a[0]?.value:a.map((u)=>u.value).join(`
|
|
49
|
+
`))||null,sources:r?c:[],optionsOpen:r&&s}}function AC(e){for(let t of["--import","--loader","--experimental-loader","--require"]){if(e===t)return{attached:!1,value:""};if(e.startsWith(`${t}=`))return{attached:!0,value:e.slice(t.length+1)}}return}function Ce(e){return Wo.has(Bo(e))}function $o(e,t){return Bo(e)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(t)}function Bo(e){let t=M(e).toLowerCase();return dc.test(t)?"python":t}function kC(e,t){return Wo.get(e)?.has(t)??!1}function TC(e){return Wo.get(e)?.has("--eval")??!1}function Cn(e,t){let n=DC(e,t);if(!Pu(n,t))return!1;he(t,n);let r=OC(n);if(Pu(r,t))return!0;return he(t,r),IC.test(r)}var IC=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function OC(e){let t=[],n=0,r=0;while(r<e.length){let o=e[r];if(o!=="'"&&o!=='"'){r++;continue}let i=e.startsWith(o.repeat(3),r)?o.repeat(3):o,s=r+i.length;while(s<e.length&&!e.startsWith(i,s))s+=e[s]==="\\"?2:1;if(s>=e.length)break;t.push(e.slice(n,r)," "),r=s+i.length,n=r}return t.push(e.slice(n)),t.join("")}function Pu(e,t){if(Mo(e,"rm",t))return!0;for(let r of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(he(t,e),r.test(e))return!0;if(Mo(e,"dd",t))return!0;for(let r of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(he(t,e),r.test(e))return!0;if(Mo(e,"find",t))return!0;let n=e.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((r)=>(he(t,e),n.some((o)=>No(o,r))))}function DC(e,t){return he(t,e),e.replace(_C,"")}function me(e,t){let n=new Set,r=!1;for(let o of e){if(o==="--"){r=!0;continue}if(r)continue;if(o.startsWith("-")&&!o.startsWith("--")&&o.length>1)for(let i=1;i<o.length;i++){let s=o[i];if(!s||!/[a-zA-Z]/.test(s))break;let a=`-${s}`;if(n.add(a),t?.shortOptsWithValue?.has(a))break}}return n}var MC=new Map([["bash",new Set(["O","o"])],["dash",new Set(["o"])],["ksh",new Set(["o"])],["sh",new Set(["o"])],["zsh",new Set(["o"])]]),NC=new Map([["zsh",new Set(["o"])]]),LC=new Map([["bash",new Set(["--init-file","--rcfile"])]]);function ku(e,t){for(let n=0;n<t.length;n++){let r=t[n];if(r===void 0||r==="--"||r==="-"||r[0]!=="-"&&r[0]!=="+")return null;if(r.startsWith("--")){let s=LC.get(e);if(FC(r,s))continue;if(!s?.has(r))continue;if(t[n+1]===void 0)return null;n++;continue}let o=WC(e,r);if(o.commandSelected)return t[n+o.followingValues+1]??null;let i=t[n+1];if(e==="ksh"&&(r==="-o"||r==="+o")&&i!==void 0&&i[0]!=="-"&&i[0]!=="+")n++;n+=o.followingValues}return null}function WC(e,t){let n=MC.get(e),r=NC.get(e),o=!1,i=0;for(let s=1;s<t.length;s++){let a=t[s];if(a===void 0)break;if(t[0]==="-"&&a==="c")o=!0;if(e==="ksh"&&a==="o"){if(s+1<t.length){let l=t.slice(s+1);if(!o&&t[0]==="-"&&l==="c")continue;if(!o&&t[0]==="-"&&l[0]==="-"&&l.endsWith("c"))o=!0;break}if(o)i++;continue}if(!n?.has(a))continue;if(r?.has(a)&&s+1<t.length)break;i++}return{commandSelected:o,followingValues:i}}function FC(e,t){return t!==void 0&&[...t].some((n)=>e.startsWith(`${n}=`))}var Tu=new Set(["rm","find","xargs","parallel"]),GC=new Set(["sudo","env","command","builtin"]),zC=new Set(["git","busybox",...Tu,...ee,...uc,...ye]);function Uo(e,t){let n=e[0];if(!n||!t.transparentWrappers.includes(M(n)))return null;let r=M(n),o=e[1]==="--"?2:1,i=$C(e,o,r,t),s=i[0];if(s===void 0)return null;return{wrapper:r,tokens:[...e.slice(s)],childIndex:s,alternativeChildIndices:i.slice(1)}}function $C(e,t,n,r){let o=e[1]==="--",i=[];for(let s=t;s<e.length;s++){let a=e[s];if(!a)continue;if(M(a)!==n&&BC(a,r))i.push(s);else if(oo.has(z(a)))break;if(o)break}return i}function BC(e,t){let n=M(e),r=z(e);return r==="git"||n==="busybox"||Bt(e)||Tu.has(n)||t.transparentWrappers.includes(n)||ee.has(r)||e==="$SHELL"||Ce(r)||ye.has(r)||t.rules.some((o)=>o.command===n)}function Bt(e){return GC.has(e.toLowerCase())}function Iu(e){let t=z(e);return zC.has(t)||Ce(t)}var ne={level:{name:"CC_SAFETY_NET_LEVEL"},strict:{name:"CC_SAFETY_NET_STRICT",legacyName:"SAFETY_NET_STRICT"},paranoid:{name:"CC_SAFETY_NET_PARANOID",legacyName:"SAFETY_NET_PARANOID"},paranoidRm:{name:"CC_SAFETY_NET_PARANOID_RM",legacyName:"SAFETY_NET_PARANOID_RM"},paranoidInterpreters:{name:"CC_SAFETY_NET_PARANOID_INTERPRETERS",legacyName:"SAFETY_NET_PARANOID_INTERPRETERS"},worktree:{name:"CC_SAFETY_NET_WORKTREE",legacyName:"SAFETY_NET_WORKTREE"},debug:{name:"CC_SAFETY_NET_DEBUG"},auditScope:{name:"CC_SAFETY_NET_AUDIT_SCOPE"}},Ho=["standard","strict","paranoid"];function UC(e){return{failClosed:e==="strict"||e==="paranoid",paranoidRm:e==="paranoid",paranoidInterpreters:e==="paranoid"}}function HC(e,t){if(!t)return e;return Ho.indexOf(t)>Ho.indexOf(e)?t:e}function jC(){let e=qs(ne.level);if(e===void 0||e==="")return;if(Ho.includes(e))return e;console.error(`CC Safety Net: ignored invalid ${ne.level.name}=${JSON.stringify(e.slice(0,40))}. Use ${Ho.join(", ")}.`);return}function VC(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function qC(){return VC(qs(ne.auditScope))==="all"}function Vs(e){if(e.failClosed&&e.paranoidRm&&e.paranoidInterpreters)return"paranoid";if(e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"strict";if(!e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"standard";return"custom"}function jo(e={}){let t=e.safety?.level??"standard",n=jC(),r=HC(t,n),o=UC(r),i={failClosed:r===t?"preset":"environment",paranoidRm:r===t?"preset":"environment",paranoidInterpreters:r===t?"preset":"environment"},s={failClosed:[`policy safety.level=${t}`],paranoidRm:[`policy safety.level=${t}`],paranoidInterpreters:[`policy safety.level=${t}`]};if(r!==t)s.failClosed.push(`env ${ne.level.name}=${n}`),s.paranoidRm.push(`env ${ne.level.name}=${n}`),s.paranoidInterpreters.push(`env ${ne.level.name}=${n}`);if(e.safety?.overrides?.failClosed!==void 0)o.failClosed=e.safety.overrides.failClosed,i.failClosed="capability_override",s.failClosed.push("policy safety.overrides.fail_closed");if(e.safety?.overrides?.paranoidRm!==void 0)o.paranoidRm=e.safety.overrides.paranoidRm,i.paranoidRm="capability_override",s.paranoidRm.push("policy safety.overrides.paranoid_rm");if(e.safety?.overrides?.paranoidInterpreters!==void 0)o.paranoidInterpreters=e.safety.overrides.paranoidInterpreters,i.paranoidInterpreters="capability_override",s.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(bn(ne.strict))o.failClosed=!0,i.failClosed="environment",s.failClosed.push(`env ${ne.strict.name}`);if(bn(ne.paranoid))o.paranoidRm=!0,o.paranoidInterpreters=!0,i.paranoidRm="environment",i.paranoidInterpreters="environment",s.paranoidRm.push(`env ${ne.paranoid.name}`),s.paranoidInterpreters.push(`env ${ne.paranoid.name}`);if(bn(ne.paranoidRm))o.paranoidRm=!0,i.paranoidRm="environment",s.paranoidRm.push(`env ${ne.paranoidRm.name}`);if(bn(ne.paranoidInterpreters))o.paranoidInterpreters=!0,i.paranoidInterpreters="environment",s.paranoidInterpreters.push(`env ${ne.paranoidInterpreters.name}`);let a=!!e.worktreeMode||bn(ne.worktree);return{strict:o.failClosed,paranoidRm:o.paranoidRm,paranoidInterpreters:o.paranoidInterpreters,worktreeMode:a,effectiveLevel:Vs(o),capabilities:{fail_closed:{enabled:o.failClosed,source:i.failClosed,sources:s.failClosed},paranoid_rm:{enabled:o.paranoidRm,source:i.paranoidRm,sources:s.paranoidRm},paranoid_interpreters:{enabled:o.paranoidInterpreters,source:i.paranoidInterpreters,sources:s.paranoidInterpreters}}}}function bn(e){let t=typeof e==="string"?ur(e):qs(e);return t==="1"||t?.toLowerCase()==="true"}function ur(e){return Object.hasOwn(process.env,e)?process.env[e]:void 0}function qs(e){let t=ur(e.name);if(t!==void 0)return t;if(e.legacyName)return ur(e.legacyName);return}function dk(e){return ur(e.name)!==void 0||!!e.legacyName&&ur(e.legacyName)!==void 0}function Ou(e,t,n,r,o){if(n.kind!=="command")return{toolName:e,input:t,route:n,context:r};return{toolName:e,input:t,route:n,context:r,command:o}}var Ks=[{id:"secret.basename.env",category:"Basename",label:".env",description:"Blocks exact .env files.",basename:".env"},{id:"secret.basename.npmrc",category:"Basename",label:".npmrc",description:"Blocks npm credential config files.",basename:".npmrc"},{id:"secret.basename.pypirc",category:"Basename",label:".pypirc",description:"Blocks Python package index credential files.",basename:".pypirc"},{id:"secret.basename.netrc",category:"Basename",label:".netrc",description:"Blocks machine login credential files.",basename:".netrc"},{id:"secret.basename.git-credentials",category:"Basename",label:".git-credentials",description:"Blocks Git credential storage files.",basename:".git-credentials"},{id:"secret.basename.id-rsa",category:"Basename",label:"id_rsa",description:"Blocks RSA private key basenames.",basename:"id_rsa"},{id:"secret.basename.id-ed25519",category:"Basename",label:"id_ed25519",description:"Blocks Ed25519 private key basenames.",basename:"id_ed25519"},{id:"secret.basename.id-ecdsa",category:"Basename",label:"id_ecdsa",description:"Blocks ECDSA private key basenames.",basename:"id_ecdsa"},{id:"secret.basename.credentials",category:"Basename",label:"credentials",description:"Blocks generic credentials file basenames.",basename:"credentials"}],Vo={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},KC=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],ZC=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Zs=[{id:"secret.home.ssh",category:"Home path",label:"~/.ssh",description:"Blocks home SSH configuration and key paths.",suffixParts:[".ssh"]},{id:"secret.home.aws",category:"Home path",label:"~/.aws",description:"Blocks home AWS credential and config paths.",suffixParts:[".aws"]},{id:"secret.home.gcp",category:"Home path",label:"~/.gcp",description:"Blocks home GCP credential paths.",suffixParts:[".gcp"]},{id:"secret.home.gcloud-config",category:"Home path",label:"~/.config/gcloud",description:"Blocks home Google Cloud SDK credential paths.",suffixParts:[".config","gcloud"]},{id:"secret.home.kube-config",category:"Home path",label:"~/.kube/config",description:"Blocks home Kubernetes config files.",suffixParts:[".kube","config"]},{id:"secret.home.docker-config",category:"Home path",label:"~/.docker/config.json",description:"Blocks home Docker credential config files.",suffixParts:[".docker","config.json"]},...ZC.flatMap((e)=>KC.map((t)=>({id:["secret.home",e.idSlug,t.slice(1)].join("."),category:"Home path",label:[e.label,t].join(""),description:["Blocks home ",e.label,t," credential backup files."].join(""),suffixParts:[...e.directoryParts,[e.basename,t].join("")]}))),{id:"secret.home.gh-hosts",category:"Home path",label:"~/.config/gh/hosts.yml",description:"Blocks GitHub CLI host credential files.",suffixParts:[".config","gh","hosts.yml"]}];var qo=[{id:"secret.cli.claude-code",category:"Coding CLI credential",label:"Claude Code credentials",paths:["~/.claude/.credentials.json"]},{id:"secret.cli.claude-code.config",category:"Coding CLI config",label:"Claude Code config",paths:["~/.claude/settings.json","~/.claude/settings.local.json","~/.claude.json","<project>/.claude/settings.local.json","<project>/.mcp.json"]},{id:"secret.cli.antigravity",category:"Coding CLI config",label:"Antigravity CLI hook config",paths:["~/.gemini/config/hooks.json","~/.gemini/config/mcp_config.json"]},{id:"secret.cli.codex",category:"Coding CLI credential",label:"Codex credentials",paths:["~/.codex/auth.json","~/.codex/.credentials.json","~/.codex/secrets","~/.codex/.sandbox-secrets"]},{id:"secret.cli.codex.config",category:"Coding CLI config",label:"Codex config",paths:["~/.codex/config.toml","~/.codex/<name>.config.toml"]},{id:"secret.cli.gemini",category:"Coding CLI credential",label:"Gemini CLI credentials",paths:["~/.gemini/oauth_creds.json","~/.gemini/mcp-oauth-tokens.json","~/.gemini/a2a-oauth-tokens.json","~/.gemini/gemini-credentials.json"]},{id:"secret.cli.gemini.config",category:"Coding CLI config",label:"Gemini CLI config",paths:["~/.gemini/settings.json","~/.gemini/google_accounts.json","<project>/.gemini/settings.json","/Library/Application Support/GeminiCli/settings.json","/etc/gemini-cli/settings.json"]},{id:"secret.cli.copilot-cli",category:"Coding CLI credential",label:"GitHub Copilot CLI credentials",paths:["~/.copilot/config.json","~/.copilot/mcp-oauth-config","~/.copilot/mcp-secrets"]},{id:"secret.cli.copilot-cli.config",category:"Coding CLI config",label:"GitHub Copilot CLI config",paths:["~/.copilot/mcp-config.json"]},{id:"secret.cli.kimi-code",category:"Coding CLI credential",label:"Kimi Code credentials",paths:["~/.kimi-code/server.token","~/.kimi-code/credentials","~/.kimi/credentials","~/.kimi/mcp-oauth"]},{id:"secret.cli.kimi-code.config",category:"Coding CLI config",label:"Kimi Code config",paths:["~/.kimi-code/config.toml","~/.kimi-code/mcp.json","~/.kimi/config.toml","~/.kimi/config.json","~/.kimi/config.json.bak","~/.kimi/mcp.json","<project>/.kimi-code/mcp.json"]},{id:"secret.cli.opencode",category:"Coding CLI credential",label:"OpenCode credentials",paths:["~/.local/share/opencode/auth.json","~/.local/share/opencode/mcp-auth.json","~/.local/share/opencode/opencode.db"]},{id:"secret.cli.opencode.config",category:"Coding CLI config",label:"OpenCode config",paths:["~/.config/opencode/opencode.json","~/.config/opencode/opencode.jsonc","/Library/Application Support/opencode/opencode.json","/etc/opencode/opencode.json","<project>/opencode.json","<project>/opencode.jsonc"]},{id:"secret.cli.pi",category:"Coding CLI credential",label:"Pi credentials",paths:["~/.pi/agent/auth.json"]},{id:"secret.cli.pi.config",category:"Coding CLI config",label:"Pi config",paths:["~/.pi/agent/models.json"]},{id:"secret.cli.amp",category:"Coding CLI credential",label:"Amp Code credentials",paths:["~/.local/share/amp/secrets.json","~/.amp/oauth"]},{id:"secret.cli.amp.config",category:"Coding CLI config",label:"Amp Code config",paths:["~/.config/amp/settings.json","~/.config/amp/settings.jsonc","<project>/.amp/settings.json","<project>/.amp/settings.jsonc"]},{id:"secret.cli.cursor",category:"Coding CLI credential",label:"Cursor CLI credentials",paths:["~/.cursor/auth.json","~/.config/cursor/auth.json","~/.cursor/projects/<name>/mcp-auth.json"]},{id:"secret.cli.cursor.config",category:"Coding CLI config",label:"Cursor CLI config",paths:["~/.cursor/mcp.json","<project>/.cursor/mcp.json"]}],Du=[{prefix:"id_rsa",slug:"id-rsa",label:"id_rsa"},{prefix:"id_dsa",slug:"id-dsa",label:"id_dsa"},{prefix:"id_ed25519",slug:"id-ed25519",label:"id_ed25519"},{prefix:"id_ecdsa",slug:"id-ecdsa",label:"id_ecdsa"},{prefix:"credentials",slug:"credentials",label:"credentials"}],YC=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Ys=Du.map((e)=>({id:`secret.variant.${e.slug}.separator`,category:"Variant",label:`${e.label}-* / ${e.label}_*`,description:`Blocks ${e.label} variants with dash or underscore suffixes.`,prefix:e.prefix})),Xs=Du.flatMap((e)=>YC.map((t)=>({id:`secret.variant.${e.slug}.${t.slice(1)}`,category:"Variant",label:`${e.label}${t}`,description:`Blocks ${e.label}${t} private credential variants.`,prefix:e.prefix,suffix:t}))),dr={id:"secret.pattern.ssh-key-basename",category:"Pattern",label:"*_(rsa|dsa|ed25519|ecdsa)",description:"Blocks extensionless SSH private key-like basenames.",pattern:/^.*_(rsa|dsa|ed25519|ecdsa)$/},Js=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((e)=>({id:`secret.ext.${e}`,category:"Extension",label:`.${e}`,description:`Blocks files with the .${e} extension.`,extension:e})),Qs=[{id:"secret.ext-pattern.key",category:"Extension pattern",label:".key / .keypair",description:"Blocks key and keypair extension patterns.",pattern:/^key(pair)?$/},{id:"secret.ext-pattern.keystore",category:"Extension pattern",label:".keystore / .keyring",description:"Blocks keystore and keyring extension patterns.",pattern:/^key(store|ring)$/},{id:"secret.ext-pattern.kdbx",category:"Extension pattern",label:".kdb / .kdbx",description:"Blocks KeePass database extension patterns.",pattern:/^kdbx?$/}],Mu=[...Ks,Vo,...Zs,...Ys,...Xs,dr,...Js,...Qs,...qo].map((e)=>({id:e.id,category:e.category,label:e.label,...e.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in e?{paths:e.paths}:{description:e.description}})),Nu=new Set(qo.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),XC=Mu.map((e)=>e.id),Ko=new Set(XC);import{createRequire as ob}from"node:module";var Lu=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);import{isAbsolute as ea,join as JC,normalize as QC,sep as Zo}from"node:path";var Wu=process.platform==="win32",eb=/[*?]/;function mr(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function Xo(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=mr(e.trim(),t);if(!ea(n))return"must be an absolute path or start with ~/";return fr(n,t)}function Jo(e,t){let n=Fu(e,t);if(n===null)return"must be a non-empty path string";if(!ea(n))return null;if(fr(n,t)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var tb="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",nb="cannot cover the guard's own configuration";function Fu(e,t){if(typeof e!=="string"||e.trim()==="")return null;return mr(e.trim().replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function Qo(e,t){let n=Fu(e,t);if(n===null)return"must be a non-empty path string";if(eb.test(n))return"cannot contain glob characters (* or ?); list the exact file or directory";if(!ea(n))return null;if(fr(n,t)!==null)return tb;return rb(n,t)?nb:null}function rb(e,t){let n=Yo(e),r=Yo(JC(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${Zo}`)}function fr(e,t){let n=Yo(e),r=Yo(t);if(n===r)return"cannot be the home directory";let o=n.endsWith(Zo)?n:`${n}${Zo}`;if(r.startsWith(o))return"cannot contain the home directory";return null}function Yo(e){let t=QC(e);if(Wu)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(Wu?3:1)&&t.endsWith(Zo))t=t.slice(0,-1);return t}var pr=64,zu="Rule config exceeds CC Safety Net's safe source limit.";var Gu=Object.freeze({maxSources:64,concurrency:4,maxRequests:131,maxResponseBytes:67108864});function ei(e={}){return{requests:0,responseBytes:0,maxRequests:e.maxRequests??Gu.maxRequests,maxResponseBytes:e.maxResponseBytes??Gu.maxResponseBytes}}function ti(e){return{controller:new AbortController,budget:ei(),resolveUrl:e}}function $u(e){if(e.requests>=e.maxRequests)throw Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");e.requests++}function Bu(e,t){if(t>e.maxResponseBytes-e.responseBytes)throw e.responseBytes+=t,Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");e.responseBytes+=t}var ib=ob(import.meta.url),Uu,sb=Array(pr+1).fill("over-limit"),Hu=/^[^/]+\/[^/]+$/,ab=/^sha256:[a-f0-9]{64}$/,ni=`must be an integer between ${Qi} and ${es}`,lb=["version","rules","overrides","transparent_wrappers"],cb=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function ju(e){if(!ke(e)||!Array.isArray(e.rules)||e.rules.length<=pr)return e;return{$schema:e.$schema,version:e.version,rules:sb,overrides:e.overrides,transparent_wrappers:e.transparent_wrappers}}function ub(){let e=ib("../vendor/zod.cjs"),t=(S)=>{let C=e.superRefine(S);return C._zod.def.when=()=>!0,C},n=e.enum(Lu),r=e.union([e.literal("off"),e.looseObject({reason:e.string({error:"required non-empty string"}).min(1,"required non-empty string").max(dn,`must be at most ${dn} characters`).describe("Replacement block reason"),intent:n.optional()})],{error:'must be "off" or an object'}).describe("Disable a rule or replace its block reason and intent."),o=e.string({error:"must be a rulebook source string"}).min(1,"must be a non-empty rulebook source string"),i=e.string({error:"must be a command string"}).regex(Nt,"must match command pattern").describe("Command name such as 'git', 'docker', or 'rtk'."),s=e.looseObject({$schema:e.unknown().optional().describe("JSON Schema reference for IDE support"),version:e.literal(1).describe("Schema version (must be 1)"),rules:e.array(o,{error:"must be an array of rulebook source strings"}).max(pr,zu).default([]).describe("Rulebook source strings such as project-rules or owner/repo#main/team-rules"),overrides:e.record(e.string().meta({pattern:Hu.source}),r).default({}).describe("Rule overrides by id"),transparent_wrappers:e.array(i,{error:"must be an array of command strings"}).default([]).describe("Commands that transparently execute a visible protected child command")}),a=(S,C)=>{if(!ke(S))return;if(Array.isArray(S.rules)&&S.rules.length<=pr){let x=new Set;S.rules.forEach((T,O)=>{if(typeof T!=="string"||T==="")return;if(T.trim()===""){C.addIssue({code:"custom",message:"must be a non-empty rulebook source string",path:["rules",O]});return}let D=jn(T);if(D){C.addIssue({code:"custom",message:D,path:["rules",O]});return}if(x.has(T)){C.addIssue({code:"custom",message:`duplicate rulebook source "${T}"`,path:["rules",O]});return}x.add(T)})}if(ke(S.overrides))for(let x of Object.keys(S.overrides)){if(Hu.test(x))continue;C.addIssue({code:"custom",message:"must use <rulebook-name>/<rule-name>",path:["overrides",x]})}if(!Array.isArray(S.transparent_wrappers))return;let P=new Set;S.transparent_wrappers.forEach((x,T)=>{if(typeof x!=="string"||!Nt.test(x))return;if(P.has(x)){C.addIssue({code:"custom",message:`duplicate command "${x}"`,path:["transparent_wrappers",T]});return}if(Iu(x)){C.addIssue({code:"custom",message:`reserved command "${x}" cannot be a wrapper`,path:["transparent_wrappers",T]});return}P.add(x)})},l=e.preprocess(ju,s.check(e.superRefine(a))),c=e.preprocess(ju,s.check(t(a))),u=e.strictObject({fail_closed:e.boolean().optional(),paranoid_rm:e.boolean().optional(),paranoid_interpreters:e.boolean().optional()}),m=(S,C)=>e.intersection(e.record(e.string().refine((P)=>S.has(P),{error:(P)=>`unknown ${C} rule id "${String(P.input)}"`}),e.unknown()),e.record(e.string(),e.enum(["on","off"]))),f=(S)=>e.array(e.string({error:"must be a non-empty path string"}),{error:"must be an array of paths"}).check(t((C,P)=>{if(!Array.isArray(C))return;let x=Wt();C.forEach((T,O)=>{if(typeof T!=="string")return;let D=S(T,x);if(D)P.addIssue({code:"custom",message:D,path:[O]})})})),d=e.strictObject({version:e.literal(1),safety:e.strictObject({level:e.enum(["standard","strict","paranoid"]).optional(),overrides:u.optional()}).optional(),workflow:e.strictObject({worktree_mode:e.boolean().optional()}).optional(),destructive_command_protection:e.strictObject({enabled:e.boolean().optional(),overrides:m(to,"destructive command").optional(),allow_paths:f(Xo).optional()}).optional(),secret_protection:e.strictObject({enabled:e.boolean().optional(),overrides:m(Ko,"secret protection").optional(),deny_paths:f(Jo).optional(),allow_paths:f(Qo).optional()}).optional(),audit:e.strictObject({retention_days:e.number({error:ni}).int(ni).min(Qi,ni).max(es,ni).optional().describe("Days of audit log history to keep before the sweep deletes it")}).optional()}),p=(S)=>{let C=(O,D)=>S==="legacy"?O:D,P=C("must match pattern (letters, numbers, hyphens, underscores)","must match command pattern"),x=`required non-empty string up to ${dn} characters`,T=e.looseObject({name:e.string({error:"required string"}).regex(_e,C("must match pattern (letters, numbers, hyphens, underscores; max 64 chars)","must match rule name pattern")),command:e.string({error:C("required string","required string matching command pattern")}).regex(Nt,C(P,"required string matching command pattern")),subcommand:e.string({error:C("must be a string if provided","must match command pattern")}).regex(Nt,P).optional(),block_args:e.array(e.string({error:C("must be a string","must be a non-empty string")}).refine((O)=>O!=="",{error:C("must not be empty","must be a non-empty string")}),{error:C("required array","required non-empty array")}).refine((O)=>O.length>0,{error:C("must have at least one element","required non-empty array")}),reason:e.string({error:C("required string",x)}).refine((O)=>O!=="",{error:C("must not be empty",x)}).refine((O)=>O.length<=dn,{error:C(`must be at most ${dn} characters`,x)}),intent:n.optional()},{error:"must be an object"});return e.array(T,{error:C("must be an array","required array")}).check(t((O,D)=>{if(!Array.isArray(O))return;let F=new Set;O.forEach((oe,xe)=>{let w=ke(oe)?oe.name:void 0;if(typeof w!=="string")return;if(F.has(w.toLowerCase())){D.addIssue({code:"custom",message:`duplicate rule name "${w}"`,path:[xe,"name"]});return}F.add(w.toLowerCase())})}))},g=e.looseObject({version:e.literal(1),rules:p("legacy").optional()}),y="required string matching rule name pattern",h=e.looseObject({command:e.string({error:"required non-empty string"}).refine((S)=>S.trim()!=="",{error:"required non-empty string"}),expect:e.enum(["blocked","allowed"]),rule:e.string({error:"must be a string if provided"}).optional()},{error:"must be an object"}).check(t((S,C)=>{if(!ke(S))return;if(S.expect!=="blocked"||typeof S.rule==="string")return;C.addIssue({code:"custom",message:"required string for blocked fixtures",path:["rule"]})})),R=e.looseObject({name:e.string({error:"required string matching rule name pattern"}).regex(_e,"required string matching rule name pattern"),version:e.string({error:"required non-empty string"}).refine((S)=>S!=="",{error:"required non-empty string"}),allowed_commands:e.array(e.string({error:"must match command pattern"}).regex(Nt,"must match command pattern"),{error:"required array"}).check(t((S,C)=>{if(!Array.isArray(S))return;let P=new Set;S.forEach((x,T)=>{if(typeof x!=="string"||!Nt.test(x))return;if(P.has(x)){C.addIssue({code:"custom",message:`duplicate command "${x}"`,path:[T]});return}P.add(x)})})),rules:p("rulebook"),tests:e.array(h,{error:"must be an array if provided"}).optional()}).check(t((S,C)=>{if(!ke(S))return;let P=new Set(ta(S));if(Array.isArray(S.tests)){let T=new Set(S.tests.flatMap((O)=>ke(O)&&O.expect==="blocked"&&typeof O.rule==="string"?[O.rule]:[]));for(let O of T){if(P.has(O))continue;C.addIssue({code:"custom",message:`blocked fixture references unknown rule "${O}"`,path:["tests"]})}}if(!Array.isArray(S.allowed_commands)||!Array.isArray(S.rules))return;let x=new Set(S.allowed_commands.filter((T)=>typeof T==="string"));S.rules.forEach((T,O)=>{let D=ke(T)?T.command:void 0;if(typeof D!=="string"||x.has(D))return;C.addIssue({code:"custom",message:`"${D}" must be listed in allowed_commands`,path:["rules",O,"command"]})})})),E=e.string({error:"required string"}).refine((S)=>S.trim()!=="",{error:"required string"}),A=e.looseObject({spec:E,name:E,version:E,digest:e.string({error:"required sha256 digest"}).regex(ab,"required sha256 digest")},{error:"must be an object"}),_=e.looseObject({rulebooks:e.array(e.intersection(A,e.discriminatedUnion("kind",[e.object({kind:e.literal("local-directory"),path:E}),e.object({kind:e.literal("github"),owner:E,repo:E,ref:E,commit:E,path:E,display_ref:e.unknown().optional()})],{error:(S)=>{if(!ke(S.input))return"must be an object";let C=S.input.kind;return typeof C==="string"?`unknown kind "${C}"`:"required string"}})))});return{RulesConfigSchema:l,RulesConfigDiagnosticSchema:c,RuleOverrideSchema:r,UserPolicySchema:d,LegacyConfigSchema:g,RulebookSchema:R,RulesLockfileSchema:_}}function Sn(){return Uu??=ub(),Uu}function Vu(){return Sn().RulesConfigSchema}function db(){return Sn().UserPolicySchema}function Tk(){return Sn().LegacyConfigSchema}function qu(){return Sn().RulebookSchema}function Ku(){return Sn().RulesLockfileSchema}function ta(e){let t=ke(e)?e.rules:void 0;return(Array.isArray(t)?t:[]).flatMap((n)=>{let r=ke(n)?n.name:void 0;return typeof r==="string"?[r]:[]})}function Zu(e){let t=Sn().RulesConfigDiagnosticSchema.safeParse(e);if(t.success)return{errors:[],sources:new Set(t.data.rules)};return{errors:vn(Xu(t.error.issues,lb)),sources:gb(e,t.error.issues)}}function gr(e){let t=db().safeParse(e);if(t.success)return[];return vn(Xu(t.error.issues,cb)," ")}function vn(e,t=": ",n=" "){return[...new Set(e.flatMap((r)=>Yu(r,t,n,[])))]}function Yu(e,t,n,r){let o=[...r,...e.path],i=pb(o);if(e.code==="unrecognized_keys")return e.keys.map((s)=>`${i?`${i}.`:""}unknown field "${s}"`);if(e.code==="invalid_key")return e.issues.map((s)=>s.message);if(e.code==="invalid_union"){let s=e.errors.flat().filter((a)=>a.path.length>0);if(s.length>0)return s.flatMap((a)=>Yu(a,t,n,o))}if(o.length===0)return[e.code==="invalid_type"?"Config must be an object":e.message];if(o.length===1&&(e.code==="too_big"||e.code==="too_small")&&e.origin==="array")return[e.message];return[`${i}${o.length===1?n:t}${mb(e)}`]}function mb(e){if(e.code==="invalid_value")return`must be ${fb(e.values)}`;if(e.code!=="invalid_type"||!e.message.startsWith("Invalid input:"))return e.message;if(e.expected==="object"||e.expected==="record")return"must be an object if provided";return e.expected==="boolean"?"must be a boolean":e.message}function fb(e){if(e.length>3)return`one of ${e.join(", ")}`;let t=e.map((n)=>typeof n==="string"?`"${n}"`:String(n));if(t.length<2)return`${t[0]}`;return`${t.slice(0,-1).join(", ")}${t.length>2?",":""} or ${t.at(-1)}`}function pb(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function Xu(e,t){let n=e.map((i)=>i.path[1]),r=[...new Set(n.filter((i)=>typeof i==="string"))],o=(i,s)=>[i.path.length===0?-1:t.indexOf(String(i.path[0])),typeof s==="number"?s:r.indexOf(String(s)),i.code==="custom"?0:1];return e.map((i,s)=>({issue:i,rank:o(i,n[s])})).sort((i,s)=>i.rank[0]-s.rank[0]||i.rank[1]-s.rank[1]||i.rank[2]-s.rank[2]).map((i)=>i.issue)}function gb(e,t){let n=ke(e)?e.rules:void 0;if(!Array.isArray(n))return new Set;if(t.some((o)=>o.path.length===1&&o.path[0]==="rules"))return new Set;let r=new Set(t.filter((o)=>o.path[0]==="rules"&&typeof o.path[1]==="number").map((o)=>o.path[1]));return new Set(n.filter((o,i)=>typeof o==="string"&&!r.has(i)))}function ke(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}var Ju={version:1,rules:[],overrides:{},transparent_wrappers:[]};function hb(e){return Zu(e)}function Rn(e){try{let t=at(Qu(e));if(t===null)return{config:null,errors:[]};if(!t.trim())return{config:null,errors:["Config file is empty"]};let n=JSON.parse(t),r=hb(n);if(r.errors.length>0)return{config:null,errors:r.errors};let o=Vu().parse(n);return{config:{version:1,rules:o.rules??[],overrides:o.overrides??{},transparent_wrappers:o.transparent_wrappers??[]},errors:[]}}catch(t){if(t instanceof N)return{config:null,errors:[t.message]};let n=t instanceof Error?t.message:String(t);return{config:null,errors:[t instanceof SyntaxError?"Invalid JSON":n]}}}function Lk(e){let t=Rn(e);if(t.errors.length>0)return{ok:!1,result:{ok:!1,errors:t.errors,warnings:[],entries:[]}};return{ok:!0,config:t.config??Ju}}function Wk(e,t=[]){ri(e,{version:1,rules:t,overrides:{},transparent_wrappers:[]})}function Fk(e,t="project-rules"){ri(e,{rulebook_version:1,name:t,version:"1.0.0",description:t==="project-rules"?"Project-specific CC Safety Net rules.":"User-specific CC Safety Net rules.",author:t==="project-rules"?"project":"user",allowed_commands:["docker"],rules:[{name:"block-docker-system-prune",command:"docker",subcommand:"system",block_args:["prune"],reason:"Use targeted cleanup instead."}],tests:[{command:"docker system prune",expect:"blocked",rule:"block-docker-system-prune"}]})}function ri(e,t,n,r){xl(Qu(e),`${JSON.stringify(t,null,2)}
|
|
50
|
+
`,n,r)}function Qu(e){return typeof e==="string"?Br(e):e}import{chmodSync as yb,existsSync as na,mkdirSync as Cb,readFileSync as ra}from"node:fs";import{dirname as nd,join as bb}from"node:path";var Sb=new Set(["standard","strict","paranoid"]),ii={version:1,safety:{level:"standard",overrides:{}},workflow:{worktree_mode:!1},destructive_command_protection:{enabled:!0,overrides:{},allow_paths:[]},secret_protection:{enabled:!0,overrides:{},deny_paths:[],allow_paths:[]},audit:{retention_days:Zr}};function xn(e){return bb(nd(lt(e)),Vr)}function Xk(e={}){let t=xn(e);if(!na(t))return{path:t,exists:!1,raw:"",policy:hr(),errors:[]};let n=ra(t,"utf-8");if(!n.trim())return{path:t,exists:!0,raw:n,policy:hr(),errors:["Config file is empty"]};try{let r=JSON.parse(n),o=gr(r);return{path:t,exists:!0,raw:n,policy:En(r),errors:o}}catch(r){return{path:t,exists:!0,raw:n,policy:hr(),errors:[`Invalid JSON: ${r instanceof Error?r.message:String(r)}`]}}}function oi(e,t={}){let n=xn(t),r=gr(e),o=r.length>0?hr():En(e);if(r.length>0)return{path:n,policy:o,errors:r};return Cb(nd(n),{recursive:!0,mode:448}),ri(n,o,384),yb(n,384),{path:n,policy:o,errors:[]}}function Jk(e){let t=gr(e);if(t.length>0)return{errors:t};return{preview:vb(En(e)),errors:[]}}function vb(e){let t=jo({safety:id(e.safety)}),n=cs({destructiveCommandProtectionEnabled:e.destructive_command_protection.enabled,destructiveCommandRuleOverrides:e.destructive_command_protection.overrides},t.capabilities),r=Object.values(n),o=r.filter((i)=>i.source!=="catastrophic");return{selectedPreset:e.safety.level,effectiveLevel:t.effectiveLevel,capabilities:t.capabilities,rules:n,counts:{enabled:o.filter((i)=>i.enabled).length,disabled:o.filter((i)=>!i.enabled).length,effectiveCustomizations:r.filter((i)=>i.changesInherited).length}}}function Qk(e={}){let t=xn(e);if(!na(t))return oi(ii,e);let n=ra(t,"utf-8");if(!n.trim())return oi(ii,e);try{return oi(En(JSON.parse(n)),e)}catch{return oi(ii,e)}}function rd(e={}){let t=wb(xn(e));return{...t.policy,errors:t.errors,...t.fallback?{fallback:t.fallback}:{}}}function En(e){if(!et(e))return hr();let t=et(e.safety)?e.safety:{},n=et(t.overrides)?t.overrides:{},r=et(e.workflow)?e.workflow:{},o=et(e.destructive_command_protection)?e.destructive_command_protection:{},i=et(e.secret_protection)?e.secret_protection:{};return{version:1,safety:{level:Sb.has(t.level)?t.level:"standard",overrides:{...typeof n.fail_closed==="boolean"?{fail_closed:n.fail_closed}:{},...typeof n.paranoid_rm==="boolean"?{paranoid_rm:n.paranoid_rm}:{},...typeof n.paranoid_interpreters==="boolean"?{paranoid_interpreters:n.paranoid_interpreters}:{}}},workflow:{worktree_mode:typeof r.worktree_mode==="boolean"?r.worktree_mode:!1},destructive_command_protection:{enabled:typeof o.enabled==="boolean"?o.enabled:!0,overrides:ed(o.overrides,to),allow_paths:Eb(o.allow_paths)},secret_protection:{enabled:typeof i.enabled==="boolean"?i.enabled:!0,overrides:ed(i.overrides,Ko),deny_paths:Rb(i.deny_paths),allow_paths:xb(i.allow_paths)},audit:{retention_days:Yr(et(e.audit)?e.audit.retention_days:void 0)}}}function ed(e,t){if(!et(e))return{};return Object.fromEntries(Object.entries(e).flatMap(([n,r])=>t.has(n)&&(r==="on"||r==="off")?[[n,r]]:[]))}function Rb(e){if(!Array.isArray(e))return[];let t=Wt();return e.filter((n)=>Jo(n,t)===null)}function Eb(e){if(!Array.isArray(e))return[];let t=Wt();return e.filter((n)=>Xo(n,t)===null)}function xb(e){if(!Array.isArray(e))return[];let t=Wt();return e.filter((n)=>Qo(n,t)===null)}function et(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function hr(){return structuredClone(ii)}function wb(e){let t=_b();if(!na(e)){let n=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!et(n))return{policy:t,errors:[]};return{policy:td(En(n)),errors:[]}}try{let n=ra(e,"utf-8");if(!n.trim())return{policy:t,errors:[`${e}: Config file is empty`],fallback:"defaults"};let r=JSON.parse(n),o=gr(r),i=td(En(r));if(o.length>0)return{policy:i,errors:o.map((s)=>`${e}: ${s}`),fallback:et(r)?"salvaged":"defaults"};return{policy:i,errors:[]}}catch(n){let r=n instanceof Error?n.message:String(n);return{policy:t,errors:[`${e}: ${n instanceof SyntaxError?"Invalid JSON":r}`],fallback:"defaults"}}}function od(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...Nu].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function _b(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:od({}),denyPaths:[],allowPaths:[]}}}function td(e){return{safety:id(e.safety),worktreeMode:e.workflow.worktree_mode,destructiveCommandProtectionEnabled:e.destructive_command_protection.enabled,destructiveCommandRuleOverrides:e.destructive_command_protection.overrides,destructiveCommandAllowPaths:e.destructive_command_protection.allow_paths,secretProtection:{enabled:e.secret_protection.enabled,disabledRules:od(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function id(e){let t={...e.overrides.fail_closed!==void 0?{failClosed:e.overrides.fail_closed}:{},...e.overrides.paranoid_rm!==void 0?{paranoidRm:e.overrides.paranoid_rm}:{},...e.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:e.overrides.paranoid_interpreters}:{}};return{level:e.level,...Object.keys(t).length>0?{overrides:t}:{}}}import{dirname as gt}from"node:path";var sd="Rulebook exceeds CC Safety Net's safe validation limits.",ad="Additional rulebook validation errors were omitted.",Ge=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function ld(e){if(oa(e.allowed_commands,Ge.maxAllowedCommands)||oa(e.rules,Ge.maxRules)||oa(e.tests,Ge.maxTests))return!1;let{maxAggregateStringCodeUnits:t,maxTotalBlockArgs:n}=Ge,r=(o,i=!1)=>{if(typeof o!=="string")return!0;if(o.length>Ge.maxStringCodeUnits||i&&o.length>Ge.maxFixtureCommandCodeUnits||o.length>t)return!1;return t-=o.length,!0};if(!r(e.name)||!r(e.version)||!r(e.description)||!r(e.author)||!r(e.migrated_from))return!1;if(Array.isArray(e.allowed_commands)){for(let o of e.allowed_commands)if(!r(o))return!1}if(Array.isArray(e.rules))for(let o of e.rules){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.name)||!r(i.command)||!r(i.subcommand)||!r(i.reason)||!r(i.intent))return!1;if(!Array.isArray(i.block_args))continue;if(i.block_args.length>Ge.maxBlockArgsPerRule||i.block_args.length>n)return!1;n-=i.block_args.length;for(let s of i.block_args)if(!r(s))return!1}if(Array.isArray(e.tests))for(let o of e.tests){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.command,!0)||!r(i.expect)||!r(i.rule))return!1}return!0}function oa(e,t){return Array.isArray(e)&&e.length>t}function Pb(e){if(!Ab(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!ld(e))return{errors:[sd],ruleNames:new Set};let t=qu().safeParse(e),n=[...e.rulebook_version===1?[]:["rulebook_version must be 1"],...t.success?[]:vn(t.error.issues,": ",": ")];return{errors:n.length>Ge.maxValidationErrors?[...n.slice(0,Ge.maxValidationErrors),ad]:n,ruleNames:new Set(ta(e).map((r)=>r.toLowerCase()))}}function wn(e){let t=Pb(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}function Ab(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}var kb=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#([A-Za-z0-9._-]+)$/;function si(e){if(an(e.spec))return Ib(e);return Tb(e)}function Tb(e){if(!_e.test(e.spec))return`Local rulebook sources must be bare names matching ${_e}: ${e.spec}`;if(e.kind!=="local-directory")return`lock entry for ${e.spec} must use local-directory kind`;if(e.path===e.spec&&e.name===e.spec)return null;return`lock entry for ${e.spec} does not match local source identity`}function Ib(e){let t=jn(e.spec);if(t)return t;let n=sn(e.spec);if(e.kind!=="github")return`lock entry for ${e.spec} must use github kind`;if(e.owner===n.owner&&e.repo===n.repo&&e.ref===n.ref&&e.path===n.path&&e.name===n.name)return null;return`lock entry for ${e.spec} does not match GitHub source identity`}function cT(e,t,n){let r=ud(e.rules,n);if(r.length>0)return{ok:!0,specs:r};if(!t)return{ok:!1,result:{ok:!1,errors:[`No lockfile available to match rulebook name ${n}; use the exact source or run ${Ne}`],warnings:[],entries:[]}};let o=new Set(e.rules),i=t.rulebooks.filter((s)=>s.name===n&&o.has(s.spec)).map((s)=>s.spec);if(i.length===1)return{ok:!0,specs:i};return cd(n,i)}function uT(e,t,n){let r=ud(e,n);if(r.length>0)return{ok:!0,specs:r};let o=Ob(e,n);if(o.length>0)return{ok:!0,specs:o};let i=Db(e,n);if(!i.ok)return i;if(i.specs.length>0)return{ok:!0,specs:i.specs};let s=t?e.filter((a)=>t.rulebooks.find((l)=>l.spec===a)?.name===n):[];if(s.length===1)return{ok:!0,specs:s};return cd(n,s)}function cd(e,t){return{ok:!1,result:{ok:!1,errors:t.length===0?[`No configured rulebook matches ${e}`]:[`Ambiguous rulebook match ${e}: ${t.join(", ")}`],warnings:[],entries:[]}}}function ud(e,t){return e.filter((n)=>n===t)}function Ob(e,t){let n=t.match(kb),r=n?.[1],o=n?.[2],i=n?.[3];if(!r||!o||!i)return[];return md(e,(s)=>s.owner===r&&s.repo===o&&s.ref===i)}function Db(e,t){if(!Ol(t))return{ok:!0,specs:[]};let[n,r]=t.split("/"),o=md(e,(s)=>s.owner===n&&s.repo===r);if(new Set(o.map((s)=>dd(s)?.ref).filter((s)=>!!s)).size<2)return{ok:!0,specs:o};return{ok:!1,result:{ok:!1,errors:[`Multiple refs are configured for ${t}. Use an explicit ref:`,` cc-safety-net rule remove ${t}#<ref>`],warnings:[],entries:[]}}}function dd(e){try{return sn(e)}catch{return null}}function md(e,t){return e.filter((n)=>{let r=dd(n);return r?t(r):!1})}function ia(e){let t=typeof e==="string"?e:e.path;try{let n=at(typeof e==="string"?Br(e):e);if(n===null)return{lock:null,errors:[]};let r=JSON.parse(n);if(!r||typeof r!=="object")return{lock:null,errors:[`malformed lockfile ${t}: must be an object`]};let o=r;if(o.version!==1||!Array.isArray(o.rulebooks))return{lock:null,errors:[`malformed lockfile ${t}`]};let i=Ku().safeParse(o),s=o.rulebooks.flatMap((l,c)=>{let u=i.success?[]:i.error.issues.filter((f)=>f.path[1]===c);if(u.length>0)return vn(u).map((f)=>`${t}: ${f}`);let m=si(l);return m?[`${t}: rulebooks[${c}]: ${m}`]:[]});if(!i.success||s.length>0)return{lock:null,errors:[`malformed lockfile ${t}`,...s]};return{lock:{version:1,rulebooks:i.data.rulebooks.map((l)=>{if(l.kind==="local-directory")return{spec:l.spec,kind:l.kind,path:l.path,name:l.name,version:l.version,digest:l.digest};let c={spec:l.spec,kind:l.kind,owner:l.owner,repo:l.repo,ref:l.ref,commit:l.commit,path:l.path,name:l.name,version:l.version,digest:l.digest};return typeof l.display_ref==="string"&&l.display_ref!==""?{...c,display_ref:l.display_ref}:c})},errors:[]}}catch(n){if(n instanceof N)return{lock:null,errors:[n.message]};return{lock:null,errors:["malformed lockfile"]}}}import{createHash as Mb}from"node:crypto";import{dirname as ai,join as Nb}from"node:path";var gd=Object.freeze({timeoutMs:15000,metadataBytes:524288,commitBytes:262144,treeBytes:16777216,rawBytes:4194304});async function fd(e,t,n,r=we(ai(ai(t)),"rules policy"),o=ti()){if(an(e))return Wb(e,o);return Lb(e,t,n,r)}async function xT(e,t,n,r,o,i=ti()){if(!an(e)||n.refresh)return fd(e,t,n,o,i);let s=r?.rulebooks.find((a)=>a.spec===e);if(!s||s.kind!=="github")return fd(e,t,n,o,i);return Fb(s,t,n,o,i)}async function wT(e,t=ti()){let[n,r]=e.split("/");if(!n||!r)throw Error(`Invalid GitHub repository source: ${e}`);let o=await yr(`https://api.github.com/repos/${n}/${r}`,"metadata",t),i=o.response;if(!i.ok)throw Error(`Failed to inspect ${e}: GitHub returned ${i.status}`);let a=JSON.parse(o.content)?.default_branch;if(typeof a!=="string"||a==="")throw Error(`Failed to inspect ${e}: missing default branch`);let l=await yd(n,r,a,e,t),c=await yr(`https://api.github.com/repos/${n}/${r}/git/trees/${l}?recursive=1`,"tree",t),u=c.response;if(!u.ok)throw Error(`Failed to inspect ${e}: GitHub tree returned ${u.status}`);let m=JSON.parse(c.content);if(!Array.isArray(m?.tree))throw Error(`Failed to inspect ${e}: unexpected GitHub tree response`);let d=m.tree.flatMap((p)=>{if(!p||typeof p!=="object")return[];let g=p;if(g.type!=="blob"||typeof g.path!=="string")return[];let y=g.path.match(Xi);return y?.[1]?[y[1]]:[]}).sort();if(d.length===0)throw Error(`No rulebooks found in ${e} under ${jr}/`);return d.map((p)=>({spec:`${n}/${r}#${l}/${p}`,display_ref:a}))}function Lb(e,t,n,r){Ji(e);let o=Bb(t,e),i=at(ie(r,o));if(i===null)throw Error(`Rulebook source not found: ${e}`);let s=wn(sa(i,"Invalid local rulebook source."));if(s.name!==e)throw Error(`rulebook name "${s.name}" must match local source "${e}"`);return{rulebook:s,content:i,entry:{spec:e,kind:"local-directory",path:e,name:s.name,version:s.version,digest:_n(i)}}}async function Wb(e,t){let n=sn(e),r=await yd(n.owner,n.repo,n.ref,e,t),o=await yr(`https://raw.githubusercontent.com/${n.owner}/${n.repo}/${r}/${n.path}`,"raw",t),i=o.response;if(!i.ok)throw Error(`Failed to fetch ${e}: GitHub raw returned ${i.status}`);let s=o.content,a=wn(sa(s,"Invalid GitHub rulebook response."));if(a.name!==n.name)throw Error(`rulebook name "${a.name}" must match GitHub source "${n.name}"`);return{rulebook:a,content:s,entry:{spec:e,kind:"github",owner:n.owner,repo:n.repo,ref:n.ref,commit:r,path:n.path,name:a.name,version:a.version,digest:_n(s)}}}async function Fb(e,t,n,r=we(ai(ai(t)),"rules policy"),o){let i=si(e);if(i)throw Error(`${i}; run ${Ne}`);let s=qr(e,Kr(t,n)),a=at(ie(r,s));if(a!==null){if(_n(a)===e.digest)return{entry:e,rulebook:hd(a,e),content:a}}return Gb(e,o)}async function Gb(e,t){let n=await yr(`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.commit}/${e.path}`,"raw",t),r=n.response;if(!r.ok)throw Error(`Failed to restore ${e.spec}: GitHub raw returned ${r.status}`);let o=n.content;if(_n(o)!==e.digest)throw Error(`locked GitHub digest mismatch for ${e.spec}; run ${Ne}`);return{entry:e,rulebook:hd(o,e),content:o}}function hd(e,t){let n=wn(sa(e,"Invalid cached rulebook."));if(n.name!==t.name)throw Error(`rulebook name "${n.name}" must match lock entry "${t.name}"`);return n}function sa(e,t){try{return JSON.parse(e)}catch{throw Error(t)}}async function yd(e,t,n,r,o){let i=await yr(`https://api.github.com/repos/${e}/${t}/commits/${encodeURIComponent(n)}`,"commit",o),s=i.response;if(!s.ok)throw Error(`Failed to resolve ${r}: GitHub returned ${s.status}`);let a=JSON.parse(i.content);if(typeof a?.sha!=="string"||a.sha==="")throw Error(`Failed to resolve commit for ${r}`);return a.sha}async function zb(e,t,n={}){if(n.signal?.aborted)throw n.signal.reason;let r=n.budget??ei(),o=new AbortController,i=()=>o.abort(n.signal?.reason);n.signal?.addEventListener("abort",i,{once:!0});let s=!1,a=setTimeout(()=>{if(o.signal.aborted)return;s=!0,o.abort()},n.timeoutMs??gd.timeoutMs);try{if(n.signal?.aborted)throw n.signal.reason;$u(r);let l=await(n.fetch??fetch)(e,{signal:o.signal,redirect:"error"});if(!l.ok)return Cd(l),{response:l,content:""};return{response:l,content:await $b(l,t,r,()=>o.abort())}}catch(l){if(s)throw Error("GitHub request timed out",{cause:l});if(n.signal?.aborted)throw n.signal.reason;throw l}finally{clearTimeout(a),n.signal?.removeEventListener("abort",i)}}function yr(e,t,n){return zb(n.resolveUrl?.(e)??e,t,{budget:n.budget,signal:n.controller.signal})}async function $b(e,t,n=ei(),r){let o=gd[`${t}Bytes`],i=Number(e.headers.get("content-length"));if(Number.isFinite(i)&&i>o)throw Cd(e),Error(`GitHub ${t} response exceeds ${o} bytes`);if(!e.body)return"";let s=e.body.getReader(),a=[],l=0;while(!0){let c=await s.read();if(c.done)break;try{Bu(n,c.value.byteLength)}catch(u){throw r?.(),pd(s),u}if(l+=c.value.byteLength,l>o)throw r?.(),pd(s),Error(`GitHub ${t} response exceeds ${o} bytes`);a.push(Buffer.from(c.value))}return Buffer.concat(a,l).toString("utf-8")}function Cd(e){if(!e.body)return;bd(()=>e.body?.cancel())}function pd(e){bd(()=>e.cancel())}function bd(e){try{Promise.resolve(e()).catch(()=>{})}catch{}}function Bb(e,t){return Nb(e,t,Hr)}function _n(e){return`sha256:${Mb("sha256").update(e).digest("hex")}`}function Rd(e={}){let t=Gl(e),n=!1;try{n=wl(t.userConfigTarget,t.projectConfigTarget)}catch(f){if(f instanceof N)return Kb(t,f.message);throw f}let r=Rn(t.userConfigTarget),o=n?{config:null,errors:[]}:Rn(t.projectConfigTarget),i=vd(t.userConfigPath,r.errors),s=vd(t.projectConfigPath,o.errors),a=new Set,l=r.config?aa(r.config,t.userLockPath,gt(t.userConfigPath),e,"user",t.userScope,a):Cr(),c=o.config?aa(o.config,t.projectLockPath,gt(t.projectConfigPath),e,"project",t.projectScope,a):Cr(),u=r.config?.overrides??{},m=o.config?.overrides??{};return{rules:[...Sd(l.rules,u),...Sd(c.rules,m)],transparent_wrappers:Vb(r.config,o.config),rulebooks:[...l.rulebooks,...c.rulebooks],errors:[...i,...s,...l.errors,...c.errors],warnings:[...l.warnings,...c.warnings,...l.canValidateOverrides?la(u,l.knownRuleIds,t.userConfigPath):[],...l.canValidateOverrides?qb(m,l.knownRuleIds,t.projectConfigPath):[],...c.canValidateOverrides?la(m,c.knownRuleIds,t.projectConfigPath):[]],userConfig:r.config??void 0,projectConfig:o.config??void 0,...t}}function MT(e,t){let n=t??we(gt(gt(e)),"rules policy"),r=Rn(ie(n,e)).config,o=ia(ie(n,Dt(e))).lock;if(!r||!o)return new Map;let i=new Set(r.rules);return new Map(o.rulebooks.filter((s)=>i.has(s.spec)).map((s)=>[s.spec,Bl(s)]))}function NT(e,t,n,r){let o=Ub(e,t,n,r);if(!o)return[];return[...o.scope.errors,...o.scope.warnings,...Hb(o.config,o.scope,e)]}function Ub(e,t,n,r){let o=r??we(gt(gt(e)),"rules policy"),i=Rn(ie(o,e)).config;if(!i)return null;return{config:i,scope:aa(i,t,gt(e),n,"project",o)}}function Hb(e,t,n){return t.canValidateOverrides?la(e.overrides??{},t.knownRuleIds,n):[]}function aa(e,t,n,r,o,i=we(gt(gt(n)),o==="user"?"user policy":"project policy"),s=new Set){let a;try{a=ie(i,t)}catch(y){if(y instanceof N)return{...Cr(),errors:[y.message],canValidateOverrides:!1};throw y}let l=ia(a);if(l.errors.length>0)return{...Cr(),errors:l.errors,canValidateOverrides:!1};let c=l.lock;if(!c&&e.rules.length>0)return{...Cr(),errors:[`missing lockfile ${t}; run ${Ne}`],canValidateOverrides:!1};let u=c?.rulebooks??[],m=new Map(u.map((y)=>[y.spec,y])),f=[],d=[],p=e.rules.flatMap((y)=>{let h=m.get(y);if(!h)return f.push(`missing lock entry for ${y}; run ${Ne}`),[];let R=jb(h,n,r,i);if(R.errors.length>0||!R.rulebook)return f.push(...R.errors),[];let E=R.rulebook;if(s.has(E.name))return d.push(`duplicate active rulebook name "${E.name}" for ${y}; keeping the first and ignoring this one, so its rules are not active; rename one of them, then run ${Ne}`),[];return s.add(E.name),[{rules:E.rules.map((A)=>({...A,name:`${E.name}/${A.name}`})),rulebook:{source:o,spec:h.spec,name:E.name,version:E.version,rules:E.rules.map((A)=>`${E.name}/${A.name}`)}}]}),g=p.flatMap((y)=>y.rules);return{rules:g,rulebooks:p.map((y)=>y.rulebook),entries:u,knownRuleIds:new Set(g.map((y)=>y.name)),errors:f,warnings:d,canValidateOverrides:f.length===0}}function jb(e,t,n,r){let o=qr(e,Kr(t,n)),i;try{i=at(ie(r,o))}catch(a){if(a instanceof N)return{rulebook:null,errors:[a.message]};throw a}if(i===null)return{rulebook:null,errors:[`missing cache entry for ${e.spec}; run ${Ne}`]};if(_n(i)!==e.digest)return{rulebook:null,errors:[`cache digest mismatch for ${e.spec}; run ${Ne}`]};let s;try{s=JSON.parse(i)}catch{return{rulebook:null,errors:[`invalid cached rulebook for ${e.spec}`]}}try{wn(s)}catch(a){return{rulebook:null,errors:[`invalid cached rulebook for ${e.spec}: ${a instanceof Error?a.message:"invalid rulebook"}`]}}return{rulebook:s,errors:[]}}function Vb(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function Sd(e,t){return e.flatMap((n)=>{let r=t[n.name];if(r==="off")return[];if(r&&typeof r==="object")return[{...n,intent:r.intent??n.intent,reason:r.reason}];return[n]})}function la(e,t,n){return Object.keys(e).filter((r)=>!t.has(r)).map((r)=>`unknown override key "${r}" in ${n}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function qb(e,t,n){return Object.keys(e).filter((r)=>t.has(r)).map((r)=>`project override cannot target user-scoped rule "${r}" in ${n}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function vd(e,t){return t.map((n)=>n.startsWith("Unable to access ")?n:`${e}: ${n}`)}function Kb(e,t){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath,userLockPath:e.userLockPath,projectLockPath:e.projectLockPath}}function Cr(){return{rules:[],rulebooks:[],entries:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}function Ed(e={}){let t=Rd(e),n=rd(e),r={rules:t.rules,transparentWrappers:t.transparent_wrappers,safety:n.safety,worktreeMode:n.worktreeMode,destructiveCommandProtectionEnabled:n.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:n.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:n.destructiveCommandAllowPaths,secretProtection:{enabled:n.secretProtection.enabled??!0,disabledRules:n.secretProtection.disabledRules??[],denyPaths:n.secretProtection.denyPaths,allowPaths:n.secretProtection.allowPaths??[]}},o={...t.userConfig?.overrides??{},...t.projectConfig?.overrides??{}},i=Object.freeze(Object.fromEntries(r.rules.map((s)=>{let a=t.rulebooks.find((c)=>c.rules.includes(s.name)),l=o[s.name];return[s.name,Object.freeze({id:s.name,...a?{rulebook:Object.freeze({name:a.name,version:a.version}),...Jb(a.spec)?{source:a.spec}:{}}:{},...l&&typeof l==="object"?{override:Object.freeze({type:"reason",reason:l.reason})}:{}})]})));return Qb(r,Zb(t,n),i)}function GT(e){if(e.state==="ready")return{state:e.state};return{state:e.state,reason:e.reason}}function Zb(e,t){let n=Xb(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:eS(e.errors.length>0?Yb(e.errors):void 0,e.warnings.length>0?ca(e.warnings.join("; ")):void 0,n)}}function Yb(e){return`${ca(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Xb(e){if(e.errors.length===0)return;let t=e.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${e.errors.join("; ")}. Enforcing ${t}; the invalid values are not active. Fix the policy file manually`}function Jb(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function Qb(e,t,n=Object.freeze({})){let r=xd(structuredClone(e));if(!t)return Object.freeze({state:"ready",policy:r,diagnostics:Object.freeze([]),ruleMetadata:n});return Object.freeze({state:"degraded",policy:r,diagnostics:Object.freeze([...t.diagnostics]),reason:t.reason,ruleMetadata:n})}function xd(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))xd(t);return Object.freeze(e)}function eS(...e){return ca(e.filter((t)=>!!t).join("; "))}function ca(e){return/[.!?]$/.test(e)?e:`${e}.`}function I(e){return e.provenance==="command-substitution"?e.raw:e.text}function Pn(e,t){return e==="posix"?t:G(t.map((n)=>n.text))}function li(e,t){return e&&e.provenance!=="unknown"?e.provenance==="literal":!/[$`*?[\]]/.test(t)}function G(e){return e.map((t)=>({kind:"word",text:t,raw:t,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function ht(e,t){tr(t,e,2);let n=e.toLowerCase(),r=n.trimStart(),o=r.startsWith("echo ")||r.startsWith("rg "),i=[{scan:"rm",label:"rm -rf"},{scan:"reset-hard",label:"git reset --hard"},{scan:"reset-merge",label:"git reset --merge"},{scan:"clean",label:"git clean -f"},{scan:"checkout",label:"git checkout --force"},{scan:"push-force",label:"git push --force"},{scan:"push-refspec",label:"git push --force"},{scan:"push-delete",label:"git push delete"},{scan:"branch",label:"git branch -D",caseSensitive:!0},{scan:"tag",label:"git tag -d"},{regex:/\bgit\s+stash\s+(drop|clear)\b/,label:"git stash drop/clear"},{regex:/\bgit\s+checkout\s+--\s/,label:"git checkout --"},{scan:"restore",label:"git restore without --staged"},{scan:"find",label:"find -delete",skipForEchoRg:!0},{regex:/\bdd\b[^\n|;&]*\bof=\/dev\/\S/,label:"dd of=/dev/",skipForEchoRg:!0},{regex:/\bmkfs(?:\.[a-z0-9_-]+)?\s+\/dev\/\S/,label:"mkfs /dev/",skipForEchoRg:!0},{regex:/\bshred\b\s+\S/,label:"shred",skipForEchoRg:!0}];for(let s of i){if(s.skipForEchoRg&&o)continue;let a=s.caseSensitive?e:n;if(s.regex)he(t,a);if((s.regex?.test(a)??!1)||s.scan&&No(a,s.scan,t))return b("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${s.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var tS=/^[A-Za-z_][A-Za-z0-9_]*=/;function _d(e,t,n){let r=e.words[0];if(!t||!r||e.words.length!==1||e.dialect!=="posix")return!1;if(!r.quoted||r.provenance!=="literal")return!1;let o=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r.text)?.[1];if(!o)return!1;tr(n,t.source,2);let i={anchored:new RegExp(`^\\$\\{?${o}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${o}(?![A-Za-z0-9_])`)};return Pd(t.nodes,r,i)}function Pd(e,t,n){return e.every((r)=>{if(r.kind==="connector")return!0;if(r.kind==="group"||r.kind==="function")return Pd(r.body.nodes,t,n);if(r.kind==="unknown")return!n.loose.test(r.source);return nS(r,t,n)})}function nS(e,t,n){if(e.nested.some((o)=>n.loose.test(o.source)))return!1;let r=e.words.findIndex((o)=>!tS.test(o.text));return e.words.every((o,i)=>o===t||wd(o.raw,n.anchored,i!==r))&&e.redirections.every((o)=>(!o.heredoc||o.heredoc.quotedDelimiter||!n.loose.test(o.heredoc.body))&&(!o.target||wd(o.target.raw,n.anchored,!0)))}function wd(e,t,n){let r=!1,o=!1;for(let i=0;i<e.length;i++){let s=e[i];if(s==="\\"&&!r){i++;continue}if(!o&&s==="'"){r=!r;continue}if(!r&&s==='"'){o=!o;continue}if(r||s!=="$")continue;if(!t.test(e.slice(i)))continue;if(!o||!n)return!1}return!0}var Ad=Object.freeze({maxDerivedTokens:16384}),kd="Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry.";class be extends Error{constructor(){super("Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry.");this.name="DerivedCommandWorkLimitError"}}function ci(){return{derivedTokens:0}}function ze(e,t){if(!Number.isSafeInteger(e.derivedTokens)||e.derivedTokens<0||e.derivedTokens>Ad.maxDerivedTokens||!Number.isSafeInteger(t)||t<0||t>Ad.maxDerivedTokens-e.derivedTokens)throw new be;e.derivedTokens+=t}import{isAbsolute as rS,resolve as Td}from"node:path";var Id=64;function br(e,t,n){let r=rS(e)?Td(e):t?Td(t,e):void 0;if(!r)return;try{return U(r,n)}catch{return r}}function Od(e){return!["/dev","/proc","/sys"].some((t)=>e===t||e.startsWith(`${t}/`))}var B=Object.freeze({maxChildAnalyses:1024,maxDerivedTokens:16384,maxDerivedBytes:1048576,maxPlaceholderReplacements:16384}),Dd="Parallel command expands beyond CC Safety Net's analysis limits. Reduce the template or explicit argument list and retry.";class di extends Error{constructor(){super("Parallel command expands beyond CC Safety Net's analysis limits. Reduce the template or explicit argument list and retry.");this.name="ParallelAnalysisLimitError"}}function Md(){return{childAnalyses:0,derivedTokens:0,derivedBytes:0,placeholderReplacements:0}}function Se(e,t){let n=t.childAnalyses??0,r=t.derivedTokens??0,o=t.derivedBytes??0,i=t.placeholderReplacements??0;if(ui(e.childAnalyses,n,B.maxChildAnalyses)||ui(e.derivedTokens,r,B.maxDerivedTokens)||ui(e.derivedBytes,o,B.maxDerivedBytes)||ui(e.placeholderReplacements,i,B.maxPlaceholderReplacements))throw new di;e.childAnalyses+=n,e.derivedTokens+=r,e.derivedBytes+=o,e.placeholderReplacements+=i}function ui(e,t,n){return!Number.isSafeInteger(e)||e<0||e>n||!Number.isSafeInteger(t)||t<0||t>n-e}import{isAbsolute as ya,normalize as GS,parse as zS,posix as rm,resolve as Tn,sep as ha}from"node:path";import{isAbsolute as oS,join as Nd,normalize as Fd,parse as iS,sep as Ld}from"node:path";var sS=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],aS=`
|
|
51
|
+
`;function Sr(e,t){if(tt(e,t))return!0;if(!e.has("TMPDIR"))return!1;return!ua(e.get("TMPDIR")??"",t)}function yt(e,t){if(e.has("TMPDIR"))return ua(e.get("TMPDIR")??"",t);let n=da(e,t);if(n===void 0)return!0;return ua(n,t)}function da(e,t){return $d(e,t,"TMPDIR")}function ua(e,t){if(!e)return!1;if(cS(e))return!1;return ma(e,t)}function tt(e,t){let n=$d(e,t,"IFS");return n!==void 0&&n!==""&&n!==aS}function ma(e,t){let n=mi(e,t.paths);return n!==null&&zd(t).some((r)=>dS(n,r))}function Gd(e,t){let n=mi(e,t.paths);return n!==null&&zd(t).includes(n)}var Wd=new WeakMap;function zd(e){let t=Wd.get(e);if(t)return t;let n=lS(e);return Wd.set(e,n),n}function lS(e){let t=sS.map((r)=>mi(r,e.paths)??Fd(r)),n=mi(e.tmpdir,e.paths);if(!n)return t;if(process.platform==="win32")return[...t,n];if(process.platform==="darwin"&&uS(n))return[...t,n];return t}function cS(e){return/[\s$`*?[]/.test(e)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(e)||/[+@!]\([^)]*\)/.test(e)}function $d(e,t,n){return e.has(n)?e.get(n):t.env.get(n)}function uS(e){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(e)}function mi(e,t){try{let n=Fd(e);if(!oS(n))return n;let r=iS(n).root,o=n.slice(r.length).split(/[\\/]+/).filter(Boolean),i=r;for(let s=0;s<o.length;s++){let a=Nd(i,o[s]??"");if(t.entryKind(a)==="missing")return Nd(a,...o.slice(s+1));let l=t.realpath(a);if(l===null)return null;i=l}return i}catch{return null}}function dS(e,t){if(e===t)return!0;let n=t.endsWith(Ld)?t:`${t}${Ld}`;return e.startsWith(n)}import{statSync as TS}from"node:fs";import{isAbsolute as Yd,join as IS,relative as Xd}from"node:path";import{isAbsolute as Bd,parse as mS}from"node:path";var Hd=/^[A-Za-z_][A-Za-z0-9_]*=/;function Te(e){if(!Hd.test(e))return null;let t=e.indexOf("=");return{name:e.slice(0,t),value:e.slice(t+1)}}function fi(e){let t=new Map,n=0;while(n<e.length){let r=e[n];if(!r)break;let o=Te(I(r));if(!o)break;t.set(o.name,o.value),n++}return{words:e.slice(n),envAssignments:t}}function jd(e){let t=e.toLowerCase();return e.includes("=")||t==="sudo"||t==="env"||t==="command"||t==="builtin"}function Ut(e,t,n,r){if(!jd(An(e)))return{words:e,envAssignments:new Map,cwd:n,rewritten:!1};let o=new Set(e),i=e,s=new Map,a=new Map(r??[]),l=[],c=n;for(let m=0;m<un;m++){let f=Ud(i),d=fi(i);for(let[g,y]of d.envAssignments)s.set(g,y),a.set(g,y);if(i=d.words,i.length===0)break;while(i.length>0&&An(i).includes("=")&&!pS(i)){let g=gS(An(i),a,t.env)??To(An(i),t.env,a);if(g)s.set(g.name,g.value),a.set(g.name,g.value);i=i.slice(1)}if(i.length===0)break;let p=An(i).toLowerCase();if(p!=="sudo"&&p!=="env"&&p!=="command"&&p!=="builtin")break;if(p==="sudo"){let g=yS(i,t.paths,c);if(i=g.words,g.cwd!==void 0)c=g.cwd}if(p==="env"){let g=SS(i,c,a,t);if(l.push(...g.envSplitValues??[]),i=g.words,g.cwd!==void 0)c=g.cwd;for(let[y,h]of g.envAssignments)s.set(y,h),a.set(y,h)}if(p==="command")i=vS(i);if(p==="builtin")i=i.slice($e(i,1)==="--"?2:1);if(Ud(i)===f)break}let u=fi(i);for(let[m,f]of u.envAssignments)s.set(m,f),a.set(m,f);return{words:u.words,envAssignments:s,cwd:c,envSplitValues:l.length>0?l:void 0,rewritten:fS(u.words,o)}}function fS(e,t){return e.some((n)=>!t.has(n))}function Ud(e){return e.map(I).join(" ")}function An(e){let t=e[0];return t?I(t):""}function $e(e,t){let n=e[t];return n?I(n):void 0}function pS(e){return Hd.test(An(e))}function gS(e,t,n){if(!e.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${t.get("TMPDIR")??n.get("TMPDIR")??""}${e.slice(8)}`}}var hS=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function yS(e,t,n){let r=1,o=n;while(r<e.length){let i=$e(e,r);if(!i)break;if(i==="--")return{words:e.slice(r+1),cwd:o};if(!i.startsWith("-"))break;if(i==="-D"||i==="--chdir"){let s=$e(e,r+1);o=s?vr(o,s,t):null,r+=2;continue}if(i.startsWith("--chdir=")){o=vr(o,i.slice(8),t),r++;continue}if(i.startsWith("-D")&&i.length>2){o=vr(o,i.slice(2),t),r++;continue}if(i==="-i"||i==="--login"){o=null,r++;continue}if(hS.has(i)){r+=2;continue}r++}return{words:e.slice(r),cwd:o}}var CS=new Set(["-i","-0","--null"]),bS=new Set(["-u","--unset","-C","--chdir","-P"]);function SS(e,t,n,r){let o=new Map,i=[],s=t,a=1,l=(c)=>({words:e.slice(c),envAssignments:o,cwd:s,envSplitValues:i.length>0?i:void 0});while(a<e.length){let c=$e(e,a);if(!c)break;if(c==="--")return l(a+1);if(c==="-i"||c==="--ignore-environment"||c==="-"){o.clear();for(let m of n.keys())o.set(m,"");o.set("TMPDIR",""),a++;continue}if(CS.has(c)){a++;continue}if(c==="-u"||c==="--unset"){let m=$e(e,a+1);if(m!==void 0)o.set(m,"");a+=2;continue}if(c.startsWith("-u")&&c.length>2&&!c.startsWith("-u=")){o.set(c.slice(2),""),a++;continue}if(c.startsWith("--unset=")){o.set(c.slice(8),""),a++;continue}let u=c==="-S"||c==="--split-string"?{value:$e(e,a+1),consumed:2}:c.startsWith("-S")&&c.length>2?{value:c.slice(2),consumed:1}:c.startsWith("--split-string=")?{value:c.slice(15),consumed:1}:null;if(u){if(u.value!==void 0)i.push(u.value);return s=null,l(a+u.consumed)}if(bS.has(c)){if(c==="-C"||c==="--chdir"){let m=$e(e,a+1);s=m?vr(s,m,r.paths):null}a+=2;continue}if(c.startsWith("-u=")){a++;continue}if(c.startsWith("-C")&&c.length>2||c.startsWith("--chdir=")){let m=c.startsWith("--chdir=")?c.slice(8):c.startsWith("-C=")?c.slice(3):c.slice(2);s=vr(s,m,r.paths),a++;continue}if(c.startsWith("-P")){a++;continue}if(c.startsWith("-")){a++;continue}if(!Te(c))break;while(a<e.length){let m=Te($e(e,a)??"");if(!m)break;o.set(m.name,m.value),a++}if($e(e,a)==="--")a++;return l(a)}return l(a)}function vr(e,t,n){if(t==="")return null;if(!e&&!Bd(t))return null;let r=Bd(t)?mS(t).root:n.realpath(e??"/");if(r===null)return null;try{return wt(r,t,n)}catch{return null}}function vS(e){if($e(e,1)==="-v")return[...G(["type"]),...e.slice(2)];let t=1;while(t<e.length){let n=$e(e,t);if(!n)break;if(n==="-p"||n==="-v"||n==="-V"){t++;continue}if(n==="--")return e.slice(t+1);if(n.startsWith("-")&&!n.startsWith("--")&&n.length>1){if(!/^[pvV]+$/.test(n.slice(1)))break;t++;continue}break}return e.slice(t)}var RS=/['"\\$`{}#]/;function pi(e,t){if(e.some((r)=>RS.test(r)))return null;let n=[...e.flatMap((r)=>r.split(/\s+/).filter((o)=>o.length>0)),...t];return n.length<=64?n:null}function kn(e,t,n){return gi(e,t,n).tokens}function ES(e){let t=[],n="",r=0;while(r<e.length){let o=e.charAt(r);if(o==='"'||o==="'"){let i=e.indexOf(o,r+1);if(i===-1)return e.split(/\s+/).map((s)=>s.replace(/["']/g,"")).filter((s)=>s.length>0);n+=e.slice(r+1,i),r=i+1;continue}if(/\s/.test(o)){if(n.length>0)t.push(n);n="",r++;continue}n+=o,r++}if(n.length>0)t.push(n);return t}function _t(e,t,n,r=0){let o=gi(e,t,n),i=(o.envSplitValues??[]).flatMap(ES);if(i.length===0)return o.tokens;let s=[...i,...o.tokens];if(r>=8)return s;return _t(s,t,n,r+1)}function gi(e,t,n,r){if(!jd(e[0]??""))return{tokens:[...e],envAssignments:new Map,cwd:n};let o=Ut(G(e),t,n,r);return{tokens:o.words.map(I),envAssignments:o.envAssignments,cwd:o.cwd,envSplitValues:o.envSplitValues}}import{basename as xS,isAbsolute as wS,normalize as _S,resolve as Vd}from"node:path";var PS=new Set(["-S","--suffix"]);function hi(e,t,n,r){if(e.status==="structural-limit")throw new Xe;if(e.status!=="complete")return r.findMalformedTarget(e.source);let o={cwd:t,variables:new Map},i=[];for(let s of e.entries){if(s.kind==="operator"){if(!s.boundary)continue;let a=r.findSegmentTarget(i,o);if(a)return a;o=AS(i,o,n,r.normalizeCwd),i=[];continue}if(s.kind==="redirection"){if(s.role==="file-write"&&s.target&&r.isRedirectionTarget(ve(s.target,o.variables),o))return s.target;continue}i.push(s.text)}return r.findSegmentTarget(i,o)}function ve(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(n,r,o,i)=>{let s=t.get(r);if(s===void 0)return n;let a=o.startsWith(":")?s!=="":!0;if(o.endsWith("-"))return a?s:ve(i,t);return a?ve(i,t):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(n,r)=>t.get(r)??n).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(n,r)=>t.get(r)??n)}function Rr(e){return e.length>0&&e.every((t)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t))}function qd(e,t,n){let r=n.environment.home,o=eo(e.trim(),n.environment).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?Vd(r,o.slice(2)):o;return _S(wS(i)?i:Vd(t,i))}function ce(e,t,n){let r=qd(e,t,n);if(!r)return"";return U(r,n.environment.paths,n).replace(/\\/g,"/")}function Kd(e,t,n,r){let o=qd(e,t,n);if(!o)return null;if(r(xS(o)))return U(o,n.environment.paths,n).replace(/\\/g,"/");let i=ac(o,n.environment.paths,n);return i===null?null:i.replace(/\\/g,"/")}function yi(e){let t=[],n=null,r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i===void 0)break;if(!r&&i==="--"){r=!0;continue}if(!r&&(i==="-t"||i==="--target-directory")){n=e[++o]??null;continue}if(!r&&i.startsWith("--target-directory=")){n=i.slice(19);continue}if(!r&&i.startsWith("-t")&&i.length>2){n=i.slice(2);continue}if(!r&&PS.has(i)){o++;continue}if(!r&&(i.startsWith("--suffix=")||i.startsWith("--backup=")))continue;if(!r&&i.startsWith("-"))continue;t.push(i)}return n?{sources:t,destination:n}:{sources:t.slice(0,-1),destination:t.at(-1)??null}}function AS(e,t,n,r){let o=Rr(e)?new Map([...t.variables,...kS(e,t.variables)]):t.variables,i=kn([...e],n.environment),s=M(i[0]??"").toLowerCase()==="cd"?i[1]:void 0;return{cwd:!s||s==="-"?t.cwd:r(ve(s,o),t.cwd,n),variables:o}}function kS(e,t){return e.flatMap((n)=>{let r=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(n),o=r?.[2]?.startsWith("=")?r[2].slice(1):void 0;return r?.[1]!==void 0&&o!==void 0?[[r[1],ve(o,t)]]:[]})}var Ie="Git metadata and hooks are protected. Ask the user before modifying them.";function Jd(e,t=pa([e.invocation.context.executionCwd,e.invocation.context.configCwd])){let n=Mt(mt()),r=e.invocation.context.executionCwd;if(!t)return null;if(e.invocation.route.kind==="patch"||e.invocation.route.kind==="path"||e.invocation.route.kind==="unknown"){if(so(e.invocation.toolName))return null;let s=e.paths.find((a)=>LS(a,r,t,n));return s?{target:s}:null}if(e.invocation.route.kind!=="command")return null;let o=ge(e,"input-candidate");if(!o)return null;let i=hi(o.shell,r,n,{findSegmentTarget:(s,a)=>FS(s,a,t,n),isRedirectionTarget:(s,a)=>WS(s,a.cwd,t,n),findMalformedTarget:()=>null,normalizeCwd:ce});return i?{target:i}:null}function pa(e,t=Mt(mt())){let n=[...new Map(e.filter((r)=>typeof r==="string"&&r!=="").flatMap((r)=>{let o=ar(ce(r,r,t));return o?[[Be(o),{dotGitPath:o,cwd:r}]]:[]})).values()].flatMap((r)=>OS(r.dotGitPath,r.cwd,t));if(n.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(n.map((r)=>r.entry))]),markerFiles:Object.freeze([...new Set(n.flatMap((r)=>r.markerFile?[r.markerFile]:[]))]),directories:Object.freeze([...new Set(n.flatMap((r)=>r.directories))]),hooksDirectories:Object.freeze([...new Set(n.flatMap((r)=>r.hooksDirectories))])})}function OS(e,t,n){try{let r=ce(e,t,n),o=TS(e),i=o.isFile()?r:null,s=o.isFile()?Hs(e):null,a=(o.isDirectory()?[r]:[s?.gitDir,s?.commonDir]).flatMap((c)=>c?[Be(ce(c,t,n))]:[]),l=[...new Set(o.isDirectory()?[Be(e.replace(/\\/g,"/")),...a]:a)];return[{entry:Be(r),markerFile:i?Be(i):null,directories:l,hooksDirectories:[...new Set(l.flatMap((c)=>{let u=Be(IS(c,"hooks"));return[u,Be(ce(u,t,n))]}))]}]}catch{return[]}}function Ht(e,t,n,r,o,i=!1){if(!n)return!1;let s=Be(ce(e,t,o)),a=s.replace(/(\/\.?\*+)+$/,"");if(a!==s&&a!==""){if(fa(a,n))return!0;let l=i||s.slice(a.length).includes("/."),c=(u)=>l?Ci(u,a):DS(u,a);if(n.markerFiles.some(c))return!0;return r&&Zd(n).some(c)}if(fa(s,n))return!0;return r&&Zd(n).some((l)=>Ci(l,s))}function DS(e,t){let n=Xd(t,e);if(n===""||n.startsWith("..")||Yd(n))return!1;return!n.split(/[\\/]/)[0]?.startsWith(".")}function MS(e,t,n,r){return Ht(e,t,n,!0,r)}function NS(e,t,n,r){if(!n)return!1;return fa(Be(ce(e,t,r)),n)}function LS(e,t,n,r){if(!n)return!1;return Qd(e,t,n,r,n.entries)}function WS(e,t,n,r){if(!n)return!1;return Qd(e,t,n,r,n.markerFiles)}function Qd(e,t,n,r,o){let i=Be(ce(e,t,r));return o.includes(i)||tm(i,n)}function em(e,t,n,r){if(!n)return!1;return n.hooksDirectories.some((o)=>e.some((i)=>Ci(o,Be(ce(i,t,r)))))}function fa(e,t){return t.entries.includes(e)||t.directories.includes(e)||tm(e,t)}function tm(e,t){return t.hooksDirectories.some((n)=>Ci(e,n))}function Zd(e){return[...e.entries,...e.directories,...e.hooksDirectories]}function Ci(e,t){let n=Xd(t,e);return n===""||!/^\.\.(?:[\\/]|$)/.test(n)&&!Yd(n)}function Be(e){return process.platform==="win32"?e.toLowerCase():e}function FS(e,t,n,r){if(Rr(e))return null;let o=_t([...e],r.environment);if(M(o[0]??"").toLowerCase()!=="mv")return null;let i=yi(o.slice(1)),s=i.sources.find((a)=>MS(ve(a,t.variables),t.cwd,n,r));if(s)return s;return i.destination&&NS(ve(i.destination,t.variables),t.cwd,n,r)?i.destination:null}var $S=process.platform==="win32",nm=64,BS=16384;function Er(e){let t=Wc(e,nm,nm,BS);return{expandedTargets:t&&"words"in t?t.words:void 0,unsafeBraceExpansion:t!==void 0&&"limited"in t,targetIsLiteral:t===void 0&&e.provenance==="literal"&&(e.quoted||e.raw!==e.text),tmpdirWordSplittingProtected:US(e)}}function US(e){let t=e.parts.filter((n)=>n.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(n.raw));return t.length>0&&t.every((n)=>HS(e.raw,n.span.start-e.span.start))}function HS(e,t){let n=null,r=!1;for(let o=0;o<t;o++){let i=e[o];if(r){r=!1;continue}if(i==="\\"&&n!=="'"){r=!0;continue}if(n===i){n=null;continue}if(n===null&&(i==="'"||i==='"'))n=i}return n==='"'}function jt(e){let t=e.environment.home,n=e.environment.paths,r=Mt(e.environment);return{anchoredCwd:e.originalCwd??e.cwd??null,resolvedCwd:e.cwd??null,strict:e.strict??!1,paranoid:e.paranoid??!1,trustTmpdirVar:e.allowTmpdirVar??!0,posixShell:e.posixShell??!1,tmpdirWordSplittingUnsafe:e.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:e.trustedTmpdirValue??e.allowTmpdirVar??!0,environment:e.environment,allowRoots:ZS(e.allowPaths,t,n,r),protectedGitMetadata:e.protectedGitMetadata,pathCanonicalizationContext:r}}function Ue(e,t,n={}){let r=n.targetIsLiteral??!1;if(!r&&t.tmpdirWordSplittingUnsafe&&!n.tmpdirWordSplittingProtected&&XS(e))return{kind:"outside_anchored_cwd"};let o=!r&&sm(e,t.posixShell);if(zt(e))return{kind:"outside_anchored_cwd"};if(Ca(e,r))return{kind:"root_or_home_target"};if(jS(e,t,r))return{kind:"root_or_home_target"};if(t.resolvedCwd&&Ht(e,t.resolvedCwd,t.protectedGitMetadata,!0,t.pathCanonicalizationContext,!t.posixShell))return{kind:"git_metadata_target"};if(VS(e,t.trustTmpdirVar,t.posixShell,o,r,n.tmpdirWordSplittingProtected??!1,t.trustedTmpdirValue,t.environment))return{kind:"temp_target"};if(o)return{kind:"dynamic_target"};if(YS(e,t,r))return{kind:"temp_target"};let i=t.anchoredCwd;if(i){if(!n.skipHomeCwd&&tv(i,t.environment.home,t.environment.paths,t.pathCanonicalizationContext))return{kind:"home_cwd_target"};if(!n.skipCwdSelf&&nv(e,t.resolvedCwd??i,t.environment.paths,t.pathCanonicalizationContext))return{kind:"cwd_self_target"};if(rv(e,i,t.resolvedCwd??i,o,r,t.environment.paths,t.pathCanonicalizationContext))return{kind:"within_anchored_cwd"}}return{kind:"outside_anchored_cwd"}}function om(e,t,n={}){let{containmentTarget:r,...o}=n;if(Ue(e,t,o).kind!=="temp_target")return!1;let i=e.trim();if(KS(i))return!1;if(Gd(i,t.environment))return!1;return![t.anchoredCwd,t.resolvedCwd].some((s)=>ov(r??i,s,t.environment.paths,t.pathCanonicalizationContext))}function Ca(e,t=!1){let n=e.trim(),r=rm.normalize(n),o=n.replace(/\\/g,"/"),i=r==="/"?r:r.replace(/\/+$/,"");if(i==="/"||i.startsWith("/")&&i.slice(1).split("/").every((s)=>/^\*+$/.test(s)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(o)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(o))return!0;if(!t&&(r==="~"||r==="~/"||r==="~/*"))return!0;if(!t&&(r==="$HOME"||r==="$HOME/"||r==="$HOME/*"))return!0;if(!t&&(r==="${HOME}"||r==="${HOME}/"||r==="${HOME}/*"))return!0;return!1}function jS(e,t,n){let r=e.trim(),o=n?r:r==="*"?".":r.endsWith("/*")?r.slice(0,-2):r;if(!o)return!1;try{let i=ya(o)?o:t.resolvedCwd?Tn(t.resolvedCwd,o):null;if(!i)return!1;let s=fe(U(i,t.environment.paths,t.pathCanonicalizationContext));if(s===zS(s).root)return!0;return s===fe(U(t.environment.home,t.environment.paths,t.pathCanonicalizationContext))}catch{return!1}}function fe(e){let t=GS(e);if($S){if(t=t.replace(/\//g,"\\").toLowerCase(),t.length>3&&t.endsWith("\\"))t=t.slice(0,-1);return t}if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);return t}function VS(e,t,n,r,o,i,s,a){let l=e.trim();if(im(l))return!1;if(!r&&ma(l,a))return!0;return(t||i&&s)&&n&&!o&&qS(l,n)}function qS(e,t){return["$TMPDIR","${TMPDIR}"].some((n)=>{if(e===n)return!0;if(!e.startsWith(`${n}/`))return!1;return!sm(e.slice(n.length+1),t)})}function KS(e){let t=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(e);if(!t)return!1;return rm.normalize(`/${t[1]??""}`)==="/"}function im(e){return e.split(/[\\/]+/).includes("..")}function ZS(e,t,n,r){if(!e?.length)return[];return e.flatMap((o)=>{let i=mr(o.trim(),t);if(!ya(i))return[];try{let s=U(i,n,r);if(fr(s,U(t,n,r)))return[];return[fe(s)]}catch{return[]}})}function YS(e,t,n){if(t.allowRoots.length===0)return!1;let r=e.trim();if(im(r))return!1;let o=n?r:mr(r,t.environment.home),i=t.resolvedCwd??t.anchoredCwd,s=ya(o)?o:i?Tn(i,o):null;if(!s)return!1;try{let a=fe(U(s,t.environment.paths,t.pathCanonicalizationContext));return t.allowRoots.some((l)=>a===l||a.startsWith(l.endsWith(ha)?l:`${l}${ha}`))}catch{return!1}}function XS(e){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(e)}function sm(e,t=!1){return e.includes("$")||e.includes("`")||JS(e)||t&&QS(e)}function JS(e){let t=!1;for(let n of e){if(t){t=!1;continue}if(n==="\\"){t=!0;continue}if(n==="*"||n==="?"||n==="[")return!0}return!1}function QS(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(t){t=!1;continue}if(r==="\\"){t=!0;continue}if(r==="{"&&ev(e,n)||(r==="+"||r==="@"||r==="!")&&e[n+1]==="(")return!0}return!1}function ev(e,t){let n=e.indexOf("}",t+1);if(n===-1)return!1;let r=e.slice(t+1,n);return r.includes(",")||r.includes("..")}function tv(e,t,n,r){try{return fe(U(e,n,r))===fe(U(t,n,r))}catch{try{return fe(e)===fe(t)}catch{return!1}}}function nv(e,t,n,r){if(e==="."||e==="./"||e===".\\")return!0;try{return fe(U(Tn(t,e),n,r))===fe(U(t,n,r))}catch{try{return fe(Tn(t,e))===fe(t)}catch{return!1}}}function rv(e,t,n,r,o,i,s){let a=n??t;if(!o&&(e.startsWith("~")||e.startsWith("$HOME")||e.startsWith("${HOME}")))return!1;if(r)return!1;if(e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e))try{return ga(e,t,i,s)}catch{return!1}if(e.startsWith("./")||e.startsWith(".\\")||!e.includes("/")&&!e.includes("\\"))try{return ga(Tn(a,e),t,i,s)}catch{return!1}if(e.startsWith("../"))return!1;try{return ga(Tn(a,e),t,i,s)}catch{return!1}}function ga(e,t,n,r){try{return am(U(e,n,r),U(t,n,r))}catch{return!1}}function ov(e,t,n,r){if(!t)return!1;try{return am(U(t,n,r),U(e,n,r))}catch{return!0}}function am(e,t){let n=fe(e),r=fe(t);return n.startsWith(`${r}${ha}`)||n===r}var iv=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),lm="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",sv="PowerShell Remove-Item -Recurse -Force for non-temporary paths is blocked by the active safety policy. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",cm="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",um="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",av="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",lv="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.";function dm(e,t,n,r=jt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths})){return cv(e.words.map((o)=>({kind:"word",text:o.text,dynamic:o.provenance!=="literal"})),t,r,n.policy)}function cv(e,t,n,r){let o=e.filter((l)=>l.kind==="word"),i=dv(o),s=o[i];if(!s||!iv.has(Sv(s.text)))return null;let a=uv(o.slice(i+1));if(a.whatIfProtected)return null;if(Q(r,"powershell.remove-item-pipeline-dynamic-target",n.strict)&&t&&(a.targets.length===0||a.recursive))return b("powershell.remove-item-pipeline-dynamic-target",lv);for(let l of a.targets)if(!zt(l.text)&&Ca(Sa(l.text)))return b(a.recursive&&a.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",um);for(let l of a.targets)if(n.resolvedCwd&&Ht(Sa(l.text),n.resolvedCwd,n.protectedGitMetadata,a.recursive,n.pathCanonicalizationContext,!0))return b("powershell.remove-item-git-metadata",Ie);if(!a.recursive||!a.force)return null;if(Q(r,"powershell.remove-item-recursive-force-dynamic-target",n.strict)&&(a.hasDynamicTarget||a.targets.length===0))return b("powershell.remove-item-recursive-force-dynamic-target",cm);for(let l of a.targets){let c=vv(Ue(Sa(l.text),n),n,r);if(c)return c}return null}function uv(e){let t=[],n=!1,r=!1,o=!1,i=!1,s=!1;for(let a=0;a<e.length;a++){let l=e[a];if(!l||l.kind!=="word")continue;if(mv(l))continue;if(s){t.push(ba(l)),i=i||l.dynamic;continue}if(l.text==="--"){s=!0;continue}let c=pv(l.text);if(!c){t.push(ba(l)),i=i||l.dynamic;continue}if(gv(c.name)){let u=c.value?fv(c.value,l):e[++a];if(u?.kind==="word")t.push(ba(u)),i=i||u.dynamic;else i=!0;continue}if(hv(c.name)){n=!0;continue}if(yv(c.name)){r=!0;continue}if(Cv(c.name))o=bv(c.value)}return{targets:t,recursive:n,force:r,whatIfProtected:o,hasDynamicTarget:i}}function dv(e){let t=e[0];if(t?.kind==="word"&&t.text==="&"||t?.text===".")return e.length>1?1:0;return 0}function ba(e){return{text:e.kind==="word"?e.text:"",dynamic:e.kind==="word"&&e.dynamic}}function mv(e){return e.kind==="word"&&e.text===","}function Sa(e){let t=e.replace(/\\/g,"/"),n=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(t);return n?`$HOME${t.slice(n[0].length)}`:t}function fv(e,t){return{kind:"word",text:e,dynamic:t.kind==="word"&&(t.dynamic||e.includes("$"))}}function pv(e){if(!e.startsWith("-")||e==="-")return null;let t=e.slice(1),n=t.indexOf(":");if(n===-1)return{name:t.toLowerCase()};return{name:t.slice(0,n).toLowerCase(),value:t.slice(n+1)}}function gv(e){return"path".startsWith(e)||"literalpath".startsWith(e)}function hv(e){return"recurse".startsWith(e)}function yv(e){return e.length>=2&&"force".startsWith(e)}function Cv(e){return e==="wi"||"whatif".startsWith(e)}function bv(e){if(e===void 0||e==="")return!0;let t=e.toLowerCase();return t==="$true"||t==="true"}function Sv(e){return e.toLowerCase()}function vv(e,t,n){switch(e.kind){case"root_or_home_target":return b("powershell.remove-item-recursive-force-root-or-home",um);case"git_metadata_target":return b("powershell.remove-item-git-metadata",Ie);case"temp_target":return null;case"dynamic_target":if(!Q(n,"powershell.remove-item-recursive-force-dynamic-target",t.strict))return null;return b("powershell.remove-item-recursive-force-dynamic-target",cm);case"home_cwd_target":return b("powershell.remove-item-recursive-force-home-cwd",av);case"cwd_self_target":return b("powershell.remove-item-recursive-force-cwd-self",lm);case"within_anchored_cwd":if(!Q(n,"powershell.remove-item-recursive-force-paranoid",t.paranoid))return null;return b("powershell.remove-item-recursive-force-paranoid",sv);case"outside_anchored_cwd":return b("powershell.remove-item-recursive-force-outside-cwd",lm)}}import{normalize as Ti}from"node:path";function He(e,t){let n=t.policy??{rules:[],transparentWrappers:[]};return bi([...e],t.environment,t.cwd,t.cwd,new Map,new Map(t.envAssignments??[]),n,{iterations:0},!1)}function*bi(e,t,n,r,o,i,s,a,l){let c=gi(e,t,n,i);for(let[d,p]of c.envAssignments)i.set(d,p),o.set(d,p);let{tokens:u,cwd:m}=c;if(c.envSplitValues){let d=pi(c.envSplitValues,u);if(!d)throw new be;va(a),yield*bi(d,t,m,r,o,i,s,a,l);return}if(Bt(u[0]??""))throw new be;let f=Uo(u,s);if(f){for(let d of[f.childIndex,...f.alternativeChildIndices])va(a),yield*bi(d===f.childIndex?f.tokens:[...u.slice(d)],t,m,r,new Map(o),new Map(i),s,a,!0);return}if(Ev(u)){va(a),yield*bi([...u.slice(1)],t,m,r,o,i,s,a,l);return}yield Rv(u,m,r,o,i,l)}function Rv(e,t,n,r,o,i){return{tokens:e,cwd:t===null?void 0:t??n,wrapperCwd:t,wrapperEnvAssignments:r,envAssignments:o,head:M(e[0]??"").toLowerCase(),wrappedByTransparent:i}}function va(e){if(e.iterations>=un)throw new be;e.iterations++}function Ev(e){return M(e[0]??"").toLowerCase()==="busybox"&&e.length>1}function Ra(e,t){let n=[],r=t;while(r<e.length){let o=e[r];if(o===void 0||o===":::")break;n.push(o),r++}return{markerIndex:r<e.length&&e[r]===":::"?r:-1,templateTokens:n}}function je(e){let t=!1,n=!1;for(let r of e){if(r==="--")break;if(r==="-r"||r==="-R"||Ea(r,"recursive"))t=!0;else if(r==="-f"||Ea(r,"force"))n=!0;else if(r.startsWith("-")&&!r.startsWith("--")){if(r.includes("r")||r.includes("R"))t=!0;if(r.includes("f"))n=!0}}return t&&n}function mm(e){let t=e.indexOf("--");return e.slice(1,t===-1?void 0:t).some((n)=>Ea(n,"recursive")||/^-[A-Za-z]+$/.test(n)&&/[rR]/.test(n.slice(1)))}function Ea(e,t){return e.length>2&&e.startsWith("--")&&t.startsWith(e.slice(2))}var xv="find -delete permanently removes files. Use -print first to preview.",wv="find -exec rm -rf is dangerous. Use explicit file list instead.",_v=new Set(["-exec","-execdir","-ok","-okdir"]),Pv=new Map([...["-Bmin","-Bnewer","-Btime","-amin","-anewer","-atime","-cmin","-cnewer","-context","-ctime","-f","-flags","-fprint","-fprint0","-fls","-fstype","-gid","-group","-ilname","-iname","-inum","-ipath","-iwholename","-iregex","-links","-lname","-maxdepth","-mindepth","-mmin","-mnewer","-mtime","-name","-newer","-newerXY","-newermt","-path","-perm","-printf","-regex","-samefile","-size","-type","-uid","-used","-user","-wholename","-xattrname","-xtype"].map((e)=>[e,1]),["-fprintf",2]]);function Si(e,t){let n=e.map(I),r=Av(e,n,t);if(r)return r;if(Ri(n,1)&&!Tv(e,n,t)){let s=k(b("find.delete",xv),t.policy);if(s)return s}let o=t.derivedCommandWorkBudget??ci(),i=0;while(i<n.length){let s=n[i],a=Pt(s??"");if(a>0){i+=a+1;continue}if(!Ct(s)){i++;continue}ze(o,n.length-i-1);let l=xr(n,i);i=l.nextIndex;let c=Ov(l.tokens,t.environment);if(c){let d=k(c,t.policy);if(d)return d}let u=s==="-execdir"||s==="-okdir",m=t.analyzeTokens?t.analyzeTokens(l.tokens,u?null:t.cwd):t.analyzeNested?t.analyzeNested(l.tokens.join(" "),{effectiveCwd:u?void 0:t.cwd,envAssignments:t.envAssignments}):null,f=m?.id.startsWith("custom.")?m:k(m,t.policy);if(f)return f}return null}function Av(e,t,n){if(!Ri(t,1)&&!xa(t,n.environment))return null;let o=vi(e)??G(["."]),i=jt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let s of o){let a=Er(s);for(let l of a.expandedTargets??[I(s)]){let c=Ue(l,i,{targetIsLiteral:a.expandedTargets!==void 0||a.targetIsLiteral,tmpdirWordSplittingProtected:a.tmpdirWordSplittingProtected});if(c.kind==="root_or_home_target")return b("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(c.kind==="git_metadata_target")return b("find.delete-git-metadata",Ie)}}if(kv(t)&&i.resolvedCwd&&em(o.map(I),i.resolvedCwd,i.protectedGitMetadata,i.pathCanonicalizationContext))return b("find.delete-git-metadata",Ie);return null}function xa(e,t){let n=0;while(n<e.length){if(!Ct(e[n])){n++;continue}let r=xr(e,n),o=_t([...r.tokens],t),i=M(o[0]??"").toLowerCase();if((i==="rm"||i==="rmdir")&&o.some((s)=>s.includes("{}")))return!0;n=r.nextIndex}return!1}function kv(e){return e.some((t,n)=>{if(!["-name","-iname"].includes(t))return!1;return e[n+1]?.toLowerCase()==="hooks"})}function Tv(e,t,n){if(t.includes("-L")||t.includes("-f")||t.includes("-follow"))return!1;let r=vi(e);if(!r)return!1;let o=n.envAssignments??new Map,i=da(o,n.environment),s=n.trustedTmpdirValue??yt(o,n.environment),a=n.allowTmpdirVar??!Sr(o,n.environment),l=jt({environment:n.environment,protectedGitMetadata:n.protectedGitMetadata,cwd:n.cwd,originalCwd:n.originalCwd,strict:n.strict,allowTmpdirVar:a&&s&&Boolean(i),allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:n.tmpdirWordSplittingUnsafe??tt(o,n.environment),trustedTmpdirValue:s});return r.every((c)=>{let u=Er(c);if(u.unsafeBraceExpansion)return!1;return(u.expandedTargets??[I(c)]).every((m)=>om(m,l,{containmentTarget:Iv(m,i),targetIsLiteral:u.expandedTargets!==void 0||u.targetIsLiteral,tmpdirWordSplittingProtected:u.tmpdirWordSplittingProtected}))})}function Iv(e,t){if(!t)return e;return e.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>t)}function vi(e){let t=(o)=>{let i=e[o];return i?I(i):void 0},n=1;while(t(n)==="-H"||t(n)==="-P")n++;if(t(n)==="--")n++;let r=[];while(n<e.length){let o=t(n),i=e[n];if(!o||!i||o.startsWith("-")||["!","(",")"].includes(o))break;r.push(i),n++}return r.length>0?r:null}function Ov(e,t){let n=kn([...e],t);if(n.length===0)return null;let r=M(n[0]??"");if(r==="busybox"&&n.length>1)n=n.slice(1),r=M(n[0]??"");if(r==="rm"&&je(n))return b("find.exec-rm-recursive-force",wv);return null}function xr(e,t){let n=t+1;while(n<e.length&&e[n]!==";"&&!(e[n]==="+"&&e[n-1]==="{}"))n++;return{tokens:e.slice(t+1,n),nextIndex:Math.min(n+1,e.length)}}function Ri(e,t){let n=t;while(n<e.length){let r=e[n];if(!r){n++;continue}if(Ct(r)){n=xr(e,n).nextIndex;continue}let o=Pt(r);if(o>0){n+=o+1;continue}if(r==="-delete")return!0;n++}return!1}function Pt(e){return Pv.get(e)??(/^-newer[A-Za-z]{2}$/.test(e)?1:0)}function Ct(e){return e!==void 0&&_v.has(e)}function*wa(e){for(let t of e.nodes)yield*Mv(t)}function Dv(e){return Object.freeze([...wa(e)])}function tO(e){return Object.freeze(Dv(e).map((t)=>Object.freeze(t.words.map((n)=>n.text))))}function wr(e){let t=Le(e,"posix");if(t.status!=="complete"||t.nodes.length!==1)return null;let n=t.nodes[0];if(n?.kind!=="command")return null;if(n.redirections.length>0||n.nested.length>0)return null;if(n.words.some((r)=>r.provenance==="command-substitution"))return null;return n.words.map((r)=>r.text)}function*Mv(e){if(e.kind==="command"){yield e;for(let t of e.nested)yield*wa(t);return}if(e.kind==="group")yield*wa(e.body)}var Nv=5,_a="Git aliases supplied through command-line or environment config can hide or execute commands. Run git without Git alias overrides, or ask the user to run it manually.";function ue(e){let t=e.indexOf("--");if(t===-1)return{index:-1,before:e,after:[]};return{index:t,before:e.slice(0,t),after:e.slice(t+1)}}function pm(e,t,n){let r=hm(e,t,n),o=Lv(r.entries);if(o.size===0)return{blockedReason:r.blockedReason,expanded:!1,tokens:e};let i=e,s=!1;for(let a=0;a<Nv;a++){let{subcommand:l,rest:c}=Ve(i),u=l?.toLowerCase();if(!u||!o.has(u))return{blockedReason:r.blockedReason,expanded:s,tokens:i};let m=o.get(u),f=$v(m);if(f===null||f.length===0)return{blockedReason:_a,expanded:!0,tokens:i};i=["git",...f,...c],s=!0}return{blockedReason:_a,expanded:!0,tokens:i}}function gm(e,t,n){return hm(e,t,n).entries.some((r)=>r.key.toLowerCase()==="core.sshcommand")}function Ve(e){if(e.length===0)return{subcommand:null,rest:[]};let t=e[0];if((t?M(t).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let r=1;while(r<e.length){let o=e[r];if(!o)break;if(o==="--"){let i=e[r+1];if(i&&!i.startsWith("-"))return{subcommand:i,rest:e.slice(r+2)};return{subcommand:null,rest:e.slice(r+1)}}if(o.startsWith("-"))if(Qe.has(o))r+=2;else if(o.startsWith("-c")&&o.length>2)r++;else if(o.startsWith("-C")&&o.length>2)r++;else r++;else return{subcommand:o,rest:e.slice(r+1)}}return{subcommand:null,rest:[]}}function Lv(e){let t=new Map;for(let n of e){let r=n.key.toLowerCase();if(!r.startsWith("alias."))continue;let o=r.slice(6);if(o!=="")t.set(o,n.value)}return t}function hm(e,t,n){if(e.length===0)return{blockedReason:null,entries:[]};let r=e[0];if((r?M(r).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let i=Fv(t,n);return{blockedReason:i.blockedReason,entries:[...i.entries,...Wv(e,t,n)]}}function Wv(e,t,n){let r=[],o=1;while(o<e.length){let i=e[o];if(!i||i==="--"||!i.startsWith("-"))return r;if(i==="-c"){let s=Pa(e[o+1]);if(s)r.push(s);o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=Pa(i.slice(2));if(s)r.push(s);o++;continue}if(i==="--config-env"){let s=fm(e[o+1],t,n);if(s)r.push(s);o+=2;continue}if(i.startsWith("--config-env=")){let s=fm(i.slice(13),t,n);if(s)r.push(s);o++;continue}if(Qe.has(i)){o+=2;continue}o++}return r}function Fv(e,t){let n=Gv(e,t),r=zv(e,t);return{blockedReason:n===null||r===null?_a:null,entries:[...n??[],...r??[]]}}function Gv(e,t){let n=Ae("GIT_CONFIG_PARAMETERS",e,t);if(n===void 0)return[];let r=[],o=wr(n);if(!o)return null;for(let i of o){let s=Pa(i);if(!s)return null;r.push(s)}return r}function zv(e,t){let n=ko(e,t);if(n.state==="absent")return[];if(n.state==="invalid")return null;let r=[];for(let o=0;o<n.count;o++){let i=Ae(`GIT_CONFIG_KEY_${o}`,e,t)?.trim(),s=Ae(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i||s===void 0)return null;r.push({key:i,value:s})}return r}function Pa(e){if(!e)return null;let t=e.indexOf("=");return{key:(t===-1?e:e.slice(0,t)).trim(),value:t===-1?void 0:e.slice(t+1)}}function fm(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;return{key:e.slice(0,r).trim(),value:Ae(e.slice(r+1),t,n)}}function $v(e){let t=e?.trimStart();if(!t||t.startsWith("!"))return null;return wr(t)}var Bv="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",Uv="git checkout --force discards uncommitted changes. Use 'git stash' first.",Hv="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",jv="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",Vv="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",qv="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",Kv="git switch --force discards uncommitted changes. Use 'git stash' first.",Zv="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",Yv="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",Xv="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",Jv="git reset --merge can lose uncommitted changes. Use 'git stash' first.",Qv="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",eR="git rm --force removes tracked files from the working tree. Use 'git rm --cached' to keep the files, or 'git rm --dry-run' to preview first.",tR="git push --force destroys remote history. Use --force-with-lease for safer force push.",nR="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",rR="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",oR="git branch -D force-deletes without merge check. Use -d for safe delete.",iR="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",sR="git merge --abort discards merge conflict resolutions. Use 'git status' first.",aR="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",lR="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",cR="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",uR="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",dR="git worktree remove --force can delete uncommitted changes. Remove --force flag.",ym=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),Cm=new Set(["--recurse-submodules","--track","-t"]),Aa=new Set(["-b","-B","-U"]),ka=new Set(["-c","-C"]),mR=new Set(["--source","--conflict","--unified","--inter-hunk-context"]),fR=new Set(["-q","--quiet","--no-quiet","-f","--force","--no-force","-d","--detach","--no-detach","-m","--merge","--no-merge","-p","--patch","--no-patch","--guess","--no-guess","--overlay","--no-overlay","--ours","--theirs","--ignore-skip-worktree-bits","--no-ignore-skip-worktree-bits","--no-track","--overwrite-ignore","--no-overwrite-ignore","--ignore-other-worktrees","--no-ignore-other-worktrees","--progress","--no-progress","--pathspec-file-nul","--no-pathspec-file-nul","--no-recurse-submodules"]);function W(e,t){let n=e.split("=",1)[0]??e;return n.length>=4&&t.startsWith(n)&&n.startsWith("--")&&n.slice(2).length>=2}var In=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function Sm(e){let{subcommand:t,rest:n}=Ve(e);if(!t)return null;switch(t.toLowerCase()){case"checkout":return At(pR(n));case"switch":return At(gR(n));case"restore":return At(yR(n));case"reset":return bR(n);case"clean":return At(vR(n));case"rm":return At(RR(n));case"push":return Vt(ER(n));case"branch":return Vt(_R(n));case"stash":return Vt(IR(n));case"worktree":return Vt(OR(n));case"rebase":return At(PR(n));case"merge":return At(AR(n));case"tag":return Vt(kR(n));case"reflog":return Vt(TR(n));default:return null}}function At(e){return e?{...e,localDiscard:!0}:null}function Vt(e){return e?{...e,localDiscard:!1}:null}function pR(e){let{index:t,before:n}=ue(e),r=me(n,{shortOptsWithValue:Aa});if(n.some((i)=>W(i,"--force"))||r.has("-f"))return b("git.checkout-force",Uv);for(let i of e){if(i==="-b"||i==="-B"||i==="--orphan")return null;if(W(i,"--pathspec-from-file"))return b("git.checkout-pathspec-from-file",jv)}if(t!==-1){if(n.some((s)=>!s.startsWith("-")))return b("git.checkout-ref-path",Hv);return b("git.checkout-double-dash",Bv)}if(hR(e).length>=2)return b("git.checkout-ambiguous",Vv);return null}function gR(e){let{before:t}=ue(e);if(t.some((r)=>W(r,"--discard-changes")))return b("git.switch-discard-changes",qv);let n=me(t,{shortOptsWithValue:ka});if(t.some((r)=>W(r,"--force"))||n.has("-f"))return b("git.switch-force",Kv);return null}function hR(e){let t=[],n=0;while(n<e.length){let r=e[n];if(!r)break;if(r==="--")break;if(r.startsWith("-"))if(ym.has(r))n+=2;else if(r.startsWith("--")&&r.includes("="))n++;else if(Cm.has(r)){let o=e[n+1];if(o&&!o.startsWith("-")&&(r==="--recurse-submodules"||r==="--track"||r==="-t"))if((r==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"]).includes(o))n+=2;else n++;else n++}else if(r.startsWith("--")&&!fR.has(r)&&!ym.has(r)&&!Cm.has(r))n++;else n++;else t.push(r),n++}return t}function yR(e){let t=CR(e);if(t.isTerminal||!t.hasPathspec&&!t.hasPatch||!t.hasWorktree)return null;return t.hasExplicitLocation?b("git.restore-worktree",Yv):b("git.restore-unstaged",Zv)}function CR(e){let t=!1,n=!1,r=!0,o=!1,i=(s)=>{if(!o)r=!1,o=!0;if(s!==void 0)r=s};for(let s=0;s<e.length;s++){let a=e[s];if(a===void 0)break;if(a==="--"){t||=s+1<e.length;break}if(a==="--pathspec-from-file"){t=!0,s++;continue}if(a.startsWith("--pathspec-from-file=")){t=!0;continue}if(a==="-h"||a==="--help"||a==="--version")return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!0};if(a==="--staged"){i();continue}if(a==="--no-staged"){i();continue}if(a==="--worktree"){i(!0);continue}if(a==="--no-worktree"){i(!1);continue}if(a==="--patch"){n=!0;continue}if(a==="--no-patch"){n=!1;continue}if(mR.has(a)){s++;continue}if(a.startsWith("--"))continue;if(a==="-"){t=!0;continue}if(!a.startsWith("-")){t=!0;continue}for(let l=1;l<a.length;l++){let c=a.charAt(l);if(c==="h")return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!0};if(c==="S"){i();continue}if(c==="W"){i(!0);continue}if(c==="p"){n=!0;continue}if(c==="s"||c==="U"){if(l===a.length-1)s++;break}}}return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!1}}function bR(e){let t=null;for(let n of e){if(W(n,"--hard")){t=b("git.reset-hard",Xv);break}if(W(n,"--merge")){t=b("git.reset-merge",Jv);break}}if(!t)return null;return SR(e)?Vt(t):At(t)}function SR(e){for(let t of e){if(t==="--")return!1;if(!t.startsWith("-"))return!0}return!1}function vR(e){for(let n of e)if(n==="-n"||W(n,"--dry-run"))return null;let t=me(e.filter((n)=>n!=="--"));if(e.some((n)=>W(n,"--force"))||t.has("-f"))return b("git.clean-force",Qv);return null}function RR(e){let t=!1,n=!1,r=!1;for(let o of ue(e).before){if(W(o,"--no-force")){t=!1;continue}if(W(o,"--force")){t=!0;continue}if(W(o,"--no-cached")){n=!1;continue}if(W(o,"--cached")){n=!0;continue}if(W(o,"--no-dry-run")){r=!1;continue}if(W(o,"--dry-run")){r=!0;continue}let i=me([o]);t||=i.has("-f"),r||=i.has("-n")}return t&&!n&&!r?b("git.rm-force",eR):null}function ER(e){let{before:t,after:n}=ue(e),r=me(t);if(t.some((s)=>W(s,"--mirror")))return b("git.push-mirror",rR);if(t.some((s)=>W(s,"--force"))||r.has("-f")||bm(t,n).some(xR))return b("git.push-force",tR);if(t.some((s)=>W(s,"--delete"))||r.has("-d")||bm(t,n).some(wR))return b("git.push-delete",nR);return null}function bm(e,t){return[...e.filter((n)=>n!==""&&!n.startsWith("-")),...t]}function xR(e){return e.startsWith("+")||e.includes(":+")}function wR(e){return e.length>1&&e.startsWith(":")}function _R(e){let{before:t}=ue(e),n=me(t),r=n.has("-D")||n.has("-d")||t.some((i)=>W(i,"--delete")),o=n.has("-D")||n.has("-f")||t.some((i)=>W(i,"--force"));if(r&&o)return b("git.branch-force-delete",oR);return null}function PR(e){let{before:t}=ue(e);return t.some((n)=>W(n,"--abort"))?b("git.rebase-abort",iR):null}function AR(e){let{before:t}=ue(e);return t.some((n)=>W(n,"--abort"))?b("git.merge-abort",sR):null}function kR(e){let{before:t}=ue(e);return me(t).has("-d")||t.some((r)=>W(r,"--delete"))?b("git.tag-delete",aR):null}function TR(e){return e[0]==="delete"?b("git.reflog-delete",lR):null}function IR(e){for(let t of e){if(t==="drop")return b("git.stash-drop",cR);if(t==="clear")return b("git.stash-clear",uR)}return null}function OR(e){let{before:t}=ue(e);if(!t.includes("remove"))return null;let r=me(t);if(t.some((o)=>W(o,"--force"))||r.has("-f"))return b("git.worktree-remove-force",dR);return null}import{execFileSync as DR}from"node:child_process";import{existsSync as Ia,readFileSync as Oa}from"node:fs";import{dirname as MR,isAbsolute as Em,join as Ta,resolve as xm}from"node:path";var NR=["/usr/bin/git","/usr/local/bin/git","/opt/homebrew/bin/git","C:\\Program Files\\Git\\cmd\\git.exe","C:\\Program Files\\Git\\bin\\git.exe"];function wm(e,t,n,r){let o=LR(e,t,n);if(o!==null)return o;let i=WR(t,n);if(i!==null)return i;if(du(n))return!0;return FR(r)}function LR(e,t,n){let r=null,o=1;while(o<e.length){let i=e[o];if(!i||i==="--")return r;if(!i.startsWith("-"))return r;if(i==="-c"){let s=vm(e[o+1]);if(s!==null)r=s;o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=vm(i.slice(2));if(s!==null)r=s;o++;continue}if(i==="--config-env"){let s=Rm(e[o+1],t,n);if(s!==null)r=s;o+=2;continue}if(i.startsWith("--config-env=")){let s=Rm(i.slice(13),t,n);if(s!==null)r=s;o++;continue}if(Qe.has(i))o+=2;else o++}return r}function WR(e,t){if(Ae("GIT_CONFIG_PARAMETERS",e,t)!==void 0)return!0;let n=ko(e,t);if(n.state==="absent")return null;if(n.state==="invalid")return!0;let r=null;for(let o=0;o<n.count;o++){let i=Ae(`GIT_CONFIG_KEY_${o}`,e,t),s=Ae(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i?.trim()||s===void 0)return!0;let a=i.trim().toLowerCase();if(Da(a))return!0;if(a!=="submodule.recurse")continue;r=_r(s)}return r}function FR(e,t=zR()){let n=GR(e);if(n===null||n)return!0;if(t===null)return!0;try{let r=DR(t,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:$R(process.env),stdio:["ignore","pipe","ignore"]}).trim();return _r(r)}catch(r){return!BR(r)}}function GR(e){let t=UR(e);if(t===null)return null;for(let n of t){if(!Ia(n))continue;if(VR(n))return!0}return!1}function zR(){for(let e of NR)if(Ia(e))return e;return null}function $R(e){let t={...e};for(let n of Object.keys(t))if(or(n))delete t[n];return t}function BR(e){return typeof e==="object"&&e!==null&&"status"in e&&e.status===1}function UR(e){let t=ar(e);if(t===null)return null;let n=HR(t);if(n===null)return null;let r=jR(n);if(r===null)return null;return[Ta(r,"config"),Ta(n,"config.worktree")]}function HR(e){try{let n=Oa(e,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!n.startsWith("gitdir:"))return e;let r=n.slice(7).trim();if(r==="")return null;return Em(r)?r:xm(MR(e),r)}catch{return null}}function jR(e){let t=Ta(e,"commondir");if(!Ia(t))return e;try{let n=Oa(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(n==="")return null;return Em(n)?n:xm(e,n)}catch{return null}}function VR(e){let t;try{t=Oa(e,"utf-8")}catch{return!0}let n="",r=!1;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i===""||i.startsWith("#")||i.startsWith(";"))continue;let s=i.match(/^\[([^\]]+)\]$/);if(s){n=s[1]?.trim().toLowerCase()??"";continue}let a=i.indexOf("="),l=(a===-1?i:i.slice(0,a)).trim().toLowerCase(),c=a===-1?"true":i.slice(a+1).trim();if(qR(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=_r(c)}return r}function qR(e){return e==="include"||e.startsWith("includeif ")}function vm(e){if(!e)return null;let t=e.indexOf("="),n=(t===-1?e:e.slice(0,t)).toLowerCase();if(Da(n))return!0;if(n!=="submodule.recurse")return null;let r=t===-1?"true":e.slice(t+1).toLowerCase();return _r(r)}function _r(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function Rm(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;let o=e.slice(0,r).toLowerCase();if(Da(o))return!0;if(o!=="submodule.recurse")return null;let i=Ae(e.slice(r+1),t,n);return i===void 0||_r(i)}function Da(e){return e==="include.path"||e.startsWith("includeif.")&&e.endsWith(".path")}function _m(e,t,n){if(!t.localDiscard||!n.worktreeMode||gu(n.env,n.envAssignments))return null;let r=hu(e,n.cwd);if(!r.gitCwd||r.hasExplicitGitContext)return null;if(!yu(r.gitCwd))return null;if(KR(e,n,r.gitCwd))return null;return{originalReason:t.reason,gitCwd:r.gitCwd}}function KR(e,t,n){let{subcommand:r,rest:o}=Ve(e),i=r?.toLowerCase();if(t.dynamicArguments||ZR(o)||wm(e,t.env,t.envAssignments,n)||JR(o)||YR(i,o))return!0;return i==="clean"&&QR(o)>1}function ZR(e){return e.some((t)=>/[$*?[]/.test(t))}function YR(e,t){if(e==="checkout"){let{before:n}=ue(t),r=me(n,{shortOptsWithValue:Aa}),o=n.some((s)=>W(s,"--force"))||r.has("-f"),i=r.has("-B")||n.some((s)=>s==="-B"||s.startsWith("-B"));return o&&i}if(e==="switch"){let{before:n}=ue(t),r=me(n,{shortOptsWithValue:ka}),o=n.some((s)=>W(s,"--force"))||n.some((s)=>W(s,"--discard-changes"))||r.has("-f"),i=n.some((s)=>s==="-C"||s.startsWith("-C")||XR(s))||r.has("-C");return o&&i}return!1}function XR(e){let t=e.split("=",1)[0]??e;return t==="--force-create"||t.length>=9&&"--force-create".startsWith(t)}function JR(e){return e.some((t)=>t.startsWith("--recurse-sub"))}function QR(e){let t=0;for(let n of e){if(n==="--force"){t++;continue}if(n.startsWith("-")&&!n.startsWith("--")){for(let r of n.slice(1))if(r==="f")t++}}return t}var eE="Git SSH environment overrides can execute arbitrary commands during network operations. Run git without GIT_SSH/GIT_SSH_COMMAND overrides, or ask the user to run it manually.",tE=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function On(e,t){return Pm(e.map(I),t)}function Pm(e,t,n){let r=pm(e,t.env,t.envAssignments),o=r.blockedReason?k(b("git.alias-config",r.blockedReason),t.policy):null;if(o)return o;let i=r.tokens;if((uu(t.envAssignments)||gm(e,t.env,t.envAssignments))&&nE(i))return b("git.ssh-env",eE);let s=Sm(i);if(!s)return null;if(r.expanded||r.blockedReason)return s;let a=_m(e,s,t);if(!a)return s;return n?.(a),null}function Am(e,t){let n=null;return{match:Pm(e.map(I),t,(o)=>{n=o}),relaxation:n}}function nE(e){let{subcommand:t,rest:n}=Ve(e),r=t?.toLowerCase();if(!r)return!1;if(tE.has(r))return!0;if(r==="archive")return ue(n).before.some((o)=>W(o,"--remote"));return r==="remote"&&rE(n)}function rE(e){return e.find((t)=>!oE(t))?.toLowerCase()==="update"}function oE(e){return e==="-v"||W(e,"--verbose")||W(e,"--no-verbose")}import{isAbsolute as KE}from"node:path";var km="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",iE="rm -rf for non-temporary paths is blocked by the active safety policy. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",sE="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",Im="rm -rf targeting root or home directory is extremely dangerous and always blocked.",aE="rm -rf in home directory is dangerous. Change to a project directory first.";function Dn(e,t){let n=jt({...t,allowPaths:t.policy?.destructiveCommandAllowPaths,posixShell:!0}),r=e.map(I),o=je(r),i=mm(r),s=cE(e);for(let a of s){let l=Er(a.word);if(o&&l.unsafeBraceExpansion){let c=k(Tm({kind:"outside_anchored_cwd"},n,t.policy),t.policy);if(c)return c;continue}for(let c of l.expandedTargets??[a.text]){let u={targetIsLiteral:l.expandedTargets!==void 0||l.targetIsLiteral,tmpdirWordSplittingProtected:l.tmpdirWordSplittingProtected};if(!i&&n.resolvedCwd&&Ht(c,n.resolvedCwd,n.protectedGitMetadata,i,n.pathCanonicalizationContext))return b("rm.git-metadata",Ie);if(i&&!o){let m=Ue(c,n,u);if(m.kind==="root_or_home_target")return b("rm.recursive-force-root-or-home",Im);if(m.kind==="git_metadata_target")return b("rm.git-metadata",Ie);continue}if(!o)continue;for(let m of lE(c,n,u)){let f=Tm(m,n,t.policy),d=k(f,t.policy);if(d)return d}}}return null}function lE(e,t,n){let r=Ue(e,t,n);if(r.kind==="cwd_self_target")return[r,Ue(e,t,{...n,skipCwdSelf:!0})];if(r.kind!=="home_cwd_target")return[r];let o=Ue(e,t,{...n,skipHomeCwd:!0});if(o.kind!=="cwd_self_target")return[r,o];return[r,o,Ue(e,t,{...n,skipHomeCwd:!0,skipCwdSelf:!0})]}function cE(e){let t=[],n=!1;for(let r of e.slice(1)){let o=I(r);if(!o)continue;if(o==="--"){n=!0;continue}if(n){t.push({text:o,word:r});continue}if(!o.startsWith("-"))t.push({text:o,word:r})}return t}function Tm(e,t,n){switch(e.kind){case"root_or_home_target":return b("rm.recursive-force-root-or-home",Im);case"git_metadata_target":return b("rm.git-metadata",Ie);case"temp_target":return null;case"dynamic_target":if(!Q(n,"rm.recursive-force-dynamic-target",t.strict))return null;return b("rm.recursive-force-dynamic-target",sE);case"home_cwd_target":return b("rm.recursive-force-home-cwd",aE);case"cwd_self_target":return b("rm.recursive-force-cwd-self",km);case"within_anchored_cwd":if(Q(n,"rm.recursive-force-paranoid",t.paranoid))return b("rm.recursive-force-paranoid",iE);return null;case"outside_anchored_cwd":return b("rm.recursive-force-outside-cwd",km)}}var uE={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Dm=new Set(["--init-file","--rcfile"]),dE=["--init-file","--rcfile"],mE=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function nt(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n)continue;if(n==="-c")return Om(e,t,!0);if(n.startsWith("-")&&n.includes("c")&&!n.startsWith("--")){let r=Om(e,t,!1);if(r!==null)return r}}return null}function Oe(e){let t=M(e[0]??"").toLowerCase();if(t==="zsh"||t==="ksh")return rt(e).syntaxCheck;let n=!1;for(let r of e.slice(1)){if(r==="--")return n;if(r.startsWith("+")&&!r.startsWith("++")){if(r.slice(1).includes("n"))n=!1;continue}if(!r.startsWith("-")||r.startsWith("--"))return n;let o=r.slice(1);if(o.includes("n"))n=!0;if(o.includes("c"))return n}return n}function Om(e,t,n){if(e[t+1]==="--")return e[t+2]||null;let r=e[t+1];if(!r||!n&&r.startsWith("-"))return null;return r}function Mm(e){let t=M(e[0]??"").toLowerCase(),n=fE(e,t),r=mE.get(t)??null,o=n.argvSource?.kind!=="absent";return{argvSource:t==="bash"?n.argvSource:null,argvSourceApplies:t==="bash"&&n.interactive&&n.argvSource?.kind==="literal",envName:r,envSourceApplies:o&&(r==="BASH_ENV"?!n.interactive:r==="ENV"&&n.interactive)}}function fE(e,t){let n=rt(e),r=n.commandIndex??n.scriptIndex??e.length,o=[],i=!1,s=!0;for(let a=1;a<r;a++){let l=e[a];if(l===void 0||l==="--"||l==="-"||l[0]!=="-"&&l[0]!=="+")break;if(l.startsWith("--")){if(t==="bash"&&s?dE.find((f)=>l===f):void 0){let f=e[a+1];o.push(f===void 0?{kind:"absent"}:{kind:"literal",value:f}),a++;continue}let m=l.split("=",1)[0]??l;if(t==="bash"&&Dm.has(m)&&!l.includes("="))a++;continue}if(t==="bash")s=!1;let c=Nm(t,l,e[a+1],"startup");if(c.interactive)i=l[0]==="-";a+=c.followingValues}return{argvSource:o.at(-1)??null,interactive:i}}function Nm(e,t,n,r){let o=!1,i=0,s=!1,a=!1,l=!1;for(let c=1;c<t.length;c++){let u=t[c];if(u===void 0)break;if(e==="ksh"&&u==="o"&&c+1<t.length){if(r==="argv"){let m=t.slice(c+1);if(t[0]==="-"&&(m==="c"||m[0]==="-"&&m.endsWith("c")))s=!0}break}if(e==="ksh"&&u==="o"&&c+1===t.length&&(n?.startsWith("-")||n?.startsWith("+")))break;if(e==="zsh"&&u==="o"&&c+1<t.length)break;if(r==="startup"&&u==="i")o=t[0]==="-";if(r==="argv"&&t[0]==="-"&&u==="c")s=!0;if(r==="argv"&&u==="n")l=t[0]==="-";if(r==="argv"&&u==="s")a=t[0]==="-";if(!uE[e]?.includes(u))continue;if(c+1===t.length)i++;break}return{interactive:o,followingValues:i,commandSelected:s,stdinMode:a,syntaxCheck:l}}function rt(e){let t=M(e[0]??"").toLowerCase(),n=!1,r=!1,o=!1;for(let i=1;i<e.length;i++){let s=e[i];if(s===void 0)break;if(s==="--"){let l=n&&e[i+1]!==void 0?i+1:null;return{command:l===null?null:e[l]??null,commandIndex:l,scriptIndex:!n&&!r&&e[i+1]!==void 0?i+1:null,readsStdinAsCommands:!n&&(r||e[i+1]===void 0),syntaxCheck:o}}if(s==="-"||s[0]!=="-"&&s[0]!=="+")return{command:n?s:null,commandIndex:n?i:null,scriptIndex:!n&&!r&&s!=="-"?i:null,readsStdinAsCommands:!n&&(r||s==="-"),syntaxCheck:o};if(s.startsWith("--")){let l=s.split("=",1)[0]??s;if(t==="bash"&&Dm.has(l)&&!s.includes("="))i++;continue}let a=Nm(t,s,e[i+1],"argv");if(a.commandSelected)n=!0;if(a.syntaxCheck)o=!0;if(a.stdinMode)r=!0;i+=a.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!n,syntaxCheck:o}}var kt={kind:"none"},qt={kind:"dynamic"},pE=new Set(["<","<<","<<-","<<<","<&","<>"]),Wm=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,gE=/^(?:[0-9]+|[@*])$/,hE=Ft.maxWords,yE=Ft.maxInputLength;function Fm(e){if(!e||M(z(e.words[0]?.text??""))!=="printf")return;if(e.words.some((o)=>o.provenance!=="literal"))return;let t=e.words.slice(e.words[1]?.text==="--"?2:1),n=t[0]?.text;if(n===void 0)return"";let r=t.slice(1).map((o)=>o.text);if(n==="%s")return r.join("");if(n==="%s\\n"||n===`%s
|
|
52
|
+
`)return`${r.join(`
|
|
53
|
+
`)}
|
|
54
|
+
`;if(n.includes("%")||/\\(?![\\nrt])/.test(n))return;return n.replaceAll("\\n",`
|
|
55
|
+
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function Mn(e){let t=Pr(e[1])==="--"?2:1;if(e.length<=t)return kt;let n=e.slice(t);if(!n.every(xi))return qt;return{kind:"literal",source:n.map(I).join(" ")}}function Gm(e){let t=Pr(e[1])==="--"?2:1,n=e[t],r=Pr(n);if(n===void 0||e.length<=t+1||r==="-"||r===""||r==="-l"||r==="-p")return kt;if(!xi(n))return qt;return{kind:"literal",source:r}}function Ei(e,t){let n=bE(e);if(n===-1)return kt;let r=SE(t);if(!r)return kt;let o=[],i=r.command?.length??0;for(let s of r.references){let a=RE(s,e,n,r.ifs);if(!a)return qt;if(i+=a.reduce((l,c)=>l+c.length+3,0),o.length+a.length>hE||i>yE)return qt;o.push(...a)}if(r.command==="eval")return{kind:"literal",source:o.join(" ")};if(o.length===0||/\s/.test(o[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[r.command,r.command&&r.optionTerminator?"--":null,...o.map(xE)].filter((s)=>s!==null).join(" ")}}function zm(e,t,n,r){if(!rt(e.map(I)).readsStdinAsCommands)return kt;let o=t.filter((i)=>(i.fd===void 0||i.fd===0)&&pE.has(i.operator)).at(-1);if(o){if(o.operator==="<<"||o.operator==="<<-")return kt;if(o.operator!=="<<<"||o.target?.provenance!=="literal")return qt;return{kind:"literal",source:o.target.text}}if(!n)return kt;return r===void 0?qt:{kind:"literal",source:r}}function ot(e){let t=rt(e.map(I)).scriptIndex;if(t===null)return kt;let n=e[t],r=Pr(n);return li(n,r)?{kind:"literal",source:r}:qt}var CE=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function Wa(e){if(e.words.length!==2||e.redirections.length!==0||e.nested.length!==1)return!1;let t=e.words[0],n=e.words[1];if(!t||t.provenance!=="literal"||t.quoted||t.raw!==t.text||!n)return!1;if(!(t.text==="eval"&&n.quoted&&n.parts.length===3&&n.parts[0]?.raw==='"'&&n.parts[1]?.provenance==="command-substitution"&&n.parts[1].raw.startsWith("$(")&&n.parts[2]?.raw==='"'||(t.text==="source"||t.text===".")&&!n.quoted&&n.parts.length===1&&n.parts[0]?.provenance==="command-substitution"&&n.parts[0].raw.startsWith("<(")))return!1;let o=e.nested[0];if(o?.status!=="complete"||o.nodes.length!==1)return!1;let i=o.nodes[0];if(i?.kind!=="command"||i.redirections.length!==0||i.nested.length!==0||i.words.some((l)=>l.provenance!=="literal"||l.parts.some((c)=>c.provenance!=="literal")))return!1;let s=i.words[0]?.text;if(s===void 0||Te(s)!==null)return!1;let a=M(z(s));return!CE.has(a)&&!ee.has(a)&&!Bt(a)}function bE(e){return rt(e.map(I)).commandIndex??-1}function SE(e){let t=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(e.trim()),n=t?.[4]??e.trim(),r=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(n),o=(r?.[3]??n).split(/\s+/).map(vE);if(o.length===0||o.some((i)=>i===null))return null;return{command:r?.[1]??null,optionTerminator:r?.[2]!==void 0,references:o.filter((i)=>!!i),ifs:t?t[1]??t[2]??t[3]??"":`
|
|
56
|
+
`}}function vE(e){let t=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(e),n=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(e),r=t??n;if(!r)return null;let o=r[1]??r[2];return{parameter:o==="@"||o==="*"?o:Number(o),quoted:t!==null}}function RE(e,t,n,r){let o=t.slice(n+2);if(e.parameter==="@")return e.quoted?Ma(o):EE(o,r);if(e.parameter==="*"){let a=Ma(o);if(!a)return;let l=a.join(r[0]??"");return e.quoted?[l]:Na(l,r)}let i=t[n+1+e.parameter];if(i&&!xi(i))return;let s=Pr(i);return e.quoted?[s]:Na(s,r)}function Ma(e){return e.every(xi)?e.map(I):void 0}function EE(e,t){let n=Ma(e);if(!n)return;let r=n.map((o)=>Na(o,t));return r.some((o)=>o===void 0)?void 0:r.flatMap((o)=>o??[])}function Na(e,t){if(["*","?","[","]"].some((n)=>e.includes(n)))return;if(t==="")return e===""?[]:[e];if(t===`
|
|
57
|
+
`)return e.trim().split(/\s+/).filter(Boolean);if(t.length!==1)return;return t===" "||t==="\t"||t===`
|
|
58
|
+
`?e.trim().split(/\s+/).filter(Boolean):e.split(t).filter(Boolean)}function xi(e){if(!e)return!0;return e.provenance==="unknown"?!/[$`]/.test(I(e)):e.provenance==="literal"}function Pr(e){return e?I(e):""}function xE(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Fa(e,t){return La(Le(e,"posix"),t)}function Nn(e){return Fa(e,new Set(Array.from(e.matchAll(Wm)).flatMap((t)=>{let n=t[1]??t[2];return n===void 0?[]:[n]})))}function La(e,t){if(e.status==="invalid"||e.status==="limited")return!1;let n=new Set(t);for(let r of e.nodes){if(r.kind==="group"){if(La(r.body,n))return!0;continue}if(r.kind!=="command")continue;if(r.nested.some((o)=>La(o,n))||$m(r.words,n))return!0;kE(r,n)}return!1}function $m(e,t){let n=e.findIndex((s)=>Te(s.text)===null);if(n===-1)return!1;let r=e[n];if(!r)return!1;if(Ar(r,t))return!0;let o=z(r.text);if(o==="source"||o==="."){let s=e[n+1]?.text==="--"?n+2:n+1;return Lm(e[s],t)}if(ee.has(o)){let s=e.slice(n),a=rt(s.map((c)=>c.text)),l=a.commandIndex??a.scriptIndex;return!a.syntaxCheck&&l!==null&&Lm(s[l],t)}let i=wE(e,n,t);if(i===null)return!1;if(i===-1)return!0;return $m(e.slice(i),t)}function wE(e,t,n){let r=z(e[t]?.text??"");if(r==="command")return _E(e,t+1);if(r==="exec")return PE(e,t+1);if(r==="env")return AE(e,t+1,n);return null}function _E(e,t){for(let n=t;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return e[n+1]?n+1:null;if(/^-[p]*[vV][pvV]*$/.test(r))return null;if(/^-p+$/.test(r))continue;return n}return null}function PE(e,t){for(let n=t;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return e[n+1]?n+1:null;if(r==="-a"){n++;continue}if(/^-a.+/.test(r)||/^-[cl]+$/.test(r))continue;return n}return null}function AE(e,t,n){for(let r=t;r<e.length;r++){let o=e[r],i=o?.text??"";if(i==="--")return e[r+1]?r+1:null;if(i==="-S"||i==="--split-string")return Ar(e[r+1],n)?-1:r+2;if(i.startsWith("-S")||i.startsWith("--split-string="))return Ar(o,n)?-1:r+1;if(i==="-u"||i==="--unset"||i==="-C"||i==="--chdir"||i==="-P"){r++;continue}if(i==="-i"||i==="-0"||i==="--null"||i.startsWith("-u=")||i.startsWith("--unset=")||i.startsWith("-C")||i.startsWith("--chdir=")||i.startsWith("-P"))continue;if(i.startsWith("-"))continue;if(Te(i))continue;return r}return null}function kE(e,t){if(!e.words.every((n)=>Te(n.text)!==null))return;for(let n of e.words){let r=Te(n.text);if(!r)continue;if(Ar(n,t))t.add(r.name)}}function Ar(e,t){if(!e)return!1;return e.parts.filter((n)=>n.provenance==="variable").some((n)=>Array.from(n.raw.matchAll(Wm)).some((r)=>{let o=r[1]??r[2];return o!==void 0&&(gE.test(o)||t.has(o))}))}function Lm(e,t){return!!e&&(e.parts.some((n)=>n.provenance!=="literal"&&n.provenance!=="variable")||Ar(e,t))}var TE=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--config-env"]),IE=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),OE=new Set;function Bm(e){if(e==="git")return TE;if(e==="docker")return IE;return OE}function re(e,t){if(e.length===0||t.length===0)return null;let n=z(e[0]??""),r=me(e);for(let o of t){if(!DE(n,o.command))continue;if(!ME(n,e,o.subcommand))continue;if(LE(e,new Set(o.block_args),r))return{id:`custom.${o.name}`,reason:`[${o.name}] ${o.reason}`,intent:o.intent??"manual_only"}}return null}function DE(e,t){return e===z(t)}function ME(e,t,n){if(!n)return!0;return Um(t,1,n,Bm(e))}function Um(e,t,n,r){let o=!1;for(let i=t;i<e.length;i++){let s=e[i];if(!s)continue;if(o){o=!1;continue}if(s==="--"){let a=e[i+1];if(a&&!a.startsWith("-"))return a===n;return!1}if(r.has(s)){o=!0;continue}if(s.startsWith("-")){if(!s.includes("=")&&NE(e,i,n,r))return!0;continue}return s===n}return!1}function NE(e,t,n,r){let o=e[t+1];if(!o||o.startsWith("-"))return!1;return Um(e,t+2,n,r)}function LE(e,t,n){for(let r of e)if(t.has(r))return!0;for(let r of n)if(t.has(r))return!0;return!1}function Tt(e,t,n={}){if(e.length===0)return null;let r=e[0];if(!r)return null;let o=z(r);if(o==="eval"){let i=Mn(G(e));if(i.kind==="dynamic")return Ln(n,t);if(i.kind==="literal"&&t.analyzeNested){let s=t.analyzeNested(i.source,{effectiveCwd:t.cwd,envAssignments:t.envAssignments});if(s)return s}return it(n,t)}if(ee.has(o)){if(Oe(e))return null;let i=nt(e);if(i){if(n.dynamicSourceInput??n.dynamicInput){let l=Ln(n,t);if(l)return l}if(Nn(i)){let l=Ln(n,t);if(l)return l}if(!t.analyzeNested)return null;let a=t.analyzeNested(i,{effectiveCwd:t.cwd,envAssignments:t.envAssignments});if(a)return a;return null}let s=ot(G(e));if(s.kind==="dynamic")return Ln(n,t);if(s.kind==="literal"){if(n.dynamicSourceInput)return Ln(n,t);return null}if(n.dynamicSourceInput??n.dynamicInput)return Ln(n,t);return null}if(ye.has(o))return k(Po(e,(i)=>t.analyzeNested?t.analyzeNested(i,{effectiveCwd:t.cwd,envAssignments:t.envAssignments}):null),t.policy)??re(e,t.policy?.rules??[])??it(n,t);if(Ce(o)){let i=Fo(e);if(!i)return it(n,t);if(Q(t.policy,"interpreter.one-liner-paranoid",!!t.paranoidInterpreters)){let a=k(b("interpreter.one-liner-paranoid",yn),t.policy);if(a)return a}if($o(o,i))return it(n,t);let s=t.analyzeNested?.(i,{effectiveCwd:t.cwd,envAssignments:t.envAssignments});if(s&&s.id!=="raw-text.dangerous-command"&&(s.reason!==Et||pn(i)))return s;if(Cn(i,t.scanWork))return k(b("interpreter.dangerous-command",$t),t.policy)??it(n,t);return it(n,t)}if(o==="rm"||o==="rmdir"){let i=o==="rm"&&(je(e)||n.dynamicRmInput);return k(Dn(G(e),{environment:t.environment,cwd:t.cwd,originalCwd:t.originalCwd,strict:t.strict,paranoid:t.paranoidRm,allowTmpdirVar:t.allowTmpdirVar,tmpdirWordSplittingUnsafe:tt(t.envAssignments,t.environment),trustedTmpdirValue:yt(t.envAssignments,t.environment),protectedGitMetadata:t.protectedGitMetadata,policy:t.policy}),t.policy)??(i&&n.dynamicRmInput?it(n,t):null)??(i?WE(n,t):null)}if(o==="find")return Si(G(e),{...t,derivedCommandWorkBudget:t.derivedCommandWorkBudget,analyzeTokens:(i,s)=>Tt(i,{...t,cwd:s??void 0,derivedCommandWorkBudget:t.derivedCommandWorkBudget},n)})??re(e,t.policy?.rules??[])??it(n,t);if(o==="git")return k(On(G(e),{env:t.environment.env,cwd:t.cwd,envAssignments:t.envAssignments,policy:t.policy,worktreeMode:n.dynamicInput?!1:t.worktreeMode}),t.policy)??re(e,t.policy?.rules??[])??it(n,t);return re(e,t.policy?.rules??[])??it(n,t)}function Ln(e,t){return e.shellDynamicMatch?k(e.shellDynamicMatch,t.policy):null}function it(e,t){return e.dynamicSourceInput&&e.dynamicSourceMatch?k(e.dynamicSourceMatch,t.policy):null}function WE(e,t){return e.dynamicInput&&e.rmDynamicMatch?k(e.rmDynamicMatch,t.policy):null}var Ga="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",za="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",FE="__CC_SAFETY_NET_XARGS_INPUT__",wi="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",_i="rm",GE=/(?:^|[;&|]\s*|\b(?:eval|source)\s+|\b(?:ba|da|z|k)?sh\s+-c\s+)\s*["']?\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,zE=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,$E=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,BE=/^(?:[0-9]+|[@*])$/;function Vm(e,t){let n=e.map(I),{childStart:r,replacementToken:o}=Kt(n),i=n.slice(r),s=b("xargs.shell-dynamic",za);if(HE(i,o,t)&&k(s,t.policy))return k(s,t.policy);for(let a of He(i,t)){let l=a.tokens,c=o!==null&&l[0]!==i[0]&&(l[0]?.includes(o)??!1)?k(s,t.policy):null;if(c)return c;let u=Ym(l,o,a.wrapperEnvAssignments),m=a.head==="rm"&&o!==null&&Km(l,o),f=Tt(l,{...t,cwd:a.cwd,envAssignments:a.envAssignments},{dynamicInput:u,dynamicSourceInput:m||qm(l,a.head,o,a.wrapperEnvAssignments,u,t.scanWork,t.environment),dynamicRmInput:m,shellDynamicMatch:s,dynamicSourceMatch:s,rmDynamicMatch:b("xargs.rm-recursive-force-dynamic",Ga)});if(f)return f;let d=UE(l,o,t.policy?.rules??[]);if(d)return d;if(a.head==="git"){let g=o===null?[...l,FE]:l,y=o!==null&&(l.some((R)=>R.includes(o))||Array.from(a.envAssignments.values()).some((R)=>R.includes(o))),h=Tt(g,{...t,cwd:a.cwd,envAssignments:a.envAssignments,worktreeMode:o===null||y?!1:t.worktreeMode});if(h)return h}let p=re(l,t.policy?.rules??[]);if(p)return p}return null}function UE(e,t,n){if(n.length===0)return null;if(t===null){for(let o of n){let i=re([...e,...o.subcommand?[o.subcommand]:[],...o.block_args],n);if(i)return i}return null}let r=new Set(n.flatMap((o)=>[o.subcommand,...o.block_args].flatMap((i)=>i?e.flatMap((s)=>$a(s,t,i)):[])));for(let o of r){let i=re(e.map((s)=>s.replaceAll(t,o)),n);if(i)return i}return null}function $a(e,t,n){let r=e.indexOf(t);if(r===-1||e.indexOf(t,r+t.length)!==-1)return[];let o=e.slice(0,r),i=e.slice(r+t.length);return n.startsWith(o)&&n.endsWith(i)?[n.slice(o.length,n.length-i.length)]:[]}function qm(e,t,n,r,o,i,s){if(ee.has(t)){if(Oe(e))return!1;if(n!==null&&jE(e,n))return!0;let a=nt(e);if(!a){let l=ot(G(e));if(l.kind==="literal")return n!==null&&l.source.includes(n);return l.kind==="none"&&o}if(n!==null&&a.includes(n))return!0;if(ht(a,i))return!0;return VE(a,n,r)}if(Ce(t))return Hm(e,n,zo,Au(t));if(ye.has(t))return Hm(e,n,Ls,iu);if(t==="eval"){let a=Mn(G(e));if(a.kind==="dynamic")return!0;if(n!==null)return a.kind==="literal"&&a.source.includes(n);return o}if(t==="find")return qE(e,n,i,s);if(t==="git"){let a=Ve(e);return n===null?a.subcommand===null:(a.subcommand?.includes(n)??!1)||a.subcommand!==null&&In.has(a.subcommand.toLowerCase())&&Zm(a.rest,n).some((l)=>l.includes(n))}return!1}function Hm(e,t,n,r){let o=n(e);if(t===null)return o.optionsOpen||n([...e,wi]).sources.some((l)=>l.value===wi);if(o.sources.some((l)=>l.value.includes(t)))return!0;let i=new Set(o.sources.map((l)=>`${l.tokenIndex}\x00${l.kind}\x00${l.value}`)),s=r.flatMap((l)=>[l.selector,...l.valueForm==="attached-only"||l.valueForm==="attached-or-separate"?[`${l.selector}${wi}`]:[],...l.valueForm==="equals-or-separate"?[`${l.selector}=${wi}`]:[]]),a=new Set(s.flatMap((l)=>e.flatMap((c)=>$a(c,t,l))));return Array.from(a).some((l)=>n(e.map((c)=>c.replaceAll(t,l))).sources.some((c)=>!i.has(`${c.tokenIndex}\x00${c.kind}\x00${c.value}`)))}function HE(e,t,n){if(e.length===0||(e[0]??"").toLowerCase()==="command")return!1;let r=new Set(Array.from(He(e,n),(i)=>i.head)),o=t===null?[...e,_i]:e.map((i,s)=>s===0?i:i.replaceAll(t,_i));return Array.from(He(o,n)).some((i)=>i.head===_i&&!r.has(_i))}function Km(e,t){return Zm(e.slice(1),t).some((n)=>n.includes(t)&&(n.startsWith("-")||n.startsWith(t)))}function Zm(e,t){let n=e.findIndex((r)=>r==="--"&&!r.includes(t));return n===-1?e:e.slice(0,n)}function Ym(e,t,n){if(t===null)return!0;return e.some((r)=>r.includes(t))||Array.from(n.values()).some((r)=>r.includes(t))}function jE(e,t){let n=rt(e);if(n.commandIndex!==null&&(e[n.commandIndex]??"").includes(t)||n.scriptIndex!==null&&(e[n.scriptIndex]??"").includes(t))return!0;return["-c","-nc","-cn",`--${t}`,t].some((o)=>e.some((i,s)=>{if(s===0||!i.includes(t))return!1;return $a(i,t,o).some((l)=>{let c=e.map((m,f)=>f===s?m.replaceAll(t,l):m),u=rt(c);if(u.commandIndex===null&&u.scriptIndex===null)return!1;if(n.commandIndex===null&&u.commandIndex!==null)return!0;if(n.scriptIndex===null&&u.scriptIndex!==null)return!0;if(u.commandIndex!==null&&(c[u.commandIndex]??"").includes(l))return!0;return u.scriptIndex!==null&&(c[u.scriptIndex]??"").includes(l)})}))}function VE(e,t,n){let r=new Set(t===null?[]:Array.from(n).filter(([,o])=>o.includes(t)).map(([o])=>o));for(let o of e.matchAll(GE))if(jm(o,r))return!0;for(let o of e.matchAll(zE))for(let i of(o[1]??"").matchAll($E))if(jm(i,r))return!0;return Fa(e,r)}function jm(e,t){let n=e[1]??e[2];return n!==void 0&&(BE.test(n)||t.has(n))}function qE(e,t,n,r){if(t===null)return!0;let o=!1,i=0;for(let s=1;s<e.length;s++){let a=e[s]??"";if(!o&&!a.startsWith("-")&&a!=="!"&&a!=="("){if(a.indexOf(t)===0)return!0;continue}if(o=!0,i>0){i--;continue}if(Ct(a)){let c=xr(e,s);s=c.nextIndex-1;for(let u of He(c.tokens,{environment:r,cwd:void 0})){let m=Ym(u.tokens,t,u.wrapperEnvAssignments);if(u.head==="rm"&&Km(u.tokens,t)||qm(u.tokens,u.head,t,u.wrapperEnvAssignments,m,n,r))return!0}continue}let l=Pt(a);if(l>0){if(i=l,a.includes(t))return!0;continue}if(a.includes(t))return!0}return!1}function Kt(e){let t=new Set(["-L","-n","-P","-s","-a","-E","-R","-S","-e","-d","-J","--max-args","--max-procs","--max-chars","--arg-file","--eof","--delimiter","--max-lines","--process-slot-var"]),n=null,r=1;while(r<e.length){let o=e[r];if(!o)break;if(o==="--")return{childStart:r+1,replacementToken:n};if(o.startsWith("-")){if(o==="-I"){n=e[r+1]??"{}",r+=2;continue}if(o.startsWith("-I")&&o.length>2){n=o.slice(2),r++;continue}if(o==="--replace"){n="{}",r++;continue}if(o.startsWith("--replace=")){let i=o.slice(10);n=i===""?"{}":i,r++;continue}if(o==="-J"){n=e[r+1]??"{}",r+=2;continue}if(t.has(o))r+=2;else r++}else return{childStart:r,replacementToken:n}}return{childStart:e.length,replacementToken:n}}var Tr="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",Ir="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",ZE="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",YE="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",XE=/\{[^{}\s]*\}/,of=/\{\}|\{-?\d+\}/g,JE=["e","f","source","file","-e","-f","--source","--file"],QE=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],ex=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),tx=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),Xm=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),nx=new Set(["--workdir","--wd"]),Jm="__CC_SAFETY_NET_PARALLEL_SOURCE__",rx=new TextEncoder,Ua=B.maxDerivedBytes+4*B.maxPlaceholderReplacements;function pe(e,t){for(let n of e){let r=t(n);if(r)return r}return null}function sf(e,t){return pe([...e],(n)=>ht(n,t.scanWork))}function af(e,t){let n=e.map(I);if((t.envAssignments?.has("PARALLEL")?t.envAssignments.get("PARALLEL"):t.environment.env.get("PARALLEL"))?.trim()){let p=Yt(t);if(p)return p}if(n.length===2&&(n[1]==="--version"||n[1]==="--help"))return null;let o=hf(n),{template:i,jobs:s,runsRemotely:a,readsCommandsFromInput:l,unsupported:c,workdir:u,dryRun:m}=o;if(c){let p=Yt(t);if(p)return p;let g=sf(t.envAssignments?.values()??[],t);if(g)return g}if(l){let p=dx(t);if(p)return p}if(u!==void 0&&a){let p=Yt(t);if(p)return p}let f=gx(u,t.cwd,t.environment.paths);if(f===null){let p=Yt(t);if(p)return p}let d=a?{...t,cwd:void 0,originalCwd:void 0}:f===null||f===void 0||f===t.cwd?t:{...t,cwd:f};if(m){if([...He(i,d)].flatMap((g)=>[...g.envAssignments.values()]).some(qa)){let g=Yt(t);if(g)return g}return null}if(i.length===0){if(s.some((y)=>y.length!==1)){let y=Yt(t);if(y)return y}let p=s.map((y)=>y[0]??"");Se(t.budget,Ha(p));let g=mf(d.envAssignments,d.cwd,a);return pe(p,(y)=>t.analyzeNested(y,g))}return pe(He(i,d),(p)=>ox(p,o,t,d))}function ox(e,t,n,r){let{jobs:o,templateHasPlaceholder:i,runsRemotely:s,usesStdin:a}=t,l=e.tokens,c={...r,cwd:e.cwd,envAssignments:e.envAssignments},u=[...e.envAssignments.values()];if(u.some(pf)){let h=Yt(n);if(h)return h}let m=sf(u,n);if(m)return m;let f=u.some(H),d=i||f,p=a&&d,g=mf(e.envAssignments,e.wrapperCwd,s||p);if(ee.has(e.head)){let h=()=>{if(!i||o.length===0)return null;return Se(n.budget,Pi(l,o,"generic")),pe(o,(A)=>Tt(l.map((_)=>It(_,A)),c))};if(Oe(l))return h();let R=nt(l);if(R){if(gf(R)){let C=Zt(n);if(C)return C;if(o.length===0)return null;return Se(n.budget,rf(R,o)),pe(o,(P)=>n.analyzeNested(It(R,P),g))}if(H(R)){if(o.length>0)return Se(n.budget,rf(R,o)),pe(o,(x)=>n.analyzeNested(It(R,x),g));Se(n.budget,tf(R));let C=wr(R);if(C?.[0]&&z(C[0])==="rm"&&je(C)){let x=ef(n);if(x)return x}let P=C?Tt(C,c,{dynamicInput:a,shellDynamicMatch:b("parallel.shell-dynamic",Ir),rmDynamicMatch:b("parallel.rm-recursive-force-dynamic",Tr)}):null;if(P)return P;return n.analyzeNested(R,g)}let A=!f&&(!i||o.length>0)?(o.length>0?o:[void 0]).map((C)=>Ei(G(C===void 0?l:i?l.map((P)=>It(P,C)):[...l,...C]),R)):[];if(A.some((C)=>C.kind==="dynamic")){let C=Zt(n);if(C)return C}let _=A.flatMap((C)=>C.kind==="literal"?[C.source]:[]);if(_.length>0)return Se(n.budget,Ha(_)),pe(_,(C)=>n.analyzeNested(C,g));if(Se(n.budget,tf(R)),Nn(R)){let C=Zt(n);if(C)return C}let S=n.analyzeNested(R,g);if(S)return S;if(d)return Zt(n);return null}let E=ot(G(l));if(E.kind==="dynamic"||E.kind==="literal"&&H(E.source))return Zt(n)??h();if(E.kind==="literal")return h();if(o.length>0){let A=Zt(n);if(A)return A;let _=h();if(_)return _;if(i)return null;let S=o.flatMap((C)=>C[0]===void 0?[]:[C[0]]);return Se(n.budget,Ha(S)),pe(S,(C)=>n.analyzeNested(C,g))}if(d||a)return Zt(n)??h();return null}if(e.head==="rm"&&je(l)){if(i&&o.length>0)return Se(n.budget,Pi(l,o,"rm")),pe(o,(R)=>Ba(l.map((E)=>ja(E,R)),e.cwd,r));if(o.length>0)return Se(n.budget,nf(l,o)),pe(o,(R)=>Ba([...l,...R],e.cwd,r));let h=Ba(l.flatMap((R,E)=>{if(E===0||!H(R))return[R];return R.startsWith("-")?[ja(R,[""])]:[]}),e.cwd,r);if(h)return h;return ef(n)}Se(n.budget,i&&o.length>0?Pi(l,o,"generic"):o.length>0?nf(l,o):df(l));let y=o.length>0?o:[void 0];return pe(y,(h)=>{let R=h===void 0?l:i?l.map((T)=>It(T,h)):[...l,...h],E=b("parallel.shell-dynamic",Ir),A=a&&e.head==="find"?ux(R,r):null,_=cf(R,a,n.policy?.rules??[],n.budget)??A?.customResult??null,S=z(e.head),C=a&&(S==="rm"&&Va(R)||S==="xargs"&&uf(R)||A?.rmOptions===!0),P=a&&(C||A?.executedSource===!0||A===null&&lf(R,S)),x=Tt(R,{...c,worktreeMode:s||a||d?!1:n.worktreeMode},{dynamicInput:a||d,dynamicRmInput:C,dynamicSourceInput:_!==null||P,shellDynamicMatch:E,dynamicSourceMatch:E,rmDynamicMatch:b("parallel.rm-recursive-force-dynamic",Tr)});if(P){let T=k(E,n.policy);if(T)return T}return x??_??re(R,n.policy?.rules??[])})}function lf(e,t){if(H(e[0]??""))return!0;if(t==="eval"||t==="source"||t===".")return!0;if(t==="parallel"||t==="xargs")return!0;if(ee.has(t))return ax(e);if(t==="git")return ix(e);if(t==="find")return!0;if(ye.has(t))return Qm(e,JE,rr);if(Ce(t))return Qm(e,QE,Go);return!1}function Va(e){let t=e.indexOf("--"),n=e.slice(1,t===-1?void 0:t);if(!e.some(H))return t===-1;return n.some((o)=>H(o)&&(o.startsWith("-")||gf(o)))}function ix(e){if(sx(e))return!0;let t=Ve(e);if(t.subcommand===null||H(t.subcommand))return!0;if(!In.has(t.subcommand.toLowerCase()))return!1;let n=t.rest.indexOf("--"),r=t.rest.slice(0,n===-1?void 0:n);if(!e.some(H))return n===-1;return r.some(H)}function sx(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n||n==="--"||!n.startsWith("-"))return!1;if(n==="-c"||n==="--config-env"){if(H(e[t+1]??""))return!0;t++;continue}if(n.startsWith("-c")&&n.length>2||n.startsWith("--config-env=")){if(H(n))return!0;continue}if(H(n))return!0}return!1}function ax(e){if(Oe(e))return!1;let t=nt(e);if(t!==null)return H(t);let n=ot(G(e));if(n.kind==="literal")return H(n.source);if(n.kind==="dynamic")return!0;return!e.some(H)}function Qm(e,t,n){let r=n(e);if(r.some((i)=>H(i.value)))return!0;if(!e.some(H))return n([...e,Jm]).some((i)=>i.value===Jm);let o=new Set(r.map((i)=>`${i.tokenIndex}\x00${i.kind}\x00${i.value}`));return t.some((i)=>n(e.map((s)=>It(s,[i]))).some((s)=>!o.has(`${s.tokenIndex}\x00${s.kind}\x00${s.value}`)))}function cf(e,t,n,r){if(!t||n.length===0)return null;let o=n.filter((s)=>z(s.command)===z(e[0]??""));if(o.length===0)return null;let i=e.some(H);if(Se(r,lx(e,o,i)),!i)return pe(o,(s)=>re([...e,...s.subcommand?[s.subcommand]:[],...s.block_args],[s]));return pe(o,(s)=>{let a=new Set([s.subcommand,...s.block_args].flatMap((l)=>l?cx(e,l):[]));return pe(a,(l)=>re(e.map((c)=>It(c,[l])),[s]))})}function lx(e,t,n){let r=n?Xt(De(t.map((o)=>o.block_args.length+(o.subcommand?1:0)),B.maxChildAnalyses),2*Math.max(e.length,1),B.maxChildAnalyses):t.length;return{childAnalyses:r,derivedTokens:Xt(r,e.length,B.maxDerivedTokens)}}function cx(e,t){return e.flatMap((n)=>{let r=[...n.matchAll(/\{[^{}\s]*\}/g)];if(r.length!==1)return[];let o=r[0];if(!o||o.index===void 0)return[];let i=n.slice(0,o.index),s=n.slice(o.index+o[0].length);if(!t.startsWith(i)||!t.endsWith(s))return[t];let a=t.slice(i.length,t.length-s.length);return a!==t?[t,a]:[t]})}function ux(e,t){let n={customResult:null,executedSource:!e.some(H),rmOptions:!1},r=!1,o=0,i=null,s=()=>{if(!i?.some(H))return;for(let a of He(i,t))n.executedSource||=lf(a.tokens,a.head),n.rmOptions||=a.head==="rm"&&Va(a.tokens)||a.head==="xargs"&&uf(a.tokens),n.customResult??=cf(a.tokens,!0,t.policy?.rules??[],t.budget)};for(let a of e.slice(1)){if(!r&&!a.startsWith("-")&&a!=="!"&&a!=="("){n.executedSource||=H(a);continue}if(r=!0,i){if(a===";"||a==="+"){s(),i=null;continue}i.push(a);continue}if(o>0){o--;continue}if(Ct(a)){i=[],n.executedSource||=H(a);continue}let l=Pt(a);if(l>0){o=l,n.executedSource||=H(a);continue}n.executedSource||=H(a)}return s(),n}function uf(e){let t=e.slice(Kt(e).childStart);return z(t[0]??"")==="rm"&&Va(t)}function Ai(e,t){return(n)=>k(b(e,t),n.policy)}var Zt=Ai("parallel.shell-dynamic",Ir),dx=Ai("parallel.command-stream-dynamic",ZE),Yt=Ai("parallel.command-stream-dynamic",YE),ef=Ai("parallel.rm-recursive-force-dynamic",Tr);function Ba(e,t,n){return k(Dn(G(e),{environment:n.environment,cwd:t,originalCwd:n.originalCwd,strict:n.strict,paranoid:n.paranoidRm,allowTmpdirVar:n.allowTmpdirVar,tmpdirWordSplittingUnsafe:tt(n.envAssignments??new Map,n.environment),trustedTmpdirValue:yt(n.envAssignments??new Map,n.environment),protectedGitMetadata:n.protectedGitMetadata,policy:n.policy}),n.policy)}function Ha(e){return{childAnalyses:e.length,derivedTokens:e.length,derivedBytes:Or(e)}}function tf(e){return df([e])}function df(e){return{childAnalyses:1,derivedTokens:e.length,derivedBytes:Or(e)}}function nf(e,t){if(t.length>B.maxChildAnalyses)return{childAnalyses:t.length};return{childAnalyses:t.length,derivedTokens:De(t.map((n)=>e.length+n.length),B.maxDerivedTokens),derivedBytes:De([Xt(Or(e),t.length,B.maxDerivedBytes),De(t.map((n)=>Or(n)),B.maxDerivedBytes)],B.maxDerivedBytes)}}function rf(e,t){return Pi([e],t,"generic")}function Pi(e,t,n){if(t.length>B.maxChildAnalyses)return{childAnalyses:t.length};let r=Xt(e.length,t.length,B.maxDerivedTokens);if(r>B.maxDerivedTokens)return{childAnalyses:t.length,derivedTokens:r};let o=px(e.map((l)=>fx(l,n))),i=Xt(o.occurrences,t.length,B.maxPlaceholderReplacements);if(i>B.maxPlaceholderReplacements)return{childAnalyses:t.length,derivedTokens:r,placeholderReplacements:i};if(mx(o,t,i))return{childAnalyses:t.length,derivedTokens:r,derivedBytes:B.maxDerivedBytes+1,placeholderReplacements:i};let s=n==="generic"?It:ja,a=De(t.map((l)=>Or(e.map((c)=>s(c,l)))),B.maxDerivedBytes);return{childAnalyses:t.length,derivedTokens:r,derivedBytes:a,placeholderReplacements:i}}function mx(e,t,n){let r=B.maxDerivedBytes+4*n;return De([Xt(e.fixedBytes,t.length,r),Xt(e.occurrences,De(t.map((o)=>o.reduce((i,s)=>Math.max(i,kr(s)),0)),r),r)],r)>r}function fx(e,t){let n=t==="generic"?e.matchAll(/\{[^{}\s]*\}/g):e.matchAll(of),r=0,o=0,i=0;for(let s of n){if(r>=B.maxPlaceholderReplacements)return{occurrences:B.maxPlaceholderReplacements+1,fixedBytes:0};o=De([o,kr(e.slice(i,s.index))],Ua),r++,i=s.index+s[0].length}return{occurrences:r,fixedBytes:r===0?kr(e):De([o,kr(e.slice(i))],Ua)}}function px(e){return{occurrences:De(e.map((t)=>t.occurrences),B.maxPlaceholderReplacements),fixedBytes:De(e.map((t)=>t.fixedBytes),Ua)}}function Or(e,t=B.maxDerivedBytes){return De(e.map(kr),t)}function kr(e){return rx.encode(e).byteLength}function De(e,t){let n=0;for(let r of e){if(!Number.isSafeInteger(r)||r<0||r>t-n)return t+1;n+=r}return n}function Xt(e,t,n){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<0||e!==0&&t>Math.floor(n/e))return n+1;return e*t}function mf(e,t,n){let r={};if(e)r.envAssignments=e;if(n)return r.effectiveCwd=null,r.worktreeMode=!1,r;if(t!==void 0)r.effectiveCwd=t;return Object.keys(r).length>0?r:void 0}function It(e,t){return e.replace(/\{[^{}\s]*\}/g,(n)=>ff(n,t))}function ja(e,t){return e.replace(of,(n)=>ff(n,t))}function ff(e,t){let n=/^\{(-?\d+)[^{}\s]*\}$/.exec(e)?.[1];if(n===void 0)return t[0]??"";let r=Number(n),o=r>0?r-1:t.length+r;return t[o]??""}function H(e){return XE.test(e)}function pf(e){if(qa(e))return!0;for(let t of e.matchAll(/\{[^{}\s]*\}/g))if(!/^(?:\{\}|\{-?\d+\})$/.test(t[0]))return!0;return!1}function qa(e){let t=e.indexOf("{=");return t!==-1&&e.indexOf("=}",t+2)!==-1}function gf(e){return/^\{[^{}\s]*\}$/.test(e)}function hf(e){let t=1,n=[],r=e.length,o=-1,i=!1,s=!1,a=!1,l,c=e.some((p)=>p==="::::"||p==="::::+"||p===":::+");while(t<e.length){let p=e[t];if(p===void 0)break;if(p===":::"){o=t;break}if(p==="--"){let E=Ra(e,t+1);n.push(...E.templateTokens),r=t+1,o=E.markerIndex;break}if(!p.startsWith("-")){let E=Ra(e,t);n.push(...E.templateTokens),r=t,o=E.markerIndex;break}let g=e[t+1],y=p.indexOf("="),h=y===-1?p:p.slice(0,y),R=y===-1?void 0:p.slice(y+1);if(p==="--dry-run"){a=!0,t++;continue}if(p==="-I"||p.startsWith("-I")&&p.length>2){c||=(p==="-I"?g:p.slice(2))!=="{}",t+=p==="-I"?2:1;continue}if(p==="--replace"||p==="-i"){c=!0,t+=2;continue}if(h==="--replace"||p.startsWith("-i")&&p.length>2){let E=h==="--replace"?R:p.slice(2);c||=E!==""&&E!=="{}",t++;continue}if(p==="-a"||tx.has(h)){c=!0,t+=R===void 0?2:1;continue}if(p==="--pipe"||p==="--pipepart"){s=!0,t++;continue}if(h==="--env"){c=!0,t+=R===void 0?2:1;continue}if(Xm.has(h)||p.startsWith("-S")&&p.length>2){i=!0,t+=Xm.has(p)?2:1;continue}if(nx.has(h)){let E=R??g;if(E===void 0||E===":::"||E==="--"){c=!0,t++;continue}l=E,c||=R!==void 0&&E==="",t+=R===void 0?2:1;continue}if(p.startsWith("-j")&&p.length>2&&/^\d+$/.test(p.slice(2))){t++;continue}if(p.startsWith("--")&&R!==void 0){t++;continue}if(ex.has(p)){if(g===void 0||g===":::"||g==="--"){c=!0,t++;continue}t+=2;continue}t+=p==="-j"||p==="--jobs"?2:1}c||=n.some(a?qa:pf);let u=[];if(o!==-1){let p=[];for(let g=o+1;g<e.length;g++){let y=e[g];if(y===":::"){u.push(p),p=[];continue}if(y!==void 0)p.push(y)}u.push(p)}let m=hx(u),f=n.some(H),d=n.length===0&&o===-1;return{template:n,jobs:m,childStart:r,templateHasPlaceholder:f,runsRemotely:i,usesStdin:s||o===-1,readsCommandsFromInput:d,unsupported:c,workdir:l,dryRun:a}}function gx(e,t,n){if(e===void 0)return;if(e==="..."||/[{}$`*?~[]/.test(e))return null;if(!t&&!KE(e))return null;try{return wt(t??e,e,n)}catch{return null}}function hx(e){if(e.length===0||e.some((n)=>n.length===0))return[];let t=[[]];for(let n of e){if(n.length===1){let o=n[0];if(o===void 0)return[];for(let i of t)i.push(o);continue}let r=[];for(let o of t)for(let i of n)if(r.push([...o,i]),r.length>B.maxChildAnalyses)return r;t=r}return t}function yf(e){return hf(e).childStart}var yx="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",ki="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function Za(e){return e?.parts.some((t)=>t.provenance==="command-substitution")??!1}function Ka(e){return e?.parts.some((t)=>t.provenance==="literal"&&t.raw.replace(/^["']/,"").startsWith("-"))??!1}function bf(e,t,n,r,o=!1,i){let a=(Jn(e,t)||r&&e!=="powershell"&&t[0]?.provenance==="variable")&&Q(i,"shell.dynamic-executable",o)?b("shell.dynamic-executable",yx):null;return k(a,i)??Sf(e,t,n,o,i)}function Sf(e,t,n,r,o){if(t.length<2)return null;let i=t.flatMap((a,l)=>Za(a)?[l]:[]);if(i.length===0)return null;let s=z(t[0]?.text??"");if(s==="git"){let a=Pn(e,t),l=bx(a);if(Q(o,"shell.dynamic-structure",r)&&i.some((m)=>m<=l))return k(b("shell.dynamic-structure",ki),o);if(k(On(a,{env:n.env}),o))return null;let c=t[l]?.text.toLowerCase(),u=a.findIndex((m,f)=>f>l&&I(m)==="--");if(Q(o,"shell.dynamic-structure",r)&&c&&In.has(c)&&i.some((m)=>m>l&&(u===-1||m<u)))return k(b("shell.dynamic-structure",ki),o);return null}if(s==="find")return Q(o,"shell.dynamic-structure",r)&&Sx(t)?k(b("shell.dynamic-structure",ki),o):null;if(s==="rm"){let a=t.findIndex((c,u)=>u>0&&I(c)==="--"),l=je(t.map(I));return Q(o,"shell.dynamic-structure",r)&&i.some((c)=>(a===-1||c<a)&&(c<t.length-1||!l))?k(b("shell.dynamic-structure",ki),o):null}if(s==="xargs")return Cf(e,t.slice(Kt(t.map(I)).childStart),"xargs",n,r,o);if(s==="parallel")return Cf(e,t.slice(yf(t.map(I))),"parallel",n,r,o);return null}function Cf(e,t,n,r,o,i){if(t.length===0)return null;let s=Cx(t,r);if(Jn(e,s)){let l=k(b(`${n}.shell-dynamic`,n==="xargs"?za:Ir),i);if(l)return l}let a=Sf(e,s,r,o,i);if(a)return a;if(s[0]?.text==="rm"&&s.slice(1).some((l)=>Za(l)&&Ka(l)))return k(b(`${n}.rm-recursive-force-dynamic`,n==="xargs"?Ga:Tr),i);return null}function Cx(e,t){let n=Ut(e,t),r=n.rewritten?G(n.words.map(I)):n.words,o=r[0];return o&&I(o)==="busybox"?r.slice(1):r}function bx(e){let t=1;while(t<e.length){let n=e[t],r=n?I(n):"";if(Qe.has(r)){t+=2;continue}if(r.startsWith("-")){t++;continue}return t}return t}function Sx(e){let t=!1,n=0,r=!1,o=!1;for(let i=1;i<e.length;i++){let s=e[i];if(!s)continue;let a=Za(s);if(n>0){n--;continue}if(o){if(s.text===";"||s.text==="+"){o=!1,t=!0,r=!1;continue}if(a&&(r||Ka(s)))return!0;r=!1;continue}if(!t&&!s.text.startsWith("-")){if(a&&(i>1||Ka(s)))return!0;continue}if(t=!0,a)return!0;let l=Pt(s.text);if(l>0){n=l;continue}if(Ct(s.text))o=!0,r=!0}return!1}function Ya(e,t){return e.some((n)=>{if(n.value==="-"&&(n.kind==="main-script"||n.kind==="program-file"))return!0;return!li(t[n.tokenIndex],n.value)})}var vx="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",Rx="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",Ex="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function vf(e,t){let n=t.slice(1);if(e==="dd"&&n.some((r)=>/^of=\/dev\/.+/.test(r)))return b("dd.device-write",vx);if((e==="mkfs"||e.startsWith("mkfs."))&&n.some((r)=>r.startsWith("/dev/")))return b("mkfs.device",Rx);if(e==="shred"&&n.length>0)return b("shred.target",Ex);return null}var Ef=[{heads:new Set(["rm","rmdir"]),analyze:(e)=>Dn(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoid:e.options.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:tt(e.envAssignments,e.options.environment),trustedTmpdirValue:yt(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,policy:e.options.policy})},{heads:new Set(["git"]),analyze:(e)=>On(e.words,Xa(e))},{heads:new Set(["find"]),analyze:(e)=>Si(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:tt(e.envAssignments,e.options.environment),trustedTmpdirValue:yt(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,derivedCommandWorkBudget:e.options.derivedCommandWorkBudget,envAssignments:e.envAssignments,policy:e.options.policy,analyzeTokens:e.analyzeChildTokens,analyzeNested:(t,n)=>Jt(e.options.analyzeNested(t,n))})},{heads:new Set(["xargs"]),analyze:(e)=>Vm(e.words,{...Rf(e),analyzeNested:(t,n)=>Jt(e.options.analyzeNested(t,n))})},{heads:new Set(["parallel"]),analyze:(e)=>af(e.words,{...Rf(e),budget:e.options.parallelBudget,analyzeNested:(t,n)=>Jt(e.options.analyzeNested(t,n))})}];function Rf(e){return{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoidRm:e.options.paranoidRm,paranoidInterpreters:e.options.paranoidInterpreters,allowTmpdirVar:e.allowTmpdirVar,protectedGitMetadata:e.options.protectedGitMetadata,derivedCommandWorkBudget:e.options.derivedCommandWorkBudget,envAssignments:e.envAssignments,worktreeMode:e.options.worktreeMode,policy:e.options.policy,scanWork:e.options.scanWork}}function Jt(e){return e?{id:e.ruleId??"",reason:e.reason,intent:e.intent??"manual_only"}:null}function Xa(e){return{env:e.options.environment.env,cwd:e.cwd,dynamicArguments:e.dynamicArguments,envAssignments:e.envAssignments,policy:e.options.policy,worktreeMode:e.options.worktreeMode}}var Pf="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function Af(e){return Ef.find((t)=>t.heads.has(e))?.analyze}function Dr(e,t,n){let r=n.trace;if(e.length===0)return null;let o=n.commandView?.dialect??"posix",i=(w)=>w.map((L)=>o==="posix"?I(L):L.text),s=n.effectiveCwd===null,a=s?void 0:n.effectiveCwd??n.cwd,l=s?void 0:n.cwd,c=fi(e);if(c.envAssignments.size>0)r?.recordSegment({type:"env-strip",input:i(e),envVars:[...c.envAssignments.keys()],output:i(c.words)});let u=Ut(c.words,n.environment,a,new Map([...n.envAssignments??[],...c.envAssignments])),m=u.envSplitValues??[];if(m.length>0){let w=[...m,...i(u.words)].join(" "),L=ht(w,n.scanWork);if(L)return r?.recordSegment({type:"dangerous-text",token:w,matched:!0,reason:L.reason}),st(L);if(n.strict)return Re(r);let Z=pi(m,i(u.words));if(Z){ze(n.derivedCommandWorkBudget,Z.length);let J=n.analyzeNested(Z.join(" "),{effectiveCwd:u.cwd===void 0?n.effectiveCwd:u.cwd,envAssignments:new Map([...n.envAssignments??[],...c.envAssignments,...u.envAssignments])});if(J)return J}}let f=u.rewritten?G(i(u.words)):Pn(o,u.words),d=i(f),p={...n,wrapperNormalizationBudget:n.wrapperNormalizationBudget??{iterations:0}};if(r&&c.words.length>f.length){let w=i(c.words);r.recordSegment({type:"leading-tokens-stripped",input:w,removed:w.slice(0,w.length-f.length),output:d})}let g=new Map([...n.envAssignments??[],...c.envAssignments,...u.envAssignments]),y=d[0];if(!y)return null;if(Bt(y))throw new be;let h=z(y),R=u.cwd===null?void 0:u.cwd??a,E=u.cwd===null?void 0:l,A=u.cwd===void 0?n.effectiveCwd:u.cwd,_=!Sr(g,n.environment),S=bf(o,u.words,n.environment,t===0,n.strict,n.policy);if(S)return r?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:S.reason}),st(S);let C=Uo(d,n.policy);if(C){for(let w of[C.childIndex,...C.alternativeChildIndices]){xf(p.wrapperNormalizationBudget);let L=f.slice(w);r?.recordSegment({type:"transparent-wrapper",wrapper:C.wrapper,output:i(L)});let Z=Dr(L,t,{...p,effectiveCwd:A,envAssignments:g});if(Z)return Z}return null}let P=h==="eval"?Mn(f):h==="trap"?Gm(f):void 0;if(P?.kind==="dynamic"&&(n.strict||!n.commandView||!Wa(n.commandView)))return Re(r);if(P?.kind==="literal"){r?.recordSegment({type:"recurse",reason:h==="eval"?"shell-eval":"shell-trap",innerCommand:P.source,depth:t+1});let w=n.analyzeNested(P.source,{effectiveCwd:A,envAssignments:g,functionDefinitions:n.functionDefinitions});if(w)return w}if(Tf(y,h)){if(Oe(d))return null;let w=xx(d,g,A,n,r,t);if(w)return w;let L=nt(d);if(L){let rn=Ei(f,L);if(rn.kind==="dynamic")return Re(r);let Bi=rn.kind==="literal"?rn.source:L,yl=wx(Bi);r?.recordSegment({type:"shell-wrapper",wrapper:h,innerCommand:yl}),r?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:yl,depth:t+1});let Cl=n.analyzeNested(Bi,{effectiveCwd:A,envAssignments:g});if(Cl)return Cl;return Nn(Bi)?Re(r):null}let Z=ot(f);if(Z.kind==="dynamic")return Re(r);if(Z.kind==="literal")return Oi(Z.source,A,g,n,r,t);let J=zm(f,n.commandView?.redirections??[],n.hasPipelineInput??!1,n.literalShellInput);if(J.kind==="dynamic")return Re(r);if(J.kind==="literal")return r?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:J.source,depth:t+1}),n.analyzeNested(J.source,{effectiveCwd:A,envAssignments:g})}if(h==="source"||h==="."){let w=d[1]==="-p"?2:null;if(w!==null){let rn=n.commandView?f[w]:void 0;if(!rn)return null;if(rn.provenance!=="literal")return Re(r)}let L=w===null?1:3,Z=d[L]==="--"?L+1:L,J=n.commandView?f[Z]:void 0;if(!J)return null;if(J.provenance==="literal")return Oi(J.text,A,g,n,r,t);if(n.strict||!n.commandView||!Wa(n.commandView))return Re(r)}if(ye.has(h)){if(n.strict&&Ya(rr(d),f))return Re(r);let w=Po(d,(Z)=>Jt(n.analyzeNested(Z,{effectiveCwd:A,envAssignments:g}))),L=k(w,n.policy);if(L)return r?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:L.reason}),st(L)}if(Ce(h)){if(n.strict&&Ya(Go(d),f))return Re(r);let w=Fo(d);if(w){let L=Q(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(r?.recordSegment({type:"interpreter",interpreter:h,codeArg:w,paranoidBlocked:L}),L){let J=k(b("interpreter.one-liner-paranoid",yn),n.policy);if(J)return st(J)}if($o(h,w))return null;r?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:w,depth:t+1});let Z=n.analyzeNested(w,{effectiveCwd:A,envAssignments:g});if(Z&&Z.ruleId!=="raw-text.dangerous-command"&&(Z.reason!==Et||pn(w)))return Z;if(Cn(w,n.scanWork)){let J=k(b("interpreter.dangerous-command",$t),n.policy);if(J)return r?.recordSegment({type:"dangerous-text",token:w,matched:!0,reason:$t}),st(J)}r=void 0}}if(h==="busybox"&&d.length>1)return xf(p.wrapperNormalizationBudget),r?.recordSegment({type:"busybox",subcommand:d[1]??"unknown"}),r?.recordSegment({type:"recurse",reason:"busybox",innerCommand:d.slice(1).join(" "),depth:t+1}),Dr(f.slice(1),t,{...p,effectiveCwd:A,envAssignments:g});let x=k(vf(h,d),n.policy);if(x)return r?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:x.reason}),st(x);let T=r===p.trace?p:{...p,trace:r},O={words:f,head:h,cwd:R,originalCwd:E,envAssignments:g,allowTmpdirVar:_,dynamicArguments:u.words.some((w)=>w.provenance==="command-substitution"),depth:t,effectiveCwd:A,options:T,analyzeChildTokens:(w,L)=>Jt(Dr(G(w),t+1,{...T,commandView:void 0,effectiveCwd:L,envAssignments:g}))??re(w,T.policy.rules)},D=Af(h);if(h==="rm"||h==="xargs"||h==="parallel")r?.recordSegment({type:"tmpdir-check",tmpdirValue:g.has("TMPDIR")||n.environment.env.has("TMPDIR")?"<redacted>":null,isOverriddenToNonTemp:!_,allowTmpdirVar:_});let F=r&&h==="git"?Am(O.words,Xa(O)):void 0,oe=wf(F?F.match:D?.(O)??null,n.policy);if(r)_x(O,oe,F?.relaxation??null);if(oe)return st(oe);let xe=D!==void 0;if(!xe)if(!oo.has(h)){let w=r?[]:void 0;for(let L=1;L<d.length;L++){let Z=d[L];if(!Z)continue;w?.push(Z);let J=wf(Px(O,d,L),n.policy);if(J)return r?.recordSegment({type:"fallback-scan",tokensScanned:w??[],embeddedCommandFound:z(Z)}),st(J)}r?.recordSegment({type:"fallback-scan",tokensScanned:w??[]})}else r?.recordSegment({type:"fallback-scan",tokensScanned:[]});else r?.recordSegment({type:"fallback-scan",tokensScanned:[]});if(t===0||!xe){let w=re(d,n.policy.rules);if(r?.recordSegment({type:"custom-rules-check",rulesChecked:n.policy.rules.length>0,matched:!!w,reason:w?.reason}),w)return st(w)}else r?.recordSegment({type:"custom-rules-check",rulesChecked:!1,matched:!1});return null}function xx(e,t,n,r,o,i){let s=Mm(e);if(s.argvSource?.kind==="absent")return Re(o);if(s.argvSourceApplies&&s.argvSource){let l=Oi(s.argvSource.value,n,t,r,o,i,!0);if(l)return l}if(!s.envSourceApplies||!s.envName)return null;let a=t.get(s.envName);if(!a)return null;return Oi(a,n,t,r,o,i,!0)}function Oi(e,t,n,r,o,i,s=!1){if(s&&/[$`*?[\]]/.test(e))return Re(o);let a=br(e,t,r.environment.paths),l=a?r.literalHeredocFiles?.get(a):void 0;if(l===void 0)return s?Re(o):null;return ze(r.derivedCommandWorkBudget,1),o?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:l,depth:i+1}),r.analyzeNested(l,{effectiveCwd:t,envAssignments:n})}function wx(e){let t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.at(-1)===t?e.slice(1,-1):e}function _x(e,t,n){let r={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[e.head];if(!r)return;if(e.options.trace?.recordSegment({type:"rule-check",rule:r,matched:!!t||!!n,reason:t?.reason??n?.originalReason}),n)e.options.trace?.recordSegment({type:"worktree-relaxation",originalReason:n.originalReason,gitCwd:n.gitCwd})}function xf(e){if(e.iterations>=un)throw new be;e.iterations++}function st(e){return{reason:e.reason,ruleId:e.id||void 0,intent:e.intent}}function Re(e){return e?.recordSegment({type:"error",message:Pf}),st(kf())}function kf(){return{id:"",reason:Pf,intent:"stop_and_explain"}}function Tf(e,t){return ee.has(t)||e==="$SHELL"||e==="${SHELL}"||ee.has(M(t))}function Px(e,t,n){let r=He(t.slice(n),{environment:e.options.environment,cwd:e.cwd,envAssignments:e.envAssignments,policy:e.options.policy});for(let o of r){let i=Ax(e,n,o);if(i)return i}return null}function Ax(e,t,n){let r=n.tokens[0];if(!r)return null;let o=z(r);if(Tf(r,o)){ze(e.options.derivedCommandWorkBudget,e.words.length-t);let l=n.tokens;if(Oe(l))return null;let c=nt(l);if(!c){if(ot(G(l)).kind==="dynamic")return kf();return Ii(e,n)}let u=e.options.analyzeNested(c,{effectiveCwd:n.wrapperCwd===void 0?e.effectiveCwd:n.wrapperCwd,envAssignments:n.envAssignments});return u?Jt(u):Ii(e,n)}let i=Af(o);if(!i||o==="xargs"||o==="parallel"){if(n.wrappedByTransparent&&e.options.policy.rules.length>0)ze(e.options.derivedCommandWorkBudget,e.words.length-t);return Ii(e,n)}ze(e.options.derivedCommandWorkBudget,e.words.length-t);let s=[o,...n.tokens.slice(1)],a={...e,words:G(s),head:o,cwd:n.cwd,originalCwd:n.wrapperCwd===null?void 0:e.originalCwd,envAssignments:n.envAssignments,allowTmpdirVar:!Sr(n.envAssignments,e.options.environment),effectiveCwd:n.wrapperCwd===void 0?e.effectiveCwd:n.wrapperCwd,options:o==="git"?{...e.options,worktreeMode:!1}:e.options};return i(a)??Ii(e,n)}function Ii(e,t){return t.wrappedByTransparent?re(t.tokens,e.options.policy.rules):null}function wf(e,t){return e?.id.startsWith("custom.")||e?.id==="raw-text.dangerous-command"?e:k(e,t)}var kx=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,Tx=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function Ix(e,t){let n=Df(e,t);if(n.length===0)return!1;let r=n[Of(n)];if(r==="cd"||r==="pushd"||r==="popd")return!0;return kx.test(e.join(" "))}function If(e,t,n,r){if(e.dialect==="powershell"){let a=Ox(e.words,r);if(a.kind==="none")return;if(!t||a.kind==="unknown")return null;return _f(Lx(a.target),t,n.paths)}let o=e.words.map(I);if(!Ix(o,n))return;if(!t)return null;let i=Df(o,n,t),s=Of(i);if(s===-1||i[s]!=="cd")return null;return _f(i[s+1],t,n.paths)}function _f(e,t,n){if(!e||e==="-"||e.includes("$")||e.includes("`"))return null;try{return Wx(wt(t,e,n),t,n)?t:null}catch{return null}}function Ox(e,t){let n=Dx(e[0])?1:0,r=e[n];if(!Mx(r,n===1))return{kind:"none"};let o=r.text.toLowerCase(),i=o.split(/[\\/]/).pop()??o;if(!Tx.has(i))return{kind:"none"};if(o!==i||i==="pop-location"||i==="popd")return{kind:"unknown"};return Nx(e.slice(n+1),t)}function Dx(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&(e.text==="&"||e.text===".")}function Mx(e,t){return e?.provenance==="literal"&&(t||!e.quoted&&e.raw===e.text)}function Nx(e,t){let n;for(let r of e){if(r.provenance!=="literal"||n!==void 0)return{kind:"unknown"};n=r.text}if(n!==void 0)return{kind:"target",target:n};return t===void 0?{kind:"unknown"}:{kind:"target",target:t}}function Lx(e){return e.includes("::")?void 0:e.replaceAll("\\","/")}function Of(e){let t=0;if(e[0]==="builtin"&&e.length>1)t=1;if(e[t]!=="time")return t;let n=t+1;while(e[n]?.startsWith("-"))n++;return n}function Df(e,t,n){let r=Fx(e);return kn([...r],t,n)}function Wx(e,t,n){let r=n.realpath(e),o=n.realpath(t);if(r===null||o===null)return Ti(e)===Ti(t);return Ti(r)===Ti(o)}function Fx(e){let t=0;while(t<e.length){let n=e[t];if(n==="{"||n==="("||n==="$(")t++;else break}return e.slice(t)}var Qa="TMPDIR",el="IFS",Mf=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Nf=/^[A-Za-z_][A-Za-z0-9_]*$/,Lf=new Set(["export","typeset","declare","readonly"]),Gx=new Set(["builtin","command","time"]);function Wf(e,t){return{env:e,effectiveEnvAssignments:Hx(e,t),shellAssignments:new Map}}function Ff(e){return{env:e.env,effectiveEnvAssignments:e.effectiveEnvAssignments?new Map(e.effectiveEnvAssignments):void 0,shellAssignments:new Map(e.shellAssignments)}}function tl(e,t){let n=zf(e,t);n.assignments.filter((s)=>s.persists).forEach((s)=>{t.shellAssignments.set(s.name,s.value),nl(t,s)});let r=n.commandIndex;if(r!==-1&&Lf.has(e[r]??""))e.filter((s)=>Nf.test(s)&&Ja(s)).forEach((s)=>{jx(t,s)});let o=r===-1?-1:$f(e,r);if(o===-1||e[o]!=="unset")return;let i=qx(e,o);if(i===null)return;e.slice(i).forEach((s)=>{Vx(t,s)})}function Gf(e,t){let n=zf(e,t).assignments;if(n.length===0)return t.effectiveEnvAssignments;let r=new Map(t.effectiveEnvAssignments??[]);return n.forEach((o)=>{r.set(o.name,o.value)}),r}function zf(e,t){let n=e.findIndex((s)=>!zx(s)),r=n!==-1&&Lf.has(e[$f(e,n)]??""),o=Ux(t);return{assignments:e.flatMap((s,a)=>{let l=$x(s,o,t.env);if(!l)return[];if(n!==-1&&a>n&&!r&&!Gs(l.name))return[];return o.set(l.name,l.value),[{...l,persists:n===-1||r}]}),commandIndex:n}}function $f(e,t){let n=t;while(Gx.has(e[n]??"")){n+=1;while(e[n]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(e[n]??""))return t;n+=1}}return n}function zx(e){return Te(e)!==null||Mf.test(e)}function $x(e,t,n){return Te(e)??Bx(e,t,n)}function Bx(e,t,n){let r=To(e,n,t);if(r)return r;let o=e.match(Mf)?.[1];if(!o)return null;let i=e.indexOf("=");return{name:o,value:`${t.has(o)?t.get(o):n.get(o)??""}${e.slice(i+1)}`}}function Ja(e){return e===Qa||e===el||zs(e)}function Ux(e){return new Map([...e.effectiveEnvAssignments??[],...e.shellAssignments])}function Hx(e,t){let n=[...Ao,Qa,el].map((r)=>{let o=e.get(r);return o===void 0?null:[r,o]}).filter((r)=>r!==null);if(n.length===0)return t;return new Map([...n,...t??[]])}function nl(e,t){let n=new Map(e.effectiveEnvAssignments??[]);n.set(t.name,t.value),e.effectiveEnvAssignments=n}function jx(e,t){nl(e,{name:t,value:e.shellAssignments.get(t)??e.effectiveEnvAssignments?.get(t)??e.env.get(t)??""})}function Vx(e,t){if(!Ja(t)&&!Nf.test(t))return;if(e.shellAssignments.set(t,""),!Ja(t)||t===Qa||t===el||or(t)){nl(e,{name:t,value:""});return}if(!e.effectiveEnvAssignments?.has(t))return;let n=new Map(e.effectiveEnvAssignments);n.delete(t),e.effectiveEnvAssignments=n.size===0?void 0:n}function qx(e,t){let n=t+1;while(n<e.length){let r=e[n];if(!r)return null;if(r==="--")return n+1;if(r==="-v"){n++;continue}if(r.startsWith("-"))return null;return n}return n}var Kx="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Qt="This heredoc form or stdin consumer is not supported safely. Use a quoted heredoc with a supported consumer (cat, tee, git apply, git commit, gh pr create, gh issue create), or ask the user to verify.",Zx=64;function al(e,t,n,r){let o=n.derivedCommandWorkBudget===void 0,i=n.parallelBudget===void 0;try{return Yx(e,t,{...n,derivedCommandWorkBudget:n.derivedCommandWorkBudget??ci(),parallelBudget:n.parallelBudget??Md()},r)}catch(s){let a=s instanceof be&&o?kd:s instanceof di&&i?Dd:void 0;if(!a)throw s;if(n.trace?.currentSegmentIndex!==void 0)n.trace.recordSegment({type:"error",message:a});else n.trace?.recordGlobal({type:"error",message:a});return{reason:a,segment:e,intent:"stop_and_explain"}}}function Yx(e,t,n,r){if(t>=ro)return n.trace?.recordSegment({type:"error",message:ut}),{reason:ut,segment:e,intent:"stop_and_explain"};let o=r??n.factStore?.getCommandProgram(e,n.shell??"auto")??Le(e,n.shell);if(o.status==="limited")return n.trace?.recordSegment({type:"error",message:ut}),{reason:ut,segment:e,intent:"stop_and_explain"};if(o.status==="invalid"){let c=o.issues.find((u)=>u.code.includes("heredoc"));if(c){if(!n.strict)return sl(e,n);let u=`Unsupported heredoc syntax: ${c.message}`;return n.trace?.recordGlobal({type:"error",message:u}),{reason:u,segment:e,intent:"stop_and_explain"}}return qf(e,n),{reason:Et,segment:e,intent:"stop_and_explain"}}if(n.strict&&o.status==="partial")return qf(e,n),{reason:Et,segment:e,intent:"stop_and_explain"};if(o.issues.some((c)=>c.code.includes("quote"))&&!n.analyzePartialProgram)return sl(e,n);let s=n.cwd,a=n.effectiveCwd!==void 0?n.effectiveCwd:n.cwd,l=Wf(n.environment.env,n.envAssignments);return Ni(o,t,{...n,rootProgram:o},s,[{effectiveCwd:a,shellGitContextState:l,literalHeredocFiles:new Map(n.literalHeredocFiles),functionDefinitions:new Map(n.functionDefinitions)}]).result}function Ni(e,t,n,r,o){let i=[...o],s,a;for(let[l,c]of e.nodes.entries()){if(c.kind==="connector"){a=c.operator;continue}let u=e.nodes[l+1],m=u?.kind==="connector"?u.operator:void 0,f=Xx(e,l,c,a,m),d=a==="&&"||a==="||",p=d?s:void 0,g=a==="&&"?p?.success??i:a==="||"?p?.failure??i:i,y=a==="||"?p?.success??[]:[],h=a==="&&"?p?.failure??[]:[],R=d||Wn(m);if(c.kind==="function"){let x=g.flatMap((O)=>{let D=Mr(O);return D.functionDefinitions.set(c.name,c.body),rl(O,[D],f,m==="&",Wn(m))}),T=ol(x,[],y,h,a,m);i=T.states,s=T.conditionalStates,a=void 0;continue}if(c.kind==="group"){let x=[],T=[];for(let D of g){let F=Ni(c.body,t,n,r,[Mr(D)]);if(F.result)return F;if(x.push(...rl(D,F.states,f,m==="&",Wn(m))),R)T.push(D,...f?F.states.map((oe)=>Di(D,oe)):F.states)}let O=ol(x,T,y,h,a,m);i=O.states,s=O.conditionalStates,a=void 0;continue}if(c.kind!=="command")continue;let E=n.trace?.flattenNested?n.trace.currentSegmentIndex:n.trace?.allocateSegment(),A=e.nodes[l-2],_=Li(a)&&A?.kind==="command"?Fm(A)??Qx(A):void 0,S=[],C=[];for(let x of g){let T=ew(c,t,n,r,[Mr(x)]);if(T.result)return{result:T.result,states:i};let O=e.dialect==="powershell"?T.states:T.states.map((D)=>Di(x,D));for(let D of O){let F=Mr(D),oe=rw(c,t,n.trace?{...n,trace:Kf(n.trace,E)}:n,r,F,Li(a),_);if(oe)return{result:oe,states:i};let xe=hw(c,F.functionDefinitions);if(xe)ze(n.derivedCommandWorkBudget,Wi(xe));let w=xe?t+1>=ro?il(c.displayText,n,[F]):Ni(xe,t+1,n,r,[F]):{result:null,states:[F]};if(w.result)return w;if(S.push(...rl(x,w.states,f,m==="&",Wn(m))),R)C.push(x),C.push(...w.states.map((L)=>f?Di(x,L):L))}}let P=ol(S,C,y,h,a,m);i=P.states,s=P.conditionalStates,a=void 0}return{result:null,states:i}}function Xx(e,t,n,r,o){if(n.kind==="group"&&n.style==="subshell")return!0;if(e.dialect==="posix"&&(Li(r)||Li(o)))return!0;if(o==="&")return!0;return e.dialect==="powershell"&&n.kind==="group"&&n.style==="brace"&&Jx(e,t)}function rl(e,t,n,r,o){let i=n?t.map((a)=>Di(e,a)):[...t],s=o?i.flatMap((a)=>Nr(e.literalHeredocFiles,a.literalHeredocFiles)?[a]:[{...a,literalHeredocFiles:new Map(e.literalHeredocFiles)},a]):i;return r?[e,...s]:s}function Di(e,t){return{...e,literalHeredocFiles:new Map(t.literalHeredocFiles)}}function Jx(e,t){let n=[...e.nodes.slice(0,t)].reverse().find((o)=>o.kind==="command"||o.kind==="connector");if(!n||n.kind!=="command")return!0;let r=n.words[0]?.text.toLowerCase();if(r==="&"||r===".")return!1;if(r==="write-output"||r==="function"||r==="start-job")return!0;if(tw(n))return!0;return n.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function Li(e){return e==="|"||e==="|&"}function Qx(e){if(e?.dialect!=="powershell")return;if(e.words.length===1&&e.words[0]?.quoted&&e.words[0].provenance==="literal")return e.words[0].text;if(e.words[0]?.text.toLowerCase()==="write-output"&&e.words.length===2&&e.words[1]?.provenance==="literal")return e.words[1].text;return}function Wn(e){return e==="&&"||e==="||"}function ol(e,t,n,r,o,i){let s={success:Mi([...n,...e]),failure:Mi([...r,...t])},a=Wn(i)?s:void 0;return{states:Wn(o)||a?Mi([...s.success,...s.failure]):s.success,conditionalStates:a}}function Kf(e,t,n=e.flattenNested){return{currentSegmentIndex:t,flattenNested:n,allocateSegment:e.allocateSegment,getNextSegmentIndex:e.getNextSegmentIndex,recordGlobal:e.recordGlobal,recordSegment:(r,o=t)=>e.recordSegment(r,o)}}function ew(e,t,n,r,o){let i=e.nested.map((s)=>({program:s,depth:t}));if(e.dialect==="powershell"){let s=nw(e);if(s){if(t+1>=ro)return il(s,n,o);let a=Le(s,"powershell");if(a.status==="limited")return il(s,n,o);if(a.status!=="complete")return Bf(i,n,r,o);ze(n.derivedCommandWorkBudget,Wi(a)),i.push({program:a,depth:t+1})}}return Bf(i,n,r,o)}function tw(e){let t=e.words[0];return t?.provenance==="variable"&&e.words.at(-1)?.text==="="?t.text.toLowerCase():void 0}function Bf(e,t,n,r){let o=[...r];for(let i of e){let s=[];for(let a of o){let l=Ni(i.program,i.depth,t,n,[Mr(a)]);if(l.result)return l;s.push(...l.states)}o=Mi(s)}return{result:null,states:o}}function nw(e){let t=e.words[0]?.provenance==="literal"&&!e.words[0].quoted&&e.words[0].raw===e.words[0].text&&(e.words[0].text==="&"||e.words[0].text==="."),n=t?1:0,r=e.words[n];if(r?.provenance!=="literal"||!t&&(r.quoted||r.raw!==r.text)||!["iex","invoke-expression"].includes(r.text.toLowerCase()))return;let o=e.words.slice(n+1),i=o[0]&&!o[0].quoted&&o[0].raw===o[0].text&&["-c","-command"].includes(o[0].text.toLowerCase())?1:0,s=o[i];return o.length===i+1&&s?.quoted&&s.provenance==="literal"?s.text:void 0}function Wi(e){return e.nodes.reduce((t,n)=>t+(n.kind==="command"?n.words.length+n.nested.reduce((r,o)=>r+Wi(o),0):n.kind==="group"||n.kind==="function"?Wi(n.body):0),0)}function il(e,t,n){return t.trace?.recordSegment({type:"error",message:ut}),{result:{reason:ut,segment:e,intent:"stop_and_explain"},states:[...n]}}function rw(e,t,n,r,o,i,s){let a=uw(e);if(a&&n.strict)return n.trace?.recordSegment({type:"error",message:a}),{reason:a,segment:e.source,intent:"stop_and_explain"};Zf(e,o,"before-consumer",n.environment.paths);let l=Pn(e.dialect,e.words).map(I),c=e.displayText,u=Gf(l,o.shellGitContextState);if(e.dialect==="powershell"){let d=k(dm(e,i,Cw(n,o.effectiveCwd)),n.policy);if(n.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!d,reason:d?.reason}),d)return yw(c,d)}if(l.length===1&&l[0]?.includes(" ")&&!Jn(e.dialect,e.words)){let d=k(ht(l[0],n.scanWork),n.policy),p=d!==null&&!n.strict&&_d(e,n.rootProgram,n.scanWork);if(d&&!p)return n.trace?.recordSegment({type:"dangerous-text",token:l[0],matched:!0,reason:d.reason}),{reason:d.reason,segment:c,ruleId:d.id,intent:d.intent};n.trace?.recordSegment({type:"dangerous-text",token:l[0],matched:!1});let g=Uf(e,a,o,u,s,n);if(g)return g;return tl(l,o.shellGitContextState),null}let m=Dr(e.words,t,{...n,commandView:e,cwd:r,effectiveCwd:o.effectiveCwd,envAssignments:u,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:o.functionDefinitions,hasPipelineInput:i,literalShellInput:s,analyzeNested:(d,p)=>{let g=p&&Object.hasOwn(p,"effectiveCwd")?p.effectiveCwd:o.effectiveCwd,y=al(d,t+1,{...n,derivedCommandWorkBudget:n.derivedCommandWorkBudget,effectiveCwd:g,envAssignments:p?.envAssignments??u,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:p?.functionDefinitions,worktreeMode:p?.worktreeMode??n.worktreeMode,trace:n.trace?Kf(n.trace,n.trace.currentSegmentIndex,!0):void 0});return y?{reason:y.reason,ruleId:y.ruleId,intent:y.intent}:null}});if(m)return{...m,segment:c};let f=Uf(e,a,o,u,s,n);if(f)return f;return tl(l,o.shellGitContextState),null}function Uf(e,t,n,r,o,i){let s=dw(e,t,n,r??new Map,i);if(s)return s;return Zf(e,n,"after-consumer",i.environment.paths),n.literalHeredocFiles.clear(),sw(e,t,n,i.environment.paths),pw(e,n,o,i.environment,i.trace),null}var ow=new Set([">>","<>"]);function Zf(e,t,n,r){for(let i of e.redirections){if(!(n==="before-consumer"?iw(i):ow.has(i.operator)))continue;Hf(i.target,t,r)}if(n!=="before-consumer"||!Ee(e.words[0],"tee"))return;let o=Yf(e.words.slice(1));if(!o)return;for(let i of o.operands)Hf(i,t,r)}function iw(e){if(e.operator===">"||e.operator===">|")return!0;return e.operator===">&"&&e.fd===void 0&&e.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(e.target.text)}function Hf(e,t,n){let r=e?.provenance==="literal"?br(e.text,t.effectiveCwd,n):void 0;if(!r)return;t.literalHeredocFiles.delete(r)}function sw(e,t,n,r){if(t)return;let o=e.redirections.find((i)=>i.operator==="<<"||i.operator==="<<-")?.heredoc;if(!o||!Fi(o))return;for(let i of aw(e)){let s=br(i.text,n.effectiveCwd,r);if(!s||!Od(s))continue;if(!n.literalHeredocFiles.has(s)&&n.literalHeredocFiles.size>=Id)throw new be;n.literalHeredocFiles.set(s,o.body)}}function aw(e){let t=cw(e.redirections)?.target,n=jf(t)?[t]:[];if(Ee(e.words[0],"cat"))return lw(e.words)?n:[];if(!Ee(e.words[0],"tee"))return[];let r=Yf(e.words.slice(1));if(!r||r.append||r.hasUnsupportedOptions||!r.operands.every(jf))return[];return[...r.operands,...n]}function lw(e){let t=!1;for(let n of e.slice(1)){if(t||n.provenance!=="literal")return!1;if(n.text==="--"){t=!0;continue}if(!/^-u+$/.test(n.text))return!1}return!0}function cw(e){let t=e.findLast((n)=>(n.fd??([">",">|",">>",">&"].includes(n.operator)?1:0))===1);return t?.operator===">"||t?.operator===">|"?t:void 0}function Yf(e){let t=[],n=!0,r=!1,o=!1;for(let i of e){if(i.provenance!=="literal")return;if(n&&Ee(i,"--")){n=!1;continue}if(n&&!i.quoted&&i.raw===i.text&&/^-[^-]/.test(i.text)){r||=i.text.slice(1).includes("a"),o||=[...i.text.slice(1)].some((s)=>s!=="a"&&s!=="i");continue}if(n&&!i.quoted&&i.raw===i.text&&i.text.startsWith("--")){r||=i.text==="--append",o||=i.text!=="--append"&&i.text!=="--ignore-interrupts";continue}t.push(i)}return{operands:t,append:r,hasUnsupportedOptions:o}}function jf(e){if(!e||e.provenance!=="literal"||e.text.length===0)return!1;if(e.quoted||e.raw!==e.text)return!0;return!e.raw.startsWith("~")&&!/[{}]/.test(e.raw)}function Ee(e,t){return e?.text===t&&e.raw===t&&e.provenance==="literal"&&!e.quoted}function Fi(e){return e.quotedDelimiter||!/[$`\\]/.test(e.body)}function uw(e){let t=e.redirections.filter((s)=>s.operator==="<<"||s.operator==="<<-");if(t.length===0)return;if(t.length!==1)return Qt;let n=t[0];if(!n?.heredoc)return Qt;if(!Fi(n.heredoc))return Kx;if(n.fd!==void 0&&n.fd!==0)return Qt;if(e.redirections.some((s)=>s!==n&&["<","<<","<<-","<<<","<&","<>"].includes(s.operator)))return Qt;let r=e.redirections.some((s)=>s!==n&&Vf(s.target));if(Ee(e.words[0],"cat"))return r?Qt:void 0;if(Ee(e.words[0],"tee"))return r||e.words.slice(1).some(Vf)?Qt:void 0;let o=e.words[0],i=e.words[1];if(Ee(o,"git")&&(Ee(i,"apply")||Ee(i,"commit")))return;if(Ee(o,"gh")&&(Ee(i,"pr")||Ee(i,"issue"))&&Ee(e.words[2],"create"))return;return Qt}function Vf(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}function dw(e,t,n,r,o){if(!t)return null;let i=e.redirections.filter((c)=>c.operator==="<<"||c.operator==="<<-"),s=i.flatMap((c)=>c.heredoc?[c.heredoc.body]:[]);if(fw(e,i,n,r,o))return null;let a=mw(e,i,o);if(a!==void 0)return a?{reason:a.reason,segment:e.displayText,ruleId:a.id,intent:a.intent}:null;let l=sl(s.length===i.length?s.join(`
|
|
59
|
+
`):e.source,o);return l?{...l,segment:e.displayText}:null}function mw(e,t,n){let r=t.length===1?t[0]:void 0;if(!r?.heredoc||!Fi(r.heredoc)||r.fd!==void 0&&r.fd!==0)return;let o=e.words[0];if(o?.provenance!=="literal"||!Ce(o.text))return;if(!e.words.slice(1).every((c)=>c.provenance==="literal"&&c.text.startsWith("-")))return;let s=r.heredoc.body,a=Q(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(n.trace?.recordSegment({type:"interpreter",interpreter:o.text,codeArg:s,paranoidBlocked:a}),a){let c=k(b("interpreter.one-liner-paranoid",yn),n.policy);if(c)return c}if(!Cn(s,n.scanWork))return null;let l=k(b("interpreter.dangerous-command",$t),n.policy);if(!l)return null;return n.trace?.recordSegment({type:"dangerous-text",token:s,matched:!0,reason:l.reason}),l}function fw(e,t,n,r,o){let i=t.length===1?t[0]:void 0;if(!i?.heredoc||!Fi(i.heredoc)||i.fd!==void 0&&i.fd!==0)return!1;let s=Ut(e.words,o.environment,n.effectiveCwd,r),a=s.words.map(I),l=z(a[0]??"");if((s.envSplitValues?.length??0)>0||!ee.has(l)&&!ee.has(M(l)))return!1;return Oe(a)}function pw(e,t,n,r,o){let i=If(e,t.effectiveCwd,r,n);if(i===null)o?.recordSegment({type:"cwd-change",segment:e.words.map(I).join(" "),effectiveCwdNowUnknown:!0});if(i!==void 0)t.effectiveCwd=i}function Mr(e){return{effectiveCwd:e.effectiveCwd,shellGitContextState:Ff(e.shellGitContextState),literalHeredocFiles:new Map(e.literalHeredocFiles),functionDefinitions:new Map(e.functionDefinitions)}}function Mi(e){let t=[];for(let n of e){if(!t.some((r)=>gw(r,n)))t.push(n);if(t.length>Zx)throw new be}return t}function gw(e,t){return e.effectiveCwd===t.effectiveCwd&&Nr(e.literalHeredocFiles,t.literalHeredocFiles)&&Nr(e.functionDefinitions,t.functionDefinitions)&&Nr(e.shellGitContextState.effectiveEnvAssignments,t.shellGitContextState.effectiveEnvAssignments)&&Nr(e.shellGitContextState.shellAssignments,t.shellGitContextState.shellAssignments)}function Nr(e,t){if(e===t)return!0;if(!e||!t||e.size!==t.size)return!1;return[...e].every(([n,r])=>t.get(n)===r&&t.has(n))}function hw(e,t){let n=vo(e);return n===void 0?void 0:t.get(n)}function yw(e,t){if(!t)return null;return{reason:t.reason,segment:e,ruleId:t.id,intent:t.intent}}function Cw(e,t=e.effectiveCwd){let n=t===null;return{environment:e.environment,cwd:n?void 0:t??e.cwd,originalCwd:n?void 0:e.cwd,strict:e.strict,paranoid:e.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,protectedGitMetadata:e.protectedGitMetadata,policy:e.policy}}function sl(e,t){let n=k(ht(e,t.scanWork),t.policy),r=t.trace?.currentSegmentIndex??t.trace?.allocateSegment(),o={type:"dangerous-text",token:e,matched:!!n,reason:n?.reason};if(t.trace?.recordSegment(o,r),!n&&/^(?:cd|pushd)\s/.test(e))t.trace?.recordSegment({type:"cwd-change",segment:e,effectiveCwdNowUnknown:!0},r);return n?{reason:n.reason,segment:e,ruleId:n.id,intent:n.intent}:null}function qf(e,t){let n={type:"strict-unparseable",rawCommand:e,reason:Et};if(t.trace?.currentSegmentIndex===void 0)t.trace?.recordGlobal(n);else t.trace.recordSegment(n)}function Xf(e){let t=e.effectiveCapabilities,n=e.strict??t.fail_closed.enabled,r=e.paranoidRm??t.paranoid_rm.enabled,o=e.paranoidInterpreters??t.paranoid_interpreters.enabled,i={fail_closed:ll(t.fail_closed,e.strict,"strict"),paranoid_rm:ll(t.paranoid_rm,e.paranoidRm,"paranoidRm"),paranoid_interpreters:ll(t.paranoid_interpreters,e.paranoidInterpreters,"paranoidInterpreters")};return{policy:cc(e.policySnapshot.policy,i),effectiveCapabilities:i,effectiveLevel:Vs({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}function ll(e,t,n){if(t===void 0||t===e.enabled)return e;return{enabled:t,source:"capability_override",sources:[...e.sources,`analysis options.${n}`]}}function SN(e,t){return cl(e,t)}function cl(e,t,n,r){let o=al(e,0,{...t,...Xf(t),factStore:r},n);if(!o)return null;return{kind:"deny",reason:o.reason,intent:o.intent??"manual_only",...o.ruleId?{ruleId:o.ruleId}:{},evidence:[{kind:"command",command:e,segment:o.segment}]}}import{basename as bw,dirname as ul}from"node:path";var tp="This path contains the protected policy config and you must not modify or delete it.",Sw=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function np(e){let t=Mt(mt()),n=_w(e.invocation.context.executionCwd,t);if(e.invocation.route.kind==="patch")return Jf(e.paths,!1,e.invocation.context.executionCwd,n,t);let r=ge(e,"input-candidate");if(e.invocation.route.kind==="command")return r?Qf(r.shell,e.invocation.context.executionCwd,n,t):null;if(e.invocation.route.kind==="unknown"&&r){let o=Qf(r.shell,e.invocation.context.executionCwd,n,t);if(o)return o}return Jf(e.paths,e.invocation.route.kind==="grep"||e.invocation.route.kind==="glob"||so(e.invocation.toolName),e.invocation.context.executionCwd,n,t)}function Jf(e,t,n,r,o){if(t)return null;let i=e.find((s)=>Lr(s,n,r,o));return i?{target:i}:null}function Qf(e,t,n,r){let o=hi(e,t,r,{findSegmentTarget:(i,s)=>vw(i,s,n,r)?.target??null,isRedirectionTarget:(i,s)=>Lr(i,s.cwd,n,r),findMalformedTarget:(i)=>ww(i,t,n,r)?.target??null,normalizeCwd:ce});return o?{target:o}:null}function vw(e,t,n,r){if(Rr(e))return null;let o=r.environment,i=_t([...e],o),s=M(i[0]??"").toLowerCase(),a=i.slice(1);if(s==="rm"&&Rw(a)){let l=Ew(a).find((c)=>ep(ve(c,t.variables),t.cwd,n,r));if(l)return{target:l}}if(s==="find"){if(Ri(i,1)||xa(i,o)){let c=(vi(G(i))??G(["."])).find((u)=>{let m=ve(u.text,t.variables);return Lr(m,t.cwd,n,r)||ep(m,t.cwd,n,r)})?.text;if(c)return{target:c}}}if(s==="mv"){let l=yi(a).sources.find((c)=>Pw(ve(c,t.variables),t.cwd,n,r));if(l)return{target:l}}if(xw(e,o))return null;for(let l of[...e,...i])for(let c of rp(l))if(Lr(ve(c,t.variables),t.cwd,n,r))return{target:c};return null}function Rw(e){return e.some((t)=>t==="--recursive"||t.startsWith("-")&&!t.startsWith("--")&&/[rR]/.test(t.slice(1)))}function Ew(e){let t=e.indexOf("--");if(t!==-1)return[...e.slice(0,t).filter((n)=>!n.startsWith("-")),...e.slice(t+1)];return e.filter((n)=>!n.startsWith("-"))}function xw(e,t){let n=_t([...e],t);if(n.length===0)return!1;let r=M(n[0]??"").toLowerCase();if(!Sw.has(r))return!1;if(r!=="sed")return!0;return!n.slice(1).some((o)=>o.startsWith("-i")||o==="--in-place"||o.startsWith("--in-place="))}function ww(e,t,n,r){for(let o of e.split(/\s+/))for(let i of rp(o))if(Lr(i,t,n,r))return{target:i};return null}function rp(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.indexOf("=");return n===-1||n===t.length-1?[t]:[t,t.slice(n+1)]}function _w(e,t){let n=ce(xn(),e,t),r=ul(n),o=new Set;for(let i=r;;i=ul(i))if(o.add(Fn(i)),ul(i)===i)break;return{file:Fn(n),directoryAndAncestors:o}}function Lr(e,t,n,r){let o=Kd(e,t,r,(i)=>Fn(i)===bw(n.file));return o!==null&&Fn(o)===n.file}function ep(e,t,n,r){return n.directoryAndAncestors.has(Fn(ce(e,t,r)))}function Pw(e,t,n,r){let o=Fn(ce(e,t,r));return o===n.file||n.directoryAndAncestors.has(o)}function Fn(e){return process.platform==="win32"?e.toLowerCase():e}import{homedir as ml}from"node:os";import{isAbsolute as Gi,posix as Aw,resolve as $i,win32 as kw}from"node:path";import{fileURLToPath as Tw}from"node:url";var pp="Access to a sensitive path is not allowed.",gp=new Set(["echo","printf"]),Iw=new Set(["find"]),Ow=new Set(["-exec","-execdir"]),Dw=new Set([";","+"]),Mw=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),Nw=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Lw=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),Ww=new Set(["node","bun"]),Fw=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),Gw=new Set(["append","awk","base64","cat","chmod","chown","connect","copy","cp","database","dd","eval","exec","fetch","file","function","grep","head","include","load","move","mv","open","popen","read","remove","rename","require","rg","rm","sed","shell","source","spawn","strings","system","tail","tar","truncate","unlink","write","xxd","zip"]),hp=new Set(["-c","-e","-r","-E","--eval","--exec"]),zw=new Set(["src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js"]),op=new Set(["cc-safety-net","ccsn"]),$w=new Set(["bunx","npx","pnpx"]),Bw=new Set(["bun","node"]),Uw=new Map([["c",new Set(["bash","sh","zsh","dash","ksh","python"])],["e",new Set(["node","deno","bun","ruby","perl","rscript","osascript"])],["E",new Set(["perl"])],["r",new Set(["php"])]]),Hw=new Set(["grep","rg"]),ip="f",sp="file",jw="files",Vw=new Set(["e","f"]),qw=new Set(["regexp","file"]),Kw=new Set(["e","f","A","B","C","m"]),Zw=new Set(["regexp","file","after-context","before-context","context","max-count"]),Yw=new Set(["|","|&"]),dl="__CC_SAFETY_NET_PIPE_INPUT__",yp=new Set(["bash","sh","zsh","dash","ksh"]),Xw=new Map([["bash",new Set(["-O"])],["sh",new Set(["-O"])],["zsh",new Set(["-o"])],["dash",new Set(["-o"])],["ksh",new Set(["-o"])],["python",new Set(["-W","-X"])],["node",new Set(["-r","--require","--loader","--import","--input-type"])]]);function ap(e,t,n,r,o){let i=Vn();for(let s of e){if(F_(s,t,n?.denyPaths??[],r,i))return{target:s,ruleId:"secret.deny-path"};if(o&&!o.has(s))continue;let a=L_(s,t,n,i);if(a){if(!a.startsWith("secret.cli.")&&G_(s,t,n?.allowPaths??[],r,i))continue;return{target:s,ruleId:a}}}return null}function Cp(e,t,n={}){let r=lp(e),o=ap(r,e.invocation.context.executionCwd,t,e.invocation.context.configCwd),i=o?.ruleId!=="secret.deny-path"&&n.strict===!1?lp(e,{refineJavaScriptInlineData:!0}):r,s=i.length===r.length?o:ap(r,e.invocation.context.executionCwd,t,e.invocation.context.configCwd,new Set(i));if(s?.ruleId!=="secret.deny-path"&&n.strict===!1&&Jw(e))return null;return s}function Jw(e){if(e.invocation.route.kind!=="command")return!1;let t=ge(e,"input-candidate")??ge(e,"declared-command");if(!t)return!1;if(t.program.nodes.some((s)=>s.kind==="command"&&s.nested.length>0))return!1;let n=[];for(let s of t.shell.entries){if(s.kind==="operator"&&s.boundary)return!1;if(s.kind==="redirection")return!1;if(s.kind!=="operator")n.push(Je(s.text))}let r=Gn(n);if(r.length===0)return!1;let o=tn(r[0]??"").toLowerCase(),i=r.slice(1);if(o==="ls"||o==="stat")return!0;if(o==="test")return i.length===2&&(i[0]==="-e"||i[0]==="-f");if(o!=="find")return!1;return!i.some((s)=>Mw.has(s))}function lp(e,t={}){if(e.invocation.route.kind==="command"){let r=ge(e,"input-candidate");return r?Gr(r.shell,e.store,t):[]}if(e.invocation.route.kind!=="unknown")return[...e.paths];let n=ge(e,"input-candidate");return[...n?Gr(n.shell,e.store,t):[],...e.paths]}function Gr(e,t,n){if(e.status==="structural-limit")throw new Xe;if(e.status==="unclosed-quote")return[];if(e.status==="invalid")throw Error("Unable to parse command for secret protection");let r=[...e.assignmentFallbacks,...C_(Je(e.source),t,n)],o=[],i=null;for(let s of e.entries){if(s.kind==="operator"){if(!s.boundary)continue;if(o.length>0){if(r.push(...zi(o,t,n)),i!==null)r.push(...up(i,o,t,n));i=Yw.has(s.operator)?o:null,o=[]}else i=null;continue}if(s.kind==="redirection"){let a=s.target?Je(s.target):void 0;if(a&&s.targetOrder==="legacy-segment")o.push(a);else if(a)r.push(a);continue}o.push(Je(s.text))}if(o.length>0){if(r.push(...zi(o,t,n)),i!==null)r.push(...up(i,o,t,n))}return r}function zi(e,t,n){let r=l_(e),o=Gn(e);if(o.length===0)return r;let i=o[0]??"",s=tn(i).toLowerCase(),a=o.slice(1),l=e_(i,s,a);if(l)return[...r,...l];if(gp.has(s))return r;if(Hw.has(s))return[...r,...__(a)];if(Iw.has(s))return[...r,...c_(a,t,n)];if(ye.has(s))return[...r,...a.flatMap((c)=>dp("awk",c)),...a.flatMap((c)=>d_(c,t,n)),...a.flatMap(m_)];if(vp(s)){if(yp.has(s)){let c=ku(s,a);if(c!==null&&t.getShellSyntax(c).status==="structural-limit")throw new Xe}return[...r,...u_(s,a,n)]}return[...r,...a.flatMap((c)=>dp(s,c))]}function Qw(e,t){if(op.has(e))return t[0]==="explain"?0:null;if($w.has(e)){let n=t[0]==="-y"||t[0]==="--yes"?1:0;return op.has(t[n]??"")&&t[n+1]==="explain"?n+1:null}if(Bw.has(e)){if(cp(t[0])&&t[1]==="explain")return 1;if(e==="bun"&&t[0]==="run"&&cp(t[1])&&t[2]==="explain")return 2}return null}function e_(e,t,n){let r=Qw(t,n);if(r===null)return null;let o=[e,...n.slice(0,r)],i=n.slice(r+1);for(let s=0;s<i.length;s++){let a=i[s];if(a==="--json"||a==="--help"||a==="-h")continue;if(a==="--cwd"){let l=i[s+1];if(l&&!l.startsWith("--"))o.push(l);s++;continue}return o}return o}function cp(e){let t=e?.replaceAll("\\","/");return[...zw].some((n)=>t===n||t?.endsWith(`/${n}`))}function up(e,t,n,r){if(i_(t,n,r))return t_(e);let o=s_(t);if(o===null)return[];return n_(e).flatMap((i)=>yp.has(o)?Gr(n.getShellSyntax(i),n,r):Ep(i))}function t_(e){let t=Gn(e);if(t.length===0)return[];let n=tn(t[0]??"").toLowerCase();if(!gp.has(n))return[];return t.slice(1)}function n_(e){let t=Gn(e);if(t.length===0)return[];let n=tn(t[0]??"").toLowerCase(),r=t.slice(1);if(n==="echo"){let o=r.findIndex((i)=>!/^-[neE]+$/.test(i));return[(o===-1?[]:r.slice(o)).join(" ")]}if(n==="printf")return r_(r);return[]}function r_(e){let t=e[0];if(t===void 0)return[];let n=(t.match(/%%|%[bqs]/g)??[]).filter((o)=>o!=="%%").length;if(n===0||e.length===1)return[bp(t)];let r=e.slice(1);return Array.from({length:Math.ceil(r.length/n)},(o,i)=>o_(t,r.slice(i*n,(i+1)*n)))}function o_(e,t){let n=0;return bp(e.replace(/%%|%[bqs]/g,(r)=>{if(r==="%%")return"%";let o=t[n]??"";return n++,o}))}function bp(e){return e.replace(/\\n/g,`
|
|
60
|
+
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function i_(e,t,n){let r=Gn(e);if(r.length===0||tn(r[0]??"").toLowerCase()!=="xargs")return!1;let o=Kt(r),i=r.slice(o.childStart);if(i.length===0)return!1;if(o.replacementToken==="")return!1;let s=o.replacementToken,a=s===null?[...i,dl]:i.map((l)=>l.split(s).join(dl));return zi(a,t,n).some((l)=>l.includes(dl))}function s_(e){let t=Gn(e);if(t.length===0)return null;let n=tn(t[0]??"").toLowerCase();if(!vp(n))return null;return a_(n,t.slice(1))?n:null}function a_(e,t){let n=Sp(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(hp.has(o)||Rp(e,o)||/^--(?:eval|exec)=/.test(o))return!1;if(o==="-")return!0;if(o.startsWith("-")){if(n==="python"&&o==="-m")return!1;if(Xw.get(n)?.has(o))r++;continue}return!1}return!0}function Sp(e){return/^python\d/.test(e)?"python":e}function l_(e){let t=[];for(let n of e){if(_p(n))continue;let r=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(n);if(r===null)break;if(r[1]!==void 0&&r[1]!=="")t.push(r[1])}return t}function dp(e,t){if(t==="--")return[];let n=[],r=t.indexOf("=");if(r>0&&r<t.length-1)n.push(t.slice(r+1));if(t.startsWith("-"))return n;if(e==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(t))return n;if(e==="zip"&&/\.zip$/i.test(t))return n;return n.push(t),n}function c_(e,t,n){let r=e.findIndex((i)=>i.startsWith("-")||i==="("||i==="!"||i===";"),o=[...e.slice(0,r===-1?e.length:r)];for(let i=0;i<e.length;i++){if(!Ow.has(e[i]??""))continue;let s=e.slice(i+1),a=s.findIndex((u)=>Dw.has(u)),l=a===-1?s:s.slice(0,a),c=zi(l,t,n);if(o.push(...c.filter((u)=>u!=="{}")),!c.includes("{}"))continue;o.push(...e.slice(0,i).flatMap((u,m,f)=>{if(!Nw.has(u))return[];let d=f[m+1];return d===void 0?[]:[d,d.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return o}function vp(e){return Lw.has(e)||/^python\d/.test(e)}function u_(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o];if(i===void 0)break;if(hp.has(i)||Rp(e,i)){let a=t[o+1];if(a!==void 0)r.push(...mp(e,a,n)),o++;continue}let s=/^--(?:eval|exec)=(.*)$/.exec(i);if(s!==null&&s[1]!==void 0){r.push(...mp(e,s[1],n));continue}if(!i.startsWith("-"))r.push(i)}return r}function Rp(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<=2)return!1;return Uw.get(t[t.length-1]??"")?.has(Sp(e))??!1}function d_(e,t,n){if(!e.includes("system"))return[];return Ws(e)?.commands.flatMap((r)=>Gr(t.getShellSyntax(r),t,n))??[]}function m_(e){return Array.from(e.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((t)=>t[1]).filter((t)=>t!==void 0&&t!=="")}function Ep(e){let t=Array.from(e.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((r)=>r[2]).filter((r)=>r!==void 0&&r!==""),n=(e.match(/[\w./~@+-]*[./~][\w./~@+-]*/g)??[]).filter((r)=>r!=="process.versions.sqlite"||t.some((o)=>o.includes(r)));return[...t,...t.flatMap(xp),...n]}function mp(e,t,n){let r=Ep(t);if(!n.refineJavaScriptInlineData||!Ww.has(e)||r.length===0)return r;let o=f_(t);return o!==null&&!g_(o)?[]:r}function f_(e){let t=e.split("");for(let n=0;n<e.length;n++){let r=e[n];if(r!=="'"&&r!=='"'&&r!=="`")continue;if(r==="`"&&p_(e,n))return null;t[n]=" ";let o=!1;for(let i=n+1;i<e.length;i++){let s=e[i];if(t[i]=" ",s==="\\"){if(i++,i<e.length)t[i]=" ";continue}if(r==="`"&&s==="$"&&e[i+1]==="{")return null;if(r!=="`"&&(s===`
|
|
61
|
+
`||s==="\r"))return null;if(s!==r)continue;n=i,o=!0;break}if(!o)return null}return t.join("")}function p_(e,t){for(let n=t-1;n>=0;n--){let r=e[n];if(!r||/\s/.test(r))continue;return/[\w$\])]/.test(r)}return!1}function g_(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(Fw.has(n.toLowerCase()))return!0;let o=n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((i)=>i.toLowerCase());if(!o.some((i)=>Gw.has(i)))continue;if(o.length>1)return!0;if(h_(e,r)===".")return!0;if(y_(e,r+n.length)==="(")return!0}return!1}function h_(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function y_(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function C_(e,t,n){return E_(e).flatMap((r)=>{let o=t.getShellSyntax(r);if(o.status==="invalid")return[];return[...Gr(o,t,n),...b_(o)?S_(o):[]]})}function b_(e){let t=e.entries;for(let n=0;n<t.length;n++){let r=t[n];if(r?.kind!=="word"||tn(Je(r.text)).toLowerCase()!=="base64")continue;for(let o=n+1;o<t.length;o++){let i=t[o];if(i?.kind==="operator")break;if(i?.kind!=="word")continue;let s=Je(i.text);if(s==="--decode"||!s.startsWith("--")&&s.startsWith("-")&&/[dD]/.test(s))return!0}}return!1}function S_(e){return e.entries.flatMap((t)=>t.kind==="word"?[Je(t.text)]:t.kind==="redirection"&&t.target?[Je(t.target)]:[]).flatMap(xp)}function xp(e){let t=R_(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||v_(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function v_(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function R_(e){if(e.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(e))return null;if(/=/.test(e.replace(/=+$/g,"")))return null;let t=e.replace(/=+$/g,"");if(t.length%4===1)return null;return`${t.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-t.length%4)%4)}`}function E_(e){let t=[],n={inSingle:!1,inDouble:!1,escaped:!1};for(let r=0;r<e.length;r++){let o=e[r];if(!o)break;if(Qn(o,n))continue;if(wp(e,r,n)){let i=x_(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=w_(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function x_(e,t){let n={inSingle:!1,inDouble:!1,escaped:!1},r=1;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i)break;if(Qn(i,n))continue;if(wp(e,o,n)){r++,o++;continue}if(!n.inSingle&&!n.inDouble&&i===")"){if(r--,r===0)return{body:e.slice(t+1,o),endIndex:o}}}return null}function w_(e,t){let n=!1;for(let r=t+1;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="`")return{body:e.slice(t+1,r),endIndex:r}}return null}function wp(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function __(e){let t=[],n=[],r=!1,o=!1,i=!1;for(let l=0;l<e.length;l++){let c=e[l];if(c===void 0)break;if(!i&&c==="--"){i=!0;continue}if(i){n.push(c);continue}let u=/^--([^=]+)(?:=(.*))?$/.exec(c);if(u!==null){let m=u[1]??"",f=u[2];if(m===jw)o=!0;if(qw.has(m))r=!0;if(f!==void 0){if(m===sp)t.push(f);continue}if(Zw.has(m)){let d=e[l+1];if(m===sp&&d!==void 0)t.push(d);l++}continue}if(c.startsWith("-")&&c.length>1){let m=c.slice(1),f="",d="";for(let p=0;p<m.length;p++){let g=m[p]??"";if(Vw.has(g))r=!0;if(Kw.has(g)){f=g,d=m.slice(p+1);break}}if(f!=="")if(d.length>0){if(f===ip)t.push(d)}else{let p=e[l+1];if(f===ip&&p!==void 0)t.push(p);l++}continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function Gn(e){let t=e.findIndex((n)=>!_p(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:[...e.slice(t)]}function _p(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var P_=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),A_=".env.",k_=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),T_=[".env.example.",".env.sample."];function I_(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function O_(e){return e.length>0&&!/\s/.test(e)}function D_(e,t,n){try{let r=zr(e,t,n);return r!==""&&Pe.entryKind(r)!=="missing"}catch(r){if(r instanceof le)throw r;return!1}}var M_=new Set(["node_modules","__pycache__"]),N_=[["vendor","bundle"],["vendor","cache"]];function L_(e,t,n,r){if(I_(e))return null;let o=St(e,t,r);if(!o)return null;let i=K(o.split("/").pop()??""),s=K(o),a=()=>O_(i)||D_(e,t,r);if(k_.has(i)||T_.some((m)=>i.startsWith(m)))return null;let l=K(B_(e,t,r));for(let m of Zs){let f=`~/${m.suffixParts.join("/")}`;if((fp(s,f)||fp(l,f))&&bt(m.id,n))return m.id}let c=W_(o,t,n,r);if(c)return c;if(P_.has(i))return null;for(let m of Ks)if(i===m.basename&&bt(m.id,n))return m.id;if(i.startsWith(A_)&&bt(Vo.id,n)&&a())return Vo.id;for(let m of Ys)if(i.length>m.prefix.length&&i.startsWith(m.prefix)){let f=i.slice(m.prefix.length)[0];if((f==="-"||f==="_")&&bt(m.id,n)&&a())return m.id}for(let m of Xs)if(i.length>m.prefix.length&&i.startsWith(m.prefix)){if(i.slice(m.prefix.length)===m.suffix&&bt(m.id,n))return m.id}if(z_(s))return null;if(!i.includes(".")&&dr.pattern.test(i)&&bt(dr.id,n))return dr.id;let u=$_(i,n);if(u)return u;return null}function W_(e,t,n,r){return qo.find((o)=>{if(!bt(o.id,n))return!1;switch(o.id){case"secret.cli.claude-code":return q(e,Y(process.env.CLAUDE_CONFIG_DIR,"~/.claude",t,r),[".credentials.json"]);case"secret.cli.claude-code.config":{let i=K(e).split("/");return q(e,Y(process.env.CLAUDE_CONFIG_DIR,"~/.claude",t,r),["settings.json","settings.local.json"])||Fr(e,"~/.claude.json",t,r)||i.at(-1)==="settings.local.json"&&i.at(-2)===".claude"||i.at(-1)===".mcp.json"}case"secret.cli.antigravity":return q(e,St("~/.gemini/config",t,r),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let i=Y(process.env.CODEX_HOME,"~/.codex",t,r);return q(e,i,["auth.json",".credentials.json"])||Wr(e,i,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let i=Y(process.env.CODEX_HOME,"~/.codex",t,r),s=K(e).split("/").at(-1)??"";return q(e,i,["config.toml"])||s.endsWith(".config.toml")&&q(e,i,[s])}case"secret.cli.gemini":return q(e,se(Y(process.env.GEMINI_CLI_HOME,"~",t,r),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let i=K(e).split("/"),s=process.env.ProgramData?[se(Y(process.env.ProgramData,"",t,r),"gemini-cli")]:[];return q(e,se(Y(process.env.GEMINI_CLI_HOME,"~",t,r),".gemini"),["settings.json","google_accounts.json"])||i.at(-1)==="settings.json"&&i.at(-2)===".gemini"||(process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH?.trim()?Fr(e,process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH,t,r):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...s].some((a)=>q(e,St(a,t,r),["settings.json"]))}case"secret.cli.copilot-cli":{let i=Y(process.env.COPILOT_HOME,"~/.copilot",t,r);return q(e,i,["config.json"])||Wr(e,i,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return q(e,Y(process.env.COPILOT_HOME,"~/.copilot",t,r),["mcp-config.json"]);case"secret.cli.kimi-code":{let i=Y(process.env.KIMI_CODE_HOME,"~/.kimi-code",t,r),s=Y(process.env.KIMI_SHARE_DIR,"~/.kimi",t,r);return q(e,i,["server.token"])||Wr(e,i,["credentials"])||Wr(e,s,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let i=["config.toml","mcp.json"],s=K(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".kimi-code"||q(e,Y(process.env.KIMI_CODE_HOME,"~/.kimi-code",t,r),i)||q(e,Y(process.env.KIMI_SHARE_DIR,"~/.kimi",t,r),[...i,"config.json","config.json.bak"])}case"secret.cli.opencode":{let i=se(Y(process.env.XDG_DATA_HOME,"~/.local/share",t,r),"opencode"),s=K(e).split("/").at(-1)??"",a=process.env.OPENCODE_DB?.trim(),l=a&&a!==":memory:"?[a,`${a}-wal`,`${a}-shm`]:[];return q(e,i,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(s)&&q(e,i,[s])||l.some((c)=>Fr(e,c,t,r))}case"secret.cli.opencode.config":{let i=process.env.OPENCODE_CONFIG_DIR?Y(process.env.OPENCODE_CONFIG_DIR,"~/.config/opencode",t,r):se(Y(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"opencode"),s=process.env.ProgramData?[se(Y(process.env.ProgramData,"",t,r),"opencode")]:[],a=["opencode.json","opencode.jsonc"];return a.includes(K(e).split("/").at(-1)??"")||q(e,i,a)||(process.env.OPENCODE_CONFIG?.trim()?Fr(e,process.env.OPENCODE_CONFIG,t,r):!1)||["/Library/Application Support/opencode","/etc/opencode",...s].some((l)=>q(e,St(l,t,r),a))}case"secret.cli.pi":return q(e,Y(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",t,r),["auth.json"]);case"secret.cli.pi.config":return q(e,Y(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",t,r),["models.json"]);case"secret.cli.amp":{let i=St("~",t,r);return[se(Y(process.env.XDG_DATA_HOME,"~/.local/share",t,r),"amp"),se(i,".local","share","amp")].some((a)=>q(e,a,["secrets.json"]))||Wr(e,se(i,".amp"),["oauth"])}case"secret.cli.amp.config":{let i=["settings.json","settings.jsonc"],s=[se(Y(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"amp"),se(St("~",t,r),".config","amp")],a=K(e).split("/");return s.some((l)=>q(e,l,i))||a.at(-2)===".amp"&&i.includes(a.at(-1)??"")||(process.env.AMP_SETTINGS_FILE?.trim()?Fr(e,process.env.AMP_SETTINGS_FILE,t,r):!1)}case"secret.cli.cursor":{let i=se(Y(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"cursor"),s=se(Y(process.env.CURSOR_DATA_DIR,"~/.cursor",t,r),"projects");return q(e,St("~/.cursor",t,r),["auth.json"])||q(e,i,["auth.json"])||K(e).split("/").at(-1)==="mcp-auth.json"&&en(K(e),K(s))}case"secret.cli.cursor.config":{let i=K(e).split("/");return i.at(-1)==="mcp.json"&&i.at(-2)===".cursor"}default:return!1}})?.id??null}function Y(e,t,n,r){return St(e?.trim()?e:t,n,r)}function q(e,t,n){return n.some((r)=>Pp(e,se(t,r)))}function Wr(e,t,n){return n.some((r)=>en(K(e),K(se(t,r))))}function Fr(e,t,n,r){return Pp(e,St(t,n,r))}function Pp(e,t){return K(e)===K(t)}function se(e,...t){return qe([e,...t].filter(Boolean).join("/"))}function F_(e,t,n,r,o){if(n.length===0)return!1;let i=K(zr(e,t,o));return n.some((s)=>en(i,K(zr(s,r,o))))}function G_(e,t,n,r,o){if(n.length===0)return!1;let i=K(zr(e,t,o));if(!i)return!1;let s=process.env.HOME??ml(),a=s?qe(U(s,Pe,o)):"",l=K(a),c=process.env.CC_SAFETY_NET_HOME,u=K(c?qe(U($i(c),Pe,o)):a&&qe(U(`${a}/.cc-safety-net`,Pe,o)));if(u&&en(i,u))return!1;return n.some((m)=>{let f=K(zr(m,r,o));if(!f)return!1;if(l&&(l===f||l.startsWith(f.endsWith("/")?f:`${f}/`)))return!1;return en(i,f)})}function z_(e){let t=e.split("/");return t.some((n)=>M_.has(n))||N_.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function $_(e,t){let n=e.lastIndexOf("."),r=n>0&&n<e.length-1?e.slice(n+1):"";if(r==="")return null;for(let o of Js)if(r===o.extension&&bt(o.id,t))return o.id;for(let o of Qs)if(o.pattern.test(r)&&bt(o.id,t))return o.id;return null}function K(e){return e.toLowerCase()}function bt(e,t){return!t?.disabledRules?.includes(e)}function St(e,t,n){let{home:r,normalized:o}=fl(e,n);if(!o)return"";if(!r)return o;let i=pl(o,r),s=Gi(i)?i:qe($i(t,i)),a=qe(U(s,Pe,n));if(!en(a,r)){if(Gi(i))return a;return a===s?o:a}let l=a.slice(r.length);return l?`~${l}`:"~"}function fp(e,t){return e===t||e.startsWith(`${t}/`)}function B_(e,t,n){let{home:r,normalized:o}=fl(e,n);if(!o||!r)return"";let i=pl(o,r),s=Aw.normalize(Gi(i)?i:qe($i(t,i))),a=qe(process.env.HOME??ml()),l=(m)=>process.platform==="win32"?m.toLowerCase():m,c=[r,a].find((m)=>m!==""&&en(l(s),l(m)));if(c===void 0)return"";let u=s.slice(c.length);return u?`~${u}`:"~"}function zr(e,t,n){let{home:r,normalized:o}=fl(e,n);if(!o)return"";let i=r?pl(o,r):o;return qe(U(Gi(i)?i:$i(t,i),Pe,n))}function fl(e,t){let n=process.env.HOME??ml(),r=n?qe(U(n,Pe,t)):"",o=qe(U_(Je(e)));return{home:r,normalized:o}}function U_(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return Tw(e)}catch{return e}}function pl(e,t){if(e==="~")return t;if(e.startsWith("~/"))return se(t,e.slice(2));return e}function H_(e){if(process.platform==="win32")return!0;return kw.parse(e).root.length>1}function qe(e){let t=e.trim(),n=(H_(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function en(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function tn(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class zn extends Error{stage;evaluation;name="GuardEvaluationError";constructor(e,t,n){super(`CC Safety Net ${e} dependency failed`,{cause:n});this.stage=e;this.evaluation=t}}var j_={findPolicyMutation:np,findGitMetadataMutation:Jd,resolveGitMetadata:pa,loadPolicySnapshot:Ed,findSensitiveTarget:Cp,analyzeCommand:cl,getModes:jo};function Ap(e,t={}){let n={...j_,...t.dependencies},r=K_(e),o=$r(e)?e.command:r,i=nn("policy-protection",o,()=>xo(e,t.factParserDependencies)),s=ge(i,"declared-command");if($r(e)&&e.command?.trim()&&s?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:ut,intent:"stop_and_explain",evidence:[{kind:"command",command:e.command,segment:e.command}]}};if(ge(i,"input-candidate")?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:rc,intent:"stop_and_explain",evidence:[]}};let a=nn("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd])),l=nn("policy-protection",o,()=>n.findPolicyMutation(i));if(l){let y=o??l.target;return{stage:"policy-protection",decision:{kind:"deny",reason:tp,intent:"hard_stop",evidence:[{kind:"command",command:y,segment:l.target}]}}}let c=nn("policy-protection",o,()=>n.findGitMetadataMutation(i,a));if(c){let y=o??c.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Ie,intent:"hard_stop",evidence:[{kind:"command",command:y,segment:c.target}]}}}let u=nn("config-load",o,()=>n.loadPolicySnapshot({...t.policyOptions,cwd:e.context.configCwd})),m=u.policy,f=n.getModes(m),d={level:f.effectiveLevel,...V_(u)},p=m.secretProtection.enabled===!1?null:nn("secret-protection",o,()=>n.findSensitiveTarget(i,m.secretProtection,{strict:$r(e)?f.strict:void 0}));if(p){let y=o??p.target;return{stage:"secret-protection",...d,decision:{kind:"deny",reason:pp,intent:"hard_stop",ruleId:p.ruleId,evidence:[{kind:"command",command:y,segment:p.target}]}}}if(!$r(e))return{stage:"non-command",...d,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...gl("command-validation",o),...d};let g=nn("command-analysis",o,()=>n.analyzeCommand(e.command,{cwd:e.context.executionCwd,shell:e.route.shell,policySnapshot:u,environment:mt(),protectedGitMetadata:a,effectiveCapabilities:f.capabilities,strict:f.strict,paranoidRm:f.paranoidRm,paranoidInterpreters:f.paranoidInterpreters,worktreeMode:f.worktreeMode},q_(i),i.store));if(g)return{stage:"command-analysis",...d,decision:g};return{stage:"command-analysis",...d,decision:{kind:"allow"}}}function V_(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function q_(e){return ge(e,"declared-command")?.program}function K_(e){try{return Zn(e.input)}catch(t){let n=$r(e)?e.command:void 0;throw new zn("policy-protection",gl("policy-protection",t instanceof dt?void 0:n,t),t)}}function nn(e,t,n){try{return n()}catch(r){throw new zn(e,gl(e,r instanceof dt?void 0:t,r),r)}}function gl(e,t,n){let r=n instanceof le||n instanceof Xe;return{stage:e,decision:{kind:"deny",reason:r?oc:Jr,intent:"stop_and_explain",evidence:t?[{kind:"command",command:t,segment:t}]:[]}}}function $r(e){return e.route.kind==="command"}import{realpathSync as Z_,statSync as Y_}from"node:fs";import{isAbsolute as kp,relative as X_,resolve as J_,sep as Q_}from"node:path";function eP(e,t){if(zt(e))return;let n=t.flatMap((o)=>hl(o));if(!n[0])return;let r=hl(kp(e)?e:J_(n[0],e))[0];if(!r)return;return n.some((o)=>Tp(r,o))?r:void 0}function tP(e){return e.flatMap((t)=>hl(t))[0]}function hl(e){try{let t=Z_(e);return Y_(t).isDirectory()?[t]:[]}catch{return[]}}function Tp(e,t){let n=X_(t,e);return n===""||n!==".."&&!n.startsWith(`..${Q_}`)&&!kp(n)}function gL(e,t){try{let n=Ap(e,t.guard);return Ip(e,n,t),n}catch(n){if(!(n instanceof zn))throw n;throw Ip(e,n.evaluation,t,!(n.cause instanceof dt),{stage:n.stage,errorCode:nP(n.cause)}),n}}function Ip(e,t,n,r=!0,o){nc(tc(e,t,n.guard?.auditAllowed??!1,r,o),n.audit.getSessionId,{agent:n.audit.agent,shape:n.audit.shape,homeDir:n.audit.homeDir})}function nP(e){if(e instanceof le)return"path-canonicalization-limit";if(e instanceof dt)return"tool-input-limit";if(e instanceof Xe)return"structural-shell-syntax-limit";return"unexpected-error"}
|
|
62
|
+
export{Xl as b,Eg as c,TP as d,IP as e,OP as f,N as g,ie as h,Br as i,at as j,xl as k,wl as l,sP as m,aP as n,lP as o,cP as p,Bp as q,_e as r,Hr as s,jr as t,Ol as u,Ne as v,Wl as w,Fl as x,yP as y,Dt as z,CP as A,bP as B,Gl as C,SP as D,Bl as E,qr as F,vP as G,Kr as H,Cg as I,Zl as J,Ql as K,Gg as L,UP as M,YP as N,XP as O,JP as P,QP as Q,le as R,Vn as S,U as T,Pe as U,mt as V,no as W,cs as X,Nt as Y,dt as Z,rh as _,Zn as $,fs as aa,ps as ba,Xe as ca,xo as da,gy as ea,Ie as fa,Jd as ga,pa as ha,Iu as ia,tO as ja,ne as ka,VC as la,qC as ma,jo as na,bn as oa,qs as pa,dk as qa,Xf as ra,SN as sa,cl as ta,Ou as ua,pr as va,zu as wa,Gu as xa,ti as ya,Mu as za,Tk as Aa,ta as Ba,gr as Ca,vn as Da,hb as Ea,Rn as Fa,Lk as Ga,Wk as Ha,Fk as Ia,ri as Ja,ii as Ka,xn as La,Xk as Ma,oi as Na,Jk as Oa,vb as Pa,Qk as Qa,En as Ra,od as Sa,id as Ta,tp as Ua,np as Va,pp as Wa,Cp as Xa,wn as Ya,cT as Za,uT as _a,ia as $a,xT as ab,wT as bb,Rd as cb,MT as db,NT as eb,aa as fb,Ed as gb,GT as hb,Qb as ib,zn as jb,eP as kb,tP as lb,Tp as mb,gL as nb};
|