cc-safety-net 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ import{accessSync as Cp,constants as al,realpathSync as bp,statSync as ll}from"node:fs";import{isAbsolute as cl,relative as Sp,resolve as vp,sep as Rp}from"node:path";import{dirname as dp,isAbsolute as mp,parse as fp,sep as pp}from"node:path";function Tt(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function bt(e,t,n){if(Tt(t))throw Error("Unsupported Windows namespace path");let r=mp(t)?hp(t):"",o=r||e;for(let i of yp(r?t.slice(r.length):t)){if(i===""||i===".")continue;if(i===".."){o=dp(o);continue}let s=gp(o,i),a=n.entryKind(s),l=a==="symlink"?n.realpath(s):s;if(a==="missing"||l===null)throw Error(`Cannot resolve path component: ${s}`);o=l}return o}function gp(e,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${t}`:`${e}${pp}${t}`}function hp(e){return fp(e).root}function yp(e){let t=process.platform==="win32"?/[\\/]+/:/\/+/;return e.split(t)}function oP(e){try{if(!ll(e).isDirectory())return!1;return Cp(e,al.R_OK|al.X_OK),!0}catch{return!1}}function iP(e,t){if(Tt(e))return;let n=t.flatMap((o)=>Ni(o));if(!n[0])return;let r=Ni(cl(e)?e:vp(n[0],e))[0];if(!r)return;return n.some((o)=>xp(r,o))?r:void 0}function sP(e){return e.flatMap((t)=>Ni(t))[0]}function Ni(e){try{let t=bp(e);return ll(t).isDirectory()?[t]:[]}catch{return[]}}function xp(e,t){let n=Sp(t,e);return n===""||n!==".."&&!n.startsWith(`..${Rp}`)&&!cl(n)}var St="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",lt="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",ul="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.",dl="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",ml="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";function fl(e,t,n,r,o){if(n.kind!=="command")return{toolName:e,input:t,route:n,context:r};return{toolName:e,input:t,route:n,context:r,command:o}}function I(e){return e.provenance==="command-substitution"?e.raw:e.text}function rn(e,t){return e==="posix"?t:G(t.map((n)=>n.text))}function Fr(e,t){return e&&e.provenance!=="unknown"?e.provenance==="literal":!/[$`*?[\]]/.test(t)}function G(e){return e.map((t)=>({kind:"word",text:t,raw:t,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}import{existsSync as zi,lstatSync as Tp,readFileSync as Br,realpathSync as Gn,statSync as Fn}from"node:fs";import{dirname as $i,isAbsolute as Bi,join as Ur,resolve as Hr}from"node:path";import{lstatSync as Ep,realpathSync as wp}from"node:fs";import{homedir as Pp,tmpdir as _p}from"node:os";var De={realpath:(e)=>{try{return wp(e)}catch{return null}},entryKind:(e)=>{let t=Ep(e,{throwIfNoEntry:!1});if(!t)return"missing";return t.isSymbolicLink()?"symlink":"present"}};function pe(e,t=process.platform){if(t!=="win32")return e;return e.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function It(){return pe(process.env.HOME||Pp())}function ct(){return{env:new Map(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),home:It(),tmpdir:_p(),paths:De}}var Wi=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],Ap=new Set(Wi);var pl=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),Gr=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),kp=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function Fi(e){return Ap.has(e)}function Wn(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function Gi(e){return Fi(e)||pl.has(e)||Gr.has(e)||Wn(e)}function we(e,t,n){return n?.has(e)?n.get(e):t.get(e)}function zr(e,t){let n=we("GIT_CONFIG_COUNT",e,t);if(n===void 0)return{state:"absent"};if(n==="")return{state:"valid",count:0};if(!/^\d+$/.test(n))return{state:"invalid"};let r=Number(n);return Number.isSafeInteger(r)&&r<=1024?{state:"valid",count:r}:{state:"invalid"}}function $r(e,t,n){let o=e.match(kp)?.[1];if(!o||!Gi(o))return null;let i=e.indexOf("=");return{name:o,value:`${we(o,t,n)??""}${e.slice(i+1)}`}}function gl(e){return yl(e,Gr)}function hl(e){return yl(e,pl)}function yl(e,t){if(!e)return!1;for(let n of e.keys())if(t.has(n))return!0;return!1}var Ye=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]);function Sl(e,t){return Wi.some((n)=>t?.has(n)||e.has(n))}function vl(e,t){if(!t)return{gitCwd:null,hasExplicitGitContext:!1};let n;try{n=Gn(Hr(t))}catch{return{gitCwd:null,hasExplicitGitContext:!1}}if(!El(n))return{gitCwd:null,hasExplicitGitContext:!1};let r=!1,o=1;while(o<e.length){let i=e[o];if(!i)break;if(i==="--")break;if(!i.startsWith("-"))break;if(i==="-C"){let s=e[o+1];if(!s)return{gitCwd:null,hasExplicitGitContext:r};let a=bl(n,s);if(!a)return{gitCwd:null,hasExplicitGitContext:r};n=a,o+=2;continue}if(i.startsWith("-C")&&i.length>2){let s=bl(n,i.slice(2));if(!s)return{gitCwd:null,hasExplicitGitContext:r};n=s,o++;continue}if(i==="--git-dir"||i==="--work-tree"){r=!0,o+=2;continue}if(i.startsWith("--git-dir=")||i.startsWith("--work-tree=")){r=!0,o++;continue}if(Ye.has(i))o+=2;else if(i.startsWith("-c")&&i.length>2)o++;else o++}return{gitCwd:n,hasExplicitGitContext:r}}function Rl(e){let t=Hp(e);if(!t)return!1;try{let n=Tp(t);if(n.isSymbolicLink()||!n.isFile())return!1;let r=Ui(t);if(!r?.commonDir)return!1;if(!Mp(r.gitDir,t))return!1;return Dp(r.gitDir,$i(t))}catch{return!1}}function Ui(e){try{let t=Ip(e);if(!t)return null;let n=Gn(Bi(t)?t:Hr($i(e),t));if(!Fn(n).isDirectory())return null;return{gitDir:n,commonDir:Op(n)}}catch{return null}}function Ip(e){let t=Br(e,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!t.startsWith("gitdir:"))return null;return t.slice(7).trim()||null}function Op(e){try{let t=Br(Ur(e,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!t)return null;let n=Gn(Bi(t)?t:Hr(e,t));return Fn(n).isDirectory()?n:null}catch{return null}}function Mp(e,t){let n=Lp(e);return n===null?!1:xl(e,n,t)}function Dp(e,t){let n=Np(e);return n===null?!0:xl(e,n,t)}function Lp(e){let t=Ur(e,"gitdir");if(!zi(t))return null;let n=Br(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return n===""?null:n}function Np(e){let t=Ur(e,"config.worktree");return zi(t)?$p(t):null}function xl(e,t,n){return Fp(Wp(e,t),n)}function Wp(e,t){return Bi(t)?t:Hr(e,t)}function Fp(e,t){try{return Gp(e,t)}catch{return!1}}function Gp(e,t){try{let n=Fn(e),r=Fn(t);if(n.ino!==0&&r.ino!==0&&n.dev===r.dev&&n.ino===r.ino)return!0}catch{}return Cl(e)===Cl(t)}function Cl(e){return zp(Gn.native(e))}function zp(e){let t=e.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"");if(t=t.replace(/\\/g,"/"),t.length>1&&t.endsWith("/"))t=t.slice(0,-1);return process.platform==="win32"?t.toLowerCase():t}function $p(e){let t=Br(e,"utf-8"),n=!1,r=null;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i===""||i.startsWith("#")||i.startsWith(";"))continue;if(i.startsWith("[")){n=/^\[core\]$/i.test(i);continue}if(!n)continue;let s=i.match(/^worktree\s*=\s*(.*)$/i);if(s)r=Bp(s[1]??"")}return r}function Bp(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;return Up(t.slice(1,-1))}function Up(e){let t="";for(let n=0;n<e.length;n++){let r=e[n];if(r!=="\\"){t+=r;continue}let o=e[n+1];if(o===void 0){t+=r;continue}switch(o){case"\\":case'"':t+=o;break;case"n":t+=`
2
+ `;break;case"t":t+="\t";break;case"b":t+="\b";break;default:t+=`\\${o}`;break}n++}return t}function bl(e,t){try{let n=bt(e,t,De);return El(n)?n:null}catch{return null}}function El(e){try{return Fn(e).isDirectory()}catch{return!1}}function Hp(e){try{return zn(Gn(e))}catch{return null}}function zn(e){let t=e;while(!0){let n=Ur(t,".git");if(zi(n))return n;let r=$i(t);if(r===t)return null;t=r}}function Hi(e,t){return{value:e,work:t}}function v(e,t){if(e.work)e.work.units=Math.min(Number.MAX_SAFE_INTEGER,e.work.units+1);return e.value[t]}function X(e){return e.value.length}function $n(e,t,n=1){if(e)e.units=Math.min(Number.MAX_SAFE_INTEGER,e.units+t.length*n)}function ge(e,t){$n(e,t)}function Ot(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t===95||t>=97&&t<=122}function K(e){if(!e)return!1;let t=e.charCodeAt(0);return t===9||t===10||t===11||t===12||t===13||t===32||t===160||t===65279||t===5760||t>=8192&&t<=8202||t===8232||t===8233||t===8239||t===8287||t===12288}function ji(e){return e===`
3
+ `||e==="\r"||e==="\u2028"||e==="\u2029"}function Y(e,t,n){if(t+n.length>X(e))return!1;for(let r=0;r<n.length;r++)if(v(e,t+r)!==n[r])return!1;return!0}function ut(e,t,n){return!Ot(v(e,t-1))&&Y(e,t,n)&&!Ot(v(e,t+n.length))}function dt(e,t){return Ot(v(e,t-1))!==Ot(v(e,t))}function te(e){return e===`
4
+ `||e===";"||e==="&"||e==="|"}function on(e){return e==="|"||e===";"}function jr(e,t,n){let r=Hi(e,n);if(t==="rm")return jp(r);if(t==="dd")return qp(r);return Tl(r,!0)}function Vr(e,t,n){let r=Hi(e,n);if(t==="rm")return Kp(r);if(t==="reset-hard")return Al(r,"--ha","rd");if(t==="reset-merge")return Al(r,"--me","rge");if(t==="clean")return Jp(r);if(t==="checkout")return eg(r);if(t==="push-force")return tg(r);if(t==="push-refspec")return ng(r);if(t==="push-delete")return rg(r);if(t==="branch")return og(r);if(t==="tag")return ag(r);if(t==="restore")return lg(r);return Tl(r,!1)}function jp(e){let t=!1,n=!1,r=!1,o=-1;for(let i=0;i<=X(e);i++){let s=v(e,i);if(!t){let l=v(e,i+2);if(ut(e,i,"rm")&&K(l)&&l!==`
5
+ `)t=!0,i++;continue}let a=Vp(e,i);if(s===`
6
+ `||a!==-1){if(t=!1,n=!1,r=!1,o=-1,a!==-1)i=a-1;continue}if(s===";"||s==="&"||s==="|"||i===X(e)){if(o>=0){let l=wl(e,o,i);n||=l.recursive,r||=l.force}if(n&&r)return!0;t=!1,n=!1,r=!1,o=-1;continue}if(K(s)){if(o>=0){if(Y(e,o,"--")&&i-o===2)t=!1,n=!1,r=!1;else{let l=wl(e,o,i);if(n||=l.recursive,r||=l.force,n&&r)return!0}o=-1}continue}if(o<0)o=i}return!1}function Vp(e,t){if(v(e,t)!=="\\"||v(e,t-1)==="\\")return-1;if(Y(e,t,String.raw`\n`))return t+2;if(Y(e,t,String.raw`\x0a`)||Y(e,t,String.raw`\x0A`))return t+5;if(Y(e,t,String.raw`\u000a`)||Y(e,t,String.raw`\u000A`))return t+7;return Y(e,t,String.raw`\012`)?t+4:-1}function wl(e,t,n){if(Pl(e,t,n,"recursive"))return{recursive:!0,force:!1};if(Pl(e,t,n,"force"))return{recursive:!1,force:!0};if(v(e,t)!=="-"||v(e,t+1)==="-")return{recursive:!1,force:!1};let r=!1,o=!1;for(let i=t+1;i<n;i++){let s=v(e,i);r||=s==="r"||s==="R",o||=s==="f"||s==="F"}return{recursive:r,force:o}}function Pl(e,t,n,r){let o=n-t-2;if(o<1||o>r.length||!Y(e,t,"--"))return!1;for(let i=0;i<o;i++)if(v(e,t+i+2)!==r[i])return!1;return!0}function qp(e){let t=!1;for(let n=0;n<X(e);n++){if(te(v(e,n))){t=!1;continue}if(ut(e,n,"dd")){t=!0,n++;continue}if(!t||!ut(e,n,"of")||!Y(e,n,"of=/dev/"))continue;let r=n+8;if(r<X(e)&&!K(v(e,r))&&v(e,r)!=="'"&&v(e,r)!=='"')return!0}return!1}function Kp(e){let t=!1,n=!1,r=!1;for(let o=0;o<=X(e);){let i=v(e,o);if(o===X(e)||te(i)){t=!1,n=!1,r=!1,o++;continue}let s=Zp(e,o);if(s>=0){if(Yp(e,s))return!0;let a=s,l=!1;while(K(v(e,a)))l||=v(e,a)===`
7
+ `,a++;if(l)n=!1,r=!1;t=!0,o=a;continue}if(!t){o++;continue}if(Y(e,o,"--")&&(o===0||K(v(e,o-1)))&&(!v(e,o+2)||K(v(e,o+2))||te(v(e,o+2)))){t=!1,n=!1,r=!1,o+=2;continue}if(n||=Y(e,o,"--recursive")&&dt(e,o+11)||Vi(e,o,"recursive"),r||=Y(e,o,"--force")&&dt(e,o+7)||Vi(e,o,"force"),n&&r)return!0;o++}return!1}function Vi(e,t,n){if(!Y(e,t,"--"))return!1;let r=0;while(r<=n.length){let o=v(e,t+r+2);if(!o||K(o)||te(o))break;if(o!==n[r])return!1;r++}return r>0&&dt(e,t+r+2)}function Yp(e,t){let n=t,r=!1,o=!1;while(n<X(e)){while(K(v(e,n)))n++;let i=n;while(n<X(e)&&!K(v(e,n)))n++;if(v(e,i)!=="-"||n-i===2&&Y(e,i,"--"))return!1;let s=_l(e,i,"recursive"),a=_l(e,i,"force");if(r&&a||o&&s)return!0;if(r||=s,o||=a,v(e,i+1)==="-")continue;let l=Xp(e,i,n);if(l.combined||r&&l.forceAtBoundary||o&&l.recursiveAtBoundary)return!0;r||=l.recursive,o||=l.force}return!1}function _l(e,t,n){return Y(e,t,`--${n}`)&&dt(e,t+n.length+2)||Vi(e,t,n)}function Zp(e,t){if(t>0&&Ot(v(e,t-1)))return-1;let n=t;if(v(e,n)==="\\")n++;if(v(e,n)!=="r")return-1;if(n++,v(e,n)==="\\")n++;if(v(e,n)!=="m"||!K(v(e,n+1)))return-1;return n+1}function Xp(e,t,n){let r=!1,o=!1,i=!1,s=!1,a=!1;if(v(e,t)!=="-")return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a};let l="";for(let c=t+1;c<n;c++){let u=v(e,c)??"",m=(u==="r"||u==="f")&&dt(e,c+1);r||=u==="r",o||=u==="f",i||=u==="r"&&m,s||=u==="f"&&m,a||=(l==="r"&&u==="f"||l==="f"&&u==="r")&&m,l=u}return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a}}function Al(e,t,n){return Un(e,"reset",on,!0,(r)=>v(e,r)==="-"&&sn(e,r,t,n)?!0:r)}function Jp(e){return Un(e,"clean",on,!0,(t)=>{if(v(e,t)!=="-")return t;if(sn(e,t,"--fo","rce"))return!0;let n=Bn(e,t,on);for(let r=t+1;r<n;r++)if(v(e,r)==="f")return!0;return n-1})}function qr(e,t,n){if(!ut(e,t,"git"))return null;let r=t+3;if(!K(v(e,r)))return{commandEnd:-1,next:r};while(K(v(e,r)))r++;while(r<X(e)){if(te(v(e,r)))return{commandEnd:-1,next:r};let o=Bn(e,r,te);if(ut(e,r,n))return{commandEnd:r+n.length,next:o};if(v(e,r)!=="-")return{commandEnd:-1,next:o};let i=o-r===2&&Y(e,r,"--"),s=Qp(e,r,o);r=o;while(K(v(e,r)))r++;if(i)return{commandEnd:ut(e,r,n)?r+n.length:-1,next:Bn(e,r,te)};if(!s)continue;if(r>=X(e)||te(v(e,r)))return{commandEnd:-1,next:r};r=Bn(e,r,te);while(K(v(e,r)))r++}return{commandEnd:-1,next:r}}function Qp(e,t,n){for(let r of Ye)if(n-t===r.length&&Y(e,t,r))return!0;return!1}function eg(e){return kl(e,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function tg(e){return Un(e,"push",on,!0,(t)=>{if(v(e,t)!=="-")return t;if(v(e,t+1)==="f"&&!Ot(v(e,t+2))&&!Y(e,t+2,"-with-lease"))return!0;let n=Il(e,t,"--fo","rce");if(n>=0&&!Y(e,n,"-with-lease"))return!0;return t})}function ng(e){return Un(e,"push",te,!1,(t)=>{if(K(v(e,t))&&v(e,t+1)==="+"&&t+2<X(e)&&!te(v(e,t+2))&&!K(v(e,t+2)))return!0;if(v(e,t)===":"&&v(e,t+1)==="+")return!0;return t})}function rg(e){return Un(e,"push",te,!1,(t)=>{if(v(e,t)==="-"&&sn(e,t,"--de","lete"))return!0;if(K(v(e,t))&&v(e,t+1)===":"&&t+2<X(e)&&!K(v(e,t+2))&&!te(v(e,t+2)))return!0;return t})}function og(e){let t=!1,n=!1,r=!1;for(let o=0;o<=X(e);o++){if(o===X(e)||te(v(e,o))){if(n&&r)return!0;t=!1,n=!1,r=!1;continue}if(!t){let a=qr(e,o,"branch");if(a){t=a.commandEnd>=0,o=Math.max(o,(t?a.commandEnd:a.next)-1);continue}}if(!t||v(e,o)!=="-")continue;let i=Bn(e,o,te),s=ig(e,o,i);if(n||=s.deletion,r||=s.force,n&&r)return!0;o=i-1}return!1}function ig(e,t,n){let r=!1,o=!1;for(let i=t;i<n;i++){if(v(e,i)!=="-")continue;if(sn(e,i,"--de","lete"))r=!0;if(sn(e,i,"--fo","rce"))o=!0;if(v(e,i+1)==="-")continue;let s=i+1,a=!1,l=!1,c=!1;while(s<n&&sg(v(e,s))){let u=v(e,s);a||=u==="d"||u==="D",l||=u==="f",c||=u==="D",s++}if(!dt(e,s))continue;r||=a,o||=l||c}return{deletion:r,force:o}}function sg(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function ag(e){return kl(e,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function kl(e,t){let n=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let r=0;r<X(e);r++){let o=v(e,r),i=n[n.length-1];if(!i)return!1;let s=i.escaped;if(i.escaped=!s&&i.quote!=="'"&&o==="\\",!s&&o==="'"&&i.quote!=='"')i.quote=i.quote==="'"?"":"'";if(!s&&o==='"'&&i.quote!=="'")i.quote=i.quote==='"'?"":'"';if(o==="$"&&v(e,r+1)==="("&&(n.length===1||!s&&i.quote!=="'")){n.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),r++;continue}if(!s&&!i.quote&&n.length>1&&o==="("){i.depth++;continue}if(!s&&!i.quote&&n.length>1&&o===")"){if(i.depth--,i.depth===0)n.pop();continue}if(K(o))i.shortActive=!1,i.hasShortFlag=!1;if(!i.outerActive){let a=qr(e,r,t.command);if(a){i.outerActive=a.commandEnd>=0&&K(v(e,a.commandEnd)),i.shortActive=!1,i.hasShortFlag=!1,r=Math.max(r,(i.outerActive?a.commandEnd:a.next)-1);continue}}if(i.outerActive&&o==="-"){if(sn(e,r,t.longPrefix,t.longOptional))return!0;i.shortActive||=!t.excludedShortStarts.includes(v(e,r+1)??"")}if(i.hasShortFlag||=i.shortActive&&o===t.shortFlag,i.hasShortFlag&&dt(e,r+1))return!0;if(on(o))i.outerActive=!1}return!1}function Un(e,t,n,r,o){let i=!1;for(let s=0;s<X(e);s++){let a=v(e,s),l=n(a);if(!i&&!l){let c=qr(e,s,t);if(c){i=c.commandEnd>=0&&(!r||K(v(e,c.commandEnd))),s=Math.max(s,(i?c.commandEnd:c.next)-1);continue}}if(i){let c=o(s);if(c===!0)return!0;for(let u=s;u<=c;u++)if(n(v(e,u)))i=!1;s=c}if(l)i=!1}return!1}function lg(e){let t=!1;for(let n=0;n<X(e);n++){if(ji(v(e,n))){if(t)return!0;t=!1;continue}if(!t){let r=qr(e,n,"restore");if(r){t=r.commandEnd>=0,n=Math.max(n,(t?r.commandEnd:r.next)-1);continue}}if(t&&v(e,n)==="-"&&v(e,n+1)==="-"&&(Y(e,n+2,"staged")||Y(e,n+2,"help")))t=!1}return t}function Tl(e,t){let n=!1;for(let r=0;r<X(e);r++){let o=v(e,r),i=t?ji(o):te(o);if(n&&K(o)&&v(e,r+1)==="-"&&ut(e,r+2,"delete"))return!0;if(i){n=!1;continue}if(ut(e,r,"find"))n=!0,r+=3}return!1}function Bn(e,t,n){let r=t;while(r<X(e)&&!K(v(e,r))&&!n(v(e,r)))r++;return r}function Il(e,t,n,r){if(!Y(e,t,n))return-1;let o=t+n.length;for(let i=0;i<r.length&&v(e,o)===r[i];i++)o++;return dt(e,o)?o:-1}function sn(e,t,n,r){return Il(e,t,n,r)>=0}var cg=["git.ssh-env","git.alias-config","git.checkout-force","git.checkout-double-dash","git.checkout-ref-path","git.checkout-pathspec-from-file","git.checkout-ambiguous","git.switch-discard-changes","git.switch-force","git.restore-worktree","git.restore-unstaged","git.reset-hard","git.reset-merge","git.clean-force","git.rm-force","git.push-force","git.push-delete","git.push-mirror","git.branch-force-delete","git.rebase-abort","git.merge-abort","git.tag-delete","git.reflog-delete","git.stash-drop","git.stash-clear","git.worktree-remove-force","rm.recursive-force-root-or-home","rm.git-metadata","rm.recursive-force-dynamic-target","rm.recursive-force-home-cwd","rm.recursive-force-cwd-self","rm.recursive-force-outside-cwd","rm.recursive-force-paranoid","powershell.remove-item-root-or-home","powershell.remove-item-recursive-force-root-or-home","powershell.remove-item-git-metadata","powershell.remove-item-recursive-force-dynamic-target","powershell.remove-item-recursive-force-home-cwd","powershell.remove-item-recursive-force-cwd-self","powershell.remove-item-recursive-force-outside-cwd","powershell.remove-item-recursive-force-paranoid","powershell.remove-item-pipeline-dynamic-target","find.delete","find.delete-git-metadata","find.exec-rm-recursive-force","dd.device-write","mkfs.device","shred.target","interpreter.dangerous-command","interpreter.one-liner-paranoid","awk.system-dynamic","xargs.rm-recursive-force-dynamic","xargs.shell-dynamic","parallel.rm-recursive-force-dynamic","parallel.shell-dynamic","parallel.command-stream-dynamic","shell.dynamic-structure","shell.dynamic-executable","raw-text.dangerous-command"],Kr=new Set(cg),Yr=[{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"}],ug=new Map(Yr.map((e)=>[e.id,e.intent])),Ol=new Set(Yr.filter((e)=>e.catastrophic).map((e)=>e.id));function b(e,t){return{id:e,reason:t,intent:ug.get(e)??"manual_only"}}function k(e,t){if(!e)return null;if(Ol.has(e.id))return e;if(t?.destructiveCommandProtectionEnabled===!1)return null;let n=t?.effectiveDestructiveCommandRules[e.id];return n&&!n.enabled?null:e}function Q(e,t,n){if(Ol.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function qi(e,t){return Object.freeze(Object.fromEntries(Yr.map((n)=>{let r=n.activationCapability?t[n.activationCapability]:void 0,o=r?.enabled??!0,i=e.destructiveCommandRuleOverrides[n.id],s=n.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...i?{override:i}:{}}:e.destructiveCommandProtectionEnabled?i?{enabled:i==="on",inheritedEnabled:o,changesInherited:i==="on"!==o,source:"rule_override",...n.activationCapability?{activationCapability:n.activationCapability}:{},override:i}:{enabled:o,inheritedEnabled:o,changesInherited:!1,source:r?.source??"built_in_default",...n.activationCapability?{activationCapability:n.activationCapability}:{}}:{enabled:!1,inheritedEnabled:o,changesInherited:!1,source:"master_disabled",...n.activationCapability?{activationCapability:n.activationCapability}:{},...i?{override:i}:{}};return[n.id,Object.freeze(s)]})))}function Ml(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:qi(e,t)})}function mt(e,t){$n(t,e,2);let n=e.toLowerCase(),r=n.trimStart(),o=r.startsWith("echo ")||r.startsWith("rg "),i=[{scan:"rm",label:"rm -rf"},{scan:"reset-hard",label:"git reset --hard"},{scan:"reset-merge",label:"git reset --merge"},{scan:"clean",label:"git clean -f"},{scan:"checkout",label:"git checkout --force"},{scan:"push-force",label:"git push --force"},{scan:"push-refspec",label:"git push --force"},{scan:"push-delete",label:"git push delete"},{scan:"branch",label:"git branch -D",caseSensitive:!0},{scan:"tag",label:"git tag -d"},{regex:/\bgit\s+stash\s+(drop|clear)\b/,label:"git stash drop/clear"},{regex:/\bgit\s+checkout\s+--\s/,label:"git checkout --"},{scan:"restore",label:"git restore without --staged"},{scan:"find",label:"find -delete",skipForEchoRg:!0},{regex:/\bdd\b[^\n|;&]*\bof=\/dev\/\S/,label:"dd of=/dev/",skipForEchoRg:!0},{regex:/\bmkfs(?:\.[a-z0-9_-]+)?\s+\/dev\/\S/,label:"mkfs /dev/",skipForEchoRg:!0},{regex:/\bshred\b\s+\S/,label:"shred",skipForEchoRg:!0}];for(let s of i){if(s.skipForEchoRg&&o)continue;let a=s.caseSensitive?e:n;if(s.regex)ge(t,a);if((s.regex?.test(a)??!1)||s.scan&&Vr(a,s.scan,t))return b("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${s.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var dg=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ll(e,t,n){let r=e.words[0];if(!t||!r||e.words.length!==1||e.dialect!=="posix")return!1;if(!r.quoted||r.provenance!=="literal")return!1;let o=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r.text)?.[1];if(!o)return!1;$n(n,t.source,2);let i={anchored:new RegExp(`^\\$\\{?${o}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${o}(?![A-Za-z0-9_])`)};return Nl(t.nodes,r,i)}function Nl(e,t,n){return e.every((r)=>{if(r.kind==="connector")return!0;if(r.kind==="group"||r.kind==="function")return Nl(r.body.nodes,t,n);if(r.kind==="unknown")return!n.loose.test(r.source);return mg(r,t,n)})}function mg(e,t,n){if(e.nested.some((o)=>n.loose.test(o.source)))return!1;let r=e.words.findIndex((o)=>!dg.test(o.text));return e.words.every((o,i)=>o===t||Dl(o.raw,n.anchored,i!==r))&&e.redirections.every((o)=>(!o.heredoc||o.heredoc.quotedDelimiter||!n.loose.test(o.heredoc.body))&&(!o.target||Dl(o.target.raw,n.anchored,!0)))}function Dl(e,t,n){let r=!1,o=!1;for(let i=0;i<e.length;i++){let s=e[i];if(s==="\\"&&!r){i++;continue}if(!o&&s==="'"){r=!r;continue}if(!r&&s==='"'){o=!o;continue}if(r||s!=="$")continue;if(!t.test(e.slice(i)))continue;if(!o||!n)return!1}return!0}var Wl=Object.freeze({maxDerivedTokens:16384}),Fl="Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry.";class he 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 Zr(){return{derivedTokens:0}}function Le(e,t){if(!Number.isSafeInteger(e.derivedTokens)||e.derivedTokens<0||e.derivedTokens>Wl.maxDerivedTokens||!Number.isSafeInteger(t)||t<0||t>Wl.maxDerivedTokens-e.derivedTokens)throw new he;e.derivedTokens+=t}import{isAbsolute as yg,resolve as zl}from"node:path";import{basename as fg,dirname as pg,join as Ki}from"node:path";var an=Object.freeze({maxEnvironmentExpansionDepth:64,maxMissingSuffixComponents:256,maxRealpathAttempts:16384,maxProcessedCandidateBytes:4194304});class Pe extends Error{name="PathCanonicalizationLimitError";constructor(){super("Path canonicalization work limit exceeded.")}}function Jr(){return{realpathAttempts:0,processedCandidateBytes:0,resolvedPaths:new Map}}function Mt(e){return{...Jr(),environment:e}}var Xr=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 Qr(e,t){return Yi(e,0,t)}function Yi(e,t,n){let r="",o=0;while(o<e.length){if(e[o]!=="$"){r+=e[o],o++;continue}if(e[o+1]==="{"){let s=Zi(e,o+2),a=gg(e,o,t);if(a===null){if(Xr.has(s))throw new Pe;r+=e.slice(o);break}let l=e.slice(o,a+1);r+=hg(l,t,n),o=a+1;continue}let i=Zi(e,o+1);if(!i){r+="$",o++;continue}r+=Xi(i,n)??`$${i}`,o+=i.length+1}return r}function gg(e,t,n){let r=1;for(let o=t+2;o<e.length;o++){if(e[o]==="\\"){o++;continue}if(e[o]==="$"&&e[o+1]==="{"){if(r++,n+r>an.maxEnvironmentExpansionDepth)throw new Pe;o++;continue}if(e[o]!=="}")continue;if(r--,r===0)return o}return null}function hg(e,t,n){let r=e.slice(2,-1),o=Zi(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return Xi(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(Xr.has(o))throw new Pe;return e}if(!Xr.has(o))return e;if(s.endsWith("="))throw new Pe;let a=Xi(o,n),l=s.startsWith(":")?a!==null&&a!=="":a!==null;if(s.endsWith("?")&&!l)throw new Pe;if(s.endsWith("-")||s.endsWith("?"))return l?a??"":Yi(i.slice(s.length),t+1,n);return l?Yi(i.slice(s.length),t+1,n):""}function Zi(e,t){if(!/[A-Za-z_]/.test(e[t]??""))return"";let n=t+1;while(/[A-Za-z0-9_]/.test(e[n]??""))n++;return e.slice(t,n)}function H(e,t,n=Jr()){if(!e)return e;let r=n.resolvedPaths.get(e);if(r!==void 0)return r;let o=[],i=e;while(!0){if(n.realpathAttempts++,n.processedCandidateBytes+=Buffer.byteLength(i),n.realpathAttempts>an.maxRealpathAttempts||n.processedCandidateBytes>an.maxProcessedCandidateBytes)throw new Pe;let s=t.realpath(i);if(s!==null){let l=o.length===0?s:Ki(s,...o.reverse());return n.resolvedPaths.set(e,l),l}let a=pg(i);if(a===i){let l=o.length===0?i:Ki(i,...o.reverse());return n.resolvedPaths.set(e,l),l}if(o.length>=an.maxMissingSuffixComponents){let l=Ki(i,...o.reverse());return n.resolvedPaths.set(e,l),l}o.push(fg(i)),i=a}}function Gl(e,t,n){let r=n.resolvedPaths.get(e);if(r!==void 0)return r;if(n.realpathAttempts++,n.processedCandidateBytes+=Buffer.byteLength(e),n.realpathAttempts>an.maxRealpathAttempts||n.processedCandidateBytes>an.maxProcessedCandidateBytes)throw new Pe;let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function Xi(e,t){if(!Xr.has(e))return null;if(e==="HOME")return t.env.get("HOME")??t.home;return t.env.get(e)??null}var $l=64;function Hn(e,t,n){let r=yg(e)?zl(e):t?zl(t,e):void 0;if(!r)return;try{return H(r,n)}catch{return r}}function Bl(e){return!["/dev","/proc","/sys"].some((t)=>e===t||e.startsWith(`${t}/`))}function z(e){return D(e).toLowerCase()}function D(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}var eo=10,ln=20,Dt=/^[a-zA-Z][a-zA-Z0-9_-]*$/,cn=256,ee=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Ul=new Set(["python","python3","python2","node","ruby","perl"]),Hl=/^python(?:[23](?:\.\d+)*)?$/,to=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 Lt="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",un="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.",no=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),Cg=new Set(["-p","--print"]),bg=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),Sg=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"])]]),vg=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),Rg=new Map([["python",new Set(["m"])]]),xg=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"])]]),Eg=new Set(["always","default","never"]),wg=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),Pg=/\\\r?\n/g,_g=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 ro(e){return io(e).code}function oo(e){return io(e).sources}function Vl(e){return _g.get(ao(e))??[]}function io(e){let t=ao(e[0]??"");if(!no.has(t))return{code:null,sources:[],optionsOpen:!1};let n=[],r=[],o=!0;for(let i=1;i<e.length;i++){let s=e[i];if(s===void 0)break;if(s==="--")return Ne(t,n,r,o,e[i+1]===void 0?void 0:i+1,e[i+1]);if(s===""||s==="-"||!s.startsWith("-"))return Ne(t,n,r,o,i,s);if(t==="node"&&Cg.has(s)){let m=e[i+1];if(m===void 0)return Ne(t,n,r,o);if(m.startsWith("-"))continue;n.push({tokenIndex:i+1,value:m}),r.push({tokenIndex:i+1,kind:"inline-code",value:m}),i++;continue}if(kg(t,s)){let m=e[i+1];if(m===void 0)return Ne(t,n,r,o);if(n.push({tokenIndex:i+1,value:m}),r.push({tokenIndex:i+1,kind:"inline-code",value:m}),t==="python")return Ne(t,n,r,o);i++;continue}let a=/^--eval=(.*)$/s.exec(s);if(Tg(t)&&a){let m=a[1]??"";n.push({tokenIndex:i,value:m}),r.push({tokenIndex:i,kind:"inline-code",value:m});continue}if(t==="node"){let m=Ag(s);if(m){if(m.attached){if(o&&=m.value!=="",m.value!=="")r.push({tokenIndex:i,kind:"module-file",value:m.value});continue}let f=e[i+1];if(f===void 0||f.startsWith("-"))return o=!1,Ne(t,n,r,o);r.push({tokenIndex:i+1,kind:"module-file",value:f}),i++;continue}}if(t==="python"&&s.startsWith("--check-hash-based-pycs=")||t==="node"&&(s==="--conditions="||s==="--diagnostic-dir="||s==="--title=")||t==="ruby"&&(s==="--disable="||s==="--enable="))return Ne(t,n,r,o);if(xg.get(t)?.has(s)){let m=e[i+1];if(m===void 0||m.startsWith("-")&&!(t==="ruby"&&wg.has(s))||t==="python"&&!Eg.has(m))return Ne(t,n,r,o);i++;continue}if(s.startsWith("--"))continue;let l,c=!1;for(let m=1;m<s.length;m++){let f=s[m];if(f===void 0)break;if(Rg.get(t)?.has(f)){let d=s.slice(m+1),p=d||e[i+1];if(p!==void 0)r.push({tokenIndex:d?i:i+1,kind:"module-file",value:p});return Ne(t,n,r,o)}if(bg.get(t)?.has(f)){l=s.slice(m+1)||e[i+1],c=m+1===s.length;break}if(t==="node"&&f==="r"){if(s==="-r"){let d=e[i+1];if(o&&=d!==void 0&&!d.startsWith("-"),o&&d!==void 0)r.push({tokenIndex:i+1,kind:"module-file",value:d});i++}else o=!1;break}if(t==="ruby"&&f==="r"){let d=s.slice(m+1),p=d||e[i+1];if(o&&=p!==void 0,p!==void 0)r.push({tokenIndex:d?i:i+1,kind:"module-file",value:p});if(!d)i++;break}if(t==="perl"&&(f==="M"||f==="m")){let d=s.slice(m+1);if(d)r.push({tokenIndex:i,kind:"module-file",value:d});else if(o=!1,m+1===s.length)i++;break}if(Sg.get(t)?.has(f)){if(m+1===s.length)i++;break}if(vg.get(t)?.has(f)&&m+1<s.length)break}if(l===void 0)continue;let u=c?i+1:i;if(n.push({tokenIndex:u,value:l}),r.push({tokenIndex:u,kind:"inline-code",value:l}),t==="python")return Ne(t,n,r,o);if(c)i++}return Ne(t,n,r,o,void 0,void 0,!0)}function Ne(e,t,n,r,o,i,s=!1){let a=e==="node"?t.slice(-1):t,l=new Set(a.map((u)=>u.tokenIndex)),c=n.filter((u)=>u.kind!=="inline-code"||l.has(u.tokenIndex));if(r&&t.length===0&&o!==void 0&&i!==void 0)c.push({tokenIndex:o,kind:"main-script",value:i});return{code:(e==="node"?a[0]?.value:a.map((u)=>u.value).join(`
8
+ `))||null,sources:r?c:[],optionsOpen:r&&s}}function Ag(e){for(let t of["--import","--loader","--experimental-loader","--require"]){if(e===t)return{attached:!1,value:""};if(e.startsWith(`${t}=`))return{attached:!0,value:e.slice(t.length+1)}}return}function ye(e){return no.has(ao(e))}function so(e,t){return ao(e)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(t)}function ao(e){let t=D(e).toLowerCase();return Hl.test(t)?"python":t}function kg(e,t){return no.get(e)?.has(t)??!1}function Tg(e){return no.get(e)?.has("--eval")??!1}function dn(e,t){let n=Mg(e,t);if(!jl(n,t))return!1;ge(t,n);let r=Og(n);if(jl(r,t))return!0;return ge(t,r),Ig.test(r)}var Ig=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function Og(e){let t=[],n=0,r=0;while(r<e.length){let o=e[r];if(o!=="'"&&o!=='"'){r++;continue}let i=e.startsWith(o.repeat(3),r)?o.repeat(3):o,s=r+i.length;while(s<e.length&&!e.startsWith(i,s))s+=e[s]==="\\"?2:1;if(s>=e.length)break;t.push(e.slice(n,r)," "),r=s+i.length,n=r}return t.push(e.slice(n)),t.join("")}function jl(e,t){if(jr(e,"rm",t))return!0;for(let r of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(ge(t,e),r.test(e))return!0;if(jr(e,"dd",t))return!0;for(let r of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(ge(t,e),r.test(e))return!0;if(jr(e,"find",t))return!0;let n=e.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((r)=>(ge(t,e),n.some((o)=>Vr(o,r))))}function Mg(e,t){return ge(t,e),e.replace(Pg,"")}var B=Object.freeze({maxChildAnalyses:1024,maxDerivedTokens:16384,maxDerivedBytes:1048576,maxPlaceholderReplacements:16384}),ql="Parallel command expands beyond CC Safety Net's analysis limits. Reduce the template or explicit argument list and retry.";class co 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 Kl(){return{childAnalyses:0,derivedTokens:0,derivedBytes:0,placeholderReplacements:0}}function Ce(e,t){let n=t.childAnalyses??0,r=t.derivedTokens??0,o=t.derivedBytes??0,i=t.placeholderReplacements??0;if(lo(e.childAnalyses,n,B.maxChildAnalyses)||lo(e.derivedTokens,r,B.maxDerivedTokens)||lo(e.derivedBytes,o,B.maxDerivedBytes)||lo(e.placeholderReplacements,i,B.maxPlaceholderReplacements))throw new co;e.childAnalyses+=n,e.derivedTokens+=r,e.derivedBytes+=o,e.placeholderReplacements+=i}function lo(e,t,n){return!Number.isSafeInteger(e)||e<0||e>n||!Number.isSafeInteger(t)||t<0||t>n-e}import{isAbsolute as _s,normalize as jy,parse as Vy,posix as pu,resolve as yn,sep as Ps}from"node:path";import{isAbsolute as Dg,join as Yl,normalize as Jl,parse as Lg,sep as Zl}from"node:path";var Ng=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],Wg=`
9
+ `;function jn(e,t){if(Ze(e,t))return!0;if(!e.has("TMPDIR"))return!1;return!Ji(e.get("TMPDIR")??"",t)}function ft(e,t){if(e.has("TMPDIR"))return Ji(e.get("TMPDIR")??"",t);let n=Qi(e,t);if(n===void 0)return!0;return Ji(n,t)}function Qi(e,t){return tc(e,t,"TMPDIR")}function Ji(e,t){if(!e)return!1;if(Gg(e))return!1;return es(e,t)}function Ze(e,t){let n=tc(e,t,"IFS");return n!==void 0&&n!==""&&n!==Wg}function es(e,t){let n=uo(e,t.paths);return n!==null&&ec(t).some((r)=>$g(n,r))}function Ql(e,t){let n=uo(e,t.paths);return n!==null&&ec(t).includes(n)}var Xl=new WeakMap;function ec(e){let t=Xl.get(e);if(t)return t;let n=Fg(e);return Xl.set(e,n),n}function Fg(e){let t=Ng.map((r)=>uo(r,e.paths)??Jl(r)),n=uo(e.tmpdir,e.paths);if(!n)return t;if(process.platform==="win32")return[...t,n];if(process.platform==="darwin"&&zg(n))return[...t,n];return t}function Gg(e){return/[\s$`*?[]/.test(e)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(e)||/[+@!]\([^)]*\)/.test(e)}function tc(e,t,n){return e.has(n)?e.get(n):t.env.get(n)}function zg(e){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(e)}function uo(e,t){try{let n=Jl(e);if(!Dg(n))return n;let r=Lg(n).root,o=n.slice(r.length).split(/[\\/]+/).filter(Boolean),i=r;for(let s=0;s<o.length;s++){let a=Yl(i,o[s]??"");if(t.entryKind(a)==="missing")return Yl(a,...o.slice(s+1));let l=t.realpath(a);if(l===null)return null;i=l}return i}catch{return null}}function $g(e,t){if(e===t)return!0;let n=t.endsWith(Zl)?t:`${t}${Zl}`;return e.startsWith(n)}import{statSync as Ty}from"node:fs";import{isAbsolute as iu,join as Iy,relative as su}from"node:path";import{isAbsolute as nc,parse as Bg}from"node:path";var oc=/^[A-Za-z_][A-Za-z0-9_]*=/;function _e(e){if(!oc.test(e))return null;let t=e.indexOf("=");return{name:e.slice(0,t),value:e.slice(t+1)}}function mo(e){let t=new Map,n=0;while(n<e.length){let r=e[n];if(!r)break;let o=_e(I(r));if(!o)break;t.set(o.name,o.value),n++}return{words:e.slice(n),envAssignments:t}}function ic(e){let t=e.toLowerCase();return e.includes("=")||t==="sudo"||t==="env"||t==="command"||t==="builtin"}function Nt(e,t,n,r){if(!ic(mn(e)))return{words:e,envAssignments:new Map,cwd:n,rewritten:!1};let o=new Set(e),i=e,s=new Map,a=new Map(r??[]),l=[],c=n;for(let m=0;m<ln;m++){let f=rc(i),d=mo(i);for(let[g,y]of d.envAssignments)s.set(g,y),a.set(g,y);if(i=d.words,i.length===0)break;while(i.length>0&&mn(i).includes("=")&&!Hg(i)){let g=jg(mn(i),a,t.env)??$r(mn(i),t.env,a);if(g)s.set(g.name,g.value),a.set(g.name,g.value);i=i.slice(1)}if(i.length===0)break;let p=mn(i).toLowerCase();if(p!=="sudo"&&p!=="env"&&p!=="command"&&p!=="builtin")break;if(p==="sudo"){let g=qg(i,t.paths,c);if(i=g.words,g.cwd!==void 0)c=g.cwd}if(p==="env"){let g=Zg(i,c,a,t);if(l.push(...g.envSplitValues??[]),i=g.words,g.cwd!==void 0)c=g.cwd;for(let[y,h]of g.envAssignments)s.set(y,h),a.set(y,h)}if(p==="command")i=Xg(i);if(p==="builtin")i=i.slice(We(i,1)==="--"?2:1);if(rc(i)===f)break}let u=mo(i);for(let[m,f]of u.envAssignments)s.set(m,f),a.set(m,f);return{words:u.words,envAssignments:s,cwd:c,envSplitValues:l.length>0?l:void 0,rewritten:Ug(u.words,o)}}function Ug(e,t){return e.some((n)=>!t.has(n))}function rc(e){return e.map(I).join(" ")}function mn(e){let t=e[0];return t?I(t):""}function We(e,t){let n=e[t];return n?I(n):void 0}function Hg(e){return oc.test(mn(e))}function jg(e,t,n){if(!e.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${t.get("TMPDIR")??n.get("TMPDIR")??""}${e.slice(8)}`}}var Vg=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function qg(e,t,n){let r=1,o=n;while(r<e.length){let i=We(e,r);if(!i)break;if(i==="--")return{words:e.slice(r+1),cwd:o};if(!i.startsWith("-"))break;if(i==="-D"||i==="--chdir"){let s=We(e,r+1);o=s?Vn(o,s,t):null,r+=2;continue}if(i.startsWith("--chdir=")){o=Vn(o,i.slice(8),t),r++;continue}if(i.startsWith("-D")&&i.length>2){o=Vn(o,i.slice(2),t),r++;continue}if(i==="-i"||i==="--login"){o=null,r++;continue}if(Vg.has(i)){r+=2;continue}r++}return{words:e.slice(r),cwd:o}}var Kg=new Set(["-i","-0","--null"]),Yg=new Set(["-u","--unset","-C","--chdir","-P"]);function Zg(e,t,n,r){let o=new Map,i=[],s=t,a=1,l=(c)=>({words:e.slice(c),envAssignments:o,cwd:s,envSplitValues:i.length>0?i:void 0});while(a<e.length){let c=We(e,a);if(!c)break;if(c==="--")return l(a+1);if(c==="-i"||c==="--ignore-environment"||c==="-"){o.clear();for(let m of n.keys())o.set(m,"");o.set("TMPDIR",""),a++;continue}if(Kg.has(c)){a++;continue}if(c==="-u"||c==="--unset"){let m=We(e,a+1);if(m!==void 0)o.set(m,"");a+=2;continue}if(c.startsWith("-u")&&c.length>2&&!c.startsWith("-u=")){o.set(c.slice(2),""),a++;continue}if(c.startsWith("--unset=")){o.set(c.slice(8),""),a++;continue}let u=c==="-S"||c==="--split-string"?{value:We(e,a+1),consumed:2}:c.startsWith("-S")&&c.length>2?{value:c.slice(2),consumed:1}:c.startsWith("--split-string=")?{value:c.slice(15),consumed:1}:null;if(u){if(u.value!==void 0)i.push(u.value);return s=null,l(a+u.consumed)}if(Yg.has(c)){if(c==="-C"||c==="--chdir"){let m=We(e,a+1);s=m?Vn(s,m,r.paths):null}a+=2;continue}if(c.startsWith("-u=")){a++;continue}if(c.startsWith("-C")&&c.length>2||c.startsWith("--chdir=")){let m=c.startsWith("--chdir=")?c.slice(8):c.startsWith("-C=")?c.slice(3):c.slice(2);s=Vn(s,m,r.paths),a++;continue}if(c.startsWith("-P")){a++;continue}if(c.startsWith("-")){a++;continue}if(!_e(c))break;while(a<e.length){let m=_e(We(e,a)??"");if(!m)break;o.set(m.name,m.value),a++}if(We(e,a)==="--")a++;return l(a)}return l(a)}function Vn(e,t,n){if(t==="")return null;if(!e&&!nc(t))return null;let r=nc(t)?Bg(t).root:n.realpath(e??"/");if(r===null)return null;try{return bt(r,t,n)}catch{return null}}function Xg(e){if(We(e,1)==="-v")return[...G(["type"]),...e.slice(2)];let t=1;while(t<e.length){let n=We(e,t);if(!n)break;if(n==="-p"||n==="-v"||n==="-V"){t++;continue}if(n==="--")return e.slice(t+1);if(n.startsWith("-")&&!n.startsWith("--")&&n.length>1){if(!/^[pvV]+$/.test(n.slice(1)))break;t++;continue}break}return e.slice(t)}var Jg=/['"\\$`{}#]/;function fo(e,t){if(e.some((r)=>Jg.test(r)))return null;let n=[...e.flatMap((r)=>r.split(/\s+/).filter((o)=>o.length>0)),...t];return n.length<=64?n:null}function fn(e,t,n){return po(e,t,n).tokens}function Qg(e){let t=[],n="",r=0;while(r<e.length){let o=e.charAt(r);if(o==='"'||o==="'"){let i=e.indexOf(o,r+1);if(i===-1)return e.split(/\s+/).map((s)=>s.replace(/["']/g,"")).filter((s)=>s.length>0);n+=e.slice(r+1,i),r=i+1;continue}if(/\s/.test(o)){if(n.length>0)t.push(n);n="",r++;continue}n+=o,r++}if(n.length>0)t.push(n);return t}function vt(e,t,n,r=0){let o=po(e,t,n),i=(o.envSplitValues??[]).flatMap(Qg);if(i.length===0)return o.tokens;let s=[...i,...o.tokens];if(r>=8)return s;return vt(s,t,n,r+1)}function po(e,t,n,r){if(!ic(e[0]??""))return{tokens:[...e],envAssignments:new Map,cwd:n};let o=Nt(G(e),t,n,r);return{tokens:o.words.map(I),envAssignments:o.envAssignments,cwd:o.cwd,envSplitValues:o.envSplitValues}}import{basename as Ey,isAbsolute as wy,normalize as Py,resolve as tu}from"node:path";function go(){return[]}function ho(){return[]}function yo(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function eh(e){return Object.freeze({...e,span:Object.freeze(e.span),words:Object.freeze(e.words),redirections:Object.freeze(e.redirections.map((t)=>Object.freeze({...t,span:Object.freeze(t.span),...t.heredoc?{heredoc:Object.freeze({...t.heredoc,bodySpan:Object.freeze(t.heredoc.bodySpan),terminatorSpan:Object.freeze(t.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(e.nested.map((t)=>ue(t)))})}function Co(e,t,n){e.push(n),t.reset()}function th(e,t,n,r,o){if(r<=n)return;e.push({raw:t.slice(n,r),span:{start:n,end:r},provenance:o})}function bo(e){let t=[];return{parts:t,push:(n,r,o)=>th(t,e,n,r,o)}}function ts(e){let t=e.parts??[{raw:e.raw,span:e.span,provenance:e.provenance}];return Object.freeze({kind:"word",...e,span:Object.freeze(e.span),parts:Object.freeze(t.map((n)=>Object.freeze({...n,span:Object.freeze(n.span)})))})}function pn(e,t,n,r,o,i,s){return ts({text:r,raw:e.slice(t,n),span:{start:t,end:n},provenance:o,quoted:i,...s?{parts:s}:{}})}function ue(e){return Object.freeze({...e,span:Object.freeze(e.span),issues:Object.freeze(e.issues.map((t)=>Object.freeze({...t,span:Object.freeze(t.span)}))),nodes:Object.freeze(e.nodes.map((t)=>{if(t.kind==="command")return eh(t);if(t.kind==="group"||t.kind==="function")return Object.freeze({...t,span:Object.freeze(t.span),body:ue(t.body)});return Object.freeze({...t,span:Object.freeze(t.span)})}))})}function ns(e,t,n){if(t>=n||ac(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!ac(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=sc(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=sc(e,s+1,n,'"');r+=l.text,i||=!l.closed,s=l.next;continue}if(a==="\\"){o=!0;let l=e[s+1];if(!l||l===`
10
+ `||l==="\r"){i=!0;break}r+=l,s+=2;continue}if(a==="`"||e.startsWith("$(",s)||e.startsWith("${",s)||e.startsWith("<(",s)||e.startsWith(">(",s))i=!0;r+=a,s++}return{delimiter:r,quoted:o,next:s,span:{start:t,end:s},ambiguous:i}}function rs(e,t,n,r){let o=[],i=t;for(let s of r){let a=i,l=!1;while(i<n){let c=nh(e,i,n);if((s.stripTabs?c.text.replace(/^\t+/,""):c.text)===s.delimiter){s.attach({body:s.stripTabs?rh(e.slice(a,i)):e.slice(a,i),delimiter:s.delimiter,quotedDelimiter:s.quotedDelimiter,bodySpan:{start:a,end:i},terminatorSpan:{start:i,end:c.contentEnd}}),i=c.next,l=!0;break}if(c.next<=i)break;i=c.next}if(l)continue;return o.push({code:"unterminated-heredoc",message:`heredoc delimiter ${s.delimiter} was not found`,span:s.declarationSpan}),{next:n,issues:o,terminated:!1}}return{next:i,issues:o,terminated:!0}}function sc(e,t,n,r){let o="",i=t;while(i<n&&e[i]!==`
11
+ `&&e[i]!=="\r"){let s=e[i]??"";if(s===r)return{text:o,next:i+1,closed:!0};if(r==='"'&&s==="\\"&&e[i+1]){let a=e[i+1]??"";o+=["$","`",'"',"\\"].includes(a)?a:`\\${a}`,i+=2;continue}o+=s,i++}return{text:o,next:i,closed:!1}}function ac(e){return/[\s;&|<>)]/u.test(e)||e==="`"}function nh(e,t,n){let r=t;while(r<n&&e[r]!==`
12
+ `&&e[r]!=="\r")r++;let o=r>=n?n:e[r]==="\r"&&e[r+1]===`
13
+ `?r+2:r+1;return{text:e.slice(t,r),contentEnd:r,next:o}}function rh(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var mc=new Set(["&&","||","|","|&"]);function fc(e,t,n){let r={start:0,end:e.length};if(e.length>n.maxInputLength)return ue({kind:"program",dialect:t,source:e,span:r,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${n.maxInputLength} UTF-16 code units`,span:r}],nodes:[]});let o=Ro(e,0,e.length,t,n,{used:0,max:n.maxWords},0);return ue({kind:"program",dialect:t,source:e,span:r,status:wo(o.issues,o.limited),issues:o.issues,nodes:o.nodes})}function Ro(e,t,n,r,o,i,s,a){let l=go(),c=ho(),u=yo(),m=[],f=()=>{if(u.words.length===0&&u.redirections.length===0)return;let p={start:u.start,end:u.end},g=u.words.map((y)=>y.text);Co(l,u,{kind:"command",dialect:r,source:e.slice(p.start,p.end),span:p,words:u.words,redirections:u.redirections,nested:u.nested,displayText:c.length>0&&l.length===0?e.slice(t,n):g.join(" ")})},d=t;while(d<n){let p=e[d];if(!p)break;if(a&&p===a)return f(),dc(l,c),{nodes:l,issues:c,next:d+1,closed:!0,limited:!1,pendingHeredocs:m};if(Eo(p)){if(p===`
14
+ `||p==="\r"){f();let P=p==="\r"&&e[d+1]===`
15
+ `?d+2:d+1,S=l.at(-1);if(S?.kind!=="connector"||!mc.has(S.operator))l.push(Object.freeze({kind:"connector",operator:e.slice(d,P),span:Object.freeze({start:d,end:P})}));if(m.length>0){let C=rs(e,P,n,m.splice(0));c.push(...C.issues),d=C.next;continue}d=P;continue}d++;continue}if(p==="#"){while(d<n&&e[d]!==`
16
+ `&&e[d]!=="\r")d++;continue}let g=u.start===-1?Rh(e,d,n):void 0;if(g){if(is(l,c,d),s>=o.maxDepth)return gn(l,c,d,"depth-limit",o.maxDepth);if(!os(i))return gn(l,c,d,"word-limit",o.maxWords);let P=Ro(e,g.braceIndex+1,n,r,o,i,s+1,"}"),S=P.next,C={start:g.braceIndex+1,end:P.closed?S-1:S},_=lc(e,r,C,P);if(l.push({kind:"function",name:g.name,span:{start:d,end:S},body:_}),c.push(...P.issues),P.pendingHeredocs.length>0||Kn(P.nodes))c.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely",span:{start:d,end:S}});if(m.push(...P.pendingHeredocs),P.limited)return vo(l,c,P.next);if(!P.closed)c.push({code:"unclosed-function-body",message:"function body is not closed",span:{start:g.braceIndex,end:S}});d=S;continue}let y=xo(e,d);if(y){if(f(),!vc(l.at(-1)))c.push({code:"unexpected-connector",message:`connector ${y} has no preceding command`,span:{start:d,end:d+y.length}});l.push(Object.freeze({kind:"connector",operator:y,span:Object.freeze({start:d,end:d+y.length})})),d+=y.length;continue}if(p===")"){f(),c.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis",span:{start:d,end:d+1}}),l.push({kind:"unknown",source:p,span:{start:d,end:d+1}}),d++;continue}if((p==="("||p==="{"&&uh(e,d,n))&&u.start===-1){if(is(l,c,d),s>=o.maxDepth)return gn(l,c,d,"depth-limit",o.maxDepth);let P=p==="("?")":"}",S=Ro(e,d+1,n,r,o,i,s+1,P),C=S.next,_={start:d+1,end:S.closed?C-1:C},E=lc(e,r,_,S);if(l.push({kind:"group",style:p==="("?"subshell":"brace",span:{start:d,end:C},body:E}),c.push(...S.issues),S.pendingHeredocs.length>0||Kn(S.nodes))c.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely",span:{start:d,end:C}});if(m.push(...S.pendingHeredocs),S.limited)return vo(l,c,S.next);if(!S.closed)c.push({code:p==="("?"unclosed-subshell":"unclosed-brace-group",message:`${p} group is not closed`,span:{start:d,end:C}});d=C;continue}let h=(p==="<"||p===">")&&e[d+1]!=="("?sh(e,d):null;if(h){let P=u.words.at(-1),S=P&&P.span.end===d&&/^[0-9]+$/.test(P.raw)?Number(P.raw):void 0;if(S!==void 0)u.words.pop();let C=S===void 0?d:P?.span.start??d;u.start=u.start===-1?d:u.start;let _=d+h.length;while(_<n&&/[ \t]/.test(e[_]??""))_++;let E=e[_],T=_>d+h.length&&E==="#",O=!E||Eo(E)||!!xo(e,_)||E===a||E===")"||T||(E==="<"||E===">")&&e[_+1]!=="(",M=h==="<<"||h==="<<-"?ns(e,_,n):void 0,F=M?{word:pn(e,_,M.next,M.delimiter,"literal",M.quoted),nested:[],issues:[],next:M.next,limited:!1}:!O?ss(e,_,n,r,o,i,s):void 0;if(F){if(c.push(...F.issues),F.limited)return vo(l,c,F.next);if(!os(i))return gn(l,c,F.next,"word-limit",o.maxWords)}let oe=F?.next??d+h.length,Ee={kind:"redirection",operator:h,span:{start:C,end:oe},...S===void 0?{}:{fd:S},...F?{target:F.word}:{}};if(u.redirections.push(Ee),h==="<<"||h==="<<-")if(!M)c.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word",span:{start:d,end:d+h.length}});else{if(M.ambiguous||M.delimiter.length===0)c.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely",span:M.span});m.push({delimiter:M.delimiter,quotedDelimiter:M.quoted,stripTabs:h==="<<-",declarationSpan:{start:C,end:oe},attach:(w)=>{Ee.heredoc=w}})}else if(!F)c.push({code:"missing-redirection-target",message:`redirection ${h} requires a target word`,span:{start:d,end:d+h.length}});if(F)u.nested.push(...F.nested);u.end=oe,d=oe;continue}if(u.start===-1)is(l,c,d);let R=ss(e,d,n,r,o,i,s);if(c.push(...R.issues),R.limited)return vo(l,c,R.next);let x=fh(u.words)?Ch(e,R.word,i.max-i.used,o.maxDepth,o.maxInputLength):void 0;if(x?.limitCode)return gn(l,c,R.next,x.limitCode,x.limitCode==="word-limit"?o.maxWords:x.limitCode==="depth-limit"?o.maxDepth:o.maxInputLength);let A=x?.words??[R.word];for(let P of A){if(!os(i))return gn(l,c,R.next,"word-limit",o.maxWords);u.words.push(P)}u.start=u.start===-1?d:u.start,u.end=R.next,u.nested.push(...R.nested),d=R.next>d?R.next:d+1}return f(),dc(l,c),c.push(...xh(m)),{nodes:l,issues:c,next:d,closed:a===void 0,limited:!1,pendingHeredocs:[]}}function lc(e,t,n,r){return{kind:"program",dialect:t,source:e.slice(n.start,n.end),span:n,status:wo(r.issues,r.limited),issues:r.issues,nodes:r.nodes}}function ss(e,t,n,r,o,i,s){let a="",l=t,c=!1,u="literal",m=[],f=[],d=!1;while(l<n){let p=e[l],g=(p==="<"||p===">")&&e[l+1]==="(";if(!p||Eo(p)||(p===";"||p==="|"||p==="&")&&xo(e,l)||(p==="<"||p===">")&&!g)break;if(p===")")break;if(p==="'"){c=!0;let h=e.indexOf("'",l+1);if(h===-1||h>=n){a+=e.slice(l+1,n),f.push({code:"unclosed-single-quote",message:"single-quoted word is not closed",span:{start:l,end:n}}),l=n;break}a+=e.slice(l+1,h),l=h+1;continue}if(p==='"'){c=!0;let h=oh(e,l,n,r,o,i,s);if(a+=h.text,m.push(...h.nested),f.push(...h.issues),d||=h.limited,u=qn(u,h.provenance),l=h.next,d)break;continue}if(e.startsWith("$'",l)){c=!0;let h=ah(e,l+2,n);if(a+=h.text,f.push(...h.issues),!h.closed)f.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed",span:{start:l,end:n}});l=h.next;continue}if(p==="\\"){let h=e[l+1];if(!h){f.push({code:"trailing-escape",message:"escape has no following character",span:{start:l,end:l+1}}),l++;break}if(h===`
17
+ `){l+=2;continue}a+=h,l+=2;continue}let y=p==="$"||p==="<"||p===">"||p==="`"?as(e,l,n,r,o,i,s):null;if(y){let h=pc(y,m,f);if(d||=h.limited,u=qn(u,h.provenance),l=h.next,d)break;continue}if(p==="$"){let h=yc(e,l,n,a,u);a=h.text,u=h.provenance,l=h.next;continue}if(p==="*"||p==="?"||p==="[")u=qn(u,"glob");a+=p,l++}return{word:pn(e,t,l,a,u,c,u==="literal"?void 0:ch(e,t,l)),nested:m,issues:f,next:l,limited:d}}function oh(e,t,n,r,o,i,s){let a="",l="literal",c=[],u=[],m=!1,f=t+1;while(f<n){let d=e[f];if(d==='"')return{text:a,provenance:l,nested:c,issues:u,next:f+1,limited:m};if(d==="\\"&&e[f+1]){let g=e[f+1]??"";if(g===`
18
+ `){f+=2;continue}if(g==="\r"&&e[f+2]===`
19
+ `){f+=3;continue}a+=["$","`",'"',"\\"].includes(g)?g:`\\${g}`,f+=2;continue}if(e.startsWith("$((",f)){let g=ls(e,f+3,n,"))"),y=g===-1?n:g+2;if(a+=e.slice(f,y),g===-1)u.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:f,end:y}});f=y;continue}let p=as(e,f,n,r,o,i,s);if(p){let g=pc(p,c,u);if(f=g.next,m||=g.limited,l=qn(l,g.provenance),m)return{text:a,provenance:l,nested:c,issues:u,next:f,limited:m};continue}if(d==="$"){let g=yc(e,f,n,a,l);a=g.text,l=g.provenance,f=g.next;continue}a+=d??"",f++}return u.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:t,end:n}}),{text:a,provenance:l,nested:c,issues:u,next:n,limited:m}}function as(e,t,n,r,o,i,s){let a=e.startsWith("$((",t),l=e.startsWith("$(",t)&&!a,c=(e.startsWith("<(",t)||e.startsWith(">(",t))&&!0,u=e[t]==="`";if(!a&&!l&&!c&&!u)return null;let m=a?3:u?1:2,f=a?"))":u?"`":")",d=ls(e,t+m,n,f),p=d===-1?n:d,g=d===-1?n:d+f.length;if(s>=o.maxDepth)return{program:vh(e,t+m,p,r,"depth-limit"),next:g,provenance:a?"arithmetic":"command-substitution"};if(a){let x=[],A=[],P=!1,S=t+m;while(S<p){let C=as(e,S,p,r,o,i,s+1);if(!C){S++;continue}if(x.push(...C.program.nodes),A.push(...C.program.issues),P||=C.program.status==="limited",S=C.next,P)break}if(d===-1)A.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:t,end:g}});return{program:ue({kind:"program",dialect:r,source:e.slice(t+m,p),span:{start:t+m,end:p},status:wo(A,P),issues:A,nodes:x}),next:g,provenance:"arithmetic"}}let y=Ro(e,t+m,p,r,o,i,s+1),h=d===-1?[{code:a?"unclosed-arithmetic":"unclosed-command-substitution",message:`${e.slice(t,t+m)} substitution is not closed`,span:{start:t,end:g}}]:[],R=(u||c)&&Kn(y.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions",span:{start:t,end:g}}]:[];return{program:ue({kind:"program",dialect:r,source:e.slice(t+m,p),span:{start:t+m,end:p},status:wo([...y.issues,...h,...R],y.limited),issues:[...y.issues,...h,...R],nodes:y.nodes}),next:g,provenance:a?"arithmetic":"command-substitution"}}function pc(e,t,n){return t.push(e.program),n.push(...e.program.issues),{provenance:e.provenance,next:e.next,limited:e.program.status==="limited"}}function ls(e,t,n,r){if(r==="`"){for(let a=t;a<n;a++)if(e[a]==="\\")a++;else if(e[a]==="`")return a;return-1}let o=1,i={single:!1,double:!1},s=[];for(let a=t;a<n;a++){let l=e[a];if((l===`
20
+ `||l==="\r")&&s.length>0){let u=l==="\r"&&e[a+1]===`
21
+ `?a+2:a+1,m=rs(e,u,n,s.splice(0));if(!m.terminated)return-1;a=m.next-1;continue}let c=gc(e,a,t,n,i);if(c!==null){a=c;continue}if(!i.double&&e.startsWith("$((",a)){let u=ih(e,a+3,n);if(u===-1)return-1;a=u+1;continue}if(r===")"&&!i.double&&l==="<"&&e[a+1]==="<"&&e[a+2]!=="<"){let u=e[a+2]==="-",m=a+(u?3:2);while(m<n&&/[ \t]/.test(e[m]??""))m++;let f=ns(e,m,n);if(f){s.push({delimiter:f.delimiter,quotedDelimiter:f.quoted,stripTabs:u,declarationSpan:{start:a,end:f.next},attach:()=>{return}}),a=f.next-1;continue}}if(e.startsWith("$(",a)&&!e.startsWith("$((",a)){o++,a++;continue}if(l==="("&&!i.double)o++;if(l===")"&&!i.double){if(o--,o===0)return r==="))"&&e[a+1]!==")"?-1:a}}return-1}function ih(e,t,n){let r=1,o={single:!1,double:!1};for(let i=t;i<n;i++){let s=e[i],a=gc(e,i,t,n,o);if(a!==null){i=a;continue}if(e.startsWith("$(",i)&&!e.startsWith("$((",i)){r++,i++;continue}if(s==="("&&!o.double)r++;if(s!==")"||o.double)continue;if(r--,r===0)return e[i+1]===")"?i:-1}return-1}function gc(e,t,n,r,o){let i=e[t];if(i==="\\"&&!o.single)return t+1;if(!o.double&&i==="'")o.single=!o.single;if(!o.single&&i==='"')o.double=!o.double;if(o.single)return t;if(o.double||i!=="#"||!Eh(e,t,n))return null;let s=t;while(s+1<r&&e[s+1]!==`
22
+ `&&e[s+1]!=="\r")s++;return s}function xo(e,t){let n=e[t];if(n===";")return";";if(n==="&")return e[t+1]==="&"?"&&":"&";if(n==="|")return e[t+1]==="|"?"||":e[t+1]==="&"?"|&":"|";return null}function sh(e,t){let n=e[t];if(n===">"){if(e[t+1]===">")return">>";if(e[t+1]==="&")return">&";return e[t+1]==="|"?">|":">"}if(n!=="<")return null;if(e.startsWith("<<<",t))return"<<<";if(e.startsWith("<<-",t))return"<<-";if(e[t+1]==="<")return"<<";if(e[t+1]==="&")return"<&";if(e[t+1]===">")return"<>";return"<"}function Eo(e){let t=e.charCodeAt(0);if(t===32||t>=9&&t<=13)return!0;if(t<128)return!1;return/\s/u.test(e)}function hc(e,t,n){if(e[t+1]==="{"){let o=e.indexOf("}",t+2);return o===-1||o>=n?n:o+1}let r=t+1;while(r<n&&/[A-Za-z0-9_?@#$!*-]/.test(e[r]??""))r++;return r===t+1?t+1:r}function ah(e,t,n){let r="",o=[],i=t;while(i<n){let s=e[i];if(s==="'")return{text:r,next:i+1,closed:!0,issues:o};if(s!=="\\"){r+=s??"",i++;continue}let a=lh(e,i+1,n);if(r+=a.text,a.invalidCodePoint!==void 0)o.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${a.invalidCodePoint}`,span:{start:i,end:a.next}});i=a.next}return{text:r,next:n,closed:!1,issues:o}}function lh(e,t,n){let r=e[t];if(!r||t>=n)return{text:"\\",next:t};let o=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
23
+ `],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(o.has(r))return{text:o.get(r)??r,next:t+1};if(r==="x")return So(e,t+1,n,16,2,t+1);if(r==="u")return So(e,t+1,n,16,4,t+1);if(r==="U")return So(e,t+1,n,16,8,t+1);if(/[0-7]/.test(r))return So(e,t,n,8,3,t+1);return{text:r,next:t+1}}function So(e,t,n,r,o,i){let s=r===16?/[0-9a-fA-F]/:/[0-7]/,a="",l=t;while(l<n&&a.length<o&&s.test(e[l]??""))a+=e[l],l++;if(!a)return{text:e[i-1]??"",next:i};let c=Number.parseInt(a,r);return c>1114111||c>=55296&&c<=57343?{text:"�",next:l,invalidCodePoint:c}:{text:String.fromCodePoint(c),next:l}}function wo(e,t=!1){if(t)return"limited";if(e.some((n)=>n.code==="invalid-ansi-c-code-point"||n.code==="missing-heredoc-delimiter"||n.code==="ambiguous-heredoc-delimiter"||n.code==="unterminated-heredoc"||n.code==="unsupported-heredoc-context"))return"invalid";return e.length>0?"partial":"complete"}function yc(e,t,n,r,o){let i=hc(e,t,n);return{text:r+e.slice(t,i),provenance:qn(o,"variable"),next:i}}function ch(e,t,n){let r=bo(e),o=t,i=!1,s=!1,a=t;while(a<n){let l=e[a];if(l==="\\"&&!i){a+=2;continue}if(!s&&l==="'"){i=!i,a++;continue}if(!i&&l==='"'){s=!s,a++;continue}if(i){a++;continue}let c=e.startsWith("$((",a),u=e.startsWith("$(",a)&&!c,m=!s&&(e.startsWith("<(",a)||e.startsWith(">(",a)),f=l==="`";if(c||u||m||f){let d=c?3:f?1:2,p=c?"))":f?"`":")",g=ls(e,a+d,n,p),y=g===-1?n:g+p.length;r.push(o,a,"literal"),r.push(a,y,c?"arithmetic":"command-substitution"),a=y,o=y;continue}if(l==="$"){let d=hc(e,a,n);if(d>a+1){r.push(o,a,"literal"),r.push(a,d,"variable"),a=d,o=d;continue}}if(!s&&(l==="*"||l==="?"||l==="[")){r.push(o,a,"literal"),r.push(a,a+1,"glob"),a++,o=a;continue}a++}return r.push(o,n,"literal"),r.parts}function qn(e,t){if(t==="command-substitution"||e==="command-substitution")return"command-substitution";if(t==="arithmetic"||e==="arithmetic")return"arithmetic";if(t==="variable"||e==="variable")return"variable";if(t==="glob"||e==="glob")return"glob";return e}function uh(e,t,n){return t+1>=n||Eo(e[t+1]??"")||xo(e,t+1)!==null}var dh=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),mh=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function fh(e){let t=0;while(t<=e.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]?.text??""))t++;if(t===e.length)return!0;let n=ph(e,t);if(n===void 0||n===null)return!1;t=n}return!1}function ph(e,t){let n=e[t]?.text.toLowerCase();if(n==="command")return gh(e,t);if(n==="env")return hh(e,t);if(n==="sudo")return yh(e,t);return}function gh(e,t){if(e[t+1]?.text==="-v")return null;for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(r==="-p"||r==="-v"||r==="-V"||/^-[pvV]+$/.test(r))continue;return n}return e.length}function hh(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(dh.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-u=")||r.startsWith("--unset=")||r.startsWith("-C")&&r.length>2||r.startsWith("--chdir=")||r.startsWith("-S")&&r.length>2||r.startsWith("--split-string=")||r.startsWith("-P"))continue;if(r.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(r))continue;return n}return e.length}function yh(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(mh.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-"))continue;return n}return e.length}function Cc(e,t,n,r){if(e.provenance!=="literal"||!e.raw.includes("{"))return;let o=[e.raw],i=e.raw.length,s=0;while(!0){let l=o.findIndex((p)=>uc(p));if(l===-1)break;if(++s>n)return{limited:!0};let c=o[l]??"",u=uc(c);if(!u||u.kind==="range")return{limited:!0};let m=u.start+c.length-u.end,f=u.alternatives.reduce((p,g)=>p+m+g.length,0);if(i-c.length+f>r||o.length-1+u.alternatives.length>t)return{limited:!0};let d=bc(c,u);o.splice(l,1,...d),i+=f-c.length}if(s===0)return;let a=o.map((l)=>Sh(l,n));if(a.some((l)=>l===null))return{limited:!0};return{words:[...new Set(a.filter((l)=>l!==null&&l!==""))]}}function Ch(e,t,n,r,o){if(t.provenance!=="literal"||t.quoted||t.raw!==t.text||!t.raw.includes("{"))return;let i=[t.text],s=t.text.length,a=0;while(!0){let c=i.findIndex((y)=>cc(y));if(c===-1)break;if(++a>r)return{limitCode:"depth-limit"};let u=i[c]??"",m=cc(u);if(!m)break;let f=m.start+u.length-m.end,d=m.alternatives.filter((y)=>f+y.length>0),p=d.reduce((y,h)=>y+f+h.length,0);if(s-u.length+p>o)return{limitCode:"brace-expansion-limit"};if(i.length-1+d.length>n)return{limitCode:"word-limit"};let g=bc(u,{...m,alternatives:d});i.splice(c,1,...g),s+=p-u.length}let l=i.filter((c)=>c.length>0);if(a===0)return;return{words:l.map((c)=>pn(e,t.span.start,t.span.end,c,"literal",!1))}}function cc(e){let t=[],n;for(let r=0;r<e.length;r++){let o=e[r];if(o==="{"){t.push({start:r,commas:[]});continue}if(o===","&&t.length>0){t.at(-1)?.commas.push(r);continue}if(o!=="}"||t.length===0)continue;let i=t.pop();if(!i||i.commas.length===0)continue;if(!n||i.start<n.start)n={start:i.start,end:r+1,commas:i.commas}}if(!n)return;return{start:n.start,end:n.end,alternatives:Sc(e,n)}}function uc(e){let t=[],n,r=null,o=!1;for(let i=0;i<e.length;i++){let s=e[i];if(o){o=!1;continue}if(s==="\\"&&r!=="'"){o=!0;continue}if(s===r){r=null;continue}if(r===null&&(s==="'"||s==='"')){r=s;continue}if(r!==null)continue;if(s==="{"){t.push({start:i,commas:[]});continue}if(s===","&&t.length>0){t.at(-1)?.commas.push(i);continue}if(s!=="}"||t.length===0)continue;let a=t.pop();if(!a)continue;let l=a.commas.length>0?{kind:"alternatives",start:a.start,end:i+1,commas:a.commas}:bh(e.slice(a.start+1,i))?{kind:"range",start:a.start,end:i+1}:void 0;if(l&&(!n||l.start<n.start))n=l}if(!n||n.kind==="range")return n;return{kind:n.kind,start:n.start,end:n.end,alternatives:Sc(e,n)}}function bc(e,t){return t.alternatives.map((n)=>`${e.slice(0,t.start)}${n}${e.slice(t.end)}`)}function Sc(e,t){let n=[t.start,...t.commas,t.end-1];return n.slice(0,-1).map((r,o)=>e.slice(r+1,n[o+1]))}function bh(e){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(e)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(e)}function Sh(e,t){let n=`x${e}`,r=ss(n,0,n.length,"posix",{maxInputLength:n.length,maxWords:1,maxDepth:t},{used:0,max:1},0);if(r.limited||r.issues.length>0||r.next!==n.length||r.word.provenance!=="literal")return null;return r.word.text.slice(1)}function vh(e,t,n,r,o){return ue({kind:"program",dialect:r,source:e.slice(t,n),span:{start:t,end:n},status:"limited",issues:[{code:o,message:"command structure exceeds parser limit",span:{start:t,end:n}}],nodes:[]})}function gn(e,t,n,r,o){return{nodes:e,issues:[...t,{code:r,message:`command structure exceeds parser limit ${o}`,span:{start:n,end:n}}],next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function vo(e,t,n){return{nodes:e,issues:t,next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function os(e){return e.used++,e.used<=e.max}function Rh(e,t,n){let r=/^([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(e.slice(t,n)),o=r?.[1];if(!r||!o)return;return{name:o,braceIndex:t+r[0].lastIndexOf("{")}}function Kn(e){return e.some((t)=>{if(t.kind==="command")return t.redirections.some((n)=>n.heredoc)||t.nested.some((n)=>Kn(n.nodes));return(t.kind==="group"||t.kind==="function")&&Kn(t.body.nodes)})}function xh(e){return e.map((t)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${t.delimiter} was not found`,span:t.declarationSpan}))}function vc(e){return e?.kind==="command"||e?.kind==="group"||e?.kind==="function"}function dc(e,t){let n=e.at(-1);if(n?.kind!=="connector"||!mc.has(n.operator))return;t.push({code:"missing-command-after-connector",message:`connector ${n.operator} requires a following command`,span:n.span})}function is(e,t,n){if(!vc(e.at(-1)))return;t.push({code:"missing-command-connector",message:"adjacent commands require a connector",span:{start:n,end:n+1}})}function Eh(e,t,n){return t===n||/[\s;&|()]/u.test(e[t-1]??"")}var Rc=new Set(["remove-item","ri","del","erase","rd","rmdir"]),xc=["-rec","-for","-path","-literalpath","-whatif"],Po={maxInputLength:131072,maxWords:16384,maxDepth:64};function Ec(e){let t=e.toLowerCase().replaceAll("`","");if(![...Rc].some((r)=>t.includes(r))&&!(t.includes("rm")&&xc.some((r)=>t.includes(r)))&&!t.includes("<#"))return!1;let n=Ah(e);return n.invalidComment||n.commands.some(wh)}function wh(e){let t=e[0]==="&"||e[0]==="."?1:0,n=e[t]?.toLowerCase();if(n&&Rc.has(n))return!0;if(n!=="rm")return!1;return e.slice(t+1).some((r)=>{let o=r.toLowerCase().split(":",1)[0]??"";return xc.some((i)=>o.startsWith(i))})}function wc(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return ue({kind:"program",dialect:"powershell",source:e,span:n,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${t.maxInputLength} UTF-16 code units`,span:n}],nodes:[]});let r=fs(e,0,e.length,t,0);return ue({kind:"program",dialect:"powershell",source:e,span:n,status:kh(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function fs(e,t,n,r,o,i=!1){let s=go(),a=ho(),l=yo(),c=0,u=!1,m=()=>{if(l.words.length===0&&l.redirections.length===0)return;let d={start:l.start,end:l.end};Co(s,l,{kind:"command",dialect:"powershell",source:e.slice(d.start,d.end),span:d,words:l.words,redirections:l.redirections,nested:l.nested,displayText:l.words.map((p)=>p.text).join(" ")})},f=t;while(f<n){let d=e[f];if(!d)break;if(i&&d==="}")return m(),{nodes:s,issues:a,next:f+1,closed:!0,words:c,limited:u};let p=Ac(e,f,n,r.maxDepth);if(p){if(p.issue)a.push(p.issue);if(p.limited)return m(),{nodes:s,issues:a,next:p.next,closed:!1,words:c,limited:!0};f=p.next;continue}if(/\s/.test(d)){if(d==="\r"||d===`
24
+ `){m();let h=d==="\r"&&e[f+1]===`
25
+ `?f+2:f+1;s.push(cs(e,f,h)),f=h;continue}f++;continue}let g=ps(e,f);if(g){m(),s.push(cs(e,f,f+g.length)),f+=g.length;continue}if(d==="{"){if(m(),o>=r.maxDepth)return a.push(_c(f,r.maxDepth)),{nodes:s,issues:a,next:n,closed:!1,words:c,limited:!0};let h=fs(e,f+1,n,r,o+1,!0),R=h.closed?h.next-1:h.next,x=ue({kind:"program",dialect:"powershell",source:e.slice(f+1,R),span:{start:f+1,end:R},status:h.limited?"limited":h.issues.length>0?"partial":"complete",issues:h.issues,nodes:h.nodes});if(s.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:f,end:h.next}),body:x})),a.push(...h.issues),!h.closed)a.push({code:"unclosed-script-block",message:"PowerShell script block is not closed",span:{start:f,end:h.next}});c+=h.words,u||=h.limited,f=h.next;continue}if(d==="}"){m(),s.push(cs(e,f,f+1)),f++;continue}if(d===">"||d==="<"){l.start=l.start===-1?f:l.start;let h=e[f+1]===d?f+2:f+1,R=h;while(/[ \t]/.test(e[R]??""))R++;let x=R<n?us(e,R,n,r,o):void 0,A=x?.next??h;if(l.redirections.push(Object.freeze({kind:"redirection",operator:e.slice(f,h),span:Object.freeze({start:f,end:A}),...x?{target:x.word}:{}})),x)a.push(...x.issues),l.nested.push(...x.nested),c+=x.words,u||=x.limited;l.end=A,f=A;continue}if(d===","){l.start=l.start===-1?f:l.start,l.words.push(ts({text:",",raw:",",span:{start:f,end:f+1},provenance:"literal",quoted:!1})),l.end=++f;continue}let y=us(e,f,n,r,o);if(l.start=l.start===-1?f:l.start,l.end=y.next,l.words.push(y.word),a.push(...y.issues),l.nested.push(...y.nested),c+=1+y.words,u||=y.limited,c>r.maxWords)return a.push({code:"word-limit",message:`command exceeds ${r.maxWords} words`,span:{start:f,end:y.next}}),m(),{nodes:s,issues:a,next:y.next,closed:!1,words:c,limited:!0};f=y.next>f?y.next:f+1}return m(),{nodes:s,issues:a,next:f,closed:!i,words:c,limited:u}}function us(e,t,n,r,o){let i="",s="literal",a=!1,l=[],c=[],u=0,m=!1,f=(p)=>{let g=Ph(e,p,n,r,o);return i+=e.slice(p,g.next),c.push(g.program),l.push(...g.program.issues),u+=ds(g.program),m||=g.program.status==="limited",s="command-substitution",g.next},d=t;while(d<n){let p=e[d];if(!p||/\s/.test(p)||ps(e,d)||p===">"||p==="<"||p==="#")break;if(p===",")break;if(p==="`"){let g=e[d+1];if(!g){l.push({code:"trailing-escape",message:"PowerShell escape has no following character",span:{start:d,end:d+1}}),d++;break}i+=g,d+=2;continue}if(e.startsWith("$(",d)){d=f(d);continue}if(p==="'"){a=!0,d++;let g=!1;while(d<e.length){if(e[d]==="'"&&e[d+1]==="'"){i+="'",d+=2;continue}if(e[d]==="'"){g=!0,d++;break}i+=e[d]??"",d++}if(!g)l.push({code:"unclosed-single-quote",message:"single-quoted word is not closed",span:{start:t,end:e.length}});continue}if(p==='"'){a=!0;let g=d++,y=!1;while(d<n){let h=e[d];if(h==="`"&&e[d+1]){i+=e[d+1],d+=2;continue}if(h==='"'){y=!0,d++;break}if(e.startsWith("$(",d)){d=f(d);continue}if(h==="$")s=e[d+1]==="("?"command-substitution":"variable";i+=h??"",d++}if(!y)l.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:g,end:e.length}});continue}if(p==="$")s=e[d+1]==="("?"command-substitution":"variable";if(p==="@"&&d===t)s="variable";i+=p,d++}return{word:pn(e,t,d,i,s,a,s==="literal"?void 0:_h(e,t,d)),next:d,issues:l,nested:c,words:u,limited:m}}function Ph(e,t,n,r,o){let i=Pc(e,t+2,n),s=i===-1?n:i,a=i===-1?n:i+1;if(o>=r.maxDepth)return{program:ue({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:"limited",issues:[_c(t,r.maxDepth)],nodes:[]}),next:a};let l=fs(e,t+2,s,r,o+1),c=i===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed",span:{start:t,end:a}}]:[];return{program:ue({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:l.limited?"limited":l.issues.length+c.length>0?"partial":"complete",issues:[...l.issues,...c],nodes:l.nodes}),next:a}}function Pc(e,t,n){let r=1,o=!1,i=!1;for(let s=t;s<n;s++){let a=e[s];if(a==="`"){s++;continue}if(!i&&a==="'"){if(o&&e[s+1]==="'"){s++;continue}o=!o;continue}if(!o&&a==='"'){i=!i;continue}if(o)continue;if(e.startsWith("$(",s)){r++,s++;continue}if(!i&&a==="(")r++;if(a!==")")continue;if(r--,r===0)return s}return-1}function ds(e){let t=0;for(let n of e.nodes){if(n.kind==="group")t+=ds(n.body);if(n.kind==="command"){t+=n.words.length;for(let r of n.nested)t+=ds(r)}}return t}function _h(e,t,n){let r=bo(e),o=t,i=!1,s=t;while(s<n){let a=e[s];if(a==="`"){s+=2;continue}if(a==="'"){if(i&&e[s+1]==="'"){s+=2;continue}i=!i,s++;continue}if(i){s++;continue}if(e.startsWith("$(",s)){let l=Pc(e,s+2,n),c=l===-1?n:l+1;r.push(o,s,"literal"),r.push(s,c,"command-substitution"),s=c,o=c;continue}if(a==="$"||a==="@"&&s===t){let l=s+1;if(e[l]==="{"){let c=e.indexOf("}",l+1);l=c===-1||c>=n?n:c+1}else while(l<n&&/[A-Za-z0-9_:?]/.test(e[l]??""))l++;r.push(o,s,"literal"),r.push(s,l,"variable"),s=l,o=l;continue}s++}return r.push(o,n,"literal"),r.parts}function _c(e,t){return{code:"depth-limit",message:`command structure exceeds parser limit ${t}`,span:{start:e,end:e}}}function Ah(e){let t=[],n=[],r=0,o=0,i=!1,s=()=>{if(n.length>0)t.push(n);n=[]};while(r<e.length&&r<131072&&o<16384){let a=e[r];if(a==="\r"||a===`
26
+ `){s(),r+=a==="\r"&&e[r+1]===`
27
+ `?2:1;continue}if(/\s/.test(a??"")){r++;continue}let l=Ac(e,r,Math.min(e.length,Po.maxInputLength),Po.maxDepth);if(l){i||=!!l.issue||l.limited,r=l.next;continue}let c=ps(e,r);if(c){s(),r+=c.length;continue}if(a==="{"||a==="}"){s(),r++;continue}let u=us(e,r,Math.min(e.length,Po.maxInputLength),Po,0);if(u.word.text)n.push(u.word.text);for(let m of u.nested)t.push(...ms(m));o++,r=u.next>r?u.next:r+1}return s(),{commands:t,invalidComment:i}}function ms(e){return e.nodes.flatMap((t)=>{if(t.kind==="group")return ms(t.body);if(t.kind!=="command")return[];return[t.words.map((n)=>n.text),...t.nested.flatMap(ms)]})}function ps(e,t){for(let n of["&&","||",";","|"])if(e.startsWith(n,t))return n;return null}function Ac(e,t,n,r){if(e[t]==="#"&&e[t+1]!==">"){let s=t+1;while(s<n&&e[s]!=="\r"&&e[s]!==`
28
+ `)s++;return{next:s,limited:!1}}if(!e.startsWith("<#",t))return null;let o=1,i=t+2;while(i<n){if(e.startsWith("<#",i)){if(o++,o>r)return{next:n,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${r}`,span:{start:t,end:i+2}},limited:!0};i+=2;continue}if(e.startsWith("#>",i)){if(o--,i+=2,o===0)return{next:i,limited:!1};continue}i++}return{next:n,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed",span:{start:t,end:n}},limited:!1}}function kh(e,t){if(t)return"limited";if(e.some((n)=>n.code==="unclosed-block-comment"))return"invalid";return e.length>0?"partial":"complete"}function cs(e,t,n){return Object.freeze({kind:"connector",operator:e.slice(t,n),span:Object.freeze({start:t,end:n})})}var Wt=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Fe(e,t="auto",n=Wt){if(t==="powershell"||t==="auto"&&Ec(e.slice(0,n.maxInputLength)))return wc(e,n);return fc(e,"posix",n)}function Yn(e,t){if(e!=="powershell")return t[0]?.provenance==="command-substitution";let n=t[0]?.text==="&"||t[0]?.text==="."?1:0,r=t[n]?.provenance;return r!==void 0&&r!=="literal"}var Th=/^[A-Za-z_][A-Za-z0-9_]*=/;function _o(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function Ao(e){let t=_o(e.words[0],"time")?1:0,n=t===1&&_o(e.words[t],"-p")?t+1:t,r=t===1&&_o(e.words[n],"--")?n+1:n,o=_o(e.words[r],"!")?r+1:r,i=e.words.slice(o).find((s)=>!Th.test(s.text));return i?.provenance==="literal"?i.text:void 0}function Zn(e,t){if(t.escaped)return t.escaped=!1,!0;if(e==="\\"&&!t.inSingle)return t.escaped=!0,!0;if(e==="'"&&!t.inDouble)return t.inSingle=!t.inSingle,!0;if(e==='"'&&!t.inSingle)return t.inDouble=!t.inDouble,!0;return!1}function hn(e){let t={inSingle:!1,inDouble:!1,escaped:!1};for(let n of Ih(e))Zn(n,t);return t.inSingle||t.inDouble}function Ih(e){let t="",n={inSingle:!1,inDouble:!1,escaped:!1},r=!1,o=!0;for(let i=0;i<e.length;i++){let s=e[i];if(!s)break;if(r){if(s===`
29
+ `||s==="\r")t+=s,r=!1,n.escaped=!1;continue}if(s==="#"&&!n.inSingle&&!n.inDouble&&o){r=!0;continue}if(t+=s,!n.inSingle&&!n.inDouble&&!n.escaped)o=/[\s;&|()<>]/.test(s);Zn(s,n)}return t}var Oh=new Set(["&&","||","|&","|","&",";"]),Mh=new Set(["<<","<<<",">|"]),Dh=/[*@#?$!_-]/,gs=Object.freeze([]),Lh=Object.freeze([]),Nh=256;function Mc(e,t){let n=t.status==="complete"?new Set(ys(t)):new Set,r=[...n].reduce((s,a)=>s.slice(0,a.start)+" ".repeat(a.end-a.start)+s.slice(a.end),e);if(hn(r))return ko("unclosed-quote",r,gs);let o={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},i=Xn(t,{source:r,suppressed:n,flags:o,depth:0,functions:new Map});if(o.limited)return ko("structural-limit",r,gs);if(o.invalid)return ko("invalid",r,gs);return ko("complete",r,i,o.assignmentFallbacks)}function ko(e,t,n,r=Lh){return Object.freeze({status:e,source:t,entries:Object.freeze(n),assignmentFallbacks:Object.freeze(r)})}function Xn(e,t){return e.nodes.flatMap((n,r)=>Wh(n,e,r,t)).sort((n,r)=>n.start-r.start).flatMap((n)=>[...n.entries])}function Wh(e,t,n,r){if(e.kind==="connector")return[{start:e.span.start,entries:[Ge(Bh(e.operator))]}];if(e.kind==="unknown")return[{start:e.span.start,entries:[Ge(e.source)]}];if(e.kind==="function")return r.functions.set(e.name,e.body),[];if(e.kind==="group"){let i=e.style!=="subshell",s=r.source[e.span.end-1]===(i?"}":")"),a=i?r:{...r,functions:new Map(r.functions)};return[{start:e.span.start,entries:[i?To("{"):Ge("("),...Xn(e.body,a),...s?[i?To("}"):Ge(")")]:[]]}]}let o=Hh(e,r.functions);if(o){if(r.depth>=Wt.maxDepth||++r.flags.expansions>Nh)return r.flags.limited=!0,[];return[{start:e.span.start,entries:[...kc(e,r),To(";"),...Xn(o,{...r,depth:r.depth+1}),To(";")]},...Tc(e,t,n,r)]}return[{start:e.span.start,entries:kc(e,r)},...Tc(e,t,n,r)]}function kc(e,t){return[...e.words.map((n)=>({start:n.span.start,entries:Lc(n,e,t,!1)})),...e.redirections.map((n)=>({start:n.span.start,entries:Fh(n,e,t)}))].sort((n,r)=>n.start-r.start).flatMap((n)=>n.entries)}function Fh(e,t,n){let r=e.operator==="<<-"?"<<":e.operator,o=e.target?Lc(e.target,t,n,!0):[],i=o[0],s=i?.kind==="word"?i.text:void 0;return[...e.fd===void 0?[]:[Cs(String(e.fd))],Object.freeze({kind:"redirection",operator:r,role:Uh(r),targetOrder:Mh.has(r)?"legacy-segment":"immediate",...s===void 0?{}:{target:s}}),...s===void 0?o:o.slice(1)]}function Tc(e,t,n,r){let o=e.redirections.filter((i)=>i.operator==="<<"||i.operator==="<<-");return[...o.flatMap((i)=>{let s=i.heredoc;if(!s)return[];let a=[Cs(s.delimiter),.../[\r\n]/.test(r.source[s.terminatorSpan.end]??"")?[Ge(";")]:[]];if(r.suppressed.has(s.bodySpan))return[{start:s.bodySpan.start,entries:a}];return[{start:s.bodySpan.start,entries:[...Dc(r.source.slice(s.bodySpan.start,s.bodySpan.end),r),...a]}]}),...o.some((i)=>!i.heredoc&&i.target)?Gh(t,n,r):[]]}function Gh(e,t,n){let r=e.nodes.slice(t+1).find((o)=>o.kind==="connector");if(!r||r.span.end>=e.span.end)return[];return[{start:r.span.end,entries:Dc(n.source.slice(r.span.end,e.span.end),n)}]}function Dc(e,t){if(t.depth>=Wt.maxDepth)return t.flags.limited=!0,[];let n=Fe(e,"posix");if(n.status==="limited")return t.flags.limited=!0,[];let r={invalid:!1,limited:!1,expansions:t.flags.expansions,assignmentFallbacks:t.flags.assignmentFallbacks},o=Xn(n,{source:e,suppressed:new Set,flags:r,depth:t.depth+1,functions:new Map});return t.flags.limited||=r.limited,t.flags.expansions=r.expansions,o}function Lc(e,t,n,r){let o=[],i={single:!1,double:!1},s="",a=!1,l=()=>{if(a&&!r)o.push(Ge("glob"));else if(s!==""||e.quoted&&o.length===0)o.push(Cs(s));s="",a=!1};for(let c of e.parts){if(c.provenance!=="command-substitution"&&c.provenance!=="arithmetic"){for(let d of hs(c.raw,i,n.flags)){if(typeof d==="string"){l(),o.push(Ge(d));continue}s+=d.text,a||=d.glob}continue}if(i.double){let d=n.source.slice(c.span.start,c.span.end);s+=hs(d,{single:!1,double:!0},n.flags).map((p)=>typeof p==="string"?p:p.text).join("");continue}let u=t.nested.find((d)=>d.span.start>=c.span.start&&d.span.end<=c.span.end),m=u?Xn(u,n):[];if(c.raw.startsWith("`")){s+="${}",l(),o.push(...m);continue}if(c.raw.startsWith("<(")||c.raw.startsWith(">(")){l(),o.push(c.raw.startsWith("<(")?Ge("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),...m,...c.raw.endsWith(")")?[Ge(")")]:[]);continue}let f=c.raw.startsWith("$((")?2:1;s+="${}",l(),o.push(...Array.from({length:f},()=>Ge("(")),...m,...c.raw.endsWith(")".repeat(f))?Array.from({length:f},()=>Ge(")")):[])}return l(),o}function hs(e,t,n){let r=[],o="",i=!1,s=0;while(s<e.length){let a=e[s]??"";if(!t.single&&!t.double&&(a==="("||a===")")){r.push({text:o,glob:i},a),o="",i=!1,s++;continue}if(t.single){if(a==="'")t.single=!1;else o+=a;s++;continue}if(t.double){if(a==='"'){t.double=!1,s++;continue}if(a==="\\"){let l=e[s+1]??"";o+=['"',"\\","$"].includes(l)?l:`\\${l}`,s+=2;continue}if(a==="$"){let l=Ic(e,s,t,n);o+=l.text,s=l.next;continue}o+=a,s++;continue}if(a==="'"||a==='"'){t.single=a==="'",t.double=a==='"',s++;continue}if(a==="\\"){let l=e[s+1]??"";i||=l==="*"||l==="?",o+=l,s+=2;continue}if(a==="$"){let l=Ic(e,s,t,n);o+=l.text,s=l.next;continue}i||=a==="*"||a==="?",o+=a,s++}return[...r,{text:o,glob:i}]}function Ic(e,t,n,r){let o=e[t+1];if(o==="{"){let s=$h(e,t+2);if(s===-1)return r.invalid=!0,{text:"",next:e.length};let a=e.slice(t,s+1);return zh(a,n,r),{text:a,next:s+1}}if(o!==void 0&&Dh.test(o))return{text:`\${${o}}`,next:t+2};let i=/^\w*/.exec(e.slice(t+1))?.[0]??"";return{text:`\${${i}}`,next:t+1+i.length}}function zh(e,t,n){let r=e.slice(2,-1),o=/^[A-Za-z_][A-Za-z0-9_]*/.exec(r)?.[0];if(!o)return;let i=r.slice(o.length),s=[":=","="].find((l)=>i.startsWith(l));if(!s)return;let a=hs(i.slice(s.length),{...t},n);n.assignmentFallbacks.push(...a.flatMap((l)=>typeof l==="string"||!l.text?[]:[l.text]))}function $h(e,t){let n=1,r=t;while(n>0&&r<e.length){if(e[r]==="{"&&e[r-1]==="$")n++;else if(e[r]==="}")n--;r++}return n===0?r-1:-1}function Bh(e){return/^[\r\n]+$/.test(e)?";":e}function Ge(e){return Object.freeze({kind:"operator",operator:e,boundary:Oh.has(e)})}function To(e){return Object.freeze({kind:"operator",operator:e,boundary:!0})}function Cs(e){return Object.freeze({kind:"word",text:e})}function Uh(e){if(e==="<<"||e==="<<<")return"here-data";if(e==="<"||e==="<&")return"file-read";return"file-write"}function ys(e){return e.nodes.flatMap((t,n)=>{if(t.kind==="group"||t.kind==="function")return ys(t.body);if(t.kind!=="command")return[];let r=t.nested.flatMap((s)=>ys(s)),o=e.nodes[n+1];if(o?.kind==="connector"&&(o.operator==="|"||o.operator==="|&")||!Vh(t))return r;return[...r,...t.redirections.flatMap((s)=>s.heredoc?.quotedDelimiter?[s.heredoc.bodySpan]:[])]})}function Hh(e,t){let n=Ao(e);return n===void 0?void 0:t.get(n)}function Rt(e,t){return e!==void 0&&e.provenance==="literal"&&!e.quoted&&e.raw===e.text&&e.text===t}function jh(e){if(Rt(e.words[0],"git"))return Rt(e.words[1],"commit");if(!Rt(e.words[0],"gh")||!Rt(e.words[2],"create"))return!1;return Rt(e.words[1],"pr")||Rt(e.words[1],"issue")}function Vh(e){return(Rt(e.words[0],"cat")||Rt(e.words[0],"tee")||jh(e))&&!e.words.some(Oc)&&!e.redirections.some((n)=>Oc(n.target))}function Oc(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}import{types as qh}from"node:util";var Kh=new Set(["applypatch","patch"]),Yh=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),Zh=new Set(["grep","grepsearch","rg"]),Xh=new Set(["find","findbyname","glob"]),Jh=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),Qh=new Set(["command","diff","input","patch","patchtext"]),Nc=new TextEncoder,ey=new TextDecoder,ty=/\s/,ny=64;class er extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var Jn=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function $c(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function Oo(e){return Jh.has($c(e))}function y_(e){let t=$c(e);if(Kh.has(t))return"patch";if(Zh.has(t))return"grep";if(Xh.has(t))return"glob";if(Yh.has(t))return"path";return"unknown"}function Mo(e){if(!e||typeof e!=="object")return;Kc(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)Xe();return}if(t.get||t.set)Xe();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function Bc(e,t){return Uc(e,t,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Uc(e,t,n,r){let o=qc(e,n,r);if(!o)return[];let i=o.entries.flatMap(([s,a])=>{let l=Uc(a,t,n,r+1);return typeof a==="string"&&t.has(Hc(s))?[a]:l});return n.ancestors.delete(o.object),i}function Hc(e){return e.replace(/-/g,"_").toLowerCase()}function jc(e){return Vc(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(oy)}function Vc(e,t,n,r){let o=qc(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>Vc(a,o.array?t:Qh.has(Hc(s)),n,r+1));return n.ancestors.delete(o.object),i}function ry(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>Jn.maxDepth||t.nodes>Jn.maxNodes)Xe();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>Jn.maxStringBytes||t.stringBytes>Jn.maxAggregateStringBytes)Xe()}function qc(e,t,n){if(ry(e,t,n),!e||typeof e!=="object")return null;let r=Kc(e);if(t.ancestors.has(e))Xe();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>Jn.maxKeys)Xe();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)Xe();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function Kc(e){if(qh.isProxy(e))Xe();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)Xe();return t}function Xe(){throw new er}function oy(e){let t=[],n=e.split(/\r?\n/),r=!1,o=!1,i=null,s=null,a=()=>{o=!1,i=null,s=null};for(let l=0;l<n.length;l++){let c=n[l]??"";if(c==="*** Begin Patch"){r=!0,a();continue}if(c==="*** End Patch"){r=!1,a();continue}if(c.startsWith("@@")){let u=iy(c);if(o=!0,i=u?.oldLines??null,s=u?.newLines??null,i===0&&s===0)a();continue}if(o&&i!==null&&s!==null){let u=c.startsWith(" ")||c.startsWith("-")?1:0,m=c.startsWith(" ")||c.startsWith("+")?1:0;if(i=Math.max(0,i-u),s=Math.max(0,s-m),i===0&&s===0)a();continue}if(c.startsWith("*** ")){a(),t.push(...bs(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...bs(c));continue}if(c.startsWith("--- ")){let u=n[l+1]??"";if(!u.startsWith("+++ "))continue;t.push(...vs(Io(c.slice(4),!0),Io(u.slice(4),!0))),l++;continue}if(!r)t.push(...bs(c))}return t}function iy(e){let t=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(e);if(!t)return null;return{oldLines:Number(t[1]??1),newLines:Number(t[2]??1)}}function bs(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return zc(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return zc(n[1]);if(e.startsWith("diff --git "))return sy(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return Gc(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return Gc(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return fy(i[1]);return[]}function sy(e){let t=ay(e);if(t.length===2&&t[0]&&t[1])return vs(t[0],t[1]);let n=ly(e);return n?vs(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function ay(e){let t=[],n=0;while(n<e.length&&t.length<2){while(Ft(e[n]))n++;if(n>=e.length)break;let r=e[n]==='"'||e[n]==="'"?e[n]:void 0;if(!r){let i=n;while(n<e.length&&!Ft(e[n]))n++;t.push(e.slice(i,n));continue}let o=Yc(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(Ft(e[n]))n++;return n===e.length?t:[]}function ly(e){let t=0;while(t<e.length&&Ft(e[t]))t++;let n=e.length;while(n>t&&Ft(e[n-1]))n--;let r=0,o=t;while(o<n){if(!Ft(e[o])){o++;continue}let i=o;while(o<n&&Ft(e[o]))o++;if(i===t||o===n)continue;if(r++,r>ny)Xe();if(cy(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function cy(e,t,n,r,o){if(Ss(e,t,n,r,o))return!0;let i=Wc(e,"/",t,n),s=Wc(e,"/",r,o);if(i<=t||s<=r)return!1;if(Ss(e,t,i,r,s))return!1;return Ss(e,i+1,n,s+1,o)}function Ss(e,t,n,r,o){if(n-t!==o-r)return!1;for(let i=0;i<n-t;i++)if(e[t+i]!==e[r+i])return!1;return!0}function Wc(e,t,n,r){for(let o=n;o<r;o++)if(e[o]===t)return o;return-1}function Ft(e){return e!==void 0&&ty.test(e)}function Yc(e,t,n){let r=[],o=t+1;while(o<e.length){let i=e[o]??"";if(i===n)return{value:ey.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...Nc.encode(i)),o++;continue}let s=e.slice(o+1),a=/^[0-7]{1,3}/.exec(s)?.[0];if(a){r.push(Number.parseInt(a,8)),o+=a.length+1;continue}r.push(...Nc.encode(uy(s[0]??""))),o+=2}return null}function uy(e){return{a:"\x07",b:"\b",f:"\f",n:`
30
+ `,r:"\r",t:"\t",v:"\v"}[e]??e}function dy(e){return Qn(py(e))}function vs(e,t){if(e==="/dev/null")return Fc(t);if(t==="/dev/null")return Fc(e);if(e.startsWith("a/")&&t.startsWith("b/"))return[e.slice(2),t.slice(2)].flatMap(Qn);let n=my(e,t)??(e===t?Zc(e):null);return[e,t,...n?[n]:[]].flatMap(Qn)}function Fc(e){let t=Zc(e);return[e,...t?[t]:[]].flatMap(Qn)}function Zc(e){let t=e.indexOf("/");return t>0&&t<e.length-1?e.slice(t+1):null}function my(e,t){let n=e.indexOf("/"),r=t.indexOf("/");if(n<1||r<1)return null;if(e.slice(0,n)===t.slice(0,r))return null;let o=e.slice(n+1);return o===t.slice(r+1)?o:null}function Gc(e){return dy(Io(e,!0))}function fy(e){return Qn(Io(e,!1))}function Io(e,t){let n=e.trim(),r=n[0]==='"'||n[0]==="'"?n[0]:void 0;if(r){let o=Yc(n,0,r);if(o&&(t||n.slice(o.end).trim()===""))return o.value}return t?n.split("\t",1)[0]?.trim()??"":n}function py(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function Qn(e){return e===""||e==="/dev/null"?[]:[e]}function zc(e){let t=e.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return t===""||t==="/dev/null"?[]:[t]}var Xc=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Jc=new Set([...Xc,"glob"]),gy=new Set([...Jc,"pattern"]),hy=[],Qc={parseCommand:Fe,projectShellSyntax:Mc};class xt extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Do(e,t={}){let n=yy({...Qc,...t}),r=Mo(e.input),o=[];if((e.route.kind==="command"||e.route.kind==="unknown")&&r)o.push({usage:"input-candidate",source:r});if(e.route.kind==="command"&&"command"in e&&e.command)o.push({usage:"declared-command",source:e.command});let i=o.reduce((s,a)=>{let l=s.findIndex((m)=>m.source===a.source);if(l!==-1){let m=s[l];if(!m)return s;return s[l]={...m,usages:[...m.usages,a.usage]},s}let c=e.route.kind==="command"?e.route.shell:"posix",u=n.getCommandProgram(a.source,c);return s.push({usages:[a.usage],source:a.source,program:u,shell:n.getShellSyntax(a.source,u)}),s},[]);return{invocation:{toolName:e.toolName,route:e.route,context:e.context},commands:i,paths:Cy(e),store:n}}function be(e,t){return e.commands.find((n)=>n.usages.includes(t))}function Je(e){if(!e.includes("$"))return e;return Qr(e,ct())}function yy(e={}){let t={...Qc,...e},n=new Map,r=new Map,o=new WeakMap,i=(a,l)=>{let c=`${l}\x00${a}`,u=r.get(c);if(u)return u;let m=t.parseCommand(a,l);return r.set(c,m),m};return{getShellSyntax:(a,l)=>{if(l&&l.source!==a)throw TypeError("Shell syntax source does not match command program source.");let c=l??i(a,"posix");if(c.status==="limited"){let f=o.get(c);if(f)return f;let d={status:"structural-limit",source:a,entries:hy,assignmentFallbacks:[]};return o.set(c,d),d}let u=n.get(a);if(u)return u;let m=t.projectShellSyntax(a,c);return n.set(a,m),m},getCommandProgram:i}}function Cy(e){let t=e.route.kind==="grep"?Jc:e.route.kind==="glob"?gy:Xc;return[...Bc(e.input,t),...e.route.kind==="patch"?jc(e.input):[]]}function de(e,t){let n=new Set,r=!1;for(let o of e){if(o==="--"){r=!0;continue}if(r)continue;if(o.startsWith("-")&&!o.startsWith("--")&&o.length>1)for(let i=1;i<o.length;i++){let s=o[i];if(!s||!/[a-zA-Z]/.test(s))break;let a=`-${s}`;if(n.add(a),t?.shortOptsWithValue?.has(a))break}}return n}var by=new Map([["bash",new Set(["O","o"])],["dash",new Set(["o"])],["ksh",new Set(["o"])],["sh",new Set(["o"])],["zsh",new Set(["o"])]]),Sy=new Map([["zsh",new Set(["o"])]]),vy=new Map([["bash",new Set(["--init-file","--rcfile"])]]);function eu(e,t){for(let n=0;n<t.length;n++){let r=t[n];if(r===void 0||r==="--"||r==="-"||r[0]!=="-"&&r[0]!=="+")return null;if(r.startsWith("--")){let s=vy.get(e);if(xy(r,s))continue;if(!s?.has(r))continue;if(t[n+1]===void 0)return null;n++;continue}let o=Ry(e,r);if(o.commandSelected)return t[n+o.followingValues+1]??null;let i=t[n+1];if(e==="ksh"&&(r==="-o"||r==="+o")&&i!==void 0&&i[0]!=="-"&&i[0]!=="+")n++;n+=o.followingValues}return null}function Ry(e,t){let n=by.get(e),r=Sy.get(e),o=!1,i=0;for(let s=1;s<t.length;s++){let a=t[s];if(a===void 0)break;if(t[0]==="-"&&a==="c")o=!0;if(e==="ksh"&&a==="o"){if(s+1<t.length){let l=t.slice(s+1);if(!o&&t[0]==="-"&&l==="c")continue;if(!o&&t[0]==="-"&&l[0]==="-"&&l.endsWith("c"))o=!0;break}if(o)i++;continue}if(!n?.has(a))continue;if(r?.has(a)&&s+1<t.length)break;i++}return{commandSelected:o,followingValues:i}}function xy(e,t){return t!==void 0&&[...t].some((n)=>e.startsWith(`${n}=`))}var _y=new Set(["-S","--suffix"]);function Lo(e,t,n,r){if(e.status==="structural-limit")throw new xt;if(e.status!=="complete")return r.findMalformedTarget(e.source);let o={cwd:t,variables:new Map},i=[];for(let s of e.entries){if(s.kind==="operator"){if(!s.boundary)continue;let a=r.findSegmentTarget(i,o);if(a)return a;o=Ay(i,o,n,r.normalizeCwd),i=[];continue}if(s.kind==="redirection"){if(s.role==="file-write"&&s.target&&r.isRedirectionTarget(Se(s.target,o.variables),o))return s.target;continue}i.push(s.text)}return r.findSegmentTarget(i,o)}function Se(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(n,r,o,i)=>{let s=t.get(r);if(s===void 0)return n;let a=o.startsWith(":")?s!=="":!0;if(o.endsWith("-"))return a?s:Se(i,t);return a?Se(i,t):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(n,r)=>t.get(r)??n).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(n,r)=>t.get(r)??n)}function tr(e){return e.length>0&&e.every((t)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t))}function nu(e,t,n){let r=n.environment.home,o=Qr(e.trim(),n.environment).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?tu(r,o.slice(2)):o,s=pe(i);return Py(wy(s)?s:tu(t,s))}function le(e,t,n){let r=nu(e,t,n);if(!r)return"";return H(r,n.environment.paths,n).replace(/\\/g,"/")}function ru(e,t,n,r){let o=nu(e,t,n);if(!o)return null;if(r(Ey(o)))return H(o,n.environment.paths,n).replace(/\\/g,"/");let i=Gl(o,n.environment.paths,n);return i===null?null:i.replace(/\\/g,"/")}function No(e){let t=[],n=null,r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i===void 0)break;if(!r&&i==="--"){r=!0;continue}if(!r&&(i==="-t"||i==="--target-directory")){n=e[++o]??null;continue}if(!r&&i.startsWith("--target-directory=")){n=i.slice(19);continue}if(!r&&i.startsWith("-t")&&i.length>2){n=i.slice(2);continue}if(!r&&_y.has(i)){o++;continue}if(!r&&(i.startsWith("--suffix=")||i.startsWith("--backup=")))continue;if(!r&&i.startsWith("-"))continue;t.push(i)}return n?{sources:t,destination:n}:{sources:t.slice(0,-1),destination:t.at(-1)??null}}function Ay(e,t,n,r){let o=tr(e)?new Map([...t.variables,...ky(e,t.variables)]):t.variables,i=fn([...e],n.environment),s=D(i[0]??"").toLowerCase()==="cd"?i[1]:void 0;return{cwd:!s||s==="-"?t.cwd:r(Se(s,o),t.cwd,n),variables:o}}function ky(e,t){return e.flatMap((n)=>{let r=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(n),o=r?.[2]?.startsWith("=")?r[2].slice(1):void 0;return r?.[1]!==void 0&&o!==void 0?[[r[1],Se(o,t)]]:[]})}var Ae="Git metadata and hooks are protected. Ask the user before modifying them.";function au(e,t=xs([e.invocation.context.executionCwd,e.invocation.context.configCwd])){let n=Mt(ct()),r=e.invocation.context.executionCwd;if(!t)return null;if(e.invocation.route.kind==="patch"||e.invocation.route.kind==="path"||e.invocation.route.kind==="unknown"){if(Oo(e.invocation.toolName))return null;let s=e.paths.find((a)=>Ny(a,r,t,n));return s?{target:s}:null}if(e.invocation.route.kind!=="command")return null;let o=be(e,"input-candidate");if(!o)return null;let i=Lo(o.shell,r,n,{findSegmentTarget:(s,a)=>Fy(s,a,t,n),isRedirectionTarget:(s,a)=>Wy(s,a.cwd,t,n),findMalformedTarget:()=>null,normalizeCwd:le});return i?{target:i}:null}function xs(e,t=Mt(ct())){let n=[...new Map(e.filter((r)=>typeof r==="string"&&r!=="").flatMap((r)=>{let o=zn(le(r,r,t));return o?[[ze(o),{dotGitPath:o,cwd:r}]]:[]})).values()].flatMap((r)=>Oy(r.dotGitPath,r.cwd,t));if(n.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(n.map((r)=>r.entry))]),markerFiles:Object.freeze([...new Set(n.flatMap((r)=>r.markerFile?[r.markerFile]:[]))]),directories:Object.freeze([...new Set(n.flatMap((r)=>r.directories))]),hooksDirectories:Object.freeze([...new Set(n.flatMap((r)=>r.hooksDirectories))])})}function Oy(e,t,n){try{let r=le(e,t,n),o=Ty(e),i=o.isFile()?r:null,s=o.isFile()?Ui(e):null,a=(o.isDirectory()?[r]:[s?.gitDir,s?.commonDir]).flatMap((c)=>c?[ze(le(c,t,n))]:[]),l=[...new Set(o.isDirectory()?[ze(e.replace(/\\/g,"/")),...a]:a)];return[{entry:ze(r),markerFile:i?ze(i):null,directories:l,hooksDirectories:[...new Set(l.flatMap((c)=>{let u=ze(Iy(c,"hooks"));return[u,ze(le(u,t,n))]}))]}]}catch{return[]}}function Gt(e,t,n,r,o,i=!1){if(!n)return!1;let s=ze(le(e,t,o)),a=s.replace(/(\/\.?\*+)+$/,"");if(a!==s&&a!==""){if(Rs(a,n))return!0;let l=i||s.slice(a.length).includes("/."),c=(u)=>l?Wo(u,a):My(u,a);if(n.markerFiles.some(c))return!0;return r&&ou(n).some(c)}if(Rs(s,n))return!0;return r&&ou(n).some((l)=>Wo(l,s))}function My(e,t){let n=su(t,e);if(n===""||n.startsWith("..")||iu(n))return!1;return!n.split(/[\\/]/)[0]?.startsWith(".")}function Dy(e,t,n,r){return Gt(e,t,n,!0,r)}function Ly(e,t,n,r){if(!n)return!1;return Rs(ze(le(e,t,r)),n)}function Ny(e,t,n,r){if(!n)return!1;return lu(e,t,n,r,n.entries)}function Wy(e,t,n,r){if(!n)return!1;return lu(e,t,n,r,n.markerFiles)}function lu(e,t,n,r,o){let i=ze(le(e,t,r));return o.includes(i)||uu(i,n)}function cu(e,t,n,r){if(!n)return!1;return n.hooksDirectories.some((o)=>e.some((i)=>Wo(o,ze(le(i,t,r)))))}function Rs(e,t){return t.entries.includes(e)||t.directories.includes(e)||uu(e,t)}function uu(e,t){return t.hooksDirectories.some((n)=>Wo(e,n))}function ou(e){return[...e.entries,...e.directories,...e.hooksDirectories]}function Wo(e,t){let n=su(t,e);return n===""||!/^\.\.(?:[\\/]|$)/.test(n)&&!iu(n)}function ze(e){return process.platform==="win32"?e.toLowerCase():e}function Fy(e,t,n,r){if(tr(e))return null;let o=vt([...e],r.environment);if(D(o[0]??"").toLowerCase()!=="mv")return null;let i=No(o.slice(1)),s=i.sources.find((a)=>Dy(Se(a,t.variables),t.cwd,n,r));if(s)return s;return i.destination&&Ly(Se(i.destination,t.variables),t.cwd,n,r)?i.destination:null}import{isAbsolute as Es,join as Gy,normalize as zy,sep as Fo}from"node:path";var du=process.platform==="win32",$y=/[*?]/;function nr(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function zo(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=nr(e.trim(),t);if(!Es(n))return"must be an absolute path or start with ~/";return rr(n,t)}function $o(e,t){let n=mu(e,t);if(n===null)return"must be a non-empty path string";if(!Es(n))return null;if(rr(n,t)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var By="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Uy="cannot cover the guard's own configuration";function mu(e,t){if(typeof e!=="string"||e.trim()==="")return null;return nr(e.trim().replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function Bo(e,t){let n=mu(e,t);if(n===null)return"must be a non-empty path string";if($y.test(n))return"cannot contain glob characters (* or ?); list the exact file or directory";if(!Es(n))return null;if(rr(n,t)!==null)return By;return Hy(n,t)?Uy:null}function Hy(e,t){let n=Go(e),r=Go(Gy(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${Fo}`)}function rr(e,t){let n=Go(e),r=Go(t);if(n===r)return"cannot be the home directory";let o=n.endsWith(Fo)?n:`${n}${Fo}`;if(r.startsWith(o))return"cannot contain the home directory";return null}function Go(e){let t=zy(e);if(du)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(du?3:1)&&t.endsWith(Fo))t=t.slice(0,-1);return t}var qy=process.platform==="win32",fu=64,Ky=16384;function or(e){let t=Cc(e,fu,fu,Ky);return{expandedTargets:t&&"words"in t?t.words:void 0,unsafeBraceExpansion:t!==void 0&&"limited"in t,targetIsLiteral:t===void 0&&e.provenance==="literal"&&(e.quoted||e.raw!==e.text),tmpdirWordSplittingProtected:Yy(e)}}function Yy(e){let t=e.parts.filter((n)=>n.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(n.raw));return t.length>0&&t.every((n)=>Zy(e.raw,n.span.start-e.span.start))}function Zy(e,t){let n=null,r=!1;for(let o=0;o<t;o++){let i=e[o];if(r){r=!1;continue}if(i==="\\"&&n!=="'"){r=!0;continue}if(n===i){n=null;continue}if(n===null&&(i==="'"||i==='"'))n=i}return n==='"'}function zt(e){let t=e.environment.home,n=e.environment.paths,r=Mt(e.environment);return{anchoredCwd:e.originalCwd??e.cwd??null,resolvedCwd:e.cwd??null,strict:e.strict??!1,paranoid:e.paranoid??!1,trustTmpdirVar:e.allowTmpdirVar??!0,posixShell:e.posixShell??!1,tmpdirWordSplittingUnsafe:e.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:e.trustedTmpdirValue??e.allowTmpdirVar??!0,environment:e.environment,allowRoots:tC(e.allowPaths,t,n,r),protectedGitMetadata:e.protectedGitMetadata,pathCanonicalizationContext:r}}function $e(e,t,n={}){let r=n.targetIsLiteral??!1;if(!r&&t.tmpdirWordSplittingUnsafe&&!n.tmpdirWordSplittingProtected&&rC(e))return{kind:"outside_anchored_cwd"};let o=!r&&yu(e,t.posixShell);if(Tt(e))return{kind:"outside_anchored_cwd"};if(As(e,r))return{kind:"root_or_home_target"};if(Xy(e,t,r))return{kind:"root_or_home_target"};if(t.resolvedCwd&&Gt(e,t.resolvedCwd,t.protectedGitMetadata,!0,t.pathCanonicalizationContext,!t.posixShell))return{kind:"git_metadata_target"};if(Jy(e,t.trustTmpdirVar,t.posixShell,o,r,n.tmpdirWordSplittingProtected??!1,t.trustedTmpdirValue,t.environment))return{kind:"temp_target"};if(o)return{kind:"dynamic_target"};if(nC(e,t,r))return{kind:"temp_target"};let i=t.anchoredCwd;if(i){if(!n.skipHomeCwd&&aC(i,t.environment.home,t.environment.paths,t.pathCanonicalizationContext))return{kind:"home_cwd_target"};if(!n.skipCwdSelf&&lC(e,t.resolvedCwd??i,t.environment.paths,t.pathCanonicalizationContext))return{kind:"cwd_self_target"};if(cC(e,i,t.resolvedCwd??i,o,r,t.environment.paths,t.pathCanonicalizationContext))return{kind:"within_anchored_cwd"}}return{kind:"outside_anchored_cwd"}}function gu(e,t,n={}){let{containmentTarget:r,...o}=n;if($e(e,t,o).kind!=="temp_target")return!1;let i=e.trim();if(eC(i))return!1;if(Ql(i,t.environment))return!1;return![t.anchoredCwd,t.resolvedCwd].some((s)=>uC(r??i,s,t.environment.paths,t.pathCanonicalizationContext))}function As(e,t=!1){let n=e.trim(),r=pu.normalize(n),o=n.replace(/\\/g,"/"),i=r==="/"?r:r.replace(/\/+$/,"");if(i==="/"||i.startsWith("/")&&i.slice(1).split("/").every((s)=>/^\*+$/.test(s)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(o)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(o))return!0;if(!t&&(r==="~"||r==="~/"||r==="~/*"))return!0;if(!t&&(r==="$HOME"||r==="$HOME/"||r==="$HOME/*"))return!0;if(!t&&(r==="${HOME}"||r==="${HOME}/"||r==="${HOME}/*"))return!0;return!1}function Xy(e,t,n){let r=e.trim(),o=n?r:r==="*"?".":r.endsWith("/*")?r.slice(0,-2):r;if(!o)return!1;try{let i=_s(o)?o:t.resolvedCwd?yn(t.resolvedCwd,o):null;if(!i)return!1;let s=me(H(i,t.environment.paths,t.pathCanonicalizationContext));if(s===Vy(s).root)return!0;return s===me(H(t.environment.home,t.environment.paths,t.pathCanonicalizationContext))}catch{return!1}}function me(e){let t=jy(e);if(qy){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 Jy(e,t,n,r,o,i,s,a){let l=e.trim();if(hu(l))return!1;if(!r&&es(l,a))return!0;return(t||i&&s)&&n&&!o&&Qy(l,n)}function Qy(e,t){return["$TMPDIR","${TMPDIR}"].some((n)=>{if(e===n)return!0;if(!e.startsWith(`${n}/`))return!1;return!yu(e.slice(n.length+1),t)})}function eC(e){let t=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(e);if(!t)return!1;return pu.normalize(`/${t[1]??""}`)==="/"}function hu(e){return e.split(/[\\/]+/).includes("..")}function tC(e,t,n,r){if(!e?.length)return[];return e.flatMap((o)=>{let i=nr(o.trim(),t);if(!_s(i))return[];try{let s=H(i,n,r);if(rr(s,H(t,n,r)))return[];return[me(s)]}catch{return[]}})}function nC(e,t,n){if(t.allowRoots.length===0)return!1;let r=e.trim();if(hu(r))return!1;let o=n?r:nr(r,t.environment.home),i=t.resolvedCwd??t.anchoredCwd,s=_s(o)?o:i?yn(i,o):null;if(!s)return!1;try{let a=me(H(s,t.environment.paths,t.pathCanonicalizationContext));return t.allowRoots.some((l)=>a===l||a.startsWith(l.endsWith(Ps)?l:`${l}${Ps}`))}catch{return!1}}function rC(e){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(e)}function yu(e,t=!1){return e.includes("$")||e.includes("`")||oC(e)||t&&iC(e)}function oC(e){let t=!1;for(let n of e){if(t){t=!1;continue}if(n==="\\"){t=!0;continue}if(n==="*"||n==="?"||n==="[")return!0}return!1}function iC(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(t){t=!1;continue}if(r==="\\"){t=!0;continue}if(r==="{"&&sC(e,n)||(r==="+"||r==="@"||r==="!")&&e[n+1]==="(")return!0}return!1}function sC(e,t){let n=e.indexOf("}",t+1);if(n===-1)return!1;let r=e.slice(t+1,n);return r.includes(",")||r.includes("..")}function aC(e,t,n,r){try{return me(H(e,n,r))===me(H(t,n,r))}catch{try{return me(e)===me(t)}catch{return!1}}}function lC(e,t,n,r){if(e==="."||e==="./"||e===".\\")return!0;try{return me(H(yn(t,e),n,r))===me(H(t,n,r))}catch{try{return me(yn(t,e))===me(t)}catch{return!1}}}function cC(e,t,n,r,o,i,s){let a=n??t;if(!o&&(e.startsWith("~")||e.startsWith("$HOME")||e.startsWith("${HOME}")))return!1;if(r)return!1;if(e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e))try{return ws(e,t,i,s)}catch{return!1}if(e.startsWith("./")||e.startsWith(".\\")||!e.includes("/")&&!e.includes("\\"))try{return ws(yn(a,e),t,i,s)}catch{return!1}if(e.startsWith("../"))return!1;try{return ws(yn(a,e),t,i,s)}catch{return!1}}function ws(e,t,n,r){try{return Cu(H(e,n,r),H(t,n,r))}catch{return!1}}function uC(e,t,n,r){if(!t)return!1;try{return Cu(H(t,n,r),H(e,n,r))}catch{return!0}}function Cu(e,t){let n=me(e),r=me(t);return n.startsWith(`${r}${Ps}`)||n===r}var dC=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),bu="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",mC="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.",Su="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",vu="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",fC="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",pC="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.";function Ru(e,t,n,r=zt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths})){return gC(e.words.map((o)=>({kind:"word",text:o.text,dynamic:o.provenance!=="literal"})),t,r,n.policy)}function gC(e,t,n,r){let o=e.filter((l)=>l.kind==="word"),i=yC(o),s=o[i];if(!s||!dC.has(PC(s.text)))return null;let a=hC(o.slice(i+1));if(a.whatIfProtected)return null;if(Q(r,"powershell.remove-item-pipeline-dynamic-target",n.strict)&&t&&(a.targets.length===0||a.recursive))return b("powershell.remove-item-pipeline-dynamic-target",pC);for(let l of a.targets)if(!Tt(l.text)&&As(Ts(l.text)))return b(a.recursive&&a.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",vu);for(let l of a.targets)if(n.resolvedCwd&&Gt(Ts(l.text),n.resolvedCwd,n.protectedGitMetadata,a.recursive,n.pathCanonicalizationContext,!0))return b("powershell.remove-item-git-metadata",Ae);if(!a.recursive||!a.force)return null;if(Q(r,"powershell.remove-item-recursive-force-dynamic-target",n.strict)&&(a.hasDynamicTarget||a.targets.length===0))return b("powershell.remove-item-recursive-force-dynamic-target",Su);for(let l of a.targets){let c=_C($e(Ts(l.text),n),n,r);if(c)return c}return null}function hC(e){let t=[],n=!1,r=!1,o=!1,i=!1,s=!1;for(let a=0;a<e.length;a++){let l=e[a];if(!l||l.kind!=="word")continue;if(CC(l))continue;if(s){t.push(ks(l)),i=i||l.dynamic;continue}if(l.text==="--"){s=!0;continue}let c=SC(l.text);if(!c){t.push(ks(l)),i=i||l.dynamic;continue}if(vC(c.name)){let u=c.value?bC(c.value,l):e[++a];if(u?.kind==="word")t.push(ks(u)),i=i||u.dynamic;else i=!0;continue}if(RC(c.name)){n=!0;continue}if(xC(c.name)){r=!0;continue}if(EC(c.name))o=wC(c.value)}return{targets:t,recursive:n,force:r,whatIfProtected:o,hasDynamicTarget:i}}function yC(e){let t=e[0];if(t?.kind==="word"&&t.text==="&"||t?.text===".")return e.length>1?1:0;return 0}function ks(e){return{text:e.kind==="word"?e.text:"",dynamic:e.kind==="word"&&e.dynamic}}function CC(e){return e.kind==="word"&&e.text===","}function Ts(e){let t=e.replace(/\\/g,"/"),n=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(t);return n?`$HOME${t.slice(n[0].length)}`:t}function bC(e,t){return{kind:"word",text:e,dynamic:t.kind==="word"&&(t.dynamic||e.includes("$"))}}function SC(e){if(!e.startsWith("-")||e==="-")return null;let t=e.slice(1),n=t.indexOf(":");if(n===-1)return{name:t.toLowerCase()};return{name:t.slice(0,n).toLowerCase(),value:t.slice(n+1)}}function vC(e){return"path".startsWith(e)||"literalpath".startsWith(e)}function RC(e){return"recurse".startsWith(e)}function xC(e){return e.length>=2&&"force".startsWith(e)}function EC(e){return e==="wi"||"whatif".startsWith(e)}function wC(e){if(e===void 0||e==="")return!0;let t=e.toLowerCase();return t==="$true"||t==="true"}function PC(e){return e.toLowerCase()}function _C(e,t,n){switch(e.kind){case"root_or_home_target":return b("powershell.remove-item-recursive-force-root-or-home",vu);case"git_metadata_target":return b("powershell.remove-item-git-metadata",Ae);case"temp_target":return null;case"dynamic_target":if(!Q(n,"powershell.remove-item-recursive-force-dynamic-target",t.strict))return null;return b("powershell.remove-item-recursive-force-dynamic-target",Su);case"home_cwd_target":return b("powershell.remove-item-recursive-force-home-cwd",fC);case"cwd_self_target":return b("powershell.remove-item-recursive-force-cwd-self",bu);case"within_anchored_cwd":if(!Q(n,"powershell.remove-item-recursive-force-paranoid",t.paranoid))return null;return b("powershell.remove-item-recursive-force-paranoid",mC);case"outside_anchored_cwd":return b("powershell.remove-item-recursive-force-outside-cwd",bu)}}import{normalize as oi}from"node:path";var ve=new Set(["awk","gawk","nawk","mawk"]),AC=new Set(["-e","--source"]),kC=new Set(["-F","-v","--assign","--field-separator"]),xu=new Set(["-f","--file"]),TC=new Set(["print","printf","return"]),Eu=[{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"}],IC="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 jo(e,t,n){let r=!1;for(let o of OC(e)){let i=MC(o,n);if(!i)continue;for(let s of i.commands){let a=t(s);if(a)return a;if(s.includes("{}")||/[$`]/.test(s))r=!0}r||=i.dynamic}return r?b("awk.system-dynamic",IC):null}function Os(e){let t=[],n=!1,r=!1,o=!0,i=!0;for(let s=1;s<e.length;s++){let a=e[s];if(a===void 0)break;if(o&&a==="--"){o=!1;continue}if(o&&AC.has(a)){n=!0;let l=e[s+1];if(l!==void 0)t.push({tokenIndex:s+1,kind:"inline-code",value:l});else i=!1;s++;continue}if(o&&a.startsWith("--source=")){n=!0,t.push({tokenIndex:s,kind:"inline-code",value:a.slice(9)});continue}if(o&&a.startsWith("-e")&&a.length>2){n=!0,t.push({tokenIndex:s,kind:"inline-code",value:a.slice(2)});continue}if(o&&(kC.has(a)||xu.has(a))){if(xu.has(a)){r=!0;let l=e[s+1];if(l!==void 0)t.push({tokenIndex:s+1,kind:"program-file",value:l});else i=!1}else if(e[s+1]===void 0)i=!1;s++;continue}if(o&&(a.startsWith("-F")||a.startsWith("-v")&&a.slice(2).includes("=")))continue;if(o&&a.startsWith("-f")&&a.length>2){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(2)});continue}if(o&&(a.startsWith("--assign=")||a.startsWith("--field-separator=")))continue;if(o&&a.startsWith("--file=")){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(7)});continue}if(o&&a.startsWith("-")&&a!=="-")continue;if(o=!1,!n&&!r)t.push({tokenIndex:s,kind:"main-program",value:a});return{sources:t,optionsOpen:!1}}return{sources:i?t:[],optionsOpen:o&&i}}function sr(e){return Os(e).sources}function OC(e){return sr(e).filter((t)=>t.kind!=="program-file").map((t)=>t.value)}function MC(e,t){ge(t,e);let n=e.includes("system")?Ms(e,t):null,r=DC(e,t);if(!n&&!r)return null;return{dynamic:!!n?.dynamic||!!r?.dynamic,commands:[...n?.commands??[],...r?.commands??[]]}}function Ms(e,t){ge(t,e);let n=[],r=!1,o=!1,i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){i=Ho(e,i,s)?.endIndex??i+1;continue}if(s==="#"){i=wu(e,i+1);continue}if(s==="/"&&Pu(e,i)){i=_u(e,i+1)??i+1;continue}if(!e.startsWith("system",i)){i++;continue}let a=i;if(i+=6,ir(e[a-1])||ir(e[i]))continue;let l=Uo(e,i);if(e[l]!=="(")continue;l=Uo(e,l+1);let c=e[l];if(c!=='"'&&c!=="'"){r=!0,o=!0;continue}let u=Ho(e,l,c);if(!u){r=!0,o=!0;continue}if(l=Uo(e,u.endIndex),r=!0,e[l]!==")"){o=!0,i=u.endIndex;continue}n.push(u.value),i=l+1}if(!r)return null;return{dynamic:o,commands:n}}function DC(e,t){ge(t,e);let n=[],r=!1,o=!1,i=0,s=0,a=null,l=null,c=0;while(i<e.length){let u=e[i];if(!u)break;if(u==='"'||u==="'"){let d=Ho(e,i,u);if(d&&c===s)l={...d,startIndex:i};c=d?.endIndex??i+1,i=d?.endIndex??i+1;continue}if(u==="#"){i=wu(e,i+1),s=i,a=null,l=null,c=i;continue}if(u==="/"&&Pu(e,i)){let d=_u(e,i+1);c=d??i+1,i=d??i+1;continue}if(`;
31
+ {}`.includes(u)){i++,s=i,a=null,l=null,c=i;continue}if(a===null&&(Is(e,i,"print")||Is(e,i,"printf")))a=i;if(u!=="|"||e[i-1]==="|"||e[i+1]==="|"){if(!/\s/.test(u))c=i+1;i++;continue}let m=e[i+1]==="&"?i+2:i+1,f=Uo(e,m);if(Is(e,f,"getline")){o=!0;let d=WC(s,l,c);if(d===null)r=!0;else n.push(d);c=m,i=m;continue}if(GC(s,a)){o=!0;let d=NC(e,f);if(!d){r=!0,c=m,i=m;continue}if(!LC(e,d.endIndex)){r=!0,c=d.endIndex,i=d.endIndex;continue}n.push(d.value),c=d.endIndex,i=d.endIndex;continue}c=m,i++}if(!o)return null;return{dynamic:r,commands:n}}function ir(e){return!!e&&/[A-Za-z0-9_]/.test(e)}function Uo(e,t){let n=t;while(/\s/.test(e[n]??""))n++;return n}function LC(e,t){let n=t;while(/[\t\f\v\r ]/.test(e[n]??""))n++;let r=e[n];return!r||`;
32
+ }#`.includes(r)}function Ho(e,t,n){let r="",o=!1;for(let i=t+1;i<e.length;i++){let s=e[i];if(!s)break;if(o){let a=FC(e,i);if(!a)return null;r+=a.value,i=a.endIndex,o=!1;continue}if(s==="\\"){o=!0;continue}if(s===n)return{value:r,endIndex:i+1};r+=s}return null}function NC(e,t){let n=e[t];if(n!=='"'&&n!=="'")return null;return Ho(e,t,n)}function WC(e,t,n){if(!t)return null;return t.startIndex>=e&&t.endIndex===n?t.value:null}function FC(e,t){let n=e[t];if(!n)return null;if(n==="x"){let o=e.slice(t+1,t+3);if(!/^[0-9A-Fa-f]{2}$/.test(o))return null;return{value:String.fromCharCode(Number.parseInt(o,16)),endIndex:t+2}}if(/[0-7]/.test(n)){let o=/^[0-7]{1,3}/.exec(e.slice(t));if(!o)return null;return{value:String.fromCharCode(Number.parseInt(o[0],8)),endIndex:t+o[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
33
+ `,r:"\r",t:"\t",v:"\v"}[n]??n,endIndex:t}}function Is(e,t,n){return e.startsWith(n,t)&&!ir(e[t-1])&&!ir(e[t+n.length])}function GC(e,t){return t!==null&&t>=e}function wu(e,t){let n=e.indexOf(`
34
+ `,t);return n===-1?e.length:n+1}function Pu(e,t){let n=zC(e,t);if(n===-1)return!0;if("{([,;!~=".includes(e[n]??""))return!0;let r=n;while(ir(e[r-1]))r--;return TC.has(e.slice(r,n+1))}function zC(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function _u(e,t){let n=!1;for(let r=t;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="/")return r+1}return null}var Au=new Set(["rm","find","xargs","parallel"]),$C=new Set(["sudo","env","command","builtin"]),BC=new Set(["git","busybox",...Au,...ee,...Ul,...ve]);function Vo(e,t){let n=e[0];if(!n||!t.transparentWrappers.includes(D(n)))return null;let r=D(n),o=e[1]==="--"?2:1,i=UC(e,o,r,t),s=i[0];if(s===void 0)return null;return{wrapper:r,tokens:[...e.slice(s)],childIndex:s,alternativeChildIndices:i.slice(1)}}function UC(e,t,n,r){let o=e[1]==="--",i=[];for(let s=t;s<e.length;s++){let a=e[s];if(!a)continue;if(D(a)!==n&&HC(a,r))i.push(s);else if(to.has(z(a)))break;if(o)break}return i}function HC(e,t){let n=D(e),r=z(e);return r==="git"||n==="busybox"||$t(e)||Au.has(n)||t.transparentWrappers.includes(n)||ee.has(r)||e==="$SHELL"||ye(r)||ve.has(r)||t.rules.some((o)=>o.command===n)}function $t(e){return $C.has(e.toLowerCase())}function ku(e){let t=z(e);return BC.has(t)||ye(t)}function Be(e,t){let n=t.policy??{rules:[],transparentWrappers:[]};return qo([...e],t.environment,t.cwd,t.cwd,new Map,new Map(t.envAssignments??[]),n,{iterations:0},!1)}function*qo(e,t,n,r,o,i,s,a,l){let c=po(e,t,n,i);for(let[d,p]of c.envAssignments)i.set(d,p),o.set(d,p);let{tokens:u,cwd:m}=c;if(c.envSplitValues){let d=fo(c.envSplitValues,u);if(!d)throw new he;Ds(a),yield*qo(d,t,m,r,o,i,s,a,l);return}if($t(u[0]??""))throw new he;let f=Vo(u,s);if(f){for(let d of[f.childIndex,...f.alternativeChildIndices])Ds(a),yield*qo(d===f.childIndex?f.tokens:[...u.slice(d)],t,m,r,new Map(o),new Map(i),s,a,!0);return}if(VC(u)){Ds(a),yield*qo([...u.slice(1)],t,m,r,o,i,s,a,l);return}yield jC(u,m,r,o,i,l)}function jC(e,t,n,r,o,i){return{tokens:e,cwd:t===null?void 0:t??n,wrapperCwd:t,wrapperEnvAssignments:r,envAssignments:o,head:D(e[0]??"").toLowerCase(),wrappedByTransparent:i}}function Ds(e){if(e.iterations>=ln)throw new he;e.iterations++}function VC(e){return D(e[0]??"").toLowerCase()==="busybox"&&e.length>1}function Ls(e,t){let n=[],r=t;while(r<e.length){let o=e[r];if(o===void 0||o===":::")break;n.push(o),r++}return{markerIndex:r<e.length&&e[r]===":::"?r:-1,templateTokens:n}}function Ue(e){let t=!1,n=!1;for(let r of e){if(r==="--")break;if(r==="-r"||r==="-R"||Ns(r,"recursive"))t=!0;else if(r==="-f"||Ns(r,"force"))n=!0;else if(r.startsWith("-")&&!r.startsWith("--")){if(r.includes("r")||r.includes("R"))t=!0;if(r.includes("f"))n=!0}}return t&&n}function Tu(e){let t=e.indexOf("--");return e.slice(1,t===-1?void 0:t).some((n)=>Ns(n,"recursive")||/^-[A-Za-z]+$/.test(n)&&/[rR]/.test(n.slice(1)))}function Ns(e,t){return e.length>2&&e.startsWith("--")&&t.startsWith(e.slice(2))}var qC="find -delete permanently removes files. Use -print first to preview.",KC="find -exec rm -rf is dangerous. Use explicit file list instead.",YC=new Set(["-exec","-execdir","-ok","-okdir"]),ZC=new Map([...["-Bmin","-Bnewer","-Btime","-amin","-anewer","-atime","-cmin","-cnewer","-context","-ctime","-f","-flags","-fprint","-fprint0","-fls","-fstype","-gid","-group","-ilname","-iname","-inum","-ipath","-iwholename","-iregex","-links","-lname","-maxdepth","-mindepth","-mmin","-mnewer","-mtime","-name","-newer","-newerXY","-newermt","-path","-perm","-printf","-regex","-samefile","-size","-type","-uid","-used","-user","-wholename","-xattrname","-xtype"].map((e)=>[e,1]),["-fprintf",2]]);function Ko(e,t){let n=e.map(I),r=XC(e,n,t);if(r)return r;if(Zo(n,1)&&!QC(e,n,t)){let s=k(b("find.delete",qC),t.policy);if(s)return s}let o=t.derivedCommandWorkBudget??Zr(),i=0;while(i<n.length){let s=n[i],a=Et(s??"");if(a>0){i+=a+1;continue}if(!pt(s)){i++;continue}Le(o,n.length-i-1);let l=ar(n,i);i=l.nextIndex;let c=tb(l.tokens,t.environment);if(c){let d=k(c,t.policy);if(d)return d}let u=s==="-execdir"||s==="-okdir",m=t.analyzeTokens?t.analyzeTokens(l.tokens,u?null:t.cwd):t.analyzeNested?t.analyzeNested(l.tokens.join(" "),{effectiveCwd:u?void 0:t.cwd,envAssignments:t.envAssignments}):null,f=m?.id.startsWith("custom.")?m:k(m,t.policy);if(f)return f}return null}function XC(e,t,n){if(!Zo(t,1)&&!Ws(t,n.environment))return null;let o=Yo(e)??G(["."]),i=zt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let s of o){let a=or(s);for(let l of a.expandedTargets??[I(s)]){let c=$e(l,i,{targetIsLiteral:a.expandedTargets!==void 0||a.targetIsLiteral,tmpdirWordSplittingProtected:a.tmpdirWordSplittingProtected});if(c.kind==="root_or_home_target")return b("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(c.kind==="git_metadata_target")return b("find.delete-git-metadata",Ae)}}if(JC(t)&&i.resolvedCwd&&cu(o.map(I),i.resolvedCwd,i.protectedGitMetadata,i.pathCanonicalizationContext))return b("find.delete-git-metadata",Ae);return null}function Ws(e,t){let n=0;while(n<e.length){if(!pt(e[n])){n++;continue}let r=ar(e,n),o=vt([...r.tokens],t),i=D(o[0]??"").toLowerCase();if((i==="rm"||i==="rmdir")&&o.some((s)=>s.includes("{}")))return!0;n=r.nextIndex}return!1}function JC(e){return e.some((t,n)=>{if(!["-name","-iname"].includes(t))return!1;return e[n+1]?.toLowerCase()==="hooks"})}function QC(e,t,n){if(t.includes("-L")||t.includes("-f")||t.includes("-follow"))return!1;let r=Yo(e);if(!r)return!1;let o=n.envAssignments??new Map,i=Qi(o,n.environment),s=n.trustedTmpdirValue??ft(o,n.environment),a=n.allowTmpdirVar??!jn(o,n.environment),l=zt({environment:n.environment,protectedGitMetadata:n.protectedGitMetadata,cwd:n.cwd,originalCwd:n.originalCwd,strict:n.strict,allowTmpdirVar:a&&s&&Boolean(i),allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:n.tmpdirWordSplittingUnsafe??Ze(o,n.environment),trustedTmpdirValue:s});return r.every((c)=>{let u=or(c);if(u.unsafeBraceExpansion)return!1;return(u.expandedTargets??[I(c)]).every((m)=>gu(m,l,{containmentTarget:eb(m,i),targetIsLiteral:u.expandedTargets!==void 0||u.targetIsLiteral,tmpdirWordSplittingProtected:u.tmpdirWordSplittingProtected}))})}function eb(e,t){if(!t)return e;return e.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>t)}function Yo(e){let t=(o)=>{let i=e[o];return i?I(i):void 0},n=1;while(t(n)==="-H"||t(n)==="-P")n++;if(t(n)==="--")n++;let r=[];while(n<e.length){let o=t(n),i=e[n];if(!o||!i||o.startsWith("-")||["!","(",")"].includes(o))break;r.push(i),n++}return r.length>0?r:null}function tb(e,t){let n=fn([...e],t);if(n.length===0)return null;let r=D(n[0]??"");if(r==="busybox"&&n.length>1)n=n.slice(1),r=D(n[0]??"");if(r==="rm"&&Ue(n))return b("find.exec-rm-recursive-force",KC);return null}function ar(e,t){let n=t+1;while(n<e.length&&e[n]!==";"&&!(e[n]==="+"&&e[n-1]==="{}"))n++;return{tokens:e.slice(t+1,n),nextIndex:Math.min(n+1,e.length)}}function Zo(e,t){let n=t;while(n<e.length){let r=e[n];if(!r){n++;continue}if(pt(r)){n=ar(e,n).nextIndex;continue}let o=Et(r);if(o>0){n+=o+1;continue}if(r==="-delete")return!0;n++}return!1}function Et(e){return ZC.get(e)??(/^-newer[A-Za-z]{2}$/.test(e)?1:0)}function pt(e){return e!==void 0&&YC.has(e)}function*Fs(e){for(let t of e.nodes)yield*rb(t)}function nb(e){return Object.freeze([...Fs(e)])}function NA(e){return Object.freeze(nb(e).map((t)=>Object.freeze(t.words.map((n)=>n.text))))}function lr(e){let t=Fe(e,"posix");if(t.status!=="complete"||t.nodes.length!==1)return null;let n=t.nodes[0];if(n?.kind!=="command")return null;if(n.redirections.length>0||n.nested.length>0)return null;if(n.words.some((r)=>r.provenance==="command-substitution"))return null;return n.words.map((r)=>r.text)}function*rb(e){if(e.kind==="command"){yield e;for(let t of e.nested)yield*Fs(t);return}if(e.kind==="group")yield*Fs(e.body)}var ob=5,Gs="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 ce(e){let t=e.indexOf("--");if(t===-1)return{index:-1,before:e,after:[]};return{index:t,before:e.slice(0,t),after:e.slice(t+1)}}function Ou(e,t,n){let r=Du(e,t,n),o=ib(r.entries);if(o.size===0)return{blockedReason:r.blockedReason,expanded:!1,tokens:e};let i=e,s=!1;for(let a=0;a<ob;a++){let{subcommand:l,rest:c}=He(i),u=l?.toLowerCase();if(!u||!o.has(u))return{blockedReason:r.blockedReason,expanded:s,tokens:i};let m=o.get(u),f=ub(m);if(f===null||f.length===0)return{blockedReason:Gs,expanded:!0,tokens:i};i=["git",...f,...c],s=!0}return{blockedReason:Gs,expanded:!0,tokens:i}}function Mu(e,t,n){return Du(e,t,n).entries.some((r)=>r.key.toLowerCase()==="core.sshcommand")}function He(e){if(e.length===0)return{subcommand:null,rest:[]};let t=e[0];if((t?D(t).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let r=1;while(r<e.length){let o=e[r];if(!o)break;if(o==="--"){let i=e[r+1];if(i&&!i.startsWith("-"))return{subcommand:i,rest:e.slice(r+2)};return{subcommand:null,rest:e.slice(r+1)}}if(o.startsWith("-"))if(Ye.has(o))r+=2;else if(o.startsWith("-c")&&o.length>2)r++;else if(o.startsWith("-C")&&o.length>2)r++;else r++;else return{subcommand:o,rest:e.slice(r+1)}}return{subcommand:null,rest:[]}}function ib(e){let t=new Map;for(let n of e){let r=n.key.toLowerCase();if(!r.startsWith("alias."))continue;let o=r.slice(6);if(o!=="")t.set(o,n.value)}return t}function Du(e,t,n){if(e.length===0)return{blockedReason:null,entries:[]};let r=e[0];if((r?D(r).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let i=ab(t,n);return{blockedReason:i.blockedReason,entries:[...i.entries,...sb(e,t,n)]}}function sb(e,t,n){let r=[],o=1;while(o<e.length){let i=e[o];if(!i||i==="--"||!i.startsWith("-"))return r;if(i==="-c"){let s=zs(e[o+1]);if(s)r.push(s);o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=zs(i.slice(2));if(s)r.push(s);o++;continue}if(i==="--config-env"){let s=Iu(e[o+1],t,n);if(s)r.push(s);o+=2;continue}if(i.startsWith("--config-env=")){let s=Iu(i.slice(13),t,n);if(s)r.push(s);o++;continue}if(Ye.has(i)){o+=2;continue}o++}return r}function ab(e,t){let n=lb(e,t),r=cb(e,t);return{blockedReason:n===null||r===null?Gs:null,entries:[...n??[],...r??[]]}}function lb(e,t){let n=we("GIT_CONFIG_PARAMETERS",e,t);if(n===void 0)return[];let r=[],o=lr(n);if(!o)return null;for(let i of o){let s=zs(i);if(!s)return null;r.push(s)}return r}function cb(e,t){let n=zr(e,t);if(n.state==="absent")return[];if(n.state==="invalid")return null;let r=[];for(let o=0;o<n.count;o++){let i=we(`GIT_CONFIG_KEY_${o}`,e,t)?.trim(),s=we(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i||s===void 0)return null;r.push({key:i,value:s})}return r}function zs(e){if(!e)return null;let t=e.indexOf("=");return{key:(t===-1?e:e.slice(0,t)).trim(),value:t===-1?void 0:e.slice(t+1)}}function Iu(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;return{key:e.slice(0,r).trim(),value:we(e.slice(r+1),t,n)}}function ub(e){let t=e?.trimStart();if(!t||t.startsWith("!"))return null;return lr(t)}var db="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",mb="git checkout --force discards uncommitted changes. Use 'git stash' first.",fb="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",pb="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",gb="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",hb="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",yb="git switch --force discards uncommitted changes. Use 'git stash' first.",Cb="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",bb="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",Sb="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",vb="git reset --merge can lose uncommitted changes. Use 'git stash' first.",Rb="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",xb="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.",Eb="git push --force destroys remote history. Use --force-with-lease for safer force push.",wb="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",Pb="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",_b="git branch -D force-deletes without merge check. Use -d for safe delete.",Ab="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",kb="git merge --abort discards merge conflict resolutions. Use 'git status' first.",Tb="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",Ib="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",Ob="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",Mb="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",Db="git worktree remove --force can delete uncommitted changes. Remove --force flag.",Lu=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),Nu=new Set(["--recurse-submodules","--track","-t"]),$s=new Set(["-b","-B","-U"]),Bs=new Set(["-c","-C"]),Lb=new Set(["--source","--conflict","--unified","--inter-hunk-context"]),Nb=new Set(["-q","--quiet","--no-quiet","-f","--force","--no-force","-d","--detach","--no-detach","-m","--merge","--no-merge","-p","--patch","--no-patch","--guess","--no-guess","--overlay","--no-overlay","--ours","--theirs","--ignore-skip-worktree-bits","--no-ignore-skip-worktree-bits","--no-track","--overwrite-ignore","--no-overwrite-ignore","--ignore-other-worktrees","--no-ignore-other-worktrees","--progress","--no-progress","--pathspec-file-nul","--no-pathspec-file-nul","--no-recurse-submodules"]);function W(e,t){let n=e.split("=",1)[0]??e;return n.length>=4&&t.startsWith(n)&&n.startsWith("--")&&n.slice(2).length>=2}var Cn=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function Fu(e){let{subcommand:t,rest:n}=He(e);if(!t)return null;switch(t.toLowerCase()){case"checkout":return wt(Wb(n));case"switch":return wt(Fb(n));case"restore":return wt(zb(n));case"reset":return Bb(n);case"clean":return wt(Hb(n));case"rm":return wt(jb(n));case"push":return Bt(Vb(n));case"branch":return Bt(Yb(n));case"stash":return Bt(eS(n));case"worktree":return Bt(tS(n));case"rebase":return wt(Zb(n));case"merge":return wt(Xb(n));case"tag":return Bt(Jb(n));case"reflog":return Bt(Qb(n));default:return null}}function wt(e){return e?{...e,localDiscard:!0}:null}function Bt(e){return e?{...e,localDiscard:!1}:null}function Wb(e){let{index:t,before:n}=ce(e),r=de(n,{shortOptsWithValue:$s});if(n.some((i)=>W(i,"--force"))||r.has("-f"))return b("git.checkout-force",mb);for(let i of e){if(i==="-b"||i==="-B"||i==="--orphan")return null;if(W(i,"--pathspec-from-file"))return b("git.checkout-pathspec-from-file",pb)}if(t!==-1){if(n.some((s)=>!s.startsWith("-")))return b("git.checkout-ref-path",fb);return b("git.checkout-double-dash",db)}if(Gb(e).length>=2)return b("git.checkout-ambiguous",gb);return null}function Fb(e){let{before:t}=ce(e);if(t.some((r)=>W(r,"--discard-changes")))return b("git.switch-discard-changes",hb);let n=de(t,{shortOptsWithValue:Bs});if(t.some((r)=>W(r,"--force"))||n.has("-f"))return b("git.switch-force",yb);return null}function Gb(e){let t=[],n=0;while(n<e.length){let r=e[n];if(!r)break;if(r==="--")break;if(r.startsWith("-"))if(Lu.has(r))n+=2;else if(r.startsWith("--")&&r.includes("="))n++;else if(Nu.has(r)){let o=e[n+1];if(o&&!o.startsWith("-")&&(r==="--recurse-submodules"||r==="--track"||r==="-t"))if((r==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"]).includes(o))n+=2;else n++;else n++}else if(r.startsWith("--")&&!Nb.has(r)&&!Lu.has(r)&&!Nu.has(r))n++;else n++;else t.push(r),n++}return t}function zb(e){let t=$b(e);if(t.isTerminal||!t.hasPathspec&&!t.hasPatch||!t.hasWorktree)return null;return t.hasExplicitLocation?b("git.restore-worktree",bb):b("git.restore-unstaged",Cb)}function $b(e){let t=!1,n=!1,r=!0,o=!1,i=(s)=>{if(!o)r=!1,o=!0;if(s!==void 0)r=s};for(let s=0;s<e.length;s++){let a=e[s];if(a===void 0)break;if(a==="--"){t||=s+1<e.length;break}if(a==="--pathspec-from-file"){t=!0,s++;continue}if(a.startsWith("--pathspec-from-file=")){t=!0;continue}if(a==="-h"||a==="--help"||a==="--version")return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!0};if(a==="--staged"){i();continue}if(a==="--no-staged"){i();continue}if(a==="--worktree"){i(!0);continue}if(a==="--no-worktree"){i(!1);continue}if(a==="--patch"){n=!0;continue}if(a==="--no-patch"){n=!1;continue}if(Lb.has(a)){s++;continue}if(a.startsWith("--"))continue;if(a==="-"){t=!0;continue}if(!a.startsWith("-")){t=!0;continue}for(let l=1;l<a.length;l++){let c=a.charAt(l);if(c==="h")return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!0};if(c==="S"){i();continue}if(c==="W"){i(!0);continue}if(c==="p"){n=!0;continue}if(c==="s"||c==="U"){if(l===a.length-1)s++;break}}}return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!1}}function Bb(e){let t=null;for(let n of e){if(W(n,"--hard")){t=b("git.reset-hard",Sb);break}if(W(n,"--merge")){t=b("git.reset-merge",vb);break}}if(!t)return null;return Ub(e)?Bt(t):wt(t)}function Ub(e){for(let t of e){if(t==="--")return!1;if(!t.startsWith("-"))return!0}return!1}function Hb(e){for(let n of e)if(n==="-n"||W(n,"--dry-run"))return null;let t=de(e.filter((n)=>n!=="--"));if(e.some((n)=>W(n,"--force"))||t.has("-f"))return b("git.clean-force",Rb);return null}function jb(e){let t=!1,n=!1,r=!1;for(let o of ce(e).before){if(W(o,"--no-force")){t=!1;continue}if(W(o,"--force")){t=!0;continue}if(W(o,"--no-cached")){n=!1;continue}if(W(o,"--cached")){n=!0;continue}if(W(o,"--no-dry-run")){r=!1;continue}if(W(o,"--dry-run")){r=!0;continue}let i=de([o]);t||=i.has("-f"),r||=i.has("-n")}return t&&!n&&!r?b("git.rm-force",xb):null}function Vb(e){let{before:t,after:n}=ce(e),r=de(t);if(t.some((s)=>W(s,"--mirror")))return b("git.push-mirror",Pb);if(t.some((s)=>W(s,"--force"))||r.has("-f")||Wu(t,n).some(qb))return b("git.push-force",Eb);if(t.some((s)=>W(s,"--delete"))||r.has("-d")||Wu(t,n).some(Kb))return b("git.push-delete",wb);return null}function Wu(e,t){return[...e.filter((n)=>n!==""&&!n.startsWith("-")),...t]}function qb(e){return e.startsWith("+")||e.includes(":+")}function Kb(e){return e.length>1&&e.startsWith(":")}function Yb(e){let{before:t}=ce(e),n=de(t),r=n.has("-D")||n.has("-d")||t.some((i)=>W(i,"--delete")),o=n.has("-D")||n.has("-f")||t.some((i)=>W(i,"--force"));if(r&&o)return b("git.branch-force-delete",_b);return null}function Zb(e){let{before:t}=ce(e);return t.some((n)=>W(n,"--abort"))?b("git.rebase-abort",Ab):null}function Xb(e){let{before:t}=ce(e);return t.some((n)=>W(n,"--abort"))?b("git.merge-abort",kb):null}function Jb(e){let{before:t}=ce(e);return de(t).has("-d")||t.some((r)=>W(r,"--delete"))?b("git.tag-delete",Tb):null}function Qb(e){return e[0]==="delete"?b("git.reflog-delete",Ib):null}function eS(e){for(let t of e){if(t==="drop")return b("git.stash-drop",Ob);if(t==="clear")return b("git.stash-clear",Mb)}return null}function tS(e){let{before:t}=ce(e);if(!t.includes("remove"))return null;let r=de(t);if(t.some((o)=>W(o,"--force"))||r.has("-f"))return b("git.worktree-remove-force",Db);return null}import{execFileSync as nS}from"node:child_process";import{existsSync as Hs,readFileSync as js}from"node:fs";import{dirname as rS,isAbsolute as $u,join as Us,resolve as Bu}from"node:path";var oS=["/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 Uu(e,t,n,r){let o=iS(e,t,n);if(o!==null)return o;let i=sS(t,n);if(i!==null)return i;if(hl(n))return!0;return aS(r)}function iS(e,t,n){let r=null,o=1;while(o<e.length){let i=e[o];if(!i||i==="--")return r;if(!i.startsWith("-"))return r;if(i==="-c"){let s=Gu(e[o+1]);if(s!==null)r=s;o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=Gu(i.slice(2));if(s!==null)r=s;o++;continue}if(i==="--config-env"){let s=zu(e[o+1],t,n);if(s!==null)r=s;o+=2;continue}if(i.startsWith("--config-env=")){let s=zu(i.slice(13),t,n);if(s!==null)r=s;o++;continue}if(Ye.has(i))o+=2;else o++}return r}function sS(e,t){if(we("GIT_CONFIG_PARAMETERS",e,t)!==void 0)return!0;let n=zr(e,t);if(n.state==="absent")return null;if(n.state==="invalid")return!0;let r=null;for(let o=0;o<n.count;o++){let i=we(`GIT_CONFIG_KEY_${o}`,e,t),s=we(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i?.trim()||s===void 0)return!0;let a=i.trim().toLowerCase();if(Vs(a))return!0;if(a!=="submodule.recurse")continue;r=cr(s)}return r}function aS(e,t=cS()){let n=lS(e);if(n===null||n)return!0;if(t===null)return!0;try{let r=nS(t,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:uS(process.env),stdio:["ignore","pipe","ignore"]}).trim();return cr(r)}catch(r){return!dS(r)}}function lS(e){let t=mS(e);if(t===null)return null;for(let n of t){if(!Hs(n))continue;if(gS(n))return!0}return!1}function cS(){for(let e of oS)if(Hs(e))return e;return null}function uS(e){let t={...e};for(let n of Object.keys(t))if(Wn(n))delete t[n];return t}function dS(e){return typeof e==="object"&&e!==null&&"status"in e&&e.status===1}function mS(e){let t=zn(e);if(t===null)return null;let n=fS(t);if(n===null)return null;let r=pS(n);if(r===null)return null;return[Us(r,"config"),Us(n,"config.worktree")]}function fS(e){try{let n=js(e,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!n.startsWith("gitdir:"))return e;let r=n.slice(7).trim();if(r==="")return null;return $u(r)?r:Bu(rS(e),r)}catch{return null}}function pS(e){let t=Us(e,"commondir");if(!Hs(t))return e;try{let n=js(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(n==="")return null;return $u(n)?n:Bu(e,n)}catch{return null}}function gS(e){let t;try{t=js(e,"utf-8")}catch{return!0}let n="",r=!1;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i===""||i.startsWith("#")||i.startsWith(";"))continue;let s=i.match(/^\[([^\]]+)\]$/);if(s){n=s[1]?.trim().toLowerCase()??"";continue}let a=i.indexOf("="),l=(a===-1?i:i.slice(0,a)).trim().toLowerCase(),c=a===-1?"true":i.slice(a+1).trim();if(hS(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=cr(c)}return r}function hS(e){return e==="include"||e.startsWith("includeif ")}function Gu(e){if(!e)return null;let t=e.indexOf("="),n=(t===-1?e:e.slice(0,t)).toLowerCase();if(Vs(n))return!0;if(n!=="submodule.recurse")return null;let r=t===-1?"true":e.slice(t+1).toLowerCase();return cr(r)}function cr(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function zu(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;let o=e.slice(0,r).toLowerCase();if(Vs(o))return!0;if(o!=="submodule.recurse")return null;let i=we(e.slice(r+1),t,n);return i===void 0||cr(i)}function Vs(e){return e==="include.path"||e.startsWith("includeif.")&&e.endsWith(".path")}function Hu(e,t,n){if(!t.localDiscard||!n.worktreeMode||Sl(n.env,n.envAssignments))return null;let r=vl(e,n.cwd);if(!r.gitCwd||r.hasExplicitGitContext)return null;if(!Rl(r.gitCwd))return null;if(yS(e,n,r.gitCwd))return null;return{originalReason:t.reason,gitCwd:r.gitCwd}}function yS(e,t,n){let{subcommand:r,rest:o}=He(e),i=r?.toLowerCase();if(t.dynamicArguments||CS(o)||Uu(e,t.env,t.envAssignments,n)||vS(o)||bS(i,o))return!0;return i==="clean"&&RS(o)>1}function CS(e){return e.some((t)=>/[$*?[]/.test(t))}function bS(e,t){if(e==="checkout"){let{before:n}=ce(t),r=de(n,{shortOptsWithValue:$s}),o=n.some((s)=>W(s,"--force"))||r.has("-f"),i=r.has("-B")||n.some((s)=>s==="-B"||s.startsWith("-B"));return o&&i}if(e==="switch"){let{before:n}=ce(t),r=de(n,{shortOptsWithValue:Bs}),o=n.some((s)=>W(s,"--force"))||n.some((s)=>W(s,"--discard-changes"))||r.has("-f"),i=n.some((s)=>s==="-C"||s.startsWith("-C")||SS(s))||r.has("-C");return o&&i}return!1}function SS(e){let t=e.split("=",1)[0]??e;return t==="--force-create"||t.length>=9&&"--force-create".startsWith(t)}function vS(e){return e.some((t)=>t.startsWith("--recurse-sub"))}function RS(e){let t=0;for(let n of e){if(n==="--force"){t++;continue}if(n.startsWith("-")&&!n.startsWith("--")){for(let r of n.slice(1))if(r==="f")t++}}return t}var xS="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.",ES=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function bn(e,t){return ju(e.map(I),t)}function ju(e,t,n){let r=Ou(e,t.env,t.envAssignments),o=r.blockedReason?k(b("git.alias-config",r.blockedReason),t.policy):null;if(o)return o;let i=r.tokens;if((gl(t.envAssignments)||Mu(e,t.env,t.envAssignments))&&wS(i))return b("git.ssh-env",xS);let s=Fu(i);if(!s)return null;if(r.expanded||r.blockedReason)return s;let a=Hu(e,s,t);if(!a)return s;return n?.(a),null}function Vu(e,t){let n=null;return{match:ju(e.map(I),t,(o)=>{n=o}),relaxation:n}}function wS(e){let{subcommand:t,rest:n}=He(e),r=t?.toLowerCase();if(!r)return!1;if(ES.has(r))return!0;if(r==="archive")return ce(n).before.some((o)=>W(o,"--remote"));return r==="remote"&&PS(n)}function PS(e){return e.find((t)=>!_S(t))?.toLowerCase()==="update"}function _S(e){return e==="-v"||W(e,"--verbose")||W(e,"--no-verbose")}import{isAbsolute as yv}from"node:path";var qu="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",AS="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.",kS="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",Yu="rm -rf targeting root or home directory is extremely dangerous and always blocked.",TS="rm -rf in home directory is dangerous. Change to a project directory first.";function Sn(e,t){let n=zt({...t,allowPaths:t.policy?.destructiveCommandAllowPaths,posixShell:!0}),r=e.map(I),o=Ue(r),i=Tu(r),s=OS(e);for(let a of s){let l=or(a.word);if(o&&l.unsafeBraceExpansion){let c=k(Ku({kind:"outside_anchored_cwd"},n,t.policy),t.policy);if(c)return c;continue}for(let c of l.expandedTargets??[a.text]){let u=pe(c),m={targetIsLiteral:l.expandedTargets!==void 0||l.targetIsLiteral,tmpdirWordSplittingProtected:l.tmpdirWordSplittingProtected};if(!i&&n.resolvedCwd&&Gt(u,n.resolvedCwd,n.protectedGitMetadata,i,n.pathCanonicalizationContext))return b("rm.git-metadata",Ae);if(i&&!o){let f=$e(u,n,m);if(f.kind==="root_or_home_target")return b("rm.recursive-force-root-or-home",Yu);if(f.kind==="git_metadata_target")return b("rm.git-metadata",Ae);continue}if(!o)continue;for(let f of IS(u,n,m)){let d=Ku(f,n,t.policy),p=k(d,t.policy);if(p)return p}}}return null}function IS(e,t,n){let r=$e(e,t,n);if(r.kind==="cwd_self_target")return[r,$e(e,t,{...n,skipCwdSelf:!0})];if(r.kind!=="home_cwd_target")return[r];let o=$e(e,t,{...n,skipHomeCwd:!0});if(o.kind!=="cwd_self_target")return[r,o];return[r,o,$e(e,t,{...n,skipHomeCwd:!0,skipCwdSelf:!0})]}function OS(e){let t=[],n=!1;for(let r of e.slice(1)){let o=I(r);if(!o)continue;if(o==="--"){n=!0;continue}if(n){t.push({text:o,word:r});continue}if(!o.startsWith("-"))t.push({text:o,word:r})}return t}function Ku(e,t,n){switch(e.kind){case"root_or_home_target":return b("rm.recursive-force-root-or-home",Yu);case"git_metadata_target":return b("rm.git-metadata",Ae);case"temp_target":return null;case"dynamic_target":if(!Q(n,"rm.recursive-force-dynamic-target",t.strict))return null;return b("rm.recursive-force-dynamic-target",kS);case"home_cwd_target":return b("rm.recursive-force-home-cwd",TS);case"cwd_self_target":return b("rm.recursive-force-cwd-self",qu);case"within_anchored_cwd":if(Q(n,"rm.recursive-force-paranoid",t.paranoid))return b("rm.recursive-force-paranoid",AS);return null;case"outside_anchored_cwd":return b("rm.recursive-force-outside-cwd",qu)}}var MS={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Xu=new Set(["--init-file","--rcfile"]),DS=["--init-file","--rcfile"],LS=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function Qe(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n)continue;if(n==="-c")return Zu(e,t,!0);if(n.startsWith("-")&&n.includes("c")&&!n.startsWith("--")){let r=Zu(e,t,!1);if(r!==null)return r}}return null}function ke(e){let t=D(e[0]??"").toLowerCase();if(t==="zsh"||t==="ksh")return et(e).syntaxCheck;let n=!1;for(let r of e.slice(1)){if(r==="--")return n;if(r.startsWith("+")&&!r.startsWith("++")){if(r.slice(1).includes("n"))n=!1;continue}if(!r.startsWith("-")||r.startsWith("--"))return n;let o=r.slice(1);if(o.includes("n"))n=!0;if(o.includes("c"))return n}return n}function Zu(e,t,n){if(e[t+1]==="--")return e[t+2]||null;let r=e[t+1];if(!r||!n&&r.startsWith("-"))return null;return r}function Ju(e){let t=D(e[0]??"").toLowerCase(),n=NS(e,t),r=LS.get(t)??null,o=n.argvSource?.kind!=="absent";return{argvSource:t==="bash"?n.argvSource:null,argvSourceApplies:t==="bash"&&n.interactive&&n.argvSource?.kind==="literal",envName:r,envSourceApplies:o&&(r==="BASH_ENV"?!n.interactive:r==="ENV"&&n.interactive)}}function NS(e,t){let n=et(e),r=n.commandIndex??n.scriptIndex??e.length,o=[],i=!1,s=!0;for(let a=1;a<r;a++){let l=e[a];if(l===void 0||l==="--"||l==="-"||l[0]!=="-"&&l[0]!=="+")break;if(l.startsWith("--")){if(t==="bash"&&s?DS.find((f)=>l===f):void 0){let f=e[a+1];o.push(f===void 0?{kind:"absent"}:{kind:"literal",value:f}),a++;continue}let m=l.split("=",1)[0]??l;if(t==="bash"&&Xu.has(m)&&!l.includes("="))a++;continue}if(t==="bash")s=!1;let c=Qu(t,l,e[a+1],"startup");if(c.interactive)i=l[0]==="-";a+=c.followingValues}return{argvSource:o.at(-1)??null,interactive:i}}function Qu(e,t,n,r){let o=!1,i=0,s=!1,a=!1,l=!1;for(let c=1;c<t.length;c++){let u=t[c];if(u===void 0)break;if(e==="ksh"&&u==="o"&&c+1<t.length){if(r==="argv"){let m=t.slice(c+1);if(t[0]==="-"&&(m==="c"||m[0]==="-"&&m.endsWith("c")))s=!0}break}if(e==="ksh"&&u==="o"&&c+1===t.length&&(n?.startsWith("-")||n?.startsWith("+")))break;if(e==="zsh"&&u==="o"&&c+1<t.length)break;if(r==="startup"&&u==="i")o=t[0]==="-";if(r==="argv"&&t[0]==="-"&&u==="c")s=!0;if(r==="argv"&&u==="n")l=t[0]==="-";if(r==="argv"&&u==="s")a=t[0]==="-";if(!MS[e]?.includes(u))continue;if(c+1===t.length)i++;break}return{interactive:o,followingValues:i,commandSelected:s,stdinMode:a,syntaxCheck:l}}function et(e){let t=D(e[0]??"").toLowerCase(),n=!1,r=!1,o=!1;for(let i=1;i<e.length;i++){let s=e[i];if(s===void 0)break;if(s==="--"){let l=n&&e[i+1]!==void 0?i+1:null;return{command:l===null?null:e[l]??null,commandIndex:l,scriptIndex:!n&&!r&&e[i+1]!==void 0?i+1:null,readsStdinAsCommands:!n&&(r||e[i+1]===void 0),syntaxCheck:o}}if(s==="-"||s[0]!=="-"&&s[0]!=="+")return{command:n?s:null,commandIndex:n?i:null,scriptIndex:!n&&!r&&s!=="-"?i:null,readsStdinAsCommands:!n&&(r||s==="-"),syntaxCheck:o};if(s.startsWith("--")){let l=s.split("=",1)[0]??s;if(t==="bash"&&Xu.has(l)&&!s.includes("="))i++;continue}let a=Qu(t,s,e[i+1],"argv");if(a.commandSelected)n=!0;if(a.syntaxCheck)o=!0;if(a.stdinMode)r=!0;i+=a.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!n,syntaxCheck:o}}var Pt={kind:"none"},Ut={kind:"dynamic"},WS=new Set(["<","<<","<<-","<<<","<&","<>"]),td=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,FS=/^(?:[0-9]+|[@*])$/,GS=Wt.maxWords,zS=Wt.maxInputLength;function nd(e){if(!e||D(z(e.words[0]?.text??""))!=="printf")return;if(e.words.some((o)=>o.provenance!=="literal"))return;let t=e.words.slice(e.words[1]?.text==="--"?2:1),n=t[0]?.text;if(n===void 0)return"";let r=t.slice(1).map((o)=>o.text);if(n==="%s")return r.join("");if(n==="%s\\n"||n===`%s
35
+ `)return`${r.join(`
36
+ `)}
37
+ `;if(n.includes("%")||/\\(?![\\nrt])/.test(n))return;return n.replaceAll("\\n",`
38
+ `).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function vn(e){let t=ur(e[1])==="--"?2:1;if(e.length<=t)return Pt;let n=e.slice(t);if(!n.every(Jo))return Ut;return{kind:"literal",source:n.map(I).join(" ")}}function rd(e){let t=ur(e[1])==="--"?2:1,n=e[t],r=ur(n);if(n===void 0||e.length<=t+1||r==="-"||r===""||r==="-l"||r==="-p")return Pt;if(!Jo(n))return Ut;return{kind:"literal",source:r}}function Xo(e,t){let n=BS(e);if(n===-1)return Pt;let r=US(t);if(!r)return Pt;let o=[],i=r.command?.length??0;for(let s of r.references){let a=jS(s,e,n,r.ifs);if(!a)return Ut;if(i+=a.reduce((l,c)=>l+c.length+3,0),o.length+a.length>GS||i>zS)return Ut;o.push(...a)}if(r.command==="eval")return{kind:"literal",source:o.join(" ")};if(o.length===0||/\s/.test(o[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[r.command,r.command&&r.optionTerminator?"--":null,...o.map(qS)].filter((s)=>s!==null).join(" ")}}function od(e,t,n,r){if(!et(e.map(I)).readsStdinAsCommands)return Pt;let o=t.filter((i)=>(i.fd===void 0||i.fd===0)&&WS.has(i.operator)).at(-1);if(o){if(o.operator==="<<"||o.operator==="<<-")return Pt;if(o.operator!=="<<<"||o.target?.provenance!=="literal")return Ut;return{kind:"literal",source:o.target.text}}if(!n)return Pt;return r===void 0?Ut:{kind:"literal",source:r}}function tt(e){let t=et(e.map(I)).scriptIndex;if(t===null)return Pt;let n=e[t],r=ur(n);return Fr(n,r)?{kind:"literal",source:r}:Ut}var $S=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function Zs(e){if(e.words.length!==2||e.redirections.length!==0||e.nested.length!==1)return!1;let t=e.words[0],n=e.words[1];if(!t||t.provenance!=="literal"||t.quoted||t.raw!==t.text||!n)return!1;if(!(t.text==="eval"&&n.quoted&&n.parts.length===3&&n.parts[0]?.raw==='"'&&n.parts[1]?.provenance==="command-substitution"&&n.parts[1].raw.startsWith("$(")&&n.parts[2]?.raw==='"'||(t.text==="source"||t.text===".")&&!n.quoted&&n.parts.length===1&&n.parts[0]?.provenance==="command-substitution"&&n.parts[0].raw.startsWith("<(")))return!1;let o=e.nested[0];if(o?.status!=="complete"||o.nodes.length!==1)return!1;let i=o.nodes[0];if(i?.kind!=="command"||i.redirections.length!==0||i.nested.length!==0||i.words.some((l)=>l.provenance!=="literal"||l.parts.some((c)=>c.provenance!=="literal")))return!1;let s=i.words[0]?.text;if(s===void 0||_e(s)!==null)return!1;let a=D(z(s));return!$S.has(a)&&!ee.has(a)&&!$t(a)}function BS(e){return et(e.map(I)).commandIndex??-1}function US(e){let t=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(e.trim()),n=t?.[4]??e.trim(),r=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(n),o=(r?.[3]??n).split(/\s+/).map(HS);if(o.length===0||o.some((i)=>i===null))return null;return{command:r?.[1]??null,optionTerminator:r?.[2]!==void 0,references:o.filter((i)=>!!i),ifs:t?t[1]??t[2]??t[3]??"":`
39
+ `}}function HS(e){let t=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(e),n=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(e),r=t??n;if(!r)return null;let o=r[1]??r[2];return{parameter:o==="@"||o==="*"?o:Number(o),quoted:t!==null}}function jS(e,t,n,r){let o=t.slice(n+2);if(e.parameter==="@")return e.quoted?qs(o):VS(o,r);if(e.parameter==="*"){let a=qs(o);if(!a)return;let l=a.join(r[0]??"");return e.quoted?[l]:Ks(l,r)}let i=t[n+1+e.parameter];if(i&&!Jo(i))return;let s=ur(i);return e.quoted?[s]:Ks(s,r)}function qs(e){return e.every(Jo)?e.map(I):void 0}function VS(e,t){let n=qs(e);if(!n)return;let r=n.map((o)=>Ks(o,t));return r.some((o)=>o===void 0)?void 0:r.flatMap((o)=>o??[])}function Ks(e,t){if(["*","?","[","]"].some((n)=>e.includes(n)))return;if(t==="")return e===""?[]:[e];if(t===`
40
+ `)return e.trim().split(/\s+/).filter(Boolean);if(t.length!==1)return;return t===" "||t==="\t"||t===`
41
+ `?e.trim().split(/\s+/).filter(Boolean):e.split(t).filter(Boolean)}function Jo(e){if(!e)return!0;return e.provenance==="unknown"?!/[$`]/.test(I(e)):e.provenance==="literal"}function ur(e){return e?I(e):""}function qS(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Xs(e,t){return Ys(Fe(e,"posix"),t)}function Rn(e){return Xs(e,new Set(Array.from(e.matchAll(td)).flatMap((t)=>{let n=t[1]??t[2];return n===void 0?[]:[n]})))}function Ys(e,t){if(e.status==="invalid"||e.status==="limited")return!1;let n=new Set(t);for(let r of e.nodes){if(r.kind==="group"){if(Ys(r.body,n))return!0;continue}if(r.kind!=="command")continue;if(r.nested.some((o)=>Ys(o,n))||id(r.words,n))return!0;JS(r,n)}return!1}function id(e,t){let n=e.findIndex((s)=>_e(s.text)===null);if(n===-1)return!1;let r=e[n];if(!r)return!1;if(dr(r,t))return!0;let o=z(r.text);if(o==="source"||o==="."){let s=e[n+1]?.text==="--"?n+2:n+1;return ed(e[s],t)}if(ee.has(o)){let s=e.slice(n),a=et(s.map((c)=>c.text)),l=a.commandIndex??a.scriptIndex;return!a.syntaxCheck&&l!==null&&ed(s[l],t)}let i=KS(e,n,t);if(i===null)return!1;if(i===-1)return!0;return id(e.slice(i),t)}function KS(e,t,n){let r=z(e[t]?.text??"");if(r==="command")return YS(e,t+1);if(r==="exec")return ZS(e,t+1);if(r==="env")return XS(e,t+1,n);return null}function YS(e,t){for(let n=t;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return e[n+1]?n+1:null;if(/^-[p]*[vV][pvV]*$/.test(r))return null;if(/^-p+$/.test(r))continue;return n}return null}function ZS(e,t){for(let n=t;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return e[n+1]?n+1:null;if(r==="-a"){n++;continue}if(/^-a.+/.test(r)||/^-[cl]+$/.test(r))continue;return n}return null}function XS(e,t,n){for(let r=t;r<e.length;r++){let o=e[r],i=o?.text??"";if(i==="--")return e[r+1]?r+1:null;if(i==="-S"||i==="--split-string")return dr(e[r+1],n)?-1:r+2;if(i.startsWith("-S")||i.startsWith("--split-string="))return dr(o,n)?-1:r+1;if(i==="-u"||i==="--unset"||i==="-C"||i==="--chdir"||i==="-P"){r++;continue}if(i==="-i"||i==="-0"||i==="--null"||i.startsWith("-u=")||i.startsWith("--unset=")||i.startsWith("-C")||i.startsWith("--chdir=")||i.startsWith("-P"))continue;if(i.startsWith("-"))continue;if(_e(i))continue;return r}return null}function JS(e,t){if(!e.words.every((n)=>_e(n.text)!==null))return;for(let n of e.words){let r=_e(n.text);if(!r)continue;if(dr(n,t))t.add(r.name)}}function dr(e,t){if(!e)return!1;return e.parts.filter((n)=>n.provenance==="variable").some((n)=>Array.from(n.raw.matchAll(td)).some((r)=>{let o=r[1]??r[2];return o!==void 0&&(FS.test(o)||t.has(o))}))}function ed(e,t){return!!e&&(e.parts.some((n)=>n.provenance!=="literal"&&n.provenance!=="variable")||dr(e,t))}var QS=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--config-env"]),ev=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),tv=new Set;function sd(e){if(e==="git")return QS;if(e==="docker")return ev;return tv}function ne(e,t){if(e.length===0||t.length===0)return null;let n=z(e[0]??""),r=de(e);for(let o of t){if(!nv(n,o.command))continue;if(!rv(n,e,o.subcommand))continue;if(iv(e,new Set(o.block_args),r))return{id:`custom.${o.name}`,reason:`[${o.name}] ${o.reason}`,intent:o.intent??"manual_only"}}return null}function nv(e,t){return e===z(t)}function rv(e,t,n){if(!n)return!0;return ad(t,1,n,sd(e))}function ad(e,t,n,r){let o=!1;for(let i=t;i<e.length;i++){let s=e[i];if(!s)continue;if(o){o=!1;continue}if(s==="--"){let a=e[i+1];if(a&&!a.startsWith("-"))return a===n;return!1}if(r.has(s)){o=!0;continue}if(s.startsWith("-")){if(!s.includes("=")&&ov(e,i,n,r))return!0;continue}return s===n}return!1}function ov(e,t,n,r){let o=e[t+1];if(!o||o.startsWith("-"))return!1;return ad(e,t+2,n,r)}function iv(e,t,n){for(let r of e)if(t.has(r))return!0;for(let r of n)if(t.has(r))return!0;return!1}function _t(e,t,n={}){if(e.length===0)return null;let r=e[0];if(!r)return null;let o=z(r);if(o==="eval"){let i=vn(G(e));if(i.kind==="dynamic")return xn(n,t);if(i.kind==="literal"&&t.analyzeNested){let s=t.analyzeNested(i.source,{effectiveCwd:t.cwd,envAssignments:t.envAssignments});if(s)return s}return nt(n,t)}if(ee.has(o)){if(ke(e))return null;let i=Qe(e);if(i){if(n.dynamicSourceInput??n.dynamicInput){let l=xn(n,t);if(l)return l}if(Rn(i)){let l=xn(n,t);if(l)return l}if(!t.analyzeNested)return null;let a=t.analyzeNested(i,{effectiveCwd:t.cwd,envAssignments:t.envAssignments});if(a)return a;return null}let s=tt(G(e));if(s.kind==="dynamic")return xn(n,t);if(s.kind==="literal"){if(n.dynamicSourceInput)return xn(n,t);return null}if(n.dynamicSourceInput??n.dynamicInput)return xn(n,t);return null}if(ve.has(o))return k(jo(e,(i)=>t.analyzeNested?t.analyzeNested(i,{effectiveCwd:t.cwd,envAssignments:t.envAssignments}):null),t.policy)??ne(e,t.policy?.rules??[])??nt(n,t);if(ye(o)){let i=ro(e);if(!i)return nt(n,t);if(Q(t.policy,"interpreter.one-liner-paranoid",!!t.paranoidInterpreters)){let a=k(b("interpreter.one-liner-paranoid",un),t.policy);if(a)return a}if(so(o,i))return nt(n,t);let s=t.analyzeNested?.(i,{effectiveCwd:t.cwd,envAssignments:t.envAssignments});if(s&&s.id!=="raw-text.dangerous-command"&&(s.reason!==St||hn(i)))return s;if(dn(i,t.scanWork))return k(b("interpreter.dangerous-command",Lt),t.policy)??nt(n,t);return nt(n,t)}if(o==="rm"||o==="rmdir"){let i=o==="rm"&&(Ue(e)||n.dynamicRmInput);return k(Sn(G(e),{environment:t.environment,cwd:t.cwd,originalCwd:t.originalCwd,strict:t.strict,paranoid:t.paranoidRm,allowTmpdirVar:t.allowTmpdirVar,tmpdirWordSplittingUnsafe:Ze(t.envAssignments,t.environment),trustedTmpdirValue:ft(t.envAssignments,t.environment),protectedGitMetadata:t.protectedGitMetadata,policy:t.policy}),t.policy)??(i&&n.dynamicRmInput?nt(n,t):null)??(i?sv(n,t):null)}if(o==="find")return Ko(G(e),{...t,derivedCommandWorkBudget:t.derivedCommandWorkBudget,analyzeTokens:(i,s)=>_t(i,{...t,cwd:s??void 0,derivedCommandWorkBudget:t.derivedCommandWorkBudget},n)})??ne(e,t.policy?.rules??[])??nt(n,t);if(o==="git")return k(bn(G(e),{env:t.environment.env,cwd:t.cwd,envAssignments:t.envAssignments,policy:t.policy,worktreeMode:n.dynamicInput?!1:t.worktreeMode}),t.policy)??ne(e,t.policy?.rules??[])??nt(n,t);return ne(e,t.policy?.rules??[])??nt(n,t)}function xn(e,t){return e.shellDynamicMatch?k(e.shellDynamicMatch,t.policy):null}function nt(e,t){return e.dynamicSourceInput&&e.dynamicSourceMatch?k(e.dynamicSourceMatch,t.policy):null}function sv(e,t){return e.dynamicInput&&e.rmDynamicMatch?k(e.rmDynamicMatch,t.policy):null}var Js="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",Qs="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",av="__CC_SAFETY_NET_XARGS_INPUT__",Qo="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",ei="rm",lv=/(?:^|[;&|]\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,cv=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,uv=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,dv=/^(?:[0-9]+|[@*])$/;function ud(e,t){let n=e.map(I),{childStart:r,replacementToken:o}=Ht(n),i=n.slice(r),s=b("xargs.shell-dynamic",Qs);if(fv(i,o,t)&&k(s,t.policy))return k(s,t.policy);for(let a of Be(i,t)){let l=a.tokens,c=o!==null&&l[0]!==i[0]&&(l[0]?.includes(o)??!1)?k(s,t.policy):null;if(c)return c;let u=pd(l,o,a.wrapperEnvAssignments),m=a.head==="rm"&&o!==null&&md(l,o),f=_t(l,{...t,cwd:a.cwd,envAssignments:a.envAssignments},{dynamicInput:u,dynamicSourceInput:m||dd(l,a.head,o,a.wrapperEnvAssignments,u,t.scanWork,t.environment),dynamicRmInput:m,shellDynamicMatch:s,dynamicSourceMatch:s,rmDynamicMatch:b("xargs.rm-recursive-force-dynamic",Js)});if(f)return f;let d=mv(l,o,t.policy?.rules??[]);if(d)return d;if(a.head==="git"){let g=o===null?[...l,av]:l,y=o!==null&&(l.some((R)=>R.includes(o))||Array.from(a.envAssignments.values()).some((R)=>R.includes(o))),h=_t(g,{...t,cwd:a.cwd,envAssignments:a.envAssignments,worktreeMode:o===null||y?!1:t.worktreeMode});if(h)return h}let p=ne(l,t.policy?.rules??[]);if(p)return p}return null}function mv(e,t,n){if(n.length===0)return null;if(t===null){for(let o of n){let i=ne([...e,...o.subcommand?[o.subcommand]:[],...o.block_args],n);if(i)return i}return null}let r=new Set(n.flatMap((o)=>[o.subcommand,...o.block_args].flatMap((i)=>i?e.flatMap((s)=>ea(s,t,i)):[])));for(let o of r){let i=ne(e.map((s)=>s.replaceAll(t,o)),n);if(i)return i}return null}function ea(e,t,n){let r=e.indexOf(t);if(r===-1||e.indexOf(t,r+t.length)!==-1)return[];let o=e.slice(0,r),i=e.slice(r+t.length);return n.startsWith(o)&&n.endsWith(i)?[n.slice(o.length,n.length-i.length)]:[]}function dd(e,t,n,r,o,i,s){if(ee.has(t)){if(ke(e))return!1;if(n!==null&&pv(e,n))return!0;let a=Qe(e);if(!a){let l=tt(G(e));if(l.kind==="literal")return n!==null&&l.source.includes(n);return l.kind==="none"&&o}if(n!==null&&a.includes(n))return!0;if(mt(a,i))return!0;return gv(a,n,r)}if(ye(t))return ld(e,n,io,Vl(t));if(ve.has(t))return ld(e,n,Os,Eu);if(t==="eval"){let a=vn(G(e));if(a.kind==="dynamic")return!0;if(n!==null)return a.kind==="literal"&&a.source.includes(n);return o}if(t==="find")return hv(e,n,i,s);if(t==="git"){let a=He(e);return n===null?a.subcommand===null:(a.subcommand?.includes(n)??!1)||a.subcommand!==null&&Cn.has(a.subcommand.toLowerCase())&&fd(a.rest,n).some((l)=>l.includes(n))}return!1}function ld(e,t,n,r){let o=n(e);if(t===null)return o.optionsOpen||n([...e,Qo]).sources.some((l)=>l.value===Qo);if(o.sources.some((l)=>l.value.includes(t)))return!0;let i=new Set(o.sources.map((l)=>`${l.tokenIndex}\x00${l.kind}\x00${l.value}`)),s=r.flatMap((l)=>[l.selector,...l.valueForm==="attached-only"||l.valueForm==="attached-or-separate"?[`${l.selector}${Qo}`]:[],...l.valueForm==="equals-or-separate"?[`${l.selector}=${Qo}`]:[]]),a=new Set(s.flatMap((l)=>e.flatMap((c)=>ea(c,t,l))));return Array.from(a).some((l)=>n(e.map((c)=>c.replaceAll(t,l))).sources.some((c)=>!i.has(`${c.tokenIndex}\x00${c.kind}\x00${c.value}`)))}function fv(e,t,n){if(e.length===0||(e[0]??"").toLowerCase()==="command")return!1;let r=new Set(Array.from(Be(e,n),(i)=>i.head)),o=t===null?[...e,ei]:e.map((i,s)=>s===0?i:i.replaceAll(t,ei));return Array.from(Be(o,n)).some((i)=>i.head===ei&&!r.has(ei))}function md(e,t){return fd(e.slice(1),t).some((n)=>n.includes(t)&&(n.startsWith("-")||n.startsWith(t)))}function fd(e,t){let n=e.findIndex((r)=>r==="--"&&!r.includes(t));return n===-1?e:e.slice(0,n)}function pd(e,t,n){if(t===null)return!0;return e.some((r)=>r.includes(t))||Array.from(n.values()).some((r)=>r.includes(t))}function pv(e,t){let n=et(e);if(n.commandIndex!==null&&(e[n.commandIndex]??"").includes(t)||n.scriptIndex!==null&&(e[n.scriptIndex]??"").includes(t))return!0;return["-c","-nc","-cn",`--${t}`,t].some((o)=>e.some((i,s)=>{if(s===0||!i.includes(t))return!1;return ea(i,t,o).some((l)=>{let c=e.map((m,f)=>f===s?m.replaceAll(t,l):m),u=et(c);if(u.commandIndex===null&&u.scriptIndex===null)return!1;if(n.commandIndex===null&&u.commandIndex!==null)return!0;if(n.scriptIndex===null&&u.scriptIndex!==null)return!0;if(u.commandIndex!==null&&(c[u.commandIndex]??"").includes(l))return!0;return u.scriptIndex!==null&&(c[u.scriptIndex]??"").includes(l)})}))}function gv(e,t,n){let r=new Set(t===null?[]:Array.from(n).filter(([,o])=>o.includes(t)).map(([o])=>o));for(let o of e.matchAll(lv))if(cd(o,r))return!0;for(let o of e.matchAll(cv))for(let i of(o[1]??"").matchAll(uv))if(cd(i,r))return!0;return Xs(e,r)}function cd(e,t){let n=e[1]??e[2];return n!==void 0&&(dv.test(n)||t.has(n))}function hv(e,t,n,r){if(t===null)return!0;let o=!1,i=0;for(let s=1;s<e.length;s++){let a=e[s]??"";if(!o&&!a.startsWith("-")&&a!=="!"&&a!=="("){if(a.indexOf(t)===0)return!0;continue}if(o=!0,i>0){i--;continue}if(pt(a)){let c=ar(e,s);s=c.nextIndex-1;for(let u of Be(c.tokens,{environment:r,cwd:void 0})){let m=pd(u.tokens,t,u.wrapperEnvAssignments);if(u.head==="rm"&&md(u.tokens,t)||dd(u.tokens,u.head,t,u.wrapperEnvAssignments,m,n,r))return!0}continue}let l=Et(a);if(l>0){if(i=l,a.includes(t))return!0;continue}if(a.includes(t))return!0}return!1}function Ht(e){let t=new Set(["-L","-n","-P","-s","-a","-E","-R","-S","-e","-d","-J","--max-args","--max-procs","--max-chars","--arg-file","--eof","--delimiter","--max-lines","--process-slot-var"]),n=null,r=1;while(r<e.length){let o=e[r];if(!o)break;if(o==="--")return{childStart:r+1,replacementToken:n};if(o.startsWith("-")){if(o==="-I"){n=e[r+1]??"{}",r+=2;continue}if(o.startsWith("-I")&&o.length>2){n=o.slice(2),r++;continue}if(o==="--replace"){n="{}",r++;continue}if(o.startsWith("--replace=")){let i=o.slice(10);n=i===""?"{}":i,r++;continue}if(o==="-J"){n=e[r+1]??"{}",r+=2;continue}if(t.has(o))r+=2;else r++}else return{childStart:r,replacementToken:n}}return{childStart:e.length,replacementToken:n}}var fr="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",pr="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",Cv="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",bv="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Sv=/\{[^{}\s]*\}/,Rd=/\{\}|\{-?\d+\}/g,vv=["e","f","source","file","-e","-f","--source","--file"],Rv=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],xv=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),Ev=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),gd=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),wv=new Set(["--workdir","--wd"]),hd="__CC_SAFETY_NET_PARALLEL_SOURCE__",Pv=new TextEncoder,na=B.maxDerivedBytes+4*B.maxPlaceholderReplacements;function fe(e,t){for(let n of e){let r=t(n);if(r)return r}return null}function xd(e,t){return fe([...e],(n)=>mt(n,t.scanWork))}function Ed(e,t){let n=e.map(I);if((t.envAssignments?.has("PARALLEL")?t.envAssignments.get("PARALLEL"):t.environment.env.get("PARALLEL"))?.trim()){let p=Vt(t);if(p)return p}if(n.length===2&&(n[1]==="--version"||n[1]==="--help"))return null;let o=Md(n),{template:i,jobs:s,runsRemotely:a,readsCommandsFromInput:l,unsupported:c,workdir:u,dryRun:m}=o;if(c){let p=Vt(t);if(p)return p;let g=xd(t.envAssignments?.values()??[],t);if(g)return g}if(l){let p=Dv(t);if(p)return p}if(u!==void 0&&a){let p=Vt(t);if(p)return p}let f=Fv(u,t.cwd,t.environment.paths);if(f===null){let p=Vt(t);if(p)return p}let d=a?{...t,cwd:void 0,originalCwd:void 0}:f===null||f===void 0||f===t.cwd?t:{...t,cwd:f};if(m){if([...Be(i,d)].flatMap((g)=>[...g.envAssignments.values()]).some(sa)){let g=Vt(t);if(g)return g}return null}if(i.length===0){if(s.some((y)=>y.length!==1)){let y=Vt(t);if(y)return y}let p=s.map((y)=>y[0]??"");Ce(t.budget,ra(p));let g=kd(d.envAssignments,d.cwd,a);return fe(p,(y)=>t.analyzeNested(y,g))}return fe(Be(i,d),(p)=>_v(p,o,t,d))}function _v(e,t,n,r){let{jobs:o,templateHasPlaceholder:i,runsRemotely:s,usesStdin:a}=t,l=e.tokens,c={...r,cwd:e.cwd,envAssignments:e.envAssignments},u=[...e.envAssignments.values()];if(u.some(Id)){let h=Vt(n);if(h)return h}let m=xd(u,n);if(m)return m;let f=u.some(j),d=i||f,p=a&&d,g=kd(e.envAssignments,e.wrapperCwd,s||p);if(ee.has(e.head)){let h=()=>{if(!i||o.length===0)return null;return Ce(n.budget,ti(l,o,"generic")),fe(o,(A)=>_t(l.map((P)=>At(P,A)),c))};if(ke(l))return h();let R=Qe(l);if(R){if(Od(R)){let C=jt(n);if(C)return C;if(o.length===0)return null;return Ce(n.budget,vd(R,o)),fe(o,(_)=>n.analyzeNested(At(R,_),g))}if(j(R)){if(o.length>0)return Ce(n.budget,vd(R,o)),fe(o,(E)=>n.analyzeNested(At(R,E),g));Ce(n.budget,bd(R));let C=lr(R);if(C?.[0]&&z(C[0])==="rm"&&Ue(C)){let E=Cd(n);if(E)return E}let _=C?_t(C,c,{dynamicInput:a,shellDynamicMatch:b("parallel.shell-dynamic",pr),rmDynamicMatch:b("parallel.rm-recursive-force-dynamic",fr)}):null;if(_)return _;return n.analyzeNested(R,g)}let A=!f&&(!i||o.length>0)?(o.length>0?o:[void 0]).map((C)=>Xo(G(C===void 0?l:i?l.map((_)=>At(_,C)):[...l,...C]),R)):[];if(A.some((C)=>C.kind==="dynamic")){let C=jt(n);if(C)return C}let P=A.flatMap((C)=>C.kind==="literal"?[C.source]:[]);if(P.length>0)return Ce(n.budget,ra(P)),fe(P,(C)=>n.analyzeNested(C,g));if(Ce(n.budget,bd(R)),Rn(R)){let C=jt(n);if(C)return C}let S=n.analyzeNested(R,g);if(S)return S;if(d)return jt(n);return null}let x=tt(G(l));if(x.kind==="dynamic"||x.kind==="literal"&&j(x.source))return jt(n)??h();if(x.kind==="literal")return h();if(o.length>0){let A=jt(n);if(A)return A;let P=h();if(P)return P;if(i)return null;let S=o.flatMap((C)=>C[0]===void 0?[]:[C[0]]);return Ce(n.budget,ra(S)),fe(S,(C)=>n.analyzeNested(C,g))}if(d||a)return jt(n)??h();return null}if(e.head==="rm"&&Ue(l)){if(i&&o.length>0)return Ce(n.budget,ti(l,o,"rm")),fe(o,(R)=>ta(l.map((x)=>oa(x,R)),e.cwd,r));if(o.length>0)return Ce(n.budget,Sd(l,o)),fe(o,(R)=>ta([...l,...R],e.cwd,r));let h=ta(l.flatMap((R,x)=>{if(x===0||!j(R))return[R];return R.startsWith("-")?[oa(R,[""])]:[]}),e.cwd,r);if(h)return h;return Cd(n)}Ce(n.budget,i&&o.length>0?ti(l,o,"generic"):o.length>0?Sd(l,o):Ad(l));let y=o.length>0?o:[void 0];return fe(y,(h)=>{let R=h===void 0?l:i?l.map((T)=>At(T,h)):[...l,...h],x=b("parallel.shell-dynamic",pr),A=a&&e.head==="find"?Mv(R,r):null,P=Pd(R,a,n.policy?.rules??[],n.budget)??A?.customResult??null,S=z(e.head),C=a&&(S==="rm"&&ia(R)||S==="xargs"&&_d(R)||A?.rmOptions===!0),_=a&&(C||A?.executedSource===!0||A===null&&wd(R,S)),E=_t(R,{...c,worktreeMode:s||a||d?!1:n.worktreeMode},{dynamicInput:a||d,dynamicRmInput:C,dynamicSourceInput:P!==null||_,shellDynamicMatch:x,dynamicSourceMatch:x,rmDynamicMatch:b("parallel.rm-recursive-force-dynamic",fr)});if(_){let T=k(x,n.policy);if(T)return T}return E??P??ne(R,n.policy?.rules??[])})}function wd(e,t){if(j(e[0]??""))return!0;if(t==="eval"||t==="source"||t===".")return!0;if(t==="parallel"||t==="xargs")return!0;if(ee.has(t))return Tv(e);if(t==="git")return Av(e);if(t==="find")return!0;if(ve.has(t))return yd(e,vv,sr);if(ye(t))return yd(e,Rv,oo);return!1}function ia(e){let t=e.indexOf("--"),n=e.slice(1,t===-1?void 0:t);if(!e.some(j))return t===-1;return n.some((o)=>j(o)&&(o.startsWith("-")||Od(o)))}function Av(e){if(kv(e))return!0;let t=He(e);if(t.subcommand===null||j(t.subcommand))return!0;if(!Cn.has(t.subcommand.toLowerCase()))return!1;let n=t.rest.indexOf("--"),r=t.rest.slice(0,n===-1?void 0:n);if(!e.some(j))return n===-1;return r.some(j)}function kv(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n||n==="--"||!n.startsWith("-"))return!1;if(n==="-c"||n==="--config-env"){if(j(e[t+1]??""))return!0;t++;continue}if(n.startsWith("-c")&&n.length>2||n.startsWith("--config-env=")){if(j(n))return!0;continue}if(j(n))return!0}return!1}function Tv(e){if(ke(e))return!1;let t=Qe(e);if(t!==null)return j(t);let n=tt(G(e));if(n.kind==="literal")return j(n.source);if(n.kind==="dynamic")return!0;return!e.some(j)}function yd(e,t,n){let r=n(e);if(r.some((i)=>j(i.value)))return!0;if(!e.some(j))return n([...e,hd]).some((i)=>i.value===hd);let o=new Set(r.map((i)=>`${i.tokenIndex}\x00${i.kind}\x00${i.value}`));return t.some((i)=>n(e.map((s)=>At(s,[i]))).some((s)=>!o.has(`${s.tokenIndex}\x00${s.kind}\x00${s.value}`)))}function Pd(e,t,n,r){if(!t||n.length===0)return null;let o=n.filter((s)=>z(s.command)===z(e[0]??""));if(o.length===0)return null;let i=e.some(j);if(Ce(r,Iv(e,o,i)),!i)return fe(o,(s)=>ne([...e,...s.subcommand?[s.subcommand]:[],...s.block_args],[s]));return fe(o,(s)=>{let a=new Set([s.subcommand,...s.block_args].flatMap((l)=>l?Ov(e,l):[]));return fe(a,(l)=>ne(e.map((c)=>At(c,[l])),[s]))})}function Iv(e,t,n){let r=n?qt(Te(t.map((o)=>o.block_args.length+(o.subcommand?1:0)),B.maxChildAnalyses),2*Math.max(e.length,1),B.maxChildAnalyses):t.length;return{childAnalyses:r,derivedTokens:qt(r,e.length,B.maxDerivedTokens)}}function Ov(e,t){return e.flatMap((n)=>{let r=[...n.matchAll(/\{[^{}\s]*\}/g)];if(r.length!==1)return[];let o=r[0];if(!o||o.index===void 0)return[];let i=n.slice(0,o.index),s=n.slice(o.index+o[0].length);if(!t.startsWith(i)||!t.endsWith(s))return[t];let a=t.slice(i.length,t.length-s.length);return a!==t?[t,a]:[t]})}function Mv(e,t){let n={customResult:null,executedSource:!e.some(j),rmOptions:!1},r=!1,o=0,i=null,s=()=>{if(!i?.some(j))return;for(let a of Be(i,t))n.executedSource||=wd(a.tokens,a.head),n.rmOptions||=a.head==="rm"&&ia(a.tokens)||a.head==="xargs"&&_d(a.tokens),n.customResult??=Pd(a.tokens,!0,t.policy?.rules??[],t.budget)};for(let a of e.slice(1)){if(!r&&!a.startsWith("-")&&a!=="!"&&a!=="("){n.executedSource||=j(a);continue}if(r=!0,i){if(a===";"||a==="+"){s(),i=null;continue}i.push(a);continue}if(o>0){o--;continue}if(pt(a)){i=[],n.executedSource||=j(a);continue}let l=Et(a);if(l>0){o=l,n.executedSource||=j(a);continue}n.executedSource||=j(a)}return s(),n}function _d(e){let t=e.slice(Ht(e).childStart);return z(t[0]??"")==="rm"&&ia(t)}function ni(e,t){return(n)=>k(b(e,t),n.policy)}var jt=ni("parallel.shell-dynamic",pr),Dv=ni("parallel.command-stream-dynamic",Cv),Vt=ni("parallel.command-stream-dynamic",bv),Cd=ni("parallel.rm-recursive-force-dynamic",fr);function ta(e,t,n){return k(Sn(G(e),{environment:n.environment,cwd:t,originalCwd:n.originalCwd,strict:n.strict,paranoid:n.paranoidRm,allowTmpdirVar:n.allowTmpdirVar,tmpdirWordSplittingUnsafe:Ze(n.envAssignments??new Map,n.environment),trustedTmpdirValue:ft(n.envAssignments??new Map,n.environment),protectedGitMetadata:n.protectedGitMetadata,policy:n.policy}),n.policy)}function ra(e){return{childAnalyses:e.length,derivedTokens:e.length,derivedBytes:gr(e)}}function bd(e){return Ad([e])}function Ad(e){return{childAnalyses:1,derivedTokens:e.length,derivedBytes:gr(e)}}function Sd(e,t){if(t.length>B.maxChildAnalyses)return{childAnalyses:t.length};return{childAnalyses:t.length,derivedTokens:Te(t.map((n)=>e.length+n.length),B.maxDerivedTokens),derivedBytes:Te([qt(gr(e),t.length,B.maxDerivedBytes),Te(t.map((n)=>gr(n)),B.maxDerivedBytes)],B.maxDerivedBytes)}}function vd(e,t){return ti([e],t,"generic")}function ti(e,t,n){if(t.length>B.maxChildAnalyses)return{childAnalyses:t.length};let r=qt(e.length,t.length,B.maxDerivedTokens);if(r>B.maxDerivedTokens)return{childAnalyses:t.length,derivedTokens:r};let o=Wv(e.map((l)=>Nv(l,n))),i=qt(o.occurrences,t.length,B.maxPlaceholderReplacements);if(i>B.maxPlaceholderReplacements)return{childAnalyses:t.length,derivedTokens:r,placeholderReplacements:i};if(Lv(o,t,i))return{childAnalyses:t.length,derivedTokens:r,derivedBytes:B.maxDerivedBytes+1,placeholderReplacements:i};let s=n==="generic"?At:oa,a=Te(t.map((l)=>gr(e.map((c)=>s(c,l)))),B.maxDerivedBytes);return{childAnalyses:t.length,derivedTokens:r,derivedBytes:a,placeholderReplacements:i}}function Lv(e,t,n){let r=B.maxDerivedBytes+4*n;return Te([qt(e.fixedBytes,t.length,r),qt(e.occurrences,Te(t.map((o)=>o.reduce((i,s)=>Math.max(i,mr(s)),0)),r),r)],r)>r}function Nv(e,t){let n=t==="generic"?e.matchAll(/\{[^{}\s]*\}/g):e.matchAll(Rd),r=0,o=0,i=0;for(let s of n){if(r>=B.maxPlaceholderReplacements)return{occurrences:B.maxPlaceholderReplacements+1,fixedBytes:0};o=Te([o,mr(e.slice(i,s.index))],na),r++,i=s.index+s[0].length}return{occurrences:r,fixedBytes:r===0?mr(e):Te([o,mr(e.slice(i))],na)}}function Wv(e){return{occurrences:Te(e.map((t)=>t.occurrences),B.maxPlaceholderReplacements),fixedBytes:Te(e.map((t)=>t.fixedBytes),na)}}function gr(e,t=B.maxDerivedBytes){return Te(e.map(mr),t)}function mr(e){return Pv.encode(e).byteLength}function Te(e,t){let n=0;for(let r of e){if(!Number.isSafeInteger(r)||r<0||r>t-n)return t+1;n+=r}return n}function qt(e,t,n){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<0||e!==0&&t>Math.floor(n/e))return n+1;return e*t}function kd(e,t,n){let r={};if(e)r.envAssignments=e;if(n)return r.effectiveCwd=null,r.worktreeMode=!1,r;if(t!==void 0)r.effectiveCwd=t;return Object.keys(r).length>0?r:void 0}function At(e,t){return e.replace(/\{[^{}\s]*\}/g,(n)=>Td(n,t))}function oa(e,t){return e.replace(Rd,(n)=>Td(n,t))}function Td(e,t){let n=/^\{(-?\d+)[^{}\s]*\}$/.exec(e)?.[1];if(n===void 0)return t[0]??"";let r=Number(n),o=r>0?r-1:t.length+r;return t[o]??""}function j(e){return Sv.test(e)}function Id(e){if(sa(e))return!0;for(let t of e.matchAll(/\{[^{}\s]*\}/g))if(!/^(?:\{\}|\{-?\d+\})$/.test(t[0]))return!0;return!1}function sa(e){let t=e.indexOf("{=");return t!==-1&&e.indexOf("=}",t+2)!==-1}function Od(e){return/^\{[^{}\s]*\}$/.test(e)}function Md(e){let t=1,n=[],r=e.length,o=-1,i=!1,s=!1,a=!1,l,c=e.some((p)=>p==="::::"||p==="::::+"||p===":::+");while(t<e.length){let p=e[t];if(p===void 0)break;if(p===":::"){o=t;break}if(p==="--"){let x=Ls(e,t+1);n.push(...x.templateTokens),r=t+1,o=x.markerIndex;break}if(!p.startsWith("-")){let x=Ls(e,t);n.push(...x.templateTokens),r=t,o=x.markerIndex;break}let g=e[t+1],y=p.indexOf("="),h=y===-1?p:p.slice(0,y),R=y===-1?void 0:p.slice(y+1);if(p==="--dry-run"){a=!0,t++;continue}if(p==="-I"||p.startsWith("-I")&&p.length>2){c||=(p==="-I"?g:p.slice(2))!=="{}",t+=p==="-I"?2:1;continue}if(p==="--replace"||p==="-i"){c=!0,t+=2;continue}if(h==="--replace"||p.startsWith("-i")&&p.length>2){let x=h==="--replace"?R:p.slice(2);c||=x!==""&&x!=="{}",t++;continue}if(p==="-a"||Ev.has(h)){c=!0,t+=R===void 0?2:1;continue}if(p==="--pipe"||p==="--pipepart"){s=!0,t++;continue}if(h==="--env"){c=!0,t+=R===void 0?2:1;continue}if(gd.has(h)||p.startsWith("-S")&&p.length>2){i=!0,t+=gd.has(p)?2:1;continue}if(wv.has(h)){let x=R??g;if(x===void 0||x===":::"||x==="--"){c=!0,t++;continue}l=x,c||=R!==void 0&&x==="",t+=R===void 0?2:1;continue}if(p.startsWith("-j")&&p.length>2&&/^\d+$/.test(p.slice(2))){t++;continue}if(p.startsWith("--")&&R!==void 0){t++;continue}if(xv.has(p)){if(g===void 0||g===":::"||g==="--"){c=!0,t++;continue}t+=2;continue}t+=p==="-j"||p==="--jobs"?2:1}c||=n.some(a?sa:Id);let u=[];if(o!==-1){let p=[];for(let g=o+1;g<e.length;g++){let y=e[g];if(y===":::"){u.push(p),p=[];continue}if(y!==void 0)p.push(y)}u.push(p)}let m=Gv(u),f=n.some(j),d=n.length===0&&o===-1;return{template:n,jobs:m,childStart:r,templateHasPlaceholder:f,runsRemotely:i,usesStdin:s||o===-1,readsCommandsFromInput:d,unsupported:c,workdir:l,dryRun:a}}function Fv(e,t,n){if(e===void 0)return;if(e==="..."||/[{}$`*?~[]/.test(e))return null;if(!t&&!yv(e))return null;try{return bt(t??e,e,n)}catch{return null}}function Gv(e){if(e.length===0||e.some((n)=>n.length===0))return[];let t=[[]];for(let n of e){if(n.length===1){let o=n[0];if(o===void 0)return[];for(let i of t)i.push(o);continue}let r=[];for(let o of t)for(let i of n)if(r.push([...o,i]),r.length>B.maxChildAnalyses)return r;t=r}return t}function Dd(e){return Md(e).childStart}var zv="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",ri="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function la(e){return e?.parts.some((t)=>t.provenance==="command-substitution")??!1}function aa(e){return e?.parts.some((t)=>t.provenance==="literal"&&t.raw.replace(/^["']/,"").startsWith("-"))??!1}function Nd(e,t,n,r,o=!1,i){let a=(Yn(e,t)||r&&e!=="powershell"&&t[0]?.provenance==="variable")&&Q(i,"shell.dynamic-executable",o)?b("shell.dynamic-executable",zv):null;return k(a,i)??Wd(e,t,n,o,i)}function Wd(e,t,n,r,o){if(t.length<2)return null;let i=t.flatMap((a,l)=>la(a)?[l]:[]);if(i.length===0)return null;let s=z(t[0]?.text??"");if(s==="git"){let a=rn(e,t),l=Bv(a);if(Q(o,"shell.dynamic-structure",r)&&i.some((m)=>m<=l))return k(b("shell.dynamic-structure",ri),o);if(k(bn(a,{env:n.env}),o))return null;let c=t[l]?.text.toLowerCase(),u=a.findIndex((m,f)=>f>l&&I(m)==="--");if(Q(o,"shell.dynamic-structure",r)&&c&&Cn.has(c)&&i.some((m)=>m>l&&(u===-1||m<u)))return k(b("shell.dynamic-structure",ri),o);return null}if(s==="find")return Q(o,"shell.dynamic-structure",r)&&Uv(t)?k(b("shell.dynamic-structure",ri),o):null;if(s==="rm"){let a=t.findIndex((c,u)=>u>0&&I(c)==="--"),l=Ue(t.map(I));return Q(o,"shell.dynamic-structure",r)&&i.some((c)=>(a===-1||c<a)&&(c<t.length-1||!l))?k(b("shell.dynamic-structure",ri),o):null}if(s==="xargs")return Ld(e,t.slice(Ht(t.map(I)).childStart),"xargs",n,r,o);if(s==="parallel")return Ld(e,t.slice(Dd(t.map(I))),"parallel",n,r,o);return null}function Ld(e,t,n,r,o,i){if(t.length===0)return null;let s=$v(t,r);if(Yn(e,s)){let l=k(b(`${n}.shell-dynamic`,n==="xargs"?Qs:pr),i);if(l)return l}let a=Wd(e,s,r,o,i);if(a)return a;if(s[0]?.text==="rm"&&s.slice(1).some((l)=>la(l)&&aa(l)))return k(b(`${n}.rm-recursive-force-dynamic`,n==="xargs"?Js:fr),i);return null}function $v(e,t){let n=Nt(e,t),r=n.rewritten?G(n.words.map(I)):n.words,o=r[0];return o&&I(o)==="busybox"?r.slice(1):r}function Bv(e){let t=1;while(t<e.length){let n=e[t],r=n?I(n):"";if(Ye.has(r)){t+=2;continue}if(r.startsWith("-")){t++;continue}return t}return t}function Uv(e){let t=!1,n=0,r=!1,o=!1;for(let i=1;i<e.length;i++){let s=e[i];if(!s)continue;let a=la(s);if(n>0){n--;continue}if(o){if(s.text===";"||s.text==="+"){o=!1,t=!0,r=!1;continue}if(a&&(r||aa(s)))return!0;r=!1;continue}if(!t&&!s.text.startsWith("-")){if(a&&(i>1||aa(s)))return!0;continue}if(t=!0,a)return!0;let l=Et(s.text);if(l>0){n=l;continue}if(pt(s.text))o=!0,r=!0}return!1}function ca(e,t){return e.some((n)=>{if(n.value==="-"&&(n.kind==="main-script"||n.kind==="program-file"))return!0;return!Fr(t[n.tokenIndex],n.value)})}var Hv="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",jv="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",Vv="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function Fd(e,t){let n=t.slice(1);if(e==="dd"&&n.some((r)=>/^of=\/dev\/.+/.test(r)))return b("dd.device-write",Hv);if((e==="mkfs"||e.startsWith("mkfs."))&&n.some((r)=>r.startsWith("/dev/")))return b("mkfs.device",jv);if(e==="shred"&&n.length>0)return b("shred.target",Vv);return null}var zd=[{heads:new Set(["rm","rmdir"]),analyze:(e)=>Sn(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoid:e.options.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:Ze(e.envAssignments,e.options.environment),trustedTmpdirValue:ft(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,policy:e.options.policy})},{heads:new Set(["git"]),analyze:(e)=>bn(e.words,ua(e))},{heads:new Set(["find"]),analyze:(e)=>Ko(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:Ze(e.envAssignments,e.options.environment),trustedTmpdirValue:ft(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,derivedCommandWorkBudget:e.options.derivedCommandWorkBudget,envAssignments:e.envAssignments,policy:e.options.policy,analyzeTokens:e.analyzeChildTokens,analyzeNested:(t,n)=>Kt(e.options.analyzeNested(t,n))})},{heads:new Set(["xargs"]),analyze:(e)=>ud(e.words,{...Gd(e),analyzeNested:(t,n)=>Kt(e.options.analyzeNested(t,n))})},{heads:new Set(["parallel"]),analyze:(e)=>Ed(e.words,{...Gd(e),budget:e.options.parallelBudget,analyzeNested:(t,n)=>Kt(e.options.analyzeNested(t,n))})}];function Gd(e){return{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoidRm:e.options.paranoidRm,paranoidInterpreters:e.options.paranoidInterpreters,allowTmpdirVar:e.allowTmpdirVar,protectedGitMetadata:e.options.protectedGitMetadata,derivedCommandWorkBudget:e.options.derivedCommandWorkBudget,envAssignments:e.envAssignments,worktreeMode:e.options.worktreeMode,policy:e.options.policy,scanWork:e.options.scanWork}}function Kt(e){return e?{id:e.ruleId??"",reason:e.reason,intent:e.intent??"manual_only"}:null}function ua(e){return{env:e.options.environment.env,cwd:e.cwd,dynamicArguments:e.dynamicArguments,envAssignments:e.envAssignments,policy:e.options.policy,worktreeMode:e.options.worktreeMode}}var Hd="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function jd(e){return zd.find((t)=>t.heads.has(e))?.analyze}function hr(e,t,n){let r=n.trace;if(e.length===0)return null;let o=n.commandView?.dialect??"posix",i=(w)=>w.map((N)=>o==="posix"?I(N):N.text),s=n.effectiveCwd===null,a=s?void 0:n.effectiveCwd??n.cwd,l=s?void 0:n.cwd,c=mo(e);if(c.envAssignments.size>0)r?.recordSegment({type:"env-strip",input:i(e),envVars:[...c.envAssignments.keys()],output:i(c.words)});let u=Nt(c.words,n.environment,a,new Map([...n.envAssignments??[],...c.envAssignments])),m=u.envSplitValues??[];if(m.length>0){let w=[...m,...i(u.words)].join(" "),N=mt(w,n.scanWork);if(N)return r?.recordSegment({type:"dangerous-text",token:w,matched:!0,reason:N.reason}),rt(N);if(n.strict)return Re(r);let Z=fo(m,i(u.words));if(Z){Le(n.derivedCommandWorkBudget,Z.length);let J=n.analyzeNested(Z.join(" "),{effectiveCwd:u.cwd===void 0?n.effectiveCwd:u.cwd,envAssignments:new Map([...n.envAssignments??[],...c.envAssignments,...u.envAssignments])});if(J)return J}}let f=u.rewritten?G(i(u.words)):rn(o,u.words),d=i(f),p={...n,wrapperNormalizationBudget:n.wrapperNormalizationBudget??{iterations:0}};if(r&&c.words.length>f.length){let w=i(c.words);r.recordSegment({type:"leading-tokens-stripped",input:w,removed:w.slice(0,w.length-f.length),output:d})}let g=new Map([...n.envAssignments??[],...c.envAssignments,...u.envAssignments]),y=d[0];if(!y)return null;if($t(y))throw new he;let h=z(y),R=u.cwd===null?void 0:u.cwd??a,x=u.cwd===null?void 0:l,A=u.cwd===void 0?n.effectiveCwd:u.cwd,P=!jn(g,n.environment),S=Nd(o,u.words,n.environment,t===0,n.strict,n.policy);if(S)return r?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:S.reason}),rt(S);let C=Vo(d,n.policy);if(C){for(let w of[C.childIndex,...C.alternativeChildIndices]){$d(p.wrapperNormalizationBudget);let N=f.slice(w);r?.recordSegment({type:"transparent-wrapper",wrapper:C.wrapper,output:i(N)});let Z=hr(N,t,{...p,effectiveCwd:A,envAssignments:g});if(Z)return Z}return null}let _=h==="eval"?vn(f):h==="trap"?rd(f):void 0;if(_?.kind==="dynamic"&&(n.strict||!n.commandView||!Zs(n.commandView)))return Re(r);if(_?.kind==="literal"){r?.recordSegment({type:"recurse",reason:h==="eval"?"shell-eval":"shell-trap",innerCommand:_.source,depth:t+1});let w=n.analyzeNested(_.source,{effectiveCwd:A,envAssignments:g,functionDefinitions:n.functionDefinitions});if(w)return w}if(qd(y,h)){if(ke(d))return null;let w=qv(d,g,A,n,r,t);if(w)return w;let N=Qe(d);if(N){let nn=Xo(f,N);if(nn.kind==="dynamic")return Re(r);let Li=nn.kind==="literal"?nn.source:N,il=Kv(Li);r?.recordSegment({type:"shell-wrapper",wrapper:h,innerCommand:il}),r?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:il,depth:t+1});let sl=n.analyzeNested(Li,{effectiveCwd:A,envAssignments:g});if(sl)return sl;return Rn(Li)?Re(r):null}let Z=tt(f);if(Z.kind==="dynamic")return Re(r);if(Z.kind==="literal")return si(Z.source,A,g,n,r,t);let J=od(f,n.commandView?.redirections??[],n.hasPipelineInput??!1,n.literalShellInput);if(J.kind==="dynamic")return Re(r);if(J.kind==="literal")return r?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:J.source,depth:t+1}),n.analyzeNested(J.source,{effectiveCwd:A,envAssignments:g})}if(h==="source"||h==="."){let w=d[1]==="-p"?2:null;if(w!==null){let nn=n.commandView?f[w]:void 0;if(!nn)return null;if(nn.provenance!=="literal")return Re(r)}let N=w===null?1:3,Z=d[N]==="--"?N+1:N,J=n.commandView?f[Z]:void 0;if(!J)return null;if(J.provenance==="literal")return si(J.text,A,g,n,r,t);if(n.strict||!n.commandView||!Zs(n.commandView))return Re(r)}if(ve.has(h)){if(n.strict&&ca(sr(d),f))return Re(r);let w=jo(d,(Z)=>Kt(n.analyzeNested(Z,{effectiveCwd:A,envAssignments:g}))),N=k(w,n.policy);if(N)return r?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:N.reason}),rt(N)}if(ye(h)){if(n.strict&&ca(oo(d),f))return Re(r);let w=ro(d);if(w){let N=Q(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(r?.recordSegment({type:"interpreter",interpreter:h,codeArg:w,paranoidBlocked:N}),N){let J=k(b("interpreter.one-liner-paranoid",un),n.policy);if(J)return rt(J)}if(so(h,w))return null;r?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:w,depth:t+1});let Z=n.analyzeNested(w,{effectiveCwd:A,envAssignments:g});if(Z&&Z.ruleId!=="raw-text.dangerous-command"&&(Z.reason!==St||hn(w)))return Z;if(dn(w,n.scanWork)){let J=k(b("interpreter.dangerous-command",Lt),n.policy);if(J)return r?.recordSegment({type:"dangerous-text",token:w,matched:!0,reason:Lt}),rt(J)}r=void 0}}if(h==="busybox"&&d.length>1)return $d(p.wrapperNormalizationBudget),r?.recordSegment({type:"busybox",subcommand:d[1]??"unknown"}),r?.recordSegment({type:"recurse",reason:"busybox",innerCommand:d.slice(1).join(" "),depth:t+1}),hr(f.slice(1),t,{...p,effectiveCwd:A,envAssignments:g});let E=k(Fd(h,d),n.policy);if(E)return r?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:E.reason}),rt(E);let T=r===p.trace?p:{...p,trace:r},O={words:f,head:h,cwd:R,originalCwd:x,envAssignments:g,allowTmpdirVar:P,dynamicArguments:u.words.some((w)=>w.provenance==="command-substitution"),depth:t,effectiveCwd:A,options:T,analyzeChildTokens:(w,N)=>Kt(hr(G(w),t+1,{...T,commandView:void 0,effectiveCwd:N,envAssignments:g}))??ne(w,T.policy.rules)},M=jd(h);if(h==="rm"||h==="xargs"||h==="parallel")r?.recordSegment({type:"tmpdir-check",tmpdirValue:g.has("TMPDIR")||n.environment.env.has("TMPDIR")?"<redacted>":null,isOverriddenToNonTemp:!P,allowTmpdirVar:P});let F=r&&h==="git"?Vu(O.words,ua(O)):void 0,oe=Bd(F?F.match:M?.(O)??null,n.policy);if(r)Yv(O,oe,F?.relaxation??null);if(oe)return rt(oe);let Ee=M!==void 0;if(!Ee)if(!to.has(h)){let w=r?[]:void 0;for(let N=1;N<d.length;N++){let Z=d[N];if(!Z)continue;w?.push(Z);let J=Bd(Zv(O,d,N),n.policy);if(J)return r?.recordSegment({type:"fallback-scan",tokensScanned:w??[],embeddedCommandFound:z(Z)}),rt(J)}r?.recordSegment({type:"fallback-scan",tokensScanned:w??[]})}else r?.recordSegment({type:"fallback-scan",tokensScanned:[]});else r?.recordSegment({type:"fallback-scan",tokensScanned:[]});if(t===0||!Ee){let w=ne(d,n.policy.rules);if(r?.recordSegment({type:"custom-rules-check",rulesChecked:n.policy.rules.length>0,matched:!!w,reason:w?.reason}),w)return rt(w)}else r?.recordSegment({type:"custom-rules-check",rulesChecked:!1,matched:!1});return null}function qv(e,t,n,r,o,i){let s=Ju(e);if(s.argvSource?.kind==="absent")return Re(o);if(s.argvSourceApplies&&s.argvSource){let l=si(s.argvSource.value,n,t,r,o,i,!0);if(l)return l}if(!s.envSourceApplies||!s.envName)return null;let a=t.get(s.envName);if(!a)return null;return si(a,n,t,r,o,i,!0)}function si(e,t,n,r,o,i,s=!1){if(s&&/[$`*?[\]]/.test(e))return Re(o);let a=Hn(e,t,r.environment.paths),l=a?r.literalHeredocFiles?.get(a):void 0;if(l===void 0)return s?Re(o):null;return Le(r.derivedCommandWorkBudget,1),o?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:l,depth:i+1}),r.analyzeNested(l,{effectiveCwd:t,envAssignments:n})}function Kv(e){let t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.at(-1)===t?e.slice(1,-1):e}function Yv(e,t,n){let r={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[e.head];if(!r)return;if(e.options.trace?.recordSegment({type:"rule-check",rule:r,matched:!!t||!!n,reason:t?.reason??n?.originalReason}),n)e.options.trace?.recordSegment({type:"worktree-relaxation",originalReason:n.originalReason,gitCwd:n.gitCwd})}function $d(e){if(e.iterations>=ln)throw new he;e.iterations++}function rt(e){return{reason:e.reason,ruleId:e.id||void 0,intent:e.intent}}function Re(e){return e?.recordSegment({type:"error",message:Hd}),rt(Vd())}function Vd(){return{id:"",reason:Hd,intent:"stop_and_explain"}}function qd(e,t){return ee.has(t)||e==="$SHELL"||e==="${SHELL}"||ee.has(D(t))}function Zv(e,t,n){let r=Be(t.slice(n),{environment:e.options.environment,cwd:e.cwd,envAssignments:e.envAssignments,policy:e.options.policy});for(let o of r){let i=Xv(e,n,o);if(i)return i}return null}function Xv(e,t,n){let r=n.tokens[0];if(!r)return null;let o=z(r);if(qd(r,o)){Le(e.options.derivedCommandWorkBudget,e.words.length-t);let l=n.tokens;if(ke(l))return null;let c=Qe(l);if(!c){if(tt(G(l)).kind==="dynamic")return Vd();return ii(e,n)}let u=e.options.analyzeNested(c,{effectiveCwd:n.wrapperCwd===void 0?e.effectiveCwd:n.wrapperCwd,envAssignments:n.envAssignments});return u?Kt(u):ii(e,n)}let i=jd(o);if(!i||o==="xargs"||o==="parallel"){if(n.wrappedByTransparent&&e.options.policy.rules.length>0)Le(e.options.derivedCommandWorkBudget,e.words.length-t);return ii(e,n)}Le(e.options.derivedCommandWorkBudget,e.words.length-t);let s=[o,...n.tokens.slice(1)],a={...e,words:G(s),head:o,cwd:n.cwd,originalCwd:n.wrapperCwd===null?void 0:e.originalCwd,envAssignments:n.envAssignments,allowTmpdirVar:!jn(n.envAssignments,e.options.environment),effectiveCwd:n.wrapperCwd===void 0?e.effectiveCwd:n.wrapperCwd,options:o==="git"?{...e.options,worktreeMode:!1}:e.options};return i(a)??ii(e,n)}function ii(e,t){return t.wrappedByTransparent?ne(t.tokens,e.options.policy.rules):null}function Bd(e,t){return e?.id.startsWith("custom.")||e?.id==="raw-text.dangerous-command"?e:k(e,t)}var Jv=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,Qv=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function eR(e,t){let n=Zd(e,t);if(n.length===0)return!1;let r=n[Yd(n)];if(r==="cd"||r==="pushd"||r==="popd")return!0;return Jv.test(e.join(" "))}function Kd(e,t,n,r){if(e.dialect==="powershell"){let a=tR(e.words,r);if(a.kind==="none")return;if(!t||a.kind==="unknown")return null;return Ud(iR(a.target),t,n.paths)}let o=e.words.map(I);if(!eR(o,n))return;if(!t)return null;let i=Zd(o,n,t),s=Yd(i);if(s===-1||i[s]!=="cd")return null;return Ud(i[s+1],t,n.paths)}function Ud(e,t,n){if(!e||e==="-"||e.includes("$")||e.includes("`"))return null;try{return sR(bt(t,e,n),t,n)?t:null}catch{return null}}function tR(e,t){let n=nR(e[0])?1:0,r=e[n];if(!rR(r,n===1))return{kind:"none"};let o=r.text.toLowerCase(),i=o.split(/[\\/]/).pop()??o;if(!Qv.has(i))return{kind:"none"};if(o!==i||i==="pop-location"||i==="popd")return{kind:"unknown"};return oR(e.slice(n+1),t)}function nR(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&(e.text==="&"||e.text===".")}function rR(e,t){return e?.provenance==="literal"&&(t||!e.quoted&&e.raw===e.text)}function oR(e,t){let n;for(let r of e){if(r.provenance!=="literal"||n!==void 0)return{kind:"unknown"};n=r.text}if(n!==void 0)return{kind:"target",target:n};return t===void 0?{kind:"unknown"}:{kind:"target",target:t}}function iR(e){return e.includes("::")?void 0:e.replaceAll("\\","/")}function Yd(e){let t=0;if(e[0]==="builtin"&&e.length>1)t=1;if(e[t]!=="time")return t;let n=t+1;while(e[n]?.startsWith("-"))n++;return n}function Zd(e,t,n){let r=aR(e);return fn([...r],t,n)}function sR(e,t,n){let r=n.realpath(e),o=n.realpath(t);if(r===null||o===null)return oi(e)===oi(t);return oi(r)===oi(o)}function aR(e){let t=0;while(t<e.length){let n=e[t];if(n==="{"||n==="("||n==="$(")t++;else break}return e.slice(t)}var ma="TMPDIR",fa="IFS",Xd=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Jd=/^[A-Za-z_][A-Za-z0-9_]*$/,Qd=new Set(["export","typeset","declare","readonly"]),lR=new Set(["builtin","command","time"]);function em(e,t){return{env:e,effectiveEnvAssignments:fR(e,t),shellAssignments:new Map}}function tm(e){return{env:e.env,effectiveEnvAssignments:e.effectiveEnvAssignments?new Map(e.effectiveEnvAssignments):void 0,shellAssignments:new Map(e.shellAssignments)}}function pa(e,t){let n=rm(e,t);n.assignments.filter((s)=>s.persists).forEach((s)=>{t.shellAssignments.set(s.name,s.value),ga(t,s)});let r=n.commandIndex;if(r!==-1&&Qd.has(e[r]??""))e.filter((s)=>Jd.test(s)&&da(s)).forEach((s)=>{pR(t,s)});let o=r===-1?-1:om(e,r);if(o===-1||e[o]!=="unset")return;let i=hR(e,o);if(i===null)return;e.slice(i).forEach((s)=>{gR(t,s)})}function nm(e,t){let n=rm(e,t).assignments;if(n.length===0)return t.effectiveEnvAssignments;let r=new Map(t.effectiveEnvAssignments??[]);return n.forEach((o)=>{r.set(o.name,o.value)}),r}function rm(e,t){let n=e.findIndex((s)=>!cR(s)),r=n!==-1&&Qd.has(e[om(e,n)]??""),o=mR(t);return{assignments:e.flatMap((s,a)=>{let l=uR(s,o,t.env);if(!l)return[];if(n!==-1&&a>n&&!r&&!Fi(l.name))return[];return o.set(l.name,l.value),[{...l,persists:n===-1||r}]}),commandIndex:n}}function om(e,t){let n=t;while(lR.has(e[n]??"")){n+=1;while(e[n]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(e[n]??""))return t;n+=1}}return n}function cR(e){return _e(e)!==null||Xd.test(e)}function uR(e,t,n){return _e(e)??dR(e,t,n)}function dR(e,t,n){let r=$r(e,n,t);if(r)return r;let o=e.match(Xd)?.[1];if(!o)return null;let i=e.indexOf("=");return{name:o,value:`${t.has(o)?t.get(o):n.get(o)??""}${e.slice(i+1)}`}}function da(e){return e===ma||e===fa||Gi(e)}function mR(e){return new Map([...e.effectiveEnvAssignments??[],...e.shellAssignments])}function fR(e,t){let n=[...Gr,ma,fa].map((r)=>{let o=e.get(r);return o===void 0?null:[r,o]}).filter((r)=>r!==null);if(n.length===0)return t;return new Map([...n,...t??[]])}function ga(e,t){let n=new Map(e.effectiveEnvAssignments??[]);n.set(t.name,t.value),e.effectiveEnvAssignments=n}function pR(e,t){ga(e,{name:t,value:e.shellAssignments.get(t)??e.effectiveEnvAssignments?.get(t)??e.env.get(t)??""})}function gR(e,t){if(!da(t)&&!Jd.test(t))return;if(e.shellAssignments.set(t,""),!da(t)||t===ma||t===fa||Wn(t)){ga(e,{name:t,value:""});return}if(!e.effectiveEnvAssignments?.has(t))return;let n=new Map(e.effectiveEnvAssignments);n.delete(t),e.effectiveEnvAssignments=n.size===0?void 0:n}function hR(e,t){let n=t+1;while(n<e.length){let r=e[n];if(!r)return null;if(r==="--")return n+1;if(r==="-v"){n++;continue}if(r.startsWith("-"))return null;return n}return n}var yR="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Yt="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.",CR=64;function Sa(e,t,n,r){let o=n.derivedCommandWorkBudget===void 0,i=n.parallelBudget===void 0;try{return bR(e,t,{...n,derivedCommandWorkBudget:n.derivedCommandWorkBudget??Zr(),parallelBudget:n.parallelBudget??Kl()},r)}catch(s){let a=s instanceof he&&o?Fl:s instanceof co&&i?ql:void 0;if(!a)throw s;if(n.trace?.currentSegmentIndex!==void 0)n.trace.recordSegment({type:"error",message:a});else n.trace?.recordGlobal({type:"error",message:a});return{reason:a,segment:e,intent:"stop_and_explain"}}}function bR(e,t,n,r){if(t>=eo)return n.trace?.recordSegment({type:"error",message:lt}),{reason:lt,segment:e,intent:"stop_and_explain"};let o=r??n.factStore?.getCommandProgram(e,n.shell??"auto")??Fe(e,n.shell);if(o.status==="limited")return n.trace?.recordSegment({type:"error",message:lt}),{reason:lt,segment:e,intent:"stop_and_explain"};if(o.status==="invalid"){let c=o.issues.find((u)=>u.code.includes("heredoc"));if(c){if(!n.strict)return ba(e,n);let u=`Unsupported heredoc syntax: ${c.message}`;return n.trace?.recordGlobal({type:"error",message:u}),{reason:u,segment:e,intent:"stop_and_explain"}}return um(e,n),{reason:St,segment:e,intent:"stop_and_explain"}}if(n.strict&&o.status==="partial")return um(e,n),{reason:St,segment:e,intent:"stop_and_explain"};if(o.issues.some((c)=>c.code.includes("quote"))&&!n.analyzePartialProgram)return ba(e,n);let s=n.cwd,a=n.effectiveCwd!==void 0?n.effectiveCwd:n.cwd,l=em(n.environment.env,n.envAssignments);return ci(o,t,{...n,rootProgram:o},s,[{effectiveCwd:a,shellGitContextState:l,literalHeredocFiles:new Map(n.literalHeredocFiles),functionDefinitions:new Map(n.functionDefinitions)}]).result}function ci(e,t,n,r,o){let i=[...o],s,a;for(let[l,c]of e.nodes.entries()){if(c.kind==="connector"){a=c.operator;continue}let u=e.nodes[l+1],m=u?.kind==="connector"?u.operator:void 0,f=SR(e,l,c,a,m),d=a==="&&"||a==="||",p=d?s:void 0,g=a==="&&"?p?.success??i:a==="||"?p?.failure??i:i,y=a==="||"?p?.success??[]:[],h=a==="&&"?p?.failure??[]:[],R=d||En(m);if(c.kind==="function"){let E=g.flatMap((O)=>{let M=yr(O);return M.functionDefinitions.set(c.name,c.body),ha(O,[M],f,m==="&",En(m))}),T=ya(E,[],y,h,a,m);i=T.states,s=T.conditionalStates,a=void 0;continue}if(c.kind==="group"){let E=[],T=[];for(let M of g){let F=ci(c.body,t,n,r,[yr(M)]);if(F.result)return F;if(E.push(...ha(M,F.states,f,m==="&",En(m))),R)T.push(M,...f?F.states.map((oe)=>ai(M,oe)):F.states)}let O=ya(E,T,y,h,a,m);i=O.states,s=O.conditionalStates,a=void 0;continue}if(c.kind!=="command")continue;let x=n.trace?.flattenNested?n.trace.currentSegmentIndex:n.trace?.allocateSegment(),A=e.nodes[l-2],P=ui(a)&&A?.kind==="command"?nd(A)??RR(A):void 0,S=[],C=[];for(let E of g){let T=xR(c,t,n,r,[yr(E)]);if(T.result)return{result:T.result,states:i};let O=e.dialect==="powershell"?T.states:T.states.map((M)=>ai(E,M));for(let M of O){let F=yr(M),oe=PR(c,t,n.trace?{...n,trace:dm(n.trace,x)}:n,r,F,ui(a),P);if(oe)return{result:oe,states:i};let Ee=GR(c,F.functionDefinitions);if(Ee)Le(n.derivedCommandWorkBudget,di(Ee));let w=Ee?t+1>=eo?Ca(c.displayText,n,[F]):ci(Ee,t+1,n,r,[F]):{result:null,states:[F]};if(w.result)return w;if(S.push(...ha(E,w.states,f,m==="&",En(m))),R)C.push(E),C.push(...w.states.map((N)=>f?ai(E,N):N))}}let _=ya(S,C,y,h,a,m);i=_.states,s=_.conditionalStates,a=void 0}return{result:null,states:i}}function SR(e,t,n,r,o){if(n.kind==="group"&&n.style==="subshell")return!0;if(e.dialect==="posix"&&(ui(r)||ui(o)))return!0;if(o==="&")return!0;return e.dialect==="powershell"&&n.kind==="group"&&n.style==="brace"&&vR(e,t)}function ha(e,t,n,r,o){let i=n?t.map((a)=>ai(e,a)):[...t],s=o?i.flatMap((a)=>Cr(e.literalHeredocFiles,a.literalHeredocFiles)?[a]:[{...a,literalHeredocFiles:new Map(e.literalHeredocFiles)},a]):i;return r?[e,...s]:s}function ai(e,t){return{...e,literalHeredocFiles:new Map(t.literalHeredocFiles)}}function vR(e,t){let n=[...e.nodes.slice(0,t)].reverse().find((o)=>o.kind==="command"||o.kind==="connector");if(!n||n.kind!=="command")return!0;let r=n.words[0]?.text.toLowerCase();if(r==="&"||r===".")return!1;if(r==="write-output"||r==="function"||r==="start-job")return!0;if(ER(n))return!0;return n.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function ui(e){return e==="|"||e==="|&"}function RR(e){if(e?.dialect!=="powershell")return;if(e.words.length===1&&e.words[0]?.quoted&&e.words[0].provenance==="literal")return e.words[0].text;if(e.words[0]?.text.toLowerCase()==="write-output"&&e.words.length===2&&e.words[1]?.provenance==="literal")return e.words[1].text;return}function En(e){return e==="&&"||e==="||"}function ya(e,t,n,r,o,i){let s={success:li([...n,...e]),failure:li([...r,...t])},a=En(i)?s:void 0;return{states:En(o)||a?li([...s.success,...s.failure]):s.success,conditionalStates:a}}function dm(e,t,n=e.flattenNested){return{currentSegmentIndex:t,flattenNested:n,allocateSegment:e.allocateSegment,getNextSegmentIndex:e.getNextSegmentIndex,recordGlobal:e.recordGlobal,recordSegment:(r,o=t)=>e.recordSegment(r,o)}}function xR(e,t,n,r,o){let i=e.nested.map((s)=>({program:s,depth:t}));if(e.dialect==="powershell"){let s=wR(e);if(s){if(t+1>=eo)return Ca(s,n,o);let a=Fe(s,"powershell");if(a.status==="limited")return Ca(s,n,o);if(a.status!=="complete")return im(i,n,r,o);Le(n.derivedCommandWorkBudget,di(a)),i.push({program:a,depth:t+1})}}return im(i,n,r,o)}function ER(e){let t=e.words[0];return t?.provenance==="variable"&&e.words.at(-1)?.text==="="?t.text.toLowerCase():void 0}function im(e,t,n,r){let o=[...r];for(let i of e){let s=[];for(let a of o){let l=ci(i.program,i.depth,t,n,[yr(a)]);if(l.result)return l;s.push(...l.states)}o=li(s)}return{result:null,states:o}}function wR(e){let t=e.words[0]?.provenance==="literal"&&!e.words[0].quoted&&e.words[0].raw===e.words[0].text&&(e.words[0].text==="&"||e.words[0].text==="."),n=t?1:0,r=e.words[n];if(r?.provenance!=="literal"||!t&&(r.quoted||r.raw!==r.text)||!["iex","invoke-expression"].includes(r.text.toLowerCase()))return;let o=e.words.slice(n+1),i=o[0]&&!o[0].quoted&&o[0].raw===o[0].text&&["-c","-command"].includes(o[0].text.toLowerCase())?1:0,s=o[i];return o.length===i+1&&s?.quoted&&s.provenance==="literal"?s.text:void 0}function di(e){return e.nodes.reduce((t,n)=>t+(n.kind==="command"?n.words.length+n.nested.reduce((r,o)=>r+di(o),0):n.kind==="group"||n.kind==="function"?di(n.body):0),0)}function Ca(e,t,n){return t.trace?.recordSegment({type:"error",message:lt}),{result:{reason:lt,segment:e,intent:"stop_and_explain"},states:[...n]}}function PR(e,t,n,r,o,i,s){let a=MR(e);if(a&&n.strict)return n.trace?.recordSegment({type:"error",message:a}),{reason:a,segment:e.source,intent:"stop_and_explain"};mm(e,o,"before-consumer",n.environment.paths);let l=rn(e.dialect,e.words).map(I),c=e.displayText,u=nm(l,o.shellGitContextState);if(e.dialect==="powershell"){let d=k(Ru(e,i,$R(n,o.effectiveCwd)),n.policy);if(n.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!d,reason:d?.reason}),d)return zR(c,d)}if(l.length===1&&l[0]?.includes(" ")&&!Yn(e.dialect,e.words)){let d=k(mt(l[0],n.scanWork),n.policy),p=d!==null&&!n.strict&&Ll(e,n.rootProgram,n.scanWork);if(d&&!p)return n.trace?.recordSegment({type:"dangerous-text",token:l[0],matched:!0,reason:d.reason}),{reason:d.reason,segment:c,ruleId:d.id,intent:d.intent};n.trace?.recordSegment({type:"dangerous-text",token:l[0],matched:!1});let g=sm(e,a,o,u,s,n);if(g)return g;return pa(l,o.shellGitContextState),null}let m=hr(e.words,t,{...n,commandView:e,cwd:r,effectiveCwd:o.effectiveCwd,envAssignments:u,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:o.functionDefinitions,hasPipelineInput:i,literalShellInput:s,analyzeNested:(d,p)=>{let g=p&&Object.hasOwn(p,"effectiveCwd")?p.effectiveCwd:o.effectiveCwd,y=Sa(d,t+1,{...n,derivedCommandWorkBudget:n.derivedCommandWorkBudget,effectiveCwd:g,envAssignments:p?.envAssignments??u,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:p?.functionDefinitions,worktreeMode:p?.worktreeMode??n.worktreeMode,trace:n.trace?dm(n.trace,n.trace.currentSegmentIndex,!0):void 0});return y?{reason:y.reason,ruleId:y.ruleId,intent:y.intent}:null}});if(m)return{...m,segment:c};let f=sm(e,a,o,u,s,n);if(f)return f;return pa(l,o.shellGitContextState),null}function sm(e,t,n,r,o,i){let s=DR(e,t,n,r??new Map,i);if(s)return s;return mm(e,n,"after-consumer",i.environment.paths),n.literalHeredocFiles.clear(),kR(e,t,n,i.environment.paths),WR(e,n,o,i.environment,i.trace),null}var _R=new Set([">>","<>"]);function mm(e,t,n,r){for(let i of e.redirections){if(!(n==="before-consumer"?AR(i):_R.has(i.operator)))continue;am(i.target,t,r)}if(n!=="before-consumer"||!xe(e.words[0],"tee"))return;let o=fm(e.words.slice(1));if(!o)return;for(let i of o.operands)am(i,t,r)}function AR(e){if(e.operator===">"||e.operator===">|")return!0;return e.operator===">&"&&e.fd===void 0&&e.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(e.target.text)}function am(e,t,n){let r=e?.provenance==="literal"?Hn(e.text,t.effectiveCwd,n):void 0;if(!r)return;t.literalHeredocFiles.delete(r)}function kR(e,t,n,r){if(t)return;let o=e.redirections.find((i)=>i.operator==="<<"||i.operator==="<<-")?.heredoc;if(!o||!mi(o))return;for(let i of TR(e)){let s=Hn(i.text,n.effectiveCwd,r);if(!s||!Bl(s))continue;if(!n.literalHeredocFiles.has(s)&&n.literalHeredocFiles.size>=$l)throw new he;n.literalHeredocFiles.set(s,o.body)}}function TR(e){let t=OR(e.redirections)?.target,n=lm(t)?[t]:[];if(xe(e.words[0],"cat"))return IR(e.words)?n:[];if(!xe(e.words[0],"tee"))return[];let r=fm(e.words.slice(1));if(!r||r.append||r.hasUnsupportedOptions||!r.operands.every(lm))return[];return[...r.operands,...n]}function IR(e){let t=!1;for(let n of e.slice(1)){if(t||n.provenance!=="literal")return!1;if(n.text==="--"){t=!0;continue}if(!/^-u+$/.test(n.text))return!1}return!0}function OR(e){let t=e.findLast((n)=>(n.fd??([">",">|",">>",">&"].includes(n.operator)?1:0))===1);return t?.operator===">"||t?.operator===">|"?t:void 0}function fm(e){let t=[],n=!0,r=!1,o=!1;for(let i of e){if(i.provenance!=="literal")return;if(n&&xe(i,"--")){n=!1;continue}if(n&&!i.quoted&&i.raw===i.text&&/^-[^-]/.test(i.text)){r||=i.text.slice(1).includes("a"),o||=[...i.text.slice(1)].some((s)=>s!=="a"&&s!=="i");continue}if(n&&!i.quoted&&i.raw===i.text&&i.text.startsWith("--")){r||=i.text==="--append",o||=i.text!=="--append"&&i.text!=="--ignore-interrupts";continue}t.push(i)}return{operands:t,append:r,hasUnsupportedOptions:o}}function lm(e){if(!e||e.provenance!=="literal"||e.text.length===0)return!1;if(e.quoted||e.raw!==e.text)return!0;return!e.raw.startsWith("~")&&!/[{}]/.test(e.raw)}function xe(e,t){return e?.text===t&&e.raw===t&&e.provenance==="literal"&&!e.quoted}function mi(e){return e.quotedDelimiter||!/[$`\\]/.test(e.body)}function MR(e){let t=e.redirections.filter((s)=>s.operator==="<<"||s.operator==="<<-");if(t.length===0)return;if(t.length!==1)return Yt;let n=t[0];if(!n?.heredoc)return Yt;if(!mi(n.heredoc))return yR;if(n.fd!==void 0&&n.fd!==0)return Yt;if(e.redirections.some((s)=>s!==n&&["<","<<","<<-","<<<","<&","<>"].includes(s.operator)))return Yt;let r=e.redirections.some((s)=>s!==n&&cm(s.target));if(xe(e.words[0],"cat"))return r?Yt:void 0;if(xe(e.words[0],"tee"))return r||e.words.slice(1).some(cm)?Yt:void 0;let o=e.words[0],i=e.words[1];if(xe(o,"git")&&(xe(i,"apply")||xe(i,"commit")))return;if(xe(o,"gh")&&(xe(i,"pr")||xe(i,"issue"))&&xe(e.words[2],"create"))return;return Yt}function cm(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}function DR(e,t,n,r,o){if(!t)return null;let i=e.redirections.filter((c)=>c.operator==="<<"||c.operator==="<<-"),s=i.flatMap((c)=>c.heredoc?[c.heredoc.body]:[]);if(NR(e,i,n,r,o))return null;let a=LR(e,i,o);if(a!==void 0)return a?{reason:a.reason,segment:e.displayText,ruleId:a.id,intent:a.intent}:null;let l=ba(s.length===i.length?s.join(`
42
+ `):e.source,o);return l?{...l,segment:e.displayText}:null}function LR(e,t,n){let r=t.length===1?t[0]:void 0;if(!r?.heredoc||!mi(r.heredoc)||r.fd!==void 0&&r.fd!==0)return;let o=e.words[0];if(o?.provenance!=="literal"||!ye(o.text))return;if(!e.words.slice(1).every((c)=>c.provenance==="literal"&&c.text.startsWith("-")))return;let s=r.heredoc.body,a=Q(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(n.trace?.recordSegment({type:"interpreter",interpreter:o.text,codeArg:s,paranoidBlocked:a}),a){let c=k(b("interpreter.one-liner-paranoid",un),n.policy);if(c)return c}if(!dn(s,n.scanWork))return null;let l=k(b("interpreter.dangerous-command",Lt),n.policy);if(!l)return null;return n.trace?.recordSegment({type:"dangerous-text",token:s,matched:!0,reason:l.reason}),l}function NR(e,t,n,r,o){let i=t.length===1?t[0]:void 0;if(!i?.heredoc||!mi(i.heredoc)||i.fd!==void 0&&i.fd!==0)return!1;let s=Nt(e.words,o.environment,n.effectiveCwd,r),a=s.words.map(I),l=z(a[0]??"");if((s.envSplitValues?.length??0)>0||!ee.has(l)&&!ee.has(D(l)))return!1;return ke(a)}function WR(e,t,n,r,o){let i=Kd(e,t.effectiveCwd,r,n);if(i===null)o?.recordSegment({type:"cwd-change",segment:e.words.map(I).join(" "),effectiveCwdNowUnknown:!0});if(i!==void 0)t.effectiveCwd=i}function yr(e){return{effectiveCwd:e.effectiveCwd,shellGitContextState:tm(e.shellGitContextState),literalHeredocFiles:new Map(e.literalHeredocFiles),functionDefinitions:new Map(e.functionDefinitions)}}function li(e){let t=[];for(let n of e){if(!t.some((r)=>FR(r,n)))t.push(n);if(t.length>CR)throw new he}return t}function FR(e,t){return e.effectiveCwd===t.effectiveCwd&&Cr(e.literalHeredocFiles,t.literalHeredocFiles)&&Cr(e.functionDefinitions,t.functionDefinitions)&&Cr(e.shellGitContextState.effectiveEnvAssignments,t.shellGitContextState.effectiveEnvAssignments)&&Cr(e.shellGitContextState.shellAssignments,t.shellGitContextState.shellAssignments)}function Cr(e,t){if(e===t)return!0;if(!e||!t||e.size!==t.size)return!1;return[...e].every(([n,r])=>t.get(n)===r&&t.has(n))}function GR(e,t){let n=Ao(e);return n===void 0?void 0:t.get(n)}function zR(e,t){if(!t)return null;return{reason:t.reason,segment:e,ruleId:t.id,intent:t.intent}}function $R(e,t=e.effectiveCwd){let n=t===null;return{environment:e.environment,cwd:n?void 0:t??e.cwd,originalCwd:n?void 0:e.cwd,strict:e.strict,paranoid:e.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,protectedGitMetadata:e.protectedGitMetadata,policy:e.policy}}function ba(e,t){let n=k(mt(e,t.scanWork),t.policy),r=t.trace?.currentSegmentIndex??t.trace?.allocateSegment(),o={type:"dangerous-text",token:e,matched:!!n,reason:n?.reason};if(t.trace?.recordSegment(o,r),!n&&/^(?:cd|pushd)\s/.test(e))t.trace?.recordSegment({type:"cwd-change",segment:e,effectiveCwdNowUnknown:!0},r);return n?{reason:n.reason,segment:e,ruleId:n.id,intent:n.intent}:null}function um(e,t){let n={type:"strict-unparseable",rawCommand:e,reason:St};if(t.trace?.currentSegmentIndex===void 0)t.trace?.recordGlobal(n);else t.trace.recordSegment(n)}var ie={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"}},fi=["standard","strict","paranoid"];function BR(e){return{failClosed:e==="strict"||e==="paranoid",paranoidRm:e==="paranoid",paranoidInterpreters:e==="paranoid"}}function UR(e,t){if(!t)return e;return fi.indexOf(t)>fi.indexOf(e)?t:e}function HR(){let e=Ra(ie.level);if(e===void 0||e==="")return;if(fi.includes(e))return e;console.error(`CC Safety Net: ignored invalid ${ie.level.name}=${JSON.stringify(e.slice(0,40))}. Use ${fi.join(", ")}.`);return}function jR(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function XI(){return jR(Ra(ie.auditScope))==="all"}function va(e){if(e.failClosed&&e.paranoidRm&&e.paranoidInterpreters)return"paranoid";if(e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"strict";if(!e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"standard";return"custom"}function pi(e={}){let t=e.safety?.level??"standard",n=HR(),r=UR(t,n),o=BR(r),i={failClosed:r===t?"preset":"environment",paranoidRm:r===t?"preset":"environment",paranoidInterpreters:r===t?"preset":"environment"},s={failClosed:[`policy safety.level=${t}`],paranoidRm:[`policy safety.level=${t}`],paranoidInterpreters:[`policy safety.level=${t}`]};if(r!==t)s.failClosed.push(`env ${ie.level.name}=${n}`),s.paranoidRm.push(`env ${ie.level.name}=${n}`),s.paranoidInterpreters.push(`env ${ie.level.name}=${n}`);if(e.safety?.overrides?.failClosed!==void 0)o.failClosed=e.safety.overrides.failClosed,i.failClosed="capability_override",s.failClosed.push("policy safety.overrides.fail_closed");if(e.safety?.overrides?.paranoidRm!==void 0)o.paranoidRm=e.safety.overrides.paranoidRm,i.paranoidRm="capability_override",s.paranoidRm.push("policy safety.overrides.paranoid_rm");if(e.safety?.overrides?.paranoidInterpreters!==void 0)o.paranoidInterpreters=e.safety.overrides.paranoidInterpreters,i.paranoidInterpreters="capability_override",s.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(br(ie.strict))o.failClosed=!0,i.failClosed="environment",s.failClosed.push(`env ${ie.strict.name}`);if(br(ie.paranoid))o.paranoidRm=!0,o.paranoidInterpreters=!0,i.paranoidRm="environment",i.paranoidInterpreters="environment",s.paranoidRm.push(`env ${ie.paranoid.name}`),s.paranoidInterpreters.push(`env ${ie.paranoid.name}`);if(br(ie.paranoidRm))o.paranoidRm=!0,i.paranoidRm="environment",s.paranoidRm.push(`env ${ie.paranoidRm.name}`);if(br(ie.paranoidInterpreters))o.paranoidInterpreters=!0,i.paranoidInterpreters="environment",s.paranoidInterpreters.push(`env ${ie.paranoidInterpreters.name}`);let a=!!e.worktreeMode||br(ie.worktree);return{strict:o.failClosed,paranoidRm:o.paranoidRm,paranoidInterpreters:o.paranoidInterpreters,worktreeMode:a,effectiveLevel:va(o),capabilities:{fail_closed:{enabled:o.failClosed,source:i.failClosed,sources:s.failClosed},paranoid_rm:{enabled:o.paranoidRm,source:i.paranoidRm,sources:s.paranoidRm},paranoid_interpreters:{enabled:o.paranoidInterpreters,source:i.paranoidInterpreters,sources:s.paranoidInterpreters}}}}function br(e){let t=typeof e==="string"?Sr(e):Ra(e);return t==="1"||t?.toLowerCase()==="true"}function Sr(e){return Object.hasOwn(process.env,e)?process.env[e]:void 0}function Ra(e){let t=Sr(e.name);if(t!==void 0)return t;if(e.legacyName)return Sr(e.legacyName);return}function JI(e){return Sr(e.name)!==void 0||!!e.legacyName&&Sr(e.legacyName)!==void 0}function pm(e){let t=e.effectiveCapabilities,n=e.strict??t.fail_closed.enabled,r=e.paranoidRm??t.paranoid_rm.enabled,o=e.paranoidInterpreters??t.paranoid_interpreters.enabled,i={fail_closed:xa(t.fail_closed,e.strict,"strict"),paranoid_rm:xa(t.paranoid_rm,e.paranoidRm,"paranoidRm"),paranoid_interpreters:xa(t.paranoid_interpreters,e.paranoidInterpreters,"paranoidInterpreters")};return{policy:Ml(e.policySnapshot.policy,i),effectiveCapabilities:i,effectiveLevel:va({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}function xa(e,t,n){if(t===void 0||t===e.enabled)return e;return{enabled:t,source:"capability_override",sources:[...e.sources,`analysis options.${n}`]}}function iO(e,t){return Ea(e,t)}function Ea(e,t,n,r){let o=Sa(e,0,{...t,...pm(t),factStore:r},n);if(!o)return null;return{kind:"deny",reason:o.reason,intent:o.intent??"manual_only",...o.ruleId?{ruleId:o.ruleId}:{},evidence:[{kind:"command",command:e,segment:o.segment}]}}import{basename as Yx,dirname as Va}from"node:path";import{chmodSync as Gx,existsSync as Ha,mkdirSync as zx,readFileSync as ja}from"node:fs";import{dirname as mf,join as $x}from"node:path";import{createRequire as ex}from"node:module";var gm=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var hm=30,wa=1,Pa=365;function ym(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var vr=64,bm="Rule config exceeds CC Safety Net's safe source limit.";var Cm=Object.freeze({maxSources:64,concurrency:4,maxRequests:131,maxResponseBytes:67108864});function gi(e={}){return{requests:0,responseBytes:0,maxRequests:e.maxRequests??Cm.maxRequests,maxResponseBytes:e.maxResponseBytes??Cm.maxResponseBytes}}function hi(e){return{controller:new AbortController,budget:gi(),resolveUrl:e}}function Sm(e){if(e.requests>=e.maxRequests)throw Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");e.requests++}function vm(e,t){if(t>e.maxResponseBytes-e.responseBytes)throw e.responseBytes+=t,Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");e.responseBytes+=t}var Ie=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,yi="rulebook.json",Ci=".cc-safety-net/rules";var Rm=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,VR=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,qR=/^[A-Za-z0-9._-]+$/,KR=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),YR="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),_a=new RegExp(`^${KR}/(${Ie.source.slice(1,-1)})/${YR}$`);function xm(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function Rr(e){if(Pn(e))try{return wn(e),null}catch(t){return t instanceof Error?t.message:String(t)}return Ie.test(e)?null:`Local rulebook sources must be bare names matching ${Ie}: ${e}`}function wn(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(Rm);if(!t?.[1]||!t[2]||!t[3])throw Error(`Invalid GitHub rulebook source: ${e}`);let[n,r,...o]=t[3].split("/");if(!n||!qR.test(n))throw Error(`GitHub rulebook refs must be a single path segment: ${e}`);if(!r||o.length>0||!Ie.test(r))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);return{owner:t[1],repo:t[2],ref:n,path:xm(r),name:r}}function Em(e){return VR.test(e)}function Pn(e){return Rm.test(e)}function Aa(e){if(!Ie.test(e))throw Error(`Local rulebook sources must be bare names matching ${Ie}: ${e}`)}var ka=[{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"}],bi={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},ZR=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],XR=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Ta=[{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"]},...XR.flatMap((e)=>ZR.map((t)=>({id:["secret.home",e.idSlug,t.slice(1)].join("."),category:"Home path",label:[e.label,t].join(""),description:["Blocks home ",e.label,t," credential backup files."].join(""),suffixParts:[...e.directoryParts,[e.basename,t].join("")]}))),{id:"secret.home.gh-hosts",category:"Home path",label:"~/.config/gh/hosts.yml",description:"Blocks GitHub CLI host credential files.",suffixParts:[".config","gh","hosts.yml"]}];var Si=[{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"]}],wm=[{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"}],JR=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Ia=wm.map((e)=>({id:`secret.variant.${e.slug}.separator`,category:"Variant",label:`${e.label}-* / ${e.label}_*`,description:`Blocks ${e.label} variants with dash or underscore suffixes.`,prefix:e.prefix})),Oa=wm.flatMap((e)=>JR.map((t)=>({id:`secret.variant.${e.slug}.${t.slice(1)}`,category:"Variant",label:`${e.label}${t}`,description:`Blocks ${e.label}${t} private credential variants.`,prefix:e.prefix,suffix:t}))),xr={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)$/},Ma=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((e)=>({id:`secret.ext.${e}`,category:"Extension",label:`.${e}`,description:`Blocks files with the .${e} extension.`,extension:e})),Da=[{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?$/}],Pm=[...ka,bi,...Ta,...Ia,...Oa,xr,...Ma,...Da,...Si].map((e)=>({id:e.id,category:e.category,label:e.label,...e.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in e?{paths:e.paths}:{description:e.description}})),_m=new Set(Si.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),QR=Pm.map((e)=>e.id),vi=new Set(QR);var tx=ex(import.meta.url),Am,nx=Array(vr+1).fill("over-limit"),km=/^[^/]+\/[^/]+$/,rx=/^sha256:[a-f0-9]{64}$/,Ri=`must be an integer between ${wa} and ${Pa}`,ox=["version","rules","overrides","transparent_wrappers"],ix=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Tm(e){if(!Oe(e)||!Array.isArray(e.rules)||e.rules.length<=vr)return e;return{$schema:e.$schema,version:e.version,rules:nx,overrides:e.overrides,transparent_wrappers:e.transparent_wrappers}}function sx(){let e=tx("../vendor/zod.cjs"),t=(S)=>{let C=e.superRefine(S);return C._zod.def.when=()=>!0,C},n=e.enum(gm),r=e.union([e.literal("off"),e.looseObject({reason:e.string({error:"required non-empty string"}).min(1,"required non-empty string").max(cn,`must be at most ${cn} characters`).describe("Replacement block reason"),intent:n.optional()})],{error:'must be "off" or an object'}).describe("Disable a rule or replace its block reason and intent."),o=e.string({error:"must be a rulebook source string"}).min(1,"must be a non-empty rulebook source string"),i=e.string({error:"must be a command string"}).regex(Dt,"must match command pattern").describe("Command name such as 'git', 'docker', or 'rtk'."),s=e.looseObject({$schema:e.unknown().optional().describe("JSON Schema reference for IDE support"),version:e.literal(1).describe("Schema version (must be 1)"),rules:e.array(o,{error:"must be an array of rulebook source strings"}).max(vr,bm).default([]).describe("Rulebook source strings such as project-rules or owner/repo#main/team-rules"),overrides:e.record(e.string().meta({pattern:km.source}),r).default({}).describe("Rule overrides by id"),transparent_wrappers:e.array(i,{error:"must be an array of command strings"}).default([]).describe("Commands that transparently execute a visible protected child command")}),a=(S,C)=>{if(!Oe(S))return;if(Array.isArray(S.rules)&&S.rules.length<=vr){let E=new Set;S.rules.forEach((T,O)=>{if(typeof T!=="string"||T==="")return;if(T.trim()===""){C.addIssue({code:"custom",message:"must be a non-empty rulebook source string",path:["rules",O]});return}let M=Rr(T);if(M){C.addIssue({code:"custom",message:M,path:["rules",O]});return}if(E.has(T)){C.addIssue({code:"custom",message:`duplicate rulebook source "${T}"`,path:["rules",O]});return}E.add(T)})}if(Oe(S.overrides))for(let E of Object.keys(S.overrides)){if(km.test(E))continue;C.addIssue({code:"custom",message:"must use <rulebook-name>/<rule-name>",path:["overrides",E]})}if(!Array.isArray(S.transparent_wrappers))return;let _=new Set;S.transparent_wrappers.forEach((E,T)=>{if(typeof E!=="string"||!Dt.test(E))return;if(_.has(E)){C.addIssue({code:"custom",message:`duplicate command "${E}"`,path:["transparent_wrappers",T]});return}if(ku(E)){C.addIssue({code:"custom",message:`reserved command "${E}" cannot be a wrapper`,path:["transparent_wrappers",T]});return}_.add(E)})},l=e.preprocess(Tm,s.check(e.superRefine(a))),c=e.preprocess(Tm,s.check(t(a))),u=e.strictObject({fail_closed:e.boolean().optional(),paranoid_rm:e.boolean().optional(),paranoid_interpreters:e.boolean().optional()}),m=(S,C)=>e.intersection(e.record(e.string().refine((_)=>S.has(_),{error:(_)=>`unknown ${C} rule id "${String(_.input)}"`}),e.unknown()),e.record(e.string(),e.enum(["on","off"]))),f=(S)=>e.array(e.string({error:"must be a non-empty path string"}),{error:"must be an array of paths"}).check(t((C,_)=>{if(!Array.isArray(C))return;let E=It();C.forEach((T,O)=>{if(typeof T!=="string")return;let M=S(T,E);if(M)_.addIssue({code:"custom",message:M,path:[O]})})})),d=e.strictObject({version:e.literal(1),safety:e.strictObject({level:e.enum(["standard","strict","paranoid"]).optional(),overrides:u.optional()}).optional(),workflow:e.strictObject({worktree_mode:e.boolean().optional()}).optional(),destructive_command_protection:e.strictObject({enabled:e.boolean().optional(),overrides:m(Kr,"destructive command").optional(),allow_paths:f(zo).optional()}).optional(),secret_protection:e.strictObject({enabled:e.boolean().optional(),overrides:m(vi,"secret protection").optional(),deny_paths:f($o).optional(),allow_paths:f(Bo).optional()}).optional(),audit:e.strictObject({retention_days:e.number({error:Ri}).int(Ri).min(wa,Ri).max(Pa,Ri).optional().describe("Days of audit log history to keep before the sweep deletes it")}).optional()}),p=(S)=>{let C=(O,M)=>S==="legacy"?O:M,_=C("must match pattern (letters, numbers, hyphens, underscores)","must match command pattern"),E=`required non-empty string up to ${cn} characters`,T=e.looseObject({name:e.string({error:"required string"}).regex(Ie,C("must match pattern (letters, numbers, hyphens, underscores; max 64 chars)","must match rule name pattern")),command:e.string({error:C("required string","required string matching command pattern")}).regex(Dt,C(_,"required string matching command pattern")),subcommand:e.string({error:C("must be a string if provided","must match command pattern")}).regex(Dt,_).optional(),block_args:e.array(e.string({error:C("must be a string","must be a non-empty string")}).refine((O)=>O!=="",{error:C("must not be empty","must be a non-empty string")}),{error:C("required array","required non-empty array")}).refine((O)=>O.length>0,{error:C("must have at least one element","required non-empty array")}),reason:e.string({error:C("required string",E)}).refine((O)=>O!=="",{error:C("must not be empty",E)}).refine((O)=>O.length<=cn,{error:C(`must be at most ${cn} characters`,E)}),intent:n.optional()},{error:"must be an object"});return e.array(T,{error:C("must be an array","required array")}).check(t((O,M)=>{if(!Array.isArray(O))return;let F=new Set;O.forEach((oe,Ee)=>{let w=Oe(oe)?oe.name:void 0;if(typeof w!=="string")return;if(F.has(w.toLowerCase())){M.addIssue({code:"custom",message:`duplicate rule name "${w}"`,path:[Ee,"name"]});return}F.add(w.toLowerCase())})}))},g=e.looseObject({version:e.literal(1),rules:p("legacy").optional()}),y="required string matching rule name pattern",h=e.looseObject({command:e.string({error:"required non-empty string"}).refine((S)=>S.trim()!=="",{error:"required non-empty string"}),expect:e.enum(["blocked","allowed"]),rule:e.string({error:"must be a string if provided"}).optional()},{error:"must be an object"}).check(t((S,C)=>{if(!Oe(S))return;if(S.expect!=="blocked"||typeof S.rule==="string")return;C.addIssue({code:"custom",message:"required string for blocked fixtures",path:["rule"]})})),R=e.looseObject({name:e.string({error:"required string matching rule name pattern"}).regex(Ie,"required string matching rule name pattern"),version:e.string({error:"required non-empty string"}).refine((S)=>S!=="",{error:"required non-empty string"}),allowed_commands:e.array(e.string({error:"must match command pattern"}).regex(Dt,"must match command pattern"),{error:"required array"}).check(t((S,C)=>{if(!Array.isArray(S))return;let _=new Set;S.forEach((E,T)=>{if(typeof E!=="string"||!Dt.test(E))return;if(_.has(E)){C.addIssue({code:"custom",message:`duplicate command "${E}"`,path:[T]});return}_.add(E)})})),rules:p("rulebook"),tests:e.array(h,{error:"must be an array if provided"}).optional()}).check(t((S,C)=>{if(!Oe(S))return;let _=new Set(La(S));if(Array.isArray(S.tests)){let T=new Set(S.tests.flatMap((O)=>Oe(O)&&O.expect==="blocked"&&typeof O.rule==="string"?[O.rule]:[]));for(let O of T){if(_.has(O))continue;C.addIssue({code:"custom",message:`blocked fixture references unknown rule "${O}"`,path:["tests"]})}}if(!Array.isArray(S.allowed_commands)||!Array.isArray(S.rules))return;let E=new Set(S.allowed_commands.filter((T)=>typeof T==="string"));S.rules.forEach((T,O)=>{let M=Oe(T)?T.command:void 0;if(typeof M!=="string"||E.has(M))return;C.addIssue({code:"custom",message:`"${M}" must be listed in allowed_commands`,path:["rules",O,"command"]})})})),x=e.string({error:"required string"}).refine((S)=>S.trim()!=="",{error:"required string"}),A=e.looseObject({spec:x,name:x,version:x,digest:e.string({error:"required sha256 digest"}).regex(rx,"required sha256 digest")},{error:"must be an object"}),P=e.looseObject({rulebooks:e.array(e.intersection(A,e.discriminatedUnion("kind",[e.object({kind:e.literal("local-directory"),path:x}),e.object({kind:e.literal("github"),owner:x,repo:x,ref:x,commit:x,path:x,display_ref:e.unknown().optional()})],{error:(S)=>{if(!Oe(S.input))return"must be an object";let C=S.input.kind;return typeof C==="string"?`unknown kind "${C}"`:"required string"}})))});return{RulesConfigSchema:l,RulesConfigDiagnosticSchema:c,RuleOverrideSchema:r,UserPolicySchema:d,LegacyConfigSchema:g,RulebookSchema:R,RulesLockfileSchema:P}}function _n(){return Am??=sx(),Am}function Im(){return _n().RulesConfigSchema}function ax(){return _n().UserPolicySchema}function xO(){return _n().LegacyConfigSchema}function Om(){return _n().RulebookSchema}function Mm(){return _n().RulesLockfileSchema}function La(e){let t=Oe(e)?e.rules:void 0;return(Array.isArray(t)?t:[]).flatMap((n)=>{let r=Oe(n)?n.name:void 0;return typeof r==="string"?[r]:[]})}function Dm(e){let t=_n().RulesConfigDiagnosticSchema.safeParse(e);if(t.success)return{errors:[],sources:new Set(t.data.rules)};return{errors:An(Nm(t.error.issues,ox)),sources:dx(e,t.error.issues)}}function Er(e){let t=ax().safeParse(e);if(t.success)return[];return An(Nm(t.error.issues,ix)," ")}function An(e,t=": ",n=" "){return[...new Set(e.flatMap((r)=>Lm(r,t,n,[])))]}function Lm(e,t,n,r){let o=[...r,...e.path],i=ux(o);if(e.code==="unrecognized_keys")return e.keys.map((s)=>`${i?`${i}.`:""}unknown field "${s}"`);if(e.code==="invalid_key")return e.issues.map((s)=>s.message);if(e.code==="invalid_union"){let s=e.errors.flat().filter((a)=>a.path.length>0);if(s.length>0)return s.flatMap((a)=>Lm(a,t,n,o))}if(o.length===0)return[e.code==="invalid_type"?"Config must be an object":e.message];if(o.length===1&&(e.code==="too_big"||e.code==="too_small")&&e.origin==="array")return[e.message];return[`${i}${o.length===1?n:t}${lx(e)}`]}function lx(e){if(e.code==="invalid_value")return`must be ${cx(e.values)}`;if(e.code!=="invalid_type"||!e.message.startsWith("Invalid input:"))return e.message;if(e.expected==="object"||e.expected==="record")return"must be an object if provided";return e.expected==="boolean"?"must be a boolean":e.message}function cx(e){if(e.length>3)return`one of ${e.join(", ")}`;let t=e.map((n)=>typeof n==="string"?`"${n}"`:String(n));if(t.length<2)return`${t[0]}`;return`${t.slice(0,-1).join(", ")}${t.length>2?",":""} or ${t.at(-1)}`}function ux(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function Nm(e,t){let n=e.map((i)=>i.path[1]),r=[...new Set(n.filter((i)=>typeof i==="string"))],o=(i,s)=>[i.path.length===0?-1:t.indexOf(String(i.path[0])),typeof s==="number"?s:r.indexOf(String(s)),i.code==="custom"?0:1];return e.map((i,s)=>({issue:i,rank:o(i,n[s])})).sort((i,s)=>i.rank[0]-s.rank[0]||i.rank[1]-s.rank[1]||i.rank[2]-s.rank[2]).map((i)=>i.issue)}function dx(e,t){let n=Oe(e)?e.rules:void 0;if(!Array.isArray(n))return new Set;if(t.some((o)=>o.path.length===1&&o.path[0]==="rules"))return new Set;let r=new Set(t.filter((o)=>o.path[0]==="rules"&&typeof o.path[1]==="number").map((o)=>o.path[1]));return new Set(n.filter((o,i)=>typeof o==="string"&&!r.has(i)))}function Oe(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}import{randomBytes as mx}from"node:crypto";import{closeSync as Fa,constants as wr,fstatSync as Na,fsyncSync as fx,lstatSync as kt,mkdirSync as Wm,openSync as Fm,readdirSync as Ga,readFileSync as px,realpathSync as Zt,renameSync as gx,rmdirSync as Gm,statSync as Wa,unlinkSync as za,writeFileSync as hx}from"node:fs";import{isAbsolute as zm,join as kn,normalize as yx,parse as $m,relative as $a,resolve as Ba,sep as _r}from"node:path";var Cx=Symbol("PolicyFilesystemScope"),bx=Symbol("PolicyFilesystemTarget"),Bm=wr.O_NOFOLLOW??0;class L extends Error{constructor(e){super(`Unable to access ${e} filesystem safely.`);this.name="PolicyFilesystemError"}}function Me(e,t){return{[Cx]:!0,root:Ba(e),label:t}}function Ar(e,t){let n=yx(t);if(t===""||zm(t)||n===".."||n.startsWith(`..${_r}`))throw new L(e.label);return{[bx]:!0,scope:e,relativePath:n,path:kn(e.root,n)}}function se(e,t){let n=$a(e.root,Ba(t));return Ar(e,n)}function xi(e,t="rules policy"){let n=Ba(e),r=$m(n).dir;return Ar(Me(r,t),$a(r,n))}function gt(e){try{if(!re(e,!1).exists)return null;let n=Fm(e.path,wr.O_RDONLY|Bm);try{let r=Na(n);if(!r.isFile())throw new L(e.scope.label);let o=px(n,"utf-8"),i=kt(e.path);if(!i.isFile()||i.isSymbolicLink()||r.dev!==i.dev||r.ino!==i.ino)throw new L(e.scope.label);return re(e,!1),o}finally{Fa(n)}}catch(t){ht(e.scope.label,t)}}function Um(e,t,n=384,r){let o=`${e.path}.${mx(8).toString("hex")}.tmp`,i=null;try{Rx(e),re(e,!0),i=Fm(o,wr.O_CREAT|wr.O_EXCL|wr.O_WRONLY|Bm,n);let s=Na(i);if(!s.isFile())throw new L(e.scope.label);hx(i,t,"utf-8"),fx(i);let a=Na(i);if(!a.isFile()||a.dev!==s.dev||a.ino!==s.ino)throw new L(e.scope.label);Fa(i),i=null,re(e,!0),Ex(e,o,a.dev,a.ino),gx(o,e.path),r?.(e.path),re(e,!1)}catch(s){if(i!==null)Px(i);_x(o),ht(e.scope.label,s)}}function Hm(e,t){if(e.path===t.path)return!0;try{if(!re(e,!1).exists||!re(t,!1).exists)return!1;return Zt(e.path)===Zt(t.path)}catch(n){if(n instanceof L)throw n;throw new L(e.scope.label)}}function Sx(e){try{if(!re(e,!1,"directory").exists)return null;let n=Ga(e.path);return re(e,!1,"directory"),n}catch(t){ht(e.scope.label,t)}}function AO(e){let t=Sx(e);if(!t)return null;try{let n=t.map((r)=>{let o=Ar(e.scope,kn(e.relativePath,r)),i=kt(o.path);if(i.isSymbolicLink()||!i.isFile()&&!i.isDirectory())throw new L(e.scope.label);return Ei(Km(e.scope),Zt(o.path),e.scope.label),{name:r,kind:i.isDirectory()?"directory":"file"}});return re(e,!1,"directory"),n}catch(n){ht(e.scope.label,n)}}function kO(e){try{if(!re(e,!0).exists)return;za(e.path),re(e,!0)}catch(t){ht(e.scope.label,t)}}function TO(e){try{qm(e,e.relativePath.split(_r))}catch(t){ht(e.scope.label,t)}}function IO(e){try{if(!vx(e))return;Vm(e),re(e,!0,"directory")}catch(t){ht(e.scope.label,t)}}function OO(e){try{if(!re(e,!0,"directory").exists)return;Gm(e.path),re(e,!0,"directory")}catch(t){ht(e.scope.label,t)}}function vx(e){try{if(!re(e,!0,"directory").exists)return!1;return jm(e),!0}catch(t){ht(e.scope.label,t)}}function re(e,t,n="file"){let r=Ua(e.scope);if(!r)return{exists:!1};let o=e.relativePath.split(_r);for(let i of o.keys()){let s=kn(e.scope.root,...o.slice(0,i+1)),a=Pr(s);if(!a){if(i===o.length-1&&t)return{exists:!1};return{exists:!1}}if(a.isSymbolicLink())throw new L(e.scope.label);if(i<o.length-1&&!a.isDirectory())throw new L(e.scope.label);if(i===o.length-1&&(n==="file"?!a.isFile():!a.isDirectory()))throw new L(e.scope.label);Ei(r,Zt(s),e.scope.label)}return{exists:!0}}function jm(e){for(let t of Ga(e.path)){let n=Ar(e.scope,kn(e.relativePath,t)),r=kt(n.path);if(r.isSymbolicLink()||!r.isDirectory()&&!r.isFile())throw new L(e.scope.label);if(r.isDirectory())jm(n)}re(e,!1,"directory")}function Vm(e){for(let t of Ga(e.path)){let n=Ar(e.scope,kn(e.relativePath,t)),r=kt(n.path);if(r.isSymbolicLink())throw new L(e.scope.label);if(r.isDirectory()){Vm(n);continue}if(!r.isFile())throw new L(e.scope.label);za(n.path)}Gm(e.path)}function Rx(e){qm(e,e.relativePath.split(_r).slice(0,-1))}function qm(e,t){xx(e.scope);let n=Km(e.scope);for(let r of t.keys()){let o=kn(e.scope.root,...t.slice(0,r+1));if(!Pr(o))Wm(o,{mode:448});let s=kt(o);if(!s.isDirectory()||s.isSymbolicLink())throw new L(e.scope.label);Ei(n,Zt(o),e.scope.label)}}function xx(e){if(Pr(e.root)){if(!Wa(e.root).isDirectory())throw new L(e.label);return}let t=[],n=e.root;while(!Pr(n)){t.unshift(n);let r=$m(n).dir;if(r===n)throw new L(e.label);n=r}if(!Wa(n).isDirectory())throw new L(e.label);for(let r of t){Wm(r,{mode:448});let o=kt(r);if(!o.isDirectory()||o.isSymbolicLink())throw new L(e.label)}}function Ua(e){if(!Pr(e.root))return null;if(!Wa(e.root).isDirectory())throw new L(e.label);return Zt(e.root)}function Km(e){let t=Ua(e);if(!t)throw new L(e.label);return t}function Ex(e,t,n,r){let o=kt(t);if(!o.isFile()||o.isSymbolicLink()||o.dev!==n||o.ino!==r)throw new L(e.scope.label);let i=Ua(e.scope);if(!i)throw new L(e.scope.label);Ei(i,Zt(t),e.scope.label)}function Ei(e,t,n){let r=$a(e,t);if(r===".."||r.startsWith(`..${_r}`)||zm(r))throw new L(n)}function Pr(e){try{return kt(e)}catch(t){if(wx(t)&&t.code==="ENOENT")return null;throw t}}function ht(e,t){if(t instanceof L)throw t;throw new L(e)}function wx(e){return e instanceof Error&&"code"in e}function Px(e){try{Fa(e)}catch{}}function _x(e){try{za(e)}catch{}}var Ym={version:1,rules:[],overrides:{},transparent_wrappers:[]};function Ax(e){return Dm(e)}function Tn(e){try{let t=gt(Zm(e));if(t===null)return{config:null,errors:[]};if(!t.trim())return{config:null,errors:["Config file is empty"]};let n=JSON.parse(t),r=Ax(n);if(r.errors.length>0)return{config:null,errors:r.errors};let o=Im().parse(n);return{config:{version:1,rules:o.rules??[],overrides:o.overrides??{},transparent_wrappers:o.transparent_wrappers??[]},errors:[]}}catch(t){if(t instanceof L)return{config:null,errors:[t.message]};let n=t instanceof Error?t.message:String(t);return{config:null,errors:[t instanceof SyntaxError?"Invalid JSON":n]}}}function FO(e){let t=Tn(e);if(t.errors.length>0)return{ok:!1,result:{ok:!1,errors:t.errors,warnings:[],entries:[]}};return{ok:!0,config:t.config??Ym}}function GO(e,t=[]){wi(e,{version:1,rules:t,overrides:{},transparent_wrappers:[]})}function zO(e,t="project-rules"){wi(e,{rulebook_version:1,name:t,version:"1.0.0",description:t==="project-rules"?"Project-specific CC Safety Net rules.":"User-specific CC Safety Net rules.",author:t==="project-rules"?"project":"user",allowed_commands:["docker"],rules:[{name:"block-docker-system-prune",command:"docker",subcommand:"system",block_args:["prune"],reason:"Use targeted cleanup instead."}],tests:[{command:"docker system prune",expect:"blocked",rule:"block-docker-system-prune"}]})}function wi(e,t,n,r){Um(Zm(e),`${JSON.stringify(t,null,2)}
43
+ `,n,r)}function Zm(e){return typeof e==="string"?xi(e):e}import{homedir as kx}from"node:os";import{dirname as ot,isAbsolute as Tx,join as je,relative as Ix,resolve as it,sep as Ox}from"node:path";var Jm="rule.json",Qm="policy.json",ef="rule.lock",Mx="config.json",tf=".cc-safety-net",Dx="rules",Xm="cache",Lx="CC_SAFETY_NET_HOME",Ve="`cc-safety-net rule sync`";function Nx(e){return it(e??process.cwd(),Ci)}function nf(e){return je(Nx(e),Jm)}function Jt(e){return e?.userConfigDir??(e?.userConfigPath?ot(e.userConfigPath):je(Wx(),Dx))}function Wx(){let e=process.env[Lx];return e?it(pe(e)):je(kx(),tf)}function rf(e){return je(Jt(e),Jm)}function KO(e){return je(Jt(e),ef)}function Xt(e){return je(ot(e),ef)}function YO(e={}){return je(ot(Jt(e)),Mx)}function ZO(e={}){return it(e.cwd??process.cwd(),".safety-net.json")}function of(e){let t=e.userConfigPath??rf(e),n=e.projectConfigPath??nf(e.cwd),r=sf(t,e),o=af(n,e);return{userConfigPath:t,projectConfigPath:n,userLockPath:Xt(t),projectLockPath:Xt(n),userScope:r,projectScope:o,userConfigTarget:se(r,t),projectConfigTarget:se(o,n),userLockTarget:se(r,Xt(t)),projectLockTarget:se(o,Xt(n))}}function XO(e){let t=e.global?e.userConfigPath??rf(e):e.projectConfigPath??nf(e.cwd),n=e.global?sf(t,e):af(t,e),r=Xt(t);return{configDir:ot(t),configPath:t,lockPath:r,filesystemScope:n,configTarget:se(n,t),lockTarget:se(n,r)}}function sf(e,t){let n=t.userConfigPath?ot(ot(it(t.userConfigPath))):ot(it(t.userConfigDir??Jt(t)));return Me(n,"user policy")}function af(e,t){let n=it(t.cwd??process.cwd()),r=it(e),o=Ix(n,r);if(o!==".."&&!o.startsWith(`..${Ox}`)&&!Tx(o))return Me(n,"project policy");return Me(ot(ot(r)),"project policy")}function lf(e){if(e.kind==="github"&&e.display_ref)return`${e.owner}/${e.repo}#${e.display_ref}/${e.name}`;return e.spec}function Pi(e,t){let n=e.digest.startsWith("sha256:")?e.digest.slice(7):e.digest;return je(cf(t),"rulebooks",`${Fx(e)}--${n.slice(0,12)}`,yi)}function JO(e){return je(cf(e),"rulebooks")}function _i(e,t){let n=t;return{cacheConfigDir:e,cwd:t.cwd,global:n.global}}function Fx(e){return(e.kind==="github"&&e.display_ref?`${e.owner}/${e.repo}#${e.display_ref}/${e.name}`:e.spec).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"rulebook"}function cf(e){let t=e?.cacheConfigDir??Jt(e),n=e;if(n&&!n.global&&n.cwd&&it(t)===it(n.cwd))return je(it(n.cwd),tf,Xm);return je(ot(t),Xm)}var Bx=new Set(["standard","strict","paranoid"]),ki={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:hm}};function On(e){return $x(mf(Jt(e)),Qm)}function mM(e={}){let t=On(e);if(!Ha(t))return{path:t,exists:!1,raw:"",policy:kr(),errors:[]};let n=ja(t,"utf-8");if(!n.trim())return{path:t,exists:!0,raw:n,policy:kr(),errors:["Config file is empty"]};try{let r=JSON.parse(n),o=Er(r);return{path:t,exists:!0,raw:n,policy:In(r),errors:o}}catch(r){return{path:t,exists:!0,raw:n,policy:kr(),errors:[`Invalid JSON: ${r instanceof Error?r.message:String(r)}`]}}}function Ai(e,t={}){let n=On(t),r=Er(e),o=r.length>0?kr():In(e);if(r.length>0)return{path:n,policy:o,errors:r};return zx(mf(n),{recursive:!0,mode:448}),wi(n,o,384),Gx(n,384),{path:n,policy:o,errors:[]}}function fM(e){let t=Er(e);if(t.length>0)return{errors:t};return{preview:Ux(In(e)),errors:[]}}function Ux(e){let t=pi({safety:gf(e.safety)}),n=qi({destructiveCommandProtectionEnabled:e.destructive_command_protection.enabled,destructiveCommandRuleOverrides:e.destructive_command_protection.overrides},t.capabilities),r=Object.values(n),o=r.filter((i)=>i.source!=="catastrophic");return{selectedPreset:e.safety.level,effectiveLevel:t.effectiveLevel,capabilities:t.capabilities,rules:n,counts:{enabled:o.filter((i)=>i.enabled).length,disabled:o.filter((i)=>!i.enabled).length,effectiveCustomizations:r.filter((i)=>i.changesInherited).length}}}function pM(e={}){let t=On(e);if(!Ha(t))return Ai(ki,e);let n=ja(t,"utf-8");if(!n.trim())return Ai(ki,e);try{return Ai(In(JSON.parse(n)),e)}catch{return Ai(ki,e)}}function ff(e={}){let t=qx(On(e));return{...t.policy,errors:t.errors,...t.fallback?{fallback:t.fallback}:{}}}function In(e){if(!st(e))return kr();let t=st(e.safety)?e.safety:{},n=st(t.overrides)?t.overrides:{},r=st(e.workflow)?e.workflow:{},o=st(e.destructive_command_protection)?e.destructive_command_protection:{},i=st(e.secret_protection)?e.secret_protection:{};return{version:1,safety:{level:Bx.has(t.level)?t.level:"standard",overrides:{...typeof n.fail_closed==="boolean"?{fail_closed:n.fail_closed}:{},...typeof n.paranoid_rm==="boolean"?{paranoid_rm:n.paranoid_rm}:{},...typeof n.paranoid_interpreters==="boolean"?{paranoid_interpreters:n.paranoid_interpreters}:{}}},workflow:{worktree_mode:typeof r.worktree_mode==="boolean"?r.worktree_mode:!1},destructive_command_protection:{enabled:typeof o.enabled==="boolean"?o.enabled:!0,overrides:uf(o.overrides,Kr),allow_paths:jx(o.allow_paths)},secret_protection:{enabled:typeof i.enabled==="boolean"?i.enabled:!0,overrides:uf(i.overrides,vi),deny_paths:Hx(i.deny_paths),allow_paths:Vx(i.allow_paths)},audit:{retention_days:ym(st(e.audit)?e.audit.retention_days:void 0)}}}function uf(e,t){if(!st(e))return{};return Object.fromEntries(Object.entries(e).flatMap(([n,r])=>t.has(n)&&(r==="on"||r==="off")?[[n,r]]:[]))}function Hx(e){if(!Array.isArray(e))return[];let t=It();return e.filter((n)=>$o(n,t)===null)}function jx(e){if(!Array.isArray(e))return[];let t=It();return e.filter((n)=>zo(n,t)===null)}function Vx(e){if(!Array.isArray(e))return[];let t=It();return e.filter((n)=>Bo(n,t)===null)}function st(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function kr(){return structuredClone(ki)}function qx(e){let t=Kx();if(!Ha(e)){let n=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!st(n))return{policy:t,errors:[]};return{policy:df(In(n)),errors:[]}}try{let n=ja(e,"utf-8");if(!n.trim())return{policy:t,errors:[`${e}: Config file is empty`],fallback:"defaults"};let r=JSON.parse(n),o=Er(r),i=df(In(r));if(o.length>0)return{policy:i,errors:o.map((s)=>`${e}: ${s}`),fallback:st(r)?"salvaged":"defaults"};return{policy:i,errors:[]}}catch(n){let r=n instanceof Error?n.message:String(n);return{policy:t,errors:[`${e}: ${n instanceof SyntaxError?"Invalid JSON":r}`],fallback:"defaults"}}}function pf(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[..._m].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function Kx(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:pf({}),denyPaths:[],allowPaths:[]}}}function df(e){return{safety:gf(e.safety),worktreeMode:e.workflow.worktree_mode,destructiveCommandProtectionEnabled:e.destructive_command_protection.enabled,destructiveCommandRuleOverrides:e.destructive_command_protection.overrides,destructiveCommandAllowPaths:e.destructive_command_protection.allow_paths,secretProtection:{enabled:e.secret_protection.enabled,disabledRules:pf(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function gf(e){let t={...e.overrides.fail_closed!==void 0?{failClosed:e.overrides.fail_closed}:{},...e.overrides.paranoid_rm!==void 0?{paranoidRm:e.overrides.paranoid_rm}:{},...e.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:e.overrides.paranoid_interpreters}:{}};return{level:e.level,...Object.keys(t).length>0?{overrides:t}:{}}}var bf="This path contains the protected policy config and you must not modify or delete it.",Zx=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Sf(e){let t=Mt(ct()),n=nE(e.invocation.context.executionCwd,t);if(e.invocation.route.kind==="patch")return hf(e.paths,!1,e.invocation.context.executionCwd,n,t);let r=be(e,"input-candidate");if(e.invocation.route.kind==="command")return r?yf(r.shell,e.invocation.context.executionCwd,n,t):null;if(e.invocation.route.kind==="unknown"&&r){let o=yf(r.shell,e.invocation.context.executionCwd,n,t);if(o)return o}return hf(e.paths,e.invocation.route.kind==="grep"||e.invocation.route.kind==="glob"||Oo(e.invocation.toolName),e.invocation.context.executionCwd,n,t)}function hf(e,t,n,r,o){if(t)return null;let i=e.find((s)=>Tr(s,n,r,o));return i?{target:i}:null}function yf(e,t,n,r){let o=Lo(e,t,r,{findSegmentTarget:(i,s)=>Xx(i,s,n,r)?.target??null,isRedirectionTarget:(i,s)=>Tr(i,s.cwd,n,r),findMalformedTarget:(i)=>tE(i,t,n,r)?.target??null,normalizeCwd:le});return o?{target:o}:null}function Xx(e,t,n,r){if(tr(e))return null;let o=r.environment,i=vt([...e],o),s=D(i[0]??"").toLowerCase(),a=i.slice(1);if(s==="rm"&&Jx(a)){let l=Qx(a).find((c)=>Cf(Se(c,t.variables),t.cwd,n,r));if(l)return{target:l}}if(s==="find"){if(Zo(i,1)||Ws(i,o)){let c=(Yo(G(i))??G(["."])).find((u)=>{let m=Se(u.text,t.variables);return Tr(m,t.cwd,n,r)||Cf(m,t.cwd,n,r)})?.text;if(c)return{target:c}}}if(s==="mv"){let l=No(a).sources.find((c)=>rE(Se(c,t.variables),t.cwd,n,r));if(l)return{target:l}}if(eE(e,o))return null;for(let l of[...e,...i])for(let c of vf(l))if(Tr(Se(c,t.variables),t.cwd,n,r))return{target:c};return null}function Jx(e){return e.some((t)=>t==="--recursive"||t.startsWith("-")&&!t.startsWith("--")&&/[rR]/.test(t.slice(1)))}function Qx(e){let t=e.indexOf("--");if(t!==-1)return[...e.slice(0,t).filter((n)=>!n.startsWith("-")),...e.slice(t+1)];return e.filter((n)=>!n.startsWith("-"))}function eE(e,t){let n=vt([...e],t);if(n.length===0)return!1;let r=D(n[0]??"").toLowerCase();if(!Zx.has(r))return!1;if(r!=="sed")return!0;return!n.slice(1).some((o)=>o.startsWith("-i")||o==="--in-place"||o.startsWith("--in-place="))}function tE(e,t,n,r){for(let o of e.split(/\s+/))for(let i of vf(o))if(Tr(i,t,n,r))return{target:i};return null}function vf(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.indexOf("=");return n===-1||n===t.length-1?[t]:[t,t.slice(n+1)]}function nE(e,t){let n=le(On(),e,t),r=Va(n),o=new Set;for(let i=r;;i=Va(i))if(o.add(Mn(i)),Va(i)===i)break;return{file:Mn(n),directoryAndAncestors:o}}function Tr(e,t,n,r){let o=ru(e,t,r,(i)=>Mn(i)===Yx(n.file));return o!==null&&Mn(o)===n.file}function Cf(e,t,n,r){return n.directoryAndAncestors.has(Mn(le(e,t,r)))}function rE(e,t,n,r){let o=Mn(le(e,t,r));return o===n.file||n.directoryAndAncestors.has(o)}function Mn(e){return process.platform==="win32"?e.toLowerCase():e}import{homedir as Ka}from"node:os";import{isAbsolute as Ti,posix as oE,resolve as Oi,win32 as iE}from"node:path";import{fileURLToPath as sE}from"node:url";var Of="Access to a sensitive path is not allowed.",Mf=new Set(["echo","printf"]),aE=new Set(["find"]),lE=new Set(["-exec","-execdir"]),cE=new Set([";","+"]),uE=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),dE=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),mE=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),fE=new Set(["node","bun"]),pE=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),gE=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"]),Df=new Set(["-c","-e","-r","-E","--eval","--exec"]),hE=new Set(["src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js"]),Rf=new Set(["cc-safety-net","ccsn"]),yE=new Set(["bunx","npx","pnpx"]),CE=new Set(["bun","node"]),bE=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"])]]),SE=new Set(["grep","rg"]),xf="f",Ef="file",vE="files",RE=new Set(["e","f"]),xE=new Set(["regexp","file"]),EE=new Set(["e","f","A","B","C","m"]),wE=new Set(["regexp","file","after-context","before-context","context","max-count"]),PE=new Set(["|","|&"]),qa="__CC_SAFETY_NET_PIPE_INPUT__",Lf=new Set(["bash","sh","zsh","dash","ksh"]),_E=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 wf(e,t,n,r,o){let i=Jr();for(let s of e){if(pw(s,t,n?.denyPaths??[],r,i))return{target:s,ruleId:"secret.deny-path"};if(o&&!o.has(s))continue;let a=mw(s,t,n,i);if(a){if(!a.startsWith("secret.cli.")&&gw(s,t,n?.allowPaths??[],r,i))continue;return{target:s,ruleId:a}}}return null}function Nf(e,t,n={}){let r=Pf(e),o=wf(r,e.invocation.context.executionCwd,t,e.invocation.context.configCwd),i=o?.ruleId!=="secret.deny-path"&&n.strict===!1?Pf(e,{refineJavaScriptInlineData:!0}):r,s=i.length===r.length?o:wf(r,e.invocation.context.executionCwd,t,e.invocation.context.configCwd,new Set(i));if(s?.ruleId!=="secret.deny-path"&&n.strict===!1&&AE(e))return null;return s}function AE(e){if(e.invocation.route.kind!=="command")return!1;let t=be(e,"input-candidate")??be(e,"declared-command");if(!t)return!1;if(t.program.nodes.some((s)=>s.kind==="command"&&s.nested.length>0))return!1;let n=[];for(let s of t.shell.entries){if(s.kind==="operator"&&s.boundary)return!1;if(s.kind==="redirection")return!1;if(s.kind!=="operator")n.push(Je(s.text))}let r=Dn(n);if(r.length===0)return!1;let o=en(r[0]??"").toLowerCase(),i=r.slice(1);if(o==="ls"||o==="stat")return!0;if(o==="test")return i.length===2&&(i[0]==="-e"||i[0]==="-f");if(o!=="find")return!1;return!i.some((s)=>uE.has(s))}function Pf(e,t={}){if(e.invocation.route.kind==="command"){let r=be(e,"input-candidate");return r?Mr(r.shell,e.store,t):[]}if(e.invocation.route.kind!=="unknown")return[...e.paths];let n=be(e,"input-candidate");return[...n?Mr(n.shell,e.store,t):[],...e.paths]}function Mr(e,t,n){if(e.status==="structural-limit")throw new xt;if(e.status==="unclosed-quote")return[];if(e.status==="invalid")throw Error("Unable to parse command for secret protection");let r=[...e.assignmentFallbacks,...KE(Je(e.source),t,n)],o=[],i=null;for(let s of e.entries){if(s.kind==="operator"){if(!s.boundary)continue;if(o.length>0){if(r.push(...Ii(o,t,n)),i!==null)r.push(...Af(i,o,t,n));i=PE.has(s.operator)?o:null,o=[]}else i=null;continue}if(s.kind==="redirection"){let a=s.target?Je(s.target):void 0;if(a&&s.targetOrder==="legacy-segment")o.push(a);else if(a)r.push(a);continue}o.push(Je(s.text))}if(o.length>0){if(r.push(...Ii(o,t,n)),i!==null)r.push(...Af(i,o,t,n))}return r}function Ii(e,t,n){let r=FE(e),o=Dn(e);if(o.length===0)return r;let i=o[0]??"",s=en(i).toLowerCase(),a=o.slice(1),l=TE(i,s,a);if(l)return[...r,...l];if(Mf.has(s))return r;if(SE.has(s))return[...r,...nw(a)];if(aE.has(s))return[...r,...GE(a,t,n)];if(ve.has(s))return[...r,...a.flatMap((c)=>kf("awk",c)),...a.flatMap((c)=>$E(c,t,n)),...a.flatMap(BE)];if(Gf(s)){if(Lf.has(s)){let c=eu(s,a);if(c!==null&&t.getShellSyntax(c).status==="structural-limit")throw new xt}return[...r,...zE(s,a,n)]}return[...r,...a.flatMap((c)=>kf(s,c))]}function kE(e,t){if(Rf.has(e))return t[0]==="explain"?0:null;if(yE.has(e)){let n=t[0]==="-y"||t[0]==="--yes"?1:0;return Rf.has(t[n]??"")&&t[n+1]==="explain"?n+1:null}if(CE.has(e)){if(_f(t[0])&&t[1]==="explain")return 1;if(e==="bun"&&t[0]==="run"&&_f(t[1])&&t[2]==="explain")return 2}return null}function TE(e,t,n){let r=kE(t,n);if(r===null)return null;let o=[e,...n.slice(0,r)],i=n.slice(r+1);for(let s=0;s<i.length;s++){let a=i[s];if(a==="--json"||a==="--help"||a==="-h")continue;if(a==="--cwd"){let l=i[s+1];if(l&&!l.startsWith("--"))o.push(l);s++;continue}return o}return o}function _f(e){let t=e?.replaceAll("\\","/");return[...hE].some((n)=>t===n||t?.endsWith(`/${n}`))}function Af(e,t,n,r){if(LE(t,n,r))return IE(e);let o=NE(t);if(o===null)return[];return OE(e).flatMap((i)=>Lf.has(o)?Mr(n.getShellSyntax(i),n,r):$f(i))}function IE(e){let t=Dn(e);if(t.length===0)return[];let n=en(t[0]??"").toLowerCase();if(!Mf.has(n))return[];return t.slice(1)}function OE(e){let t=Dn(e);if(t.length===0)return[];let n=en(t[0]??"").toLowerCase(),r=t.slice(1);if(n==="echo"){let o=r.findIndex((i)=>!/^-[neE]+$/.test(i));return[(o===-1?[]:r.slice(o)).join(" ")]}if(n==="printf")return ME(r);return[]}function ME(e){let t=e[0];if(t===void 0)return[];let n=(t.match(/%%|%[bqs]/g)??[]).filter((o)=>o!=="%%").length;if(n===0||e.length===1)return[Wf(t)];let r=e.slice(1);return Array.from({length:Math.ceil(r.length/n)},(o,i)=>DE(t,r.slice(i*n,(i+1)*n)))}function DE(e,t){let n=0;return Wf(e.replace(/%%|%[bqs]/g,(r)=>{if(r==="%%")return"%";let o=t[n]??"";return n++,o}))}function Wf(e){return e.replace(/\\n/g,`
44
+ `).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function LE(e,t,n){let r=Dn(e);if(r.length===0||en(r[0]??"").toLowerCase()!=="xargs")return!1;let o=Ht(r),i=r.slice(o.childStart);if(i.length===0)return!1;if(o.replacementToken==="")return!1;let s=o.replacementToken,a=s===null?[...i,qa]:i.map((l)=>l.split(s).join(qa));return Ii(a,t,n).some((l)=>l.includes(qa))}function NE(e){let t=Dn(e);if(t.length===0)return null;let n=en(t[0]??"").toLowerCase();if(!Gf(n))return null;return WE(n,t.slice(1))?n:null}function WE(e,t){let n=Ff(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(Df.has(o)||zf(e,o)||/^--(?:eval|exec)=/.test(o))return!1;if(o==="-")return!0;if(o.startsWith("-")){if(n==="python"&&o==="-m")return!1;if(_E.get(n)?.has(o))r++;continue}return!1}return!0}function Ff(e){return/^python\d/.test(e)?"python":e}function FE(e){let t=[];for(let n of e){if(Hf(n))continue;let r=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(n);if(r===null)break;if(r[1]!==void 0&&r[1]!=="")t.push(r[1])}return t}function kf(e,t){if(t==="--")return[];let n=[],r=t.indexOf("=");if(r>0&&r<t.length-1)n.push(t.slice(r+1));if(t.startsWith("-"))return n;if(e==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(t))return n;if(e==="zip"&&/\.zip$/i.test(t))return n;return n.push(t),n}function GE(e,t,n){let r=e.findIndex((i)=>i.startsWith("-")||i==="("||i==="!"||i===";"),o=[...e.slice(0,r===-1?e.length:r)];for(let i=0;i<e.length;i++){if(!lE.has(e[i]??""))continue;let s=e.slice(i+1),a=s.findIndex((u)=>cE.has(u)),l=a===-1?s:s.slice(0,a),c=Ii(l,t,n);if(o.push(...c.filter((u)=>u!=="{}")),!c.includes("{}"))continue;o.push(...e.slice(0,i).flatMap((u,m,f)=>{if(!dE.has(u))return[];let d=f[m+1];return d===void 0?[]:[d,d.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return o}function Gf(e){return mE.has(e)||/^python\d/.test(e)}function zE(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o];if(i===void 0)break;if(Df.has(i)||zf(e,i)){let a=t[o+1];if(a!==void 0)r.push(...Tf(e,a,n)),o++;continue}let s=/^--(?:eval|exec)=(.*)$/.exec(i);if(s!==null&&s[1]!==void 0){r.push(...Tf(e,s[1],n));continue}if(!i.startsWith("-"))r.push(i)}return r}function zf(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<=2)return!1;return bE.get(t[t.length-1]??"")?.has(Ff(e))??!1}function $E(e,t,n){if(!e.includes("system"))return[];return Ms(e)?.commands.flatMap((r)=>Mr(t.getShellSyntax(r),t,n))??[]}function BE(e){return Array.from(e.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((t)=>t[1]).filter((t)=>t!==void 0&&t!=="")}function $f(e){let t=Array.from(e.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((r)=>r[2]).filter((r)=>r!==void 0&&r!==""),n=(e.match(/[\w./~@+-]*[./~][\w./~@+-]*/g)??[]).filter((r)=>r!=="process.versions.sqlite"||t.some((o)=>o.includes(r)));return[...t,...t.flatMap(Bf),...n]}function Tf(e,t,n){let r=$f(t);if(!n.refineJavaScriptInlineData||!fE.has(e)||r.length===0)return r;let o=UE(t);return o!==null&&!jE(o)?[]:r}function UE(e){let t=e.split("");for(let n=0;n<e.length;n++){let r=e[n];if(r!=="'"&&r!=='"'&&r!=="`")continue;if(r==="`"&&HE(e,n))return null;t[n]=" ";let o=!1;for(let i=n+1;i<e.length;i++){let s=e[i];if(t[i]=" ",s==="\\"){if(i++,i<e.length)t[i]=" ";continue}if(r==="`"&&s==="$"&&e[i+1]==="{")return null;if(r!=="`"&&(s===`
45
+ `||s==="\r"))return null;if(s!==r)continue;n=i,o=!0;break}if(!o)return null}return t.join("")}function HE(e,t){for(let n=t-1;n>=0;n--){let r=e[n];if(!r||/\s/.test(r))continue;return/[\w$\])]/.test(r)}return!1}function jE(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(pE.has(n.toLowerCase()))return!0;let o=n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((i)=>i.toLowerCase());if(!o.some((i)=>gE.has(i)))continue;if(o.length>1)return!0;if(VE(e,r)===".")return!0;if(qE(e,r+n.length)==="(")return!0}return!1}function VE(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function qE(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function KE(e,t,n){return QE(e).flatMap((r)=>{let o=t.getShellSyntax(r);if(o.status==="invalid")return[];return[...Mr(o,t,n),...YE(o)?ZE(o):[]]})}function YE(e){let t=e.entries;for(let n=0;n<t.length;n++){let r=t[n];if(r?.kind!=="word"||en(Je(r.text)).toLowerCase()!=="base64")continue;for(let o=n+1;o<t.length;o++){let i=t[o];if(i?.kind==="operator")break;if(i?.kind!=="word")continue;let s=Je(i.text);if(s==="--decode"||!s.startsWith("--")&&s.startsWith("-")&&/[dD]/.test(s))return!0}}return!1}function ZE(e){return e.entries.flatMap((t)=>t.kind==="word"?[Je(t.text)]:t.kind==="redirection"&&t.target?[Je(t.target)]:[]).flatMap(Bf)}function Bf(e){let t=JE(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||XE(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function XE(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function JE(e){if(e.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(e))return null;if(/=/.test(e.replace(/=+$/g,"")))return null;let t=e.replace(/=+$/g,"");if(t.length%4===1)return null;return`${t.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-t.length%4)%4)}`}function QE(e){let t=[],n={inSingle:!1,inDouble:!1,escaped:!1};for(let r=0;r<e.length;r++){let o=e[r];if(!o)break;if(Zn(o,n))continue;if(Uf(e,r,n)){let i=ew(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=tw(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function ew(e,t){let n={inSingle:!1,inDouble:!1,escaped:!1},r=1;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i)break;if(Zn(i,n))continue;if(Uf(e,o,n)){r++,o++;continue}if(!n.inSingle&&!n.inDouble&&i===")"){if(r--,r===0)return{body:e.slice(t+1,o),endIndex:o}}}return null}function tw(e,t){let n=!1;for(let r=t+1;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="`")return{body:e.slice(t+1,r),endIndex:r}}return null}function Uf(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function nw(e){let t=[],n=[],r=!1,o=!1,i=!1;for(let l=0;l<e.length;l++){let c=e[l];if(c===void 0)break;if(!i&&c==="--"){i=!0;continue}if(i){n.push(c);continue}let u=/^--([^=]+)(?:=(.*))?$/.exec(c);if(u!==null){let m=u[1]??"",f=u[2];if(m===vE)o=!0;if(xE.has(m))r=!0;if(f!==void 0){if(m===Ef)t.push(f);continue}if(wE.has(m)){let d=e[l+1];if(m===Ef&&d!==void 0)t.push(d);l++}continue}if(c.startsWith("-")&&c.length>1){let m=c.slice(1),f="",d="";for(let p=0;p<m.length;p++){let g=m[p]??"";if(RE.has(g))r=!0;if(EE.has(g)){f=g,d=m.slice(p+1);break}}if(f!=="")if(d.length>0){if(f===xf)t.push(d)}else{let p=e[l+1];if(f===xf&&p!==void 0)t.push(p);l++}continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function Dn(e){let t=e.findIndex((n)=>!Hf(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:[...e.slice(t)]}function Hf(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var rw=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),ow=".env.",iw=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),sw=[".env.example.",".env.sample."];function aw(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function lw(e){return e.length>0&&!/\s/.test(e)}function cw(e,t,n){try{let r=Dr(e,t,n);return r!==""&&De.entryKind(r)!=="missing"}catch(r){if(r instanceof Pe)throw r;return!1}}var uw=new Set(["node_modules","__pycache__"]),dw=[["vendor","bundle"],["vendor","cache"]];function mw(e,t,n,r){if(aw(e))return null;let o=at(e,t,r);if(!o)return null;let i=q(o.split("/").pop()??""),s=q(o),a=()=>lw(i)||cw(e,t,r);if(iw.has(i)||sw.some((m)=>i.startsWith(m)))return null;let l=q(Cw(e,t,r));for(let m of Ta){let f=`~/${m.suffixParts.join("/")}`;if((If(s,f)||If(l,f))&&yt(m.id,n))return m.id}let c=fw(o,t,n,r);if(c)return c;if(rw.has(i))return null;for(let m of ka)if(i===m.basename&&yt(m.id,n))return m.id;if(i.startsWith(ow)&&yt(bi.id,n)&&a())return bi.id;for(let m of Ia)if(i.length>m.prefix.length&&i.startsWith(m.prefix)){let f=i.slice(m.prefix.length)[0];if((f==="-"||f==="_")&&yt(m.id,n)&&a())return m.id}for(let m of Oa)if(i.length>m.prefix.length&&i.startsWith(m.prefix)){if(i.slice(m.prefix.length)===m.suffix&&yt(m.id,n))return m.id}if(hw(s))return null;if(!i.includes(".")&&xr.pattern.test(i)&&yt(xr.id,n))return xr.id;let u=yw(i,n);if(u)return u;return null}function fw(e,t,n,r){return Si.find((o)=>{if(!yt(o.id,n))return!1;switch(o.id){case"secret.cli.claude-code":return U(e,V(process.env.CLAUDE_CONFIG_DIR,"~/.claude",t,r),[".credentials.json"]);case"secret.cli.claude-code.config":{let i=q(e).split("/");return U(e,V(process.env.CLAUDE_CONFIG_DIR,"~/.claude",t,r),["settings.json","settings.local.json"])||Or(e,"~/.claude.json",t,r)||i.at(-1)==="settings.local.json"&&i.at(-2)===".claude"||i.at(-1)===".mcp.json"}case"secret.cli.antigravity":return U(e,at("~/.gemini/config",t,r),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let i=V(process.env.CODEX_HOME,"~/.codex",t,r);return U(e,i,["auth.json",".credentials.json"])||Ir(e,i,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let i=V(process.env.CODEX_HOME,"~/.codex",t,r),s=q(e).split("/").at(-1)??"";return U(e,i,["config.toml"])||s.endsWith(".config.toml")&&U(e,i,[s])}case"secret.cli.gemini":return U(e,ae(V(process.env.GEMINI_CLI_HOME,"~",t,r),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let i=q(e).split("/"),s=process.env.ProgramData?[ae(V(process.env.ProgramData,"",t,r),"gemini-cli")]:[];return U(e,ae(V(process.env.GEMINI_CLI_HOME,"~",t,r),".gemini"),["settings.json","google_accounts.json"])||i.at(-1)==="settings.json"&&i.at(-2)===".gemini"||(process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH?.trim()?Or(e,process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH,t,r):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...s].some((a)=>U(e,at(a,t,r),["settings.json"]))}case"secret.cli.copilot-cli":{let i=V(process.env.COPILOT_HOME,"~/.copilot",t,r);return U(e,i,["config.json"])||Ir(e,i,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return U(e,V(process.env.COPILOT_HOME,"~/.copilot",t,r),["mcp-config.json"]);case"secret.cli.kimi-code":{let i=V(process.env.KIMI_CODE_HOME,"~/.kimi-code",t,r),s=V(process.env.KIMI_SHARE_DIR,"~/.kimi",t,r);return U(e,i,["server.token"])||Ir(e,i,["credentials"])||Ir(e,s,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let i=["config.toml","mcp.json"],s=q(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".kimi-code"||U(e,V(process.env.KIMI_CODE_HOME,"~/.kimi-code",t,r),i)||U(e,V(process.env.KIMI_SHARE_DIR,"~/.kimi",t,r),[...i,"config.json","config.json.bak"])}case"secret.cli.opencode":{let i=ae(V(process.env.XDG_DATA_HOME,"~/.local/share",t,r),"opencode"),s=q(e).split("/").at(-1)??"",a=process.env.OPENCODE_DB?.trim(),l=a&&a!==":memory:"?[a,`${a}-wal`,`${a}-shm`]:[];return U(e,i,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(s)&&U(e,i,[s])||l.some((c)=>Or(e,c,t,r))}case"secret.cli.opencode.config":{let i=process.env.OPENCODE_CONFIG_DIR?V(process.env.OPENCODE_CONFIG_DIR,"~/.config/opencode",t,r):ae(V(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"opencode"),s=process.env.ProgramData?[ae(V(process.env.ProgramData,"",t,r),"opencode")]:[],a=["opencode.json","opencode.jsonc"];return a.includes(q(e).split("/").at(-1)??"")||U(e,i,a)||(process.env.OPENCODE_CONFIG?.trim()?Or(e,process.env.OPENCODE_CONFIG,t,r):!1)||["/Library/Application Support/opencode","/etc/opencode",...s].some((l)=>U(e,at(l,t,r),a))}case"secret.cli.pi":return U(e,V(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",t,r),["auth.json"]);case"secret.cli.pi.config":return U(e,V(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",t,r),["models.json"]);case"secret.cli.amp":{let i=at("~",t,r);return[ae(V(process.env.XDG_DATA_HOME,"~/.local/share",t,r),"amp"),ae(i,".local","share","amp")].some((a)=>U(e,a,["secrets.json"]))||Ir(e,ae(i,".amp"),["oauth"])}case"secret.cli.amp.config":{let i=["settings.json","settings.jsonc"],s=[ae(V(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"amp"),ae(at("~",t,r),".config","amp")],a=q(e).split("/");return s.some((l)=>U(e,l,i))||a.at(-2)===".amp"&&i.includes(a.at(-1)??"")||(process.env.AMP_SETTINGS_FILE?.trim()?Or(e,process.env.AMP_SETTINGS_FILE,t,r):!1)}case"secret.cli.cursor":{let i=ae(V(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"cursor"),s=ae(V(process.env.CURSOR_DATA_DIR,"~/.cursor",t,r),"projects");return U(e,at("~/.cursor",t,r),["auth.json"])||U(e,i,["auth.json"])||q(e).split("/").at(-1)==="mcp-auth.json"&&Qt(q(e),q(s))}case"secret.cli.cursor.config":{let i=q(e).split("/");return i.at(-1)==="mcp.json"&&i.at(-2)===".cursor"}case"secret.cli.grok-build":return U(e,V(process.env.GROK_HOME,"~/.grok",t,r),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let i=q(e).split("/");return i.at(-1)==="config.toml"&&i.at(-2)===".grok"||U(e,V(process.env.GROK_HOME,"~/.grok",t,r),["config.toml","managed_config.toml","requirements.toml"])||U(e,at("/etc/grok",t,r),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}function V(e,t,n,r){return at(e?.trim()?e:t,n,r)}function U(e,t,n){return n.some((r)=>jf(e,ae(t,r)))}function Ir(e,t,n){return n.some((r)=>Qt(q(e),q(ae(t,r))))}function Or(e,t,n,r){return jf(e,at(t,n,r))}function jf(e,t){return q(e)===q(t)}function ae(e,...t){return qe([e,...t].filter(Boolean).join("/"))}function pw(e,t,n,r,o){if(n.length===0)return!1;let i=q(Dr(e,t,o));return n.some((s)=>Qt(i,q(Dr(s,r,o))))}function gw(e,t,n,r,o){if(n.length===0)return!1;let i=q(Dr(e,t,o));if(!i)return!1;let s=process.env.HOME??Ka(),a=s?qe(H(pe(s),De,o)):"",l=q(a),c=process.env.CC_SAFETY_NET_HOME,u=q(c?qe(H(Oi(pe(c)),De,o)):a&&qe(H(`${a}/.cc-safety-net`,De,o)));if(u&&Qt(i,u))return!1;return n.some((m)=>{let f=q(Dr(m,r,o));if(!f)return!1;if(l&&(l===f||l.startsWith(f.endsWith("/")?f:`${f}/`)))return!1;return Qt(i,f)})}function hw(e){let t=e.split("/");return t.some((n)=>uw.has(n))||dw.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function yw(e,t){let n=e.lastIndexOf("."),r=n>0&&n<e.length-1?e.slice(n+1):"";if(r==="")return null;for(let o of Ma)if(r===o.extension&&yt(o.id,t))return o.id;for(let o of Da)if(o.pattern.test(r)&&yt(o.id,t))return o.id;return null}function q(e){return e.toLowerCase()}function yt(e,t){return!t?.disabledRules?.includes(e)}function at(e,t,n){let{home:r,normalized:o}=Ya(e,n);if(!o)return"";if(!r)return o;let i=Za(o,r),s=Ti(i)?i:qe(Oi(t,i)),a=qe(H(s,De,n));if(!Qt(a,r)){if(Ti(i))return a;return a===s?o:a}let l=a.slice(r.length);return l?`~${l}`:"~"}function If(e,t){return e===t||e.startsWith(`${t}/`)}function Cw(e,t,n){let{home:r,normalized:o}=Ya(e,n);if(!o||!r)return"";let i=Za(o,r),s=oE.normalize(Ti(i)?i:qe(Oi(t,i))),a=qe(pe(process.env.HOME??Ka())),l=(m)=>process.platform==="win32"?m.toLowerCase():m,c=[r,a].find((m)=>m!==""&&Qt(l(s),l(m)));if(c===void 0)return"";let u=s.slice(c.length);return u?`~${u}`:"~"}function Dr(e,t,n){let{home:r,normalized:o}=Ya(e,n);if(!o)return"";let i=r?Za(o,r):o;return qe(H(Ti(i)?i:Oi(t,i),De,n))}function Ya(e,t){let n=process.env.HOME??Ka(),r=n?qe(H(pe(n),De,t)):"",o=qe(pe(bw(Je(e))));return{home:r,normalized:o}}function bw(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return sE(e)}catch{return e}}function Za(e,t){if(e==="~")return t;if(e.startsWith("~/"))return ae(t,e.slice(2));return e}function Sw(e){if(process.platform==="win32")return!0;return iE.parse(e).root.length>1}function qe(e){let t=e.trim(),n=(Sw(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function Qt(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function en(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}import{dirname as Ct}from"node:path";var Vf="Rulebook exceeds CC Safety Net's safe validation limits.",qf="Additional rulebook validation errors were omitted.",Ke=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Kf(e){if(Xa(e.allowed_commands,Ke.maxAllowedCommands)||Xa(e.rules,Ke.maxRules)||Xa(e.tests,Ke.maxTests))return!1;let{maxAggregateStringCodeUnits:t,maxTotalBlockArgs:n}=Ke,r=(o,i=!1)=>{if(typeof o!=="string")return!0;if(o.length>Ke.maxStringCodeUnits||i&&o.length>Ke.maxFixtureCommandCodeUnits||o.length>t)return!1;return t-=o.length,!0};if(!r(e.name)||!r(e.version)||!r(e.description)||!r(e.author)||!r(e.migrated_from))return!1;if(Array.isArray(e.allowed_commands)){for(let o of e.allowed_commands)if(!r(o))return!1}if(Array.isArray(e.rules))for(let o of e.rules){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.name)||!r(i.command)||!r(i.subcommand)||!r(i.reason)||!r(i.intent))return!1;if(!Array.isArray(i.block_args))continue;if(i.block_args.length>Ke.maxBlockArgsPerRule||i.block_args.length>n)return!1;n-=i.block_args.length;for(let s of i.block_args)if(!r(s))return!1}if(Array.isArray(e.tests))for(let o of e.tests){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.command,!0)||!r(i.expect)||!r(i.rule))return!1}return!0}function Xa(e,t){return Array.isArray(e)&&e.length>t}function vw(e){if(!Rw(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Kf(e))return{errors:[Vf],ruleNames:new Set};let t=Om().safeParse(e),n=[...e.rulebook_version===1?[]:["rulebook_version must be 1"],...t.success?[]:An(t.error.issues,": ",": ")];return{errors:n.length>Ke.maxValidationErrors?[...n.slice(0,Ke.maxValidationErrors),qf]:n,ruleNames:new Set(La(e).map((r)=>r.toLowerCase()))}}function Ln(e){let t=vw(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}function Rw(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}var xw=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#([A-Za-z0-9._-]+)$/;function Mi(e){if(Pn(e.spec))return ww(e);return Ew(e)}function Ew(e){if(!Ie.test(e.spec))return`Local rulebook sources must be bare names matching ${Ie}: ${e.spec}`;if(e.kind!=="local-directory")return`lock entry for ${e.spec} must use local-directory kind`;if(e.path===e.spec&&e.name===e.spec)return null;return`lock entry for ${e.spec} does not match local source identity`}function ww(e){let t=Rr(e.spec);if(t)return t;let n=wn(e.spec);if(e.kind!=="github")return`lock entry for ${e.spec} must use github kind`;if(e.owner===n.owner&&e.repo===n.repo&&e.ref===n.ref&&e.path===n.path&&e.name===n.name)return null;return`lock entry for ${e.spec} does not match GitHub source identity`}function ZM(e,t,n){let r=Zf(e.rules,n);if(r.length>0)return{ok:!0,specs:r};if(!t)return{ok:!1,result:{ok:!1,errors:[`No lockfile available to match rulebook name ${n}; use the exact source or run ${Ve}`],warnings:[],entries:[]}};let o=new Set(e.rules),i=t.rulebooks.filter((s)=>s.name===n&&o.has(s.spec)).map((s)=>s.spec);if(i.length===1)return{ok:!0,specs:i};return Yf(n,i)}function XM(e,t,n){let r=Zf(e,n);if(r.length>0)return{ok:!0,specs:r};let o=Pw(e,n);if(o.length>0)return{ok:!0,specs:o};let i=_w(e,n);if(!i.ok)return i;if(i.specs.length>0)return{ok:!0,specs:i.specs};let s=t?e.filter((a)=>t.rulebooks.find((l)=>l.spec===a)?.name===n):[];if(s.length===1)return{ok:!0,specs:s};return Yf(n,s)}function Yf(e,t){return{ok:!1,result:{ok:!1,errors:t.length===0?[`No configured rulebook matches ${e}`]:[`Ambiguous rulebook match ${e}: ${t.join(", ")}`],warnings:[],entries:[]}}}function Zf(e,t){return e.filter((n)=>n===t)}function Pw(e,t){let n=t.match(xw),r=n?.[1],o=n?.[2],i=n?.[3];if(!r||!o||!i)return[];return Jf(e,(s)=>s.owner===r&&s.repo===o&&s.ref===i)}function _w(e,t){if(!Em(t))return{ok:!0,specs:[]};let[n,r]=t.split("/"),o=Jf(e,(s)=>s.owner===n&&s.repo===r);if(new Set(o.map((s)=>Xf(s)?.ref).filter((s)=>!!s)).size<2)return{ok:!0,specs:o};return{ok:!1,result:{ok:!1,errors:[`Multiple refs are configured for ${t}. Use an explicit ref:`,` cc-safety-net rule remove ${t}#<ref>`],warnings:[],entries:[]}}}function Xf(e){try{return wn(e)}catch{return null}}function Jf(e,t){return e.filter((n)=>{let r=Xf(n);return r?t(r):!1})}function Ja(e){let t=typeof e==="string"?e:e.path;try{let n=gt(typeof e==="string"?xi(e):e);if(n===null)return{lock:null,errors:[]};let r=JSON.parse(n);if(!r||typeof r!=="object")return{lock:null,errors:[`malformed lockfile ${t}: must be an object`]};let o=r;if(o.version!==1||!Array.isArray(o.rulebooks))return{lock:null,errors:[`malformed lockfile ${t}`]};let i=Mm().safeParse(o),s=o.rulebooks.flatMap((l,c)=>{let u=i.success?[]:i.error.issues.filter((f)=>f.path[1]===c);if(u.length>0)return An(u).map((f)=>`${t}: ${f}`);let m=Mi(l);return m?[`${t}: rulebooks[${c}]: ${m}`]:[]});if(!i.success||s.length>0)return{lock:null,errors:[`malformed lockfile ${t}`,...s]};return{lock:{version:1,rulebooks:i.data.rulebooks.map((l)=>{if(l.kind==="local-directory")return{spec:l.spec,kind:l.kind,path:l.path,name:l.name,version:l.version,digest:l.digest};let c={spec:l.spec,kind:l.kind,owner:l.owner,repo:l.repo,ref:l.ref,commit:l.commit,path:l.path,name:l.name,version:l.version,digest:l.digest};return typeof l.display_ref==="string"&&l.display_ref!==""?{...c,display_ref:l.display_ref}:c})},errors:[]}}catch(n){if(n instanceof L)return{lock:null,errors:[n.message]};return{lock:null,errors:["malformed lockfile"]}}}import{createHash as Aw}from"node:crypto";import{dirname as Di,join as kw}from"node:path";var tp=Object.freeze({timeoutMs:15000,metadataBytes:524288,commitBytes:262144,treeBytes:16777216,rawBytes:4194304});async function Qf(e,t,n,r=Me(Di(Di(t)),"rules policy"),o=hi()){if(Pn(e))return Iw(e,o);return Tw(e,t,n,r)}async function dD(e,t,n,r,o,i=hi()){if(!Pn(e)||n.refresh)return Qf(e,t,n,o,i);let s=r?.rulebooks.find((a)=>a.spec===e);if(!s||s.kind!=="github")return Qf(e,t,n,o,i);return Ow(s,t,n,o,i)}async function mD(e,t=hi()){let[n,r]=e.split("/");if(!n||!r)throw Error(`Invalid GitHub repository source: ${e}`);let o=await Lr(`https://api.github.com/repos/${n}/${r}`,"metadata",t),i=o.response;if(!i.ok)throw Error(`Failed to inspect ${e}: GitHub returned ${i.status}`);let a=JSON.parse(o.content)?.default_branch;if(typeof a!=="string"||a==="")throw Error(`Failed to inspect ${e}: missing default branch`);let l=await rp(n,r,a,e,t),c=await Lr(`https://api.github.com/repos/${n}/${r}/git/trees/${l}?recursive=1`,"tree",t),u=c.response;if(!u.ok)throw Error(`Failed to inspect ${e}: GitHub tree returned ${u.status}`);let m=JSON.parse(c.content);if(!Array.isArray(m?.tree))throw Error(`Failed to inspect ${e}: unexpected GitHub tree response`);let d=m.tree.flatMap((p)=>{if(!p||typeof p!=="object")return[];let g=p;if(g.type!=="blob"||typeof g.path!=="string")return[];let y=g.path.match(_a);return y?.[1]?[y[1]]:[]}).sort();if(d.length===0)throw Error(`No rulebooks found in ${e} under ${Ci}/`);return d.map((p)=>({spec:`${n}/${r}#${l}/${p}`,display_ref:a}))}function Tw(e,t,n,r){Aa(e);let o=Nw(t,e),i=gt(se(r,o));if(i===null)throw Error(`Rulebook source not found: ${e}`);let s=Ln(Qa(i,"Invalid local rulebook source."));if(s.name!==e)throw Error(`rulebook name "${s.name}" must match local source "${e}"`);return{rulebook:s,content:i,entry:{spec:e,kind:"local-directory",path:e,name:s.name,version:s.version,digest:Nn(i)}}}async function Iw(e,t){let n=wn(e),r=await rp(n.owner,n.repo,n.ref,e,t),o=await Lr(`https://raw.githubusercontent.com/${n.owner}/${n.repo}/${r}/${n.path}`,"raw",t),i=o.response;if(!i.ok)throw Error(`Failed to fetch ${e}: GitHub raw returned ${i.status}`);let s=o.content,a=Ln(Qa(s,"Invalid GitHub rulebook response."));if(a.name!==n.name)throw Error(`rulebook name "${a.name}" must match GitHub source "${n.name}"`);return{rulebook:a,content:s,entry:{spec:e,kind:"github",owner:n.owner,repo:n.repo,ref:n.ref,commit:r,path:n.path,name:a.name,version:a.version,digest:Nn(s)}}}async function Ow(e,t,n,r=Me(Di(Di(t)),"rules policy"),o){let i=Mi(e);if(i)throw Error(`${i}; run ${Ve}`);let s=Pi(e,_i(t,n)),a=gt(se(r,s));if(a!==null){if(Nn(a)===e.digest)return{entry:e,rulebook:np(a,e),content:a}}return Mw(e,o)}async function Mw(e,t){let n=await Lr(`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.commit}/${e.path}`,"raw",t),r=n.response;if(!r.ok)throw Error(`Failed to restore ${e.spec}: GitHub raw returned ${r.status}`);let o=n.content;if(Nn(o)!==e.digest)throw Error(`locked GitHub digest mismatch for ${e.spec}; run ${Ve}`);return{entry:e,rulebook:np(o,e),content:o}}function np(e,t){let n=Ln(Qa(e,"Invalid cached rulebook."));if(n.name!==t.name)throw Error(`rulebook name "${n.name}" must match lock entry "${t.name}"`);return n}function Qa(e,t){try{return JSON.parse(e)}catch{throw Error(t)}}async function rp(e,t,n,r,o){let i=await Lr(`https://api.github.com/repos/${e}/${t}/commits/${encodeURIComponent(n)}`,"commit",o),s=i.response;if(!s.ok)throw Error(`Failed to resolve ${r}: GitHub returned ${s.status}`);let a=JSON.parse(i.content);if(typeof a?.sha!=="string"||a.sha==="")throw Error(`Failed to resolve commit for ${r}`);return a.sha}async function Dw(e,t,n={}){if(n.signal?.aborted)throw n.signal.reason;let r=n.budget??gi(),o=new AbortController,i=()=>o.abort(n.signal?.reason);n.signal?.addEventListener("abort",i,{once:!0});let s=!1,a=setTimeout(()=>{if(o.signal.aborted)return;s=!0,o.abort()},n.timeoutMs??tp.timeoutMs);try{if(n.signal?.aborted)throw n.signal.reason;Sm(r);let l=await(n.fetch??fetch)(e,{signal:o.signal,redirect:"error"});if(!l.ok)return op(l),{response:l,content:""};return{response:l,content:await Lw(l,t,r,()=>o.abort())}}catch(l){if(s)throw Error("GitHub request timed out",{cause:l});if(n.signal?.aborted)throw n.signal.reason;throw l}finally{clearTimeout(a),n.signal?.removeEventListener("abort",i)}}function Lr(e,t,n){return Dw(n.resolveUrl?.(e)??e,t,{budget:n.budget,signal:n.controller.signal})}async function Lw(e,t,n=gi(),r){let o=tp[`${t}Bytes`],i=Number(e.headers.get("content-length"));if(Number.isFinite(i)&&i>o)throw op(e),Error(`GitHub ${t} response exceeds ${o} bytes`);if(!e.body)return"";let s=e.body.getReader(),a=[],l=0;while(!0){let c=await s.read();if(c.done)break;try{vm(n,c.value.byteLength)}catch(u){throw r?.(),ep(s),u}if(l+=c.value.byteLength,l>o)throw r?.(),ep(s),Error(`GitHub ${t} response exceeds ${o} bytes`);a.push(Buffer.from(c.value))}return Buffer.concat(a,l).toString("utf-8")}function op(e){if(!e.body)return;ip(()=>e.body?.cancel())}function ep(e){ip(()=>e.cancel())}function ip(e){try{Promise.resolve(e()).catch(()=>{})}catch{}}function Nw(e,t){return kw(e,t,yi)}function Nn(e){return`sha256:${Aw("sha256").update(e).digest("hex")}`}function lp(e={}){let t=of(e),n=!1;try{n=Hm(t.userConfigTarget,t.projectConfigTarget)}catch(f){if(f instanceof L)return Bw(t,f.message);throw f}let r=Tn(t.userConfigTarget),o=n?{config:null,errors:[]}:Tn(t.projectConfigTarget),i=ap(t.userConfigPath,r.errors),s=ap(t.projectConfigPath,o.errors),a=new Set,l=r.config?el(r.config,t.userLockPath,Ct(t.userConfigPath),e,"user",t.userScope,a):Nr(),c=o.config?el(o.config,t.projectLockPath,Ct(t.projectConfigPath),e,"project",t.projectScope,a):Nr(),u=r.config?.overrides??{},m=o.config?.overrides??{};return{rules:[...sp(l.rules,u),...sp(c.rules,m)],transparent_wrappers:zw(r.config,o.config),rulebooks:[...l.rulebooks,...c.rulebooks],errors:[...i,...s,...l.errors,...c.errors],warnings:[...l.warnings,...c.warnings,...l.canValidateOverrides?tl(u,l.knownRuleIds,t.userConfigPath):[],...l.canValidateOverrides?$w(m,l.knownRuleIds,t.projectConfigPath):[],...c.canValidateOverrides?tl(m,c.knownRuleIds,t.projectConfigPath):[]],userConfig:r.config??void 0,projectConfig:o.config??void 0,...t}}function vD(e,t){let n=t??Me(Ct(Ct(e)),"rules policy"),r=Tn(se(n,e)).config,o=Ja(se(n,Xt(e))).lock;if(!r||!o)return new Map;let i=new Set(r.rules);return new Map(o.rulebooks.filter((s)=>i.has(s.spec)).map((s)=>[s.spec,lf(s)]))}function RD(e,t,n,r){let o=Ww(e,t,n,r);if(!o)return[];return[...o.scope.errors,...o.scope.warnings,...Fw(o.config,o.scope,e)]}function Ww(e,t,n,r){let o=r??Me(Ct(Ct(e)),"rules policy"),i=Tn(se(o,e)).config;if(!i)return null;return{config:i,scope:el(i,t,Ct(e),n,"project",o)}}function Fw(e,t,n){return t.canValidateOverrides?tl(e.overrides??{},t.knownRuleIds,n):[]}function el(e,t,n,r,o,i=Me(Ct(Ct(n)),o==="user"?"user policy":"project policy"),s=new Set){let a;try{a=se(i,t)}catch(y){if(y instanceof L)return{...Nr(),errors:[y.message],canValidateOverrides:!1};throw y}let l=Ja(a);if(l.errors.length>0)return{...Nr(),errors:l.errors,canValidateOverrides:!1};let c=l.lock;if(!c&&e.rules.length>0)return{...Nr(),errors:[`missing lockfile ${t}; run ${Ve}`],canValidateOverrides:!1};let u=c?.rulebooks??[],m=new Map(u.map((y)=>[y.spec,y])),f=[],d=[],p=e.rules.flatMap((y)=>{let h=m.get(y);if(!h)return f.push(`missing lock entry for ${y}; run ${Ve}`),[];let R=Gw(h,n,r,i);if(R.errors.length>0||!R.rulebook)return f.push(...R.errors),[];let x=R.rulebook;if(s.has(x.name))return d.push(`duplicate active rulebook name "${x.name}" for ${y}; keeping the first and ignoring this one, so its rules are not active; rename one of them, then run ${Ve}`),[];return s.add(x.name),[{rules:x.rules.map((A)=>({...A,name:`${x.name}/${A.name}`})),rulebook:{source:o,spec:h.spec,name:x.name,version:x.version,rules:x.rules.map((A)=>`${x.name}/${A.name}`)}}]}),g=p.flatMap((y)=>y.rules);return{rules:g,rulebooks:p.map((y)=>y.rulebook),entries:u,knownRuleIds:new Set(g.map((y)=>y.name)),errors:f,warnings:d,canValidateOverrides:f.length===0}}function Gw(e,t,n,r){let o=Pi(e,_i(t,n)),i;try{i=gt(se(r,o))}catch(a){if(a instanceof L)return{rulebook:null,errors:[a.message]};throw a}if(i===null)return{rulebook:null,errors:[`missing cache entry for ${e.spec}; run ${Ve}`]};if(Nn(i)!==e.digest)return{rulebook:null,errors:[`cache digest mismatch for ${e.spec}; run ${Ve}`]};let s;try{s=JSON.parse(i)}catch{return{rulebook:null,errors:[`invalid cached rulebook for ${e.spec}`]}}try{Ln(s)}catch(a){return{rulebook:null,errors:[`invalid cached rulebook for ${e.spec}: ${a instanceof Error?a.message:"invalid rulebook"}`]}}return{rulebook:s,errors:[]}}function zw(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function sp(e,t){return e.flatMap((n)=>{let r=t[n.name];if(r==="off")return[];if(r&&typeof r==="object")return[{...n,intent:r.intent??n.intent,reason:r.reason}];return[n]})}function tl(e,t,n){return Object.keys(e).filter((r)=>!t.has(r)).map((r)=>`unknown override key "${r}" in ${n}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function $w(e,t,n){return Object.keys(e).filter((r)=>t.has(r)).map((r)=>`project override cannot target user-scoped rule "${r}" in ${n}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function ap(e,t){return t.map((n)=>n.startsWith("Unable to access ")?n:`${e}: ${n}`)}function Bw(e,t){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath,userLockPath:e.userLockPath,projectLockPath:e.projectLockPath}}function Nr(){return{rules:[],rulebooks:[],entries:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}function cp(e={}){let t=lp(e),n=ff(e),r={rules:t.rules,transparentWrappers:t.transparent_wrappers,safety:n.safety,worktreeMode:n.worktreeMode,destructiveCommandProtectionEnabled:n.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:n.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:n.destructiveCommandAllowPaths,secretProtection:{enabled:n.secretProtection.enabled??!0,disabledRules:n.secretProtection.disabledRules??[],denyPaths:n.secretProtection.denyPaths,allowPaths:n.secretProtection.allowPaths??[]}},o={...t.userConfig?.overrides??{},...t.projectConfig?.overrides??{}},i=Object.freeze(Object.fromEntries(r.rules.map((s)=>{let a=t.rulebooks.find((c)=>c.rules.includes(s.name)),l=o[s.name];return[s.name,Object.freeze({id:s.name,...a?{rulebook:Object.freeze({name:a.name,version:a.version}),...Vw(a.spec)?{source:a.spec}:{}}:{},...l&&typeof l==="object"?{override:Object.freeze({type:"reason",reason:l.reason})}:{}})]})));return qw(r,Uw(t,n),i)}function PD(e){if(e.state==="ready")return{state:e.state};return{state:e.state,reason:e.reason}}function Uw(e,t){let n=jw(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:Kw(e.errors.length>0?Hw(e.errors):void 0,e.warnings.length>0?nl(e.warnings.join("; ")):void 0,n)}}function Hw(e){return`${nl(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function jw(e){if(e.errors.length===0)return;let t=e.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${e.errors.join("; ")}. Enforcing ${t}; the invalid values are not active. Fix the policy file manually`}function Vw(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function qw(e,t,n=Object.freeze({})){let r=up(structuredClone(e));if(!t)return Object.freeze({state:"ready",policy:r,diagnostics:Object.freeze([]),ruleMetadata:n});return Object.freeze({state:"degraded",policy:r,diagnostics:Object.freeze([...t.diagnostics]),reason:t.reason,ruleMetadata:n})}function up(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))up(t);return Object.freeze(e)}function Kw(...e){return nl(e.filter((t)=>!!t).join("; "))}function nl(e){return/[.!?]$/.test(e)?e:`${e}.`}class rl extends Error{stage;evaluation;name="GuardEvaluationError";constructor(e,t,n){super(`CC Safety Net ${e} dependency failed`,{cause:n});this.stage=e;this.evaluation=t}}var Yw={findPolicyMutation:Sf,findGitMetadataMutation:au,resolveGitMetadata:xs,loadPolicySnapshot:cp,findSensitiveTarget:Nf,analyzeCommand:Ea,getModes:pi};function GD(e,t={}){let n={...Yw,...t.dependencies},r=Jw(e),o=Wr(e)?e.command:r,i=tn("policy-protection",o,()=>Do(e,t.factParserDependencies)),s=be(i,"declared-command");if(Wr(e)&&e.command?.trim()&&s?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:lt,intent:"stop_and_explain",evidence:[{kind:"command",command:e.command,segment:e.command}]}};if(be(i,"input-candidate")?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:ul,intent:"stop_and_explain",evidence:[]}};let a=tn("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd])),l=tn("policy-protection",o,()=>n.findPolicyMutation(i));if(l){let y=o??l.target;return{stage:"policy-protection",decision:{kind:"deny",reason:bf,intent:"hard_stop",evidence:[{kind:"command",command:y,segment:l.target}]}}}let c=tn("policy-protection",o,()=>n.findGitMetadataMutation(i,a));if(c){let y=o??c.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Ae,intent:"hard_stop",evidence:[{kind:"command",command:y,segment:c.target}]}}}let u=tn("config-load",o,()=>n.loadPolicySnapshot({...t.policyOptions,cwd:e.context.configCwd})),m=u.policy,f=n.getModes(m),d={level:f.effectiveLevel,...Zw(u)},p=m.secretProtection.enabled===!1?null:tn("secret-protection",o,()=>n.findSensitiveTarget(i,m.secretProtection,{strict:Wr(e)?f.strict:void 0}));if(p){let y=o??p.target;return{stage:"secret-protection",...d,decision:{kind:"deny",reason:Of,intent:"hard_stop",ruleId:p.ruleId,evidence:[{kind:"command",command:y,segment:p.target}]}}}if(!Wr(e))return{stage:"non-command",...d,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...ol("command-validation",o),...d};let g=tn("command-analysis",o,()=>n.analyzeCommand(e.command,{cwd:e.context.executionCwd,shell:e.route.shell,policySnapshot:u,environment:ct(),protectedGitMetadata:a,effectiveCapabilities:f.capabilities,strict:f.strict,paranoidRm:f.paranoidRm,paranoidInterpreters:f.paranoidInterpreters,worktreeMode:f.worktreeMode},Xw(i),i.store));if(g)return{stage:"command-analysis",...d,decision:g};return{stage:"command-analysis",...d,decision:{kind:"allow"}}}function Zw(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function Xw(e){return be(e,"declared-command")?.program}function Jw(e){try{return Mo(e.input)}catch(t){let n=Wr(e)?e.command:void 0;throw new rl("policy-protection",ol("policy-protection",t instanceof er?void 0:n,t),t)}}function tn(e,t,n){try{return n()}catch(r){throw new rl(e,ol(e,r instanceof er?void 0:t,r),r)}}function ol(e,t,n){let r=n instanceof Pe||n instanceof xt;return{stage:e,decision:{kind:"deny",reason:r?dl:ml,intent:"stop_and_explain",evidence:t?[{kind:"command",command:t,segment:t}]:[]}}}function Wr(e){return e.route.kind==="command"}
46
+ export{hm as q,ym as r,De as s,ct as t,L as u,se as v,xi as w,gt as x,Um as y,Hm as z,AO as A,kO as B,TO as C,IO as D,OO as E,vx as F,Ie as G,yi as H,Ci as I,Em as J,Qm as K,Ve as L,nf as M,Jt as N,rf as O,KO as P,Xt as Q,YO as R,ZO as S,of as T,XO as U,lf as V,Pi as W,JO as X,_i as Y,oP as Z,iP as _,sP as $,xp as aa,ml as ba,Pe as ca,Jr as da,H as ea,Yr as fa,qi as ga,Dt as ha,er as ia,y_ as ja,Mo as ka,Bc as la,jc as ma,xt as na,Do as oa,yy as pa,Ae as qa,au as ra,xs as sa,ku as ta,NA as ua,ie as va,jR as wa,XI as xa,pi as ya,br as za,Ra as Aa,JI as Ba,pm as Ca,iO as Da,Ea,fl as Fa,vr as Ga,bm as Ha,Cm as Ia,hi as Ja,Pm as Ka,xO as La,La as Ma,Er as Na,An as Oa,Ax as Pa,Tn as Qa,FO as Ra,GO as Sa,zO as Ta,wi as Ua,ki as Va,On as Wa,mM as Xa,Ai as Ya,fM as Za,Ux as _a,pM as $a,In as ab,pf as bb,gf as cb,bf as db,Sf as eb,Of as fb,Nf as gb,Ln as hb,ZM as ib,XM as jb,Ja as kb,dD as lb,mD as mb,lp as nb,vD as ob,RD as pb,el as qb,cp as rb,PD as sb,qw as tb,rl as ub,GD as vb};