cc-safety-net 2.3.2 → 2.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,46 +0,0 @@
1
- import{accessSync as Cp,constants as rl,realpathSync as Sp,statSync as ol}from"node:fs";import{isAbsolute as il,relative as bp,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 It(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function mt(e,t,n){if(It(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 lP(e){try{if(!ol(e).isDirectory())return!1;return Cp(e,rl.R_OK|rl.X_OK),!0}catch{return!1}}function cP(e,t){if(It(e))return;let n=t.flatMap((o)=>Ai(o));if(!n[0])return;let r=Ai(il(e)?e:vp(n[0],e))[0];if(!r)return;return n.some((o)=>xp(r,o))?r:void 0}function uP(e){return e.flatMap((t)=>Ai(t))[0]}function Ai(e){try{let t=Sp(e);return ol(t).isDirectory()?[t]:[]}catch{return[]}}function xp(e,t){let n=bp(t,e);return n===""||n!==".."&&!n.startsWith(`..${Rp}`)&&!il(n)}var ft="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",nt="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",sl="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.",al="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",ll="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";function Ti(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 k(e){return e.provenance==="command-substitution"?e.raw:e.text}function en(e,t){return e==="posix"?t:W(t.map((n)=>n.text))}function Dr(e,t){return e&&e.provenance!=="unknown"?e.provenance==="literal":!/[$`*?[\]]/.test(t)}function W(e){return e.map((t)=>({kind:"word",text:t,raw:t,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}import{existsSync as Mi,lstatSync as Ip,readFileSync as Fr,realpathSync as Tn,statSync as An}from"node:fs";import{dirname as Di,isAbsolute as Ni,join as Gr,resolve as zr}from"node:path";import{lstatSync as Ep,realpathSync as _p}from"node:fs";import{homedir as Pp,tmpdir as wp}from"node:os";var Oe={realpath:(e)=>{try{return _p(e)}catch{return null}},entryKind:(e)=>{let t=Ep(e,{throwIfNoEntry:!1});if(!t)return"missing";return t.isSymbolicLink()?"symlink":"present"}};function he(e,t=process.platform){if(t!=="win32")return e;return e.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function kt(){return he(process.env.HOME||Pp())}function Me(){return{env:new Map(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),home:kt(),tmpdir:wp(),paths:Oe}}var Ii=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],Ap=new Set(Ii);var cl=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),Nr=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),Tp=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ki(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 Oi(e){return ki(e)||cl.has(e)||Nr.has(e)||wn(e)}function _e(e,t,n){return n?.has(e)?n.get(e):t.get(e)}function Lr(e,t){let n=_e("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 Wr(e,t,n){let o=e.match(Tp)?.[1];if(!o||!Oi(o))return null;let i=e.indexOf("=");return{name:o,value:`${_e(o,t,n)??""}${e.slice(i+1)}`}}function ul(e){return ml(e,Nr)}function dl(e){return ml(e,cl)}function ml(e,t){if(!e)return!1;for(let n of e.keys())if(t.has(n))return!0;return!1}var Pe=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]);function gl(e,t){return Ii.some((n)=>t?.has(n)||e.has(n))}function hl(e,t){if(!t)return{gitCwd:null,hasExplicitGitContext:!1};let n;try{n=Tn(zr(t))}catch{return{gitCwd:null,hasExplicitGitContext:!1}}if(!Sl(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=pl(n,s);if(!a)return{gitCwd:null,hasExplicitGitContext:r};n=a,o+=2;continue}if(i.startsWith("-C")&&i.length>2){let s=pl(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(Pe.has(i))o+=2;else if(i.startsWith("-c")&&i.length>2)o++;else o++}return{gitCwd:n,hasExplicitGitContext:r}}function yl(e){let t=jp(e);if(!t)return!1;try{let n=Ip(t);if(n.isSymbolicLink()||!n.isFile())return!1;let r=Li(t);if(!r?.commonDir)return!1;if(!Mp(r.gitDir,t))return!1;return Dp(r.gitDir,Di(t))}catch{return!1}}function Li(e){try{let t=kp(e);if(!t)return null;let n=Tn(Ni(t)?t:zr(Di(e),t));if(!An(n).isDirectory())return null;return{gitDir:n,commonDir:Op(n)}}catch{return null}}function kp(e){let t=Fr(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=Fr(Gr(e,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!t)return null;let n=Tn(Ni(t)?t:zr(e,t));return An(n).isDirectory()?n:null}catch{return null}}function Mp(e,t){let n=Np(e);return n===null?!1:Cl(e,n,t)}function Dp(e,t){let n=Lp(e);return n===null?!0:Cl(e,n,t)}function Np(e){let t=Gr(e,"gitdir");if(!Mi(t))return null;let n=Fr(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return n===""?null:n}function Lp(e){let t=Gr(e,"config.worktree");return Mi(t)?Bp(t):null}function Cl(e,t,n){return Fp(Wp(e,t),n)}function Wp(e,t){return Ni(t)?t:zr(e,t)}function Fp(e,t){try{return Gp(e,t)}catch{return!1}}function Gp(e,t){try{let n=An(e),r=An(t);if(n.ino!==0&&r.ino!==0&&n.dev===r.dev&&n.ino===r.ino)return!0}catch{}return fl(e)===fl(t)}function fl(e){return zp(Tn.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 Bp(e){let t=Fr(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=Up(s[1]??"")}return r}function Up(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;return $p(t.slice(1,-1))}function $p(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 pl(e,t){try{let n=mt(e,t,Oe);return Sl(n)?n:null}catch{return null}}function Sl(e){try{return An(e).isDirectory()}catch{return!1}}function jp(e){try{return In(Tn(e))}catch{return null}}function In(e){let t=e;while(!0){let n=Gr(t,".git");if(Mi(n))return n;let r=Di(t);if(r===t)return null;t=r}}function Wi(e,t){return{value:e,work:t}}function b(e,t){if(e.work)e.work.units=Math.min(Number.MAX_SAFE_INTEGER,e.work.units+1);return e.value[t]}function ee(e){return e.value.length}function kn(e,t,n=1){if(e)e.units=Math.min(Number.MAX_SAFE_INTEGER,e.units+t.length*n)}function ye(e,t){kn(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 J(e){if(!e)return!1;let t=e.charCodeAt(0);return t===9||t===10||t===11||t===12||t===13||t===32||t===160||t===65279||t===5760||t>=8192&&t<=8202||t===8232||t===8233||t===8239||t===8287||t===12288}function Fi(e){return e===`
3
- `||e==="\r"||e==="\u2028"||e==="\u2029"}function Q(e,t,n){if(t+n.length>ee(e))return!1;for(let r=0;r<n.length;r++)if(b(e,t+r)!==n[r])return!1;return!0}function rt(e,t,n){return!Ot(b(e,t-1))&&Q(e,t,n)&&!Ot(b(e,t+n.length))}function ot(e,t){return Ot(b(e,t-1))!==Ot(b(e,t))}function oe(e){return e===`
4
- `||e===";"||e==="&"||e==="|"}function tn(e){return e==="|"||e===";"}function Br(e,t,n){let r=Wi(e,n);if(t==="rm")return Hp(r);if(t==="dd")return qp(r);return _l(r,!0)}function Ur(e,t,n){let r=Wi(e,n);if(t==="rm")return Kp(r);if(t==="reset-hard")return xl(r,"--ha","rd");if(t==="reset-merge")return xl(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 _l(r,!1)}function Hp(e){let t=!1,n=!1,r=!1,o=-1;for(let i=0;i<=ee(e);i++){let s=b(e,i);if(!t){let l=b(e,i+2);if(rt(e,i,"rm")&&J(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===ee(e)){if(o>=0){let l=bl(e,o,i);n||=l.recursive,r||=l.force}if(n&&r)return!0;t=!1,n=!1,r=!1,o=-1;continue}if(J(s)){if(o>=0){if(Q(e,o,"--")&&i-o===2)t=!1,n=!1,r=!1;else{let l=bl(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(b(e,t)!=="\\"||b(e,t-1)==="\\")return-1;if(Q(e,t,String.raw`\n`))return t+2;if(Q(e,t,String.raw`\x0a`)||Q(e,t,String.raw`\x0A`))return t+5;if(Q(e,t,String.raw`\u000a`)||Q(e,t,String.raw`\u000A`))return t+7;return Q(e,t,String.raw`\012`)?t+4:-1}function bl(e,t,n){if(vl(e,t,n,"recursive"))return{recursive:!0,force:!1};if(vl(e,t,n,"force"))return{recursive:!1,force:!0};if(b(e,t)!=="-"||b(e,t+1)==="-")return{recursive:!1,force:!1};let r=!1,o=!1;for(let i=t+1;i<n;i++){let s=b(e,i);r||=s==="r"||s==="R",o||=s==="f"||s==="F"}return{recursive:r,force:o}}function vl(e,t,n,r){let o=n-t-2;if(o<1||o>r.length||!Q(e,t,"--"))return!1;for(let i=0;i<o;i++)if(b(e,t+i+2)!==r[i])return!1;return!0}function qp(e){let t=!1;for(let n=0;n<ee(e);n++){if(oe(b(e,n))){t=!1;continue}if(rt(e,n,"dd")){t=!0,n++;continue}if(!t||!rt(e,n,"of")||!Q(e,n,"of=/dev/"))continue;let r=n+8;if(r<ee(e)&&!J(b(e,r))&&b(e,r)!=="'"&&b(e,r)!=='"')return!0}return!1}function Kp(e){let t=!1,n=!1,r=!1;for(let o=0;o<=ee(e);){let i=b(e,o);if(o===ee(e)||oe(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(J(b(e,a)))l||=b(e,a)===`
7
- `,a++;if(l)n=!1,r=!1;t=!0,o=a;continue}if(!t){o++;continue}if(Q(e,o,"--")&&(o===0||J(b(e,o-1)))&&(!b(e,o+2)||J(b(e,o+2))||oe(b(e,o+2)))){t=!1,n=!1,r=!1,o+=2;continue}if(n||=Q(e,o,"--recursive")&&ot(e,o+11)||Gi(e,o,"recursive"),r||=Q(e,o,"--force")&&ot(e,o+7)||Gi(e,o,"force"),n&&r)return!0;o++}return!1}function Gi(e,t,n){if(!Q(e,t,"--"))return!1;let r=0;while(r<=n.length){let o=b(e,t+r+2);if(!o||J(o)||oe(o))break;if(o!==n[r])return!1;r++}return r>0&&ot(e,t+r+2)}function Yp(e,t){let n=t,r=!1,o=!1;while(n<ee(e)){while(J(b(e,n)))n++;let i=n;while(n<ee(e)&&!J(b(e,n)))n++;if(b(e,i)!=="-"||n-i===2&&Q(e,i,"--"))return!1;let s=Rl(e,i,"recursive"),a=Rl(e,i,"force");if(r&&a||o&&s)return!0;if(r||=s,o||=a,b(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 Rl(e,t,n){return Q(e,t,`--${n}`)&&ot(e,t+n.length+2)||Gi(e,t,n)}function Zp(e,t){if(t>0&&Ot(b(e,t-1)))return-1;let n=t;if(b(e,n)==="\\")n++;if(b(e,n)!=="r")return-1;if(n++,b(e,n)==="\\")n++;if(b(e,n)!=="m"||!J(b(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(b(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=b(e,c)??"",d=(u==="r"||u==="f")&&ot(e,c+1);r||=u==="r",o||=u==="f",i||=u==="r"&&d,s||=u==="f"&&d,a||=(l==="r"&&u==="f"||l==="f"&&u==="r")&&d,l=u}return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a}}function xl(e,t,n){return Mn(e,"reset",tn,!0,(r)=>b(e,r)==="-"&&nn(e,r,t,n)?!0:r)}function Jp(e){return Mn(e,"clean",tn,!0,(t)=>{if(b(e,t)!=="-")return t;if(nn(e,t,"--fo","rce"))return!0;let n=On(e,t,tn);for(let r=t+1;r<n;r++)if(b(e,r)==="f")return!0;return n-1})}function $r(e,t,n){if(!rt(e,t,"git"))return null;let r=t+3;if(!J(b(e,r)))return{commandEnd:-1,next:r};while(J(b(e,r)))r++;while(r<ee(e)){if(oe(b(e,r)))return{commandEnd:-1,next:r};let o=On(e,r,oe);if(rt(e,r,n))return{commandEnd:r+n.length,next:o};if(b(e,r)!=="-")return{commandEnd:-1,next:o};let i=o-r===2&&Q(e,r,"--"),s=Qp(e,r,o);r=o;while(J(b(e,r)))r++;if(i)return{commandEnd:rt(e,r,n)?r+n.length:-1,next:On(e,r,oe)};if(!s)continue;if(r>=ee(e)||oe(b(e,r)))return{commandEnd:-1,next:r};r=On(e,r,oe);while(J(b(e,r)))r++}return{commandEnd:-1,next:r}}function Qp(e,t,n){for(let r of Pe)if(n-t===r.length&&Q(e,t,r))return!0;return!1}function eg(e){return El(e,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function tg(e){return Mn(e,"push",tn,!0,(t)=>{if(b(e,t)!=="-")return t;if(b(e,t+1)==="f"&&!Ot(b(e,t+2))&&!Q(e,t+2,"-with-lease"))return!0;let n=Pl(e,t,"--fo","rce");if(n>=0&&!Q(e,n,"-with-lease"))return!0;return t})}function ng(e){return Mn(e,"push",oe,!1,(t)=>{if(J(b(e,t))&&b(e,t+1)==="+"&&t+2<ee(e)&&!oe(b(e,t+2))&&!J(b(e,t+2)))return!0;if(b(e,t)===":"&&b(e,t+1)==="+")return!0;return t})}function rg(e){return Mn(e,"push",oe,!1,(t)=>{if(b(e,t)==="-"&&nn(e,t,"--de","lete"))return!0;if(J(b(e,t))&&b(e,t+1)===":"&&t+2<ee(e)&&!J(b(e,t+2))&&!oe(b(e,t+2)))return!0;return t})}function og(e){let t=!1,n=!1,r=!1;for(let o=0;o<=ee(e);o++){if(o===ee(e)||oe(b(e,o))){if(n&&r)return!0;t=!1,n=!1,r=!1;continue}if(!t){let a=$r(e,o,"branch");if(a){t=a.commandEnd>=0,o=Math.max(o,(t?a.commandEnd:a.next)-1);continue}}if(!t||b(e,o)!=="-")continue;let i=On(e,o,oe),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(b(e,i)!=="-")continue;if(nn(e,i,"--de","lete"))r=!0;if(nn(e,i,"--fo","rce"))o=!0;if(b(e,i+1)==="-")continue;let s=i+1,a=!1,l=!1,c=!1;while(s<n&&sg(b(e,s))){let u=b(e,s);a||=u==="d"||u==="D",l||=u==="f",c||=u==="D",s++}if(!ot(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 El(e,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function El(e,t){let n=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let r=0;r<ee(e);r++){let o=b(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==="$"&&b(e,r+1)==="("&&(n.length===1||!s&&i.quote!=="'")){n.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),r++;continue}if(!s&&!i.quote&&n.length>1&&o==="("){i.depth++;continue}if(!s&&!i.quote&&n.length>1&&o===")"){if(i.depth--,i.depth===0)n.pop();continue}if(J(o))i.shortActive=!1,i.hasShortFlag=!1;if(!i.outerActive){let a=$r(e,r,t.command);if(a){i.outerActive=a.commandEnd>=0&&J(b(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(nn(e,r,t.longPrefix,t.longOptional))return!0;i.shortActive||=!t.excludedShortStarts.includes(b(e,r+1)??"")}if(i.hasShortFlag||=i.shortActive&&o===t.shortFlag,i.hasShortFlag&&ot(e,r+1))return!0;if(tn(o))i.outerActive=!1}return!1}function Mn(e,t,n,r,o){let i=!1;for(let s=0;s<ee(e);s++){let a=b(e,s),l=n(a);if(!i&&!l){let c=$r(e,s,t);if(c){i=c.commandEnd>=0&&(!r||J(b(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(b(e,u)))i=!1;s=c}if(l)i=!1}return!1}function lg(e){let t=!1;for(let n=0;n<ee(e);n++){if(Fi(b(e,n))){if(t)return!0;t=!1;continue}if(!t){let r=$r(e,n,"restore");if(r){t=r.commandEnd>=0,n=Math.max(n,(t?r.commandEnd:r.next)-1);continue}}if(t&&b(e,n)==="-"&&b(e,n+1)==="-"&&(Q(e,n+2,"staged")||Q(e,n+2,"help")))t=!1}return t}function _l(e,t){let n=!1;for(let r=0;r<ee(e);r++){let o=b(e,r),i=t?Fi(o):oe(o);if(n&&J(o)&&b(e,r+1)==="-"&&rt(e,r+2,"delete"))return!0;if(i){n=!1;continue}if(rt(e,r,"find"))n=!0,r+=3}return!1}function On(e,t,n){let r=t;while(r<ee(e)&&!J(b(e,r))&&!n(b(e,r)))r++;return r}function Pl(e,t,n,r){if(!Q(e,t,n))return-1;let o=t+n.length;for(let i=0;i<r.length&&b(e,o)===r[i];i++)o++;return ot(e,o)?o:-1}function nn(e,t,n,r){return Pl(e,t,n,r)>=0}var wl=[{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"}],Dn=new Set(wl.map((e)=>e.id)),jr=wl,cg=new Map(jr.map((e)=>[e.id,e.intent])),Al=new Set(jr.filter((e)=>e.catastrophic).map((e)=>e.id));function C(e,t){return{id:e,reason:t,intent:cg.get(e)??"manual_only"}}function I(e,t){if(!e)return null;if(Al.has(e.id))return e;if(t?.destructiveCommandProtectionEnabled===!1)return null;let n=t?.effectiveDestructiveCommandRules[e.id];return n&&!n.enabled?null:e}function te(e,t,n){if(Al.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function zi(e,t){return Object.freeze(Object.fromEntries(jr.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 Tl(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:zi(e,t)})}function it(e,t){kn(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},{regex:/\b(?:curl|wget|fetch|aria2c|https?|xhs?|ncat|netcat|nc)\b(?:[^\n|;&]|\\\n)*\|(?:\s|\\\n)*(?:(?:sudo|env|command|builtin)(?:\s+(?:-\S+|\w+=\S*))*\s+)?(?:[^\s|;&]*\/)?(?:ba|da|z|k)?sh(?![^\s;&|])/,label:"download piped to shell",skipForEchoRg:!0}];for(let s of i){if(s.skipForEchoRg&&o)continue;let a=s.caseSensitive?e:n;if(s.regex)ye(t,a);if((s.regex?.test(a)??!1)||s.scan&&Ur(a,s.scan,t))return C("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 ug=/^[A-Za-z_][A-Za-z0-9_]*=/;function kl(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;kn(n,t.source,2);let i={anchored:new RegExp(`^\\$\\{?${o}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${o}(?![A-Za-z0-9_])`)};return Ol(t.nodes,r,i)}function Ol(e,t,n){return e.every((r)=>{if(r.kind==="connector")return!0;if(r.kind==="group"||r.kind==="function")return Ol(r.body.nodes,t,n);if(r.kind==="unknown")return!n.loose.test(r.source);return dg(r,t,n)})}function dg(e,t,n){if(e.nested.some((o)=>n.loose.test(o.source)))return!1;let r=e.words.findIndex((o)=>!ug.test(o.text));return e.words.every((o,i)=>o===t||Il(o.raw,n.anchored,i!==r))&&e.redirections.every((o)=>(!o.heredoc||o.heredoc.quotedDelimiter||!n.loose.test(o.heredoc.body))&&(!o.target||Il(o.target.raw,n.anchored,!0)))}function Il(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 Ml=Object.freeze({maxDerivedTokens:16384}),Dl="Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry.";class Ce 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 Hr(){return{derivedTokens:0}}function De(e,t){if(!Number.isSafeInteger(e.derivedTokens)||e.derivedTokens<0||e.derivedTokens>Ml.maxDerivedTokens||!Number.isSafeInteger(t)||t<0||t>Ml.maxDerivedTokens-e.derivedTokens)throw new Ce;e.derivedTokens+=t}import{isAbsolute as hg,resolve as Ll}from"node:path";import{basename as mg,dirname as fg,join as Bi}from"node:path";var rn=Object.freeze({maxEnvironmentExpansionDepth:64,maxMissingSuffixComponents:256,maxRealpathAttempts:16384,maxProcessedCandidateBytes:4194304});class we extends Error{name="PathCanonicalizationLimitError";constructor(){super("Path canonicalization work limit exceeded.")}}function qr(){return{realpathAttempts:0,processedCandidateBytes:0,resolvedPaths:new Map}}function st(e){return{...qr(),environment:e}}var Vr=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 Kr(e,t){return Ui(e,0,t)}function Ui(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=$i(e,o+2),a=pg(e,o,t);if(a===null){if(Vr.has(s))throw new we;r+=e.slice(o);break}let l=e.slice(o,a+1);r+=gg(l,t,n),o=a+1;continue}let i=$i(e,o+1);if(!i){r+="$",o++;continue}r+=ji(i,n)??`$${i}`,o+=i.length+1}return r}function pg(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>rn.maxEnvironmentExpansionDepth)throw new we;o++;continue}if(e[o]!=="}")continue;if(r--,r===0)return o}return null}function gg(e,t,n){let r=e.slice(2,-1),o=$i(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return ji(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(Vr.has(o))throw new we;return e}if(!Vr.has(o))return e;if(s.endsWith("="))throw new we;let a=ji(o,n),l=s.startsWith(":")?a!==null&&a!=="":a!==null;if(s.endsWith("?")&&!l)throw new we;if(s.endsWith("-")||s.endsWith("?"))return l?a??"":Ui(i.slice(s.length),t+1,n);return l?Ui(i.slice(s.length),t+1,n):""}function $i(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 V(e,t,n=qr()){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>rn.maxRealpathAttempts||n.processedCandidateBytes>rn.maxProcessedCandidateBytes)throw new we;let s=t.realpath(i);if(s!==null){let l=o.length===0?s:Bi(s,...o.reverse());return n.resolvedPaths.set(e,l),l}let a=fg(i);if(a===i){let l=o.length===0?i:Bi(i,...o.reverse());return n.resolvedPaths.set(e,l),l}if(o.length>=rn.maxMissingSuffixComponents){let l=Bi(i,...o.reverse());return n.resolvedPaths.set(e,l),l}o.push(mg(i)),i=a}}function Nl(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>rn.maxRealpathAttempts||n.processedCandidateBytes>rn.maxProcessedCandidateBytes)throw new we;let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function ji(e,t){if(!Vr.has(e))return null;if(e==="HOME")return t.env.get("HOME")??t.home;return t.env.get(e)??null}var Wl=64;function Nn(e,t,n){let r=hg(e)?Ll(e):t?Ll(t,e):void 0;if(!r)return;try{return V(r,n)}catch{return r}}function Fl(e){return!["/dev","/proc","/sys"].some((t)=>e===t||e.startsWith(`${t}/`))}function B(e){return M(e).toLowerCase()}function M(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}var Yr=10,on=20,Mt=/^[a-zA-Z][a-zA-Z0-9_-]*$/,sn=256,ne=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Gl=new Set(["python","python3","python2","node","ruby","perl"]),zl=/^python(?:[23](?:\.\d+)*)?$/,Zr=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 Dt="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",an="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.",Xr=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),yg=new Set(["-p","--print"]),Cg=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"])]]),bg=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),vg=new Map([["python",new Set(["m"])]]),Rg=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"])]]),xg=new Set(["always","default","never"]),Eg=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),_g=/\\\r?\n/g,Pg=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 Jr(e){return eo(e).code}function Qr(e){return eo(e).sources}function Ul(e){return Pg.get(no(e))??[]}function eo(e){let t=no(e[0]??"");if(!Xr.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"&&yg.has(s)){let d=e[i+1];if(d===void 0)return Ne(t,n,r,o);if(d.startsWith("-"))continue;n.push({tokenIndex:i+1,value:d}),r.push({tokenIndex:i+1,kind:"inline-code",value:d}),i++;continue}if(Ag(t,s)){let d=e[i+1];if(d===void 0)return Ne(t,n,r,o);if(n.push({tokenIndex:i+1,value:d}),r.push({tokenIndex:i+1,kind:"inline-code",value:d}),t==="python")return Ne(t,n,r,o);i++;continue}let a=/^--eval=(.*)$/s.exec(s);if(Tg(t)&&a){let d=a[1]??"";n.push({tokenIndex:i,value:d}),r.push({tokenIndex:i,kind:"inline-code",value:d});continue}if(t==="node"){let d=wg(s);if(d){if(d.attached){if(o&&=d.value!=="",d.value!=="")r.push({tokenIndex:i,kind:"module-file",value:d.value});continue}let m=e[i+1];if(m===void 0||m.startsWith("-"))return o=!1,Ne(t,n,r,o);r.push({tokenIndex:i+1,kind:"module-file",value:m}),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(Rg.get(t)?.has(s)){let d=e[i+1];if(d===void 0||d.startsWith("-")&&!(t==="ruby"&&Eg.has(s))||t==="python"&&!xg.has(d))return Ne(t,n,r,o);i++;continue}if(s.startsWith("--"))continue;let l,c=!1;for(let d=1;d<s.length;d++){let m=s[d];if(m===void 0)break;if(vg.get(t)?.has(m)){let f=s.slice(d+1),p=f||e[i+1];if(p!==void 0)r.push({tokenIndex:f?i:i+1,kind:"module-file",value:p});return Ne(t,n,r,o)}if(Cg.get(t)?.has(m)){l=s.slice(d+1)||e[i+1],c=d+1===s.length;break}if(t==="node"&&m==="r"){if(s==="-r"){let f=e[i+1];if(o&&=f!==void 0&&!f.startsWith("-"),o&&f!==void 0)r.push({tokenIndex:i+1,kind:"module-file",value:f});i++}else o=!1;break}if(t==="ruby"&&m==="r"){let f=s.slice(d+1),p=f||e[i+1];if(o&&=p!==void 0,p!==void 0)r.push({tokenIndex:f?i:i+1,kind:"module-file",value:p});if(!f)i++;break}if(t==="perl"&&(m==="M"||m==="m")){let f=s.slice(d+1);if(f)r.push({tokenIndex:i,kind:"module-file",value:f});else if(o=!1,d+1===s.length)i++;break}if(Sg.get(t)?.has(m)){if(d+1===s.length)i++;break}if(bg.get(t)?.has(m)&&d+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 wg(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 Se(e){return Xr.has(no(e))}function to(e,t){return no(e)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(t)}function no(e){let t=M(e).toLowerCase();return zl.test(t)?"python":t}function Ag(e,t){return Xr.get(e)?.has(t)??!1}function Tg(e){return Xr.get(e)?.has("--eval")??!1}function ln(e,t){let n=Og(e,t);if(!Bl(n,t))return!1;ye(t,n);let r=kg(n);if(Bl(r,t))return!0;return ye(t,r),Ig.test(r)}var Ig=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function kg(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 Bl(e,t){if(Br(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(ye(t,e),r.test(e))return!0;if(Br(e,"dd",t))return!0;for(let r of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(ye(t,e),r.test(e))return!0;if(Br(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)=>(ye(t,e),n.some((o)=>Ur(o,r))))}function Og(e,t){return ye(t,e),e.replace(_g,"")}var U=Object.freeze({maxChildAnalyses:1024,maxDerivedTokens:16384,maxDerivedBytes:1048576,maxPlaceholderReplacements:16384}),$l="Parallel command expands beyond CC Safety Net's analysis limits. Reduce the template or explicit argument list and retry.";class oo 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 jl(){return{childAnalyses:0,derivedTokens:0,derivedBytes:0,placeholderReplacements:0}}function be(e,t){let n=t.childAnalyses??0,r=t.derivedTokens??0,o=t.derivedBytes??0,i=t.placeholderReplacements??0;if(ro(e.childAnalyses,n,U.maxChildAnalyses)||ro(e.derivedTokens,r,U.maxDerivedTokens)||ro(e.derivedBytes,o,U.maxDerivedBytes)||ro(e.placeholderReplacements,i,U.maxPlaceholderReplacements))throw new oo;e.childAnalyses+=n,e.derivedTokens+=r,e.derivedBytes+=o,e.placeholderReplacements+=i}function ro(e,t,n){return!Number.isSafeInteger(e)||e<0||e>n||!Number.isSafeInteger(t)||t<0||t>n-e}import{isAbsolute as Ss,normalize as Xy,parse as Jy,posix as uu,resolve as pn,sep as Cs}from"node:path";import{isAbsolute as Mg,join as Hl,normalize as Kl,parse as Dg,sep as Vl}from"node:path";var Ng=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],Lg=`
9
- `;function Ln(e,t){if(qe(e,t))return!0;if(!e.has("TMPDIR"))return!1;return!Hi(e.get("TMPDIR")??"",t)}function at(e,t){if(e.has("TMPDIR"))return Hi(e.get("TMPDIR")??"",t);let n=Vi(e,t);if(n===void 0)return!0;return Hi(n,t)}function Vi(e,t){return Xl(e,t,"TMPDIR")}function Hi(e,t){if(!e)return!1;if(Fg(e))return!1;return qi(e,t)}function qe(e,t){let n=Xl(e,t,"IFS");return n!==void 0&&n!==""&&n!==Lg}function qi(e,t){let n=io(e,t.paths);if(n===null)return!1;return Zl(t).some((r)=>zg(n,r))}function Yl(e,t){let n=io(e,t.paths);if(n===null)return!1;return Zl(t).some((r)=>so(r)===so(n))}var ql=new WeakMap;function Zl(e){let t=ql.get(e);if(t)return t;let n=Wg(e);return ql.set(e,n),n}function Wg(e){let t=Ng.map((r)=>io(r,e.paths)??Kl(r)),n=io(e.tmpdir,e.paths);if(!n)return t;if(process.platform==="win32")return[...t,n];if(process.platform==="darwin"&&Gg(n))return[...t,n];return t}function Fg(e){return/[\s$`*?[]/.test(e)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(e)||/[+@!]\([^)]*\)/.test(e)}function Xl(e,t,n){return e.has(n)?e.get(n):t.env.get(n)}function Gg(e){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(e)}function io(e,t){try{let n=Kl(e);if(!Mg(n))return n;let r=Dg(n).root,o=n.slice(r.length).split(/[\\/]+/).filter(Boolean),i=r;for(let s=0;s<o.length;s++){let a=Hl(i,o[s]??"");if(t.entryKind(a)==="missing")return Hl(a,...o.slice(s+1));let l=t.realpath(a);if(l===null)return null;i=l}return i}catch{return null}}function zg(e,t){let n=so(e),r=so(t);if(n===r)return!0;let o=r.endsWith(Vl)?r:`${r}${Vl}`;return n.startsWith(o)}function so(e){return process.platform==="win32"?e.toLowerCase():e}import{statSync as Ly}from"node:fs";import{isAbsolute as tu,join as Wy,relative as nu}from"node:path";import{isAbsolute as Jl,parse as Bg}from"node:path";var ec=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ae(e){if(!ec.test(e))return null;let t=e.indexOf("=");return{name:e.slice(0,t),value:e.slice(t+1)}}function ao(e){let t=new Map,n=0;while(n<e.length){let r=e[n];if(!r)break;let o=Ae(k(r));if(!o)break;t.set(o.name,o.value),n++}return{words:e.slice(n),envAssignments:t}}function tc(e){let t=e.toLowerCase();return e.includes("=")||t==="sudo"||t==="env"||t==="command"||t==="builtin"}function Nt(e,t,n,r){if(!tc(cn(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 d=0;d<on;d++){let m=Ql(i),f=ao(i);for(let[g,h]of f.envAssignments)s.set(g,h),a.set(g,h);if(i=f.words,i.length===0)break;while(i.length>0&&cn(i).includes("=")&&!$g(i)){let g=jg(cn(i),a,t.env)??Wr(cn(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=cn(i).toLowerCase();if(p!=="sudo"&&p!=="env"&&p!=="command"&&p!=="builtin")break;if(p==="sudo"){let g=Vg(i,t.paths,c);if(i=g.words,g.cwd!==void 0)c=g.cwd}if(p==="env"){let g=Yg(i,c,a,t);if(l.push(...g.envSplitValues??[]),i=g.words,g.cwd!==void 0)c=g.cwd;for(let[h,y]of g.envAssignments)s.set(h,y),a.set(h,y)}if(p==="command")i=Zg(i);if(p==="builtin")i=i.slice(Le(i,1)==="--"?2:1);if(Ql(i)===m)break}let u=ao(i);for(let[d,m]of u.envAssignments)s.set(d,m),a.set(d,m);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 Ql(e){return e.map(k).join(" ")}function cn(e){let t=e[0];return t?k(t):""}function Le(e,t){let n=e[t];return n?k(n):void 0}function $g(e){return ec.test(cn(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 Hg=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function Vg(e,t,n){let r=1,o=n;while(r<e.length){let i=Le(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=Le(e,r+1);o=s?Wn(o,s,t):null,r+=2;continue}if(i.startsWith("--chdir=")){o=Wn(o,i.slice(8),t),r++;continue}if(i.startsWith("-D")&&i.length>2){o=Wn(o,i.slice(2),t),r++;continue}if(i==="-i"||i==="--login"){o=null,r++;continue}if(Hg.has(i)){r+=2;continue}r++}return{words:e.slice(r),cwd:o}}var qg=new Set(["-i","-0","--null"]),Kg=new Set(["-u","--unset","-C","--chdir","-P"]);function Yg(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=Le(e,a);if(!c)break;if(c==="--")return l(a+1);if(c==="-i"||c==="--ignore-environment"||c==="-"){o.clear();for(let d of n.keys())o.set(d,"");o.set("TMPDIR",""),a++;continue}if(qg.has(c)){a++;continue}if(c==="-u"||c==="--unset"){let d=Le(e,a+1);if(d!==void 0)o.set(d,"");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:Le(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(Kg.has(c)){if(c==="-C"||c==="--chdir"){let d=Le(e,a+1);s=d?Wn(s,d,r.paths):null}a+=2;continue}if(c.startsWith("-u=")){a++;continue}if(c.startsWith("-C")&&c.length>2||c.startsWith("--chdir=")){let d=c.startsWith("--chdir=")?c.slice(8):c.startsWith("-C=")?c.slice(3):c.slice(2);s=Wn(s,d,r.paths),a++;continue}if(c.startsWith("-P")){a++;continue}if(c.startsWith("-")){a++;continue}if(!Ae(c))break;while(a<e.length){let d=Ae(Le(e,a)??"");if(!d)break;o.set(d.name,d.value),a++}if(Le(e,a)==="--")a++;return l(a)}return l(a)}function Wn(e,t,n){if(t==="")return null;if(!e&&!Jl(t))return null;let r=Jl(t)?Bg(t).root:n.realpath(e??"/");if(r===null)return null;try{return mt(r,t,n)}catch{return null}}function Zg(e){if(Le(e,1)==="-v")return[...W(["type"]),...e.slice(2)];let t=1;while(t<e.length){let n=Le(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 Xg=/['"\\$`{}#]/;function lo(e,t){if(e.some((r)=>Xg.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 pt(e,t,n){return co(e,t,n).tokens}function Jg(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 gt(e,t,n,r=0){let o=co(e,t,n),i=(o.envSplitValues??[]).flatMap(Jg);if(i.length===0)return o.tokens;let s=[...i,...o.tokens];if(r>=8)return s;return gt(s,t,n,r+1)}function co(e,t,n,r){if(!tc(e[0]??""))return{tokens:[...e],envAssignments:new Map,cwd:n};let o=Nt(W(e),t,n,r);return{tokens:o.words.map(k),envAssignments:o.envAssignments,cwd:o.cwd,envSplitValues:o.envSplitValues}}import{basename as Iy,isAbsolute as ky,normalize as Oy,resolve as Xc}from"node:path";function uo(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Qg(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)=>me(t)))})}function mo(e,t,n){e.push(n),t.reset()}function eh(e,t,n,r,o){if(r<=n)return;e.push({raw:t.slice(n,r),span:{start:n,end:r},provenance:o})}function fo(e){let t=[];return{parts:t,push:(n,r,o)=>eh(t,e,n,r,o)}}function Ki(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 un(e,t,n,r,o,i,s){return Ki({text:r,raw:e.slice(t,n),span:{start:t,end:n},provenance:o,quoted:i,...s?{parts:s}:{}})}function me(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 Qg(t);if(t.kind==="group"||t.kind==="function")return Object.freeze({...t,span:Object.freeze(t.span),body:me(t.body)});return Object.freeze({...t,span:Object.freeze(t.span)})}))})}function Yi(e,t,n){if(t>=n||rc(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!rc(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=nc(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=nc(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 Zi(e,t,n,r){let o=[],i=t;for(let s of r){let a=i,l=!1;while(i<n){let c=th(e,i,n);if((s.stripTabs?c.text.replace(/^\t+/,""):c.text)===s.delimiter){s.attach({body:s.stripTabs?nh(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 nc(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 rc(e){return/[\s;&|<>)]/u.test(e)||e==="`"}function th(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 nh(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var lc=new Set(["&&","||","|","|&"]);function cc(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return me({kind:"program",dialect:"posix",source:e,span:n,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${t.maxInputLength} UTF-16 code units`,span:n}],nodes:[]});let r=ho(e,0,e.length,t,{used:0,max:t.maxWords},0);return me({kind:"program",dialect:"posix",source:e,span:n,status:So(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function ho(e,t,n,r,o,i,s){let a=[],l=[],c=uo(),u=[],d=()=>{if(c.words.length===0&&c.redirections.length===0)return;let f={start:c.start,end:c.end},p=c.words.map((g)=>g.text);mo(a,c,{kind:"command",dialect:"posix",source:e.slice(f.start,f.end),span:f,words:c.words,redirections:c.redirections,nested:c.nested,displayText:l.length>0&&a.length===0?e.slice(t,n):p.join(" ")})},m=t;while(m<n){let f=e[m];if(!f)break;if(s&&f===s)return d(),ac(a,l),{nodes:a,issues:l,next:m+1,closed:!0,limited:!1,pendingHeredocs:u};if(Co(f)){if(f===`
14
- `||f==="\r"){d();let E=f==="\r"&&e[m+1]===`
15
- `?m+2:m+1,w=a.at(-1);if(w?.kind!=="connector"||!lc.has(w.operator))a.push(Object.freeze({kind:"connector",operator:e.slice(m,E),span:Object.freeze({start:m,end:E})}));if(u.length>0){let O=Zi(e,E,n,u.splice(0));l.push(...O.issues),m=O.next;continue}m=E;continue}m++;continue}if(f==="#"){while(m<n&&e[m]!==`
16
- `&&e[m]!=="\r")m++;continue}let p=c.start===-1?Rh(e,m,n):void 0;if(p){if(Ji(a,l,m),i>=r.maxDepth)return dn(a,l,m,"depth-limit",r.maxDepth);if(!Xi(o))return dn(a,l,m,"word-limit",r.maxWords);let E=ho(e,p.braceIndex+1,n,r,o,i+1,"}"),w=E.next,O={start:p.braceIndex+1,end:E.closed?w-1:w},_=oc(e,O,E);if(a.push({kind:"function",name:p.name,span:{start:m,end:w},body:_}),l.push(...E.issues),E.pendingHeredocs.length>0||Gn(E.nodes))l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely",span:{start:m,end:w}});if(u.push(...E.pendingHeredocs),E.limited)return go(a,l,E.next);if(!E.closed)l.push({code:"unclosed-function-body",message:"function body is not closed",span:{start:p.braceIndex,end:w}});m=w;continue}let g=yo(e,m);if(g){if(d(),!yc(a.at(-1)))l.push({code:"unexpected-connector",message:`connector ${g} has no preceding command`,span:{start:m,end:m+g.length}});a.push(Object.freeze({kind:"connector",operator:g,span:Object.freeze({start:m,end:m+g.length})})),m+=g.length;continue}if(f===")"){d(),l.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis",span:{start:m,end:m+1}}),a.push({kind:"unknown",source:f,span:{start:m,end:m+1}}),m++;continue}if((f==="("||f==="{"&&uh(e,m,n))&&c.start===-1){if(Ji(a,l,m),i>=r.maxDepth)return dn(a,l,m,"depth-limit",r.maxDepth);let E=f==="("?")":"}",w=ho(e,m+1,n,r,o,i+1,E),O=w.next,_={start:m+1,end:w.closed?O-1:O},F=oc(e,_,w);if(a.push({kind:"group",style:f==="("?"subshell":"brace",span:{start:m,end:O},body:F}),l.push(...w.issues),w.pendingHeredocs.length>0||Gn(w.nodes))l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely",span:{start:m,end:O}});if(u.push(...w.pendingHeredocs),w.limited)return go(a,l,w.next);if(!w.closed)l.push({code:f==="("?"unclosed-subshell":"unclosed-brace-group",message:`${f} group is not closed`,span:{start:m,end:O}});m=O;continue}let h=(f==="<"||f===">")&&e[m+1]!=="("?sh(e,m):null;if(h){let E=c.words.at(-1),w=E&&E.span.end===m&&/^[0-9]+$/.test(E.raw)?Number(E.raw):void 0;if(w!==void 0)c.words.pop();let O=w===void 0?m:E?.span.start??m;c.start=c.start===-1?m:c.start;let _=m+h.length;while(_<n&&/[ \t]/.test(e[_]??""))_++;let F=e[_],Z=_>m+h.length&&F==="#",X=!F||Co(F)||!!yo(e,_)||F===s||F===")"||Z||(F==="<"||F===">")&&e[_+1]!=="(",j=h==="<<"||h==="<<-"?Yi(e,_,n):void 0,G=j?{word:un(e,_,j.next,j.delimiter,"literal",j.quoted),nested:[],issues:[],next:j.next,limited:!1}:!X?Qi(e,_,n,r,o,i):void 0;if(G){if(l.push(...G.issues),G.limited)return go(a,l,G.next);if(!Xi(o))return dn(a,l,G.next,"word-limit",r.maxWords)}let R=G?.next??m+h.length,A={kind:"redirection",operator:h,span:{start:O,end:R},...w===void 0?{}:{fd:w},...G?{target:G.word}:{}};if(c.redirections.push(A),h==="<<"||h==="<<-")if(!j)l.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word",span:{start:m,end:m+h.length}});else{if(j.ambiguous||j.delimiter.length===0)l.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely",span:j.span});let z=c.nested;u.push({delimiter:j.delimiter,quotedDelimiter:j.quoted,stripTabs:h==="<<-",declarationSpan:{start:O,end:R},attach:(S)=>{if(A.heredoc=S,S.quotedDelimiter)return;z.push(...oh(e,S.bodySpan.start,S.bodySpan.end,r,o,i+1))}})}else if(!G)l.push({code:"missing-redirection-target",message:`redirection ${h} requires a target word`,span:{start:m,end:m+h.length}});if(G)c.nested.push(...G.nested);c.end=R,m=R;continue}if(c.start===-1)Ji(a,l,m);let y=Qi(e,m,n,r,o,i);if(l.push(...y.issues),y.limited)return go(a,l,y.next);let x=fh(c.words)?Ch(e,y.word,o.max-o.used,r.maxDepth,r.maxInputLength):void 0;if(x?.limitCode)return dn(a,l,y.next,x.limitCode,x.limitCode==="word-limit"?r.maxWords:x.limitCode==="depth-limit"?r.maxDepth:r.maxInputLength);let P=x?.words??[y.word];for(let E of P){if(!Xi(o))return dn(a,l,y.next,"word-limit",r.maxWords);c.words.push(E)}c.start=c.start===-1?m:c.start,c.end=y.next,c.nested.push(...y.nested),m=y.next>m?y.next:m+1}return d(),ac(a,l),l.push(...xh(u)),{nodes:a,issues:l,next:m,closed:s===void 0,limited:!1,pendingHeredocs:[]}}function oc(e,t,n){return{kind:"program",dialect:"posix",source:e.slice(t.start,t.end),span:t,status:So(n.issues,n.limited),issues:n.issues,nodes:n.nodes}}function Qi(e,t,n,r,o,i){let s="",a=t,l=!1,c="literal",u=[],d=[],m=!1;while(a<n){let f=e[a],p=(f==="<"||f===">")&&e[a+1]==="(";if(!f||Co(f)||(f===";"||f==="|"||f==="&")&&yo(e,a)||(f==="<"||f===">")&&!p)break;if(f===")")break;if(f==="'"){l=!0;let h=e.indexOf("'",a+1);if(h===-1||h>=n){s+=e.slice(a+1,n),d.push({code:"unclosed-single-quote",message:"single-quoted word is not closed",span:{start:a,end:n}}),a=n;break}s+=e.slice(a+1,h),a=h+1;continue}if(f==='"'){l=!0;let h=rh(e,a,n,r,o,i);if(s+=h.text,u.push(...h.nested),d.push(...h.issues),m||=h.limited,c=Fn(c,h.provenance),a=h.next,m)break;continue}if(e.startsWith("$'",a)){l=!0;let h=ah(e,a+2,n);if(s+=h.text,d.push(...h.issues),!h.closed)d.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed",span:{start:a,end:n}});a=h.next;continue}if(f==="\\"){let h=e[a+1];if(!h){d.push({code:"trailing-escape",message:"escape has no following character",span:{start:a,end:a+1}}),a++;break}if(h===`
17
- `){a+=2;continue}s+=h,a+=2;continue}let g=f==="$"||f==="<"||f===">"||f==="`"?bo(e,a,n,r,o,i):null;if(g){let h=uc(g,u,d);if(m||=h.limited,c=Fn(c,h.provenance),a=h.next,m)break;continue}if(f==="$"){let h=fc(e,a,n,s,c);s=h.text,c=h.provenance,a=h.next;continue}if(f==="*"||f==="?"||f==="[")c=Fn(c,"glob");s+=f,a++}return{word:un(e,t,a,s,c,l,c==="literal"?void 0:ch(e,t,a)),nested:u,issues:d,next:a,limited:m}}function rh(e,t,n,r,o,i){let s="",a="literal",l=[],c=[],u=!1,d=t+1;while(d<n){let m=e[d];if(m==='"')return{text:s,provenance:a,nested:l,issues:c,next:d+1,limited:u};if(m==="\\"&&e[d+1]){let p=e[d+1]??"";if(p===`
18
- `){d+=2;continue}if(p==="\r"&&e[d+2]===`
19
- `){d+=3;continue}s+=["$","`",'"',"\\"].includes(p)?p:`\\${p}`,d+=2;continue}if(e.startsWith("$((",d)){let p=es(e,d+3,n,"))"),g=p===-1?n:p+2;if(s+=e.slice(d,g),p===-1)c.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:d,end:g}});d=g;continue}let f=bo(e,d,n,r,o,i);if(f){let p=uc(f,l,c);if(d=p.next,u||=p.limited,a=Fn(a,p.provenance),u)return{text:s,provenance:a,nested:l,issues:c,next:d,limited:u};continue}if(m==="$"){let p=fc(e,d,n,s,a);s=p.text,a=p.provenance,d=p.next;continue}s+=m??"",d++}return c.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:t,end:n}}),{text:s,provenance:a,nested:l,issues:c,next:n,limited:u}}function bo(e,t,n,r,o,i){let s=e.startsWith("$((",t),a=e.startsWith("$(",t)&&!s,l=e.startsWith("<(",t)||e.startsWith(">(",t),c=e[t]==="`";if(!s&&!a&&!l&&!c)return null;let u=s?3:c?1:2,d=s?"))":c?"`":")",m=es(e,t+u,n,d),f=m===-1?n:m,p=m===-1?n:m+d.length;if(i>=r.maxDepth)return{program:vh(e,t+u,f,"depth-limit"),next:p,provenance:s?"arithmetic":"command-substitution"};if(s){let x=[],P=[],E=!1,w=t+u;while(w<f){let O=bo(e,w,f,r,o,i+1);if(!O){w++;continue}if(x.push(...O.program.nodes),P.push(...O.program.issues),E||=O.program.status==="limited",w=O.next,E)break}if(m===-1)P.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:t,end:p}});return{program:me({kind:"program",dialect:"posix",source:e.slice(t+u,f),span:{start:t+u,end:f},status:So(P,E),issues:P,nodes:x}),next:p,provenance:"arithmetic"}}let g=ho(e,t+u,f,r,o,i+1),h=m===-1?[{code:"unclosed-command-substitution",message:`${e.slice(t,t+u)} substitution is not closed`,span:{start:t,end:p}}]:[],y=(c||l)&&Gn(g.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions",span:{start:t,end:p}}]:[];return{program:me({kind:"program",dialect:"posix",source:e.slice(t+u,f),span:{start:t+u,end:f},status:So([...g.issues,...h,...y],g.limited),issues:[...g.issues,...h,...y],nodes:g.nodes}),next:p,provenance:"command-substitution"}}function oh(e,t,n,r,o,i){let s=[],a=t;while(a<n){let l=e[a];if(l==="\\"){a+=2;continue}let c=l==="$"||l==="`"?bo(e,a,n,r,o,i):null;if(!c){a++;continue}if(s.push(c.program),a=c.next,c.program.status==="limited")break}return s}function uc(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 es(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,d=Zi(e,u,n,s.splice(0));if(!d.terminated)return-1;a=d.next-1;continue}let c=dc(e,a,t,n,i);if(c!==null){a=c;continue}if(!i.double&&e.startsWith("$((",a)){let u=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]==="-",d=a+(u?3:2);while(d<n&&/[ \t]/.test(e[d]??""))d++;let m=Yi(e,d,n);if(m){s.push({delimiter:m.delimiter,quotedDelimiter:m.quoted,stripTabs:u,declarationSpan:{start:a,end:m.next},attach:()=>{return}}),a=m.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=dc(e,i,t,n,o);if(a!==null){i=a;continue}if(e.startsWith("$(",i)&&!e.startsWith("$((",i)){r++,i++;continue}if(s==="("&&!o.double)r++;if(s!==")"||o.double)continue;if(r--,r===0)return e[i+1]===")"?i:-1}return-1}function dc(e,t,n,r,o){let i=e[t];if(i==="\\"&&!o.single)return t+1;if(!o.double&&i==="'")o.single=!o.single;if(!o.single&&i==='"')o.double=!o.double;if(o.single)return t;if(o.double||i!=="#"||!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 yo(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 Co(e){let t=e.charCodeAt(0);if(t===32||t>=9&&t<=13)return!0;if(t<128)return!1;return/\s/u.test(e)}function mc(e,t,n){if(e[t+1]==="{"){let o=e.indexOf("}",t+2);return o===-1||o>=n?n:o+1}let r=t+1;while(r<n&&/[A-Za-z0-9_?@#$!*-]/.test(e[r]??""))r++;return r===t+1?t+1:r}function 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 po(e,t+1,n,16,2,t+1);if(r==="u")return po(e,t+1,n,16,4,t+1);if(r==="U")return po(e,t+1,n,16,8,t+1);if(/[0-7]/.test(r))return po(e,t,n,8,3,t+1);return{text:r,next:t+1}}function po(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 So(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 fc(e,t,n,r,o){let i=mc(e,t,n);return{text:r+e.slice(t,i),provenance:Fn(o,"variable"),next:i}}function ch(e,t,n){let r=fo(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,d=!s&&(e.startsWith("<(",a)||e.startsWith(">(",a)),m=l==="`";if(c||u||d||m){let f=c?3:m?1:2,p=c?"))":m?"`":")",g=es(e,a+f,n,p),h=g===-1?n:g+p.length;r.push(o,a,"literal"),r.push(a,h,c?"arithmetic":"command-substitution"),a=h,o=h;continue}if(l==="$"){let f=mc(e,a,n);if(f>a+1){r.push(o,a,"literal"),r.push(a,f,"variable"),a=f,o=f;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 Fn(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||Co(e[t+1]??"")||yo(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 pc(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)=>sc(p));if(l===-1)break;if(++s>n)return{limited:!0};let c=o[l]??"",u=sc(c);if(!u||u.kind==="range")return{limited:!0};let d=u.start+c.length-u.end,m=u.alternatives.reduce((p,g)=>p+d+g.length,0);if(i-c.length+m>r||o.length-1+u.alternatives.length>t)return{limited:!0};let f=gc(c,u);o.splice(l,1,...f),i+=m-c.length}if(s===0)return;let a=o.map((l)=>bh(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((h)=>ic(h));if(c===-1)break;if(++a>r)return{limitCode:"depth-limit"};let u=i[c]??"",d=ic(u);if(!d)break;let m=d.start+u.length-d.end,f=d.alternatives.filter((h)=>m+h.length>0),p=f.reduce((h,y)=>h+m+y.length,0);if(s-u.length+p>o)return{limitCode:"brace-expansion-limit"};if(i.length-1+f.length>n)return{limitCode:"word-limit"};let g=gc(u,{...d,alternatives:f});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)=>un(e,t.span.start,t.span.end,c,"literal",!1))}}function ic(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:hc(e,n)}}function sc(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}:Sh(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:hc(e,n)}}function gc(e,t){return t.alternatives.map((n)=>`${e.slice(0,t.start)}${n}${e.slice(t.end)}`)}function hc(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 Sh(e){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(e)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(e)}function bh(e,t){let n=`x${e}`,r=Qi(n,0,n.length,{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){return me({kind:"program",dialect:"posix",source:e.slice(t,n),span:{start:t,end:n},status:"limited",issues:[{code:r,message:"command structure exceeds parser limit",span:{start:t,end:n}}],nodes:[]})}function dn(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 go(e,t,n){return{nodes:e,issues:t,next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function Xi(e){return e.used++,e.used<=e.max}function Rh(e,t,n){let r=e.slice(t,n),o=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(r)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(r),i=o?.[1];if(!o||!i)return;return{name:i,braceIndex:t+o[0].lastIndexOf("{")}}function Gn(e){return e.some((t)=>{if(t.kind==="command")return t.redirections.some((n)=>n.heredoc)||t.nested.some((n)=>Gn(n.nodes));return(t.kind==="group"||t.kind==="function")&&Gn(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 yc(e){return e?.kind==="command"||e?.kind==="group"||e?.kind==="function"}function ac(e,t){let n=e.at(-1);if(n?.kind!=="connector"||!lc.has(n.operator))return;t.push({code:"missing-command-after-connector",message:`connector ${n.operator} requires a following command`,span:n.span})}function Ji(e,t,n){if(!yc(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 Cc=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),_h=new Set(["gc","cat","type","cp","mv","rm"]),Sc=["-rec","-for","-path","-literalpath","-whatif"],Ph=/^\$env:\w/i,wh=/^(?:\$\{?\w+\}?|~)\\./,vo={maxInputLength:131072,maxWords:16384,maxDepth:64};function bc(e){let t=e.toLowerCase().replaceAll("`","");if(![...Cc].some((r)=>t.includes(r))&&!(t.includes("rm")&&Sc.some((r)=>t.includes(r)))&&!t.includes("<#")&&!Ah(t))return!1;let n=Mh(e);return n.invalidComment||n.commands.some(Th)}function Ah(e){if(e.includes("$env:"))return!0;return e.includes("\\")&&(e.includes("$")||e.includes("~"))}function Th(e){let t=e[0]==="&"||e[0]==="."?1:0,n=e[t]?.toLowerCase();if(n&&Cc.has(n))return!0;let r=e.slice(t+1);if(n&&_h.has(n)&&r.some(Ih))return!0;if(n!=="rm")return!1;return r.some((o)=>{let i=o.toLowerCase().split(":",1)[0]??"";return Sc.some((s)=>i.startsWith(s))})}function Ih(e){return Ph.test(e)||wh.test(e)}function vc(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return me({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=is(e,0,e.length,t,0);return me({kind:"program",dialect:"powershell",source:e,span:n,status:Dh(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function is(e,t,n,r,o,i=!1){let s=[],a=[],l=uo(),c=0,u=!1,d=()=>{if(l.words.length===0&&l.redirections.length===0)return;let f={start:l.start,end:l.end};mo(s,l,{kind:"command",dialect:"powershell",source:e.slice(f.start,f.end),span:f,words:l.words,redirections:l.redirections,nested:l.nested,displayText:l.words.map((p)=>p.text).join(" ")})},m=t;while(m<n){let f=e[m];if(!f)break;if(i&&f==="}")return d(),{nodes:s,issues:a,next:m+1,closed:!0,words:c,limited:u};let p=Ec(e,m,n,r.maxDepth);if(p){if(p.issue)a.push(p.issue);if(p.limited)return d(),{nodes:s,issues:a,next:p.next,closed:!1,words:c,limited:!0};m=p.next;continue}if(/\s/.test(f)){if(f==="\r"||f===`
24
- `){d();let y=f==="\r"&&e[m+1]===`
25
- `?m+2:m+1;s.push(ts(e,m,y)),m=y;continue}m++;continue}let g=ss(e,m);if(g){d(),s.push(ts(e,m,m+g.length)),m+=g.length;continue}if(f==="{"){if(d(),o>=r.maxDepth)return a.push(xc(m,r.maxDepth)),{nodes:s,issues:a,next:n,closed:!1,words:c,limited:!0};let y=is(e,m+1,n,r,o+1,!0),x=y.closed?y.next-1:y.next,P=me({kind:"program",dialect:"powershell",source:e.slice(m+1,x),span:{start:m+1,end:x},status:y.limited?"limited":y.issues.length>0?"partial":"complete",issues:y.issues,nodes:y.nodes});if(s.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:m,end:y.next}),body:P})),a.push(...y.issues),!y.closed)a.push({code:"unclosed-script-block",message:"PowerShell script block is not closed",span:{start:m,end:y.next}});c+=y.words,u||=y.limited,m=y.next;continue}if(f==="}"){d(),s.push(ts(e,m,m+1)),m++;continue}if(f===">"||f==="<"){l.start=l.start===-1?m:l.start;let y=e[m+1]===f?m+2:m+1,x=y;while(/[ \t]/.test(e[x]??""))x++;let P=x<n?ns(e,x,n,r,o):void 0,E=P?.next??y;if(l.redirections.push(Object.freeze({kind:"redirection",operator:e.slice(m,y),span:Object.freeze({start:m,end:E}),...P?{target:P.word}:{}})),P)a.push(...P.issues),l.nested.push(...P.nested),c+=P.words,u||=P.limited;l.end=E,m=E;continue}if(f===","){l.start=l.start===-1?m:l.start,l.words.push(Ki({text:",",raw:",",span:{start:m,end:m+1},provenance:"literal",quoted:!1})),l.end=++m;continue}let h=ns(e,m,n,r,o);if(l.start=l.start===-1?m:l.start,l.end=h.next,l.words.push(h.word),a.push(...h.issues),l.nested.push(...h.nested),c+=1+h.words,u||=h.limited,c>r.maxWords)return a.push({code:"word-limit",message:`command exceeds ${r.maxWords} words`,span:{start:m,end:h.next}}),d(),{nodes:s,issues:a,next:h.next,closed:!1,words:c,limited:!0};m=h.next>m?h.next:m+1}return d(),{nodes:s,issues:a,next:m,closed:!i,words:c,limited:u}}function ns(e,t,n,r,o){let i="",s="literal",a=!1,l=[],c=[],u=0,d=!1,m=(p)=>{let g=kh(e,p,n,r,o);return i+=e.slice(p,g.next),c.push(g.program),l.push(...g.program.issues),u+=rs(g.program),d||=g.program.status==="limited",s="command-substitution",g.next},f=t;while(f<n){let p=e[f];if(!p||/\s/.test(p)||ss(e,f)||p===">"||p==="<"||p==="#")break;if(p===",")break;if(p==="`"){let g=e[f+1];if(!g){l.push({code:"trailing-escape",message:"PowerShell escape has no following character",span:{start:f,end:f+1}}),f++;break}i+=g,f+=2;continue}if(e.startsWith("$(",f)){f=m(f);continue}if(p==="'"){a=!0,f++;let g=!1;while(f<e.length){if(e[f]==="'"&&e[f+1]==="'"){i+="'",f+=2;continue}if(e[f]==="'"){g=!0,f++;break}i+=e[f]??"",f++}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=f++,h=!1;while(f<n){let y=e[f];if(y==="`"&&e[f+1]){i+=e[f+1],f+=2;continue}if(y==='"'){h=!0,f++;break}if(e.startsWith("$(",f)){f=m(f);continue}if(y==="$")s=e[f+1]==="("?"command-substitution":"variable";i+=y??"",f++}if(!h)l.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:g,end:e.length}});continue}if(p==="$")s=e[f+1]==="("?"command-substitution":"variable";if(p==="@"&&f===t)s="variable";i+=p,f++}return{word:un(e,t,f,i,s,a,s==="literal"?void 0:Oh(e,t,f)),next:f,issues:l,nested:c,words:u,limited:d}}function kh(e,t,n,r,o){let i=Rc(e,t+2,n),s=i===-1?n:i,a=i===-1?n:i+1;if(o>=r.maxDepth)return{program:me({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:"limited",issues:[xc(t,r.maxDepth)],nodes:[]}),next:a};let l=is(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:me({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 Rc(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 rs(e){let t=0;for(let n of e.nodes){if(n.kind==="group")t+=rs(n.body);if(n.kind==="command"){t+=n.words.length;for(let r of n.nested)t+=rs(r)}}return t}function Oh(e,t,n){let r=fo(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=Rc(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 xc(e,t){return{code:"depth-limit",message:`command structure exceeds parser limit ${t}`,span:{start:e,end:e}}}function Mh(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=Ec(e,r,Math.min(e.length,vo.maxInputLength),vo.maxDepth);if(l){i||=!!l.issue||l.limited,r=l.next;continue}let c=ss(e,r);if(c){s(),r+=c.length;continue}if(a==="{"||a==="}"){s(),r++;continue}let u=ns(e,r,Math.min(e.length,vo.maxInputLength),vo,0);if(u.word.text)n.push(u.word.text);for(let d of u.nested)t.push(...os(d));o++,r=u.next>r?u.next:r+1}return s(),{commands:t,invalidComment:i}}function os(e){return e.nodes.flatMap((t)=>{if(t.kind==="group")return os(t.body);if(t.kind!=="command")return[];return[t.words.map((n)=>n.text),...t.nested.flatMap(os)]})}function ss(e,t){for(let n of["&&","||",";","|"])if(e.startsWith(n,t))return n;return null}function Ec(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 Dh(e,t){if(t)return"limited";if(e.some((n)=>n.code==="unclosed-block-comment"))return"invalid";return e.length>0?"partial":"complete"}function ts(e,t,n){return Object.freeze({kind:"connector",operator:e.slice(t,n),span:Object.freeze({start:t,end:n})})}var Lt=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function We(e,t="auto",n=Lt){if(t==="powershell"||t==="auto"&&bc(e.slice(0,n.maxInputLength)))return vc(e,n);return cc(e,n)}function zn(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 Nh=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ro(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function xo(e){let t=Ro(e.words[0],"time")?1:0,n=t===1&&Ro(e.words[t],"-p")?t+1:t,r=t===1&&Ro(e.words[n],"--")?n+1:n,o=Ro(e.words[r],"!")?r+1:r,i=e.words.slice(o).find((s)=>!Nh.test(s.text));return i?.provenance==="literal"?i.text:void 0}function Bn(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 mn(e){let t={inSingle:!1,inDouble:!1,escaped:!1};for(let n of Lh(e))Bn(n,t);return t.inSingle||t.inDouble}function Lh(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);Bn(s,n)}return t}var Wh=new Set(["&&","||","|&","|","&",";"]),Fh=new Set(["<<","<<<",">|"]),Gh=/[*@#?$!_-]/,zh=/^\w+(?::\w+)*/,as=Object.freeze([]),Bh=Object.freeze([]),Uh=256;function Tc(e,t){let n=t.status==="complete"?new Set(cs(t)):new Set,r=[...n].reduce((s,a)=>s.slice(0,a.start)+" ".repeat(a.end-a.start)+s.slice(a.end),e);if(mn(r))return Eo("unclosed-quote",r,as);let o={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},i=Un(t,{source:r,suppressed:n,flags:o,depth:0,functions:new Map,powershell:t.dialect==="powershell"});if(o.limited)return Eo("structural-limit",r,as);if(o.invalid)return Eo("invalid",r,as);return Eo("complete",r,i,o.assignmentFallbacks)}function Eo(e,t,n,r=Bh){return Object.freeze({status:e,source:t,entries:Object.freeze(n),assignmentFallbacks:Object.freeze(r)})}function Un(e,t){return e.nodes.flatMap((n,r)=>$h(n,e,r,t)).sort((n,r)=>n.start-r.start).flatMap((n)=>[...n.entries])}function $h(e,t,n,r){if(e.kind==="connector")return[{start:e.span.start,entries:[Fe(Kh(e.operator))]}];if(e.kind==="unknown")return[{start:e.span.start,entries:[Fe(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?_o("{"):Fe("("),...Un(e.body,a),...s?[i?_o("}"):Fe(")")]:[]]}]}let o=Zh(e,r.functions);if(o){if(r.depth>=Lt.maxDepth||++r.flags.expansions>Uh)return r.flags.limited=!0,[];return[{start:e.span.start,entries:[..._c(e,r),_o(";"),...Un(o,{...r,depth:r.depth+1}),_o(";")]},...Pc(e,t,n,r)]}return[{start:e.span.start,entries:_c(e,r)},...Pc(e,t,n,r)]}function _c(e,t){return[...e.words.map((n)=>({start:n.span.start,entries:kc(n,e,t,!1)})),...e.redirections.map((n)=>({start:n.span.start,entries:jh(n,e,t)}))].sort((n,r)=>n.start-r.start).flatMap((n)=>n.entries)}function jh(e,t,n){let r=e.operator==="<<-"?"<<":e.operator,o=e.target?kc(e.target,t,n,!0):[],i=o[0],s=i?.kind==="word"?i.text:void 0;return[...e.fd===void 0?[]:[us(String(e.fd))],Object.freeze({kind:"redirection",operator:r,role:Yh(r),targetOrder:Fh.has(r)?"legacy-segment":"immediate",...s===void 0?{}:{target:s}}),...s===void 0?o:o.slice(1)]}function Pc(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=[us(s.delimiter),.../[\r\n]/.test(r.source[s.terminatorSpan.end]??"")?[Fe(";")]:[]];if(r.suppressed.has(s.bodySpan))return[{start:s.bodySpan.start,entries:a}];return[{start:s.bodySpan.start,entries:[...Ic(r.source.slice(s.bodySpan.start,s.bodySpan.end),r),...a]}]}),...o.some((i)=>!i.heredoc&&i.target)?Hh(t,n,r):[]]}function Hh(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:Ic(n.source.slice(r.span.end,e.span.end),n)}]}function Ic(e,t){if(t.depth>=Lt.maxDepth)return t.flags.limited=!0,[];let n=We(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=Un(n,{source:e,suppressed:new Set,flags:r,depth:t.depth+1,functions:new Map,powershell:!1});return t.flags.limited||=r.limited,t.flags.expansions=r.expansions,o}function kc(e,t,n,r){let o=[],i={single:!1,double:!1},s="",a=!1,l=()=>{if(a&&!r)o.push(Fe("glob"));else if(s!==""||e.quoted&&o.length===0)o.push(us(s));s="",a=!1};for(let c of e.parts){if(c.provenance!=="command-substitution"&&c.provenance!=="arithmetic"){for(let f of ls(c.raw,i,n.flags,n.powershell)){if(typeof f==="string"){l(),o.push(Fe(f));continue}s+=f.text,a||=f.glob}continue}if(i.double){let f=n.source.slice(c.span.start,c.span.end);s+=ls(f,{single:!1,double:!0},n.flags,n.powershell).map((p)=>typeof p==="string"?p:p.text).join("");continue}let u=t.nested.find((f)=>f.span.start>=c.span.start&&f.span.end<=c.span.end),d=u?Un(u,n):[];if(c.raw.startsWith("`")){s+="${}",l(),o.push(...d);continue}if(c.raw.startsWith("<(")||c.raw.startsWith(">(")){l(),o.push(c.raw.startsWith("<(")?Fe("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),...d,...c.raw.endsWith(")")?[Fe(")")]:[]);continue}let m=c.raw.startsWith("$((")?2:1;s+="${}",l(),o.push(...Array.from({length:m},()=>Fe("(")),...d,...c.raw.endsWith(")".repeat(m))?Array.from({length:m},()=>Fe(")")):[])}return l(),o}function ls(e,t,n,r){let o=[],i="",s=!1,a=0;while(a<e.length){let l=e[a]??"";if(!t.single&&!t.double&&(l==="("||l===")")){o.push({text:i,glob:s},l),i="",s=!1,a++;continue}if(r&&l==="`"&&!t.single){i+=e[a+1]??"",a+=2;continue}if(t.single){if(l==="'")t.single=!1;else i+=l;a++;continue}if(t.double){if(l==='"'){t.double=!1,a++;continue}if(!r&&l==="\\"){let c=e[a+1]??"";i+=['"',"\\","$"].includes(c)?c:`\\${c}`,a+=2;continue}if(l==="$"){let c=wc(e,a,t,n,r);i+=c.text,a=c.next;continue}i+=l,a++;continue}if(l==="'"||l==='"'){t.single=l==="'",t.double=l==='"',a++;continue}if(!r&&l==="\\"){let c=e[a+1]??"";s||=c==="*"||c==="?",i+=c,a+=2;continue}if(l==="$"){let c=wc(e,a,t,n,r);i+=c.text,a=c.next;continue}s||=l==="*"||l==="?",i+=l,a++}return[...o,{text:i,glob:s}]}function wc(e,t,n,r,o){let i=e[t+1];if(i==="{"){let a=qh(e,t+2);if(a===-1)return r.invalid=!0,{text:"",next:e.length};let l=e.slice(t,a+1);return Vh(l,n,r,o),{text:l,next:a+1}}if(i!==void 0&&Gh.test(i))return{text:`\${${i}}`,next:t+2};let s=(o?zh:/^\w*/).exec(e.slice(t+1))?.[0]??"";return{text:`\${${s}}`,next:t+1+s.length}}function Vh(e,t,n,r){let o=e.slice(2,-1),i=/^[A-Za-z_][A-Za-z0-9_]*/.exec(o)?.[0];if(!i)return;let s=o.slice(i.length),a=[":=","="].find((c)=>s.startsWith(c));if(!a)return;let l=ls(s.slice(a.length),{...t},n,r);n.assignmentFallbacks.push(...l.flatMap((c)=>typeof c==="string"||!c.text?[]:[c.text]))}function qh(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 Kh(e){return/^[\r\n]+$/.test(e)?";":e}function Fe(e){return Object.freeze({kind:"operator",operator:e,boundary:Wh.has(e)})}function _o(e){return Object.freeze({kind:"operator",operator:e,boundary:!0})}function us(e){return Object.freeze({kind:"word",text:e})}function Yh(e){if(e==="<<"||e==="<<<")return"here-data";if(e==="<"||e==="<&")return"file-read";return"file-write"}function cs(e){return e.nodes.flatMap((t,n)=>{if(t.kind==="group"||t.kind==="function")return cs(t.body);if(t.kind!=="command")return[];let r=t.nested.flatMap((s)=>cs(s)),o=e.nodes[n+1];if(o?.kind==="connector"&&(o.operator==="|"||o.operator==="|&")||!Jh(t))return r;return[...r,...t.redirections.flatMap((s)=>s.heredoc?.quotedDelimiter?[s.heredoc.bodySpan]:[])]})}function Zh(e,t){let n=xo(e);return n===void 0?void 0:t.get(n)}function ht(e,t){return e!==void 0&&e.provenance==="literal"&&!e.quoted&&e.raw===e.text&&e.text===t}function Xh(e){if(ht(e.words[0],"git"))return ht(e.words[1],"commit");if(!ht(e.words[0],"gh")||!ht(e.words[2],"create"))return!1;return ht(e.words[1],"pr")||ht(e.words[1],"issue")}function Jh(e){return(ht(e.words[0],"cat")||ht(e.words[0],"tee")||Xh(e))&&!e.words.some(Ac)&&!e.redirections.some((n)=>Ac(n.target))}function Ac(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}import{types as Qh}from"node:util";var ey=new Set(["applypatch","patch"]),ty=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),ny=new Set(["grep","grepsearch","rg"]),ry=new Set(["find","findbyname","glob"]),oy=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),iy=new Set(["command","diff","input","patch","patchtext"]),Oc=new TextEncoder,sy=new TextDecoder,ay=/\s/,ly=64;class Hn extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var $n=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Wc(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function wo(e){return oy.has(Wc(e))}function vw(e){let t=Wc(e);if(ey.has(t))return"patch";if(ny.has(t))return"grep";if(ry.has(t))return"glob";if(ty.has(t))return"path";return"unknown"}function Ao(e){if(!e||typeof e!=="object")return;jc(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)Ke();return}if(t.get||t.set)Ke();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function Fc(e,t){return Gc(e,t,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Gc(e,t,n,r){let o=$c(e,n,r);if(!o)return[];let i=o.entries.flatMap(([s,a])=>{let l=Gc(a,t,n,r+1);return typeof a==="string"&&t.has(zc(s))?[a]:l});return n.ancestors.delete(o.object),i}function zc(e){return e.replace(/-/g,"_").toLowerCase()}function Bc(e){return Uc(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(uy)}function Uc(e,t,n,r){let o=$c(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>Uc(a,o.array?t:iy.has(zc(s)),n,r+1));return n.ancestors.delete(o.object),i}function cy(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>$n.maxDepth||t.nodes>$n.maxNodes)Ke();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>$n.maxStringBytes||t.stringBytes>$n.maxAggregateStringBytes)Ke()}function $c(e,t,n){if(cy(e,t,n),!e||typeof e!=="object")return null;let r=jc(e);if(t.ancestors.has(e))Ke();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>$n.maxKeys)Ke();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)Ke();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function jc(e){if(Qh.isProxy(e))Ke();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)Ke();return t}function Ke(){throw new Hn}function uy(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=dy(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,d=c.startsWith(" ")||c.startsWith("+")?1:0;if(i=Math.max(0,i-u),s=Math.max(0,s-d),i===0&&s===0)a();continue}if(c.startsWith("*** ")){a(),t.push(...ds(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...ds(c));continue}if(c.startsWith("--- ")){let u=n[l+1]??"";if(!u.startsWith("+++ "))continue;t.push(...fs(Po(c.slice(4),!0),Po(u.slice(4),!0))),l++;continue}if(!r)t.push(...ds(c))}return t}function dy(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 ds(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return Lc(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return Lc(n[1]);if(e.startsWith("diff --git "))return my(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return Nc(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return Nc(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return Sy(i[1]);return[]}function my(e){let t=fy(e);if(t.length===2&&t[0]&&t[1])return fs(t[0],t[1]);let n=py(e);return n?fs(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function fy(e){let t=[],n=0;while(n<e.length&&t.length<2){while(Wt(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&&!Wt(e[n]))n++;t.push(e.slice(i,n));continue}let o=Hc(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(Wt(e[n]))n++;return n===e.length?t:[]}function py(e){let t=0;while(t<e.length&&Wt(e[t]))t++;let n=e.length;while(n>t&&Wt(e[n-1]))n--;let r=0,o=t;while(o<n){if(!Wt(e[o])){o++;continue}let i=o;while(o<n&&Wt(e[o]))o++;if(i===t||o===n)continue;if(r++,r>ly)Ke();if(gy(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function gy(e,t,n,r,o){if(ms(e,t,n,r,o))return!0;let i=Mc(e,"/",t,n),s=Mc(e,"/",r,o);if(i<=t||s<=r)return!1;if(ms(e,t,i,r,s))return!1;return ms(e,i+1,n,s+1,o)}function ms(e,t,n,r,o){if(n-t!==o-r)return!1;for(let i=0;i<n-t;i++)if(e[t+i]!==e[r+i])return!1;return!0}function Mc(e,t,n,r){for(let o=n;o<r;o++)if(e[o]===t)return o;return-1}function Wt(e){return e!==void 0&&ay.test(e)}function Hc(e,t,n){let r=[],o=t+1;while(o<e.length){let i=e[o]??"";if(i===n)return{value:sy.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...Oc.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(...Oc.encode(hy(s[0]??""))),o+=2}return null}function hy(e){return{a:"\x07",b:"\b",f:"\f",n:`
30
- `,r:"\r",t:"\t",v:"\v"}[e]??e}function yy(e){return jn(by(e))}function fs(e,t){if(e==="/dev/null")return Dc(t);if(t==="/dev/null")return Dc(e);if(e.startsWith("a/")&&t.startsWith("b/"))return[e.slice(2),t.slice(2)].flatMap(jn);let n=Cy(e,t)??(e===t?Vc(e):null);return[e,t,...n?[n]:[]].flatMap(jn)}function Dc(e){let t=Vc(e);return[e,...t?[t]:[]].flatMap(jn)}function Vc(e){let t=e.indexOf("/");return t>0&&t<e.length-1?e.slice(t+1):null}function Cy(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 Nc(e){return yy(Po(e,!0))}function Sy(e){return jn(Po(e,!1))}function Po(e,t){let n=e.trim(),r=n[0]==='"'||n[0]==="'"?n[0]:void 0;if(r){let o=Hc(n,0,r);if(o&&(t||n.slice(o.end).trim()===""))return o.value}return t?n.split("\t",1)[0]?.trim()??"":n}function by(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function jn(e){return e===""||e==="/dev/null"?[]:[e]}function Lc(e){let t=e.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return t===""||t==="/dev/null"?[]:[t]}var qc=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Kc=new Set([...qc,"glob"]),vy=new Set([...Kc,"pattern"]),Ry=[],Yc={parseCommand:We,projectShellSyntax:Tc};class yt extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Vn(e,t={}){let n=xy({...Yc,...t}),r=Ao(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((d)=>d.source===a.source);if(l!==-1){let d=s[l];if(!d)return s;return s[l]={...d,usages:[...d.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:Ey(e),store:n}}function ue(e,t){return e.commands.find((n)=>n.usages.includes(t))}function Ye(e){if(!e.includes("$"))return e;return Kr(e,Me())}function xy(e={}){let t={...Yc,...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 d=t.parseCommand(a,l);return r.set(c,d),d};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 m=o.get(c);if(m)return m;let f={status:"structural-limit",source:a,entries:Ry,assignmentFallbacks:[]};return o.set(c,f),f}let u=n.get(a);if(u)return u;let d=t.projectShellSyntax(a,c);return n.set(a,d),d},getCommandProgram:i}}function Ey(e){let t=e.route.kind==="grep"?Kc:e.route.kind==="glob"?vy:qc;return[...Fc(e.input,t),...e.route.kind==="patch"?Bc(e.input):[]]}function fe(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 _y=new Map([["bash",new Set(["O","o"])],["dash",new Set(["o"])],["ksh",new Set(["o"])],["sh",new Set(["o"])],["zsh",new Set(["o"])]]),Py=new Map([["zsh",new Set(["o"])]]),wy=new Map([["bash",new Set(["--init-file","--rcfile"])]]);function Zc(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=wy.get(e);if(Ty(r,s))continue;if(!s?.has(r))continue;if(t[n+1]===void 0)return null;n++;continue}let o=Ay(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 Ay(e,t){let n=_y.get(e),r=Py.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 Ty(e,t){return t!==void 0&&[...t].some((n)=>e.startsWith(`${n}=`))}var My=new Set(["-S","--suffix"]);function fn(e,t,n,r){if(e.status==="structural-limit")throw new yt;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=Dy(i,o,n,r.normalizeCwd),i=[];continue}if(s.kind==="redirection"){if(s.role==="file-write"&&s.target&&r.isRedirectionTarget(ve(s.target,o.variables),o))return s.target;continue}i.push(s.text)}return r.findSegmentTarget(i,o)}function ve(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(n,r,o,i)=>{let s=t.get(r);if(s===void 0)return n;let a=o.startsWith(":")?s!=="":!0;if(o.endsWith("-"))return a?s:ve(i,t);return a?ve(i,t):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(n,r)=>t.get(r)??n).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(n,r)=>t.get(r)??n)}function qn(e){return e.length>0&&e.every((t)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t))}function Jc(e,t,n){let r=n.environment.home,o=Kr(e.trim(),n.environment).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?Xc(r,o.slice(2)):o,s=he(i);return Oy(ky(s)?s:Xc(t,s))}function ie(e,t,n){let r=Jc(e,t,n);if(!r)return"";return V(r,n.environment.paths,n).replace(/\\/g,"/")}function Qc(e,t,n,r){let o=Jc(e,t,n);if(!o)return null;if(r(Iy(o)))return V(o,n.environment.paths,n).replace(/\\/g,"/");let i=Nl(o,n.environment.paths,n);return i===null?null:i.replace(/\\/g,"/")}function To(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&&My.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 Dy(e,t,n,r){let o=qn(e)?new Map([...t.variables,...Ny(e,t.variables)]):t.variables,i=pt([...e],n.environment),s=M(i[0]??"").toLowerCase()==="cd"?i[1]:void 0;return{cwd:!s||s==="-"?t.cwd:r(ve(s,o),t.cwd,n),variables:o}}function Ny(e,t){return e.flatMap((n)=>{let r=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(n),o=r?.[2]?.startsWith("=")?r[2].slice(1):void 0;return r?.[1]!==void 0&&o!==void 0?[[r[1],ve(o,t)]]:[]})}var Te="Git metadata and hooks are protected. Ask the user before modifying them.";function ru(e,t=gs([e.invocation.context.executionCwd,e.invocation.context.configCwd])){let n=st(Me()),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(wo(e.invocation.toolName))return null;let s=e.paths.find((a)=>Uy(a,r,t,n));return s?{target:s}:null}if(e.invocation.route.kind!=="command")return null;let o=ue(e,"input-candidate");if(!o)return null;let i=fn(o.shell,r,n,{findSegmentTarget:(s,a)=>jy(s,a,t,n),isRedirectionTarget:(s,a)=>$y(s,a.cwd,t,n),findMalformedTarget:()=>null,normalizeCwd:ie});return i?{target:i}:null}function gs(e,t=st(Me())){let n=[...new Map(e.filter((r)=>typeof r==="string"&&r!=="").flatMap((r)=>{let o=In(ie(r,r,t));return o?[[Ge(o),{dotGitPath:o,cwd:r}]]:[]})).values()].flatMap((r)=>Fy(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 Fy(e,t,n){try{let r=ie(e,t,n),o=Ly(e),i=o.isFile()?r:null,s=o.isFile()?Li(e):null,a=(o.isDirectory()?[r]:[s?.gitDir,s?.commonDir]).flatMap((c)=>c?[Ge(ie(c,t,n))]:[]),l=[...new Set(o.isDirectory()?[Ge(e.replace(/\\/g,"/")),...a]:a)];return[{entry:Ge(r),markerFile:i?Ge(i):null,directories:l,hooksDirectories:[...new Set(l.flatMap((c)=>{let u=Ge(Wy(c,"hooks"));return[u,Ge(ie(u,t,n))]}))]}]}catch{return[]}}function Ft(e,t,n,r,o,i=!1){if(!n)return!1;let s=Ge(ie(e,t,o)),a=s.replace(/(\/\.?\*+)+$/,"");if(a!==s&&a!==""){if(ps(a,n))return!0;let l=i||s.slice(a.length).includes("/."),c=(u)=>l?Io(u,a):Gy(u,a);if(n.markerFiles.some(c))return!0;return r&&eu(n).some(c)}if(ps(s,n))return!0;return r&&eu(n).some((l)=>Io(l,s))}function Gy(e,t){let n=nu(t,e);if(n===""||n.startsWith("..")||tu(n))return!1;return!n.split(/[\\/]/)[0]?.startsWith(".")}function zy(e,t,n,r){return Ft(e,t,n,!0,r)}function By(e,t,n,r){if(!n)return!1;return ps(Ge(ie(e,t,r)),n)}function Uy(e,t,n,r){if(!n)return!1;return ou(e,t,n,r,n.entries)}function $y(e,t,n,r){if(!n)return!1;return ou(e,t,n,r,n.markerFiles)}function ou(e,t,n,r,o){let i=Ge(ie(e,t,r));return o.includes(i)||su(i,n)}function iu(e,t,n,r){if(!n)return!1;return n.hooksDirectories.some((o)=>e.some((i)=>Io(o,Ge(ie(i,t,r)))))}function ps(e,t){return t.entries.includes(e)||t.directories.includes(e)||su(e,t)}function su(e,t){return t.hooksDirectories.some((n)=>Io(e,n))}function eu(e){return[...e.entries,...e.directories,...e.hooksDirectories]}function Io(e,t){let n=nu(t,e);return n===""||!/^\.\.(?:[\\/]|$)/.test(n)&&!tu(n)}function Ge(e){return process.platform==="win32"?e.toLowerCase():e}function jy(e,t,n,r){if(qn(e))return null;let o=gt([...e],r.environment);if(M(o[0]??"").toLowerCase()!=="mv")return null;let i=To(o.slice(1)),s=i.sources.find((a)=>zy(ve(a,t.variables),t.cwd,n,r));if(s)return s;return i.destination&&By(ve(i.destination,t.variables),t.cwd,n,r)?i.destination:null}import{isAbsolute as hs,join as Hy,normalize as Vy,sep as ko}from"node:path";var au=process.platform==="win32",qy=/[*?]/;function Kn(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function Mo(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=Kn(e.trim(),t);if(!hs(n))return"must be an absolute path or start with ~/";return Yn(n,t)}function Do(e,t){let n=lu(e,t);if(n===null)return"must be a non-empty path string";if(!hs(n))return null;if(Yn(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 Ky="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Yy="cannot cover the guard's own configuration";function lu(e,t){if(typeof e!=="string"||e.trim()==="")return null;return Kn(e.trim().replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function No(e,t){let n=lu(e,t);if(n===null)return"must be a non-empty path string";if(qy.test(n))return"cannot contain glob characters (* or ?); list the exact file or directory";if(!hs(n))return null;if(Yn(n,t)!==null)return Ky;return Zy(n,t)?Yy:null}function Zy(e,t){let n=Oo(e),r=Oo(Hy(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${ko}`)}function Yn(e,t){let n=Oo(e),r=Oo(t);if(n===r)return"cannot be the home directory";let o=n.endsWith(ko)?n:`${n}${ko}`;if(r.startsWith(o))return"cannot contain the home directory";return null}function Oo(e){let t=Vy(e);if(au)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(au?3:1)&&t.endsWith(ko))t=t.slice(0,-1);return t}var Qy=process.platform==="win32",cu=64,eC=16384;function Zn(e){let t=pc(e,cu,cu,eC);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:tC(e)}}function tC(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)=>nC(e.raw,n.span.start-e.span.start))}function nC(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 Gt(e){let t=e.environment.home,n=e.environment.paths,r=st(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:aC(e.allowPaths,t,n,r),protectedGitMetadata:e.protectedGitMetadata,pathCanonicalizationContext:r}}function ze(e,t,n={}){let r=n.targetIsLiteral??!1;if(!r&&t.tmpdirWordSplittingUnsafe&&!n.tmpdirWordSplittingProtected&&cC(e))return{kind:"outside_anchored_cwd"};let o=!r&&fu(e,t.posixShell);if(It(e))return{kind:"outside_anchored_cwd"};if(bs(e,r))return{kind:"root_or_home_target"};if(rC(e,t,r))return{kind:"root_or_home_target"};if(t.resolvedCwd&&Ft(e,t.resolvedCwd,t.protectedGitMetadata,!0,t.pathCanonicalizationContext,!t.posixShell))return{kind:"git_metadata_target"};if(oC(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(lC(e,t,r))return{kind:"temp_target"};let i=t.anchoredCwd;if(i){if(!n.skipHomeCwd&&fC(i,t.environment.home,t.environment.paths,t.pathCanonicalizationContext))return{kind:"home_cwd_target"};if(!n.skipCwdSelf&&pC(e,t.resolvedCwd??i,t.environment.paths,t.pathCanonicalizationContext))return{kind:"cwd_self_target"};if(gC(e,i,t.resolvedCwd??i,o,r,t.environment.paths,t.pathCanonicalizationContext))return{kind:"within_anchored_cwd"}}return{kind:"outside_anchored_cwd"}}function du(e,t,n={}){let{containmentTarget:r,...o}=n;if(ze(e,t,o).kind!=="temp_target")return!1;let i=e.trim();if(sC(i))return!1;if(Yl(i,t.environment))return!1;return![t.anchoredCwd,t.resolvedCwd].some((s)=>hC(r??i,s,t.environment.paths,t.pathCanonicalizationContext))}function bs(e,t=!1){let n=e.trim(),r=uu.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 rC(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=Ss(o)?o:t.resolvedCwd?pn(t.resolvedCwd,o):null;if(!i)return!1;let s=pe(V(i,t.environment.paths,t.pathCanonicalizationContext));if(s===Jy(s).root)return!0;return s===pe(V(t.environment.home,t.environment.paths,t.pathCanonicalizationContext))}catch{return!1}}function pe(e){let t=Xy(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 oC(e,t,n,r,o,i,s,a){let l=e.trim();if(mu(l))return!1;if(!r&&qi(l,a))return!0;return(t||i&&s)&&n&&!o&&iC(l,n)}function iC(e,t){return["$TMPDIR","${TMPDIR}"].some((n)=>{if(e===n)return!0;if(!e.startsWith(`${n}/`))return!1;return!fu(e.slice(n.length+1),t)})}function sC(e){let t=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(e);if(!t)return!1;return uu.normalize(`/${t[1]??""}`)==="/"}function mu(e){return e.split(/[\\/]+/).includes("..")}function aC(e,t,n,r){if(!e?.length)return[];return e.flatMap((o)=>{let i=Kn(o.trim(),t);if(!Ss(i))return[];try{let s=V(i,n,r);if(Yn(s,V(t,n,r)))return[];return[pe(s)]}catch{return[]}})}function lC(e,t,n){if(t.allowRoots.length===0)return!1;let r=e.trim();if(mu(r))return!1;let o=n?r:Kn(r,t.environment.home),i=t.resolvedCwd??t.anchoredCwd,s=Ss(o)?o:i?pn(i,o):null;if(!s)return!1;try{let a=pe(V(s,t.environment.paths,t.pathCanonicalizationContext));return t.allowRoots.some((l)=>a===l||a.startsWith(l.endsWith(Cs)?l:`${l}${Cs}`))}catch{return!1}}function cC(e){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(e)}function fu(e,t=!1){return e.includes("$")||e.includes("`")||uC(e)||t&&dC(e)}function uC(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 dC(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==="{"&&mC(e,n)||(r==="+"||r==="@"||r==="!")&&e[n+1]==="(")return!0}return!1}function mC(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 fC(e,t,n,r){try{return pe(V(e,n,r))===pe(V(t,n,r))}catch{try{return pe(e)===pe(t)}catch{return!1}}}function pC(e,t,n,r){if(e==="."||e==="./"||e===".\\")return!0;try{return pe(V(pn(t,e),n,r))===pe(V(t,n,r))}catch{try{return pe(pn(t,e))===pe(t)}catch{return!1}}}function gC(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 ys(e,t,i,s)}catch{return!1}if(e.startsWith("./")||e.startsWith(".\\")||!e.includes("/")&&!e.includes("\\"))try{return ys(pn(a,e),t,i,s)}catch{return!1}if(e.startsWith("../"))return!1;try{return ys(pn(a,e),t,i,s)}catch{return!1}}function ys(e,t,n,r){try{return pu(V(e,n,r),V(t,n,r))}catch{return!1}}function hC(e,t,n,r){if(!t)return!1;try{return pu(V(t,n,r),V(e,n,r))}catch{return!0}}function pu(e,t){let n=pe(e),r=pe(t);return n.startsWith(`${r}${Cs}`)||n===r}var yC=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),gu="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",CC="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.",hu="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",yu="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",SC="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",bC="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.";function Cu(e,t,n,r=Gt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths})){return vC(e.words.map((o)=>({kind:"word",text:o.text,dynamic:o.provenance!=="literal"})),t,r,n.policy)}function vC(e,t,n,r){let o=e.filter((l)=>l.kind==="word"),i=xC(o),s=o[i];if(!s||!yC.has(OC(s.text)))return null;let a=RC(o.slice(i+1));if(a.whatIfProtected)return null;if(te(r,"powershell.remove-item-pipeline-dynamic-target",n.strict)&&t&&(a.targets.length===0||a.recursive))return C("powershell.remove-item-pipeline-dynamic-target",bC);for(let l of a.targets)if(!It(l.text)&&bs(Rs(l.text)))return C(a.recursive&&a.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",yu);for(let l of a.targets)if(n.resolvedCwd&&Ft(Rs(l.text),n.resolvedCwd,n.protectedGitMetadata,a.recursive,n.pathCanonicalizationContext,!0))return C("powershell.remove-item-git-metadata",Te);if(!a.recursive||!a.force)return null;if(te(r,"powershell.remove-item-recursive-force-dynamic-target",n.strict)&&(a.hasDynamicTarget||a.targets.length===0))return C("powershell.remove-item-recursive-force-dynamic-target",hu);for(let l of a.targets){let c=MC(ze(Rs(l.text),n),n,r);if(c)return c}return null}function RC(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(EC(l))continue;if(s){t.push(vs(l)),i=i||l.dynamic;continue}if(l.text==="--"){s=!0;continue}let c=PC(l.text);if(!c){t.push(vs(l)),i=i||l.dynamic;continue}if(wC(c.name)){let u=c.value?_C(c.value,l):e[++a];if(u?.kind==="word")t.push(vs(u)),i=i||u.dynamic;else i=!0;continue}if(AC(c.name)){n=!0;continue}if(TC(c.name)){r=!0;continue}if(IC(c.name))o=kC(c.value)}return{targets:t,recursive:n,force:r,whatIfProtected:o,hasDynamicTarget:i}}function xC(e){let t=e[0];if(t?.kind==="word"&&t.text==="&"||t?.text===".")return e.length>1?1:0;return 0}function vs(e){return{text:e.kind==="word"?e.text:"",dynamic:e.kind==="word"&&e.dynamic}}function EC(e){return e.kind==="word"&&e.text===","}function Rs(e){let t=e.replace(/\\/g,"/"),n=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(t);return n?`$HOME${t.slice(n[0].length)}`:t}function _C(e,t){return{kind:"word",text:e,dynamic:t.kind==="word"&&(t.dynamic||e.includes("$"))}}function PC(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 wC(e){return"path".startsWith(e)||"literalpath".startsWith(e)}function AC(e){return"recurse".startsWith(e)}function TC(e){return e.length>=2&&"force".startsWith(e)}function IC(e){return e==="wi"||"whatif".startsWith(e)}function kC(e){if(e===void 0||e==="")return!0;let t=e.toLowerCase();return t==="$true"||t==="true"}function OC(e){return e.toLowerCase()}function MC(e,t,n){switch(e.kind){case"root_or_home_target":return C("powershell.remove-item-recursive-force-root-or-home",yu);case"git_metadata_target":return C("powershell.remove-item-git-metadata",Te);case"temp_target":return null;case"dynamic_target":if(!te(n,"powershell.remove-item-recursive-force-dynamic-target",t.strict))return null;return C("powershell.remove-item-recursive-force-dynamic-target",hu);case"home_cwd_target":return C("powershell.remove-item-recursive-force-home-cwd",SC);case"cwd_self_target":return C("powershell.remove-item-recursive-force-cwd-self",gu);case"within_anchored_cwd":if(!te(n,"powershell.remove-item-recursive-force-paranoid",t.paranoid))return null;return C("powershell.remove-item-recursive-force-paranoid",CC);case"outside_anchored_cwd":return C("powershell.remove-item-recursive-force-outside-cwd",gu)}}import{normalize as Xo}from"node:path";var Re=new Set(["awk","gawk","nawk","mawk"]),DC=new Set(["-e","--source"]),NC=new Set(["-F","-v","--assign","--field-separator"]),Su=new Set(["-f","--file"]),LC=new Set(["print","printf","return"]),bu=[{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"}],WC="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 Fo(e,t,n){let r=!1;for(let o of FC(e)){let i=GC(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?C("awk.system-dynamic",WC):null}function Es(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&&DC.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&&(NC.has(a)||Su.has(a))){if(Su.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 Jn(e){return Es(e).sources}function FC(e){return Jn(e).filter((t)=>t.kind!=="program-file").map((t)=>t.value)}function GC(e,t){ye(t,e);let n=e.includes("system")?_s(e,t):null,r=zC(e,t);if(!n&&!r)return null;return{dynamic:!!n?.dynamic||!!r?.dynamic,commands:[...n?.commands??[],...r?.commands??[]]}}function _s(e,t){ye(t,e);let n=[],r=!1,o=!1,i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){i=Wo(e,i,s)?.endIndex??i+1;continue}if(s==="#"){i=vu(e,i+1);continue}if(s==="/"&&Ru(e,i)){i=xu(e,i+1)??i+1;continue}if(!e.startsWith("system",i)){i++;continue}let a=i;if(i+=6,Xn(e[a-1])||Xn(e[i]))continue;let l=Lo(e,i);if(e[l]!=="(")continue;l=Lo(e,l+1);let c=e[l];if(c!=='"'&&c!=="'"){r=!0,o=!0;continue}let u=Wo(e,l,c);if(!u){r=!0,o=!0;continue}if(l=Lo(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 zC(e,t){ye(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 f=Wo(e,i,u);if(f&&c===s)l={...f,startIndex:i};c=f?.endIndex??i+1,i=f?.endIndex??i+1;continue}if(u==="#"){i=vu(e,i+1),s=i,a=null,l=null,c=i;continue}if(u==="/"&&Ru(e,i)){let f=xu(e,i+1);c=f??i+1,i=f??i+1;continue}if(`;
31
- {}`.includes(u)){i++,s=i,a=null,l=null,c=i;continue}if(a===null&&(xs(e,i,"print")||xs(e,i,"printf")))a=i;if(u!=="|"||e[i-1]==="|"||e[i+1]==="|"){if(!/\s/.test(u))c=i+1;i++;continue}let d=e[i+1]==="&"?i+2:i+1,m=Lo(e,d);if(xs(e,m,"getline")){o=!0;let f=$C(s,l,c);if(f===null)r=!0;else n.push(f);c=d,i=d;continue}if(HC(s,a)){o=!0;let f=UC(e,m);if(!f){r=!0,c=d,i=d;continue}if(!BC(e,f.endIndex)){r=!0,c=f.endIndex,i=f.endIndex;continue}n.push(f.value),c=f.endIndex,i=f.endIndex;continue}c=d,i++}if(!o)return null;return{dynamic:r,commands:n}}function Xn(e){return!!e&&/[A-Za-z0-9_]/.test(e)}function Lo(e,t){let n=t;while(/\s/.test(e[n]??""))n++;return n}function BC(e,t){let n=t;while(/[\t\f\v\r ]/.test(e[n]??""))n++;let r=e[n];return!r||`;
32
- }#`.includes(r)}function Wo(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=jC(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 UC(e,t){let n=e[t];if(n!=='"'&&n!=="'")return null;return Wo(e,t,n)}function $C(e,t,n){if(!t)return null;return t.startIndex>=e&&t.endIndex===n?t.value:null}function jC(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 xs(e,t,n){return e.startsWith(n,t)&&!Xn(e[t-1])&&!Xn(e[t+n.length])}function HC(e,t){return t!==null&&t>=e}function vu(e,t){let n=e.indexOf(`
34
- `,t);return n===-1?e.length:n+1}function Ru(e,t){let n=VC(e,t);if(n===-1)return!0;if("{([,;!~=".includes(e[n]??""))return!0;let r=n;while(Xn(e[r-1]))r--;return LC.has(e.slice(r,n+1))}function VC(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function xu(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 Eu=new Set(["rm","find","xargs","parallel"]),qC=new Set(["sudo","env","command","builtin"]),KC=new Set(["git","busybox",...Eu,...ne,...Gl,...Re]);function Go(e,t){let n=e[0];if(!n||!t.transparentWrappers.includes(M(n)))return null;let r=M(n),o=e[1]==="--"?2:1,i=YC(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 YC(e,t,n,r){let o=e[1]==="--",i=[];for(let s=t;s<e.length;s++){let a=e[s];if(!a)continue;if(M(a)!==n&&ZC(a,r))i.push(s);else if(Zr.has(B(a)))break;if(o)break}return i}function ZC(e,t){let n=M(e),r=B(e);return r==="git"||n==="busybox"||zt(e)||Eu.has(n)||t.transparentWrappers.includes(n)||ne.has(r)||e==="$SHELL"||Se(r)||Re.has(r)||t.rules.some((o)=>o.command===n)}function zt(e){return qC.has(e.toLowerCase())}function _u(e){let t=B(e);return KC.has(t)||Se(t)}function Be(e,t){let n=t.policy??{rules:[],transparentWrappers:[]};return zo([...e],t.environment,t.cwd,t.cwd,new Map,new Map(t.envAssignments??[]),n,{iterations:0},!1)}function*zo(e,t,n,r,o,i,s,a,l){let c=co(e,t,n,i);for(let[f,p]of c.envAssignments)i.set(f,p),o.set(f,p);let{tokens:u,cwd:d}=c;if(c.envSplitValues){let f=lo(c.envSplitValues,u);if(!f)throw new Ce;Ps(a),yield*zo(f,t,d,r,o,i,s,a,l);return}if(zt(u[0]??""))throw new Ce;let m=Go(u,s);if(m){for(let f of[m.childIndex,...m.alternativeChildIndices])Ps(a),yield*zo(f===m.childIndex?m.tokens:[...u.slice(f)],t,d,r,new Map(o),new Map(i),s,a,!0);return}if(JC(u)){Ps(a),yield*zo([...u.slice(1)],t,d,r,o,i,s,a,l);return}yield XC(u,d,r,o,i,l)}function XC(e,t,n,r,o,i){return{tokens:e,cwd:t===null?void 0:t??n,wrapperCwd:t,wrapperEnvAssignments:r,envAssignments:o,head:M(e[0]??"").toLowerCase(),wrappedByTransparent:i}}function Ps(e){if(e.iterations>=on)throw new Ce;e.iterations++}function JC(e){return M(e[0]??"").toLowerCase()==="busybox"&&e.length>1}function ws(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"||As(r,"recursive"))t=!0;else if(r==="-f"||As(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 Pu(e){let t=e.indexOf("--");return e.slice(1,t===-1?void 0:t).some((n)=>As(n,"recursive")||/^-[A-Za-z]+$/.test(n)&&/[rR]/.test(n.slice(1)))}function As(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.",eS="find -exec rm -rf is dangerous. Use explicit file list instead.",tS=new Set(["-exec","-execdir","-ok","-okdir"]),nS=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 Bo(e,t){let n=e.map(k),r=rS(e,n,t);if(r)return r;if($o(n,1)&&!iS(e,n,t)){let s=I(C("find.delete",QC),t.policy);if(s)return s}let o=t.derivedCommandWorkBudget??Hr(),i=0;while(i<n.length){let s=n[i],a=Ct(s??"");if(a>0){i+=a+1;continue}if(!lt(s)){i++;continue}De(o,n.length-i-1);let l=Qn(n,i);i=l.nextIndex;let c=aS(l.tokens,t.environment);if(c){let f=I(c,t.policy);if(f)return f}let u=s==="-execdir"||s==="-okdir",d=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,m=d?.id.startsWith("custom.")?d:I(d,t.policy);if(m)return m}return null}function rS(e,t,n){if(!$o(t,1)&&!Ts(t,n.environment))return null;let o=Uo(e)??W(["."]),i=Gt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let s of o){let a=Zn(s);for(let l of a.expandedTargets??[k(s)]){let c=ze(l,i,{targetIsLiteral:a.expandedTargets!==void 0||a.targetIsLiteral,tmpdirWordSplittingProtected:a.tmpdirWordSplittingProtected});if(c.kind==="root_or_home_target")return C("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 C("find.delete-git-metadata",Te)}}if(oS(t)&&i.resolvedCwd&&iu(o.map(k),i.resolvedCwd,i.protectedGitMetadata,i.pathCanonicalizationContext))return C("find.delete-git-metadata",Te);return null}function Ts(e,t){let n=0;while(n<e.length){if(!lt(e[n])){n++;continue}let r=Qn(e,n),o=gt([...r.tokens],t),i=M(o[0]??"").toLowerCase();if((i==="rm"||i==="rmdir")&&o.some((s)=>s.includes("{}")))return!0;n=r.nextIndex}return!1}function oS(e){return e.some((t,n)=>{if(!["-name","-iname"].includes(t))return!1;return e[n+1]?.toLowerCase()==="hooks"})}function iS(e,t,n){if(t.includes("-L")||t.includes("-f")||t.includes("-follow"))return!1;let r=Uo(e);if(!r)return!1;let o=n.envAssignments??new Map,i=Vi(o,n.environment),s=n.trustedTmpdirValue??at(o,n.environment),a=n.allowTmpdirVar??!Ln(o,n.environment),l=Gt({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??qe(o,n.environment),trustedTmpdirValue:s});return r.every((c)=>{let u=Zn(c);if(u.unsafeBraceExpansion)return!1;return(u.expandedTargets??[k(c)]).every((d)=>du(d,l,{containmentTarget:sS(d,i),targetIsLiteral:u.expandedTargets!==void 0||u.targetIsLiteral,tmpdirWordSplittingProtected:u.tmpdirWordSplittingProtected}))})}function sS(e,t){if(!t)return e;return e.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>t)}function Uo(e){let t=(o)=>{let i=e[o];return i?k(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 aS(e,t){let n=pt([...e],t);if(n.length===0)return null;let r=M(n[0]??"");if(r==="busybox"&&n.length>1)n=n.slice(1),r=M(n[0]??"");if(r==="rm"&&Ue(n))return C("find.exec-rm-recursive-force",eS);return null}function Qn(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 $o(e,t){let n=t;while(n<e.length){let r=e[n];if(!r){n++;continue}if(lt(r)){n=Qn(e,n).nextIndex;continue}let o=Ct(r);if(o>0){n+=o+1;continue}if(r==="-delete")return!0;n++}return!1}function Ct(e){return nS.get(e)??(/^-newer[A-Za-z]{2}$/.test(e)?1:0)}function lt(e){return e!==void 0&&tS.has(e)}function*Is(e){for(let t of e.nodes)yield*cS(t)}function lS(e){return Object.freeze([...Is(e)])}function zA(e){return Object.freeze(lS(e).map((t)=>Object.freeze(t.words.map((n)=>n.text))))}function er(e){let t=We(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*cS(e){if(e.kind==="command"){yield e;for(let t of e.nested)yield*Is(t);return}if(e.kind==="group")yield*Is(e.body)}var uS=5,ks="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 de(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 Au(e,t,n){let r=Iu(e,t,n),o=dS(r.entries);if(o.size===0)return{blockedReason:r.blockedReason,expanded:!1,tokens:e};let i=e,s=!1;for(let a=0;a<uS;a++){let{subcommand:l,rest:c}=$e(i),u=l?.toLowerCase();if(!u||!o.has(u))return{blockedReason:r.blockedReason,expanded:s,tokens:i};let d=o.get(u),m=hS(d);if(m===null||m.length===0)return{blockedReason:ks,expanded:!0,tokens:i};i=["git",...m,...c],s=!0}return{blockedReason:ks,expanded:!0,tokens:i}}function Tu(e,t,n){return Iu(e,t,n).entries.some((r)=>r.key.toLowerCase()==="core.sshcommand")}function $e(e){if(e.length===0)return{subcommand:null,rest:[]};let t=e[0];if((t?M(t).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let r=1;while(r<e.length){let o=e[r];if(!o)break;if(o==="--"){let i=e[r+1];if(i&&!i.startsWith("-"))return{subcommand:i,rest:e.slice(r+2)};return{subcommand:null,rest:e.slice(r+1)}}if(o.startsWith("-"))if(Pe.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 dS(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 Iu(e,t,n){if(e.length===0)return{blockedReason:null,entries:[]};let r=e[0];if((r?M(r).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let i=fS(t,n);return{blockedReason:i.blockedReason,entries:[...i.entries,...mS(e,t,n)]}}function mS(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=Os(e[o+1]);if(s)r.push(s);o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=Os(i.slice(2));if(s)r.push(s);o++;continue}if(i==="--config-env"){let s=wu(e[o+1],t,n);if(s)r.push(s);o+=2;continue}if(i.startsWith("--config-env=")){let s=wu(i.slice(13),t,n);if(s)r.push(s);o++;continue}if(Pe.has(i)){o+=2;continue}o++}return r}function fS(e,t){let n=pS(e,t),r=gS(e,t);return{blockedReason:n===null||r===null?ks:null,entries:[...n??[],...r??[]]}}function pS(e,t){let n=_e("GIT_CONFIG_PARAMETERS",e,t);if(n===void 0)return[];let r=[],o=er(n);if(!o)return null;for(let i of o){let s=Os(i);if(!s)return null;r.push(s)}return r}function gS(e,t){let n=Lr(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=_e(`GIT_CONFIG_KEY_${o}`,e,t)?.trim(),s=_e(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i||s===void 0)return null;r.push({key:i,value:s})}return r}function Os(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 wu(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;return{key:e.slice(0,r).trim(),value:_e(e.slice(r+1),t,n)}}function hS(e){let t=e?.trimStart();if(!t||t.startsWith("!"))return null;return er(t)}var yS="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",CS="git checkout --force discards uncommitted changes. Use 'git stash' first.",SS="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",bS="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",vS="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",RS="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",xS="git switch --force discards uncommitted changes. Use 'git stash' first.",ES="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",_S="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",PS="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",wS="git reset --merge can lose uncommitted changes. Use 'git stash' first.",AS="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",TS="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.",IS="git push --force destroys remote history. Use --force-with-lease for safer force push.",kS="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",OS="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",MS="git branch -D force-deletes without merge check. Use -d for safe delete.",DS="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",NS="git merge --abort discards merge conflict resolutions. Use 'git status' first.",LS="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",WS="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",FS="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",GS="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",zS="git worktree remove --force can delete uncommitted changes. Remove --force flag.",ku=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),Ou=new Set(["--recurse-submodules","--track","-t"]),Ms=new Set(["-b","-B","-U"]),Ds=new Set(["-c","-C"]),BS=new Set(["--source","--conflict","--unified","--inter-hunk-context"]),US=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 N(e,t){let n=e.split("=",1)[0]??e;return n.length>=4&&t.startsWith(n)&&n.startsWith("--")&&n.slice(2).length>=2}var gn=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function Du(e){let{subcommand:t,rest:n}=$e(e);if(!t)return null;switch(t.toLowerCase()){case"checkout":return St($S(n));case"switch":return St(jS(n));case"restore":return St(VS(n));case"reset":return KS(n);case"clean":return St(ZS(n));case"rm":return St(XS(n));case"push":return Bt(JS(n));case"branch":return Bt(tb(n));case"stash":return Bt(sb(n));case"worktree":return Bt(ab(n));case"rebase":return St(nb(n));case"merge":return St(rb(n));case"tag":return Bt(ob(n));case"reflog":return Bt(ib(n));default:return null}}function St(e){return e?{...e,localDiscard:!0}:null}function Bt(e){return e?{...e,localDiscard:!1}:null}function $S(e){let{index:t,before:n}=de(e),r=fe(n,{shortOptsWithValue:Ms});if(n.some((i)=>N(i,"--force"))||r.has("-f"))return C("git.checkout-force",CS);for(let i of e){if(i==="-b"||i==="-B"||i==="--orphan")return null;if(N(i,"--pathspec-from-file"))return C("git.checkout-pathspec-from-file",bS)}if(t!==-1){if(n.some((s)=>!s.startsWith("-")))return C("git.checkout-ref-path",SS);return C("git.checkout-double-dash",yS)}if(HS(e).length>=2)return C("git.checkout-ambiguous",vS);return null}function jS(e){let{before:t}=de(e);if(t.some((r)=>N(r,"--discard-changes")))return C("git.switch-discard-changes",RS);let n=fe(t,{shortOptsWithValue:Ds});if(t.some((r)=>N(r,"--force"))||n.has("-f"))return C("git.switch-force",xS);return null}function HS(e){let t=[],n=0;while(n<e.length){let r=e[n];if(!r)break;if(r==="--")break;if(r.startsWith("-"))if(ku.has(r))n+=2;else if(r.startsWith("--")&&r.includes("="))n++;else if(Ou.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("--")&&!US.has(r)&&!ku.has(r)&&!Ou.has(r))n++;else n++;else t.push(r),n++}return t}function VS(e){let t=qS(e);if(t.isTerminal||!t.hasPathspec&&!t.hasPatch||!t.hasWorktree)return null;return t.hasExplicitLocation?C("git.restore-worktree",_S):C("git.restore-unstaged",ES)}function qS(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(BS.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 KS(e){let t=null;for(let n of e){if(N(n,"--hard")){t=C("git.reset-hard",PS);break}if(N(n,"--merge")){t=C("git.reset-merge",wS);break}}if(!t)return null;return YS(e)?Bt(t):St(t)}function YS(e){for(let t of e){if(t==="--")return!1;if(!t.startsWith("-"))return!0}return!1}function ZS(e){for(let n of e)if(n==="-n"||N(n,"--dry-run"))return null;let t=fe(e.filter((n)=>n!=="--"));if(e.some((n)=>N(n,"--force"))||t.has("-f"))return C("git.clean-force",AS);return null}function XS(e){let t=!1,n=!1,r=!1;for(let o of de(e).before){if(N(o,"--no-force")){t=!1;continue}if(N(o,"--force")){t=!0;continue}if(N(o,"--no-cached")){n=!1;continue}if(N(o,"--cached")){n=!0;continue}if(N(o,"--no-dry-run")){r=!1;continue}if(N(o,"--dry-run")){r=!0;continue}let i=fe([o]);t||=i.has("-f"),r||=i.has("-n")}return t&&!n&&!r?C("git.rm-force",TS):null}function JS(e){let{before:t,after:n}=de(e),r=fe(t);if(t.some((s)=>N(s,"--mirror")))return C("git.push-mirror",OS);if(t.some((s)=>N(s,"--force"))||r.has("-f")||Mu(t,n).some(QS))return C("git.push-force",IS);if(t.some((s)=>N(s,"--delete"))||r.has("-d")||Mu(t,n).some(eb))return C("git.push-delete",kS);return null}function Mu(e,t){return[...e.filter((n)=>n!==""&&!n.startsWith("-")),...t]}function QS(e){return e.startsWith("+")||e.includes(":+")}function eb(e){return e.length>1&&e.startsWith(":")}function tb(e){let{before:t}=de(e),n=fe(t),r=n.has("-D")||n.has("-d")||t.some((i)=>N(i,"--delete")),o=n.has("-D")||n.has("-f")||t.some((i)=>N(i,"--force"));if(r&&o)return C("git.branch-force-delete",MS);return null}function nb(e){let{before:t}=de(e);return t.some((n)=>N(n,"--abort"))?C("git.rebase-abort",DS):null}function rb(e){let{before:t}=de(e);return t.some((n)=>N(n,"--abort"))?C("git.merge-abort",NS):null}function ob(e){let{before:t}=de(e);return fe(t).has("-d")||t.some((r)=>N(r,"--delete"))?C("git.tag-delete",LS):null}function ib(e){return e[0]==="delete"?C("git.reflog-delete",WS):null}function sb(e){for(let t of e){if(t==="drop")return C("git.stash-drop",FS);if(t==="clear")return C("git.stash-clear",GS)}return null}function ab(e){let{before:t}=de(e);if(!t.includes("remove"))return null;let r=fe(t);if(t.some((o)=>N(o,"--force"))||r.has("-f"))return C("git.worktree-remove-force",zS);return null}import{execFileSync as lb}from"node:child_process";import{existsSync as Ls,readFileSync as Ws}from"node:fs";import{dirname as cb,isAbsolute as Wu,join as Ns,resolve as Fu}from"node:path";var ub=["/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 Gu(e,t,n,r){let o=db(e,t,n);if(o!==null)return o;let i=mb(t,n);if(i!==null)return i;if(dl(n))return!0;return fb(r)}function db(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=Nu(e[o+1]);if(s!==null)r=s;o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=Nu(i.slice(2));if(s!==null)r=s;o++;continue}if(i==="--config-env"){let s=Lu(e[o+1],t,n);if(s!==null)r=s;o+=2;continue}if(i.startsWith("--config-env=")){let s=Lu(i.slice(13),t,n);if(s!==null)r=s;o++;continue}if(Pe.has(i))o+=2;else o++}return r}function mb(e,t){if(_e("GIT_CONFIG_PARAMETERS",e,t)!==void 0)return!0;let n=Lr(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=_e(`GIT_CONFIG_KEY_${o}`,e,t),s=_e(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i?.trim()||s===void 0)return!0;let a=i.trim().toLowerCase();if(Fs(a))return!0;if(a!=="submodule.recurse")continue;r=tr(s)}return r}function fb(e,t=gb()){let n=pb(e);if(n===null||n)return!0;if(t===null)return!0;try{let r=lb(t,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:hb(process.env),stdio:["ignore","pipe","ignore"]}).trim();return tr(r)}catch(r){return!yb(r)}}function pb(e){let t=Cb(e);if(t===null)return null;for(let n of t){if(!Ls(n))continue;if(vb(n))return!0}return!1}function gb(){for(let e of ub)if(Ls(e))return e;return null}function hb(e){let t={...e};for(let n of Object.keys(t))if(wn(n))delete t[n];return t}function yb(e){return typeof e==="object"&&e!==null&&"status"in e&&e.status===1}function Cb(e){let t=In(e);if(t===null)return null;let n=Sb(t);if(n===null)return null;let r=bb(n);if(r===null)return null;return[Ns(r,"config"),Ns(n,"config.worktree")]}function Sb(e){try{let n=Ws(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 Wu(r)?r:Fu(cb(e),r)}catch{return null}}function bb(e){let t=Ns(e,"commondir");if(!Ls(t))return e;try{let n=Ws(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(n==="")return null;return Wu(n)?n:Fu(e,n)}catch{return null}}function vb(e){let t;try{t=Ws(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(Rb(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=tr(c)}return r}function Rb(e){return e==="include"||e.startsWith("includeif ")}function Nu(e){if(!e)return null;let t=e.indexOf("="),n=(t===-1?e:e.slice(0,t)).toLowerCase();if(Fs(n))return!0;if(n!=="submodule.recurse")return null;let r=t===-1?"true":e.slice(t+1).toLowerCase();return tr(r)}function tr(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function Lu(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;let o=e.slice(0,r).toLowerCase();if(Fs(o))return!0;if(o!=="submodule.recurse")return null;let i=_e(e.slice(r+1),t,n);return i===void 0||tr(i)}function Fs(e){return e==="include.path"||e.startsWith("includeif.")&&e.endsWith(".path")}function zu(e,t,n){if(!t.localDiscard||!n.worktreeMode||gl(n.env,n.envAssignments))return null;let r=hl(e,n.cwd);if(!r.gitCwd||r.hasExplicitGitContext)return null;if(!yl(r.gitCwd))return null;if(xb(e,n,r.gitCwd))return null;return{originalReason:t.reason,gitCwd:r.gitCwd}}function xb(e,t,n){let{subcommand:r,rest:o}=$e(e),i=r?.toLowerCase();if(t.dynamicArguments||Eb(o)||Gu(e,t.env,t.envAssignments,n)||wb(o)||_b(i,o))return!0;return i==="clean"&&Ab(o)>1}function Eb(e){return e.some((t)=>/[$*?[]/.test(t))}function _b(e,t){if(e==="checkout"){let{before:n}=de(t),r=fe(n,{shortOptsWithValue:Ms}),o=n.some((s)=>N(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}=de(t),r=fe(n,{shortOptsWithValue:Ds}),o=n.some((s)=>N(s,"--force"))||n.some((s)=>N(s,"--discard-changes"))||r.has("-f"),i=n.some((s)=>s==="-C"||s.startsWith("-C")||Pb(s))||r.has("-C");return o&&i}return!1}function Pb(e){let t=e.split("=",1)[0]??e;return t==="--force-create"||t.length>=9&&"--force-create".startsWith(t)}function wb(e){return e.some((t)=>t.startsWith("--recurse-sub"))}function Ab(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 Tb="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.",Ib=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function hn(e,t){return Bu(e.map(k),t)}function Bu(e,t,n){let r=Au(e,t.env,t.envAssignments),o=r.blockedReason?I(C("git.alias-config",r.blockedReason),t.policy):null;if(o)return o;let i=r.tokens;if((ul(t.envAssignments)||Tu(e,t.env,t.envAssignments))&&kb(i))return C("git.ssh-env",Tb);let s=Du(i);if(!s)return null;if(r.expanded||r.blockedReason)return s;let a=zu(e,s,t);if(!a)return s;return n?.(a),null}function Uu(e,t){let n=null;return{match:Bu(e.map(k),t,(o)=>{n=o}),relaxation:n}}function kb(e){let{subcommand:t,rest:n}=$e(e),r=t?.toLowerCase();if(!r)return!1;if(Ib.has(r))return!0;if(r==="archive")return de(n).before.some((o)=>N(o,"--remote"));return r==="remote"&&Ob(n)}function Ob(e){return e.find((t)=>!Mb(t))?.toLowerCase()==="update"}function Mb(e){return e==="-v"||N(e,"--verbose")||N(e,"--no-verbose")}import{isAbsolute as Av}from"node:path";var $u="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Db="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.",Nb="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",Hu="rm -rf targeting root or home directory is extremely dangerous and always blocked.",Lb="rm -rf in home directory is dangerous. Change to a project directory first.";function yn(e,t){let n=Gt({...t,allowPaths:t.policy?.destructiveCommandAllowPaths,posixShell:!0}),r=e.map(k),o=Ue(r),i=Pu(r),s=Fb(e);for(let a of s){let l=Zn(a.word);if(o&&l.unsafeBraceExpansion){let c=I(ju({kind:"outside_anchored_cwd"},n,t.policy),t.policy);if(c)return c;continue}for(let c of l.expandedTargets??[a.text]){let u=he(c),d={targetIsLiteral:l.expandedTargets!==void 0||l.targetIsLiteral,tmpdirWordSplittingProtected:l.tmpdirWordSplittingProtected};if(!i&&n.resolvedCwd&&Ft(u,n.resolvedCwd,n.protectedGitMetadata,i,n.pathCanonicalizationContext))return C("rm.git-metadata",Te);if(i&&!o){let m=ze(u,n,d);if(m.kind==="root_or_home_target")return C("rm.recursive-force-root-or-home",Hu);if(m.kind==="git_metadata_target")return C("rm.git-metadata",Te);continue}if(!o)continue;for(let m of Wb(u,n,d)){let f=ju(m,n,t.policy),p=I(f,t.policy);if(p)return p}}}return null}function Wb(e,t,n){let r=ze(e,t,n);if(r.kind==="cwd_self_target")return[r,ze(e,t,{...n,skipCwdSelf:!0})];if(r.kind!=="home_cwd_target")return[r];let o=ze(e,t,{...n,skipHomeCwd:!0});if(o.kind!=="cwd_self_target")return[r,o];return[r,o,ze(e,t,{...n,skipHomeCwd:!0,skipCwdSelf:!0})]}function Fb(e){let t=[],n=!1;for(let r of e.slice(1)){let o=k(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 ju(e,t,n){switch(e.kind){case"root_or_home_target":return C("rm.recursive-force-root-or-home",Hu);case"git_metadata_target":return C("rm.git-metadata",Te);case"temp_target":return null;case"dynamic_target":if(!te(n,"rm.recursive-force-dynamic-target",t.strict))return null;return C("rm.recursive-force-dynamic-target",Nb);case"home_cwd_target":return C("rm.recursive-force-home-cwd",Lb);case"cwd_self_target":return C("rm.recursive-force-cwd-self",$u);case"within_anchored_cwd":if(te(n,"rm.recursive-force-paranoid",t.paranoid))return C("rm.recursive-force-paranoid",Db);return null;case"outside_anchored_cwd":return C("rm.recursive-force-outside-cwd",$u)}}var Gb={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},qu=new Set(["--init-file","--rcfile"]),zb=["--init-file","--rcfile"],Bb=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function Ze(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n)continue;if(n==="-c")return Vu(e,t,!0);if(n.startsWith("-")&&n.includes("c")&&!n.startsWith("--")){let r=Vu(e,t,!1);if(r!==null)return r}}return null}function Ie(e){let t=M(e[0]??"").toLowerCase();if(t==="zsh"||t==="ksh")return Xe(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 Vu(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 Ku(e){let t=M(e[0]??"").toLowerCase(),n=Ub(e,t),r=Bb.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 Ub(e,t){let n=Xe(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?zb.find((m)=>l===m):void 0){let m=e[a+1];o.push(m===void 0?{kind:"absent"}:{kind:"literal",value:m}),a++;continue}let d=l.split("=",1)[0]??l;if(t==="bash"&&qu.has(d)&&!l.includes("="))a++;continue}if(t==="bash")s=!1;let c=Yu(t,l,e[a+1],"startup");if(c.interactive)i=l[0]==="-";a+=c.followingValues}return{argvSource:o.at(-1)??null,interactive:i}}function Yu(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 d=t.slice(c+1);if(t[0]==="-"&&(d==="c"||d[0]==="-"&&d.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(!Gb[e]?.includes(u))continue;if(c+1===t.length)i++;break}return{interactive:o,followingValues:i,commandSelected:s,stdinMode:a,syntaxCheck:l}}function Xe(e){let t=M(e[0]??"").toLowerCase(),n=!1,r=!1,o=!1;for(let i=1;i<e.length;i++){let s=e[i];if(s===void 0)break;if(s==="--"){let l=n&&e[i+1]!==void 0?i+1:null;return{command:l===null?null:e[l]??null,commandIndex:l,scriptIndex:!n&&!r&&e[i+1]!==void 0?i+1:null,readsStdinAsCommands:!n&&(r||e[i+1]===void 0),syntaxCheck:o}}if(s==="-"||s[0]!=="-"&&s[0]!=="+")return{command:n?s:null,commandIndex:n?i:null,scriptIndex:!n&&!r&&s!=="-"?i:null,readsStdinAsCommands:!n&&(r||s==="-"),syntaxCheck:o};if(s.startsWith("--")){let l=s.split("=",1)[0]??s;if(t==="bash"&&qu.has(l)&&!s.includes("="))i++;continue}let a=Yu(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 bt={kind:"none"},Ut={kind:"dynamic"},$b=new Set(["<","<<","<<-","<<<","<&","<>"]),Xu=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,jb=/^(?:[0-9]+|[@*])$/,Hb=Lt.maxWords,Vb=Lt.maxInputLength;function Ju(e){if(!e||M(B(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 Cn(e){let t=nr(e[1])==="--"?2:1;if(e.length<=t)return bt;let n=e.slice(t);if(!n.every(Ho))return Ut;return{kind:"literal",source:n.map(k).join(" ")}}function Qu(e){let t=nr(e[1])==="--"?2:1,n=e[t],r=nr(n);if(n===void 0||e.length<=t+1||r==="-"||r===""||r==="-l"||r==="-p")return bt;if(!Ho(n))return Ut;return{kind:"literal",source:r}}function jo(e,t){let n=Kb(e);if(n===-1)return bt;let r=Yb(t);if(!r)return bt;let o=[],i=r.command?.length??0;for(let s of r.references){let a=Xb(s,e,n,r.ifs);if(!a)return Ut;if(i+=a.reduce((l,c)=>l+c.length+3,0),o.length+a.length>Hb||i>Vb)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(Qb)].filter((s)=>s!==null).join(" ")}}function ed(e,t,n,r){if(!Xe(e.map(k)).readsStdinAsCommands)return bt;let o=t.filter((i)=>(i.fd===void 0||i.fd===0)&&$b.has(i.operator)).at(-1);if(o){if(o.operator==="<<"||o.operator==="<<-")return bt;if(o.operator!=="<<<"||o.target?.provenance!=="literal")return Ut;return{kind:"literal",source:o.target.text}}if(!n)return bt;return r===void 0?Ut:{kind:"literal",source:r}}function Je(e){let t=Xe(e.map(k)).scriptIndex;if(t===null)return bt;let n=e[t],r=nr(n);return Dr(n,r)?{kind:"literal",source:r}:Ut}var qb=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function Us(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||Ae(s)!==null)return!1;let a=M(B(s));return!qb.has(a)&&!ne.has(a)&&!zt(a)}function Kb(e){return Xe(e.map(k)).commandIndex??-1}function Yb(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(Zb);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 Zb(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 Xb(e,t,n,r){let o=t.slice(n+2);if(e.parameter==="@")return e.quoted?Gs(o):Jb(o,r);if(e.parameter==="*"){let a=Gs(o);if(!a)return;let l=a.join(r[0]??"");return e.quoted?[l]:zs(l,r)}let i=t[n+1+e.parameter];if(i&&!Ho(i))return;let s=nr(i);return e.quoted?[s]:zs(s,r)}function Gs(e){return e.every(Ho)?e.map(k):void 0}function Jb(e,t){let n=Gs(e);if(!n)return;let r=n.map((o)=>zs(o,t));return r.some((o)=>o===void 0)?void 0:r.flatMap((o)=>o??[])}function zs(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 Ho(e){if(!e)return!0;return e.provenance==="unknown"?!/[$`]/.test(k(e)):e.provenance==="literal"}function nr(e){return e?k(e):""}function Qb(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function $s(e,t){return Bs(We(e,"posix"),t)}function Sn(e){return $s(e,new Set(Array.from(e.matchAll(Xu)).flatMap((t)=>{let n=t[1]??t[2];return n===void 0?[]:[n]})))}function Bs(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(Bs(r.body,n))return!0;continue}if(r.kind!=="command")continue;if(r.nested.some((o)=>Bs(o,n))||td(r.words,n))return!0;ov(r,n)}return!1}function td(e,t){let n=e.findIndex((s)=>Ae(s.text)===null);if(n===-1)return!1;let r=e[n];if(!r)return!1;if(rr(r,t))return!0;let o=B(r.text);if(o==="source"||o==="."){let s=e[n+1]?.text==="--"?n+2:n+1;return Zu(e[s],t)}if(ne.has(o)){let s=e.slice(n),a=Xe(s.map((c)=>c.text)),l=a.commandIndex??a.scriptIndex;return!a.syntaxCheck&&l!==null&&Zu(s[l],t)}let i=ev(e,n,t);if(i===null)return!1;if(i===-1)return!0;return td(e.slice(i),t)}function ev(e,t,n){let r=B(e[t]?.text??"");if(r==="command")return tv(e,t+1);if(r==="exec")return nv(e,t+1);if(r==="env")return rv(e,t+1,n);return null}function tv(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 nv(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 rv(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 rr(e[r+1],n)?-1:r+2;if(i.startsWith("-S")||i.startsWith("--split-string="))return rr(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(Ae(i))continue;return r}return null}function ov(e,t){if(!e.words.every((n)=>Ae(n.text)!==null))return;for(let n of e.words){let r=Ae(n.text);if(!r)continue;if(rr(n,t))t.add(r.name)}}function rr(e,t){if(!e)return!1;return e.parts.filter((n)=>n.provenance==="variable").some((n)=>Array.from(n.raw.matchAll(Xu)).some((r)=>{let o=r[1]??r[2];return o!==void 0&&(jb.test(o)||t.has(o))}))}function Zu(e,t){return!!e&&(e.parts.some((n)=>n.provenance!=="literal"&&n.provenance!=="variable")||rr(e,t))}var iv=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),sv=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),av=new Set(["-o","--output","--query","--subscription"]),lv=new Set;function nd(e){if(e==="aws")return iv;if(e==="gcloud")return sv;if(e==="az")return av;return lv}var cv=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),uv=new Set;function rd(e){if(e==="git")return Pe;if(e==="docker")return cv;return uv}function se(e,t){if(e.length===0||t.length===0)return null;let n=B(e[0]??""),r=fe(e);for(let o of t){if(!fv(n,o.command))continue;if(o.match){if(dv(n,e,o.match))return od(o);continue}if(!pv(n,e,o.subcommand))continue;if(hv(e,new Set(o.block_args),r))return od(o)}return null}function od(e){return{id:`custom.${e.name}`,reason:`[${e.name}] ${e.reason}`,intent:e.intent??"manual_only"}}function dv(e,t,n){let r=t.slice(1);if(n.exclude_args?.some((o)=>r.includes(o)))return!1;if(n.any_args&&!n.any_args.some((o)=>r.includes(o)))return!1;return mv(r,n.command_path,nd(e))}function mv(e,t,n){let r=0,o=!1;for(let i of e){if(r>=t.length)return!0;if(o){o=!1;continue}if(i.startsWith("-")){o=!i.includes("=")&&n.has(i);continue}if(i!==t[r])return!1;r++}return r>=t.length}function fv(e,t){return e===B(t)}function pv(e,t,n){if(!n)return!0;return id(t,1,n,rd(e))}function id(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("=")&&gv(e,i,n,r))return!0;continue}return s===n}return!1}function gv(e,t,n,r){let o=e[t+1];if(!o||o.startsWith("-"))return!1;return id(e,t+2,n,r)}function hv(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 vt(e,t,n={}){if(e.length===0)return null;let r=e[0];if(!r)return null;let o=B(r);if(o==="eval"){let i=Cn(W(e));if(i.kind==="dynamic")return bn(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 Qe(n,t)}if(ne.has(o)){if(Ie(e))return null;let i=Ze(e);if(i){if(n.dynamicSourceInput??n.dynamicInput){let l=bn(n,t);if(l)return l}if(Sn(i)){let l=bn(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=Je(W(e));if(s.kind==="dynamic")return bn(n,t);if(s.kind==="literal"){if(n.dynamicSourceInput)return bn(n,t);return null}if(n.dynamicSourceInput??n.dynamicInput)return bn(n,t);return null}if(Re.has(o))return I(Fo(e,(i)=>t.analyzeNested?t.analyzeNested(i,{effectiveCwd:t.cwd,envAssignments:t.envAssignments}):null),t.policy)??se(e,t.policy?.rules??[])??Qe(n,t);if(Se(o)){let i=Jr(e);if(!i)return Qe(n,t);if(te(t.policy,"interpreter.one-liner-paranoid",!!t.paranoidInterpreters)){let a=I(C("interpreter.one-liner-paranoid",an),t.policy);if(a)return a}if(to(o,i))return Qe(n,t);let s=t.analyzeNested?.(i,{effectiveCwd:t.cwd,envAssignments:t.envAssignments});if(s&&s.id!=="raw-text.dangerous-command"&&(s.reason!==ft||mn(i)))return s;if(ln(i,t.scanWork))return I(C("interpreter.dangerous-command",Dt),t.policy)??Qe(n,t);return Qe(n,t)}if(o==="rm"||o==="rmdir"){let i=o==="rm"&&(Ue(e)||n.dynamicRmInput);return I(yn(W(e),{environment:t.environment,cwd:t.cwd,originalCwd:t.originalCwd,strict:t.strict,paranoid:t.paranoidRm,allowTmpdirVar:t.allowTmpdirVar,tmpdirWordSplittingUnsafe:qe(t.envAssignments,t.environment),trustedTmpdirValue:at(t.envAssignments,t.environment),protectedGitMetadata:t.protectedGitMetadata,policy:t.policy}),t.policy)??(i&&n.dynamicRmInput?Qe(n,t):null)??(i?yv(n,t):null)}if(o==="find")return Bo(W(e),{...t,derivedCommandWorkBudget:t.derivedCommandWorkBudget,analyzeTokens:(i,s)=>vt(i,{...t,cwd:s??void 0,derivedCommandWorkBudget:t.derivedCommandWorkBudget},n)})??se(e,t.policy?.rules??[])??Qe(n,t);if(o==="git")return I(hn(W(e),{env:t.environment.env,cwd:t.cwd,envAssignments:t.envAssignments,policy:t.policy,worktreeMode:n.dynamicInput?!1:t.worktreeMode}),t.policy)??se(e,t.policy?.rules??[])??Qe(n,t);return se(e,t.policy?.rules??[])??Qe(n,t)}function bn(e,t){return e.shellDynamicMatch?I(e.shellDynamicMatch,t.policy):null}function Qe(e,t){return e.dynamicSourceInput&&e.dynamicSourceMatch?I(e.dynamicSourceMatch,t.policy):null}function yv(e,t){return e.dynamicInput&&e.rmDynamicMatch?I(e.rmDynamicMatch,t.policy):null}var js="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",Hs="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",Cv="__CC_SAFETY_NET_XARGS_INPUT__",Vo="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",qo="rm",Sv=/(?:^|[;&|]\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,bv=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,vv=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,Rv=/^(?:[0-9]+|[@*])$/;function ld(e,t){let n=e.map(k),{childStart:r,replacementToken:o}=$t(n),i=n.slice(r),s=C("xargs.shell-dynamic",Hs);if(Ev(i,o,t)&&I(s,t.policy))return I(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)?I(s,t.policy):null;if(c)return c;let u=md(l,o,a.wrapperEnvAssignments),d=a.head==="rm"&&o!==null&&ud(l,o),m=vt(l,{...t,cwd:a.cwd,envAssignments:a.envAssignments},{dynamicInput:u,dynamicSourceInput:d||cd(l,a.head,o,a.wrapperEnvAssignments,u,t.scanWork,t.environment),dynamicRmInput:d,shellDynamicMatch:s,dynamicSourceMatch:s,rmDynamicMatch:C("xargs.rm-recursive-force-dynamic",js)});if(m)return m;let f=xv(l,o,t.policy?.rules??[]);if(f)return f;if(a.head==="git"){let g=o===null?[...l,Cv]:l,h=o!==null&&(l.some((x)=>x.includes(o))||Array.from(a.envAssignments.values()).some((x)=>x.includes(o))),y=vt(g,{...t,cwd:a.cwd,envAssignments:a.envAssignments,worktreeMode:o===null||h?!1:t.worktreeMode});if(y)return y}let p=se(l,t.policy?.rules??[]);if(p)return p}return null}function xv(e,t,n){if(n.length===0)return null;if(t===null){for(let o of n){let i=se([...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)=>Vs(s,t,i)):[])));for(let o of r){let i=se(e.map((s)=>s.replaceAll(t,o)),n);if(i)return i}return null}function Vs(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 cd(e,t,n,r,o,i,s){if(ne.has(t)){if(Ie(e))return!1;if(n!==null&&_v(e,n))return!0;let a=Ze(e);if(!a){let l=Je(W(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(it(a,i))return!0;return Pv(a,n,r)}if(Se(t))return sd(e,n,eo,Ul(t));if(Re.has(t))return sd(e,n,Es,bu);if(t==="eval"){let a=Cn(W(e));if(a.kind==="dynamic")return!0;if(n!==null)return a.kind==="literal"&&a.source.includes(n);return o}if(t==="find")return wv(e,n,i,s);if(t==="git"){let a=$e(e);return n===null?a.subcommand===null:(a.subcommand?.includes(n)??!1)||a.subcommand!==null&&gn.has(a.subcommand.toLowerCase())&&dd(a.rest,n).some((l)=>l.includes(n))}return!1}function sd(e,t,n,r){let o=n(e);if(t===null)return o.optionsOpen||n([...e,Vo]).sources.some((l)=>l.value===Vo);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}${Vo}`]:[],...l.valueForm==="equals-or-separate"?[`${l.selector}=${Vo}`]:[]]),a=new Set(s.flatMap((l)=>e.flatMap((c)=>Vs(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 Ev(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,qo]:e.map((i,s)=>s===0?i:i.replaceAll(t,qo));return Array.from(Be(o,n)).some((i)=>i.head===qo&&!r.has(qo))}function ud(e,t){return dd(e.slice(1),t).some((n)=>n.includes(t)&&(n.startsWith("-")||n.startsWith(t)))}function dd(e,t){let n=e.findIndex((r)=>r==="--"&&!r.includes(t));return n===-1?e:e.slice(0,n)}function md(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 _v(e,t){let n=Xe(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 Vs(i,t,o).some((l)=>{let c=e.map((d,m)=>m===s?d.replaceAll(t,l):d),u=Xe(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 Pv(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(Sv))if(ad(o,r))return!0;for(let o of e.matchAll(bv))for(let i of(o[1]??"").matchAll(vv))if(ad(i,r))return!0;return $s(e,r)}function ad(e,t){let n=e[1]??e[2];return n!==void 0&&(Rv.test(n)||t.has(n))}function wv(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(lt(a)){let c=Qn(e,s);s=c.nextIndex-1;for(let u of Be(c.tokens,{environment:r,cwd:void 0})){let d=md(u.tokens,t,u.wrapperEnvAssignments);if(u.head==="rm"&&ud(u.tokens,t)||cd(u.tokens,u.head,t,u.wrapperEnvAssignments,d,n,r))return!0}continue}let l=Ct(a);if(l>0){if(i=l,a.includes(t))return!0;continue}if(a.includes(t))return!0}return!1}function $t(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 ir="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",sr="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",Tv="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",Iv="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",kv=/\{[^{}\s]*\}/,bd=/\{\}|\{-?\d+\}/g,Ov=["e","f","source","file","-e","-f","--source","--file"],Mv=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],Dv=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),Nv=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),fd=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),Lv=new Set(["--workdir","--wd"]),pd="__CC_SAFETY_NET_PARALLEL_SOURCE__",Wv=new TextEncoder,Ks=U.maxDerivedBytes+4*U.maxPlaceholderReplacements;function ge(e,t){for(let n of e){let r=t(n);if(r)return r}return null}function vd(e,t){return ge([...e],(n)=>it(n,t.scanWork))}function Rd(e,t){let n=e.map(k);if((t.envAssignments?.has("PARALLEL")?t.envAssignments.get("PARALLEL"):t.environment.env.get("PARALLEL"))?.trim()){let p=Ht(t);if(p)return p}if(n.length===2&&(n[1]==="--version"||n[1]==="--help"))return null;let o=kd(n),{template:i,jobs:s,runsRemotely:a,readsCommandsFromInput:l,unsupported:c,workdir:u,dryRun:d}=o;if(c){let p=Ht(t);if(p)return p;let g=vd(t.envAssignments?.values()??[],t);if(g)return g}if(l){let p=Hv(t);if(p)return p}if(u!==void 0&&a){let p=Ht(t);if(p)return p}let m=Yv(u,t.cwd,t.environment.paths);if(m===null){let p=Ht(t);if(p)return p}let f=a?{...t,cwd:void 0,originalCwd:void 0}:m===null||m===void 0||m===t.cwd?t:{...t,cwd:m};if(d){if([...Be(i,f)].flatMap((g)=>[...g.envAssignments.values()]).some(Js)){let g=Ht(t);if(g)return g}return null}if(i.length===0){if(s.some((h)=>h.length!==1)){let h=Ht(t);if(h)return h}let p=s.map((h)=>h[0]??"");be(t.budget,Ys(p));let g=wd(f.envAssignments,f.cwd,a);return ge(p,(h)=>t.analyzeNested(h,g))}return ge(Be(i,f),(p)=>Fv(p,o,t,f))}function Fv(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(Td)){let y=Ht(n);if(y)return y}let d=vd(u,n);if(d)return d;let m=u.some(q),f=i||m,p=a&&f,g=wd(e.envAssignments,e.wrapperCwd,s||p);if(ne.has(e.head)){let y=()=>{if(!i||o.length===0)return null;return be(n.budget,Ko(l,o,"generic")),ge(o,(E)=>vt(l.map((w)=>Rt(w,E)),c))};if(Ie(l))return y();let x=Ze(l);if(x){if(Id(x)){let _=jt(n);if(_)return _;if(o.length===0)return null;return be(n.budget,Sd(x,o)),ge(o,(F)=>n.analyzeNested(Rt(x,F),g))}if(q(x)){if(o.length>0)return be(n.budget,Sd(x,o)),ge(o,(Z)=>n.analyzeNested(Rt(x,Z),g));be(n.budget,yd(x));let _=er(x);if(_?.[0]&&B(_[0])==="rm"&&Ue(_)){let Z=hd(n);if(Z)return Z}let F=_?vt(_,c,{dynamicInput:a,shellDynamicMatch:C("parallel.shell-dynamic",sr),rmDynamicMatch:C("parallel.rm-recursive-force-dynamic",ir)}):null;if(F)return F;return n.analyzeNested(x,g)}let E=!m&&(!i||o.length>0)?(o.length>0?o:[void 0]).map((_)=>jo(W(_===void 0?l:i?l.map((F)=>Rt(F,_)):[...l,..._]),x)):[];if(E.some((_)=>_.kind==="dynamic")){let _=jt(n);if(_)return _}let w=E.flatMap((_)=>_.kind==="literal"?[_.source]:[]);if(w.length>0)return be(n.budget,Ys(w)),ge(w,(_)=>n.analyzeNested(_,g));if(be(n.budget,yd(x)),Sn(x)){let _=jt(n);if(_)return _}let O=n.analyzeNested(x,g);if(O)return O;if(f)return jt(n);return null}let P=Je(W(l));if(P.kind==="dynamic"||P.kind==="literal"&&q(P.source))return jt(n)??y();if(P.kind==="literal")return y();if(o.length>0){let E=jt(n);if(E)return E;let w=y();if(w)return w;if(i)return null;let O=o.flatMap((_)=>_[0]===void 0?[]:[_[0]]);return be(n.budget,Ys(O)),ge(O,(_)=>n.analyzeNested(_,g))}if(f||a)return jt(n)??y();return null}if(e.head==="rm"&&Ue(l)){if(i&&o.length>0)return be(n.budget,Ko(l,o,"rm")),ge(o,(x)=>qs(l.map((P)=>Zs(P,x)),e.cwd,r));if(o.length>0)return be(n.budget,Cd(l,o)),ge(o,(x)=>qs([...l,...x],e.cwd,r));let y=qs(l.flatMap((x,P)=>{if(P===0||!q(x))return[x];return x.startsWith("-")?[Zs(x,[""])]:[]}),e.cwd,r);if(y)return y;return hd(n)}be(n.budget,i&&o.length>0?Ko(l,o,"generic"):o.length>0?Cd(l,o):Pd(l));let h=o.length>0?o:[void 0];return ge(h,(y)=>{let x=y===void 0?l:i?l.map((X)=>Rt(X,y)):[...l,...y],P=C("parallel.shell-dynamic",sr),E=a&&e.head==="find"?jv(x,r):null,w=Ed(x,a,n.policy?.rules??[],n.budget)??E?.customResult??null,O=B(e.head),_=a&&(O==="rm"&&Xs(x)||O==="xargs"&&_d(x)||E?.rmOptions===!0),F=a&&(_||E?.executedSource===!0||E===null&&xd(x,O)),Z=vt(x,{...c,worktreeMode:s||a||f?!1:n.worktreeMode},{dynamicInput:a||f,dynamicRmInput:_,dynamicSourceInput:w!==null||F,shellDynamicMatch:P,dynamicSourceMatch:P,rmDynamicMatch:C("parallel.rm-recursive-force-dynamic",ir)});if(F){let X=I(P,n.policy);if(X)return X}return Z??w??se(x,n.policy?.rules??[])})}function xd(e,t){if(q(e[0]??""))return!0;if(t==="eval"||t==="source"||t===".")return!0;if(t==="parallel"||t==="xargs")return!0;if(ne.has(t))return Bv(e);if(t==="git")return Gv(e);if(t==="find")return!0;if(Re.has(t))return gd(e,Ov,Jn);if(Se(t))return gd(e,Mv,Qr);return!1}function Xs(e){let t=e.indexOf("--"),n=e.slice(1,t===-1?void 0:t);if(!e.some(q))return t===-1;return n.some((o)=>q(o)&&(o.startsWith("-")||Id(o)))}function Gv(e){if(zv(e))return!0;let t=$e(e);if(t.subcommand===null||q(t.subcommand))return!0;if(!gn.has(t.subcommand.toLowerCase()))return!1;let n=t.rest.indexOf("--"),r=t.rest.slice(0,n===-1?void 0:n);if(!e.some(q))return n===-1;return r.some(q)}function zv(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(q(e[t+1]??""))return!0;t++;continue}if(n.startsWith("-c")&&n.length>2||n.startsWith("--config-env=")){if(q(n))return!0;continue}if(q(n))return!0}return!1}function Bv(e){if(Ie(e))return!1;let t=Ze(e);if(t!==null)return q(t);let n=Je(W(e));if(n.kind==="literal")return q(n.source);if(n.kind==="dynamic")return!0;return!e.some(q)}function gd(e,t,n){let r=n(e);if(r.some((i)=>q(i.value)))return!0;if(!e.some(q))return n([...e,pd]).some((i)=>i.value===pd);let o=new Set(r.map((i)=>`${i.tokenIndex}\x00${i.kind}\x00${i.value}`));return t.some((i)=>n(e.map((s)=>Rt(s,[i]))).some((s)=>!o.has(`${s.tokenIndex}\x00${s.kind}\x00${s.value}`)))}function Ed(e,t,n,r){if(!t||n.length===0)return null;let o=n.filter((s)=>B(s.command)===B(e[0]??""));if(o.length===0)return null;let i=e.some(q);if(be(r,Uv(e,o,i)),!i)return ge(o,(s)=>se([...e,...s.subcommand?[s.subcommand]:[],...s.block_args],[s]));return ge(o,(s)=>{let a=new Set([s.subcommand,...s.block_args].flatMap((l)=>l?$v(e,l):[]));return ge(a,(l)=>se(e.map((c)=>Rt(c,[l])),[s]))})}function Uv(e,t,n){let r=n?Vt(ke(t.map((o)=>o.block_args.length+(o.subcommand?1:0)),U.maxChildAnalyses),2*Math.max(e.length,1),U.maxChildAnalyses):t.length;return{childAnalyses:r,derivedTokens:Vt(r,e.length,U.maxDerivedTokens)}}function $v(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 jv(e,t){let n={customResult:null,executedSource:!e.some(q),rmOptions:!1},r=!1,o=0,i=null,s=()=>{if(!i?.some(q))return;for(let a of Be(i,t))n.executedSource||=xd(a.tokens,a.head),n.rmOptions||=a.head==="rm"&&Xs(a.tokens)||a.head==="xargs"&&_d(a.tokens),n.customResult??=Ed(a.tokens,!0,t.policy?.rules??[],t.budget)};for(let a of e.slice(1)){if(!r&&!a.startsWith("-")&&a!=="!"&&a!=="("){n.executedSource||=q(a);continue}if(r=!0,i){if(a===";"||a==="+"){s(),i=null;continue}i.push(a);continue}if(o>0){o--;continue}if(lt(a)){i=[],n.executedSource||=q(a);continue}let l=Ct(a);if(l>0){o=l,n.executedSource||=q(a);continue}n.executedSource||=q(a)}return s(),n}function _d(e){let t=e.slice($t(e).childStart);return B(t[0]??"")==="rm"&&Xs(t)}function Yo(e,t){return(n)=>I(C(e,t),n.policy)}var jt=Yo("parallel.shell-dynamic",sr),Hv=Yo("parallel.command-stream-dynamic",Tv),Ht=Yo("parallel.command-stream-dynamic",Iv),hd=Yo("parallel.rm-recursive-force-dynamic",ir);function qs(e,t,n){return I(yn(W(e),{environment:n.environment,cwd:t,originalCwd:n.originalCwd,strict:n.strict,paranoid:n.paranoidRm,allowTmpdirVar:n.allowTmpdirVar,tmpdirWordSplittingUnsafe:qe(n.envAssignments??new Map,n.environment),trustedTmpdirValue:at(n.envAssignments??new Map,n.environment),protectedGitMetadata:n.protectedGitMetadata,policy:n.policy}),n.policy)}function Ys(e){return{childAnalyses:e.length,derivedTokens:e.length,derivedBytes:ar(e)}}function yd(e){return Pd([e])}function Pd(e){return{childAnalyses:1,derivedTokens:e.length,derivedBytes:ar(e)}}function Cd(e,t){if(t.length>U.maxChildAnalyses)return{childAnalyses:t.length};return{childAnalyses:t.length,derivedTokens:ke(t.map((n)=>e.length+n.length),U.maxDerivedTokens),derivedBytes:ke([Vt(ar(e),t.length,U.maxDerivedBytes),ke(t.map((n)=>ar(n)),U.maxDerivedBytes)],U.maxDerivedBytes)}}function Sd(e,t){return Ko([e],t,"generic")}function Ko(e,t,n){if(t.length>U.maxChildAnalyses)return{childAnalyses:t.length};let r=Vt(e.length,t.length,U.maxDerivedTokens);if(r>U.maxDerivedTokens)return{childAnalyses:t.length,derivedTokens:r};let o=Kv(e.map((l)=>qv(l,n))),i=Vt(o.occurrences,t.length,U.maxPlaceholderReplacements);if(i>U.maxPlaceholderReplacements)return{childAnalyses:t.length,derivedTokens:r,placeholderReplacements:i};if(Vv(o,t,i))return{childAnalyses:t.length,derivedTokens:r,derivedBytes:U.maxDerivedBytes+1,placeholderReplacements:i};let s=n==="generic"?Rt:Zs,a=ke(t.map((l)=>ar(e.map((c)=>s(c,l)))),U.maxDerivedBytes);return{childAnalyses:t.length,derivedTokens:r,derivedBytes:a,placeholderReplacements:i}}function Vv(e,t,n){let r=U.maxDerivedBytes+4*n;return ke([Vt(e.fixedBytes,t.length,r),Vt(e.occurrences,ke(t.map((o)=>o.reduce((i,s)=>Math.max(i,or(s)),0)),r),r)],r)>r}function qv(e,t){let n=t==="generic"?e.matchAll(/\{[^{}\s]*\}/g):e.matchAll(bd),r=0,o=0,i=0;for(let s of n){if(r>=U.maxPlaceholderReplacements)return{occurrences:U.maxPlaceholderReplacements+1,fixedBytes:0};o=ke([o,or(e.slice(i,s.index))],Ks),r++,i=s.index+s[0].length}return{occurrences:r,fixedBytes:r===0?or(e):ke([o,or(e.slice(i))],Ks)}}function Kv(e){return{occurrences:ke(e.map((t)=>t.occurrences),U.maxPlaceholderReplacements),fixedBytes:ke(e.map((t)=>t.fixedBytes),Ks)}}function ar(e,t=U.maxDerivedBytes){return ke(e.map(or),t)}function or(e){return Wv.encode(e).byteLength}function ke(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 Vt(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 wd(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 Rt(e,t){return e.replace(/\{[^{}\s]*\}/g,(n)=>Ad(n,t))}function Zs(e,t){return e.replace(bd,(n)=>Ad(n,t))}function Ad(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 q(e){return kv.test(e)}function Td(e){if(Js(e))return!0;for(let t of e.matchAll(/\{[^{}\s]*\}/g))if(!/^(?:\{\}|\{-?\d+\})$/.test(t[0]))return!0;return!1}function Js(e){let t=e.indexOf("{=");return t!==-1&&e.indexOf("=}",t+2)!==-1}function Id(e){return/^\{[^{}\s]*\}$/.test(e)}function kd(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 P=ws(e,t+1);n.push(...P.templateTokens),r=t+1,o=P.markerIndex;break}if(!p.startsWith("-")){let P=ws(e,t);n.push(...P.templateTokens),r=t,o=P.markerIndex;break}let g=e[t+1],h=p.indexOf("="),y=h===-1?p:p.slice(0,h),x=h===-1?void 0:p.slice(h+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(y==="--replace"||p.startsWith("-i")&&p.length>2){let P=y==="--replace"?x:p.slice(2);c||=P!==""&&P!=="{}",t++;continue}if(p==="-a"||Nv.has(y)){c=!0,t+=x===void 0?2:1;continue}if(p==="--pipe"||p==="--pipepart"){s=!0,t++;continue}if(y==="--env"){c=!0,t+=x===void 0?2:1;continue}if(fd.has(y)||p.startsWith("-S")&&p.length>2){i=!0,t+=fd.has(p)?2:1;continue}if(Lv.has(y)){let P=x??g;if(P===void 0||P===":::"||P==="--"){c=!0,t++;continue}l=P,c||=x!==void 0&&P==="",t+=x===void 0?2:1;continue}if(p.startsWith("-j")&&p.length>2&&/^\d+$/.test(p.slice(2))){t++;continue}if(p.startsWith("--")&&x!==void 0){t++;continue}if(Dv.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?Js:Td);let u=[];if(o!==-1){let p=[];for(let g=o+1;g<e.length;g++){let h=e[g];if(h===":::"){u.push(p),p=[];continue}if(h!==void 0)p.push(h)}u.push(p)}let d=Zv(u),m=n.some(q),f=n.length===0&&o===-1;return{template:n,jobs:d,childStart:r,templateHasPlaceholder:m,runsRemotely:i,usesStdin:s||o===-1,readsCommandsFromInput:f,unsupported:c,workdir:l,dryRun:a}}function Yv(e,t,n){if(e===void 0)return;if(e==="..."||/[{}$`*?~[]/.test(e))return null;if(!t&&!Av(e))return null;try{return mt(t??e,e,n)}catch{return null}}function Zv(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>U.maxChildAnalyses)return r;t=r}return t}function Od(e){return kd(e).childStart}var Xv="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",Zo="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function ea(e){return e?.parts.some((t)=>t.provenance==="command-substitution")??!1}function Qs(e){return e?.parts.some((t)=>t.provenance==="literal"&&t.raw.replace(/^["']/,"").startsWith("-"))??!1}function Dd(e,t,n,r,o=!1,i){let a=(zn(e,t)||r&&e!=="powershell"&&t[0]?.provenance==="variable")&&te(i,"shell.dynamic-executable",o)?C("shell.dynamic-executable",Xv):null;return I(a,i)??Nd(e,t,n,o,i)}function Nd(e,t,n,r,o){if(t.length<2)return null;let i=t.flatMap((a,l)=>ea(a)?[l]:[]);if(i.length===0)return null;let s=B(t[0]?.text??"");if(s==="git"){let a=en(e,t),l=Qv(a);if(te(o,"shell.dynamic-structure",r)&&i.some((d)=>d<=l))return I(C("shell.dynamic-structure",Zo),o);if(I(hn(a,{env:n.env}),o))return null;let c=t[l]?.text.toLowerCase(),u=a.findIndex((d,m)=>m>l&&k(d)==="--");if(te(o,"shell.dynamic-structure",r)&&c&&gn.has(c)&&i.some((d)=>d>l&&(u===-1||d<u)))return I(C("shell.dynamic-structure",Zo),o);return null}if(s==="find")return te(o,"shell.dynamic-structure",r)&&eR(t)?I(C("shell.dynamic-structure",Zo),o):null;if(s==="rm"){let a=t.findIndex((c,u)=>u>0&&k(c)==="--"),l=Ue(t.map(k));return te(o,"shell.dynamic-structure",r)&&i.some((c)=>(a===-1||c<a)&&(c<t.length-1||!l))?I(C("shell.dynamic-structure",Zo),o):null}if(s==="xargs")return Md(e,t.slice($t(t.map(k)).childStart),"xargs",n,r,o);if(s==="parallel")return Md(e,t.slice(Od(t.map(k))),"parallel",n,r,o);return null}function Md(e,t,n,r,o,i){if(t.length===0)return null;let s=Jv(t,r);if(zn(e,s)){let l=I(C(`${n}.shell-dynamic`,n==="xargs"?Hs:sr),i);if(l)return l}let a=Nd(e,s,r,o,i);if(a)return a;if(s[0]?.text==="rm"&&s.slice(1).some((l)=>ea(l)&&Qs(l)))return I(C(`${n}.rm-recursive-force-dynamic`,n==="xargs"?js:ir),i);return null}function Jv(e,t){let n=Nt(e,t),r=n.rewritten?W(n.words.map(k)):n.words,o=r[0];return o&&k(o)==="busybox"?r.slice(1):r}function Qv(e){let t=1;while(t<e.length){let n=e[t],r=n?k(n):"";if(Pe.has(r)){t+=2;continue}if(r.startsWith("-")){t++;continue}return t}return t}function eR(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=ea(s);if(n>0){n--;continue}if(o){if(s.text===";"||s.text==="+"){o=!1,t=!0,r=!1;continue}if(a&&(r||Qs(s)))return!0;r=!1;continue}if(!t&&!s.text.startsWith("-")){if(a&&(i>1||Qs(s)))return!0;continue}if(t=!0,a)return!0;let l=Ct(s.text);if(l>0){n=l;continue}if(lt(s.text))o=!0,r=!0}return!1}function ta(e,t){return e.some((n)=>{if(n.value==="-"&&(n.kind==="main-script"||n.kind==="program-file"))return!0;return!Dr(t[n.tokenIndex],n.value)})}var tR="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",nR="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",rR="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function Ld(e,t){let n=t.slice(1);if(e==="dd"&&n.some((r)=>/^of=\/dev\/.+/.test(r)))return C("dd.device-write",tR);if((e==="mkfs"||e.startsWith("mkfs."))&&n.some((r)=>r.startsWith("/dev/")))return C("mkfs.device",nR);if(e==="shred"&&n.length>0)return C("shred.target",rR);return null}var Fd=[{heads:new Set(["rm","rmdir"]),analyze:(e)=>yn(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoid:e.options.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:qe(e.envAssignments,e.options.environment),trustedTmpdirValue:at(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,policy:e.options.policy})},{heads:new Set(["git"]),analyze:(e)=>hn(e.words,na(e))},{heads:new Set(["find"]),analyze:(e)=>Bo(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:qe(e.envAssignments,e.options.environment),trustedTmpdirValue:at(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)=>qt(e.options.analyzeNested(t,n))})},{heads:new Set(["xargs"]),analyze:(e)=>ld(e.words,{...Wd(e),analyzeNested:(t,n)=>qt(e.options.analyzeNested(t,n))})},{heads:new Set(["parallel"]),analyze:(e)=>Rd(e.words,{...Wd(e),budget:e.options.parallelBudget,analyzeNested:(t,n)=>qt(e.options.analyzeNested(t,n))})}];function Wd(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 qt(e){return e?{id:e.ruleId??"",reason:e.reason,intent:e.intent??"manual_only"}:null}function na(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 Ud="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function $d(e){return Fd.find((t)=>t.heads.has(e))?.analyze}function lr(e,t,n){let r=n.trace;if(e.length===0)return null;let o=n.commandView?.dialect??"posix",i=(S)=>S.map((v)=>o==="posix"?k(v):v.text),s=n.effectiveCwd===null,a=s?void 0:n.effectiveCwd??n.cwd,l=s?void 0:n.cwd,c=ao(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])),d=u.envSplitValues??[];if(d.length>0){let S=[...d,...i(u.words)].join(" "),v=it(S,n.scanWork);if(v)return r?.recordSegment({type:"dangerous-text",token:S,matched:!0,reason:v.reason}),et(v);if(n.strict)return xe(r);let T=lo(d,i(u.words));if(T){De(n.derivedCommandWorkBudget,T.length);let L=n.analyzeNested(T.join(" "),{effectiveCwd:u.cwd===void 0?n.effectiveCwd:u.cwd,envAssignments:new Map([...n.envAssignments??[],...c.envAssignments,...u.envAssignments])});if(L)return L}}let m=u.rewritten?W(i(u.words)):en(o,u.words),f=i(m),p={...n,wrapperNormalizationBudget:n.wrapperNormalizationBudget??{iterations:0}};if(r&&c.words.length>m.length){let S=i(c.words);r.recordSegment({type:"leading-tokens-stripped",input:S,removed:S.slice(0,S.length-m.length),output:f})}let g=new Map([...n.envAssignments??[],...c.envAssignments,...u.envAssignments]),h=f[0];if(!h)return null;if(zt(h))throw new Ce;let y=B(h),x=u.cwd===null?void 0:u.cwd??a,P=u.cwd===null?void 0:l,E=u.cwd===void 0?n.effectiveCwd:u.cwd,w=!Ln(g,n.environment),O=Dd(o,u.words,n.environment,t===0,n.strict,n.policy);if(O)return r?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:O.reason}),et(O);let _=Go(f,n.policy);if(_){for(let S of[_.childIndex,..._.alternativeChildIndices]){Gd(p.wrapperNormalizationBudget);let v=m.slice(S);r?.recordSegment({type:"transparent-wrapper",wrapper:_.wrapper,output:i(v)});let T=lr(v,t,{...p,effectiveCwd:E,envAssignments:g});if(T)return T}return null}let F=y==="eval"?Cn(m):y==="trap"?Qu(m):void 0;if(F?.kind==="dynamic"&&(n.strict||!n.commandView||!Us(n.commandView)))return xe(r);if(F?.kind==="literal"){r?.recordSegment({type:"recurse",reason:y==="eval"?"shell-eval":"shell-trap",innerCommand:F.source,depth:t+1});let S=n.analyzeNested(F.source,{effectiveCwd:E,envAssignments:g,functionDefinitions:n.functionDefinitions});if(S)return S}if(Hd(h,y)){if(Ie(f))return null;let S=oR(f,g,E,n,r,t);if(S)return S;let v=Ze(f);if(v){let Qt=jo(m,v);if(Qt.kind==="dynamic")return xe(r);let wi=Qt.kind==="literal"?Qt.source:v,tl=iR(wi);r?.recordSegment({type:"shell-wrapper",wrapper:y,innerCommand:tl}),r?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:tl,depth:t+1});let nl=n.analyzeNested(wi,{effectiveCwd:E,envAssignments:g});if(nl)return nl;return Sn(wi)?xe(r):null}let T=Je(m);if(T.kind==="dynamic")return xe(r);if(T.kind==="literal")return Qo(T.source,E,g,n,r,t);let L=ed(m,n.commandView?.redirections??[],n.hasPipelineInput??!1,n.literalShellInput);if(L.kind==="dynamic")return xe(r);if(L.kind==="literal")return r?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:L.source,depth:t+1}),n.analyzeNested(L.source,{effectiveCwd:E,envAssignments:g})}if(y==="source"||y==="."){let S=f[1]==="-p"?2:null;if(S!==null){let Qt=n.commandView?m[S]:void 0;if(!Qt)return null;if(Qt.provenance!=="literal")return xe(r)}let v=S===null?1:3,T=f[v]==="--"?v+1:v,L=n.commandView?m[T]:void 0;if(!L)return null;if(L.provenance==="literal")return Qo(L.text,E,g,n,r,t);if(n.strict||!n.commandView||!Us(n.commandView))return xe(r)}if(Re.has(y)){if(n.strict&&ta(Jn(f),m))return xe(r);let S=Fo(f,(T)=>qt(n.analyzeNested(T,{effectiveCwd:E,envAssignments:g}))),v=I(S,n.policy);if(v)return r?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:v.reason}),et(v)}if(Se(y)){if(n.strict&&ta(Qr(f),m))return xe(r);let S=Jr(f);if(S){let v=te(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(r?.recordSegment({type:"interpreter",interpreter:y,codeArg:S,paranoidBlocked:v}),v){let L=I(C("interpreter.one-liner-paranoid",an),n.policy);if(L)return et(L)}if(to(y,S))return null;r?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:S,depth:t+1});let T=n.analyzeNested(S,{effectiveCwd:E,envAssignments:g});if(T&&T.ruleId!=="raw-text.dangerous-command"&&(T.reason!==ft||mn(S)))return T;if(ln(S,n.scanWork)){let L=I(C("interpreter.dangerous-command",Dt),n.policy);if(L)return r?.recordSegment({type:"dangerous-text",token:S,matched:!0,reason:Dt}),et(L)}r=void 0}}if(y==="busybox"&&f.length>1)return Gd(p.wrapperNormalizationBudget),r?.recordSegment({type:"busybox",subcommand:f[1]??"unknown"}),r?.recordSegment({type:"recurse",reason:"busybox",innerCommand:f.slice(1).join(" "),depth:t+1}),lr(m.slice(1),t,{...p,effectiveCwd:E,envAssignments:g});let Z=I(Ld(y,f),n.policy);if(Z)return r?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:Z.reason}),et(Z);let X=r===p.trace?p:{...p,trace:r},j={words:m,head:y,cwd:x,originalCwd:P,envAssignments:g,allowTmpdirVar:w,dynamicArguments:u.words.some((S)=>S.provenance==="command-substitution"),depth:t,effectiveCwd:E,options:X,analyzeChildTokens:(S,v)=>qt(lr(W(S),t+1,{...X,commandView:void 0,effectiveCwd:v,envAssignments:g}))??se(S,X.policy.rules)},G=$d(y);if(y==="rm"||y==="xargs"||y==="parallel")r?.recordSegment({type:"tmpdir-check",tmpdirValue:g.has("TMPDIR")||n.environment.env.has("TMPDIR")?"<redacted>":null,isOverriddenToNonTemp:!w,allowTmpdirVar:w});let R=r&&y==="git"?Uu(j.words,na(j)):void 0,A=zd(R?R.match:G?.(j)??null,n.policy);if(r)sR(j,A,R?.relaxation??null);if(A)return et(A);let z=G!==void 0;if(!z)if(!Zr.has(y)){let S=r?[]:void 0;for(let v=1;v<f.length;v++){let T=f[v];if(!T)continue;S?.push(T);let L=zd(aR(j,f,v),n.policy);if(L)return r?.recordSegment({type:"fallback-scan",tokensScanned:S??[],embeddedCommandFound:B(T)}),et(L)}r?.recordSegment({type:"fallback-scan",tokensScanned:S??[]})}else r?.recordSegment({type:"fallback-scan",tokensScanned:[]});else r?.recordSegment({type:"fallback-scan",tokensScanned:[]});if(t===0||!z){let S=se(f,n.policy.rules);if(r?.recordSegment({type:"custom-rules-check",rulesChecked:n.policy.rules.length>0,matched:!!S,reason:S?.reason}),S)return et(S)}else r?.recordSegment({type:"custom-rules-check",rulesChecked:!1,matched:!1});return null}function oR(e,t,n,r,o,i){let s=Ku(e);if(s.argvSource?.kind==="absent")return xe(o);if(s.argvSourceApplies&&s.argvSource){let l=Qo(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 Qo(a,n,t,r,o,i,!0)}function Qo(e,t,n,r,o,i,s=!1){if(s&&/[$`*?[\]]/.test(e))return xe(o);let a=Nn(e,t,r.environment.paths),l=a?r.literalHeredocFiles?.get(a):void 0;if(l===void 0)return s?xe(o):null;return De(r.derivedCommandWorkBudget,1),o?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:l,depth:i+1}),r.analyzeNested(l,{effectiveCwd:t,envAssignments:n})}function iR(e){let t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.at(-1)===t?e.slice(1,-1):e}function sR(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 Gd(e){if(e.iterations>=on)throw new Ce;e.iterations++}function et(e){return{reason:e.reason,ruleId:e.id||void 0,intent:e.intent}}function xe(e){return e?.recordSegment({type:"error",message:Ud}),et(jd())}function jd(){return{id:"",reason:Ud,intent:"stop_and_explain"}}function Hd(e,t){return ne.has(t)||e==="$SHELL"||e==="${SHELL}"||ne.has(M(t))}function aR(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=lR(e,n,o);if(i)return i}return null}function lR(e,t,n){let r=n.tokens[0];if(!r)return null;let o=B(r);if(Hd(r,o)){De(e.options.derivedCommandWorkBudget,e.words.length-t);let l=n.tokens;if(Ie(l))return null;let c=Ze(l);if(!c){if(Je(W(l)).kind==="dynamic")return jd();return Jo(e,n)}let u=e.options.analyzeNested(c,{effectiveCwd:n.wrapperCwd===void 0?e.effectiveCwd:n.wrapperCwd,envAssignments:n.envAssignments});return u?qt(u):Jo(e,n)}let i=$d(o);if(!i||o==="xargs"||o==="parallel"){if(n.wrappedByTransparent&&e.options.policy.rules.length>0)De(e.options.derivedCommandWorkBudget,e.words.length-t);return Jo(e,n)}De(e.options.derivedCommandWorkBudget,e.words.length-t);let s=[o,...n.tokens.slice(1)],a={...e,words:W(s),head:o,cwd:n.cwd,originalCwd:n.wrapperCwd===null?void 0:e.originalCwd,envAssignments:n.envAssignments,allowTmpdirVar:!Ln(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)??Jo(e,n)}function Jo(e,t){return t.wrappedByTransparent?se(t.tokens,e.options.policy.rules):null}function zd(e,t){return e?.id.startsWith("custom.")||e?.id==="raw-text.dangerous-command"?e:I(e,t)}var cR=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,uR=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function dR(e,t){let n=Kd(e,t);if(n.length===0)return!1;let r=n[qd(n)];if(r==="cd"||r==="pushd"||r==="popd")return!0;return cR.test(e.join(" "))}function Vd(e,t,n,r){if(e.dialect==="powershell"){let a=mR(e.words,r);if(a.kind==="none")return;if(!t||a.kind==="unknown")return null;return Bd(hR(a.target),t,n.paths)}let o=e.words.map(k);if(!dR(o,n))return;if(!t)return null;let i=Kd(o,n,t),s=qd(i);if(s===-1||i[s]!=="cd")return null;return Bd(i[s+1],t,n.paths)}function Bd(e,t,n){if(!e||e==="-"||e.includes("$")||e.includes("`"))return null;try{return yR(mt(t,e,n),t,n)?t:null}catch{return null}}function mR(e,t){let n=fR(e[0])?1:0,r=e[n];if(!pR(r,n===1))return{kind:"none"};let o=r.text.toLowerCase(),i=o.split(/[\\/]/).pop()??o;if(!uR.has(i))return{kind:"none"};if(o!==i||i==="pop-location"||i==="popd")return{kind:"unknown"};return gR(e.slice(n+1),t)}function fR(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&(e.text==="&"||e.text===".")}function pR(e,t){return e?.provenance==="literal"&&(t||!e.quoted&&e.raw===e.text)}function gR(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 hR(e){return e.includes("::")?void 0:e.replaceAll("\\","/")}function qd(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 Kd(e,t,n){let r=CR(e);return pt([...r],t,n)}function yR(e,t,n){let r=n.realpath(e),o=n.realpath(t);if(r===null||o===null)return Xo(e)===Xo(t);return Xo(r)===Xo(o)}function CR(e){let t=0;while(t<e.length){let n=e[t];if(n==="{"||n==="("||n==="$(")t++;else break}return e.slice(t)}var oa="TMPDIR",ia="IFS",Yd=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Zd=/^[A-Za-z_][A-Za-z0-9_]*$/,Xd=new Set(["export","typeset","declare","readonly"]),SR=new Set(["builtin","command","time"]);function Jd(e,t){return{env:e,effectiveEnvAssignments:ER(e,t),shellAssignments:new Map}}function Qd(e){return{env:e.env,effectiveEnvAssignments:e.effectiveEnvAssignments?new Map(e.effectiveEnvAssignments):void 0,shellAssignments:new Map(e.shellAssignments)}}function sa(e,t){let n=tm(e,t);n.assignments.filter((s)=>s.persists).forEach((s)=>{t.shellAssignments.set(s.name,s.value),aa(t,s)});let r=n.commandIndex;if(r!==-1&&Xd.has(e[r]??""))e.filter((s)=>Zd.test(s)&&ra(s)).forEach((s)=>{_R(t,s)});let o=r===-1?-1:nm(e,r);if(o===-1||e[o]!=="unset")return;let i=wR(e,o);if(i===null)return;e.slice(i).forEach((s)=>{PR(t,s)})}function em(e,t){let n=tm(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 tm(e,t){let n=e.findIndex((s)=>!bR(s)),r=n!==-1&&Xd.has(e[nm(e,n)]??""),o=xR(t);return{assignments:e.flatMap((s,a)=>{let l=vR(s,o,t.env);if(!l)return[];if(n!==-1&&a>n&&!r&&!ki(l.name))return[];return o.set(l.name,l.value),[{...l,persists:n===-1||r}]}),commandIndex:n}}function nm(e,t){let n=t;while(SR.has(e[n]??"")){n+=1;while(e[n]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(e[n]??""))return t;n+=1}}return n}function bR(e){return Ae(e)!==null||Yd.test(e)}function vR(e,t,n){return Ae(e)??RR(e,t,n)}function RR(e,t,n){let r=Wr(e,n,t);if(r)return r;let o=e.match(Yd)?.[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 ra(e){return e===oa||e===ia||Oi(e)}function xR(e){return new Map([...e.effectiveEnvAssignments??[],...e.shellAssignments])}function ER(e,t){let n=[...Nr,oa,ia].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 aa(e,t){let n=new Map(e.effectiveEnvAssignments??[]);n.set(t.name,t.value),e.effectiveEnvAssignments=n}function _R(e,t){aa(e,{name:t,value:e.shellAssignments.get(t)??e.effectiveEnvAssignments?.get(t)??e.env.get(t)??""})}function PR(e,t){if(!ra(t)&&!Zd.test(t))return;if(e.shellAssignments.set(t,""),!ra(t)||t===oa||t===ia||wn(t)){aa(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 wR(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 AR="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Kt="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.",TR=64;function ma(e,t,n,r){let o=n.derivedCommandWorkBudget===void 0,i=n.parallelBudget===void 0;try{return IR(e,t,{...n,derivedCommandWorkBudget:n.derivedCommandWorkBudget??Hr(),parallelBudget:n.parallelBudget??jl()},r)}catch(s){let a=s instanceof Ce&&o?Dl:s instanceof oo&&i?$l: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 IR(e,t,n,r){if(t>=Yr)return n.trace?.recordSegment({type:"error",message:nt}),{reason:nt,segment:e,intent:"stop_and_explain"};let o=r??n.factStore?.getCommandProgram(e,n.shell??"auto")??We(e,n.shell);if(o.status==="limited")return n.trace?.recordSegment({type:"error",message:nt}),{reason:nt,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 da(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 lm(e,n),{reason:ft,segment:e,intent:"stop_and_explain"}}if(n.strict&&o.status==="partial")return lm(e,n),{reason:ft,segment:e,intent:"stop_and_explain"};if(o.issues.some((c)=>c.code.includes("quote"))&&!n.analyzePartialProgram)return da(e,n);let s=n.cwd,a=n.effectiveCwd!==void 0?n.effectiveCwd:n.cwd,l=Jd(n.environment.env,n.envAssignments);return ni(o,t,{...n,rootProgram:o},s,[{effectiveCwd:a,shellGitContextState:l,literalHeredocFiles:new Map(n.literalHeredocFiles),functionDefinitions:new Map(n.functionDefinitions)}]).result}function ni(e,t,n,r,o){let i=[...o],s,a;for(let[l,c]of e.nodes.entries()){if(c.kind==="connector"){a=c.operator;continue}let u=e.nodes[l+1],d=u?.kind==="connector"?u.operator:void 0,m=kR(e,l,c,a,d),f=a==="&&"||a==="||",p=f?s:void 0,g=a==="&&"?p?.success??i:a==="||"?p?.failure??i:i,h=a==="||"?p?.success??[]:[],y=a==="&&"?p?.failure??[]:[],x=f||vn(d);if(c.kind==="function"){let Z=g.flatMap((j)=>{let G=cr(j);return G.functionDefinitions.set(c.name,c.body),la(j,[G],m,d==="&",vn(d))}),X=ca(Z,[],h,y,a,d);i=X.states,s=X.conditionalStates,a=void 0;continue}if(c.kind==="group"){let Z=[],X=[];for(let G of g){let R=ni(c.body,t,n,r,[cr(G)]);if(R.result)return R;if(Z.push(...la(G,R.states,m,d==="&",vn(d))),x)X.push(G,...m?R.states.map((A)=>ei(G,A)):R.states)}let j=ca(Z,X,h,y,a,d);i=j.states,s=j.conditionalStates,a=void 0;continue}if(c.kind!=="command")continue;let P=n.trace?.flattenNested?n.trace.currentSegmentIndex:n.trace?.allocateSegment(),E=e.nodes[l-2],w=ri(a)&&E?.kind==="command"?Ju(E)??MR(E):void 0,O=[],_=[];for(let Z of g){let X=DR(c,t,n,r,[cr(Z)]);if(X.result)return{result:X.result,states:i};let j=e.dialect==="powershell"?X.states:X.states.map((G)=>ei(Z,G));for(let G of j){let R=cr(G),A=WR(c,t,n.trace?{...n,trace:cm(n.trace,P)}:n,r,R,ri(a),w);if(A)return{result:A,states:i};let z=ZR(c,R.functionDefinitions);if(z)De(n.derivedCommandWorkBudget,oi(z));let S=z?t+1>=Yr?ua(c.displayText,n,[R]):ni(z,t+1,n,r,[R]):{result:null,states:[R]};if(S.result)return S;if(O.push(...la(Z,S.states,m,d==="&",vn(d))),x)_.push(Z),_.push(...S.states.map((v)=>m?ei(Z,v):v))}}let F=ca(O,_,h,y,a,d);i=F.states,s=F.conditionalStates,a=void 0}return{result:null,states:i}}function kR(e,t,n,r,o){if(n.kind==="group"&&n.style==="subshell")return!0;if(e.dialect==="posix"&&(ri(r)||ri(o)))return!0;if(o==="&")return!0;return e.dialect==="powershell"&&n.kind==="group"&&n.style==="brace"&&OR(e,t)}function la(e,t,n,r,o){let i=n?t.map((a)=>ei(e,a)):[...t],s=o?i.flatMap((a)=>ur(e.literalHeredocFiles,a.literalHeredocFiles)?[a]:[{...a,literalHeredocFiles:new Map(e.literalHeredocFiles)},a]):i;return r?[e,...s]:s}function ei(e,t){return{...e,literalHeredocFiles:new Map(t.literalHeredocFiles)}}function OR(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(NR(n))return!0;return n.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function ri(e){return e==="|"||e==="|&"}function MR(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 vn(e){return e==="&&"||e==="||"}function ca(e,t,n,r,o,i){let s={success:ti([...n,...e]),failure:ti([...r,...t])},a=vn(i)?s:void 0;return{states:vn(o)||a?ti([...s.success,...s.failure]):s.success,conditionalStates:a}}function cm(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 DR(e,t,n,r,o){let i=e.nested.map((s)=>({program:s,depth:t}));if(e.dialect==="powershell"){let s=LR(e);if(s){if(t+1>=Yr)return ua(s,n,o);let a=We(s,"powershell");if(a.status==="limited")return ua(s,n,o);if(a.status!=="complete")return rm(i,n,r,o);De(n.derivedCommandWorkBudget,oi(a)),i.push({program:a,depth:t+1})}}return rm(i,n,r,o)}function NR(e){let t=e.words[0];return t?.provenance==="variable"&&e.words.at(-1)?.text==="="?t.text.toLowerCase():void 0}function rm(e,t,n,r){let o=[...r];for(let i of e){let s=[];for(let a of o){let l=ni(i.program,i.depth,t,n,[cr(a)]);if(l.result)return l;s.push(...l.states)}o=ti(s)}return{result:null,states:o}}function LR(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 oi(e){return e.nodes.reduce((t,n)=>t+(n.kind==="command"?n.words.length+n.nested.reduce((r,o)=>r+oi(o),0):n.kind==="group"||n.kind==="function"?oi(n.body):0),0)}function ua(e,t,n){return t.trace?.recordSegment({type:"error",message:nt}),{result:{reason:nt,segment:e,intent:"stop_and_explain"},states:[...n]}}function WR(e,t,n,r,o,i,s){let a=jR(e);if(a&&n.strict)return n.trace?.recordSegment({type:"error",message:a}),{reason:a,segment:e.source,intent:"stop_and_explain"};um(e,o,"before-consumer",n.environment.paths);let l=en(e.dialect,e.words).map(k),c=e.displayText,u=em(l,o.shellGitContextState);if(e.dialect==="powershell"){let f=I(Cu(e,i,JR(n,o.effectiveCwd)),n.policy);if(n.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!f,reason:f?.reason}),f)return XR(c,f)}if(l.length===1&&l[0]?.includes(" ")&&!zn(e.dialect,e.words)){let f=I(it(l[0],n.scanWork),n.policy),p=f!==null&&!n.strict&&kl(e,n.rootProgram,n.scanWork);if(f&&!p)return n.trace?.recordSegment({type:"dangerous-text",token:l[0],matched:!0,reason:f.reason}),{reason:f.reason,segment:c,ruleId:f.id,intent:f.intent};n.trace?.recordSegment({type:"dangerous-text",token:l[0],matched:!1});let g=om(e,a,o,u,s,n);if(g)return g;return sa(l,o.shellGitContextState),null}let d=lr(e.words,t,{...n,commandView:e,cwd:r,effectiveCwd:o.effectiveCwd,envAssignments:u,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:o.functionDefinitions,hasPipelineInput:i,literalShellInput:s,analyzeNested:(f,p)=>{let g=p&&Object.hasOwn(p,"effectiveCwd")?p.effectiveCwd:o.effectiveCwd,h=ma(f,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?cm(n.trace,n.trace.currentSegmentIndex,!0):void 0});return h?{reason:h.reason,ruleId:h.ruleId,intent:h.intent}:null}});if(d)return{...d,segment:c};let m=om(e,a,o,u,s,n);if(m)return m;return sa(l,o.shellGitContextState),null}function om(e,t,n,r,o,i){let s=HR(e,t,n,r??new Map,i);if(s)return s;return um(e,n,"after-consumer",i.environment.paths),n.literalHeredocFiles.clear(),zR(e,t,n,i.environment.paths),KR(e,n,o,i.environment,i.trace),null}var FR=new Set([">>","<>"]);function um(e,t,n,r){for(let i of e.redirections){if(!(n==="before-consumer"?GR(i):FR.has(i.operator)))continue;im(i.target,t,r)}if(n!=="before-consumer"||!Ee(e.words[0],"tee"))return;let o=dm(e.words.slice(1));if(!o)return;for(let i of o.operands)im(i,t,r)}function GR(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 im(e,t,n){let r=e?.provenance==="literal"?Nn(e.text,t.effectiveCwd,n):void 0;if(!r)return;t.literalHeredocFiles.delete(r)}function zR(e,t,n,r){if(t)return;let o=e.redirections.find((i)=>i.operator==="<<"||i.operator==="<<-")?.heredoc;if(!o||!ii(o))return;for(let i of BR(e)){let s=Nn(i.text,n.effectiveCwd,r);if(!s||!Fl(s))continue;if(!n.literalHeredocFiles.has(s)&&n.literalHeredocFiles.size>=Wl)throw new Ce;n.literalHeredocFiles.set(s,o.body)}}function BR(e){let t=$R(e.redirections)?.target,n=sm(t)?[t]:[];if(Ee(e.words[0],"cat"))return UR(e.words)?n:[];if(!Ee(e.words[0],"tee"))return[];let r=dm(e.words.slice(1));if(!r||r.append||r.hasUnsupportedOptions||!r.operands.every(sm))return[];return[...r.operands,...n]}function UR(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 $R(e){let t=e.findLast((n)=>(n.fd??([">",">|",">>",">&"].includes(n.operator)?1:0))===1);return t?.operator===">"||t?.operator===">|"?t:void 0}function dm(e){let t=[],n=!0,r=!1,o=!1;for(let i of e){if(i.provenance!=="literal")return;if(n&&Ee(i,"--")){n=!1;continue}if(n&&!i.quoted&&i.raw===i.text&&/^-[^-]/.test(i.text)){r||=i.text.slice(1).includes("a"),o||=[...i.text.slice(1)].some((s)=>s!=="a"&&s!=="i");continue}if(n&&!i.quoted&&i.raw===i.text&&i.text.startsWith("--")){r||=i.text==="--append",o||=i.text!=="--append"&&i.text!=="--ignore-interrupts";continue}t.push(i)}return{operands:t,append:r,hasUnsupportedOptions:o}}function sm(e){if(!e||e.provenance!=="literal"||e.text.length===0)return!1;if(e.quoted||e.raw!==e.text)return!0;return!e.raw.startsWith("~")&&!/[{}]/.test(e.raw)}function Ee(e,t){return e?.text===t&&e.raw===t&&e.provenance==="literal"&&!e.quoted}function ii(e){return e.quotedDelimiter||!/[$`\\]/.test(e.body)}function jR(e){let t=e.redirections.filter((s)=>s.operator==="<<"||s.operator==="<<-");if(t.length===0)return;if(t.length!==1)return Kt;let n=t[0];if(!n?.heredoc)return Kt;if(!ii(n.heredoc))return AR;if(n.fd!==void 0&&n.fd!==0)return Kt;if(e.redirections.some((s)=>s!==n&&["<","<<","<<-","<<<","<&","<>"].includes(s.operator)))return Kt;let r=e.redirections.some((s)=>s!==n&&am(s.target));if(Ee(e.words[0],"cat"))return r?Kt:void 0;if(Ee(e.words[0],"tee"))return r||e.words.slice(1).some(am)?Kt:void 0;let o=e.words[0],i=e.words[1];if(Ee(o,"git")&&(Ee(i,"apply")||Ee(i,"commit")))return;if(Ee(o,"gh")&&(Ee(i,"pr")||Ee(i,"issue"))&&Ee(e.words[2],"create"))return;return Kt}function am(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}function HR(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(qR(e,i,n,r,o))return null;let a=VR(e,i,o);if(a!==void 0)return a?{reason:a.reason,segment:e.displayText,ruleId:a.id,intent:a.intent}:null;let l=da(s.length===i.length?s.join(`
42
- `):e.source,o);return l?{...l,segment:e.displayText}:null}function VR(e,t,n){let r=t.length===1?t[0]:void 0;if(!r?.heredoc||!ii(r.heredoc)||r.fd!==void 0&&r.fd!==0)return;let o=e.words[0];if(o?.provenance!=="literal"||!Se(o.text))return;if(!e.words.slice(1).every((c)=>c.provenance==="literal"&&c.text.startsWith("-")))return;let s=r.heredoc.body,a=te(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(n.trace?.recordSegment({type:"interpreter",interpreter:o.text,codeArg:s,paranoidBlocked:a}),a){let c=I(C("interpreter.one-liner-paranoid",an),n.policy);if(c)return c}if(!ln(s,n.scanWork))return null;let l=I(C("interpreter.dangerous-command",Dt),n.policy);if(!l)return null;return n.trace?.recordSegment({type:"dangerous-text",token:s,matched:!0,reason:l.reason}),l}function qR(e,t,n,r,o){let i=t.length===1?t[0]:void 0;if(!i?.heredoc||!ii(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(k),l=B(a[0]??"");if((s.envSplitValues?.length??0)>0||!ne.has(l)&&!ne.has(M(l)))return!1;return Ie(a)}function KR(e,t,n,r,o){let i=Vd(e,t.effectiveCwd,r,n);if(i===null)o?.recordSegment({type:"cwd-change",segment:e.words.map(k).join(" "),effectiveCwdNowUnknown:!0});if(i!==void 0)t.effectiveCwd=i}function cr(e){return{effectiveCwd:e.effectiveCwd,shellGitContextState:Qd(e.shellGitContextState),literalHeredocFiles:new Map(e.literalHeredocFiles),functionDefinitions:new Map(e.functionDefinitions)}}function ti(e){let t=[];for(let n of e){if(!t.some((r)=>YR(r,n)))t.push(n);if(t.length>TR)throw new Ce}return t}function YR(e,t){return e.effectiveCwd===t.effectiveCwd&&ur(e.literalHeredocFiles,t.literalHeredocFiles)&&ur(e.functionDefinitions,t.functionDefinitions)&&ur(e.shellGitContextState.effectiveEnvAssignments,t.shellGitContextState.effectiveEnvAssignments)&&ur(e.shellGitContextState.shellAssignments,t.shellGitContextState.shellAssignments)}function ur(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 ZR(e,t){let n=xo(e);return n===void 0?void 0:t.get(n)}function XR(e,t){if(!t)return null;return{reason:t.reason,segment:e,ruleId:t.id,intent:t.intent}}function JR(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 da(e,t){let n=I(it(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 lm(e,t){let n={type:"strict-unparseable",rawCommand:e,reason:ft};if(t.trace?.currentSegmentIndex===void 0)t.trace?.recordGlobal(n);else t.trace.recordSegment(n)}var dr=["fail_closed","paranoid_rm","paranoid_interpreters"],si={standard:{fail_closed:!1,paranoid_rm:!1,paranoid_interpreters:!1},strict:{fail_closed:!0,paranoid_rm:!1,paranoid_interpreters:!1},paranoid:{fail_closed:!0,paranoid_rm:!0,paranoid_interpreters:!0}};var le={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"}},ai=["standard","strict","paranoid"];function QR(e,t){if(!t)return e;return ai.indexOf(t)>ai.indexOf(e)?t:e}function ex(){let e=pa(le.level);if(e===void 0||e==="")return;if(ai.includes(e))return e;console.error(`CC Safety Net: ignored invalid ${le.level.name}=${JSON.stringify(e.slice(0,40))}. Use ${ai.join(", ")}.`);return}function tx(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function sO(){return tx(pa(le.auditScope))==="all"}function fa(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 li(e={}){let t=e.safety?.level??"standard",n=ex(),r=QR(t,n),o=si[r],i={failClosed:o.fail_closed,paranoidRm:o.paranoid_rm,paranoidInterpreters:o.paranoid_interpreters},s={failClosed:r===t?"preset":"environment",paranoidRm:r===t?"preset":"environment",paranoidInterpreters:r===t?"preset":"environment"},a={failClosed:[`policy safety.level=${t}`],paranoidRm:[`policy safety.level=${t}`],paranoidInterpreters:[`policy safety.level=${t}`]};if(r!==t)a.failClosed.push(`env ${le.level.name}=${n}`),a.paranoidRm.push(`env ${le.level.name}=${n}`),a.paranoidInterpreters.push(`env ${le.level.name}=${n}`);if(e.safety?.overrides?.failClosed!==void 0)i.failClosed=e.safety.overrides.failClosed,s.failClosed="capability_override",a.failClosed.push("policy safety.overrides.fail_closed");if(e.safety?.overrides?.paranoidRm!==void 0)i.paranoidRm=e.safety.overrides.paranoidRm,s.paranoidRm="capability_override",a.paranoidRm.push("policy safety.overrides.paranoid_rm");if(e.safety?.overrides?.paranoidInterpreters!==void 0)i.paranoidInterpreters=e.safety.overrides.paranoidInterpreters,s.paranoidInterpreters="capability_override",a.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(mr(le.strict))i.failClosed=!0,s.failClosed="environment",a.failClosed.push(`env ${le.strict.name}`);if(mr(le.paranoid))i.paranoidRm=!0,i.paranoidInterpreters=!0,s.paranoidRm="environment",s.paranoidInterpreters="environment",a.paranoidRm.push(`env ${le.paranoid.name}`),a.paranoidInterpreters.push(`env ${le.paranoid.name}`);if(mr(le.paranoidRm))i.paranoidRm=!0,s.paranoidRm="environment",a.paranoidRm.push(`env ${le.paranoidRm.name}`);if(mr(le.paranoidInterpreters))i.paranoidInterpreters=!0,s.paranoidInterpreters="environment",a.paranoidInterpreters.push(`env ${le.paranoidInterpreters.name}`);let l=!!e.worktreeMode||mr(le.worktree);return{strict:i.failClosed,paranoidRm:i.paranoidRm,paranoidInterpreters:i.paranoidInterpreters,worktreeMode:l,effectiveLevel:fa(i),capabilities:{fail_closed:{enabled:i.failClosed,source:s.failClosed,sources:a.failClosed},paranoid_rm:{enabled:i.paranoidRm,source:s.paranoidRm,sources:a.paranoidRm},paranoid_interpreters:{enabled:i.paranoidInterpreters,source:s.paranoidInterpreters,sources:a.paranoidInterpreters}}}}function mr(e){let t=typeof e==="string"?fr(e):pa(e);return t==="1"||t?.toLowerCase()==="true"}function fr(e){return Object.hasOwn(process.env,e)?process.env[e]:void 0}function pa(e){let t=fr(e.name);if(t!==void 0)return t;if(e.legacyName)return fr(e.legacyName);return}function aO(e){return fr(e.name)!==void 0||!!e.legacyName&&fr(e.legacyName)!==void 0}function mm(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:ga(t.fail_closed,e.strict,"strict"),paranoid_rm:ga(t.paranoid_rm,e.paranoidRm,"paranoidRm"),paranoid_interpreters:ga(t.paranoid_interpreters,e.paranoidInterpreters,"paranoidInterpreters")};return{policy:Tl(e.policySnapshot.policy,i),effectiveCapabilities:i,effectiveLevel:fa({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}function ga(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 pO(e,t){return ha(e,t)}function ha(e,t,n,r){let o=ma(e,0,{...t,...mm(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}]}}var nx=new Set(["src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js"]),Ca=new Set(["cc-safety-net","ccsn"]),rx=new Set(["bunx","npx","pnpx"]),ox=new Set(["pnpm","yarn"]),ix=new Set(["npm","pnpm","yarn"]),sx=new Set(["bun","node"]);function ui(e,t,n={}){if(Ca.has(e))return 0;if(rx.has(e)){if(n.broad)return ya(t);let o=t[0]==="-y"||t[0]==="--yes"?1:0;return ci(t[o])?o+1:null}let r=n.broad?t.findIndex((o)=>!o.startsWith("-")):0;if(r!==-1&&ix.has(e)&&n.broad&&t[r]==="exec"){let o=ya(t.slice(r+1));return o===null?null:r+1+o}if(ox.has(e)){if(e==="yarn"&&!n.broad)return null;if(!n.broad)return t[0]==="dlx"&&ci(t[1])?2:null;if(r===-1||t[r]!=="dlx")return null;let o=ya(t.slice(r+1));return o===null?null:r+1+o}if(sx.has(e)){let o=n.broad&&r!==-1?r:0;if(fm(t[o]))return o+1;if(e==="bun"&&t[o]==="run"&&fm(t[o+1]))return o+2}return null}function ya(e){let t=e.findIndex((r)=>ci(r));if(t===-1)return null;let n=t;while(n<e.length){let r=e[n]??"";if(!r.startsWith("-")&&!ci(r))break;n++}return n}function ci(e){if(!e)return!1;let t=e.indexOf("@");if(t===-1)return Ca.has(e);if(t===0)return!1;let n=e.slice(t+1);if(n===""||n.includes("/")||n.includes(":"))return!1;return Ca.has(e.slice(0,t))}function fm(e){let t=e?.replaceAll("\\","/");return[...nx].some((n)=>t===n||t?.endsWith(`/${n}`))}var pm="Only the user may apply a policy proposal, because it rewrites the configuration CC Safety Net enforces. Ask them to run `cc-safety-net policy apply <file>` themselves in a terminal; you can run `cc-safety-net policy check <file>` to show them what it would change.";function gm(e){let t=ue(e,"input-candidate");if(!t)return null;let n=st(Me()),r=fn(t.shell,e.invocation.context.executionCwd,n,{findSegmentTarget:(o)=>ax(o,n.environment),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null,normalizeCwd:ie});return r?{target:r}:null}function ax(e,t){let n=pt([...e],t),r=n.slice(1),o=ui(M(n[0]??"").toLowerCase(),r,{broad:!0});if(o===null)return null;let i=r.slice(o).filter((s)=>s!=="-g"&&s!=="--global");return i[0]==="policy"&&i[1]==="apply"?n.join(" "):null}import{dirname as xi}from"node:path";import{chmodSync as rE,existsSync as Ga,mkdirSync as oE,readFileSync as za}from"node:fs";import{dirname as gf,join as iE}from"node:path";import{createRequire as hx}from"node:module";var hm=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var ym=30,Sa=1,ba=365;function Cm(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var pr=64,bm="Rule config exceeds CC Safety Net's safe source limit.";var Sm=Object.freeze({maxSources:64,concurrency:4,maxRequests:131,maxResponseBytes:67108864});function lx(e={}){return{requests:0,responseBytes:0,maxRequests:e.maxRequests??Sm.maxRequests,maxResponseBytes:e.maxResponseBytes??Sm.maxResponseBytes}}function AO(e){return{controller:new AbortController,budget:lx(),resolveUrl:e}}function TO(e){return e instanceof Error&&e.message==="Rule synchronization exceeds CC Safety Net's safe resource limits."}function IO(e){if(e.requests>=e.maxRequests)throw Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");e.requests++}function kO(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 ct=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,vm="rulebook.json",Rm=".cc-safety-net/rules";var xm=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,cx=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,Em=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,ux=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),dx="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),MO=new RegExp(`^${ux}/(${ct.source.slice(1,-1)})/${dx}$`);function _m(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function Pm(e){if(di(e))try{return va(e),null}catch(t){return t instanceof Error?t.message:String(t)}return ct.test(e)?null:`Local rulebook sources must be bare names matching ${ct}: ${e}`}function va(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(xm);if(!t?.[1]||!t[2]||!t[3])throw Error(`Invalid GitHub rulebook source: ${e}`);let n=t[3].lastIndexOf("/");if(n<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);let r=t[3].slice(0,n),o=t[3].slice(n+1);if(!r||!Em.test(r))throw Error(`GitHub rulebook refs must use valid path segments: ${e}`);if(!o||!ct.test(o))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);return{owner:t[1],repo:t[2],ref:r,path:_m(o),name:o}}function DO(e){return cx.test(e)}function NO(e){return Em.test(e)}function di(e){return xm.test(e)}function LO(e){if(!ct.test(e))throw Error(`Local rulebook sources must be bare names matching ${ct}: ${e}`)}var Ra=[{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"}],mi={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},mx=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],fx=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],xa=[{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"]},...fx.flatMap((e)=>mx.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 fi=[{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"}],px=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Ea=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})),_a=wm.flatMap((e)=>px.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}))),gr={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)$/},Pa=["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})),wa=[{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?$/}],Am=[...Ra,mi,...xa,...Ea,..._a,gr,...Pa,...wa,...fi].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}})),pi=new Set(fi.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),gx=Am.map((e)=>e.id),hr=new Set(gx);var yx=hx(import.meta.url),Tm,Cx=Array(pr+1).fill("over-limit"),Im=/^[^/]+\/[^/]+$/,gi=`must be an integer between ${Sa} and ${ba}`,Sx=["version","rules","overrides","transparent_wrappers"],bx=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function km(e){if(!je(e)||!Array.isArray(e.rules)||e.rules.length<=pr)return e;return{$schema:e.$schema,version:e.version,rules:Cx,overrides:e.overrides,transparent_wrappers:e.transparent_wrappers}}function vx(){let e=yx("../vendor/zod.cjs"),t=(R)=>{let A=e.superRefine(R);return A._zod.def.when=()=>!0,A},n=e.enum(hm),r=e.union([e.literal("off"),e.looseObject({reason:e.string({error:"required non-empty string"}).min(1,"required non-empty string").max(sn,`must be at most ${sn} 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(Mt,"must match command pattern").describe("Command name such as 'git', 'docker', or 'rtk'."),s=e.looseObject({$schema:e.unknown().optional().describe("JSON Schema reference for IDE support"),version:e.literal(1).describe("Schema version (must be 1)"),rules:e.array(o,{error:"must be an array of rulebook source strings"}).max(pr,bm).default([]).describe("Rulebook source strings such as project-rules or owner/repo#main/team-rules"),overrides:e.record(e.string().meta({pattern:Im.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=(R,A)=>{if(!je(R))return;if(Array.isArray(R.rules)&&R.rules.length<=pr){let S=new Set;R.rules.forEach((v,T)=>{if(typeof v!=="string"||v==="")return;if(v.trim()===""){A.addIssue({code:"custom",message:"must be a non-empty rulebook source string",path:["rules",T]});return}let L=Pm(v);if(L){A.addIssue({code:"custom",message:L,path:["rules",T]});return}if(S.has(v)){A.addIssue({code:"custom",message:`duplicate rulebook source "${v}"`,path:["rules",T]});return}S.add(v)})}if(je(R.overrides))for(let S of Object.keys(R.overrides)){if(Im.test(S))continue;A.addIssue({code:"custom",message:"must use <rulebook-name>/<rule-name>",path:["overrides",S]})}if(!Array.isArray(R.transparent_wrappers))return;let z=new Set;R.transparent_wrappers.forEach((S,v)=>{if(typeof S!=="string"||!Mt.test(S))return;if(z.has(S)){A.addIssue({code:"custom",message:`duplicate command "${S}"`,path:["transparent_wrappers",v]});return}if(_u(S)){A.addIssue({code:"custom",message:`reserved command "${S}" cannot be a wrapper`,path:["transparent_wrappers",v]});return}z.add(S)})},l=e.preprocess(km,s.check(e.superRefine(a))),c=e.preprocess(km,s.check(t(a))),u=e.strictObject({fail_closed:e.boolean().optional(),paranoid_rm:e.boolean().optional(),paranoid_interpreters:e.boolean().optional()}),d=(R,A)=>e.intersection(e.record(e.string().refine((z)=>R.has(z),{error:(z)=>`unknown ${A} rule id "${String(z.input)}"`}),e.unknown()),e.record(e.string(),e.enum(["on","off"]))),m=(R)=>e.array(e.string({error:"must be a non-empty path string"}),{error:"must be an array of paths"}).check(t((A,z)=>{if(!Array.isArray(A))return;let S=kt();A.forEach((v,T)=>{if(typeof v!=="string")return;let L=R(v,S);if(L)z.addIssue({code:"custom",message:L,path:[T]})})})),f=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:d(Dn,"destructive command").optional(),allow_paths:m(Mo).optional()}).optional(),secret_protection:e.strictObject({enabled:e.boolean().optional(),overrides:d(hr,"secret protection").optional(),deny_paths:m(Do).optional(),allow_paths:m(No).optional()}).optional(),audit:e.strictObject({retention_days:e.number({error:gi}).int(gi).min(Sa,gi).max(ba,gi).optional().describe("Days of audit log history to keep before the sweep deletes it")}).optional()}),p=(R,A)=>{if(!Array.isArray(R))return;let z=new Set;R.forEach((S,v)=>{let T=je(S)?S.name:void 0;if(typeof T!=="string")return;if(z.has(T.toLowerCase())){A.addIssue({code:"custom",message:`duplicate rule name "${T}"`,path:[v,"name"]});return}z.add(T.toLowerCase())})},g=(R)=>{let A=(v,T)=>R==="legacy"?v:T,z=A("must match pattern (letters, numbers, hyphens, underscores)","must match command pattern"),S=`required non-empty string up to ${sn} characters`;return e.looseObject({name:e.string({error:"required string"}).regex(ct,A("must match pattern (letters, numbers, hyphens, underscores; max 64 chars)","must match rule name pattern")),command:e.string({error:A("required string","required string matching command pattern")}).regex(Mt,A(z,"required string matching command pattern")),subcommand:e.string({error:A("must be a string if provided","must match command pattern")}).regex(Mt,z).optional(),block_args:e.array(e.string({error:A("must be a string","must be a non-empty string")}).refine((v)=>v!=="",{error:A("must not be empty","must be a non-empty string")}),{error:A("required array","required non-empty array")}).refine((v)=>v.length>0,{error:A("must have at least one element","required non-empty array")}),reason:e.string({error:A("required string",S)}).refine((v)=>v!=="",{error:A("must not be empty",S)}).refine((v)=>v.length<=sn,{error:A(`must be at most ${sn} characters`,S)}),intent:n.optional()},{error:"must be an object"})},h=(R)=>e.array(g(R),{error:R==="legacy"?"must be an array":"required array"}).check(t(p)),y=e.looseObject({version:e.literal(1),rules:h("legacy").optional()}),x="required string matching rule name pattern",P=e.looseObject({command:e.string({error:"required non-empty string"}).refine((R)=>R.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((R,A)=>{if(!je(R))return;if(R.expect!=="blocked"||typeof R.rule==="string")return;A.addIssue({code:"custom",message:"required string for blocked fixtures",path:["rule"]})})),E=(R,A)=>{if(!je(R))return;let z=new Set(Aa(R));if(Array.isArray(R.tests)){let v=new Set(R.tests.flatMap((T)=>je(T)&&T.expect==="blocked"&&typeof T.rule==="string"?[T.rule]:[]));for(let T of v){if(z.has(T))continue;A.addIssue({code:"custom",message:`blocked fixture references unknown rule "${T}"`,path:["tests"]})}}if(!Array.isArray(R.allowed_commands)||!Array.isArray(R.rules))return;let S=new Set(R.allowed_commands.filter((v)=>typeof v==="string"));R.rules.forEach((v,T)=>{let L=je(v)?v.command:void 0;if(typeof L!=="string"||S.has(L))return;A.addIssue({code:"custom",message:`"${L}" must be listed in allowed_commands`,path:["rules",T,"command"]})})},w=(R)=>e.looseObject({name:e.string({error:"required string matching rule name pattern"}).regex(ct,"required string matching rule name pattern"),version:e.string({error:"required non-empty string"}).refine((A)=>A!=="",{error:"required non-empty string"}),allowed_commands:e.array(e.string({error:"must match command pattern"}).regex(Mt,"must match command pattern"),{error:"required array"}).check(t((A,z)=>{if(!Array.isArray(A))return;let S=new Set;A.forEach((v,T)=>{if(typeof v!=="string"||!Mt.test(v))return;if(S.has(v)){z.addIssue({code:"custom",message:`duplicate command "${v}"`,path:[T]});return}S.add(v)})})),rules:R,tests:e.array(P,{error:"must be an array if provided"}).optional()}).check(t(E)),O=w(h("rulebook")),_=e.string({error:"must be a non-empty string"}).refine((R)=>R!=="",{error:"must be a non-empty string"}),F="must be a non-empty array of unique non-empty strings",Z="required non-empty array of non-empty strings",X=e.array(_,{error:"must be a non-empty array of unique non-empty strings"}).refine((R)=>R.length>0,{error:"must be a non-empty array of unique non-empty strings"}).refine((R)=>new Set(R).size===R.length,{error:"must not contain duplicate values"}),j=e.looseObject({command_path:e.array(_,{error:"required non-empty array of non-empty strings"}).refine((R)=>R.length>0,{error:"required non-empty array of non-empty strings"}),any_args:X.optional(),exclude_args:X.optional()},{error:"required object"}),G=w(e.array(g("rulebook").omit({subcommand:!0,block_args:!0}).extend({match:j,subcommand:e.never({error:"not supported in rulebook_version 2"}).optional(),block_args:e.never({error:"not supported in rulebook_version 2"}).optional()}),{error:"required array"}).check(t(p)));return{RulesConfigSchema:l,RulesConfigDiagnosticSchema:c,RuleOverrideSchema:r,UserPolicySchema:f,LegacyConfigSchema:y,RulebookSchema:O,RulebookV2Schema:G}}function Rn(){return Tm??=vx(),Tm}function Om(){return Rn().RulesConfigSchema}function Rx(){return Rn().UserPolicySchema}function ZO(){return Rn().LegacyConfigSchema}function Mm(){return Rn().RulebookSchema}function Dm(){return Rn().RulebookV2Schema}function Aa(e){let t=je(e)?e.rules:void 0;return(Array.isArray(t)?t:[]).flatMap((n)=>{let r=je(n)?n.name:void 0;return typeof r==="string"?[r]:[]})}function Nm(e){let t=Rn().RulesConfigDiagnosticSchema.safeParse(e);if(t.success)return{errors:[],sources:new Set(t.data.rules)};return{errors:hi(Wm(t.error.issues,Sx)),sources:Px(e,t.error.issues)}}function yr(e){let t=Rx().safeParse(e);if(t.success)return[];return hi(Wm(t.error.issues,bx)," ")}function hi(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=_x(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}${xx(e)}`]}function xx(e){if(e.code==="invalid_value")return`must be ${Ex(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 Ex(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 _x(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function Wm(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 Px(e,t){let n=je(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 je(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}var Fm={standard:0,strict:1,paranoid:2};function Bm(e,t){return{policy:{version:1,safety:{level:t.safety?.level??e.safety.level,overrides:{...e.safety.overrides,...t.safety?.overrides}},workflow:{worktree_mode:t.workflow?.worktree_mode??e.workflow.worktree_mode},destructive_command_protection:{enabled:t.destructive_command_protection?.enabled??e.destructive_command_protection.enabled,overrides:{...e.destructive_command_protection.overrides,...t.destructive_command_protection?.overrides},allow_paths:Ta(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths)},secret_protection:{enabled:t.secret_protection?.enabled??e.secret_protection.enabled,overrides:{...e.secret_protection.overrides,...t.secret_protection?.overrides},deny_paths:Ta(e.secret_protection.deny_paths,t.secret_protection?.deny_paths),allow_paths:Ta(e.secret_protection.allow_paths,t.secret_protection?.allow_paths)},audit:e.audit},weakenings:wx(e,t)}}function Ta(e,t){return[...new Set([...e,...t??[]])]}function wx(e,t){let n=t.safety?.level,r=si[e.safety.level];return[...n&&Fm[n]<Fm[e.safety.level]?[`project policy lowers level: ${e.safety.level} -> ${n}`]:[],...dr.flatMap((o)=>t.safety?.overrides?.[o]===!1&&(e.safety.overrides[o]??r[o])?[`project policy disables ${o}`]:[]),...t.workflow?.worktree_mode===!0&&!e.workflow.worktree_mode?["project policy enables worktree mode relaxations"]:[],...t.destructive_command_protection?.enabled===!1&&e.destructive_command_protection.enabled?["project policy disables destructive command protection"]:[],...t.secret_protection?.enabled===!1&&e.secret_protection.enabled?["project policy disables secret protection"]:[],...Gm(t.destructive_command_protection?.overrides,(o)=>e.destructive_command_protection.enabled&&e.destructive_command_protection.overrides[o]!=="off"),...Gm(t.secret_protection?.overrides,(o)=>e.secret_protection.enabled&&(e.secret_protection.overrides[o]==="on"?!0:e.secret_protection.overrides[o]!=="off"&&!pi.has(o))),...e.destructive_command_protection.enabled?zm(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths).map((o)=>`project policy adds destructive allow path: ${o}`):[],...e.secret_protection.enabled?zm(e.secret_protection.allow_paths,t.secret_protection?.allow_paths).map((o)=>`project policy adds secret allow path: ${o}`):[]]}function Gm(e,t){return Object.entries(e??{}).flatMap(([n,r])=>r==="off"&&t(n)?[`project policy disables rule ${n}`]:[])}function zm(e,t){return(t??[]).filter((n)=>!e.includes(n))}import{randomBytes as Ax}from"node:crypto";import{closeSync as Oa,constants as Cr,fstatSync as Ia,fsyncSync as Tx,lstatSync as xt,mkdirSync as Um,openSync as $m,readdirSync as Ma,readFileSync as Ix,realpathSync as Yt,renameSync as kx,rmdirSync as jm,statSync as ka,unlinkSync as Da,writeFileSync as Ox}from"node:fs";import{isAbsolute as Hm,join as xn,normalize as Mx,parse as Vm,relative as Na,resolve as La,sep as yi}from"node:path";var Dx=Symbol("PolicyFilesystemScope"),Nx=Symbol("PolicyFilesystemTarget"),qm=Cr.O_NOFOLLOW??0;class D extends Error{constructor(e){super(`Unable to access ${e} filesystem safely.`);this.name="PolicyFilesystemError"}}function Et(e,t){return{[Dx]:!0,root:La(e),label:t}}function br(e,t){let n=Mx(t);if(t===""||Hm(t)||n===".."||n.startsWith(`..${yi}`))throw new D(e.label);return{[Nx]:!0,scope:e,relativePath:n,path:xn(e.root,n)}}function _t(e,t){let n=Na(e.root,La(t));return br(e,n)}function Km(e,t="rules policy"){let n=La(e),r=Vm(n).dir;return br(Et(r,t),Na(r,n))}function Ci(e){try{if(!ae(e,!1).exists)return null;let n=$m(e.path,Cr.O_RDONLY|qm);try{let r=Ia(n);if(!r.isFile())throw new D(e.scope.label);let o=Ix(n,"utf-8"),i=xt(e.path);if(!i.isFile()||i.isSymbolicLink()||r.dev!==i.dev||r.ino!==i.ino)throw new D(e.scope.label);return ae(e,!1),o}finally{Oa(n)}}catch(t){Pt(e.scope.label,t)}}function Ym(e,t,n=384,r){let o=`${e.path}.${Ax(8).toString("hex")}.tmp`,i=null;try{Fx(e),ae(e,!0),i=$m(o,Cr.O_CREAT|Cr.O_EXCL|Cr.O_WRONLY|qm,n);let s=Ia(i);if(!s.isFile())throw new D(e.scope.label);Ox(i,t,"utf-8"),Tx(i);let a=Ia(i);if(!a.isFile()||a.dev!==s.dev||a.ino!==s.ino)throw new D(e.scope.label);Oa(i),i=null,ae(e,!0),Bx(e,o,a.dev,a.ino),kx(o,e.path),r?.(e.path),ae(e,!1)}catch(s){if(i!==null)$x(i);jx(o),Pt(e.scope.label,s)}}function Zm(e,t){if(e.path===t.path)return!0;try{if(!ae(e,!1).exists||!ae(t,!1).exists)return!1;return Yt(e.path)===Yt(t.path)}catch(n){if(n instanceof D)throw n;throw new D(e.scope.label)}}function Lx(e){try{if(!ae(e,!1,"directory").exists)return null;let n=Ma(e.path);return ae(e,!1,"directory"),n}catch(t){Pt(e.scope.label,t)}}function oM(e){let t=Lx(e);if(!t)return null;try{let n=t.map((r)=>{let o=br(e.scope,xn(e.relativePath,r)),i=xt(o.path);if(i.isSymbolicLink()||!i.isFile()&&!i.isDirectory())throw new D(e.scope.label);return Si(Qm(e.scope),Yt(o.path),e.scope.label),{name:r,kind:i.isDirectory()?"directory":"file"}});return ae(e,!1,"directory"),n}catch(n){Pt(e.scope.label,n)}}function iM(e){try{if(!ae(e,!0).exists)return;Da(e.path),ae(e,!0)}catch(t){Pt(e.scope.label,t)}}function sM(e){try{if(!Wx(e))return;Jm(e),ae(e,!0,"directory")}catch(t){Pt(e.scope.label,t)}}function aM(e){try{if(!ae(e,!0,"directory").exists)return;jm(e.path),ae(e,!0,"directory")}catch(t){Pt(e.scope.label,t)}}function Wx(e){try{if(!ae(e,!0,"directory").exists)return!1;return Xm(e),!0}catch(t){Pt(e.scope.label,t)}}function ae(e,t,n="file"){let r=Wa(e.scope);if(!r)return{exists:!1};let o=e.relativePath.split(yi);for(let i of o.keys()){let s=xn(e.scope.root,...o.slice(0,i+1)),a=Sr(s);if(!a){if(i===o.length-1&&t)return{exists:!1};return{exists:!1}}if(a.isSymbolicLink())throw new D(e.scope.label);if(i<o.length-1&&!a.isDirectory())throw new D(e.scope.label);if(i===o.length-1&&(n==="file"?!a.isFile():!a.isDirectory()))throw new D(e.scope.label);Si(r,Yt(s),e.scope.label)}return{exists:!0}}function Xm(e){for(let t of Ma(e.path)){let n=br(e.scope,xn(e.relativePath,t)),r=xt(n.path);if(r.isSymbolicLink()||!r.isDirectory()&&!r.isFile())throw new D(e.scope.label);if(r.isDirectory())Xm(n)}ae(e,!1,"directory")}function Jm(e){for(let t of Ma(e.path)){let n=br(e.scope,xn(e.relativePath,t)),r=xt(n.path);if(r.isSymbolicLink())throw new D(e.scope.label);if(r.isDirectory()){Jm(n);continue}if(!r.isFile())throw new D(e.scope.label);Da(n.path)}jm(e.path)}function Fx(e){Gx(e,e.relativePath.split(yi).slice(0,-1))}function Gx(e,t){zx(e.scope);let n=Qm(e.scope);for(let r of t.keys()){let o=xn(e.scope.root,...t.slice(0,r+1));if(!Sr(o))Um(o,{mode:448});let s=xt(o);if(!s.isDirectory()||s.isSymbolicLink())throw new D(e.scope.label);Si(n,Yt(o),e.scope.label)}}function zx(e){if(Sr(e.root)){if(!ka(e.root).isDirectory())throw new D(e.label);return}let t=[],n=e.root;while(!Sr(n)){t.unshift(n);let r=Vm(n).dir;if(r===n)throw new D(e.label);n=r}if(!ka(n).isDirectory())throw new D(e.label);for(let r of t){Um(r,{mode:448});let o=xt(r);if(!o.isDirectory()||o.isSymbolicLink())throw new D(e.label)}}function Wa(e){if(!Sr(e.root))return null;if(!ka(e.root).isDirectory())throw new D(e.label);return Yt(e.root)}function Qm(e){let t=Wa(e);if(!t)throw new D(e.label);return t}function Bx(e,t,n,r){let o=xt(t);if(!o.isFile()||o.isSymbolicLink()||o.dev!==n||o.ino!==r)throw new D(e.scope.label);let i=Wa(e.scope);if(!i)throw new D(e.scope.label);Si(i,Yt(t),e.scope.label)}function Si(e,t,n){let r=Na(e,t);if(r===".."||r.startsWith(`..${yi}`)||Hm(r))throw new D(n)}function Sr(e){try{return xt(e)}catch(t){if(Ux(t)&&t.code==="ENOENT")return null;throw t}}function Pt(e,t){if(t instanceof D)throw t;throw new D(e)}function Ux(e){return e instanceof Error&&"code"in e}function $x(e){try{Oa(e)}catch{}}function jx(e){try{Da(e)}catch{}}var ef={version:1,rules:[],overrides:{},transparent_wrappers:[]};function Hx(e){return Nm(e)}function vr(e){try{let t=Ci(tf(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=Hx(n);if(r.errors.length>0)return{config:null,errors:r.errors};let o=Om().parse(n);return{config:{version:1,rules:o.rules??[],overrides:o.overrides??{},transparent_wrappers:o.transparent_wrappers??[]},errors:[]}}catch(t){if(t instanceof D)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 fM(e){let t=vr(e);if(t.errors.length>0)return{ok:!1,result:{ok:!1,errors:t.errors,entries:[]}};return{ok:!0,config:t.config??ef}}function pM(e,t=[]){bi(e,{version:1,rules:t,overrides:{},transparent_wrappers:[]})}function gM(e,t="project-rules"){bi(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 bi(e,t,n,r){Ym(tf(e),`${JSON.stringify(t,null,2)}
43
- `,n,r)}function tf(e){return typeof e==="string"?Km(e):e}import{homedir as Vx}from"node:os";import{dirname as ut,isAbsolute as qx,join as At,relative as Kx,resolve as wt,sep as Yx}from"node:path";var nf="rule.json",Rr="policy.json",Zx="rule.lock",Xx="config.json",rf=".cc-safety-net",Jx="rules",Qx="CC_SAFETY_NET_HOME",of="`cc-safety-net rule update`";function eE(e){return wt(e??process.cwd(),Rm)}function sf(e){return At(eE(e),nf)}function xr(e){return At(wt(e??process.cwd()),rf,Rr)}function Er(e){return e?.userConfigDir??(e?.userConfigPath?ut(e.userConfigPath):At(tE(),Jx))}function tE(){let e=process.env[Qx];return e?wt(he(e)):At(Vx(),rf)}function af(e){return At(Er(e),nf)}function nE(e){return At(ut(e),Zx)}function xM(e={}){return At(ut(Er(e)),Xx)}function EM(e={}){return wt(e.cwd??process.cwd(),".safety-net.json")}function lf(e){let t=e.userConfigPath??af(e),n=e.projectConfigPath??sf(e.cwd),r=cf(t,e),o=uf(n,e);return{userConfigPath:t,projectConfigPath:n,userScope:r,projectScope:o,userConfigTarget:_t(r,t),projectConfigTarget:_t(o,n)}}function _M(e){let t=e.global?e.userConfigPath??af(e):e.projectConfigPath??sf(e.cwd),n=e.global?cf(t,e):uf(t,e),r=nE(t);return{configDir:ut(t),configPath:t,lockPath:r,filesystemScope:n,configTarget:_t(n,t),lockTarget:_t(n,r)}}function cf(e,t){let n=t.userConfigPath?ut(ut(wt(t.userConfigPath))):ut(wt(t.userConfigDir??Er(t)));return Et(n,"user policy")}function uf(e,t){let n=wt(t.cwd??process.cwd()),r=wt(e),o=Kx(n,r);if(o!==".."&&!o.startsWith(`..${Yx}`)&&!qx(o))return Et(n,"project policy");return Et(ut(ut(r)),"project policy")}function df(e,t){return At(e,t,vm)}var Ba=new Set(["standard","strict","paranoid"]),_r={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:ym}};function _n(e){return iE(gf(Er(e)),Rr)}function BM(e={}){let t=_n(e);if(!Ga(t))return{path:t,exists:!1,raw:"",policy:Pr(),errors:[]};let n=za(t,"utf-8");if(!n.trim())return{path:t,exists:!0,raw:n,policy:Pr(),errors:["Config file is empty"]};try{let r=JSON.parse(n),o=yr(r);return{path:t,exists:!0,raw:n,policy:En(r),errors:o}}catch(r){return{path:t,exists:!0,raw:n,policy:Pr(),errors:[`Invalid JSON: ${r instanceof Error?r.message:String(r)}`]}}}function vi(e,t={}){let n=_n(t),r=yr(e),o=r.length>0?Pr():En(e);if(r.length>0)return{path:n,policy:o,errors:r};return oE(gf(n),{recursive:!0,mode:448}),bi(n,o,384),rE(n,384),{path:n,policy:o,errors:[]}}function UM(e){let t=yr(e);if(t.length>0)return{errors:t};return{preview:sE(En(e)),errors:[]}}function sE(e){let t=li({safety:xf(e.safety)}),n=zi({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 $M(e={}){let t=_n(e);if(!Ga(t))return vi(_r,e);let n=za(t,"utf-8");if(!n.trim())return vi(_r,e);try{return vi(En(JSON.parse(n)),e)}catch{return vi(_r,e)}}function hf(e={}){let t=cE(_n(e)),n=xr(e.cwd),r=vf(n),o=lE(r.parsed),i=Object.keys(o.policy).length>0?Bm(t.gui??_r,o.policy):void 0,s=[...t.errors,...r.errors,...o.diagnostics],a=(t.fallback==="defaults"&&i?"salvaged":t.fallback)??(t.gui?void 0:r.fallback)??(s.length>0?"salvaged":void 0),l=o.policy.safety?.level?"project":t.levelPresent?"user":"default";return{...i?Fa(i.policy):t.policy,errors:s,...a?{fallback:a}:{},...r.exists?{policyScopes:{levelScope:l,weakenings:i?.weakenings??[]}}:{}}}var aE="project policy audit settings are ignored; audit is user scope only";function lE(e){if(!re(e))return{policy:{},diagnostics:[]};let t=re(e.safety)?e.safety:{},n=re(e.workflow)?e.workflow:{},r=re(e.destructive_command_protection)?e.destructive_command_protection:{},o=re(e.secret_protection)?e.secret_protection:{},i={...Ba.has(t.level)?{level:t.level}:{},...re(t.overrides)?mf({overrides:yf(t.overrides,dr)}):{}},s={...typeof r.enabled==="boolean"?{enabled:r.enabled}:{},...r.overrides!==void 0?{overrides:Ri(r.overrides,Dn)}:{},...r.allow_paths!==void 0?{allow_paths:Sf(r.allow_paths)}:{}},a={...typeof o.enabled==="boolean"?{enabled:o.enabled}:{},...o.overrides!==void 0?{overrides:Ri(o.overrides,hr)}:{},...o.deny_paths!==void 0?{deny_paths:Cf(o.deny_paths)}:{},...o.allow_paths!==void 0?{allow_paths:bf(o.allow_paths)}:{}};return{policy:mf({safety:i,workflow:typeof n.worktree_mode==="boolean"?{worktree_mode:n.worktree_mode}:{},destructive_command_protection:s,secret_protection:a}),diagnostics:e.audit===void 0?[]:[aE]}}function yf(e,t){return Object.fromEntries(t.flatMap((n)=>typeof e[n]==="boolean"?[[n,e[n]]]:[]))}function mf(e){return Object.fromEntries(Object.entries(e).flatMap((t)=>Object.keys(t[1]).length>0?[t]:[]))}function En(e){if(!re(e))return Pr();let t=re(e.safety)?e.safety:{},n=re(t.overrides)?t.overrides:{},r=re(e.workflow)?e.workflow:{},o=re(e.destructive_command_protection)?e.destructive_command_protection:{},i=re(e.secret_protection)?e.secret_protection:{};return{version:1,safety:{level:Ba.has(t.level)?t.level:"standard",overrides:yf(n,dr)},workflow:{worktree_mode:typeof r.worktree_mode==="boolean"?r.worktree_mode:!1},destructive_command_protection:{enabled:typeof o.enabled==="boolean"?o.enabled:!0,overrides:Ri(o.overrides,Dn),allow_paths:Sf(o.allow_paths)},secret_protection:{enabled:typeof i.enabled==="boolean"?i.enabled:!0,overrides:Ri(i.overrides,hr),deny_paths:Cf(i.deny_paths),allow_paths:bf(i.allow_paths)},audit:{retention_days:Cm(re(e.audit)?e.audit.retention_days:void 0)}}}function Ri(e,t){if(!re(e))return{};return Object.fromEntries(Object.entries(e).flatMap(([n,r])=>t.has(n)&&(r==="on"||r==="off")?[[n,r]]:[]))}function Cf(e){if(!Array.isArray(e))return[];let t=kt();return e.filter((n)=>Do(n,t)===null)}function Sf(e){if(!Array.isArray(e))return[];let t=kt();return e.filter((n)=>Mo(n,t)===null)}function bf(e){if(!Array.isArray(e))return[];let t=kt();return e.filter((n)=>No(n,t)===null)}function re(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Pr(){return structuredClone(_r)}function vf(e){if(!Ga(e))return{exists:!1,errors:[]};try{let t=za(e,"utf-8");if(!t.trim())return{exists:!0,errors:[`${e}: Config file is empty`],fallback:"defaults"};let n=JSON.parse(t),r=yr(n);if(r.length===0)return{exists:!0,parsed:n,errors:[]};return{exists:!0,parsed:n,errors:r.map((o)=>`${e}: ${o}`),fallback:re(n)?"salvaged":"defaults"}}catch(t){let n=t instanceof Error?t.message:String(t);return{exists:!0,errors:[`${e}: ${t instanceof SyntaxError?"Invalid JSON":n}`],fallback:"defaults"}}}function cE(e){let t=vf(e);if(!t.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!re(r))return{policy:pf(),errors:[]};let o=En(r);return{policy:Fa(o),gui:o,errors:[],levelPresent:ff(r)}}if(t.parsed===void 0)return{policy:pf(),errors:t.errors,...t.fallback?{fallback:t.fallback}:{}};let n=En(t.parsed);return{policy:Fa(n),gui:n,errors:t.errors,...t.fallback?{fallback:t.fallback}:{},levelPresent:ff(t.parsed)}}function ff(e){let t=re(e)&&re(e.safety)?e.safety:{};return Ba.has(t.level)}function Rf(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...pi].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function pf(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Rf({}),denyPaths:[],allowPaths:[]}}}function Fa(e){return{safety:xf(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:Rf(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function xf(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 wf="This path contains the protected policy config and you must not modify or delete it.",uE=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Af(e){let t=st(Me()),n=hE(e.invocation.context,t);if(e.invocation.route.kind==="patch")return Ef(e.paths,!1,e.invocation.context.executionCwd,n,t);let r=ue(e,"input-candidate");if(e.invocation.route.kind==="command")return r?_f(r.shell,e.invocation.context.executionCwd,n,t):null;if(e.invocation.route.kind==="unknown"&&r){let o=_f(r.shell,e.invocation.context.executionCwd,n,t);if(o)return o}return Ef(e.paths,e.invocation.route.kind==="grep"||e.invocation.route.kind==="glob"||wo(e.invocation.toolName),e.invocation.context.executionCwd,n,t)}function Ef(e,t,n,r,o){if(t)return null;let i=e.find((s)=>wr(s,n,r,o));return i?{target:i}:null}function _f(e,t,n,r){let o=fn(e,t,r,{findSegmentTarget:(i,s)=>dE(i,s,n,r)?.target??null,isRedirectionTarget:(i,s)=>wr(i,s.cwd,n,r),findMalformedTarget:(i)=>gE(i,t,n,r)?.target??null,normalizeCwd:ie});return o?{target:o}:null}function dE(e,t,n,r){if(qn(e))return null;let o=r.environment,i=gt([...e],o),s=M(i[0]??"").toLowerCase(),a=i.slice(1);if(s==="rm"&&mE(a)){let l=fE(a).find((c)=>Pf(ve(c,t.variables),t.cwd,n,r));if(l)return{target:l}}if(s==="find"){if($o(i,1)||Ts(i,o)){let c=(Uo(W(i))??W(["."])).find((u)=>{let d=ve(u.text,t.variables);return wr(d,t.cwd,n,r)||Pf(d,t.cwd,n,r)})?.text;if(c)return{target:c}}}if(s==="mv"){let l=To(a).sources.find((c)=>yE(ve(c,t.variables),t.cwd,n,r));if(l)return{target:l}}if(pE(e,o))return null;for(let l of[...e,...i])for(let c of Tf(l))if(wr(ve(c,t.variables),t.cwd,n,r))return{target:c};return null}function mE(e){return e.some((t)=>t==="--recursive"||t.startsWith("-")&&!t.startsWith("--")&&/[rR]/.test(t.slice(1)))}function fE(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 pE(e,t){let n=gt([...e],t);if(n.length===0)return!1;let r=M(n[0]??"").toLowerCase();if(!uE.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 gE(e,t,n,r){for(let o of e.split(/\s+/))for(let i of Tf(o))if(wr(i,t,n,r))return{target:i};return null}function Tf(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.indexOf("=");return n===-1||n===t.length-1?[t]:[t,t.slice(n+1)]}function hE(e,t){let n=(s)=>Ar(ie(s,e.executionCwd,t)),r=n(_n()),o=[n(xr(e.executionCwd)),n(xr(e.configCwd))],i=new Set(o.map((s)=>xi(s)));for(let s=xi(r);;s=xi(s))if(i.add(s),xi(s)===s)break;return{files:new Set([r,...o]),directoriesAndAncestors:i}}function wr(e,t,n,r){let o=Qc(e,t,r,(i)=>Ar(i)===Rr);return o!==null&&n.files.has(Ar(o))}function Pf(e,t,n,r){return n.directoriesAndAncestors.has(Ar(ie(e,t,r)))}function yE(e,t,n,r){let o=Ar(ie(e,t,r));return n.files.has(o)||n.directoriesAndAncestors.has(o)}function Ar(e){return process.platform==="win32"?e.toLowerCase():e}import{homedir as Ha}from"node:os";import{isAbsolute as Ei,posix as CE,resolve as Pi,win32 as SE}from"node:path";import{fileURLToPath as bE}from"node:url";var Bf="Access to a sensitive path is not allowed.",Uf=new Set(["echo","printf"]),vE=new Set(["find"]),RE=new Set(["-exec","-execdir"]),xE=new Set([";","+"]),EE=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),_E=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),$f=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),PE=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),wE=new Set(["node","bun"]),AE=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),TE=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"]),jf=new Set(["-c","-e","-r","-E","--eval","--exec"]),IE=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"])]]),kE=new Set(["grep","rg"]),If="f",kf="file",OE="files",ME=new Set(["e","f"]),DE=new Set(["regexp","file"]),NE=new Set(["e","f","A","B","C","m"]),LE=new Set(["regexp","file","after-context","before-context","context","max-count"]),WE=new Set(["|","|&"]),Ua="__CC_SAFETY_NET_PIPE_INPUT__",Hf=new Set(["bash","sh","zsh","dash","ksh"]),FE=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 Of(e,t,n,r,o){let i=qr();for(let s of e){if(w_(s,t,n?.denyPaths??[],r,i))return{target:s,ruleId:"secret.deny-path"};if(o&&!o.has(s))continue;let a=__(s,t,n,i);if(a){if(!a.startsWith("secret.cli.")&&A_(s,t,n?.allowPaths??[],r,i))continue;return{target:s,ruleId:a}}}return null}function Vf(e,t,n={}){let r=Mf(e),o=Of(r,e.invocation.context.executionCwd,t,e.invocation.context.configCwd),i=o?.ruleId!=="secret.deny-path"&&n.strict===!1?Mf(e,{refineJavaScriptInlineData:!0}):r,s=i.length===r.length?o:Of(r,e.invocation.context.executionCwd,t,e.invocation.context.configCwd,new Set(i));if(s?.ruleId!=="secret.deny-path"&&n.strict===!1&&GE(e))return null;return s}function GE(e){if(e.invocation.route.kind!=="command")return!1;let t=ue(e,"input-candidate")??ue(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(Ye(s.text))}let r=Pn(n);if(r.length===0)return!1;let o=Xt(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)=>EE.has(s))}function Mf(e,t={}){if(e.invocation.route.kind==="command"){let r=ue(e,"input-candidate");return r?kr(r.shell,e.store,t,Df(r)):[]}if(e.invocation.route.kind!=="unknown")return[...e.paths];let n=ue(e,"input-candidate");return[...n?kr(n.shell,e.store,t,Df(n)):[],...e.paths]}function Df(e){return e.program.dialect==="powershell"}function kr(e,t,n,r=!1){if(e.status==="structural-limit")throw new yt;if(e.status==="unclosed-quote")return[];if(e.status==="invalid")throw Error("Unable to parse command for secret protection");let o=[...e.assignmentFallbacks,...a_(Ye(e.source),t,n)],i=[],s=null;for(let a of e.entries){if(a.kind==="operator"){if(!a.boundary)continue;if(i.length>0){if(o.push(..._i(i,t,n)),s!==null)o.push(...Nf(s,i,t,n));s=WE.has(a.operator)?i:null,i=[]}else s=null;continue}if(a.kind==="redirection"){let l=a.target?Ye(Wf(a.target,r)):void 0;if(l&&a.targetOrder==="legacy-segment")i.push(l);else if(l)o.push(l);continue}i.push(Ye(Wf(a.text,r)))}if(i.length>0){if(o.push(..._i(i,t,n)),s!==null)o.push(...Nf(s,i,t,n))}return o}function _i(e,t,n){let r=KE(e),o=Pn(e);if(o.length===0)return r;let i=o[0]??"",s=Xt(i).toLowerCase(),a=o.slice(1),l=zE(i,s,a);if(l)return[...r,...l];if(Uf.has(s))return r;if(kE.has(s))return[...r,...g_(a)];if(vE.has(s))return[...r,...JE(a,t,n)];if(Re.has(s))return[...r,...a.flatMap((c)=>$a("awk",c)),...a.flatMap((c)=>e_(c,t,n)),...a.flatMap(t_)];if(s==="curl")return[...r,...a.flatMap((c)=>$a(s,c)),...YE(a)];if(Yf(s)){if(Hf.has(s)){let c=Zc(s,a);if(c!==null&&t.getShellSyntax(c).status==="structural-limit")throw new yt}return[...r,...QE(s,a,n)]}return[...r,...a.flatMap((c)=>$a(s,c))]}function zE(e,t,n){let r=ui(t,n);if(r===null||n[r]!=="explain")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 Nf(e,t,n,r){if(HE(t,n,r))return BE(e);let o=VE(t);if(o===null)return[];return UE(e).flatMap((i)=>Hf.has(o)?kr(n.getShellSyntax(i),n,r):Xf(i))}function BE(e){let t=Pn(e);if(t.length===0)return[];let n=Xt(t[0]??"").toLowerCase();if(!Uf.has(n))return[];return t.slice(1)}function UE(e){let t=Pn(e);if(t.length===0)return[];let n=Xt(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 $E(r);return[]}function $E(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[qf(t)];let r=e.slice(1);return Array.from({length:Math.ceil(r.length/n)},(o,i)=>jE(t,r.slice(i*n,(i+1)*n)))}function jE(e,t){let n=0;return qf(e.replace(/%%|%[bqs]/g,(r)=>{if(r==="%%")return"%";let o=t[n]??"";return n++,o}))}function qf(e){return e.replace(/\\n/g,`
44
- `).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function HE(e,t,n){let r=Pn(e);if(r.length===0||Xt(r[0]??"").toLowerCase()!=="xargs")return!1;let o=$t(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,Ua]:i.map((l)=>l.split(s).join(Ua));return _i(a,t,n).some((l)=>l.includes(Ua))}function VE(e){let t=Pn(e);if(t.length===0)return null;let n=Xt(t[0]??"").toLowerCase();if(!Yf(n))return null;return qE(n,t.slice(1))?n:null}function qE(e,t){let n=Kf(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(jf.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(FE.get(n)?.has(o))r++;continue}return!1}return!0}function Kf(e){return/^python\d/.test(e)?"python":e}function KE(e){let t=[];for(let n of e){if(ep(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}var Lf=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function Wf(e,t){if(!t||!Lf.test(e))return e;return`~${e.replace(Lf,"").replace(/\\/g,"/")}`}function $a(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 YE(e){return e.flatMap((t,n)=>{let r=XE(t);if(r!==null)return Ff(r.flag,r.value);let o=ZE(e[n-1]);return o===null?[]:Ff(o,t)})}function Ff(e,t){if(e==="-F"||e==="--form"){let n=t.indexOf("="),r=n===-1?t:t.slice(n+1);if(!r.startsWith("@")&&!r.startsWith("<"))return[];return ja(r.slice(1).split(";")[0]??"")}if(e==="--data-urlencode"){let n=t.indexOf("@"),r=t.indexOf("=");if(n===-1||r!==-1&&r<n)return[];return ja(t.slice(n+1))}return t.startsWith("@")?ja(t.slice(1)):[]}function ZE(e){if(e===void 0)return null;if($f.has(e))return e;return/^-[A-Za-z]+[dF]$/.test(e)?`-${e.slice(-1)}`:null}function XE(e){let t=e.slice(0,2);if(e.length>2&&(t==="-d"||t==="-F"))return{flag:t,value:e.slice(2)};let n=e.indexOf("=");if(n===-1)return null;let r=e.slice(0,n);return $f.has(r)?{flag:r,value:e.slice(n+1)}:null}function ja(e){return e===""||e==="-"?[]:[e]}function JE(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(!RE.has(e[i]??""))continue;let s=e.slice(i+1),a=s.findIndex((u)=>xE.has(u)),l=a===-1?s:s.slice(0,a),c=_i(l,t,n);if(o.push(...c.filter((u)=>u!=="{}")),!c.includes("{}"))continue;o.push(...e.slice(0,i).flatMap((u,d,m)=>{if(!_E.has(u))return[];let f=m[d+1];return f===void 0?[]:[f,f.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return o}function Yf(e){return PE.has(e)||/^python\d/.test(e)}function QE(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o];if(i===void 0)break;if(jf.has(i)||Zf(e,i)){let a=t[o+1];if(a!==void 0)r.push(...Gf(e,a,n)),o++;continue}let s=/^--(?:eval|exec)=(.*)$/.exec(i);if(s!==null&&s[1]!==void 0){r.push(...Gf(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 IE.get(t[t.length-1]??"")?.has(Kf(e))??!1}function e_(e,t,n){if(!e.includes("system"))return[];return _s(e)?.commands.flatMap((r)=>kr(t.getShellSyntax(r),t,n))??[]}function t_(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 Xf(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(Jf),...n]}function Gf(e,t,n){let r=Xf(t);if(!n.refineJavaScriptInlineData||!wE.has(e)||r.length===0)return r;let o=n_(t);return o!==null&&!o_(o)?[]:r}function n_(e){let t=e.split("");for(let n=0;n<e.length;n++){let r=e[n];if(r!=="'"&&r!=='"'&&r!=="`")continue;if(r==="`"&&r_(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 r_(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 o_(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(AE.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)=>TE.has(i)))continue;if(o.length>1)return!0;if(i_(e,r)===".")return!0;if(s_(e,r+n.length)==="(")return!0}return!1}function i_(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function s_(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function a_(e,t,n){return m_(e).flatMap((r)=>{let o=t.getShellSyntax(r);if(o.status==="invalid")return[];return[...kr(o,t,n),...l_(o)?c_(o):[]]})}function l_(e){let t=e.entries;for(let n=0;n<t.length;n++){let r=t[n];if(r?.kind!=="word"||Xt(Ye(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=Ye(i.text);if(s==="--decode"||!s.startsWith("--")&&s.startsWith("-")&&/[dD]/.test(s))return!0}}return!1}function c_(e){return e.entries.flatMap((t)=>t.kind==="word"?[Ye(t.text)]:t.kind==="redirection"&&t.target?[Ye(t.target)]:[]).flatMap(Jf)}function Jf(e){let t=d_(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||u_(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function u_(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function d_(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 m_(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(Bn(o,n))continue;if(Qf(e,r,n)){let i=f_(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=p_(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function f_(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(Bn(i,n))continue;if(Qf(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 p_(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 Qf(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function g_(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 d=u[1]??"",m=u[2];if(d===OE)o=!0;if(DE.has(d))r=!0;if(m!==void 0){if(d===kf)t.push(m);continue}if(LE.has(d)){let f=e[l+1];if(d===kf&&f!==void 0)t.push(f);l++}continue}if(c.startsWith("-")&&c.length>1){let d=c.slice(1),m="",f="";for(let p=0;p<d.length;p++){let g=d[p]??"";if(ME.has(g))r=!0;if(NE.has(g)){m=g,f=d.slice(p+1);break}}if(m!=="")if(f.length>0){if(m===If)t.push(f)}else{let p=e[l+1];if(m===If&&p!==void 0)t.push(p);l++}continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function Pn(e){let t=e.findIndex((n)=>!ep(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:[...e.slice(t)]}function ep(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var h_=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),y_=".env.",C_=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),S_=[".env.example.",".env.sample."];function b_(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function v_(e){return e.length>0&&!/\s/.test(e)}function R_(e,t,n){try{let r=Or(e,t,n);return r!==""&&Oe.entryKind(r)!=="missing"}catch(r){if(r instanceof we)throw r;return!1}}var x_=new Set(["node_modules","__pycache__"]),E_=[["vendor","bundle"],["vendor","cache"]];function __(e,t,n,r){if(b_(e))return null;let o=tt(e,t,r);if(!o)return null;let i=Y(o.split("/").pop()??""),s=Y(o),a=()=>v_(i)||R_(e,t,r);if(C_.has(i)||S_.some((d)=>i.startsWith(d)))return null;let l=Y(k_(e,t,r));for(let d of xa){let m=`~/${d.suffixParts.join("/")}`;if((zf(s,m)||zf(l,m))&&dt(d.id,n))return d.id}let c=P_(o,t,n,r);if(c)return c;if(h_.has(i))return null;for(let d of Ra)if(i===d.basename&&dt(d.id,n))return d.id;if(i.startsWith(y_)&&dt(mi.id,n)&&a())return mi.id;for(let d of Ea)if(i.length>d.prefix.length&&i.startsWith(d.prefix)){let m=i.slice(d.prefix.length)[0];if((m==="-"||m==="_")&&dt(d.id,n)&&a())return d.id}for(let d of _a)if(i.length>d.prefix.length&&i.startsWith(d.prefix)){if(i.slice(d.prefix.length)===d.suffix&&dt(d.id,n))return d.id}if(T_(s))return null;if(!i.includes(".")&&gr.pattern.test(i)&&dt(gr.id,n))return gr.id;let u=I_(i,n);if(u)return u;return null}function P_(e,t,n,r){return fi.find((o)=>{if(!dt(o.id,n))return!1;switch(o.id){case"secret.cli.claude-code":return H(e,K(process.env.CLAUDE_CONFIG_DIR,"~/.claude",t,r),[".credentials.json"]);case"secret.cli.claude-code.config":{let i=Y(e).split("/");return H(e,K(process.env.CLAUDE_CONFIG_DIR,"~/.claude",t,r),["settings.json","settings.local.json"])||Ir(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 H(e,tt("~/.gemini/config",t,r),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let i=K(process.env.CODEX_HOME,"~/.codex",t,r);return H(e,i,["auth.json",".credentials.json"])||Tr(e,i,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let i=K(process.env.CODEX_HOME,"~/.codex",t,r),s=Y(e).split("/").at(-1)??"";return H(e,i,["config.toml"])||s.endsWith(".config.toml")&&H(e,i,[s])}case"secret.cli.gemini":return H(e,ce(K(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=Y(e).split("/"),s=process.env.ProgramData?[ce(K(process.env.ProgramData,"",t,r),"gemini-cli")]:[];return H(e,ce(K(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()?Ir(e,process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH,t,r):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...s].some((a)=>H(e,tt(a,t,r),["settings.json"]))}case"secret.cli.copilot-cli":{let i=K(process.env.COPILOT_HOME,"~/.copilot",t,r);return H(e,i,["config.json"])||Tr(e,i,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return H(e,K(process.env.COPILOT_HOME,"~/.copilot",t,r),["mcp-config.json"]);case"secret.cli.kimi-code":{let i=K(process.env.KIMI_CODE_HOME,"~/.kimi-code",t,r),s=K(process.env.KIMI_SHARE_DIR,"~/.kimi",t,r);return H(e,i,["server.token"])||Tr(e,i,["credentials"])||Tr(e,s,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let i=["config.toml","mcp.json"],s=Y(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".kimi-code"||H(e,K(process.env.KIMI_CODE_HOME,"~/.kimi-code",t,r),i)||H(e,K(process.env.KIMI_SHARE_DIR,"~/.kimi",t,r),[...i,"config.json","config.json.bak"])}case"secret.cli.opencode":{let i=ce(K(process.env.XDG_DATA_HOME,"~/.local/share",t,r),"opencode"),s=Y(e).split("/").at(-1)??"",a=process.env.OPENCODE_DB?.trim(),l=a&&a!==":memory:"?[a,`${a}-wal`,`${a}-shm`]:[];return H(e,i,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(s)&&H(e,i,[s])||l.some((c)=>Ir(e,c,t,r))}case"secret.cli.opencode.config":{let i=process.env.OPENCODE_CONFIG_DIR?K(process.env.OPENCODE_CONFIG_DIR,"~/.config/opencode",t,r):ce(K(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"opencode"),s=process.env.ProgramData?[ce(K(process.env.ProgramData,"",t,r),"opencode")]:[],a=["opencode.json","opencode.jsonc"];return a.includes(Y(e).split("/").at(-1)??"")||H(e,i,a)||(process.env.OPENCODE_CONFIG?.trim()?Ir(e,process.env.OPENCODE_CONFIG,t,r):!1)||["/Library/Application Support/opencode","/etc/opencode",...s].some((l)=>H(e,tt(l,t,r),a))}case"secret.cli.pi":return H(e,K(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",t,r),["auth.json"]);case"secret.cli.pi.config":return H(e,K(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",t,r),["models.json"]);case"secret.cli.amp":{let i=tt("~",t,r);return[ce(K(process.env.XDG_DATA_HOME,"~/.local/share",t,r),"amp"),ce(i,".local","share","amp")].some((a)=>H(e,a,["secrets.json"]))||Tr(e,ce(i,".amp"),["oauth"])}case"secret.cli.amp.config":{let i=["settings.json","settings.jsonc"],s=[ce(K(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"amp"),ce(tt("~",t,r),".config","amp")],a=Y(e).split("/");return s.some((l)=>H(e,l,i))||a.at(-2)===".amp"&&i.includes(a.at(-1)??"")||(process.env.AMP_SETTINGS_FILE?.trim()?Ir(e,process.env.AMP_SETTINGS_FILE,t,r):!1)}case"secret.cli.cursor":{let i=ce(K(process.env.XDG_CONFIG_HOME,"~/.config",t,r),"cursor"),s=ce(K(process.env.CURSOR_DATA_DIR,"~/.cursor",t,r),"projects");return H(e,tt("~/.cursor",t,r),["auth.json"])||H(e,i,["auth.json"])||Y(e).split("/").at(-1)==="mcp-auth.json"&&Zt(Y(e),Y(s))}case"secret.cli.cursor.config":{let i=Y(e).split("/");return i.at(-1)==="mcp.json"&&i.at(-2)===".cursor"}case"secret.cli.grok-build":return H(e,K(process.env.GROK_HOME,"~/.grok",t,r),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let i=Y(e).split("/");return i.at(-1)==="config.toml"&&i.at(-2)===".grok"||H(e,K(process.env.GROK_HOME,"~/.grok",t,r),["config.toml","managed_config.toml","requirements.toml"])||H(e,tt("/etc/grok",t,r),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}function K(e,t,n,r){return tt(e?.trim()?e:t,n,r)}function H(e,t,n){return n.some((r)=>tp(e,ce(t,r)))}function Tr(e,t,n){return n.some((r)=>Zt(Y(e),Y(ce(t,r))))}function Ir(e,t,n,r){return tp(e,tt(t,n,r))}function tp(e,t){return Y(e)===Y(t)}function ce(e,...t){return He([e,...t].filter(Boolean).join("/"))}function w_(e,t,n,r,o){if(n.length===0)return!1;let i=Y(Or(e,t,o));return n.some((s)=>Zt(i,Y(Or(s,r,o))))}function A_(e,t,n,r,o){if(n.length===0)return!1;let i=Y(Or(e,t,o));if(!i)return!1;let s=process.env.HOME??Ha(),a=s?He(V(he(s),Oe,o)):"",l=Y(a),c=process.env.CC_SAFETY_NET_HOME,u=Y(c?He(V(Pi(he(c)),Oe,o)):a&&He(V(`${a}/.cc-safety-net`,Oe,o)));if(u&&Zt(i,u))return!1;return n.some((d)=>{let m=Y(Or(d,r,o));if(!m)return!1;if(l&&(l===m||l.startsWith(m.endsWith("/")?m:`${m}/`)))return!1;return Zt(i,m)})}function T_(e){let t=e.split("/");return t.some((n)=>x_.has(n))||E_.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function I_(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 Pa)if(r===o.extension&&dt(o.id,t))return o.id;for(let o of wa)if(o.pattern.test(r)&&dt(o.id,t))return o.id;return null}function Y(e){return e.toLowerCase()}function dt(e,t){return!t?.disabledRules?.includes(e)}function tt(e,t,n){let{home:r,normalized:o}=Va(e,n);if(!o)return"";if(!r)return o;let i=qa(o,r),s=Ei(i)?i:He(Pi(t,i)),a=He(V(s,Oe,n));if(!Zt(a,r)){if(Ei(i))return a;return a===s?o:a}let l=a.slice(r.length);return l?`~${l}`:"~"}function zf(e,t){return e===t||e.startsWith(`${t}/`)}function k_(e,t,n){let{home:r,normalized:o}=Va(e,n);if(!o||!r)return"";let i=qa(o,r),s=CE.normalize(Ei(i)?i:He(Pi(t,i))),a=He(he(process.env.HOME??Ha())),l=(d)=>process.platform==="win32"?d.toLowerCase():d,c=[r,a].find((d)=>d!==""&&Zt(l(s),l(d)));if(c===void 0)return"";let u=s.slice(c.length);return u?`~${u}`:"~"}function Or(e,t,n){let{home:r,normalized:o}=Va(e,n);if(!o)return"";let i=r?qa(o,r):o;return He(V(Ei(i)?i:Pi(t,i),Oe,n))}function Va(e,t){let n=process.env.HOME??Ha(),r=n?He(V(he(n),Oe,t)):"",o=He(he(O_(Ye(e))));return{home:r,normalized:o}}function O_(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return bE(e)}catch{return e}}function qa(e,t){if(e==="~")return t;if(e.startsWith("~/"))return ce(t,e.slice(2));return e}function M_(e){if(process.platform==="win32")return!0;return SE.parse(e).root.length>1}function He(e){let t=e.trim(),n=(M_(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function Zt(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function Xt(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}import{dirname as Jt}from"node:path";var np="Rulebook exceeds CC Safety Net's safe validation limits.",rp="Additional rulebook validation errors were omitted.",Ve=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function op(e){if(Ka(e.allowed_commands,Ve.maxAllowedCommands)||Ka(e.rules,Ve.maxRules)||Ka(e.tests,Ve.maxTests))return!1;let{maxAggregateStringCodeUnits:t,maxTotalBlockArgs:n}=Ve,r=(o,i=!1)=>{if(typeof o!=="string")return!0;if(o.length>Ve.maxStringCodeUnits||i&&o.length>Ve.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;let s=i.match&&typeof i.match==="object"?i.match:{};for(let a of[i.block_args,s.command_path,s.any_args,s.exclude_args]){if(!Array.isArray(a))continue;if(a.length>Ve.maxBlockArgsPerRule||a.length>n)return!1;n-=a.length;for(let l of a)if(!r(l))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 Ka(e,t){return Array.isArray(e)&&e.length>t}function D_(e){if(!N_(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!op(e))return{errors:[np],ruleNames:new Set};let t=(e.rulebook_version===2?Dm():Mm()).safeParse(e),n=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...t.success?[]:hi(t.error.issues,": ",": ")];return{errors:n.length>Ve.maxValidationErrors?[...n.slice(0,Ve.maxValidationErrors),rp]:n,ruleNames:new Set(Aa(e).map((r)=>r.toLowerCase()))}}function ip(e){let t=D_(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}function N_(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function cp(e={}){let t=lf(e),n=!1;try{n=Zm(t.userConfigTarget,t.projectConfigTarget)}catch(m){if(m instanceof D)return V_(t,m.message);throw m}let r=vr(t.userConfigTarget),o=n?{config:null,errors:[]}:vr(t.projectConfigTarget),i=ap(t.userConfigPath,r.errors),s=ap(t.projectConfigPath,o.errors),a=new Set,l=r.config?Ya(r.config,Jt(t.userConfigPath),"user",t.userScope,a):lp(),c=o.config?Ya(o.config,Jt(t.projectConfigPath),"project",t.projectScope,a):lp(),u=r.config?.overrides??{},d=o.config?.overrides??{};return{rules:[...sp(l.rules,u),...sp(c.rules,d)],transparent_wrappers:j_(r.config,o.config),rulebooks:[...l.rulebooks,...c.rulebooks],errors:[...i,...s,...l.errors,...c.errors],warnings:[...l.warnings,...c.warnings,...l.canValidateOverrides?Za(u,l.knownRuleIds,t.userConfigPath):[],...l.canValidateOverrides?H_(d,l.knownRuleIds,t.projectConfigPath):[],...c.canValidateOverrides?Za(d,c.knownRuleIds,t.projectConfigPath):[]],userConfig:r.config??void 0,projectConfig:o.config??void 0,...t}}function kD(e,t){let n=L_(e,t);if(!n)return[];return[...n.scope.errors,...n.scope.warnings,...W_(n.config,n.scope,e)]}function L_(e,t){let n=t??Et(Jt(Jt(e)),"rules policy"),r=vr(_t(n,e)).config;if(!r)return null;return{config:r,scope:Ya(r,Jt(e),"project",n)}}function W_(e,t,n){return t.canValidateOverrides?Za(e.overrides??{},t.knownRuleIds,n):[]}function Ya(e,t,n,r=Et(Jt(Jt(t)),n==="user"?"user policy":"project policy"),o=new Set){let i=[],s=[],a=e.rules.flatMap((c)=>{let u=G_(c,t,r);if(u.errors.length>0||!u.rulebook)return i.push(...u.errors),[];let d=u.rulebook;if(o.has(d.name))return s.push(`duplicate active rulebook name "${d.name}" for ${c}; keeping the first and ignoring this one, so its rules are not active; rename one of them in its rulebook file and in the rules config that lists it`),[];return o.add(d.name),[{rules:F_(d),rulebook:{source:n,spec:c,name:d.name,version:d.version,rules:d.rules.map((m)=>`${d.name}/${m.name}`)}}]}),l=a.flatMap((c)=>c.rules);return{rules:l,rulebooks:a.map((c)=>c.rulebook),entries:a.map((c)=>({spec:c.rulebook.spec,name:c.rulebook.name,version:c.rulebook.version,ruleCount:c.rulebook.rules.length})),knownRuleIds:new Set(l.map((c)=>c.name)),errors:i,warnings:s,canValidateOverrides:i.length===0}}function F_(e){if(e.rulebook_version===2)return e.rules.map((t)=>({name:`${e.name}/${t.name}`,command:t.command,block_args:[],match:t.match,reason:t.reason,intent:t.intent}));return e.rules.map((t)=>({...t,name:`${e.name}/${t.name}`,match:void 0}))}function G_(e,t,n){let r=z_(e),o=df(t,r),i=U_(o,n);if("error"in i)return{rulebook:null,errors:[i.error]};if(i.content===null)return{rulebook:null,errors:[`missing rulebook file ${o} for ${e}; ${B_(e)}`]};let s=$_(i.content);if("problem"in s)return{rulebook:null,errors:[`invalid rulebook ${o}: ${s.problem}; fix that file`]};if(s.rulebook.name!==r)return{rulebook:null,errors:[`rulebook name "${s.rulebook.name}" in ${o} must match source "${e}"; fix that file`]};return{rulebook:s.rulebook,errors:[]}}function z_(e){return di(e)?va(e).name:e}function B_(e){return di(e)?`run ${of} to vendor ${e}`:"create that file or remove that source from the rules config"}function U_(e,t){try{return{content:Ci(_t(t,e))}}catch(n){if(n instanceof D)return{error:n.message};throw n}}function $_(e){let t;try{t=JSON.parse(e)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:ip(t)}}catch(n){return{problem:n instanceof Error?n.message:"invalid rulebook"}}}function j_(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 Za(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 H_(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 V_(e,t){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath}}function lp(){return{rules:[],rulebooks:[],entries:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}function up(e={}){let t=cp(e),n=hf(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}),...Z_(a.spec)?{source:a.spec}:{}}:{},...l&&typeof l==="object"?{override:Object.freeze({type:"reason",reason:l.reason})}:{}})]})));return X_(r,q_(t,n),i,n.policyScopes)}function ND(e){if(e.state==="ready")return{state:e.state};return{state:e.state,reason:e.reason}}function q_(e,t){let n=Y_(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:J_(e.errors.length>0?K_(e.errors):void 0,e.warnings.length>0?Ja(e.warnings.join("; ")):void 0,n)}}function K_(e){return`${Ja(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Y_(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 Z_(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function X_(e,t,n=Object.freeze({}),r){let o=Xa(structuredClone(e)),i=r?{policyScopes:Xa(structuredClone(r))}:{};if(!t)return Object.freeze({state:"ready",policy:o,diagnostics:Object.freeze([]),ruleMetadata:n,...i});return Object.freeze({state:"degraded",policy:o,diagnostics:Object.freeze([...t.diagnostics]),reason:t.reason,ruleMetadata:n,...i})}function Xa(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))Xa(t);return Object.freeze(e)}function J_(...e){return Ja(e.filter((t)=>!!t).join("; "))}function Ja(e){return/[.!?]$/.test(e)?e:`${e}.`}class Qa 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 Q_={findPolicyMutation:Af,findGitMetadataMutation:ru,resolveGitMetadata:gs,loadPolicySnapshot:up,findSensitiveTarget:Vf,analyzeCommand:ha,getModes:li};function YD(e,t={}){let n={...Q_,...t.dependencies},r=nP(e),o=Mr(e)?e.command:r,i=Tt("policy-protection",o,()=>Vn(e,t.factParserDependencies)),s=ue(i,"declared-command");if(Mr(e)&&e.command?.trim()&&s?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:nt,intent:"stop_and_explain",evidence:[{kind:"command",command:e.command,segment:e.command}]}};if(ue(i,"input-candidate")?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:sl,intent:"stop_and_explain",evidence:[]}};let a=Tt("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd])),l=Tt("policy-protection",o,()=>n.findPolicyMutation(i));if(l){let y=o??l.target;return{stage:"policy-protection",decision:{kind:"deny",reason:wf,intent:"hard_stop",evidence:[{kind:"command",command:y,segment:l.target}]}}}let c=Tt("policy-protection",o,()=>gm(i));if(c){let y=o??c.target;return{stage:"policy-protection",decision:{kind:"deny",reason:pm,intent:"hard_stop",evidence:[{kind:"command",command:y,segment:c.target}]}}}let u=Tt("policy-protection",o,()=>n.findGitMetadataMutation(i,a));if(u){let y=o??u.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Te,intent:"hard_stop",evidence:[{kind:"command",command:y,segment:u.target}]}}}let d=Tt("config-load",o,()=>n.loadPolicySnapshot({...t.policyOptions,cwd:e.context.configCwd})),m=d.policy,f=n.getModes(m),p={level:f.effectiveLevel,...eP(d)},g=m.secretProtection.enabled===!1?null:Tt("secret-protection",o,()=>n.findSensitiveTarget(i,m.secretProtection,{strict:Mr(e)?f.strict:void 0}));if(g){let y=o??g.target;return{stage:"secret-protection",...p,decision:{kind:"deny",reason:Bf,intent:"hard_stop",ruleId:g.ruleId,evidence:[{kind:"command",command:y,segment:g.target}]}}}if(!Mr(e))return{stage:"non-command",...p,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...el("command-validation",o),...p};let h=Tt("command-analysis",o,()=>n.analyzeCommand(e.command,{cwd:e.context.executionCwd,shell:e.route.shell,policySnapshot:d,environment:Me(),protectedGitMetadata:a,effectiveCapabilities:f.capabilities,strict:f.strict,paranoidRm:f.paranoidRm,paranoidInterpreters:f.paranoidInterpreters,worktreeMode:f.worktreeMode},tP(i),i.store));if(h)return{stage:"command-analysis",...p,decision:h};return{stage:"command-analysis",...p,decision:{kind:"allow"}}}function eP(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function tP(e){return ue(e,"declared-command")?.program}function nP(e){try{return Ao(e.input)}catch(t){let n=Mr(e)?e.command:void 0;throw new Qa("policy-protection",el("policy-protection",t instanceof Hn?void 0:n,t),t)}}function Tt(e,t,n){try{return n()}catch(r){throw new Qa(e,el(e,r instanceof Hn?void 0:t,r),r)}}function el(e,t,n){let r=n instanceof we||n instanceof yt;return{stage:e,decision:{kind:"deny",reason:r?al:ll,intent:"stop_and_explain",evidence:t?[{kind:"command",command:t,segment:t}]:[]}}}function Mr(e){return e.route.kind==="command"}
46
- export{ym as q,Cm as r,Oe as s,Me as t,D as u,Et as v,_t as w,Km as x,Ci as y,Ym as z,oM as A,iM as B,sM as C,aM as D,ct as E,vm as F,Rm as G,MO as H,va as I,DO as J,NO as K,di as L,LO as M,Rr as N,sf as O,xr as P,Er as Q,af as R,xM as S,EM as T,lf as U,_M as V,df as W,lP as X,cP as Y,uP as Z,xp as _,ll as $,we as aa,qr as ba,V as ca,k as da,en as ea,jr as fa,zi as ga,Mt as ha,ao as ia,We as ja,Hn as ka,vw as la,Ao as ma,Fc as na,Bc as oa,yt as pa,Vn as qa,xy as ra,Te as sa,ru as ta,gs as ua,_u as va,zA as wa,se as xa,le as ya,tx as za,sO as Aa,li as Ba,mr as Ca,pa as Da,aO as Ea,mm as Fa,pO as Ga,ha as Ha,Ti as Ia,pm as Ja,gm as Ka,pr as La,bm as Ma,Sm as Na,lx as Oa,AO as Pa,TO as Qa,IO as Ra,kO as Sa,Am as Ta,ZO as Ua,Aa as Va,yr as Wa,hi as Xa,Bm as Ya,Hx as Za,vr as _a,fM as $a,pM as ab,gM as bb,bi as cb,_r as db,_n as eb,BM as fb,vi as gb,UM as hb,sE as ib,$M as jb,lE as kb,En as lb,Rf as mb,xf as nb,wf as ob,Af as pb,Bf as qb,Vf as rb,ip as sb,cp as tb,kD as ub,Ya as vb,z_ as wb,$_ as xb,up as yb,ND as zb,X_ as Ab,Qa as Bb,YD as Cb};