cc-safety-net 2.0.8 → 2.0.9
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/dist/amp/cc-safety-net/index.ts +73 -75
- package/dist/bin/cc-safety-net.js +175 -227
- package/dist/chunks/index-tdm5076r.js +62 -0
- package/dist/index.js +1 -1
- package/dist/openclaw/cc-safety-net/index.js +73 -75
- 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 +2 -2
- package/dist/vendor/zod.cjs +21 -21
- package/package.json +3 -3
- package/dist/chunks/index-hwg5anw1.js +0 -64
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import{randomBytes as Ip}from"node:crypto";import{closeSync as Hi,constants as $n,fstatSync as Bi,fsyncSync as Op,lstatSync as vt,mkdirSync as yl,openSync as Cl,readdirSync as ji,readFileSync as Dp,realpathSync as Ot,renameSync as Mp,rmdirSync as Np,statSync as Ui,unlinkSync as Vi,writeFileSync as Lp}from"node:fs";import{isAbsolute as bl,join as on,normalize as Wp,parse as Sl,relative as qi,resolve as Ki,sep as Un}from"node:path";var Fp=Symbol("PolicyFilesystemScope"),Gp=Symbol("PolicyFilesystemTarget"),vl=$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{[Fp]:!0,root:Ki(e),label:t}}function Hn(e,t){let n=Wp(t);if(t===""||bl(t)||n===".."||n.startsWith(`..${Un}`))throw new N(e.label);return{[Gp]:!0,scope:e,relativePath:n,path:on(e.root,n)}}function ie(e,t){let n=qi(e.root,Ki(t));return Hn(e,n)}function Br(e,t="rules policy"){let n=Ki(e),r=Sl(n).dir;return Hn(we(r,t),qi(r,n))}function at(e){try{if(!le(e,!1).exists)return null;let n=Cl(e.path,$n.O_RDONLY|vl);try{let r=Bi(n);if(!r.isFile())throw new N(e.scope.label);let o=Dp(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 le(e,!1),o}finally{Hi(n)}}catch(t){Rt(e.scope.label,t)}}function Rl(e,t,n=384,r){let o=`${e.path}.${Ip(8).toString("hex")}.tmp`,i=null;try{Bp(e),le(e,!0),i=Cl(o,$n.O_CREAT|$n.O_EXCL|$n.O_WRONLY|vl,n);let s=Bi(i);if(!s.isFile())throw new N(e.scope.label);Lp(i,t,"utf-8"),Op(i);let a=Bi(i);if(!a.isFile()||a.dev!==s.dev||a.ino!==s.ino)throw new N(e.scope.label);Hi(i),i=null,le(e,!0),Hp(e,o,a.dev,a.ino),Mp(o,e.path),r?.(e.path),le(e,!1)}catch(s){if(i!==null)Vp(i);qp(o),Rt(e.scope.label,s)}}function El(e,t){if(e.path===t.path)return!0;try{if(!le(e,!1).exists||!le(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 zp(e){try{if(!le(e,!1,"directory").exists)return null;let n=ji(e.path);return le(e,!1,"directory"),n}catch(t){Rt(e.scope.label,t)}}function oP(e){let t=zp(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(Pl(e.scope),Ot(o.path),e.scope.label),{name:r,kind:i.isDirectory()?"directory":"file"}});return le(e,!1,"directory"),n}catch(n){Rt(e.scope.label,n)}}function iP(e){try{if(!le(e,!0).exists)return;Vi(e.path),le(e,!0)}catch(t){Rt(e.scope.label,t)}}function sP(e){try{_l(e,e.relativePath.split(Un))}catch(t){Rt(e.scope.label,t)}}function aP(e){try{if(!$p(e))return;wl(e),le(e,!0,"directory")}catch(t){Rt(e.scope.label,t)}}function $p(e){try{if(!le(e,!0,"directory").exists)return!1;return xl(e),!0}catch(t){Rt(e.scope.label,t)}}function le(e,t,n="file"){let r=Zi(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 xl(e){for(let t of ji(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())xl(n)}le(e,!1,"directory")}function wl(e){for(let t of ji(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()){wl(n);continue}if(!r.isFile())throw new N(e.scope.label);Vi(n.path)}Np(e.path)}function Bp(e){_l(e,e.relativePath.split(Un).slice(0,-1))}function _l(e,t){Up(e.scope);let n=Pl(e.scope);for(let r of t.keys()){let o=on(e.scope.root,...t.slice(0,r+1));if(!Bn(o))yl(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 Up(e){if(Bn(e.root)){if(!Ui(e.root).isDirectory())throw new N(e.label);return}let t=[],n=e.root;while(!Bn(n)){t.unshift(n);let r=Sl(n).dir;if(r===n)throw new N(e.label);n=r}if(!Ui(n).isDirectory())throw new N(e.label);for(let r of t){yl(r,{mode:448});let o=vt(r);if(!o.isDirectory()||o.isSymbolicLink())throw new N(e.label)}}function Zi(e){if(!Bn(e.root))return null;if(!Ui(e.root).isDirectory())throw new N(e.label);return Ot(e.root)}function Pl(e){let t=Zi(e);if(!t)throw new N(e.label);return t}function Hp(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=Zi(e.scope);if(!i)throw new N(e.scope.label);Ur(i,Ot(t),e.scope.label)}function Ur(e,t,n){let r=qi(e,t);if(r===".."||r.startsWith(`..${Un}`)||bl(r))throw new N(n)}function Bn(e){try{return vt(e)}catch(t){if(jp(t)&&t.code==="ENOENT")return null;throw t}}function Rt(e,t){if(t instanceof N)throw t;throw new N(e)}function jp(e){return e instanceof Error&&"code"in e}function Vp(e){try{Hi(e)}catch{}}function qp(e){try{Vi(e)}catch{}}import{homedir as Jp}from"node:os";import{dirname as qe,isAbsolute as Qp,join as Me,relative as eg,resolve as Ke,sep as tg}from"node:path";var _e=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,Hr="rulebook.json",jr=".cc-safety-net/rules";var Al=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,Kp=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,Zp=/^[A-Za-z0-9._-]+$/,Yp=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Xp="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Yi=new RegExp(`^${Yp}/(${_e.source.slice(1,-1)})/${Xp}$`);function kl(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(Al);if(!t?.[1]||!t[2]||!t[3])throw Error(`Invalid GitHub rulebook source: ${e}`);let[n,r,...o]=t[3].split("/");if(!n||!Zp.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:kl(r),name:r}}function Tl(e){return Kp.test(e)}function an(e){return Al.test(e)}function Xi(e){if(!_e.test(e))throw Error(`Local rulebook sources must be bare names matching ${_e}: ${e}`)}var Ol="rule.json",Vr="policy.json",Dl="rule.lock",ng="config.json",Ml=".cc-safety-net",rg="rules",Il="cache",og="CC_SAFETY_NET_HOME",Ne="`cc-safety-net rule sync`";function ig(e){return Ke(e??process.cwd(),jr)}function Nl(e){return Me(ig(e),Ol)}function lt(e){return e?.userConfigDir??(e?.userConfigPath?qe(e.userConfigPath):Me(sg(),rg))}function sg(){let e=process.env[og];return e?Ke(e):Me(Jp(),Ml)}function Ll(e){return Me(lt(e),Ol)}function gP(e){return Me(lt(e),Dl)}function Dt(e){return Me(qe(e),Dl)}function hP(e={}){return Me(qe(lt(e)),ng)}function yP(e={}){return Ke(e.cwd??process.cwd(),".safety-net.json")}function Wl(e){let t=e.userConfigPath??Ll(e),n=e.projectConfigPath??Nl(e.cwd),r=Fl(t,e),o=Gl(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 CP(e){let t=e.global?e.userConfigPath??Ll(e):e.projectConfigPath??Nl(e.cwd),n=e.global?Fl(t,e):Gl(t,e),r=Dt(t);return{configDir:qe(t),configPath:t,lockPath:r,filesystemScope:n,configTarget:ie(n,t),lockTarget:ie(n,r)}}function Fl(e,t){let n=t.userConfigPath?qe(qe(Ke(t.userConfigPath))):qe(Ke(t.userConfigDir??lt(t)));return we(n,"user policy")}function Gl(e,t){let n=Ke(t.cwd??process.cwd()),r=Ke(e),o=eg(n,r);if(o!==".."&&!o.startsWith(`..${tg}`)&&!Qp(o))return we(n,"project policy");return we(qe(qe(r)),"project policy")}function zl(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($l(t),"rulebooks",`${ag(e)}--${n.slice(0,12)}`,Hr)}function bP(e){return Me($l(e),"rulebooks")}function Kr(e,t){let n=t;return{cacheConfigDir:e,cwd:t.cwd,global:n.global}}function ag(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 $l(e){let t=e?.cacheConfigDir??lt(e),n=e;if(n&&!n.global&&n.cwd&&Ke(t)===Ke(n.cwd))return Me(Ke(n.cwd),Ml,Il);return Me(qe(t),Il)}import{lstatSync as Bl,readdirSync as lg,readFileSync as Vl,rmdirSync as cg,statSync as Ul,unlinkSync as ug,utimesSync as dg,writeFileSync as mg}from"node:fs";import{dirname as fg,join as ln}from"node:path";var Zr=30,Ji=1,Qi=365;function Yr(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var ts=86400000,pg=".last-prune",gg=/^\d{4}-\d{2}$/,hg=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Hl=(e)=>Math.floor(e/ts);function yg(e){try{let t=ln(fg(lt(e)),Vr),n=JSON.parse(Vl(t,"utf-8"));return Yr(n?.audit?.retention_days)}catch{return Zr}}function ql(e,t=()=>new Date){try{let n=t().getTime();if(!Ul(e,{throwIfNoEntry:!1})?.isDirectory())return;let r=ln(e,pg),o=Ul(r,{throwIfNoEntry:!1})?.mtimeMs;if(o!==void 0&&Hl(o)===Hl(n))return;let i=n-yg()*ts,s=new Date(n).toISOString().slice(0,7);for(let a of es(e)){if(a.isDirectory()){Cg(ln(e,a.name),i,s);continue}if(a.isFile()&&a.name.endsWith(".jsonl"))bg(ln(e,a.name),i)}mg(r,"",{mode:384}),dg(r,n/1000,n/1000)}catch{}}function Cg(e,t,n){for(let r of es(e)){if(!r.isDirectory()||!gg.test(r.name))continue;let o=ln(e,r.name);for(let i of es(o)){if(!i.isFile())continue;let s=hg.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+ts;if(!Number.isFinite(a)||a>=t)continue;Kl(ln(o,i.name))}if(r.name!==n)jl(o)}jl(e)}function bg(e,t){try{let n=Bl(e);if(n.mtimeMs>=t)return;let r=Vl(e,"utf-8").split(`
|
|
2
|
+
`).filter((o)=>o.trim()).map(Sg);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(Bl(e).mtimeMs!==n.mtimeMs)return;Kl(e)}catch{}}function Sg(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 es(e){try{return lg(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Kl(e){try{ug(e)}catch{}}function jl(e){try{cg(e)}catch{}}import{randomBytes as wg}from"node:crypto";import{appendFileSync as _g,mkdirSync as Pg}from"node:fs";import{homedir as Ag,userInfo as kg}from"node:os";import{isAbsolute as Tg,join as ns}from"node:path";var vg=[/\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 Zl(t)}function Zl(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 vg)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 Rg(e){return Yl(e).reduceRight((n,r)=>`${n.slice(0,r.valueStart)}<redacted>${n.slice(r.valueEnd)}`,e)}function AP(e){return Zl(Rg(e))}function kP(e){return Yl(e).map((t)=>e.slice(t.valueStart,t.valueEnd))}function TP(e){return/[A-Za-z_][A-Za-z0-9_]*=/.test(e)}function Yl(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:Eg(e,s)})}return t}function Eg(e,t){if(e.startsWith("$(",t))return xg(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 xg(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 Ig="2.0.9",Og=1e4,Dg=2000,Mg=256,Ng=32768;function Lg(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 Wg(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function rs(e,t,n,r,o,i={}){let s=Lg(e);if(!s)return;let a=i.homeDir??Xl();if(!a)return;let l=Fg(a);if(!l)return;try{let c=(i.now??(()=>new Date))().toISOString(),u=Xr(ct(t),i.failureStage?Number.POSITIVE_INFINITY:Og),m=Xr(ct(n),Dg),f=i.toolName?Xr(ct(i.toolName),Mg):void 0,d=o===null?void 0:Xr(ct(o),Ng),p=ns(l,Wg(d?.value??null),c.slice(0,7));Pg(p,{recursive:!0,mode:448});let g=ns(p,`${c.slice(0,10)}-${s}.jsonl`),y={ts:c,id:(i.createId??(()=>wg(8).toString("hex")))(),v:Ig,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};_g(g,`${JSON.stringify(y)}
|
|
3
|
+
`,{encoding:"utf-8",mode:384}),ql(l,i.now)}catch{}}function Xr(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function Xl(e=process.env.CC_SAFETY_NET_AUDIT_HOME||process.env.HOME){let t=e||Ag()||kg().homedir;return t&&Tg(t)?t:null}function Fg(e=Xl()){return e?ns(e,".cc-safety-net","logs"):null}function Ql(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=Jl(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?Jl(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 Jl(e){return"command"in e?e.command??"":""}function ec(e,t,n){if(!e)return;let r;try{r=t()}catch{return}if(typeof r!=="string"||!r.trim())return;rs(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 $P(e,t,n){let r;try{r=t()}catch{return}if(typeof r!=="string"||!r.trim())return;rs(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.",tc="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.",nc="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 oc(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: ${rc(l,i)}`}if(r&&r!==n){let l=s(r);a+=`
|
|
12
|
+
|
|
13
|
+
Segment: ${rc(l,i)}`}if(e.configWarning)a+=`
|
|
14
|
+
|
|
15
|
+
Config warning: ${s(e.configWarning)}`;return a+=`
|
|
16
|
+
|
|
17
|
+
${Gg(e.intent??"manual_only")}`,a}function Gg(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 rc(e,t){return e.length>t?`${e.slice(0,t)}...`:e}function KP(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 ZP(e={}){return{reason:Jr,intent:"stop_and_explain",command:e.command,segment:e.segment??e.command,toolName:e.toolName}}function YP(e){return oc({...e,redact:ct})}function XP(e){return ct(e instanceof Error?e.message:String(e))}import{basename as zg,dirname as $g,join as ic}from"node:path";var cn=Object.freeze({maxEnvironmentExpansionDepth:64,maxMissingSuffixComponents:256,maxRealpathAttempts:16384,maxProcessedCandidateBytes:4194304});class se 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 os(e,0,t)}function os(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=is(e,o+2),a=Bg(e,o,t);if(a===null){if(Qr.has(s))throw new se;r+=e.slice(o);break}let l=e.slice(o,a+1);r+=Ug(l,t,n),o=a+1;continue}let i=is(e,o+1);if(!i){r+="$",o++;continue}r+=ss(i,n)??`$${i}`,o+=i.length+1}return r}function Bg(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 se;o++;continue}if(e[o]!=="}")continue;if(r--,r===0)return o}return null}function Ug(e,t,n){let r=e.slice(2,-1),o=is(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return ss(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(Qr.has(o))throw new se;return e}if(!Qr.has(o))return e;if(s.endsWith("="))throw new se;let a=ss(o,n),l=s.startsWith(":")?a!==null&&a!=="":a!==null;if(s.endsWith("?")&&!l)throw new se;if(s.endsWith("-")||s.endsWith("?"))return l?a??"":os(i.slice(s.length),t+1,n);return l?os(i.slice(s.length),t+1,n):""}function is(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 se;let s=t.realpath(i);if(s!==null){let l=o.length===0?s:ic(s,...o.reverse());return n.resolvedPaths.set(e,l),l}let a=$g(i);if(a===i){let l=o.length===0?i:ic(i,...o.reverse());return n.resolvedPaths.set(e,l),l}if(o.length>=cn.maxMissingSuffixComponents)throw new se;o.push(zg(i)),i=a}}function sc(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 se;let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function ss(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 Hg=["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(Hg),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"}],jg=new Map(no.map((e)=>[e.id,e.intent])),ac=new Set(no.filter((e)=>e.catastrophic).map((e)=>e.id));function b(e,t){return{id:e,reason:t,intent:jg.get(e)??"manual_only"}}function k(e,t){if(!e)return null;if(ac.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(ac.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function as(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 lc(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:as(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"]),cc=new Set(["python","python3","python2","node","ruby","perl"]),uc=/^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 Vg}from"node:util";var qg=new Set(["applypatch","patch"]),Kg=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),Zg=new Set(["grep","grepsearch","rg"]),Yg=new Set(["find","findbyname","glob"]),Xg=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),Jg=new Set(["command","diff","input","patch","patchtext"]),dc=new TextEncoder,Qg=new TextDecoder,eh=/\s/,th=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 hc(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function so(e){return Xg.has(hc(e))}function nh(e){let t=hc(e);if(qg.has(t))return"patch";if(Zg.has(t))return"grep";if(Yg.has(t))return"glob";if(Kg.has(t))return"path";return"unknown"}function Zn(e){if(!e||typeof e!=="object")return;vc(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)Ze();return}if(t.get||t.set)Ze();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function ds(e,t){return yc(e,t,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function yc(e,t,n,r){let o=Sc(e,n,r);if(!o)return[];let i=o.entries.flatMap(([s,a])=>{let l=yc(a,t,n,r+1);return typeof a==="string"&&t.has(Cc(s))?[a]:l});return n.ancestors.delete(o.object),i}function Cc(e){return e.replace(/-/g,"_").toLowerCase()}function ms(e){return bc(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(oh)}function bc(e,t,n,r){let o=Sc(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>bc(a,o.array?t:Jg.has(Cc(s)),n,r+1));return n.ancestors.delete(o.object),i}function rh(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>qn.maxDepth||t.nodes>qn.maxNodes)Ze();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>qn.maxStringBytes||t.stringBytes>qn.maxAggregateStringBytes)Ze()}function Sc(e,t,n){if(rh(e,t,n),!e||typeof e!=="object")return null;let r=vc(e);if(t.ancestors.has(e))Ze();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>qn.maxKeys)Ze();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)Ze();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function vc(e){if(Vg.isProxy(e))Ze();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)Ze();return t}function Ze(){throw new dt}function oh(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=ih(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(...ls(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...ls(c));continue}if(c.startsWith("--- ")){let u=n[l+1]??"";if(!u.startsWith("+++ "))continue;t.push(...us(io(c.slice(4),!0),io(u.slice(4),!0))),l++;continue}if(!r)t.push(...ls(c))}return t}function ih(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 ls(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return gc(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return gc(n[1]);if(e.startsWith("diff --git "))return sh(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return pc(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return pc(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return fh(i[1]);return[]}function sh(e){let t=ah(e);if(t.length===2&&t[0]&&t[1])return us(t[0],t[1]);let n=lh(e);return n?us(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function ah(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=Rc(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(Lt(e[n]))n++;return n===e.length?t:[]}function lh(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>th)Ze();if(ch(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function ch(e,t,n,r,o){if(cs(e,t,n,r,o))return!0;let i=mc(e,"/",t,n),s=mc(e,"/",r,o);if(i<=t||s<=r)return!1;if(cs(e,t,i,r,s))return!1;return cs(e,i+1,n,s+1,o)}function cs(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 mc(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&&eh.test(e)}function Rc(e,t,n){let r=[],o=t+1;while(o<e.length){let i=e[o]??"";if(i===n)return{value:Qg.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...dc.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(...dc.encode(uh(s[0]??""))),o+=2}return null}function uh(e){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
18
|
+
`,r:"\r",t:"\t",v:"\v"}[e]??e}function dh(e){return Kn(ph(e))}function us(e,t){if(e==="/dev/null")return fc(t);if(t==="/dev/null")return fc(e);if(e.startsWith("a/")&&t.startsWith("b/"))return[e.slice(2),t.slice(2)].flatMap(Kn);let n=mh(e,t)??(e===t?Ec(e):null);return[e,t,...n?[n]:[]].flatMap(Kn)}function fc(e){let t=Ec(e);return[e,...t?[t]:[]].flatMap(Kn)}function Ec(e){let t=e.indexOf("/");return t>0&&t<e.length-1?e.slice(t+1):null}function mh(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 pc(e){return dh(io(e,!0))}function fh(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=Rc(n,0,r);if(o&&(t||n.slice(o.end).trim()===""))return o.value}return t?n.split("\t",1)[0]?.trim()??"":n}function ph(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function Kn(e){return e===""||e==="/dev/null"?[]:[e]}function gc(e){let t=e.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return t===""||t==="/dev/null"?[]:[t]}import{lstatSync as gh,realpathSync as hh}from"node:fs";import{homedir as yh,tmpdir as Ch}from"node:os";var Pe={realpath:(e)=>{try{return hh(e)}catch{return null}},entryKind:(e)=>{let t=gh(e,{throwIfNoEntry:!1});if(!t)return"missing";return t.isSymbolicLink()?"symlink":"present"}};function Wt(){return process.env.HOME||yh()}function mt(){return{env:new Map(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),home:Wt(),tmpdir:Ch(),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 bh(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 Sh(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)=>Sh(t,e,n,r,o)}}function fs(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 fs({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 bh(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 ps(e,t,n){if(t>=n||wc(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!wc(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=xc(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=xc(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 gs(e,t,n,r){let o=[],i=t;for(let s of r){let a=i,l=!1;while(i<n){let c=vh(e,i,n);if((s.stripTabs?c.text.replace(/^\t+/,""):c.text)===s.delimiter){s.attach({body:s.stripTabs?Rh(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 xc(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 wc(e){return/[\s;&|<>)]/u.test(e)||e==="`"}function vh(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 Rh(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Tc=new Set(["&&","||","|","|&"]);function Ic(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(),kc(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"||!Tc.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=gs(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?$h(e,d,n):void 0;if(g){if(ys(l,c,d),s>=o.maxDepth)return fn(l,c,d,"depth-limit",o.maxDepth);if(!hs(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=_c(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(),!Gc(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==="{"&&kh(e,d,n))&&u.start===-1){if(ys(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=_c(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]!=="("?wh(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==="<<-"?ps(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?Cs(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(!hs(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)ys(l,c,d);let R=Cs(e,d,n,r,o,i,s);if(c.push(...R.issues),R.limited)return po(l,c,R.next);let E=Oh(u.words)?Wh(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(!hs(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(),kc(l,c),c.push(...Bh(m)),{nodes:l,issues:c,next:d,closed:a===void 0,limited:!1,pendingHeredocs:[]}}function _c(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 Cs(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=Eh(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=_h(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==="`"?bs(e,l,n,r,o,i,s):null;if(y){let h=Oc(y,m,f);if(d||=h.limited,u=Yn(u,h.provenance),l=h.next,d)break;continue}if(p==="$"){let h=Nc(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:Ah(e,t,l)),nested:m,issues:f,next:l,limited:d}}function Eh(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=Ss(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=bs(e,f,n,r,o,i,s);if(p){let g=Oc(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=Nc(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 bs(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=Ss(e,t+m,n,f),p=d===-1?n:d,g=d===-1?n:d+f.length;if(s>=o.maxDepth)return{program:zh(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=bs(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 Oc(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 Ss(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=gs(e,u,n,s.splice(0));if(!m.terminated)return-1;a=m.next-1;continue}let c=Dc(e,a,t,n,i);if(c!==null){a=c;continue}if(!i.double&&e.startsWith("$((",a)){let u=xh(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=ps(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 xh(e,t,n){let r=1,o={single:!1,double:!1};for(let i=t;i<n;i++){let s=e[i],a=Dc(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 Dc(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!=="#"||!Uh(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 wh(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 Mc(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 _h(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=Ph(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 Ph(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 Nc(e,t,n,r,o){let i=Mc(e,t,n);return{text:r+e.slice(t,i),provenance:Yn(o,"variable"),next:i}}function Ah(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=Ss(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=Mc(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 kh(e,t,n){return t+1>=n||yo(e[t+1]??"")||ho(e,t+1)!==null}var Th=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),Ih=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function Oh(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=Dh(e,t);if(n===void 0||n===null)return!1;t=n}return!1}function Dh(e,t){let n=e[t]?.text.toLowerCase();if(n==="command")return Mh(e,t);if(n==="env")return Nh(e,t);if(n==="sudo")return Lh(e,t);return}function Mh(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 Nh(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(Th.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 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("-"))continue;return n}return e.length}function Lc(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)=>Ac(p));if(l===-1)break;if(++s>n)return{limited:!0};let c=o[l]??"",u=Ac(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=Wc(c,u);o.splice(l,1,...d),i+=f-c.length}if(s===0)return;let a=o.map((l)=>Gh(l,n));if(a.some((l)=>l===null))return{limited:!0};return{words:[...new Set(a.filter((l)=>l!==null&&l!==""))]}}function Wh(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)=>Pc(y));if(c===-1)break;if(++a>r)return{limitCode:"depth-limit"};let u=i[c]??"",m=Pc(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=Wc(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 Pc(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:Fc(e,n)}}function Ac(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}:Fh(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:Fc(e,n)}}function Wc(e,t){return t.alternatives.map((n)=>`${e.slice(0,t.start)}${n}${e.slice(t.end)}`)}function Fc(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 Fh(e){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(e)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(e)}function Gh(e,t){let n=`x${e}`,r=Cs(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 zh(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 hs(e){return e.used++,e.used<=e.max}function $h(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 Bh(e){return e.map((t)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${t.delimiter} was not found`,span:t.declarationSpan}))}function Gc(e){return e?.kind==="command"||e?.kind==="group"||e?.kind==="function"}function kc(e,t){let n=e.at(-1);if(n?.kind!=="connector"||!Tc.has(n.operator))return;t.push({code:"missing-command-after-connector",message:`connector ${n.operator} requires a following command`,span:n.span})}function ys(e,t,n){if(!Gc(e.at(-1)))return;t.push({code:"missing-command-connector",message:"adjacent commands require a connector",span:{start:n,end:n+1}})}function Uh(e,t,n){return t===n||/[\s;&|()]/u.test(e[t-1]??"")}var zc=new Set(["remove-item","ri","del","erase","rd","rmdir"]),$c=["-rec","-for","-path","-literalpath","-whatif"],bo={maxInputLength:131072,maxWords:16384,maxDepth:64};function Bc(e){let t=e.toLowerCase().replaceAll("`","");if(![...zc].some((r)=>t.includes(r))&&!(t.includes("rm")&&$c.some((r)=>t.includes(r)))&&!t.includes("<#"))return!1;let n=qh(e);return n.invalidComment||n.commands.some(Hh)}function Hh(e){let t=e[0]==="&"||e[0]==="."?1:0,n=e[t]?.toLowerCase();if(n&&zc.has(n))return!0;if(n!=="rm")return!1;return e.slice(t+1).some((r)=>{let o=r.toLowerCase().split(":",1)[0]??"";return $c.some((i)=>o.startsWith(i))})}function Uc(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=ws(e,0,e.length,t,0);return de({kind:"program",dialect:"powershell",source:e,span:n,status:Kh(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function ws(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=Vc(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(vs(e,f,h)),f=h;continue}f++;continue}let g=_s(e,f);if(g){m(),s.push(vs(e,f,f+g.length)),f+=g.length;continue}if(d==="{"){if(m(),o>=r.maxDepth)return a.push(jc(f,r.maxDepth)),{nodes:s,issues:a,next:n,closed:!1,words:c,limited:!0};let h=ws(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(vs(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?Rs(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(fs({text:",",raw:",",span:{start:f,end:f+1},provenance:"literal",quoted:!1})),l.end=++f;continue}let y=Rs(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 Rs(e,t,n,r,o){let i="",s="literal",a=!1,l=[],c=[],u=0,m=!1,f=(p)=>{let g=jh(e,p,n,r,o);return i+=e.slice(p,g.next),c.push(g.program),l.push(...g.program.issues),u+=Es(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)||_s(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:Vh(e,t,d)),next:d,issues:l,nested:c,words:u,limited:m}}function jh(e,t,n,r,o){let i=Hc(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:[jc(t,r.maxDepth)],nodes:[]}),next:a};let l=ws(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 Hc(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 Es(e){let t=0;for(let n of e.nodes){if(n.kind==="group")t+=Es(n.body);if(n.kind==="command"){t+=n.words.length;for(let r of n.nested)t+=Es(r)}}return t}function Vh(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=Hc(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 jc(e,t){return{code:"depth-limit",message:`command structure exceeds parser limit ${t}`,span:{start:e,end:e}}}function qh(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=Vc(e,r,Math.min(e.length,bo.maxInputLength),bo.maxDepth);if(l){i||=!!l.issue||l.limited,r=l.next;continue}let c=_s(e,r);if(c){s(),r+=c.length;continue}if(a==="{"||a==="}"){s(),r++;continue}let u=Rs(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(...xs(m));o++,r=u.next>r?u.next:r+1}return s(),{commands:t,invalidComment:i}}function xs(e){return e.nodes.flatMap((t)=>{if(t.kind==="group")return xs(t.body);if(t.kind!=="command")return[];return[t.words.map((n)=>n.text),...t.nested.flatMap(xs)]})}function _s(e,t){for(let n of["&&","||",";","|"])if(e.startsWith(n,t))return n;return null}function Vc(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 Kh(e,t){if(t)return"limited";if(e.some((n)=>n.code==="unclosed-block-comment"))return"invalid";return e.length>0?"partial":"complete"}function vs(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"&&Bc(e.slice(0,n.maxInputLength)))return Uc(e,n);return Ic(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 Zh=/^[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)=>!Zh.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 Yh(e))Qn(n,t);return t.inSingle||t.inDouble}function Yh(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 Xh=new Set(["&&","||","|&","|","&",";"]),Jh=new Set(["<<","<<<",">|"]),Qh=/[*@#?$!_-]/,Ps=Object.freeze([]),ey=Object.freeze([]),ty=256;function Xc(e,t){let n=t.status==="complete"?new Set(ks(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,Ps);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,Ps);if(o.invalid)return Ro("invalid",r,Ps);return Ro("complete",r,i,o.assignmentFallbacks)}function Ro(e,t,n,r=ey){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)=>ny(n,e,r,t)).sort((n,r)=>n.start-r.start).flatMap((n)=>[...n.entries])}function ny(e,t,n,r){if(e.kind==="connector")return[{start:e.span.start,entries:[We(ay(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=cy(e,r.functions);if(o){if(r.depth>=Ft.maxDepth||++r.flags.expansions>ty)return r.flags.limited=!0,[];return[{start:e.span.start,entries:[...qc(e,r),Eo(";"),...er(o,{...r,depth:r.depth+1}),Eo(";")]},...Kc(e,t,n,r)]}return[{start:e.span.start,entries:qc(e,r)},...Kc(e,t,n,r)]}function qc(e,t){return[...e.words.map((n)=>({start:n.span.start,entries:Qc(n,e,t,!1)})),...e.redirections.map((n)=>({start:n.span.start,entries:ry(n,e,t)}))].sort((n,r)=>n.start-r.start).flatMap((n)=>n.entries)}function ry(e,t,n){let r=e.operator==="<<-"?"<<":e.operator,o=e.target?Qc(e.target,t,n,!0):[],i=o[0],s=i?.kind==="word"?i.text:void 0;return[...e.fd===void 0?[]:[Ts(String(e.fd))],Object.freeze({kind:"redirection",operator:r,role:ly(r),targetOrder:Jh.has(r)?"legacy-segment":"immediate",...s===void 0?{}:{target:s}}),...s===void 0?o:o.slice(1)]}function Kc(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=[Ts(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:[...Jc(r.source.slice(s.bodySpan.start,s.bodySpan.end),r),...a]}]}),...o.some((i)=>!i.heredoc&&i.target)?oy(t,n,r):[]]}function oy(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:Jc(n.source.slice(r.span.end,e.span.end),n)}]}function Jc(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 Qc(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(Ts(s));s="",a=!1};for(let c of e.parts){if(c.provenance!=="command-substitution"&&c.provenance!=="arithmetic"){for(let d of As(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+=As(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 As(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=Zc(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=Zc(e,s,t,n);o+=l.text,s=l.next;continue}i||=a==="*"||a==="?",o+=a,s++}return[...r,{text:o,glob:i}]}function Zc(e,t,n,r){let o=e[t+1];if(o==="{"){let s=sy(e,t+2);if(s===-1)return r.invalid=!0,{text:"",next:e.length};let a=e.slice(t,s+1);return iy(a,n,r),{text:a,next:s+1}}if(o!==void 0&&Qh.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 iy(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=As(i.slice(s.length),{...t},n);n.assignmentFallbacks.push(...a.flatMap((l)=>typeof l==="string"||!l.text?[]:[l.text]))}function sy(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 ay(e){return/^[\r\n]+$/.test(e)?";":e}function We(e){return Object.freeze({kind:"operator",operator:e,boundary:Xh.has(e)})}function Eo(e){return Object.freeze({kind:"operator",operator:e,boundary:!0})}function Ts(e){return Object.freeze({kind:"word",text:e})}function ly(e){if(e==="<<"||e==="<<<")return"here-data";if(e==="<"||e==="<&")return"file-read";return"file-write"}function ks(e){return e.nodes.flatMap((t,n)=>{if(t.kind==="group"||t.kind==="function")return ks(t.body);if(t.kind!=="command")return[];let r=t.nested.flatMap((s)=>ks(s)),o=e.nodes[n+1];if(o?.kind==="connector"&&(o.operator==="|"||o.operator==="|&")||!dy(t))return r;return[...r,...t.redirections.flatMap((s)=>s.heredoc?.quotedDelimiter?[s.heredoc.bodySpan]:[])]})}function cy(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 uy(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 dy(e){return(xt(e.words[0],"cat")||xt(e.words[0],"tee")||uy(e))&&!e.words.some(Yc)&&!e.redirections.some((n)=>Yc(n.target))}function Yc(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}var eu=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),tu=new Set([...eu,"glob"]),my=new Set([...tu,"pattern"]),fy=[],nu={parseCommand:Le,projectShellSyntax:Xc};class Ye extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function xo(e,t={}){let n=py({...nu,...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:gy(e),store:n}}function ge(e,t){return e.commands.find((n)=>n.usages.includes(t))}function Xe(e){if(!e.includes("$"))return e;return eo(e,mt())}function py(e={}){let t={...nu,...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:fy,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 gy(e){let t=e.route.kind==="grep"?tu:e.route.kind==="glob"?my:eu;return[...ds(e.input,t),...e.route.kind==="patch"?ms(e.input):[]]}function Is(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 Os(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"]),hy=new Set(["-e","--source"]),yy=new Set(["-F","-v","--assign","--field-separator"]),ru=new Set(["-f","--file"]),Cy=new Set(["print","printf","return"]),ou=[{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"}],by="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 Sy(e)){let i=vy(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",by):null}function Ms(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&&hy.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&&(yy.has(a)||ru.has(a))){if(ru.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 Ms(e).sources}function Sy(e){return rr(e).filter((t)=>t.kind!=="program-file").map((t)=>t.value)}function vy(e,t){he(t,e);let n=e.includes("system")?Ns(e,t):null,r=Ry(e,t);if(!n&&!r)return null;return{dynamic:!!n?.dynamic||!!r?.dynamic,commands:[...n?.commands??[],...r?.commands??[]]}}function Ns(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=iu(e,i+1);continue}if(s==="/"&&su(e,i)){i=au(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 Ry(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=iu(e,i+1),s=i,a=null,l=null,c=i;continue}if(u==="/"&&su(e,i)){let d=au(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&&(Ds(e,i,"print")||Ds(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(Ds(e,f,"getline")){o=!0;let d=wy(s,l,c);if(d===null)r=!0;else n.push(d);c=m,i=m;continue}if(Py(s,a)){o=!0;let d=xy(e,f);if(!d){r=!0,c=m,i=m;continue}if(!Ey(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 Ey(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=_y(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 xy(e,t){let n=e[t];if(n!=='"'&&n!=="'")return null;return _o(e,t,n)}function wy(e,t,n){if(!t)return null;return t.startIndex>=e&&t.endIndex===n?t.value:null}function _y(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 Ds(e,t,n){return e.startsWith(n,t)&&!nr(e[t-1])&&!nr(e[t+n.length])}function Py(e,t){return t!==null&&t>=e}function iu(e,t){let n=e.indexOf(`
|
|
44
|
+
`,t);return n===-1?e.length:n+1}function su(e,t){let n=Ay(e,t);if(n===-1)return!0;if("{([,;!~=".includes(e[n]??""))return!0;let r=n;while(nr(e[r-1]))r--;return Cy.has(e.slice(r,n+1))}function Ay(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function au(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 Gs,lstatSync as Fy,readFileSync as Io,realpathSync as sr,statSync as ir}from"node:fs";import{dirname as zs,isAbsolute as $s,join as Oo,resolve as Do}from"node:path";import{dirname as ky,isAbsolute as Ty,parse as Iy,sep as Oy}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=Ty(t)?My(t):"",o=r||e;for(let i of Ny(r?t.slice(r.length):t)){if(i===""||i===".")continue;if(i===".."){o=ky(o);continue}let s=Dy(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 Dy(e,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${t}`:`${e}${Oy}${t}`}function My(e){return Iy(e).root}function Ny(e){let t=process.platform==="win32"?/[\\/]+/:/\/+/;return e.split(t)}var Ls=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],Ly=new Set(Ls);var lu=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"]),Wy=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function Ws(e){return Ly.has(e)}function or(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function Fs(e){return Ws(e)||lu.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(Wy)?.[1];if(!o||!Fs(o))return null;let i=e.indexOf("=");return{name:o,value:`${Ae(o,t,n)??""}${e.slice(i+1)}`}}function cu(e){return du(e,Ao)}function uu(e){return du(e,lu)}function du(e,t){if(!e)return!1;for(let n of e.keys())if(t.has(n))return!0;return!1}var Je=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]);function pu(e,t){return Ls.some((n)=>t?.has(n)||e.has(n))}function gu(e,t){if(!t)return{gitCwd:null,hasExplicitGitContext:!1};let n;try{n=sr(Do(t))}catch{return{gitCwd:null,hasExplicitGitContext:!1}}if(!Cu(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=fu(n,s);if(!a)return{gitCwd:null,hasExplicitGitContext:r};n=a,o+=2;continue}if(i.startsWith("-C")&&i.length>2){let s=fu(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(Je.has(i))o+=2;else if(i.startsWith("-c")&&i.length>2)o++;else o++}return{gitCwd:n,hasExplicitGitContext:r}}function hu(e){let t=Jy(e);if(!t)return!1;try{let n=Fy(t);if(n.isSymbolicLink()||!n.isFile())return!1;let r=Bs(t);if(!r?.commonDir)return!1;if(!$y(r.gitDir,t))return!1;return By(r.gitDir,zs(t))}catch{return!1}}function Bs(e){try{let t=Gy(e);if(!t)return null;let n=sr($s(t)?t:Do(zs(e),t));if(!ir(n).isDirectory())return null;return{gitDir:n,commonDir:zy(n)}}catch{return null}}function Gy(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 zy(e){try{let t=Io(Oo(e,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!t)return null;let n=sr($s(t)?t:Do(e,t));return ir(n).isDirectory()?n:null}catch{return null}}function $y(e,t){let n=Uy(e);return n===null?!1:yu(e,n,t)}function By(e,t){let n=Hy(e);return n===null?!0:yu(e,n,t)}function Uy(e){let t=Oo(e,"gitdir");if(!Gs(t))return null;let n=Io(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return n===""?null:n}function Hy(e){let t=Oo(e,"config.worktree");return Gs(t)?Zy(t):null}function yu(e,t,n){return Vy(jy(e,t),n)}function jy(e,t){return $s(t)?t:Do(e,t)}function Vy(e,t){try{return qy(e,t)}catch{return!1}}function qy(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 mu(e)===mu(t)}function mu(e){return Ky(sr.native(e))}function Ky(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 Zy(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=Yy(s[1]??"")}return r}function Yy(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;return Xy(t.slice(1,-1))}function Xy(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 fu(e,t){try{let n=wt(e,t,Pe);return Cu(n)?n:null}catch{return null}}function Cu(e){try{return ir(e).isDirectory()}catch{return!1}}function Jy(e){try{return ar(sr(e))}catch{return null}}function ar(e){let t=e;while(!0){let n=Oo(t,".git");if(Gs(n))return n;let r=zs(t);if(r===t)return null;t=r}}function Mo(e,t,n){let r=Is(e,n);if(t==="rm")return Qy(r);if(t==="dd")return tC(r);return xu(r,!0)}function No(e,t,n){let r=Is(e,n);if(t==="rm")return nC(r);if(t==="reset-hard")return Ru(r,"--ha","rd");if(t==="reset-merge")return Ru(r,"--me","rge");if(t==="clean")return sC(r);if(t==="checkout")return lC(r);if(t==="push-force")return cC(r);if(t==="push-refspec")return uC(r);if(t==="push-delete")return dC(r);if(t==="branch")return mC(r);if(t==="tag")return gC(r);if(t==="restore")return hC(r);return xu(r,!1)}function Qy(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=eC(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=bu(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=bu(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 eC(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 bu(e,t,n){if(Su(e,t,n,"recursive"))return{recursive:!0,force:!1};if(Su(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 Su(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 tC(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 nC(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=oC(e,o);if(s>=0){if(rC(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)||Us(e,o,"recursive"),r||=V(e,o,"--force")&&pt(e,o+7)||Us(e,o,"force"),n&&r)return!0;o++}return!1}function Us(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 rC(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=vu(e,i,"recursive"),a=vu(e,i,"force");if(r&&a||o&&s)return!0;if(r||=s,o||=a,v(e,i+1)==="-")continue;let l=iC(e,i,n);if(l.combined||r&&l.forceAtBoundary||o&&l.recursiveAtBoundary)return!0;r||=l.recursive,o||=l.force}return!1}function vu(e,t,n){return V(e,t,`--${n}`)&&pt(e,t+n.length+2)||Us(e,t,n)}function oC(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 iC(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 Ru(e,t,n){return cr(e,"reset",gn,!0,(r)=>v(e,r)==="-"&&hn(e,r,t,n)?!0:r)}function sC(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=aC(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 aC(e,t,n){for(let r of Je)if(n-t===r.length&&V(e,t,r))return!0;return!1}function lC(e){return Eu(e,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function cC(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=wu(e,t,"--fo","rce");if(n>=0&&!V(e,n,"-with-lease"))return!0;return t})}function uC(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 dC(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 mC(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=fC(e,o,i);if(n||=s.deletion,r||=s.force,n&&r)return!0;o=i-1}return!1}function fC(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&&pC(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 pC(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function gC(e){return Eu(e,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function Eu(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 hC(e){let t=!1;for(let n=0;n<X(e);n++){if(Os(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 xu(e,t){let n=!1;for(let r=0;r<X(e);r++){let o=v(e,r),i=t?Os(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 wu(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 wu(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"])]]),yC=new Set(["-p","--print"]),CC=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),bC=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"])]]),SC=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),vC=new Map([["python",new Set(["m"])]]),RC=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"])]]),EC=new Set(["always","default","never"]),xC=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),wC=/\\\r?\n/g,_C=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 Pu(e){return _C.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"&&yC.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(AC(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(kC(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=PC(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(RC.get(t)?.has(s)){let m=e[i+1];if(m===void 0||m.startsWith("-")&&!(t==="ruby"&&xC.has(s))||t==="python"&&!EC.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(vC.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(CC.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(bC.get(t)?.has(f)){if(m+1===s.length)i++;break}if(SC.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 PC(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 uc.test(t)?"python":t}function AC(e,t){return Wo.get(e)?.has(t)??!1}function kC(e){return Wo.get(e)?.has("--eval")??!1}function Cn(e,t){let n=OC(e,t);if(!_u(n,t))return!1;he(t,n);let r=IC(n);if(_u(r,t))return!0;return he(t,r),TC.test(r)}var TC=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function IC(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 _u(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 OC(e,t){return he(t,e),e.replace(wC,"")}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 DC=new Map([["bash",new Set(["O","o"])],["dash",new Set(["o"])],["ksh",new Set(["o"])],["sh",new Set(["o"])],["zsh",new Set(["o"])]]),MC=new Map([["zsh",new Set(["o"])]]),NC=new Map([["bash",new Set(["--init-file","--rcfile"])]]);function Au(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=NC.get(e);if(WC(r,s))continue;if(!s?.has(r))continue;if(t[n+1]===void 0)return null;n++;continue}let o=LC(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 LC(e,t){let n=DC.get(e),r=MC.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 WC(e,t){return t!==void 0&&[...t].some((n)=>e.startsWith(`${n}=`))}var ku=new Set(["rm","find","xargs","parallel"]),FC=new Set(["sudo","env","command","builtin"]),GC=new Set(["git","busybox",...ku,...ee,...cc,...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=zC(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 zC(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&&$C(a,r))i.push(s);else if(oo.has(z(a)))break;if(o)break}return i}function $C(e,t){let n=M(e),r=z(e);return r==="git"||n==="busybox"||Bt(e)||ku.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 FC.has(e.toLowerCase())}function Tu(e){let t=z(e);return GC.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 BC(e){return{failClosed:e==="strict"||e==="paranoid",paranoidRm:e==="paranoid",paranoidInterpreters:e==="paranoid"}}function UC(e,t){if(!t)return e;return Ho.indexOf(t)>Ho.indexOf(e)?t:e}function HC(){let e=js(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 jC(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function VC(){return jC(js(ne.auditScope))==="all"}function Hs(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=HC(),r=UC(t,n),o=BC(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:Hs(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):js(e);return t==="1"||t?.toLowerCase()==="true"}function ur(e){return Object.hasOwn(process.env,e)?process.env[e]:void 0}function js(e){let t=ur(e.name);if(t!==void 0)return t;if(e.legacyName)return ur(e.legacyName);return}function ck(e){return ur(e.name)!==void 0||!!e.legacyName&&ur(e.legacyName)!==void 0}function Iu(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 Vs=[{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."},qC=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],KC=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],qs=[{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"]},...KC.flatMap((e)=>qC.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"]}],Ou=[{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"}],ZC=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Ks=Ou.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})),Zs=Ou.flatMap((e)=>ZC.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)$/},Ys=["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})),Xs=[{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?$/}],Du=[...Vs,Vo,...qs,...Ks,...Zs,dr,...Ys,...Xs,...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}})),Mu=new Set(qo.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),YC=Du.map((e)=>e.id),Ko=new Set(YC);import{createRequire as rb}from"node:module";var Nu=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);import{isAbsolute as Js,join as XC,normalize as JC,sep as Zo}from"node:path";var Lu=process.platform==="win32",QC=/[*?]/;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(!Js(n))return"must be an absolute path or start with ~/";return fr(n,t)}function Jo(e,t){let n=Wu(e,t);if(n===null)return"must be a non-empty path string";if(!Js(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 eb="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",tb="cannot cover the guard's own configuration";function Wu(e,t){if(typeof e!=="string"||e.trim()==="")return null;return mr(e.trim().replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function Qo(e,t){let n=Wu(e,t);if(n===null)return"must be a non-empty path string";if(QC.test(n))return"cannot contain glob characters (* or ?); list the exact file or directory";if(!Js(n))return null;if(fr(n,t)!==null)return eb;return nb(n,t)?tb:null}function nb(e,t){let n=Yo(e),r=Yo(XC(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=JC(e);if(Lu)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(Lu?3:1)&&t.endsWith(Zo))t=t.slice(0,-1);return t}var pr=64,Gu="Rule config exceeds CC Safety Net's safe source limit.";var Fu=Object.freeze({maxSources:64,concurrency:4,maxRequests:131,maxResponseBytes:67108864});function ei(e={}){return{requests:0,responseBytes:0,maxRequests:e.maxRequests??Fu.maxRequests,maxResponseBytes:e.maxResponseBytes??Fu.maxResponseBytes}}function ti(e){return{controller:new AbortController,budget:ei(),resolveUrl:e}}function zu(e){if(e.requests>=e.maxRequests)throw Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");e.requests++}function $u(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 ob=rb(import.meta.url),Bu,ib=Array(pr+1).fill("over-limit"),Uu=/^[^/]+\/[^/]+$/,sb=/^sha256:[a-f0-9]{64}$/,ni=`must be an integer between ${Ji} and ${Qi}`,ab=["version","rules","overrides","transparent_wrappers"],lb=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Hu(e){if(!ke(e)||!Array.isArray(e.rules)||e.rules.length<=pr)return e;return{$schema:e.$schema,version:e.version,rules:ib,overrides:e.overrides,transparent_wrappers:e.transparent_wrappers}}function cb(){let e=ob("../vendor/zod.cjs"),t=(S)=>{let C=e.superRefine(S);return C._zod.def.when=()=>!0,C},n=e.enum(Nu),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,Gu).default([]).describe("Rulebook source strings such as project-rules or owner/repo#main/team-rules"),overrides:e.record(e.string().meta({pattern:Uu.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(Uu.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(Tu(x)){C.addIssue({code:"custom",message:`reserved command "${x}" cannot be a wrapper`,path:["transparent_wrappers",T]});return}P.add(x)})},l=e.preprocess(Hu,s.check(e.superRefine(a))),c=e.preprocess(Hu,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(Ji,ni).max(Qi,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(Qs(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(sb,"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 Bu??=cb(),Bu}function ju(){return Sn().RulesConfigSchema}function ub(){return Sn().UserPolicySchema}function Ak(){return Sn().LegacyConfigSchema}function Vu(){return Sn().RulebookSchema}function qu(){return Sn().RulesLockfileSchema}function Qs(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 Ku(e){let t=Sn().RulesConfigDiagnosticSchema.safeParse(e);if(t.success)return{errors:[],sources:new Set(t.data.rules)};return{errors:vn(Yu(t.error.issues,ab)),sources:pb(e,t.error.issues)}}function gr(e){let t=ub().safeParse(e);if(t.success)return[];return vn(Yu(t.error.issues,lb)," ")}function vn(e,t=": ",n=" "){return[...new Set(e.flatMap((r)=>Zu(r,t,n,[])))]}function Zu(e,t,n,r){let o=[...r,...e.path],i=fb(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)=>Zu(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}${db(e)}`]}function db(e){if(e.code==="invalid_value")return`must be ${mb(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 mb(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 fb(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function Yu(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 pb(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 Xu={version:1,rules:[],overrides:{},transparent_wrappers:[]};function gb(e){return Ku(e)}function Rn(e){try{let t=at(Ju(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=gb(n);if(r.errors.length>0)return{config:null,errors:r.errors};let o=ju().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 Mk(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??Xu}}function Nk(e,t=[]){ri(e,{version:1,rules:t,overrides:{},transparent_wrappers:[]})}function Lk(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){Rl(Ju(e),`${JSON.stringify(t,null,2)}
|
|
50
|
+
`,n,r)}function Ju(e){return typeof e==="string"?Br(e):e}import{chmodSync as hb,existsSync as ea,mkdirSync as yb,readFileSync as ta}from"node:fs";import{dirname as td,join as Cb}from"node:path";var bb=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 Cb(td(lt(e)),Vr)}function Zk(e={}){let t=xn(e);if(!ea(t))return{path:t,exists:!1,raw:"",policy:hr(),errors:[]};let n=ta(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 yb(td(n),{recursive:!0,mode:448}),ri(n,o,384),hb(n,384),{path:n,policy:o,errors:[]}}function Yk(e){let t=gr(e);if(t.length>0)return{errors:t};return{preview:Sb(En(e)),errors:[]}}function Sb(e){let t=jo({safety:od(e.safety)}),n=as({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 Xk(e={}){let t=xn(e);if(!ea(t))return oi(ii,e);let n=ta(t,"utf-8");if(!n.trim())return oi(ii,e);try{return oi(En(JSON.parse(n)),e)}catch{return oi(ii,e)}}function nd(e={}){let t=xb(xn(e));return{...t.policy,errors:t.errors,...t.fallback?{fallback:t.fallback}:{}}}function En(e){if(!Qe(e))return hr();let t=Qe(e.safety)?e.safety:{},n=Qe(t.overrides)?t.overrides:{},r=Qe(e.workflow)?e.workflow:{},o=Qe(e.destructive_command_protection)?e.destructive_command_protection:{},i=Qe(e.secret_protection)?e.secret_protection:{};return{version:1,safety:{level:bb.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:Qu(o.overrides,to),allow_paths:Rb(o.allow_paths)},secret_protection:{enabled:typeof i.enabled==="boolean"?i.enabled:!0,overrides:Qu(i.overrides,Ko),deny_paths:vb(i.deny_paths),allow_paths:Eb(i.allow_paths)},audit:{retention_days:Yr(Qe(e.audit)?e.audit.retention_days:void 0)}}}function Qu(e,t){if(!Qe(e))return{};return Object.fromEntries(Object.entries(e).flatMap(([n,r])=>t.has(n)&&(r==="on"||r==="off")?[[n,r]]:[]))}function vb(e){if(!Array.isArray(e))return[];let t=Wt();return e.filter((n)=>Jo(n,t)===null)}function Rb(e){if(!Array.isArray(e))return[];let t=Wt();return e.filter((n)=>Xo(n,t)===null)}function Eb(e){if(!Array.isArray(e))return[];let t=Wt();return e.filter((n)=>Qo(n,t)===null)}function Qe(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function hr(){return structuredClone(ii)}function xb(e){let t=wb();if(!ea(e)){let n=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!Qe(n))return{policy:t,errors:[]};return{policy:ed(En(n)),errors:[]}}try{let n=ta(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=ed(En(r));if(o.length>0)return{policy:i,errors:o.map((s)=>`${e}: ${s}`),fallback:Qe(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 rd(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...Mu].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function wb(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:rd({}),denyPaths:[],allowPaths:[]}}}function ed(e){return{safety:od(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:rd(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function od(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 id="Rulebook exceeds CC Safety Net's safe validation limits.",sd="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 ad(e){if(na(e.allowed_commands,Ge.maxAllowedCommands)||na(e.rules,Ge.maxRules)||na(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 na(e,t){return Array.isArray(e)&&e.length>t}function _b(e){if(!Pb(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!ad(e))return{errors:[id],ruleNames:new Set};let t=Vu().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),sd]:n,ruleNames:new Set(Qs(e).map((r)=>r.toLowerCase()))}}function wn(e){let t=_b(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}function Pb(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}var Ab=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#([A-Za-z0-9._-]+)$/;function si(e){if(an(e.spec))return Tb(e);return kb(e)}function kb(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 Tb(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 aT(e,t,n){let r=cd(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 ld(n,i)}function lT(e,t,n){let r=cd(e,n);if(r.length>0)return{ok:!0,specs:r};let o=Ib(e,n);if(o.length>0)return{ok:!0,specs:o};let i=Ob(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 ld(n,s)}function ld(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 cd(e,t){return e.filter((n)=>n===t)}function Ib(e,t){let n=t.match(Ab),r=n?.[1],o=n?.[2],i=n?.[3];if(!r||!o||!i)return[];return dd(e,(s)=>s.owner===r&&s.repo===o&&s.ref===i)}function Ob(e,t){if(!Tl(t))return{ok:!0,specs:[]};let[n,r]=t.split("/"),o=dd(e,(s)=>s.owner===n&&s.repo===r);if(new Set(o.map((s)=>ud(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 ud(e){try{return sn(e)}catch{return null}}function dd(e,t){return e.filter((n)=>{let r=ud(n);return r?t(r):!1})}function ra(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=qu().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 Db}from"node:crypto";import{dirname as ai,join as Mb}from"node:path";var pd=Object.freeze({timeoutMs:15000,metadataBytes:524288,commitBytes:262144,treeBytes:16777216,rawBytes:4194304});async function md(e,t,n,r=we(ai(ai(t)),"rules policy"),o=ti()){if(an(e))return Lb(e,o);return Nb(e,t,n,r)}async function RT(e,t,n,r,o,i=ti()){if(!an(e)||n.refresh)return md(e,t,n,o,i);let s=r?.rulebooks.find((a)=>a.spec===e);if(!s||s.kind!=="github")return md(e,t,n,o,i);return Wb(s,t,n,o,i)}async function ET(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 s=JSON.parse(o.content);if(!s.default_branch)throw Error(`Failed to inspect ${e}: missing default branch`);let a=await hd(n,r,s.default_branch,e,t),l=await yr(`https://api.github.com/repos/${n}/${r}/git/trees/${a}?recursive=1`,"tree",t),c=l.response;if(!c.ok)throw Error(`Failed to inspect ${e}: GitHub tree returned ${c.status}`);let m=(JSON.parse(l.content).tree??[]).flatMap((f)=>{if(f.type!=="blob"||typeof f.path!=="string")return[];let d=f.path.match(Yi);return d?.[1]?[d[1]]:[]}).sort();if(m.length===0)throw Error(`No rulebooks found in ${e} under ${jr}/`);return m.map((f)=>({spec:`${n}/${r}#${a}/${f}`,display_ref:s.default_branch}))}function Nb(e,t,n,r){Xi(e);let o=$b(t,e),i=at(ie(r,o));if(i===null)throw Error(`Rulebook source not found: ${e}`);let s=wn(oa(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 Lb(e,t){let n=sn(e),r=await hd(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(oa(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 Wb(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:gd(a,e),content:a}}return Fb(e,o)}async function Fb(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:gd(o,e),content:o}}function gd(e,t){let n=wn(oa(e,"Invalid cached rulebook."));if(n.name!==t.name)throw Error(`rulebook name "${n.name}" must match lock entry "${t.name}"`);return n}function oa(e,t){try{return JSON.parse(e)}catch{throw Error(t)}}async function hd(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(!a.sha)throw Error(`Failed to resolve commit for ${r}`);return a.sha}async function Gb(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??pd.timeoutMs);try{if(n.signal?.aborted)throw n.signal.reason;zu(r);let l=await(n.fetch??fetch)(e,{signal:o.signal,redirect:"error"});if(!l.ok)return yd(l),{response:l,content:""};return{response:l,content:await zb(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 Gb(n.resolveUrl?.(e)??e,t,{budget:n.budget,signal:n.controller.signal})}async function zb(e,t,n=ei(),r){let o=pd[`${t}Bytes`],i=Number(e.headers.get("content-length"));if(Number.isFinite(i)&&i>o)throw yd(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{$u(n,c.value.byteLength)}catch(u){throw r?.(),fd(s),u}if(l+=c.value.byteLength,l>o)throw r?.(),fd(s),Error(`GitHub ${t} response exceeds ${o} bytes`);a.push(Buffer.from(c.value))}return Buffer.concat(a,l).toString("utf-8")}function yd(e){if(!e.body)return;Cd(()=>e.body?.cancel())}function fd(e){Cd(()=>e.cancel())}function Cd(e){try{Promise.resolve(e()).catch(()=>{})}catch{}}function $b(e,t){return Mb(e,t,Hr)}function _n(e){return`sha256:${Db("sha256").update(e).digest("hex")}`}function vd(e={}){let t=Wl(e),n=!1;try{n=El(t.userConfigTarget,t.projectConfigTarget)}catch(f){if(f instanceof N)return qb(t,f.message);throw f}let r=Rn(t.userConfigTarget),o=n?{config:null,errors:[]}:Rn(t.projectConfigTarget),i=Sd(t.userConfigPath,r.errors),s=Sd(t.projectConfigPath,o.errors),a=new Set,l=r.config?ia(r.config,t.userLockPath,gt(t.userConfigPath),e,"user",t.userScope,a):Cr(),c=o.config?ia(o.config,t.projectLockPath,gt(t.projectConfigPath),e,"project",t.projectScope,a):Cr(),u=r.config?.overrides??{},m=o.config?.overrides??{};return{rules:[...bd(l.rules,u),...bd(c.rules,m)],transparent_wrappers:jb(r.config,o.config),rulebooks:[...l.rulebooks,...c.rulebooks],errors:[...i,...s,...l.errors,...c.errors],warnings:[...l.warnings,...c.warnings,...l.canValidateOverrides?sa(u,l.knownRuleIds,t.userConfigPath):[],...l.canValidateOverrides?Vb(m,l.knownRuleIds,t.projectConfigPath):[],...c.canValidateOverrides?sa(m,c.knownRuleIds,t.projectConfigPath):[]],userConfig:r.config??void 0,projectConfig:o.config??void 0,...t}}function OT(e,t){let n=t??we(gt(gt(e)),"rules policy"),r=Rn(ie(n,e)).config,o=ra(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,zl(s)]))}function DT(e,t,n,r){let o=Bb(e,t,n,r);if(!o)return[];return[...o.scope.errors,...o.scope.warnings,...Ub(o.config,o.scope,e)]}function Bb(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:ia(i,t,gt(e),n,"project",o)}}function Ub(e,t,n){return t.canValidateOverrides?sa(e.overrides??{},t.knownRuleIds,n):[]}function ia(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=ra(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=Hb(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 Hb(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 jb(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function bd(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 sa(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 Vb(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 Sd(e,t){return t.map((n)=>n.startsWith("Unable to access ")?n:`${e}: ${n}`)}function qb(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 Rd(e={}){let t=vd(e),n=nd(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}),...Xb(a.spec)?{source:a.spec}:{}}:{},...l&&typeof l==="object"?{override:Object.freeze({type:"reason",reason:l.reason})}:{}})]})));return Jb(r,Kb(t,n),i)}function WT(e){if(e.state==="ready")return{state:e.state};return{state:e.state,reason:e.reason}}function Kb(e,t){let n=Yb(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:Qb(e.errors.length>0?Zb(e.errors):void 0,e.warnings.length>0?aa(e.warnings.join("; ")):void 0,n)}}function Zb(e){return`${aa(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Yb(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 Xb(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function Jb(e,t,n=Object.freeze({})){let r=Ed(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 Ed(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))Ed(t);return Object.freeze(e)}function Qb(...e){return aa(e.filter((t)=>!!t).join("; "))}function aa(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 eS=/^[A-Za-z_][A-Za-z0-9_]*=/;function wd(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 _d(t.nodes,r,i)}function _d(e,t,n){return e.every((r)=>{if(r.kind==="connector")return!0;if(r.kind==="group"||r.kind==="function")return _d(r.body.nodes,t,n);if(r.kind==="unknown")return!n.loose.test(r.source);return tS(r,t,n)})}function tS(e,t,n){if(e.nested.some((o)=>n.loose.test(o.source)))return!1;let r=e.words.findIndex((o)=>!eS.test(o.text));return e.words.every((o,i)=>o===t||xd(o.raw,n.anchored,i!==r))&&e.redirections.every((o)=>(!o.heredoc||o.heredoc.quotedDelimiter||!n.loose.test(o.heredoc.body))&&(!o.target||xd(o.target.raw,n.anchored,!0)))}function xd(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 Pd=Object.freeze({maxDerivedTokens:16384}),Ad="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>Pd.maxDerivedTokens||!Number.isSafeInteger(t)||t<0||t>Pd.maxDerivedTokens-e.derivedTokens)throw new be;e.derivedTokens+=t}import{isAbsolute as nS,resolve as kd}from"node:path";var Td=64;function br(e,t,n){let r=nS(e)?kd(e):t?kd(t,e):void 0;if(!r)return;try{return U(r,n)}catch{return r}}function Id(e){return!["/dev","/proc","/sys"].some((t)=>e===t||e.startsWith(`${t}/`))}var B=Object.freeze({maxChildAnalyses:1024,maxDerivedTokens:16384,maxDerivedBytes:1048576,maxPlaceholderReplacements:16384}),Od="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 Dd(){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 ga,normalize as WS,parse as FS,posix as nm,resolve as Tn,sep as pa}from"node:path";import{isAbsolute as rS,join as Md,normalize as Wd,parse as oS,sep as Nd}from"node:path";var iS=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],sS=`
|
|
51
|
+
`;function Sr(e,t){if(et(e,t))return!0;if(!e.has("TMPDIR"))return!1;return!la(e.get("TMPDIR")??"",t)}function yt(e,t){if(e.has("TMPDIR"))return la(e.get("TMPDIR")??"",t);let n=ca(e,t);if(n===void 0)return!0;return la(n,t)}function ca(e,t){return zd(e,t,"TMPDIR")}function la(e,t){if(!e)return!1;if(lS(e))return!1;return ua(e,t)}function et(e,t){let n=zd(e,t,"IFS");return n!==void 0&&n!==""&&n!==sS}function ua(e,t){let n=mi(e,t.paths);return n!==null&&Gd(t).some((r)=>uS(n,r))}function Fd(e,t){let n=mi(e,t.paths);return n!==null&&Gd(t).includes(n)}var Ld=new WeakMap;function Gd(e){let t=Ld.get(e);if(t)return t;let n=aS(e);return Ld.set(e,n),n}function aS(e){let t=iS.map((r)=>mi(r,e.paths)??Wd(r)),n=mi(e.tmpdir,e.paths);if(!n)return t;if(process.platform==="win32")return[...t,n];if(process.platform==="darwin"&&cS(n))return[...t,n];return t}function lS(e){return/[\s$`*?[]/.test(e)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(e)||/[+@!]\([^)]*\)/.test(e)}function zd(e,t,n){return e.has(n)?e.get(n):t.env.get(n)}function cS(e){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(e)}function mi(e,t){try{let n=Wd(e);if(!rS(n))return n;let r=oS(n).root,o=n.slice(r.length).split(/[\\/]+/).filter(Boolean),i=r;for(let s=0;s<o.length;s++){let a=Md(i,o[s]??"");if(t.entryKind(a)==="missing")return Md(a,...o.slice(s+1));let l=t.realpath(a);if(l===null)return null;i=l}return i}catch{return null}}function uS(e,t){if(e===t)return!0;let n=t.endsWith(Nd)?t:`${t}${Nd}`;return e.startsWith(n)}import{statSync as kS}from"node:fs";import{isAbsolute as Zd,join as TS,relative as Yd}from"node:path";import{isAbsolute as $d,parse as dS}from"node:path";var Ud=/^[A-Za-z_][A-Za-z0-9_]*=/;function Te(e){if(!Ud.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 Hd(e){let t=e.toLowerCase();return e.includes("=")||t==="sudo"||t==="env"||t==="command"||t==="builtin"}function Ut(e,t,n,r){if(!Hd(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=Bd(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("=")&&!fS(i)){let g=pS(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=hS(i,t.paths,c);if(i=g.words,g.cwd!==void 0)c=g.cwd}if(p==="env"){let g=bS(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=SS(i);if(p==="builtin")i=i.slice($e(i,1)==="--"?2:1);if(Bd(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:mS(u.words,o)}}function mS(e,t){return e.some((n)=>!t.has(n))}function Bd(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 fS(e){return Ud.test(An(e))}function pS(e,t,n){if(!e.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${t.get("TMPDIR")??n.get("TMPDIR")??""}${e.slice(8)}`}}var gS=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function hS(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(gS.has(i)){r+=2;continue}r++}return{words:e.slice(r),cwd:o}}var yS=new Set(["-i","-0","--null"]),CS=new Set(["-u","--unset","-C","--chdir","-P"]);function bS(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(yS.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(CS.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&&!$d(t))return null;let r=$d(t)?dS(t).root:n.realpath(e??"/");if(r===null)return null;try{return wt(r,t,n)}catch{return null}}function SS(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 vS=/['"\\$`{}#]/;function pi(e,t){if(e.some((r)=>vS.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 RS(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(RS);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(!Hd(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 ES,isAbsolute as xS,normalize as wS,resolve as jd}from"node:path";var _S=new Set(["-S","--suffix"]);function hi(e,t,n,r){if(e.status==="structural-limit")throw new Ye;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=PS(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 Vd(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("~/")?jd(r,o.slice(2)):o;return wS(xS(i)?i:jd(t,i))}function ce(e,t,n){let r=Vd(e,t,n);if(!r)return"";return U(r,n.environment.paths,n).replace(/\\/g,"/")}function qd(e,t,n,r){let o=Vd(e,t,n);if(!o)return null;if(r(ES(o)))return U(o,n.environment.paths,n).replace(/\\/g,"/");let i=sc(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&&_S.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 PS(e,t,n,r){let o=Rr(e)?new Map([...t.variables,...AS(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 AS(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 Xd(e,t=ma(e.invocation.context.executionCwd)){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)=>MS(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)=>LS(s,a,t,n),isRedirectionTarget:(s,a)=>NS(s,a.cwd,t,n),findMalformedTarget:()=>null,normalizeCwd:ce});return i?{target:i}:null}function ma(e,t=Mt(mt())){if(typeof e!=="string"||!e)return null;let n=ar(ce(e,e,t));if(!n)return null;try{let r=ce(n,e,t),o=kS(n),i=o.isFile()?r:null,s=o.isFile()?Bs(n):null,a=(o.isDirectory()?[r]:[s?.gitDir,s?.commonDir]).flatMap((c)=>c?[tt(ce(c,e,t))]:[]),l=[...new Set(o.isDirectory()?[tt(n.replace(/\\/g,"/")),...a]:a)];return Object.freeze({entry:tt(r),markerFile:i?tt(i):null,directories:Object.freeze(l),hooksDirectories:Object.freeze([...new Set(l.flatMap((c)=>{let u=tt(TS(c,"hooks"));return[u,tt(ce(u,e,t))]}))])})}catch{return null}}function Ht(e,t,n,r,o,i=!1){if(!n)return!1;let s=tt(ce(e,t,o)),a=s.replace(/(\/\.?\*+)+$/,"");if(a!==s&&a!==""){if(da(a,n))return!0;let l=i||s.slice(a.length).includes("/."),c=(u)=>l?Ci(u,a):IS(u,a);if(n.markerFile&&c(n.markerFile))return!0;return r&&Kd(n).some(c)}if(da(s,n))return!0;return r&&Kd(n).some((l)=>Ci(l,s))}function IS(e,t){let n=Yd(t,e);if(n===""||n.startsWith("..")||Zd(n))return!1;return!n.split(/[\\/]/)[0]?.startsWith(".")}function OS(e,t,n,r){return Ht(e,t,n,!0,r)}function DS(e,t,n,r){if(!n)return!1;return da(tt(ce(e,t,r)),n)}function MS(e,t,n,r){if(!n)return!1;return Jd(e,t,n,r,n.entry)}function NS(e,t,n,r){if(!n)return!1;return Jd(e,t,n,r,n.markerFile)}function Jd(e,t,n,r,o){let i=tt(ce(e,t,r));return i===o||em(i,n)}function Qd(e,t,n,r){if(!n)return!1;return n.hooksDirectories.some((o)=>e.some((i)=>Ci(o,tt(ce(i,t,r)))))}function da(e,t){return e===t.entry||t.directories.includes(e)||em(e,t)}function em(e,t){return t.hooksDirectories.some((n)=>Ci(e,n))}function Kd(e){return[e.entry,...e.directories,...e.hooksDirectories]}function Ci(e,t){let n=Yd(t,e);return n===""||!/^\.\.(?:[\\/]|$)/.test(n)&&!Zd(n)}function tt(e){return process.platform==="win32"?e.toLowerCase():e}function LS(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)=>OS(ve(a,t.variables),t.cwd,n,r));if(s)return s;return i.destination&&DS(ve(i.destination,t.variables),t.cwd,n,r)?i.destination:null}var GS=process.platform==="win32",tm=64,zS=16384;function Er(e){let t=Lc(e,tm,tm,zS);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:$S(e)}}function $S(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)=>BS(e.raw,n.span.start-e.span.start))}function BS(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:qS(e.allowPaths,t,n,r),protectedGitMetadata:e.protectedGitMetadata,pathCanonicalizationContext:r}}function Be(e,t,n={}){let r=n.targetIsLiteral??!1;if(!r&&t.tmpdirWordSplittingUnsafe&&!n.tmpdirWordSplittingProtected&&ZS(e))return{kind:"outside_anchored_cwd"};let o=!r&&im(e,t.posixShell);if(zt(e))return{kind:"outside_anchored_cwd"};if(ha(e,r))return{kind:"root_or_home_target"};if(US(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(HS(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(KS(e,t,r))return{kind:"temp_target"};let i=t.anchoredCwd;if(i){if(!n.skipHomeCwd&&QS(i,t.environment.home,t.environment.paths,t.pathCanonicalizationContext))return{kind:"home_cwd_target"};if(!n.skipCwdSelf&&ev(e,t.resolvedCwd??i,t.environment.paths,t.pathCanonicalizationContext))return{kind:"cwd_self_target"};if(tv(e,i,t.resolvedCwd??i,o,r,t.environment.paths,t.pathCanonicalizationContext))return{kind:"within_anchored_cwd"}}return{kind:"outside_anchored_cwd"}}function rm(e,t,n={}){let{containmentTarget:r,...o}=n;if(Be(e,t,o).kind!=="temp_target")return!1;let i=e.trim();if(VS(i))return!1;if(Fd(i,t.environment))return!1;return![t.anchoredCwd,t.resolvedCwd].some((s)=>nv(r??i,s,t.environment.paths,t.pathCanonicalizationContext))}function ha(e,t=!1){let n=e.trim(),r=nm.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 US(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=ga(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===FS(s).root)return!0;return s===fe(U(t.environment.home,t.environment.paths,t.pathCanonicalizationContext))}catch{return!1}}function fe(e){let t=WS(e);if(GS){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 HS(e,t,n,r,o,i,s,a){let l=e.trim();if(om(l))return!1;if(!r&&ua(l,a))return!0;return(t||i&&s)&&n&&!o&&jS(l,n)}function jS(e,t){return["$TMPDIR","${TMPDIR}"].some((n)=>{if(e===n)return!0;if(!e.startsWith(`${n}/`))return!1;return!im(e.slice(n.length+1),t)})}function VS(e){let t=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(e);if(!t)return!1;return nm.normalize(`/${t[1]??""}`)==="/"}function om(e){return e.split(/[\\/]+/).includes("..")}function qS(e,t,n,r){if(!e?.length)return[];return e.flatMap((o)=>{let i=mr(o.trim(),t);if(!ga(i))return[];try{let s=U(i,n,r);if(fr(s,U(t,n,r)))return[];return[fe(s)]}catch{return[]}})}function KS(e,t,n){if(t.allowRoots.length===0)return!1;let r=e.trim();if(om(r))return!1;let o=n?r:mr(r,t.environment.home),i=t.resolvedCwd??t.anchoredCwd,s=ga(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(pa)?l:`${l}${pa}`))}catch{return!1}}function ZS(e){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(e)}function im(e,t=!1){return e.includes("$")||e.includes("`")||YS(e)||t&&XS(e)}function YS(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 XS(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==="{"&&JS(e,n)||(r==="+"||r==="@"||r==="!")&&e[n+1]==="(")return!0}return!1}function JS(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 QS(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 ev(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 tv(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 fa(e,t,i,s)}catch{return!1}if(e.startsWith("./")||e.startsWith(".\\")||!e.includes("/")&&!e.includes("\\"))try{return fa(Tn(a,e),t,i,s)}catch{return!1}if(e.startsWith("../"))return!1;try{return fa(Tn(a,e),t,i,s)}catch{return!1}}function fa(e,t,n,r){try{return sm(U(e,n,r),U(t,n,r))}catch{return!1}}function nv(e,t,n,r){if(!t)return!1;try{return sm(U(t,n,r),U(e,n,r))}catch{return!0}}function sm(e,t){let n=fe(e),r=fe(t);return n.startsWith(`${r}${pa}`)||n===r}var rv=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),am="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",ov="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.",lm="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",cm="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",iv="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",sv="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.";function um(e,t,n,r=jt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths})){return av(e.words.map((o)=>({kind:"word",text:o.text,dynamic:o.provenance!=="literal"})),t,r,n.policy)}function av(e,t,n,r){let o=e.filter((l)=>l.kind==="word"),i=cv(o),s=o[i];if(!s||!rv.has(Cv(s.text)))return null;let a=lv(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",sv);for(let l of a.targets)if(!zt(l.text)&&ha(Ca(l.text)))return b(a.recursive&&a.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",cm);for(let l of a.targets)if(n.resolvedCwd&&Ht(Ca(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",lm);for(let l of a.targets){let c=bv(Be(Ca(l.text),n),n,r);if(c)return c}return null}function lv(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(uv(l))continue;if(s){t.push(ya(l)),i=i||l.dynamic;continue}if(l.text==="--"){s=!0;continue}let c=mv(l.text);if(!c){t.push(ya(l)),i=i||l.dynamic;continue}if(fv(c.name)){let u=c.value?dv(c.value,l):e[++a];if(u?.kind==="word")t.push(ya(u)),i=i||u.dynamic;else i=!0;continue}if(pv(c.name)){n=!0;continue}if(gv(c.name)){r=!0;continue}if(hv(c.name))o=yv(c.value)}return{targets:t,recursive:n,force:r,whatIfProtected:o,hasDynamicTarget:i}}function cv(e){let t=e[0];if(t?.kind==="word"&&t.text==="&"||t?.text===".")return e.length>1?1:0;return 0}function ya(e){return{text:e.kind==="word"?e.text:"",dynamic:e.kind==="word"&&e.dynamic}}function uv(e){return e.kind==="word"&&e.text===","}function Ca(e){let t=e.replace(/\\/g,"/"),n=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(t);return n?`$HOME${t.slice(n[0].length)}`:t}function dv(e,t){return{kind:"word",text:e,dynamic:t.kind==="word"&&(t.dynamic||e.includes("$"))}}function mv(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 fv(e){return"path".startsWith(e)||"literalpath".startsWith(e)}function pv(e){return"recurse".startsWith(e)}function gv(e){return e.length>=2&&"force".startsWith(e)}function hv(e){return e==="wi"||"whatif".startsWith(e)}function yv(e){if(e===void 0||e==="")return!0;let t=e.toLowerCase();return t==="$true"||t==="true"}function Cv(e){return e.toLowerCase()}function bv(e,t,n){switch(e.kind){case"root_or_home_target":return b("powershell.remove-item-recursive-force-root-or-home",cm);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",lm);case"home_cwd_target":return b("powershell.remove-item-recursive-force-home-cwd",iv);case"cwd_self_target":return b("powershell.remove-item-recursive-force-cwd-self",am);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",ov);case"outside_anchored_cwd":return b("powershell.remove-item-recursive-force-outside-cwd",am)}}import{normalize as Ti}from"node:path";function Ue(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;ba(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])ba(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(vv(u)){ba(a),yield*bi([...u.slice(1)],t,m,r,o,i,s,a,l);return}yield Sv(u,m,r,o,i,l)}function Sv(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 ba(e){if(e.iterations>=un)throw new be;e.iterations++}function vv(e){return M(e[0]??"").toLowerCase()==="busybox"&&e.length>1}function Sa(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 He(e){let t=!1,n=!1;for(let r of e){if(r==="--")break;if(r==="-r"||r==="-R"||va(r,"recursive"))t=!0;else if(r==="-f"||va(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 dm(e){let t=e.indexOf("--");return e.slice(1,t===-1?void 0:t).some((n)=>va(n,"recursive")||/^-[A-Za-z]+$/.test(n)&&/[rR]/.test(n.slice(1)))}function va(e,t){return e.length>2&&e.startsWith("--")&&t.startsWith(e.slice(2))}var Rv="find -delete permanently removes files. Use -print first to preview.",Ev="find -exec rm -rf is dangerous. Use explicit file list instead.",xv=new Set(["-exec","-execdir","-ok","-okdir"]),wv=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=_v(e,n,t);if(r)return r;if(Ri(n,1)&&!Av(e,n,t)){let s=k(b("find.delete",Rv),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=Tv(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 _v(e,t,n){if(!Ri(t,1)&&!Ra(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=Be(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(Pv(t)&&i.resolvedCwd&&Qd(o.map(I),i.resolvedCwd,i.protectedGitMetadata,i.pathCanonicalizationContext))return b("find.delete-git-metadata",Ie);return null}function Ra(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 Pv(e){return e.some((t,n)=>{if(!["-name","-iname"].includes(t))return!1;return e[n+1]?.toLowerCase()==="hooks"})}function Av(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=ca(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??et(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)=>rm(m,l,{containmentTarget:kv(m,i),targetIsLiteral:u.expandedTargets!==void 0||u.targetIsLiteral,tmpdirWordSplittingProtected:u.tmpdirWordSplittingProtected}))})}function kv(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 Tv(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"&&He(n))return b("find.exec-rm-recursive-force",Ev);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 wv.get(e)??(/^-newer[A-Za-z]{2}$/.test(e)?1:0)}function Ct(e){return e!==void 0&&xv.has(e)}function*Ea(e){for(let t of e.nodes)yield*Ov(t)}function Iv(e){return Object.freeze([...Ea(e)])}function QI(e){return Object.freeze(Iv(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*Ov(e){if(e.kind==="command"){yield e;for(let t of e.nested)yield*Ea(t);return}if(e.kind==="group")yield*Ea(e.body)}var Dv=5,xa="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 fm(e,t,n){let r=gm(e,t,n),o=Mv(r.entries);if(o.size===0)return{blockedReason:r.blockedReason,expanded:!1,tokens:e};let i=e,s=!1;for(let a=0;a<Dv;a++){let{subcommand:l,rest:c}=je(i),u=l?.toLowerCase();if(!u||!o.has(u))return{blockedReason:r.blockedReason,expanded:s,tokens:i};let m=o.get(u),f=Gv(m);if(f===null||f.length===0)return{blockedReason:xa,expanded:!0,tokens:i};i=["git",...f,...c],s=!0}return{blockedReason:xa,expanded:!0,tokens:i}}function pm(e,t,n){return gm(e,t,n).entries.some((r)=>r.key.toLowerCase()==="core.sshcommand")}function je(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(Je.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 Mv(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 gm(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=Lv(t,n);return{blockedReason:i.blockedReason,entries:[...i.entries,...Nv(e,t,n)]}}function Nv(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=wa(e[o+1]);if(s)r.push(s);o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=wa(i.slice(2));if(s)r.push(s);o++;continue}if(i==="--config-env"){let s=mm(e[o+1],t,n);if(s)r.push(s);o+=2;continue}if(i.startsWith("--config-env=")){let s=mm(i.slice(13),t,n);if(s)r.push(s);o++;continue}if(Je.has(i)){o+=2;continue}o++}return r}function Lv(e,t){let n=Wv(e,t),r=Fv(e,t);return{blockedReason:n===null||r===null?xa:null,entries:[...n??[],...r??[]]}}function Wv(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=wa(i);if(!s)return null;r.push(s)}return r}function Fv(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 wa(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 mm(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 Gv(e){let t=e?.trimStart();if(!t||t.startsWith("!"))return null;return wr(t)}var zv="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",$v="git checkout --force discards uncommitted changes. Use 'git stash' first.",Bv="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",Uv="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",Hv="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",jv="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",Vv="git switch --force discards uncommitted changes. Use 'git stash' first.",qv="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",Kv="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",Zv="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",Yv="git reset --merge can lose uncommitted changes. Use 'git stash' first.",Xv="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",Jv="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.",Qv="git push --force destroys remote history. Use --force-with-lease for safer force push.",eR="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",tR="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",nR="git branch -D force-deletes without merge check. Use -d for safe delete.",rR="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",oR="git merge --abort discards merge conflict resolutions. Use 'git status' first.",iR="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",sR="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",aR="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",lR="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",cR="git worktree remove --force can delete uncommitted changes. Remove --force flag.",hm=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),ym=new Set(["--recurse-submodules","--track","-t"]),_a=new Set(["-b","-B","-U"]),Pa=new Set(["-c","-C"]),uR=new Set(["--source","--conflict","--unified","--inter-hunk-context"]),dR=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 bm(e){let{subcommand:t,rest:n}=je(e);if(!t)return null;switch(t.toLowerCase()){case"checkout":return At(mR(n));case"switch":return At(fR(n));case"restore":return At(gR(n));case"reset":return yR(n);case"clean":return At(bR(n));case"rm":return At(SR(n));case"push":return Vt(vR(n));case"branch":return Vt(xR(n));case"stash":return Vt(kR(n));case"worktree":return Vt(TR(n));case"rebase":return At(wR(n));case"merge":return At(_R(n));case"tag":return Vt(PR(n));case"reflog":return Vt(AR(n));default:return null}}function At(e){return e?{...e,localDiscard:!0}:null}function Vt(e){return e?{...e,localDiscard:!1}:null}function mR(e){let{index:t,before:n}=ue(e),r=me(n,{shortOptsWithValue:_a});if(n.some((i)=>W(i,"--force"))||r.has("-f"))return b("git.checkout-force",$v);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",Uv)}if(t!==-1){if(n.some((s)=>!s.startsWith("-")))return b("git.checkout-ref-path",Bv);return b("git.checkout-double-dash",zv)}if(pR(e).length>=2)return b("git.checkout-ambiguous",Hv);return null}function fR(e){let{before:t}=ue(e);if(t.some((r)=>W(r,"--discard-changes")))return b("git.switch-discard-changes",jv);let n=me(t,{shortOptsWithValue:Pa});if(t.some((r)=>W(r,"--force"))||n.has("-f"))return b("git.switch-force",Vv);return null}function pR(e){let t=[],n=0;while(n<e.length){let r=e[n];if(!r)break;if(r==="--")break;if(r.startsWith("-"))if(hm.has(r))n+=2;else if(r.startsWith("--")&&r.includes("="))n++;else if(ym.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("--")&&!dR.has(r)&&!hm.has(r)&&!ym.has(r))n++;else n++;else t.push(r),n++}return t}function gR(e){let t=hR(e);if(t.isTerminal||!t.hasPathspec&&!t.hasPatch||!t.hasWorktree)return null;return t.hasExplicitLocation?b("git.restore-worktree",Kv):b("git.restore-unstaged",qv)}function hR(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(uR.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 yR(e){let t=null;for(let n of e){if(W(n,"--hard")){t=b("git.reset-hard",Zv);break}if(W(n,"--merge")){t=b("git.reset-merge",Yv);break}}if(!t)return null;return CR(e)?Vt(t):At(t)}function CR(e){for(let t of e){if(t==="--")return!1;if(!t.startsWith("-"))return!0}return!1}function bR(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",Xv);return null}function SR(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",Jv):null}function vR(e){let{before:t,after:n}=ue(e),r=me(t);if(t.some((s)=>W(s,"--mirror")))return b("git.push-mirror",tR);if(t.some((s)=>W(s,"--force"))||r.has("-f")||Cm(t,n).some(RR))return b("git.push-force",Qv);if(t.some((s)=>W(s,"--delete"))||r.has("-d")||Cm(t,n).some(ER))return b("git.push-delete",eR);return null}function Cm(e,t){return[...e.filter((n)=>n!==""&&!n.startsWith("-")),...t]}function RR(e){return e.startsWith("+")||e.includes(":+")}function ER(e){return e.length>1&&e.startsWith(":")}function xR(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",nR);return null}function wR(e){let{before:t}=ue(e);return t.some((n)=>W(n,"--abort"))?b("git.rebase-abort",rR):null}function _R(e){let{before:t}=ue(e);return t.some((n)=>W(n,"--abort"))?b("git.merge-abort",oR):null}function PR(e){let{before:t}=ue(e);return me(t).has("-d")||t.some((r)=>W(r,"--delete"))?b("git.tag-delete",iR):null}function AR(e){return e[0]==="delete"?b("git.reflog-delete",sR):null}function kR(e){for(let t of e){if(t==="drop")return b("git.stash-drop",aR);if(t==="clear")return b("git.stash-clear",lR)}return null}function TR(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",cR);return null}import{execFileSync as IR}from"node:child_process";import{existsSync as ka,readFileSync as Ta}from"node:fs";import{dirname as OR,isAbsolute as Rm,join as Aa,resolve as Em}from"node:path";var DR=["/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 xm(e,t,n,r){let o=MR(e,t,n);if(o!==null)return o;let i=NR(t,n);if(i!==null)return i;if(uu(n))return!0;return LR(r)}function MR(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=Sm(e[o+1]);if(s!==null)r=s;o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=Sm(i.slice(2));if(s!==null)r=s;o++;continue}if(i==="--config-env"){let s=vm(e[o+1],t,n);if(s!==null)r=s;o+=2;continue}if(i.startsWith("--config-env=")){let s=vm(i.slice(13),t,n);if(s!==null)r=s;o++;continue}if(Je.has(i))o+=2;else o++}return r}function NR(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(Ia(a))return!0;if(a!=="submodule.recurse")continue;r=_r(s)}return r}function LR(e,t=FR()){let n=WR(e);if(n===null||n)return!0;if(t===null)return!0;try{let r=IR(t,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:GR(process.env),stdio:["ignore","pipe","ignore"]}).trim();return _r(r)}catch(r){return!zR(r)}}function WR(e){let t=$R(e);if(t===null)return null;for(let n of t){if(!ka(n))continue;if(HR(n))return!0}return!1}function FR(){for(let e of DR)if(ka(e))return e;return null}function GR(e){let t={...e};for(let n of Object.keys(t))if(or(n))delete t[n];return t}function zR(e){return typeof e==="object"&&e!==null&&"status"in e&&e.status===1}function $R(e){let t=ar(e);if(t===null)return null;let n=BR(t);if(n===null)return null;let r=UR(n);if(r===null)return null;return[Aa(r,"config"),Aa(n,"config.worktree")]}function BR(e){try{let n=Ta(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 Rm(r)?r:Em(OR(e),r)}catch{return null}}function UR(e){let t=Aa(e,"commondir");if(!ka(t))return e;try{let n=Ta(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(n==="")return null;return Rm(n)?n:Em(e,n)}catch{return null}}function HR(e){let t;try{t=Ta(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(jR(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=_r(c)}return r}function jR(e){return e==="include"||e.startsWith("includeif ")}function Sm(e){if(!e)return null;let t=e.indexOf("="),n=(t===-1?e:e.slice(0,t)).toLowerCase();if(Ia(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 vm(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;let o=e.slice(0,r).toLowerCase();if(Ia(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 Ia(e){return e==="include.path"||e.startsWith("includeif.")&&e.endsWith(".path")}function wm(e,t,n){if(!t.localDiscard||!n.worktreeMode||pu(n.env,n.envAssignments))return null;let r=gu(e,n.cwd);if(!r.gitCwd||r.hasExplicitGitContext)return null;if(!hu(r.gitCwd))return null;if(VR(e,n,r.gitCwd))return null;return{originalReason:t.reason,gitCwd:r.gitCwd}}function VR(e,t,n){let{subcommand:r,rest:o}=je(e),i=r?.toLowerCase();if(t.dynamicArguments||qR(o)||xm(e,t.env,t.envAssignments,n)||YR(o)||KR(i,o))return!0;return i==="clean"&&XR(o)>1}function qR(e){return e.some((t)=>/[$*?[]/.test(t))}function KR(e,t){if(e==="checkout"){let{before:n}=ue(t),r=me(n,{shortOptsWithValue:_a}),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:Pa}),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")||ZR(s))||r.has("-C");return o&&i}return!1}function ZR(e){let t=e.split("=",1)[0]??e;return t==="--force-create"||t.length>=9&&"--force-create".startsWith(t)}function YR(e){return e.some((t)=>t.startsWith("--recurse-sub"))}function XR(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 JR="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.",QR=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function On(e,t){return _m(e.map(I),t)}function _m(e,t,n){let r=fm(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((cu(t.envAssignments)||pm(e,t.env,t.envAssignments))&&eE(i))return b("git.ssh-env",JR);let s=bm(i);if(!s)return null;if(r.expanded||r.blockedReason)return s;let a=wm(e,s,t);if(!a)return s;return n?.(a),null}function Pm(e,t){let n=null;return{match:_m(e.map(I),t,(o)=>{n=o}),relaxation:n}}function eE(e){let{subcommand:t,rest:n}=je(e),r=t?.toLowerCase();if(!r)return!1;if(QR.has(r))return!0;if(r==="archive")return ue(n).before.some((o)=>W(o,"--remote"));return r==="remote"&&tE(n)}function tE(e){return e.find((t)=>!nE(t))?.toLowerCase()==="update"}function nE(e){return e==="-v"||W(e,"--verbose")||W(e,"--no-verbose")}import{isAbsolute as VE}from"node:path";var Am="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",rE="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.",oE="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",Tm="rm -rf targeting root or home directory is extremely dangerous and always blocked.",iE="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=He(r),i=dm(r),s=aE(e);for(let a of s){let l=Er(a.word);if(o&&l.unsafeBraceExpansion){let c=k(km({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=Be(c,n,u);if(m.kind==="root_or_home_target")return b("rm.recursive-force-root-or-home",Tm);if(m.kind==="git_metadata_target")return b("rm.git-metadata",Ie);continue}if(!o)continue;for(let m of sE(c,n,u)){let f=km(m,n,t.policy),d=k(f,t.policy);if(d)return d}}}return null}function sE(e,t,n){let r=Be(e,t,n);if(r.kind==="cwd_self_target")return[r,Be(e,t,{...n,skipCwdSelf:!0})];if(r.kind!=="home_cwd_target")return[r];let o=Be(e,t,{...n,skipHomeCwd:!0});if(o.kind!=="cwd_self_target")return[r,o];return[r,o,Be(e,t,{...n,skipHomeCwd:!0,skipCwdSelf:!0})]}function aE(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 km(e,t,n){switch(e.kind){case"root_or_home_target":return b("rm.recursive-force-root-or-home",Tm);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",oE);case"home_cwd_target":return b("rm.recursive-force-home-cwd",iE);case"cwd_self_target":return b("rm.recursive-force-cwd-self",Am);case"within_anchored_cwd":if(Q(n,"rm.recursive-force-paranoid",t.paranoid))return b("rm.recursive-force-paranoid",rE);return null;case"outside_anchored_cwd":return b("rm.recursive-force-outside-cwd",Am)}}var lE={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Om=new Set(["--init-file","--rcfile"]),cE=["--init-file","--rcfile"],uE=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 Im(e,t,!0);if(n.startsWith("-")&&n.includes("c")&&!n.startsWith("--")){let r=Im(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 Im(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 Dm(e){let t=M(e[0]??"").toLowerCase(),n=dE(e,t),r=uE.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 dE(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?cE.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"&&Om.has(m)&&!l.includes("="))a++;continue}if(t==="bash")s=!1;let c=Mm(t,l,e[a+1],"startup");if(c.interactive)i=l[0]==="-";a+=c.followingValues}return{argvSource:o.at(-1)??null,interactive:i}}function Mm(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(!lE[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"&&Om.has(l)&&!s.includes("="))i++;continue}let a=Mm(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"},mE=new Set(["<","<<","<<-","<<<","<&","<>"]),Lm=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,fE=/^(?:[0-9]+|[@*])$/,pE=Ft.maxWords,gE=Ft.maxInputLength;function Wm(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 Fm(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=yE(e);if(n===-1)return kt;let r=CE(t);if(!r)return kt;let o=[],i=r.command?.length??0;for(let s of r.references){let a=SE(s,e,n,r.ifs);if(!a)return qt;if(i+=a.reduce((l,c)=>l+c.length+3,0),o.length+a.length>pE||i>gE)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(RE)].filter((s)=>s!==null).join(" ")}}function Gm(e,t,n,r){if(!rt(e.map(I)).readsStdinAsCommands)return kt;let o=t.filter((i)=>(i.fd===void 0||i.fd===0)&&mE.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 hE=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function Na(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!hE.has(a)&&!ee.has(a)&&!Bt(a)}function yE(e){return rt(e.map(I)).commandIndex??-1}function CE(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(bE);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 bE(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 SE(e,t,n,r){let o=t.slice(n+2);if(e.parameter==="@")return e.quoted?Oa(o):vE(o,r);if(e.parameter==="*"){let a=Oa(o);if(!a)return;let l=a.join(r[0]??"");return e.quoted?[l]:Da(l,r)}let i=t[n+1+e.parameter];if(i&&!xi(i))return;let s=Pr(i);return e.quoted?[s]:Da(s,r)}function Oa(e){return e.every(xi)?e.map(I):void 0}function vE(e,t){let n=Oa(e);if(!n)return;let r=n.map((o)=>Da(o,t));return r.some((o)=>o===void 0)?void 0:r.flatMap((o)=>o??[])}function Da(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 RE(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function La(e,t){return Ma(Le(e,"posix"),t)}function Nn(e){return La(e,new Set(Array.from(e.matchAll(Lm)).flatMap((t)=>{let n=t[1]??t[2];return n===void 0?[]:[n]})))}function Ma(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(Ma(r.body,n))return!0;continue}if(r.kind!=="command")continue;if(r.nested.some((o)=>Ma(o,n))||zm(r.words,n))return!0;PE(r,n)}return!1}function zm(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 Nm(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&&Nm(s[l],t)}let i=EE(e,n,t);if(i===null)return!1;if(i===-1)return!0;return zm(e.slice(i),t)}function EE(e,t,n){let r=z(e[t]?.text??"");if(r==="command")return xE(e,t+1);if(r==="exec")return wE(e,t+1);if(r==="env")return _E(e,t+1,n);return null}function xE(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 wE(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 _E(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 PE(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(Lm)).some((r)=>{let o=r[1]??r[2];return o!==void 0&&(fE.test(o)||t.has(o))}))}function Nm(e,t){return!!e&&(e.parts.some((n)=>n.provenance!=="literal"&&n.provenance!=="variable")||Ar(e,t))}var AE=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--config-env"]),kE=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),TE=new Set;function $m(e){if(e==="git")return AE;if(e==="docker")return kE;return TE}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(!IE(n,o.command))continue;if(!OE(n,e,o.subcommand))continue;if(ME(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 IE(e,t){return e===z(t)}function OE(e,t,n){if(!n)return!0;return Bm(t,1,n,$m(e))}function Bm(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("=")&&DE(e,i,n,r))return!0;continue}return s===n}return!1}function DE(e,t,n,r){let o=e[t+1];if(!o||o.startsWith("-"))return!1;return Bm(e,t+2,n,r)}function ME(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"&&(He(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:et(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?NE(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 NE(e,t){return e.dynamicInput&&e.rmDynamicMatch?k(e.rmDynamicMatch,t.policy):null}var Wa="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",Fa="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",LE="__CC_SAFETY_NET_XARGS_INPUT__",wi="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",_i="rm",WE=/(?:^|[;&|]\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,FE=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,GE=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,zE=/^(?:[0-9]+|[@*])$/;function jm(e,t){let n=e.map(I),{childStart:r,replacementToken:o}=Kt(n),i=n.slice(r),s=b("xargs.shell-dynamic",Fa);if(BE(i,o,t)&&k(s,t.policy))return k(s,t.policy);for(let a of Ue(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=Zm(l,o,a.wrapperEnvAssignments),m=a.head==="rm"&&o!==null&&qm(l,o),f=Tt(l,{...t,cwd:a.cwd,envAssignments:a.envAssignments},{dynamicInput:u,dynamicSourceInput:m||Vm(l,a.head,o,a.wrapperEnvAssignments,u,t.scanWork,t.environment),dynamicRmInput:m,shellDynamicMatch:s,dynamicSourceMatch:s,rmDynamicMatch:b("xargs.rm-recursive-force-dynamic",Wa)});if(f)return f;let d=$E(l,o,t.policy?.rules??[]);if(d)return d;if(a.head==="git"){let g=o===null?[...l,LE]: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 $E(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)=>Ga(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 Ga(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 Vm(e,t,n,r,o,i,s){if(ee.has(t)){if(Oe(e))return!1;if(n!==null&&UE(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 HE(a,n,r)}if(Ce(t))return Um(e,n,zo,Pu(t));if(ye.has(t))return Um(e,n,Ms,ou);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 jE(e,n,i,s);if(t==="git"){let a=je(e);return n===null?a.subcommand===null:(a.subcommand?.includes(n)??!1)||a.subcommand!==null&&In.has(a.subcommand.toLowerCase())&&Km(a.rest,n).some((l)=>l.includes(n))}return!1}function Um(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)=>Ga(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 BE(e,t,n){if(e.length===0||(e[0]??"").toLowerCase()==="command")return!1;let r=new Set(Array.from(Ue(e,n),(i)=>i.head)),o=t===null?[...e,_i]:e.map((i,s)=>s===0?i:i.replaceAll(t,_i));return Array.from(Ue(o,n)).some((i)=>i.head===_i&&!r.has(_i))}function qm(e,t){return Km(e.slice(1),t).some((n)=>n.includes(t)&&(n.startsWith("-")||n.startsWith(t)))}function Km(e,t){let n=e.findIndex((r)=>r==="--"&&!r.includes(t));return n===-1?e:e.slice(0,n)}function Zm(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 UE(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 Ga(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 HE(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(WE))if(Hm(o,r))return!0;for(let o of e.matchAll(FE))for(let i of(o[1]??"").matchAll(GE))if(Hm(i,r))return!0;return La(e,r)}function Hm(e,t){let n=e[1]??e[2];return n!==void 0&&(zE.test(n)||t.has(n))}function jE(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 Ue(c.tokens,{environment:r,cwd:void 0})){let m=Zm(u.tokens,t,u.wrapperEnvAssignments);if(u.head==="rm"&&qm(u.tokens,t)||Vm(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.",qE="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",KE="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",ZE=/\{[^{}\s]*\}/,rf=/\{\}|\{-?\d+\}/g,YE=["e","f","source","file","-e","-f","--source","--file"],XE=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],JE=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),QE=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),Ym=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),ex=new Set(["--workdir","--wd"]),Xm="__CC_SAFETY_NET_PARALLEL_SOURCE__",tx=new TextEncoder,$a=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 of(e,t){return pe([...e],(n)=>ht(n,t.scanWork))}function sf(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=gf(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=of(t.envAssignments?.values()??[],t);if(g)return g}if(l){let p=cx(t);if(p)return p}if(u!==void 0&&a){let p=Yt(t);if(p)return p}let f=fx(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([...Ue(i,d)].flatMap((g)=>[...g.envAssignments.values()]).some(ja)){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,Ba(p));let g=df(d.envAssignments,d.cwd,a);return pe(p,(y)=>t.analyzeNested(y,g))}return pe(Ue(i,d),(p)=>nx(p,o,t,d))}function nx(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(ff)){let h=Yt(n);if(h)return h}let m=of(u,n);if(m)return m;let f=u.some(H),d=i||f,p=a&&d,g=df(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(pf(R)){let C=Zt(n);if(C)return C;if(o.length===0)return null;return Se(n.budget,nf(R,o)),pe(o,(P)=>n.analyzeNested(It(R,P),g))}if(H(R)){if(o.length>0)return Se(n.budget,nf(R,o)),pe(o,(x)=>n.analyzeNested(It(R,x),g));Se(n.budget,ef(R));let C=wr(R);if(C?.[0]&&z(C[0])==="rm"&&He(C)){let x=Qm(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,Ba(_)),pe(_,(C)=>n.analyzeNested(C,g));if(Se(n.budget,ef(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,Ba(S)),pe(S,(C)=>n.analyzeNested(C,g))}if(d||a)return Zt(n)??h();return null}if(e.head==="rm"&&He(l)){if(i&&o.length>0)return Se(n.budget,Pi(l,o,"rm")),pe(o,(R)=>za(l.map((E)=>Ua(E,R)),e.cwd,r));if(o.length>0)return Se(n.budget,tf(l,o)),pe(o,(R)=>za([...l,...R],e.cwd,r));let h=za(l.flatMap((R,E)=>{if(E===0||!H(R))return[R];return R.startsWith("-")?[Ua(R,[""])]:[]}),e.cwd,r);if(h)return h;return Qm(n)}Se(n.budget,i&&o.length>0?Pi(l,o,"generic"):o.length>0?tf(l,o):uf(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"?lx(R,r):null,_=lf(R,a,n.policy?.rules??[],n.budget)??A?.customResult??null,S=z(e.head),C=a&&(S==="rm"&&Ha(R)||S==="xargs"&&cf(R)||A?.rmOptions===!0),P=a&&(C||A?.executedSource===!0||A===null&&af(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 af(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 ix(e);if(t==="git")return rx(e);if(t==="find")return!0;if(ye.has(t))return Jm(e,YE,rr);if(Ce(t))return Jm(e,XE,Go);return!1}function Ha(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("-")||pf(o)))}function rx(e){if(ox(e))return!0;let t=je(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 ox(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 ix(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 Jm(e,t,n){let r=n(e);if(r.some((i)=>H(i.value)))return!0;if(!e.some(H))return n([...e,Xm]).some((i)=>i.value===Xm);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 lf(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,sx(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?ax(e,l):[]));return pe(a,(l)=>re(e.map((c)=>It(c,[l])),[s]))})}function sx(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 ax(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 lx(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 Ue(i,t))n.executedSource||=af(a.tokens,a.head),n.rmOptions||=a.head==="rm"&&Ha(a.tokens)||a.head==="xargs"&&cf(a.tokens),n.customResult??=lf(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 cf(e){let t=e.slice(Kt(e).childStart);return z(t[0]??"")==="rm"&&Ha(t)}function Ai(e,t){return(n)=>k(b(e,t),n.policy)}var Zt=Ai("parallel.shell-dynamic",Ir),cx=Ai("parallel.command-stream-dynamic",qE),Yt=Ai("parallel.command-stream-dynamic",KE),Qm=Ai("parallel.rm-recursive-force-dynamic",Tr);function za(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:et(n.envAssignments??new Map,n.environment),trustedTmpdirValue:yt(n.envAssignments??new Map,n.environment),protectedGitMetadata:n.protectedGitMetadata,policy:n.policy}),n.policy)}function Ba(e){return{childAnalyses:e.length,derivedTokens:e.length,derivedBytes:Or(e)}}function ef(e){return uf([e])}function uf(e){return{childAnalyses:1,derivedTokens:e.length,derivedBytes:Or(e)}}function tf(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 nf(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=mx(e.map((l)=>dx(l,n))),i=Xt(o.occurrences,t.length,B.maxPlaceholderReplacements);if(i>B.maxPlaceholderReplacements)return{childAnalyses:t.length,derivedTokens:r,placeholderReplacements:i};if(ux(o,t,i))return{childAnalyses:t.length,derivedTokens:r,derivedBytes:B.maxDerivedBytes+1,placeholderReplacements:i};let s=n==="generic"?It:Ua,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 ux(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 dx(e,t){let n=t==="generic"?e.matchAll(/\{[^{}\s]*\}/g):e.matchAll(rf),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))],$a),r++,i=s.index+s[0].length}return{occurrences:r,fixedBytes:r===0?kr(e):De([o,kr(e.slice(i))],$a)}}function mx(e){return{occurrences:De(e.map((t)=>t.occurrences),B.maxPlaceholderReplacements),fixedBytes:De(e.map((t)=>t.fixedBytes),$a)}}function Or(e,t=B.maxDerivedBytes){return De(e.map(kr),t)}function kr(e){return tx.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 df(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)=>mf(n,t))}function Ua(e,t){return e.replace(rf,(n)=>mf(n,t))}function mf(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 ZE.test(e)}function ff(e){if(ja(e))return!0;for(let t of e.matchAll(/\{[^{}\s]*\}/g))if(!/^(?:\{\}|\{-?\d+\})$/.test(t[0]))return!0;return!1}function ja(e){let t=e.indexOf("{=");return t!==-1&&e.indexOf("=}",t+2)!==-1}function pf(e){return/^\{[^{}\s]*\}$/.test(e)}function gf(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=Sa(e,t+1);n.push(...E.templateTokens),r=t+1,o=E.markerIndex;break}if(!p.startsWith("-")){let E=Sa(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"||QE.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(Ym.has(h)||p.startsWith("-S")&&p.length>2){i=!0,t+=Ym.has(p)?2:1;continue}if(ex.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(JE.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?ja:ff);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=px(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 fx(e,t,n){if(e===void 0)return;if(e==="..."||/[{}$`*?~[]/.test(e))return null;if(!t&&!VE(e))return null;try{return wt(t??e,e,n)}catch{return null}}function px(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 hf(e){return gf(e).childStart}var gx="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 qa(e){return e?.parts.some((t)=>t.provenance==="command-substitution")??!1}function Va(e){return e?.parts.some((t)=>t.provenance==="literal"&&t.raw.replace(/^["']/,"").startsWith("-"))??!1}function Cf(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",gx):null;return k(a,i)??bf(e,t,n,o,i)}function bf(e,t,n,r,o){if(t.length<2)return null;let i=t.flatMap((a,l)=>qa(a)?[l]:[]);if(i.length===0)return null;let s=z(t[0]?.text??"");if(s==="git"){let a=Pn(e,t),l=yx(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)&&Cx(t)?k(b("shell.dynamic-structure",ki),o):null;if(s==="rm"){let a=t.findIndex((c,u)=>u>0&&I(c)==="--"),l=He(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 yf(e,t.slice(Kt(t.map(I)).childStart),"xargs",n,r,o);if(s==="parallel")return yf(e,t.slice(hf(t.map(I))),"parallel",n,r,o);return null}function yf(e,t,n,r,o,i){if(t.length===0)return null;let s=hx(t,r);if(Jn(e,s)){let l=k(b(`${n}.shell-dynamic`,n==="xargs"?Fa:Ir),i);if(l)return l}let a=bf(e,s,r,o,i);if(a)return a;if(s[0]?.text==="rm"&&s.slice(1).some((l)=>qa(l)&&Va(l)))return k(b(`${n}.rm-recursive-force-dynamic`,n==="xargs"?Wa:Tr),i);return null}function hx(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 yx(e){let t=1;while(t<e.length){let n=e[t],r=n?I(n):"";if(Je.has(r)){t+=2;continue}if(r.startsWith("-")){t++;continue}return t}return t}function Cx(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=qa(s);if(n>0){n--;continue}if(o){if(s.text===";"||s.text==="+"){o=!1,t=!0,r=!1;continue}if(a&&(r||Va(s)))return!0;r=!1;continue}if(!t&&!s.text.startsWith("-")){if(a&&(i>1||Va(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 Ka(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 bx="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",Sx="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",vx="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function Sf(e,t){let n=t.slice(1);if(e==="dd"&&n.some((r)=>/^of=\/dev\/.+/.test(r)))return b("dd.device-write",bx);if((e==="mkfs"||e.startsWith("mkfs."))&&n.some((r)=>r.startsWith("/dev/")))return b("mkfs.device",Sx);if(e==="shred"&&n.length>0)return b("shred.target",vx);return null}var Rf=[{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:et(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,Za(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:et(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)=>jm(e.words,{...vf(e),analyzeNested:(t,n)=>Jt(e.options.analyzeNested(t,n))})},{heads:new Set(["parallel"]),analyze:(e)=>sf(e.words,{...vf(e),budget:e.options.parallelBudget,analyzeNested:(t,n)=>Jt(e.options.analyzeNested(t,n))})}];function vf(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 Za(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 _f="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function Pf(e){return Rf.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=Cf(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]){Ef(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"?Fm(f):void 0;if(P?.kind==="dynamic"&&(n.strict||!n.commandView||!Na(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(kf(y,h)){if(Oe(d))return null;let w=Rx(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 $i=rn.kind==="literal"?rn.source:L,gl=Ex($i);r?.recordSegment({type:"shell-wrapper",wrapper:h,innerCommand:gl}),r?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:gl,depth:t+1});let hl=n.analyzeNested($i,{effectiveCwd:A,envAssignments:g});if(hl)return hl;return Nn($i)?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=Gm(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||!Na(n.commandView))return Re(r)}if(ye.has(h)){if(n.strict&&Ka(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&&Ka(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 Ef(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(Sf(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=Pf(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"?Pm(O.words,Za(O)):void 0,oe=xf(F?F.match:D?.(O)??null,n.policy);if(r)xx(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=xf(wx(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 Rx(e,t,n,r,o,i){let s=Dm(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 Ex(e){let t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.at(-1)===t?e.slice(1,-1):e}function xx(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 Ef(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:_f}),st(Af())}function Af(){return{id:"",reason:_f,intent:"stop_and_explain"}}function kf(e,t){return ee.has(t)||e==="$SHELL"||e==="${SHELL}"||ee.has(M(t))}function wx(e,t,n){let r=Ue(t.slice(n),{environment:e.options.environment,cwd:e.cwd,envAssignments:e.envAssignments,policy:e.options.policy});for(let o of r){let i=_x(e,n,o);if(i)return i}return null}function _x(e,t,n){let r=n.tokens[0];if(!r)return null;let o=z(r);if(kf(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 Af();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=Pf(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 xf(e,t){return e?.id.startsWith("custom.")||e?.id==="raw-text.dangerous-command"?e:k(e,t)}var Px=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,Ax=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function kx(e,t){let n=Of(e,t);if(n.length===0)return!1;let r=n[If(n)];if(r==="cd"||r==="pushd"||r==="popd")return!0;return Px.test(e.join(" "))}function Tf(e,t,n,r){if(e.dialect==="powershell"){let a=Tx(e.words,r);if(a.kind==="none")return;if(!t||a.kind==="unknown")return null;return wf(Mx(a.target),t,n.paths)}let o=e.words.map(I);if(!kx(o,n))return;if(!t)return null;let i=Of(o,n,t),s=If(i);if(s===-1||i[s]!=="cd")return null;return wf(i[s+1],t,n.paths)}function wf(e,t,n){if(!e||e==="-"||e.includes("$")||e.includes("`"))return null;try{return Nx(wt(t,e,n),t,n)?t:null}catch{return null}}function Tx(e,t){let n=Ix(e[0])?1:0,r=e[n];if(!Ox(r,n===1))return{kind:"none"};let o=r.text.toLowerCase(),i=o.split(/[\\/]/).pop()??o;if(!Ax.has(i))return{kind:"none"};if(o!==i||i==="pop-location"||i==="popd")return{kind:"unknown"};return Dx(e.slice(n+1),t)}function Ix(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&(e.text==="&"||e.text===".")}function Ox(e,t){return e?.provenance==="literal"&&(t||!e.quoted&&e.raw===e.text)}function Dx(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 Mx(e){return e.includes("::")?void 0:e.replaceAll("\\","/")}function If(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 Of(e,t,n){let r=Lx(e);return kn([...r],t,n)}function Nx(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 Lx(e){let t=0;while(t<e.length){let n=e[t];if(n==="{"||n==="("||n==="$(")t++;else break}return e.slice(t)}var Xa="TMPDIR",Ja="IFS",Df=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Mf=/^[A-Za-z_][A-Za-z0-9_]*$/,Nf=new Set(["export","typeset","declare","readonly"]),Wx=new Set(["builtin","command","time"]);function Lf(e,t){return{env:e,effectiveEnvAssignments:Bx(e,t),shellAssignments:new Map}}function Wf(e){return{env:e.env,effectiveEnvAssignments:e.effectiveEnvAssignments?new Map(e.effectiveEnvAssignments):void 0,shellAssignments:new Map(e.shellAssignments)}}function Qa(e,t){let n=Gf(e,t);n.assignments.filter((s)=>s.persists).forEach((s)=>{t.shellAssignments.set(s.name,s.value),el(t,s)});let r=n.commandIndex;if(r!==-1&&Nf.has(e[r]??""))e.filter((s)=>Mf.test(s)&&Ya(s)).forEach((s)=>{Ux(t,s)});let o=r===-1?-1:zf(e,r);if(o===-1||e[o]!=="unset")return;let i=jx(e,o);if(i===null)return;e.slice(i).forEach((s)=>{Hx(t,s)})}function Ff(e,t){let n=Gf(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 Gf(e,t){let n=e.findIndex((s)=>!Fx(s)),r=n!==-1&&Nf.has(e[zf(e,n)]??""),o=$x(t);return{assignments:e.flatMap((s,a)=>{let l=Gx(s,o,t.env);if(!l)return[];if(n!==-1&&a>n&&!r&&!Ws(l.name))return[];return o.set(l.name,l.value),[{...l,persists:n===-1||r}]}),commandIndex:n}}function zf(e,t){let n=t;while(Wx.has(e[n]??"")){n+=1;while(e[n]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(e[n]??""))return t;n+=1}}return n}function Fx(e){return Te(e)!==null||Df.test(e)}function Gx(e,t,n){return Te(e)??zx(e,t,n)}function zx(e,t,n){let r=To(e,n,t);if(r)return r;let o=e.match(Df)?.[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 Ya(e){return e===Xa||e===Ja||Fs(e)}function $x(e){return new Map([...e.effectiveEnvAssignments??[],...e.shellAssignments])}function Bx(e,t){let n=[...Ao,Xa,Ja].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 el(e,t){let n=new Map(e.effectiveEnvAssignments??[]);n.set(t.name,t.value),e.effectiveEnvAssignments=n}function Ux(e,t){el(e,{name:t,value:e.shellAssignments.get(t)??e.effectiveEnvAssignments?.get(t)??e.env.get(t)??""})}function Hx(e,t){if(!Ya(t)&&!Mf.test(t))return;if(e.shellAssignments.set(t,""),!Ya(t)||t===Xa||t===Ja||or(t)){el(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 jx(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 Vx="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.",qx=64;function il(e,t,n,r){let o=n.derivedCommandWorkBudget===void 0,i=n.parallelBudget===void 0;try{return Kx(e,t,{...n,derivedCommandWorkBudget:n.derivedCommandWorkBudget??ci(),parallelBudget:n.parallelBudget??Dd()},r)}catch(s){let a=s instanceof be&&o?Ad:s instanceof di&&i?Od: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 Kx(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 ol(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 Vf(e,n),{reason:Et,segment:e,intent:"stop_and_explain"}}if(n.strict&&o.status==="partial")return Vf(e,n),{reason:Et,segment:e,intent:"stop_and_explain"};if(o.issues.some((c)=>c.code.includes("quote"))&&!n.analyzePartialProgram)return ol(e,n);let s=n.cwd,a=n.effectiveCwd!==void 0?n.effectiveCwd:n.cwd,l=Lf(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=Zx(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),tl(O,[D],f,m==="&",Wn(m))}),T=nl(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(...tl(D,F.states,f,m==="&",Wn(m))),R)T.push(D,...f?F.states.map((oe)=>Di(D,oe)):F.states)}let O=nl(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"?Wm(A)??Xx(A):void 0,S=[],C=[];for(let x of g){let T=Jx(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=tw(c,t,n.trace?{...n,trace:qf(n.trace,E)}:n,r,F,Li(a),_);if(oe)return{result:oe,states:i};let xe=pw(c,F.functionDefinitions);if(xe)ze(n.derivedCommandWorkBudget,Wi(xe));let w=xe?t+1>=ro?rl(c.displayText,n,[F]):Ni(xe,t+1,n,r,[F]):{result:null,states:[F]};if(w.result)return w;if(S.push(...tl(x,w.states,f,m==="&",Wn(m))),R)C.push(x),C.push(...w.states.map((L)=>f?Di(x,L):L))}}let P=nl(S,C,y,h,a,m);i=P.states,s=P.conditionalStates,a=void 0}return{result:null,states:i}}function Zx(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"&&Yx(e,t)}function tl(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 Yx(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(Qx(n))return!0;return n.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function Li(e){return e==="|"||e==="|&"}function Xx(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 nl(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 qf(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 Jx(e,t,n,r,o){let i=e.nested.map((s)=>({program:s,depth:t}));if(e.dialect==="powershell"){let s=ew(e);if(s){if(t+1>=ro)return rl(s,n,o);let a=Le(s,"powershell");if(a.status==="limited")return rl(s,n,o);if(a.status!=="complete")return $f(i,n,r,o);ze(n.derivedCommandWorkBudget,Wi(a)),i.push({program:a,depth:t+1})}}return $f(i,n,r,o)}function Qx(e){let t=e.words[0];return t?.provenance==="variable"&&e.words.at(-1)?.text==="="?t.text.toLowerCase():void 0}function $f(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 ew(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 rl(e,t,n){return t.trace?.recordSegment({type:"error",message:ut}),{result:{reason:ut,segment:e,intent:"stop_and_explain"},states:[...n]}}function tw(e,t,n,r,o,i,s){let a=lw(e);if(a&&n.strict)return n.trace?.recordSegment({type:"error",message:a}),{reason:a,segment:e.source,intent:"stop_and_explain"};Kf(e,o,"before-consumer",n.environment.paths);let l=Pn(e.dialect,e.words).map(I),c=e.displayText,u=Ff(l,o.shellGitContextState);if(e.dialect==="powershell"){let d=k(um(e,i,hw(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 gw(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&&wd(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=Bf(e,a,o,u,s,n);if(g)return g;return Qa(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=il(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?qf(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=Bf(e,a,o,u,s,n);if(f)return f;return Qa(l,o.shellGitContextState),null}function Bf(e,t,n,r,o,i){let s=cw(e,t,n,r??new Map,i);if(s)return s;return Kf(e,n,"after-consumer",i.environment.paths),n.literalHeredocFiles.clear(),ow(e,t,n,i.environment.paths),mw(e,n,o,i.environment,i.trace),null}var nw=new Set([">>","<>"]);function Kf(e,t,n,r){for(let i of e.redirections){if(!(n==="before-consumer"?rw(i):nw.has(i.operator)))continue;Uf(i.target,t,r)}if(n!=="before-consumer"||!Ee(e.words[0],"tee"))return;let o=Zf(e.words.slice(1));if(!o)return;for(let i of o.operands)Uf(i,t,r)}function rw(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 Uf(e,t,n){let r=e?.provenance==="literal"?br(e.text,t.effectiveCwd,n):void 0;if(!r)return;t.literalHeredocFiles.delete(r)}function ow(e,t,n,r){if(t)return;let o=e.redirections.find((i)=>i.operator==="<<"||i.operator==="<<-")?.heredoc;if(!o?.quotedDelimiter)return;for(let i of iw(e)){let s=br(i.text,n.effectiveCwd,r);if(!s||!Id(s))continue;if(!n.literalHeredocFiles.has(s)&&n.literalHeredocFiles.size>=Td)throw new be;n.literalHeredocFiles.set(s,o.body)}}function iw(e){let t=aw(e.redirections)?.target,n=Hf(t)?[t]:[];if(Ee(e.words[0],"cat"))return sw(e.words)?n:[];if(!Ee(e.words[0],"tee"))return[];let r=Zf(e.words.slice(1));if(!r||r.append||r.hasUnsupportedOptions||!r.operands.every(Hf))return[];return[...r.operands,...n]}function sw(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 aw(e){let t=e.findLast((n)=>(n.fd??([">",">|",">>",">&"].includes(n.operator)?1:0))===1);return t?.operator===">"||t?.operator===">|"?t:void 0}function Zf(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 Hf(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 lw(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(!n.heredoc.quotedDelimiter)return Vx;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&&jf(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(jf)?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 jf(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}function cw(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(dw(e,i,n,r,o))return null;let a=uw(e,i,o);if(a!==void 0)return a?{reason:a.reason,segment:e.displayText,ruleId:a.id,intent:a.intent}:null;let l=ol(s.length===i.length?s.join(`
|
|
59
|
+
`):e.source,o);return l?{...l,segment:e.displayText}:null}function uw(e,t,n){let r=t.length===1?t[0]:void 0;if(!r?.heredoc?.quotedDelimiter||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 dw(e,t,n,r,o){let i=t.length===1?t[0]:void 0;if(!i?.heredoc?.quotedDelimiter||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 mw(e,t,n,r,o){let i=Tf(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:Wf(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)=>fw(r,n)))t.push(n);if(t.length>qx)throw new be}return t}function fw(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 pw(e,t){let n=vo(e);return n===void 0?void 0:t.get(n)}function gw(e,t){if(!t)return null;return{reason:t.reason,segment:e,ruleId:t.id,intent:t.intent}}function hw(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 ol(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 Vf(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 Yf(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:sl(t.fail_closed,e.strict,"strict"),paranoid_rm:sl(t.paranoid_rm,e.paranoidRm,"paranoidRm"),paranoid_interpreters:sl(t.paranoid_interpreters,e.paranoidInterpreters,"paranoidInterpreters")};return{policy:lc(e.policySnapshot.policy,i),effectiveCapabilities:i,effectiveLevel:Hs({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}function sl(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 CN(e,t){return al(e,t)}function al(e,t,n,r){let o=il(e,0,{...t,...Yf(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 yw,dirname as ll}from"node:path";var ep="This path contains the protected policy config and you must not modify or delete it.",Cw=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function tp(e){let t=Mt(mt()),n=xw(e.invocation.context.executionCwd,t);if(e.invocation.route.kind==="patch")return Xf(e.paths,!1,e.invocation.context.executionCwd,n,t);let r=ge(e,"input-candidate");if(e.invocation.route.kind==="command")return r?Jf(r.shell,e.invocation.context.executionCwd,n,t):null;if(e.invocation.route.kind==="unknown"&&r){let o=Jf(r.shell,e.invocation.context.executionCwd,n,t);if(o)return o}return Xf(e.paths,e.invocation.route.kind==="grep"||e.invocation.route.kind==="glob"||so(e.invocation.toolName),e.invocation.context.executionCwd,n,t)}function Xf(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 Jf(e,t,n,r){let o=hi(e,t,r,{findSegmentTarget:(i,s)=>bw(i,s,n,r)?.target??null,isRedirectionTarget:(i,s)=>Lr(i,s.cwd,n,r),findMalformedTarget:(i)=>Ew(i,t,n,r)?.target??null,normalizeCwd:ce});return o?{target:o}:null}function bw(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"&&Sw(a)){let l=vw(a).find((c)=>Qf(ve(c,t.variables),t.cwd,n,r));if(l)return{target:l}}if(s==="find"){if(Ri(i,1)||Ra(i,o)){let c=(vi(G(i))??G(["."])).find((u)=>{let m=ve(u.text,t.variables);return Lr(m,t.cwd,n,r)||Qf(m,t.cwd,n,r)})?.text;if(c)return{target:c}}}if(s==="mv"){let l=yi(a).sources.find((c)=>ww(ve(c,t.variables),t.cwd,n,r));if(l)return{target:l}}if(Rw(e,o))return null;for(let l of[...e,...i])for(let c of np(l))if(Lr(ve(c,t.variables),t.cwd,n,r))return{target:c};return null}function Sw(e){return e.some((t)=>t==="--recursive"||t.startsWith("-")&&!t.startsWith("--")&&/[rR]/.test(t.slice(1)))}function vw(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 Rw(e,t){let n=_t([...e],t);if(n.length===0)return!1;let r=M(n[0]??"").toLowerCase();if(!Cw.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 Ew(e,t,n,r){for(let o of e.split(/\s+/))for(let i of np(o))if(Lr(i,t,n,r))return{target:i};return null}function np(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.indexOf("=");return n===-1||n===t.length-1?[t]:[t,t.slice(n+1)]}function xw(e,t){let n=ce(xn(),e,t),r=ll(n),o=new Set;for(let i=r;;i=ll(i))if(o.add(Fn(i)),ll(i)===i)break;return{file:Fn(n),directoryAndAncestors:o}}function Lr(e,t,n,r){let o=qd(e,t,r,(i)=>Fn(i)===yw(n.file));return o!==null&&Fn(o)===n.file}function Qf(e,t,n,r){return n.directoryAndAncestors.has(Fn(ce(e,t,r)))}function ww(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 ul}from"node:os";import{isAbsolute as Fi,posix as _w,resolve as zi,win32 as Pw}from"node:path";import{fileURLToPath as Aw}from"node:url";var fp="Access to a sensitive path is not allowed.",pp=new Set(["echo","printf"]),kw=new Set(["find"]),Tw=new Set(["-exec","-execdir"]),Iw=new Set([";","+"]),Ow=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),Dw=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Mw=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),Nw=new Set(["node","bun"]),Lw=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),Ww=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"]),gp=new Set(["-c","-e","-r","-E","--eval","--exec"]),Fw=new Set(["src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js"]),rp=new Set(["cc-safety-net","ccsn"]),Gw=new Set(["bunx","npx","pnpx"]),zw=new Set(["bun","node"]),$w=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"])]]),Bw=new Set(["grep","rg"]),op="f",ip="file",Uw="files",Hw=new Set(["e","f"]),jw=new Set(["regexp","file"]),Vw=new Set(["e","f","A","B","C","m"]),qw=new Set(["regexp","file","after-context","before-context","context","max-count"]),Kw=new Set(["|","|&"]),cl="__CC_SAFETY_NET_PIPE_INPUT__",hp=new Set(["bash","sh","zsh","dash","ksh"]),Zw=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 sp(e,t,n,r,o){let i=Vn();for(let s of e){if(L_(s,t,n?.denyPaths??[],r,i))return{target:s,ruleId:"secret.deny-path"};if(o&&!o.has(s))continue;let a=M_(s,t,n,i);if(a){if(!a.startsWith("secret.cli.")&&W_(s,t,n?.allowPaths??[],r,i))continue;return{target:s,ruleId:a}}}return null}function yp(e,t,n={}){let r=ap(e),o=sp(r,e.invocation.context.executionCwd,t,e.invocation.context.configCwd),i=o?.ruleId!=="secret.deny-path"&&n.strict===!1?ap(e,{refineJavaScriptInlineData:!0}):r,s=i.length===r.length?o:sp(r,e.invocation.context.executionCwd,t,e.invocation.context.configCwd,new Set(i));if(s?.ruleId!=="secret.deny-path"&&n.strict===!1&&Yw(e))return null;return s}function Yw(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(Xe(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)=>Ow.has(s))}function ap(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 Ye;if(e.status==="unclosed-quote")return[];if(e.status==="invalid")throw Error("Unable to parse command for secret protection");let r=[...e.assignmentFallbacks,...h_(Xe(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(...Gi(o,t,n)),i!==null)r.push(...cp(i,o,t,n));i=Kw.has(s.operator)?o:null,o=[]}else i=null;continue}if(s.kind==="redirection"){let a=s.target?Xe(s.target):void 0;if(a&&s.targetOrder==="legacy-segment")o.push(a);else if(a)r.push(a);continue}o.push(Xe(s.text))}if(o.length>0){if(r.push(...Gi(o,t,n)),i!==null)r.push(...cp(i,o,t,n))}return r}function Gi(e,t,n){let r=s_(e),o=Gn(e);if(o.length===0)return r;let i=o[0]??"",s=tn(i).toLowerCase(),a=o.slice(1),l=Jw(i,s,a);if(l)return[...r,...l];if(pp.has(s))return r;if(Bw.has(s))return[...r,...x_(a)];if(kw.has(s))return[...r,...a_(a,t,n)];if(ye.has(s))return[...r,...a.flatMap((c)=>up("awk",c)),...a.flatMap((c)=>c_(c,t,n)),...a.flatMap(u_)];if(Sp(s)){if(hp.has(s)){let c=Au(s,a);if(c!==null&&t.getShellSyntax(c).status==="structural-limit")throw new Ye}return[...r,...l_(s,a,n)]}return[...r,...a.flatMap((c)=>up(s,c))]}function Xw(e,t){if(rp.has(e))return t[0]==="explain"?0:null;if(Gw.has(e)){let n=t[0]==="-y"||t[0]==="--yes"?1:0;return rp.has(t[n]??"")&&t[n+1]==="explain"?n+1:null}if(zw.has(e)){if(lp(t[0])&&t[1]==="explain")return 1;if(e==="bun"&&t[0]==="run"&&lp(t[1])&&t[2]==="explain")return 2}return null}function Jw(e,t,n){let r=Xw(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 lp(e){let t=e?.replaceAll("\\","/");return[...Fw].some((n)=>t===n||t?.endsWith(`/${n}`))}function cp(e,t,n,r){if(r_(t,n,r))return Qw(e);let o=o_(t);if(o===null)return[];return e_(e).flatMap((i)=>hp.has(o)?Gr(n.getShellSyntax(i),n,r):Rp(i))}function Qw(e){let t=Gn(e);if(t.length===0)return[];let n=tn(t[0]??"").toLowerCase();if(!pp.has(n))return[];return t.slice(1)}function e_(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 t_(r);return[]}function t_(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[Cp(t)];let r=e.slice(1);return Array.from({length:Math.ceil(r.length/n)},(o,i)=>n_(t,r.slice(i*n,(i+1)*n)))}function n_(e,t){let n=0;return Cp(e.replace(/%%|%[bqs]/g,(r)=>{if(r==="%%")return"%";let o=t[n]??"";return n++,o}))}function Cp(e){return e.replace(/\\n/g,`
|
|
60
|
+
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function r_(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,cl]:i.map((l)=>l.split(s).join(cl));return Gi(a,t,n).some((l)=>l.includes(cl))}function o_(e){let t=Gn(e);if(t.length===0)return null;let n=tn(t[0]??"").toLowerCase();if(!Sp(n))return null;return i_(n,t.slice(1))?n:null}function i_(e,t){let n=bp(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(gp.has(o)||vp(e,o)||/^--(?:eval|exec)=/.test(o))return!1;if(o==="-")return!0;if(o.startsWith("-")){if(n==="python"&&o==="-m")return!1;if(Zw.get(n)?.has(o))r++;continue}return!1}return!0}function bp(e){return/^python\d/.test(e)?"python":e}function s_(e){let t=[];for(let n of e){if(wp(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 up(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 a_(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(!Tw.has(e[i]??""))continue;let s=e.slice(i+1),a=s.findIndex((u)=>Iw.has(u)),l=a===-1?s:s.slice(0,a),c=Gi(l,t,n);if(o.push(...c.filter((u)=>u!=="{}")),!c.includes("{}"))continue;o.push(...e.slice(0,i).flatMap((u,m,f)=>{if(!Dw.has(u))return[];let d=f[m+1];return d===void 0?[]:[d,d.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return o}function Sp(e){return Mw.has(e)||/^python\d/.test(e)}function l_(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o];if(i===void 0)break;if(gp.has(i)||vp(e,i)){let a=t[o+1];if(a!==void 0)r.push(...dp(e,a,n)),o++;continue}let s=/^--(?:eval|exec)=(.*)$/.exec(i);if(s!==null&&s[1]!==void 0){r.push(...dp(e,s[1],n));continue}if(!i.startsWith("-"))r.push(i)}return r}function vp(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<=2)return!1;return $w.get(t[t.length-1]??"")?.has(bp(e))??!1}function c_(e,t,n){if(!e.includes("system"))return[];return Ns(e)?.commands.flatMap((r)=>Gr(t.getShellSyntax(r),t,n))??[]}function u_(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 Rp(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(Ep),...n]}function dp(e,t,n){let r=Rp(t);if(!n.refineJavaScriptInlineData||!Nw.has(e)||r.length===0)return r;let o=d_(t);return o!==null&&!f_(o)?[]:r}function d_(e){let t=e.split("");for(let n=0;n<e.length;n++){let r=e[n];if(r!=="'"&&r!=='"'&&r!=="`")continue;if(r==="`"&&m_(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 m_(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 f_(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(Lw.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)=>Ww.has(i)))continue;if(o.length>1)return!0;if(p_(e,r)===".")return!0;if(g_(e,r+n.length)==="(")return!0}return!1}function p_(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function g_(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function h_(e,t,n){return v_(e).flatMap((r)=>{let o=t.getShellSyntax(r);if(o.status==="invalid")return[];return[...Gr(o,t,n),...y_(o)?C_(o):[]]})}function y_(e){let t=e.entries;for(let n=0;n<t.length;n++){let r=t[n];if(r?.kind!=="word"||tn(Xe(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=Xe(i.text);if(s==="--decode"||!s.startsWith("--")&&s.startsWith("-")&&/[dD]/.test(s))return!0}}return!1}function C_(e){return e.entries.flatMap((t)=>t.kind==="word"?[Xe(t.text)]:t.kind==="redirection"&&t.target?[Xe(t.target)]:[]).flatMap(Ep)}function Ep(e){let t=S_(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||b_(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function b_(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function S_(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 v_(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(xp(e,r,n)){let i=R_(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=E_(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function R_(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(xp(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 E_(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 xp(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function x_(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===Uw)o=!0;if(jw.has(m))r=!0;if(f!==void 0){if(m===ip)t.push(f);continue}if(qw.has(m)){let d=e[l+1];if(m===ip&&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(Hw.has(g))r=!0;if(Vw.has(g)){f=g,d=m.slice(p+1);break}}if(f!=="")if(d.length>0){if(f===op)t.push(d)}else{let p=e[l+1];if(f===op&&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)=>!wp(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:[...e.slice(t)]}function wp(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var w_=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),__=".env.",P_=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),A_=[".env.example.",".env.sample."];function k_(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function T_(e){return e.length>0&&!/\s/.test(e)}function I_(e,t,n){try{let r=zr(e,t,n);return r!==""&&Pe.entryKind(r)!=="missing"}catch(r){if(r instanceof se)throw r;return!1}}var O_=new Set(["node_modules","__pycache__"]),D_=[["vendor","bundle"],["vendor","cache"]];function M_(e,t,n,r){if(k_(e))return null;let o=St(e,t,r);if(!o)return null;let i=K(o.split("/").pop()??""),s=K(o),a=()=>T_(i)||I_(e,t,r);if(P_.has(i)||A_.some((m)=>i.startsWith(m)))return null;let l=K(z_(e,t,r));for(let m of qs){let f=`~/${m.suffixParts.join("/")}`;if((mp(s,f)||mp(l,f))&&bt(m.id,n))return m.id}let c=N_(o,t,n,r);if(c)return c;if(w_.has(i))return null;for(let m of Vs)if(i===m.basename&&bt(m.id,n))return m.id;if(i.startsWith(__)&&bt(Vo.id,n)&&a())return Vo.id;for(let m of Ks)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 Zs)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(F_(s))return null;if(!i.includes(".")&&dr.pattern.test(i)&&bt(dr.id,n))return dr.id;let u=G_(i,n);if(u)return u;return null}function N_(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,ae(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?[ae(Y(process.env.ProgramData,"",t,r),"gemini-cli")]:[];return q(e,ae(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=ae(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):ae(Y(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"opencode"),s=process.env.ProgramData?[ae(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[ae(Y(process.env.XDG_DATA_HOME,"~/.local/share",t,r),"amp"),ae(i,".local","share","amp")].some((a)=>q(e,a,["secrets.json"]))||Wr(e,ae(i,".amp"),["oauth"])}case"secret.cli.amp.config":{let i=["settings.json","settings.jsonc"],s=[ae(Y(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"amp"),ae(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=ae(Y(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"cursor"),s=ae(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)=>_p(e,ae(t,r)))}function Wr(e,t,n){return n.some((r)=>en(K(e),K(ae(t,r))))}function Fr(e,t,n,r){return _p(e,St(t,n,r))}function _p(e,t){return K(e)===K(t)}function ae(e,...t){return Ve([e,...t].filter(Boolean).join("/"))}function L_(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 W_(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??ul(),a=s?Ve(U(s,Pe,o)):"",l=K(a),c=process.env.CC_SAFETY_NET_HOME,u=K(c?Ve(U(zi(c),Pe,o)):a&&Ve(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 F_(e){let t=e.split("/");return t.some((n)=>O_.has(n))||D_.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function G_(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 Ys)if(r===o.extension&&bt(o.id,t))return o.id;for(let o of Xs)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}=dl(e,n);if(!o)return"";if(!r)return o;let i=ml(o,r),s=Fi(i)?i:Ve(zi(t,i)),a=Ve(U(s,Pe,n));if(!en(a,r)){if(Fi(i))return a;return a===s?o:a}let l=a.slice(r.length);return l?`~${l}`:"~"}function mp(e,t){return e===t||e.startsWith(`${t}/`)}function z_(e,t,n){let{home:r,normalized:o}=dl(e,n);if(!o||!r)return"";let i=ml(o,r),s=_w.normalize(Fi(i)?i:Ve(zi(t,i))),a=Ve(process.env.HOME??ul()),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}=dl(e,n);if(!o)return"";let i=r?ml(o,r):o;return Ve(U(Fi(i)?i:zi(t,i),Pe,n))}function dl(e,t){let n=process.env.HOME??ul(),r=n?Ve(U(n,Pe,t)):"",o=Ve($_(Xe(e)));return{home:r,normalized:o}}function $_(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return Aw(e)}catch{return e}}function ml(e,t){if(e==="~")return t;if(e.startsWith("~/"))return ae(t,e.slice(2));return e}function B_(e){if(process.platform==="win32")return!0;return Pw.parse(e).root.length>1}function Ve(e){let t=e.trim(),n=(B_(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 U_={findPolicyMutation:tp,findGitMetadataMutation:Xd,resolveGitMetadata:ma,loadPolicySnapshot:Rd,findSensitiveTarget:yp,analyzeCommand:al,getModes:jo};function Pp(e,t={}){let n={...U_,...t.dependencies},r=V_(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:tc,intent:"stop_and_explain",evidence:[]}};let a=nn("policy-protection",o,()=>n.resolveGitMetadata(e.context.executionCwd)),l=nn("policy-protection",o,()=>n.findPolicyMutation(i));if(l){let y=o??l.target;return{stage:"policy-protection",decision:{kind:"deny",reason:ep,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,...H_(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:fp,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{...fl("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},j_(i),i.store));if(g)return{stage:"command-analysis",...d,decision:g};return{stage:"command-analysis",...d,decision:{kind:"allow"}}}function H_(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function j_(e){return ge(e,"declared-command")?.program}function V_(e){try{return Zn(e.input)}catch(t){let n=$r(e)?e.command:void 0;throw new zn("policy-protection",fl("policy-protection",t instanceof dt?void 0:n,t),t)}}function nn(e,t,n){try{return n()}catch(r){throw new zn(e,fl(e,r instanceof dt?void 0:t,r),r)}}function fl(e,t,n){let r=n instanceof se||n instanceof Ye;return{stage:e,decision:{kind:"deny",reason:r?nc:Jr,intent:"stop_and_explain",evidence:t?[{kind:"command",command:t,segment:t}]:[]}}}function $r(e){return e.route.kind==="command"}import{realpathSync as q_,statSync as K_}from"node:fs";import{isAbsolute as Ap,relative as Z_,resolve as Y_,sep as X_}from"node:path";function J_(e,t){if(zt(e))return;let n=t.flatMap((o)=>pl(o));if(!n[0])return;let r=pl(Ap(e)?e:Y_(n[0],e))[0];if(!r)return;return n.some((o)=>kp(r,o))?r:void 0}function Q_(e){return e.flatMap((t)=>pl(t))[0]}function pl(e){try{let t=q_(e);return K_(t).isDirectory()?[t]:[]}catch{return[]}}function kp(e,t){let n=Z_(t,e);return n===""||n!==".."&&!n.startsWith(`..${X_}`)&&!Ap(n)}function fL(e,t){try{let n=Pp(e,t.guard);return Tp(e,n,t),n}catch(n){if(!(n instanceof zn))throw n;throw Tp(e,n.evaluation,t,!(n.cause instanceof dt),{stage:n.stage,errorCode:eP(n.cause)}),n}}function Tp(e,t,n,r=!0,o){ec(Ql(e,t,n.guard?.auditAllowed??!1,r,o),n.audit.getSessionId,{agent:n.audit.agent,shape:n.audit.shape,homeDir:n.audit.homeDir})}function eP(e){if(e instanceof se)return"path-canonicalization-limit";if(e instanceof dt)return"tool-input-limit";if(e instanceof Ye)return"structural-shell-syntax-limit";return"unexpected-error"}
|
|
62
|
+
export{Zl as b,Rg as c,AP as d,kP as e,TP as f,N as g,ie as h,Br as i,at as j,Rl as k,El as l,oP as m,iP as n,sP as o,aP as p,$p as q,_e as r,Hr as s,jr as t,Tl as u,Ne as v,Nl as w,Ll as x,gP as y,Dt as z,hP as A,yP as B,Wl as C,CP as D,zl as E,qr as F,bP as G,Kr as H,yg as I,ql as J,Xl as K,Fg as L,$P as M,KP as N,ZP as O,YP as P,XP as Q,se as R,Vn as S,U as T,Pe as U,mt as V,no as W,as as X,Nt as Y,dt as Z,nh as _,Zn as $,ds as aa,ms as ba,Ye as ca,xo as da,py as ea,Ie as fa,Xd as ga,ma as ha,Tu as ia,QI as ja,ne as ka,jC as la,VC as ma,jo as na,bn as oa,js as pa,ck as qa,Yf as ra,CN as sa,al as ta,Iu as ua,pr as va,Gu as wa,Fu as xa,ti as ya,Du as za,Ak as Aa,Qs as Ba,gr as Ca,vn as Da,gb as Ea,Rn as Fa,Mk as Ga,Nk as Ha,Lk as Ia,ri as Ja,ii as Ka,xn as La,Zk as Ma,oi as Na,Yk as Oa,Sb as Pa,Xk as Qa,En as Ra,rd as Sa,od as Ta,ep as Ua,tp as Va,fp as Wa,yp as Xa,wn as Ya,aT as Za,lT as _a,ra as $a,RT as ab,ET as bb,vd as cb,OT as db,DT as eb,ia as fb,Rd as gb,WT as hb,Jb as ib,zn as jb,J_ as kb,Q_ as lb,kp as mb,fL as nb};
|