cc-safety-net 2.3.3 → 2.3.4

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.
@@ -0,0 +1,46 @@
1
+ import{accessSync as ag,constants as xc,realpathSync as lg,statSync as Ec}from"node:fs";import{isAbsolute as _c,relative as cg,resolve as ug,sep as dg}from"node:path";import{dirname as eg,isAbsolute as tg,parse as ng,sep as rg}from"node:path";function Ir(A,T=process.platform){if(T!=="win32")return!1;return(A[0]==="/"||A[0]==="\\")&&(A[1]==="/"||A[1]==="\\")}function gr(A,T,F){if(Ir(T))throw Error("Unsupported Windows namespace path");let j=tg(T)?ig(T):"",q=j||A;for(let K of sg(j?T.slice(j.length):T)){if(K===""||K===".")continue;if(K===".."){q=eg(q);continue}let ee=og(q,K),te=F.entryKind(ee),ce=te==="symlink"?F.realpath(ee):ee;if(te==="missing"||ce===null)throw Error(`Cannot resolve path component: ${ee}`);q=ce}return q}function og(A,T){return A.endsWith("/")||A.endsWith("\\")?`${A}${T}`:`${A}${rg}${T}`}function ig(A){return ng(A).root}function sg(A){let T=process.platform==="win32"?/[\\/]+/:/\/+/;return A.split(T)}function Se(A){try{if(!Ec(A).isDirectory())return!1;return ag(A,xc.R_OK|xc.X_OK),!0}catch{return!1}}function O(A,T){if(Ir(A))return;let F=T.flatMap((q)=>oa(q));if(!F[0])return;let j=oa(_c(A)?A:ug(F[0],A))[0];if(!j)return;return F.some((q)=>ct(j,q))?j:void 0}function N(A){return A.flatMap((T)=>oa(T))[0]}function oa(A){try{let T=lg(A);return Ec(T).isDirectory()?[T]:[]}catch{return[]}}function ct(A,T){let F=cg(T,A);return F===""||F!==".."&&!F.startsWith(`..${dg}`)&&!_c(F)}var hr="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",sr="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",Pc="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.",wc="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",he="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";function c(A,T,F,j,q){if(F.kind!=="command")return{toolName:A,input:T,route:F,context:j};return{toolName:A,input:T,route:F,context:j,command:q}}function e(A){return A.provenance==="command-substitution"?A.raw:A.text}function oe(A,T){return A==="posix"?T:Yt(T.map((F)=>F.text))}function vi(A,T){return A&&A.provenance!=="unknown"?A.provenance==="literal":!/[$`*?[\]]/.test(T)}function Yt(A){return A.map((T)=>({kind:"word",text:T,raw:T,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}import{existsSync as la,lstatSync as Cg,readFileSync as _i,realpathSync as Po,statSync as _o}from"node:fs";import{dirname as ca,isAbsolute as ua,join as Pi,resolve as wi}from"node:path";import{lstatSync as mg,realpathSync as fg}from"node:fs";import{homedir as pg,tmpdir as gg}from"node:os";var m={realpath:(A)=>{try{return fg(A)}catch{return null}},entryKind:(A)=>{let T=mg(A,{throwIfNoEntry:!1});if(!T)return"missing";return T.isSymbolicLink()?"symlink":"present"}};function Pn(A,T=process.platform){if(T!=="win32")return A;return A.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function kr(){return Pn(process.env.HOME||pg())}function L(){return{env:new Map(Object.entries(process.env).flatMap(([A,T])=>T===void 0?[]:[[A,T]])),home:kr(),tmpdir:gg(),paths:m}}var ia=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],hg=new Set(ia);var Ac=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),Ri=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),yg=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function sa(A){return hg.has(A)}function Eo(A){return A==="GIT_CONFIG_COUNT"||A==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(A)}function aa(A){return sa(A)||Ac.has(A)||Ri.has(A)||Eo(A)}function Nn(A,T,F){return F?.has(A)?F.get(A):T.get(A)}function xi(A,T){let F=Nn("GIT_CONFIG_COUNT",A,T);if(F===void 0)return{state:"absent"};if(F==="")return{state:"valid",count:0};if(!/^\d+$/.test(F))return{state:"invalid"};let j=Number(F);return Number.isSafeInteger(j)&&j<=1024?{state:"valid",count:j}:{state:"invalid"}}function Ei(A,T,F){let q=A.match(yg)?.[1];if(!q||!aa(q))return null;let K=A.indexOf("=");return{name:q,value:`${Nn(q,T,F)??""}${A.slice(K+1)}`}}function Tc(A){return kc(A,Ri)}function Ic(A){return kc(A,Ac)}function kc(A,T){if(!A)return!1;for(let F of A.keys())if(T.has(F))return!0;return!1}var vn=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]);function Dc(A,T){return ia.some((F)=>T?.has(F)||A.has(F))}function Nc(A,T){if(!T)return{gitCwd:null,hasExplicitGitContext:!1};let F;try{F=Po(wi(T))}catch{return{gitCwd:null,hasExplicitGitContext:!1}}if(!Fc(F))return{gitCwd:null,hasExplicitGitContext:!1};let j=!1,q=1;while(q<A.length){let K=A[q];if(!K)break;if(K==="--")break;if(!K.startsWith("-"))break;if(K==="-C"){let ee=A[q+1];if(!ee)return{gitCwd:null,hasExplicitGitContext:j};let te=Mc(F,ee);if(!te)return{gitCwd:null,hasExplicitGitContext:j};F=te,q+=2;continue}if(K.startsWith("-C")&&K.length>2){let ee=Mc(F,K.slice(2));if(!ee)return{gitCwd:null,hasExplicitGitContext:j};F=ee,q++;continue}if(K==="--git-dir"||K==="--work-tree"){j=!0,q+=2;continue}if(K.startsWith("--git-dir=")||K.startsWith("--work-tree=")){j=!0,q++;continue}if(vn.has(K))q+=2;else if(K.startsWith("-c")&&K.length>2)q++;else q++}return{gitCwd:F,hasExplicitGitContext:j}}function Lc(A){let T=Og(A);if(!T)return!1;try{let F=Cg(T);if(F.isSymbolicLink()||!F.isFile())return!1;let j=da(T);if(!j?.commonDir)return!1;if(!vg(j.gitDir,T))return!1;return Rg(j.gitDir,ca(T))}catch{return!1}}function da(A){try{let T=Sg(A);if(!T)return null;let F=Po(ua(T)?T:wi(ca(A),T));if(!_o(F).isDirectory())return null;return{gitDir:F,commonDir:bg(F)}}catch{return null}}function Sg(A){let T=_i(A,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!T.startsWith("gitdir:"))return null;return T.slice(7).trim()||null}function bg(A){try{let T=_i(Pi(A,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!T)return null;let F=Po(ua(T)?T:wi(A,T));return _o(F).isDirectory()?F:null}catch{return null}}function vg(A,T){let F=xg(A);return F===null?!1:Wc(A,F,T)}function Rg(A,T){let F=Eg(A);return F===null?!0:Wc(A,F,T)}function xg(A){let T=Pi(A,"gitdir");if(!la(T))return null;let F=_i(T,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return F===""?null:F}function Eg(A){let T=Pi(A,"config.worktree");return la(T)?Tg(T):null}function Wc(A,T,F){return Pg(_g(A,T),F)}function _g(A,T){return ua(T)?T:wi(A,T)}function Pg(A,T){try{return wg(A,T)}catch{return!1}}function wg(A,T){try{let F=_o(A),j=_o(T);if(F.ino!==0&&j.ino!==0&&F.dev===j.dev&&F.ino===j.ino)return!0}catch{}return Oc(A)===Oc(T)}function Oc(A){return Ag(Po.native(A))}function Ag(A){let T=A.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 Tg(A){let T=_i(A,"utf-8"),F=!1,j=null;for(let q of T.split(/\r?\n/)){let K=q.trim();if(K===""||K.startsWith("#")||K.startsWith(";"))continue;if(K.startsWith("[")){F=/^\[core\]$/i.test(K);continue}if(!F)continue;let ee=K.match(/^worktree\s*=\s*(.*)$/i);if(ee)j=Ig(ee[1]??"")}return j}function Ig(A){let T=A.trim();if(!T.startsWith('"')||!T.endsWith('"'))return T;return kg(T.slice(1,-1))}function kg(A){let T="";for(let F=0;F<A.length;F++){let j=A[F];if(j!=="\\"){T+=j;continue}let q=A[F+1];if(q===void 0){T+=j;continue}switch(q){case"\\":case'"':T+=q;break;case"n":T+=`
2
+ `;break;case"t":T+="\t";break;case"b":T+="\b";break;default:T+=`\\${q}`;break}F++}return T}function Mc(A,T){try{let F=gr(A,T,m);return Fc(F)?F:null}catch{return null}}function Fc(A){try{return _o(A).isDirectory()}catch{return!1}}function Og(A){try{return wo(Po(A))}catch{return null}}function wo(A){let T=A;while(!0){let F=Pi(T,".git");if(la(F))return F;let j=ca(T);if(j===T)return null;T=j}}function ma(A,T){return{value:A,work:T}}function Mt(A,T){if(A.work)A.work.units=Math.min(Number.MAX_SAFE_INTEGER,A.work.units+1);return A.value[T]}function dn(A){return A.value.length}function Ao(A,T,F=1){if(A)A.units=Math.min(Number.MAX_SAFE_INTEGER,A.units+T.length*F)}function wn(A,T){Ao(A,T)}function Or(A){if(!A)return!1;let T=A.charCodeAt(0);return T>=48&&T<=57||T>=65&&T<=90||T===95||T>=97&&T<=122}function cn(A){if(!A)return!1;let T=A.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 fa(A){return A===`
3
+ `||A==="\r"||A==="\u2028"||A==="\u2029"}function un(A,T,F){if(T+F.length>dn(A))return!1;for(let j=0;j<F.length;j++)if(Mt(A,T+j)!==F[j])return!1;return!0}function ar(A,T,F){return!Or(Mt(A,T-1))&&un(A,T,F)&&!Or(Mt(A,T+F.length))}function lr(A,T){return Or(Mt(A,T-1))!==Or(Mt(A,T))}function gn(A){return A===`
4
+ `||A===";"||A==="&"||A==="|"}function eo(A){return A==="|"||A===";"}function Ai(A,T,F){let j=ma(A,F);if(T==="rm")return Mg(j);if(T==="dd")return Ng(j);return jc(j,!0)}function Ti(A,T,F){let j=ma(A,F);if(T==="rm")return Lg(j);if(T==="reset-hard")return Uc(j,"--ha","rd");if(T==="reset-merge")return Uc(j,"--me","rge");if(T==="clean")return zg(j);if(T==="checkout")return Ug(j);if(T==="push-force")return $g(j);if(T==="push-refspec")return jg(j);if(T==="push-delete")return Hg(j);if(T==="branch")return Vg(j);if(T==="tag")return Yg(j);if(T==="restore")return Zg(j);return jc(j,!1)}function Mg(A){let T=!1,F=!1,j=!1,q=-1;for(let K=0;K<=dn(A);K++){let ee=Mt(A,K);if(!T){let ce=Mt(A,K+2);if(ar(A,K,"rm")&&cn(ce)&&ce!==`
5
+ `)T=!0,K++;continue}let te=Dg(A,K);if(ee===`
6
+ `||te!==-1){if(T=!1,F=!1,j=!1,q=-1,te!==-1)K=te-1;continue}if(ee===";"||ee==="&"||ee==="|"||K===dn(A)){if(q>=0){let ce=Gc(A,q,K);F||=ce.recursive,j||=ce.force}if(F&&j)return!0;T=!1,F=!1,j=!1,q=-1;continue}if(cn(ee)){if(q>=0){if(un(A,q,"--")&&K-q===2)T=!1,F=!1,j=!1;else{let ce=Gc(A,q,K);if(F||=ce.recursive,j||=ce.force,F&&j)return!0}q=-1}continue}if(q<0)q=K}return!1}function Dg(A,T){if(Mt(A,T)!=="\\"||Mt(A,T-1)==="\\")return-1;if(un(A,T,String.raw`\n`))return T+2;if(un(A,T,String.raw`\x0a`)||un(A,T,String.raw`\x0A`))return T+5;if(un(A,T,String.raw`\u000a`)||un(A,T,String.raw`\u000A`))return T+7;return un(A,T,String.raw`\012`)?T+4:-1}function Gc(A,T,F){if(zc(A,T,F,"recursive"))return{recursive:!0,force:!1};if(zc(A,T,F,"force"))return{recursive:!1,force:!0};if(Mt(A,T)!=="-"||Mt(A,T+1)==="-")return{recursive:!1,force:!1};let j=!1,q=!1;for(let K=T+1;K<F;K++){let ee=Mt(A,K);j||=ee==="r"||ee==="R",q||=ee==="f"||ee==="F"}return{recursive:j,force:q}}function zc(A,T,F,j){let q=F-T-2;if(q<1||q>j.length||!un(A,T,"--"))return!1;for(let K=0;K<q;K++)if(Mt(A,T+K+2)!==j[K])return!1;return!0}function Ng(A){let T=!1;for(let F=0;F<dn(A);F++){if(gn(Mt(A,F))){T=!1;continue}if(ar(A,F,"dd")){T=!0,F++;continue}if(!T||!ar(A,F,"of")||!un(A,F,"of=/dev/"))continue;let j=F+8;if(j<dn(A)&&!cn(Mt(A,j))&&Mt(A,j)!=="'"&&Mt(A,j)!=='"')return!0}return!1}function Lg(A){let T=!1,F=!1,j=!1;for(let q=0;q<=dn(A);){let K=Mt(A,q);if(q===dn(A)||gn(K)){T=!1,F=!1,j=!1,q++;continue}let ee=Fg(A,q);if(ee>=0){if(Wg(A,ee))return!0;let te=ee,ce=!1;while(cn(Mt(A,te)))ce||=Mt(A,te)===`
7
+ `,te++;if(ce)F=!1,j=!1;T=!0,q=te;continue}if(!T){q++;continue}if(un(A,q,"--")&&(q===0||cn(Mt(A,q-1)))&&(!Mt(A,q+2)||cn(Mt(A,q+2))||gn(Mt(A,q+2)))){T=!1,F=!1,j=!1,q+=2;continue}if(F||=un(A,q,"--recursive")&&lr(A,q+11)||pa(A,q,"recursive"),j||=un(A,q,"--force")&&lr(A,q+7)||pa(A,q,"force"),F&&j)return!0;q++}return!1}function pa(A,T,F){if(!un(A,T,"--"))return!1;let j=0;while(j<=F.length){let q=Mt(A,T+j+2);if(!q||cn(q)||gn(q))break;if(q!==F[j])return!1;j++}return j>0&&lr(A,T+j+2)}function Wg(A,T){let F=T,j=!1,q=!1;while(F<dn(A)){while(cn(Mt(A,F)))F++;let K=F;while(F<dn(A)&&!cn(Mt(A,F)))F++;if(Mt(A,K)!=="-"||F-K===2&&un(A,K,"--"))return!1;let ee=Bc(A,K,"recursive"),te=Bc(A,K,"force");if(j&&te||q&&ee)return!0;if(j||=ee,q||=te,Mt(A,K+1)==="-")continue;let ce=Gg(A,K,F);if(ce.combined||j&&ce.forceAtBoundary||q&&ce.recursiveAtBoundary)return!0;j||=ce.recursive,q||=ce.force}return!1}function Bc(A,T,F){return un(A,T,`--${F}`)&&lr(A,T+F.length+2)||pa(A,T,F)}function Fg(A,T){if(T>0&&Or(Mt(A,T-1)))return-1;let F=T;if(Mt(A,F)==="\\")F++;if(Mt(A,F)!=="r")return-1;if(F++,Mt(A,F)==="\\")F++;if(Mt(A,F)!=="m"||!cn(Mt(A,F+1)))return-1;return F+1}function Gg(A,T,F){let j=!1,q=!1,K=!1,ee=!1,te=!1;if(Mt(A,T)!=="-")return{recursive:j,force:q,recursiveAtBoundary:K,forceAtBoundary:ee,combined:te};let ce="";for(let de=T+1;de<F;de++){let _e=Mt(A,de)??"",Pe=(_e==="r"||_e==="f")&&lr(A,de+1);j||=_e==="r",q||=_e==="f",K||=_e==="r"&&Pe,ee||=_e==="f"&&Pe,te||=(ce==="r"&&_e==="f"||ce==="f"&&_e==="r")&&Pe,ce=_e}return{recursive:j,force:q,recursiveAtBoundary:K,forceAtBoundary:ee,combined:te}}function Uc(A,T,F){return Io(A,"reset",eo,!0,(j)=>Mt(A,j)==="-"&&to(A,j,T,F)?!0:j)}function zg(A){return Io(A,"clean",eo,!0,(T)=>{if(Mt(A,T)!=="-")return T;if(to(A,T,"--fo","rce"))return!0;let F=To(A,T,eo);for(let j=T+1;j<F;j++)if(Mt(A,j)==="f")return!0;return F-1})}function Ii(A,T,F){if(!ar(A,T,"git"))return null;let j=T+3;if(!cn(Mt(A,j)))return{commandEnd:-1,next:j};while(cn(Mt(A,j)))j++;while(j<dn(A)){if(gn(Mt(A,j)))return{commandEnd:-1,next:j};let q=To(A,j,gn);if(ar(A,j,F))return{commandEnd:j+F.length,next:q};if(Mt(A,j)!=="-")return{commandEnd:-1,next:q};let K=q-j===2&&un(A,j,"--"),ee=Bg(A,j,q);j=q;while(cn(Mt(A,j)))j++;if(K)return{commandEnd:ar(A,j,F)?j+F.length:-1,next:To(A,j,gn)};if(!ee)continue;if(j>=dn(A)||gn(Mt(A,j)))return{commandEnd:-1,next:j};j=To(A,j,gn);while(cn(Mt(A,j)))j++}return{commandEnd:-1,next:j}}function Bg(A,T,F){for(let j of vn)if(F-T===j.length&&un(A,T,j))return!0;return!1}function Ug(A){return $c(A,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function $g(A){return Io(A,"push",eo,!0,(T)=>{if(Mt(A,T)!=="-")return T;if(Mt(A,T+1)==="f"&&!Or(Mt(A,T+2))&&!un(A,T+2,"-with-lease"))return!0;let F=Hc(A,T,"--fo","rce");if(F>=0&&!un(A,F,"-with-lease"))return!0;return T})}function jg(A){return Io(A,"push",gn,!1,(T)=>{if(cn(Mt(A,T))&&Mt(A,T+1)==="+"&&T+2<dn(A)&&!gn(Mt(A,T+2))&&!cn(Mt(A,T+2)))return!0;if(Mt(A,T)===":"&&Mt(A,T+1)==="+")return!0;return T})}function Hg(A){return Io(A,"push",gn,!1,(T)=>{if(Mt(A,T)==="-"&&to(A,T,"--de","lete"))return!0;if(cn(Mt(A,T))&&Mt(A,T+1)===":"&&T+2<dn(A)&&!cn(Mt(A,T+2))&&!gn(Mt(A,T+2)))return!0;return T})}function Vg(A){let T=!1,F=!1,j=!1;for(let q=0;q<=dn(A);q++){if(q===dn(A)||gn(Mt(A,q))){if(F&&j)return!0;T=!1,F=!1,j=!1;continue}if(!T){let te=Ii(A,q,"branch");if(te){T=te.commandEnd>=0,q=Math.max(q,(T?te.commandEnd:te.next)-1);continue}}if(!T||Mt(A,q)!=="-")continue;let K=To(A,q,gn),ee=qg(A,q,K);if(F||=ee.deletion,j||=ee.force,F&&j)return!0;q=K-1}return!1}function qg(A,T,F){let j=!1,q=!1;for(let K=T;K<F;K++){if(Mt(A,K)!=="-")continue;if(to(A,K,"--de","lete"))j=!0;if(to(A,K,"--fo","rce"))q=!0;if(Mt(A,K+1)==="-")continue;let ee=K+1,te=!1,ce=!1,de=!1;while(ee<F&&Kg(Mt(A,ee))){let _e=Mt(A,ee);te||=_e==="d"||_e==="D",ce||=_e==="f",de||=_e==="D",ee++}if(!lr(A,ee))continue;j||=te,q||=ce||de}return{deletion:j,force:q}}function Kg(A){if(!A)return!1;let T=A.charCodeAt(0);return T>=65&&T<=90||T>=97&&T<=122}function Yg(A){return $c(A,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function $c(A,T){let F=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let j=0;j<dn(A);j++){let q=Mt(A,j),K=F[F.length-1];if(!K)return!1;let ee=K.escaped;if(K.escaped=!ee&&K.quote!=="'"&&q==="\\",!ee&&q==="'"&&K.quote!=='"')K.quote=K.quote==="'"?"":"'";if(!ee&&q==='"'&&K.quote!=="'")K.quote=K.quote==='"'?"":'"';if(q==="$"&&Mt(A,j+1)==="("&&(F.length===1||!ee&&K.quote!=="'")){F.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),j++;continue}if(!ee&&!K.quote&&F.length>1&&q==="("){K.depth++;continue}if(!ee&&!K.quote&&F.length>1&&q===")"){if(K.depth--,K.depth===0)F.pop();continue}if(cn(q))K.shortActive=!1,K.hasShortFlag=!1;if(!K.outerActive){let te=Ii(A,j,T.command);if(te){K.outerActive=te.commandEnd>=0&&cn(Mt(A,te.commandEnd)),K.shortActive=!1,K.hasShortFlag=!1,j=Math.max(j,(K.outerActive?te.commandEnd:te.next)-1);continue}}if(K.outerActive&&q==="-"){if(to(A,j,T.longPrefix,T.longOptional))return!0;K.shortActive||=!T.excludedShortStarts.includes(Mt(A,j+1)??"")}if(K.hasShortFlag||=K.shortActive&&q===T.shortFlag,K.hasShortFlag&&lr(A,j+1))return!0;if(eo(q))K.outerActive=!1}return!1}function Io(A,T,F,j,q){let K=!1;for(let ee=0;ee<dn(A);ee++){let te=Mt(A,ee),ce=F(te);if(!K&&!ce){let de=Ii(A,ee,T);if(de){K=de.commandEnd>=0&&(!j||cn(Mt(A,de.commandEnd))),ee=Math.max(ee,(K?de.commandEnd:de.next)-1);continue}}if(K){let de=q(ee);if(de===!0)return!0;for(let _e=ee;_e<=de;_e++)if(F(Mt(A,_e)))K=!1;ee=de}if(ce)K=!1}return!1}function Zg(A){let T=!1;for(let F=0;F<dn(A);F++){if(fa(Mt(A,F))){if(T)return!0;T=!1;continue}if(!T){let j=Ii(A,F,"restore");if(j){T=j.commandEnd>=0,F=Math.max(F,(T?j.commandEnd:j.next)-1);continue}}if(T&&Mt(A,F)==="-"&&Mt(A,F+1)==="-"&&(un(A,F+2,"staged")||un(A,F+2,"help")))T=!1}return T}function jc(A,T){let F=!1;for(let j=0;j<dn(A);j++){let q=Mt(A,j),K=T?fa(q):gn(q);if(F&&cn(q)&&Mt(A,j+1)==="-"&&ar(A,j+2,"delete"))return!0;if(K){F=!1;continue}if(ar(A,j,"find"))F=!0,j+=3}return!1}function To(A,T,F){let j=T;while(j<dn(A)&&!cn(Mt(A,j))&&!F(Mt(A,j)))j++;return j}function Hc(A,T,F,j){if(!un(A,T,F))return-1;let q=T+F.length;for(let K=0;K<j.length&&Mt(A,q)===j[K];K++)q++;return lr(A,q)?q:-1}function to(A,T,F,j){return Hc(A,T,F,j)>=0}var Vc=[{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"}],ko=new Set(Vc.map((A)=>A.id)),J=Vc,Xg=new Map(J.map((A)=>[A.id,A.intent])),qc=new Set(J.filter((A)=>A.catastrophic).map((A)=>A.id));function It(A,T){return{id:A,reason:T,intent:Xg.get(A)??"manual_only"}}function jt(A,T){if(!A)return null;if(qc.has(A.id))return A;if(T?.destructiveCommandProtectionEnabled===!1)return null;let F=T?.effectiveDestructiveCommandRules[A.id];return F&&!F.enabled?null:A}function mn(A,T,F){if(qc.has(T))return!0;if(A?.destructiveCommandProtectionEnabled===!1)return!1;return A?.effectiveDestructiveCommandRules[T]?.enabled??F}function U(A,T){return Object.freeze(Object.fromEntries(J.map((F)=>{let j=F.activationCapability?T[F.activationCapability]:void 0,q=j?.enabled??!0,K=A.destructiveCommandRuleOverrides[F.id],ee=F.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...K?{override:K}:{}}:A.destructiveCommandProtectionEnabled?K?{enabled:K==="on",inheritedEnabled:q,changesInherited:K==="on"!==q,source:"rule_override",...F.activationCapability?{activationCapability:F.activationCapability}:{},override:K}:{enabled:q,inheritedEnabled:q,changesInherited:!1,source:j?.source??"built_in_default",...F.activationCapability?{activationCapability:F.activationCapability}:{}}:{enabled:!1,inheritedEnabled:q,changesInherited:!1,source:"master_disabled",...F.activationCapability?{activationCapability:F.activationCapability}:{},...K?{override:K}:{}};return[F.id,Object.freeze(ee)]})))}function Kc(A,T){return Object.freeze({...A,effectiveDestructiveCommandRules:U(A,T)})}function cr(A,T){Ao(T,A,2);let F=A.toLowerCase(),j=F.trimStart(),q=j.startsWith("echo ")||j.startsWith("rg "),K=[{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},{regex:/\b(?:curl|wget|fetch|aria2c|https?|xhs?|ncat|netcat|nc)\b(?:[^\n|;&]|\\\n)*\|(?:\s|\\\n)*(?:(?:sudo|env|command|builtin)(?:\s+(?:-\S+|\w+=\S*))*\s+)?(?:[^\s|;&]*\/)?(?:ba|da|z|k)?sh(?![^\s;&|])/,label:"download piped to shell",skipForEchoRg:!0}];for(let ee of K){if(ee.skipForEchoRg&&q)continue;let te=ee.caseSensitive?A:F;if(ee.regex)wn(T,te);if((ee.regex?.test(te)??!1)||ee.scan&&Ti(te,ee.scan,T))return It("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${ee.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var Jg=/^[A-Za-z_][A-Za-z0-9_]*=/;function Zc(A,T,F){let j=A.words[0];if(!T||!j||A.words.length!==1||A.dialect!=="posix")return!1;if(!j.quoted||j.provenance!=="literal")return!1;let q=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(j.text)?.[1];if(!q)return!1;Ao(F,T.source,2);let K={anchored:new RegExp(`^\\$\\{?${q}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${q}(?![A-Za-z0-9_])`)};return Xc(T.nodes,j,K)}function Xc(A,T,F){return A.every((j)=>{if(j.kind==="connector")return!0;if(j.kind==="group"||j.kind==="function")return Xc(j.body.nodes,T,F);if(j.kind==="unknown")return!F.loose.test(j.source);return Qg(j,T,F)})}function Qg(A,T,F){if(A.nested.some((q)=>F.loose.test(q.source)))return!1;let j=A.words.findIndex((q)=>!Jg.test(q.text));return A.words.every((q,K)=>q===T||Yc(q.raw,F.anchored,K!==j))&&A.redirections.every((q)=>(!q.heredoc||q.heredoc.quotedDelimiter||!F.loose.test(q.heredoc.body))&&(!q.target||Yc(q.target.raw,F.anchored,!0)))}function Yc(A,T,F){let j=!1,q=!1;for(let K=0;K<A.length;K++){let ee=A[K];if(ee==="\\"&&!j){K++;continue}if(!q&&ee==="'"){j=!j;continue}if(!j&&ee==='"'){q=!q;continue}if(j||ee!=="$")continue;if(!T.test(A.slice(K)))continue;if(!q||!F)return!1}return!0}var Jc=Object.freeze({maxDerivedTokens:16384}),Qc="Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry.";class An 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 ki(){return{derivedTokens:0}}function Gn(A,T){if(!Number.isSafeInteger(A.derivedTokens)||A.derivedTokens<0||A.derivedTokens>Jc.maxDerivedTokens||!Number.isSafeInteger(T)||T<0||T>Jc.maxDerivedTokens-A.derivedTokens)throw new An;A.derivedTokens+=T}import{isAbsolute as oh,resolve as tu}from"node:path";import{basename as eh,dirname as th,join as ga}from"node:path";var no=Object.freeze({maxEnvironmentExpansionDepth:64,maxMissingSuffixComponents:256,maxRealpathAttempts:16384,maxProcessedCandidateBytes:4194304});class s extends Error{name="PathCanonicalizationLimitError";constructor(){super("Path canonicalization work limit exceeded.")}}function re(){return{realpathAttempts:0,processedCandidateBytes:0,resolvedPaths:new Map}}function ur(A){return{...re(),environment:A}}var Oi=new Set(["CC_SAFETY_NET_HOME","CLAUDE_CONFIG_DIR","CODEX_HOME","COPILOT_HOME","GEMINI_CLI_HOME","GROK_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 Mi(A,T){return ha(A,0,T)}function ha(A,T,F){let j="",q=0;while(q<A.length){if(A[q]!=="$"){j+=A[q],q++;continue}if(A[q+1]==="{"){let ee=ya(A,q+2),te=nh(A,q,T);if(te===null){if(Oi.has(ee))throw new s;j+=A.slice(q);break}let ce=A.slice(q,te+1);j+=rh(ce,T,F),q=te+1;continue}let K=ya(A,q+1);if(!K){j+="$",q++;continue}j+=Ca(K,F)??`$${K}`,q+=K.length+1}return j}function nh(A,T,F){let j=1;for(let q=T+2;q<A.length;q++){if(A[q]==="\\"){q++;continue}if(A[q]==="$"&&A[q+1]==="{"){if(j++,F+j>no.maxEnvironmentExpansionDepth)throw new s;q++;continue}if(A[q]!=="}")continue;if(j--,j===0)return q}return null}function rh(A,T,F){let j=A.slice(2,-1),q=ya(j,0);if(!q)return A;let K=j.slice(q.length);if(!K)return Ca(q,F)??A;let ee=[":-",":+",":=",":?","-","+","=","?"].find((de)=>K.startsWith(de));if(!ee){if(Oi.has(q))throw new s;return A}if(!Oi.has(q))return A;if(ee.endsWith("="))throw new s;let te=Ca(q,F),ce=ee.startsWith(":")?te!==null&&te!=="":te!==null;if(ee.endsWith("?")&&!ce)throw new s;if(ee.endsWith("-")||ee.endsWith("?"))return ce?te??"":ha(K.slice(ee.length),T+1,F);return ce?ha(K.slice(ee.length),T+1,F):""}function ya(A,T){if(!/[A-Za-z_]/.test(A[T]??""))return"";let F=T+1;while(/[A-Za-z0-9_]/.test(A[F]??""))F++;return A.slice(T,F)}function i(A,T,F=re()){if(!A)return A;let j=F.resolvedPaths.get(A);if(j!==void 0)return j;let q=[],K=A;while(!0){if(F.realpathAttempts++,F.processedCandidateBytes+=Buffer.byteLength(K),F.realpathAttempts>no.maxRealpathAttempts||F.processedCandidateBytes>no.maxProcessedCandidateBytes)throw new s;let ee=T.realpath(K);if(ee!==null){let ce=q.length===0?ee:ga(ee,...q.reverse());return F.resolvedPaths.set(A,ce),ce}let te=th(K);if(te===K){let ce=q.length===0?K:ga(K,...q.reverse());return F.resolvedPaths.set(A,ce),ce}if(q.length>=no.maxMissingSuffixComponents){let ce=ga(K,...q.reverse());return F.resolvedPaths.set(A,ce),ce}q.push(eh(K)),K=te}}function eu(A,T,F){let j=F.resolvedPaths.get(A);if(j!==void 0)return j;if(F.realpathAttempts++,F.processedCandidateBytes+=Buffer.byteLength(A),F.realpathAttempts>no.maxRealpathAttempts||F.processedCandidateBytes>no.maxProcessedCandidateBytes)throw new s;let q=T.realpath(A);if(q!==null)F.resolvedPaths.set(A,q);return q}function Ca(A,T){if(!Oi.has(A))return null;if(A==="HOME")return T.env.get("HOME")??T.home;return T.env.get(A)??null}var nu=64;function Oo(A,T,F){let j=oh(A)?tu(A):T?tu(T,A):void 0;if(!j)return;try{return i(j,F)}catch{return j}}function ru(A){return!["/dev","/proc","/sys"].some((T)=>A===T||A.startsWith(`${T}/`))}function Qt(A){return Vt(A).toLowerCase()}function Vt(A){return A.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??A}var Di=10,ro=20,z=/^[a-zA-Z][a-zA-Z0-9_-]*$/,oo=256,fn=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),ou=new Set(["python","python3","python2","node","ruby","perl"]),iu=/^python(?:[23](?:\.\d+)*)?$/,Ni=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"]);var Mr="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",io="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.",Li=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),ih=new Set(["-p","--print"]),sh=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),ah=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"])]]),lh=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),ch=new Map([["python",new Set(["m"])]]),uh=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"])]]),dh=new Set(["always","default","never"]),mh=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),fh=/\\\r?\n/g,ph=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 Wi(A){return Gi(A).code}function Fi(A){return Gi(A).sources}function au(A){return ph.get(Bi(A))??[]}function Gi(A){let T=Bi(A[0]??"");if(!Li.has(T))return{code:null,sources:[],optionsOpen:!1};let F=[],j=[],q=!0;for(let K=1;K<A.length;K++){let ee=A[K];if(ee===void 0)break;if(ee==="--")return zn(T,F,j,q,A[K+1]===void 0?void 0:K+1,A[K+1]);if(ee===""||ee==="-"||!ee.startsWith("-"))return zn(T,F,j,q,K,ee);if(T==="node"&&ih.has(ee)){let Pe=A[K+1];if(Pe===void 0)return zn(T,F,j,q);if(Pe.startsWith("-"))continue;F.push({tokenIndex:K+1,value:Pe}),j.push({tokenIndex:K+1,kind:"inline-code",value:Pe}),K++;continue}if(hh(T,ee)){let Pe=A[K+1];if(Pe===void 0)return zn(T,F,j,q);if(F.push({tokenIndex:K+1,value:Pe}),j.push({tokenIndex:K+1,kind:"inline-code",value:Pe}),T==="python")return zn(T,F,j,q);K++;continue}let te=/^--eval=(.*)$/s.exec(ee);if(yh(T)&&te){let Pe=te[1]??"";F.push({tokenIndex:K,value:Pe}),j.push({tokenIndex:K,kind:"inline-code",value:Pe});continue}if(T==="node"){let Pe=gh(ee);if(Pe){if(Pe.attached){if(q&&=Pe.value!=="",Pe.value!=="")j.push({tokenIndex:K,kind:"module-file",value:Pe.value});continue}let je=A[K+1];if(je===void 0||je.startsWith("-"))return q=!1,zn(T,F,j,q);j.push({tokenIndex:K+1,kind:"module-file",value:je}),K++;continue}}if(T==="python"&&ee.startsWith("--check-hash-based-pycs=")||T==="node"&&(ee==="--conditions="||ee==="--diagnostic-dir="||ee==="--title=")||T==="ruby"&&(ee==="--disable="||ee==="--enable="))return zn(T,F,j,q);if(uh.get(T)?.has(ee)){let Pe=A[K+1];if(Pe===void 0||Pe.startsWith("-")&&!(T==="ruby"&&mh.has(ee))||T==="python"&&!dh.has(Pe))return zn(T,F,j,q);K++;continue}if(ee.startsWith("--"))continue;let ce,de=!1;for(let Pe=1;Pe<ee.length;Pe++){let je=ee[Pe];if(je===void 0)break;if(ch.get(T)?.has(je)){let it=ee.slice(Pe+1),st=it||A[K+1];if(st!==void 0)j.push({tokenIndex:it?K:K+1,kind:"module-file",value:st});return zn(T,F,j,q)}if(sh.get(T)?.has(je)){ce=ee.slice(Pe+1)||A[K+1],de=Pe+1===ee.length;break}if(T==="node"&&je==="r"){if(ee==="-r"){let it=A[K+1];if(q&&=it!==void 0&&!it.startsWith("-"),q&&it!==void 0)j.push({tokenIndex:K+1,kind:"module-file",value:it});K++}else q=!1;break}if(T==="ruby"&&je==="r"){let it=ee.slice(Pe+1),st=it||A[K+1];if(q&&=st!==void 0,st!==void 0)j.push({tokenIndex:it?K:K+1,kind:"module-file",value:st});if(!it)K++;break}if(T==="perl"&&(je==="M"||je==="m")){let it=ee.slice(Pe+1);if(it)j.push({tokenIndex:K,kind:"module-file",value:it});else if(q=!1,Pe+1===ee.length)K++;break}if(ah.get(T)?.has(je)){if(Pe+1===ee.length)K++;break}if(lh.get(T)?.has(je)&&Pe+1<ee.length)break}if(ce===void 0)continue;let _e=de?K+1:K;if(F.push({tokenIndex:_e,value:ce}),j.push({tokenIndex:_e,kind:"inline-code",value:ce}),T==="python")return zn(T,F,j,q);if(de)K++}return zn(T,F,j,q,void 0,void 0,!0)}function zn(A,T,F,j,q,K,ee=!1){let te=A==="node"?T.slice(-1):T,ce=new Set(te.map((_e)=>_e.tokenIndex)),de=F.filter((_e)=>_e.kind!=="inline-code"||ce.has(_e.tokenIndex));if(j&&T.length===0&&q!==void 0&&K!==void 0)de.push({tokenIndex:q,kind:"main-script",value:K});return{code:(A==="node"?te[0]?.value:te.map((_e)=>_e.value).join(`
8
+ `))||null,sources:j?de:[],optionsOpen:j&&ee}}function gh(A){for(let T of["--import","--loader","--experimental-loader","--require"]){if(A===T)return{attached:!1,value:""};if(A.startsWith(`${T}=`))return{attached:!0,value:A.slice(T.length+1)}}return}function Tn(A){return Li.has(Bi(A))}function zi(A,T){return Bi(A)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(T)}function Bi(A){let T=Vt(A).toLowerCase();return iu.test(T)?"python":T}function hh(A,T){return Li.get(A)?.has(T)??!1}function yh(A){return Li.get(A)?.has("--eval")??!1}function so(A,T){let F=bh(A,T);if(!su(F,T))return!1;wn(T,F);let j=Sh(F);if(su(j,T))return!0;return wn(T,j),Ch.test(j)}var Ch=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function Sh(A){let T=[],F=0,j=0;while(j<A.length){let q=A[j];if(q!=="'"&&q!=='"'){j++;continue}let K=A.startsWith(q.repeat(3),j)?q.repeat(3):q,ee=j+K.length;while(ee<A.length&&!A.startsWith(K,ee))ee+=A[ee]==="\\"?2:1;if(ee>=A.length)break;T.push(A.slice(F,j)," "),j=ee+K.length,F=j}return T.push(A.slice(F)),T.join("")}function su(A,T){if(Ai(A,"rm",T))return!0;for(let j of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(wn(T,A),j.test(A))return!0;if(Ai(A,"dd",T))return!0;for(let j of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(wn(T,A),j.test(A))return!0;if(Ai(A,"find",T))return!0;let F=A.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((j)=>(wn(T,A),F.some((q)=>Ti(q,j))))}function bh(A,T){return wn(T,A),A.replace(fh,"")}var en=Object.freeze({maxChildAnalyses:1024,maxDerivedTokens:16384,maxDerivedBytes:1048576,maxPlaceholderReplacements:16384}),lu="Parallel command expands beyond CC Safety Net's analysis limits. Reduce the template or explicit argument list and retry.";class $i 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 cu(){return{childAnalyses:0,derivedTokens:0,derivedBytes:0,placeholderReplacements:0}}function In(A,T){let F=T.childAnalyses??0,j=T.derivedTokens??0,q=T.derivedBytes??0,K=T.placeholderReplacements??0;if(Ui(A.childAnalyses,F,en.maxChildAnalyses)||Ui(A.derivedTokens,j,en.maxDerivedTokens)||Ui(A.derivedBytes,q,en.maxDerivedBytes)||Ui(A.placeholderReplacements,K,en.maxPlaceholderReplacements))throw new $i;A.childAnalyses+=F,A.derivedTokens+=j,A.derivedBytes+=q,A.placeholderReplacements+=K}function Ui(A,T,F){return!Number.isSafeInteger(A)||A<0||A>F||!Number.isSafeInteger(T)||T<0||T>F-A}import{isAbsolute as Va,normalize as FC,parse as GC,posix as Pd,resolve as fo,sep as Ha}from"node:path";import{isAbsolute as vh,join as uu,normalize as fu,parse as Rh,sep as du}from"node:path";var xh=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],Eh=`
9
+ `;function Mo(A,T){if(Xn(A,T))return!0;if(!A.has("TMPDIR"))return!1;return!Sa(A.get("TMPDIR")??"",T)}function dr(A,T){if(A.has("TMPDIR"))return Sa(A.get("TMPDIR")??"",T);let F=ba(A,T);if(F===void 0)return!0;return Sa(F,T)}function ba(A,T){return hu(A,T,"TMPDIR")}function Sa(A,T){if(!A)return!1;if(Ph(A))return!1;return va(A,T)}function Xn(A,T){let F=hu(A,T,"IFS");return F!==void 0&&F!==""&&F!==Eh}function va(A,T){let F=ji(A,T.paths);if(F===null)return!1;return gu(T).some((j)=>Ah(F,j))}function pu(A,T){let F=ji(A,T.paths);if(F===null)return!1;return gu(T).some((j)=>Hi(j)===Hi(F))}var mu=new WeakMap;function gu(A){let T=mu.get(A);if(T)return T;let F=_h(A);return mu.set(A,F),F}function _h(A){let T=xh.map((j)=>ji(j,A.paths)??fu(j)),F=ji(A.tmpdir,A.paths);if(!F)return T;if(process.platform==="win32")return[...T,F];if(process.platform==="darwin"&&wh(F))return[...T,F];return T}function Ph(A){return/[\s$`*?[]/.test(A)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(A)||/[+@!]\([^)]*\)/.test(A)}function hu(A,T,F){return A.has(F)?A.get(F):T.env.get(F)}function wh(A){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(A)}function ji(A,T){try{let F=fu(A);if(!vh(F))return F;let j=Rh(F).root,q=F.slice(j.length).split(/[\\/]+/).filter(Boolean),K=j;for(let ee=0;ee<q.length;ee++){let te=uu(K,q[ee]??"");if(T.entryKind(te)==="missing")return uu(te,...q.slice(ee+1));let ce=T.realpath(te);if(ce===null)return null;K=ce}return K}catch{return null}}function Ah(A,T){let F=Hi(A),j=Hi(T);if(F===j)return!0;let q=j.endsWith(du)?j:`${j}${du}`;return F.startsWith(q)}function Hi(A){return process.platform==="win32"?A.toLowerCase():A}import{statSync as xC}from"node:fs";import{isAbsolute as Cd,join as EC,relative as Sd}from"node:path";import{isAbsolute as yu,parse as Th}from"node:path";var Su=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ln(A){if(!Su.test(A))return null;let T=A.indexOf("=");return{name:A.slice(0,T),value:A.slice(T+1)}}function xe(A){let T=new Map,F=0;while(F<A.length){let j=A[F];if(!j)break;let q=Ln(e(j));if(!q)break;T.set(q.name,q.value),F++}return{words:A.slice(F),envAssignments:T}}function bu(A){let T=A.toLowerCase();return A.includes("=")||T==="sudo"||T==="env"||T==="command"||T==="builtin"}function Dr(A,T,F,j){if(!bu(ao(A)))return{words:A,envAssignments:new Map,cwd:F,rewritten:!1};let q=new Set(A),K=A,ee=new Map,te=new Map(j??[]),ce=[],de=F;for(let Pe=0;Pe<ro;Pe++){let je=Cu(K),it=xe(K);for(let[yt,At]of it.envAssignments)ee.set(yt,At),te.set(yt,At);if(K=it.words,K.length===0)break;while(K.length>0&&ao(K).includes("=")&&!kh(K)){let yt=Oh(ao(K),te,T.env)??Ei(ao(K),T.env,te);if(yt)ee.set(yt.name,yt.value),te.set(yt.name,yt.value);K=K.slice(1)}if(K.length===0)break;let st=ao(K).toLowerCase();if(st!=="sudo"&&st!=="env"&&st!=="command"&&st!=="builtin")break;if(st==="sudo"){let yt=Dh(K,T.paths,de);if(K=yt.words,yt.cwd!==void 0)de=yt.cwd}if(st==="env"){let yt=Wh(K,de,te,T);if(ce.push(...yt.envSplitValues??[]),K=yt.words,yt.cwd!==void 0)de=yt.cwd;for(let[At,Tt]of yt.envAssignments)ee.set(At,Tt),te.set(At,Tt)}if(st==="command")K=Fh(K);if(st==="builtin")K=K.slice(Bn(K,1)==="--"?2:1);if(Cu(K)===je)break}let _e=xe(K);for(let[Pe,je]of _e.envAssignments)ee.set(Pe,je),te.set(Pe,je);return{words:_e.words,envAssignments:ee,cwd:de,envSplitValues:ce.length>0?ce:void 0,rewritten:Ih(_e.words,q)}}function Ih(A,T){return A.some((F)=>!T.has(F))}function Cu(A){return A.map(e).join(" ")}function ao(A){let T=A[0];return T?e(T):""}function Bn(A,T){let F=A[T];return F?e(F):void 0}function kh(A){return Su.test(ao(A))}function Oh(A,T,F){if(!A.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${T.get("TMPDIR")??F.get("TMPDIR")??""}${A.slice(8)}`}}var Mh=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function Dh(A,T,F){let j=1,q=F;while(j<A.length){let K=Bn(A,j);if(!K)break;if(K==="--")return{words:A.slice(j+1),cwd:q};if(!K.startsWith("-"))break;if(K==="-D"||K==="--chdir"){let ee=Bn(A,j+1);q=ee?Do(q,ee,T):null,j+=2;continue}if(K.startsWith("--chdir=")){q=Do(q,K.slice(8),T),j++;continue}if(K.startsWith("-D")&&K.length>2){q=Do(q,K.slice(2),T),j++;continue}if(K==="-i"||K==="--login"){q=null,j++;continue}if(Mh.has(K)){j+=2;continue}j++}return{words:A.slice(j),cwd:q}}var Nh=new Set(["-i","-0","--null"]),Lh=new Set(["-u","--unset","-C","--chdir","-P"]);function Wh(A,T,F,j){let q=new Map,K=[],ee=T,te=1,ce=(de)=>({words:A.slice(de),envAssignments:q,cwd:ee,envSplitValues:K.length>0?K:void 0});while(te<A.length){let de=Bn(A,te);if(!de)break;if(de==="--")return ce(te+1);if(de==="-i"||de==="--ignore-environment"||de==="-"){q.clear();for(let Pe of F.keys())q.set(Pe,"");q.set("TMPDIR",""),te++;continue}if(Nh.has(de)){te++;continue}if(de==="-u"||de==="--unset"){let Pe=Bn(A,te+1);if(Pe!==void 0)q.set(Pe,"");te+=2;continue}if(de.startsWith("-u")&&de.length>2&&!de.startsWith("-u=")){q.set(de.slice(2),""),te++;continue}if(de.startsWith("--unset=")){q.set(de.slice(8),""),te++;continue}let _e=de==="-S"||de==="--split-string"?{value:Bn(A,te+1),consumed:2}:de.startsWith("-S")&&de.length>2?{value:de.slice(2),consumed:1}:de.startsWith("--split-string=")?{value:de.slice(15),consumed:1}:null;if(_e){if(_e.value!==void 0)K.push(_e.value);return ee=null,ce(te+_e.consumed)}if(Lh.has(de)){if(de==="-C"||de==="--chdir"){let Pe=Bn(A,te+1);ee=Pe?Do(ee,Pe,j.paths):null}te+=2;continue}if(de.startsWith("-u=")){te++;continue}if(de.startsWith("-C")&&de.length>2||de.startsWith("--chdir=")){let Pe=de.startsWith("--chdir=")?de.slice(8):de.startsWith("-C=")?de.slice(3):de.slice(2);ee=Do(ee,Pe,j.paths),te++;continue}if(de.startsWith("-P")){te++;continue}if(de.startsWith("-")){te++;continue}if(!Ln(de))break;while(te<A.length){let Pe=Ln(Bn(A,te)??"");if(!Pe)break;q.set(Pe.name,Pe.value),te++}if(Bn(A,te)==="--")te++;return ce(te)}return ce(te)}function Do(A,T,F){if(T==="")return null;if(!A&&!yu(T))return null;let j=yu(T)?Th(T).root:F.realpath(A??"/");if(j===null)return null;try{return gr(j,T,F)}catch{return null}}function Fh(A){if(Bn(A,1)==="-v")return[...Yt(["type"]),...A.slice(2)];let T=1;while(T<A.length){let F=Bn(A,T);if(!F)break;if(F==="-p"||F==="-v"||F==="-V"){T++;continue}if(F==="--")return A.slice(T+1);if(F.startsWith("-")&&!F.startsWith("--")&&F.length>1){if(!/^[pvV]+$/.test(F.slice(1)))break;T++;continue}break}return A.slice(T)}var Gh=/['"\\$`{}#]/;function Vi(A,T){if(A.some((j)=>Gh.test(j)))return null;let F=[...A.flatMap((j)=>j.split(/\s+/).filter((q)=>q.length>0)),...T];return F.length<=64?F:null}function yr(A,T,F){return qi(A,T,F).tokens}function zh(A){let T=[],F="",j=0;while(j<A.length){let q=A.charAt(j);if(q==='"'||q==="'"){let K=A.indexOf(q,j+1);if(K===-1)return A.split(/\s+/).map((ee)=>ee.replace(/["']/g,"")).filter((ee)=>ee.length>0);F+=A.slice(j+1,K),j=K+1;continue}if(/\s/.test(q)){if(F.length>0)T.push(F);F="",j++;continue}F+=q,j++}if(F.length>0)T.push(F);return T}function Cr(A,T,F,j=0){let q=qi(A,T,F),K=(q.envSplitValues??[]).flatMap(zh);if(K.length===0)return q.tokens;let ee=[...K,...q.tokens];if(j>=8)return ee;return Cr(ee,T,F,j+1)}function qi(A,T,F,j){if(!bu(A[0]??""))return{tokens:[...A],envAssignments:new Map,cwd:F};let q=Dr(Yt(A),T,F,j);return{tokens:q.words.map(e),envAssignments:q.envAssignments,cwd:q.cwd,envSplitValues:q.envSplitValues}}import{basename as yC,isAbsolute as CC,normalize as SC,resolve as pd}from"node:path";function Ki(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Bh(A){return Object.freeze({...A,span:Object.freeze(A.span),words:Object.freeze(A.words),redirections:Object.freeze(A.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(A.nested.map((T)=>Rn(T)))})}function Yi(A,T,F){A.push(F),T.reset()}function Uh(A,T,F,j,q){if(j<=F)return;A.push({raw:T.slice(F,j),span:{start:F,end:j},provenance:q})}function Zi(A){let T=[];return{parts:T,push:(F,j,q)=>Uh(T,A,F,j,q)}}function Ra(A){let T=A.parts??[{raw:A.raw,span:A.span,provenance:A.provenance}];return Object.freeze({kind:"word",...A,span:Object.freeze(A.span),parts:Object.freeze(T.map((F)=>Object.freeze({...F,span:Object.freeze(F.span)})))})}function lo(A,T,F,j,q,K,ee){return Ra({text:j,raw:A.slice(T,F),span:{start:T,end:F},provenance:q,quoted:K,...ee?{parts:ee}:{}})}function Rn(A){return Object.freeze({...A,span:Object.freeze(A.span),issues:Object.freeze(A.issues.map((T)=>Object.freeze({...T,span:Object.freeze(T.span)}))),nodes:Object.freeze(A.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:Rn(T.body)});return Object.freeze({...T,span:Object.freeze(T.span)})}))})}function xa(A,T,F){if(T>=F||Ru(A[T]??""))return null;let j="",q=!1,K=!1,ee=T;while(ee<F&&!Ru(A[ee]??"")){let te=A[ee]??"";if(te==="'"){q=!0;let ce=vu(A,ee+1,F,"'");j+=ce.text,K||=!ce.closed,ee=ce.next;continue}if(te==='"'){q=!0;let ce=vu(A,ee+1,F,'"');j+=ce.text,K||=!ce.closed,ee=ce.next;continue}if(te==="\\"){q=!0;let ce=A[ee+1];if(!ce||ce===`
10
+ `||ce==="\r"){K=!0;break}j+=ce,ee+=2;continue}if(te==="`"||A.startsWith("$(",ee)||A.startsWith("${",ee)||A.startsWith("<(",ee)||A.startsWith(">(",ee))K=!0;j+=te,ee++}return{delimiter:j,quoted:q,next:ee,span:{start:T,end:ee},ambiguous:K}}function Ea(A,T,F,j){let q=[],K=T;for(let ee of j){let te=K,ce=!1;while(K<F){let de=$h(A,K,F);if((ee.stripTabs?de.text.replace(/^\t+/,""):de.text)===ee.delimiter){ee.attach({body:ee.stripTabs?jh(A.slice(te,K)):A.slice(te,K),delimiter:ee.delimiter,quotedDelimiter:ee.quotedDelimiter,bodySpan:{start:te,end:K},terminatorSpan:{start:K,end:de.contentEnd}}),K=de.next,ce=!0;break}if(de.next<=K)break;K=de.next}if(ce)continue;return q.push({code:"unterminated-heredoc",message:`heredoc delimiter ${ee.delimiter} was not found`,span:ee.declarationSpan}),{next:F,issues:q,terminated:!1}}return{next:K,issues:q,terminated:!0}}function vu(A,T,F,j){let q="",K=T;while(K<F&&A[K]!==`
11
+ `&&A[K]!=="\r"){let ee=A[K]??"";if(ee===j)return{text:q,next:K+1,closed:!0};if(j==='"'&&ee==="\\"&&A[K+1]){let te=A[K+1]??"";q+=["$","`",'"',"\\"].includes(te)?te:`\\${te}`,K+=2;continue}q+=ee,K++}return{text:q,next:K,closed:!1}}function Ru(A){return/[\s;&|<>)]/u.test(A)||A==="`"}function $h(A,T,F){let j=T;while(j<F&&A[j]!==`
12
+ `&&A[j]!=="\r")j++;let q=j>=F?F:A[j]==="\r"&&A[j+1]===`
13
+ `?j+2:j+1;return{text:A.slice(T,j),contentEnd:j,next:q}}function jh(A){return A.replace(/(^|\r\n?|\n)\t+/g,"$1")}var wu=new Set(["&&","||","|","|&"]);function Au(A,T){let F={start:0,end:A.length};if(A.length>T.maxInputLength)return Rn({kind:"program",dialect:"posix",source:A,span:F,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${T.maxInputLength} UTF-16 code units`,span:F}],nodes:[]});let j=Qi(A,0,A.length,T,{used:0,max:T.maxWords},0);return Rn({kind:"program",dialect:"posix",source:A,span:F,status:ns(j.issues,j.limited),issues:j.issues,nodes:j.nodes})}function Qi(A,T,F,j,q,K,ee){let te=[],ce=[],de=Ki(),_e=[],Pe=()=>{if(de.words.length===0&&de.redirections.length===0)return;let it={start:de.start,end:de.end},st=de.words.map((yt)=>yt.text);Yi(te,de,{kind:"command",dialect:"posix",source:A.slice(it.start,it.end),span:it,words:de.words,redirections:de.redirections,nested:de.nested,displayText:ce.length>0&&te.length===0?A.slice(T,F):st.join(" ")})},je=T;while(je<F){let it=A[je];if(!it)break;if(ee&&it===ee)return Pe(),Pu(te,ce),{nodes:te,issues:ce,next:je+1,closed:!0,limited:!1,pendingHeredocs:_e};if(ts(it)){if(it===`
14
+ `||it==="\r"){Pe();let Ft=it==="\r"&&A[je+1]===`
15
+ `?je+2:je+1,Bt=te.at(-1);if(Bt?.kind!=="connector"||!wu.has(Bt.operator))te.push(Object.freeze({kind:"connector",operator:A.slice(je,Ft),span:Object.freeze({start:je,end:Ft})}));if(_e.length>0){let Ht=Ea(A,Ft,F,_e.splice(0));ce.push(...Ht.issues),je=Ht.next;continue}je=Ft;continue}je++;continue}if(it==="#"){while(je<F&&A[je]!==`
16
+ `&&A[je]!=="\r")je++;continue}let st=de.start===-1?uy(A,je,F):void 0;if(st){if(Pa(te,ce,je),K>=j.maxDepth)return co(te,ce,je,"depth-limit",j.maxDepth);if(!_a(q))return co(te,ce,je,"word-limit",j.maxWords);let Ft=Qi(A,st.braceIndex+1,F,j,q,K+1,"}"),Bt=Ft.next,Ht={start:st.braceIndex+1,end:Ft.closed?Bt-1:Bt},Gt=xu(A,Ht,Ft);if(te.push({kind:"function",name:st.name,span:{start:je,end:Bt},body:Gt}),ce.push(...Ft.issues),Ft.pendingHeredocs.length>0||Lo(Ft.nodes))ce.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely",span:{start:je,end:Bt}});if(_e.push(...Ft.pendingHeredocs),Ft.limited)return Ji(te,ce,Ft.next);if(!Ft.closed)ce.push({code:"unclosed-function-body",message:"function body is not closed",span:{start:st.braceIndex,end:Bt}});je=Bt;continue}let yt=es(A,je);if(yt){if(Pe(),!Lu(te.at(-1)))ce.push({code:"unexpected-connector",message:`connector ${yt} has no preceding command`,span:{start:je,end:je+yt.length}});te.push(Object.freeze({kind:"connector",operator:yt,span:Object.freeze({start:je,end:je+yt.length})})),je+=yt.length;continue}if(it===")"){Pe(),ce.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis",span:{start:je,end:je+1}}),te.push({kind:"unknown",source:it,span:{start:je,end:je+1}}),je++;continue}if((it==="("||it==="{"&&Jh(A,je,F))&&de.start===-1){if(Pa(te,ce,je),K>=j.maxDepth)return co(te,ce,je,"depth-limit",j.maxDepth);let Ft=it==="("?")":"}",Bt=Qi(A,je+1,F,j,q,K+1,Ft),Ht=Bt.next,Gt={start:je+1,end:Bt.closed?Ht-1:Ht},Zt=xu(A,Gt,Bt);if(te.push({kind:"group",style:it==="("?"subshell":"brace",span:{start:je,end:Ht},body:Zt}),ce.push(...Bt.issues),Bt.pendingHeredocs.length>0||Lo(Bt.nodes))ce.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely",span:{start:je,end:Ht}});if(_e.push(...Bt.pendingHeredocs),Bt.limited)return Ji(te,ce,Bt.next);if(!Bt.closed)ce.push({code:it==="("?"unclosed-subshell":"unclosed-brace-group",message:`${it} group is not closed`,span:{start:je,end:Ht}});je=Ht;continue}let At=(it==="<"||it===">")&&A[je+1]!=="("?Kh(A,je):null;if(At){let Ft=de.words.at(-1),Bt=Ft&&Ft.span.end===je&&/^[0-9]+$/.test(Ft.raw)?Number(Ft.raw):void 0;if(Bt!==void 0)de.words.pop();let Ht=Bt===void 0?je:Ft?.span.start??je;de.start=de.start===-1?je:de.start;let Gt=je+At.length;while(Gt<F&&/[ \t]/.test(A[Gt]??""))Gt++;let Zt=A[Gt],an=Gt>je+At.length&&Zt==="#",ln=!Zt||ts(Zt)||!!es(A,Gt)||Zt===ee||Zt===")"||an||(Zt==="<"||Zt===">")&&A[Gt+1]!=="(",tn=At==="<<"||At==="<<-"?xa(A,Gt,F):void 0,Xt=tn?{word:lo(A,Gt,tn.next,tn.delimiter,"literal",tn.quoted),nested:[],issues:[],next:tn.next,limited:!1}:!ln?wa(A,Gt,F,j,q,K):void 0;if(Xt){if(ce.push(...Xt.issues),Xt.limited)return Ji(te,ce,Xt.next);if(!_a(q))return co(te,ce,Xt.next,"word-limit",j.maxWords)}let Wt=Xt?.next??je+At.length,Ut={kind:"redirection",operator:At,span:{start:Ht,end:Wt},...Bt===void 0?{}:{fd:Bt},...Xt?{target:Xt.word}:{}};if(de.redirections.push(Ut),At==="<<"||At==="<<-")if(!tn)ce.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word",span:{start:je,end:je+At.length}});else{if(tn.ambiguous||tn.delimiter.length===0)ce.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely",span:tn.span});let Jt=de.nested;_e.push({delimiter:tn.delimiter,quotedDelimiter:tn.quoted,stripTabs:At==="<<-",declarationSpan:{start:Ht,end:Wt},attach:(Ot)=>{if(Ut.heredoc=Ot,Ot.quotedDelimiter)return;Jt.push(...Vh(A,Ot.bodySpan.start,Ot.bodySpan.end,j,q,K+1))}})}else if(!Xt)ce.push({code:"missing-redirection-target",message:`redirection ${At} requires a target word`,span:{start:je,end:je+At.length}});if(Xt)de.nested.push(...Xt.nested);de.end=Wt,je=Wt;continue}if(de.start===-1)Pa(te,ce,je);let Tt=wa(A,je,F,j,q,K);if(ce.push(...Tt.issues),Tt.limited)return Ji(te,ce,Tt.next);let Dt=ty(de.words)?sy(A,Tt.word,q.max-q.used,j.maxDepth,j.maxInputLength):void 0;if(Dt?.limitCode)return co(te,ce,Tt.next,Dt.limitCode,Dt.limitCode==="word-limit"?j.maxWords:Dt.limitCode==="depth-limit"?j.maxDepth:j.maxInputLength);let zt=Dt?.words??[Tt.word];for(let Ft of zt){if(!_a(q))return co(te,ce,Tt.next,"word-limit",j.maxWords);de.words.push(Ft)}de.start=de.start===-1?je:de.start,de.end=Tt.next,de.nested.push(...Tt.nested),je=Tt.next>je?Tt.next:je+1}return Pe(),Pu(te,ce),ce.push(...dy(_e)),{nodes:te,issues:ce,next:je,closed:ee===void 0,limited:!1,pendingHeredocs:[]}}function xu(A,T,F){return{kind:"program",dialect:"posix",source:A.slice(T.start,T.end),span:T,status:ns(F.issues,F.limited),issues:F.issues,nodes:F.nodes}}function wa(A,T,F,j,q,K){let ee="",te=T,ce=!1,de="literal",_e=[],Pe=[],je=!1;while(te<F){let it=A[te],st=(it==="<"||it===">")&&A[te+1]==="(";if(!it||ts(it)||(it===";"||it==="|"||it==="&")&&es(A,te)||(it==="<"||it===">")&&!st)break;if(it===")")break;if(it==="'"){ce=!0;let At=A.indexOf("'",te+1);if(At===-1||At>=F){ee+=A.slice(te+1,F),Pe.push({code:"unclosed-single-quote",message:"single-quoted word is not closed",span:{start:te,end:F}}),te=F;break}ee+=A.slice(te+1,At),te=At+1;continue}if(it==='"'){ce=!0;let At=Hh(A,te,F,j,q,K);if(ee+=At.text,_e.push(...At.nested),Pe.push(...At.issues),je||=At.limited,de=No(de,At.provenance),te=At.next,je)break;continue}if(A.startsWith("$'",te)){ce=!0;let At=Yh(A,te+2,F);if(ee+=At.text,Pe.push(...At.issues),!At.closed)Pe.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed",span:{start:te,end:F}});te=At.next;continue}if(it==="\\"){let At=A[te+1];if(!At){Pe.push({code:"trailing-escape",message:"escape has no following character",span:{start:te,end:te+1}}),te++;break}if(At===`
17
+ `){te+=2;continue}ee+=At,te+=2;continue}let yt=it==="$"||it==="<"||it===">"||it==="`"?rs(A,te,F,j,q,K):null;if(yt){let At=Tu(yt,_e,Pe);if(je||=At.limited,de=No(de,At.provenance),te=At.next,je)break;continue}if(it==="$"){let At=Ou(A,te,F,ee,de);ee=At.text,de=At.provenance,te=At.next;continue}if(it==="*"||it==="?"||it==="[")de=No(de,"glob");ee+=it,te++}return{word:lo(A,T,te,ee,de,ce,de==="literal"?void 0:Xh(A,T,te)),nested:_e,issues:Pe,next:te,limited:je}}function Hh(A,T,F,j,q,K){let ee="",te="literal",ce=[],de=[],_e=!1,Pe=T+1;while(Pe<F){let je=A[Pe];if(je==='"')return{text:ee,provenance:te,nested:ce,issues:de,next:Pe+1,limited:_e};if(je==="\\"&&A[Pe+1]){let st=A[Pe+1]??"";if(st===`
18
+ `){Pe+=2;continue}if(st==="\r"&&A[Pe+2]===`
19
+ `){Pe+=3;continue}ee+=["$","`",'"',"\\"].includes(st)?st:`\\${st}`,Pe+=2;continue}if(A.startsWith("$((",Pe)){let st=Aa(A,Pe+3,F,"))"),yt=st===-1?F:st+2;if(ee+=A.slice(Pe,yt),st===-1)de.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:Pe,end:yt}});Pe=yt;continue}let it=rs(A,Pe,F,j,q,K);if(it){let st=Tu(it,ce,de);if(Pe=st.next,_e||=st.limited,te=No(te,st.provenance),_e)return{text:ee,provenance:te,nested:ce,issues:de,next:Pe,limited:_e};continue}if(je==="$"){let st=Ou(A,Pe,F,ee,te);ee=st.text,te=st.provenance,Pe=st.next;continue}ee+=je??"",Pe++}return de.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:T,end:F}}),{text:ee,provenance:te,nested:ce,issues:de,next:F,limited:_e}}function rs(A,T,F,j,q,K){let ee=A.startsWith("$((",T),te=A.startsWith("$(",T)&&!ee,ce=A.startsWith("<(",T)||A.startsWith(">(",T),de=A[T]==="`";if(!ee&&!te&&!ce&&!de)return null;let _e=ee?3:de?1:2,Pe=ee?"))":de?"`":")",je=Aa(A,T+_e,F,Pe),it=je===-1?F:je,st=je===-1?F:je+Pe.length;if(K>=j.maxDepth)return{program:cy(A,T+_e,it,"depth-limit"),next:st,provenance:ee?"arithmetic":"command-substitution"};if(ee){let Dt=[],zt=[],Ft=!1,Bt=T+_e;while(Bt<it){let Ht=rs(A,Bt,it,j,q,K+1);if(!Ht){Bt++;continue}if(Dt.push(...Ht.program.nodes),zt.push(...Ht.program.issues),Ft||=Ht.program.status==="limited",Bt=Ht.next,Ft)break}if(je===-1)zt.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:T,end:st}});return{program:Rn({kind:"program",dialect:"posix",source:A.slice(T+_e,it),span:{start:T+_e,end:it},status:ns(zt,Ft),issues:zt,nodes:Dt}),next:st,provenance:"arithmetic"}}let yt=Qi(A,T+_e,it,j,q,K+1),At=je===-1?[{code:"unclosed-command-substitution",message:`${A.slice(T,T+_e)} substitution is not closed`,span:{start:T,end:st}}]:[],Tt=(de||ce)&&Lo(yt.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions",span:{start:T,end:st}}]:[];return{program:Rn({kind:"program",dialect:"posix",source:A.slice(T+_e,it),span:{start:T+_e,end:it},status:ns([...yt.issues,...At,...Tt],yt.limited),issues:[...yt.issues,...At,...Tt],nodes:yt.nodes}),next:st,provenance:"command-substitution"}}function Vh(A,T,F,j,q,K){let ee=[],te=T;while(te<F){let ce=A[te];if(ce==="\\"){te+=2;continue}let de=ce==="$"||ce==="`"?rs(A,te,F,j,q,K):null;if(!de){te++;continue}if(ee.push(de.program),te=de.next,de.program.status==="limited")break}return ee}function Tu(A,T,F){return T.push(A.program),F.push(...A.program.issues),{provenance:A.provenance,next:A.next,limited:A.program.status==="limited"}}function Aa(A,T,F,j){if(j==="`"){for(let te=T;te<F;te++)if(A[te]==="\\")te++;else if(A[te]==="`")return te;return-1}let q=1,K={single:!1,double:!1},ee=[];for(let te=T;te<F;te++){let ce=A[te];if((ce===`
20
+ `||ce==="\r")&&ee.length>0){let _e=ce==="\r"&&A[te+1]===`
21
+ `?te+2:te+1,Pe=Ea(A,_e,F,ee.splice(0));if(!Pe.terminated)return-1;te=Pe.next-1;continue}let de=Iu(A,te,T,F,K);if(de!==null){te=de;continue}if(!K.double&&A.startsWith("$((",te)){let _e=qh(A,te+3,F);if(_e===-1)return-1;te=_e+1;continue}if(j===")"&&!K.double&&ce==="<"&&A[te+1]==="<"&&A[te+2]!=="<"){let _e=A[te+2]==="-",Pe=te+(_e?3:2);while(Pe<F&&/[ \t]/.test(A[Pe]??""))Pe++;let je=xa(A,Pe,F);if(je){ee.push({delimiter:je.delimiter,quotedDelimiter:je.quoted,stripTabs:_e,declarationSpan:{start:te,end:je.next},attach:()=>{return}}),te=je.next-1;continue}}if(A.startsWith("$(",te)&&!A.startsWith("$((",te)){q++,te++;continue}if(ce==="("&&!K.double)q++;if(ce===")"&&!K.double){if(q--,q===0)return j==="))"&&A[te+1]!==")"?-1:te}}return-1}function qh(A,T,F){let j=1,q={single:!1,double:!1};for(let K=T;K<F;K++){let ee=A[K],te=Iu(A,K,T,F,q);if(te!==null){K=te;continue}if(A.startsWith("$(",K)&&!A.startsWith("$((",K)){j++,K++;continue}if(ee==="("&&!q.double)j++;if(ee!==")"||q.double)continue;if(j--,j===0)return A[K+1]===")"?K:-1}return-1}function Iu(A,T,F,j,q){let K=A[T];if(K==="\\"&&!q.single)return T+1;if(!q.double&&K==="'")q.single=!q.single;if(!q.single&&K==='"')q.double=!q.double;if(q.single)return T;if(q.double||K!=="#"||!my(A,T,F))return null;let ee=T;while(ee+1<j&&A[ee+1]!==`
22
+ `&&A[ee+1]!=="\r")ee++;return ee}function es(A,T){let F=A[T];if(F===";")return";";if(F==="&")return A[T+1]==="&"?"&&":"&";if(F==="|")return A[T+1]==="|"?"||":A[T+1]==="&"?"|&":"|";return null}function Kh(A,T){let F=A[T];if(F===">"){if(A[T+1]===">")return">>";if(A[T+1]==="&")return">&";return A[T+1]==="|"?">|":">"}if(F!=="<")return null;if(A.startsWith("<<<",T))return"<<<";if(A.startsWith("<<-",T))return"<<-";if(A[T+1]==="<")return"<<";if(A[T+1]==="&")return"<&";if(A[T+1]===">")return"<>";return"<"}function ts(A){let T=A.charCodeAt(0);if(T===32||T>=9&&T<=13)return!0;if(T<128)return!1;return/\s/u.test(A)}function ku(A,T,F){if(A[T+1]==="{"){let q=A.indexOf("}",T+2);return q===-1||q>=F?F:q+1}let j=T+1;while(j<F&&/[A-Za-z0-9_?@#$!*-]/.test(A[j]??""))j++;return j===T+1?T+1:j}function Yh(A,T,F){let j="",q=[],K=T;while(K<F){let ee=A[K];if(ee==="'")return{text:j,next:K+1,closed:!0,issues:q};if(ee!=="\\"){j+=ee??"",K++;continue}let te=Zh(A,K+1,F);if(j+=te.text,te.invalidCodePoint!==void 0)q.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${te.invalidCodePoint}`,span:{start:K,end:te.next}});K=te.next}return{text:j,next:F,closed:!1,issues:q}}function Zh(A,T,F){let j=A[T];if(!j||T>=F)return{text:"\\",next:T};let q=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
23
+ `],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(q.has(j))return{text:q.get(j)??j,next:T+1};if(j==="x")return Xi(A,T+1,F,16,2,T+1);if(j==="u")return Xi(A,T+1,F,16,4,T+1);if(j==="U")return Xi(A,T+1,F,16,8,T+1);if(/[0-7]/.test(j))return Xi(A,T,F,8,3,T+1);return{text:j,next:T+1}}function Xi(A,T,F,j,q,K){let ee=j===16?/[0-9a-fA-F]/:/[0-7]/,te="",ce=T;while(ce<F&&te.length<q&&ee.test(A[ce]??""))te+=A[ce],ce++;if(!te)return{text:A[K-1]??"",next:K};let de=Number.parseInt(te,j);return de>1114111||de>=55296&&de<=57343?{text:"�",next:ce,invalidCodePoint:de}:{text:String.fromCodePoint(de),next:ce}}function ns(A,T=!1){if(T)return"limited";if(A.some((F)=>F.code==="invalid-ansi-c-code-point"||F.code==="missing-heredoc-delimiter"||F.code==="ambiguous-heredoc-delimiter"||F.code==="unterminated-heredoc"||F.code==="unsupported-heredoc-context"))return"invalid";return A.length>0?"partial":"complete"}function Ou(A,T,F,j,q){let K=ku(A,T,F);return{text:j+A.slice(T,K),provenance:No(q,"variable"),next:K}}function Xh(A,T,F){let j=Zi(A),q=T,K=!1,ee=!1,te=T;while(te<F){let ce=A[te];if(ce==="\\"&&!K){te+=2;continue}if(!ee&&ce==="'"){K=!K,te++;continue}if(!K&&ce==='"'){ee=!ee,te++;continue}if(K){te++;continue}let de=A.startsWith("$((",te),_e=A.startsWith("$(",te)&&!de,Pe=!ee&&(A.startsWith("<(",te)||A.startsWith(">(",te)),je=ce==="`";if(de||_e||Pe||je){let it=de?3:je?1:2,st=de?"))":je?"`":")",yt=Aa(A,te+it,F,st),At=yt===-1?F:yt+st.length;j.push(q,te,"literal"),j.push(te,At,de?"arithmetic":"command-substitution"),te=At,q=At;continue}if(ce==="$"){let it=ku(A,te,F);if(it>te+1){j.push(q,te,"literal"),j.push(te,it,"variable"),te=it,q=it;continue}}if(!ee&&(ce==="*"||ce==="?"||ce==="[")){j.push(q,te,"literal"),j.push(te,te+1,"glob"),te++,q=te;continue}te++}return j.push(q,F,"literal"),j.parts}function No(A,T){if(T==="command-substitution"||A==="command-substitution")return"command-substitution";if(T==="arithmetic"||A==="arithmetic")return"arithmetic";if(T==="variable"||A==="variable")return"variable";if(T==="glob"||A==="glob")return"glob";return A}function Jh(A,T,F){return T+1>=F||ts(A[T+1]??"")||es(A,T+1)!==null}var Qh=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),ey=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function ty(A){let T=0;while(T<=A.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(A[T]?.text??""))T++;if(T===A.length)return!0;let F=ny(A,T);if(F===void 0||F===null)return!1;T=F}return!1}function ny(A,T){let F=A[T]?.text.toLowerCase();if(F==="command")return ry(A,T);if(F==="env")return oy(A,T);if(F==="sudo")return iy(A,T);return}function ry(A,T){if(A[T+1]?.text==="-v")return null;for(let F=T+1;F<A.length;F++){let j=A[F]?.text??"";if(j==="--")return F+1;if(j==="-p"||j==="-v"||j==="-V"||/^-[pvV]+$/.test(j))continue;return F}return A.length}function oy(A,T){for(let F=T+1;F<A.length;F++){let j=A[F]?.text??"";if(j==="--")return F+1;if(Qh.has(j)){if(A[F+1]===void 0)return null;F++;continue}if(j.startsWith("-u=")||j.startsWith("--unset=")||j.startsWith("-C")&&j.length>2||j.startsWith("--chdir=")||j.startsWith("-S")&&j.length>2||j.startsWith("--split-string=")||j.startsWith("-P"))continue;if(j.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(j))continue;return F}return A.length}function iy(A,T){for(let F=T+1;F<A.length;F++){let j=A[F]?.text??"";if(j==="--")return F+1;if(ey.has(j)){if(A[F+1]===void 0)return null;F++;continue}if(j.startsWith("-"))continue;return F}return A.length}function Mu(A,T,F,j){if(A.provenance!=="literal"||!A.raw.includes("{"))return;let q=[A.raw],K=A.raw.length,ee=0;while(!0){let ce=q.findIndex((st)=>_u(st));if(ce===-1)break;if(++ee>F)return{limited:!0};let de=q[ce]??"",_e=_u(de);if(!_e||_e.kind==="range")return{limited:!0};let Pe=_e.start+de.length-_e.end,je=_e.alternatives.reduce((st,yt)=>st+Pe+yt.length,0);if(K-de.length+je>j||q.length-1+_e.alternatives.length>T)return{limited:!0};let it=Du(de,_e);q.splice(ce,1,...it),K+=je-de.length}if(ee===0)return;let te=q.map((ce)=>ly(ce,F));if(te.some((ce)=>ce===null))return{limited:!0};return{words:[...new Set(te.filter((ce)=>ce!==null&&ce!==""))]}}function sy(A,T,F,j,q){if(T.provenance!=="literal"||T.quoted||T.raw!==T.text||!T.raw.includes("{"))return;let K=[T.text],ee=T.text.length,te=0;while(!0){let de=K.findIndex((At)=>Eu(At));if(de===-1)break;if(++te>j)return{limitCode:"depth-limit"};let _e=K[de]??"",Pe=Eu(_e);if(!Pe)break;let je=Pe.start+_e.length-Pe.end,it=Pe.alternatives.filter((At)=>je+At.length>0),st=it.reduce((At,Tt)=>At+je+Tt.length,0);if(ee-_e.length+st>q)return{limitCode:"brace-expansion-limit"};if(K.length-1+it.length>F)return{limitCode:"word-limit"};let yt=Du(_e,{...Pe,alternatives:it});K.splice(de,1,...yt),ee+=st-_e.length}let ce=K.filter((de)=>de.length>0);if(te===0)return;return{words:ce.map((de)=>lo(A,T.span.start,T.span.end,de,"literal",!1))}}function Eu(A){let T=[],F;for(let j=0;j<A.length;j++){let q=A[j];if(q==="{"){T.push({start:j,commas:[]});continue}if(q===","&&T.length>0){T.at(-1)?.commas.push(j);continue}if(q!=="}"||T.length===0)continue;let K=T.pop();if(!K||K.commas.length===0)continue;if(!F||K.start<F.start)F={start:K.start,end:j+1,commas:K.commas}}if(!F)return;return{start:F.start,end:F.end,alternatives:Nu(A,F)}}function _u(A){let T=[],F,j=null,q=!1;for(let K=0;K<A.length;K++){let ee=A[K];if(q){q=!1;continue}if(ee==="\\"&&j!=="'"){q=!0;continue}if(ee===j){j=null;continue}if(j===null&&(ee==="'"||ee==='"')){j=ee;continue}if(j!==null)continue;if(ee==="{"){T.push({start:K,commas:[]});continue}if(ee===","&&T.length>0){T.at(-1)?.commas.push(K);continue}if(ee!=="}"||T.length===0)continue;let te=T.pop();if(!te)continue;let ce=te.commas.length>0?{kind:"alternatives",start:te.start,end:K+1,commas:te.commas}:ay(A.slice(te.start+1,K))?{kind:"range",start:te.start,end:K+1}:void 0;if(ce&&(!F||ce.start<F.start))F=ce}if(!F||F.kind==="range")return F;return{kind:F.kind,start:F.start,end:F.end,alternatives:Nu(A,F)}}function Du(A,T){return T.alternatives.map((F)=>`${A.slice(0,T.start)}${F}${A.slice(T.end)}`)}function Nu(A,T){let F=[T.start,...T.commas,T.end-1];return F.slice(0,-1).map((j,q)=>A.slice(j+1,F[q+1]))}function ay(A){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(A)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(A)}function ly(A,T){let F=`x${A}`,j=wa(F,0,F.length,{maxInputLength:F.length,maxWords:1,maxDepth:T},{used:0,max:1},0);if(j.limited||j.issues.length>0||j.next!==F.length||j.word.provenance!=="literal")return null;return j.word.text.slice(1)}function cy(A,T,F,j){return Rn({kind:"program",dialect:"posix",source:A.slice(T,F),span:{start:T,end:F},status:"limited",issues:[{code:j,message:"command structure exceeds parser limit",span:{start:T,end:F}}],nodes:[]})}function co(A,T,F,j,q){return{nodes:A,issues:[...T,{code:j,message:`command structure exceeds parser limit ${q}`,span:{start:F,end:F}}],next:F,closed:!1,limited:!0,pendingHeredocs:[]}}function Ji(A,T,F){return{nodes:A,issues:T,next:F,closed:!1,limited:!0,pendingHeredocs:[]}}function _a(A){return A.used++,A.used<=A.max}function uy(A,T,F){let j=A.slice(T,F),q=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(j)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(j),K=q?.[1];if(!q||!K)return;return{name:K,braceIndex:T+q[0].lastIndexOf("{")}}function Lo(A){return A.some((T)=>{if(T.kind==="command")return T.redirections.some((F)=>F.heredoc)||T.nested.some((F)=>Lo(F.nodes));return(T.kind==="group"||T.kind==="function")&&Lo(T.body.nodes)})}function dy(A){return A.map((T)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${T.delimiter} was not found`,span:T.declarationSpan}))}function Lu(A){return A?.kind==="command"||A?.kind==="group"||A?.kind==="function"}function Pu(A,T){let F=A.at(-1);if(F?.kind!=="connector"||!wu.has(F.operator))return;T.push({code:"missing-command-after-connector",message:`connector ${F.operator} requires a following command`,span:F.span})}function Pa(A,T,F){if(!Lu(A.at(-1)))return;T.push({code:"missing-command-connector",message:"adjacent commands require a connector",span:{start:F,end:F+1}})}function my(A,T,F){return T===F||/[\s;&|()]/u.test(A[T-1]??"")}var Wu=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),fy=new Set(["gc","cat","type","cp","mv","rm"]),Fu=["-rec","-for","-path","-literalpath","-whatif"],py=/^\$env:\w/i,gy=/^(?:\$\{?\w+\}?|~)\\./,os={maxInputLength:131072,maxWords:16384,maxDepth:64};function Gu(A){let T=A.toLowerCase().replaceAll("`","");if(![...Wu].some((j)=>T.includes(j))&&!(T.includes("rm")&&Fu.some((j)=>T.includes(j)))&&!T.includes("<#")&&!hy(T))return!1;let F=vy(A);return F.invalidComment||F.commands.some(yy)}function hy(A){if(A.includes("$env:"))return!0;return A.includes("\\")&&(A.includes("$")||A.includes("~"))}function yy(A){let T=A[0]==="&"||A[0]==="."?1:0,F=A[T]?.toLowerCase();if(F&&Wu.has(F))return!0;let j=A.slice(T+1);if(F&&fy.has(F)&&j.some(Cy))return!0;if(F!=="rm")return!1;return j.some((q)=>{let K=q.toLowerCase().split(":",1)[0]??"";return Fu.some((ee)=>K.startsWith(ee))})}function Cy(A){return py.test(A)||gy.test(A)}function zu(A,T){let F={start:0,end:A.length};if(A.length>T.maxInputLength)return Rn({kind:"program",dialect:"powershell",source:A,span:F,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${T.maxInputLength} UTF-16 code units`,span:F}],nodes:[]});let j=Ma(A,0,A.length,T,0);return Rn({kind:"program",dialect:"powershell",source:A,span:F,status:Ry(j.issues,j.limited),issues:j.issues,nodes:j.nodes})}function Ma(A,T,F,j,q,K=!1){let ee=[],te=[],ce=Ki(),de=0,_e=!1,Pe=()=>{if(ce.words.length===0&&ce.redirections.length===0)return;let it={start:ce.start,end:ce.end};Yi(ee,ce,{kind:"command",dialect:"powershell",source:A.slice(it.start,it.end),span:it,words:ce.words,redirections:ce.redirections,nested:ce.nested,displayText:ce.words.map((st)=>st.text).join(" ")})},je=T;while(je<F){let it=A[je];if(!it)break;if(K&&it==="}")return Pe(),{nodes:ee,issues:te,next:je+1,closed:!0,words:de,limited:_e};let st=$u(A,je,F,j.maxDepth);if(st){if(st.issue)te.push(st.issue);if(st.limited)return Pe(),{nodes:ee,issues:te,next:st.next,closed:!1,words:de,limited:!0};je=st.next;continue}if(/\s/.test(it)){if(it==="\r"||it===`
24
+ `){Pe();let Tt=it==="\r"&&A[je+1]===`
25
+ `?je+2:je+1;ee.push(Ta(A,je,Tt)),je=Tt;continue}je++;continue}let yt=Da(A,je);if(yt){Pe(),ee.push(Ta(A,je,je+yt.length)),je+=yt.length;continue}if(it==="{"){if(Pe(),q>=j.maxDepth)return te.push(Uu(je,j.maxDepth)),{nodes:ee,issues:te,next:F,closed:!1,words:de,limited:!0};let Tt=Ma(A,je+1,F,j,q+1,!0),Dt=Tt.closed?Tt.next-1:Tt.next,zt=Rn({kind:"program",dialect:"powershell",source:A.slice(je+1,Dt),span:{start:je+1,end:Dt},status:Tt.limited?"limited":Tt.issues.length>0?"partial":"complete",issues:Tt.issues,nodes:Tt.nodes});if(ee.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:je,end:Tt.next}),body:zt})),te.push(...Tt.issues),!Tt.closed)te.push({code:"unclosed-script-block",message:"PowerShell script block is not closed",span:{start:je,end:Tt.next}});de+=Tt.words,_e||=Tt.limited,je=Tt.next;continue}if(it==="}"){Pe(),ee.push(Ta(A,je,je+1)),je++;continue}if(it===">"||it==="<"){ce.start=ce.start===-1?je:ce.start;let Tt=A[je+1]===it?je+2:je+1,Dt=Tt;while(/[ \t]/.test(A[Dt]??""))Dt++;let zt=Dt<F?Ia(A,Dt,F,j,q):void 0,Ft=zt?.next??Tt;if(ce.redirections.push(Object.freeze({kind:"redirection",operator:A.slice(je,Tt),span:Object.freeze({start:je,end:Ft}),...zt?{target:zt.word}:{}})),zt)te.push(...zt.issues),ce.nested.push(...zt.nested),de+=zt.words,_e||=zt.limited;ce.end=Ft,je=Ft;continue}if(it===","){ce.start=ce.start===-1?je:ce.start,ce.words.push(Ra({text:",",raw:",",span:{start:je,end:je+1},provenance:"literal",quoted:!1})),ce.end=++je;continue}let At=Ia(A,je,F,j,q);if(ce.start=ce.start===-1?je:ce.start,ce.end=At.next,ce.words.push(At.word),te.push(...At.issues),ce.nested.push(...At.nested),de+=1+At.words,_e||=At.limited,de>j.maxWords)return te.push({code:"word-limit",message:`command exceeds ${j.maxWords} words`,span:{start:je,end:At.next}}),Pe(),{nodes:ee,issues:te,next:At.next,closed:!1,words:de,limited:!0};je=At.next>je?At.next:je+1}return Pe(),{nodes:ee,issues:te,next:je,closed:!K,words:de,limited:_e}}function Ia(A,T,F,j,q){let K="",ee="literal",te=!1,ce=[],de=[],_e=0,Pe=!1,je=(st)=>{let yt=Sy(A,st,F,j,q);return K+=A.slice(st,yt.next),de.push(yt.program),ce.push(...yt.program.issues),_e+=ka(yt.program),Pe||=yt.program.status==="limited",ee="command-substitution",yt.next},it=T;while(it<F){let st=A[it];if(!st||/\s/.test(st)||Da(A,it)||st===">"||st==="<"||st==="#")break;if(st===",")break;if(st==="`"){let yt=A[it+1];if(!yt){ce.push({code:"trailing-escape",message:"PowerShell escape has no following character",span:{start:it,end:it+1}}),it++;break}K+=yt,it+=2;continue}if(A.startsWith("$(",it)){it=je(it);continue}if(st==="'"){te=!0,it++;let yt=!1;while(it<A.length){if(A[it]==="'"&&A[it+1]==="'"){K+="'",it+=2;continue}if(A[it]==="'"){yt=!0,it++;break}K+=A[it]??"",it++}if(!yt)ce.push({code:"unclosed-single-quote",message:"single-quoted word is not closed",span:{start:T,end:A.length}});continue}if(st==='"'){te=!0;let yt=it++,At=!1;while(it<F){let Tt=A[it];if(Tt==="`"&&A[it+1]){K+=A[it+1],it+=2;continue}if(Tt==='"'){At=!0,it++;break}if(A.startsWith("$(",it)){it=je(it);continue}if(Tt==="$")ee=A[it+1]==="("?"command-substitution":"variable";K+=Tt??"",it++}if(!At)ce.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:yt,end:A.length}});continue}if(st==="$")ee=A[it+1]==="("?"command-substitution":"variable";if(st==="@"&&it===T)ee="variable";K+=st,it++}return{word:lo(A,T,it,K,ee,te,ee==="literal"?void 0:by(A,T,it)),next:it,issues:ce,nested:de,words:_e,limited:Pe}}function Sy(A,T,F,j,q){let K=Bu(A,T+2,F),ee=K===-1?F:K,te=K===-1?F:K+1;if(q>=j.maxDepth)return{program:Rn({kind:"program",dialect:"powershell",source:A.slice(T+2,ee),span:{start:T+2,end:ee},status:"limited",issues:[Uu(T,j.maxDepth)],nodes:[]}),next:te};let ce=Ma(A,T+2,ee,j,q+1),de=K===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed",span:{start:T,end:te}}]:[];return{program:Rn({kind:"program",dialect:"powershell",source:A.slice(T+2,ee),span:{start:T+2,end:ee},status:ce.limited?"limited":ce.issues.length+de.length>0?"partial":"complete",issues:[...ce.issues,...de],nodes:ce.nodes}),next:te}}function Bu(A,T,F){let j=1,q=!1,K=!1;for(let ee=T;ee<F;ee++){let te=A[ee];if(te==="`"){ee++;continue}if(!K&&te==="'"){if(q&&A[ee+1]==="'"){ee++;continue}q=!q;continue}if(!q&&te==='"'){K=!K;continue}if(q)continue;if(A.startsWith("$(",ee)){j++,ee++;continue}if(!K&&te==="(")j++;if(te!==")")continue;if(j--,j===0)return ee}return-1}function ka(A){let T=0;for(let F of A.nodes){if(F.kind==="group")T+=ka(F.body);if(F.kind==="command"){T+=F.words.length;for(let j of F.nested)T+=ka(j)}}return T}function by(A,T,F){let j=Zi(A),q=T,K=!1,ee=T;while(ee<F){let te=A[ee];if(te==="`"){ee+=2;continue}if(te==="'"){if(K&&A[ee+1]==="'"){ee+=2;continue}K=!K,ee++;continue}if(K){ee++;continue}if(A.startsWith("$(",ee)){let ce=Bu(A,ee+2,F),de=ce===-1?F:ce+1;j.push(q,ee,"literal"),j.push(ee,de,"command-substitution"),ee=de,q=de;continue}if(te==="$"||te==="@"&&ee===T){let ce=ee+1;if(A[ce]==="{"){let de=A.indexOf("}",ce+1);ce=de===-1||de>=F?F:de+1}else while(ce<F&&/[A-Za-z0-9_:?]/.test(A[ce]??""))ce++;j.push(q,ee,"literal"),j.push(ee,ce,"variable"),ee=ce,q=ce;continue}ee++}return j.push(q,F,"literal"),j.parts}function Uu(A,T){return{code:"depth-limit",message:`command structure exceeds parser limit ${T}`,span:{start:A,end:A}}}function vy(A){let T=[],F=[],j=0,q=0,K=!1,ee=()=>{if(F.length>0)T.push(F);F=[]};while(j<A.length&&j<131072&&q<16384){let te=A[j];if(te==="\r"||te===`
26
+ `){ee(),j+=te==="\r"&&A[j+1]===`
27
+ `?2:1;continue}if(/\s/.test(te??"")){j++;continue}let ce=$u(A,j,Math.min(A.length,os.maxInputLength),os.maxDepth);if(ce){K||=!!ce.issue||ce.limited,j=ce.next;continue}let de=Da(A,j);if(de){ee(),j+=de.length;continue}if(te==="{"||te==="}"){ee(),j++;continue}let _e=Ia(A,j,Math.min(A.length,os.maxInputLength),os,0);if(_e.word.text)F.push(_e.word.text);for(let Pe of _e.nested)T.push(...Oa(Pe));q++,j=_e.next>j?_e.next:j+1}return ee(),{commands:T,invalidComment:K}}function Oa(A){return A.nodes.flatMap((T)=>{if(T.kind==="group")return Oa(T.body);if(T.kind!=="command")return[];return[T.words.map((F)=>F.text),...T.nested.flatMap(Oa)]})}function Da(A,T){for(let F of["&&","||",";","|"])if(A.startsWith(F,T))return F;return null}function $u(A,T,F,j){if(A[T]==="#"&&A[T+1]!==">"){let ee=T+1;while(ee<F&&A[ee]!=="\r"&&A[ee]!==`
28
+ `)ee++;return{next:ee,limited:!1}}if(!A.startsWith("<#",T))return null;let q=1,K=T+2;while(K<F){if(A.startsWith("<#",K)){if(q++,q>j)return{next:F,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${j}`,span:{start:T,end:K+2}},limited:!0};K+=2;continue}if(A.startsWith("#>",K)){if(q--,K+=2,q===0)return{next:K,limited:!1};continue}K++}return{next:F,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed",span:{start:T,end:F}},limited:!1}}function Ry(A,T){if(T)return"limited";if(A.some((F)=>F.code==="unclosed-block-comment"))return"invalid";return A.length>0?"partial":"complete"}function Ta(A,T,F){return Object.freeze({kind:"connector",operator:A.slice(T,F),span:Object.freeze({start:T,end:F})})}var Nr=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function R(A,T="auto",F=Nr){if(T==="powershell"||T==="auto"&&Gu(A.slice(0,F.maxInputLength)))return zu(A,F);return Au(A,F)}function Wo(A,T){if(A!=="powershell")return T[0]?.provenance==="command-substitution";let F=T[0]?.text==="&"||T[0]?.text==="."?1:0,j=T[F]?.provenance;return j!==void 0&&j!=="literal"}var xy=/^[A-Za-z_][A-Za-z0-9_]*=/;function is(A,T){return A?.provenance==="literal"&&!A.quoted&&A.raw===T&&A.text===T}function ss(A){let T=is(A.words[0],"time")?1:0,F=T===1&&is(A.words[T],"-p")?T+1:T,j=T===1&&is(A.words[F],"--")?F+1:F,q=is(A.words[j],"!")?j+1:j,K=A.words.slice(q).find((ee)=>!xy.test(ee.text));return K?.provenance==="literal"?K.text:void 0}function Fo(A,T){if(T.escaped)return T.escaped=!1,!0;if(A==="\\"&&!T.inSingle)return T.escaped=!0,!0;if(A==="'"&&!T.inDouble)return T.inSingle=!T.inSingle,!0;if(A==='"'&&!T.inSingle)return T.inDouble=!T.inDouble,!0;return!1}function uo(A){let T={inSingle:!1,inDouble:!1,escaped:!1};for(let F of Ey(A))Fo(F,T);return T.inSingle||T.inDouble}function Ey(A){let T="",F={inSingle:!1,inDouble:!1,escaped:!1},j=!1,q=!0;for(let K=0;K<A.length;K++){let ee=A[K];if(!ee)break;if(j){if(ee===`
29
+ `||ee==="\r")T+=ee,j=!1,F.escaped=!1;continue}if(ee==="#"&&!F.inSingle&&!F.inDouble&&q){j=!0;continue}if(T+=ee,!F.inSingle&&!F.inDouble&&!F.escaped)q=/[\s;&|()<>]/.test(ee);Fo(ee,F)}return T}var _y=new Set(["&&","||","|&","|","&",";"]),Py=new Set(["<<","<<<",">|"]),wy=/[*@#?$!_-]/,Ay=/^\w+(?::\w+)*/,Na=Object.freeze([]),Ty=Object.freeze([]),Iy=256;function Ku(A,T){let F=T.status==="complete"?new Set(Wa(T)):new Set,j=[...F].reduce((ee,te)=>ee.slice(0,te.start)+" ".repeat(te.end-te.start)+ee.slice(te.end),A);if(uo(j))return as("unclosed-quote",j,Na);let q={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},K=Go(T,{source:j,suppressed:F,flags:q,depth:0,functions:new Map,powershell:T.dialect==="powershell"});if(q.limited)return as("structural-limit",j,Na);if(q.invalid)return as("invalid",j,Na);return as("complete",j,K,q.assignmentFallbacks)}function as(A,T,F,j=Ty){return Object.freeze({status:A,source:T,entries:Object.freeze(F),assignmentFallbacks:Object.freeze(j)})}function Go(A,T){return A.nodes.flatMap((F,j)=>ky(F,A,j,T)).sort((F,j)=>F.start-j.start).flatMap((F)=>[...F.entries])}function ky(A,T,F,j){if(A.kind==="connector")return[{start:A.span.start,entries:[Un(Ly(A.operator))]}];if(A.kind==="unknown")return[{start:A.span.start,entries:[Un(A.source)]}];if(A.kind==="function")return j.functions.set(A.name,A.body),[];if(A.kind==="group"){let K=A.style!=="subshell",ee=j.source[A.span.end-1]===(K?"}":")"),te=K?j:{...j,functions:new Map(j.functions)};return[{start:A.span.start,entries:[K?ls("{"):Un("("),...Go(A.body,te),...ee?[K?ls("}"):Un(")")]:[]]}]}let q=Fy(A,j.functions);if(q){if(j.depth>=Nr.maxDepth||++j.flags.expansions>Iy)return j.flags.limited=!0,[];return[{start:A.span.start,entries:[...ju(A,j),ls(";"),...Go(q,{...j,depth:j.depth+1}),ls(";")]},...Hu(A,T,F,j)]}return[{start:A.span.start,entries:ju(A,j)},...Hu(A,T,F,j)]}function ju(A,T){return[...A.words.map((F)=>({start:F.span.start,entries:Zu(F,A,T,!1)})),...A.redirections.map((F)=>({start:F.span.start,entries:Oy(F,A,T)}))].sort((F,j)=>F.start-j.start).flatMap((F)=>F.entries)}function Oy(A,T,F){let j=A.operator==="<<-"?"<<":A.operator,q=A.target?Zu(A.target,T,F,!0):[],K=q[0],ee=K?.kind==="word"?K.text:void 0;return[...A.fd===void 0?[]:[Fa(String(A.fd))],Object.freeze({kind:"redirection",operator:j,role:Wy(j),targetOrder:Py.has(j)?"legacy-segment":"immediate",...ee===void 0?{}:{target:ee}}),...ee===void 0?q:q.slice(1)]}function Hu(A,T,F,j){let q=A.redirections.filter((K)=>K.operator==="<<"||K.operator==="<<-");return[...q.flatMap((K)=>{let ee=K.heredoc;if(!ee)return[];let te=[Fa(ee.delimiter),.../[\r\n]/.test(j.source[ee.terminatorSpan.end]??"")?[Un(";")]:[]];if(j.suppressed.has(ee.bodySpan))return[{start:ee.bodySpan.start,entries:te}];return[{start:ee.bodySpan.start,entries:[...Yu(j.source.slice(ee.bodySpan.start,ee.bodySpan.end),j),...te]}]}),...q.some((K)=>!K.heredoc&&K.target)?My(T,F,j):[]]}function My(A,T,F){let j=A.nodes.slice(T+1).find((q)=>q.kind==="connector");if(!j||j.span.end>=A.span.end)return[];return[{start:j.span.end,entries:Yu(F.source.slice(j.span.end,A.span.end),F)}]}function Yu(A,T){if(T.depth>=Nr.maxDepth)return T.flags.limited=!0,[];let F=R(A,"posix");if(F.status==="limited")return T.flags.limited=!0,[];let j={invalid:!1,limited:!1,expansions:T.flags.expansions,assignmentFallbacks:T.flags.assignmentFallbacks},q=Go(F,{source:A,suppressed:new Set,flags:j,depth:T.depth+1,functions:new Map,powershell:!1});return T.flags.limited||=j.limited,T.flags.expansions=j.expansions,q}function Zu(A,T,F,j){let q=[],K={single:!1,double:!1},ee="",te=!1,ce=()=>{if(te&&!j)q.push(Un("glob"));else if(ee!==""||A.quoted&&q.length===0)q.push(Fa(ee));ee="",te=!1};for(let de of A.parts){if(de.provenance!=="command-substitution"&&de.provenance!=="arithmetic"){for(let it of La(de.raw,K,F.flags,F.powershell)){if(typeof it==="string"){ce(),q.push(Un(it));continue}ee+=it.text,te||=it.glob}continue}if(K.double){let it=F.source.slice(de.span.start,de.span.end);ee+=La(it,{single:!1,double:!0},F.flags,F.powershell).map((st)=>typeof st==="string"?st:st.text).join("");continue}let _e=T.nested.find((it)=>it.span.start>=de.span.start&&it.span.end<=de.span.end),Pe=_e?Go(_e,F):[];if(de.raw.startsWith("`")){ee+="${}",ce(),q.push(...Pe);continue}if(de.raw.startsWith("<(")||de.raw.startsWith(">(")){ce(),q.push(de.raw.startsWith("<(")?Un("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),...Pe,...de.raw.endsWith(")")?[Un(")")]:[]);continue}let je=de.raw.startsWith("$((")?2:1;ee+="${}",ce(),q.push(...Array.from({length:je},()=>Un("(")),...Pe,...de.raw.endsWith(")".repeat(je))?Array.from({length:je},()=>Un(")")):[])}return ce(),q}function La(A,T,F,j){let q=[],K="",ee=!1,te=0;while(te<A.length){let ce=A[te]??"";if(!T.single&&!T.double&&(ce==="("||ce===")")){q.push({text:K,glob:ee},ce),K="",ee=!1,te++;continue}if(j&&ce==="`"&&!T.single){K+=A[te+1]??"",te+=2;continue}if(T.single){if(ce==="'")T.single=!1;else K+=ce;te++;continue}if(T.double){if(ce==='"'){T.double=!1,te++;continue}if(!j&&ce==="\\"){let de=A[te+1]??"";K+=['"',"\\","$"].includes(de)?de:`\\${de}`,te+=2;continue}if(ce==="$"){let de=Vu(A,te,T,F,j);K+=de.text,te=de.next;continue}K+=ce,te++;continue}if(ce==="'"||ce==='"'){T.single=ce==="'",T.double=ce==='"',te++;continue}if(!j&&ce==="\\"){let de=A[te+1]??"";ee||=de==="*"||de==="?",K+=de,te+=2;continue}if(ce==="$"){let de=Vu(A,te,T,F,j);K+=de.text,te=de.next;continue}ee||=ce==="*"||ce==="?",K+=ce,te++}return[...q,{text:K,glob:ee}]}function Vu(A,T,F,j,q){let K=A[T+1];if(K==="{"){let te=Ny(A,T+2);if(te===-1)return j.invalid=!0,{text:"",next:A.length};let ce=A.slice(T,te+1);return Dy(ce,F,j,q),{text:ce,next:te+1}}if(K!==void 0&&wy.test(K))return{text:`\${${K}}`,next:T+2};let ee=(q?Ay:/^\w*/).exec(A.slice(T+1))?.[0]??"";return{text:`\${${ee}}`,next:T+1+ee.length}}function Dy(A,T,F,j){let q=A.slice(2,-1),K=/^[A-Za-z_][A-Za-z0-9_]*/.exec(q)?.[0];if(!K)return;let ee=q.slice(K.length),te=[":=","="].find((de)=>ee.startsWith(de));if(!te)return;let ce=La(ee.slice(te.length),{...T},F,j);F.assignmentFallbacks.push(...ce.flatMap((de)=>typeof de==="string"||!de.text?[]:[de.text]))}function Ny(A,T){let F=1,j=T;while(F>0&&j<A.length){if(A[j]==="{"&&A[j-1]==="$")F++;else if(A[j]==="}")F--;j++}return F===0?j-1:-1}function Ly(A){return/^[\r\n]+$/.test(A)?";":A}function Un(A){return Object.freeze({kind:"operator",operator:A,boundary:_y.has(A)})}function ls(A){return Object.freeze({kind:"operator",operator:A,boundary:!0})}function Fa(A){return Object.freeze({kind:"word",text:A})}function Wy(A){if(A==="<<"||A==="<<<")return"here-data";if(A==="<"||A==="<&")return"file-read";return"file-write"}function Wa(A){return A.nodes.flatMap((T,F)=>{if(T.kind==="group"||T.kind==="function")return Wa(T.body);if(T.kind!=="command")return[];let j=T.nested.flatMap((ee)=>Wa(ee)),q=A.nodes[F+1];if(q?.kind==="connector"&&(q.operator==="|"||q.operator==="|&")||!zy(T))return j;return[...j,...T.redirections.flatMap((ee)=>ee.heredoc?.quotedDelimiter?[ee.heredoc.bodySpan]:[])]})}function Fy(A,T){let F=ss(A);return F===void 0?void 0:T.get(F)}function Sr(A,T){return A!==void 0&&A.provenance==="literal"&&!A.quoted&&A.raw===A.text&&A.text===T}function Gy(A){if(Sr(A.words[0],"git"))return Sr(A.words[1],"commit");if(!Sr(A.words[0],"gh")||!Sr(A.words[2],"create"))return!1;return Sr(A.words[1],"pr")||Sr(A.words[1],"issue")}function zy(A){return(Sr(A.words[0],"cat")||Sr(A.words[0],"tee")||Gy(A))&&!A.words.some(qu)&&!A.redirections.some((F)=>qu(F.target))}function qu(A){return A?.parts.some((T)=>T.provenance==="command-substitution"&&T.raw.startsWith(">("))??!1}import{types as By}from"node:util";var Uy=new Set(["applypatch","patch"]),$y=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),jy=new Set(["grep","grepsearch","rg"]),Hy=new Set(["find","findbyname","glob"]),Vy=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),qy=new Set(["command","diff","input","patch","patchtext"]),Xu=new TextEncoder,Ky=new TextDecoder,Yy=/\s/,Zy=64;class a extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var zo=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function nd(A){return A.replace(/[-_\s]/g,"").toLowerCase()}function us(A){return Vy.has(nd(A))}function ie(A){let T=nd(A);if(Uy.has(T))return"patch";if(jy.has(T))return"grep";if(Hy.has(T))return"glob";if($y.has(T))return"path";return"unknown"}function B(A){if(!A||typeof A!=="object")return;ad(A);let T=Object.getOwnPropertyDescriptor(A,"command");if(!T){if("command"in A)Jn();return}if(T.get||T.set)Jn();let F=T.value;return typeof F==="string"&&F!==""?F:void 0}function We(A,T){return rd(A,T,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function rd(A,T,F,j){let q=sd(A,F,j);if(!q)return[];let K=q.entries.flatMap(([ee,te])=>{let ce=rd(te,T,F,j+1);return typeof te==="string"&&T.has(od(ee))?[te]:ce});return F.ancestors.delete(q.object),K}function od(A){return A.replace(/-/g,"_").toLowerCase()}function Ue(A){return id(A,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Jy)}function id(A,T,F,j){let q=sd(A,F,j);if(typeof A==="string")return T?[A]:[];if(!q)return[];let K=q.entries.flatMap(([ee,te])=>id(te,q.array?T:qy.has(od(ee)),F,j+1));return F.ancestors.delete(q.object),K}function Xy(A,T,F){if(T.nodes++,A!==null&&typeof A==="object"&&F>zo.maxDepth||T.nodes>zo.maxNodes)Jn();if(typeof A!=="string")return;let j=Buffer.byteLength(A);if(T.stringBytes+=j,j>zo.maxStringBytes||T.stringBytes>zo.maxAggregateStringBytes)Jn()}function sd(A,T,F){if(Xy(A,T,F),!A||typeof A!=="object")return null;let j=ad(A);if(T.ancestors.has(A))Jn();let q=Reflect.ownKeys(A);if(T.keys+=q.length,T.keys>zo.maxKeys)Jn();let K=q.flatMap((ee)=>{let te=Object.getOwnPropertyDescriptor(A,ee);if(!te||te.get||te.set)Jn();return typeof ee==="string"&&te.enumerable?[[ee,te.value]]:[]});return T.ancestors.add(A),{object:A,array:j,entries:K}}function ad(A){if(By.isProxy(A))Jn();let T=Array.isArray(A),F=Object.getPrototypeOf(A);if(T&&F!==Array.prototype||!T&&F!==Object.prototype&&F!==null)Jn();return T}function Jn(){throw new a}function Jy(A){let T=[],F=A.split(/\r?\n/),j=!1,q=!1,K=null,ee=null,te=()=>{q=!1,K=null,ee=null};for(let ce=0;ce<F.length;ce++){let de=F[ce]??"";if(de==="*** Begin Patch"){j=!0,te();continue}if(de==="*** End Patch"){j=!1,te();continue}if(de.startsWith("@@")){let _e=Qy(de);if(q=!0,K=_e?.oldLines??null,ee=_e?.newLines??null,K===0&&ee===0)te();continue}if(q&&K!==null&&ee!==null){let _e=de.startsWith(" ")||de.startsWith("-")?1:0,Pe=de.startsWith(" ")||de.startsWith("+")?1:0;if(K=Math.max(0,K-_e),ee=Math.max(0,ee-Pe),K===0&&ee===0)te();continue}if(de.startsWith("*** ")){te(),T.push(...Ga(de));continue}if(q)continue;if(de.startsWith("diff --git ")){T.push(...Ga(de));continue}if(de.startsWith("--- ")){let _e=F[ce+1]??"";if(!_e.startsWith("+++ "))continue;T.push(...Ba(cs(de.slice(4),!0),cs(_e.slice(4),!0))),ce++;continue}if(!j)T.push(...Ga(de))}return T}function Qy(A){let T=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(A);if(!T)return null;return{oldLines:Number(T[1]??1),newLines:Number(T[2]??1)}}function Ga(A){let T=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(A);if(T?.[1])return td(T[1]);let F=/^\*\*\* Move to: (.+)$/.exec(A);if(F?.[1])return td(F[1]);if(A.startsWith("diff --git "))return eC(A.slice(11));let j=/^--- (.+)$/.exec(A);if(j?.[1])return ed(j[1]);let q=/^\+\+\+ (.+)$/.exec(A);if(q?.[1])return ed(q[1]);let K=/^(?:rename|copy) (?:from|to) (.+)$/.exec(A);if(K?.[1])return aC(K[1]);return[]}function eC(A){let T=tC(A);if(T.length===2&&T[0]&&T[1])return Ba(T[0],T[1]);let F=nC(A);return F?Ba(A.slice(F.oldStart,F.oldEnd),A.slice(F.newStart,F.newEnd)):[]}function tC(A){let T=[],F=0;while(F<A.length&&T.length<2){while(Lr(A[F]))F++;if(F>=A.length)break;let j=A[F]==='"'||A[F]==="'"?A[F]:void 0;if(!j){let K=F;while(F<A.length&&!Lr(A[F]))F++;T.push(A.slice(K,F));continue}let q=ld(A,F,j);if(!q)return[];T.push(q.value),F=q.end}while(Lr(A[F]))F++;return F===A.length?T:[]}function nC(A){let T=0;while(T<A.length&&Lr(A[T]))T++;let F=A.length;while(F>T&&Lr(A[F-1]))F--;let j=0,q=T;while(q<F){if(!Lr(A[q])){q++;continue}let K=q;while(q<F&&Lr(A[q]))q++;if(K===T||q===F)continue;if(j++,j>Zy)Jn();if(rC(A,T,K,q,F))return{oldStart:T,oldEnd:K,newStart:q,newEnd:F}}return null}function rC(A,T,F,j,q){if(za(A,T,F,j,q))return!0;let K=Ju(A,"/",T,F),ee=Ju(A,"/",j,q);if(K<=T||ee<=j)return!1;if(za(A,T,K,j,ee))return!1;return za(A,K+1,F,ee+1,q)}function za(A,T,F,j,q){if(F-T!==q-j)return!1;for(let K=0;K<F-T;K++)if(A[T+K]!==A[j+K])return!1;return!0}function Ju(A,T,F,j){for(let q=F;q<j;q++)if(A[q]===T)return q;return-1}function Lr(A){return A!==void 0&&Yy.test(A)}function ld(A,T,F){let j=[],q=T+1;while(q<A.length){let K=A[q]??"";if(K===F)return{value:Ky.decode(Uint8Array.from(j)),end:q+1};if(K!=="\\"||F==="'"){j.push(...Xu.encode(K)),q++;continue}let ee=A.slice(q+1),te=/^[0-7]{1,3}/.exec(ee)?.[0];if(te){j.push(Number.parseInt(te,8)),q+=te.length+1;continue}j.push(...Xu.encode(oC(ee[0]??""))),q+=2}return null}function oC(A){return{a:"\x07",b:"\b",f:"\f",n:`
30
+ `,r:"\r",t:"\t",v:"\v"}[A]??A}function iC(A){return Bo(lC(A))}function Ba(A,T){if(A==="/dev/null")return Qu(T);if(T==="/dev/null")return Qu(A);if(A.startsWith("a/")&&T.startsWith("b/"))return[A.slice(2),T.slice(2)].flatMap(Bo);let F=sC(A,T)??(A===T?cd(A):null);return[A,T,...F?[F]:[]].flatMap(Bo)}function Qu(A){let T=cd(A);return[A,...T?[T]:[]].flatMap(Bo)}function cd(A){let T=A.indexOf("/");return T>0&&T<A.length-1?A.slice(T+1):null}function sC(A,T){let F=A.indexOf("/"),j=T.indexOf("/");if(F<1||j<1)return null;if(A.slice(0,F)===T.slice(0,j))return null;let q=A.slice(F+1);return q===T.slice(j+1)?q:null}function ed(A){return iC(cs(A,!0))}function aC(A){return Bo(cs(A,!1))}function cs(A,T){let F=A.trim(),j=F[0]==='"'||F[0]==="'"?F[0]:void 0;if(j){let q=ld(F,0,j);if(q&&(T||F.slice(q.end).trim()===""))return q.value}return T?F.split("\t",1)[0]?.trim()??"":F}function lC(A){return A.startsWith("a/")||A.startsWith("b/")?A.slice(2):A}function Bo(A){return A===""||A==="/dev/null"?[]:[A]}function td(A){let T=A.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return T===""||T==="/dev/null"?[]:[T]}var ud=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),dd=new Set([...ud,"glob"]),cC=new Set([...dd,"pattern"]),uC=[],md={parseCommand:R,projectShellSyntax:Ku};class w extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function ye(A,T={}){let F=dt({...md,...T}),j=B(A.input),q=[];if((A.route.kind==="command"||A.route.kind==="unknown")&&j)q.push({usage:"input-candidate",source:j});if(A.route.kind==="command"&&"command"in A&&A.command)q.push({usage:"declared-command",source:A.command});let K=q.reduce((ee,te)=>{let ce=ee.findIndex((Pe)=>Pe.source===te.source);if(ce!==-1){let Pe=ee[ce];if(!Pe)return ee;return ee[ce]={...Pe,usages:[...Pe.usages,te.usage]},ee}let de=A.route.kind==="command"?A.route.shell:process.platform==="win32"?"powershell":"posix",_e=F.getCommandProgram(te.source,de);return ee.push({usages:[te.usage],source:te.source,program:_e,shell:F.getShellSyntax(te.source,_e)}),ee},[]);return{invocation:{toolName:A.toolName,route:A.route,context:A.context},commands:K,paths:dC(A),store:F}}function Sn(A,T){return A.commands.find((F)=>F.usages.includes(T))}function Qn(A){if(!A.includes("$"))return A;return Mi(A,L())}function dt(A={}){let T={...md,...A},F=new Map,j=new Map,q=new WeakMap,K=(te,ce)=>{let de=`${ce}\x00${te}`,_e=j.get(de);if(_e)return _e;let Pe=T.parseCommand(te,ce);return j.set(de,Pe),Pe};return{getShellSyntax:(te,ce)=>{if(ce&&ce.source!==te)throw TypeError("Shell syntax source does not match command program source.");let de=ce??K(te,"posix");if(de.status==="limited"){let je=q.get(de);if(je)return je;let it={status:"structural-limit",source:te,entries:uC,assignmentFallbacks:[]};return q.set(de,it),it}let _e=F.get(te);if(_e)return _e;let Pe=T.projectShellSyntax(te,de);return F.set(te,Pe),Pe},getCommandProgram:K}}function dC(A){let T=A.route.kind==="grep"?dd:A.route.kind==="glob"?cC:ud;return[...We(A.input,T),...A.route.kind==="patch"?Ue(A.input):[]]}function xn(A,T){let F=new Set,j=!1;for(let q of A){if(q==="--"){j=!0;continue}if(j)continue;if(q.startsWith("-")&&!q.startsWith("--")&&q.length>1)for(let K=1;K<q.length;K++){let ee=q[K];if(!ee||!/[a-zA-Z]/.test(ee))break;let te=`-${ee}`;if(F.add(te),T?.shortOptsWithValue?.has(te))break}}return F}var mC=new Map([["bash",new Set(["O","o"])],["dash",new Set(["o"])],["ksh",new Set(["o"])],["sh",new Set(["o"])],["zsh",new Set(["o"])]]),fC=new Map([["zsh",new Set(["o"])]]),pC=new Map([["bash",new Set(["--init-file","--rcfile"])]]);function fd(A,T){for(let F=0;F<T.length;F++){let j=T[F];if(j===void 0||j==="--"||j==="-"||j[0]!=="-"&&j[0]!=="+")return null;if(j.startsWith("--")){let ee=pC.get(A);if(hC(j,ee))continue;if(!ee?.has(j))continue;if(T[F+1]===void 0)return null;F++;continue}let q=gC(A,j);if(q.commandSelected)return T[F+q.followingValues+1]??null;let K=T[F+1];if(A==="ksh"&&(j==="-o"||j==="+o")&&K!==void 0&&K[0]!=="-"&&K[0]!=="+")F++;F+=q.followingValues}return null}function gC(A,T){let F=mC.get(A),j=fC.get(A),q=!1,K=0;for(let ee=1;ee<T.length;ee++){let te=T[ee];if(te===void 0)break;if(T[0]==="-"&&te==="c")q=!0;if(A==="ksh"&&te==="o"){if(ee+1<T.length){let ce=T.slice(ee+1);if(!q&&T[0]==="-"&&ce==="c")continue;if(!q&&T[0]==="-"&&ce[0]==="-"&&ce.endsWith("c"))q=!0;break}if(q)K++;continue}if(!F?.has(te))continue;if(j?.has(te)&&ee+1<T.length)break;K++}return{commandSelected:q,followingValues:K}}function hC(A,T){return T!==void 0&&[...T].some((F)=>A.startsWith(`${F}=`))}var bC=new Set(["-S","--suffix"]);function mo(A,T,F,j){if(A.status==="structural-limit")throw new w;if(A.status!=="complete")return j.findMalformedTarget(A.source);let q={cwd:T,variables:new Map},K=[];for(let ee of A.entries){if(ee.kind==="operator"){if(!ee.boundary)continue;let te=j.findSegmentTarget(K,q);if(te)return te;q=vC(K,q,F,j.normalizeCwd),K=[];continue}if(ee.kind==="redirection"){if(ee.role==="file-write"&&ee.target&&j.isRedirectionTarget(kn(ee.target,q.variables),q))return ee.target;continue}K.push(ee.text)}return j.findSegmentTarget(K,q)}function kn(A,T){return A.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(F,j,q,K)=>{let ee=T.get(j);if(ee===void 0)return F;let te=q.startsWith(":")?ee!=="":!0;if(q.endsWith("-"))return te?ee:kn(K,T);return te?kn(K,T):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(F,j)=>T.get(j)??F).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(F,j)=>T.get(j)??F)}function Uo(A){return A.length>0&&A.every((T)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(T))}function gd(A,T,F){let j=F.environment.home,q=Mi(A.trim(),F.environment).replace(/\\/g,"/");if(!q)return"";let K=q==="~"?j:q.startsWith("~/")?pd(j,q.slice(2)):q,ee=Pn(K);return SC(CC(ee)?ee:pd(T,ee))}function hn(A,T,F){let j=gd(A,T,F);if(!j)return"";return i(j,F.environment.paths,F).replace(/\\/g,"/")}function hd(A,T,F,j){let q=gd(A,T,F);if(!q)return null;if(j(yC(q)))return i(q,F.environment.paths,F).replace(/\\/g,"/");let K=eu(q,F.environment.paths,F);return K===null?null:K.replace(/\\/g,"/")}function ds(A){let T=[],F=null,j=!1;for(let q=0;q<A.length;q++){let K=A[q];if(K===void 0)break;if(!j&&K==="--"){j=!0;continue}if(!j&&(K==="-t"||K==="--target-directory")){F=A[++q]??null;continue}if(!j&&K.startsWith("--target-directory=")){F=K.slice(19);continue}if(!j&&K.startsWith("-t")&&K.length>2){F=K.slice(2);continue}if(!j&&bC.has(K)){q++;continue}if(!j&&(K.startsWith("--suffix=")||K.startsWith("--backup=")))continue;if(!j&&K.startsWith("-"))continue;T.push(K)}return F?{sources:T,destination:F}:{sources:T.slice(0,-1),destination:T.at(-1)??null}}function vC(A,T,F,j){let q=Uo(A)?new Map([...T.variables,...RC(A,T.variables)]):T.variables,K=yr([...A],F.environment),ee=Vt(K[0]??"").toLowerCase()==="cd"?K[1]:void 0;return{cwd:!ee||ee==="-"?T.cwd:j(kn(ee,q),T.cwd,F),variables:q}}function RC(A,T){return A.flatMap((F)=>{let j=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(F),q=j?.[2]?.startsWith("=")?j[2].slice(1):void 0;return j?.[1]!==void 0&&q!==void 0?[[j[1],kn(q,T)]]:[]})}var S="Git metadata and hooks are protected. Ask the user before modifying them.";function ze(A,T=Te([A.invocation.context.executionCwd,A.invocation.context.configCwd])){let F=ur(L()),j=A.invocation.context.executionCwd;if(!T)return null;if(A.invocation.route.kind==="patch"||A.invocation.route.kind==="path"||A.invocation.route.kind==="unknown"){if(us(A.invocation.toolName))return null;let ee=A.paths.find((te)=>TC(te,j,T,F));return ee?{target:ee}:null}if(A.invocation.route.kind!=="command")return null;let q=Sn(A,"input-candidate");if(!q)return null;let K=mo(q.shell,j,F,{findSegmentTarget:(ee,te)=>kC(ee,te,T,F),isRedirectionTarget:(ee,te)=>IC(ee,te.cwd,T,F),findMalformedTarget:()=>null,normalizeCwd:hn});return K?{target:K}:null}function Te(A,T=ur(L())){let F=[...new Map(A.filter((j)=>typeof j==="string"&&j!=="").flatMap((j)=>{let q=wo(hn(j,j,T));return q?[[$n(q),{dotGitPath:q,cwd:j}]]:[]})).values()].flatMap((j)=>_C(j.dotGitPath,j.cwd,T));if(F.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(F.map((j)=>j.entry))]),markerFiles:Object.freeze([...new Set(F.flatMap((j)=>j.markerFile?[j.markerFile]:[]))]),directories:Object.freeze([...new Set(F.flatMap((j)=>j.directories))]),hooksDirectories:Object.freeze([...new Set(F.flatMap((j)=>j.hooksDirectories))])})}function _C(A,T,F){try{let j=hn(A,T,F),q=xC(A),K=q.isFile()?j:null,ee=q.isFile()?da(A):null,te=(q.isDirectory()?[j]:[ee?.gitDir,ee?.commonDir]).flatMap((de)=>de?[$n(hn(de,T,F))]:[]),ce=[...new Set(q.isDirectory()?[$n(A.replace(/\\/g,"/")),...te]:te)];return[{entry:$n(j),markerFile:K?$n(K):null,directories:ce,hooksDirectories:[...new Set(ce.flatMap((de)=>{let _e=$n(EC(de,"hooks"));return[_e,$n(hn(_e,T,F))]}))]}]}catch{return[]}}function Wr(A,T,F,j,q,K=!1){if(!F)return!1;let ee=$n(hn(A,T,q)),te=ee.replace(/(\/\.?\*+)+$/,"");if(te!==ee&&te!==""){if(Ua(te,F))return!0;let ce=K||ee.slice(te.length).includes("/."),de=(_e)=>ce?ms(_e,te):PC(_e,te);if(F.markerFiles.some(de))return!0;return j&&yd(F).some(de)}if(Ua(ee,F))return!0;return j&&yd(F).some((ce)=>ms(ce,ee))}function PC(A,T){let F=Sd(T,A);if(F===""||F.startsWith("..")||Cd(F))return!1;return!F.split(/[\\/]/)[0]?.startsWith(".")}function wC(A,T,F,j){return Wr(A,T,F,!0,j)}function AC(A,T,F,j){if(!F)return!1;return Ua($n(hn(A,T,j)),F)}function TC(A,T,F,j){if(!F)return!1;return bd(A,T,F,j,F.entries)}function IC(A,T,F,j){if(!F)return!1;return bd(A,T,F,j,F.markerFiles)}function bd(A,T,F,j,q){let K=$n(hn(A,T,j));return q.includes(K)||Rd(K,F)}function vd(A,T,F,j){if(!F)return!1;return F.hooksDirectories.some((q)=>A.some((K)=>ms(q,$n(hn(K,T,j)))))}function Ua(A,T){return T.entries.includes(A)||T.directories.includes(A)||Rd(A,T)}function Rd(A,T){return T.hooksDirectories.some((F)=>ms(A,F))}function yd(A){return[...A.entries,...A.directories,...A.hooksDirectories]}function ms(A,T){let F=Sd(T,A);return F===""||!/^\.\.(?:[\\/]|$)/.test(F)&&!Cd(F)}function $n(A){return process.platform==="win32"?A.toLowerCase():A}function kC(A,T,F,j){if(Uo(A))return null;let q=Cr([...A],j.environment);if(Vt(q[0]??"").toLowerCase()!=="mv")return null;let K=ds(q.slice(1)),ee=K.sources.find((te)=>wC(kn(te,T.variables),T.cwd,F,j));if(ee)return ee;return K.destination&&AC(kn(K.destination,T.variables),T.cwd,F,j)?K.destination:null}import{isAbsolute as $a,join as OC,normalize as MC,sep as fs}from"node:path";var xd=process.platform==="win32",DC=/[*?]/;function $o(A,T){if(A==="~")return T;if(A.startsWith("~/"))return`${T}${A.slice(1)}`;return A}function gs(A,T){if(typeof A!=="string"||A.trim()==="")return"must be a non-empty path string";let F=$o(A.trim(),T);if(!$a(F))return"must be an absolute path or start with ~/";return jo(F,T)}function hs(A,T){let F=Ed(A,T);if(F===null)return"must be a non-empty path string";if(!$a(F))return null;if(jo(F,T)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var NC="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",LC="cannot cover the guard's own configuration";function Ed(A,T){if(typeof A!=="string"||A.trim()==="")return null;return $o(A.trim().replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),T)}function ys(A,T){let F=Ed(A,T);if(F===null)return"must be a non-empty path string";if(DC.test(F))return"cannot contain glob characters (* or ?); list the exact file or directory";if(!$a(F))return null;if(jo(F,T)!==null)return NC;return WC(F,T)?LC:null}function WC(A,T){let F=ps(A),j=ps(OC(T,".cc-safety-net"));return F===j||F.startsWith(`${j}${fs}`)}function jo(A,T){let F=ps(A),j=ps(T);if(F===j)return"cannot be the home directory";let q=F.endsWith(fs)?F:`${F}${fs}`;if(j.startsWith(q))return"cannot contain the home directory";return null}function ps(A){let T=MC(A);if(xd)T=T.replace(/\//g,"\\").toLowerCase();if(T.length>(xd?3:1)&&T.endsWith(fs))T=T.slice(0,-1);return T}var zC=process.platform==="win32",_d=64,BC=16384;function Ho(A){let T=Mu(A,_d,_d,BC);return{expandedTargets:T&&"words"in T?T.words:void 0,unsafeBraceExpansion:T!==void 0&&"limited"in T,targetIsLiteral:T===void 0&&A.provenance==="literal"&&(A.quoted||A.raw!==A.text),tmpdirWordSplittingProtected:UC(A)}}function UC(A){let T=A.parts.filter((F)=>F.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(F.raw));return T.length>0&&T.every((F)=>$C(A.raw,F.span.start-A.span.start))}function $C(A,T){let F=null,j=!1;for(let q=0;q<T;q++){let K=A[q];if(j){j=!1;continue}if(K==="\\"&&F!=="'"){j=!0;continue}if(F===K){F=null;continue}if(F===null&&(K==="'"||K==='"'))F=K}return F==='"'}function Fr(A){let T=A.environment.home,F=A.environment.paths,j=ur(A.environment);return{anchoredCwd:A.originalCwd??A.cwd??null,resolvedCwd:A.cwd??null,strict:A.strict??!1,paranoid:A.paranoid??!1,trustTmpdirVar:A.allowTmpdirVar??!0,posixShell:A.posixShell??!1,tmpdirWordSplittingUnsafe:A.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:A.trustedTmpdirValue??A.allowTmpdirVar??!0,environment:A.environment,allowRoots:KC(A.allowPaths,T,F,j),protectedGitMetadata:A.protectedGitMetadata,pathCanonicalizationContext:j}}function jn(A,T,F={}){let j=F.targetIsLiteral??!1;if(!j&&T.tmpdirWordSplittingUnsafe&&!F.tmpdirWordSplittingProtected&&ZC(A))return{kind:"outside_anchored_cwd"};let q=!j&&Td(A,T.posixShell);if(Ir(A))return{kind:"outside_anchored_cwd"};if(qa(A,j))return{kind:"root_or_home_target"};if(jC(A,T,j))return{kind:"root_or_home_target"};if(T.resolvedCwd&&Wr(A,T.resolvedCwd,T.protectedGitMetadata,!0,T.pathCanonicalizationContext,!T.posixShell))return{kind:"git_metadata_target"};if(HC(A,T.trustTmpdirVar,T.posixShell,q,j,F.tmpdirWordSplittingProtected??!1,T.trustedTmpdirValue,T.environment))return{kind:"temp_target"};if(q)return{kind:"dynamic_target"};if(YC(A,T,j))return{kind:"temp_target"};let K=T.anchoredCwd;if(K){if(!F.skipHomeCwd&&eS(K,T.environment.home,T.environment.paths,T.pathCanonicalizationContext))return{kind:"home_cwd_target"};if(!F.skipCwdSelf&&tS(A,T.resolvedCwd??K,T.environment.paths,T.pathCanonicalizationContext))return{kind:"cwd_self_target"};if(nS(A,K,T.resolvedCwd??K,q,j,T.environment.paths,T.pathCanonicalizationContext))return{kind:"within_anchored_cwd"}}return{kind:"outside_anchored_cwd"}}function wd(A,T,F={}){let{containmentTarget:j,...q}=F;if(jn(A,T,q).kind!=="temp_target")return!1;let K=A.trim();if(qC(K))return!1;if(pu(K,T.environment))return!1;return![T.anchoredCwd,T.resolvedCwd].some((ee)=>rS(j??K,ee,T.environment.paths,T.pathCanonicalizationContext))}function qa(A,T=!1){let F=A.trim(),j=Pd.normalize(F),q=F.replace(/\\/g,"/"),K=j==="/"?j:j.replace(/\/+$/,"");if(K==="/"||K.startsWith("/")&&K.slice(1).split("/").every((ee)=>/^\*+$/.test(ee)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(q)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(q))return!0;if(!T&&(j==="~"||j==="~/"||j==="~/*"))return!0;if(!T&&(j==="$HOME"||j==="$HOME/"||j==="$HOME/*"))return!0;if(!T&&(j==="${HOME}"||j==="${HOME}/"||j==="${HOME}/*"))return!0;return!1}function jC(A,T,F){let j=A.trim(),q=F?j:j==="*"?".":j.endsWith("/*")?j.slice(0,-2):j;if(!q)return!1;try{let K=Va(q)?q:T.resolvedCwd?fo(T.resolvedCwd,q):null;if(!K)return!1;let ee=En(i(K,T.environment.paths,T.pathCanonicalizationContext));if(ee===GC(ee).root)return!0;return ee===En(i(T.environment.home,T.environment.paths,T.pathCanonicalizationContext))}catch{return!1}}function En(A){let T=FC(A);if(zC){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 HC(A,T,F,j,q,K,ee,te){let ce=A.trim();if(Ad(ce))return!1;if(!j&&va(ce,te))return!0;return(T||K&&ee)&&F&&!q&&VC(ce,F)}function VC(A,T){return["$TMPDIR","${TMPDIR}"].some((F)=>{if(A===F)return!0;if(!A.startsWith(`${F}/`))return!1;return!Td(A.slice(F.length+1),T)})}function qC(A){let T=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(A);if(!T)return!1;return Pd.normalize(`/${T[1]??""}`)==="/"}function Ad(A){return A.split(/[\\/]+/).includes("..")}function KC(A,T,F,j){if(!A?.length)return[];return A.flatMap((q)=>{let K=$o(q.trim(),T);if(!Va(K))return[];try{let ee=i(K,F,j);if(jo(ee,i(T,F,j)))return[];return[En(ee)]}catch{return[]}})}function YC(A,T,F){if(T.allowRoots.length===0)return!1;let j=A.trim();if(Ad(j))return!1;let q=F?j:$o(j,T.environment.home),K=T.resolvedCwd??T.anchoredCwd,ee=Va(q)?q:K?fo(K,q):null;if(!ee)return!1;try{let te=En(i(ee,T.environment.paths,T.pathCanonicalizationContext));return T.allowRoots.some((ce)=>te===ce||te.startsWith(ce.endsWith(Ha)?ce:`${ce}${Ha}`))}catch{return!1}}function ZC(A){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(A)}function Td(A,T=!1){return A.includes("$")||A.includes("`")||XC(A)||T&&JC(A)}function XC(A){let T=!1;for(let F of A){if(T){T=!1;continue}if(F==="\\"){T=!0;continue}if(F==="*"||F==="?"||F==="[")return!0}return!1}function JC(A){let T=!1;for(let F=0;F<A.length;F++){let j=A[F];if(T){T=!1;continue}if(j==="\\"){T=!0;continue}if(j==="{"&&QC(A,F)||(j==="+"||j==="@"||j==="!")&&A[F+1]==="(")return!0}return!1}function QC(A,T){let F=A.indexOf("}",T+1);if(F===-1)return!1;let j=A.slice(T+1,F);return j.includes(",")||j.includes("..")}function eS(A,T,F,j){try{return En(i(A,F,j))===En(i(T,F,j))}catch{try{return En(A)===En(T)}catch{return!1}}}function tS(A,T,F,j){if(A==="."||A==="./"||A===".\\")return!0;try{return En(i(fo(T,A),F,j))===En(i(T,F,j))}catch{try{return En(fo(T,A))===En(T)}catch{return!1}}}function nS(A,T,F,j,q,K,ee){let te=F??T;if(!q&&(A.startsWith("~")||A.startsWith("$HOME")||A.startsWith("${HOME}")))return!1;if(j)return!1;if(A.startsWith("/")||/^[A-Za-z]:[\\/]/.test(A))try{return ja(A,T,K,ee)}catch{return!1}if(A.startsWith("./")||A.startsWith(".\\")||!A.includes("/")&&!A.includes("\\"))try{return ja(fo(te,A),T,K,ee)}catch{return!1}if(A.startsWith("../"))return!1;try{return ja(fo(te,A),T,K,ee)}catch{return!1}}function ja(A,T,F,j){try{return Id(i(A,F,j),i(T,F,j))}catch{return!1}}function rS(A,T,F,j){if(!T)return!1;try{return Id(i(T,F,j),i(A,F,j))}catch{return!0}}function Id(A,T){let F=En(A),j=En(T);return F.startsWith(`${j}${Ha}`)||F===j}var oS=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),kd="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",iS="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.",Od="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",Md="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",sS="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",aS="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.";function Dd(A,T,F,j=Fr({...F,allowPaths:F.policy?.destructiveCommandAllowPaths})){return lS(A.words.map((q)=>({kind:"word",text:q.text,dynamic:q.provenance!=="literal"})),T,j,F.policy)}function lS(A,T,F,j){let q=A.filter((ce)=>ce.kind==="word"),K=uS(q),ee=q[K];if(!ee||!oS.has(SS(ee.text)))return null;let te=cS(q.slice(K+1));if(te.whatIfProtected)return null;if(mn(j,"powershell.remove-item-pipeline-dynamic-target",F.strict)&&T&&(te.targets.length===0||te.recursive))return It("powershell.remove-item-pipeline-dynamic-target",aS);for(let ce of te.targets)if(!Ir(ce.text)&&qa(Ya(ce.text)))return It(te.recursive&&te.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Md);for(let ce of te.targets)if(F.resolvedCwd&&Wr(Ya(ce.text),F.resolvedCwd,F.protectedGitMetadata,te.recursive,F.pathCanonicalizationContext,!0))return It("powershell.remove-item-git-metadata",S);if(!te.recursive||!te.force)return null;if(mn(j,"powershell.remove-item-recursive-force-dynamic-target",F.strict)&&(te.hasDynamicTarget||te.targets.length===0))return It("powershell.remove-item-recursive-force-dynamic-target",Od);for(let ce of te.targets){let de=bS(jn(Ya(ce.text),F),F,j);if(de)return de}return null}function cS(A){let T=[],F=!1,j=!1,q=!1,K=!1,ee=!1;for(let te=0;te<A.length;te++){let ce=A[te];if(!ce||ce.kind!=="word")continue;if(dS(ce))continue;if(ee){T.push(Ka(ce)),K=K||ce.dynamic;continue}if(ce.text==="--"){ee=!0;continue}let de=fS(ce.text);if(!de){T.push(Ka(ce)),K=K||ce.dynamic;continue}if(pS(de.name)){let _e=de.value?mS(de.value,ce):A[++te];if(_e?.kind==="word")T.push(Ka(_e)),K=K||_e.dynamic;else K=!0;continue}if(gS(de.name)){F=!0;continue}if(hS(de.name)){j=!0;continue}if(yS(de.name))q=CS(de.value)}return{targets:T,recursive:F,force:j,whatIfProtected:q,hasDynamicTarget:K}}function uS(A){let T=A[0];if(T?.kind==="word"&&T.text==="&"||T?.text===".")return A.length>1?1:0;return 0}function Ka(A){return{text:A.kind==="word"?A.text:"",dynamic:A.kind==="word"&&A.dynamic}}function dS(A){return A.kind==="word"&&A.text===","}function Ya(A){let T=A.replace(/\\/g,"/"),F=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(T);return F?`$HOME${T.slice(F[0].length)}`:T}function mS(A,T){return{kind:"word",text:A,dynamic:T.kind==="word"&&(T.dynamic||A.includes("$"))}}function fS(A){if(!A.startsWith("-")||A==="-")return null;let T=A.slice(1),F=T.indexOf(":");if(F===-1)return{name:T.toLowerCase()};return{name:T.slice(0,F).toLowerCase(),value:T.slice(F+1)}}function pS(A){return"path".startsWith(A)||"literalpath".startsWith(A)}function gS(A){return"recurse".startsWith(A)}function hS(A){return A.length>=2&&"force".startsWith(A)}function yS(A){return A==="wi"||"whatif".startsWith(A)}function CS(A){if(A===void 0||A==="")return!0;let T=A.toLowerCase();return T==="$true"||T==="true"}function SS(A){return A.toLowerCase()}function bS(A,T,F){switch(A.kind){case"root_or_home_target":return It("powershell.remove-item-recursive-force-root-or-home",Md);case"git_metadata_target":return It("powershell.remove-item-git-metadata",S);case"temp_target":return null;case"dynamic_target":if(!mn(F,"powershell.remove-item-recursive-force-dynamic-target",T.strict))return null;return It("powershell.remove-item-recursive-force-dynamic-target",Od);case"home_cwd_target":return It("powershell.remove-item-recursive-force-home-cwd",sS);case"cwd_self_target":return It("powershell.remove-item-recursive-force-cwd-self",kd);case"within_anchored_cwd":if(!mn(F,"powershell.remove-item-recursive-force-paranoid",T.paranoid))return null;return It("powershell.remove-item-recursive-force-paranoid",iS);case"outside_anchored_cwd":return It("powershell.remove-item-recursive-force-outside-cwd",kd)}}import{normalize as Ms}from"node:path";var On=new Set(["awk","gawk","nawk","mawk"]),vS=new Set(["-e","--source"]),RS=new Set(["-F","-v","--assign","--field-separator"]),Nd=new Set(["-f","--file"]),xS=new Set(["print","printf","return"]),Ld=[{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"}],ES="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 bs(A,T,F){let j=!1;for(let q of _S(A)){let K=PS(q,F);if(!K)continue;for(let ee of K.commands){let te=T(ee);if(te)return te;if(ee.includes("{}")||/[$`]/.test(ee))j=!0}j||=K.dynamic}return j?It("awk.system-dynamic",ES):null}function Xa(A){let T=[],F=!1,j=!1,q=!0,K=!0;for(let ee=1;ee<A.length;ee++){let te=A[ee];if(te===void 0)break;if(q&&te==="--"){q=!1;continue}if(q&&vS.has(te)){F=!0;let ce=A[ee+1];if(ce!==void 0)T.push({tokenIndex:ee+1,kind:"inline-code",value:ce});else K=!1;ee++;continue}if(q&&te.startsWith("--source=")){F=!0,T.push({tokenIndex:ee,kind:"inline-code",value:te.slice(9)});continue}if(q&&te.startsWith("-e")&&te.length>2){F=!0,T.push({tokenIndex:ee,kind:"inline-code",value:te.slice(2)});continue}if(q&&(RS.has(te)||Nd.has(te))){if(Nd.has(te)){j=!0;let ce=A[ee+1];if(ce!==void 0)T.push({tokenIndex:ee+1,kind:"program-file",value:ce});else K=!1}else if(A[ee+1]===void 0)K=!1;ee++;continue}if(q&&(te.startsWith("-F")||te.startsWith("-v")&&te.slice(2).includes("=")))continue;if(q&&te.startsWith("-f")&&te.length>2){j=!0,T.push({tokenIndex:ee,kind:"program-file",value:te.slice(2)});continue}if(q&&(te.startsWith("--assign=")||te.startsWith("--field-separator=")))continue;if(q&&te.startsWith("--file=")){j=!0,T.push({tokenIndex:ee,kind:"program-file",value:te.slice(7)});continue}if(q&&te.startsWith("-")&&te!=="-")continue;if(q=!1,!F&&!j)T.push({tokenIndex:ee,kind:"main-program",value:te});return{sources:T,optionsOpen:!1}}return{sources:K?T:[],optionsOpen:q&&K}}function qo(A){return Xa(A).sources}function _S(A){return qo(A).filter((T)=>T.kind!=="program-file").map((T)=>T.value)}function PS(A,T){wn(T,A);let F=A.includes("system")?Ja(A,T):null,j=wS(A,T);if(!F&&!j)return null;return{dynamic:!!F?.dynamic||!!j?.dynamic,commands:[...F?.commands??[],...j?.commands??[]]}}function Ja(A,T){wn(T,A);let F=[],j=!1,q=!1,K=0;while(K<A.length){let ee=A[K];if(ee==='"'||ee==="'"){K=Ss(A,K,ee)?.endIndex??K+1;continue}if(ee==="#"){K=Wd(A,K+1);continue}if(ee==="/"&&Fd(A,K)){K=Gd(A,K+1)??K+1;continue}if(!A.startsWith("system",K)){K++;continue}let te=K;if(K+=6,Vo(A[te-1])||Vo(A[K]))continue;let ce=Cs(A,K);if(A[ce]!=="(")continue;ce=Cs(A,ce+1);let de=A[ce];if(de!=='"'&&de!=="'"){j=!0,q=!0;continue}let _e=Ss(A,ce,de);if(!_e){j=!0,q=!0;continue}if(ce=Cs(A,_e.endIndex),j=!0,A[ce]!==")"){q=!0,K=_e.endIndex;continue}F.push(_e.value),K=ce+1}if(!j)return null;return{dynamic:q,commands:F}}function wS(A,T){wn(T,A);let F=[],j=!1,q=!1,K=0,ee=0,te=null,ce=null,de=0;while(K<A.length){let _e=A[K];if(!_e)break;if(_e==='"'||_e==="'"){let it=Ss(A,K,_e);if(it&&de===ee)ce={...it,startIndex:K};de=it?.endIndex??K+1,K=it?.endIndex??K+1;continue}if(_e==="#"){K=Wd(A,K+1),ee=K,te=null,ce=null,de=K;continue}if(_e==="/"&&Fd(A,K)){let it=Gd(A,K+1);de=it??K+1,K=it??K+1;continue}if(`;
31
+ {}`.includes(_e)){K++,ee=K,te=null,ce=null,de=K;continue}if(te===null&&(Za(A,K,"print")||Za(A,K,"printf")))te=K;if(_e!=="|"||A[K-1]==="|"||A[K+1]==="|"){if(!/\s/.test(_e))de=K+1;K++;continue}let Pe=A[K+1]==="&"?K+2:K+1,je=Cs(A,Pe);if(Za(A,je,"getline")){q=!0;let it=IS(ee,ce,de);if(it===null)j=!0;else F.push(it);de=Pe,K=Pe;continue}if(OS(ee,te)){q=!0;let it=TS(A,je);if(!it){j=!0,de=Pe,K=Pe;continue}if(!AS(A,it.endIndex)){j=!0,de=it.endIndex,K=it.endIndex;continue}F.push(it.value),de=it.endIndex,K=it.endIndex;continue}de=Pe,K++}if(!q)return null;return{dynamic:j,commands:F}}function Vo(A){return!!A&&/[A-Za-z0-9_]/.test(A)}function Cs(A,T){let F=T;while(/\s/.test(A[F]??""))F++;return F}function AS(A,T){let F=T;while(/[\t\f\v\r ]/.test(A[F]??""))F++;let j=A[F];return!j||`;
32
+ }#`.includes(j)}function Ss(A,T,F){let j="",q=!1;for(let K=T+1;K<A.length;K++){let ee=A[K];if(!ee)break;if(q){let te=kS(A,K);if(!te)return null;j+=te.value,K=te.endIndex,q=!1;continue}if(ee==="\\"){q=!0;continue}if(ee===F)return{value:j,endIndex:K+1};j+=ee}return null}function TS(A,T){let F=A[T];if(F!=='"'&&F!=="'")return null;return Ss(A,T,F)}function IS(A,T,F){if(!T)return null;return T.startIndex>=A&&T.endIndex===F?T.value:null}function kS(A,T){let F=A[T];if(!F)return null;if(F==="x"){let q=A.slice(T+1,T+3);if(!/^[0-9A-Fa-f]{2}$/.test(q))return null;return{value:String.fromCharCode(Number.parseInt(q,16)),endIndex:T+2}}if(/[0-7]/.test(F)){let q=/^[0-7]{1,3}/.exec(A.slice(T));if(!q)return null;return{value:String.fromCharCode(Number.parseInt(q[0],8)),endIndex:T+q[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
33
+ `,r:"\r",t:"\t",v:"\v"}[F]??F,endIndex:T}}function Za(A,T,F){return A.startsWith(F,T)&&!Vo(A[T-1])&&!Vo(A[T+F.length])}function OS(A,T){return T!==null&&T>=A}function Wd(A,T){let F=A.indexOf(`
34
+ `,T);return F===-1?A.length:F+1}function Fd(A,T){let F=MS(A,T);if(F===-1)return!0;if("{([,;!~=".includes(A[F]??""))return!0;let j=F;while(Vo(A[j-1]))j--;return xS.has(A.slice(j,F+1))}function MS(A,T){for(let F=T-1;F>=0;F--)if(!/\s/.test(A[F]??""))return F;return-1}function Gd(A,T){let F=!1;for(let j=T;j<A.length;j++){let q=A[j];if(!q)break;if(F){F=!1;continue}if(q==="\\"){F=!0;continue}if(q==="/")return j+1}return null}var zd=new Set(["rm","find","xargs","parallel"]),DS=new Set(["sudo","env","command","builtin"]),NS=new Set(["git","busybox",...zd,...fn,...ou,...On]);function vs(A,T){let F=A[0];if(!F||!T.transparentWrappers.includes(Vt(F)))return null;let j=Vt(F),q=A[1]==="--"?2:1,K=LS(A,q,j,T),ee=K[0];if(ee===void 0)return null;return{wrapper:j,tokens:[...A.slice(ee)],childIndex:ee,alternativeChildIndices:K.slice(1)}}function LS(A,T,F,j){let q=A[1]==="--",K=[];for(let ee=T;ee<A.length;ee++){let te=A[ee];if(!te)continue;if(Vt(te)!==F&&WS(te,j))K.push(ee);else if(Ni.has(Qt(te)))break;if(q)break}return K}function WS(A,T){let F=Vt(A),j=Qt(A);return j==="git"||F==="busybox"||Gr(A)||zd.has(F)||T.transparentWrappers.includes(F)||fn.has(j)||A==="$SHELL"||Tn(j)||On.has(j)||T.rules.some((q)=>q.command===F)}function Gr(A){return DS.has(A.toLowerCase())}function Ie(A){let T=Qt(A);return NS.has(T)||Tn(T)}function Hn(A,T){let F=T.policy??{rules:[],transparentWrappers:[]};return Rs([...A],T.environment,T.cwd,T.cwd,new Map,new Map(T.envAssignments??[]),F,{iterations:0},!1)}function*Rs(A,T,F,j,q,K,ee,te,ce){let de=qi(A,T,F,K);for(let[it,st]of de.envAssignments)K.set(it,st),q.set(it,st);let{tokens:_e,cwd:Pe}=de;if(de.envSplitValues){let it=Vi(de.envSplitValues,_e);if(!it)throw new An;Qa(te),yield*Rs(it,T,Pe,j,q,K,ee,te,ce);return}if(Gr(_e[0]??""))throw new An;let je=vs(_e,ee);if(je){for(let it of[je.childIndex,...je.alternativeChildIndices])Qa(te),yield*Rs(it===je.childIndex?je.tokens:[..._e.slice(it)],T,Pe,j,new Map(q),new Map(K),ee,te,!0);return}if(GS(_e)){Qa(te),yield*Rs([..._e.slice(1)],T,Pe,j,q,K,ee,te,ce);return}yield FS(_e,Pe,j,q,K,ce)}function FS(A,T,F,j,q,K){return{tokens:A,cwd:T===null?void 0:T??F,wrapperCwd:T,wrapperEnvAssignments:j,envAssignments:q,head:Vt(A[0]??"").toLowerCase(),wrappedByTransparent:K}}function Qa(A){if(A.iterations>=ro)throw new An;A.iterations++}function GS(A){return Vt(A[0]??"").toLowerCase()==="busybox"&&A.length>1}function el(A,T){let F=[],j=T;while(j<A.length){let q=A[j];if(q===void 0||q===":::")break;F.push(q),j++}return{markerIndex:j<A.length&&A[j]===":::"?j:-1,templateTokens:F}}function Vn(A){let T=!1,F=!1;for(let j of A){if(j==="--")break;if(j==="-r"||j==="-R"||tl(j,"recursive"))T=!0;else if(j==="-f"||tl(j,"force"))F=!0;else if(j.startsWith("-")&&!j.startsWith("--")){if(j.includes("r")||j.includes("R"))T=!0;if(j.includes("f"))F=!0}}return T&&F}function Bd(A){let T=A.indexOf("--");return A.slice(1,T===-1?void 0:T).some((F)=>tl(F,"recursive")||/^-[A-Za-z]+$/.test(F)&&/[rR]/.test(F.slice(1)))}function tl(A,T){return A.length>2&&A.startsWith("--")&&T.startsWith(A.slice(2))}var zS="find -delete permanently removes files. Use -print first to preview.",BS="find -exec rm -rf is dangerous. Use explicit file list instead.",US=new Set(["-exec","-execdir","-ok","-okdir"]),$S=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((A)=>[A,1]),["-fprintf",2]]);function xs(A,T){let F=A.map(e),j=jS(A,F,T);if(j)return j;if(_s(F,1)&&!VS(A,F,T)){let ee=jt(It("find.delete",zS),T.policy);if(ee)return ee}let q=T.derivedCommandWorkBudget??ki(),K=0;while(K<F.length){let ee=F[K],te=br(ee??"");if(te>0){K+=te+1;continue}if(!mr(ee)){K++;continue}Gn(q,F.length-K-1);let ce=Ko(F,K);K=ce.nextIndex;let de=KS(ce.tokens,T.environment);if(de){let it=jt(de,T.policy);if(it)return it}let _e=ee==="-execdir"||ee==="-okdir",Pe=T.analyzeTokens?T.analyzeTokens(ce.tokens,_e?null:T.cwd):T.analyzeNested?T.analyzeNested(ce.tokens.join(" "),{effectiveCwd:_e?void 0:T.cwd,envAssignments:T.envAssignments}):null,je=Pe?.id.startsWith("custom.")?Pe:jt(Pe,T.policy);if(je)return je}return null}function jS(A,T,F){if(!_s(T,1)&&!nl(T,F.environment))return null;let q=Es(A)??Yt(["."]),K=Fr({...F,allowPaths:F.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let ee of q){let te=Ho(ee);for(let ce of te.expandedTargets??[e(ee)]){let de=jn(ce,K,{targetIsLiteral:te.expandedTargets!==void 0||te.targetIsLiteral,tmpdirWordSplittingProtected:te.tmpdirWordSplittingProtected});if(de.kind==="root_or_home_target")return It("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(de.kind==="git_metadata_target")return It("find.delete-git-metadata",S)}}if(HS(T)&&K.resolvedCwd&&vd(q.map(e),K.resolvedCwd,K.protectedGitMetadata,K.pathCanonicalizationContext))return It("find.delete-git-metadata",S);return null}function nl(A,T){let F=0;while(F<A.length){if(!mr(A[F])){F++;continue}let j=Ko(A,F),q=Cr([...j.tokens],T),K=Vt(q[0]??"").toLowerCase();if((K==="rm"||K==="rmdir")&&q.some((ee)=>ee.includes("{}")))return!0;F=j.nextIndex}return!1}function HS(A){return A.some((T,F)=>{if(!["-name","-iname"].includes(T))return!1;return A[F+1]?.toLowerCase()==="hooks"})}function VS(A,T,F){if(T.includes("-L")||T.includes("-f")||T.includes("-follow"))return!1;let j=Es(A);if(!j)return!1;let q=F.envAssignments??new Map,K=ba(q,F.environment),ee=F.trustedTmpdirValue??dr(q,F.environment),te=F.allowTmpdirVar??!Mo(q,F.environment),ce=Fr({environment:F.environment,protectedGitMetadata:F.protectedGitMetadata,cwd:F.cwd,originalCwd:F.originalCwd,strict:F.strict,allowTmpdirVar:te&&ee&&Boolean(K),allowPaths:F.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:F.tmpdirWordSplittingUnsafe??Xn(q,F.environment),trustedTmpdirValue:ee});return j.every((de)=>{let _e=Ho(de);if(_e.unsafeBraceExpansion)return!1;return(_e.expandedTargets??[e(de)]).every((Pe)=>wd(Pe,ce,{containmentTarget:qS(Pe,K),targetIsLiteral:_e.expandedTargets!==void 0||_e.targetIsLiteral,tmpdirWordSplittingProtected:_e.tmpdirWordSplittingProtected}))})}function qS(A,T){if(!T)return A;return A.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>T)}function Es(A){let T=(q)=>{let K=A[q];return K?e(K):void 0},F=1;while(T(F)==="-H"||T(F)==="-P")F++;if(T(F)==="--")F++;let j=[];while(F<A.length){let q=T(F),K=A[F];if(!q||!K||q.startsWith("-")||["!","(",")"].includes(q))break;j.push(K),F++}return j.length>0?j:null}function KS(A,T){let F=yr([...A],T);if(F.length===0)return null;let j=Vt(F[0]??"");if(j==="busybox"&&F.length>1)F=F.slice(1),j=Vt(F[0]??"");if(j==="rm"&&Vn(F))return It("find.exec-rm-recursive-force",BS);return null}function Ko(A,T){let F=T+1;while(F<A.length&&A[F]!==";"&&!(A[F]==="+"&&A[F-1]==="{}"))F++;return{tokens:A.slice(T+1,F),nextIndex:Math.min(F+1,A.length)}}function _s(A,T){let F=T;while(F<A.length){let j=A[F];if(!j){F++;continue}if(mr(j)){F=Ko(A,F).nextIndex;continue}let q=br(j);if(q>0){F+=q+1;continue}if(j==="-delete")return!0;F++}return!1}function br(A){return $S.get(A)??(/^-newer[A-Za-z]{2}$/.test(A)?1:0)}function mr(A){return A!==void 0&&US.has(A)}function*rl(A){for(let T of A.nodes)yield*ZS(T)}function YS(A){return Object.freeze([...rl(A)])}function wt(A){return Object.freeze(YS(A).map((T)=>Object.freeze(T.words.map((F)=>F.text))))}function Yo(A){let T=R(A,"posix");if(T.status!=="complete"||T.nodes.length!==1)return null;let F=T.nodes[0];if(F?.kind!=="command")return null;if(F.redirections.length>0||F.nested.length>0)return null;if(F.words.some((j)=>j.provenance==="command-substitution"))return null;return F.words.map((j)=>j.text)}function*ZS(A){if(A.kind==="command"){yield A;for(let T of A.nested)yield*rl(T);return}if(A.kind==="group")yield*rl(A.body)}var XS=5,ol="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 bn(A){let T=A.indexOf("--");if(T===-1)return{index:-1,before:A,after:[]};return{index:T,before:A.slice(0,T),after:A.slice(T+1)}}function $d(A,T,F){let j=Hd(A,T,F),q=JS(j.entries);if(q.size===0)return{blockedReason:j.blockedReason,expanded:!1,tokens:A};let K=A,ee=!1;for(let te=0;te<XS;te++){let{subcommand:ce,rest:de}=qn(K),_e=ce?.toLowerCase();if(!_e||!q.has(_e))return{blockedReason:j.blockedReason,expanded:ee,tokens:K};let Pe=q.get(_e),je=rb(Pe);if(je===null||je.length===0)return{blockedReason:ol,expanded:!0,tokens:K};K=["git",...je,...de],ee=!0}return{blockedReason:ol,expanded:!0,tokens:K}}function jd(A,T,F){return Hd(A,T,F).entries.some((j)=>j.key.toLowerCase()==="core.sshcommand")}function qn(A){if(A.length===0)return{subcommand:null,rest:[]};let T=A[0];if((T?Vt(T).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let j=1;while(j<A.length){let q=A[j];if(!q)break;if(q==="--"){let K=A[j+1];if(K&&!K.startsWith("-"))return{subcommand:K,rest:A.slice(j+2)};return{subcommand:null,rest:A.slice(j+1)}}if(q.startsWith("-"))if(vn.has(q))j+=2;else if(q.startsWith("-c")&&q.length>2)j++;else if(q.startsWith("-C")&&q.length>2)j++;else j++;else return{subcommand:q,rest:A.slice(j+1)}}return{subcommand:null,rest:[]}}function JS(A){let T=new Map;for(let F of A){let j=F.key.toLowerCase();if(!j.startsWith("alias."))continue;let q=j.slice(6);if(q!=="")T.set(q,F.value)}return T}function Hd(A,T,F){if(A.length===0)return{blockedReason:null,entries:[]};let j=A[0];if((j?Vt(j).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let K=eb(T,F);return{blockedReason:K.blockedReason,entries:[...K.entries,...QS(A,T,F)]}}function QS(A,T,F){let j=[],q=1;while(q<A.length){let K=A[q];if(!K||K==="--"||!K.startsWith("-"))return j;if(K==="-c"){let ee=il(A[q+1]);if(ee)j.push(ee);q+=2;continue}if(K.startsWith("-c")&&K.length>2){let ee=il(K.slice(2));if(ee)j.push(ee);q++;continue}if(K==="--config-env"){let ee=Ud(A[q+1],T,F);if(ee)j.push(ee);q+=2;continue}if(K.startsWith("--config-env=")){let ee=Ud(K.slice(13),T,F);if(ee)j.push(ee);q++;continue}if(vn.has(K)){q+=2;continue}q++}return j}function eb(A,T){let F=tb(A,T),j=nb(A,T);return{blockedReason:F===null||j===null?ol:null,entries:[...F??[],...j??[]]}}function tb(A,T){let F=Nn("GIT_CONFIG_PARAMETERS",A,T);if(F===void 0)return[];let j=[],q=Yo(F);if(!q)return null;for(let K of q){let ee=il(K);if(!ee)return null;j.push(ee)}return j}function nb(A,T){let F=xi(A,T);if(F.state==="absent")return[];if(F.state==="invalid")return null;let j=[];for(let q=0;q<F.count;q++){let K=Nn(`GIT_CONFIG_KEY_${q}`,A,T)?.trim(),ee=Nn(`GIT_CONFIG_VALUE_${q}`,A,T);if(!K||ee===void 0)return null;j.push({key:K,value:ee})}return j}function il(A){if(!A)return null;let T=A.indexOf("=");return{key:(T===-1?A:A.slice(0,T)).trim(),value:T===-1?void 0:A.slice(T+1)}}function Ud(A,T,F){let j=A?.indexOf("=")??-1;if(!A||j===-1)return null;return{key:A.slice(0,j).trim(),value:Nn(A.slice(j+1),T,F)}}function rb(A){let T=A?.trimStart();if(!T||T.startsWith("!"))return null;return Yo(T)}var ob="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",ib="git checkout --force discards uncommitted changes. Use 'git stash' first.",sb="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",ab="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",lb="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",cb="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",ub="git switch --force discards uncommitted changes. Use 'git stash' first.",db="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",mb="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",fb="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",pb="git reset --merge can lose uncommitted changes. Use 'git stash' first.",gb="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",hb="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.",yb="git push --force destroys remote history. Use --force-with-lease for safer force push.",Cb="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",Sb="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",bb="git branch -D force-deletes without merge check. Use -d for safe delete.",vb="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",Rb="git merge --abort discards merge conflict resolutions. Use 'git status' first.",xb="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",Eb="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",_b="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",Pb="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",wb="git worktree remove --force can delete uncommitted changes. Remove --force flag.",Vd=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),qd=new Set(["--recurse-submodules","--track","-t"]),sl=new Set(["-b","-B","-U"]),al=new Set(["-c","-C"]),Ab=new Set(["--source","--conflict","--unified","--inter-hunk-context"]),Tb=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 qt(A,T){let F=A.split("=",1)[0]??A;return F.length>=4&&T.startsWith(F)&&F.startsWith("--")&&F.slice(2).length>=2}var po=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function Yd(A){let{subcommand:T,rest:F}=qn(A);if(!T)return null;switch(T.toLowerCase()){case"checkout":return vr(Ib(F));case"switch":return vr(kb(F));case"restore":return vr(Mb(F));case"reset":return Nb(F);case"clean":return vr(Wb(F));case"rm":return vr(Fb(F));case"push":return zr(Gb(F));case"branch":return zr(Ub(F));case"stash":return zr(qb(F));case"worktree":return zr(Kb(F));case"rebase":return vr($b(F));case"merge":return vr(jb(F));case"tag":return zr(Hb(F));case"reflog":return zr(Vb(F));default:return null}}function vr(A){return A?{...A,localDiscard:!0}:null}function zr(A){return A?{...A,localDiscard:!1}:null}function Ib(A){let{index:T,before:F}=bn(A),j=xn(F,{shortOptsWithValue:sl});if(F.some((K)=>qt(K,"--force"))||j.has("-f"))return It("git.checkout-force",ib);for(let K of A){if(K==="-b"||K==="-B"||K==="--orphan")return null;if(qt(K,"--pathspec-from-file"))return It("git.checkout-pathspec-from-file",ab)}if(T!==-1){if(F.some((ee)=>!ee.startsWith("-")))return It("git.checkout-ref-path",sb);return It("git.checkout-double-dash",ob)}if(Ob(A).length>=2)return It("git.checkout-ambiguous",lb);return null}function kb(A){let{before:T}=bn(A);if(T.some((j)=>qt(j,"--discard-changes")))return It("git.switch-discard-changes",cb);let F=xn(T,{shortOptsWithValue:al});if(T.some((j)=>qt(j,"--force"))||F.has("-f"))return It("git.switch-force",ub);return null}function Ob(A){let T=[],F=0;while(F<A.length){let j=A[F];if(!j)break;if(j==="--")break;if(j.startsWith("-"))if(Vd.has(j))F+=2;else if(j.startsWith("--")&&j.includes("="))F++;else if(qd.has(j)){let q=A[F+1];if(q&&!q.startsWith("-")&&(j==="--recurse-submodules"||j==="--track"||j==="-t"))if((j==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"]).includes(q))F+=2;else F++;else F++}else if(j.startsWith("--")&&!Tb.has(j)&&!Vd.has(j)&&!qd.has(j))F++;else F++;else T.push(j),F++}return T}function Mb(A){let T=Db(A);if(T.isTerminal||!T.hasPathspec&&!T.hasPatch||!T.hasWorktree)return null;return T.hasExplicitLocation?It("git.restore-worktree",mb):It("git.restore-unstaged",db)}function Db(A){let T=!1,F=!1,j=!0,q=!1,K=(ee)=>{if(!q)j=!1,q=!0;if(ee!==void 0)j=ee};for(let ee=0;ee<A.length;ee++){let te=A[ee];if(te===void 0)break;if(te==="--"){T||=ee+1<A.length;break}if(te==="--pathspec-from-file"){T=!0,ee++;continue}if(te.startsWith("--pathspec-from-file=")){T=!0;continue}if(te==="-h"||te==="--help"||te==="--version")return{hasPathspec:T,hasPatch:F,hasWorktree:j,hasExplicitLocation:q,isTerminal:!0};if(te==="--staged"){K();continue}if(te==="--no-staged"){K();continue}if(te==="--worktree"){K(!0);continue}if(te==="--no-worktree"){K(!1);continue}if(te==="--patch"){F=!0;continue}if(te==="--no-patch"){F=!1;continue}if(Ab.has(te)){ee++;continue}if(te.startsWith("--"))continue;if(te==="-"){T=!0;continue}if(!te.startsWith("-")){T=!0;continue}for(let ce=1;ce<te.length;ce++){let de=te.charAt(ce);if(de==="h")return{hasPathspec:T,hasPatch:F,hasWorktree:j,hasExplicitLocation:q,isTerminal:!0};if(de==="S"){K();continue}if(de==="W"){K(!0);continue}if(de==="p"){F=!0;continue}if(de==="s"||de==="U"){if(ce===te.length-1)ee++;break}}}return{hasPathspec:T,hasPatch:F,hasWorktree:j,hasExplicitLocation:q,isTerminal:!1}}function Nb(A){let T=null;for(let F of A){if(qt(F,"--hard")){T=It("git.reset-hard",fb);break}if(qt(F,"--merge")){T=It("git.reset-merge",pb);break}}if(!T)return null;return Lb(A)?zr(T):vr(T)}function Lb(A){for(let T of A){if(T==="--")return!1;if(!T.startsWith("-"))return!0}return!1}function Wb(A){for(let F of A)if(F==="-n"||qt(F,"--dry-run"))return null;let T=xn(A.filter((F)=>F!=="--"));if(A.some((F)=>qt(F,"--force"))||T.has("-f"))return It("git.clean-force",gb);return null}function Fb(A){let T=!1,F=!1,j=!1;for(let q of bn(A).before){if(qt(q,"--no-force")){T=!1;continue}if(qt(q,"--force")){T=!0;continue}if(qt(q,"--no-cached")){F=!1;continue}if(qt(q,"--cached")){F=!0;continue}if(qt(q,"--no-dry-run")){j=!1;continue}if(qt(q,"--dry-run")){j=!0;continue}let K=xn([q]);T||=K.has("-f"),j||=K.has("-n")}return T&&!F&&!j?It("git.rm-force",hb):null}function Gb(A){let{before:T,after:F}=bn(A),j=xn(T);if(T.some((ee)=>qt(ee,"--mirror")))return It("git.push-mirror",Sb);if(T.some((ee)=>qt(ee,"--force"))||j.has("-f")||Kd(T,F).some(zb))return It("git.push-force",yb);if(T.some((ee)=>qt(ee,"--delete"))||j.has("-d")||Kd(T,F).some(Bb))return It("git.push-delete",Cb);return null}function Kd(A,T){return[...A.filter((F)=>F!==""&&!F.startsWith("-")),...T]}function zb(A){return A.startsWith("+")||A.includes(":+")}function Bb(A){return A.length>1&&A.startsWith(":")}function Ub(A){let{before:T}=bn(A),F=xn(T),j=F.has("-D")||F.has("-d")||T.some((K)=>qt(K,"--delete")),q=F.has("-D")||F.has("-f")||T.some((K)=>qt(K,"--force"));if(j&&q)return It("git.branch-force-delete",bb);return null}function $b(A){let{before:T}=bn(A);return T.some((F)=>qt(F,"--abort"))?It("git.rebase-abort",vb):null}function jb(A){let{before:T}=bn(A);return T.some((F)=>qt(F,"--abort"))?It("git.merge-abort",Rb):null}function Hb(A){let{before:T}=bn(A);return xn(T).has("-d")||T.some((j)=>qt(j,"--delete"))?It("git.tag-delete",xb):null}function Vb(A){return A[0]==="delete"?It("git.reflog-delete",Eb):null}function qb(A){for(let T of A){if(T==="drop")return It("git.stash-drop",_b);if(T==="clear")return It("git.stash-clear",Pb)}return null}function Kb(A){let{before:T}=bn(A);if(!T.includes("remove"))return null;let j=xn(T);if(T.some((q)=>qt(q,"--force"))||j.has("-f"))return It("git.worktree-remove-force",wb);return null}import{execFileSync as Yb}from"node:child_process";import{existsSync as cl,readFileSync as ul}from"node:fs";import{dirname as Zb,isAbsolute as Jd,join as ll,resolve as Qd}from"node:path";var Xb=["/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 em(A,T,F,j){let q=Jb(A,T,F);if(q!==null)return q;let K=Qb(T,F);if(K!==null)return K;if(Ic(F))return!0;return ev(j)}function Jb(A,T,F){let j=null,q=1;while(q<A.length){let K=A[q];if(!K||K==="--")return j;if(!K.startsWith("-"))return j;if(K==="-c"){let ee=Zd(A[q+1]);if(ee!==null)j=ee;q+=2;continue}if(K.startsWith("-c")&&K.length>2){let ee=Zd(K.slice(2));if(ee!==null)j=ee;q++;continue}if(K==="--config-env"){let ee=Xd(A[q+1],T,F);if(ee!==null)j=ee;q+=2;continue}if(K.startsWith("--config-env=")){let ee=Xd(K.slice(13),T,F);if(ee!==null)j=ee;q++;continue}if(vn.has(K))q+=2;else q++}return j}function Qb(A,T){if(Nn("GIT_CONFIG_PARAMETERS",A,T)!==void 0)return!0;let F=xi(A,T);if(F.state==="absent")return null;if(F.state==="invalid")return!0;let j=null;for(let q=0;q<F.count;q++){let K=Nn(`GIT_CONFIG_KEY_${q}`,A,T),ee=Nn(`GIT_CONFIG_VALUE_${q}`,A,T);if(!K?.trim()||ee===void 0)return!0;let te=K.trim().toLowerCase();if(dl(te))return!0;if(te!=="submodule.recurse")continue;j=Zo(ee)}return j}function ev(A,T=nv()){let F=tv(A);if(F===null||F)return!0;if(T===null)return!0;try{let j=Yb(T,["config","--get","submodule.recurse"],{cwd:A,encoding:"utf8",env:rv(process.env),stdio:["ignore","pipe","ignore"]}).trim();return Zo(j)}catch(j){return!ov(j)}}function tv(A){let T=iv(A);if(T===null)return null;for(let F of T){if(!cl(F))continue;if(lv(F))return!0}return!1}function nv(){for(let A of Xb)if(cl(A))return A;return null}function rv(A){let T={...A};for(let F of Object.keys(T))if(Eo(F))delete T[F];return T}function ov(A){return typeof A==="object"&&A!==null&&"status"in A&&A.status===1}function iv(A){let T=wo(A);if(T===null)return null;let F=sv(T);if(F===null)return null;let j=av(F);if(j===null)return null;return[ll(j,"config"),ll(F,"config.worktree")]}function sv(A){try{let F=ul(A,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!F.startsWith("gitdir:"))return A;let j=F.slice(7).trim();if(j==="")return null;return Jd(j)?j:Qd(Zb(A),j)}catch{return null}}function av(A){let T=ll(A,"commondir");if(!cl(T))return A;try{let F=ul(T,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(F==="")return null;return Jd(F)?F:Qd(A,F)}catch{return null}}function lv(A){let T;try{T=ul(A,"utf-8")}catch{return!0}let F="",j=!1;for(let q of T.split(/\r?\n/)){let K=q.trim();if(K===""||K.startsWith("#")||K.startsWith(";"))continue;let ee=K.match(/^\[([^\]]+)\]$/);if(ee){F=ee[1]?.trim().toLowerCase()??"";continue}let te=K.indexOf("="),ce=(te===-1?K:K.slice(0,te)).trim().toLowerCase(),de=te===-1?"true":K.slice(te+1).trim();if(cv(F)&&ce==="path")return!0;if(F==="submodule"&&ce==="recurse")j=Zo(de)}return j}function cv(A){return A==="include"||A.startsWith("includeif ")}function Zd(A){if(!A)return null;let T=A.indexOf("="),F=(T===-1?A:A.slice(0,T)).toLowerCase();if(dl(F))return!0;if(F!=="submodule.recurse")return null;let j=T===-1?"true":A.slice(T+1).toLowerCase();return Zo(j)}function Zo(A){let T=A.toLowerCase();return T!=="false"&&T!=="no"&&T!=="off"&&T!=="0"}function Xd(A,T,F){let j=A?.indexOf("=")??-1;if(!A||j===-1)return null;let q=A.slice(0,j).toLowerCase();if(dl(q))return!0;if(q!=="submodule.recurse")return null;let K=Nn(A.slice(j+1),T,F);return K===void 0||Zo(K)}function dl(A){return A==="include.path"||A.startsWith("includeif.")&&A.endsWith(".path")}function tm(A,T,F){if(!T.localDiscard||!F.worktreeMode||Dc(F.env,F.envAssignments))return null;let j=Nc(A,F.cwd);if(!j.gitCwd||j.hasExplicitGitContext)return null;if(!Lc(j.gitCwd))return null;if(uv(A,F,j.gitCwd))return null;return{originalReason:T.reason,gitCwd:j.gitCwd}}function uv(A,T,F){let{subcommand:j,rest:q}=qn(A),K=j?.toLowerCase();if(T.dynamicArguments||dv(q)||em(A,T.env,T.envAssignments,F)||pv(q)||mv(K,q))return!0;return K==="clean"&&gv(q)>1}function dv(A){return A.some((T)=>/[$*?[]/.test(T))}function mv(A,T){if(A==="checkout"){let{before:F}=bn(T),j=xn(F,{shortOptsWithValue:sl}),q=F.some((ee)=>qt(ee,"--force"))||j.has("-f"),K=j.has("-B")||F.some((ee)=>ee==="-B"||ee.startsWith("-B"));return q&&K}if(A==="switch"){let{before:F}=bn(T),j=xn(F,{shortOptsWithValue:al}),q=F.some((ee)=>qt(ee,"--force"))||F.some((ee)=>qt(ee,"--discard-changes"))||j.has("-f"),K=F.some((ee)=>ee==="-C"||ee.startsWith("-C")||fv(ee))||j.has("-C");return q&&K}return!1}function fv(A){let T=A.split("=",1)[0]??A;return T==="--force-create"||T.length>=9&&"--force-create".startsWith(T)}function pv(A){return A.some((T)=>T.startsWith("--recurse-sub"))}function gv(A){let T=0;for(let F of A){if(F==="--force"){T++;continue}if(F.startsWith("-")&&!F.startsWith("--")){for(let j of F.slice(1))if(j==="f")T++}}return T}var hv="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.",yv=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function go(A,T){return nm(A.map(e),T)}function nm(A,T,F){let j=$d(A,T.env,T.envAssignments),q=j.blockedReason?jt(It("git.alias-config",j.blockedReason),T.policy):null;if(q)return q;let K=j.tokens;if((Tc(T.envAssignments)||jd(A,T.env,T.envAssignments))&&Cv(K))return It("git.ssh-env",hv);let ee=Yd(K);if(!ee)return null;if(j.expanded||j.blockedReason)return ee;let te=tm(A,ee,T);if(!te)return ee;return F?.(te),null}function rm(A,T){let F=null;return{match:nm(A.map(e),T,(q)=>{F=q}),relaxation:F}}function Cv(A){let{subcommand:T,rest:F}=qn(A),j=T?.toLowerCase();if(!j)return!1;if(yv.has(j))return!0;if(j==="archive")return bn(F).before.some((q)=>qt(q,"--remote"));return j==="remote"&&Sv(F)}function Sv(A){return A.find((T)=>!bv(T))?.toLowerCase()==="update"}function bv(A){return A==="-v"||qt(A,"--verbose")||qt(A,"--no-verbose")}import{isAbsolute as gR}from"node:path";var om="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",vv="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.",Rv="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",sm="rm -rf targeting root or home directory is extremely dangerous and always blocked.",xv="rm -rf in home directory is dangerous. Change to a project directory first.";function ho(A,T){let F=Fr({...T,allowPaths:T.policy?.destructiveCommandAllowPaths,posixShell:!0}),j=A.map(e),q=Vn(j),K=Bd(j),ee=_v(A);for(let te of ee){let ce=Ho(te.word);if(q&&ce.unsafeBraceExpansion){let de=jt(im({kind:"outside_anchored_cwd"},F,T.policy),T.policy);if(de)return de;continue}for(let de of ce.expandedTargets??[te.text]){let _e=Pn(de),Pe={targetIsLiteral:ce.expandedTargets!==void 0||ce.targetIsLiteral,tmpdirWordSplittingProtected:ce.tmpdirWordSplittingProtected};if(!K&&F.resolvedCwd&&Wr(_e,F.resolvedCwd,F.protectedGitMetadata,K,F.pathCanonicalizationContext))return It("rm.git-metadata",S);if(K&&!q){let je=jn(_e,F,Pe);if(je.kind==="root_or_home_target")return It("rm.recursive-force-root-or-home",sm);if(je.kind==="git_metadata_target")return It("rm.git-metadata",S);continue}if(!q)continue;for(let je of Ev(_e,F,Pe)){let it=im(je,F,T.policy),st=jt(it,T.policy);if(st)return st}}}return null}function Ev(A,T,F){let j=jn(A,T,F);if(j.kind==="cwd_self_target")return[j,jn(A,T,{...F,skipCwdSelf:!0})];if(j.kind!=="home_cwd_target")return[j];let q=jn(A,T,{...F,skipHomeCwd:!0});if(q.kind!=="cwd_self_target")return[j,q];return[j,q,jn(A,T,{...F,skipHomeCwd:!0,skipCwdSelf:!0})]}function _v(A){let T=[],F=!1;for(let j of A.slice(1)){let q=e(j);if(!q)continue;if(q==="--"){F=!0;continue}if(F){T.push({text:q,word:j});continue}if(!q.startsWith("-"))T.push({text:q,word:j})}return T}function im(A,T,F){switch(A.kind){case"root_or_home_target":return It("rm.recursive-force-root-or-home",sm);case"git_metadata_target":return It("rm.git-metadata",S);case"temp_target":return null;case"dynamic_target":if(!mn(F,"rm.recursive-force-dynamic-target",T.strict))return null;return It("rm.recursive-force-dynamic-target",Rv);case"home_cwd_target":return It("rm.recursive-force-home-cwd",xv);case"cwd_self_target":return It("rm.recursive-force-cwd-self",om);case"within_anchored_cwd":if(mn(F,"rm.recursive-force-paranoid",T.paranoid))return It("rm.recursive-force-paranoid",vv);return null;case"outside_anchored_cwd":return It("rm.recursive-force-outside-cwd",om)}}var Pv={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},lm=new Set(["--init-file","--rcfile"]),wv=["--init-file","--rcfile"],Av=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function er(A){for(let T=1;T<A.length;T++){let F=A[T];if(!F)continue;if(F==="-c")return am(A,T,!0);if(F.startsWith("-")&&F.includes("c")&&!F.startsWith("--")){let j=am(A,T,!1);if(j!==null)return j}}return null}function Wn(A){let T=Vt(A[0]??"").toLowerCase();if(T==="zsh"||T==="ksh")return tr(A).syntaxCheck;let F=!1;for(let j of A.slice(1)){if(j==="--")return F;if(j.startsWith("+")&&!j.startsWith("++")){if(j.slice(1).includes("n"))F=!1;continue}if(!j.startsWith("-")||j.startsWith("--"))return F;let q=j.slice(1);if(q.includes("n"))F=!0;if(q.includes("c"))return F}return F}function am(A,T,F){if(A[T+1]==="--")return A[T+2]||null;let j=A[T+1];if(!j||!F&&j.startsWith("-"))return null;return j}function cm(A){let T=Vt(A[0]??"").toLowerCase(),F=Tv(A,T),j=Av.get(T)??null,q=F.argvSource?.kind!=="absent";return{argvSource:T==="bash"?F.argvSource:null,argvSourceApplies:T==="bash"&&F.interactive&&F.argvSource?.kind==="literal",envName:j,envSourceApplies:q&&(j==="BASH_ENV"?!F.interactive:j==="ENV"&&F.interactive)}}function Tv(A,T){let F=tr(A),j=F.commandIndex??F.scriptIndex??A.length,q=[],K=!1,ee=!0;for(let te=1;te<j;te++){let ce=A[te];if(ce===void 0||ce==="--"||ce==="-"||ce[0]!=="-"&&ce[0]!=="+")break;if(ce.startsWith("--")){if(T==="bash"&&ee?wv.find((je)=>ce===je):void 0){let je=A[te+1];q.push(je===void 0?{kind:"absent"}:{kind:"literal",value:je}),te++;continue}let Pe=ce.split("=",1)[0]??ce;if(T==="bash"&&lm.has(Pe)&&!ce.includes("="))te++;continue}if(T==="bash")ee=!1;let de=um(T,ce,A[te+1],"startup");if(de.interactive)K=ce[0]==="-";te+=de.followingValues}return{argvSource:q.at(-1)??null,interactive:K}}function um(A,T,F,j){let q=!1,K=0,ee=!1,te=!1,ce=!1;for(let de=1;de<T.length;de++){let _e=T[de];if(_e===void 0)break;if(A==="ksh"&&_e==="o"&&de+1<T.length){if(j==="argv"){let Pe=T.slice(de+1);if(T[0]==="-"&&(Pe==="c"||Pe[0]==="-"&&Pe.endsWith("c")))ee=!0}break}if(A==="ksh"&&_e==="o"&&de+1===T.length&&(F?.startsWith("-")||F?.startsWith("+")))break;if(A==="zsh"&&_e==="o"&&de+1<T.length)break;if(j==="startup"&&_e==="i")q=T[0]==="-";if(j==="argv"&&T[0]==="-"&&_e==="c")ee=!0;if(j==="argv"&&_e==="n")ce=T[0]==="-";if(j==="argv"&&_e==="s")te=T[0]==="-";if(!Pv[A]?.includes(_e))continue;if(de+1===T.length)K++;break}return{interactive:q,followingValues:K,commandSelected:ee,stdinMode:te,syntaxCheck:ce}}function tr(A){let T=Vt(A[0]??"").toLowerCase(),F=!1,j=!1,q=!1;for(let K=1;K<A.length;K++){let ee=A[K];if(ee===void 0)break;if(ee==="--"){let ce=F&&A[K+1]!==void 0?K+1:null;return{command:ce===null?null:A[ce]??null,commandIndex:ce,scriptIndex:!F&&!j&&A[K+1]!==void 0?K+1:null,readsStdinAsCommands:!F&&(j||A[K+1]===void 0),syntaxCheck:q}}if(ee==="-"||ee[0]!=="-"&&ee[0]!=="+")return{command:F?ee:null,commandIndex:F?K:null,scriptIndex:!F&&!j&&ee!=="-"?K:null,readsStdinAsCommands:!F&&(j||ee==="-"),syntaxCheck:q};if(ee.startsWith("--")){let ce=ee.split("=",1)[0]??ee;if(T==="bash"&&lm.has(ce)&&!ee.includes("="))K++;continue}let te=um(T,ee,A[K+1],"argv");if(te.commandSelected)F=!0;if(te.syntaxCheck)q=!0;if(te.stdinMode)j=!0;K+=te.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!F,syntaxCheck:q}}var Rr={kind:"none"},Br={kind:"dynamic"},Iv=new Set(["<","<<","<<-","<<<","<&","<>"]),mm=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,kv=/^(?:[0-9]+|[@*])$/,Ov=Nr.maxWords,Mv=Nr.maxInputLength;function fm(A){if(!A||Vt(Qt(A.words[0]?.text??""))!=="printf")return;if(A.words.some((q)=>q.provenance!=="literal"))return;let T=A.words.slice(A.words[1]?.text==="--"?2:1),F=T[0]?.text;if(F===void 0)return"";let j=T.slice(1).map((q)=>q.text);if(F==="%s")return j.join("");if(F==="%s\\n"||F===`%s
35
+ `)return`${j.join(`
36
+ `)}
37
+ `;if(F.includes("%")||/\\(?![\\nrt])/.test(F))return;return F.replaceAll("\\n",`
38
+ `).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function yo(A){let T=Xo(A[1])==="--"?2:1;if(A.length<=T)return Rr;let F=A.slice(T);if(!F.every(ws))return Br;return{kind:"literal",source:F.map(e).join(" ")}}function pm(A){let T=Xo(A[1])==="--"?2:1,F=A[T],j=Xo(F);if(F===void 0||A.length<=T+1||j==="-"||j===""||j==="-l"||j==="-p")return Rr;if(!ws(F))return Br;return{kind:"literal",source:j}}function Ps(A,T){let F=Nv(A);if(F===-1)return Rr;let j=Lv(T);if(!j)return Rr;let q=[],K=j.command?.length??0;for(let ee of j.references){let te=Fv(ee,A,F,j.ifs);if(!te)return Br;if(K+=te.reduce((ce,de)=>ce+de.length+3,0),q.length+te.length>Ov||K>Mv)return Br;q.push(...te)}if(j.command==="eval")return{kind:"literal",source:q.join(" ")};if(q.length===0||/\s/.test(q[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[j.command,j.command&&j.optionTerminator?"--":null,...q.map(zv)].filter((ee)=>ee!==null).join(" ")}}function gm(A,T,F,j){if(!tr(A.map(e)).readsStdinAsCommands)return Rr;let q=T.filter((K)=>(K.fd===void 0||K.fd===0)&&Iv.has(K.operator)).at(-1);if(q){if(q.operator==="<<"||q.operator==="<<-")return Rr;if(q.operator!=="<<<"||q.target?.provenance!=="literal")return Br;return{kind:"literal",source:q.target.text}}if(!F)return Rr;return j===void 0?Br:{kind:"literal",source:j}}function nr(A){let T=tr(A.map(e)).scriptIndex;if(T===null)return Rr;let F=A[T],j=Xo(F);return vi(F,j)?{kind:"literal",source:j}:Br}var Dv=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function gl(A){if(A.words.length!==2||A.redirections.length!==0||A.nested.length!==1)return!1;let T=A.words[0],F=A.words[1];if(!T||T.provenance!=="literal"||T.quoted||T.raw!==T.text||!F)return!1;if(!(T.text==="eval"&&F.quoted&&F.parts.length===3&&F.parts[0]?.raw==='"'&&F.parts[1]?.provenance==="command-substitution"&&F.parts[1].raw.startsWith("$(")&&F.parts[2]?.raw==='"'||(T.text==="source"||T.text===".")&&!F.quoted&&F.parts.length===1&&F.parts[0]?.provenance==="command-substitution"&&F.parts[0].raw.startsWith("<(")))return!1;let q=A.nested[0];if(q?.status!=="complete"||q.nodes.length!==1)return!1;let K=q.nodes[0];if(K?.kind!=="command"||K.redirections.length!==0||K.nested.length!==0||K.words.some((ce)=>ce.provenance!=="literal"||ce.parts.some((de)=>de.provenance!=="literal")))return!1;let ee=K.words[0]?.text;if(ee===void 0||Ln(ee)!==null)return!1;let te=Vt(Qt(ee));return!Dv.has(te)&&!fn.has(te)&&!Gr(te)}function Nv(A){return tr(A.map(e)).commandIndex??-1}function Lv(A){let T=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(A.trim()),F=T?.[4]??A.trim(),j=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(F),q=(j?.[3]??F).split(/\s+/).map(Wv);if(q.length===0||q.some((K)=>K===null))return null;return{command:j?.[1]??null,optionTerminator:j?.[2]!==void 0,references:q.filter((K)=>!!K),ifs:T?T[1]??T[2]??T[3]??"":`
39
+ `}}function Wv(A){let T=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(A),F=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(A),j=T??F;if(!j)return null;let q=j[1]??j[2];return{parameter:q==="@"||q==="*"?q:Number(q),quoted:T!==null}}function Fv(A,T,F,j){let q=T.slice(F+2);if(A.parameter==="@")return A.quoted?ml(q):Gv(q,j);if(A.parameter==="*"){let te=ml(q);if(!te)return;let ce=te.join(j[0]??"");return A.quoted?[ce]:fl(ce,j)}let K=T[F+1+A.parameter];if(K&&!ws(K))return;let ee=Xo(K);return A.quoted?[ee]:fl(ee,j)}function ml(A){return A.every(ws)?A.map(e):void 0}function Gv(A,T){let F=ml(A);if(!F)return;let j=F.map((q)=>fl(q,T));return j.some((q)=>q===void 0)?void 0:j.flatMap((q)=>q??[])}function fl(A,T){if(["*","?","[","]"].some((F)=>A.includes(F)))return;if(T==="")return A===""?[]:[A];if(T===`
40
+ `)return A.trim().split(/\s+/).filter(Boolean);if(T.length!==1)return;return T===" "||T==="\t"||T===`
41
+ `?A.trim().split(/\s+/).filter(Boolean):A.split(T).filter(Boolean)}function ws(A){if(!A)return!0;return A.provenance==="unknown"?!/[$`]/.test(e(A)):A.provenance==="literal"}function Xo(A){return A?e(A):""}function zv(A){return`'${A.replaceAll("'",`'"'"'`)}'`}function hl(A,T){return pl(R(A,"posix"),T)}function Co(A){return hl(A,new Set(Array.from(A.matchAll(mm)).flatMap((T)=>{let F=T[1]??T[2];return F===void 0?[]:[F]})))}function pl(A,T){if(A.status==="invalid"||A.status==="limited")return!1;let F=new Set(T);for(let j of A.nodes){if(j.kind==="group"){if(pl(j.body,F))return!0;continue}if(j.kind!=="command")continue;if(j.nested.some((q)=>pl(q,F))||hm(j.words,F))return!0;Hv(j,F)}return!1}function hm(A,T){let F=A.findIndex((ee)=>Ln(ee.text)===null);if(F===-1)return!1;let j=A[F];if(!j)return!1;if(Jo(j,T))return!0;let q=Qt(j.text);if(q==="source"||q==="."){let ee=A[F+1]?.text==="--"?F+2:F+1;return dm(A[ee],T)}if(fn.has(q)){let ee=A.slice(F),te=tr(ee.map((de)=>de.text)),ce=te.commandIndex??te.scriptIndex;return!te.syntaxCheck&&ce!==null&&dm(ee[ce],T)}let K=Bv(A,F,T);if(K===null)return!1;if(K===-1)return!0;return hm(A.slice(K),T)}function Bv(A,T,F){let j=Qt(A[T]?.text??"");if(j==="command")return Uv(A,T+1);if(j==="exec")return $v(A,T+1);if(j==="env")return jv(A,T+1,F);return null}function Uv(A,T){for(let F=T;F<A.length;F++){let j=A[F]?.text??"";if(j==="--")return A[F+1]?F+1:null;if(/^-[p]*[vV][pvV]*$/.test(j))return null;if(/^-p+$/.test(j))continue;return F}return null}function $v(A,T){for(let F=T;F<A.length;F++){let j=A[F]?.text??"";if(j==="--")return A[F+1]?F+1:null;if(j==="-a"){F++;continue}if(/^-a.+/.test(j)||/^-[cl]+$/.test(j))continue;return F}return null}function jv(A,T,F){for(let j=T;j<A.length;j++){let q=A[j],K=q?.text??"";if(K==="--")return A[j+1]?j+1:null;if(K==="-S"||K==="--split-string")return Jo(A[j+1],F)?-1:j+2;if(K.startsWith("-S")||K.startsWith("--split-string="))return Jo(q,F)?-1:j+1;if(K==="-u"||K==="--unset"||K==="-C"||K==="--chdir"||K==="-P"){j++;continue}if(K==="-i"||K==="-0"||K==="--null"||K.startsWith("-u=")||K.startsWith("--unset=")||K.startsWith("-C")||K.startsWith("--chdir=")||K.startsWith("-P"))continue;if(K.startsWith("-"))continue;if(Ln(K))continue;return j}return null}function Hv(A,T){if(!A.words.every((F)=>Ln(F.text)!==null))return;for(let F of A.words){let j=Ln(F.text);if(!j)continue;if(Jo(F,T))T.add(j.name)}}function Jo(A,T){if(!A)return!1;return A.parts.filter((F)=>F.provenance==="variable").some((F)=>Array.from(F.raw.matchAll(mm)).some((j)=>{let q=j[1]??j[2];return q!==void 0&&(kv.test(q)||T.has(q))}))}function dm(A,T){return!!A&&(A.parts.some((F)=>F.provenance!=="literal"&&F.provenance!=="variable")||Jo(A,T))}var Vv=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),qv=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),Kv=new Set(["-o","--output","--query","--subscription"]),Yv=new Set;function ym(A){if(A==="aws")return Vv;if(A==="gcloud")return qv;if(A==="az")return Kv;return Yv}var Zv=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),Xv=new Set;function Cm(A){if(A==="git")return vn;if(A==="docker")return Zv;return Xv}function l(A,T){if(A.length===0||T.length===0)return null;let F=Qt(A[0]??""),j=xn(A);for(let q of T){if(!eR(F,q.command))continue;if(q.match){if(Jv(F,A,q.match))return Sm(q);continue}if(!tR(F,A,q.subcommand))continue;if(rR(A,new Set(q.block_args),j))return Sm(q)}return null}function Sm(A){return{id:`custom.${A.name}`,reason:`[${A.name}] ${A.reason}`,intent:A.intent??"manual_only"}}function Jv(A,T,F){let j=T.slice(1);if(F.exclude_args?.some((q)=>j.includes(q)))return!1;if(F.any_args&&!F.any_args.some((q)=>j.includes(q)))return!1;return Qv(j,F.command_path,ym(A))}function Qv(A,T,F){let j=0,q=!1;for(let K of A){if(j>=T.length)return!0;if(q){q=!1;continue}if(K.startsWith("-")){q=!K.includes("=")&&F.has(K);continue}if(K!==T[j])return!1;j++}return j>=T.length}function eR(A,T){return A===Qt(T)}function tR(A,T,F){if(!F)return!0;return bm(T,1,F,Cm(A))}function bm(A,T,F,j){let q=!1;for(let K=T;K<A.length;K++){let ee=A[K];if(!ee)continue;if(q){q=!1;continue}if(ee==="--"){let te=A[K+1];if(te&&!te.startsWith("-"))return te===F;return!1}if(j.has(ee)){q=!0;continue}if(ee.startsWith("-")){if(!ee.includes("=")&&nR(A,K,F,j))return!0;continue}return ee===F}return!1}function nR(A,T,F,j){let q=A[T+1];if(!q||q.startsWith("-"))return!1;return bm(A,T+2,F,j)}function rR(A,T,F){for(let j of A)if(T.has(j))return!0;for(let j of F)if(T.has(j))return!0;return!1}function xr(A,T,F={}){if(A.length===0)return null;let j=A[0];if(!j)return null;let q=Qt(j);if(q==="eval"){let K=yo(Yt(A));if(K.kind==="dynamic")return So(F,T);if(K.kind==="literal"&&T.analyzeNested){let ee=T.analyzeNested(K.source,{effectiveCwd:T.cwd,envAssignments:T.envAssignments});if(ee)return ee}return rr(F,T)}if(fn.has(q)){if(Wn(A))return null;let K=er(A);if(K){if(F.dynamicSourceInput??F.dynamicInput){let ce=So(F,T);if(ce)return ce}if(Co(K)){let ce=So(F,T);if(ce)return ce}if(!T.analyzeNested)return null;let te=T.analyzeNested(K,{effectiveCwd:T.cwd,envAssignments:T.envAssignments});if(te)return te;return null}let ee=nr(Yt(A));if(ee.kind==="dynamic")return So(F,T);if(ee.kind==="literal"){if(F.dynamicSourceInput)return So(F,T);return null}if(F.dynamicSourceInput??F.dynamicInput)return So(F,T);return null}if(On.has(q))return jt(bs(A,(K)=>T.analyzeNested?T.analyzeNested(K,{effectiveCwd:T.cwd,envAssignments:T.envAssignments}):null),T.policy)??l(A,T.policy?.rules??[])??rr(F,T);if(Tn(q)){let K=Wi(A);if(!K)return rr(F,T);if(mn(T.policy,"interpreter.one-liner-paranoid",!!T.paranoidInterpreters)){let te=jt(It("interpreter.one-liner-paranoid",io),T.policy);if(te)return te}if(zi(q,K))return rr(F,T);let ee=T.analyzeNested?.(K,{effectiveCwd:T.cwd,envAssignments:T.envAssignments});if(ee&&ee.id!=="raw-text.dangerous-command"&&(ee.reason!==hr||uo(K)))return ee;if(so(K,T.scanWork))return jt(It("interpreter.dangerous-command",Mr),T.policy)??rr(F,T);return rr(F,T)}if(q==="rm"||q==="rmdir"){let K=q==="rm"&&(Vn(A)||F.dynamicRmInput);return jt(ho(Yt(A),{environment:T.environment,cwd:T.cwd,originalCwd:T.originalCwd,strict:T.strict,paranoid:T.paranoidRm,allowTmpdirVar:T.allowTmpdirVar,tmpdirWordSplittingUnsafe:Xn(T.envAssignments,T.environment),trustedTmpdirValue:dr(T.envAssignments,T.environment),protectedGitMetadata:T.protectedGitMetadata,policy:T.policy}),T.policy)??(K&&F.dynamicRmInput?rr(F,T):null)??(K?oR(F,T):null)}if(q==="find")return xs(Yt(A),{...T,derivedCommandWorkBudget:T.derivedCommandWorkBudget,analyzeTokens:(K,ee)=>xr(K,{...T,cwd:ee??void 0,derivedCommandWorkBudget:T.derivedCommandWorkBudget},F)})??l(A,T.policy?.rules??[])??rr(F,T);if(q==="git")return jt(go(Yt(A),{env:T.environment.env,cwd:T.cwd,envAssignments:T.envAssignments,policy:T.policy,worktreeMode:F.dynamicInput?!1:T.worktreeMode}),T.policy)??l(A,T.policy?.rules??[])??rr(F,T);return l(A,T.policy?.rules??[])??rr(F,T)}function So(A,T){return A.shellDynamicMatch?jt(A.shellDynamicMatch,T.policy):null}function rr(A,T){return A.dynamicSourceInput&&A.dynamicSourceMatch?jt(A.dynamicSourceMatch,T.policy):null}function oR(A,T){return A.dynamicInput&&A.rmDynamicMatch?jt(A.rmDynamicMatch,T.policy):null}var yl="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",Cl="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",iR="__CC_SAFETY_NET_XARGS_INPUT__",As="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",Ts="rm",sR=/(?:^|[;&|]\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,aR=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,lR=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,cR=/^(?:[0-9]+|[@*])$/;function xm(A,T){let F=A.map(e),{childStart:j,replacementToken:q}=Ur(F),K=F.slice(j),ee=It("xargs.shell-dynamic",Cl);if(dR(K,q,T)&&jt(ee,T.policy))return jt(ee,T.policy);for(let te of Hn(K,T)){let ce=te.tokens,de=q!==null&&ce[0]!==K[0]&&(ce[0]?.includes(q)??!1)?jt(ee,T.policy):null;if(de)return de;let _e=wm(ce,q,te.wrapperEnvAssignments),Pe=te.head==="rm"&&q!==null&&_m(ce,q),je=xr(ce,{...T,cwd:te.cwd,envAssignments:te.envAssignments},{dynamicInput:_e,dynamicSourceInput:Pe||Em(ce,te.head,q,te.wrapperEnvAssignments,_e,T.scanWork,T.environment),dynamicRmInput:Pe,shellDynamicMatch:ee,dynamicSourceMatch:ee,rmDynamicMatch:It("xargs.rm-recursive-force-dynamic",yl)});if(je)return je;let it=uR(ce,q,T.policy?.rules??[]);if(it)return it;if(te.head==="git"){let yt=q===null?[...ce,iR]:ce,At=q!==null&&(ce.some((Dt)=>Dt.includes(q))||Array.from(te.envAssignments.values()).some((Dt)=>Dt.includes(q))),Tt=xr(yt,{...T,cwd:te.cwd,envAssignments:te.envAssignments,worktreeMode:q===null||At?!1:T.worktreeMode});if(Tt)return Tt}let st=l(ce,T.policy?.rules??[]);if(st)return st}return null}function uR(A,T,F){if(F.length===0)return null;if(T===null){for(let q of F){let K=l([...A,...q.subcommand?[q.subcommand]:[],...q.block_args],F);if(K)return K}return null}let j=new Set(F.flatMap((q)=>[q.subcommand,...q.block_args].flatMap((K)=>K?A.flatMap((ee)=>Sl(ee,T,K)):[])));for(let q of j){let K=l(A.map((ee)=>ee.replaceAll(T,q)),F);if(K)return K}return null}function Sl(A,T,F){let j=A.indexOf(T);if(j===-1||A.indexOf(T,j+T.length)!==-1)return[];let q=A.slice(0,j),K=A.slice(j+T.length);return F.startsWith(q)&&F.endsWith(K)?[F.slice(q.length,F.length-K.length)]:[]}function Em(A,T,F,j,q,K,ee){if(fn.has(T)){if(Wn(A))return!1;if(F!==null&&mR(A,F))return!0;let te=er(A);if(!te){let ce=nr(Yt(A));if(ce.kind==="literal")return F!==null&&ce.source.includes(F);return ce.kind==="none"&&q}if(F!==null&&te.includes(F))return!0;if(cr(te,K))return!0;return fR(te,F,j)}if(Tn(T))return vm(A,F,Gi,au(T));if(On.has(T))return vm(A,F,Xa,Ld);if(T==="eval"){let te=yo(Yt(A));if(te.kind==="dynamic")return!0;if(F!==null)return te.kind==="literal"&&te.source.includes(F);return q}if(T==="find")return pR(A,F,K,ee);if(T==="git"){let te=qn(A);return F===null?te.subcommand===null:(te.subcommand?.includes(F)??!1)||te.subcommand!==null&&po.has(te.subcommand.toLowerCase())&&Pm(te.rest,F).some((ce)=>ce.includes(F))}return!1}function vm(A,T,F,j){let q=F(A);if(T===null)return q.optionsOpen||F([...A,As]).sources.some((ce)=>ce.value===As);if(q.sources.some((ce)=>ce.value.includes(T)))return!0;let K=new Set(q.sources.map((ce)=>`${ce.tokenIndex}\x00${ce.kind}\x00${ce.value}`)),ee=j.flatMap((ce)=>[ce.selector,...ce.valueForm==="attached-only"||ce.valueForm==="attached-or-separate"?[`${ce.selector}${As}`]:[],...ce.valueForm==="equals-or-separate"?[`${ce.selector}=${As}`]:[]]),te=new Set(ee.flatMap((ce)=>A.flatMap((de)=>Sl(de,T,ce))));return Array.from(te).some((ce)=>F(A.map((de)=>de.replaceAll(T,ce))).sources.some((de)=>!K.has(`${de.tokenIndex}\x00${de.kind}\x00${de.value}`)))}function dR(A,T,F){if(A.length===0||(A[0]??"").toLowerCase()==="command")return!1;let j=new Set(Array.from(Hn(A,F),(K)=>K.head)),q=T===null?[...A,Ts]:A.map((K,ee)=>ee===0?K:K.replaceAll(T,Ts));return Array.from(Hn(q,F)).some((K)=>K.head===Ts&&!j.has(Ts))}function _m(A,T){return Pm(A.slice(1),T).some((F)=>F.includes(T)&&(F.startsWith("-")||F.startsWith(T)))}function Pm(A,T){let F=A.findIndex((j)=>j==="--"&&!j.includes(T));return F===-1?A:A.slice(0,F)}function wm(A,T,F){if(T===null)return!0;return A.some((j)=>j.includes(T))||Array.from(F.values()).some((j)=>j.includes(T))}function mR(A,T){let F=tr(A);if(F.commandIndex!==null&&(A[F.commandIndex]??"").includes(T)||F.scriptIndex!==null&&(A[F.scriptIndex]??"").includes(T))return!0;return["-c","-nc","-cn",`--${T}`,T].some((q)=>A.some((K,ee)=>{if(ee===0||!K.includes(T))return!1;return Sl(K,T,q).some((ce)=>{let de=A.map((Pe,je)=>je===ee?Pe.replaceAll(T,ce):Pe),_e=tr(de);if(_e.commandIndex===null&&_e.scriptIndex===null)return!1;if(F.commandIndex===null&&_e.commandIndex!==null)return!0;if(F.scriptIndex===null&&_e.scriptIndex!==null)return!0;if(_e.commandIndex!==null&&(de[_e.commandIndex]??"").includes(ce))return!0;return _e.scriptIndex!==null&&(de[_e.scriptIndex]??"").includes(ce)})}))}function fR(A,T,F){let j=new Set(T===null?[]:Array.from(F).filter(([,q])=>q.includes(T)).map(([q])=>q));for(let q of A.matchAll(sR))if(Rm(q,j))return!0;for(let q of A.matchAll(aR))for(let K of(q[1]??"").matchAll(lR))if(Rm(K,j))return!0;return hl(A,j)}function Rm(A,T){let F=A[1]??A[2];return F!==void 0&&(cR.test(F)||T.has(F))}function pR(A,T,F,j){if(T===null)return!0;let q=!1,K=0;for(let ee=1;ee<A.length;ee++){let te=A[ee]??"";if(!q&&!te.startsWith("-")&&te!=="!"&&te!=="("){if(te.indexOf(T)===0)return!0;continue}if(q=!0,K>0){K--;continue}if(mr(te)){let de=Ko(A,ee);ee=de.nextIndex-1;for(let _e of Hn(de.tokens,{environment:j,cwd:void 0})){let Pe=wm(_e.tokens,T,_e.wrapperEnvAssignments);if(_e.head==="rm"&&_m(_e.tokens,T)||Em(_e.tokens,_e.head,T,_e.wrapperEnvAssignments,Pe,F,j))return!0}continue}let ce=br(te);if(ce>0){if(K=ce,te.includes(T))return!0;continue}if(te.includes(T))return!0}return!1}function Ur(A){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"]),F=null,j=1;while(j<A.length){let q=A[j];if(!q)break;if(q==="--")return{childStart:j+1,replacementToken:F};if(q.startsWith("-")){if(q==="-I"){F=A[j+1]??"{}",j+=2;continue}if(q.startsWith("-I")&&q.length>2){F=q.slice(2),j++;continue}if(q==="--replace"){F="{}",j++;continue}if(q.startsWith("--replace=")){let K=q.slice(10);F=K===""?"{}":K,j++;continue}if(q==="-J"){F=A[j+1]??"{}",j+=2;continue}if(T.has(q))j+=2;else j++}else return{childStart:j,replacementToken:F}}return{childStart:A.length,replacementToken:F}}var ei="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",ti="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",hR="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",yR="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",CR=/\{[^{}\s]*\}/,Nm=/\{\}|\{-?\d+\}/g,SR=["e","f","source","file","-e","-f","--source","--file"],bR=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],vR=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),RR=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),Am=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),xR=new Set(["--workdir","--wd"]),Tm="__CC_SAFETY_NET_PARALLEL_SOURCE__",ER=new TextEncoder,vl=en.maxDerivedBytes+4*en.maxPlaceholderReplacements;function _n(A,T){for(let F of A){let j=T(F);if(j)return j}return null}function Lm(A,T){return _n([...A],(F)=>cr(F,T.scanWork))}function Wm(A,T){let F=A.map(e);if((T.envAssignments?.has("PARALLEL")?T.envAssignments.get("PARALLEL"):T.environment.env.get("PARALLEL"))?.trim()){let st=jr(T);if(st)return st}if(F.length===2&&(F[1]==="--version"||F[1]==="--help"))return null;let q=Vm(F),{template:K,jobs:ee,runsRemotely:te,readsCommandsFromInput:ce,unsupported:de,workdir:_e,dryRun:Pe}=q;if(de){let st=jr(T);if(st)return st;let yt=Lm(T.envAssignments?.values()??[],T);if(yt)return yt}if(ce){let st=OR(T);if(st)return st}if(_e!==void 0&&te){let st=jr(T);if(st)return st}let je=LR(_e,T.cwd,T.environment.paths);if(je===null){let st=jr(T);if(st)return st}let it=te?{...T,cwd:void 0,originalCwd:void 0}:je===null||je===void 0||je===T.cwd?T:{...T,cwd:je};if(Pe){if([...Hn(K,it)].flatMap((yt)=>[...yt.envAssignments.values()]).some(_l)){let yt=jr(T);if(yt)return yt}return null}if(K.length===0){if(ee.some((At)=>At.length!==1)){let At=jr(T);if(At)return At}let st=ee.map((At)=>At[0]??"");In(T.budget,Rl(st));let yt=Um(it.envAssignments,it.cwd,te);return _n(st,(At)=>T.analyzeNested(At,yt))}return _n(Hn(K,it),(st)=>_R(st,q,T,it))}function _R(A,T,F,j){let{jobs:q,templateHasPlaceholder:K,runsRemotely:ee,usesStdin:te}=T,ce=A.tokens,de={...j,cwd:A.cwd,envAssignments:A.envAssignments},_e=[...A.envAssignments.values()];if(_e.some(jm)){let Tt=jr(F);if(Tt)return Tt}let Pe=Lm(_e,F);if(Pe)return Pe;let je=_e.some(rn),it=K||je,st=te&&it,yt=Um(A.envAssignments,A.wrapperCwd,ee||st);if(fn.has(A.head)){let Tt=()=>{if(!K||q.length===0)return null;return In(F.budget,Is(ce,q,"generic")),_n(q,(Ft)=>xr(ce.map((Bt)=>Er(Bt,Ft)),de))};if(Wn(ce))return Tt();let Dt=er(ce);if(Dt){if(Hm(Dt)){let Gt=$r(F);if(Gt)return Gt;if(q.length===0)return null;return In(F.budget,Dm(Dt,q)),_n(q,(Zt)=>F.analyzeNested(Er(Dt,Zt),yt))}if(rn(Dt)){if(q.length>0)return In(F.budget,Dm(Dt,q)),_n(q,(an)=>F.analyzeNested(Er(Dt,an),yt));In(F.budget,Om(Dt));let Gt=Yo(Dt);if(Gt?.[0]&&Qt(Gt[0])==="rm"&&Vn(Gt)){let an=km(F);if(an)return an}let Zt=Gt?xr(Gt,de,{dynamicInput:te,shellDynamicMatch:It("parallel.shell-dynamic",ti),rmDynamicMatch:It("parallel.rm-recursive-force-dynamic",ei)}):null;if(Zt)return Zt;return F.analyzeNested(Dt,yt)}let Ft=!je&&(!K||q.length>0)?(q.length>0?q:[void 0]).map((Gt)=>Ps(Yt(Gt===void 0?ce:K?ce.map((Zt)=>Er(Zt,Gt)):[...ce,...Gt]),Dt)):[];if(Ft.some((Gt)=>Gt.kind==="dynamic")){let Gt=$r(F);if(Gt)return Gt}let Bt=Ft.flatMap((Gt)=>Gt.kind==="literal"?[Gt.source]:[]);if(Bt.length>0)return In(F.budget,Rl(Bt)),_n(Bt,(Gt)=>F.analyzeNested(Gt,yt));if(In(F.budget,Om(Dt)),Co(Dt)){let Gt=$r(F);if(Gt)return Gt}let Ht=F.analyzeNested(Dt,yt);if(Ht)return Ht;if(it)return $r(F);return null}let zt=nr(Yt(ce));if(zt.kind==="dynamic"||zt.kind==="literal"&&rn(zt.source))return $r(F)??Tt();if(zt.kind==="literal")return Tt();if(q.length>0){let Ft=$r(F);if(Ft)return Ft;let Bt=Tt();if(Bt)return Bt;if(K)return null;let Ht=q.flatMap((Gt)=>Gt[0]===void 0?[]:[Gt[0]]);return In(F.budget,Rl(Ht)),_n(Ht,(Gt)=>F.analyzeNested(Gt,yt))}if(it||te)return $r(F)??Tt();return null}if(A.head==="rm"&&Vn(ce)){if(K&&q.length>0)return In(F.budget,Is(ce,q,"rm")),_n(q,(Dt)=>bl(ce.map((zt)=>xl(zt,Dt)),A.cwd,j));if(q.length>0)return In(F.budget,Mm(ce,q)),_n(q,(Dt)=>bl([...ce,...Dt],A.cwd,j));let Tt=bl(ce.flatMap((Dt,zt)=>{if(zt===0||!rn(Dt))return[Dt];return Dt.startsWith("-")?[xl(Dt,[""])]:[]}),A.cwd,j);if(Tt)return Tt;return km(F)}In(F.budget,K&&q.length>0?Is(ce,q,"generic"):q.length>0?Mm(ce,q):Bm(ce));let At=q.length>0?q:[void 0];return _n(At,(Tt)=>{let Dt=Tt===void 0?ce:K?ce.map((ln)=>Er(ln,Tt)):[...ce,...Tt],zt=It("parallel.shell-dynamic",ti),Ft=te&&A.head==="find"?kR(Dt,j):null,Bt=Gm(Dt,te,F.policy?.rules??[],F.budget)??Ft?.customResult??null,Ht=Qt(A.head),Gt=te&&(Ht==="rm"&&El(Dt)||Ht==="xargs"&&zm(Dt)||Ft?.rmOptions===!0),Zt=te&&(Gt||Ft?.executedSource===!0||Ft===null&&Fm(Dt,Ht)),an=xr(Dt,{...de,worktreeMode:ee||te||it?!1:F.worktreeMode},{dynamicInput:te||it,dynamicRmInput:Gt,dynamicSourceInput:Bt!==null||Zt,shellDynamicMatch:zt,dynamicSourceMatch:zt,rmDynamicMatch:It("parallel.rm-recursive-force-dynamic",ei)});if(Zt){let ln=jt(zt,F.policy);if(ln)return ln}return an??Bt??l(Dt,F.policy?.rules??[])})}function Fm(A,T){if(rn(A[0]??""))return!0;if(T==="eval"||T==="source"||T===".")return!0;if(T==="parallel"||T==="xargs")return!0;if(fn.has(T))return AR(A);if(T==="git")return PR(A);if(T==="find")return!0;if(On.has(T))return Im(A,SR,qo);if(Tn(T))return Im(A,bR,Fi);return!1}function El(A){let T=A.indexOf("--"),F=A.slice(1,T===-1?void 0:T);if(!A.some(rn))return T===-1;return F.some((q)=>rn(q)&&(q.startsWith("-")||Hm(q)))}function PR(A){if(wR(A))return!0;let T=qn(A);if(T.subcommand===null||rn(T.subcommand))return!0;if(!po.has(T.subcommand.toLowerCase()))return!1;let F=T.rest.indexOf("--"),j=T.rest.slice(0,F===-1?void 0:F);if(!A.some(rn))return F===-1;return j.some(rn)}function wR(A){for(let T=1;T<A.length;T++){let F=A[T];if(!F||F==="--"||!F.startsWith("-"))return!1;if(F==="-c"||F==="--config-env"){if(rn(A[T+1]??""))return!0;T++;continue}if(F.startsWith("-c")&&F.length>2||F.startsWith("--config-env=")){if(rn(F))return!0;continue}if(rn(F))return!0}return!1}function AR(A){if(Wn(A))return!1;let T=er(A);if(T!==null)return rn(T);let F=nr(Yt(A));if(F.kind==="literal")return rn(F.source);if(F.kind==="dynamic")return!0;return!A.some(rn)}function Im(A,T,F){let j=F(A);if(j.some((K)=>rn(K.value)))return!0;if(!A.some(rn))return F([...A,Tm]).some((K)=>K.value===Tm);let q=new Set(j.map((K)=>`${K.tokenIndex}\x00${K.kind}\x00${K.value}`));return T.some((K)=>F(A.map((ee)=>Er(ee,[K]))).some((ee)=>!q.has(`${ee.tokenIndex}\x00${ee.kind}\x00${ee.value}`)))}function Gm(A,T,F,j){if(!T||F.length===0)return null;let q=F.filter((ee)=>Qt(ee.command)===Qt(A[0]??""));if(q.length===0)return null;let K=A.some(rn);if(In(j,TR(A,q,K)),!K)return _n(q,(ee)=>l([...A,...ee.subcommand?[ee.subcommand]:[],...ee.block_args],[ee]));return _n(q,(ee)=>{let te=new Set([ee.subcommand,...ee.block_args].flatMap((ce)=>ce?IR(A,ce):[]));return _n(te,(ce)=>l(A.map((de)=>Er(de,[ce])),[ee]))})}function TR(A,T,F){let j=F?Hr(Fn(T.map((q)=>q.block_args.length+(q.subcommand?1:0)),en.maxChildAnalyses),2*Math.max(A.length,1),en.maxChildAnalyses):T.length;return{childAnalyses:j,derivedTokens:Hr(j,A.length,en.maxDerivedTokens)}}function IR(A,T){return A.flatMap((F)=>{let j=[...F.matchAll(/\{[^{}\s]*\}/g)];if(j.length!==1)return[];let q=j[0];if(!q||q.index===void 0)return[];let K=F.slice(0,q.index),ee=F.slice(q.index+q[0].length);if(!T.startsWith(K)||!T.endsWith(ee))return[T];let te=T.slice(K.length,T.length-ee.length);return te!==T?[T,te]:[T]})}function kR(A,T){let F={customResult:null,executedSource:!A.some(rn),rmOptions:!1},j=!1,q=0,K=null,ee=()=>{if(!K?.some(rn))return;for(let te of Hn(K,T))F.executedSource||=Fm(te.tokens,te.head),F.rmOptions||=te.head==="rm"&&El(te.tokens)||te.head==="xargs"&&zm(te.tokens),F.customResult??=Gm(te.tokens,!0,T.policy?.rules??[],T.budget)};for(let te of A.slice(1)){if(!j&&!te.startsWith("-")&&te!=="!"&&te!=="("){F.executedSource||=rn(te);continue}if(j=!0,K){if(te===";"||te==="+"){ee(),K=null;continue}K.push(te);continue}if(q>0){q--;continue}if(mr(te)){K=[],F.executedSource||=rn(te);continue}let ce=br(te);if(ce>0){q=ce,F.executedSource||=rn(te);continue}F.executedSource||=rn(te)}return ee(),F}function zm(A){let T=A.slice(Ur(A).childStart);return Qt(T[0]??"")==="rm"&&El(T)}function ks(A,T){return(F)=>jt(It(A,T),F.policy)}var $r=ks("parallel.shell-dynamic",ti),OR=ks("parallel.command-stream-dynamic",hR),jr=ks("parallel.command-stream-dynamic",yR),km=ks("parallel.rm-recursive-force-dynamic",ei);function bl(A,T,F){return jt(ho(Yt(A),{environment:F.environment,cwd:T,originalCwd:F.originalCwd,strict:F.strict,paranoid:F.paranoidRm,allowTmpdirVar:F.allowTmpdirVar,tmpdirWordSplittingUnsafe:Xn(F.envAssignments??new Map,F.environment),trustedTmpdirValue:dr(F.envAssignments??new Map,F.environment),protectedGitMetadata:F.protectedGitMetadata,policy:F.policy}),F.policy)}function Rl(A){return{childAnalyses:A.length,derivedTokens:A.length,derivedBytes:ni(A)}}function Om(A){return Bm([A])}function Bm(A){return{childAnalyses:1,derivedTokens:A.length,derivedBytes:ni(A)}}function Mm(A,T){if(T.length>en.maxChildAnalyses)return{childAnalyses:T.length};return{childAnalyses:T.length,derivedTokens:Fn(T.map((F)=>A.length+F.length),en.maxDerivedTokens),derivedBytes:Fn([Hr(ni(A),T.length,en.maxDerivedBytes),Fn(T.map((F)=>ni(F)),en.maxDerivedBytes)],en.maxDerivedBytes)}}function Dm(A,T){return Is([A],T,"generic")}function Is(A,T,F){if(T.length>en.maxChildAnalyses)return{childAnalyses:T.length};let j=Hr(A.length,T.length,en.maxDerivedTokens);if(j>en.maxDerivedTokens)return{childAnalyses:T.length,derivedTokens:j};let q=NR(A.map((ce)=>DR(ce,F))),K=Hr(q.occurrences,T.length,en.maxPlaceholderReplacements);if(K>en.maxPlaceholderReplacements)return{childAnalyses:T.length,derivedTokens:j,placeholderReplacements:K};if(MR(q,T,K))return{childAnalyses:T.length,derivedTokens:j,derivedBytes:en.maxDerivedBytes+1,placeholderReplacements:K};let ee=F==="generic"?Er:xl,te=Fn(T.map((ce)=>ni(A.map((de)=>ee(de,ce)))),en.maxDerivedBytes);return{childAnalyses:T.length,derivedTokens:j,derivedBytes:te,placeholderReplacements:K}}function MR(A,T,F){let j=en.maxDerivedBytes+4*F;return Fn([Hr(A.fixedBytes,T.length,j),Hr(A.occurrences,Fn(T.map((q)=>q.reduce((K,ee)=>Math.max(K,Qo(ee)),0)),j),j)],j)>j}function DR(A,T){let F=T==="generic"?A.matchAll(/\{[^{}\s]*\}/g):A.matchAll(Nm),j=0,q=0,K=0;for(let ee of F){if(j>=en.maxPlaceholderReplacements)return{occurrences:en.maxPlaceholderReplacements+1,fixedBytes:0};q=Fn([q,Qo(A.slice(K,ee.index))],vl),j++,K=ee.index+ee[0].length}return{occurrences:j,fixedBytes:j===0?Qo(A):Fn([q,Qo(A.slice(K))],vl)}}function NR(A){return{occurrences:Fn(A.map((T)=>T.occurrences),en.maxPlaceholderReplacements),fixedBytes:Fn(A.map((T)=>T.fixedBytes),vl)}}function ni(A,T=en.maxDerivedBytes){return Fn(A.map(Qo),T)}function Qo(A){return ER.encode(A).byteLength}function Fn(A,T){let F=0;for(let j of A){if(!Number.isSafeInteger(j)||j<0||j>T-F)return T+1;F+=j}return F}function Hr(A,T,F){if(!Number.isSafeInteger(A)||!Number.isSafeInteger(T)||A<0||T<0||A!==0&&T>Math.floor(F/A))return F+1;return A*T}function Um(A,T,F){let j={};if(A)j.envAssignments=A;if(F)return j.effectiveCwd=null,j.worktreeMode=!1,j;if(T!==void 0)j.effectiveCwd=T;return Object.keys(j).length>0?j:void 0}function Er(A,T){return A.replace(/\{[^{}\s]*\}/g,(F)=>$m(F,T))}function xl(A,T){return A.replace(Nm,(F)=>$m(F,T))}function $m(A,T){let F=/^\{(-?\d+)[^{}\s]*\}$/.exec(A)?.[1];if(F===void 0)return T[0]??"";let j=Number(F),q=j>0?j-1:T.length+j;return T[q]??""}function rn(A){return CR.test(A)}function jm(A){if(_l(A))return!0;for(let T of A.matchAll(/\{[^{}\s]*\}/g))if(!/^(?:\{\}|\{-?\d+\})$/.test(T[0]))return!0;return!1}function _l(A){let T=A.indexOf("{=");return T!==-1&&A.indexOf("=}",T+2)!==-1}function Hm(A){return/^\{[^{}\s]*\}$/.test(A)}function Vm(A){let T=1,F=[],j=A.length,q=-1,K=!1,ee=!1,te=!1,ce,de=A.some((st)=>st==="::::"||st==="::::+"||st===":::+");while(T<A.length){let st=A[T];if(st===void 0)break;if(st===":::"){q=T;break}if(st==="--"){let zt=el(A,T+1);F.push(...zt.templateTokens),j=T+1,q=zt.markerIndex;break}if(!st.startsWith("-")){let zt=el(A,T);F.push(...zt.templateTokens),j=T,q=zt.markerIndex;break}let yt=A[T+1],At=st.indexOf("="),Tt=At===-1?st:st.slice(0,At),Dt=At===-1?void 0:st.slice(At+1);if(st==="--dry-run"){te=!0,T++;continue}if(st==="-I"||st.startsWith("-I")&&st.length>2){de||=(st==="-I"?yt:st.slice(2))!=="{}",T+=st==="-I"?2:1;continue}if(st==="--replace"||st==="-i"){de=!0,T+=2;continue}if(Tt==="--replace"||st.startsWith("-i")&&st.length>2){let zt=Tt==="--replace"?Dt:st.slice(2);de||=zt!==""&&zt!=="{}",T++;continue}if(st==="-a"||RR.has(Tt)){de=!0,T+=Dt===void 0?2:1;continue}if(st==="--pipe"||st==="--pipepart"){ee=!0,T++;continue}if(Tt==="--env"){de=!0,T+=Dt===void 0?2:1;continue}if(Am.has(Tt)||st.startsWith("-S")&&st.length>2){K=!0,T+=Am.has(st)?2:1;continue}if(xR.has(Tt)){let zt=Dt??yt;if(zt===void 0||zt===":::"||zt==="--"){de=!0,T++;continue}ce=zt,de||=Dt!==void 0&&zt==="",T+=Dt===void 0?2:1;continue}if(st.startsWith("-j")&&st.length>2&&/^\d+$/.test(st.slice(2))){T++;continue}if(st.startsWith("--")&&Dt!==void 0){T++;continue}if(vR.has(st)){if(yt===void 0||yt===":::"||yt==="--"){de=!0,T++;continue}T+=2;continue}T+=st==="-j"||st==="--jobs"?2:1}de||=F.some(te?_l:jm);let _e=[];if(q!==-1){let st=[];for(let yt=q+1;yt<A.length;yt++){let At=A[yt];if(At===":::"){_e.push(st),st=[];continue}if(At!==void 0)st.push(At)}_e.push(st)}let Pe=WR(_e),je=F.some(rn),it=F.length===0&&q===-1;return{template:F,jobs:Pe,childStart:j,templateHasPlaceholder:je,runsRemotely:K,usesStdin:ee||q===-1,readsCommandsFromInput:it,unsupported:de,workdir:ce,dryRun:te}}function LR(A,T,F){if(A===void 0)return;if(A==="..."||/[{}$`*?~[]/.test(A))return null;if(!T&&!gR(A))return null;try{return gr(T??A,A,F)}catch{return null}}function WR(A){if(A.length===0||A.some((F)=>F.length===0))return[];let T=[[]];for(let F of A){if(F.length===1){let q=F[0];if(q===void 0)return[];for(let K of T)K.push(q);continue}let j=[];for(let q of T)for(let K of F)if(j.push([...q,K]),j.length>en.maxChildAnalyses)return j;T=j}return T}function qm(A){return Vm(A).childStart}var FR="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",Os="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function wl(A){return A?.parts.some((T)=>T.provenance==="command-substitution")??!1}function Pl(A){return A?.parts.some((T)=>T.provenance==="literal"&&T.raw.replace(/^["']/,"").startsWith("-"))??!1}function Ym(A,T,F,j,q=!1,K){let te=(Wo(A,T)||j&&A!=="powershell"&&T[0]?.provenance==="variable")&&mn(K,"shell.dynamic-executable",q)?It("shell.dynamic-executable",FR):null;return jt(te,K)??Zm(A,T,F,q,K)}function Zm(A,T,F,j,q){if(T.length<2)return null;let K=T.flatMap((te,ce)=>wl(te)?[ce]:[]);if(K.length===0)return null;let ee=Qt(T[0]?.text??"");if(ee==="git"){let te=oe(A,T),ce=zR(te);if(mn(q,"shell.dynamic-structure",j)&&K.some((Pe)=>Pe<=ce))return jt(It("shell.dynamic-structure",Os),q);if(jt(go(te,{env:F.env}),q))return null;let de=T[ce]?.text.toLowerCase(),_e=te.findIndex((Pe,je)=>je>ce&&e(Pe)==="--");if(mn(q,"shell.dynamic-structure",j)&&de&&po.has(de)&&K.some((Pe)=>Pe>ce&&(_e===-1||Pe<_e)))return jt(It("shell.dynamic-structure",Os),q);return null}if(ee==="find")return mn(q,"shell.dynamic-structure",j)&&BR(T)?jt(It("shell.dynamic-structure",Os),q):null;if(ee==="rm"){let te=T.findIndex((de,_e)=>_e>0&&e(de)==="--"),ce=Vn(T.map(e));return mn(q,"shell.dynamic-structure",j)&&K.some((de)=>(te===-1||de<te)&&(de<T.length-1||!ce))?jt(It("shell.dynamic-structure",Os),q):null}if(ee==="xargs")return Km(A,T.slice(Ur(T.map(e)).childStart),"xargs",F,j,q);if(ee==="parallel")return Km(A,T.slice(qm(T.map(e))),"parallel",F,j,q);return null}function Km(A,T,F,j,q,K){if(T.length===0)return null;let ee=GR(T,j);if(Wo(A,ee)){let ce=jt(It(`${F}.shell-dynamic`,F==="xargs"?Cl:ti),K);if(ce)return ce}let te=Zm(A,ee,j,q,K);if(te)return te;if(ee[0]?.text==="rm"&&ee.slice(1).some((ce)=>wl(ce)&&Pl(ce)))return jt(It(`${F}.rm-recursive-force-dynamic`,F==="xargs"?yl:ei),K);return null}function GR(A,T){let F=Dr(A,T),j=F.rewritten?Yt(F.words.map(e)):F.words,q=j[0];return q&&e(q)==="busybox"?j.slice(1):j}function zR(A){let T=1;while(T<A.length){let F=A[T],j=F?e(F):"";if(vn.has(j)){T+=2;continue}if(j.startsWith("-")){T++;continue}return T}return T}function BR(A){let T=!1,F=0,j=!1,q=!1;for(let K=1;K<A.length;K++){let ee=A[K];if(!ee)continue;let te=wl(ee);if(F>0){F--;continue}if(q){if(ee.text===";"||ee.text==="+"){q=!1,T=!0,j=!1;continue}if(te&&(j||Pl(ee)))return!0;j=!1;continue}if(!T&&!ee.text.startsWith("-")){if(te&&(K>1||Pl(ee)))return!0;continue}if(T=!0,te)return!0;let ce=br(ee.text);if(ce>0){F=ce;continue}if(mr(ee.text))q=!0,j=!0}return!1}function Al(A,T){return A.some((F)=>{if(F.value==="-"&&(F.kind==="main-script"||F.kind==="program-file"))return!0;return!vi(T[F.tokenIndex],F.value)})}var UR="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",$R="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",jR="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function Xm(A,T){let F=T.slice(1);if(A==="dd"&&F.some((j)=>/^of=\/dev\/.+/.test(j)))return It("dd.device-write",UR);if((A==="mkfs"||A.startsWith("mkfs."))&&F.some((j)=>j.startsWith("/dev/")))return It("mkfs.device",$R);if(A==="shred"&&F.length>0)return It("shred.target",jR);return null}var Qm=[{heads:new Set(["rm","rmdir"]),analyze:(A)=>ho(A.words,{environment:A.options.environment,cwd:A.cwd,originalCwd:A.originalCwd,strict:A.options.strict,paranoid:A.options.paranoidRm,allowTmpdirVar:A.allowTmpdirVar,tmpdirWordSplittingUnsafe:Xn(A.envAssignments,A.options.environment),trustedTmpdirValue:dr(A.envAssignments,A.options.environment),protectedGitMetadata:A.options.protectedGitMetadata,policy:A.options.policy})},{heads:new Set(["git"]),analyze:(A)=>go(A.words,Tl(A))},{heads:new Set(["find"]),analyze:(A)=>xs(A.words,{environment:A.options.environment,cwd:A.cwd,originalCwd:A.originalCwd,strict:A.options.strict,allowTmpdirVar:A.allowTmpdirVar,tmpdirWordSplittingUnsafe:Xn(A.envAssignments,A.options.environment),trustedTmpdirValue:dr(A.envAssignments,A.options.environment),protectedGitMetadata:A.options.protectedGitMetadata,derivedCommandWorkBudget:A.options.derivedCommandWorkBudget,envAssignments:A.envAssignments,policy:A.options.policy,analyzeTokens:A.analyzeChildTokens,analyzeNested:(T,F)=>Vr(A.options.analyzeNested(T,F))})},{heads:new Set(["xargs"]),analyze:(A)=>xm(A.words,{...Jm(A),analyzeNested:(T,F)=>Vr(A.options.analyzeNested(T,F))})},{heads:new Set(["parallel"]),analyze:(A)=>Wm(A.words,{...Jm(A),budget:A.options.parallelBudget,analyzeNested:(T,F)=>Vr(A.options.analyzeNested(T,F))})}];function Jm(A){return{environment:A.options.environment,cwd:A.cwd,originalCwd:A.originalCwd,strict:A.options.strict,paranoidRm:A.options.paranoidRm,paranoidInterpreters:A.options.paranoidInterpreters,allowTmpdirVar:A.allowTmpdirVar,protectedGitMetadata:A.options.protectedGitMetadata,derivedCommandWorkBudget:A.options.derivedCommandWorkBudget,envAssignments:A.envAssignments,worktreeMode:A.options.worktreeMode,policy:A.options.policy,scanWork:A.options.scanWork}}function Vr(A){return A?{id:A.ruleId??"",reason:A.reason,intent:A.intent??"manual_only"}:null}function Tl(A){return{env:A.options.environment.env,cwd:A.cwd,dynamicArguments:A.dynamicArguments,envAssignments:A.envAssignments,policy:A.options.policy,worktreeMode:A.options.worktreeMode}}var rf="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function of(A){return Qm.find((T)=>T.heads.has(A))?.analyze}function ri(A,T,F){let j=F.trace;if(A.length===0)return null;let q=F.commandView?.dialect??"posix",K=(Ot)=>Ot.map((Nt)=>q==="posix"?e(Nt):Nt.text),ee=F.effectiveCwd===null,te=ee?void 0:F.effectiveCwd??F.cwd,ce=ee?void 0:F.cwd,de=xe(A);if(de.envAssignments.size>0)j?.recordSegment({type:"env-strip",input:K(A),envVars:[...de.envAssignments.keys()],output:K(de.words)});let _e=Dr(de.words,F.environment,te,new Map([...F.envAssignments??[],...de.envAssignments])),Pe=_e.envSplitValues??[];if(Pe.length>0){let Ot=[...Pe,...K(_e.words)].join(" "),Nt=cr(Ot,F.scanWork);if(Nt)return j?.recordSegment({type:"dangerous-text",token:Ot,matched:!0,reason:Nt.reason}),or(Nt);if(F.strict)return Mn(j);let $t=Vi(Pe,K(_e.words));if($t){Gn(F.derivedCommandWorkBudget,$t.length);let Kt=F.analyzeNested($t.join(" "),{effectiveCwd:_e.cwd===void 0?F.effectiveCwd:_e.cwd,envAssignments:new Map([...F.envAssignments??[],...de.envAssignments,..._e.envAssignments])});if(Kt)return Kt}}let je=_e.rewritten?Yt(K(_e.words)):oe(q,_e.words),it=K(je),st={...F,wrapperNormalizationBudget:F.wrapperNormalizationBudget??{iterations:0}};if(j&&de.words.length>je.length){let Ot=K(de.words);j.recordSegment({type:"leading-tokens-stripped",input:Ot,removed:Ot.slice(0,Ot.length-je.length),output:it})}let yt=new Map([...F.envAssignments??[],...de.envAssignments,..._e.envAssignments]),At=it[0];if(!At)return null;if(Gr(At))throw new An;let Tt=Qt(At),Dt=_e.cwd===null?void 0:_e.cwd??te,zt=_e.cwd===null?void 0:ce,Ft=_e.cwd===void 0?F.effectiveCwd:_e.cwd,Bt=!Mo(yt,F.environment),Ht=Ym(q,_e.words,F.environment,T===0,F.strict,F.policy);if(Ht)return j?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:Ht.reason}),or(Ht);let Gt=vs(it,F.policy);if(Gt){for(let Ot of[Gt.childIndex,...Gt.alternativeChildIndices]){ef(st.wrapperNormalizationBudget);let Nt=je.slice(Ot);j?.recordSegment({type:"transparent-wrapper",wrapper:Gt.wrapper,output:K(Nt)});let $t=ri(Nt,T,{...st,effectiveCwd:Ft,envAssignments:yt});if($t)return $t}return null}let Zt=Tt==="eval"?yo(je):Tt==="trap"?pm(je):void 0;if(Zt?.kind==="dynamic"&&(F.strict||!F.commandView||!gl(F.commandView)))return Mn(j);if(Zt?.kind==="literal"){j?.recordSegment({type:"recurse",reason:Tt==="eval"?"shell-eval":"shell-trap",innerCommand:Zt.source,depth:T+1});let Ot=F.analyzeNested(Zt.source,{effectiveCwd:Ft,envAssignments:yt,functionDefinitions:F.functionDefinitions});if(Ot)return Ot}if(af(At,Tt)){if(Wn(it))return null;let Ot=HR(it,yt,Ft,F,j,T);if(Ot)return Ot;let Nt=er(it);if(Nt){let Qr=Ps(je,Nt);if(Qr.kind==="dynamic")return Mn(j);let ra=Qr.kind==="literal"?Qr.source:Nt,vc=VR(ra);j?.recordSegment({type:"shell-wrapper",wrapper:Tt,innerCommand:vc}),j?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:vc,depth:T+1});let Rc=F.analyzeNested(ra,{effectiveCwd:Ft,envAssignments:yt});if(Rc)return Rc;return Co(ra)?Mn(j):null}let $t=nr(je);if($t.kind==="dynamic")return Mn(j);if($t.kind==="literal")return Ns($t.source,Ft,yt,F,j,T);let Kt=gm(je,F.commandView?.redirections??[],F.hasPipelineInput??!1,F.literalShellInput);if(Kt.kind==="dynamic")return Mn(j);if(Kt.kind==="literal")return j?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:Kt.source,depth:T+1}),F.analyzeNested(Kt.source,{effectiveCwd:Ft,envAssignments:yt})}if(Tt==="source"||Tt==="."){let Ot=it[1]==="-p"?2:null;if(Ot!==null){let Qr=F.commandView?je[Ot]:void 0;if(!Qr)return null;if(Qr.provenance!=="literal")return Mn(j)}let Nt=Ot===null?1:3,$t=it[Nt]==="--"?Nt+1:Nt,Kt=F.commandView?je[$t]:void 0;if(!Kt)return null;if(Kt.provenance==="literal")return Ns(Kt.text,Ft,yt,F,j,T);if(F.strict||!F.commandView||!gl(F.commandView))return Mn(j)}if(On.has(Tt)){if(F.strict&&Al(qo(it),je))return Mn(j);let Ot=bs(it,($t)=>Vr(F.analyzeNested($t,{effectiveCwd:Ft,envAssignments:yt}))),Nt=jt(Ot,F.policy);if(Nt)return j?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:Nt.reason}),or(Nt)}if(Tn(Tt)){if(F.strict&&Al(Fi(it),je))return Mn(j);let Ot=Wi(it);if(Ot){let Nt=mn(F.policy,"interpreter.one-liner-paranoid",!!F.paranoidInterpreters);if(j?.recordSegment({type:"interpreter",interpreter:Tt,codeArg:Ot,paranoidBlocked:Nt}),Nt){let Kt=jt(It("interpreter.one-liner-paranoid",io),F.policy);if(Kt)return or(Kt)}if(zi(Tt,Ot))return null;j?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:Ot,depth:T+1});let $t=F.analyzeNested(Ot,{effectiveCwd:Ft,envAssignments:yt});if($t&&$t.ruleId!=="raw-text.dangerous-command"&&($t.reason!==hr||uo(Ot)))return $t;if(so(Ot,F.scanWork)){let Kt=jt(It("interpreter.dangerous-command",Mr),F.policy);if(Kt)return j?.recordSegment({type:"dangerous-text",token:Ot,matched:!0,reason:Mr}),or(Kt)}j=void 0}}if(Tt==="busybox"&&it.length>1)return ef(st.wrapperNormalizationBudget),j?.recordSegment({type:"busybox",subcommand:it[1]??"unknown"}),j?.recordSegment({type:"recurse",reason:"busybox",innerCommand:it.slice(1).join(" "),depth:T+1}),ri(je.slice(1),T,{...st,effectiveCwd:Ft,envAssignments:yt});let an=jt(Xm(Tt,it),F.policy);if(an)return j?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:an.reason}),or(an);let ln=j===st.trace?st:{...st,trace:j},tn={words:je,head:Tt,cwd:Dt,originalCwd:zt,envAssignments:yt,allowTmpdirVar:Bt,dynamicArguments:_e.words.some((Ot)=>Ot.provenance==="command-substitution"),depth:T,effectiveCwd:Ft,options:ln,analyzeChildTokens:(Ot,Nt)=>Vr(ri(Yt(Ot),T+1,{...ln,commandView:void 0,effectiveCwd:Nt,envAssignments:yt}))??l(Ot,ln.policy.rules)},Xt=of(Tt);if(Tt==="rm"||Tt==="xargs"||Tt==="parallel")j?.recordSegment({type:"tmpdir-check",tmpdirValue:yt.has("TMPDIR")||F.environment.env.has("TMPDIR")?"<redacted>":null,isOverriddenToNonTemp:!Bt,allowTmpdirVar:Bt});let Wt=j&&Tt==="git"?rm(tn.words,Tl(tn)):void 0,Ut=tf(Wt?Wt.match:Xt?.(tn)??null,F.policy);if(j)qR(tn,Ut,Wt?.relaxation??null);if(Ut)return or(Ut);let Jt=Xt!==void 0;if(!Jt)if(!Ni.has(Tt)){let Ot=j?[]:void 0;for(let Nt=1;Nt<it.length;Nt++){let $t=it[Nt];if(!$t)continue;Ot?.push($t);let Kt=tf(KR(tn,it,Nt),F.policy);if(Kt)return j?.recordSegment({type:"fallback-scan",tokensScanned:Ot??[],embeddedCommandFound:Qt($t)}),or(Kt)}j?.recordSegment({type:"fallback-scan",tokensScanned:Ot??[]})}else j?.recordSegment({type:"fallback-scan",tokensScanned:[]});else j?.recordSegment({type:"fallback-scan",tokensScanned:[]});if(T===0||!Jt){let Ot=l(it,F.policy.rules);if(j?.recordSegment({type:"custom-rules-check",rulesChecked:F.policy.rules.length>0,matched:!!Ot,reason:Ot?.reason}),Ot)return or(Ot)}else j?.recordSegment({type:"custom-rules-check",rulesChecked:!1,matched:!1});return null}function HR(A,T,F,j,q,K){let ee=cm(A);if(ee.argvSource?.kind==="absent")return Mn(q);if(ee.argvSourceApplies&&ee.argvSource){let ce=Ns(ee.argvSource.value,F,T,j,q,K,!0);if(ce)return ce}if(!ee.envSourceApplies||!ee.envName)return null;let te=T.get(ee.envName);if(!te)return null;return Ns(te,F,T,j,q,K,!0)}function Ns(A,T,F,j,q,K,ee=!1){if(ee&&/[$`*?[\]]/.test(A))return Mn(q);let te=Oo(A,T,j.environment.paths),ce=te?j.literalHeredocFiles?.get(te):void 0;if(ce===void 0)return ee?Mn(q):null;return Gn(j.derivedCommandWorkBudget,1),q?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:ce,depth:K+1}),j.analyzeNested(ce,{effectiveCwd:T,envAssignments:F})}function VR(A){let T=A[0];return A.length>=2&&(T==='"'||T==="'")&&A.at(-1)===T?A.slice(1,-1):A}function qR(A,T,F){let j={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[A.head];if(!j)return;if(A.options.trace?.recordSegment({type:"rule-check",rule:j,matched:!!T||!!F,reason:T?.reason??F?.originalReason}),F)A.options.trace?.recordSegment({type:"worktree-relaxation",originalReason:F.originalReason,gitCwd:F.gitCwd})}function ef(A){if(A.iterations>=ro)throw new An;A.iterations++}function or(A){return{reason:A.reason,ruleId:A.id||void 0,intent:A.intent}}function Mn(A){return A?.recordSegment({type:"error",message:rf}),or(sf())}function sf(){return{id:"",reason:rf,intent:"stop_and_explain"}}function af(A,T){return fn.has(T)||A==="$SHELL"||A==="${SHELL}"||fn.has(Vt(T))}function KR(A,T,F){let j=Hn(T.slice(F),{environment:A.options.environment,cwd:A.cwd,envAssignments:A.envAssignments,policy:A.options.policy});for(let q of j){let K=YR(A,F,q);if(K)return K}return null}function YR(A,T,F){let j=F.tokens[0];if(!j)return null;let q=Qt(j);if(af(j,q)){Gn(A.options.derivedCommandWorkBudget,A.words.length-T);let ce=F.tokens;if(Wn(ce))return null;let de=er(ce);if(!de){if(nr(Yt(ce)).kind==="dynamic")return sf();return Ds(A,F)}let _e=A.options.analyzeNested(de,{effectiveCwd:F.wrapperCwd===void 0?A.effectiveCwd:F.wrapperCwd,envAssignments:F.envAssignments});return _e?Vr(_e):Ds(A,F)}let K=of(q);if(!K||q==="xargs"||q==="parallel"){if(F.wrappedByTransparent&&A.options.policy.rules.length>0)Gn(A.options.derivedCommandWorkBudget,A.words.length-T);return Ds(A,F)}Gn(A.options.derivedCommandWorkBudget,A.words.length-T);let ee=[q,...F.tokens.slice(1)],te={...A,words:Yt(ee),head:q,cwd:F.cwd,originalCwd:F.wrapperCwd===null?void 0:A.originalCwd,envAssignments:F.envAssignments,allowTmpdirVar:!Mo(F.envAssignments,A.options.environment),effectiveCwd:F.wrapperCwd===void 0?A.effectiveCwd:F.wrapperCwd,options:q==="git"?{...A.options,worktreeMode:!1}:A.options};return K(te)??Ds(A,F)}function Ds(A,T){return T.wrappedByTransparent?l(T.tokens,A.options.policy.rules):null}function tf(A,T){return A?.id.startsWith("custom.")||A?.id==="raw-text.dangerous-command"?A:jt(A,T)}var ZR=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,XR=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function JR(A,T){let F=uf(A,T);if(F.length===0)return!1;let j=F[cf(F)];if(j==="cd"||j==="pushd"||j==="popd")return!0;return ZR.test(A.join(" "))}function lf(A,T,F,j){if(A.dialect==="powershell"){let te=QR(A.words,j);if(te.kind==="none")return;if(!T||te.kind==="unknown")return null;return nf(rx(te.target),T,F.paths)}let q=A.words.map(e);if(!JR(q,F))return;if(!T)return null;let K=uf(q,F,T),ee=cf(K);if(ee===-1||K[ee]!=="cd")return null;return nf(K[ee+1],T,F.paths)}function nf(A,T,F){if(!A||A==="-"||A.includes("$")||A.includes("`"))return null;try{return ox(gr(T,A,F),T,F)?T:null}catch{return null}}function QR(A,T){let F=ex(A[0])?1:0,j=A[F];if(!tx(j,F===1))return{kind:"none"};let q=j.text.toLowerCase(),K=q.split(/[\\/]/).pop()??q;if(!XR.has(K))return{kind:"none"};if(q!==K||K==="pop-location"||K==="popd")return{kind:"unknown"};return nx(A.slice(F+1),T)}function ex(A){return A?.provenance==="literal"&&!A.quoted&&A.raw===A.text&&(A.text==="&"||A.text===".")}function tx(A,T){return A?.provenance==="literal"&&(T||!A.quoted&&A.raw===A.text)}function nx(A,T){let F;for(let j of A){if(j.provenance!=="literal"||F!==void 0)return{kind:"unknown"};F=j.text}if(F!==void 0)return{kind:"target",target:F};return T===void 0?{kind:"unknown"}:{kind:"target",target:T}}function rx(A){return A.includes("::")?void 0:A.replaceAll("\\","/")}function cf(A){let T=0;if(A[0]==="builtin"&&A.length>1)T=1;if(A[T]!=="time")return T;let F=T+1;while(A[F]?.startsWith("-"))F++;return F}function uf(A,T,F){let j=ix(A);return yr([...j],T,F)}function ox(A,T,F){let j=F.realpath(A),q=F.realpath(T);if(j===null||q===null)return Ms(A)===Ms(T);return Ms(j)===Ms(q)}function ix(A){let T=0;while(T<A.length){let F=A[T];if(F==="{"||F==="("||F==="$(")T++;else break}return A.slice(T)}var kl="TMPDIR",Ol="IFS",df=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,mf=/^[A-Za-z_][A-Za-z0-9_]*$/,ff=new Set(["export","typeset","declare","readonly"]),sx=new Set(["builtin","command","time"]);function pf(A,T){return{env:A,effectiveEnvAssignments:dx(A,T),shellAssignments:new Map}}function gf(A){return{env:A.env,effectiveEnvAssignments:A.effectiveEnvAssignments?new Map(A.effectiveEnvAssignments):void 0,shellAssignments:new Map(A.shellAssignments)}}function Ml(A,T){let F=yf(A,T);F.assignments.filter((ee)=>ee.persists).forEach((ee)=>{T.shellAssignments.set(ee.name,ee.value),Dl(T,ee)});let j=F.commandIndex;if(j!==-1&&ff.has(A[j]??""))A.filter((ee)=>mf.test(ee)&&Il(ee)).forEach((ee)=>{mx(T,ee)});let q=j===-1?-1:Cf(A,j);if(q===-1||A[q]!=="unset")return;let K=px(A,q);if(K===null)return;A.slice(K).forEach((ee)=>{fx(T,ee)})}function hf(A,T){let F=yf(A,T).assignments;if(F.length===0)return T.effectiveEnvAssignments;let j=new Map(T.effectiveEnvAssignments??[]);return F.forEach((q)=>{j.set(q.name,q.value)}),j}function yf(A,T){let F=A.findIndex((ee)=>!ax(ee)),j=F!==-1&&ff.has(A[Cf(A,F)]??""),q=ux(T);return{assignments:A.flatMap((ee,te)=>{let ce=lx(ee,q,T.env);if(!ce)return[];if(F!==-1&&te>F&&!j&&!sa(ce.name))return[];return q.set(ce.name,ce.value),[{...ce,persists:F===-1||j}]}),commandIndex:F}}function Cf(A,T){let F=T;while(sx.has(A[F]??"")){F+=1;while(A[F]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(A[F]??""))return T;F+=1}}return F}function ax(A){return Ln(A)!==null||df.test(A)}function lx(A,T,F){return Ln(A)??cx(A,T,F)}function cx(A,T,F){let j=Ei(A,F,T);if(j)return j;let q=A.match(df)?.[1];if(!q)return null;let K=A.indexOf("=");return{name:q,value:`${T.has(q)?T.get(q):F.get(q)??""}${A.slice(K+1)}`}}function Il(A){return A===kl||A===Ol||aa(A)}function ux(A){return new Map([...A.effectiveEnvAssignments??[],...A.shellAssignments])}function dx(A,T){let F=[...Ri,kl,Ol].map((j)=>{let q=A.get(j);return q===void 0?null:[j,q]}).filter((j)=>j!==null);if(F.length===0)return T;return new Map([...F,...T??[]])}function Dl(A,T){let F=new Map(A.effectiveEnvAssignments??[]);F.set(T.name,T.value),A.effectiveEnvAssignments=F}function mx(A,T){Dl(A,{name:T,value:A.shellAssignments.get(T)??A.effectiveEnvAssignments?.get(T)??A.env.get(T)??""})}function fx(A,T){if(!Il(T)&&!mf.test(T))return;if(A.shellAssignments.set(T,""),!Il(T)||T===kl||T===Ol||Eo(T)){Dl(A,{name:T,value:""});return}if(!A.effectiveEnvAssignments?.has(T))return;let F=new Map(A.effectiveEnvAssignments);F.delete(T),A.effectiveEnvAssignments=F.size===0?void 0:F}function px(A,T){let F=T+1;while(F<A.length){let j=A[F];if(!j)return null;if(j==="--")return F+1;if(j==="-v"){F++;continue}if(j.startsWith("-"))return null;return F}return F}var gx="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",qr="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.",hx=64;function Gl(A,T,F,j){let q=F.derivedCommandWorkBudget===void 0,K=F.parallelBudget===void 0;try{return yx(A,T,{...F,derivedCommandWorkBudget:F.derivedCommandWorkBudget??ki(),parallelBudget:F.parallelBudget??cu()},j)}catch(ee){let te=ee instanceof An&&q?Qc:ee instanceof $i&&K?lu:void 0;if(!te)throw ee;if(F.trace?.currentSegmentIndex!==void 0)F.trace.recordSegment({type:"error",message:te});else F.trace?.recordGlobal({type:"error",message:te});return{reason:te,segment:A,intent:"stop_and_explain"}}}function yx(A,T,F,j){if(T>=Di)return F.trace?.recordSegment({type:"error",message:sr}),{reason:sr,segment:A,intent:"stop_and_explain"};let q=j??F.factStore?.getCommandProgram(A,F.shell??"auto")??R(A,F.shell);if(q.status==="limited")return F.trace?.recordSegment({type:"error",message:sr}),{reason:sr,segment:A,intent:"stop_and_explain"};if(q.status==="invalid"){let de=q.issues.find((_e)=>_e.code.includes("heredoc"));if(de){if(!F.strict)return Fl(A,F);let _e=`Unsupported heredoc syntax: ${de.message}`;return F.trace?.recordGlobal({type:"error",message:_e}),{reason:_e,segment:A,intent:"stop_and_explain"}}return Ef(A,F),{reason:hr,segment:A,intent:"stop_and_explain"}}if(F.strict&&q.status==="partial")return Ef(A,F),{reason:hr,segment:A,intent:"stop_and_explain"};if(q.issues.some((de)=>de.code.includes("quote"))&&!F.analyzePartialProgram)return Fl(A,F);let ee=F.cwd,te=F.effectiveCwd!==void 0?F.effectiveCwd:F.cwd,ce=pf(F.environment.env,F.envAssignments);return Fs(q,T,{...F,rootProgram:q},ee,[{effectiveCwd:te,shellGitContextState:ce,literalHeredocFiles:new Map(F.literalHeredocFiles),functionDefinitions:new Map(F.functionDefinitions)}]).result}function Fs(A,T,F,j,q){let K=[...q],ee,te;for(let[ce,de]of A.nodes.entries()){if(de.kind==="connector"){te=de.operator;continue}let _e=A.nodes[ce+1],Pe=_e?.kind==="connector"?_e.operator:void 0,je=Cx(A,ce,de,te,Pe),it=te==="&&"||te==="||",st=it?ee:void 0,yt=te==="&&"?st?.success??K:te==="||"?st?.failure??K:K,At=te==="||"?st?.success??[]:[],Tt=te==="&&"?st?.failure??[]:[],Dt=it||bo(Pe);if(de.kind==="function"){let an=yt.flatMap((tn)=>{let Xt=oi(tn);return Xt.functionDefinitions.set(de.name,de.body),Nl(tn,[Xt],je,Pe==="&",bo(Pe))}),ln=Ll(an,[],At,Tt,te,Pe);K=ln.states,ee=ln.conditionalStates,te=void 0;continue}if(de.kind==="group"){let an=[],ln=[];for(let Xt of yt){let Wt=Fs(de.body,T,F,j,[oi(Xt)]);if(Wt.result)return Wt;if(an.push(...Nl(Xt,Wt.states,je,Pe==="&",bo(Pe))),Dt)ln.push(Xt,...je?Wt.states.map((Ut)=>Ls(Xt,Ut)):Wt.states)}let tn=Ll(an,ln,At,Tt,te,Pe);K=tn.states,ee=tn.conditionalStates,te=void 0;continue}if(de.kind!=="command")continue;let zt=F.trace?.flattenNested?F.trace.currentSegmentIndex:F.trace?.allocateSegment(),Ft=A.nodes[ce-2],Bt=Gs(te)&&Ft?.kind==="command"?fm(Ft)??bx(Ft):void 0,Ht=[],Gt=[];for(let an of yt){let ln=vx(de,T,F,j,[oi(an)]);if(ln.result)return{result:ln.result,states:K};let tn=A.dialect==="powershell"?ln.states:ln.states.map((Xt)=>Ls(an,Xt));for(let Xt of tn){let Wt=oi(Xt),Ut=Ex(de,T,F.trace?{...F,trace:_f(F.trace,zt)}:F,j,Wt,Gs(te),Bt);if(Ut)return{result:Ut,states:K};let Jt=Wx(de,Wt.functionDefinitions);if(Jt)Gn(F.derivedCommandWorkBudget,zs(Jt));let Ot=Jt?T+1>=Di?Wl(de.displayText,F,[Wt]):Fs(Jt,T+1,F,j,[Wt]):{result:null,states:[Wt]};if(Ot.result)return Ot;if(Ht.push(...Nl(an,Ot.states,je,Pe==="&",bo(Pe))),Dt)Gt.push(an),Gt.push(...Ot.states.map((Nt)=>je?Ls(an,Nt):Nt))}}let Zt=Ll(Ht,Gt,At,Tt,te,Pe);K=Zt.states,ee=Zt.conditionalStates,te=void 0}return{result:null,states:K}}function Cx(A,T,F,j,q){if(F.kind==="group"&&F.style==="subshell")return!0;if(A.dialect==="posix"&&(Gs(j)||Gs(q)))return!0;if(q==="&")return!0;return A.dialect==="powershell"&&F.kind==="group"&&F.style==="brace"&&Sx(A,T)}function Nl(A,T,F,j,q){let K=F?T.map((te)=>Ls(A,te)):[...T],ee=q?K.flatMap((te)=>ii(A.literalHeredocFiles,te.literalHeredocFiles)?[te]:[{...te,literalHeredocFiles:new Map(A.literalHeredocFiles)},te]):K;return j?[A,...ee]:ee}function Ls(A,T){return{...A,literalHeredocFiles:new Map(T.literalHeredocFiles)}}function Sx(A,T){let F=[...A.nodes.slice(0,T)].reverse().find((q)=>q.kind==="command"||q.kind==="connector");if(!F||F.kind!=="command")return!0;let j=F.words[0]?.text.toLowerCase();if(j==="&"||j===".")return!1;if(j==="write-output"||j==="function"||j==="start-job")return!0;if(Rx(F))return!0;return F.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function Gs(A){return A==="|"||A==="|&"}function bx(A){if(A?.dialect!=="powershell")return;if(A.words.length===1&&A.words[0]?.quoted&&A.words[0].provenance==="literal")return A.words[0].text;if(A.words[0]?.text.toLowerCase()==="write-output"&&A.words.length===2&&A.words[1]?.provenance==="literal")return A.words[1].text;return}function bo(A){return A==="&&"||A==="||"}function Ll(A,T,F,j,q,K){let ee={success:Ws([...F,...A]),failure:Ws([...j,...T])},te=bo(K)?ee:void 0;return{states:bo(q)||te?Ws([...ee.success,...ee.failure]):ee.success,conditionalStates:te}}function _f(A,T,F=A.flattenNested){return{currentSegmentIndex:T,flattenNested:F,allocateSegment:A.allocateSegment,getNextSegmentIndex:A.getNextSegmentIndex,recordGlobal:A.recordGlobal,recordSegment:(j,q=T)=>A.recordSegment(j,q)}}function vx(A,T,F,j,q){let K=A.nested.map((ee)=>({program:ee,depth:T}));if(A.dialect==="powershell"){let ee=xx(A);if(ee){if(T+1>=Di)return Wl(ee,F,q);let te=R(ee,"powershell");if(te.status==="limited")return Wl(ee,F,q);if(te.status!=="complete")return Sf(K,F,j,q);Gn(F.derivedCommandWorkBudget,zs(te)),K.push({program:te,depth:T+1})}}return Sf(K,F,j,q)}function Rx(A){let T=A.words[0];return T?.provenance==="variable"&&A.words.at(-1)?.text==="="?T.text.toLowerCase():void 0}function Sf(A,T,F,j){let q=[...j];for(let K of A){let ee=[];for(let te of q){let ce=Fs(K.program,K.depth,T,F,[oi(te)]);if(ce.result)return ce;ee.push(...ce.states)}q=Ws(ee)}return{result:null,states:q}}function xx(A){let T=A.words[0]?.provenance==="literal"&&!A.words[0].quoted&&A.words[0].raw===A.words[0].text&&(A.words[0].text==="&"||A.words[0].text==="."),F=T?1:0,j=A.words[F];if(j?.provenance!=="literal"||!T&&(j.quoted||j.raw!==j.text)||!["iex","invoke-expression"].includes(j.text.toLowerCase()))return;let q=A.words.slice(F+1),K=q[0]&&!q[0].quoted&&q[0].raw===q[0].text&&["-c","-command"].includes(q[0].text.toLowerCase())?1:0,ee=q[K];return q.length===K+1&&ee?.quoted&&ee.provenance==="literal"?ee.text:void 0}function zs(A){return A.nodes.reduce((T,F)=>T+(F.kind==="command"?F.words.length+F.nested.reduce((j,q)=>j+zs(q),0):F.kind==="group"||F.kind==="function"?zs(F.body):0),0)}function Wl(A,T,F){return T.trace?.recordSegment({type:"error",message:sr}),{result:{reason:sr,segment:A,intent:"stop_and_explain"},states:[...F]}}function Ex(A,T,F,j,q,K,ee){let te=kx(A);if(te&&F.strict)return F.trace?.recordSegment({type:"error",message:te}),{reason:te,segment:A.source,intent:"stop_and_explain"};Pf(A,q,"before-consumer",F.environment.paths);let ce=oe(A.dialect,A.words).map(e),de=A.displayText,_e=hf(ce,q.shellGitContextState);if(A.dialect==="powershell"){let it=jt(Dd(A,K,Gx(F,q.effectiveCwd)),F.policy);if(F.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!it,reason:it?.reason}),it)return Fx(de,it)}if(ce.length===1&&ce[0]?.includes(" ")&&!Wo(A.dialect,A.words)){let it=jt(cr(ce[0],F.scanWork),F.policy),st=it!==null&&!F.strict&&Zc(A,F.rootProgram,F.scanWork);if(it&&!st)return F.trace?.recordSegment({type:"dangerous-text",token:ce[0],matched:!0,reason:it.reason}),{reason:it.reason,segment:de,ruleId:it.id,intent:it.intent};F.trace?.recordSegment({type:"dangerous-text",token:ce[0],matched:!1});let yt=bf(A,te,q,_e,ee,F);if(yt)return yt;return Ml(ce,q.shellGitContextState),null}let Pe=ri(A.words,T,{...F,commandView:A,cwd:j,effectiveCwd:q.effectiveCwd,envAssignments:_e,literalHeredocFiles:q.literalHeredocFiles,functionDefinitions:q.functionDefinitions,hasPipelineInput:K,literalShellInput:ee,analyzeNested:(it,st)=>{let yt=st&&Object.hasOwn(st,"effectiveCwd")?st.effectiveCwd:q.effectiveCwd,At=Gl(it,T+1,{...F,derivedCommandWorkBudget:F.derivedCommandWorkBudget,effectiveCwd:yt,envAssignments:st?.envAssignments??_e,literalHeredocFiles:q.literalHeredocFiles,functionDefinitions:st?.functionDefinitions,worktreeMode:st?.worktreeMode??F.worktreeMode,trace:F.trace?_f(F.trace,F.trace.currentSegmentIndex,!0):void 0});return At?{reason:At.reason,ruleId:At.ruleId,intent:At.intent}:null}});if(Pe)return{...Pe,segment:de};let je=bf(A,te,q,_e,ee,F);if(je)return je;return Ml(ce,q.shellGitContextState),null}function bf(A,T,F,j,q,K){let ee=Ox(A,T,F,j??new Map,K);if(ee)return ee;return Pf(A,F,"after-consumer",K.environment.paths),F.literalHeredocFiles.clear(),wx(A,T,F,K.environment.paths),Nx(A,F,q,K.environment,K.trace),null}var _x=new Set([">>","<>"]);function Pf(A,T,F,j){for(let K of A.redirections){if(!(F==="before-consumer"?Px(K):_x.has(K.operator)))continue;vf(K.target,T,j)}if(F!=="before-consumer"||!Dn(A.words[0],"tee"))return;let q=wf(A.words.slice(1));if(!q)return;for(let K of q.operands)vf(K,T,j)}function Px(A){if(A.operator===">"||A.operator===">|")return!0;return A.operator===">&"&&A.fd===void 0&&A.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(A.target.text)}function vf(A,T,F){let j=A?.provenance==="literal"?Oo(A.text,T.effectiveCwd,F):void 0;if(!j)return;T.literalHeredocFiles.delete(j)}function wx(A,T,F,j){if(T)return;let q=A.redirections.find((K)=>K.operator==="<<"||K.operator==="<<-")?.heredoc;if(!q||!Bs(q))return;for(let K of Ax(A)){let ee=Oo(K.text,F.effectiveCwd,j);if(!ee||!ru(ee))continue;if(!F.literalHeredocFiles.has(ee)&&F.literalHeredocFiles.size>=nu)throw new An;F.literalHeredocFiles.set(ee,q.body)}}function Ax(A){let T=Ix(A.redirections)?.target,F=Rf(T)?[T]:[];if(Dn(A.words[0],"cat"))return Tx(A.words)?F:[];if(!Dn(A.words[0],"tee"))return[];let j=wf(A.words.slice(1));if(!j||j.append||j.hasUnsupportedOptions||!j.operands.every(Rf))return[];return[...j.operands,...F]}function Tx(A){let T=!1;for(let F of A.slice(1)){if(T||F.provenance!=="literal")return!1;if(F.text==="--"){T=!0;continue}if(!/^-u+$/.test(F.text))return!1}return!0}function Ix(A){let T=A.findLast((F)=>(F.fd??([">",">|",">>",">&"].includes(F.operator)?1:0))===1);return T?.operator===">"||T?.operator===">|"?T:void 0}function wf(A){let T=[],F=!0,j=!1,q=!1;for(let K of A){if(K.provenance!=="literal")return;if(F&&Dn(K,"--")){F=!1;continue}if(F&&!K.quoted&&K.raw===K.text&&/^-[^-]/.test(K.text)){j||=K.text.slice(1).includes("a"),q||=[...K.text.slice(1)].some((ee)=>ee!=="a"&&ee!=="i");continue}if(F&&!K.quoted&&K.raw===K.text&&K.text.startsWith("--")){j||=K.text==="--append",q||=K.text!=="--append"&&K.text!=="--ignore-interrupts";continue}T.push(K)}return{operands:T,append:j,hasUnsupportedOptions:q}}function Rf(A){if(!A||A.provenance!=="literal"||A.text.length===0)return!1;if(A.quoted||A.raw!==A.text)return!0;return!A.raw.startsWith("~")&&!/[{}]/.test(A.raw)}function Dn(A,T){return A?.text===T&&A.raw===T&&A.provenance==="literal"&&!A.quoted}function Bs(A){return A.quotedDelimiter||!/[$`\\]/.test(A.body)}function kx(A){let T=A.redirections.filter((ee)=>ee.operator==="<<"||ee.operator==="<<-");if(T.length===0)return;if(T.length!==1)return qr;let F=T[0];if(!F?.heredoc)return qr;if(!Bs(F.heredoc))return gx;if(F.fd!==void 0&&F.fd!==0)return qr;if(A.redirections.some((ee)=>ee!==F&&["<","<<","<<-","<<<","<&","<>"].includes(ee.operator)))return qr;let j=A.redirections.some((ee)=>ee!==F&&xf(ee.target));if(Dn(A.words[0],"cat"))return j?qr:void 0;if(Dn(A.words[0],"tee"))return j||A.words.slice(1).some(xf)?qr:void 0;let q=A.words[0],K=A.words[1];if(Dn(q,"git")&&(Dn(K,"apply")||Dn(K,"commit")))return;if(Dn(q,"gh")&&(Dn(K,"pr")||Dn(K,"issue"))&&Dn(A.words[2],"create"))return;return qr}function xf(A){return A?.parts.some((T)=>T.provenance==="command-substitution"&&T.raw.startsWith(">("))??!1}function Ox(A,T,F,j,q){if(!T)return null;let K=A.redirections.filter((de)=>de.operator==="<<"||de.operator==="<<-"),ee=K.flatMap((de)=>de.heredoc?[de.heredoc.body]:[]);if(Dx(A,K,F,j,q))return null;let te=Mx(A,K,q);if(te!==void 0)return te?{reason:te.reason,segment:A.displayText,ruleId:te.id,intent:te.intent}:null;let ce=Fl(ee.length===K.length?ee.join(`
42
+ `):A.source,q);return ce?{...ce,segment:A.displayText}:null}function Mx(A,T,F){let j=T.length===1?T[0]:void 0;if(!j?.heredoc||!Bs(j.heredoc)||j.fd!==void 0&&j.fd!==0)return;let q=A.words[0];if(q?.provenance!=="literal"||!Tn(q.text))return;if(!A.words.slice(1).every((de)=>de.provenance==="literal"&&de.text.startsWith("-")))return;let ee=j.heredoc.body,te=mn(F.policy,"interpreter.one-liner-paranoid",!!F.paranoidInterpreters);if(F.trace?.recordSegment({type:"interpreter",interpreter:q.text,codeArg:ee,paranoidBlocked:te}),te){let de=jt(It("interpreter.one-liner-paranoid",io),F.policy);if(de)return de}if(!so(ee,F.scanWork))return null;let ce=jt(It("interpreter.dangerous-command",Mr),F.policy);if(!ce)return null;return F.trace?.recordSegment({type:"dangerous-text",token:ee,matched:!0,reason:ce.reason}),ce}function Dx(A,T,F,j,q){let K=T.length===1?T[0]:void 0;if(!K?.heredoc||!Bs(K.heredoc)||K.fd!==void 0&&K.fd!==0)return!1;let ee=Dr(A.words,q.environment,F.effectiveCwd,j),te=ee.words.map(e),ce=Qt(te[0]??"");if((ee.envSplitValues?.length??0)>0||!fn.has(ce)&&!fn.has(Vt(ce)))return!1;return Wn(te)}function Nx(A,T,F,j,q){let K=lf(A,T.effectiveCwd,j,F);if(K===null)q?.recordSegment({type:"cwd-change",segment:A.words.map(e).join(" "),effectiveCwdNowUnknown:!0});if(K!==void 0)T.effectiveCwd=K}function oi(A){return{effectiveCwd:A.effectiveCwd,shellGitContextState:gf(A.shellGitContextState),literalHeredocFiles:new Map(A.literalHeredocFiles),functionDefinitions:new Map(A.functionDefinitions)}}function Ws(A){let T=[];for(let F of A){if(!T.some((j)=>Lx(j,F)))T.push(F);if(T.length>hx)throw new An}return T}function Lx(A,T){return A.effectiveCwd===T.effectiveCwd&&ii(A.literalHeredocFiles,T.literalHeredocFiles)&&ii(A.functionDefinitions,T.functionDefinitions)&&ii(A.shellGitContextState.effectiveEnvAssignments,T.shellGitContextState.effectiveEnvAssignments)&&ii(A.shellGitContextState.shellAssignments,T.shellGitContextState.shellAssignments)}function ii(A,T){if(A===T)return!0;if(!A||!T||A.size!==T.size)return!1;return[...A].every(([F,j])=>T.get(F)===j&&T.has(F))}function Wx(A,T){let F=ss(A);return F===void 0?void 0:T.get(F)}function Fx(A,T){if(!T)return null;return{reason:T.reason,segment:A,ruleId:T.id,intent:T.intent}}function Gx(A,T=A.effectiveCwd){let F=T===null;return{environment:A.environment,cwd:F?void 0:T??A.cwd,originalCwd:F?void 0:A.cwd,strict:A.strict,paranoid:A.paranoidRm,allowTmpdirVar:A.allowTmpdirVar,protectedGitMetadata:A.protectedGitMetadata,policy:A.policy}}function Fl(A,T){let F=jt(cr(A,T.scanWork),T.policy),j=T.trace?.currentSegmentIndex??T.trace?.allocateSegment(),q={type:"dangerous-text",token:A,matched:!!F,reason:F?.reason};if(T.trace?.recordSegment(q,j),!F&&/^(?:cd|pushd)\s/.test(A))T.trace?.recordSegment({type:"cwd-change",segment:A,effectiveCwdNowUnknown:!0},j);return F?{reason:F.reason,segment:A,ruleId:F.id,intent:F.intent}:null}function Ef(A,T){let F={type:"strict-unparseable",rawCommand:A,reason:hr};if(T.trace?.currentSegmentIndex===void 0)T.trace?.recordGlobal(F);else T.trace.recordSegment(F)}var si=["fail_closed","paranoid_rm","paranoid_interpreters"],Us={standard:{fail_closed:!1,paranoid_rm:!1,paranoid_interpreters:!1},strict:{fail_closed:!0,paranoid_rm:!1,paranoid_interpreters:!1},paranoid:{fail_closed:!0,paranoid_rm:!0,paranoid_interpreters:!0}};var r={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"}},$s=["standard","strict","paranoid"];function zx(A,T){if(!T)return A;return $s.indexOf(T)>$s.indexOf(A)?T:A}function Bx(){let A=Le(r.level);if(A===void 0||A==="")return;if($s.includes(A))return A;console.error(`CC Safety Net: ignored invalid ${r.level.name}=${JSON.stringify(A.slice(0,40))}. Use ${$s.join(", ")}.`);return}function Be(A){if(A===void 0||A==="all")return"all";if(A==="blocked")return"blocked";return"invalid"}function se(){return Be(Le(r.auditScope))==="all"}function zl(A){if(A.failClosed&&A.paranoidRm&&A.paranoidInterpreters)return"paranoid";if(A.failClosed&&!A.paranoidRm&&!A.paranoidInterpreters)return"strict";if(!A.failClosed&&!A.paranoidRm&&!A.paranoidInterpreters)return"standard";return"custom"}function E(A={}){let T=A.safety?.level??"standard",F=Bx(),j=zx(T,F),q=Us[j],K={failClosed:q.fail_closed,paranoidRm:q.paranoid_rm,paranoidInterpreters:q.paranoid_interpreters},ee={failClosed:j===T?"preset":"environment",paranoidRm:j===T?"preset":"environment",paranoidInterpreters:j===T?"preset":"environment"},te={failClosed:[`policy safety.level=${T}`],paranoidRm:[`policy safety.level=${T}`],paranoidInterpreters:[`policy safety.level=${T}`]};if(j!==T)te.failClosed.push(`env ${r.level.name}=${F}`),te.paranoidRm.push(`env ${r.level.name}=${F}`),te.paranoidInterpreters.push(`env ${r.level.name}=${F}`);if(A.safety?.overrides?.failClosed!==void 0)K.failClosed=A.safety.overrides.failClosed,ee.failClosed="capability_override",te.failClosed.push("policy safety.overrides.fail_closed");if(A.safety?.overrides?.paranoidRm!==void 0)K.paranoidRm=A.safety.overrides.paranoidRm,ee.paranoidRm="capability_override",te.paranoidRm.push("policy safety.overrides.paranoid_rm");if(A.safety?.overrides?.paranoidInterpreters!==void 0)K.paranoidInterpreters=A.safety.overrides.paranoidInterpreters,ee.paranoidInterpreters="capability_override",te.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(P(r.strict))K.failClosed=!0,ee.failClosed="environment",te.failClosed.push(`env ${r.strict.name}`);if(P(r.paranoid))K.paranoidRm=!0,K.paranoidInterpreters=!0,ee.paranoidRm="environment",ee.paranoidInterpreters="environment",te.paranoidRm.push(`env ${r.paranoid.name}`),te.paranoidInterpreters.push(`env ${r.paranoid.name}`);if(P(r.paranoidRm))K.paranoidRm=!0,ee.paranoidRm="environment",te.paranoidRm.push(`env ${r.paranoidRm.name}`);if(P(r.paranoidInterpreters))K.paranoidInterpreters=!0,ee.paranoidInterpreters="environment",te.paranoidInterpreters.push(`env ${r.paranoidInterpreters.name}`);let ce=!!A.worktreeMode||P(r.worktree);return{strict:K.failClosed,paranoidRm:K.paranoidRm,paranoidInterpreters:K.paranoidInterpreters,worktreeMode:ce,effectiveLevel:zl(K),capabilities:{fail_closed:{enabled:K.failClosed,source:ee.failClosed,sources:te.failClosed},paranoid_rm:{enabled:K.paranoidRm,source:ee.paranoidRm,sources:te.paranoidRm},paranoid_interpreters:{enabled:K.paranoidInterpreters,source:ee.paranoidInterpreters,sources:te.paranoidInterpreters}}}}function P(A){let T=typeof A==="string"?ai(A):Le(A);return T==="1"||T?.toLowerCase()==="true"}function ai(A){return Object.hasOwn(process.env,A)?process.env[A]:void 0}function Le(A){let T=ai(A.name);if(T!==void 0)return T;if(A.legacyName)return ai(A.legacyName);return}function ut(A){return ai(A.name)!==void 0||!!A.legacyName&&ai(A.legacyName)!==void 0}function Ve(A){let T=A.effectiveCapabilities,F=A.strict??T.fail_closed.enabled,j=A.paranoidRm??T.paranoid_rm.enabled,q=A.paranoidInterpreters??T.paranoid_interpreters.enabled,K={fail_closed:Bl(T.fail_closed,A.strict,"strict"),paranoid_rm:Bl(T.paranoid_rm,A.paranoidRm,"paranoidRm"),paranoid_interpreters:Bl(T.paranoid_interpreters,A.paranoidInterpreters,"paranoidInterpreters")};return{policy:Kc(A.policySnapshot.policy,K),effectiveCapabilities:K,effectiveLevel:zl({failClosed:F,paranoidRm:j,paranoidInterpreters:q}),strict:F,paranoidRm:j,paranoidInterpreters:q,worktreeMode:A.worktreeMode??!1}}function Bl(A,T,F){if(T===void 0||T===A.enabled)return A;return{enabled:T,source:"capability_override",sources:[...A.sources,`analysis options.${F}`]}}function St(A,T){return De(A,T)}function De(A,T,F,j){let q=Gl(A,0,{...T,...Ve(T),factStore:j},F);if(!q)return null;return{kind:"deny",reason:q.reason,intent:q.intent??"manual_only",...q.ruleId?{ruleId:q.ruleId}:{},evidence:[{kind:"command",command:A,segment:q.segment}]}}var Ux=new Set(["src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js"]),$l=new Set(["cc-safety-net","ccsn"]),$x=new Set(["bunx","npx","pnpx"]),jx=new Set(["pnpm","yarn"]),Hx=new Set(["npm","pnpm","yarn"]),Vx=new Set(["bun","node"]);function Hs(A,T,F={}){if($l.has(A))return 0;if($x.has(A)){if(F.broad)return Ul(T);let q=T[0]==="-y"||T[0]==="--yes"?1:0;return js(T[q])?q+1:null}let j=F.broad?T.findIndex((q)=>!q.startsWith("-")):0;if(j!==-1&&Hx.has(A)&&F.broad&&T[j]==="exec"){let q=Ul(T.slice(j+1));return q===null?null:j+1+q}if(jx.has(A)){if(A==="yarn"&&!F.broad)return null;if(!F.broad)return T[0]==="dlx"&&js(T[1])?2:null;if(j===-1||T[j]!=="dlx")return null;let q=Ul(T.slice(j+1));return q===null?null:j+1+q}if(Vx.has(A)){let q=F.broad&&j!==-1?j:0;if(Af(T[q]))return q+1;if(A==="bun"&&T[q]==="run"&&Af(T[q+1]))return q+2}return null}function Ul(A){let T=A.findIndex((j)=>js(j));if(T===-1)return null;let F=T;while(F<A.length){let j=A[F]??"";if(!j.startsWith("-")&&!js(j))break;F++}return F}function js(A){if(!A)return!1;let T=A.indexOf("@");if(T===-1)return $l.has(A);if(T===0)return!1;let F=A.slice(T+1);if(F===""||F.includes("/")||F.includes(":"))return!1;return $l.has(A.slice(0,T))}function Af(A){let T=A?.replaceAll("\\","/");return[...Ux].some((F)=>T===F||T?.endsWith(`/${F}`))}var qe="Only the user may apply a policy proposal, because it rewrites the configuration CC Safety Net enforces. Ask them to run `cc-safety-net policy apply <file>` themselves in a terminal; you can run `cc-safety-net policy check <file>` to show them what it would change.";function Ke(A){let T=Sn(A,"input-candidate");if(!T)return null;let F=ur(L()),j=mo(T.shell,A.invocation.context.executionCwd,F,{findSegmentTarget:(q)=>qx(q,F.environment),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null,normalizeCwd:hn});return j?{target:j}:null}function qx(A,T){let F=yr([...A],T),j=F.slice(1),q=Hs(Vt(F[0]??"").toLowerCase(),j,{broad:!0});if(q===null)return null;let K=j.slice(q).filter((ee)=>ee!=="-g"&&ee!=="--global");return K[0]==="policy"&&K[1]==="apply"?F.join(" "):null}import{dirname as Qs}from"node:path";import{chmodSync as BE,existsSync as lc,mkdirSync as UE,readFileSync as cc}from"node:fs";import{dirname as fp,join as $E}from"node:path";import{createRequire as tE}from"node:module";var Tf=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var Ge=30,jl=1,Hl=365;function He(A){if(typeof A!=="number"||!Number.isInteger(A))return 30;if(A<1)return 1;return A>365?365:A}var ae=64,Oe="Rule config exceeds CC Safety Net's safe source limit.";var Ye=Object.freeze({maxSources:64,concurrency:4,maxRequests:131,maxResponseBytes:67108864});function Je(A={}){return{requests:0,responseBytes:0,maxRequests:A.maxRequests??Ye.maxRequests,maxResponseBytes:A.maxResponseBytes??Ye.maxResponseBytes}}function Z(A){return{controller:new AbortController,budget:Je(),resolveUrl:A}}function xt(A){return A instanceof Error&&A.message==="Rule synchronization exceeds CC Safety Net's safe resource limits."}function Lt(A){if(A.requests>=A.maxRequests)throw Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");A.requests++}function kt(A,T){if(T>A.maxResponseBytes-A.responseBytes)throw A.responseBytes+=T,Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");A.responseBytes+=T}var u=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,we="rulebook.json",pe=".cc-safety-net/rules";var If=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,Kx=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,kf=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,Yx=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Zx="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),at=new RegExp(`^${Yx}/(${u.source.slice(1,-1)})/${Zx}$`);function Of(A){return`.cc-safety-net/rules/${A}/rulebook.json`}function Mf(A){if(b(A))try{return G(A),null}catch(T){return T instanceof Error?T.message:String(T)}return u.test(A)?null:`Local rulebook sources must be bare names matching ${u}: ${A}`}function G(A){if(A.startsWith("github:"))throw Error(`Invalid rulebook source: ${A}`);let T=A.match(If);if(!T?.[1]||!T[2]||!T[3])throw Error(`Invalid GitHub rulebook source: ${A}`);let F=T[3].lastIndexOf("/");if(F<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${A}`);let j=T[3].slice(0,F),q=T[3].slice(F+1);if(!j||!kf.test(j))throw Error(`GitHub rulebook refs must use valid path segments: ${A}`);if(!q||!u.test(q))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${A}`);return{owner:T[1],repo:T[2],ref:j,path:Of(q),name:q}}function ne(A){return Kx.test(A)}function fe(A){return kf.test(A)}function b(A){return If.test(A)}function lt(A){if(!u.test(A))throw Error(`Local rulebook sources must be bare names matching ${u}: ${A}`)}var Vl=[{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"}],Vs={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Xx=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Jx=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],ql=[{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"]},...Jx.flatMap((A)=>Xx.map((T)=>({id:["secret.home",A.idSlug,T.slice(1)].join("."),category:"Home path",label:[A.label,T].join(""),description:["Blocks home ",A.label,T," credential backup files."].join(""),suffixParts:[...A.directoryParts,[A.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 qs=[{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"]},{id:"secret.cli.grok-build",category:"Coding CLI credential",label:"Grok Build credentials",paths:["~/.grok/auth.json","~/.grok/mcp_credentials.json"]},{id:"secret.cli.grok-build.config",category:"Coding CLI config",label:"Grok Build config",paths:["~/.grok/config.toml","~/.grok/managed_config.toml","~/.grok/requirements.toml","<project>/.grok/config.toml","/etc/grok/managed_config.toml","/etc/grok/requirements.toml"]}],Df=[{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"}],Qx=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Kl=Df.map((A)=>({id:`secret.variant.${A.slug}.separator`,category:"Variant",label:`${A.label}-* / ${A.label}_*`,description:`Blocks ${A.label} variants with dash or underscore suffixes.`,prefix:A.prefix})),Yl=Df.flatMap((A)=>Qx.map((T)=>({id:`secret.variant.${A.slug}.${T.slice(1)}`,category:"Variant",label:`${A.label}${T}`,description:`Blocks ${A.label}${T} private credential variants.`,prefix:A.prefix,suffix:T}))),li={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)$/},Zl=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((A)=>({id:`secret.ext.${A}`,category:"Extension",label:`.${A}`,description:`Blocks files with the .${A} extension.`,extension:A})),Xl=[{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?$/}],Ze=[...Vl,Vs,...ql,...Kl,...Yl,li,...Zl,...Xl,...qs].map((A)=>({id:A.id,category:A.category,label:A.label,...A.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in A?{paths:A.paths}:{description:A.description}})),Ks=new Set(qs.flatMap((A)=>A.category==="Coding CLI config"?[A.id]:[])),eE=Ze.map((A)=>A.id),ci=new Set(eE);var nE=tE(import.meta.url),Nf,rE=Array(ae+1).fill("over-limit"),Lf=/^[^/]+\/[^/]+$/,Ys=`must be an integer between ${jl} and ${Hl}`,oE=["version","rules","overrides","transparent_wrappers"],iE=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Wf(A){if(!Kn(A)||!Array.isArray(A.rules)||A.rules.length<=ae)return A;return{$schema:A.$schema,version:A.version,rules:rE,overrides:A.overrides,transparent_wrappers:A.transparent_wrappers}}function sE(){let A=nE("../vendor/zod.cjs"),T=(Wt)=>{let Ut=A.superRefine(Wt);return Ut._zod.def.when=()=>!0,Ut},F=A.enum(Tf),j=A.union([A.literal("off"),A.looseObject({reason:A.string({error:"required non-empty string"}).min(1,"required non-empty string").max(oo,`must be at most ${oo} characters`).describe("Replacement block reason"),intent:F.optional()})],{error:'must be "off" or an object'}).describe("Disable a rule or replace its block reason and intent."),q=A.string({error:"must be a rulebook source string"}).min(1,"must be a non-empty rulebook source string"),K=A.string({error:"must be a command string"}).regex(z,"must match command pattern").describe("Command name such as 'git', 'docker', or 'rtk'."),ee=A.looseObject({$schema:A.unknown().optional().describe("JSON Schema reference for IDE support"),version:A.literal(1).describe("Schema version (must be 1)"),rules:A.array(q,{error:"must be an array of rulebook source strings"}).max(ae,Oe).default([]).describe("Rulebook source strings such as project-rules or owner/repo#main/team-rules"),overrides:A.record(A.string().meta({pattern:Lf.source}),j).default({}).describe("Rule overrides by id"),transparent_wrappers:A.array(K,{error:"must be an array of command strings"}).default([]).describe("Commands that transparently execute a visible protected child command")}),te=(Wt,Ut)=>{if(!Kn(Wt))return;if(Array.isArray(Wt.rules)&&Wt.rules.length<=ae){let Ot=new Set;Wt.rules.forEach((Nt,$t)=>{if(typeof Nt!=="string"||Nt==="")return;if(Nt.trim()===""){Ut.addIssue({code:"custom",message:"must be a non-empty rulebook source string",path:["rules",$t]});return}let Kt=Mf(Nt);if(Kt){Ut.addIssue({code:"custom",message:Kt,path:["rules",$t]});return}if(Ot.has(Nt)){Ut.addIssue({code:"custom",message:`duplicate rulebook source "${Nt}"`,path:["rules",$t]});return}Ot.add(Nt)})}if(Kn(Wt.overrides))for(let Ot of Object.keys(Wt.overrides)){if(Lf.test(Ot))continue;Ut.addIssue({code:"custom",message:"must use <rulebook-name>/<rule-name>",path:["overrides",Ot]})}if(!Array.isArray(Wt.transparent_wrappers))return;let Jt=new Set;Wt.transparent_wrappers.forEach((Ot,Nt)=>{if(typeof Ot!=="string"||!z.test(Ot))return;if(Jt.has(Ot)){Ut.addIssue({code:"custom",message:`duplicate command "${Ot}"`,path:["transparent_wrappers",Nt]});return}if(Ie(Ot)){Ut.addIssue({code:"custom",message:`reserved command "${Ot}" cannot be a wrapper`,path:["transparent_wrappers",Nt]});return}Jt.add(Ot)})},ce=A.preprocess(Wf,ee.check(A.superRefine(te))),de=A.preprocess(Wf,ee.check(T(te))),_e=A.strictObject({fail_closed:A.boolean().optional(),paranoid_rm:A.boolean().optional(),paranoid_interpreters:A.boolean().optional()}),Pe=(Wt,Ut)=>A.intersection(A.record(A.string().refine((Jt)=>Wt.has(Jt),{error:(Jt)=>`unknown ${Ut} rule id "${String(Jt.input)}"`}),A.unknown()),A.record(A.string(),A.enum(["on","off"]))),je=(Wt)=>A.array(A.string({error:"must be a non-empty path string"}),{error:"must be an array of paths"}).check(T((Ut,Jt)=>{if(!Array.isArray(Ut))return;let Ot=kr();Ut.forEach((Nt,$t)=>{if(typeof Nt!=="string")return;let Kt=Wt(Nt,Ot);if(Kt)Jt.addIssue({code:"custom",message:Kt,path:[$t]})})})),it=A.strictObject({version:A.literal(1),safety:A.strictObject({level:A.enum(["standard","strict","paranoid"]).optional(),overrides:_e.optional()}).optional(),workflow:A.strictObject({worktree_mode:A.boolean().optional()}).optional(),destructive_command_protection:A.strictObject({enabled:A.boolean().optional(),overrides:Pe(ko,"destructive command").optional(),allow_paths:je(gs).optional()}).optional(),secret_protection:A.strictObject({enabled:A.boolean().optional(),overrides:Pe(ci,"secret protection").optional(),deny_paths:je(hs).optional(),allow_paths:je(ys).optional()}).optional(),audit:A.strictObject({retention_days:A.number({error:Ys}).int(Ys).min(jl,Ys).max(Hl,Ys).optional().describe("Days of audit log history to keep before the sweep deletes it")}).optional()}),st=(Wt,Ut)=>{if(!Array.isArray(Wt))return;let Jt=new Set;Wt.forEach((Ot,Nt)=>{let $t=Kn(Ot)?Ot.name:void 0;if(typeof $t!=="string")return;if(Jt.has($t.toLowerCase())){Ut.addIssue({code:"custom",message:`duplicate rule name "${$t}"`,path:[Nt,"name"]});return}Jt.add($t.toLowerCase())})},yt=(Wt)=>{let Ut=(Nt,$t)=>Wt==="legacy"?Nt:$t,Jt=Ut("must match pattern (letters, numbers, hyphens, underscores)","must match command pattern"),Ot=`required non-empty string up to ${oo} characters`;return A.looseObject({name:A.string({error:"required string"}).regex(u,Ut("must match pattern (letters, numbers, hyphens, underscores; max 64 chars)","must match rule name pattern")),command:A.string({error:Ut("required string","required string matching command pattern")}).regex(z,Ut(Jt,"required string matching command pattern")),subcommand:A.string({error:Ut("must be a string if provided","must match command pattern")}).regex(z,Jt).optional(),block_args:A.array(A.string({error:Ut("must be a string","must be a non-empty string")}).refine((Nt)=>Nt!=="",{error:Ut("must not be empty","must be a non-empty string")}),{error:Ut("required array","required non-empty array")}).refine((Nt)=>Nt.length>0,{error:Ut("must have at least one element","required non-empty array")}),reason:A.string({error:Ut("required string",Ot)}).refine((Nt)=>Nt!=="",{error:Ut("must not be empty",Ot)}).refine((Nt)=>Nt.length<=oo,{error:Ut(`must be at most ${oo} characters`,Ot)}),intent:F.optional()},{error:"must be an object"})},At=(Wt)=>A.array(yt(Wt),{error:Wt==="legacy"?"must be an array":"required array"}).check(T(st)),Tt=A.looseObject({version:A.literal(1),rules:At("legacy").optional()}),Dt="required string matching rule name pattern",zt=A.looseObject({command:A.string({error:"required non-empty string"}).refine((Wt)=>Wt.trim()!=="",{error:"required non-empty string"}),expect:A.enum(["blocked","allowed"]),rule:A.string({error:"must be a string if provided"}).optional()},{error:"must be an object"}).check(T((Wt,Ut)=>{if(!Kn(Wt))return;if(Wt.expect!=="blocked"||typeof Wt.rule==="string")return;Ut.addIssue({code:"custom",message:"required string for blocked fixtures",path:["rule"]})})),Ft=(Wt,Ut)=>{if(!Kn(Wt))return;let Jt=new Set(Ne(Wt));if(Array.isArray(Wt.tests)){let Nt=new Set(Wt.tests.flatMap(($t)=>Kn($t)&&$t.expect==="blocked"&&typeof $t.rule==="string"?[$t.rule]:[]));for(let $t of Nt){if(Jt.has($t))continue;Ut.addIssue({code:"custom",message:`blocked fixture references unknown rule "${$t}"`,path:["tests"]})}}if(!Array.isArray(Wt.allowed_commands)||!Array.isArray(Wt.rules))return;let Ot=new Set(Wt.allowed_commands.filter((Nt)=>typeof Nt==="string"));Wt.rules.forEach((Nt,$t)=>{let Kt=Kn(Nt)?Nt.command:void 0;if(typeof Kt!=="string"||Ot.has(Kt))return;Ut.addIssue({code:"custom",message:`"${Kt}" must be listed in allowed_commands`,path:["rules",$t,"command"]})})},Bt=(Wt)=>A.looseObject({name:A.string({error:"required string matching rule name pattern"}).regex(u,"required string matching rule name pattern"),version:A.string({error:"required non-empty string"}).refine((Ut)=>Ut!=="",{error:"required non-empty string"}),allowed_commands:A.array(A.string({error:"must match command pattern"}).regex(z,"must match command pattern"),{error:"required array"}).check(T((Ut,Jt)=>{if(!Array.isArray(Ut))return;let Ot=new Set;Ut.forEach((Nt,$t)=>{if(typeof Nt!=="string"||!z.test(Nt))return;if(Ot.has(Nt)){Jt.addIssue({code:"custom",message:`duplicate command "${Nt}"`,path:[$t]});return}Ot.add(Nt)})})),rules:Wt,tests:A.array(zt,{error:"must be an array if provided"}).optional()}).check(T(Ft)),Ht=Bt(At("rulebook")),Gt=A.string({error:"must be a non-empty string"}).refine((Wt)=>Wt!=="",{error:"must be a non-empty string"}),Zt="must be a non-empty array of unique non-empty strings",an="required non-empty array of non-empty strings",ln=A.array(Gt,{error:"must be a non-empty array of unique non-empty strings"}).refine((Wt)=>Wt.length>0,{error:"must be a non-empty array of unique non-empty strings"}).refine((Wt)=>new Set(Wt).size===Wt.length,{error:"must not contain duplicate values"}),tn=A.looseObject({command_path:A.array(Gt,{error:"required non-empty array of non-empty strings"}).refine((Wt)=>Wt.length>0,{error:"required non-empty array of non-empty strings"}),any_args:ln.optional(),exclude_args:ln.optional()},{error:"required object"}),Xt=Bt(A.array(yt("rulebook").omit({subcommand:!0,block_args:!0}).extend({match:tn,subcommand:A.never({error:"not supported in rulebook_version 2"}).optional(),block_args:A.never({error:"not supported in rulebook_version 2"}).optional()}),{error:"required array"}).check(T(st)));return{RulesConfigSchema:ce,RulesConfigDiagnosticSchema:de,RuleOverrideSchema:j,UserPolicySchema:it,LegacyConfigSchema:Tt,RulebookSchema:Ht,RulebookV2Schema:Xt}}function vo(){return Nf??=sE(),Nf}function Ff(){return vo().RulesConfigSchema}function aE(){return vo().UserPolicySchema}function Rt(){return vo().LegacyConfigSchema}function Gf(){return vo().RulebookSchema}function zf(){return vo().RulebookV2Schema}function Ne(A){let T=Kn(A)?A.rules:void 0;return(Array.isArray(T)?T:[]).flatMap((F)=>{let j=Kn(F)?F.name:void 0;return typeof j==="string"?[j]:[]})}function Bf(A){let T=vo().RulesConfigDiagnosticSchema.safeParse(A);if(T.success)return{errors:[],sources:new Set(T.data.rules)};return{errors:ke($f(T.error.issues,oE)),sources:dE(A,T.error.issues)}}function _(A){let T=aE().safeParse(A);if(T.success)return[];return ke($f(T.error.issues,iE)," ")}function ke(A,T=": ",F=" "){return[...new Set(A.flatMap((j)=>Uf(j,T,F,[])))]}function Uf(A,T,F,j){let q=[...j,...A.path],K=uE(q);if(A.code==="unrecognized_keys")return A.keys.map((ee)=>`${K?`${K}.`:""}unknown field "${ee}"`);if(A.code==="invalid_key")return A.issues.map((ee)=>ee.message);if(A.code==="invalid_union"){let ee=A.errors.flat().filter((te)=>te.path.length>0);if(ee.length>0)return ee.flatMap((te)=>Uf(te,T,F,q))}if(q.length===0)return[A.code==="invalid_type"?"Config must be an object":A.message];if(q.length===1&&(A.code==="too_big"||A.code==="too_small")&&A.origin==="array")return[A.message];return[`${K}${q.length===1?F:T}${lE(A)}`]}function lE(A){if(A.code==="invalid_value")return`must be ${cE(A.values)}`;if(A.code!=="invalid_type"||!A.message.startsWith("Invalid input:"))return A.message;if(A.expected==="object"||A.expected==="record")return"must be an object if provided";return A.expected==="boolean"?"must be a boolean":A.message}function cE(A){if(A.length>3)return`one of ${A.join(", ")}`;let T=A.map((F)=>typeof F==="string"?`"${F}"`:String(F));if(T.length<2)return`${T[0]}`;return`${T.slice(0,-1).join(", ")}${T.length>2?",":""} or ${T.at(-1)}`}function uE(A){return A.map((T,F)=>{if(typeof T==="number")return`[${T}]`;return F===0?String(T):`.${String(T)}`}).join("")}function $f(A,T){let F=A.map((K)=>K.path[1]),j=[...new Set(F.filter((K)=>typeof K==="string"))],q=(K,ee)=>[K.path.length===0?-1:T.indexOf(String(K.path[0])),typeof ee==="number"?ee:j.indexOf(String(ee)),K.code==="custom"?0:1];return A.map((K,ee)=>({issue:K,rank:q(K,F[ee])})).sort((K,ee)=>K.rank[0]-ee.rank[0]||K.rank[1]-ee.rank[1]||K.rank[2]-ee.rank[2]).map((K)=>K.issue)}function dE(A,T){let F=Kn(A)?A.rules:void 0;if(!Array.isArray(F))return new Set;if(T.some((q)=>q.path.length===1&&q.path[0]==="rules"))return new Set;let j=new Set(T.filter((q)=>q.path[0]==="rules"&&typeof q.path[1]==="number").map((q)=>q.path[1]));return new Set(F.filter((q,K)=>typeof q==="string"&&!j.has(K)))}function Kn(A){return!!A&&typeof A==="object"&&!Array.isArray(A)}var jf={standard:0,strict:1,paranoid:2};function X(A,T){return{policy:{version:1,safety:{level:T.safety?.level??A.safety.level,overrides:{...A.safety.overrides,...T.safety?.overrides}},workflow:{worktree_mode:T.workflow?.worktree_mode??A.workflow.worktree_mode},destructive_command_protection:{enabled:T.destructive_command_protection?.enabled??A.destructive_command_protection.enabled,overrides:{...A.destructive_command_protection.overrides,...T.destructive_command_protection?.overrides},allow_paths:Jl(A.destructive_command_protection.allow_paths,T.destructive_command_protection?.allow_paths)},secret_protection:{enabled:T.secret_protection?.enabled??A.secret_protection.enabled,overrides:{...A.secret_protection.overrides,...T.secret_protection?.overrides},deny_paths:Jl(A.secret_protection.deny_paths,T.secret_protection?.deny_paths),allow_paths:Jl(A.secret_protection.allow_paths,T.secret_protection?.allow_paths)},audit:A.audit},weakenings:mE(A,T)}}function Jl(A,T){return[...new Set([...A,...T??[]])]}function mE(A,T){let F=T.safety?.level,j=Us[A.safety.level];return[...F&&jf[F]<jf[A.safety.level]?[`project policy lowers level: ${A.safety.level} -> ${F}`]:[],...si.flatMap((q)=>T.safety?.overrides?.[q]===!1&&(A.safety.overrides[q]??j[q])?[`project policy disables ${q}`]:[]),...T.workflow?.worktree_mode===!0&&!A.workflow.worktree_mode?["project policy enables worktree mode relaxations"]:[],...T.destructive_command_protection?.enabled===!1&&A.destructive_command_protection.enabled?["project policy disables destructive command protection"]:[],...T.secret_protection?.enabled===!1&&A.secret_protection.enabled?["project policy disables secret protection"]:[],...Hf(T.destructive_command_protection?.overrides,(q)=>A.destructive_command_protection.enabled&&A.destructive_command_protection.overrides[q]!=="off"),...Hf(T.secret_protection?.overrides,(q)=>A.secret_protection.enabled&&(A.secret_protection.overrides[q]==="on"?!0:A.secret_protection.overrides[q]!=="off"&&!Ks.has(q))),...A.destructive_command_protection.enabled?Vf(A.destructive_command_protection.allow_paths,T.destructive_command_protection?.allow_paths).map((q)=>`project policy adds destructive allow path: ${q}`):[],...A.secret_protection.enabled?Vf(A.secret_protection.allow_paths,T.secret_protection?.allow_paths).map((q)=>`project policy adds secret allow path: ${q}`):[]]}function Hf(A,T){return Object.entries(A??{}).flatMap(([F,j])=>j==="off"&&T(F)?[`project policy disables rule ${F}`]:[])}function Vf(A,T){return(T??[]).filter((F)=>!A.includes(F))}import{randomBytes as fE}from"node:crypto";import{closeSync as tc,constants as ui,fstatSync as Ql,fsyncSync as pE,lstatSync as _r,mkdirSync as qf,openSync as Kf,readdirSync as nc,readFileSync as gE,realpathSync as Kr,renameSync as hE,rmdirSync as Yf,statSync as ec,unlinkSync as rc,writeFileSync as yE}from"node:fs";import{isAbsolute as Zf,join as Ro,normalize as CE,parse as Xf,relative as oc,resolve as ic,sep as Zs}from"node:path";var SE=Symbol("PolicyFilesystemScope"),bE=Symbol("PolicyFilesystemTarget"),Jf=ui.O_NOFOLLOW??0;class t extends Error{constructor(A){super(`Unable to access ${A} filesystem safely.`);this.name="PolicyFilesystemError"}}function k(A,T){return{[SE]:!0,root:ic(A),label:T}}function mi(A,T){let F=CE(T);if(T===""||Zf(T)||F===".."||F.startsWith(`..${Zs}`))throw new t(A.label);return{[bE]:!0,scope:A,relativePath:F,path:Ro(A.root,F)}}function o(A,T){let F=oc(A.root,ic(T));return mi(A,F)}function ue(A,T="rules policy"){let F=ic(A),j=Xf(F).dir;return mi(k(j,T),oc(j,F))}function n(A){try{if(!yn(A,!1).exists)return null;let F=Kf(A.path,ui.O_RDONLY|Jf);try{let j=Ql(F);if(!j.isFile())throw new t(A.scope.label);let q=gE(F,"utf-8"),K=_r(A.path);if(!K.isFile()||K.isSymbolicLink()||j.dev!==K.dev||j.ino!==K.ino)throw new t(A.scope.label);return yn(A,!1),q}finally{tc(F)}}catch(T){Pr(A.scope.label,T)}}function v(A,T,F=384,j){let q=`${A.path}.${fE(8).toString("hex")}.tmp`,K=null;try{xE(A),yn(A,!0),K=Kf(q,ui.O_CREAT|ui.O_EXCL|ui.O_WRONLY|Jf,F);let ee=Ql(K);if(!ee.isFile())throw new t(A.scope.label);yE(K,T,"utf-8"),pE(K);let te=Ql(K);if(!te.isFile()||te.dev!==ee.dev||te.ino!==ee.ino)throw new t(A.scope.label);tc(K),K=null,yn(A,!0),PE(A,q,te.dev,te.ino),hE(q,A.path),j?.(A.path),yn(A,!1)}catch(ee){if(K!==null)AE(K);TE(q),Pr(A.scope.label,ee)}}function Qf(A,T){if(A.path===T.path)return!0;try{if(!yn(A,!1).exists||!yn(T,!1).exists)return!1;return Kr(A.path)===Kr(T.path)}catch(F){if(F instanceof t)throw F;throw new t(A.scope.label)}}function vE(A){try{if(!yn(A,!1,"directory").exists)return null;let F=nc(A.path);return yn(A,!1,"directory"),F}catch(T){Pr(A.scope.label,T)}}function Ce(A){let T=vE(A);if(!T)return null;try{let F=T.map((j)=>{let q=mi(A.scope,Ro(A.relativePath,j)),K=_r(q.path);if(K.isSymbolicLink()||!K.isFile()&&!K.isDirectory())throw new t(A.scope.label);return Xs(np(A.scope),Kr(q.path),A.scope.label),{name:j,kind:K.isDirectory()?"directory":"file"}});return yn(A,!1,"directory"),F}catch(F){Pr(A.scope.label,F)}}function Y(A){try{if(!yn(A,!0).exists)return;rc(A.path),yn(A,!0)}catch(T){Pr(A.scope.label,T)}}function vt(A){try{if(!RE(A))return;tp(A),yn(A,!0,"directory")}catch(T){Pr(A.scope.label,T)}}function bt(A){try{if(!yn(A,!0,"directory").exists)return;Yf(A.path),yn(A,!0,"directory")}catch(T){Pr(A.scope.label,T)}}function RE(A){try{if(!yn(A,!0,"directory").exists)return!1;return ep(A),!0}catch(T){Pr(A.scope.label,T)}}function yn(A,T,F="file"){let j=sc(A.scope);if(!j)return{exists:!1};let q=A.relativePath.split(Zs);for(let K of q.keys()){let ee=Ro(A.scope.root,...q.slice(0,K+1)),te=di(ee);if(!te){if(K===q.length-1&&T)return{exists:!1};return{exists:!1}}if(te.isSymbolicLink())throw new t(A.scope.label);if(K<q.length-1&&!te.isDirectory())throw new t(A.scope.label);if(K===q.length-1&&(F==="file"?!te.isFile():!te.isDirectory()))throw new t(A.scope.label);Xs(j,Kr(ee),A.scope.label)}return{exists:!0}}function ep(A){for(let T of nc(A.path)){let F=mi(A.scope,Ro(A.relativePath,T)),j=_r(F.path);if(j.isSymbolicLink()||!j.isDirectory()&&!j.isFile())throw new t(A.scope.label);if(j.isDirectory())ep(F)}yn(A,!1,"directory")}function tp(A){for(let T of nc(A.path)){let F=mi(A.scope,Ro(A.relativePath,T)),j=_r(F.path);if(j.isSymbolicLink())throw new t(A.scope.label);if(j.isDirectory()){tp(F);continue}if(!j.isFile())throw new t(A.scope.label);rc(F.path)}Yf(A.path)}function xE(A){EE(A,A.relativePath.split(Zs).slice(0,-1))}function EE(A,T){_E(A.scope);let F=np(A.scope);for(let j of T.keys()){let q=Ro(A.scope.root,...T.slice(0,j+1));if(!di(q))qf(q,{mode:448});let ee=_r(q);if(!ee.isDirectory()||ee.isSymbolicLink())throw new t(A.scope.label);Xs(F,Kr(q),A.scope.label)}}function _E(A){if(di(A.root)){if(!ec(A.root).isDirectory())throw new t(A.label);return}let T=[],F=A.root;while(!di(F)){T.unshift(F);let j=Xf(F).dir;if(j===F)throw new t(A.label);F=j}if(!ec(F).isDirectory())throw new t(A.label);for(let j of T){qf(j,{mode:448});let q=_r(j);if(!q.isDirectory()||q.isSymbolicLink())throw new t(A.label)}}function sc(A){if(!di(A.root))return null;if(!ec(A.root).isDirectory())throw new t(A.label);return Kr(A.root)}function np(A){let T=sc(A);if(!T)throw new t(A.label);return T}function PE(A,T,F,j){let q=_r(T);if(!q.isFile()||q.isSymbolicLink()||q.dev!==F||q.ino!==j)throw new t(A.scope.label);let K=sc(A.scope);if(!K)throw new t(A.scope.label);Xs(K,Kr(T),A.scope.label)}function Xs(A,T,F){let j=oc(A,T);if(j===".."||j.startsWith(`..${Zs}`)||Zf(j))throw new t(F)}function di(A){try{return _r(A)}catch(T){if(wE(T)&&T.code==="ENOENT")return null;throw T}}function Pr(A,T){if(T instanceof t)throw T;throw new t(A)}function wE(A){return A instanceof Error&&"code"in A}function AE(A){try{tc(A)}catch{}}function TE(A){try{rc(A)}catch{}}var rp={version:1,rules:[],overrides:{},transparent_wrappers:[]};function pt(A){return Bf(A)}function p(A){try{let T=n(op(A));if(T===null)return{config:null,errors:[]};if(!T.trim())return{config:null,errors:["Config file is empty"]};let F=JSON.parse(T),j=pt(F);if(j.errors.length>0)return{config:null,errors:j.errors};let q=Ff().parse(F);return{config:{version:1,rules:q.rules??[],overrides:q.overrides??{},transparent_wrappers:q.transparent_wrappers??[]},errors:[]}}catch(T){if(T instanceof t)return{config:null,errors:[T.message]};let F=T instanceof Error?T.message:String(T);return{config:null,errors:[T instanceof SyntaxError?"Invalid JSON":F]}}}function ft(A){let T=p(A);if(T.errors.length>0)return{ok:!1,result:{ok:!1,errors:T.errors,entries:[]}};return{ok:!0,config:T.config??rp}}function mt(A,T=[]){h(A,{version:1,rules:T,overrides:{},transparent_wrappers:[]})}function gt(A,T="project-rules"){h(A,{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 h(A,T,F,j){v(op(A),`${JSON.stringify(T,null,2)}
43
+ `,F,j)}function op(A){return typeof A==="string"?ue(A):A}import{homedir as IE}from"node:os";import{dirname as fr,isAbsolute as kE,join as Ar,relative as OE,resolve as wr,sep as ME}from"node:path";var ip="rule.json",me="policy.json",DE="rule.lock",NE="config.json",sp=".cc-safety-net",LE="rules",WE="CC_SAFETY_NET_HOME",ap="`cc-safety-net rule update`";function FE(A){return wr(A??process.cwd(),pe)}function I(A){return Ar(FE(A),ip)}function g(A){return Ar(wr(A??process.cwd()),sp,me)}function ge(A){return A?.userConfigDir??(A?.userConfigPath?fr(A.userConfigPath):Ar(GE(),LE))}function GE(){let A=process.env[WE];return A?wr(Pn(A)):Ar(IE(),sp)}function D(A){return Ar(ge(A),ip)}function zE(A){return Ar(fr(A),DE)}function Ae(A={}){return Ar(fr(ge(A)),NE)}function Ct(A={}){return wr(A.cwd??process.cwd(),".safety-net.json")}function H(A){let T=A.userConfigPath??D(A),F=A.projectConfigPath??I(A.cwd),j=lp(T,A),q=cp(F,A);return{userConfigPath:T,projectConfigPath:F,userScope:j,projectScope:q,userConfigTarget:o(j,T),projectConfigTarget:o(q,F)}}function C(A){let T=A.global?A.userConfigPath??D(A):A.projectConfigPath??I(A.cwd),F=A.global?lp(T,A):cp(T,A),j=zE(T);return{configDir:fr(T),configPath:T,lockPath:j,filesystemScope:F,configTarget:o(F,T),lockTarget:o(F,j)}}function lp(A,T){let F=T.userConfigPath?fr(fr(wr(T.userConfigPath))):fr(wr(T.userConfigDir??ge(T)));return k(F,"user policy")}function cp(A,T){let F=wr(T.cwd??process.cwd()),j=wr(A),q=OE(F,j);if(q!==".."&&!q.startsWith(`..${ME}`)&&!kE(q))return k(F,"project policy");return k(fr(fr(j)),"project policy")}function W(A,T){return Ar(A,T,we)}var uc=new Set(["standard","strict","paranoid"]),ve={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:Ge}};function y(A){return $E(fp(ge(A)),me)}function Et(A={}){let T=y(A);if(!lc(T))return{path:T,exists:!1,raw:"",policy:fi(),errors:[]};let F=cc(T,"utf-8");if(!F.trim())return{path:T,exists:!0,raw:F,policy:fi(),errors:["Config file is empty"]};try{let j=JSON.parse(F),q=_(j);return{path:T,exists:!0,raw:F,policy:f(j),errors:q}}catch(j){return{path:T,exists:!0,raw:F,policy:fi(),errors:[`Invalid JSON: ${j instanceof Error?j.message:String(j)}`]}}}function Q(A,T={}){let F=y(T),j=_(A),q=j.length>0?fi():f(A);if(j.length>0)return{path:F,policy:q,errors:j};return UE(fp(F),{recursive:!0,mode:448}),h(F,q,384),BE(F,384),{path:F,policy:q,errors:[]}}function Pt(A){let T=_(A);if(T.length>0)return{errors:T};return{preview:ht(f(A)),errors:[]}}function ht(A){let T=E({safety:Qe(A.safety)}),F=U({destructiveCommandProtectionEnabled:A.destructive_command_protection.enabled,destructiveCommandRuleOverrides:A.destructive_command_protection.overrides},T.capabilities),j=Object.values(F),q=j.filter((K)=>K.source!=="catastrophic");return{selectedPreset:A.safety.level,effectiveLevel:T.effectiveLevel,capabilities:T.capabilities,rules:F,counts:{enabled:q.filter((K)=>K.enabled).length,disabled:q.filter((K)=>!K.enabled).length,effectiveCustomizations:j.filter((K)=>K.changesInherited).length}}}function _t(A={}){let T=y(A);if(!lc(T))return Q(ve,A);let F=cc(T,"utf-8");if(!F.trim())return Q(ve,A);try{return Q(f(JSON.parse(F)),A)}catch{return Q(ve,A)}}function pp(A={}){let T=HE(y(A)),F=g(A.cwd),j=Sp(F),q=le(j.parsed),K=Object.keys(q.policy).length>0?X(T.gui??ve,q.policy):void 0,ee=[...T.errors,...j.errors,...q.diagnostics],te=(T.fallback==="defaults"&&K?"salvaged":T.fallback)??(T.gui?void 0:j.fallback)??(ee.length>0?"salvaged":void 0),ce=q.policy.safety?.level?"project":T.levelPresent?"user":"default";return{...K?ac(K.policy):T.policy,errors:ee,...te?{fallback:te}:{},...j.exists?{policyScopes:{levelScope:ce,weakenings:K?.weakenings??[]}}:{}}}var jE="project policy audit settings are ignored; audit is user scope only";function le(A){if(!pn(A))return{policy:{},diagnostics:[]};let T=pn(A.safety)?A.safety:{},F=pn(A.workflow)?A.workflow:{},j=pn(A.destructive_command_protection)?A.destructive_command_protection:{},q=pn(A.secret_protection)?A.secret_protection:{},K={...uc.has(T.level)?{level:T.level}:{},...pn(T.overrides)?up({overrides:gp(T.overrides,si)}):{}},ee={...typeof j.enabled==="boolean"?{enabled:j.enabled}:{},...j.overrides!==void 0?{overrides:Js(j.overrides,ko)}:{},...j.allow_paths!==void 0?{allow_paths:yp(j.allow_paths)}:{}},te={...typeof q.enabled==="boolean"?{enabled:q.enabled}:{},...q.overrides!==void 0?{overrides:Js(q.overrides,ci)}:{},...q.deny_paths!==void 0?{deny_paths:hp(q.deny_paths)}:{},...q.allow_paths!==void 0?{allow_paths:Cp(q.allow_paths)}:{}};return{policy:up({safety:K,workflow:typeof F.worktree_mode==="boolean"?{worktree_mode:F.worktree_mode}:{},destructive_command_protection:ee,secret_protection:te}),diagnostics:A.audit===void 0?[]:[jE]}}function gp(A,T){return Object.fromEntries(T.flatMap((F)=>typeof A[F]==="boolean"?[[F,A[F]]]:[]))}function up(A){return Object.fromEntries(Object.entries(A).flatMap((T)=>Object.keys(T[1]).length>0?[T]:[]))}function f(A){if(!pn(A))return fi();let T=pn(A.safety)?A.safety:{},F=pn(T.overrides)?T.overrides:{},j=pn(A.workflow)?A.workflow:{},q=pn(A.destructive_command_protection)?A.destructive_command_protection:{},K=pn(A.secret_protection)?A.secret_protection:{};return{version:1,safety:{level:uc.has(T.level)?T.level:"standard",overrides:gp(F,si)},workflow:{worktree_mode:typeof j.worktree_mode==="boolean"?j.worktree_mode:!1},destructive_command_protection:{enabled:typeof q.enabled==="boolean"?q.enabled:!0,overrides:Js(q.overrides,ko),allow_paths:yp(q.allow_paths)},secret_protection:{enabled:typeof K.enabled==="boolean"?K.enabled:!0,overrides:Js(K.overrides,ci),deny_paths:hp(K.deny_paths),allow_paths:Cp(K.allow_paths)},audit:{retention_days:He(pn(A.audit)?A.audit.retention_days:void 0)}}}function Js(A,T){if(!pn(A))return{};return Object.fromEntries(Object.entries(A).flatMap(([F,j])=>T.has(F)&&(j==="on"||j==="off")?[[F,j]]:[]))}function hp(A){if(!Array.isArray(A))return[];let T=kr();return A.filter((F)=>hs(F,T)===null)}function yp(A){if(!Array.isArray(A))return[];let T=kr();return A.filter((F)=>gs(F,T)===null)}function Cp(A){if(!Array.isArray(A))return[];let T=kr();return A.filter((F)=>ys(F,T)===null)}function pn(A){return!!A&&typeof A==="object"&&!Array.isArray(A)}function fi(){return structuredClone(ve)}function Sp(A){if(!lc(A))return{exists:!1,errors:[]};try{let T=cc(A,"utf-8");if(!T.trim())return{exists:!0,errors:[`${A}: Config file is empty`],fallback:"defaults"};let F=JSON.parse(T),j=_(F);if(j.length===0)return{exists:!0,parsed:F,errors:[]};return{exists:!0,parsed:F,errors:j.map((q)=>`${A}: ${q}`),fallback:pn(F)?"salvaged":"defaults"}}catch(T){let F=T instanceof Error?T.message:String(T);return{exists:!0,errors:[`${A}: ${T instanceof SyntaxError?"Invalid JSON":F}`],fallback:"defaults"}}}function HE(A){let T=Sp(A);if(!T.exists){let j=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!pn(j))return{policy:mp(),errors:[]};let q=f(j);return{policy:ac(q),gui:q,errors:[],levelPresent:dp(j)}}if(T.parsed===void 0)return{policy:mp(),errors:T.errors,...T.fallback?{fallback:T.fallback}:{}};let F=f(T.parsed);return{policy:ac(F),gui:F,errors:T.errors,...T.fallback?{fallback:T.fallback}:{},levelPresent:dp(T.parsed)}}function dp(A){let T=pn(A)&&pn(A.safety)?A.safety:{};return uc.has(T.level)}function Xe(A){let T=Object.entries(A),F=new Set(T.flatMap(([j,q])=>q==="on"?[j]:[]));return[...new Set([...[...Ks].filter((j)=>!F.has(j)),...T.flatMap(([j,q])=>q==="off"?[j]:[])])]}function mp(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Xe({}),denyPaths:[],allowPaths:[]}}}function ac(A){return{safety:Qe(A.safety),worktreeMode:A.workflow.worktree_mode,destructiveCommandProtectionEnabled:A.destructive_command_protection.enabled,destructiveCommandRuleOverrides:A.destructive_command_protection.overrides,destructiveCommandAllowPaths:A.destructive_command_protection.allow_paths,secretProtection:{enabled:A.secret_protection.enabled,disabledRules:Xe(A.secret_protection.overrides),denyPaths:A.secret_protection.deny_paths,allowPaths:A.secret_protection.allow_paths}}}function Qe(A){let T={...A.overrides.fail_closed!==void 0?{failClosed:A.overrides.fail_closed}:{},...A.overrides.paranoid_rm!==void 0?{paranoidRm:A.overrides.paranoid_rm}:{},...A.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:A.overrides.paranoid_interpreters}:{}};return{level:A.level,...Object.keys(T).length>0?{overrides:T}:{}}}var et="This path contains the protected policy config and you must not modify or delete it.",VE=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function tt(A){let T=ur(L()),F=JE(A.invocation.context,T);if(A.invocation.route.kind==="patch")return bp(A.paths,!1,A.invocation.context.executionCwd,F,T);let j=Sn(A,"input-candidate");if(A.invocation.route.kind==="command")return j?vp(j.shell,A.invocation.context.executionCwd,F,T):null;if(A.invocation.route.kind==="unknown"&&j){let q=vp(j.shell,A.invocation.context.executionCwd,F,T);if(q)return q}return bp(A.paths,A.invocation.route.kind==="grep"||A.invocation.route.kind==="glob"||us(A.invocation.toolName),A.invocation.context.executionCwd,F,T)}function bp(A,T,F,j,q){if(T)return null;let K=A.find((ee)=>pi(ee,F,j,q));return K?{target:K}:null}function vp(A,T,F,j){let q=mo(A,T,j,{findSegmentTarget:(K,ee)=>qE(K,ee,F,j)?.target??null,isRedirectionTarget:(K,ee)=>pi(K,ee.cwd,F,j),findMalformedTarget:(K)=>XE(K,T,F,j)?.target??null,normalizeCwd:hn});return q?{target:q}:null}function qE(A,T,F,j){if(Uo(A))return null;let q=j.environment,K=Cr([...A],q),ee=Vt(K[0]??"").toLowerCase(),te=K.slice(1);if(ee==="rm"&&KE(te)){let ce=YE(te).find((de)=>Rp(kn(de,T.variables),T.cwd,F,j));if(ce)return{target:ce}}if(ee==="find"){if(_s(K,1)||nl(K,q)){let de=(Es(Yt(K))??Yt(["."])).find((_e)=>{let Pe=kn(_e.text,T.variables);return pi(Pe,T.cwd,F,j)||Rp(Pe,T.cwd,F,j)})?.text;if(de)return{target:de}}}if(ee==="mv"){let ce=ds(te).sources.find((de)=>QE(kn(de,T.variables),T.cwd,F,j));if(ce)return{target:ce}}if(ZE(A,q))return null;for(let ce of[...A,...K])for(let de of xp(ce))if(pi(kn(de,T.variables),T.cwd,F,j))return{target:de};return null}function KE(A){return A.some((T)=>T==="--recursive"||T.startsWith("-")&&!T.startsWith("--")&&/[rR]/.test(T.slice(1)))}function YE(A){let T=A.indexOf("--");if(T!==-1)return[...A.slice(0,T).filter((F)=>!F.startsWith("-")),...A.slice(T+1)];return A.filter((F)=>!F.startsWith("-"))}function ZE(A,T){let F=Cr([...A],T);if(F.length===0)return!1;let j=Vt(F[0]??"").toLowerCase();if(!VE.has(j))return!1;if(j!=="sed")return!0;return!F.slice(1).some((q)=>q.startsWith("-i")||q==="--in-place"||q.startsWith("--in-place="))}function XE(A,T,F,j){for(let q of A.split(/\s+/))for(let K of xp(q))if(pi(K,T,F,j))return{target:K};return null}function xp(A){let T=A.trim().replace(/^['"]|['"]$/g,""),F=T.indexOf("=");return F===-1||F===T.length-1?[T]:[T,T.slice(F+1)]}function JE(A,T){let F=(ee)=>gi(hn(ee,A.executionCwd,T)),j=F(y()),q=[F(g(A.executionCwd)),F(g(A.configCwd))],K=new Set(q.map((ee)=>Qs(ee)));for(let ee=Qs(j);;ee=Qs(ee))if(K.add(ee),Qs(ee)===ee)break;return{files:new Set([j,...q]),directoriesAndAncestors:K}}function pi(A,T,F,j){let q=hd(A,T,j,(K)=>gi(K)===me);return q!==null&&F.files.has(gi(q))}function Rp(A,T,F,j){return F.directoriesAndAncestors.has(gi(hn(A,T,j)))}function QE(A,T,F,j){let q=gi(hn(A,T,j));return F.files.has(q)||F.directoriesAndAncestors.has(q)}function gi(A){return process.platform==="win32"?A.toLowerCase():A}import{homedir as fc}from"node:os";import{isAbsolute as ea,posix as e_,resolve as na,win32 as t_}from"node:path";import{fileURLToPath as n_}from"node:url";var nt="Access to a sensitive path is not allowed.",Np=new Set(["echo","printf"]),r_=new Set(["find"]),o_=new Set(["-exec","-execdir"]),i_=new Set([";","+"]),s_=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),a_=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Lp=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),l_=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),c_=new Set(["node","bun"]),u_=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),d_=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"]),Wp=new Set(["-c","-e","-r","-E","--eval","--exec"]),m_=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"])]]),f_=new Set(["grep","rg"]),Ep="f",_p="file",p_="files",g_=new Set(["e","f"]),h_=new Set(["regexp","file"]),y_=new Set(["e","f","A","B","C","m"]),C_=new Set(["regexp","file","after-context","before-context","context","max-count"]),S_=new Set(["|","|&"]),dc="__CC_SAFETY_NET_PIPE_INPUT__",Fp=new Set(["bash","sh","zsh","dash","ksh"]),b_=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 Pp(A,T,F,j,q){let K=re();for(let ee of A){if(uP(ee,T,F?.denyPaths??[],j,K))return{target:ee,ruleId:"secret.deny-path"};if(q&&!q.has(ee))continue;let te=lP(ee,T,F,K);if(te){if(!te.startsWith("secret.cli.")&&dP(ee,T,F?.allowPaths??[],j,K))continue;return{target:ee,ruleId:te}}}return null}function rt(A,T,F={}){let j=wp(A),q=Pp(j,A.invocation.context.executionCwd,T,A.invocation.context.configCwd),K=q?.ruleId!=="secret.deny-path"&&F.strict===!1?wp(A,{refineJavaScriptInlineData:!0}):j,ee=K.length===j.length?q:Pp(j,A.invocation.context.executionCwd,T,A.invocation.context.configCwd,new Set(K));if(ee?.ruleId!=="secret.deny-path"&&F.strict===!1&&v_(A))return null;return ee}function v_(A){let T=Sn(A,"input-candidate")??Sn(A,"declared-command");if(!T)return!1;if(T.program.nodes.some((ee)=>ee.kind==="command"&&ee.nested.length>0))return!1;let F=[];for(let ee of T.shell.entries){if(ee.kind==="operator"&&ee.boundary)return!1;if(ee.kind==="redirection")return!1;if(ee.kind!=="operator")F.push(Qn(ee.text))}let j=xo(F);if(j.length===0)return!1;let q=Xr(j[0]??"").toLowerCase(),K=j.slice(1);if(A.invocation.route.kind==="unknown")return T.program.dialect==="powershell"&&(q==="ls"||q==="stat");if(q==="ls"||q==="stat")return!0;if(q==="test")return K.length===2&&(K[0]==="-e"||K[0]==="-f");if(q!=="find")return!1;return!K.some((ee)=>s_.has(ee))}function wp(A,T={}){if(A.invocation.route.kind==="command"){let j=Sn(A,"input-candidate");return j?Ci(j.shell,A.store,T,Ap(j)):[]}if(A.invocation.route.kind!=="unknown")return[...A.paths];let F=Sn(A,"input-candidate");return[...F?Ci(F.shell,A.store,T,Ap(F)):[],...A.paths]}function Ap(A){return A.program.dialect==="powershell"}function Ci(A,T,F,j=!1){if(A.status==="structural-limit")throw new w;if(A.status==="unclosed-quote")return[];if(A.status==="invalid")throw Error("Unable to parse command for secret protection");let q=[...A.assignmentFallbacks,...j_(Qn(A.source),T,F)],K=[],ee=null;for(let te of A.entries){if(te.kind==="operator"){if(!te.boundary)continue;if(K.length>0){if(q.push(...ta(K,T,F)),ee!==null)q.push(...Tp(ee,K,T,F));ee=S_.has(te.operator)?K:null,K=[]}else ee=null;continue}if(te.kind==="redirection"){let ce=te.target?Qn(kp(te.target,j)):void 0;if(ce&&te.targetOrder==="legacy-segment")K.push(ce);else if(ce)q.push(ce);continue}K.push(Qn(kp(te.text,j)))}if(K.length>0){if(q.push(...ta(K,T,F)),ee!==null)q.push(...Tp(ee,K,T,F))}return q}function ta(A,T,F){let j=I_(A),q=xo(A);if(q.length===0)return j;let K=q[0]??"",ee=Xr(K).toLowerCase(),te=q.slice(1),ce=R_(K,ee,te);if(ce)return[...j,...ce];if(Np.has(ee))return j;if(ee==="export")return[...j,...te.flatMap((de)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(de)?[de.slice(de.indexOf("=")+1)]:Yr(ee,de))];if(ee==="git")return[...j,...k_(te)];if(f_.has(ee))return[...j,...J_(te)];if(r_.has(ee))return[...j,...N_(te,T,F)];if(On.has(ee))return[...j,...te.flatMap((de)=>Yr("awk",de)),...te.flatMap((de)=>W_(de,T,F)),...te.flatMap(F_)];if(ee==="curl")return[...j,...te.flatMap((de)=>Yr(ee,de)),...O_(te)];if(Bp(ee)){if(Fp.has(ee)){let de=fd(ee,te);if(de!==null&&T.getShellSyntax(de).status==="structural-limit")throw new w}return[...j,...L_(ee,te,F)]}return[...j,...te.flatMap((de)=>Yr(ee,de))]}function R_(A,T,F){let j=Hs(T,F);if(j===null||F[j]!=="explain")return null;let q=[A,...F.slice(0,j)],K=F.slice(j+1);for(let ee=0;ee<K.length;ee++){let te=K[ee];if(te==="--json"||te==="--help"||te==="-h")continue;if(te==="--cwd"){let ce=K[ee+1];if(ce&&!ce.startsWith("--"))q.push(ce);ee++;continue}return q}return q}function Tp(A,T,F,j){if(w_(T,F,j))return x_(A);let q=A_(T);if(q===null)return[];return E_(A).flatMap((K)=>Fp.has(q)?Ci(F.getShellSyntax(K),F,j):$p(K))}function x_(A){let T=xo(A);if(T.length===0)return[];let F=Xr(T[0]??"").toLowerCase();if(!Np.has(F))return[];return T.slice(1)}function E_(A){let T=xo(A);if(T.length===0)return[];let F=Xr(T[0]??"").toLowerCase(),j=T.slice(1);if(F==="echo"){let q=j.findIndex((K)=>!/^-[neE]+$/.test(K));return[(q===-1?[]:j.slice(q)).join(" ")]}if(F==="printf")return __(j);return[]}function __(A){let T=A[0];if(T===void 0)return[];let F=(T.match(/%%|%[bqs]/g)??[]).filter((q)=>q!=="%%").length;if(F===0||A.length===1)return[Gp(T)];let j=A.slice(1);return Array.from({length:Math.ceil(j.length/F)},(q,K)=>P_(T,j.slice(K*F,(K+1)*F)))}function P_(A,T){let F=0;return Gp(A.replace(/%%|%[bqs]/g,(j)=>{if(j==="%%")return"%";let q=T[F]??"";return F++,q}))}function Gp(A){return A.replace(/\\n/g,`
44
+ `).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function w_(A,T,F){let j=xo(A);if(j.length===0||Xr(j[0]??"").toLowerCase()!=="xargs")return!1;let q=Ur(j),K=j.slice(q.childStart);if(K.length===0)return!1;if(q.replacementToken==="")return!1;let ee=q.replacementToken,te=ee===null?[...K,dc]:K.map((ce)=>ce.split(ee).join(dc));return ta(te,T,F).some((ce)=>ce.includes(dc))}function A_(A){let T=xo(A);if(T.length===0)return null;let F=Xr(T[0]??"").toLowerCase();if(!Bp(F))return null;return T_(F,T.slice(1))?F:null}function T_(A,T){let F=zp(A);for(let j=0;j<T.length;j++){let q=T[j];if(q===void 0)break;if(Wp.has(q)||Up(A,q)||/^--(?:eval|exec)=/.test(q))return!1;if(q==="-")return!0;if(q.startsWith("-")){if(F==="python"&&q==="-m")return!1;if(b_.get(F)?.has(q))j++;continue}return!1}return!0}function zp(A){return/^python\d/.test(A)?"python":A}function I_(A){let T=[];for(let F of A){if(Vp(F))continue;let j=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(F);if(j===null)break;if(j[1]!==void 0&&j[1]!=="")T.push(j[1])}return T}var Ip=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function kp(A,T){if(!T||!Ip.test(A))return A;return`~${A.replace(Ip,"").replace(/\\/g,"/")}`}function Yr(A,T){if(T==="--")return[];let F=[],j=T.indexOf("=");if(j>0&&j<T.length-1)F.push(T.slice(j+1));if(T.startsWith("-"))return F;if(A==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(T))return F;if(A==="zip"&&/\.zip$/i.test(T))return F;return F.push(T),F}function k_(A){let T=[];for(let F=0;F<A.length;F++){let j=A[F]??"";if(j==="--"||!j.startsWith("-"))return[...T,...A.slice(F).flatMap((K)=>Yr("git",K))];if(T.push(...Yr("git",j)),!vn.has(j))continue;let q=A[F+1];if(q===void 0)break;T.push(...j==="-c"&&q.includes("=")?[q.slice(q.indexOf("=")+1)]:Yr("git",q)),F++}return T}function O_(A){return A.flatMap((T,F)=>{let j=D_(T);if(j!==null)return Op(j.flag,j.value);let q=M_(A[F-1]);return q===null?[]:Op(q,T)})}function Op(A,T){if(A==="-F"||A==="--form"){let F=T.indexOf("="),j=F===-1?T:T.slice(F+1);if(!j.startsWith("@")&&!j.startsWith("<"))return[];return mc(j.slice(1).split(";")[0]??"")}if(A==="--data-urlencode"){let F=T.indexOf("@"),j=T.indexOf("=");if(F===-1||j!==-1&&j<F)return[];return mc(T.slice(F+1))}return T.startsWith("@")?mc(T.slice(1)):[]}function M_(A){if(A===void 0)return null;if(Lp.has(A))return A;return/^-[A-Za-z]+[dF]$/.test(A)?`-${A.slice(-1)}`:null}function D_(A){let T=A.slice(0,2);if(A.length>2&&(T==="-d"||T==="-F"))return{flag:T,value:A.slice(2)};let F=A.indexOf("=");if(F===-1)return null;let j=A.slice(0,F);return Lp.has(j)?{flag:j,value:A.slice(F+1)}:null}function mc(A){return A===""||A==="-"?[]:[A]}function N_(A,T,F){let j=A.findIndex((K)=>K.startsWith("-")||K==="("||K==="!"||K===";"),q=[...A.slice(0,j===-1?A.length:j)];for(let K=0;K<A.length;K++){if(!o_.has(A[K]??""))continue;let ee=A.slice(K+1),te=ee.findIndex((_e)=>i_.has(_e)),ce=te===-1?ee:ee.slice(0,te),de=ta(ce,T,F);if(q.push(...de.filter((_e)=>_e!=="{}")),!de.includes("{}"))continue;q.push(...A.slice(0,K).flatMap((_e,Pe,je)=>{if(!a_.has(_e))return[];let it=je[Pe+1];return it===void 0?[]:[it,it.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return q}function Bp(A){return l_.has(A)||/^python\d/.test(A)}function L_(A,T,F){let j=[];for(let q=0;q<T.length;q++){let K=T[q];if(K===void 0)break;if(Wp.has(K)||Up(A,K)){let te=T[q+1];if(te!==void 0)j.push(...Mp(A,te,F)),q++;continue}let ee=/^--(?:eval|exec)=(.*)$/.exec(K);if(ee!==null&&ee[1]!==void 0){j.push(...Mp(A,ee[1],F));continue}if(!K.startsWith("-"))j.push(K)}return j}function Up(A,T){if(!T.startsWith("-")||T.startsWith("--")||T.length<=2)return!1;return m_.get(T[T.length-1]??"")?.has(zp(A))??!1}function W_(A,T,F){if(!A.includes("system"))return[];return Ja(A)?.commands.flatMap((j)=>Ci(T.getShellSyntax(j),T,F))??[]}function F_(A){return Array.from(A.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((T)=>T[1]).filter((T)=>T!==void 0&&T!=="")}function $p(A){let T=Array.from(A.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((j)=>j[2]).filter((j)=>j!==void 0&&j!==""),F=(A.match(/[\w./~@+-]*[./~][\w./~@+-]*/g)??[]).filter((j)=>j!=="process.versions.sqlite"||T.some((q)=>q.includes(j)));return[...T,...T.flatMap(jp),...F]}function Mp(A,T,F){let j=$p(T);if(!F.refineJavaScriptInlineData||!c_.has(A)||j.length===0)return j;let q=G_(T);return q!==null&&!B_(q)?[]:j}function G_(A){let T=A.split("");for(let F=0;F<A.length;F++){let j=A[F];if(j!=="'"&&j!=='"'&&j!=="`")continue;if(j==="`"&&z_(A,F))return null;T[F]=" ";let q=!1;for(let K=F+1;K<A.length;K++){let ee=A[K];if(T[K]=" ",ee==="\\"){if(K++,K<A.length)T[K]=" ";continue}if(j==="`"&&ee==="$"&&A[K+1]==="{")return null;if(j!=="`"&&(ee===`
45
+ `||ee==="\r"))return null;if(ee!==j)continue;F=K,q=!0;break}if(!q)return null}return T.join("")}function z_(A,T){for(let F=T-1;F>=0;F--){let j=A[F];if(!j||/\s/.test(j))continue;return/[\w$\])]/.test(j)}return!1}function B_(A){for(let T of A.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let F=T[0],j=T.index;if(u_.has(F.toLowerCase()))return!0;let q=F.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((K)=>K.toLowerCase());if(!q.some((K)=>d_.has(K)))continue;if(q.length>1)return!0;if(U_(A,j)===".")return!0;if($_(A,j+F.length)==="(")return!0}return!1}function U_(A,T){for(let F=T-1;F>=0;F--)if(!/\s/.test(A[F]??""))return A[F];return}function $_(A,T){for(let F=T;F<A.length;F++)if(!/\s/.test(A[F]??""))return A[F];return}function j_(A,T,F){return Y_(A).flatMap((j)=>{let q=T.getShellSyntax(j);if(q.status==="invalid")return[];return[...Ci(q,T,F),...H_(q)?V_(q):[]]})}function H_(A){let T=A.entries;for(let F=0;F<T.length;F++){let j=T[F];if(j?.kind!=="word"||Xr(Qn(j.text)).toLowerCase()!=="base64")continue;for(let q=F+1;q<T.length;q++){let K=T[q];if(K?.kind==="operator")break;if(K?.kind!=="word")continue;let ee=Qn(K.text);if(ee==="--decode"||!ee.startsWith("--")&&ee.startsWith("-")&&/[dD]/.test(ee))return!0}}return!1}function V_(A){return A.entries.flatMap((T)=>T.kind==="word"?[Qn(T.text)]:T.kind==="redirection"&&T.target?[Qn(T.target)]:[]).flatMap(jp)}function jp(A){let T=K_(A);if(T===null)return[];let F=Buffer.from(T,"base64").toString("utf8");if(F===""||q_(F))return[];return Buffer.from(F,"utf8").toString("base64").replace(/=+$/g,"")===T.replace(/=+$/g,"")?[F]:[]}function q_(A){return Array.from(A).some((T)=>{let F=T.charCodeAt(0);return F<32||F===127})}function K_(A){if(A.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(A))return null;if(/=/.test(A.replace(/=+$/g,"")))return null;let T=A.replace(/=+$/g,"");if(T.length%4===1)return null;return`${T.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-T.length%4)%4)}`}function Y_(A){let T=[],F={inSingle:!1,inDouble:!1,escaped:!1};for(let j=0;j<A.length;j++){let q=A[j];if(!q)break;if(Fo(q,F))continue;if(Hp(A,j,F)){let K=Z_(A,j+1);if(K!==null)T.push(K.body),j=K.endIndex;continue}if(!F.inSingle&&q==="`"){let K=X_(A,j);if(K!==null)T.push(K.body),j=K.endIndex}}return T}function Z_(A,T){let F={inSingle:!1,inDouble:!1,escaped:!1},j=1;for(let q=T+1;q<A.length;q++){let K=A[q];if(!K)break;if(Fo(K,F))continue;if(Hp(A,q,F)){j++,q++;continue}if(!F.inSingle&&!F.inDouble&&K===")"){if(j--,j===0)return{body:A.slice(T+1,q),endIndex:q}}}return null}function X_(A,T){let F=!1;for(let j=T+1;j<A.length;j++){let q=A[j];if(!q)break;if(F){F=!1;continue}if(q==="\\"){F=!0;continue}if(q==="`")return{body:A.slice(T+1,j),endIndex:j}}return null}function Hp(A,T,F){return!F.inSingle&&A[T]==="$"&&A[T+1]==="("&&A[T+2]!=="("}function J_(A){let T=[],F=[],j=!1,q=!1,K=!1;for(let ce=0;ce<A.length;ce++){let de=A[ce];if(de===void 0)break;if(!K&&de==="--"){K=!0;continue}if(K){F.push(de);continue}let _e=/^--([^=]+)(?:=(.*))?$/.exec(de);if(_e!==null){let Pe=_e[1]??"",je=_e[2];if(Pe===p_)q=!0;if(h_.has(Pe))j=!0;if(je!==void 0){if(Pe===_p)T.push(je);continue}if(C_.has(Pe)){let it=A[ce+1];if(Pe===_p&&it!==void 0)T.push(it);ce++}continue}if(de.startsWith("-")&&de.length>1){let Pe=de.slice(1),je="",it="";for(let st=0;st<Pe.length;st++){let yt=Pe[st]??"";if(g_.has(yt))j=!0;if(y_.has(yt)){je=yt,it=Pe.slice(st+1);break}}if(je!=="")if(it.length>0){if(je===Ep)T.push(it)}else{let st=A[ce+1];if(je===Ep&&st!==void 0)T.push(st);ce++}continue}F.push(de)}let te=!j&&!q?F.slice(1):F;return[...T,...te]}function xo(A){let T=A.findIndex((F)=>!Vp(F)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(F));return T===-1?[]:[...A.slice(T)]}function Vp(A){return A==="env"||A==="command"||A==="builtin"||A==="sudo"}var Q_=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),eP=".env.",tP=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),nP=[".env.example.",".env.sample."];function rP(A){let T;try{T=new URL(A.trim())}catch{return!1}return T.protocol!=="file:"&&T.host!==""}function oP(A){return A.length>0&&!/\s/.test(A)}function iP(A,T,F){try{let j=Si(A,T,F);return j!==""&&m.entryKind(j)!=="missing"}catch(j){if(j instanceof s)throw j;return!1}}var sP=new Set(["node_modules","__pycache__"]),aP=[["vendor","bundle"],["vendor","cache"]];function lP(A,T,F,j){if(rP(A))return null;let q=ir(A,T,j);if(!q)return null;let K=sn(q.split("/").pop()??""),ee=sn(q),te=()=>oP(K)||iP(A,T,j);if(tP.has(K)||nP.some((Pe)=>K.startsWith(Pe)))return null;let ce=sn(pP(A,T,j));for(let Pe of ql){let je=`~/${Pe.suffixParts.join("/")}`;if((Dp(ee,je)||Dp(ce,je))&&pr(Pe.id,F))return Pe.id}let de=cP(q,T,F,j);if(de)return de;if(Q_.has(K))return null;for(let Pe of Vl)if(K===Pe.basename&&pr(Pe.id,F))return Pe.id;if(K.startsWith(eP)&&pr(Vs.id,F)&&te())return Vs.id;for(let Pe of Kl)if(K.length>Pe.prefix.length&&K.startsWith(Pe.prefix)){let je=K.slice(Pe.prefix.length)[0];if((je==="-"||je==="_")&&pr(Pe.id,F)&&te())return Pe.id}for(let Pe of Yl)if(K.length>Pe.prefix.length&&K.startsWith(Pe.prefix)){if(K.slice(Pe.prefix.length)===Pe.suffix&&pr(Pe.id,F))return Pe.id}if(mP(ee))return null;if(!K.includes(".")&&li.pattern.test(K)&&pr(li.id,F))return li.id;let _e=fP(K,F);if(_e)return _e;return null}function cP(A,T,F,j){return qs.find((q)=>{if(!pr(q.id,F))return!1;switch(q.id){case"secret.cli.claude-code":return nn(A,on(process.env.CLAUDE_CONFIG_DIR,"~/.claude",T,j),[".credentials.json"]);case"secret.cli.claude-code.config":{let K=sn(A).split("/");return nn(A,on(process.env.CLAUDE_CONFIG_DIR,"~/.claude",T,j),["settings.json","settings.local.json"])||yi(A,"~/.claude.json",T,j)||K.at(-1)==="settings.local.json"&&K.at(-2)===".claude"||K.at(-1)===".mcp.json"}case"secret.cli.antigravity":return nn(A,ir("~/.gemini/config",T,j),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let K=on(process.env.CODEX_HOME,"~/.codex",T,j);return nn(A,K,["auth.json",".credentials.json"])||hi(A,K,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let K=on(process.env.CODEX_HOME,"~/.codex",T,j),ee=sn(A).split("/").at(-1)??"";return nn(A,K,["config.toml"])||ee.endsWith(".config.toml")&&nn(A,K,[ee])}case"secret.cli.gemini":return nn(A,Cn(on(process.env.GEMINI_CLI_HOME,"~",T,j),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let K=sn(A).split("/"),ee=process.env.ProgramData?[Cn(on(process.env.ProgramData,"",T,j),"gemini-cli")]:[];return nn(A,Cn(on(process.env.GEMINI_CLI_HOME,"~",T,j),".gemini"),["settings.json","google_accounts.json"])||K.at(-1)==="settings.json"&&K.at(-2)===".gemini"||(process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH?.trim()?yi(A,process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH,T,j):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...ee].some((te)=>nn(A,ir(te,T,j),["settings.json"]))}case"secret.cli.copilot-cli":{let K=on(process.env.COPILOT_HOME,"~/.copilot",T,j);return nn(A,K,["config.json"])||hi(A,K,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return nn(A,on(process.env.COPILOT_HOME,"~/.copilot",T,j),["mcp-config.json"]);case"secret.cli.kimi-code":{let K=on(process.env.KIMI_CODE_HOME,"~/.kimi-code",T,j),ee=on(process.env.KIMI_SHARE_DIR,"~/.kimi",T,j);return nn(A,K,["server.token"])||hi(A,K,["credentials"])||hi(A,ee,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let K=["config.toml","mcp.json"],ee=sn(A).split("/");return ee.at(-1)==="mcp.json"&&ee.at(-2)===".kimi-code"||nn(A,on(process.env.KIMI_CODE_HOME,"~/.kimi-code",T,j),K)||nn(A,on(process.env.KIMI_SHARE_DIR,"~/.kimi",T,j),[...K,"config.json","config.json.bak"])}case"secret.cli.opencode":{let K=Cn(on(process.env.XDG_DATA_HOME,"~/.local/share",T,j),"opencode"),ee=sn(A).split("/").at(-1)??"",te=process.env.OPENCODE_DB?.trim(),ce=te&&te!==":memory:"?[te,`${te}-wal`,`${te}-shm`]:[];return nn(A,K,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(ee)&&nn(A,K,[ee])||ce.some((de)=>yi(A,de,T,j))}case"secret.cli.opencode.config":{let K=process.env.OPENCODE_CONFIG_DIR?on(process.env.OPENCODE_CONFIG_DIR,"~/.config/opencode",T,j):Cn(on(process.env.XDG_CONFIG_HOME,"~/.config",T,j),"opencode"),ee=process.env.ProgramData?[Cn(on(process.env.ProgramData,"",T,j),"opencode")]:[],te=["opencode.json","opencode.jsonc"];return te.includes(sn(A).split("/").at(-1)??"")||nn(A,K,te)||(process.env.OPENCODE_CONFIG?.trim()?yi(A,process.env.OPENCODE_CONFIG,T,j):!1)||["/Library/Application Support/opencode","/etc/opencode",...ee].some((ce)=>nn(A,ir(ce,T,j),te))}case"secret.cli.pi":return nn(A,on(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",T,j),["auth.json"]);case"secret.cli.pi.config":return nn(A,on(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",T,j),["models.json"]);case"secret.cli.amp":{let K=ir("~",T,j);return[Cn(on(process.env.XDG_DATA_HOME,"~/.local/share",T,j),"amp"),Cn(K,".local","share","amp")].some((te)=>nn(A,te,["secrets.json"]))||hi(A,Cn(K,".amp"),["oauth"])}case"secret.cli.amp.config":{let K=["settings.json","settings.jsonc"],ee=[Cn(on(process.env.XDG_CONFIG_HOME,"~/.config",T,j),"amp"),Cn(ir("~",T,j),".config","amp")],te=sn(A).split("/");return ee.some((ce)=>nn(A,ce,K))||te.at(-2)===".amp"&&K.includes(te.at(-1)??"")||(process.env.AMP_SETTINGS_FILE?.trim()?yi(A,process.env.AMP_SETTINGS_FILE,T,j):!1)}case"secret.cli.cursor":{let K=Cn(on(process.env.XDG_CONFIG_HOME,"~/.config",T,j),"cursor"),ee=Cn(on(process.env.CURSOR_DATA_DIR,"~/.cursor",T,j),"projects");return nn(A,ir("~/.cursor",T,j),["auth.json"])||nn(A,K,["auth.json"])||sn(A).split("/").at(-1)==="mcp-auth.json"&&Zr(sn(A),sn(ee))}case"secret.cli.cursor.config":{let K=sn(A).split("/");return K.at(-1)==="mcp.json"&&K.at(-2)===".cursor"}case"secret.cli.grok-build":return nn(A,on(process.env.GROK_HOME,"~/.grok",T,j),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let K=sn(A).split("/");return K.at(-1)==="config.toml"&&K.at(-2)===".grok"||nn(A,on(process.env.GROK_HOME,"~/.grok",T,j),["config.toml","managed_config.toml","requirements.toml"])||nn(A,ir("/etc/grok",T,j),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}function on(A,T,F,j){return ir(A?.trim()?A:T,F,j)}function nn(A,T,F){return F.some((j)=>qp(A,Cn(T,j)))}function hi(A,T,F){return F.some((j)=>Zr(sn(A),sn(Cn(T,j))))}function yi(A,T,F,j){return qp(A,ir(T,F,j))}function qp(A,T){return sn(A)===sn(T)}function Cn(A,...T){return Yn([A,...T].filter(Boolean).join("/"))}function uP(A,T,F,j,q){if(F.length===0)return!1;let K=sn(Si(A,T,q));return F.some((ee)=>Zr(K,sn(Si(ee,j,q))))}function dP(A,T,F,j,q){if(F.length===0)return!1;let K=sn(Si(A,T,q));if(!K)return!1;let ee=process.env.HOME??fc(),te=ee?Yn(i(Pn(ee),m,q)):"",ce=sn(te),de=process.env.CC_SAFETY_NET_HOME,_e=sn(de?Yn(i(na(Pn(de)),m,q)):te&&Yn(i(`${te}/.cc-safety-net`,m,q)));if(_e&&Zr(K,_e))return!1;return F.some((Pe)=>{let je=sn(Si(Pe,j,q));if(!je)return!1;if(ce&&(ce===je||ce.startsWith(je.endsWith("/")?je:`${je}/`)))return!1;return Zr(K,je)})}function mP(A){let T=A.split("/");return T.some((F)=>sP.has(F))||aP.some(([F,j])=>T.some((q,K)=>q===F&&T[K+1]===j))}function fP(A,T){let F=A.lastIndexOf("."),j=F>0&&F<A.length-1?A.slice(F+1):"";if(j==="")return null;for(let q of Zl)if(j===q.extension&&pr(q.id,T))return q.id;for(let q of Xl)if(q.pattern.test(j)&&pr(q.id,T))return q.id;return null}function sn(A){return A.toLowerCase()}function pr(A,T){return!T?.disabledRules?.includes(A)}function ir(A,T,F){let{home:j,normalized:q}=pc(A,F);if(!q)return"";if(!j)return q;let K=gc(q,j),ee=ea(K)?K:Yn(na(T,K)),te=Yn(i(ee,m,F));if(!Zr(te,j)){if(ea(K))return te;return te===ee?q:te}let ce=te.slice(j.length);return ce?`~${ce}`:"~"}function Dp(A,T){return A===T||A.startsWith(`${T}/`)}function pP(A,T,F){let{home:j,normalized:q}=pc(A,F);if(!q||!j)return"";let K=gc(q,j),ee=e_.normalize(ea(K)?K:Yn(na(T,K))),te=Yn(Pn(process.env.HOME??fc())),ce=(Pe)=>process.platform==="win32"?Pe.toLowerCase():Pe,de=[j,te].find((Pe)=>Pe!==""&&Zr(ce(ee),ce(Pe)));if(de===void 0)return"";let _e=ee.slice(de.length);return _e?`~${_e}`:"~"}function Si(A,T,F){let{home:j,normalized:q}=pc(A,F);if(!q)return"";let K=j?gc(q,j):q;return Yn(i(ea(K)?K:na(T,K),m,F))}function pc(A,T){let F=process.env.HOME??fc(),j=F?Yn(i(Pn(F),m,T)):"",q=Yn(Pn(gP(Qn(A))));return{home:j,normalized:q}}function gP(A){if(!A.trim().toLowerCase().startsWith("file:"))return A;try{return n_(A)}catch{return A}}function gc(A,T){if(A==="~")return T;if(A.startsWith("~/"))return Cn(T,A.slice(2));return A}function hP(A){if(process.platform==="win32")return!0;return t_.parse(A).root.length>1}function Yn(A){let T=A.trim(),F=(hP(T)?T.replace(/\\/g,"/"):T).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(F==="/")return F;return F.replace(/\/+$/g,"")}function Zr(A,T){return A===T||A.startsWith(T.endsWith("/")?T:`${T}/`)}function Xr(A){return A.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??A}import{dirname as Jr}from"node:path";var Kp="Rulebook exceeds CC Safety Net's safe validation limits.",Yp="Additional rulebook validation errors were omitted.",Zn=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Zp(A){if(hc(A.allowed_commands,Zn.maxAllowedCommands)||hc(A.rules,Zn.maxRules)||hc(A.tests,Zn.maxTests))return!1;let{maxAggregateStringCodeUnits:T,maxTotalBlockArgs:F}=Zn,j=(q,K=!1)=>{if(typeof q!=="string")return!0;if(q.length>Zn.maxStringCodeUnits||K&&q.length>Zn.maxFixtureCommandCodeUnits||q.length>T)return!1;return T-=q.length,!0};if(!j(A.name)||!j(A.version)||!j(A.description)||!j(A.author)||!j(A.migrated_from))return!1;if(Array.isArray(A.allowed_commands)){for(let q of A.allowed_commands)if(!j(q))return!1}if(Array.isArray(A.rules))for(let q of A.rules){if(!q||typeof q!=="object")continue;let K=q;if(!j(K.name)||!j(K.command)||!j(K.subcommand)||!j(K.reason)||!j(K.intent))return!1;let ee=K.match&&typeof K.match==="object"?K.match:{};for(let te of[K.block_args,ee.command_path,ee.any_args,ee.exclude_args]){if(!Array.isArray(te))continue;if(te.length>Zn.maxBlockArgsPerRule||te.length>F)return!1;F-=te.length;for(let ce of te)if(!j(ce))return!1}}if(Array.isArray(A.tests))for(let q of A.tests){if(!q||typeof q!=="object")continue;let K=q;if(!j(K.command,!0)||!j(K.expect)||!j(K.rule))return!1}return!0}function hc(A,T){return Array.isArray(A)&&A.length>T}function yP(A){if(!CP(A))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Zp(A))return{errors:[Kp],ruleNames:new Set};let T=(A.rulebook_version===2?zf():Gf()).safeParse(A),F=[...A.rulebook_version===1||A.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...T.success?[]:ke(T.error.issues,": ",": ")];return{errors:F.length>Zn.maxValidationErrors?[...F.slice(0,Zn.maxValidationErrors),Yp]:F,ruleNames:new Set(Ne(A).map((j)=>j.toLowerCase()))}}function be(A){let T=yP(A);if(T.errors.length>0)throw Error(T.errors.join("; "));return A}function CP(A){return!!A&&typeof A==="object"&&!Array.isArray(A)}function V(A={}){let T=H(A),F=!1;try{F=Qf(T.userConfigTarget,T.projectConfigTarget)}catch(je){if(je instanceof t)return wP(T,je.message);throw je}let j=p(T.userConfigTarget),q=F?{config:null,errors:[]}:p(T.projectConfigTarget),K=Jp(T.userConfigPath,j.errors),ee=Jp(T.projectConfigPath,q.errors),te=new Set,ce=j.config?Me(j.config,Jr(T.userConfigPath),"user",T.userScope,te):Qp(),de=q.config?Me(q.config,Jr(T.projectConfigPath),"project",T.projectScope,te):Qp(),_e=j.config?.overrides??{},Pe=q.config?.overrides??{};return{rules:[...Xp(ce.rules,_e),...Xp(de.rules,Pe)],transparent_wrappers:_P(j.config,q.config),rulebooks:[...ce.rulebooks,...de.rulebooks],errors:[...K,...ee,...ce.errors,...de.errors],warnings:[...ce.warnings,...de.warnings,...ce.canValidateOverrides?yc(_e,ce.knownRuleIds,T.userConfigPath):[],...ce.canValidateOverrides?PP(Pe,ce.knownRuleIds,T.projectConfigPath):[],...de.canValidateOverrides?yc(Pe,de.knownRuleIds,T.projectConfigPath):[]],userConfig:j.config??void 0,projectConfig:q.config??void 0,...T}}function M(A,T){let F=SP(A,T);if(!F)return[];return[...F.scope.errors,...F.scope.warnings,...bP(F.config,F.scope,A)]}function SP(A,T){let F=T??k(Jr(Jr(A)),"rules policy"),j=p(o(F,A)).config;if(!j)return null;return{config:j,scope:Me(j,Jr(A),"project",F)}}function bP(A,T,F){return T.canValidateOverrides?yc(A.overrides??{},T.knownRuleIds,F):[]}function Me(A,T,F,j=k(Jr(Jr(T)),F==="user"?"user policy":"project policy"),q=new Set){let K=[],ee=[],te=A.rules.flatMap((de)=>{let _e=RP(de,T,j);if(_e.errors.length>0||!_e.rulebook)return K.push(..._e.errors),[];let Pe=_e.rulebook;if(q.has(Pe.name))return ee.push(`duplicate active rulebook name "${Pe.name}" for ${de}; keeping the first and ignoring this one, so its rules are not active; rename one of them in its rulebook file and in the rules config that lists it`),[];return q.add(Pe.name),[{rules:vP(Pe),rulebook:{source:F,spec:de,name:Pe.name,version:Pe.version,rules:Pe.rules.map((je)=>`${Pe.name}/${je.name}`)}}]}),ce=te.flatMap((de)=>de.rules);return{rules:ce,rulebooks:te.map((de)=>de.rulebook),entries:te.map((de)=>({spec:de.rulebook.spec,name:de.rulebook.name,version:de.rulebook.version,ruleCount:de.rulebook.rules.length})),knownRuleIds:new Set(ce.map((de)=>de.name)),errors:K,warnings:ee,canValidateOverrides:K.length===0}}function vP(A){if(A.rulebook_version===2)return A.rules.map((T)=>({name:`${A.name}/${T.name}`,command:T.command,block_args:[],match:T.match,reason:T.reason,intent:T.intent}));return A.rules.map((T)=>({...T,name:`${A.name}/${T.name}`,match:void 0}))}function RP(A,T,F){let j=ot(A),q=W(T,j),K=EP(q,F);if("error"in K)return{rulebook:null,errors:[K.error]};if(K.content===null)return{rulebook:null,errors:[`missing rulebook file ${q} for ${A}; ${xP(A)}`]};let ee=Re(K.content);if("problem"in ee)return{rulebook:null,errors:[`invalid rulebook ${q}: ${ee.problem}; fix that file`]};if(ee.rulebook.name!==j)return{rulebook:null,errors:[`rulebook name "${ee.rulebook.name}" in ${q} must match source "${A}"; fix that file`]};return{rulebook:ee.rulebook,errors:[]}}function ot(A){return b(A)?G(A).name:A}function xP(A){return b(A)?`run ${ap} to vendor ${A}`:"create that file or remove that source from the rules config"}function EP(A,T){try{return{content:n(o(T,A))}}catch(F){if(F instanceof t)return{error:F.message};throw F}}function Re(A){let T;try{T=JSON.parse(A)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:be(T)}}catch(F){return{problem:F instanceof Error?F.message:"invalid rulebook"}}}function _P(A,T){return[...new Set([...A?.transparent_wrappers??[],...T?.transparent_wrappers??[]])]}function Xp(A,T){return A.flatMap((F)=>{let j=T[F.name];if(j==="off")return[];if(j&&typeof j==="object")return[{...F,intent:j.intent??F.intent,reason:j.reason}];return[F]})}function yc(A,T,F){return Object.keys(A).filter((j)=>!T.has(j)).map((j)=>`unknown override key "${j}" in ${F}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function PP(A,T,F){return Object.keys(A).filter((j)=>T.has(j)).map((j)=>`project override cannot target user-scoped rule "${j}" in ${F}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function Jp(A,T){return T.map((F)=>F.startsWith("Unable to access ")?F:`${A}: ${F}`)}function wP(A,T){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[T],warnings:[],userConfigPath:A.userConfigPath,projectConfigPath:A.projectConfigPath}}function Qp(){return{rules:[],rulebooks:[],entries:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}function x(A={}){let T=V(A),F=pp(A),j={rules:T.rules,transparentWrappers:T.transparent_wrappers,safety:F.safety,worktreeMode:F.worktreeMode,destructiveCommandProtectionEnabled:F.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:F.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:F.destructiveCommandAllowPaths,secretProtection:{enabled:F.secretProtection.enabled??!0,disabledRules:F.secretProtection.disabledRules??[],denyPaths:F.secretProtection.denyPaths,allowPaths:F.secretProtection.allowPaths??[]}},q={...T.userConfig?.overrides??{},...T.projectConfig?.overrides??{}},K=Object.freeze(Object.fromEntries(j.rules.map((ee)=>{let te=T.rulebooks.find((de)=>de.rules.includes(ee.name)),ce=q[ee.name];return[ee.name,Object.freeze({id:ee.name,...te?{rulebook:Object.freeze({name:te.name,version:te.version}),...kP(te.spec)?{source:te.spec}:{}}:{},...ce&&typeof ce==="object"?{override:Object.freeze({type:"reason",reason:ce.reason})}:{}})]})));return Ee(j,AP(T,F),K,F.policyScopes)}function $e(A){if(A.state==="ready")return{state:A.state};return{state:A.state,reason:A.reason}}function AP(A,T){let F=IP(T);if(A.errors.length===0&&A.warnings.length===0&&!F)return;return{diagnostics:[...A.errors,...A.warnings,...T.errors],reason:OP(A.errors.length>0?TP(A.errors):void 0,A.warnings.length>0?Sc(A.warnings.join("; ")):void 0,F)}}function TP(A){return`${Sc(A.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function IP(A){if(A.errors.length===0)return;let T=A.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${A.errors.join("; ")}. Enforcing ${T}; the invalid values are not active. Fix the policy file manually`}function kP(A){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(A)}function Ee(A,T,F=Object.freeze({}),j){let q=Cc(structuredClone(A)),K=j?{policyScopes:Cc(structuredClone(j))}:{};if(!T)return Object.freeze({state:"ready",policy:q,diagnostics:Object.freeze([]),ruleMetadata:F,...K});return Object.freeze({state:"degraded",policy:q,diagnostics:Object.freeze([...T.diagnostics]),reason:T.reason,ruleMetadata:F,...K})}function Cc(A){if(typeof A!=="object"||A===null)return A;for(let T of Object.values(A))Cc(T);return Object.freeze(A)}function OP(...A){return Sc(A.filter((T)=>!!T).join("; "))}function Sc(A){return/[.!?]$/.test(A)?A:`${A}.`}class d extends Error{stage;evaluation;name="GuardEvaluationError";constructor(A,T,F){super(`CC Safety Net ${A} dependency failed`,{cause:F});this.stage=A;this.evaluation=T}}var MP={findPolicyMutation:tt,findGitMetadataMutation:ze,resolveGitMetadata:Te,loadPolicySnapshot:x,findSensitiveTarget:rt,analyzeCommand:De,getModes:E};function Fe(A,T={}){let F={...MP,...T.dependencies},j=LP(A),q=bi(A)?A.command:j,K=Tr("policy-protection",q,()=>ye(A,T.factParserDependencies)),ee=Sn(K,"input-candidate"),te=Sn(K,"declared-command");if(bi(A)&&A.command?.trim()&&te?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:sr,intent:"stop_and_explain",evidence:[{kind:"command",command:A.command,segment:A.command}]}};if(ee?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:Pc,intent:"stop_and_explain",evidence:[]}};let ce=Tr("policy-protection",q,()=>F.resolveGitMetadata([A.context.executionCwd,A.context.configCwd])),de=Tr("policy-protection",q,()=>F.findPolicyMutation(K));if(de){let Dt=q??de.target;return{stage:"policy-protection",decision:{kind:"deny",reason:et,intent:"hard_stop",evidence:[{kind:"command",command:Dt,segment:de.target}]}}}let _e=Tr("policy-protection",q,()=>Ke(K));if(_e){let Dt=q??_e.target;return{stage:"policy-protection",decision:{kind:"deny",reason:qe,intent:"hard_stop",evidence:[{kind:"command",command:Dt,segment:_e.target}]}}}let Pe=Tr("policy-protection",q,()=>F.findGitMetadataMutation(K,ce));if(Pe){let Dt=q??Pe.target;return{stage:"policy-protection",decision:{kind:"deny",reason:S,intent:"hard_stop",evidence:[{kind:"command",command:Dt,segment:Pe.target}]}}}let je=Tr("config-load",q,()=>F.loadPolicySnapshot({...T.policyOptions,cwd:A.context.configCwd})),it=je.policy,st=F.getModes(it),yt={level:st.effectiveLevel,...DP(je)},At=it.secretProtection.enabled===!1?null:Tr("secret-protection",q,()=>F.findSensitiveTarget(K,it.secretProtection,{strict:bi(A)||ee?.program.dialect==="powershell"?st.strict:void 0}));if(At){let Dt=q??At.target;return{stage:"secret-protection",...yt,decision:{kind:"deny",reason:nt,intent:"hard_stop",ruleId:At.ruleId,evidence:[{kind:"command",command:Dt,segment:At.target}]}}}if(!bi(A))return{stage:"non-command",...yt,decision:{kind:"allow"}};if(!A.command||A.command.trim()==="")return{...bc("command-validation",q),...yt};let Tt=Tr("command-analysis",q,()=>F.analyzeCommand(A.command,{cwd:A.context.executionCwd,shell:A.route.shell,policySnapshot:je,environment:L(),protectedGitMetadata:ce,effectiveCapabilities:st.capabilities,strict:st.strict,paranoidRm:st.paranoidRm,paranoidInterpreters:st.paranoidInterpreters,worktreeMode:st.worktreeMode},NP(K),K.store));if(Tt)return{stage:"command-analysis",...yt,decision:Tt};return{stage:"command-analysis",...yt,decision:{kind:"allow"}}}function DP(A){if(A.state==="ready")return{};return{configFallback:{reason:A.reason}}}function NP(A){return Sn(A,"declared-command")?.program}function LP(A){try{return B(A.input)}catch(T){let F=bi(A)?A.command:void 0;throw new d("policy-protection",bc("policy-protection",T instanceof a?void 0:F,T),T)}}function Tr(A,T,F){try{return F()}catch(j){throw new d(A,bc(A,j instanceof a?void 0:T,j),j)}}function bc(A,T,F){let j=F instanceof s||F instanceof w;return{stage:A,decision:{kind:"deny",reason:j?wc:he,intent:"stop_and_explain",evidence:T?[{kind:"command",command:T,segment:T}]:[]}}}function bi(A){return A.route.kind==="command"}
46
+ export{Ge,He,m,L,t,k,o,ue,n,v,Ce,Y,vt,bt,u,we,pe,at,G,ne,fe,b,lt,me,I,g,ge,D,Ae,Ct,H,C,W,Se,O,N,ct,he,s,re,i,e,oe,J,U,z,xe,R,a,ie,B,We,Ue,w,ye,dt,S,ze,Te,Ie,wt,l,r,Be,se,E,P,Le,ut,Ve,St,De,c,qe,Ke,ae,Oe,Ye,Je,Z,xt,Lt,kt,Ze,Rt,Ne,_,ke,X,pt,p,ft,mt,gt,h,ve,y,Et,Q,Pt,ht,_t,le,f,Xe,Qe,et,tt,nt,rt,be,V,M,Me,ot,Re,x,$e,Ee,d,Fe};