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