cc-safety-net 2.5.0 → 2.5.2
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 +22 -133
- package/dist/amp/cc-safety-net/index.ts +42 -42
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/bin/hook.js +40 -40
- package/dist/chunks/index-0naqmp5p.js +45 -0
- package/dist/chunks/{index-mrn9mahg.js → index-e1xw96x7.js} +4 -4
- package/dist/chunks/index-n8c4p97n.js +2 -0
- package/dist/cli.js +91 -91
- package/dist/deepseek-harness/index.js +1 -1
- package/dist/index.js +3 -3
- package/dist/openclaw/cc-safety-net/index.js +41 -41
- 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 +3 -3
- package/dist/chunks/index-8cqwk53d.js +0 -45
- package/dist/chunks/index-yya83mcj.js +0 -2
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
var Js="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Gn="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",vo="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var Xs={errorCode:"path-canonicalization-limit",reason:"CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry."},Co={errorCode:"structural-shell-syntax-limit",reason:"Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry."},a=Object.freeze({realpathAttempts:{cap:16384,...Xs},processedCandidateBytes:{cap:4194304,...Xs},pathEnvironmentExpansion:{cap:64,...Xs},recursionDepth:{cap:10,errorCode:"structural-shell-syntax-limit",reason:"Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry."},derivedTokens:{cap:16384,...Co},trackedHeredocFiles:{cap:64,...Co},controlFlowStates:{cap:64,...Co},wrapperPeelIterations:{cap:20,...Co},derivedCommandShape:Co});class s extends Error{kind;name="AnalysisLimit";constructor(M){super(a[M].reason);this.kind=M}}function Fn(){let M=new Map;return{counters:M,resolvedPaths:new Map,charge(L,F=1){let q=(M.get(L)??0)+F;if(M.set(L,q),q>a[L].cap)throw new s(L)}}}var Rg=[/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bglpat-[A-Za-z0-9_-]{20,}\b/g,/\bxox[abeprs]-[A-Za-z0-9-]{20,}\b/g,/\bnpm_[A-Za-z0-9_]{20,}\b/g,/\bpypi-[A-Za-z0-9_-]{20,}\b/g,/\b[rs]k_(?:live|test)_[A-Za-z0-9_]{20,}\b/g,/\bsk-[A-Za-z0-9_-]{20,}\b/g,/\bsk_[A-Za-z0-9]{20,}\b/g,/\bgsk_[A-Za-z0-9]{52,}\b/g,/\bxai-[A-Za-z0-9_-]{80,}\b/g,/\bpplx-[A-Za-z0-9_-]{20,}\b/g,/\bbastn_[A-Za-z0-9]{16,}\b/g,/\btgp_v1_[A-Za-z0-9_-]{43,}\b/g,/\bflp_[A-Za-z0-9]{10,}\b/g,/\bwfr_[A-Za-z0-9]{20,}\b/g,/\bfwp?_[A-Za-z0-9_-]{20,}\b/g,/\btp-[A-Za-z0-9_-]{20,}\b/g,/\bpsk-[A-Za-z0-9_-]{8,}-[A-Za-z0-9_-]{8,}\b/g,/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/g];function K(M){return _e(M.replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_DSN|CONNECTION_STRING)=("[^"]*"|'[^']*'|[^\s]+(?:\s+[A-Z_][A-Z0-9_]*=[^\s]+)*)/gi,"$1=<redacted>").replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_(?:URL|URI|CONNECTION_STRING))=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIALS)[A-Z0-9_]*)=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>"))}function _e(M){return Rg.reduce((L,F)=>L.replace(F,"<redacted>"),M.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi,"<redacted>").replace(/((?:(['"])(?:authorization|cookie|x-api-key|api-key)\2|(?:authorization|cookie|x-api-key|api-key))\s*:\s*)(['"])(?:\\[^\r\n]|(?!\3)[^\\\r\n])*\3/gi,"$1$3<redacted>$3").replace(/(['"]?\s*(?:authorization|cookie|x-api-key|api-key)\s*:(?!\s*(?:"<redacted>"|'<redacted>'))\s*)([^'"\r\n]+)(['"]?)/gi,"$1<redacted>$3").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s@/]+)@/gi,"$1<redacted>:<redacted>@").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+)@/gi,"$1<redacted>@").replace(/(^|[\s?&;|])((?:x-amz-signature|x-goog-signature|sig|signature)=)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^&#\s'"`;|<>()]*)/gi,"$1$2<redacted>").replace(/(^|\s)((?:-u|--user)(?:\s+|=))([^\s:]+):([^\s]+)/g,"$1$2<redacted>:<redacted>")).replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"<redacted>").replace(/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,"<redacted>")}function We(M){return Wc(M).reduceRight((L,F)=>`${L.slice(0,F.valueStart)}<redacted>${L.slice(F.valueEnd)}`,M)}function R(M){return _e(We(M))}function tt(M){return Wc(M).map((L)=>M.slice(L.valueStart,L.valueEnd))}function Be(M){return/[A-Za-z_][A-Za-z0-9_]*=/.test(M)}function Wc(M){return[...M.matchAll(/[A-Za-z_][A-Za-z0-9_]*=/g)].flatMap((L)=>{let F=M[L.index-1];if(L.index>0&&F&&!/[\s"'([{]/.test(F))return[];let q=L.index+L[0].length;if(q>=M.length)return[];return[{valueStart:q,valueEnd:_g(M,q)}]})}function _g(M,L){if(M.startsWith("$(",L))return wg(M,L);let F=M[L];if(F==='"'||F==="'"){for(let ne=L+1;ne<M.length;ne++){if(F==='"'&&M[ne]==="\\"){ne++;continue}if(M[ne]===F)return ne+1}return M.length}let q=L;while(q<M.length&&!/\s/.test(M[q]??""))q++;return q}function wg(M,L){let F=0,q;for(let ne=L;ne<M.length;ne++){let re=M[ne];if(q){if(q==='"'&&re==="\\"){ne++;continue}if(re===q)q=void 0;continue}if(re==='"'||re==="'"){q=re;continue}if(re==="$"&&M[ne+1]==="("){F++,ne++;continue}if(re!==")")continue;if(F--,F===0)return ne+1}return M.length}var Pg={hard_stop:"Do not retry this operation or attempt any workaround (other tools, flags, or paths). Report the block to the user and continue with the rest of the task.",use_alternative:"Do not retry the blocked form. Continue the task using the safer alternative described above.",scope_down:"Retry with a narrower, explicit target as described above. Escalate to the user if the broad operation is truly required.",manual_only:"If this operation is truly needed, ask the user for explicit permission and have them run the command manually.",stop_and_explain:"Do not brute-force variants. Simplify or restructure the command so it can be analyzed, or report the block to the user."};function Ag(M){let L=M.maxLen??200,F=M.redact??((ne)=>ne),q=(ne)=>ne.length>L?`${ne.slice(0,L)}...`:ne;return[M.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${F(M.reason)}`,M.ruleId?`Rule: ${M.ruleId}`:void 0,M.toolName?`Tool: ${M.toolName}`:void 0,M.command?`Command: ${q(F(M.command))}`:void 0,M.segment&&M.segment!==M.command?`Segment: ${q(F(M.segment))}`:void 0,M.cwd?`Working directory: ${q(F(M.cwd))}`:void 0,M.configWarning?`Config warning: ${F(M.configWarning)}`:void 0,M.askUser?"Approve only if you expected this command.":Pg[M.intent??"manual_only"]].filter((ne)=>ne!==void 0).join(`
|
|
2
|
+
|
|
3
|
+
`)}function we(M,L){if(M.decision.kind!=="deny")return;let F=L.includeEvidence?M.decision.evidence:void 0;return{reason:M.decision.reason,ruleId:M.decision.ruleId,intent:M.decision.intent,command:F?.command,segment:F?.segment,toolName:L.toolName,...M.configFallback?{configWarning:M.configFallback.reason}:{},...M.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function I(M={}){return{reason:vo,ruleId:"analysis.failed-closed",intent:"stop_and_explain",command:M.command,segment:M.segment??M.command,toolName:M.toolName}}var Tg={session:{unusable:{reason:"CC Safety Net cannot check tool calls because the session's working directory or workspace root no longer exists, is inaccessible, is not a directory, or uses an unsupported path form. Ask the user to restart the session from an existing directory.",intent:"hard_stop",ruleId:"cwd.session-unusable"},"outside-workspace":{reason:"CC Safety Net cannot check tool calls because the session's working directory is outside its workspace roots. Ask the user to restart the session from a directory inside the workspace.",intent:"hard_stop",ruleId:"cwd.session-outside-workspace"}},requested:{unusable:{reason:"CC Safety Net could not use the requested working directory because it does not exist, is inaccessible, is not a directory, or uses an unsupported path form. Use an existing accessible working directory. If the requested directory is missing, create it from an accessible location before retrying the command.",intent:"use_alternative",ruleId:"cwd.requested-unusable"},"outside-workspace":{reason:"CC Safety Net could not use the requested working directory because it is outside the session's workspace. Use a working directory inside the workspace.",intent:"use_alternative",ruleId:"cwd.requested-outside-workspace"}}};function O(M,L={}){return{...Tg[M.directory][M.problem],command:L.command,toolName:L.toolName,cwd:M.cwd}}function J(M){return Ag({...M,redact:K})}function nt(M){return K(M instanceof Error?M.message:String(M))}import{lstatSync as dh,realpathSync as fh,statSync as mh}from"node:fs";import{homedir as ph,tmpdir as gh}from"node:os";import{statSync as lh}from"node:fs";import{join as ch}from"node:path";import{basename as zc,dirname as Ig,isAbsolute as kg,join as Og,normalize as Mg,resolve as Gc}from"node:path";var Dg=256,hi=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 hn(M,L=process.platform){if(L!=="win32")return M;return M.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function rr(M,L=process.platform){if(L!=="win32")return!1;return(M[0]==="/"||M[0]==="\\")&&(M[1]==="/"||M[1]==="\\")}function na(M,L){return Qs(M,0,L)}function Qs(M,L,F){let q="",ne=0;while(ne<M.length){if(M[ne]!=="$"){q+=M[ne],ne++;continue}if(M[ne+1]==="{"){let ue=ea(M,ne+2),Se=Ng(M,ne,L);if(Se===null){if(hi.has(ue))throw new s("pathEnvironmentExpansion");q+=M.slice(ne);break}let ve=M.slice(ne,Se+1);q+=Lg(ve,L,F),ne=Se+1;continue}let re=ea(M,ne+1);if(!re){q+="$",ne++;continue}q+=ta(re,F)??`$${re}`,ne+=re.length+1}return q}function Ng(M,L,F){let q=1;for(let ne=L+2;ne<M.length;ne++){if(M[ne]==="\\"){ne++;continue}if(M[ne]==="$"&&M[ne+1]==="{"){if(q++,F+q>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");ne++;continue}if(M[ne]!=="}")continue;if(q--,q===0)return ne}return null}function Lg(M,L,F){let q=M.slice(2,-1),ne=ea(q,0);if(!ne)return M;let re=q.slice(ne.length);if(!re)return ta(ne,F)??M;let ue=[":-",":+",":=",":?","-","+","=","?"].find((He)=>re.startsWith(He));if(!ue){if(hi.has(ne))throw new s("pathEnvironmentExpansion");return M}if(!hi.has(ne))return M;if(ue.endsWith("="))throw new s("pathEnvironmentExpansion");let Se=ta(ne,F),ve=ue.startsWith(":")?Se!==null&&Se!=="":Se!==null;if(ue.endsWith("?")&&!ve)throw new s("pathEnvironmentExpansion");if(ue.endsWith("-")||ue.endsWith("?"))return ve?Se??"":Qs(re.slice(ue.length),L+1,F);return ve?Qs(re.slice(ue.length),L+1,F):""}function ea(M,L){if(!/[A-Za-z_]/.test(M[L]??""))return"";let F=L+1;while(/[A-Za-z0-9_]/.test(M[F]??""))F++;return M.slice(L,F)}function ta(M,L){if(!hi.has(M))return null;if(M==="HOME")return L.env.get("HOME")??L.home;return L.env.get(M)??null}function Dt(M,L,F){if(!M)return M;let q=F.resolvedPaths.get(M);if(q!==void 0)return q;let ne=[],re=M;while(!0){Bc(F,re);let ue=L.realpath(re);if(ue!==null)return Fc(F,M,ue,ne);let Se=Ig(re);if(Se===re||ne.length>=Dg)return Fc(F,M,re,ne);ne.push(zc(re)),re=Se}}function Fc(M,L,F,q){let ne=q.length===0?F:Og(F,...q.reverse());return M.resolvedPaths.set(L,ne),ne}function Wg(M,L,F){let q=F.resolvedPaths.get(M);if(q!==void 0)return q;Bc(F,M);let ne=L.realpath(M);if(ne!==null)F.resolvedPaths.set(M,ne);return ne}function Bc(M,L){M.charge("realpathAttempts"),M.charge("processedCandidateBytes",Buffer.byteLength(L))}function rn(M,L,F,q){let ne=Uc(M,L,F);if(!ne)return"";return Dt(ne,F.paths,q).replace(/\\/g,"/")}function $c(M,L,F,q,ne){let re=Uc(M,L,F);if(!re)return null;if(ne(zc(re)))return Dt(re,F.paths,q).replace(/\\/g,"/");let ue=Wg(re,F.paths,q);return ue===null?null:ue.replace(/\\/g,"/")}function Uc(M,L,F){let q=F.home,ne=na(M.trim(),F).replace(/\\/g,"/");if(!ne)return"";let re=ne==="~"?q:ne.startsWith("~/")?Gc(q,ne.slice(2)):ne,ue=hn(re);return Mg(kg(ue)?ue:Gc(L,ue))}import{spawnSync as Gg}from"node:child_process";import{existsSync as xo,lstatSync as Fg,readFileSync as Ro,realpathSync as Br,statSync as Eo}from"node:fs";import{dirname as ra,isAbsolute as oa,join as $r,resolve as yi}from"node:path";var zg=["/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"],Bg=5000;function jc(M,L=oh(),F=Bg){let q=$g(M),ne=q===null?null:Ug(q);if(q===null||ne===null)return null;let re=nh(q,ne,L,F);return re===null?null:{recursiveSubmodules:re}}function $g(M){try{let L=Br(yi(M));return Eo(L).isDirectory()?L:null}catch{return null}}function Ug(M){let L=th(M);if(!L)return null;try{let F=Fg(L);if(F.isSymbolicLink()||!F.isFile())return null;let q=ia(L);if(!q?.commonDir)return null;if(!Vg(q.gitDir,L))return null;return Kg(q.gitDir,ra(L))?{gitDir:q.gitDir,commonDir:q.commonDir}:null}catch{return null}}function ia(M){try{let L=Hg(M);if(!L)return null;let F=Br(oa(L)?L:yi(ra(M),L));if(!Eo(F).isDirectory())return null;return{gitDir:F,commonDir:jg(F)}}catch{return null}}function Hg(M){let L=Ro(M,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!L.startsWith("gitdir:"))return null;return L.slice(7).trim()||null}function jg(M){try{let L=Ro($r(M,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!L)return null;let F=Br(oa(L)?L:yi(M,L));return Eo(F).isDirectory()?F:null}catch{return null}}function Vg(M,L){let F=qg(M);return F===null?!1:Vc(M,F,L)}function Kg(M,L){let F=Yg(M);return F===null?!0:Vc(M,F,L)}function qg(M){let L=$r(M,"gitdir");if(!xo(L))return null;let F=Ro(L,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return F===""?null:F}function Yg(M){let L=$r(M,"config.worktree");return xo(L)?Xg(L):null}function Vc(M,L,F){try{return Zg(oa(L)?L:yi(M,L),F)}catch{return!1}}function Zg(M,L){try{let F=Eo(M),q=Eo(L);if(F.ino!==0&&q.ino!==0&&F.dev===q.dev&&F.ino===q.ino)return!0}catch{}return Hc(Br.native(M))===Hc(Br.native(L))}function Hc(M){let L=M.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),F=L.length>1&&L.endsWith("/")?L.slice(0,-1):L;return process.platform==="win32"?F.toLowerCase():F}function Xg(M){let L=Ro(M,"utf-8"),F=!1,q=null;for(let ne of L.split(/\r?\n/)){let re=ne.trim();if(re===""||re.startsWith("#")||re.startsWith(";"))continue;if(re.startsWith("[")){F=/^\[core\]$/i.test(re);continue}if(!F)continue;let ue=re.match(/^worktree\s*=\s*(.*)$/i);if(ue)q=Jg(ue[1]??"")}return q}function Jg(M){let L=M.trim();if(!L.startsWith('"')||!L.endsWith('"'))return L;return eh(L.slice(1,-1))}var Qg={"\\":"\\",'"':'"',n:`
|
|
4
|
+
`,t:"\t",b:"\b"};function eh(M){return M.replace(/\\(.?)/gs,(L,F)=>F===""?L:Qg[F]??L)}function th(M){try{return sa(Br(M))}catch{return null}}function sa(M){let L=M;while(!0){let F=$r(L,".git");if(xo(F))return F;let q=ra(L);if(q===L)return null;L=q}}function nh(M,L,F,q){if(rh(L))return!0;if(F===null)return!0;let ne=Gg(F,["config","--get","submodule.recurse"],{cwd:M,encoding:"utf8",env:ih(process.env),stdio:["ignore","pipe","ignore"],timeout:q});if(ne.error!==void 0||ne.status!==0&&ne.status!==1)return null;return ne.status===0&&Kc(ne.stdout.trim())}function rh(M){return[$r(M.commonDir,"config"),$r(M.gitDir,"config.worktree")].filter((L)=>xo(L)).some((L)=>sh(L))}function oh(){return zg.find((M)=>xo(M))??null}function _o(M){return M==="GIT_CONFIG_COUNT"||M==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(M)}function ih(M){return Object.fromEntries(Object.entries(M).filter(([L])=>!_o(L)))}function sh(M){let L;try{L=Ro(M,"utf-8")}catch{return!0}let F="",q=!1;for(let ne of L.split(/\r?\n/)){let re=ne.trim();if(re===""||re.startsWith("#")||re.startsWith(";"))continue;let ue=re.match(/^\[([^\]]+)\]$/);if(ue){F=ue[1]?.trim().toLowerCase()??"";continue}let Se=re.indexOf("="),ve=(Se===-1?re:re.slice(0,Se)).trim().toLowerCase(),He=Se===-1?"true":re.slice(Se+1).trim();if(ah(F)&&ve==="path")return!0;if(F==="submodule"&&ve==="recurse")q=Kc(He)}return q}function ah(M){return M==="include"||M.startsWith("includeif ")}function Kc(M){let L=M.toLowerCase();return L!=="false"&&L!=="no"&&L!=="off"&&L!=="0"}function qc(M,L){if(M==="")return null;let F=Fn(),q=sa(rn(M,M,L,F)),ne=q?uh(q,M,L,F):null;if(!ne)return null;return Object.freeze({entries:Object.freeze([ne.entry]),markerFiles:Object.freeze(ne.markerFile?[ne.markerFile]:[]),directories:Object.freeze(ne.directories),hooksDirectories:Object.freeze(ne.hooksDirectories)})}function uh(M,L,F,q){try{let ne=rn(M,L,F,q),re=lh(M),ue=re.isFile()?ne:null,Se=re.isFile()?ia(M):null,ve=(re.isDirectory()?[ne]:[Se?.gitDir,Se?.commonDir]).flatMap((dt)=>dt?[Ur(rn(dt,L,F,q))]:[]),He=[...new Set(re.isDirectory()?[Ur(M.replace(/\\/g,"/")),...ve]:ve)];return{entry:Ur(ne),markerFile:ue?Ur(ue):null,directories:He,hooksDirectories:[...new Set(He.flatMap((dt)=>{let mt=Ur(ch(dt,"hooks").replace(/\\/g,"/"));return[mt,Ur(rn(mt,L,F,q))]}))]}}catch{return null}}function Ur(M){return process.platform==="win32"?M.toLowerCase():M}var hh={realpath:(M)=>{try{return fh(M)}catch{return null}},entryKind:(M)=>{let L=dh(M,{throwIfNoEntry:!1});if(!L)return"missing";return L.isSymbolicLink()?"symlink":"present"},isDirectory:(M)=>{try{return mh(M).isDirectory()}catch{return!1}}};function c(){return yh({env:new Map(Object.entries(process.env).flatMap(([M,L])=>L===void 0?[]:[[M,L]])),home:hn(process.env.HOME||ph()),tmpdir:gh(),paths:hh})}function yh(M,L={}){let F=new Map,q=new Map,ne={...M,gitMetadata:(re)=>Yc(F,re,()=>qc(re,ne)),worktreeFacts:(re)=>Yc(q,re,()=>jc(re)),...L};return ne}function Yc(M,L,F){let q=M.get(L);if(q!==void 0)return q;let ne=F();return M.set(L,ne),ne}import{accessSync as zh,constants as du,statSync as Bh}from"node:fs";import{isAbsolute as fu,relative as $h,resolve as Uh,sep as Hh}from"node:path";import{types as bh}from"node:util";var Sh=new Set(["applypatch","patch"]),Ch=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),vh=new Set(["grep","grepsearch","rg"]),Eh=new Set(["find","findbyname","glob"]),xh=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),Rh=new Set(["command","diff","input","patch","patchtext"]),Zc=new TextEncoder,_h=new TextDecoder,wh=/\s/,Ph=64;class f extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var wo=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function tu(M){return M.replace(/[-_\s]/g,"").toLowerCase()}function Si(M){return xh.has(tu(M))}function _(M){let L=tu(M);if(Sh.has(L))return"patch";if(vh.has(L))return"grep";if(Eh.has(L))return"glob";if(Ch.has(L))return"path";return"unknown"}function oe(M){if(!M||typeof M!=="object")return;lu(M);let L=Object.getOwnPropertyDescriptor(M,"command");if(!L){if("command"in M)zn();return}if(L.get||L.set)zn();let F=L.value;return typeof F==="string"&&F!==""?F:void 0}function nu(M,L){return ru(M,L,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function ru(M,L,F,q,ne){let re=au(M,q,ne);if(typeof M==="string")return F?[M]:[];if(!re)return[];let ue=re.entries.flatMap(([Se,ve])=>ru(ve,L,re.array?F:L.has(ou(Se)),q,ne+1));return q.ancestors.delete(re.object),ue}function ou(M){return M.replace(/-/g,"_").toLowerCase()}function iu(M){return su(M,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Th)}function su(M,L,F,q){let ne=au(M,F,q);if(typeof M==="string")return L?[M]:[];if(!ne)return[];let re=ne.entries.flatMap(([ue,Se])=>su(Se,ne.array?L:Rh.has(ou(ue)),F,q+1));return F.ancestors.delete(ne.object),re}function Ah(M,L,F){if(L.nodes++,M!==null&&typeof M==="object"&&F>wo.maxDepth||L.nodes>wo.maxNodes)zn();if(typeof M!=="string")return;let q=Buffer.byteLength(M);if(L.stringBytes+=q,q>wo.maxStringBytes||L.stringBytes>wo.maxAggregateStringBytes)zn()}function au(M,L,F){if(Ah(M,L,F),!M||typeof M!=="object")return null;let q=lu(M);if(L.ancestors.has(M))zn();let ne=Reflect.ownKeys(M);if(L.keys+=ne.length,L.keys>wo.maxKeys)zn();let re=ne.flatMap((ue)=>{let Se=Object.getOwnPropertyDescriptor(M,ue);if(!Se||Se.get||Se.set)zn();return typeof ue==="string"&&Se.enumerable?[[ue,Se.value]]:[]});return L.ancestors.add(M),{object:M,array:q,entries:re}}function lu(M){if(bh.isProxy(M))zn();let L=Array.isArray(M),F=Object.getPrototypeOf(M);if(L&&F!==Array.prototype||!L&&F!==Object.prototype&&F!==null)zn();return L}function zn(){throw new f}function Th(M){let L=[],F=M.split(/\r?\n/),q=!1,ne=!1,re=null,ue=null,Se=()=>{ne=!1,re=null,ue=null};for(let ve=0;ve<F.length;ve++){let He=F[ve]??"";if(He==="*** Begin Patch"){q=!0,Se();continue}if(He==="*** End Patch"){q=!1,Se();continue}if(He.startsWith("@@")){let dt=Ih(He);if(ne=!0,re=dt?.oldLines??null,ue=dt?.newLines??null,re===0&&ue===0)Se();continue}if(ne&&re!==null&&ue!==null){let dt=He.startsWith(" ")||He.startsWith("-")?1:0,mt=He.startsWith(" ")||He.startsWith("+")?1:0;if(re=Math.max(0,re-dt),ue=Math.max(0,ue-mt),re===0&&ue===0)Se();continue}if(He.startsWith("*** ")){Se(),L.push(...aa(He));continue}if(ne)continue;if(He.startsWith("diff --git ")){L.push(...aa(He));continue}if(He.startsWith("--- ")){let dt=F[ve+1]??"";if(!dt.startsWith("+++ "))continue;L.push(...ca(bi(He.slice(4),!0),bi(dt.slice(4),!0))),ve++;continue}if(!q)L.push(...aa(He))}return L}function Ih(M){let L=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(M);if(!L)return null;return{oldLines:Number(L[1]??1),newLines:Number(L[2]??1)}}function aa(M){let L=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(M);if(L?.[1])return eu(L[1]);let F=/^\*\*\* Move to: (.+)$/.exec(M);if(F?.[1])return eu(F[1]);if(M.startsWith("diff --git "))return kh(M.slice(11));let q=/^--- (.+)$/.exec(M);if(q?.[1])return Qc(q[1]);let ne=/^\+\+\+ (.+)$/.exec(M);if(ne?.[1])return Qc(ne[1]);let re=/^(?:rename|copy) (?:from|to) (.+)$/.exec(M);if(re?.[1])return Gh(re[1]);return[]}function kh(M){let L=Oh(M);if(L.length===2&&L[0]&&L[1])return ca(L[0],L[1]);let F=Mh(M);return F?ca(M.slice(F.oldStart,F.oldEnd),M.slice(F.newStart,F.newEnd)):[]}function Oh(M){let L=[],F=0;while(F<M.length&&L.length<2){while(br(M[F]))F++;if(F>=M.length)break;let q=M[F]==='"'||M[F]==="'"?M[F]:void 0;if(!q){let re=F;while(F<M.length&&!br(M[F]))F++;L.push(M.slice(re,F));continue}let ne=cu(M,F,q);if(!ne)return[];L.push(ne.value),F=ne.end}while(br(M[F]))F++;return F===M.length?L:[]}function Mh(M){let L=0;while(L<M.length&&br(M[L]))L++;let F=M.length;while(F>L&&br(M[F-1]))F--;let q=0,ne=L;while(ne<F){if(!br(M[ne])){ne++;continue}let re=ne;while(ne<F&&br(M[ne]))ne++;if(re===L||ne===F)continue;if(q++,q>Ph)zn();if(Dh(M,L,re,ne,F))return{oldStart:L,oldEnd:re,newStart:ne,newEnd:F}}return null}function Dh(M,L,F,q,ne){if(la(M,L,F,q,ne))return!0;let re=Xc(M,"/",L,F),ue=Xc(M,"/",q,ne);if(re<=L||ue<=q)return!1;if(la(M,L,re,q,ue))return!1;return la(M,re+1,F,ue+1,ne)}function la(M,L,F,q,ne){if(F-L!==ne-q)return!1;for(let re=0;re<F-L;re++)if(M[L+re]!==M[q+re])return!1;return!0}function Xc(M,L,F,q){for(let ne=F;ne<q;ne++)if(M[ne]===L)return ne;return-1}function br(M){return M!==void 0&&wh.test(M)}function cu(M,L,F){let q=[],ne=L+1;while(ne<M.length){let re=String.fromCodePoint(M.codePointAt(ne)??0);if(re===F)return{value:_h.decode(Uint8Array.from(q)),end:ne+1};if(re!=="\\"||F==="'"){q.push(...Zc.encode(re)),ne+=re.length;continue}let ue=M.slice(ne+1),Se=/^[0-7]{1,3}/.exec(ue)?.[0];if(Se){q.push(Number.parseInt(Se,8)),ne+=Se.length+1;continue}q.push(...Zc.encode(Nh(ue[0]??""))),ne+=2}return null}function Nh(M){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
5
|
+
`,r:"\r",t:"\t",v:"\v"}[M]??M}function Lh(M){return Po(Fh(M))}function ca(M,L){if(M==="/dev/null")return Jc(L);if(L==="/dev/null")return Jc(M);if(M.startsWith("a/")&&L.startsWith("b/"))return[M.slice(2),L.slice(2)].flatMap(Po);let F=Wh(M,L)??(M===L?uu(M):null);return[M,L,...F?[F]:[]].flatMap(Po)}function Jc(M){let L=uu(M);return[M,...L?[L]:[]].flatMap(Po)}function uu(M){let L=M.indexOf("/");return L>0&&L<M.length-1?M.slice(L+1):null}function Wh(M,L){let F=M.indexOf("/"),q=L.indexOf("/");if(F<1||q<1)return null;if(M.slice(0,F)===L.slice(0,q))return null;let ne=M.slice(F+1);return ne===L.slice(q+1)?ne:null}function Qc(M){return Lh(bi(M,!0))}function Gh(M){return Po(bi(M,!1))}function bi(M,L){let F=M.trim(),q=F[0]==='"'||F[0]==="'"?F[0]:void 0;if(q){let ne=cu(F,0,q);if(ne&&(L||F.slice(ne.end).trim()===""))return ne.value}return L?F.split("\t",1)[0]?.trim()??"":F}function Fh(M){return M.startsWith("a/")||M.startsWith("b/")?M.slice(2):M}function Po(M){return M===""||M==="/dev/null"?[]:[M]}function eu(M){let L=M.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return L===""||L==="/dev/null"?[]:[L]}function pe(M){try{if(!Bh(M).isDirectory())return!1;return zh(M,du.R_OK|du.X_OK),!0}catch{return!1}}function ot(M,L,F){if(rr(M))return;let q=L.flatMap((re)=>ua(re,F));if(!q[0])return;let ne=ua(fu(M)?M:Uh(q[0],M),F)[0];if(!ne)return;return q.some((re)=>jh(ne,re))?ne:void 0}function Ve(M,L){return M.flatMap((F)=>ua(F,L))[0]}function ua(M,L){let F=L.realpath(M);if(F===null)return[];return L.isDirectory(F)?[F]:[]}function jh(M,L){let F=$h(L,M);return F===""||F!==".."&&!F.startsWith(`..${Hh}`)&&!fu(F)}var Vh=8388608;async function qe(M){let L=[],F=0;for await(let q of M){let ne=typeof q==="string"?Buffer.from(q,"utf-8"):Buffer.from(q.buffer,q.byteOffset,q.byteLength);if(F+=ne.byteLength,F>Vh)throw Kh(M),Error("hook input byte limit exceeded");L.push(ne)}return Buffer.concat(L,F).toString("utf-8")}function Kh(M){let L=M.destroy??M.cancel;if(!L)return;try{Promise.resolve(L.call(M)).catch(()=>{})}catch{}}function l(M,L,F,q,ne){if(F.kind!=="command")return{toolName:M,input:L,route:F,context:q};return{toolName:M,input:L,route:F,context:q,command:ne}}var Hr=["fail_closed","paranoid_rm","paranoid_interpreters"],Ci={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 n={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"},projectTightenOnly:{name:"CC_SAFETY_NET_PROJECT_TIGHTEN_ONLY"}},vi=["standard","strict","paranoid"];function mu(M,L){if(!L)return M;return vi.indexOf(L)>vi.indexOf(M)?L:M}function pu(M){let L=de(n.level,M);return vi.find((F)=>F===L)}function gu(M,L){return mu(M,pu(L))}function qh(M){let L=de(n.level,M);if(!L)return;let F=pu(M);if(F)return F;console.error(`CC Safety Net: ignored invalid ${n.level.name}=${JSON.stringify(L.slice(0,40))}. Use ${vi.join(", ")}.`);return}function ze(M){if(M===void 0||M==="all")return"all";if(M==="blocked")return"blocked";return"invalid"}function Ce(M){return ze(de(n.auditScope,M))==="all"}function da(M){if(M.failClosed&&M.paranoidRm&&M.paranoidInterpreters)return"paranoid";if(M.failClosed&&!M.paranoidRm&&!M.paranoidInterpreters)return"strict";if(!M.failClosed&&!M.paranoidRm&&!M.paranoidInterpreters)return"standard";return"custom"}function T(M={},L){let F=M.safety?.level??"standard",q=qh(L),ne=mu(F,q),re=Ci[ne],ue={failClosed:re.fail_closed,paranoidRm:re.paranoid_rm,paranoidInterpreters:re.paranoid_interpreters},Se={failClosed:ne===F?"preset":"environment",paranoidRm:ne===F?"preset":"environment",paranoidInterpreters:ne===F?"preset":"environment"},ve={failClosed:[`policy safety.level=${F}`],paranoidRm:[`policy safety.level=${F}`],paranoidInterpreters:[`policy safety.level=${F}`]};if(ne!==F)ve.failClosed.push(`env ${n.level.name}=${q}`),ve.paranoidRm.push(`env ${n.level.name}=${q}`),ve.paranoidInterpreters.push(`env ${n.level.name}=${q}`);if(M.safety?.overrides?.failClosed!==void 0)ue.failClosed=M.safety.overrides.failClosed,Se.failClosed="capability_override",ve.failClosed.push("policy safety.overrides.fail_closed");if(M.safety?.overrides?.paranoidRm!==void 0)ue.paranoidRm=M.safety.overrides.paranoidRm,Se.paranoidRm="capability_override",ve.paranoidRm.push("policy safety.overrides.paranoid_rm");if(M.safety?.overrides?.paranoidInterpreters!==void 0)ue.paranoidInterpreters=M.safety.overrides.paranoidInterpreters,Se.paranoidInterpreters="capability_override",ve.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(x(n.strict,L))ue.failClosed=!0,Se.failClosed="environment",ve.failClosed.push(`env ${n.strict.name}`);if(x(n.paranoid,L))ue.paranoidRm=!0,ue.paranoidInterpreters=!0,Se.paranoidRm="environment",Se.paranoidInterpreters="environment",ve.paranoidRm.push(`env ${n.paranoid.name}`),ve.paranoidInterpreters.push(`env ${n.paranoid.name}`);if(x(n.paranoidRm,L))ue.paranoidRm=!0,Se.paranoidRm="environment",ve.paranoidRm.push(`env ${n.paranoidRm.name}`);if(x(n.paranoidInterpreters,L))ue.paranoidInterpreters=!0,Se.paranoidInterpreters="environment",ve.paranoidInterpreters.push(`env ${n.paranoidInterpreters.name}`);let He=!!M.worktreeMode||x(n.worktree,L);return{strict:ue.failClosed,paranoidRm:ue.paranoidRm,paranoidInterpreters:ue.paranoidInterpreters,worktreeMode:He,effectiveLevel:da(ue),capabilities:{fail_closed:{enabled:ue.failClosed,source:Se.failClosed,sources:ve.failClosed},paranoid_rm:{enabled:ue.paranoidRm,source:Se.paranoidRm,sources:ve.paranoidRm},paranoid_interpreters:{enabled:ue.paranoidInterpreters,source:Se.paranoidInterpreters,sources:ve.paranoidInterpreters}}}}function x(M,L){let F=typeof M==="string"?Ao(M,L):de(M,L);return F==="1"||F?.toLowerCase()==="true"}function Ao(M,L){return L.get(M)}function de(M,L){let F=Ao(M.name,L);if(F!==void 0)return F;if(M.legacyName)return Ao(M.legacyName,L);return}function rt(M,L){return Ao(M.name,L)!==void 0||!!M.legacyName&&Ao(M.legacyName,L)!==void 0}import{dirname as xr}from"node:path";import{closeSync as Yh,constants as To,fstatSync as fa,fsyncSync as Zh,lstatSync as xn,mkdirSync as hu,openSync as yu,readdirSync as pa,readFileSync as Xh,realpathSync as jr,renameSync as Jh,rmdirSync as bu,statSync as ma,unlinkSync as ga,writeFileSync as Qh}from"node:fs";import{isAbsolute as Su,join as Sr,normalize as ey,parse as Ei,relative as ha,resolve as ya,sep as xi}from"node:path";function Pe(){let M=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${M()}${M()}`}var ty=Symbol("PolicyFilesystemScope"),ny=Symbol("PolicyFilesystemTarget"),Cu=To.O_NOFOLLOW??0;class o extends Error{name="PolicyFilesystemError";constructor(M){super(`Unable to access ${M} filesystem safely.`)}}function v(M,L){return{[ty]:!0,root:ya(M),label:L}}function Io(M,L){let F=ey(L);if(L===""||Su(L)||F===".."||F.startsWith(`..${xi}`))throw new o(M.label);return{[ny]:!0,scope:M,relativePath:F,path:Sr(M.root,F)}}function i(M,L){return Io(M,ha(M.root,ya(L)))}function ie(M,L="rules policy"){let F=ya(M),q=Ei(F).dir;return Io(v(q,L),ha(q,F))}function r(M){return Vn(M.scope.label,()=>{if(!Xt(M))return null;let L=yu(M.path,To.O_RDONLY|Cu);return Eu(L,()=>{let F=fa(L);if(!F.isFile())throw new o(M.scope.label);let q=Xh(L,"utf-8"),ne=xn(M.path);if(!ne.isFile()||ne.isSymbolicLink()||F.dev!==ne.dev||F.ino!==ne.ino)throw new o(M.scope.label);return Xt(M),q})})}function g(M,L,F=384,q){let ne=`${M.path}.${Pe()}.tmp`;Vn(M.scope.label,()=>{oy(M),Xt(M);let re=yu(ne,To.O_CREAT|To.O_EXCL|To.O_WRONLY|Cu,F),ue=Eu(re,()=>{let Se=fa(re);if(!Se.isFile())throw new o(M.scope.label);Qh(re,L,"utf-8"),Zh(re);let ve=fa(re);if(!ve.isFile()||ve.dev!==Se.dev||ve.ino!==Se.ino)throw new o(M.scope.label);return ve});Xt(M),sy(M,ne,ue.dev,ue.ino),Jh(ne,M.path),q?.(M.path),Xt(M)},()=>ay(ne))}function vu(M,L){if(M.path===L.path)return!0;return Vn(M.scope.label,()=>{if(!Xt(M)||!Xt(L))return!1;let F=(q)=>Sr(jr(Ei(q).dir),Ei(q).base);return F(M.path)===F(L.path)})}function fe(M){let L=Vn(M.scope.label,()=>{if(!Xt(M,"directory"))return null;let F=pa(M.path);return Xt(M,"directory"),F});if(!L)return null;return Vn(M.scope.label,()=>{let F=L.map((q)=>{let ne=Io(M.scope,Sr(M.relativePath,q)),re=xn(ne.path);if(re.isSymbolicLink()||!re.isFile()&&!re.isDirectory())throw new o(M.scope.label);return Ri(ba(M.scope),jr(ne.path),M.scope.label),{name:q,kind:re.isDirectory()?"directory":"file"}});return Xt(M,"directory"),F})}function j(M){Vn(M.scope.label,()=>{if(!Xt(M))return;ga(M.path),Xt(M)})}function it(M){Vn(M.scope.label,()=>{if(!ry(M))return;Ru(M),Xt(M,"directory")})}function st(M){Vn(M.scope.label,()=>{if(!Xt(M,"directory"))return;bu(M.path),Xt(M,"directory")})}function ry(M){return Vn(M.scope.label,()=>{if(!Xt(M,"directory"))return!1;return xu(M),!0})}function Vn(M,L,F){try{return L()}catch(q){if(F?.(),q instanceof o)throw q;throw new o(M)}}function Eu(M,L){try{return L()}finally{Yh(M)}}function Xt(M,L="file"){let F=_u(M.scope);if(!F)return!1;let q=M.relativePath.split(xi);for(let ne of q.keys()){let re=Sr(M.scope.root,...q.slice(0,ne+1)),ue=xn(re,{throwIfNoEntry:!1});if(!ue)return!1;if(ue.isSymbolicLink())throw new o(M.scope.label);if(ne<q.length-1&&!ue.isDirectory())throw new o(M.scope.label);if(ne===q.length-1&&(L==="file"?!ue.isFile():!ue.isDirectory()))throw new o(M.scope.label);Ri(F,jr(re),M.scope.label)}return!0}function xu(M){for(let L of pa(M.path)){let F=Io(M.scope,Sr(M.relativePath,L)),q=xn(F.path);if(q.isSymbolicLink()||!q.isDirectory()&&!q.isFile())throw new o(M.scope.label);if(q.isDirectory())xu(F)}Xt(M,"directory")}function Ru(M){for(let L of pa(M.path)){let F=Io(M.scope,Sr(M.relativePath,L)),q=xn(F.path);if(q.isSymbolicLink())throw new o(M.scope.label);if(q.isDirectory()){Ru(F);continue}if(!q.isFile())throw new o(M.scope.label);ga(F.path)}bu(M.path)}function oy(M){iy(M.scope);let L=ba(M.scope),F=M.relativePath.split(xi).slice(0,-1);for(let q of F.keys()){let ne=Sr(M.scope.root,...F.slice(0,q+1));if(!xn(ne,{throwIfNoEntry:!1}))hu(ne,{mode:448});let re=xn(ne);if(!re.isDirectory()||re.isSymbolicLink())throw new o(M.scope.label);Ri(L,jr(ne),M.scope.label)}}function iy(M){if(xn(M.root,{throwIfNoEntry:!1})){if(!ma(M.root).isDirectory())throw new o(M.label);return}let L=[],F=M.root;while(!xn(F,{throwIfNoEntry:!1})){L.unshift(F);let q=Ei(F).dir;if(q===F)throw new o(M.label);F=q}if(!ma(F).isDirectory())throw new o(M.label);for(let q of L){hu(q,{mode:448});let ne=xn(q);if(!ne.isDirectory()||ne.isSymbolicLink())throw new o(M.label)}}function _u(M){if(!xn(M.root,{throwIfNoEntry:!1}))return null;if(!ma(M.root).isDirectory())throw new o(M.label);return jr(M.root)}function ba(M){let L=_u(M);if(!L)throw new o(M.label);return L}function sy(M,L,F,q){let ne=xn(L);if(!ne.isFile()||ne.isSymbolicLink()||ne.dev!==F||ne.ino!==q)throw new o(M.scope.label);Ri(ba(M.scope),jr(L),M.scope.label)}function Ri(M,L,F){let q=ha(M,L);if(q===".."||q.startsWith(`..${xi}`)||Su(q))throw new o(F)}function ay(M){try{ga(M)}catch{}}import{dirname as Cr,isAbsolute as fy,join as Er,relative as my,resolve as vr,sep as py}from"node:path";var u=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,me="rulebook.json",ge=".cc-safety-net/rules";var wu=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,ly=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,Pu=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,cy=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),uy="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),at=new RegExp(`^${cy}/(${u.source.slice(1,-1)})/${uy}$`);function dy(M){return`.cc-safety-net/rules/${M}/rulebook.json`}function Au(M){if(S(M))try{return D(M),null}catch(L){return L instanceof Error?L.message:String(L)}return u.test(M)?null:`Local rulebook sources must be bare names matching ${u}: ${M}`}function D(M){if(M.startsWith("github:"))throw Error(`Invalid rulebook source: ${M}`);let L=M.match(wu);if(!L?.[1]||!L[2]||!L[3])throw Error(`Invalid GitHub rulebook source: ${M}`);let F=L[3].lastIndexOf("/");if(F<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${M}`);let q=L[3].slice(0,F),ne=L[3].slice(F+1);if(!q||!Pu.test(q))throw Error(`GitHub rulebook refs must use valid path segments: ${M}`);if(!ne||!u.test(ne))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${M}`);return{owner:L[1],repo:L[2],ref:q,path:dy(ne),name:ne}}function Y(M){return ly.test(M)}function se(M){return Pu.test(M)}function S(M){return wu.test(M)}function ct(M){if(!u.test(M))throw Error(`Local rulebook sources must be bare names matching ${u}: ${M}`)}var Tu="rule.json",_i="policy.json",Iu=".cc-safety-net",gy="rules",hy="CC_SAFETY_NET_HOME",ku="`cc-safety-net rule update`";function yy(M){return vr(M,ge)}function U(M){return Er(yy(M),Tu)}function b(M){return Er(vr(M),Iu,_i)}function Ee(M,L={}){return L.userConfigDir??(L.userConfigPath?Cr(L.userConfigPath):Er(by(M),gy))}function by(M){let L=M.env.get(hy);return L?vr(hn(L)):Er(M.home,Iu)}function G(M,L={}){return Er(Ee(M,L),Tu)}function d(M,L={}){return Er(Cr(Ee(M,L)),_i)}function Z(M,L){let F=L.userConfigPath??G(M,L),q=L.projectConfigPath??U(L.cwd),ne=Ke(M,L),re=Je(q,L.cwd);return{userConfigPath:F,projectConfigPath:q,userScope:ne,projectScope:re,userConfigTarget:i(ne,F),projectConfigTarget:i(re,q)}}function Ke(M,L){let F=L.userConfigPath?Cr(Cr(vr(L.userConfigPath))):Cr(vr(L.userConfigDir??Ee(M,L)));return v(F,"user policy")}function Je(M,L){let F=vr(L),q=vr(M),ne=my(F,q);if(ne!==".."&&!ne.startsWith(`..${py}`)&&!fy(ne))return v(F,"project policy");return v(Cr(Cr(q)),"project policy")}function N(M,L){return Er(M,L,me)}var yn=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),w=/^[a-zA-Z][a-zA-Z0-9_-]*$/,P=256,Ht=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Ou=new Set(["python","python3","python2","node","ruby","perl"]),wi=/^python(?:[23](?:\.\d+)*)?$/,Rn=new Set(["awk","gawk","nawk","mawk"]),Pi=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 Mu="Rulebook exceeds CC Safety Net's safe validation limits.",Du="Additional rulebook validation errors were omitted.",An=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Nu(M){if(Sa(M.allowed_commands,An.maxAllowedCommands)||Sa(M.rules,An.maxRules)||Sa(M.tests,An.maxTests))return!1;let{maxAggregateStringCodeUnits:L,maxTotalBlockArgs:F}=An,q=(ne,re=!1)=>{if(typeof ne!=="string")return!0;if(ne.length>An.maxStringCodeUnits||re&&ne.length>An.maxFixtureCommandCodeUnits||ne.length>L)return!1;return L-=ne.length,!0};if(!q(M.name)||!q(M.version)||!q(M.description)||!q(M.author)||!q(M.migrated_from))return!1;if(Array.isArray(M.allowed_commands)){for(let ne of M.allowed_commands)if(!q(ne))return!1}if(Array.isArray(M.rules))for(let ne of M.rules){if(!ne||typeof ne!=="object")continue;let re=ne;if(!q(re.name)||!q(re.command)||!q(re.subcommand)||!q(re.reason)||!q(re.intent))return!1;let ue=re.match&&typeof re.match==="object"?re.match:{};for(let Se of[re.block_args,ue.command_path,ue.any_args,ue.exclude_args]){if(!Array.isArray(Se))continue;if(Se.length>An.maxBlockArgsPerRule||Se.length>F)return!1;F-=Se.length;for(let ve of Se)if(!q(ve))return!1}}if(Array.isArray(M.tests))for(let ne of M.tests){if(!ne||typeof ne!=="object")continue;let re=ne;if(!q(re.command,!0)||!q(re.expect)||!q(re.rule))return!1}return!0}function Sa(M,L){return Array.isArray(M)&&M.length>L}var Ca=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var he=64,ye="Rule config exceeds CC Safety Net's safe source limit.";function It(M){return wt(M).toLowerCase()}function wt(M){return M.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??M}function ln(M,L){let F=new Set,q=!1;for(let ne of M){if(ne==="--"){q=!0;continue}if(q)continue;if(ne.startsWith("-")&&!ne.startsWith("--")&&ne.length>1)for(let re=1;re<ne.length;re++){let ue=ne[re];if(!ue||!/[a-zA-Z]/.test(ue))break;let Se=`-${ue}`;if(F.add(Se),L?.shortOptsWithValue?.has(Se))break}}return F}var Sy={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},va=new Set(["--init-file","--rcfile"]);function Ea(M,L,F,q){let ne=!1,re=0,ue=!1,Se=!1,ve=!1;for(let He=1;He<L.length;He++){let dt=L[He];if(dt===void 0)break;if(M==="ksh"&&dt==="o"&&He+1<L.length){if(q==="argv"){let mt=L.slice(He+1);if(L[0]==="-"&&(mt==="c"||mt[0]==="-"&&mt.endsWith("c")))ue=!0}break}if(M==="ksh"&&dt==="o"&&He+1===L.length&&(F?.startsWith("-")||F?.startsWith("+")))break;if(M==="zsh"&&dt==="o"&&He+1<L.length)break;if(q==="startup"&&dt==="i")ne=L[0]==="-";if(q==="argv"&&L[0]==="-"&&dt==="c")ue=!0;if(q==="argv"&&dt==="n")ve=L[0]==="-";if(q==="argv"&&dt==="s")Se=L[0]==="-";if(!Sy[M]?.includes(dt))continue;if(He+1===L.length)re++;break}return{interactive:ne,followingValues:re,commandSelected:ue,stdinMode:Se,syntaxCheck:ve}}function bn(M){let L=wt(M[0]??"").toLowerCase(),F=!1,q=!1,ne=!1;for(let re=1;re<M.length;re++){let ue=M[re];if(ue===void 0)break;if(ue==="--"){let ve=F&&M[re+1]!==void 0?re+1:null;return{command:ve===null?null:M[ve]??null,commandIndex:ve,scriptIndex:!F&&!q&&M[re+1]!==void 0?re+1:null,readsStdinAsCommands:!F&&(q||M[re+1]===void 0),syntaxCheck:ne}}if(ue==="-"||ue[0]!=="-"&&ue[0]!=="+")return{command:F?ue:null,commandIndex:F?re:null,scriptIndex:!F&&!q&&ue!=="-"?re:null,readsStdinAsCommands:!F&&(q||ue==="-"),syntaxCheck:ne};if(ue.startsWith("--")){let ve=ue.split("=",1)[0]??ue;if(L==="bash"&&va.has(ve)&&!ue.includes("="))re++;continue}let Se=Ea(L,ue,M[re+1],"argv");if(Se.commandSelected)F=!0;if(Se.syntaxCheck)ne=!0;if(Se.stdinMode)q=!0;re+=Se.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!F,syntaxCheck:ne}}function ko(M,L){if(L.escaped)return L.escaped=!1,!0;if(M==="\\"&&!L.inSingle)return L.escaped=!0,!0;if(M==="'"&&!L.inDouble)return L.inSingle=!L.inSingle,!0;if(M==='"'&&!L.inSingle)return L.inDouble=!L.inDouble,!0;return!1}function Ai(M){let L={inSingle:!1,inDouble:!1,escaped:!1};for(let F of Cy(M))ko(F,L);return L.inSingle||L.inDouble}function Cy(M){let L="",F={inSingle:!1,inDouble:!1,escaped:!1},q=!1,ne=!0;for(let re=0;re<M.length;re++){let ue=M[re];if(!ue)break;if(q){if(ue===`
|
|
6
|
+
`||ue==="\r")L+=ue,q=!1,F.escaped=!1;continue}if(ue==="#"&&!F.inSingle&&!F.inDouble&&ne){q=!0;continue}if(L+=ue,!F.inSingle&&!F.inDouble&&!F.escaped)ne=/[\s;&|()<>]/.test(ue);ko(ue,F)}return L}var xa=new Set(["rm","find","xargs","parallel"]),vy=new Set(["git","busybox",...xa,...Ht,...Ou,...Rn]),Ey=new Set(["python","node","ruby","perl"]);function Ae(M){let L=It(M);return vy.has(L)||Tn(L)}function Tn(M){return Ey.has(xy(M))}function xy(M){let L=wt(M).toLowerCase();return wi.test(L)?"python":L}var lt={version:1,rules:[],overrides:{},transparent_wrappers:[]};function m(M){try{let L=r(Ry(M));if(L===null)return{config:null,errors:[]};if(!L.trim())return{config:null,errors:["Config file is empty"]};let F=JSON.parse(L),q=Ye(F);if(q.errors.length>0)return{config:null,errors:q.errors};return{config:{version:1,rules:F.rules??[],overrides:F.overrides??{},transparent_wrappers:F.transparent_wrappers??[]},errors:[]}}catch(L){if(L instanceof o)return{config:null,errors:[L.message]};let F=L instanceof Error?L.message:String(L);return{config:null,errors:[L instanceof SyntaxError?"Invalid JSON":F]}}}function Ry(M){return typeof M==="string"?ie(M):M}var e=(M,L)=>({path:M,message:L,kind:"typed"}),Jt=(M,L)=>({path:M,message:L,kind:"custom"});function Ie(M){let L=new Set;return M.flatMap((F,q)=>{let ne=Vr(F)?F.name:void 0;if(typeof ne!=="string")return[];if(L.has(ne.toLowerCase()))return[Jt(["rules",q,"name"],`duplicate rule name "${ne}"`)];return L.add(ne.toLowerCase()),[]})}var ke=`must be one of ${Ca.join(", ")}`,_y=/^[^/]+\/[^/]+$/,wy=["version","rules","overrides","transparent_wrappers"];function Ye(M){let L=Py(M);return{errors:ae(Ze(L,wy,(F)=>F.kind==="custom"),": "," "),sources:Ny(M,L)}}function Py(M){if(!Vr(M))return[e([],"Config must be an object")];let L=Array.isArray(M.rules)&&M.rules.length>he;return[...M.version===1?[]:[e(["version"],"must be 1")],...Ay(M.rules,L),...ky(M.overrides),...My(M.transparent_wrappers),...L?[]:Iy(M.rules),...Vr(M.overrides)?Object.keys(M.overrides).filter((F)=>!_y.test(F)).map((F)=>Jt(["overrides",F],"must use <rulebook-name>/<rule-name>")):[],...Dy(M.transparent_wrappers)]}function Ay(M,L){if(M===void 0)return[];if(!Array.isArray(M))return[e(["rules"],"must be an array of rulebook source strings"),...Lu(M,he)?[e(["rules"],ye)]:[]];if(L)return[{path:["rules"],message:ye,kind:"limit"}];return M.flatMap((F,q)=>{if(typeof F!=="string")return[e(["rules",q],"must be a rulebook source string"),...Ty(F,1)?[e(["rules",q],"must be a non-empty rulebook source string")]:[]];return F===""?[e(["rules",q],"must be a non-empty rulebook source string")]:[]})}function Lu(M,L){let F=Wu(M);return F!==void 0&&!(F<=L)}function Ty(M,L){let F=Wu(M);return F!==void 0&&!(F>=L)}function Wu(M){if(M===null||M===void 0)return;let L=M.length;return L===void 0?void 0:Number(L)}function Iy(M){if(!Array.isArray(M))return[];let L=new Set;return M.flatMap((F,q)=>{if(typeof F!=="string"||F==="")return[];if(F.trim()==="")return[Jt(["rules",q],"must be a non-empty rulebook source string")];let ne=Au(F);if(ne)return[Jt(["rules",q],ne)];if(L.has(F))return[Jt(["rules",q],`duplicate rulebook source "${F}"`)];return L.add(F),[]})}function ky(M){if(M===void 0)return[];if(!Vr(M))return[e(["overrides"],"must be an object if provided")];return Object.keys(M).flatMap((L)=>{let F=M[L];if(F==="off")return[];if(!Vr(F))return[e(["overrides",L],'must be "off" or an object')];return[...Oy(F.reason,["overrides",L,"reason"]),...F.intent===void 0||Re(F.intent)?[]:[e(["overrides",L,"intent"],ke)]]})}function Oy(M,L){if(typeof M!=="string")return[e(L,"required non-empty string"),...Lu(M,P)?[e(L,`must be at most ${P} characters`)]:[]];if(M==="")return[e(L,"required non-empty string")];return M.length>P?[e(L,`must be at most ${P} characters`)]:[]}function My(M){if(M===void 0)return[];if(!Array.isArray(M))return[e(["transparent_wrappers"],"must be an array of command strings")];return M.flatMap((L,F)=>{if(typeof L!=="string")return[e(["transparent_wrappers",F],"must be a command string")];return w.test(L)?[]:[e(["transparent_wrappers",F],"must match command pattern")]})}function Dy(M){if(!Array.isArray(M))return[];let L=new Set;return M.flatMap((F,q)=>{if(typeof F!=="string"||!w.test(F))return[];if(L.has(F))return[Jt(["transparent_wrappers",q],`duplicate command "${F}"`)];if(Ae(F))return[Jt(["transparent_wrappers",q],`reserved command "${F}" cannot be a wrapper`)];return L.add(F),[]})}function Ny(M,L){let F=Vr(M)?M.rules:void 0;if(!Array.isArray(F))return new Set;if(L.some((ne)=>ne.path.length===1&&ne.path[0]==="rules"))return new Set;let q=new Set(L.filter((ne)=>ne.path[0]==="rules"&&typeof ne.path[1]==="number").map((ne)=>ne.path[1]));return new Set(F.filter((ne,re)=>typeof ne==="string"&&!q.has(re)))}function Ze(M,L,F){let q=M.map((ue)=>ue.path[1]),ne=[...new Set(q.filter((ue)=>typeof ue==="string"))],re=(ue,Se)=>[ue.path.length===0?-1:L.indexOf(String(ue.path[0])),typeof Se==="number"?Se:ne.indexOf(String(Se)),F(ue)?0:1];return M.map((ue,Se)=>({issue:ue,rank:re(ue,q[Se])})).sort((ue,Se)=>ue.rank[0]-Se.rank[0]||ue.rank[1]-Se.rank[1]||ue.rank[2]-Se.rank[2]).map((ue)=>ue.issue)}function ae(M,L,F){return[...new Set(M.map((q)=>{let ne=Ra(q.path);if(q.kind==="unknownKeys")return`${ne?`${ne}.`:""}unknown field "${q.message}"`;if(q.kind==="key"||q.kind==="limit"||q.path.length===0)return q.message;return`${ne}${q.path.length===1?F:L}${q.message}`}))]}function Ra(M){return M.map((L,F)=>{if(typeof L==="number")return`[${L}]`;return F===0?String(L):`.${String(L)}`}).join("")}function Re(M){return Ca.includes(M)}function Vr(M){return!!M&&typeof M==="object"&&!Array.isArray(M)}function ce(M){let L=Gy(M);if(L.errors.length>0)throw Error(L.errors.join("; "));return M}var Ly=`required non-empty string up to ${P} characters`,Gu="must be a non-empty array of unique non-empty strings",Wy="required non-empty array of non-empty strings";function Gy(M){if(!or(M))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Nu(M))return{errors:[Mu],ruleNames:new Set};let L=[...M.rulebook_version===1||M.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ae(Fy(M,M.rulebook_version===2),": ",": ")];return{errors:L.length>An.maxValidationErrors?[...L.slice(0,An.maxValidationErrors),Du]:L,ruleNames:new Set(Oe(M).map((F)=>F.toLowerCase()))}}function Oe(M){let L=or(M)?M.rules:void 0;return(Array.isArray(L)?L:[]).flatMap((F)=>{let q=or(F)?F.name:void 0;return typeof q==="string"?[q]:[]})}function Fy(M,L){return[...typeof M.name==="string"&&u.test(M.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof M.version==="string"&&M.version!==""?[]:[e(["version"],"required non-empty string")],...zy(M.allowed_commands),...By(M.rules,L),...jy(M.tests),...Vy(M),...Ky(M)]}function zy(M){if(!Array.isArray(M))return[e(["allowed_commands"],"required array")];let L=new Set;return[...M.flatMap((F,q)=>typeof F==="string"&&w.test(F)?[]:[e(["allowed_commands",q],"must match command pattern")]),...M.flatMap((F,q)=>{if(typeof F!=="string"||!w.test(F))return[];if(L.has(F))return[Jt(["allowed_commands",q],`duplicate command "${F}"`)];return L.add(F),[]})]}function By(M,L){if(!Array.isArray(M))return[e(["rules"],"required array")];return[...M.flatMap((F,q)=>{if(!or(F))return[e(["rules",q],"must be an object")];return L?Uy(F,["rules",q]):$y(F,["rules",q])}),...Ie(M)]}function $y(M,L){return[...Fu(M.name,L),...zu(M.command,L),...M.subcommand===void 0||typeof M.subcommand==="string"&&w.test(M.subcommand)?[]:[e([...L,"subcommand"],"must match command pattern")],...Ti(M.block_args,[...L,"block_args"],"required non-empty array",!1),...Bu(M.reason,L),...$u(M.intent,L)]}function Uy(M,L){return[...Fu(M.name,L),...zu(M.command,L),...Bu(M.reason,L),...$u(M.intent,L),...Hy(M.match,[...L,"match"]),...M.subcommand===void 0?[]:[e([...L,"subcommand"],"not supported in rulebook_version 2")],...M.block_args===void 0?[]:[e([...L,"block_args"],"not supported in rulebook_version 2")]]}function Fu(M,L){if(typeof M!=="string")return[e([...L,"name"],"required string")];return u.test(M)?[]:[e([...L,"name"],"must match rule name pattern")]}function zu(M,L){return typeof M==="string"&&w.test(M)?[]:[e([...L,"command"],"required string matching command pattern")]}function Bu(M,L){return typeof M==="string"&&M!==""&&M.length<=P?[]:[e([...L,"reason"],Ly)]}function $u(M,L){return M===void 0||Re(M)?[]:[e([...L,"intent"],ke)]}function Hy(M,L){if(!or(M))return[e(L,"required object")];return[...Ti(M.command_path,[...L,"command_path"],Wy,!1),...M.any_args===void 0?[]:Ti(M.any_args,[...L,"any_args"],Gu,!0),...M.exclude_args===void 0?[]:Ti(M.exclude_args,[...L,"exclude_args"],Gu,!0)]}function Ti(M,L,F,q){if(!Array.isArray(M))return[e(L,F)];let ne=M.flatMap((re,ue)=>{if(typeof re!=="string")return[e([...L,ue],"must be a non-empty string")];return re===""?[Jt([...L,ue],"must be a non-empty string")]:[]});if(M.some((re)=>typeof re!=="string"))return ne;return[...ne,...M.length===0?[Jt(L,F)]:[],...q&&new Set(M).size!==M.length?[Jt(L,"must not contain duplicate values")]:[]]}function jy(M){if(M===void 0)return[];if(!Array.isArray(M))return[e(["tests"],"must be an array if provided")];return M.flatMap((L,F)=>{if(!or(L))return[e(["tests",F],"must be an object")];return[...typeof L.command==="string"&&L.command.trim()!==""?[]:[e(["tests",F,"command"],"required non-empty string")],...L.expect==="blocked"||L.expect==="allowed"?[]:[e(["tests",F,"expect"],'must be "blocked" or "allowed"')],...L.rule===void 0||typeof L.rule==="string"?[]:[e(["tests",F,"rule"],"must be a string if provided")],...L.expect==="blocked"&&typeof L.rule!=="string"?[Jt(["tests",F,"rule"],"required string for blocked fixtures")]:[]]})}function Vy(M){if(!Array.isArray(M.tests))return[];let L=new Set(Oe(M));return[...new Set(M.tests.flatMap((F)=>or(F)&&F.expect==="blocked"&&typeof F.rule==="string"?[F.rule]:[]))].filter((F)=>!L.has(F)).map((F)=>Jt(["tests"],`blocked fixture references unknown rule "${F}"`))}function Ky(M){if(!Array.isArray(M.allowed_commands)||!Array.isArray(M.rules))return[];let L=new Set(M.allowed_commands.filter((F)=>typeof F==="string"));return M.rules.flatMap((F,q)=>{let ne=or(F)?F.command:void 0;if(typeof ne!=="string"||L.has(ne))return[];return[Jt(["rules",q,"command"],`"${ne}" must be listed in allowed_commands`)]})}function or(M){return!!M&&typeof M==="object"&&!Array.isArray(M)}function X(M,L){let F=Z(M,L),q;try{q=vu(F.userConfigTarget,F.projectConfigTarget)}catch(pt){if(pt instanceof o)return nb(F,pt.message);throw pt}let ne=m(F.userConfigTarget),re=q?{config:null,errors:[]}:m(F.projectConfigTarget),ue=Hu(F.userConfigPath,ne.errors),Se=Hu(F.projectConfigPath,re.errors),ve=new Set,He=ne.config?_a(ne.config,xr(F.userConfigPath),"user",F.userScope,ve):ju(),dt=re.config?_a(re.config,xr(F.projectConfigPath),"project",F.projectScope,ve):ju(),mt=ne.config?.overrides??{},ft=re.config?.overrides??{};return{rules:[...Uu(He.rules,mt),...Uu(dt.rules,ft)],transparent_wrappers:eb(ne.config,re.config),rulebooks:[...He.rulebooks,...dt.rulebooks],errors:[...ue,...Se,...He.errors,...dt.errors],warnings:[...He.warnings,...dt.warnings,...He.canValidateOverrides?wa(mt,He.knownRuleIds,F.userConfigPath):[],...He.canValidateOverrides?tb(ft,He.knownRuleIds,F.projectConfigPath):[],...dt.canValidateOverrides?wa(ft,dt.knownRuleIds,F.projectConfigPath):[]],userConfig:ne.config??void 0,projectConfig:re.config??void 0,...F}}function H(M,L){let F=qy(M,L);if(!F)return[];return[...F.scope.errors,...F.scope.warnings,...Yy(F.config,F.scope,M)]}function qy(M,L){let F=L??v(xr(xr(M)),"rules policy"),q=m(i(F,M)).config;if(!q)return null;return{config:q,scope:_a(q,xr(M),"project",F)}}function Yy(M,L,F){return L.canValidateOverrides?wa(M.overrides??{},L.knownRuleIds,F):[]}function _a(M,L,F,q=v(xr(xr(L)),F==="user"?"user policy":"project policy"),ne=new Set){let re=[],ue=[],Se=M.rules.flatMap((He)=>{let dt=Xy(He,L,q);if(dt.errors.length>0||!dt.rulebook)return re.push(...dt.errors),[];let mt=dt.rulebook;if(ne.has(mt.name))return ue.push(`duplicate active rulebook name "${mt.name}" for ${He}; 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 ne.add(mt.name),[{rules:Zy(mt),rulebook:{source:F,spec:He,name:mt.name,version:mt.version,rules:mt.rules.map((ft)=>`${mt.name}/${ft.name}`)}}]}),ve=Se.flatMap((He)=>He.rules);return{rules:ve,rulebooks:Se.map((He)=>He.rulebook),knownRuleIds:new Set(ve.map((He)=>He.name)),errors:re,warnings:ue,canValidateOverrides:re.length===0}}function Zy(M){if(M.rulebook_version===2)return M.rules.map((L)=>({name:`${M.name}/${L.name}`,command:L.command,block_args:[],match:L.match,reason:L.reason,intent:L.intent}));return M.rules.map((L)=>({...L,name:`${M.name}/${L.name}`,match:void 0}))}function Xy(M,L,F){let q=De(M),ne=N(L,q),re=Qy(ne,F);if("error"in re)return{rulebook:null,errors:[re.error]};if(re.content===null)return{rulebook:null,errors:[`missing rulebook file ${ne} for ${M}; ${Jy(M)}`]};let ue=be(re.content);if("problem"in ue)return{rulebook:null,errors:[`invalid rulebook ${ne}: ${ue.problem}; fix that file`]};if(ue.rulebook.name!==q)return{rulebook:null,errors:[`rulebook name "${ue.rulebook.name}" in ${ne} must match source "${M}"; fix that file`]};return{rulebook:ue.rulebook,errors:[]}}function De(M){return S(M)?D(M).name:M}function Jy(M){return S(M)?`run ${ku} to vendor ${M}`:"create that file or remove that source from the rules config"}function Qy(M,L){try{return{content:r(i(L,M))}}catch(F){if(F instanceof o)return{error:F.message};throw F}}function be(M){let L;try{L=JSON.parse(M)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:ce(L)}}catch(F){return{problem:F instanceof Error?F.message:"invalid rulebook"}}}function eb(M,L){return[...new Set([...M?.transparent_wrappers??[],...L?.transparent_wrappers??[]])]}function Uu(M,L){return M.flatMap((F)=>{let q=L[F.name];if(q==="off")return[];if(q&&typeof q==="object")return[{...F,intent:q.intent??F.intent,reason:q.reason}];return[F]})}function wa(M,L,F){return Object.keys(M).filter((q)=>!L.has(q)).map((q)=>`unknown override key "${q}" in ${F}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function tb(M,L,F){return Object.keys(M).filter((q)=>L.has(q)).map((q)=>`project override cannot target user-scoped rule "${q}" in ${F}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function Hu(M,L){return L.map((F)=>F.startsWith("Unable to access ")?F:`${M}: ${F}`)}function nb(M,L){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[L],warnings:[],userConfigPath:M.userConfigPath,projectConfigPath:M.projectConfigPath}}function ju(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as mb,readFileSync as pb}from"node:fs";var Vu=[{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, with or without --.",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"}],Pa=new Set(Vu.map((M)=>M.id)),W=Vu,rb=new Map(W.map((M)=>[M.id,M.intent]));function Et(M,L){return{id:M,reason:L,intent:rb.get(M)??"manual_only"}}var Aa=[{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"}],Ii={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},ob=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],ib=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Ta=[{id:"secret.home.ssh",category:"Home path",label:"~/.ssh",description:"Blocks home SSH configuration and key paths.",suffixParts:[".ssh"]},{id:"secret.home.aws",category:"Home path",label:"~/.aws",description:"Blocks home AWS credential and config paths.",suffixParts:[".aws"]},{id:"secret.home.gcp",category:"Home path",label:"~/.gcp",description:"Blocks home GCP credential paths.",suffixParts:[".gcp"]},{id:"secret.home.gcloud-config",category:"Home path",label:"~/.config/gcloud",description:"Blocks home Google Cloud SDK credential paths.",suffixParts:[".config","gcloud"]},{id:"secret.home.kube-config",category:"Home path",label:"~/.kube/config",description:"Blocks home Kubernetes config files.",suffixParts:[".kube","config"]},{id:"secret.home.docker-config",category:"Home path",label:"~/.docker/config.json",description:"Blocks home Docker credential config files.",suffixParts:[".docker","config.json"]},...ib.flatMap((M)=>ob.map((L)=>({id:["secret.home",M.idSlug,L.slice(1)].join("."),category:"Home path",label:[M.label,L].join(""),description:["Blocks home ",M.label,L," credential backup files."].join(""),suffixParts:[...M.directoryParts,[M.basename,L].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 ki=[{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","~/.config/opencode/config.json","/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"]}],Ku=[{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"}],sb=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Ia=Ku.map((M)=>({id:`secret.variant.${M.slug}.separator`,category:"Variant",label:`${M.label}-* / ${M.label}_*`,description:`Blocks ${M.label} variants with dash or underscore suffixes.`,prefix:M.prefix})),ka=Ku.flatMap((M)=>sb.map((L)=>({id:`secret.variant.${M.slug}.${L.slice(1)}`,category:"Variant",label:`${M.label}${L}`,description:`Blocks ${M.label}${L} private credential variants.`,prefix:M.prefix,suffix:L}))),Oo={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)$/},Oa=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((M)=>({id:`secret.ext.${M}`,category:"Extension",label:`.${M}`,description:`Blocks files with the .${M} extension.`,extension:M})),Ma=[{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?$/}],Xe=[...Aa,Ii,...Ta,...Ia,...ka,Oo,...Oa,...Ma,...ki].map((M)=>({id:M.id,category:M.category,label:M.label,...M.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in M?{paths:M.paths}:{description:M.description}})),Oi=new Set(ki.flatMap((M)=>M.category==="Coding CLI config"?[M.id]:[])),Da=new Set(Xe.map((M)=>M.id));import{isAbsolute as Na,join as ab,normalize as lb,sep as Mi}from"node:path";var Di=process.platform==="win32",qu=/[*?]/;function La(M){let L=M.trim(),F=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(Di?L.replaceAll("\\","/"):L);if(!F)return null;let q=F[1]??"",ne=F[2]??"";if(qu.test(q)||ne==="."||ne==="..")return null;return{root:q||"/",name:ne}}function Mo(M,L){if(M==="~")return L;if(M.startsWith("~/"))return`${L}${M.slice(1)}`;return M}function Wa(M,L){if(typeof M!=="string"||M.trim()==="")return"must be a non-empty path string";let F=Mo(M.trim(),L);if(!Na(F))return"must be an absolute path or start with ~/";return Do(F,L)}function Ga(M,L){let F=Yu(M,L);if(F===null)return"must be a non-empty path string";if(!Na(F))return null;if(Do(F,L)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var cb="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",ub="cannot cover the guard's own configuration";function Yu(M,L){if(typeof M!=="string"||M.trim()==="")return null;let F=M.trim(),q=Di?F.replaceAll("\\","/"):F;return Mo(q.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),L)}function Fa(M,L){let F=Yu(M,L);if(F===null)return"must be a non-empty path string";let q=La(F)?.root??F;if(qu.test(q))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Na(q))return null;if(Do(q,L)!==null)return cb;return db(q,L)?ub:null}function db(M,L){let F=Ni(M),q=Ni(ab(L,".cc-safety-net"));return F===q||F.startsWith(`${q}${Mi}`)}function Do(M,L){let F=Ni(M),q=Ni(L);if(F===q)return"cannot be the home directory";let ne=F.endsWith(Mi)?F:`${F}${Mi}`;if(q.startsWith(ne))return"cannot contain the home directory";return null}function Ni(M){let L=lb(M);if(Di)L=L.replace(/\//g,"\\").toLowerCase();if(L.length>(Di?3:1)&&L.endsWith(Mi))L=L.slice(0,-1);return L}var Zu=30,Li=1,Wi=365;function Xu(M){if(typeof M!=="number"||!Number.isInteger(M))return 30;if(M<1)return 1;return M>365?365:M}var Ju=new Set(W.filter((M)=>M.catastrophic).map((M)=>M.id));function _t(M,L){if(!M)return null;if(Ju.has(M.id))return M;if(L?.destructiveCommandProtectionEnabled===!1)return null;let F=L?.effectiveDestructiveCommandRules[M.id];return F&&!F.enabled?null:M}function Yt(M,L,F){if(Ju.has(L))return!0;if(M?.destructiveCommandProtectionEnabled===!1)return!1;return M?.effectiveDestructiveCommandRules[L]?.enabled??F}function B(M,L){return Object.freeze(Object.fromEntries(W.map((F)=>{let q=F.activationCapability?L[F.activationCapability]:void 0,ne=q?.enabled??!0,re=M.destructiveCommandRuleOverrides[F.id],ue=F.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...re?{override:re}:{}}:M.destructiveCommandProtectionEnabled?re?{enabled:re==="on",inheritedEnabled:ne,changesInherited:re==="on"!==ne,source:"rule_override",...F.activationCapability?{activationCapability:F.activationCapability}:{},override:re}:{enabled:ne,inheritedEnabled:ne,changesInherited:!1,source:q?.source??"built_in_default",...F.activationCapability?{activationCapability:F.activationCapability}:{}}:{enabled:!1,inheritedEnabled:ne,changesInherited:!1,source:"master_disabled",...F.activationCapability?{activationCapability:F.activationCapability}:{},...re?{override:re}:{}};return[F.id,Object.freeze(ue)]})))}function Qu(M,L){return Object.freeze({...M,effectiveDestructiveCommandRules:B(M,L)})}var ed={standard:0,strict:1,paranoid:2};function Q(M,L,F=!1,q=M.safety.level){let ne=fb(M,L,q),re=new Set(F?ne.map((dt)=>dt.field):[]),ue=(dt,mt)=>re.has(dt)?void 0:mt,Se=(dt,mt)=>Object.fromEntries(Object.entries(mt??{}).filter(([ft])=>!re.has(`${dt}.${ft}`))),ve=(dt,mt)=>mt?.filter((ft)=>!re.has(`${dt}.${ft}`));return{policy:{version:1,safety:{level:ue("safety.level",L.safety?.level)??M.safety.level,overrides:{...M.safety.overrides,...Se("safety.overrides",L.safety?.overrides)}},workflow:{worktree_mode:ue("workflow.worktree_mode",L.workflow?.worktree_mode)??M.workflow.worktree_mode},destructive_command_protection:{enabled:ue("destructive_command_protection.enabled",L.destructive_command_protection?.enabled)??M.destructive_command_protection.enabled,overrides:{...M.destructive_command_protection.overrides,...Se("destructive_command_protection.overrides",L.destructive_command_protection?.overrides)},allow_paths:za(M.destructive_command_protection.allow_paths,ve("destructive_command_protection.allow_paths",L.destructive_command_protection?.allow_paths))},secret_protection:{enabled:ue("secret_protection.enabled",L.secret_protection?.enabled)??M.secret_protection.enabled,overrides:{...M.secret_protection.overrides,...Se("secret_protection.overrides",L.secret_protection?.overrides)},deny_paths:za(M.secret_protection.deny_paths,L.secret_protection?.deny_paths),allow_paths:za(M.secret_protection.allow_paths,ve("secret_protection.allow_paths",L.secret_protection?.allow_paths))},audit:M.audit},weakenings:ne.map((dt)=>dt.message)}}function za(M,L){return[...new Set([...M,...L??[]])]}function fb(M,L,F){let q=L.safety?.level,ne=Ci[F];return[...q&&ed[q]<ed[M.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${M.safety.level} -> ${q}`}]:[],...Hr.flatMap((re)=>L.safety?.overrides?.[re]===!1&&(M.safety.overrides[re]??ne[re])?[{field:`safety.overrides.${re}`,message:`project policy disables ${re}`}]:[]),...L.workflow?.worktree_mode===!0&&!M.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...L.destructive_command_protection?.enabled===!1&&M.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...L.secret_protection?.enabled===!1&&M.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...td("destructive_command_protection.overrides",L.destructive_command_protection?.overrides,(re)=>M.destructive_command_protection.enabled&&M.destructive_command_protection.overrides[re]!=="off"),...td("secret_protection.overrides",L.secret_protection?.overrides,(re)=>M.secret_protection.enabled&&(M.secret_protection.overrides[re]==="on"?!0:M.secret_protection.overrides[re]!=="off"&&!Oi.has(re))),...M.destructive_command_protection.enabled?nd(M.destructive_command_protection.allow_paths,L.destructive_command_protection?.allow_paths).map((re)=>({field:`destructive_command_protection.allow_paths.${re}`,message:`project policy adds destructive allow path: ${re}`})):[],...M.secret_protection.enabled?nd(M.secret_protection.allow_paths,L.secret_protection?.allow_paths).map((re)=>({field:`secret_protection.allow_paths.${re}`,message:`project policy adds secret allow path: ${re}`})):[]]}function td(M,L,F){return Object.entries(L??{}).flatMap(([q,ne])=>ne==="off"&&F(q)?[{field:`${M}.${q}`,message:`project policy disables rule ${q}`}]:[])}function nd(M,L){return(L??[]).filter((F)=>!M.includes(F))}var Ua=new Set(["standard","strict","paranoid"]),ee={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:Zu}};function sd(M,L){let F=Cb(d(M,L),M.home),q=Le(b(L.cwd),M.home),ne=le(q.parsed,M.home),re=x(n.projectTightenOnly,M.env),ue=F.gui??ee,Se=Object.keys(ne.policy).length>0?Q(ue,ne.policy,re,gu(ue.safety.level,M.env)):void 0,ve=[...F.errors,...q.errors,...ne.diagnostics],He=(F.fallback==="defaults"&&Se?"salvaged":F.fallback)??(F.gui?void 0:q.fallback)??(ve.length>0?"salvaged":void 0),dt=ne.policy.safety?.level&&Se?.policy.safety.level===ne.policy.safety.level?"project":F.levelPresent?"user":"default";return{...Se?$a(Se.policy):F.policy,errors:ve,...He?{fallback:He}:{},...q.exists?{policyScopes:{levelScope:dt,weakenings:Se?.weakenings??[],weakeningsIgnored:re}}:{}}}var gb="project policy audit settings are ignored; audit is user scope only";function le(M,L){if(!Sn(M))return{policy:{},diagnostics:[]};let F=Sn(M.safety)?M.safety:{},q=Sn(M.workflow)?M.workflow:{},ne=Sn(M.destructive_command_protection)?M.destructive_command_protection:{},re=Sn(M.secret_protection)?M.secret_protection:{},ue={...Ua.has(F.level)?{level:F.level}:{},...Sn(F.overrides)?rd({overrides:ad(F.overrides,Hr,["safety","overrides"],Rr)}):{}},Se={...typeof ne.enabled==="boolean"?{enabled:ne.enabled}:{},...ne.overrides!==void 0?{overrides:Gi(ne.overrides,Pa,cd,Rr)}:{},...ne.allow_paths!==void 0?{allow_paths:qr(ne.allow_paths,Wa,L,["destructive_command_protection","allow_paths"],Rr)}:{}},ve={...typeof re.enabled==="boolean"?{enabled:re.enabled}:{},...re.overrides!==void 0?{overrides:Gi(re.overrides,Da,ud,Rr)}:{},...re.deny_paths!==void 0?{deny_paths:qr(re.deny_paths,Ga,L,["secret_protection","deny_paths"],Rr)}:{},...re.allow_paths!==void 0?{allow_paths:qr(re.allow_paths,Fa,L,["secret_protection","allow_paths"],Rr)}:{}};return{policy:rd({safety:ue,workflow:typeof q.worktree_mode==="boolean"?{worktree_mode:q.worktree_mode}:{},destructive_command_protection:Se,secret_protection:ve}),diagnostics:M.audit===void 0?[]:[gb]}}function ad(M,L,F,q){return Object.fromEntries(L.flatMap((ne)=>{let re=M[ne];if(typeof re==="boolean")return[[ne,re]];if(re!==void 0)q(e([...F,ne],Ha));return[]}))}function rd(M){return Object.fromEntries(Object.entries(M).flatMap((L)=>Object.keys(L[1]).length>0?[L]:[]))}var Rr=()=>{return},Ha="must be a boolean",ja="must be an object if provided",ld=`must be an integer between ${Li} and ${Wi}`,cd={path:["destructive_command_protection","overrides"],label:"destructive command"},ud={path:["secret_protection","overrides"],label:"secret protection"},Qe=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function et(M,L){let F=[];return{policy:dd(M,L,(ne)=>{F.push(ne)}),issues:F}}function C(M,L){return dd(M,L,Rr)}function dd(M,L,F){if(!Sn(M))return F(e([],"Config must be an object")),z();if(M.version!==1)F(e(["version"],"must be 1"));let q=Kr(M.safety,["safety"],["level","overrides"],F),ne=Kr(q.overrides,["safety","overrides"],Hr,F),re=Kr(M.workflow,["workflow"],["worktree_mode"],F),ue=Kr(M.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],F),Se=Kr(M.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],F),ve=Kr(M.audit,["audit"],["retention_days"],F);return fd(M,Qe,[],F),{version:1,safety:{level:hb(q.level,F),overrides:ad(ne,Hr,["safety","overrides"],F)},workflow:{worktree_mode:Ba(re.worktree_mode,["workflow","worktree_mode"],!1,F)},destructive_command_protection:{enabled:Ba(ue.enabled,["destructive_command_protection","enabled"],!0,F),overrides:Gi(ue.overrides,Pa,cd,F),allow_paths:qr(ue.allow_paths,Wa,L,["destructive_command_protection","allow_paths"],F)},secret_protection:{enabled:Ba(Se.enabled,["secret_protection","enabled"],!0,F),overrides:Gi(Se.overrides,Da,ud,F),deny_paths:qr(Se.deny_paths,Ga,L,["secret_protection","deny_paths"],F),allow_paths:qr(Se.allow_paths,Fa,L,["secret_protection","allow_paths"],F)},audit:{retention_days:yb(ve.retention_days,F)}}}function Kr(M,L,F,q){if(M===void 0)return{};if(!Sn(M))return q(e(L,ja)),{};return fd(M,F,L,q),M}function fd(M,L,F,q){for(let ne of Object.keys(M).filter((re)=>!L.includes(re)))q({path:F,message:ne,kind:"unknownKeys"})}function hb(M,L){if(M===void 0)return"standard";if(Ua.has(M))return M;return L(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Ba(M,L,F,q){if(typeof M==="boolean")return M;if(M!==void 0)q(e(L,Ha));return F}function yb(M,L){if(!(M===void 0||typeof M==="number"&&Number.isInteger(M)&&M>=Li&&M<=Wi))L(e(["audit","retention_days"],ld));return Xu(M)}function Gi(M,L,F,q){if(M===void 0)return{};if(!Sn(M))return q(e(F.path,ja)),{};return Object.fromEntries(Object.entries(M).flatMap(([ne,re])=>{if(!L.has(ne))return q({path:[...F.path,ne],message:`unknown ${F.label} rule id "${ne}"`,kind:"key"}),[];if(re==="on"||re==="off")return[[ne,re]];return q(e([...F.path,ne],'must be "on" or "off"')),[]}))}function qr(M,L,F,q,ne){if(M===void 0)return[];if(!Array.isArray(M))return ne(e(q,"must be an array of paths")),[];return M.flatMap((re,ue)=>{let Se=L(re,F);if(Se===null)return[re];return ne(typeof re==="string"?Jt([...q,ue],Se):e([...q,ue],Se)),[]})}function Sn(M){return!!M&&typeof M==="object"&&!Array.isArray(M)}function z(){return structuredClone(ee)}function Ne(M,L){let F=T({safety:Me(M.safety)},L),q=B({destructiveCommandProtectionEnabled:M.destructive_command_protection.enabled,destructiveCommandRuleOverrides:M.destructive_command_protection.overrides},F.capabilities),ne=Object.values(q),re=ne.filter((ue)=>ue.source!=="catastrophic");return{selectedPreset:M.safety.level,effectiveLevel:F.effectiveLevel,capabilities:F.capabilities,rules:q,counts:{enabled:re.filter((ue)=>ue.enabled).length,disabled:re.filter((ue)=>!ue.enabled).length,effectiveCustomizations:ne.filter((ue)=>ue.changesInherited).length}}}function Le(M,L){if(!mb(M))return{exists:!1,policy:z(),errors:[]};try{let F=pb(M,"utf-8");if(!F.trim())return{exists:!0,policy:z(),errors:[`${M}: Config file is empty`],fallback:"defaults"};let q=JSON.parse(F),ne=et(q,L);if(ne.issues.length===0)return{exists:!0,parsed:q,policy:ne.policy,errors:[]};return{exists:!0,parsed:q,policy:ne.policy,errors:ne.issues.map((re)=>`${M}: ${Sb(re)}`),fallback:Sn(q)?"salvaged":"defaults"}}catch(F){let q=F instanceof Error?F.message:String(F);return{exists:!0,policy:z(),errors:[`${M}: ${F instanceof SyntaxError?"Invalid JSON":q}`],fallback:"defaults"}}}var bb=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[ja,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[Ha,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[ld,`not an integer between ${Li} and ${Wi}`]]);function Sb(M){let L=Ra(M.path);if(M.kind==="unknownKeys")return`${L===""?"":`${L}.`}${M.message}: unknown field`;if(M.kind==="key")return`${L}: unknown rule id`;let F=bb.get(M.message)??M.message;return L===""?F:`${L}: ${F}`}function Cb(M,L){let F=Le(M,L);if(!F.exists){let q=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!Sn(q))return{policy:id(),errors:[]};let ne=C(q,L);return{policy:$a(ne),gui:ne,errors:[],levelPresent:od(q)}}if(F.parsed===void 0)return{policy:id(),errors:F.errors,...F.fallback?{fallback:F.fallback}:{}};return{policy:$a(F.policy),gui:F.policy,errors:F.errors,...F.fallback?{fallback:F.fallback}:{},levelPresent:od(F.parsed)}}function od(M){let L=Sn(M)&&Sn(M.safety)?M.safety:{};return Ua.has(L.level)}function Fe(M){let L=Object.entries(M),F=new Set(L.flatMap(([q,ne])=>ne==="on"?[q]:[]));return[...new Set([...[...Oi].filter((q)=>!F.has(q)),...L.flatMap(([q,ne])=>ne==="off"?[q]:[])])]}function id(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Fe({}),denyPaths:[],allowPaths:[]}}}function $a(M){return{safety:Me(M.safety),worktreeMode:M.workflow.worktree_mode,destructiveCommandProtectionEnabled:M.destructive_command_protection.enabled,destructiveCommandRuleOverrides:M.destructive_command_protection.overrides,destructiveCommandAllowPaths:M.destructive_command_protection.allow_paths,secretProtection:{enabled:M.secret_protection.enabled,disabledRules:Fe(M.secret_protection.overrides),denyPaths:M.secret_protection.deny_paths,allowPaths:M.secret_protection.allow_paths}}}function Me(M){let L={...M.overrides.fail_closed!==void 0?{failClosed:M.overrides.fail_closed}:{},...M.overrides.paranoid_rm!==void 0?{paranoidRm:M.overrides.paranoid_rm}:{},...M.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:M.overrides.paranoid_interpreters}:{}};return{level:M.level,...Object.keys(L).length>0?{overrides:L}:{}}}function E(M,L){let F=X(M,L),q=sd(M,L),ne={rules:F.rules,transparentWrappers:F.transparent_wrappers,safety:q.safety,worktreeMode:q.worktreeMode,destructiveCommandProtectionEnabled:q.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:q.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:q.destructiveCommandAllowPaths,secretProtection:{enabled:q.secretProtection.enabled??!0,disabledRules:q.secretProtection.disabledRules??[],denyPaths:q.secretProtection.denyPaths,allowPaths:q.secretProtection.allowPaths??[]}},re={...F.userConfig?.overrides,...F.projectConfig?.overrides},ue=Object.freeze(Object.fromEntries(ne.rules.map((Se)=>{let ve=F.rulebooks.find((dt)=>dt.rules.includes(Se.name)),He=re[Se.name];return[Se.name,Object.freeze({id:Se.name,...ve?{rulebook:Object.freeze({name:ve.name,version:ve.version}),...Rb(ve.spec)?{source:ve.spec}:{}}:{},...He&&typeof He==="object"?{override:Object.freeze({type:"reason",reason:He.reason})}:{}})]})));return Te(ne,vb(F,q),ue,q.policyScopes)}function $e(M){if(M.state==="ready")return{state:M.state};return{state:M.state,reason:M.reason}}function vb(M,L){let F=xb(L);if(M.errors.length===0&&M.warnings.length===0&&!F)return;return{diagnostics:[...M.errors,...M.warnings,...L.errors],reason:_b(M.errors.length>0?Eb(M.errors):void 0,M.warnings.length>0?Ka(M.warnings.join("; ")):void 0,F)}}function Eb(M){return`${Ka(M.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function xb(M){if(M.errors.length===0)return;let L=M.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${M.errors.join("; ")}. Enforcing ${L}; the invalid values are not active. Fix the policy file manually`}function Rb(M){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(M)}function Te(M,L,F=Object.freeze({}),q){let ne=Va(structuredClone(M)),re=q?{policyScopes:Va(structuredClone(q))}:{};if(!L)return Object.freeze({state:"ready",policy:ne,diagnostics:Object.freeze([]),ruleMetadata:F,...re});return Object.freeze({state:"degraded",policy:ne,diagnostics:Object.freeze([...L.diagnostics]),reason:L.reason,ruleMetadata:F,...re})}function Va(M){if(typeof M!=="object"||M===null)return M;for(let L of Object.values(M))Va(L);return Object.freeze(M)}function _b(...M){return Ka(M.filter((L)=>!!L).join("; "))}function Ka(M){return/[.!?]$/.test(M)?M:`${M}.`}function je(M){let L=M.effectiveCapabilities,F=M.strict??L.fail_closed.enabled,q=M.paranoidRm??L.paranoid_rm.enabled,ne=M.paranoidInterpreters??L.paranoid_interpreters.enabled,re={fail_closed:qa(L.fail_closed,M.strict,"strict"),paranoid_rm:qa(L.paranoid_rm,M.paranoidRm,"paranoidRm"),paranoid_interpreters:qa(L.paranoid_interpreters,M.paranoidInterpreters,"paranoidInterpreters")};return{policy:Qu(M.policySnapshot.policy,re),effectiveCapabilities:re,effectiveLevel:da({failClosed:F,paranoidRm:q,paranoidInterpreters:ne}),strict:F,paranoidRm:q,paranoidInterpreters:ne,worktreeMode:M.worktreeMode??!1}}function qa(M,L,F){if(L===void 0||L===M.enabled)return M;return{enabled:L,source:"capability_override",sources:[...M.sources,`analysis options.${F}`]}}import{dirname as O_,isAbsolute as M_,join as D_,parse as N_,resolve as L_,sep as W_}from"node:path";function No(M,L){if(M!=="powershell")return L[0]?.provenance==="command-substitution";let F=L[0]?.text==="&"||L[0]?.text==="."?1:0,q=L[F]?.provenance;return q!==void 0&&q!=="literal"}var wb=/^[A-Za-z_][A-Za-z0-9_]*=/;function Fi(M,L){return M?.provenance==="literal"&&!M.quoted&&M.raw===L&&M.text===L}function Lo(M){let L=Fi(M.words[0],"time")?1:0,F=L===1&&Fi(M.words[L],"-p")?L+1:L,q=L===1&&Fi(M.words[F],"--")?F+1:F,ne=Fi(M.words[q],"!")?q+1:q,re=M.words.slice(ne).find((ue)=>!wb.test(ue.text));return re?.provenance==="literal"?re.text:void 0}var ir=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function zi(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Pb(M){return Object.freeze({...M,span:Object.freeze(M.span),words:Object.freeze(M.words),redirections:Object.freeze(M.redirections.map((L)=>Object.freeze({...L,span:Object.freeze(L.span),...L.heredoc?{heredoc:Object.freeze({...L.heredoc,bodySpan:Object.freeze(L.heredoc.bodySpan),terminatorSpan:Object.freeze(L.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(M.nested.map((L)=>cn(L)))})}function Bi(M,L,F){M.push(F),L.reset()}function $i(M){let L=[];return{parts:L,push:(F,q,ne)=>{if(q<=F)return;L.push({raw:M.slice(F,q),span:{start:F,end:q},provenance:ne})}}}function Ya(M){let L=M.parts??[{raw:M.raw,span:M.span,provenance:M.provenance}];return Object.freeze({kind:"word",...M,span:Object.freeze(M.span),parts:Object.freeze(L.map((F)=>Object.freeze({...F,span:Object.freeze(F.span)})))})}function Yr(M,L,F,q,ne,re,ue){return Ya({text:q,raw:M.slice(L,F),span:{start:L,end:F},provenance:ne,quoted:re,...ue?{parts:ue}:{}})}function cn(M){return Object.freeze({...M,span:Object.freeze(M.span),issues:Object.freeze(M.issues.map((L)=>Object.freeze({...L}))),nodes:Object.freeze(M.nodes.map((L)=>{if(L.kind==="command")return Pb(L);if(L.kind==="group"||L.kind==="function")return Object.freeze({...L,span:Object.freeze(L.span),body:cn(L.body)});return Object.freeze({...L,span:Object.freeze(L.span)})}))})}function Za(M,L,F){if(L>=F||pd(M[L]??""))return null;let q="",ne=!1,re=!1,ue=L;while(ue<F&&!pd(M[ue]??"")){let Se=M[ue]??"";if(Se==="'"){ne=!0;let ve=md(M,ue+1,F,"'");q+=ve.text,re||=!ve.closed,ue=ve.next;continue}if(Se==='"'){ne=!0;let ve=md(M,ue+1,F,'"');q+=ve.text,re||=!ve.closed,ue=ve.next;continue}if(Se==="\\"){ne=!0;let ve=M[ue+1];if(!ve||ve===`
|
|
7
|
+
`||ve==="\r"){re=!0;break}q+=ve,ue+=2;continue}if(Se==="`"||M.startsWith("$(",ue)||M.startsWith("${",ue)||M.startsWith("<(",ue)||M.startsWith(">(",ue))re=!0;q+=Se,ue++}return{delimiter:q,quoted:ne,next:ue,ambiguous:re}}function Xa(M,L,F,q){let ne=[],re=L;for(let ue of q){let Se=re,ve=!1;while(re<F){let He=Ab(M,re,F);if((ue.stripTabs?He.text.replace(/^\t+/,""):He.text)===ue.delimiter){ue.attach({body:ue.stripTabs?Tb(M.slice(Se,re)):M.slice(Se,re),delimiter:ue.delimiter,quotedDelimiter:ue.quotedDelimiter,bodySpan:{start:Se,end:re},terminatorSpan:{start:re,end:He.contentEnd}}),re=He.next,ve=!0;break}if(He.next<=re)break;re=He.next}if(ve)continue;return ne.push({code:"unterminated-heredoc",message:`heredoc delimiter ${ue.delimiter} was not found`}),{next:F,issues:ne,terminated:!1}}return{next:re,issues:ne,terminated:!0}}function md(M,L,F,q){let ne="",re=L;while(re<F&&M[re]!==`
|
|
8
|
+
`&&M[re]!=="\r"){let ue=M[re]??"";if(ue===q)return{text:ne,next:re+1,closed:!0};if(q==='"'&&ue==="\\"&&M[re+1]){let Se=M[re+1]??"";ne+=["$","`",'"',"\\"].includes(Se)?Se:`\\${Se}`,re+=2;continue}ne+=ue,re++}return{text:ne,next:re,closed:!1}}function pd(M){return M!=="\r"&&(/[\s;&|<>)]/u.test(M)||M==="`")}function Ab(M,L,F){let q=L;while(q<F&&M[q]!==`
|
|
9
|
+
`)q++;let ne=q>=F?F:q+1;return{text:M.slice(L,q),contentEnd:q,next:ne}}function Tb(M){return M.replace(/(^|\r\n?|\n)\t+/g,"$1")}var bd=new Set(["&&","||","|","|&"]),Ib=new Set(["!","do","elif","else","if","then","until","while"]);function Sd(M,L){let F={start:0,end:M.length};if(M.length>L.maxInputLength)return cn({kind:"program",dialect:"posix",source:M,span:F,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${L.maxInputLength} UTF-16 code units`}],nodes:[]});let q=ji(M,0,M.length,L,{used:0,max:L.maxWords},0);return cn({kind:"program",dialect:"posix",source:M,span:F,status:qi(q.issues,q.limited),issues:q.issues,nodes:q.nodes})}function ji(M,L,F,q,ne,re,ue){let Se=[],ve=[],He=zi(),dt=[],mt=()=>{if(He.words.length===0&&He.redirections.length===0)return;let pt={start:He.start,end:He.end},ht=He.words.map((gt)=>gt.text);Bi(Se,He,{kind:"command",dialect:"posix",source:M.slice(pt.start,pt.end),span:pt,words:He.words,redirections:He.redirections,nested:He.nested,displayText:ve.length>0&&Se.length===0?M.slice(L,F):ht.join(" ")})},ft=L;while(ft<F){let pt=M[ft];if(!pt)break;if(ue&&pt===ue)return mt(),yd(Se,ve),{nodes:Se,issues:ve,next:ft+1,closed:!0,limited:!1,pendingHeredocs:dt};if(Ki(pt)){if(pt===`
|
|
10
|
+
`||pt==="\r"){mt();let At=pt==="\r"&&M[ft+1]===`
|
|
11
|
+
`?ft+2:ft+1,Tt=Se.at(-1);if(Tt?.kind!=="connector"||!bd.has(Tt.operator))Se.push(Object.freeze({kind:"connector",operator:M.slice(ft,At),span:Object.freeze({start:ft,end:At})}));if(dt.length>0){let Ot=Xa(M,At,F,dt.splice(0));ve.push(...Ot.issues),ft=Ot.next;continue}ft=At;continue}ft++;continue}if(pt==="#"){while(ft<F&&M[ft]!==`
|
|
12
|
+
`&&M[ft]!=="\r")ft++;continue}let ht=He.start===-1?Xb(M,ft,F):void 0;if(ht){if(Qa(Se,ve),re>=q.maxDepth)return Zr(Se,ve,ft,"depth-limit",q.maxDepth);if(!Ja(ne))return Zr(Se,ve,ft,"word-limit",q.maxWords);let At=ji(M,ht.braceIndex+1,F,q,ne,re+1,"}"),Tt=At.next,Ot={start:ht.braceIndex+1,end:At.closed?Tt-1:Tt},jt=gd(M,Ot,At);if(Se.push({kind:"function",name:ht.name,span:{start:ft,end:Tt},body:jt}),ve.push(...At.issues),At.pendingHeredocs.length>0||Go(At.nodes))ve.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(dt.push(...At.pendingHeredocs),At.limited)return Hi(Se,ve,At.next);if(!At.closed)ve.push({code:"unclosed-function-body",message:"function body is not closed"});ft=Tt;continue}let gt=Vi(M,ft);if(gt){if(mt(),!Pd(Se.at(-1)))ve.push({code:"unexpected-connector",message:`connector ${gt} has no preceding command`});Se.push(Object.freeze({kind:"connector",operator:gt,span:Object.freeze({start:ft,end:ft+gt.length})})),ft+=gt.length;continue}if(pt===")"){mt(),ve.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),Se.push({kind:"unknown",source:pt,span:{start:ft,end:ft+1}}),ft++;continue}if((pt==="("||pt==="{"&&Gb(M,ft,F))&&He.start===-1){if(Qa(Se,ve),re>=q.maxDepth)return Zr(Se,ve,ft,"depth-limit",q.maxDepth);let At=pt==="("?")":"}",Tt=ji(M,ft+1,F,q,ne,re+1,At),Ot=Tt.next,jt={start:ft+1,end:Tt.closed?Ot-1:Ot},sn=gd(M,jt,Tt);if(Se.push({kind:"group",style:pt==="("?"subshell":"brace",span:{start:ft,end:Ot},body:sn}),ve.push(...Tt.issues),Tt.pendingHeredocs.length>0||Go(Tt.nodes))ve.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(dt.push(...Tt.pendingHeredocs),Tt.limited)return Hi(Se,ve,Tt.next);if(!Tt.closed)ve.push({code:pt==="("?"unclosed-subshell":"unclosed-brace-group",message:`${pt} group is not closed`});ft=Ot;continue}let yt=(pt==="<"||pt===">")&&M[ft+1]!=="("?Db(M,ft):null;if(yt){let At=He.words.at(-1),Tt=At&&At.span.end===ft&&/^[0-9]+$/.test(At.raw)?Number(At.raw):void 0;if(Tt!==void 0)He.words.pop();let Ot=Tt===void 0?ft:At?.span.start??ft;He.start=He.start===-1?ft:He.start;let jt=ft+yt.length;while(jt<F&&/[ \t]/.test(M[jt]??""))jt++;let sn=M[jt],jn=jt>ft+yt.length&&sn==="#",pn=!sn||Ki(sn)||!!Vi(M,jt)||sn===ue||sn===")"||jn||(sn==="<"||sn===">")&&M[jt+1]!=="(",hr=yt==="<<"||yt==="<<-",Gt=hr?Za(M,jt,F):void 0,Mt=Gt?{word:Yr(M,jt,Gt.next,Gt.delimiter,"literal",Gt.quoted),nested:[],issues:[],next:Gt.next,limited:!1}:!pn?el(M,jt,F,q,ne,re):void 0;if(Mt){if(ve.push(...Mt.issues),Mt.limited)return Hi(Se,ve,Mt.next);if(!Ja(ne))return Zr(Se,ve,Mt.next,"word-limit",q.maxWords)}let nn=Mt?.next??ft+yt.length,Kt={kind:"redirection",operator:yt,span:{start:Ot,end:nn},...Tt===void 0?{}:{fd:Tt},...Mt?{target:Mt.word}:{}};if(He.redirections.push(Kt),hr&&!Gt)ve.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if(Gt){if(Gt.ambiguous||Gt.delimiter.length===0)ve.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let qt=He.nested;dt.push({delimiter:Gt.delimiter,quotedDelimiter:Gt.quoted,stripTabs:yt==="<<-",attach:(gn)=>{if(Kt.heredoc=gn,gn.quotedDelimiter)return;qt.push(...Ob(M,gn.bodySpan.start,gn.bodySpan.end,q,ne,re+1))}})}if(!hr&&!Mt)ve.push({code:"missing-redirection-target",message:`redirection ${yt} requires a target word`});if(Mt)He.nested.push(...Mt.nested);He.end=nn,ft=nn;continue}let St=He.start===-1;if(St)Qa(Se,ve);let Ct=el(M,ft,F,q,ne,re);if(ve.push(...Ct.issues),Ct.limited)return Hi(Se,ve,Ct.next);let bt=Bb(He.words)?Vb(M,Ct.word,ne.max-ne.used,q.maxDepth,q.maxInputLength):void 0;if(bt?.limitCode)return Zr(Se,ve,Ct.next,bt.limitCode,bt.limitCode==="word-limit"?q.maxWords:bt.limitCode==="depth-limit"?q.maxDepth:q.maxInputLength);let xt=bt?.words??[Ct.word];for(let At of xt){if(!Ja(ne))return Zr(Se,ve,Ct.next,"word-limit",q.maxWords);He.words.push(At)}if(He.start=He.start===-1?ft:He.start,He.end=Ct.next,He.nested.push(...Ct.nested),St&&Ad(Ct.word))mt();ft=Ct.next>ft?Ct.next:ft+1}return mt(),yd(Se,ve),ve.push(...Jb(dt)),{nodes:Se,issues:ve,next:ft,closed:ue===void 0,limited:!1,pendingHeredocs:[]}}function gd(M,L,F){return{kind:"program",dialect:"posix",source:M.slice(L.start,L.end),span:L,status:qi(F.issues,F.limited),issues:F.issues,nodes:F.nodes}}function el(M,L,F,q,ne,re){let ue="",Se=L,ve=!1,He="literal",dt=[],mt=[],ft=!1;while(Se<F){let pt=M[Se],ht=(pt==="<"||pt===">")&&M[Se+1]==="(";if(!pt||Ki(pt)||(pt===";"||pt==="|"||pt==="&")&&Vi(M,Se)||(pt==="<"||pt===">")&&!ht)break;if(pt===")")break;if(pt==="'"){ve=!0;let yt=M.indexOf("'",Se+1);if(yt===-1||yt>=F){ue+=M.slice(Se+1,F),mt.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),Se=F;break}ue+=M.slice(Se+1,yt),Se=yt+1;continue}if(pt==='"'){ve=!0;let yt=kb(M,Se,F,q,ne,re);if(ue+=yt.text,dt.push(...yt.nested),mt.push(...yt.issues),ft||=yt.limited,He=Wo(He,yt.provenance),Se=yt.next,ft)break;continue}if(M.startsWith("$'",Se)){ve=!0;let yt=Nb(M,Se+2,F);if(ue+=yt.text,mt.push(...yt.issues),!yt.closed)mt.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});Se=yt.next;continue}if(pt==="\\"){let yt=M[Se+1];if(!yt){mt.push({code:"trailing-escape",message:"escape has no following character"}),Se++;break}if(yt===`
|
|
13
|
+
`){Se+=2;continue}ue+=yt,Se+=2;continue}let gt=pt==="$"||pt==="<"||pt===">"||pt==="`"?Yi(M,Se,F,q,ne,re):null;if(gt){let yt=Cd(gt,dt,mt);if(ft||=yt.limited,He=Wo(He,yt.provenance),Se=yt.next,ft)break;continue}if(pt==="$"){let yt=xd(M,Se,F,ue,He);ue=yt.text,He=yt.provenance,Se=yt.next;continue}if(pt==="*"||pt==="?"||pt==="[")He=Wo(He,"glob");ue+=pt,Se++}return{word:Yr(M,L,Se,ue,He,ve,He==="literal"?void 0:Wb(M,L,Se)),nested:dt,issues:mt,next:Se,limited:ft}}function kb(M,L,F,q,ne,re){let ue="",Se="literal",ve=[],He=[],dt=!1,mt=L+1;while(mt<F){let ft=M[mt];if(ft==='"')return{text:ue,provenance:Se,nested:ve,issues:He,next:mt+1,limited:dt};if(ft==="\\"&&M[mt+1]){let ht=M[mt+1]??"";if(ht===`
|
|
14
|
+
`){mt+=2;continue}if(ht==="\r"&&M[mt+2]===`
|
|
15
|
+
`){mt+=3;continue}ue+=["$","`",'"',"\\"].includes(ht)?ht:`\\${ht}`,mt+=2;continue}if(M.startsWith("$((",mt)){let ht=tl(M,mt+3,F,"))"),gt=ht===-1?F:ht+2;if(ue+=M.slice(mt,gt),ht===-1)He.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});mt=gt;continue}let pt=Yi(M,mt,F,q,ne,re);if(pt){let ht=Cd(pt,ve,He);if(mt=ht.next,dt||=ht.limited,Se=Wo(Se,ht.provenance),dt)return{text:ue,provenance:Se,nested:ve,issues:He,next:mt,limited:dt};continue}if(ft==="$"){let ht=xd(M,mt,F,ue,Se);ue=ht.text,Se=ht.provenance,mt=ht.next;continue}ue+=ft??"",mt++}return He.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:ue,provenance:Se,nested:ve,issues:He,next:F,limited:dt}}function Yi(M,L,F,q,ne,re){let ue=M.startsWith("$((",L),Se=M.startsWith("$(",L)&&!ue,ve=M.startsWith("<(",L)||M.startsWith(">(",L),He=M[L]==="`";if(!ue&&!Se&&!ve&&!He)return null;let dt=ue?3:He?1:2,mt=ue?"))":He?"`":")",ft=tl(M,L+dt,F,mt),pt=ft===-1?F:ft,ht=ft===-1?F:ft+mt.length;if(re>=q.maxDepth)return{program:Zb(M,L+dt,pt,"depth-limit"),next:ht,provenance:ue?"arithmetic":"command-substitution"};if(ue){let Ct=[],bt=[],xt=!1,At=L+dt;while(At<pt){let Tt=Yi(M,At,pt,q,ne,re+1);if(!Tt){At++;continue}if(Ct.push(...Tt.program.nodes),bt.push(...Tt.program.issues),xt||=Tt.program.status==="limited",At=Tt.next,xt)break}if(ft===-1)bt.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:cn({kind:"program",dialect:"posix",source:M.slice(L+dt,pt),span:{start:L+dt,end:pt},status:qi(bt,xt),issues:bt,nodes:Ct}),next:ht,provenance:"arithmetic"}}let gt=ji(M,L+dt,pt,q,ne,re+1),yt=ft===-1?[{code:"unclosed-command-substitution",message:`${M.slice(L,L+dt)} substitution is not closed`}]:[],St=(He||ve)&&Go(gt.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[];return{program:cn({kind:"program",dialect:"posix",source:M.slice(L+dt,pt),span:{start:L+dt,end:pt},status:qi([...gt.issues,...yt,...St],gt.limited),issues:[...gt.issues,...yt,...St],nodes:gt.nodes}),next:ht,provenance:"command-substitution"}}function Ob(M,L,F,q,ne,re){let ue=[],Se=L;while(Se<F){let ve=M[Se];if(ve==="\\"){Se+=2;continue}let He=ve==="$"||ve==="`"?Yi(M,Se,F,q,ne,re):null;if(!He){Se++;continue}if(ue.push(He.program),Se=He.next,He.program.status==="limited")break}return ue}function Cd(M,L,F){return L.push(M.program),F.push(...M.program.issues),{provenance:M.provenance,next:M.next,limited:M.program.status==="limited"}}function tl(M,L,F,q){if(q==="`"){for(let Se=L;Se<F;Se++){if(M[Se]==="\\"){Se++;continue}if(M[Se]==="`")return Se}return-1}let ne=1,re={single:!1,double:!1},ue=[];for(let Se=L;Se<F;Se++){let ve=M[Se];if((ve===`
|
|
16
|
+
`||ve==="\r")&&ue.length>0){let dt=ve==="\r"&&M[Se+1]===`
|
|
17
|
+
`?Se+2:Se+1,mt=Xa(M,dt,F,ue.splice(0));if(!mt.terminated)return-1;Se=mt.next-1;continue}let He=vd(M,Se,L,F,re);if(He!==null){Se=He;continue}if(!re.double&&M.startsWith("$((",Se)){let dt=Mb(M,Se+3,F);if(dt===-1)return-1;Se=dt+1;continue}if(q===")"&&!re.double&&ve==="<"&&M[Se+1]==="<"&&M[Se+2]!=="<"){let dt=M[Se+2]==="-",mt=Se+(dt?3:2);while(mt<F&&/[ \t]/.test(M[mt]??""))mt++;let ft=Za(M,mt,F);if(ft){ue.push({delimiter:ft.delimiter,quotedDelimiter:ft.quoted,stripTabs:dt,attach:()=>{return}}),Se=ft.next-1;continue}}if(M.startsWith("$(",Se)&&!M.startsWith("$((",Se)){ne++,Se++;continue}if(ve==="("&&!re.double)ne++;if(ve===")"&&!re.double){if(ne--,ne===0)return q==="))"&&M[Se+1]!==")"?-1:Se}}return-1}function Mb(M,L,F){let q=1,ne={single:!1,double:!1};for(let re=L;re<F;re++){let ue=M[re],Se=vd(M,re,L,F,ne);if(Se!==null){re=Se;continue}if(M.startsWith("$(",re)&&!M.startsWith("$((",re)){q++,re++;continue}if(ue==="("&&!ne.double)q++;if(ue!==")"||ne.double)continue;if(q--,q===0)return M[re+1]===")"?re:-1}return-1}function vd(M,L,F,q,ne){let re=M[L];if(re==="\\"&&!ne.single)return L+1;if(!ne.double&&re==="'")ne.single=!ne.single;if(!ne.single&&re==='"')ne.double=!ne.double;if(ne.single)return L;if(ne.double||re!=="#"||!Qb(M,L,F))return null;let ue=L;while(ue+1<q&&M[ue+1]!==`
|
|
18
|
+
`&&M[ue+1]!=="\r")ue++;return ue}function Vi(M,L){let F=M[L];if(F===";")return";";if(F==="&")return M[L+1]==="&"?"&&":"&";if(F==="|")return M[L+1]==="|"?"||":M[L+1]==="&"?"|&":"|";return null}function Db(M,L){let F=M[L];if(F===">"){if(M[L+1]===">")return">>";if(M[L+1]==="&")return">&";return M[L+1]==="|"?">|":">"}if(F!=="<")return null;if(M.startsWith("<<<",L))return"<<<";if(M.startsWith("<<-",L))return"<<-";if(M[L+1]==="<")return"<<";if(M[L+1]==="&")return"<&";if(M[L+1]===">")return"<>";return"<"}function Ki(M){let L=M.charCodeAt(0);if(L===32||L>=9&&L<=13)return!0;if(L<128)return!1;return/\s/u.test(M)}function Ed(M,L,F){if(M[L+1]==="{"){let ne=M.indexOf("}",L+2);return ne===-1||ne>=F?F:ne+1}let q=L+1;while(q<F&&/[A-Za-z0-9_?@#$!*-]/.test(M[q]??""))q++;return q===L+1?L+1:q}function Nb(M,L,F){let q="",ne=[],re=L;while(re<F){let ue=M[re];if(ue==="'")return{text:q,next:re+1,closed:!0,issues:ne};if(ue!=="\\"){q+=ue??"",re++;continue}let Se=Lb(M,re+1,F);if(q+=Se.text,Se.invalidCodePoint!==void 0)ne.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${Se.invalidCodePoint}`});re=Se.next}return{text:q,next:F,closed:!1,issues:ne}}function Lb(M,L,F){let q=M[L];if(!q||L>=F)return{text:"\\",next:L};let ne=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
|
|
19
|
+
`],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(ne.has(q))return{text:ne.get(q)??q,next:L+1};if(q==="x")return Ui(M,L+1,F,16,2,L+1);if(q==="u")return Ui(M,L+1,F,16,4,L+1);if(q==="U")return Ui(M,L+1,F,16,8,L+1);if(/[0-7]/.test(q))return Ui(M,L,F,8,3,L+1);return{text:q,next:L+1}}function Ui(M,L,F,q,ne,re){let ue=q===16?/[0-9a-fA-F]/:/[0-7]/,Se="",ve=L;while(ve<F&&Se.length<ne&&ue.test(M[ve]??""))Se+=M[ve],ve++;if(!Se)return{text:M[re-1]??"",next:re};let He=Number.parseInt(Se,q);return He>1114111||He>=55296&&He<=57343?{text:"�",next:ve,invalidCodePoint:He}:{text:String.fromCodePoint(He),next:ve}}function qi(M,L=!1){if(L)return"limited";if(M.some((F)=>F.code==="invalid-ansi-c-code-point"||F.code==="missing-heredoc-delimiter"||F.code==="ambiguous-heredoc-delimiter"||F.code==="unterminated-heredoc"||F.code==="unsupported-heredoc-context"))return"invalid";return M.length>0?"partial":"complete"}function xd(M,L,F,q,ne){let re=Ed(M,L,F);return{text:q+M.slice(L,re),provenance:Wo(ne,"variable"),next:re}}function Wb(M,L,F){let q=$i(M),ne=L,re=!1,ue=!1,Se=L;while(Se<F){let ve=M[Se];if(ve==="\\"&&!re){Se+=2;continue}if(!ue&&ve==="'"){re=!re,Se++;continue}if(!re&&ve==='"'){ue=!ue,Se++;continue}if(re){Se++;continue}let He=M.startsWith("$((",Se),dt=M.startsWith("$(",Se)&&!He,mt=!ue&&(M.startsWith("<(",Se)||M.startsWith(">(",Se)),ft=ve==="`";if(He||dt||mt||ft){let pt=He?3:ft?1:2,ht=He?"))":ft?"`":")",gt=tl(M,Se+pt,F,ht),yt=gt===-1?F:gt+ht.length;q.push(ne,Se,"literal"),q.push(Se,yt,He?"arithmetic":"command-substitution"),Se=yt,ne=yt;continue}if(ve==="$"){let pt=Ed(M,Se,F);if(pt>Se+1){q.push(ne,Se,"literal"),q.push(Se,pt,"variable"),Se=pt,ne=pt;continue}}if(!ue&&(ve==="*"||ve==="?"||ve==="[")){q.push(ne,Se,"literal"),q.push(Se,Se+1,"glob"),Se++,ne=Se;continue}Se++}return q.push(ne,F,"literal"),q.parts}function Wo(M,L){if(L==="command-substitution"||M==="command-substitution")return"command-substitution";if(L==="arithmetic"||M==="arithmetic")return"arithmetic";if(L==="variable"||M==="variable")return"variable";if(L==="glob"||M==="glob")return"glob";return M}function Gb(M,L,F){return L+1>=F||Ki(M[L+1]??"")||Vi(M,L+1)!==null}var Fb=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),zb=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function Bb(M){let L=0;while(L<=M.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(M[L]?.text??""))L++;if(L===M.length)return!0;let F=$b(M,L);if(F===void 0||F===null)return!1;L=F}return!1}function $b(M,L){let F=M[L]?.text.toLowerCase();if(F==="command")return Ub(M,L);if(F==="env")return Hb(M,L);if(F==="sudo")return jb(M,L);return}function Ub(M,L){if(M[L+1]?.text==="-v")return null;for(let F=L+1;F<M.length;F++){let q=M[F]?.text??"";if(q==="--")return F+1;if(q==="-p"||q==="-v"||q==="-V"||/^-[pvV]+$/.test(q))continue;return F}return M.length}function Hb(M,L){for(let F=L+1;F<M.length;F++){let q=M[F]?.text??"";if(q==="--")return F+1;if(Fb.has(q)){if(M[F+1]===void 0)return null;F++;continue}if(q.startsWith("-u=")||q.startsWith("--unset=")||q.startsWith("-C")&&q.length>2||q.startsWith("--chdir=")||q.startsWith("-S")&&q.length>2||q.startsWith("--split-string=")||q.startsWith("-P"))continue;if(q.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(q))continue;return F}return M.length}function jb(M,L){for(let F=L+1;F<M.length;F++){let q=M[F]?.text??"";if(q==="--")return F+1;if(zb.has(q)){if(M[F+1]===void 0)return null;F++;continue}if(q.startsWith("-"))continue;return F}return M.length}function Rd(M,L,F,q){if(M.provenance!=="literal"||!M.raw.includes("{"))return;let ne=_d(M.raw,L,F,q,!0);if(!ne)return;if("limited"in ne)return{limited:!0};let re=ne.values.map((ue)=>wd(ue,F));if(re.some((ue)=>ue===null))return{limited:!0};return{words:[...new Set(re.filter((ue)=>ue!==null&&ue!==""))]}}function Vb(M,L,F,q,ne){if(L.provenance!=="literal"||!L.raw.includes("{"))return;let re=_d(L.raw,F,q,ne,!1);if(!re)return;if("limited"in re){if(re.limited==="expansions")return{limitCode:"depth-limit"};return{limitCode:re.limited==="length"?"brace-expansion-limit":"word-limit"}}let ue=re.values.map((Se)=>wd(Se,q));if(ue.some((Se)=>Se===null))return;return{words:ue.filter((Se)=>Se!==null&&Se!=="").map((Se)=>Yr(M,L.span.start,L.span.end,Se,"literal",!1))}}function _d(M,L,F,q,ne){let re=[M],ue=M.length,Se=0;while(!0){let ve=re.findIndex((pt)=>hd(pt,ne));if(ve===-1)break;if(++Se>F)return{limited:"expansions"};let He=re[ve]??"",dt=hd(He,ne);if(!dt||dt.kind==="range")return{limited:"expansions"};let mt=dt.start+He.length-dt.end,ft=dt.alternatives.reduce((pt,ht)=>pt+mt+ht.length,0);if(ue-He.length+ft>q)return{limited:"length"};if(re.length-1+dt.alternatives.length>L)return{limited:"words"};re.splice(ve,1,...Kb(He,dt)),ue+=ft-He.length}return Se===0?void 0:{values:re}}function hd(M,L){let F=[],q,ne=null,re=!1;for(let ue=0;ue<M.length;ue++){let Se=M[ue];if(re){re=!1;continue}if(Se==="\\"&&ne!=="'"){re=!0;continue}if(Se===ne){ne=null;continue}if(ne===null&&(Se==="'"||Se==='"')){ne=Se;continue}if(ne!==null)continue;if(Se==="{"){F.push({start:ue,commas:[]});continue}if(Se===","&&F.length>0){F.at(-1)?.commas.push(ue);continue}if(Se!=="}"||F.length===0)continue;let ve=F.pop();if(!ve)continue;let He=ve.commas.length>0?{kind:"alternatives",start:ve.start,end:ue+1,commas:ve.commas}:L&&Yb(M.slice(ve.start+1,ue))?{kind:"range",start:ve.start,end:ue+1}:void 0;if(He&&(!q||He.start<q.start))q=He}if(!q||q.kind==="range")return q;return{kind:q.kind,start:q.start,end:q.end,alternatives:qb(M,q)}}function Kb(M,L){return L.alternatives.map((F)=>`${M.slice(0,L.start)}${F}${M.slice(L.end)}`)}function qb(M,L){let F=[L.start,...L.commas,L.end-1];return F.slice(0,-1).map((q,ne)=>M.slice(q+1,F[ne+1]))}function Yb(M){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(M)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(M)}function wd(M,L){let F=`x${M}`,q=el(F,0,F.length,{maxInputLength:F.length,maxWords:1,maxDepth:L},{used:0,max:1},0);if(q.limited||q.issues.length>0||q.next!==F.length||q.word.provenance!=="literal")return null;return q.word.text.slice(1)}function Zb(M,L,F,q){return cn({kind:"program",dialect:"posix",source:M.slice(L,F),span:{start:L,end:F},status:"limited",issues:[{code:q,message:"command structure exceeds parser limit"}],nodes:[]})}function Zr(M,L,F,q,ne){return{nodes:M,issues:[...L,{code:q,message:`command structure exceeds parser limit ${ne}`}],next:F,closed:!1,limited:!0,pendingHeredocs:[]}}function Hi(M,L,F){return{nodes:M,issues:L,next:F,closed:!1,limited:!0,pendingHeredocs:[]}}function Ja(M){return M.used++,M.used<=M.max}function Xb(M,L,F){let q=M.slice(L,F),ne=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(q)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(q),re=ne?.[1];if(!ne||!re)return;return{name:re,braceIndex:L+ne[0].lastIndexOf("{")}}function Go(M){return M.some((L)=>{if(L.kind==="command")return L.redirections.some((F)=>F.heredoc)||L.nested.some((F)=>Go(F.nodes));return(L.kind==="group"||L.kind==="function")&&Go(L.body.nodes)})}function Jb(M){return M.map((L)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${L.delimiter} was not found`}))}function Pd(M){return M?.kind==="command"||M?.kind==="group"||M?.kind==="function"}function yd(M,L){let F=M.at(-1);if(F?.kind!=="connector"||!bd.has(F.operator))return;L.push({code:"missing-command-after-connector",message:`connector ${F.operator} requires a following command`})}function Ad(M){return M?.provenance==="literal"&&!M.quoted&&M.raw===M.text&&Ib.has(M.text)}function Qa(M,L){let F=M.at(-1);if(!Pd(F))return;if(F?.kind==="command"&&Ad(F.words[0]))return;L.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function Qb(M,L,F){return L===F||/[\s;&|()]/u.test(M[L-1]??"")}var Id=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),eS=new Set(["gc","cat","type","cp","mv","rm"]),kd=["-rec","-for","-path","-literalpath","-whatif"],tS=/^\$env:\w/i,nS=/^(?:\$\{?\w+\}?|~)\\./;function Od(M,L){let F=M.toLowerCase().replaceAll("`","");if(![...Id].some((ne)=>F.includes(ne))&&!(F.includes("rm")&&kd.some((ne)=>F.includes(ne)))&&!F.includes("<#")&&!rS(F))return!1;let q=il(M,L);if(Md(q))return!1;return q.issues.some((ne)=>ne.code==="unclosed-block-comment"||ne.code==="comment-depth-limit")||ol(q).some(oS)}function Md(M){return M.nodes.some((L)=>{if(L.kind==="group")return Md(L.body);if(L.kind!=="command")return!1;return L.redirections.some((F)=>F.operator==="<<")})}function rS(M){if(M.includes("$env:"))return!0;return M.includes("\\")&&(M.includes("$")||M.includes("~"))}function oS(M){let L=M[0]==="&"||M[0]==="."?1:0,F=M[L]?.toLowerCase();if(F&&Id.has(F))return!0;let q=M.slice(L+1);if(F&&eS.has(F)&&q.some(iS))return!0;if(F!=="rm")return!1;return q.some((ne)=>{let re=ne.toLowerCase().split(":",1)[0]??"";return kd.some((ue)=>re.startsWith(ue))})}function iS(M){return tS.test(M)||nS.test(M)}function il(M,L){let F={start:0,end:M.length};if(M.length>L.maxInputLength)return cn({kind:"program",dialect:"powershell",source:M,span:F,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${L.maxInputLength} UTF-16 code units`}],nodes:[]});let q=sl(M,0,M.length,L,0);return cn({kind:"program",dialect:"powershell",source:M,span:F,status:uS(q.issues,q.limited),issues:q.issues,nodes:q.nodes})}function sl(M,L,F,q,ne,re=!1){let ue=[],Se=[],ve=zi(),He=0,dt=!1,mt=()=>{if(ve.words.length===0&&ve.redirections.length===0)return;let pt={start:ve.start,end:ve.end};Bi(ue,ve,{kind:"command",dialect:"powershell",source:M.slice(pt.start,pt.end),span:pt,words:ve.words,redirections:ve.redirections,nested:ve.nested,displayText:ve.words.map((ht)=>ht.text).join(" ")})},ft=L;while(ft<F){let pt=M[ft];if(!pt)break;if(re&&pt==="}")return mt(),{nodes:ue,issues:Se,next:ft+1,closed:!0,words:He,limited:dt};let ht=cS(M,ft,F,q.maxDepth);if(ht){if(ht.issue)Se.push(ht.issue);if(ht.limited)return mt(),{nodes:ue,issues:Se,next:ht.next,closed:!1,words:He,limited:!0};ft=ht.next;continue}if(/\s/.test(pt)){if(pt==="\r"||pt===`
|
|
20
|
+
`){mt();let St=pt==="\r"&&M[ft+1]===`
|
|
21
|
+
`?ft+2:ft+1;ue.push(nl(M,ft,St)),ft=St;continue}ft++;continue}let gt=Ld(M,ft);if(gt){mt(),ue.push(nl(M,ft,ft+gt.length)),ft+=gt.length;continue}if(pt==="{"){if(mt(),ne>=q.maxDepth)return Se.push(Nd(q.maxDepth)),{nodes:ue,issues:Se,next:F,closed:!1,words:He,limited:!0};let St=sl(M,ft+1,F,q,ne+1,!0),Ct=St.closed?St.next-1:St.next,bt=cn({kind:"program",dialect:"powershell",source:M.slice(ft+1,Ct),span:{start:ft+1,end:Ct},status:St.limited?"limited":St.issues.length>0?"partial":"complete",issues:St.issues,nodes:St.nodes});if(ue.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:ft,end:St.next}),body:bt})),Se.push(...St.issues),!St.closed)Se.push({code:"unclosed-script-block",message:"PowerShell script block is not closed"});He+=St.words,dt||=St.limited,ft=St.next;continue}if(pt==="}"){mt(),ue.push(nl(M,ft,ft+1)),ft++;continue}if(pt===">"||pt==="<"){ve.start=ve.start===-1?ft:ve.start;let St=M[ft+1]===pt?ft+2:ft+1,Ct=St;while(/[ \t]/.test(M[Ct]??""))Ct++;let bt=Ct<F?Td(M,Ct,F,q,ne):void 0,xt=bt?.next??St;if(ve.redirections.push(Object.freeze({kind:"redirection",operator:M.slice(ft,St),span:Object.freeze({start:ft,end:xt}),...bt?{target:bt.word}:{}})),bt)Se.push(...bt.issues),ve.nested.push(...bt.nested),He+=bt.words,dt||=bt.limited;ve.end=xt,ft=xt;continue}if(pt===","){ve.start=ve.start===-1?ft:ve.start,ve.words.push(Ya({text:",",raw:",",span:{start:ft,end:ft+1},provenance:"literal",quoted:!1})),ve.end=++ft;continue}let yt=Td(M,ft,F,q,ne);if(ve.start=ve.start===-1?ft:ve.start,ve.end=yt.next,ve.words.push(yt.word),Se.push(...yt.issues),ve.nested.push(...yt.nested),He+=1+yt.words,dt||=yt.limited,He>q.maxWords)return Se.push({code:"word-limit",message:`command exceeds ${q.maxWords} words`}),mt(),{nodes:ue,issues:Se,next:yt.next,closed:!1,words:He,limited:!0};ft=yt.next>ft?yt.next:ft+1}return mt(),{nodes:ue,issues:Se,next:ft,closed:!re,words:He,limited:dt}}function Td(M,L,F,q,ne){let re="",ue="literal",Se=!1,ve=[],He=[],dt=0,mt=!1,ft=(ht)=>{let gt=sS(M,ht,F,q,ne);return re+=M.slice(ht,gt.next),He.push(gt.program),ve.push(...gt.program.issues),dt+=rl(gt.program),mt||=gt.program.status==="limited",ue="command-substitution",gt.next},pt=L;while(pt<F){let ht=M[pt];if(!ht||/\s/.test(ht)||Ld(M,pt)||ht===">"||ht==="<"||ht==="#")break;if(ht===",")break;if(ht==="`"){let gt=M[pt+1];if(!gt){ve.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),pt++;break}re+=gt,pt+=2;continue}if(M.startsWith("$(",pt)){pt=ft(pt);continue}if(ht==="'"){Se=!0,pt++;let gt=!1;while(pt<M.length){if(M[pt]==="'"&&M[pt+1]==="'"){re+="'",pt+=2;continue}if(M[pt]==="'"){gt=!0,pt++;break}re+=M[pt]??"",pt++}if(!gt)ve.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(ht==='"'){Se=!0,pt++;let gt=!1;while(pt<F){let yt=M[pt];if(yt==="`"&&M[pt+1]){re+=M[pt+1],pt+=2;continue}if(yt==='"'){gt=!0,pt++;break}if(M.startsWith("$(",pt)){pt=ft(pt);continue}if(yt==="$")ue=M[pt+1]==="("?"command-substitution":"variable";re+=yt??"",pt++}if(!gt)ve.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(ht==="$")ue=M[pt+1]==="("?"command-substitution":"variable";if(ht==="@"&&pt===L)ue="variable";re+=ht,pt++}return{word:Yr(M,L,pt,re,ue,Se,ue==="literal"?void 0:aS(M,L,pt)),next:pt,issues:ve,nested:He,words:dt,limited:mt}}function sS(M,L,F,q,ne){let re=Dd(M,L+2,F),ue=re===-1?F:re,Se=re===-1?F:re+1;if(ne>=q.maxDepth)return{program:cn({kind:"program",dialect:"powershell",source:M.slice(L+2,ue),span:{start:L+2,end:ue},status:"limited",issues:[Nd(q.maxDepth)],nodes:[]}),next:Se};let ve=sl(M,L+2,ue,q,ne+1),He=re===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:cn({kind:"program",dialect:"powershell",source:M.slice(L+2,ue),span:{start:L+2,end:ue},status:ve.limited?"limited":ve.issues.length+He.length>0?"partial":"complete",issues:[...ve.issues,...He],nodes:ve.nodes}),next:Se}}function Dd(M,L,F){let q=1,ne=!1,re=!1;for(let ue=L;ue<F;ue++){let Se=M[ue];if(Se==="`"){ue++;continue}if(!re&&Se==="'"){if(ne&&M[ue+1]==="'"){ue++;continue}ne=!ne;continue}if(!ne&&Se==='"'){re=!re;continue}if(ne)continue;if(M.startsWith("$(",ue)){q++,ue++;continue}if(!re&&Se==="(")q++;if(Se!==")")continue;if(q--,q===0)return ue}return-1}function rl(M){let L=0;for(let F of M.nodes){if(F.kind==="group")L+=rl(F.body);if(F.kind==="command"){L+=F.words.length;for(let q of F.nested)L+=rl(q)}}return L}function aS(M,L,F){let q=$i(M),ne=L,re=!1,ue=L;while(ue<F){let Se=M[ue];if(Se==="`"){ue+=2;continue}if(Se==="'"){if(re&&M[ue+1]==="'"){ue+=2;continue}re=!re,ue++;continue}if(re){ue++;continue}if(M.startsWith("$(",ue)){let ve=Dd(M,ue+2,F),He=ve===-1?F:ve+1;q.push(ne,ue,"literal"),q.push(ue,He,"command-substitution"),ue=He,ne=He;continue}if(Se==="$"||Se==="@"&&ue===L){let ve=lS(M,ue+1,F);q.push(ne,ue,"literal"),q.push(ue,ve,"variable"),ue=ve,ne=ve;continue}ue++}return q.push(ne,F,"literal"),q.parts}function lS(M,L,F){if(M[L]==="{"){let ne=M.indexOf("}",L+1);return ne===-1||ne>=F?F:ne+1}let q=L;while(q<F&&/[A-Za-z0-9_:?]/.test(M[q]??""))q++;return q}function Nd(M){return{code:"depth-limit",message:`command structure exceeds parser limit ${M}`}}function ol(M){return M.nodes.flatMap((L)=>{if(L.kind==="group")return ol(L.body);if(L.kind!=="command")return[];return[[...L.words,...L.redirections.flatMap((F)=>F.target?[F.target]:[])].sort((F,q)=>F.span.start-q.span.start).filter((F)=>F.text!==""&&F.raw!==",").map((F)=>F.text),...L.nested.flatMap(ol)]})}function Ld(M,L){for(let F of["&&","||",";","|"])if(M.startsWith(F,L))return F;return null}function cS(M,L,F,q){if(M[L]==="#"&&M[L+1]!==">"){let ue=L+1;while(ue<F&&M[ue]!=="\r"&&M[ue]!==`
|
|
22
|
+
`)ue++;return{next:ue,limited:!1}}if(!M.startsWith("<#",L))return null;let ne=1,re=L+2;while(re<F){if(M.startsWith("<#",re)){if(ne++,ne>q)return{next:F,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${q}`},limited:!0};re+=2;continue}if(M.startsWith("#>",re)){if(ne--,re+=2,ne===0)return{next:re,limited:!1};continue}re++}return{next:F,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function uS(M,L){if(L)return"limited";if(M.some((F)=>F.code==="unclosed-block-comment"))return"invalid";return M.length>0?"partial":"complete"}function nl(M,L,F){return Object.freeze({kind:"connector",operator:M.slice(L,F),span:Object.freeze({start:L,end:F})})}function h(M,L="auto",F=ir){if(L==="powershell"||L==="auto"&&Od(M.slice(0,F.maxInputLength),F))return il(M,F);return Sd(M,F)}function t(M){return M.provenance==="command-substitution"?M.raw:M.text}function te(M,L){return M==="posix"?L:Ut(L.map((F)=>F.text))}function Zi(M,L){return M&&M.provenance!=="unknown"?M.provenance==="literal":!/[$`*?[\]]/.test(L)}function Ut(M){return M.map((L)=>({kind:"word",text:L,raw:L,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function al(M,L){return{value:M,work:L}}function vt(M,L){if(M.work)M.work.units=Math.min(Number.MAX_SAFE_INTEGER,M.work.units+1);return M.value[L]}function Vt(M){return M.value.length}function Fo(M,L,F=1){if(M)M.units=Math.min(Number.MAX_SAFE_INTEGER,M.units+L.length*F)}function Cn(M,L){Fo(M,L)}function _r(M){if(!M)return!1;let L=M.charCodeAt(0);return L>=48&&L<=57||L>=65&&L<=90||L===95||L>=97&&L<=122}function zt(M){if(!M)return!1;let L=M.charCodeAt(0);return L===9||L===10||L===11||L===12||L===13||L===32||L===160||L===65279||L===5760||L>=8192&&L<=8202||L===8232||L===8233||L===8239||L===8287||L===12288}function ll(M){return M===`
|
|
23
|
+
`||M==="\r"||M==="\u2028"||M==="\u2029"}function Bt(M,L,F){if(L+F.length>Vt(M))return!1;for(let q=0;q<F.length;q++)if(vt(M,L+q)!==F[q])return!1;return!0}function Kn(M,L,F){return!_r(vt(M,L-1))&&Bt(M,L,F)&&!_r(vt(M,L+F.length))}function qn(M,L){return _r(vt(M,L-1))!==_r(vt(M,L))}function Qt(M){return M===`
|
|
24
|
+
`||M===";"||M==="&"||M==="|"}function Xr(M){return M==="|"||M===";"}function Xi(M,L,F){let q=al(M,F);if(L==="rm")return dS(q);if(L==="dd")return mS(q);return $d(q,!0)}function Ji(M,L,F){let q=al(M,F);if(L==="rm")return pS(q);if(L==="reset-hard")return zd(q,"--ha","rd");if(L==="reset-merge")return zd(q,"--me","rge");if(L==="clean")return bS(q);if(L==="checkout")return CS(q);if(L==="push-force")return vS(q);if(L==="push-refspec")return ES(q);if(L==="push-delete")return xS(q);if(L==="branch")return RS(q);if(L==="tag")return PS(q);if(L==="restore")return AS(q);return $d(q,!1)}function dS(M){let L=!1,F=!1,q=!1,ne=-1;for(let re=0;re<=Vt(M);re++){let ue=vt(M,re);if(!L){let ve=vt(M,re+2);if(Kn(M,re,"rm")&&zt(ve)&&ve!==`
|
|
25
|
+
`)L=!0,re++;continue}let Se=fS(M,re);if(ue===`
|
|
26
|
+
`||Se!==-1){if(L=!1,F=!1,q=!1,ne=-1,Se!==-1)re=Se-1;continue}if(ue===";"||ue==="&"||ue==="|"||re===Vt(M)){if(ne>=0){let ve=Wd(M,ne,re);F||=ve.recursive,q||=ve.force}if(F&&q)return!0;L=!1,F=!1,q=!1,ne=-1;continue}if(zt(ue)){if(ne<0)continue;if(Bt(M,ne,"--")&&re-ne===2){L=!1,F=!1,q=!1,ne=-1;continue}let ve=Wd(M,ne,re);if(F||=ve.recursive,q||=ve.force,F&&q)return!0;ne=-1;continue}if(ne<0)ne=re}return!1}function fS(M,L){if(vt(M,L)!=="\\"||vt(M,L-1)==="\\")return-1;if(Bt(M,L,String.raw`\n`))return L+2;if(Bt(M,L,String.raw`\x0a`)||Bt(M,L,String.raw`\x0A`))return L+5;if(Bt(M,L,String.raw`\u000a`)||Bt(M,L,String.raw`\u000A`))return L+7;return Bt(M,L,String.raw`\012`)?L+4:-1}function Wd(M,L,F){if(Gd(M,L,F,"recursive"))return{recursive:!0,force:!1};if(Gd(M,L,F,"force"))return{recursive:!1,force:!0};if(vt(M,L)!=="-"||vt(M,L+1)==="-")return{recursive:!1,force:!1};let q=!1,ne=!1;for(let re=L+1;re<F;re++){let ue=vt(M,re);q||=ue==="r"||ue==="R",ne||=ue==="f"||ue==="F"}return{recursive:q,force:ne}}function Gd(M,L,F,q){let ne=F-L-2;if(ne<1||ne>q.length||!Bt(M,L,"--"))return!1;for(let re=0;re<ne;re++)if(vt(M,L+re+2)!==q[re])return!1;return!0}function mS(M){let L=!1;for(let F=0;F<Vt(M);F++){if(Qt(vt(M,F))){L=!1;continue}if(Kn(M,F,"dd")){L=!0,F++;continue}if(!L||!Kn(M,F,"of")||!Bt(M,F,"of=/dev/"))continue;let q=F+8;if(q<Vt(M)&&!zt(vt(M,q))&&vt(M,q)!=="'"&&vt(M,q)!=='"')return!0}return!1}function pS(M){let L=!1,F=!1,q=!1;for(let ne=0;ne<=Vt(M);){let re=vt(M,ne);if(ne===Vt(M)||Qt(re)){L=!1,F=!1,q=!1,ne++;continue}let ue=hS(M,ne);if(ue>=0){if(gS(M,ue))return!0;let Se=ue,ve=!1;while(zt(vt(M,Se)))ve||=vt(M,Se)===`
|
|
27
|
+
`,Se++;if(ve)F=!1,q=!1;L=!0,ne=Se;continue}if(!L){ne++;continue}if(Bt(M,ne,"--")&&(ne===0||zt(vt(M,ne-1)))&&(!vt(M,ne+2)||zt(vt(M,ne+2))||Qt(vt(M,ne+2)))){L=!1,F=!1,q=!1,ne+=2;continue}if(F||=Bt(M,ne,"--recursive")&&qn(M,ne+11)||cl(M,ne,"recursive"),q||=Bt(M,ne,"--force")&&qn(M,ne+7)||cl(M,ne,"force"),F&&q)return!0;ne++}return!1}function cl(M,L,F){if(!Bt(M,L,"--"))return!1;let q=0;while(q<=F.length){let ne=vt(M,L+q+2);if(!ne||zt(ne)||Qt(ne))break;if(ne!==F[q])return!1;q++}return q>0&&qn(M,L+q+2)}function gS(M,L){let F=L,q=!1,ne=!1;while(F<Vt(M)){while(zt(vt(M,F)))F++;let re=F;while(F<Vt(M)&&!zt(vt(M,F)))F++;if(vt(M,re)!=="-"||F-re===2&&Bt(M,re,"--"))return!1;let ue=Fd(M,re,"recursive"),Se=Fd(M,re,"force");if(q&&Se||ne&&ue)return!0;if(q||=ue,ne||=Se,vt(M,re+1)==="-")continue;let ve=yS(M,re,F);if(ve.combined||q&&ve.forceAtBoundary||ne&&ve.recursiveAtBoundary)return!0;q||=ve.recursive,ne||=ve.force}return!1}function Fd(M,L,F){return Bt(M,L,`--${F}`)&&qn(M,L+F.length+2)||cl(M,L,F)}function hS(M,L){if(L>0&&_r(vt(M,L-1)))return-1;let F=L;if(vt(M,F)==="\\")F++;if(vt(M,F)!=="r")return-1;if(F++,vt(M,F)==="\\")F++;if(vt(M,F)!=="m"||!zt(vt(M,F+1)))return-1;return F+1}function yS(M,L,F){let q=!1,ne=!1,re=!1,ue=!1,Se=!1;if(vt(M,L)!=="-")return{recursive:q,force:ne,recursiveAtBoundary:re,forceAtBoundary:ue,combined:Se};let ve="";for(let He=L+1;He<F;He++){let dt=vt(M,He)??"",mt=(dt==="r"||dt==="f")&&qn(M,He+1);q||=dt==="r",ne||=dt==="f",re||=dt==="r"&&mt,ue||=dt==="f"&&mt,Se||=(ve==="r"&&dt==="f"||ve==="f"&&dt==="r")&&mt,ve=dt}return{recursive:q,force:ne,recursiveAtBoundary:re,forceAtBoundary:ue,combined:Se}}function zd(M,L,F){return Bo(M,"reset",Xr,!0,(q)=>vt(M,q)==="-"&&Jr(M,q,L,F)?!0:q)}function bS(M){return Bo(M,"clean",Xr,!0,(L)=>{if(vt(M,L)!=="-")return L;if(Jr(M,L,"--fo","rce"))return!0;let F=zo(M,L,Xr);for(let q=L+1;q<F;q++)if(vt(M,q)==="f")return!0;return F-1})}function Qi(M,L,F){if(!Kn(M,L,"git"))return null;let q=L+3;if(!zt(vt(M,q)))return{commandEnd:-1,next:q};while(zt(vt(M,q)))q++;while(q<Vt(M)){if(Qt(vt(M,q)))return{commandEnd:-1,next:q};let ne=zo(M,q,Qt);if(Kn(M,q,F))return{commandEnd:q+F.length,next:ne};if(vt(M,q)!=="-")return{commandEnd:-1,next:ne};let re=ne-q===2&&Bt(M,q,"--"),ue=SS(M,q,ne);q=ne;while(zt(vt(M,q)))q++;if(re)return{commandEnd:Kn(M,q,F)?q+F.length:-1,next:zo(M,q,Qt)};if(!ue)continue;if(q>=Vt(M)||Qt(vt(M,q)))return{commandEnd:-1,next:q};q=zo(M,q,Qt);while(zt(vt(M,q)))q++}return{commandEnd:-1,next:q}}function SS(M,L,F){for(let q of yn)if(F-L===q.length&&Bt(M,L,q))return!0;return!1}function CS(M){return Bd(M,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function vS(M){return Bo(M,"push",Xr,!0,(L)=>{if(vt(M,L)!=="-")return L;if(vt(M,L+1)==="f"&&!_r(vt(M,L+2))&&!Bt(M,L+2,"-with-lease"))return!0;let F=Ud(M,L,"--fo","rce");if(F>=0&&!Bt(M,F,"-with-lease"))return!0;return L})}function ES(M){return Bo(M,"push",Qt,!1,(L)=>{if(zt(vt(M,L))&&vt(M,L+1)==="+"&&L+2<Vt(M)&&!Qt(vt(M,L+2))&&!zt(vt(M,L+2)))return!0;if(vt(M,L)===":"&&vt(M,L+1)==="+")return!0;return L})}function xS(M){return Bo(M,"push",Qt,!1,(L)=>{if(vt(M,L)==="-"&&Jr(M,L,"--de","lete"))return!0;if(zt(vt(M,L))&&vt(M,L+1)===":"&&L+2<Vt(M)&&!zt(vt(M,L+2))&&!Qt(vt(M,L+2)))return!0;return L})}function RS(M){let L=!1,F=!1,q=!1;for(let ne=0;ne<=Vt(M);ne++){if(ne===Vt(M)||Qt(vt(M,ne))){if(F&&q)return!0;L=!1,F=!1,q=!1;continue}if(!L){let Se=Qi(M,ne,"branch");if(Se){L=Se.commandEnd>=0,ne=Math.max(ne,(L?Se.commandEnd:Se.next)-1);continue}}if(!L||vt(M,ne)!=="-")continue;let re=zo(M,ne,Qt),ue=_S(M,ne,re);if(F||=ue.deletion,q||=ue.force,F&&q)return!0;ne=re-1}return!1}function _S(M,L,F){let q=!1,ne=!1;for(let re=L;re<F;re++){if(vt(M,re)!=="-")continue;if(Jr(M,re,"--de","lete"))q=!0;if(Jr(M,re,"--fo","rce"))ne=!0;if(vt(M,re+1)==="-")continue;let ue=re+1,Se=!1,ve=!1,He=!1;while(ue<F&&wS(vt(M,ue))){let dt=vt(M,ue);Se||=dt==="d"||dt==="D",ve||=dt==="f",He||=dt==="D",ue++}if(!qn(M,ue))continue;q||=Se,ne||=ve||He}return{deletion:q,force:ne}}function wS(M){if(!M)return!1;let L=M.charCodeAt(0);return L>=65&&L<=90||L>=97&&L<=122}function PS(M){return Bd(M,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function Bd(M,L){let F=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let q=0;q<Vt(M);q++){let ne=vt(M,q),re=F[F.length-1];if(!re)return!1;let ue=re.escaped;if(re.escaped=!ue&&re.quote!=="'"&&ne==="\\",!ue&&ne==="'"&&re.quote!=='"')re.quote=re.quote==="'"?"":"'";if(!ue&&ne==='"'&&re.quote!=="'")re.quote=re.quote==='"'?"":'"';if(ne==="$"&&vt(M,q+1)==="("&&(F.length===1||!ue&&re.quote!=="'")){F.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),q++;continue}if(!ue&&!re.quote&&F.length>1&&ne==="("){re.depth++;continue}if(!ue&&!re.quote&&F.length>1&&ne===")"){if(re.depth--,re.depth===0)F.pop();continue}if(zt(ne))re.shortActive=!1,re.hasShortFlag=!1;if(!re.outerActive){let Se=Qi(M,q,L.command);if(Se){re.outerActive=Se.commandEnd>=0&&zt(vt(M,Se.commandEnd)),re.shortActive=!1,re.hasShortFlag=!1,q=Math.max(q,(re.outerActive?Se.commandEnd:Se.next)-1);continue}}if(re.outerActive&&ne==="-"){if(Jr(M,q,L.longPrefix,L.longOptional))return!0;re.shortActive||=!L.excludedShortStarts.includes(vt(M,q+1)??"")}if(re.hasShortFlag||=re.shortActive&&ne===L.shortFlag,re.hasShortFlag&&qn(M,q+1))return!0;if(Xr(ne))re.outerActive=!1}return!1}function Bo(M,L,F,q,ne){let re=!1;for(let ue=0;ue<Vt(M);ue++){let Se=vt(M,ue),ve=F(Se);if(!re&&!ve){let He=Qi(M,ue,L);if(He){re=He.commandEnd>=0&&(!q||zt(vt(M,He.commandEnd))),ue=Math.max(ue,(re?He.commandEnd:He.next)-1);continue}}if(re){let He=ne(ue);if(He===!0)return!0;for(let dt=ue;dt<=He;dt++)if(F(vt(M,dt)))re=!1;ue=He}if(ve)re=!1}return!1}function AS(M){let L=!1;for(let F=0;F<Vt(M);F++){if(ll(vt(M,F))){if(L)return!0;L=!1;continue}if(!L){let q=Qi(M,F,"restore");if(q){L=q.commandEnd>=0,F=Math.max(F,(L?q.commandEnd:q.next)-1);continue}}if(L&&vt(M,F)==="-"&&vt(M,F+1)==="-"&&(Bt(M,F+2,"staged")||Bt(M,F+2,"help")))L=!1}return L}function $d(M,L){let F=!1;for(let q=0;q<Vt(M);q++){let ne=vt(M,q),re=L?ll(ne):Qt(ne);if(F&&zt(ne)&&vt(M,q+1)==="-"&&Kn(M,q+2,"delete"))return!0;if(re){F=!1;continue}if(Kn(M,q,"find"))F=!0,q+=3}return!1}function zo(M,L,F){let q=L;while(q<Vt(M)&&!zt(vt(M,q))&&!F(vt(M,q)))q++;return q}function Ud(M,L,F,q){if(!Bt(M,L,F))return-1;let ne=L+F.length;for(let re=0;re<q.length&&vt(M,ne)===q[re];re++)ne++;return qn(M,ne)?ne:-1}function Jr(M,L,F,q){return Ud(M,L,F,q)>=0}function _n(M,L){Fo(L,M,2);let F=M.toLowerCase(),q=F.trimStart(),ne=q.startsWith("echo ")||q.startsWith("rg "),re=[{scan:"rm",label:"rm -rf"},{scan:"reset-hard",label:"git reset --hard"},{scan:"reset-merge",label:"git reset --merge"},{scan:"clean",label:"git clean -f"},{scan:"checkout",label:"git checkout --force"},{scan:"push-force",label:"git push --force"},{scan:"push-refspec",label:"git push --force"},{scan:"push-delete",label:"git push delete"},{scan:"branch",label:"git branch -D",caseSensitive:!0},{scan:"tag",label:"git tag -d"},{regex:/\bgit\s+stash\s+(drop|clear)\b/,label:"git stash drop/clear"},{regex:/\bgit\s+checkout\s+--\s/,label:"git checkout --"},{scan:"restore",label:"git restore without --staged"},{scan:"find",label:"find -delete",skipForEchoRg:!0},{regex:/\bdd\b[^\n|;&]*\bof=\/dev\/\S/,label:"dd of=/dev/",skipForEchoRg:!0},{regex:/\bmkfs(?:\.[a-z0-9_-]+)?\s+\/dev\/\S/,label:"mkfs /dev/",skipForEchoRg:!0},{regex:/\bshred\b\s+\S/,label:"shred",skipForEchoRg:!0},{regex:/\b(?:curl|wget|fetch|aria2c|https?|xhs?|ncat|netcat|nc)\b(?:[^\n|;&]|\\\n)*\|(?:\s|\\\n)*(?:(?:sudo|env|command|builtin)(?:\s+(?:-\S+|\w+=\S*))*\s+)?(?:[^\s|;&]*\/)?(?:ba|da|z|k)?sh(?![^\s;&|])/,label:"download piped to shell",skipForEchoRg:!0}];for(let ue of re){if(ue.skipForEchoRg&&ne)continue;let Se=ue.caseSensitive?M:F;if(ue.regex)Cn(L,Se);if((ue.regex?.test(Se)??!1)||ue.scan&&Ji(Se,ue.scan,L))return Et("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${ue.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var TS=/^[A-Za-z_][A-Za-z0-9_]*=/;function jd(M,L,F){let q=M.words[0];if(!L||!q||M.words.length!==1||M.dialect!=="posix")return!1;if(!q.quoted||q.provenance!=="literal")return!1;let ne=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(q.text)?.[1];if(!ne)return!1;Fo(F,L.source,2);let re={anchored:new RegExp(`^\\$\\{?${ne}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${ne}(?![A-Za-z0-9_])`)};return Vd(L.nodes,q,re)}function Vd(M,L,F){return M.every((q)=>{if(q.kind==="connector")return!0;if(q.kind==="group"||q.kind==="function")return Vd(q.body.nodes,L,F);if(q.kind==="unknown")return!F.loose.test(q.source);return IS(q,L,F)})}function IS(M,L,F){if(M.nested.some((ne)=>F.loose.test(ne.source)))return!1;let q=M.words.findIndex((ne)=>!TS.test(ne.text));return M.words.every((ne,re)=>ne===L||Hd(ne.raw,F.anchored,re!==q))&&M.redirections.every((ne)=>(!ne.heredoc||ne.heredoc.quotedDelimiter||!F.loose.test(ne.heredoc.body))&&(!ne.target||Hd(ne.target.raw,F.anchored,!0)))}function Hd(M,L,F){let q=!1,ne=!1;for(let re=0;re<M.length;re++){let ue=M[re];if(ue==="\\"&&!q){re++;continue}if(!ne&&ue==="'"){q=!q;continue}if(!q&&ue==='"'){ne=!ne;continue}if(q||ue!=="$")continue;if(!L.test(M.slice(re)))continue;if(!ne||!F)return!1}return!0}import{isAbsolute as kS,resolve as Kd}from"node:path";function $o(M,L,F,q){let ne=kS(M)?Kd(M):L?Kd(L,M):void 0;if(!ne)return;try{return Dt(ne,F,q)}catch{return ne}}function qd(M){return!["/dev","/proc","/sys"].some((L)=>M===L||M.startsWith(`${L}/`))}var Qr="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",Uo="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.",dl=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),OS=new Set(["-p","--print"]),MS=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),DS=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"])]]),NS=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),LS=new Map([["python",new Set(["m"])]]),WS=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"])]]),GS=new Set(["always","default","never"]),FS=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),zS=/\\\r?\n/g,BS=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 Yd(M){return ts(M).code}function es(M){return ts(M).sources}function Zd(M){return BS.get(ml(M))??[]}function ts(M){let L=ml(M[0]??"");if(!dl.has(L))return{code:null,sources:[],optionsOpen:!1};let F=[],q=[],ne=!0;for(let re=1;re<M.length;re++){let ue=M[re];if(ue===void 0)break;if(ue==="--")return In(L,F,q,ne,M[re+1]===void 0?void 0:re+1,M[re+1]);if(ue===""||ue==="-"||!ue.startsWith("-"))return In(L,F,q,ne,re,ue);if(L==="node"&&OS.has(ue)){let mt=M[re+1];if(mt===void 0)return In(L,F,q,ne);if(mt.startsWith("-"))continue;F.push({tokenIndex:re+1,value:mt}),q.push({tokenIndex:re+1,kind:"inline-code",value:mt}),re++;continue}if(US(L,ue)){let mt=M[re+1];if(mt===void 0)return In(L,F,q,ne);if(F.push({tokenIndex:re+1,value:mt}),q.push({tokenIndex:re+1,kind:"inline-code",value:mt}),L==="python")return In(L,F,q,ne);re++;continue}let Se=/^--eval=(.*)$/s.exec(ue);if(HS(L)&&Se){let mt=Se[1]??"";F.push({tokenIndex:re,value:mt}),q.push({tokenIndex:re,kind:"inline-code",value:mt});continue}if(L==="node"){let mt=$S(ue);if(mt){if(mt.attached){if(ne&&=mt.value!=="",mt.value!=="")q.push({tokenIndex:re,kind:"module-file",value:mt.value});continue}let ft=M[re+1];if(ft===void 0||ft.startsWith("-"))return ne=!1,In(L,F,q,ne);q.push({tokenIndex:re+1,kind:"module-file",value:ft}),re++;continue}}if(L==="python"&&ue.startsWith("--check-hash-based-pycs=")||L==="node"&&(ue==="--conditions="||ue==="--diagnostic-dir="||ue==="--title=")||L==="ruby"&&(ue==="--disable="||ue==="--enable="))return In(L,F,q,ne);if(WS.get(L)?.has(ue)){let mt=M[re+1];if(mt===void 0||mt.startsWith("-")&&!(L==="ruby"&&FS.has(ue))||L==="python"&&!GS.has(mt))return In(L,F,q,ne);re++;continue}if(ue.startsWith("--"))continue;let ve,He=!1;for(let mt=1;mt<ue.length;mt++){let ft=ue[mt];if(ft===void 0)break;if(LS.get(L)?.has(ft)){let pt=ue.slice(mt+1),ht=pt||M[re+1];if(ht!==void 0)q.push({tokenIndex:pt?re:re+1,kind:"module-file",value:ht});return In(L,F,q,ne)}if(MS.get(L)?.has(ft)){ve=ue.slice(mt+1)||M[re+1],He=mt+1===ue.length;break}if(L==="node"&&ft==="r"){if(ne&&=ue==="-r",ue==="-r"){let pt=M[re+1];if(ne&&=pt!==void 0&&!pt.startsWith("-"),ne&&pt!==void 0)q.push({tokenIndex:re+1,kind:"module-file",value:pt});re++}break}if(L==="ruby"&&ft==="r"){let pt=ue.slice(mt+1),ht=pt||M[re+1];if(ne&&=ht!==void 0,ht!==void 0)q.push({tokenIndex:pt?re:re+1,kind:"module-file",value:ht});if(!pt)re++;break}if(L==="perl"&&(ft==="M"||ft==="m")){let pt=ue.slice(mt+1);if(!pt){if(ne=!1,mt+1===ue.length)re++;break}q.push({tokenIndex:re,kind:"module-file",value:pt});break}if(DS.get(L)?.has(ft)){if(mt+1===ue.length)re++;break}if(NS.get(L)?.has(ft)&&mt+1<ue.length)break}if(ve===void 0)continue;let dt=He?re+1:re;if(F.push({tokenIndex:dt,value:ve}),q.push({tokenIndex:dt,kind:"inline-code",value:ve}),L==="python")return In(L,F,q,ne);if(He)re++}return In(L,F,q,ne,void 0,void 0,!0)}function In(M,L,F,q,ne,re,ue=!1){let Se=M==="node"?L.slice(-1):L,ve=new Set(Se.map((dt)=>dt.tokenIndex)),He=F.filter((dt)=>dt.kind!=="inline-code"||ve.has(dt.tokenIndex));if(q&&L.length===0&&ne!==void 0&&re!==void 0)He.push({tokenIndex:ne,kind:"main-script",value:re});return{code:(M==="node"?Se[0]?.value:Se.map((dt)=>dt.value).join(`
|
|
28
|
+
`))||null,sources:q?He:[],optionsOpen:q&&ue}}function $S(M){for(let L of["--import","--loader","--experimental-loader","--require"]){if(M===L)return{attached:!1,value:""};if(M.startsWith(`${L}=`))return{attached:!0,value:M.slice(L.length+1)}}return}function fl(M,L){return ml(M)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(L)}function ml(M){let L=wt(M).toLowerCase();return wi.test(L)?"python":L}function US(M,L){return dl.get(M)?.has(L)??!1}function HS(M){return dl.get(M)?.has("--eval")??!1}function Ho(M,L,F=!1){let q=KS(M,L);if(!ul(q,L))return!1;Cn(L,q);let ne=VS(q);if(ul(ne,L))return!0;if(Cn(L,ne),!Xd.test(ne))return!1;return!F||jS(q,L)}function jS(M,L){if(/`|%x|\bqx\b/.test(M))return!0;let q=M.split(""),ne=[];for(let ve=0;ve<M.length;ve++){let He=M[ve];if(He!=="'"&&He!=='"')continue;let dt=M.startsWith(He.repeat(3),ve)?He.repeat(3):He,mt=ve+dt.length,ft=mt;while(ft<M.length&&!M.startsWith(dt,ft))ft+=M[ft]==="\\"?2:1;if(ft>=M.length)return!0;ne.push({start:mt,text:M.slice(mt,ft)}),q.fill(" ",ve,ft+dt.length),ve=ft+dt.length-1}let re=q.join(""),ue=Array.from(re.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((ve)=>Xd.test(ve[1]??"")).map((ve)=>{let He=ve.index+ve[0].length;return{start:He,end:pl(re,He)}});if(ue.some((ve)=>gl(re,ve.start)))return!0;return ne.some((ve)=>{let He=/\b(?:system|exec|spawn|popen)\s*$/.test(re.slice(0,ve.start)),dt=ue.some((mt)=>ve.start>=mt.start&&ve.start<mt.end);return(He||dt)&&ul(ve.text,L)})}function pl(M,L){let F=1;for(let q=L;q<M.length;q++){if(M[q]==="(")F++;if(M[q]===")")F--;if(F===0)return q}return M.length}function gl(M,L){let F=0;for(let q=L;q<M.length;q++){let ne=M[q]??"";if("([{".includes(ne))F++;if(")]}".includes(ne)&&F--===0)return!1;if(ne===","&&F===0)return!1;if(/[A-Za-z_$]/.test(ne))return!0}return!1}var Xd=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function VS(M){let L=[],F=0,q=0;while(q<M.length){let ne=M[q];if(ne!=="'"&&ne!=='"'){q++;continue}let re=M.startsWith(ne.repeat(3),q)?ne.repeat(3):ne,ue=q+re.length;while(ue<M.length&&!M.startsWith(re,ue))ue+=M[ue]==="\\"?2:1;if(ue>=M.length)break;L.push(M.slice(F,q)," "),q=ue+re.length,F=q}return L.push(M.slice(F)),L.join("")}function ul(M,L){if(Xi(M,"rm",L))return!0;for(let q of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(Cn(L,M),q.test(M))return!0;if(Xi(M,"dd",L))return!0;for(let q of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(Cn(L,M),q.test(M))return!0;if(Xi(M,"find",L))return!0;let F=M.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((q)=>(Cn(L,M),F.some((ne)=>Ji(ne,q))))}function KS(M,L){return Cn(L,M),M.replace(zS,"")}import{lstatSync as HC,readdirSync as jC}from"node:fs";import{basename as VC,isAbsolute as Rf,join as KC,relative as _f}from"node:path";import{isAbsolute as of,parse as rC}from"node:path";import{dirname as qS,isAbsolute as YS,parse as ZS,sep as XS}from"node:path";function sr(M,L,F){if(rr(L))throw Error("Unsupported Windows namespace path");let q=YS(L)?ZS(L).root:"",ne=q||M;for(let re of QS(q?L.slice(q.length):L)){if(re===""||re===".")continue;if(re===".."){ne=qS(ne);continue}let ue=JS(ne,re),Se=F.entryKind(ue),ve=Se==="symlink"?F.realpath(ue):ue;if(Se==="missing"||ve===null)throw Error(`Cannot resolve path component: ${ue}`);ne=ve}return ne}function JS(M,L){return M.endsWith("/")||M.endsWith("\\")?`${M}${L}`:`${M}${XS}${L}`}function QS(M){let L=process.platform==="win32"?/[\\/]+/:/\/+/;return M.split(L)}var hl=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],eC=new Set(hl),tC=1024,Jd=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),Qd=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),nC=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ns(M){return eC.has(M)}function yl(M){return ns(M)||Jd.has(M)||Qd.has(M)||_o(M)}function Yn(M,L,F){return F?.has(M)?F.get(M):L.get(M)}function ef(M,L){let F=Yn("GIT_CONFIG_COUNT",M,L);if(F===void 0)return{state:"absent"};if(F==="")return{state:"valid",count:0};if(!/^\d+$/.test(F))return{state:"invalid"};let q=Number(F);return Number.isSafeInteger(q)&&q<=tC?{state:"valid",count:q}:{state:"invalid"}}function rs(M,L,F){let ne=M.match(nC)?.[1];if(!ne||!yl(ne))return null;let re=M.indexOf("=");return{name:ne,value:`${Yn(ne,L,F)??""}${M.slice(re+1)}`}}function tf(M){return rf(M,Qd)}function nf(M){return rf(M,Jd)}function rf(M,L){if(!M)return!1;for(let F of M.keys())if(L.has(F))return!0;return!1}var af=/^[A-Za-z_][A-Za-z0-9_]*=/;function wn(M){if(!af.test(M))return null;let L=M.indexOf("=");return{name:M.slice(0,L),value:M.slice(L+1)}}function xe(M){let L=new Map,F=0;while(F<M.length){let q=M[F];if(!q)break;let ne=wn(t(q));if(!ne)break;L.set(ne.name,ne.value),F++}return{words:M.slice(F),envAssignments:L}}function lf(M){let L=It(M);return M.includes("=")||L==="sudo"||L==="env"||L==="command"||L==="builtin"}function wr(M,L,F,q){if(!lf(eo(M)))return{words:M,envAssignments:new Map,cwd:F,rewritten:!1};let ne=new Set(M),re=M,ue=new Map,Se=new Map(q??[]),ve=[],He=F;for(let mt=0;mt<a.wrapperPeelIterations.cap;mt++){let ft=sf(re),pt=xe(re);for(let[gt,yt]of pt.envAssignments)ue.set(gt,yt),Se.set(gt,yt);if(re=pt.words,re.length===0)break;while(re.length>0&&eo(re).includes("=")&&!iC(re)){let gt=sC(eo(re),Se,L.env)??rs(eo(re),L.env,Se);if(gt)ue.set(gt.name,gt.value),Se.set(gt.name,gt.value);re=re.slice(1)}if(re.length===0)break;let ht=It(eo(re));if(ht!=="sudo"&&ht!=="env"&&ht!=="command"&&ht!=="builtin")break;if(ht==="sudo"){let gt=lC(re,L.paths,He);if(re=gt.words,gt.cwd!==void 0)He=gt.cwd}if(ht==="env"){let gt=dC(re,He,Se,L);if(ve.push(...gt.envSplitValues??[]),re=gt.words,gt.cwd!==void 0)He=gt.cwd;for(let[yt,St]of gt.envAssignments)ue.set(yt,St),Se.set(yt,St)}if(ht==="command")re=fC(re);if(ht==="builtin")re=re.slice(kn(re,1)==="--"?2:1);if(sf(re)===ft)break}let dt=xe(re);for(let[mt,ft]of dt.envAssignments)ue.set(mt,ft),Se.set(mt,ft);return{words:dt.words,envAssignments:ue,cwd:He,envSplitValues:ve.length>0?ve:void 0,rewritten:oC(dt.words,ne)}}function oC(M,L){return M.some((F)=>!L.has(F))}function sf(M){return M.map(t).join(" ")}function eo(M){let L=M[0];return L?t(L):""}function kn(M,L){let F=M[L];return F?t(F):void 0}function iC(M){return af.test(eo(M))}function sC(M,L,F){if(!M.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${L.get("TMPDIR")??F.get("TMPDIR")??""}${M.slice(8)}`}}var aC=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function lC(M,L,F){let q=1,ne=F;while(q<M.length){let re=kn(M,q);if(!re)break;if(re==="--")return{words:M.slice(q+1),cwd:ne};if(!re.startsWith("-"))break;if(re==="-D"||re==="--chdir"){let ue=kn(M,q+1);ne=ue?jo(ne,ue,L):null,q+=2;continue}if(re.startsWith("--chdir=")){ne=jo(ne,re.slice(8),L),q++;continue}if(re.startsWith("-D")&&re.length>2){ne=jo(ne,re.slice(2),L),q++;continue}if(re==="-i"||re==="--login"){ne=null,q++;continue}if(aC.has(re)){q+=2;continue}q++}return{words:M.slice(q),cwd:ne}}var cC=new Set(["-i","-0","--null"]),uC=new Set(["-u","--unset","-C","--chdir","-P"]);function dC(M,L,F,q){let ne=new Map,re=[],ue=L,Se=1,ve=(He)=>({words:M.slice(He),envAssignments:ne,cwd:ue,envSplitValues:re.length>0?re:void 0});while(Se<M.length){let He=kn(M,Se);if(!He)break;if(He==="--")return ve(Se+1);if(He==="-i"||He==="--ignore-environment"||He==="-"){ne.clear();for(let mt of F.keys())ne.set(mt,"");ne.set("TMPDIR",""),Se++;continue}if(cC.has(He)){Se++;continue}if(He==="-u"||He==="--unset"){let mt=kn(M,Se+1);if(mt!==void 0)ne.set(mt,"");Se+=2;continue}if(He.startsWith("-u")&&He.length>2&&!He.startsWith("-u=")){ne.set(He.slice(2),""),Se++;continue}if(He.startsWith("--unset=")){ne.set(He.slice(8),""),Se++;continue}let dt=He==="-S"||He==="--split-string"?{value:kn(M,Se+1),consumed:2}:He.startsWith("-S")&&He.length>2?{value:He.slice(2),consumed:1}:He.startsWith("--split-string=")?{value:He.slice(15),consumed:1}:null;if(dt){if(dt.value!==void 0)re.push(dt.value);return ue=null,ve(Se+dt.consumed)}if(uC.has(He)){if(He==="-C"||He==="--chdir"){let mt=kn(M,Se+1);ue=mt?jo(ue,mt,q.paths):null}Se+=2;continue}if(He.startsWith("-u=")){Se++;continue}if(He.startsWith("-C")&&He.length>2||He.startsWith("--chdir=")){let mt=He.startsWith("--chdir=")?He.slice(8):He.startsWith("-C=")?He.slice(3):He.slice(2);ue=jo(ue,mt,q.paths),Se++;continue}if(He.startsWith("-P")){Se++;continue}if(He.startsWith("-")){Se++;continue}if(!wn(He))break;while(Se<M.length){let mt=wn(kn(M,Se)??"");if(!mt)break;ne.set(mt.name,mt.value),Se++}if(kn(M,Se)==="--")Se++;return ve(Se)}return ve(Se)}function jo(M,L,F){if(L==="")return null;if(!M&&!of(L))return null;let q=of(L)?rC(L).root:F.realpath(M??"/");if(q===null)return null;try{return sr(q,L,F)}catch{return null}}function fC(M){if(kn(M,1)==="-v")return[...Ut(["type"]),...M.slice(2)];let L=1;while(L<M.length){let F=kn(M,L);if(!F)break;if(F==="-p"||F==="-v"||F==="-V"){L++;continue}if(F==="--")return M.slice(L+1);if(F.startsWith("-")&&!F.startsWith("--")&&F.length>1){if(!/^[pvV]+$/.test(F.slice(1)))break;L++;continue}break}return M.slice(L)}var mC=/['"\\$`{}#]/;function os(M,L){if(M.some((q)=>mC.test(q)))return null;let F=[...M.flatMap((q)=>q.split(/\s+/).filter((ne)=>ne.length>0)),...L];return F.length<=64?F:null}function ar(M,L,F){return is(M,L,F).tokens}function pC(M){let L=[],F="",q=0;while(q<M.length){let ne=M.charAt(q);if(ne==='"'||ne==="'"){let re=M.indexOf(ne,q+1);if(re===-1)return M.split(/\s+/).map((ue)=>ue.replace(/["']/g,"")).filter((ue)=>ue.length>0);F+=M.slice(q+1,re),q=re+1;continue}if(/\s/.test(ne)){if(F.length>0)L.push(F);F="",q++;continue}F+=ne,q++}if(F.length>0)L.push(F);return L}function lr(M,L,F,q=0){let ne=is(M,L,F),re=(ne.envSplitValues??[]).flatMap(pC);if(re.length===0)return ne.tokens;let ue=[...re,...ne.tokens];if(q>=8)return ue;return lr(ue,L,F,q+1)}function is(M,L,F,q){if(!lf(M[0]??""))return{tokens:[...M],envAssignments:new Map,cwd:F};let ne=wr(Ut(M),L,F,q);return{tokens:ne.words.map(t),envAssignments:ne.envAssignments,cwd:ne.cwd,envSplitValues:ne.envSplitValues}}var vl=Symbol("adopt-as-operand"),gC=new Set(["env","sudo","command","builtin"]),hC=new Set(["&&","||","|&","|","&",";"]),yC=new Set(["<<","<<<",">|"]),bC=new Set(["|","|&"]),SC=/[*@#?$!_-]/,CC=/^\w+(?::\w+)*/,vC=Object.freeze([]),Vo=Object.freeze({kind:"scope",edge:"enter"}),Ko=Object.freeze({kind:"scope",edge:"exit"}),EC=Object.freeze([]),xC=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),qo=new Set(["bash","sh","zsh","dash","ksh"]),RC=256,mf=new WeakMap;function pf(M,L){let F=L.status==="complete"?new Set(Cl(L)):new Set,q=PC(M,F);if(Ai(q))return ss("unclosed-quote",q,L);let ne={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},re=Pr(L,{source:q,suppressed:F,flags:ne,depth:0,functions:new Map,powershell:L.dialect==="powershell"});if(ne.limited)return ss("structural-limit",q,L);if(ne.invalid)return ss("invalid",q,L);let ue=ss("complete",q,L,ne.assignmentFallbacks);return mf.set(ue,Object.freeze(re)),ue}function ls(M,L,F,q,ne){let re=ne.word??((mt)=>mt),ue={cwd:L,variables:new Map,previous:null},Se=[],ve=new Set,He=null,dt=[];for(let mt of gf(M)){if(mt.kind==="scope"){if(mt.edge==="enter"){dt.push({state:ue,segment:[...Se],shellWords:new Set(ve),pipeProducer:He});continue}let ft=ne.segment(Se,ue,He,null,ve);if(ft)return ft;let pt=dt.pop();if(pt===void 0)throw Error("scope exit without a matching enter");ue=pt.state,Se=pt.segment,ve=pt.shellWords,He=pt.pipeProducer;continue}if(mt.kind==="operator"){if(!mt.boundary)continue;let ft=ne.segment(Se,ue,He,mt.operator,ve);if(ft)return ft;ue=_C(Se,ue,F,q),He=Se.length>0&&bC.has(mt.operator)?Se:null,Se=[],ve=new Set;continue}if(mt.kind==="redirection"){if(mt.fd!==void 0)ve.add(Se.length-1);if(mt.target===void 0)continue;let ft=ne.redirection({operator:mt.operator,role:mt.role,targetOrder:mt.targetOrder,target:mt.target,...mt.body===void 0?{}:{body:mt.body,consumer:mt.consumer}},ue);if(ft===vl){ve.add(Se.length),Se.push(re(mt.target));continue}if(ft)return ft;continue}Se.push(re(mt.text))}return ne.segment(Se,ue,He,null,ve)}function cs(M){return gf(M).flatMap((L)=>{if(L.kind==="word")return[{kind:"word",text:L.text}];if(L.kind==="operator")return[{kind:"operator",boundary:L.boundary}];if(L.kind==="redirection")return[{kind:"redirection",target:L.target}];return[]})}function un(M,L){return M.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(F,q,ne,re)=>{let ue=L.get(q);if(ue===void 0)return F;let Se=ne.startsWith(":")?ue!=="":!0;if(ne.endsWith("-"))return Se?ue:un(re,L);return Se?un(re,L):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(F,q)=>L.get(q)??F).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(F,q)=>L.get(q)??F)}function Yo(M){return M.length>0&&M.every((L)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(L))}function _C(M,L,F,q){let ne=Yo(M)?new Map([...L.variables,...wC(M,L.variables)]):L.variables,re=ar([...M],F),ue=wt(re[0]??"").toLowerCase()==="cd"?re[1]:void 0;if(!ue)return{...L,variables:ne};if(ue==="-"){if(L.previous===null)return{...L,variables:ne};return{cwd:L.previous,variables:ne,previous:L.cwd}}return{cwd:rn(un(ue,ne),L.cwd,F,q),variables:ne,previous:L.cwd}}function wC(M,L){return M.flatMap((F)=>{let q=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(F),ne=q?.[2]?.startsWith("=")?q[2].slice(1):void 0;return q?.[1]!==void 0&&ne!==void 0?[[q[1],un(ne,L)]]:[]})}function gf(M){return mf.get(M)??vC}function PC(M,L){return[...L].reduce((F,q)=>F.slice(0,q.start)+" ".repeat(q.end-q.start)+F.slice(q.end),M)}function ss(M,L,F,q=EC){return Object.freeze({status:M,source:L,program:F,assignmentFallbacks:Object.freeze(q)})}function Pr(M,L){return M.nodes.flatMap((F,q)=>AC(F,M,q,L)).sort((F,q)=>F.start-q.start).flatMap((F)=>[...F.events])}function AC(M,L,F,q){if(M.kind==="connector")return[{start:M.span.start,events:[On(MC(M.operator))]}];if(M.kind==="unknown")return[{start:M.span.start,events:[On(M.source)]}];if(M.kind==="function")return q.functions.set(M.name,M.body),[];if(M.kind==="group"){let re=M.style!=="subshell",ue=q.source[M.span.end-1]===(re?"}":")"),Se=re?q:{...q,functions:new Map(q.functions)};return[{start:M.span.start,events:re?[as("{"),...Pr(M.body,Se),...ue?[as("}")]:[]]:[Vo,On("("),...Pr(M.body,Se),...ue?[On(")")]:[],Ko]}]}let ne=WC(M,q.functions);if(ne){if(q.depth>=ir.maxDepth||++q.flags.expansions>RC)return q.flags.limited=!0,[];return[{start:M.span.start,events:[...cf(M,q),as(";"),...Pr(ne,{...q,depth:q.depth+1}),as(";")]},...uf(M,L,F,q)]}return[{start:M.span.start,events:cf(M,q)},...uf(M,L,F,q)]}function cf(M,L){return[...M.words.map((F)=>({start:F.span.start,events:yf(F,M,L,!1)})),...M.redirections.map((F)=>({start:F.span.start,events:TC(F,M,L)}))].sort((F,q)=>F.start-q.start).flatMap((F)=>F.events)}function TC(M,L,F){let q=M.operator==="<<-"?"<<":M.operator,ne=M.target?yf(M.target,L,F,!0):[],re=ne[0],ue=re?.kind==="word"?re.text:void 0;return[...M.fd===void 0?[]:[El(String(M.fd))],Object.freeze({kind:"redirection",operator:q,...M.fd===void 0?{}:{fd:M.fd},role:DC(q),targetOrder:yC.has(q)?"legacy-segment":"immediate",...ue===void 0?{}:{target:ue},...M.heredoc&&F.suppressed.has(M.heredoc.bodySpan)?{body:M.heredoc.body,consumer:Sf(L)}:{}}),...ue===void 0?ne:ne.slice(1)]}function uf(M,L,F,q){let ne=M.redirections.filter((re)=>re.operator==="<<"||re.operator==="<<-");return[...ne.flatMap((re)=>{let ue=re.heredoc;if(!ue)return[];let Se=[El(ue.delimiter),.../[\r\n]/.test(q.source[ue.terminatorSpan.end]??"")?[On(";")]:[]];if(q.suppressed.has(ue.bodySpan))return[{start:ue.bodySpan.start,events:Se}];return[{start:ue.bodySpan.start,events:[...hf(q.source.slice(ue.bodySpan.start,ue.bodySpan.end),q),...Se]}]}),...ne.some((re)=>!re.heredoc&&re.target)?IC(L,F,q):[]]}function IC(M,L,F){let q=M.nodes.slice(L+1).find((ne)=>ne.kind==="connector");if(!q||q.span.end>=M.span.end)return[];return[{start:q.span.end,events:hf(F.source.slice(q.span.end,M.span.end),F)}]}function hf(M,L){if(L.depth>=ir.maxDepth)return L.flags.limited=!0,[];let F=h(M,"posix");if(F.status==="limited")return L.flags.limited=!0,[];let q={invalid:!1,limited:!1,expansions:L.flags.expansions,assignmentFallbacks:L.flags.assignmentFallbacks},ne=Pr(F,{source:M,suppressed:new Set,flags:q,depth:L.depth+1,functions:new Map,powershell:!1});return L.flags.limited||=q.limited,L.flags.expansions=q.expansions,ne}function yf(M,L,F,q){let ne=[],re={single:!1,double:!1},ue="",Se=!1,ve=()=>{let He=Se&&!q?On("glob"):ue!==""||M.quoted&&ne.length===0?El(ue):void 0;if(He)ne.push(He);ue="",Se=!1};for(let He of M.parts){if(He.provenance!=="command-substitution"&&He.provenance!=="arithmetic"){for(let pt of bl(He.raw,re,F.flags,F.powershell)){if(typeof pt==="string"){ve(),ne.push(On(pt));continue}ue+=pt.text,Se||=pt.glob}continue}let dt=L.nested.find((pt)=>pt.span.start>=He.span.start&&pt.span.end<=He.span.end);if(re.double){let pt=F.source.slice(He.span.start,He.span.end);ue+=bl(pt,{single:!1,double:!0},F.flags,F.powershell).map((gt)=>typeof gt==="string"?gt:gt.text).join("");let ht=dt?Pr(dt,F).filter((gt)=>gt.kind==="redirection"&>.body!==void 0):[];if(ht.length>0)ne.push(Vo,...ht,Ko);continue}let mt=dt?Pr(dt,F):[];if(He.raw.startsWith("`")){ue+="${}",ve(),ne.push(Vo,...mt,Ko);continue}if(He.raw.startsWith("<(")||He.raw.startsWith(">(")){ve(),ne.push(He.raw.startsWith("<(")?On("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),Vo,...mt,...He.raw.endsWith(")")?[On(")")]:[],Ko);continue}let ft=He.raw.startsWith("$((")?2:1;ue+="${}",ve(),ne.push(...Array.from({length:ft},()=>On("(")),...ft===1?[Vo]:[],...mt,...He.raw.endsWith(")".repeat(ft))?Array.from({length:ft},()=>On(")")):[],...ft===1?[Ko]:[])}return ve(),ne}function bl(M,L,F,q){let ne=[],re="",ue=!1,Se=0;while(Se<M.length){let ve=M[Se]??"";if(!L.single&&!L.double&&(ve==="("||ve===")")){ne.push({text:re,glob:ue},ve),re="",ue=!1,Se++;continue}if(q&&ve==="`"&&!L.single){re+=M[Se+1]??"",Se+=2;continue}if(L.single&&ve==="'"){L.single=!1,Se++;continue}if(L.single){re+=ve,Se++;continue}if(L.double){if(ve==='"'){L.double=!1,Se++;continue}if(!q&&ve==="\\"){let He=M[Se+1]??"";re+=['"',"\\","$"].includes(He)?He:`\\${He}`,Se+=2;continue}if(ve==="$"){let He=df(M,Se,L,F,q);re+=He.text,Se=He.next;continue}re+=ve,Se++;continue}if(ve==="'"||ve==='"'){L.single=ve==="'",L.double=ve==='"',Se++;continue}if(!q&&ve==="\\"){let He=M[Se+1]??"";ue||=He==="*"||He==="?",re+=He,Se+=2;continue}if(ve==="$"){let He=df(M,Se,L,F,q);re+=He.text,Se=He.next;continue}ue||=ve==="*"||ve==="?",re+=ve,Se++}return[...ne,{text:re,glob:ue}]}function df(M,L,F,q,ne){let re=M[L+1];if(re==="{"){let Se=OC(M,L+2);if(Se===-1)return q.invalid=!0,{text:"",next:M.length};let ve=M.slice(L,Se+1);return kC(ve,F,q,ne),{text:ve,next:Se+1}}if(re!==void 0&&SC.test(re))return{text:`\${${re}}`,next:L+2};let ue=(ne?CC:/^\w*/).exec(M.slice(L+1))?.[0]??"";return{text:`\${${ue}}`,next:L+1+ue.length}}function kC(M,L,F,q){let ne=M.slice(2,-1),re=/^[A-Za-z_][A-Za-z0-9_]*/.exec(ne)?.[0];if(!re)return;let ue=ne.slice(re.length),Se=[":=","="].find((He)=>ue.startsWith(He));if(!Se)return;let ve=bl(ue.slice(Se.length),{...L},F,q);F.assignmentFallbacks.push(...ve.flatMap((He)=>typeof He==="string"||!He.text?[]:[He.text]))}function OC(M,L){let F=1,q=L;while(F>0&&q<M.length){if(M[q]==="{"&&M[q-1]==="$")F++;if(M[q]==="}")F--;q++}return F===0?q-1:-1}function MC(M){return/^[\r\n]+$/.test(M)?";":M}function On(M){return Object.freeze({kind:"operator",operator:M,boundary:hC.has(M)})}function as(M){return Object.freeze({kind:"operator",operator:M,boundary:!0})}function El(M){return Object.freeze({kind:"word",text:M})}function DC(M){if(M==="<<"||M==="<<<")return"here-data";if(M==="<"||M==="<&")return"file-read";return"file-write"}function Zo(M){return xC.has(M)||/^python\d/.test(M)}var NC=new Map([["sudo",new Set(["-u","-g","-h","-p","-C","-D","-r","-t","-T","-U","--user","--group","--host","--prompt","--chdir","--role","--type","--other-user"])],["env",new Set(["-u","-C","-P","-S","--unset","--chdir","--split-string"])]]);function bf(M,L){let F=L[0];if(F===void 0||!F.startsWith("-"))return L;let q=NC.get(M)?.has(F)??!1;return bf(M,L.slice(q?2:1))}function Sl(M){let L=M[0];if(L===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(L))return Sl(M.slice(1));if(!gC.has(L))return[...M];return Sl(bf(L,M.slice(1)))}function Sf(M){let L=Lo(M),F=M.words.findIndex((q)=>q.provenance==="literal"&&q.text===L);return Sl(F<0?[]:M.words.slice(F).map((q)=>q.text))}function LC(M){let L=Sf(M)[0];if(L===void 0)return!1;let F=wt(L).toLowerCase();return Zo(F)&&!qo.has(F)}function Cl(M){return M.nodes.flatMap((L,F)=>{if(L.kind==="group"||L.kind==="function")return Cl(L.body);if(L.kind!=="command")return[];let q=L.nested.flatMap((Se)=>Cl(Se)),ne=L.redirections.flatMap((Se)=>Se.heredoc?.quotedDelimiter?[Se.heredoc.bodySpan]:[]);if(LC(L))return[...q,...ne];let re=M.nodes[F+1];if(re?.kind==="connector"&&(re.operator==="|"||re.operator==="|&")||!FC(L))return q;return[...q,...ne]})}function WC(M,L){let F=Lo(M);return F===void 0?void 0:L.get(F)}function cr(M,L){return M!==void 0&&M.provenance==="literal"&&!M.quoted&&M.raw===M.text&&M.text===L}function GC(M){if(cr(M.words[0],"git"))return cr(M.words[1],"commit");if(!cr(M.words[0],"gh")||!cr(M.words[2],"create"))return!1;return cr(M.words[1],"pr")||cr(M.words[1],"issue")}function FC(M){return(cr(M.words[0],"cat")||cr(M.words[0],"tee")||GC(M))&&!M.words.some(ff)&&!M.redirections.some((F)=>ff(F.target))}function ff(M){return M?.parts.some((L)=>L.provenance==="command-substitution"&&L.raw.startsWith(">("))??!1}var Cf=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),vf=new Set([...Cf,"glob"]),zC=new Set([...vf,"pattern"]);class y extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Ef(M){let L=BC(),F=oe(M.input),q=[];if((M.route.kind==="command"||M.route.kind==="unknown")&&F)q.push({usage:"input-candidate",source:F});if(M.route.kind==="command"&&"command"in M&&M.command)q.push({usage:"declared-command",source:M.command});let ne=q.reduce((re,ue)=>{let Se=re.findIndex((dt)=>dt.source===ue.source);if(Se!==-1){let dt=re[Se];if(!dt)return re;return re[Se]={...dt,usages:[...dt.usages,ue.usage]},re}let ve=M.route.kind==="command"?M.route.shell:process.platform==="win32"?"powershell":"posix",He=L.getCommandProgram(ue.source,ve);return re.push({usages:[ue.usage],source:ue.source,program:He,shell:L.getShellSyntax(ue.source,He)}),re},[]);return{invocation:{toolName:M.toolName,route:M.route,context:M.context},commands:ne,paths:$C(M),store:L}}function dn(M,L){return M.commands.find((F)=>F.usages.includes(L))}function Zn(M,L){if(!M.includes("$"))return M;return na(M,L)}function BC(){let M=new Map,L=new Map,F=new WeakMap,q=(re,ue)=>{let Se=`${ue}\x00${re}`,ve=L.get(Se);if(ve)return ve;let He=h(re,ue);return L.set(Se,He),He};return{getShellSyntax:(re,ue)=>{if(ue&&ue.source!==re)throw TypeError("Shell syntax source does not match command program source.");let Se=ue??q(re,"posix");if(Se.status==="limited"){let dt=F.get(Se);if(dt)return dt;let mt={status:"structural-limit",source:re,program:Se,assignmentFallbacks:[]};return F.set(Se,mt),mt}let ve=M.get(re);if(ve)return ve;let He=pf(re,Se);return M.set(re,He),He},getCommandProgram:q}}function $C(M){let L=M.route.kind==="grep"?vf:M.route.kind==="glob"?zC:Cf;return[...nu(M.input,L),...M.route.kind==="patch"||typeof M.input==="string"?iu(M.input):[]]}var UC=new Set(["-S","--suffix"]);function to(M,L,F,q,ne){if(M.status==="structural-limit")throw new y;if(M.status!=="complete")return ne.findMalformedTarget(M.source);return ls(M,L,F,q,{segment:(re,ue)=>ne.findSegmentTarget(re,ue),redirection:(re,ue)=>re.role==="file-write"&&ne.isRedirectionTarget(un(re.target,ue.variables),ue)?re.target:null})}function us(M){let L=[],F=null,q=!1;for(let ne=0;ne<M.length;ne++){let re=M[ne];if(re===void 0)break;if(!q&&re==="--"){q=!0;continue}if(!q&&(re==="-t"||re==="--target-directory")){F=M[++ne]??null;continue}if(!q&&re.startsWith("--target-directory=")){F=re.slice(19);continue}if(!q&&re.startsWith("-t")&&re.length>2){F=re.slice(2);continue}if(!q&&UC.has(re)){ne++;continue}if(!q&&(re.startsWith("--suffix=")||re.startsWith("--backup=")))continue;if(!q&&re.startsWith("-"))continue;L.push(re)}return F?{sources:L,destination:F}:{sources:L.slice(0,-1),destination:L.at(-1)??null}}var k="Git metadata and hooks are protected. Ask the user before modifying them.";function wf(M,L,F,q){let ne=M.invocation.context.executionCwd;if(!L)return null;if(M.invocation.route.kind==="patch"||M.invocation.route.kind==="path"||M.invocation.route.kind==="unknown"){if(Si(M.invocation.toolName))return null;let Se=M.paths.find((ve)=>xf(ve,ne,L,F,q,L.entries));return Se?{target:Se}:null}if(M.invocation.route.kind!=="command")return null;let re=dn(M,"input-candidate");if(!re)return null;let ue=to(re.shell,ne,F,q,{findSegmentTarget:(Se,ve)=>QC(Se,ve,L,F,q),isRedirectionTarget:(Se,ve)=>xf(Se,ve.cwd,L,F,q,L.markerFiles),findMalformedTarget:()=>null});return ue?{target:ue}:null}function Ar(M,L,F,q,ne,re,ue=!1){if(!F)return!1;let Se=fs(rn(M,L,ne,re)),ve=Se.replace(/(\/\.?\*+)+$/,"");if(ve!==Se&&ve!==""){if(xl(ve,F))return!0;let He=ue||Se.slice(ve.length).includes("/."),dt=(mt)=>He?ds(mt,ve):qC(mt,ve);if(F.markerFiles.some(dt))return!0;return q&&Rl(F).some(dt)}if(xl(Se,F))return!0;return q&&Rl(F).some((He)=>ds(He,Se))}function qC(M,L){let F=_f(L,M);if(F===""||F.startsWith("..")||Rf(F))return!1;return!F.split(/[\\/]/)[0]?.startsWith(".")}function YC(M,L,F,q,ne){return Ar(M,L,F,!0,q,ne)}function ZC(M,L,F,q,ne){if(!F)return!1;return xl(fs(rn(M,L,q,ne)),F)}function xf(M,L,F,q,ne,re){let ue=fs(rn(M,L,q,ne));return re.includes(ue)||Af(ue,F)}function Pf(M,L,F,q,ne){if(!F)return!1;return F.hooksDirectories.some((re)=>M.some((ue)=>ds(re,fs(rn(ue,L,q,ne)))))}function xl(M,L){return L.entries.includes(M)||L.directories.includes(M)||Af(M,L)}function Af(M,L){return L.hooksDirectories.some((F)=>ds(M,F))}var XC=50000;function Tf(M,L){let F=[...new Set(Rl(M))];if(F.some((ne)=>L(VC(ne))))return!0;let q=0;while(F.length>0){let ne=F.pop()??"",re=JC(ne);if(!re)return!0;if(q+=re.length,q>XC)return!0;if(re.some((ue)=>L(ue.name)))return!0;F.push(...re.filter((ue)=>ue.isDirectory()).map((ue)=>KC(ne,ue.name)))}return!1}function JC(M){try{let L=HC(M,{throwIfNoEntry:!1});if(!L)return[];if(!L.isDirectory())return L.isSymbolicLink()?null:[];return jC(M,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function Rl(M){return[...M.entries,...M.directories,...M.hooksDirectories]}function ds(M,L){let F=_f(L,M);return F===""||!/^\.\.(?:[\\/]|$)/.test(F)&&!Rf(F)}function fs(M){return process.platform==="win32"?M.toLowerCase():M}function QC(M,L,F,q,ne){if(Yo(M))return null;let re=lr([...M],q);if(wt(re[0]??"").toLowerCase()!=="mv")return null;let ue=us(re.slice(1)),Se=ue.sources.find((ve)=>YC(un(ve,L.variables),L.cwd,F,q,ne));if(Se)return Se;return ue.destination&&ZC(un(ue.destination,L.variables),L.cwd,F,q,ne)?ue.destination:null}import{isAbsolute as hs,normalize as av,parse as lv,posix as Wf,resolve as Ir,sep as Al}from"node:path";import{isAbsolute as ev,join as If,normalize as Mf,parse as tv,sep as kf}from"node:path";var nv=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],rv=`
|
|
29
|
+
`;function Xo(M,L){if(Tr(M,L))return!0;if(!M.has("TMPDIR"))return!1;return!_l(M.get("TMPDIR")??"",L)}function no(M,L){if(M.has("TMPDIR"))return _l(M.get("TMPDIR")??"",L);let F=wl(M,L);if(F===void 0)return!0;return _l(F,L)}function wl(M,L){return Nf(M,L,"TMPDIR")}function _l(M,L){if(!M)return!1;if(iv(M))return!1;return ro(M,L)}function Tr(M,L){let F=Nf(M,L,"IFS");return F!==void 0&&F!==""&&F!==rv}function ro(M,L){let F=ms(M,L.paths);if(F===null)return!1;return Df(L).some((q)=>oo(F,q))}function gs(M,L){let F=ms(M,L.paths);if(F===null)return!1;return Df(L).some((q)=>ps(q)===ps(F))}var Of=new WeakMap;function Df(M){let L=Of.get(M);if(L)return L;let F=ov(M);return Of.set(M,F),F}function ov(M){let L=nv.map((q)=>ms(q,M.paths)??Mf(q)),F=ms(M.tmpdir,M.paths);if(!F)return L;if(process.platform==="win32")return[...L,F];if(process.platform==="darwin"&&sv(F))return[...L,F];return L}function iv(M){return/[\s$`*?[]/.test(M)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(M)||/[+@!]\([^)]*\)/.test(M)}function Nf(M,L,F){return M.has(F)?M.get(F):L.env.get(F)}function sv(M){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(M)}function ms(M,L){try{let F=Mf(M);if(!ev(F))return F;let q=tv(F).root,ne=F.slice(q.length).split(/[\\/]+/).filter(Boolean),re=q;for(let ue=0;ue<ne.length;ue++){let Se=If(re,ne[ue]??"");if(L.entryKind(Se)==="missing")return If(Se,...ne.slice(ue+1));let ve=L.realpath(Se);if(ve===null)return null;re=ve}return re}catch{return null}}function oo(M,L){let F=ps(M),q=ps(L);if(F===q)return!0;let ne=q.endsWith(kf)?q:`${q}${kf}`;return F.startsWith(ne)}function ps(M){return process.platform==="win32"?M.toLowerCase():M}var cv=process.platform==="win32",Lf=64,uv=16384;function Jo(M,L,F,q){if(M.kind==="temp_target")return null;let ne=q[M.kind];if(M.kind==="dynamic_target"&&!Yt(F,ne.id,L.strict))return null;if(M.kind==="within_anchored_cwd"&&!Yt(F,ne.id,L.paranoid))return null;return Et(ne.id,ne.reason)}function Qo(M){let L=Rd(M,Lf,Lf,uv);return{expandedTargets:L&&"words"in L?L.words:void 0,unsafeBraceExpansion:L!==void 0&&"limited"in L,targetIsLiteral:L===void 0&&M.provenance==="literal"&&(M.quoted||M.raw!==M.text),tmpdirWordSplittingProtected:dv(M)}}function dv(M){let L=M.parts.filter((F)=>F.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(F.raw));return L.length>0&&L.every((F)=>fv(M.raw,F.span.start-M.span.start))}function fv(M,L){let F=null,q=!1;for(let ne=0;ne<L;ne++){let re=M[ne];if(q){q=!1;continue}if(re==="\\"&&F!=="'"){q=!0;continue}if(F===re){F=null;continue}if(F===null&&(re==="'"||re==='"'))F=re}return F==='"'}function ur(M){let L=M.environment.home,F=M.environment.paths,q=M.budget??Fn();return{anchoredCwd:M.originalCwd??M.cwd??null,resolvedCwd:M.cwd??null,strict:M.strict??!1,paranoid:M.paranoid??!1,trustTmpdirVar:M.allowTmpdirVar??!0,posixShell:M.posixShell??!1,tmpdirWordSplittingUnsafe:M.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:M.trustedTmpdirValue??M.allowTmpdirVar??!0,environment:M.environment,allowRoots:bv(M.allowPaths,L,F,q),protectedGitMetadata:M.protectedGitMetadata,budget:q}}function Mn(M,L,F={}){let q=F.targetIsLiteral??!1;if(!q&&L.tmpdirWordSplittingUnsafe&&!F.tmpdirWordSplittingProtected&&Cv(M))return{kind:"outside_anchored_cwd"};let ne=!q&&Ff(M,L.posixShell);if(rr(M))return{kind:"outside_anchored_cwd"};if(Tl(M,q))return{kind:"root_or_home_target"};if(pv(M,L,q))return{kind:"root_or_home_target"};if(L.resolvedCwd&&Ar(M,L.resolvedCwd,L.protectedGitMetadata,!0,L.environment,L.budget,!L.posixShell))return{kind:"git_metadata_target"};if(gv(M,L.trustTmpdirVar,L.posixShell,ne,q,F.tmpdirWordSplittingProtected??!1,L.trustedTmpdirValue,L.environment))return{kind:"temp_target"};if(ne)return{kind:"dynamic_target"};if(Sv(M,L,q))return{kind:"temp_target"};let re=L.anchoredCwd;if(re){if(!F.skipHomeCwd&&Rv(re,L.environment.home,L.environment.paths,L.budget))return{kind:"home_cwd_target"};if(!F.skipCwdSelf&&[L.resolvedCwd??re,re].some((ue)=>_v(M,L.resolvedCwd??re,L.environment.paths,L.budget,ue)))return{kind:"cwd_self_target"};if(wv(M,re,L.resolvedCwd??re,ne,q,L.environment.paths,L.budget))return{kind:"within_anchored_cwd"}}if(mv(M,L,ne))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function mv(M,L,F){let q=M.trim();if(F||!L.resolvedCwd||!L.anchoredCwd||!q)return!1;if(hs(q)||q.startsWith("~"))return!1;if(Il(q))return!1;if(zf(L.resolvedCwd,L.anchoredCwd,L.environment.paths,L.budget))return!1;return ro(Ir(L.resolvedCwd,q),L.environment)}function Gf(M,L,F={}){let{containmentTarget:q,...ne}=F;if(Mn(M,L,ne).kind!=="temp_target")return!1;let re=M.trim();if(yv(re))return!1;if(gs(re,L.environment))return!1;return![L.anchoredCwd,L.resolvedCwd].some((ue)=>zf(q??re,ue,L.environment.paths,L.budget))}function Tl(M,L=!1){let F=M.trim(),q=Wf.normalize(F),ne=F.replace(/\\/g,"/"),re=q==="/"?q:q.replace(/\/+$/,"");if(re==="/"||re.startsWith("/")&&re.slice(1).split("/").every((ue)=>/^\*+$/.test(ue)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(ne)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(ne))return!0;if(!L&&(q==="~"||q==="~/"||q==="~/*"))return!0;if(!L&&(q==="$HOME"||q==="$HOME/"||q==="$HOME/*"))return!0;if(!L&&(q==="${HOME}"||q==="${HOME}/"||q==="${HOME}/*"))return!0;return!1}function pv(M,L,F){let q=M.trim(),ne=F?q:q==="*"?".":q.endsWith("/*")?q.slice(0,-2):q;if(!ne)return!1;try{let re=hs(ne)?ne:L.resolvedCwd?Ir(L.resolvedCwd,ne):null;if(!re)return!1;let ue=fn(Dt(re,L.environment.paths,L.budget));if(ue===lv(ue).root)return!0;return ue===fn(Dt(L.environment.home,L.environment.paths,L.budget))}catch{return!1}}function fn(M){let L=av(M);if(cv){if(L=L.replace(/\//g,"\\").toLowerCase(),L.length>3&&L.endsWith("\\"))L=L.slice(0,-1);return L}if(L.length>1&&L.endsWith("/"))L=L.slice(0,-1);return L}function gv(M,L,F,q,ne,re,ue,Se){let ve=M.trim();if(Il(ve))return!1;if(!q&&ro(ve,Se))return!0;return(L||re&&ue)&&F&&!ne&&hv(ve,F)}function hv(M,L){return["$TMPDIR","${TMPDIR}"].some((F)=>{if(M===F)return!0;if(!M.startsWith(`${F}/`))return!1;return!Ff(M.slice(F.length+1),L)})}function yv(M){let L=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(M);if(!L)return!1;return Wf.normalize(`/${L[1]??""}`)==="/"}function Il(M){return M.split(/[\\/]+/).includes("..")}function bv(M,L,F,q){if(!M?.length)return[];return M.flatMap((ne)=>{let re=Mo(ne.trim(),L);if(!hs(re))return[];try{let ue=Dt(re,F,q);if(Do(ue,Dt(L,F,q)))return[];return[fn(ue)]}catch{return[]}})}function Sv(M,L,F){if(L.allowRoots.length===0)return!1;let q=M.trim();if(Il(q))return!1;let ne=F?q:Mo(q,L.environment.home),re=L.resolvedCwd??L.anchoredCwd,ue=hs(ne)?ne:re?Ir(re,ne):null;if(!ue)return!1;try{let Se=fn(Dt(ue,L.environment.paths,L.budget));return L.allowRoots.some((ve)=>Se===ve||Se.startsWith(ve.endsWith(Al)?ve:`${ve}${Al}`))}catch{return!1}}function Cv(M){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(M)}function Ff(M,L=!1){return M.includes("$")||M.includes("`")||vv(M)||L&&Ev(M)}function vv(M){let L=!1;for(let F of M){if(L){L=!1;continue}if(F==="\\"){L=!0;continue}if(F==="*"||F==="?"||F==="[")return!0}return!1}function Ev(M){let L=!1;for(let F=0;F<M.length;F++){let q=M[F];if(L){L=!1;continue}if(q==="\\"){L=!0;continue}if(q==="{"&&xv(M,F)||(q==="+"||q==="@"||q==="!")&&M[F+1]==="(")return!0}return!1}function xv(M,L){let F=M.indexOf("}",L+1);if(F===-1)return!1;let q=M.slice(L+1,F);return q.includes(",")||q.includes("..")}function Rv(M,L,F,q){try{return fn(Dt(M,F,q))===fn(Dt(L,F,q))}catch{try{return fn(M)===fn(L)}catch{return!1}}}function _v(M,L,F,q,ne=L){if(ne===L&&(M==="."||M==="./"||M===".\\"))return!0;try{return fn(Dt(Ir(L,M),F,q))===fn(Dt(ne,F,q))}catch{try{return fn(Ir(L,M))===fn(ne)}catch{return!1}}}function wv(M,L,F,q,ne,re,ue){let Se=F??L;if(!ne&&(M.startsWith("~")||M.startsWith("$HOME")||M.startsWith("${HOME}")))return!1;if(q)return!1;if(M.startsWith("/")||/^[A-Za-z]:[\\/]/.test(M))try{return Pl(M,L,re,ue)}catch{return!1}if(M.startsWith("./")||M.startsWith(".\\")||!M.includes("/")&&!M.includes("\\"))try{return Pl(Ir(Se,M),L,re,ue)}catch{return!1}if(M.startsWith("../"))return!1;try{return Pl(Ir(Se,M),L,re,ue)}catch{return!1}}function Pl(M,L,F,q){try{return Bf(Dt(M,F,q),Dt(L,F,q))}catch{return!1}}function zf(M,L,F,q){if(!L)return!1;try{return Bf(Dt(L,F,q),Dt(M,F,q))}catch{return!0}}function Bf(M,L){let F=fn(M),q=fn(L);return F.startsWith(`${q}${Al}`)||F===q}var Pv=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),$f="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Av="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.",Uf="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",Hf="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",Tv="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",Iv="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",kv={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:Hf},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:k},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:Uf},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:Tv},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:$f},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:Av},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:$f}};function jf(M,L,F){return Ov(M.words.map((q)=>({kind:"word",text:q.text,dynamic:q.provenance!=="literal"})),L,ur({...F,allowPaths:F.policy?.destructiveCommandAllowPaths}),F.policy)}function Ov(M,L,F,q){let ne=M.filter((ve)=>ve.kind==="word"),re=Dv(ne),ue=ne[re];if(!ue||!Pv.has(Uv(ue.text)))return null;let Se=Mv(ne.slice(re+1));if(Se.whatIfProtected)return null;if(Yt(q,"powershell.remove-item-pipeline-dynamic-target",F.strict)&&L&&(Se.targets.length===0||Se.recursive))return Et("powershell.remove-item-pipeline-dynamic-target",Iv);for(let ve of Se.targets)if(!rr(ve.text)&&Tl(Ol(ve.text)))return Et(Se.recursive&&Se.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Hf);for(let ve of Se.targets)if(F.resolvedCwd&&Ar(Ol(ve.text),F.resolvedCwd,F.protectedGitMetadata,Se.recursive,F.environment,F.budget,!0))return Et("powershell.remove-item-git-metadata",k);if(!Se.recursive||!Se.force)return null;if(Yt(q,"powershell.remove-item-recursive-force-dynamic-target",F.strict)&&(Se.hasDynamicTarget||Se.targets.length===0))return Et("powershell.remove-item-recursive-force-dynamic-target",Uf);for(let ve of Se.targets){let He=Jo(Mn(Ol(ve.text),F),F,q,kv);if(He)return He}return null}function Mv(M){let L=[],F=!1,q=!1,ne=!1,re=!1,ue=!1;for(let Se=0;Se<M.length;Se++){let ve=M[Se];if(!ve||ve.kind!=="word")continue;if(Nv(ve))continue;if(ue){L.push(kl(ve)),re=re||ve.dynamic;continue}if(ve.text==="--"){ue=!0;continue}let He=Wv(ve.text);if(!He){L.push(kl(ve)),re=re||ve.dynamic;continue}if(Gv(He.name)){let dt=He.value?Lv(He.value,ve):M[++Se];if(dt?.kind==="word"){L.push(kl(dt)),re=re||dt.dynamic;continue}re=!0;continue}if(Fv(He.name)){F=!0;continue}if(zv(He.name)){q=!0;continue}if(Bv(He.name))ne=$v(He.value)}return{targets:L,recursive:F,force:q,whatIfProtected:ne,hasDynamicTarget:re}}function Dv(M){let L=M[0];if(L?.kind==="word"&&L.text==="&"||L?.text===".")return M.length>1?1:0;return 0}function kl(M){return{text:M.kind==="word"?M.text:"",dynamic:M.kind==="word"&&M.dynamic}}function Nv(M){return M.kind==="word"&&M.text===","}function Ol(M){let L=M.replace(/\\/g,"/"),F=/^(?:\$env:(?:userprofile|home)|\$home|\$\{home\})(?=$|\/)/i.exec(L);return F?`$HOME${L.slice(F[0].length)}`:L}function Lv(M,L){return{kind:"word",text:M,dynamic:L.kind==="word"&&(L.dynamic||M.includes("$"))}}function Wv(M){if(!M.startsWith("-")||M==="-")return null;let L=M.slice(1),F=L.indexOf(":");if(F===-1)return{name:L.toLowerCase()};return{name:L.slice(0,F).toLowerCase(),value:L.slice(F+1)}}function Gv(M){return"path".startsWith(M)||"literalpath".startsWith(M)}function Fv(M){return"recurse".startsWith(M)}function zv(M){return M.length>=2&&"force".startsWith(M)}function Bv(M){return M==="wi"||"whatif".startsWith(M)}function $v(M){if(M===void 0||M==="")return!0;let L=M.toLowerCase();return L==="$true"||L==="true"}function Uv(M){return M.toLowerCase()}var io="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",ys="Unsupported heredoc syntax",ei="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.",Vf="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var Hv=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),jv=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),Vv=new Set(["-o","--output","--query","--subscription"]),Kv=new Set;function Kf(M){if(M==="aws")return Hv;if(M==="gcloud")return jv;if(M==="az")return Vv;return Kv}var qv=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),Yv=new Set;function qf(M){if(M==="git")return yn;if(M==="docker")return qv;return Yv}function A(M,L){if(M.length===0||L.length===0)return null;let F=It(M[0]??""),q=ln(M);for(let ne of L){if(!Jv(F,ne.command))continue;if(ne.match){if(Zv(F,M,ne.match))return Yf(ne);continue}if(!Qv(F,M,ne.subcommand))continue;if(tE(M,new Set(ne.block_args),q))return Yf(ne)}return null}function Yf(M){return{id:`custom.${M.name}`,reason:`[${M.name}] ${M.reason}`,intent:M.intent??"manual_only"}}function Zv(M,L,F){let q=L.slice(1);if(F.exclude_args?.some((ne)=>q.includes(ne)))return!1;if(F.any_args&&!F.any_args.some((ne)=>q.includes(ne)))return!1;return Xv(q,F.command_path,Kf(M))}function Xv(M,L,F){let q=0,ne=!1;for(let re of M){if(q>=L.length)return!0;if(ne){ne=!1;continue}if(re.startsWith("-")){ne=!re.includes("=")&&F.has(re);continue}if(re!==L[q])return!1;q++}return q>=L.length}function Jv(M,L){return M===It(L)}function Qv(M,L,F){if(!F)return!0;return Zf(L,1,F,qf(M))}function Zf(M,L,F,q){let ne=!1;for(let re=L;re<M.length;re++){let ue=M[re];if(!ue)continue;if(ne){ne=!1;continue}if(ue==="--"){let Se=M[re+1];if(Se&&!Se.startsWith("-"))return Se===F;return!1}if(q.has(ue)){ne=!0;continue}if(ue.startsWith("-")){if(!ue.includes("=")&&eE(M,re,F,q))return!0;continue}return ue===F}return!1}function eE(M,L,F,q){let ne=M[L+1];if(!ne||ne.startsWith("-"))return!1;return Zf(M,L+2,F,q)}function tE(M,L,F){return M.some((q)=>L.has(q))||[...F].some((q)=>L.has(q))}var nE=new Set(["-e","--source"]),rE=new Set(["-F","-v","--assign","--field-separator"]),Xf=new Set(["-f","--file"]),oE=new Set(["print","printf","return"]),Jf=[{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"}],iE="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 Qf(M,L,F){let q=!1;for(let ne of sE(M)){let re=aE(ne,F);if(!re)continue;for(let ue of re.commands){let Se=L(ue);if(Se)return Se;if(ue.includes("{}")||/[$`]/.test(ue))q=!0}q||=re.dynamic}return q?Et("awk.system-dynamic",iE):null}function Dl(M){let L=[],F=!1,q=!1,ne=!0,re=!0;for(let ue=1;ue<M.length;ue++){let Se=M[ue];if(Se===void 0)break;if(ne&&Se==="--"){ne=!1;continue}if(ne&&nE.has(Se)){F=!0;let ve=M[ue+1];if(re&&=ve!==void 0,ve!==void 0)L.push({tokenIndex:ue+1,kind:"inline-code",value:ve});ue++;continue}if(ne&&Se.startsWith("--source=")){F=!0,L.push({tokenIndex:ue,kind:"inline-code",value:Se.slice(9)});continue}if(ne&&Se.startsWith("-e")&&Se.length>2){F=!0,L.push({tokenIndex:ue,kind:"inline-code",value:Se.slice(2)});continue}if(ne&&(rE.has(Se)||Xf.has(Se))){let ve=M[ue+1];if(re&&=ve!==void 0,Xf.has(Se)){if(q=!0,ve!==void 0)L.push({tokenIndex:ue+1,kind:"program-file",value:ve})}ue++;continue}if(ne&&(Se.startsWith("-F")||Se.startsWith("-v")&&Se.slice(2).includes("=")))continue;if(ne&&Se.startsWith("-f")&&Se.length>2){q=!0,L.push({tokenIndex:ue,kind:"program-file",value:Se.slice(2)});continue}if(ne&&(Se.startsWith("--assign=")||Se.startsWith("--field-separator=")))continue;if(ne&&Se.startsWith("--file=")){q=!0,L.push({tokenIndex:ue,kind:"program-file",value:Se.slice(7)});continue}if(ne&&Se.startsWith("-")&&Se!=="-")continue;if(!F&&!q)L.push({tokenIndex:ue,kind:"main-program",value:Se});return{sources:L,optionsOpen:!1}}return{sources:re?L:[],optionsOpen:ne&&re}}function ni(M){return Dl(M).sources}function sE(M){return ni(M).filter((L)=>L.kind!=="program-file").map((L)=>L.value)}function aE(M,L){Cn(L,M);let F=M.includes("system")?Nl(M,L):null,q=lE(M,L);if(!F&&!q)return null;return{dynamic:!!F?.dynamic||!!q?.dynamic,commands:[...F?.commands??[],...q?.commands??[]]}}function Nl(M,L){Cn(L,M);let F=[],q=!1,ne=!1,re=0;while(re<M.length){let ue=M[re];if(ue==='"'||ue==="'"){re=Ss(M,re,ue)?.endIndex??re+1;continue}if(ue==="#"){re=em(M,re+1);continue}if(ue==="/"&&tm(M,re)){re=nm(M,re+1)??re+1;continue}if(!M.startsWith("system",re)){re++;continue}let Se=re;if(re+=6,ti(M[Se-1])||ti(M[re]))continue;let ve=bs(M,re);if(M[ve]!=="(")continue;ve=bs(M,ve+1);let He=M[ve];if(He!=='"'&&He!=="'"){q=!0,ne=!0;continue}let dt=Ss(M,ve,He);if(!dt){q=!0,ne=!0;continue}if(ve=bs(M,dt.endIndex),q=!0,M[ve]!==")"){ne=!0,re=dt.endIndex;continue}F.push(dt.value),re=ve+1}if(!q)return null;return{dynamic:ne,commands:F}}function lE(M,L){Cn(L,M);let F=[],q=!1,ne=!1,re=0,ue=0,Se=null,ve=null,He=0;while(re<M.length){let dt=M[re];if(!dt)break;if(dt==='"'||dt==="'"){let pt=Ss(M,re,dt);if(pt&&He===ue)ve={...pt,startIndex:re};He=pt?.endIndex??re+1,re=pt?.endIndex??re+1;continue}if(dt==="#"){re=em(M,re+1),ue=re,Se=null,ve=null,He=re;continue}if(dt==="/"&&tm(M,re)){let pt=nm(M,re+1);He=pt??re+1,re=pt??re+1;continue}if(`;
|
|
30
|
+
{}`.includes(dt)){re++,ue=re,Se=null,ve=null,He=re;continue}if(Se===null&&(Ml(M,re,"print")||Ml(M,re,"printf")))Se=re;if(dt!=="|"||M[re-1]==="|"||M[re+1]==="|"){if(!/\s/.test(dt))He=re+1;re++;continue}let mt=M[re+1]==="&"?re+2:re+1,ft=bs(M,mt);if(Ml(M,ft,"getline")){ne=!0;let pt=dE(ue,ve,He);if(q||=pt===null,pt!==null)F.push(pt);He=mt,re=mt;continue}if(mE(ue,Se)){ne=!0;let pt=uE(M,ft);if(!pt){q=!0,He=mt,re=mt;continue}if(!cE(M,pt.endIndex)){q=!0,He=pt.endIndex,re=pt.endIndex;continue}F.push(pt.value),He=pt.endIndex,re=pt.endIndex;continue}He=mt,re++}if(!ne)return null;return{dynamic:q,commands:F}}function ti(M){return!!M&&/[A-Za-z0-9_]/.test(M)}function bs(M,L){let F=L;while(/\s/.test(M[F]??""))F++;return F}function cE(M,L){let F=L;while(/[\t\f\v\r ]/.test(M[F]??""))F++;let q=M[F];return!q||`;
|
|
31
|
+
}#`.includes(q)}function Ss(M,L,F){let q="",ne=!1;for(let re=L+1;re<M.length;re++){let ue=M[re];if(!ue)break;if(ne){let Se=fE(M,re);if(!Se)return null;q+=Se.value,re=Se.endIndex,ne=!1;continue}if(ue==="\\"){ne=!0;continue}if(ue===F)return{value:q,endIndex:re+1};q+=ue}return null}function uE(M,L){let F=M[L];if(F!=='"'&&F!=="'")return null;return Ss(M,L,F)}function dE(M,L,F){if(!L)return null;return L.startIndex>=M&&L.endIndex===F?L.value:null}function fE(M,L){let F=M[L];if(!F)return null;if(F==="x"){let ne=M.slice(L+1,L+3);if(!/^[0-9A-Fa-f]{2}$/.test(ne))return null;return{value:String.fromCharCode(Number.parseInt(ne,16)),endIndex:L+2}}if(/[0-7]/.test(F)){let ne=/^[0-7]{1,3}/.exec(M.slice(L));if(!ne)return null;return{value:String.fromCharCode(Number.parseInt(ne[0],8)),endIndex:L+ne[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
|
|
32
|
+
`,r:"\r",t:"\t",v:"\v"}[F]??F,endIndex:L}}function Ml(M,L,F){return M.startsWith(F,L)&&!ti(M[L-1])&&!ti(M[L+F.length])}function mE(M,L){return L!==null&&L>=M}function em(M,L){let F=M.indexOf(`
|
|
33
|
+
`,L);return F===-1?M.length:F+1}function tm(M,L){let F=pE(M,L);if(F===-1)return!0;if("{([,;!~=".includes(M[F]??""))return!0;let q=F;while(ti(M[q-1]))q--;return oE.has(M.slice(q,F+1))}function pE(M,L){for(let F=L-1;F>=0;F--)if(!/\s/.test(M[F]??""))return F;return-1}function nm(M,L){let F=!1;for(let q=L;q<M.length;q++){let ne=M[q];if(!ne)break;if(F){F=!1;continue}if(ne==="\\"){F=!0;continue}if(ne==="/")return q+1}return null}var gE="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",hE="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",yE="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function rm(M){return M==="dd"||M==="shred"||M==="mkfs"||M.startsWith("mkfs.")}function om(M,L){let F=L.slice(1);if(M==="dd"&&F.some((q)=>/^of=\/dev\/.+/.test(q)))return Et("dd.device-write",gE);if((M==="mkfs"||M.startsWith("mkfs."))&&F.some((q)=>q.startsWith("/dev/")))return Et("mkfs.device",hE);if(M==="shred"&&F.length>0)return Et("shred.target",yE);return null}var bE=new Set(["sudo","env","command","builtin"]),SE=new Set(["caffeinate","exec","nice","nohup","setsid","stdbuf","time","timeout"]);function Cs(M,L){let F=M[0];if(!F||!im(wt(F),L))return null;let q=wt(F),ne=M[1]==="--"?2:1,re=CE(M,ne,q,L),ue=re[0];if(ue===void 0)return null;return{wrapper:q,tokens:M.slice(ue),childIndex:ue,alternativeChildIndices:re.slice(1)}}function CE(M,L,F,q){let ne=M[1]==="--",re=[];for(let ue=L;ue<M.length;ue++){let Se=M[ue];if(!Se)continue;let ve=wt(Se)!==F&&vE(Se,q);if(ve)re.push(ue);if(!ve&&Pi.has(It(Se)))break;if(ne)break}return re}function vE(M,L){let F=wt(M),q=It(M);return q==="git"||F==="busybox"||kr(M)||xa.has(F)||rm(q)||im(F,L)||Ht.has(q)||M==="$SHELL"||Tn(q)||Rn.has(q)||L.rules.some((ne)=>ne.command===F)}function im(M,L){return SE.has(M)||L.transparentWrappers.includes(M)}function kr(M){return bE.has(M.toLowerCase())}function Or(M,L){return{embedded:!1,cwd:M.cwd,originalCwd:L.originalCwd,effectiveCwd:M.cwd,envAssignments:M.envAssignments,allowTmpdirVar:L.allowTmpdirVar,worktreeMode:L.worktreeMode,wrappedByTransparent:!1}}function Dn(M,L){let F=L.policy??{rules:[],transparentWrappers:[]};return vs([...M],L.environment,L.cwd,L.cwd,new Map,new Map(L.envAssignments??[]),F,{iterations:0},!1)}function*vs(M,L,F,q,ne,re,ue,Se,ve){let He=is(M,L,F,re);for(let[pt,ht]of He.envAssignments)re.set(pt,ht),ne.set(pt,ht);let{tokens:dt,cwd:mt}=He;if(He.envSplitValues){let pt=os(He.envSplitValues,dt);if(!pt)throw new s("derivedCommandShape");Ll(Se),yield*vs(pt,L,mt,q,ne,re,ue,Se,ve);return}if(kr(dt[0]??""))throw new s("wrapperPeelIterations");let ft=Cs(dt,ue);if(ft){for(let pt of[ft.childIndex,...ft.alternativeChildIndices])Ll(Se),yield*vs(pt===ft.childIndex?ft.tokens:dt.slice(pt),L,mt,q,new Map(ne),new Map(re),ue,Se,!0);return}if(xE(dt)){Ll(Se),yield*vs(dt.slice(1),L,mt,q,ne,re,ue,Se,ve);return}yield EE(dt,mt,q,ne,re,ve)}function EE(M,L,F,q,ne,re){return{tokens:M,cwd:L===null?void 0:L??F,wrapperCwd:L,wrapperEnvAssignments:q,envAssignments:ne,head:wt(M[0]??"").toLowerCase(),wrappedByTransparent:re}}function Ll(M){if(M.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");M.iterations++}function xE(M){return wt(M[0]??"").toLowerCase()==="busybox"&&M.length>1}function Wl(M,L){let F=[],q=L;while(q<M.length){let ne=M[q];if(ne===void 0||ne===":::")break;F.push(ne),q++}return{markerIndex:q<M.length&&M[q]===":::"?q:-1,templateTokens:F}}function Xn(M){let L=!1,F=!1;for(let q of M){if(q==="--")break;if(q==="-r"||q==="-R"||Gl(q,"recursive")){L=!0;continue}if(q==="-f"||Gl(q,"force")){F=!0;continue}if(q.startsWith("-")&&!q.startsWith("--")){if(q.includes("r")||q.includes("R"))L=!0;if(q.includes("f"))F=!0}}return L&&F}function Es(M){let L=M.indexOf("--");return M.slice(1,L===-1?void 0:L).some((F)=>Gl(F,"recursive")||/^-[A-Za-z]+$/.test(F)&&/[rR]/.test(F.slice(1)))}function Gl(M,L){return M.length>2&&M.startsWith("--")&&L.startsWith(M.slice(2))}var RE=["--init-file","--rcfile"],_E=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function Nn(M){for(let L=1;L<M.length;L++){let F=M[L];if(!F)continue;if(F==="-c")return sm(M,L,!0);if(F.startsWith("-")&&F.includes("c")&&!F.startsWith("--")){let q=sm(M,L,!1);if(q!==null)return q}}return null}function Jn(M){let L=wt(M[0]??"").toLowerCase();if(L==="zsh"||L==="ksh")return bn(M).syntaxCheck;let F=!1;for(let q of M.slice(1)){if(q==="--")return F;if(q.startsWith("+")&&!q.startsWith("++")){if(q.slice(1).includes("n"))F=!1;continue}if(!q.startsWith("-")||q.startsWith("--"))return F;let ne=q.slice(1);if(ne.includes("n"))F=!0;if(ne.includes("c"))return F}return F}function sm(M,L,F){if(M[L+1]==="--")return M[L+2]||null;let q=M[L+1];if(!q||!F&&q.startsWith("-"))return null;return q}function am(M){let L=wt(M[0]??"").toLowerCase(),F=wE(M,L),q=_E.get(L)??null,ne=F.argvSource?.kind!=="absent";return{argvSource:L==="bash"?F.argvSource:null,argvSourceApplies:L==="bash"&&F.interactive&&F.argvSource?.kind==="literal",envName:q,envSourceApplies:ne&&(q==="BASH_ENV"?!F.interactive:q==="ENV"&&F.interactive)}}function wE(M,L){let F=bn(M),q=F.commandIndex??F.scriptIndex??M.length,ne=[],re=!1,ue=!0;for(let Se=1;Se<q;Se++){let ve=M[Se];if(ve===void 0||ve==="--"||ve==="-"||ve[0]!=="-"&&ve[0]!=="+")break;if(ve.startsWith("--")){if(L==="bash"&&ue?RE.find((ft)=>ve===ft):void 0){let ft=M[Se+1];ne.push(ft===void 0?{kind:"absent"}:{kind:"literal",value:ft}),Se++;continue}let mt=ve.split("=",1)[0]??ve;if(L==="bash"&&va.has(mt)&&!ve.includes("="))Se++;continue}if(L==="bash")ue=!1;let He=Ea(L,ve,M[Se+1],"startup");if(He.interactive)re=ve[0]==="-";Se+=He.followingValues}return{argvSource:ne.at(-1)??null,interactive:re}}var PE="find -delete permanently removes files. Use -print first to preview.",AE="find -exec rm -rf is dangerous. Use explicit file list instead.",TE=new Set(["-exec","-execdir","-ok","-okdir"]),IE=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((M)=>[M,1]),["-fprintf",2]]);function lm(M,L){let F=M.map(t),q=kE(M,F,L);if(q)return q;if(xs(F,1)&&!WE(M,F,L)){let ue=_t(Et("find.delete",PE),L.policy);if(ue)return ue}let ne=L.budget??Fn(),re=0;while(re<F.length){let ue=F[re],Se=Qn(ue??"");if(Se>0){re+=Se+1;continue}if(!Bn(ue)){re++;continue}ne.charge("derivedTokens",F.length-re-1);let ve=so(F,re);re=ve.nextIndex;let He=FE(ve.tokens,L.environment);if(He){let pt=_t(He,L.policy);if(pt)return pt}let dt=ue==="-execdir"||ue==="-okdir",mt=L.analyzeTokens?.(ve.tokens,dt?null:L.cwd)??null,ft=mt?.id.startsWith("custom.")?mt:_t(mt,L.policy);if(ft)return ft}return null}function kE(M,L,F){if(!xs(L,1)&&!Fl(L,F.environment))return null;let ne=ri(M)??Ut(["."]),re=ur({...F,allowPaths:F.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let ue of ne){let Se=Qo(ue);for(let ve of Se.expandedTargets??[t(ue)]){let He=Mn(ve,re,{targetIsLiteral:Se.expandedTargets!==void 0||Se.targetIsLiteral,tmpdirWordSplittingProtected:Se.tmpdirWordSplittingProtected});if(He.kind==="root_or_home_target")return Et("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(He.kind==="git_metadata_target"&&!OE(M,re.protectedGitMetadata,F.environment))return Et("find.delete-git-metadata",k)}}if(LE(L)&&re.resolvedCwd&&Pf(ne.map(t),re.resolvedCwd,re.protectedGitMetadata,re.environment,re.budget))return Et("find.delete-git-metadata",k);return null}function OE(M,L,F){if(!L)return!1;let q=M.map(t),ne=[],re=!1,ue=ri(M)?.at(-1),Se=ue?M.indexOf(ue)+1:1;while(Se<q.length){let ve=q[Se]??"";if(Bn(ve)){let He=so(q,Se),dt=lr([...He.tokens],F),mt=Es(dt),ft=Ht.has(wt(dt[0]??"").toLowerCase()),pt=He.tokens.some((gt)=>gt!=="{}"&>.includes("{}")),ht=(ve==="-execdir"||ve==="-okdir")&&dt.slice(1).some((gt)=>gt!=="{}"&&!gt.startsWith("-"));if(mt||ft||pt||ht)return!1;re=!0,Se=He.nextIndex;continue}if(ve==="-delete"){re=!0,Se++;continue}if(ve==="-name"||ve==="-iname"){let He=M[Se+1];if(!(He?.provenance==="literal"&&!/[[\\]/.test(He.text)))return!1;if(!re)ne.push(DE(He.text,ve==="-iname"));Se+=2;continue}if(!ME.has(ve))return!1;Se+=1+Qn(ve)}return ne.length>0&&!Tf(L,(ve)=>ne.every((He)=>He.test(ve)))}var ME=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function DE(M,L){let F=M.replace(/[*?]|[.+^${}()|\]/]/g,(q)=>q==="*"?".*":q==="?"?".":`\\${q}`);return new RegExp(`^${F}$`,L?"isu":"su")}var NE=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function Fl(M,L){let F=0;while(F<M.length){if(!Bn(M[F])){F++;continue}let q=so(M,F),ne=lr([...q.tokens],L),re=wt(ne[0]??"").toLowerCase(),ue=Ht.has(re)&&NE.test((Nn(ne)??"").replace(/["'\\]/g,""));if((re==="rm"||re==="rmdir"||ue)&&ne.some((ve)=>ve.includes("{}")))return!0;F=q.nextIndex}return!1}function LE(M){return M.some((L,F)=>{if(!["-name","-iname"].includes(L))return!1;return M[F+1]?.toLowerCase()==="hooks"})}function WE(M,L,F){if(L.includes("-L")||L.includes("-f")||L.includes("-follow"))return!1;let q=ri(M);if(!q)return!1;let ne=F.envAssignments??new Map,re=wl(ne,F.environment),ue=F.trustedTmpdirValue??no(ne,F.environment),Se=F.allowTmpdirVar??!Xo(ne,F.environment),ve={environment:F.environment,protectedGitMetadata:F.protectedGitMetadata,cwd:F.cwd,originalCwd:F.originalCwd,strict:F.strict,allowTmpdirVar:Se&&ue&&Boolean(re),allowPaths:F.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:F.tmpdirWordSplittingUnsafe??Tr(ne,F.environment),trustedTmpdirValue:ue,budget:F.budget},He=ur(ve),dt=ur({...ve,cwd:F.originalCwd??F.cwd}),mt=F.originalCwd&&F.environment.paths.realpath(F.originalCwd),ft=F.cwd&&F.environment.paths.realpath(F.cwd),pt=mt&&ft&&!oo(ft,mt)?F.cwd:void 0;return q.every((ht)=>{let gt=Qo(ht);if(gt.unsafeBraceExpansion)return!1;return(gt.expandedTargets??[t(ht)]).every((yt)=>{let St=/^\.\/*$/.test(yt)?pt:void 0,Ct=St??yt,bt={targetIsLiteral:gt.expandedTargets!==void 0||gt.targetIsLiteral,tmpdirWordSplittingProtected:gt.tmpdirWordSplittingProtected};if(!Yt(F.policy,"rm.recursive-force-paranoid",F.paranoid??!1)&&!St&&Mn(Ct,He,bt).kind==="within_anchored_cwd")return!0;return Gf(Ct,St?dt:He,{...bt,containmentTarget:GE(Ct,re)})})})}function GE(M,L){if(!L)return M;return M.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>L)}function ri(M){let L=(ne)=>{let re=M[ne];return re?t(re):void 0},F=1;while(L(F)==="-H"||L(F)==="-P")F++;if(L(F)==="--")F++;let q=[];while(F<M.length){let ne=L(F),re=M[F];if(!ne||!re||ne.startsWith("-")||["!","(",")"].includes(ne))break;q.push(re),F++}return q.length>0?q:null}function FE(M,L){let F=ar([...M],L);if(F.length===0)return null;let q=wt(F[0]??"");if(q==="busybox"&&F.length>1)F=F.slice(1),q=wt(F[0]??"");if(q==="rm"&&Xn(F))return Et("find.exec-rm-recursive-force",AE);return null}function so(M,L){let F=L+1;while(F<M.length&&M[F]!==";"&&!(M[F]==="+"&&M[F-1]==="{}"))F++;return{tokens:M.slice(L+1,F),nextIndex:Math.min(F+1,M.length)}}function xs(M,L){let F=L;while(F<M.length){let q=M[F];if(!q){F++;continue}if(Bn(q)){F=so(M,F).nextIndex;continue}let ne=Qn(q);if(ne>0){F+=ne+1;continue}if(q==="-delete")return!0;F++}return!1}function Qn(M){return IE.get(M)??(/^-newer[A-Za-z]{2}$/.test(M)?1:0)}function Bn(M){return M!==void 0&&TE.has(M)}import{resolve as pR}from"node:path";function*zl(M){for(let L of M.nodes)yield*BE(L)}function zE(M){return Object.freeze([...zl(M)])}function ut(M){return Object.freeze(zE(M).map((L)=>Object.freeze(L.words.map((F)=>F.text))))}function oi(M){let L=h(M,"posix");if(L.status!=="complete"||L.nodes.length!==1)return null;let F=L.nodes[0];if(F?.kind!=="command")return null;if(F.redirections.length>0||F.nested.length>0)return null;if(F.words.some((q)=>q.provenance==="command-substitution"))return null;return F.words.map((q)=>q.text)}function*BE(M){if(M.kind==="command"){yield M;for(let L of M.nested)yield*zl(L);return}if(M.kind==="group")yield*zl(M.body)}var $E=5,Bl="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 en(M){let L=M.indexOf("--");if(L===-1)return{index:-1,before:M,after:[]};return{index:L,before:M.slice(0,L),after:M.slice(L+1)}}function um(M,L,F){let q=Rs(M,L,F),ne=UE(q.entries);if(ne.size===0)return{blockedReason:q.blockedReason,expanded:!1,tokens:M};let re=M,ue=!1;for(let Se=0;Se<$E;Se++){let{subcommand:ve,rest:He}=vn(re),dt=ve?.toLowerCase();if(!dt||!ne.has(dt))return{blockedReason:q.blockedReason,expanded:ue,tokens:re};let mt=ne.get(dt),ft=qE(mt);if(ft===null||ft.length===0)return{blockedReason:Bl,expanded:!0,tokens:re};re=["git",...ft,...He],ue=!0}return{blockedReason:Bl,expanded:!0,tokens:re}}function dm(M,L,F){return Rs(M,L,F).entries.some((q)=>q.key.toLowerCase()==="core.sshcommand")}function vn(M){if(M.length===0)return{subcommand:null,rest:[]};let L=M[0];if((L?wt(L).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let q=1;while(q<M.length){let ne=M[q];if(!ne)break;if(ne==="--"){let re=M[q+1];if(re&&!re.startsWith("-"))return{subcommand:re,rest:M.slice(q+2)};return{subcommand:null,rest:M.slice(q+1)}}if(!ne.startsWith("-"))return{subcommand:ne,rest:M.slice(q+1)};q+=yn.has(ne)?2:1}return{subcommand:null,rest:[]}}function UE(M){let L=new Map;for(let F of M){let q=F.key.toLowerCase();if(!q.startsWith("alias."))continue;let ne=q.slice(6);if(ne!=="")L.set(ne,F.value)}return L}function Rs(M,L,F){if(M.length===0)return{blockedReason:null,entries:[]};let q=M[0];if((q?wt(q).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let re=jE(L,F);return{blockedReason:re.blockedReason,entries:[...re.entries,...HE(M,L,F)]}}function HE(M,L,F){let q=[],ne=1;while(ne<M.length){let re=M[ne];if(!re||re==="--"||!re.startsWith("-"))return q;if(re==="-c"){let ue=$l(M[ne+1]);if(ue)q.push(ue);ne+=2;continue}if(re.startsWith("-c")&&re.length>2){let ue=$l(re.slice(2));if(ue)q.push(ue);ne++;continue}if(re==="--config-env"){let ue=cm(M[ne+1],L,F);if(ue)q.push(ue);ne+=2;continue}if(re.startsWith("--config-env=")){let ue=cm(re.slice(13),L,F);if(ue)q.push(ue);ne++;continue}if(yn.has(re)){ne+=2;continue}ne++}return q}function jE(M,L){let F=VE(M,L),q=KE(M,L);return{blockedReason:F===null||q===null?Bl:null,entries:[...F??[],...q??[]]}}function VE(M,L){let F=Yn("GIT_CONFIG_PARAMETERS",M,L);if(F===void 0)return[];let q=[],ne=oi(F);if(!ne)return null;for(let re of ne){let ue=$l(re);if(!ue)return null;q.push(ue)}return q}function KE(M,L){let F=ef(M,L);if(F.state==="absent")return[];if(F.state==="invalid")return null;let q=[];for(let ne=0;ne<F.count;ne++){let re=Yn(`GIT_CONFIG_KEY_${ne}`,M,L)?.trim(),ue=Yn(`GIT_CONFIG_VALUE_${ne}`,M,L);if(!re||ue===void 0)return null;q.push({key:re,value:ue})}return q}function $l(M){if(!M)return null;let L=M.indexOf("=");return{key:(L===-1?M:M.slice(0,L)).trim(),value:L===-1?void 0:M.slice(L+1)}}function cm(M,L,F){let q=M?.indexOf("=")??-1;if(!M||q===-1)return null;return{key:M.slice(0,q).trim(),value:Yn(M.slice(q+1),L,F)}}function qE(M){let L=M?.trimStart();if(!L||L.startsWith("!"))return null;return oi(L)}var YE="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",ZE="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",XE="git checkout --force discards uncommitted changes. Use 'git stash' first.",JE="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",QE="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",ex="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",tx="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",nx="git switch --force discards uncommitted changes. Use 'git stash' first.",rx="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",ox="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",ix="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",sx="git reset --merge can lose uncommitted changes. Use 'git stash' first.",ax="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",lx="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.",cx="git push --force destroys remote history. Use --force-with-lease for safer force push.",ux="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",dx="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",fx="git branch -D force-deletes without merge check. Use -d for safe delete.",mx="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",px="git merge --abort discards merge conflict resolutions. Use 'git status' first.",gx="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",hx="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",yx="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",bx="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",Sx="git worktree remove --force can delete uncommitted changes. Remove --force flag.",Cx=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),vx=new Set(["--recurse-submodules","--track","-t"]),Ul=new Set(["-b","-B","-U"]),Hl=new Set(["-c","-C"]),Ex=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function kt(M,L){let F=M.split("=",1)[0]??M;return F.length>=4&&L.startsWith(F)&&F.startsWith("--")&&F.slice(2).length>=2}var ao=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function mm(M,L){let{subcommand:F,rest:q}=vn(M);if(!F)return null;switch(F.toLowerCase()){case"checkout":return dr(xx(q,L));case"switch":return dr(_x(q));case"restore":return dr(Px(q));case"reset":return Tx(q);case"clean":return dr(kx(q));case"rm":return dr(Ox(q));case"push":return Mr(Mx(q));case"branch":return Mr(Lx(q));case"stash":return Mr(Bx(q));case"worktree":return Mr($x(q));case"rebase":return dr(Wx(q));case"merge":return dr(Gx(q));case"tag":return Mr(Fx(q));case"reflog":return Mr(zx(q));default:return null}}function dr(M){return M?{...M,localDiscard:!0}:null}function Mr(M){return M?{...M,localDiscard:!1}:null}function xx(M,L){let{index:F,before:q}=en(M),ne=ln(q,{shortOptsWithValue:Ul});if(q.some((Se)=>kt(Se,"--force"))||ne.has("-f"))return Et("git.checkout-force",XE);for(let Se of M){if(Se==="-b"||Se==="-B"||Se==="--orphan")return null;if(kt(Se,"--pathspec-from-file"))return Et("git.checkout-pathspec-from-file",QE)}if(F!==-1){if(q.some((ve)=>!ve.startsWith("-")))return Et("git.checkout-ref-path",JE);return Et("git.checkout-double-dash",YE)}let re=wx(M);if(re.length>=2)return Et("git.checkout-ambiguous",ex);let ue=re[0];if(ue===void 0||ne.has("-d")||ne.has("-t")||M.some((Se)=>kt(Se,"--detach")||kt(Se,"--track")))return null;if(Rx(ue)||L(ue))return Et("git.checkout-double-dash",ZE);return null}function Rx(M){return M==="."||M===".."||/^\.\.?[/\\]/.test(M)||/^([/\\]|[A-Za-z]:[/\\])/.test(M)||M.endsWith("/")||M.startsWith(":")||/[*?[]/.test(M)}function _x(M){let{before:L}=en(M);if(L.some((q)=>kt(q,"--discard-changes")))return Et("git.switch-discard-changes",tx);let F=ln(L,{shortOptsWithValue:Hl});if(L.some((q)=>kt(q,"--force"))||F.has("-f"))return Et("git.switch-force",nx);return null}function wx(M){let L=[],F=0;while(F<M.length){let q=M[F];if(!q)break;if(q==="--")break;if(!q.startsWith("-")){L.push(q),F++;continue}if(Cx.has(q)){F+=2;continue}if(vx.has(q)){let ne=M[F+1],re=q==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"];F+=ne&&!ne.startsWith("-")&&re.includes(ne)?2:1;continue}F++}return L}function Px(M){let L=Ax(M);if(L.isTerminal||!L.hasPathspec&&!L.hasPatch||!L.hasWorktree)return null;return L.hasExplicitLocation?Et("git.restore-worktree",ox):Et("git.restore-unstaged",rx)}function Ax(M){let L=!1,F=!1,q=!0,ne=!1,re=(ue)=>{if(!ne)q=!1,ne=!0;if(ue!==void 0)q=ue};for(let ue=0;ue<M.length;ue++){let Se=M[ue];if(Se===void 0)break;if(Se==="--"){L||=ue+1<M.length;break}if(Se==="--pathspec-from-file"){L=!0,ue++;continue}if(Se.startsWith("--pathspec-from-file=")){L=!0;continue}if(Se==="-h"||Se==="--help"||Se==="--version")return{hasPathspec:L,hasPatch:F,hasWorktree:q,hasExplicitLocation:ne,isTerminal:!0};if(Se==="--staged"){re();continue}if(Se==="--no-staged"){re();continue}if(Se==="--worktree"){re(!0);continue}if(Se==="--no-worktree"){re(!1);continue}if(Se==="--patch"){F=!0;continue}if(Se==="--no-patch"){F=!1;continue}if(Ex.has(Se)){ue++;continue}if(Se.startsWith("--"))continue;if(Se==="-"){L=!0;continue}if(!Se.startsWith("-")){L=!0;continue}for(let ve=1;ve<Se.length;ve++){let He=Se.charAt(ve);if(He==="h")return{hasPathspec:L,hasPatch:F,hasWorktree:q,hasExplicitLocation:ne,isTerminal:!0};if(He==="S"){re();continue}if(He==="W"){re(!0);continue}if(He==="p"){F=!0;continue}if(He==="s"||He==="U"){if(ve===Se.length-1)ue++;break}}}return{hasPathspec:L,hasPatch:F,hasWorktree:q,hasExplicitLocation:ne,isTerminal:!1}}function Tx(M){let L=null;for(let F of M){if(kt(F,"--hard")){L=Et("git.reset-hard",ix);break}if(kt(F,"--merge")){L=Et("git.reset-merge",sx);break}}if(!L)return null;return Ix(M)?Mr(L):dr(L)}function Ix(M){for(let L of M){if(L==="--")return!1;if(!L.startsWith("-"))return!0}return!1}function kx(M){for(let F of M)if(F==="-n"||kt(F,"--dry-run"))return null;let L=ln(M.filter((F)=>F!=="--"));if(M.some((F)=>kt(F,"--force"))||L.has("-f"))return Et("git.clean-force",ax);return null}function Ox(M){let L=!1,F=!1,q=!1;for(let ne of en(M).before){if(kt(ne,"--no-force")){L=!1;continue}if(kt(ne,"--force")){L=!0;continue}if(kt(ne,"--no-cached")){F=!1;continue}if(kt(ne,"--cached")){F=!0;continue}if(kt(ne,"--no-dry-run")){q=!1;continue}if(kt(ne,"--dry-run")){q=!0;continue}let re=ln([ne]);L||=re.has("-f"),q||=re.has("-n")}return L&&!F&&!q?Et("git.rm-force",lx):null}function Mx(M){let{before:L,after:F}=en(M),q=ln(L);if(L.some((ue)=>kt(ue,"--mirror")))return Et("git.push-mirror",dx);if(L.some((ue)=>kt(ue,"--force"))||q.has("-f")||fm(L,F).some(Dx))return Et("git.push-force",cx);if(L.some((ue)=>kt(ue,"--delete"))||q.has("-d")||fm(L,F).some(Nx))return Et("git.push-delete",ux);return null}function fm(M,L){return[...M.filter((F)=>F!==""&&!F.startsWith("-")),...L]}function Dx(M){return M.startsWith("+")||M.includes(":+")}function Nx(M){return M.length>1&&M.startsWith(":")}function Lx(M){let{before:L}=en(M),F=ln(L),q=F.has("-D")||F.has("-d")||L.some((re)=>kt(re,"--delete")),ne=F.has("-D")||F.has("-f")||L.some((re)=>kt(re,"--force"));if(q&&ne)return Et("git.branch-force-delete",fx);return null}function Wx(M){let{before:L}=en(M);return L.some((F)=>kt(F,"--abort"))?Et("git.rebase-abort",mx):null}function Gx(M){let{before:L}=en(M);return L.some((F)=>kt(F,"--abort"))?Et("git.merge-abort",px):null}function Fx(M){let{before:L}=en(M);return ln(L).has("-d")||L.some((q)=>kt(q,"--delete"))?Et("git.tag-delete",gx):null}function zx(M){return M[0]==="delete"?Et("git.reflog-delete",hx):null}function Bx(M){for(let L of M){if(L==="drop")return Et("git.stash-drop",yx);if(L==="clear")return Et("git.stash-clear",bx)}return null}function $x(M){let{before:L}=en(M);if(!L.includes("remove"))return null;let q=ln(L);if(L.some((ne)=>kt(ne,"--force"))||q.has("-f"))return Et("git.worktree-remove-force",Sx);return null}import{dirname as cR,isAbsolute as uR,join as Am,resolve as dR}from"node:path";var Vl="TMPDIR",Kl="IFS",gm=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,hm=/^[A-Za-z_][A-Za-z0-9_]*$/,ym=new Set(["export","typeset","declare","readonly"]),Ux=new Set(["builtin","command","time"]),Hx=new Set(["do","then","else"]),jx=new Set(["do","then","case"]),pm=new Set(["done","fi","esac"]),Vx=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function bm(M,L){return M.map((F)=>F.provenance==="variable"&&_m(F.text)?Sm(F.text,L.shellAssignments):t(F))}function Sm(M,L){return M.replace(Vx,(F,q,ne)=>L.get(q??ne??"")??F)}function $n(M,L){let F=M.parts.every((ne)=>ne.provenance!=="literal"||!/[$`]/.test(ne.raw));if(M.provenance!=="variable"||!F)return null;let q=Sm(M.text,L);return/^[~-]/.test(q)||/[\s$`*?[]/.test(q)?null:q}function Cm(M,L){return{env:M,effectiveEnvAssignments:Zx(M,L),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function vm(M){return{env:M.env,effectiveEnvAssignments:M.effectiveEnvAssignments?new Map(M.effectiveEnvAssignments):void 0,shellAssignments:new Map(M.shellAssignments),bodyDepth:M.bodyDepth,bodyAssignments:new Set(M.bodyAssignments)}}function ql(M,L){let F=xm(M,L),q=M[0]??"";if(jx.has(q))L.bodyDepth+=1;if(q==="elif"||pm.has(q))L.bodyDepth=Math.max(0,L.bodyDepth-1);if(pm.has(q)&&L.bodyDepth===0)L.bodyAssignments.forEach((Se)=>{L.shellAssignments.delete(Se)}),L.bodyAssignments.clear();F.assignments.filter((Se)=>Se.persists).forEach((Se)=>{if(L.shellAssignments.set(Se.name,Se.value),L.bodyDepth>0)L.bodyAssignments.add(Se.name);Yl(L,Se)});let ne=F.commandIndex;if(ne!==-1&&ym.has(M[ne]??""))M.filter((Se)=>hm.test(Se)&&jl(Se)).forEach((Se)=>{Xx(L,Se)});let re=ne===-1?-1:Rm(M,ne);if(re===-1||M[re]!=="unset")return;let ue=Qx(M,re);if(ue===null)return;M.slice(ue).forEach((Se)=>{if(L.bodyDepth>0){L.shellAssignments.set(Se,"");return}Jx(L,Se)})}function Em(M,L){let F=xm(M,L).assignments;if(F.length===0)return L.effectiveEnvAssignments;let q=new Map(L.effectiveEnvAssignments??[]);return F.forEach((ne)=>{q.set(ne.name,ne.value)}),q}function xm(M,L){let F=Hx.has(M[0]??"")?1:0,q=M.findIndex((Se,ve)=>ve>=F&&!_m(Se)),ne=q!==-1&&ym.has(M[Rm(M,q)]??""),re=Yx(L);return{assignments:M.flatMap((Se,ve)=>{let He=Kx(Se,re,L.env);if(!He)return[];if(q!==-1&&ve>q&&!ne&&!ns(He.name))return[];return re.set(He.name,He.value),[{...He,persists:q===-1||ne}]}),commandIndex:q}}function Rm(M,L){let F=L;while(Ux.has(M[F]??"")){F+=1;while(M[F]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(M[F]??""))return L;F+=1}}return F}function _m(M){return wn(M)!==null||gm.test(M)}function Kx(M,L,F){return wn(M)??qx(M,L,F)}function qx(M,L,F){let q=rs(M,F,L);if(q)return q;let ne=M.match(gm)?.[1];if(!ne)return null;let re=M.indexOf("=");return{name:ne,value:`${L.has(ne)?L.get(ne):F.get(ne)??""}${M.slice(re+1)}`}}function jl(M){return M===Vl||M===Kl||yl(M)}function Yx(M){return new Map([...M.effectiveEnvAssignments??[],...M.shellAssignments])}function Zx(M,L){let F=[Vl,Kl].map((q)=>{let ne=M.get(q);return ne===void 0?null:[q,ne]}).filter((q)=>q!==null);if(F.length===0)return L;return new Map([...F,...L??[]])}function Yl(M,L){let F=new Map(M.effectiveEnvAssignments??[]);F.set(L.name,L.value),M.effectiveEnvAssignments=F}function Xx(M,L){Yl(M,{name:L,value:M.shellAssignments.get(L)??M.effectiveEnvAssignments?.get(L)??M.env.get(L)??""})}function Jx(M,L){if(!jl(L)&&!hm.test(L))return;if(M.shellAssignments.set(L,""),ns(L)&&M.env.has(L)){let q=new Map(M.env);q.delete(L),M.env=q}if(!jl(L)||L===Vl||L===Kl||_o(L)){Yl(M,{name:L,value:""});return}if(!M.effectiveEnvAssignments?.has(L))return;let F=new Map(M.effectiveEnvAssignments);F.delete(L),M.effectiveEnvAssignments=F.size===0?void 0:F}function Qx(M,L){let F=L+1;while(F<M.length){let q=M[F];if(!q)return null;if(q==="--")return F+1;if(q==="-v"){F++;continue}if(q.startsWith("-"))return null;return F}return F}import{resolve as eR}from"node:path";function _s(M,L){return hl.some((F)=>L?.has(F)||M.has(F))}function lo(M,L,F){if(!L)return{gitCwd:null,hasExplicitGitContext:!1};let q=F.realpath(eR(L));if(q===null||!F.isDirectory(q))return{gitCwd:null,hasExplicitGitContext:!1};let ne=q,re=!1,ue=1;while(ue<M.length){let Se=M[ue];if(!Se)break;if(Se==="--")break;if(!Se.startsWith("-"))break;if(Se==="-C"){let ve=M[ue+1];if(!ve)return{gitCwd:null,hasExplicitGitContext:re};let He=wm(ne,ve,F);if(!He)return{gitCwd:null,hasExplicitGitContext:re};ne=He,ue+=2;continue}if(Se.startsWith("-C")&&Se.length>2){let ve=wm(ne,Se.slice(2),F);if(!ve)return{gitCwd:null,hasExplicitGitContext:re};ne=ve,ue++;continue}if(Se==="--git-dir"||Se==="--work-tree"){re=!0,ue+=2;continue}if(Se.startsWith("--git-dir=")||Se.startsWith("--work-tree=")){re=!0,ue++;continue}ue+=yn.has(Se)?2:1}return{gitCwd:ne,hasExplicitGitContext:re}}function wm(M,L,F){try{let q=sr(M,L,F);return F.isDirectory(q)?q:null}catch{return null}}function Pm(M,L,F){if(!L.localDiscard||!F.worktreeMode||_s(F.environment.env,F.envAssignments))return null;let q=lo(M,F.cwd,F.environment.paths);if(!q.gitCwd||q.hasExplicitGitContext)return null;let ne=F.environment.worktreeFacts(q.gitCwd);if(!ne)return null;if(Zl(M,F,ne))return null;return{kind:"worktree",originalReason:L.reason,gitCwd:q.gitCwd}}function Zl(M,L,F){let{subcommand:q,rest:ne}=vn(M),re=q?.toLowerCase();if(L.dynamicArguments||tR(ne)||sR(M,L.environment.env,L.envAssignments,F)||oR(ne)||nR(re,ne))return!0;return re==="clean"&&iR(ne)>1}function tR(M){return M.some((L)=>/[$*?[]/.test(L))}function nR(M,L){if(M==="checkout"){let{before:F}=en(L),q=ln(F,{shortOptsWithValue:Ul}),ne=F.some((ue)=>kt(ue,"--force"))||q.has("-f"),re=q.has("-B")||F.some((ue)=>ue==="-B"||ue.startsWith("-B"));return ne&&re}if(M==="switch"){let{before:F}=en(L),q=ln(F,{shortOptsWithValue:Hl}),ne=F.some((ue)=>kt(ue,"--force"))||F.some((ue)=>kt(ue,"--discard-changes"))||q.has("-f"),re=F.some((ue)=>ue==="-C"||ue.startsWith("-C")||rR(ue))||q.has("-C");return ne&&re}return!1}function rR(M){let L=M.split("=",1)[0]??M;return L==="--force-create"||L.length>=9&&"--force-create".startsWith(L)}function oR(M){return M.some((L)=>L.startsWith("--recurse-sub"))}function iR(M){let L=0;for(let F of M){if(F==="--force"){L++;continue}if(F.startsWith("-")&&!F.startsWith("--")){for(let q of F.slice(1))if(q==="f")L++}}return L}function sR(M,L,F,q){if(Yn("GIT_CONFIG_PARAMETERS",L,F)!==void 0)return!0;let ne=Rs(M,L,F);if(ne.blockedReason!==null)return!0;let re=ne.entries.map((Se)=>({key:Se.key.toLowerCase(),value:Se.value}));if(re.some((Se)=>lR(Se.key)))return!0;let ue=re.filter((Se)=>Se.key==="submodule.recurse").at(-1);if(ue)return ue.value===void 0||aR(ue.value);if(nf(F))return!0;return q.recursiveSubmodules}function aR(M){let L=M.toLowerCase();return L!=="false"&&L!=="no"&&L!=="off"&&L!=="0"}function lR(M){return M==="include.path"||M.startsWith("includeif.")&&M.endsWith(".path")}function Tm(M,L,F){let q=M.map((ve)=>$n(ve,F.shellAssignments??new Map)??t(ve)),ne=F.environment.paths,re=lo(q,F.cwd,ne),ue=F.originalCwd?ne.realpath(dR(F.originalCwd)):null;if(L.id.startsWith("git.push-")||ue===null||re.gitCwd===null||re.hasExplicitGitContext||_s(F.environment.env,F.envAssignments))return null;let Se=L.id==="git.worktree-remove-force"?mR(M,F.shellAssignments,ne):Im(re.gitCwd,ne);if(Se===null||L.id!=="git.worktree-remove-force"&&!fR(Se,q,L,F)||!ro(Se,F.environment)||gs(Se,F.environment)||oo(ue,Se)||oo(Se,ue))return null;return{kind:"temp-root",originalReason:L.reason,gitCwd:re.gitCwd}}function fR(M,L,F,q){let ne=q.environment.paths,re=Am(M,".git");if(ne.entryKind(re)!=="present")return!1;if(ne.isDirectory(re))return!0;if(!F.localDiscard)return!1;let Se=q.environment.worktreeFacts(M);return Se!==null&&!Zl(L,q,Se)}function mR(M,L,F){let q=vn(M.map(t)).rest,{before:ne,after:re}=en(q.slice(q.indexOf("remove")+1)),ue=[...ne.filter((dt)=>!dt.startsWith("-")),...re],Se=ue.length===1?ue[0]??"":"",ve=M.find((dt)=>dt.text===Se),He=(ve&&$n(ve,L??new Map))??Se;if(!uR(He)||/[\s$`*?[]/.test(He)||F.entryKind(He)!=="present"||!F.isDirectory(He))return null;return F.realpath(He)}function Im(M,L){if(L.entryKind(Am(M,".git"))!=="missing")return M;let F=cR(M);return F===M?null:Im(F,L)}var gR="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.",hR=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function ws(M,L){return km(M,L)}function km(M,L,F){let q=M.map(t),ne=um(q,L.environment.env,L.envAssignments),re=ne.blockedReason?_t(Et("git.alias-config",ne.blockedReason),L.policy):null;if(re)return re;let ue=ne.tokens;if((tf(L.envAssignments)||dm(q,L.environment.env,L.envAssignments))&&yR(ue))return Et("git.ssh-env",gR);let Se=mm(ue,(He)=>{let dt=lo(q,L.cwd,L.environment.paths).gitCwd;return dt!==null&&L.environment.paths.entryKind(pR(dt,He))!=="missing"});if(!Se)return null;if(ne.expanded||ne.blockedReason)return Se;let ve=Pm(q,Se,L)??Tm(M,Se,L);if(!ve)return Se;return F?.(ve),null}function Om(M,L){let F=null;return{match:km(M,L,(ne)=>{F=ne}),relaxation:F}}function yR(M){let{subcommand:L,rest:F}=vn(M),q=L?.toLowerCase();if(!q)return!1;if(hR.has(q))return!0;if(q==="archive")return en(F).before.some((ne)=>kt(ne,"--remote"));return q==="remote"&&bR(F)}function bR(M){return M.find((L)=>!SR(L))?.toLowerCase()==="update"}function SR(M){return M==="-v"||kt(M,"--verbose")||kt(M,"--no-verbose")}import{isAbsolute as YR}from"node:path";function Mm(M,L,F,q){let ne=M.slice(0,L),re=M.slice(L+F);return q.startsWith(ne)&&q.endsWith(re)?q.slice(ne.length,q.length-re.length):null}function Ps(M,L,F){let q=(re)=>`${re.tokenIndex}\x00${re.kind}\x00${re.value}`,ne=new Set(M.map(q));return Array.from(L).some((re)=>F(re).some((ue)=>!ne.has(q(ue))))}var Dm="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",CR="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.",vR="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",ER="rm -rf targeting root or home directory is extremely dangerous and always blocked.",xR="rm -rf in home directory is dangerous. Change to a project directory first.",Nm={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:ER},git_metadata_target:{id:"rm.git-metadata",reason:k},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:vR},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:xR},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:Dm},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:CR},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:Dm}};function As(M,L){let F=ur({...L,allowPaths:L.policy?.destructiveCommandAllowPaths,posixShell:!0}),q=M.map(t),ne=Es(q),re=_R(M);for(let ue of re){let Se=Qo(ue.word);if(ne&&Se.unsafeBraceExpansion){let ve=_t(Jo({kind:"outside_anchored_cwd"},F,L.policy,Nm),L.policy);if(ve)return ve;continue}for(let ve of Se.expandedTargets??[ue.text]){let He=hn(ve),dt={targetIsLiteral:Se.expandedTargets!==void 0||Se.targetIsLiteral,tmpdirWordSplittingProtected:Se.tmpdirWordSplittingProtected};if(!ne&&F.resolvedCwd&&Ar(He,F.resolvedCwd,F.protectedGitMetadata,ne,F.environment,F.budget))return Et("rm.git-metadata",k);if(!ne)continue;for(let mt of RR(He,F,dt)){let ft=Jo(mt,F,L.policy,Nm),pt=_t(ft,L.policy);if(pt)return pt}}}return null}function RR(M,L,F){let q=Mn(M,L,F);if(q.kind==="cwd_self_target")return[q,Mn(M,L,{...F,skipCwdSelf:!0})];if(q.kind!=="home_cwd_target")return[q];let ne=Mn(M,L,{...F,skipHomeCwd:!0});if(ne.kind!=="cwd_self_target")return[q,ne];return[q,ne,Mn(M,L,{...F,skipHomeCwd:!0,skipCwdSelf:!0})]}function _R(M){let L=[],F=!1;for(let q of M.slice(1)){let ne=t(q);if(!ne)continue;if(ne==="--"){F=!0;continue}if(F){L.push({text:ne,word:q});continue}if(!ne.startsWith("-"))L.push({text:ne,word:q})}return L}var fr={kind:"none"},Dr={kind:"dynamic"},wR=new Set(["<","<<","<<-","<<<","<&","<>"]),Wm=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,PR=/^(?:[0-9]+|[@*])$/,AR=ir.maxWords,Gm=ir.maxInputLength;function Fm(M){if(!M||wt(It(M.words[0]?.text??""))!=="printf")return;if(M.words.some((ne)=>ne.provenance!=="literal"))return;let L=M.words.slice(M.words[1]?.text==="--"?2:1),F=L[0]?.text;if(F===void 0)return"";let q=L.slice(1).map((ne)=>ne.text);if(F==="%s")return q.join("");if(F==="%s\\n"||F===`%s
|
|
34
|
+
`)return`${q.join(`
|
|
35
|
+
`)}
|
|
36
|
+
`;if(F.includes("%")||/\\(?![\\nrt])/.test(F))return;return F.replaceAll("\\n",`
|
|
37
|
+
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function Ts(M){let L=co(M[1])==="--"?2:1;if(M.length<=L)return fr;let F=M.slice(L);if(!F.every(si))return Dr;return{kind:"literal",source:F.map(t).join(" ")}}function zm(M){let L=co(M[1])==="--"?2:1,F=M[L],q=co(F);if(F===void 0||M.length<=L+1||q==="-"||q===""||q==="-l"||q==="-p")return fr;if(!si(F))return Dr;return{kind:"literal",source:q}}function Is(M,L){let F=Um(M);if(F===-1)return fr;let q=IR(L);if(!q)return fr;let ne=[],re=q.command?.length??0;for(let ue of q.references){let Se=OR(ue,M,F,q.ifs);if(!Se)return Dr;if(re+=Se.reduce((ve,He)=>ve+He.length+3,0),ne.length+Se.length>AR||re>Gm)return Dr;ne.push(...Se)}if(q.command==="eval")return{kind:"literal",source:ne.join(" ")};if(ne.length===0||/\s/.test(ne[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[q.command,q.command&&q.optionTerminator?"--":null,...ne.map(ks)].filter((ue)=>ue!==null).join(" ")}}function Bm(M,L){let F=Um(M),q=M.slice(F+1),ne=/\bIFS\b/.test(L);if(F===-1||!q.every(si)||ne)return L;let re=q.map(co),ue="",Se=null,ve=0;while(ve<L.length){let He=L[ve]??"",dt=Se==="'"?null:/^\$(?:\{([0-9]+|[@*])\}|([0-9@*]))/.exec(L.slice(ve));if(dt){let mt=dt[1]??dt[2],ft=mt==="@"||mt==="*"?re.slice(1):[re[Number(mt)]??""];if(Se!=='"'&&ft.some((ht)=>/[*?[]/.test(ht)))return L;if(ue+=Se==='"'?ft.map((ht)=>ht.replace(/["$`\\]/g,"\\$&")).join(mt==="@"?'" "':" "):ft.map((ht)=>ht.split(/[ \t\n]+/).map((gt)=>gt?ks(gt):"").join(" ")).join(" "),ue.length>Gm)return L;ve+=dt[0].length;continue}if(He==="\\"&&Se!=="'"){ue+=L.slice(ve,ve+2),ve+=2;continue}if(He==="'"&&Se!=='"'||He==='"'&&Se!=="'")Se=Se?null:He;ue+=He,ve++}return ue}function $m(M,L,F,q){if(!bn(M.map(t)).readsStdinAsCommands)return fr;let ne=L.filter((re)=>(re.fd===void 0||re.fd===0)&&wR.has(re.operator)).at(-1);if(ne){if(ne.operator==="<<"||ne.operator==="<<-")return fr;if(ne.operator!=="<<<"||ne.target?.provenance!=="literal")return Dr;return{kind:"literal",source:ne.target.text}}if(!F)return fr;return q===void 0?Dr:{kind:"literal",source:q}}function er(M,L=new Map){let F=bn(M.map(t)).scriptIndex;if(F===null)return fr;let q=M[F],ne=co(q);if(Zi(q,ne))return{kind:"literal",source:ne};let re=q?$n(q,L):null;return re===null?Dr:{kind:"literal",source:re}}var TR=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function ec(M){if(M.words.length!==2||M.redirections.length!==0||M.nested.length!==1)return!1;let L=M.words[0],F=M.words[1];if(!L||L.provenance!=="literal"||L.quoted||L.raw!==L.text||!F)return!1;if(!(L.text==="eval"&&F.quoted&&F.parts.length===3&&F.parts[0]?.raw==='"'&&F.parts[1]?.provenance==="command-substitution"&&F.parts[1].raw.startsWith("$(")&&F.parts[2]?.raw==='"'||L.text==="eval"&&!F.quoted&&F.parts.length===1&&F.parts[0]?.provenance==="command-substitution"&&F.parts[0].raw.startsWith("$(")||(L.text==="source"||L.text===".")&&!F.quoted&&F.parts.length===1&&F.parts[0]?.provenance==="command-substitution"&&F.parts[0].raw.startsWith("<(")))return!1;let ne=M.nested[0];if(ne?.status!=="complete"||ne.nodes.length!==1)return!1;let re=ne.nodes[0];if(re?.kind!=="command"||re.redirections.length!==0||re.nested.length!==0||re.words.some((ve)=>ve.provenance!=="literal"||ve.parts.some((He)=>He.provenance!=="literal")))return!1;let ue=re.words[0]?.text;if(ue===void 0||wn(ue)!==null)return!1;let Se=wt(It(ue));return!TR.has(Se)&&!Ht.has(Se)&&!kr(Se)}function Um(M){return bn(M.map(t)).commandIndex??-1}function IR(M){let L=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(M.trim()),F=L?.[4]??M.trim(),q=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(F),ne=(q?.[3]??F).split(/\s+/).map(kR);if(ne.length===0||ne.some((re)=>re===null))return null;return{command:q?.[1]??null,optionTerminator:q?.[2]!==void 0,references:ne.filter((re)=>!!re),ifs:L?L[1]??L[2]??L[3]??"":`
|
|
38
|
+
`}}function kR(M){let L=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(M),F=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(M),q=L??F;if(!q)return null;let ne=q[1]??q[2];return{parameter:ne==="@"||ne==="*"?ne:Number(ne),quoted:L!==null}}function OR(M,L,F,q){let ne=L.slice(F+2);if(M.parameter==="@")return M.quoted?Xl(ne):MR(ne,q);if(M.parameter==="*"){let Se=Xl(ne);if(!Se)return;let ve=Se.join(q[0]??"");return M.quoted?[ve]:Jl(ve,q)}let re=L[F+1+M.parameter];if(re&&!si(re))return;let ue=co(re);return M.quoted?[ue]:Jl(ue,q)}function Xl(M){return M.every(si)?M.map(t):void 0}function MR(M,L){let F=Xl(M);if(!F)return;let q=F.map((ne)=>Jl(ne,L));return q.some((ne)=>ne===void 0)?void 0:q.flatMap((ne)=>ne??[])}function Jl(M,L){if(["*","?","[","]"].some((F)=>M.includes(F)))return;if(L==="")return M===""?[]:[M];if(L===`
|
|
39
|
+
`)return M.trim().split(/\s+/).filter(Boolean);if(L.length!==1)return;return L===" "||L==="\t"||L===`
|
|
40
|
+
`?M.trim().split(/\s+/).filter(Boolean):M.split(L).filter(Boolean)}function si(M){if(!M)return!0;return M.provenance==="unknown"?!/[$`]/.test(t(M)):M.provenance==="literal"}function co(M){return M?t(M):""}function ks(M){return`'${M.replaceAll("'",`'"'"'`)}'`}function tc(M,L){return Ql(h(M,"posix"),L)}function ai(M){return tc(M,new Set(Array.from(M.matchAll(Wm)).flatMap((L)=>{let F=L[1]??L[2];return F===void 0?[]:[F]})))}function Ql(M,L){if(M.status==="invalid"||M.status==="limited")return!1;let F=new Set(L);for(let q of M.nodes){if(q.kind==="group"){if(Ql(q.body,F))return!0;continue}if(q.kind!=="command")continue;if(q.nested.some((ne)=>Ql(ne,F))||Hm(q.words,F))return!0;GR(q,F)}return!1}function Hm(M,L){let F=M.findIndex((ue)=>wn(ue.text)===null);if(F===-1)return!1;let q=M[F];if(!q)return!1;if(ii(q,L))return!0;let ne=It(q.text);if(ne==="source"||ne==="."){let ue=M[F+1]?.text==="--"?F+2:F+1;return Lm(M[ue],L)}if(Ht.has(ne)){let ue=M.slice(F),Se=bn(ue.map((He)=>He.text)),ve=Se.commandIndex??Se.scriptIndex;return!Se.syntaxCheck&&ve!==null&&Lm(ue[ve],L)}let re=DR(M,F,L);if(re===null)return!1;if(re===-1)return!0;return Hm(M.slice(re),L)}function DR(M,L,F){let q=It(M[L]?.text??"");if(q==="command")return NR(M,L+1);if(q==="exec")return LR(M,L+1);if(q==="env")return WR(M,L+1,F);return null}function NR(M,L){for(let F=L;F<M.length;F++){let q=M[F]?.text??"";if(q==="--")return M[F+1]?F+1:null;if(/^-[p]*[vV][pvV]*$/.test(q))return null;if(/^-p+$/.test(q))continue;return F}return null}function LR(M,L){for(let F=L;F<M.length;F++){let q=M[F]?.text??"";if(q==="--")return M[F+1]?F+1:null;if(q==="-a"){F++;continue}if(/^-a.+/.test(q)||/^-[cl]+$/.test(q))continue;return F}return null}function WR(M,L,F){for(let q=L;q<M.length;q++){let ne=M[q],re=ne?.text??"";if(re==="--")return M[q+1]?q+1:null;if(re==="-S"||re==="--split-string")return ii(M[q+1],F)?-1:q+2;if(re.startsWith("-S")||re.startsWith("--split-string="))return ii(ne,F)?-1:q+1;if(re==="-u"||re==="--unset"||re==="-C"||re==="--chdir"||re==="-P"){q++;continue}if(re==="-i"||re==="-0"||re==="--null"||re.startsWith("-u=")||re.startsWith("--unset=")||re.startsWith("-C")||re.startsWith("--chdir=")||re.startsWith("-P"))continue;if(re.startsWith("-"))continue;if(wn(re))continue;return q}return null}function GR(M,L){if(!M.words.every((F)=>wn(F.text)!==null))return;for(let F of M.words){let q=wn(F.text);if(!q)continue;if(ii(F,L))L.add(q.name)}}function ii(M,L){if(!M)return!1;return M.parts.filter((F)=>F.provenance==="variable").some((F)=>Array.from(F.raw.matchAll(Wm)).some((q)=>{let ne=q[1]??q[2];return ne!==void 0&&(PR.test(ne)||L.has(ne))}))}function Lm(M,L){return!!M&&(M.parts.some((F)=>F.provenance!=="literal"&&F.provenance!=="variable")||ii(M,L))}var nc="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",rc="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",FR="__CC_SAFETY_NET_XARGS_INPUT__",Os="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",Ms="rm",zR=/(?:^|[;&|]\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,BR=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,$R=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,UR=/^(?:[0-9]+|[@*])$/;function Km(M,L){let F=M.map(t),{childStart:q,replacementToken:ne}=Nr(F),re=F.slice(q),ue=Et("xargs.shell-dynamic",rc);if(jR(re,ne,L)&&_t(ue,L.policy))return _t(ue,L.policy);for(let Se of Dn(re,L)){let ve=Se.tokens,He=ne!==null&&ve[0]!==re[0]&&(ve[0]?.includes(ne)??!1)?_t(ue,L.policy):null;if(He)return He;let dt=Qm(ve,ne,Se.wrapperEnvAssignments),mt=Se.head==="rm"&&ne!==null&&Xm(ve,ne),ft=L.analyzeChild(ve,{...Or(Se,L),dynamicInput:dt,dynamicSourceInput:mt||Ym(ve,Se.head,ne,Se.wrapperEnvAssignments,dt,L.environment,L.strict?void 0:L.analyzeNested),dynamicRmInput:mt,shellDynamicMatch:ue,dynamicSourceMatch:ue,rmDynamicMatch:Et("xargs.rm-recursive-force-dynamic",nc)});if(ft)return ft;let pt=HR(ve,ne,L.policy?.rules??[],_t(ue,L.policy));if(pt)return pt;if(Se.head==="git"){let gt=ne===null?[...ve,FR]:ve,yt=ne!==null&&(ve.some((Ct)=>Ct.includes(ne))||Array.from(Se.envAssignments.values()).some((Ct)=>Ct.includes(ne))),St=L.analyzeChild(gt,{...Or(Se,L),worktreeMode:ne===null||yt?!1:L.worktreeMode});if(St)return St}let ht=A(ve,L.policy?.rules??[]);if(ht)return ht}return null}function HR(M,L,F,q){if(F.length===0)return null;if(L===null){for(let re of F){let ue=A([...M,...re.subcommand?[re.subcommand]:[],...re.block_args],F);if(ue)return ue}return null}let ne=It(M[0]??"");if(!F.some((re)=>It(re.command)===ne))return null;return M.slice(1).some((re)=>re.includes(L))?q:null}function qm(M,L,F){let q=M.indexOf(L);if(q===-1||M.indexOf(L,q+L.length)!==-1)return[];let ne=Mm(M,q,L.length,F);return ne===null?[]:[ne]}function Ym(M,L,F,q,ne,re,ue){if(Ht.has(L)){if(Jn(M))return!1;if(F!==null&&VR(M,F,ue))return!0;let Se=Nn(M);if(!Se){let ve=er(Ut(M));if(ve.kind==="literal")return F!==null&&ve.source.includes(F);return ve.kind==="none"&&ne}if(F!==null&&Se.includes(F)&&!Zm(Se,F,ue))return!0;if(_n(Se))return!0;return KR(Se,F,q)}if(Tn(L))return jm(M,F,ts,Zd(L));if(Rn.has(L))return jm(M,F,Dl,Jf);if(L==="eval"){let Se=Ts(Ut(M));if(Se.kind==="dynamic")return!0;if(F!==null)return Se.kind==="literal"&&Se.source.includes(F);return ne}if(L==="find")return qR(M,F,re);if(L==="git"){let Se=vn(M);return F===null?Se.subcommand===null:(Se.subcommand?.includes(F)??!1)||Se.subcommand!==null&&ao.has(Se.subcommand.toLowerCase())&&Jm(Se.rest,F).some((ve)=>ve.includes(F))}return!1}function Zm(M,L,F){if(F===void 0)return!1;let q=L.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`(?:^|[;&|({!\`\\n]|\\b(?:then|do|else|elif|if|while|until|time|command|builtin|nohup|eval|exec|source))\\s*(?:[A-Za-z_][A-Za-z0-9_]*=\\S*\\s+)*["']?${q}`).test(M)||/\bcase\b/.test(M))return!1;let re=M.replaceAll(L,"/");return _n(re)===null&&F(re)===null}function jm(M,L,F,q){let ne=F(M);if(L===null)return ne.optionsOpen||F([...M,Os]).sources.some((Se)=>Se.value===Os);if(ne.sources.some((Se)=>Se.value.includes(L)))return!0;let re=q.flatMap((Se)=>[Se.selector,...Se.valueForm==="attached-only"||Se.valueForm==="attached-or-separate"?[`${Se.selector}${Os}`]:[],...Se.valueForm==="equals-or-separate"?[`${Se.selector}=${Os}`]:[]]),ue=new Set(re.flatMap((Se)=>M.flatMap((ve)=>qm(ve,L,Se))));return Ps(ne.sources,ue,(Se)=>F(M.map((ve)=>ve.replaceAll(L,Se))).sources)}function jR(M,L,F){if(M.length===0||(M[0]??"").toLowerCase()==="command")return!1;let q=new Set(Array.from(Dn(M,F),(re)=>re.head)),ne=L===null?[...M,Ms]:M.map((re,ue)=>ue===0?re:re.replaceAll(L,Ms));return Array.from(Dn(ne,F)).some((re)=>re.head===Ms&&!q.has(Ms))}function Xm(M,L){return Jm(M.slice(1),L).some((F)=>F.includes(L)&&(F.startsWith("-")||F.startsWith(L)))}function Jm(M,L){let F=M.findIndex((q)=>q==="--"&&!q.includes(L));return F===-1?M:M.slice(0,F)}function Qm(M,L,F){if(L===null)return!0;return M.some((q)=>q.includes(L))||Array.from(F.values()).some((q)=>q.includes(L))}function VR(M,L,F){let q=bn(M),ne=q.commandIndex===null?"":M[q.commandIndex]??"";if(ne.includes(L)&&!Zm(ne,L,F)||q.scriptIndex!==null&&(M[q.scriptIndex]??"").includes(L))return!0;return["-c","-nc","-cn",`--${L}`,L].some((ue)=>M.some((Se,ve)=>{if(ve===0||!Se.includes(L))return!1;return qm(Se,L,ue).some((dt)=>{let mt=M.map((pt,ht)=>ht===ve?pt.replaceAll(L,dt):pt),ft=bn(mt);if(ft.commandIndex===null&&ft.scriptIndex===null)return!1;if(q.commandIndex===null&&ft.commandIndex!==null)return!0;if(q.scriptIndex===null&&ft.scriptIndex!==null)return!0;if(ft.commandIndex!==null&&(mt[ft.commandIndex]??"").includes(dt))return!0;return ft.scriptIndex!==null&&(mt[ft.scriptIndex]??"").includes(dt)})}))}function KR(M,L,F){let q=new Set(L===null?[]:Array.from(F).filter(([,ne])=>ne.includes(L)).map(([ne])=>ne));for(let ne of M.matchAll(zR))if(Vm(ne,q))return!0;for(let ne of M.matchAll(BR))for(let re of(ne[1]??"").matchAll($R))if(Vm(re,q))return!0;return tc(M,q)}function Vm(M,L){let F=M[1]??M[2];return F!==void 0&&(UR.test(F)||L.has(F))}function qR(M,L,F){if(L===null)return!0;let q=!1,ne=0;for(let re=1;re<M.length;re++){let ue=M[re]??"";if(!q&&!ue.startsWith("-")&&ue!=="!"&&ue!=="("){if(ue.indexOf(L)===0)return!0;continue}if(q=!0,ne>0){ne--;continue}if(Bn(ue)){let ve=so(M,re);re=ve.nextIndex-1;for(let He of Dn(ve.tokens,{environment:F,cwd:void 0})){let dt=Qm(He.tokens,L,He.wrapperEnvAssignments);if(He.head==="rm"&&Xm(He.tokens,L)||Ym(He.tokens,He.head,L,He.wrapperEnvAssignments,dt,F))return!0}continue}let Se=Qn(ue);if(Se>0){if(ne=Se,ue.includes(L))return!0;continue}if(ue.includes(L))return!0}return!1}function Nr(M){let L=new Set(["-L","-n","-P","-s","-a","-E","-R","-S","-e","-d","-J","--max-args","--max-procs","--max-chars","--arg-file","--eof","--delimiter","--max-lines","--process-slot-var"]),F=null,q=1;while(q<M.length){let ne=M[q];if(!ne)break;if(ne==="--")return{childStart:q+1,replacementToken:F};if(!ne.startsWith("-"))return{childStart:q,replacementToken:F};if(ne==="-I"){F=M[q+1]??"{}",q+=2;continue}if(ne.startsWith("-I")&&ne.length>2){F=ne.slice(2),q++;continue}if(ne==="--replace"){F="{}",q++;continue}if(ne.startsWith("--replace=")){let re=ne.slice(10);F=re===""?"{}":re,q++;continue}if(ne==="-J"){F=M[q+1]??"{}",q+=2;continue}q+=L.has(ne)?2:1}return{childStart:M.length,replacementToken:F}}var li="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",ci="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",ZR="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",XR="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Ns=/\{[^{}\s]*\}/g,ep=/\{\}|\{-?\d+\}/g,tp=/[\s;&|<>()$`\\"']/,JR=["e","f","source","file","-e","-f","--source","--file"],QR=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],e_=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),t_=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),np=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),n_=new Set(["--workdir","--wd"]),rp="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Pn(M,L){for(let F of M){let q=L(F);if(q)return q}return null}function sp(M){return Pn([...M],(L)=>_n(L))}function ap(M,L){let F=M.map(t);if((L.envAssignments?.has("PARALLEL")?L.envAssignments.get("PARALLEL"):L.environment.env.get("PARALLEL"))?.trim()){let ht=uo(L);if(ht)return ht}if(F.length===2&&(F[1]==="--version"||F[1]==="--help"))return null;let ne=Sp(F),{template:re,jobs:ue,runsRemotely:Se,readsCommandsFromInput:ve,unsupported:He,workdir:dt,dryRun:mt}=ne;if(He){let ht=uo(L);if(ht)return ht;let gt=sp(L.envAssignments?.values()??[]);if(gt)return gt}if(ve){let ht=c_(L);if(ht)return ht}if(dt!==void 0&&Se){let ht=uo(L);if(ht)return ht}let ft=u_(dt,L.cwd,L.environment.paths);if(ft===null){let ht=uo(L);if(ht)return ht}let pt=Se?{...L,cwd:void 0,originalCwd:void 0}:ft===null||ft===void 0||ft===L.cwd?L:{...L,cwd:ft};if(mt){if([...Dn(re,pt)].flatMap((gt)=>[...gt.envAssignments.values()]).some(sc)){let gt=uo(L);if(gt)return gt}return null}if(re.length===0){let ht=ue.map((yt)=>yt[0]??"");L.budget.charge("derivedTokens",ht.length);let gt=mp(pt.envAssignments,pt.cwd,Se);return Pn(ht,(yt)=>L.analyzeNested(yt,gt))}return Pn(Dn(re,pt),(ht)=>r_(ht,ne,L,pt))}function r_(M,L,F,q){let{templateHasPlaceholder:ne,runsRemotely:re,usesStdin:ue}=L,Se=M.tokens,ve=[...M.envAssignments.values()];if(ve.some(yp)){let xt=uo(F);if(xt)return xt}let He=sp(ve);if(He)return He;let dt=ve.some(Nt),mt=ne||dt,ft=ue&&mt,pt=mp(M.envAssignments,M.wrapperCwd,re||ft),ht=mt?{...pt,worktreeMode:!1}:pt,gt=Se.join(" "),yt=Nt(gt.split(/[ \t\n=]/,1)[0]??""),St=!L.quotesCommand&&(yt||Se.some((xt)=>tp.test(xt))),Ct=yt||tp.test(Se[0]??""),bt=St&&Ct&&L.jobs.length>0?null:o_(M,L,F,q,ht,dt);if(bt||!St)return bt;return lp(Nt(gt)?gt:`${gt} {}`,!yt,M,L,F,q,ht)}function o_(M,L,F,q,ne,re){let{jobs:ue,templateHasPlaceholder:Se,runsRemotely:ve,usesStdin:He}=L,dt=M.tokens,mt=Se||re;if(Ht.has(M.head)){let pt=()=>{if(!Se||ue.length===0)return null;return Pn(ue,(yt)=>F.analyzeChild(Ds(dt,yt,F.budget),Or(M,q)))};if(Jn(dt))return pt();let ht=Nn(dt);if(ht){if(bp(ht)){let bt=mr(F);if(bt)return bt;if(ue.length===0)return null;return Pn(ue,(xt)=>F.analyzeNested(gp(ht,xt,F.budget),ne))}if(Nt(ht))return lp(ht,!1,M,L,F,q,ne);let yt=!re&&(!Se||ue.length>0)?(ue.length>0?ue:[void 0]).map((bt)=>Is(Ut(bt===void 0?dt:Se?dt.map((xt)=>pp(xt,bt)):[...dt,...bt]),ht)):[];if(yt.some((bt)=>bt.kind==="dynamic")){let bt=mr(F);if(bt)return bt}let St=yt.flatMap((bt)=>bt.kind==="literal"?[bt.source]:[]);if(St.length>0)return F.budget.charge("derivedTokens",St.length),Pn(St,(bt)=>F.analyzeNested(bt,ne));if(ai(ht)){let bt=mr(F);if(bt)return bt}let Ct=F.analyzeNested(ht,ne);if(Ct)return Ct;if(mt)return mr(F);return null}let gt=er(Ut(dt));if(gt.kind==="dynamic"||gt.kind==="literal"&&Nt(gt.source))return mr(F)??pt();if(gt.kind==="literal")return pt();if(ue.length>0){let yt=mr(F);if(yt)return yt;let St=pt();if(St)return St;if(Se)return null;let Ct=ue.flatMap((bt)=>bt[0]===void 0?[]:[bt[0]]);return F.budget.charge("derivedTokens",Ct.length),Pn(Ct,(bt)=>F.analyzeNested(bt,ne))}if(mt||He)return mr(F)??pt();return null}if(M.head==="rm"&&Xn(dt)){if(Se&&ue.length>0)return Pn(ue,(ht)=>oc(Ds(dt,ht,F.budget,ep),M.cwd,q));if(ue.length>0)return Pn(ue,(ht)=>oc(ip(dt,ht,F.budget),M.cwd,q));let pt=oc(dt.flatMap((ht,gt)=>{if(gt===0||!Nt(ht))return[ht];return ht.startsWith("-")?[ht.replace(ep,"")]:[]}),M.cwd,q);if(pt)return pt;return fp(F)}let ft=ue.length>0?ue:[void 0];return Pn(ft,(pt)=>{let ht=pt===void 0?dt:Se?Ds(dt,pt,F.budget):ip(dt,pt,F.budget),gt=Et("parallel.shell-dynamic",ci),yt=He&&M.head==="find"?l_(ht,q):null,St=up(ht,He,F)??yt?.customResult??null,Ct=It(M.head),bt=He&&(Ct==="rm"&&ic(ht)||Ct==="xargs"&&dp(ht)||yt?.rmOptions===!0),xt=He&&(bt||yt?.executedSource===!0||yt===null&&cp(ht,Ct)),At=F.analyzeChild(ht,{...Or(M,q),worktreeMode:ve||He||mt?!1:F.worktreeMode,dynamicInput:He||mt,dynamicRmInput:bt,dynamicSourceInput:St!==null||xt,shellDynamicMatch:gt,dynamicSourceMatch:gt,rmDynamicMatch:Et("parallel.rm-recursive-force-dynamic",li)});if(xt){let Tt=_t(gt,F.policy);if(Tt)return Tt}return At??St??A(ht,F.policy?.rules??[])})}function lp(M,L,F,q,ne,re,ue){if(q.jobs.length>0)return Pn(q.jobs,(He)=>ne.analyzeNested(gp(M,L?He.map(ks):He,ne.budget),ue));let Se=oi(M);if(Se?.[0]&&It(Se[0])==="rm"&&Xn(Se)){let He=fp(ne);if(He)return He}return(Se?ne.analyzeChild(Se,{...Or(F,re),dynamicInput:q.usesStdin,shellDynamicMatch:Et("parallel.shell-dynamic",ci),rmDynamicMatch:Et("parallel.rm-recursive-force-dynamic",li)}):null)??ne.analyzeNested(M,ue)}function cp(M,L){if(Nt(M[0]??""))return!0;if(L==="eval"||L==="source"||L===".")return!0;if(L==="parallel"||L==="xargs")return!0;if(Ht.has(L))return a_(M);if(L==="git")return i_(M);if(L==="find")return!0;if(Rn.has(L))return op(M,JR,ni);if(Tn(L))return op(M,QR,es);return!1}function ic(M){let L=M.indexOf("--"),F=M.slice(1,L===-1?void 0:L);if(!M.some(Nt))return L===-1;return F.some((ne)=>Nt(ne)&&(ne.startsWith("-")||bp(ne)))}function i_(M){if(s_(M))return!0;let L=vn(M);if(L.subcommand===null||Nt(L.subcommand))return!0;if(!ao.has(L.subcommand.toLowerCase()))return!1;let F=L.rest.indexOf("--"),q=L.rest.slice(0,F===-1?void 0:F);if(!M.some(Nt))return F===-1;return q.some(Nt)}function s_(M){for(let L=1;L<M.length;L++){let F=M[L];if(!F||F==="--"||!F.startsWith("-"))return!1;if(F==="-c"||F==="--config-env"){if(Nt(M[L+1]??""))return!0;L++;continue}if(F.startsWith("-c")&&F.length>2||F.startsWith("--config-env=")){if(Nt(F))return!0;continue}if(Nt(F))return!0}return!1}function a_(M){if(Jn(M))return!1;let L=Nn(M);if(L!==null)return Nt(L);let F=er(Ut(M));if(F.kind==="literal")return Nt(F.source);if(F.kind==="dynamic")return!0;return!M.some(Nt)}function op(M,L,F){let q=F(M);if(q.some((ne)=>Nt(ne.value)))return!0;if(!M.some(Nt))return F([...M,rp]).some((ne)=>ne.value===rp);return Ps(q,L,(ne)=>F(M.map((re)=>pp(re,[ne]))))}function up(M,L,F){let q=F.policy?.rules??[];if(!L||q.length===0)return null;let ne=q.filter((re)=>It(re.command)===It(M[0]??""));if(ne.length===0)return null;if(M.slice(1).some(Nt))return mr(F);return Pn(ne,(re)=>A([...M,...re.subcommand?[re.subcommand]:[],...re.block_args],[re]))}function l_(M,L){let F={customResult:null,executedSource:!M.some(Nt),rmOptions:!1},q=!1,ne=0,re=null,ue=()=>{if(!re?.some(Nt))return;for(let Se of Dn(re,L))F.executedSource||=cp(Se.tokens,Se.head),F.rmOptions||=Se.head==="rm"&&ic(Se.tokens)||Se.head==="xargs"&&dp(Se.tokens),F.customResult??=up(Se.tokens,!0,L)};for(let Se of M.slice(1)){if(!q&&!Se.startsWith("-")&&Se!=="!"&&Se!=="("){F.executedSource||=Nt(Se);continue}if(q=!0,re){if(Se===";"||Se==="+"){ue(),re=null;continue}re.push(Se);continue}if(ne>0){ne--;continue}if(Bn(Se)){re=[],F.executedSource||=Nt(Se);continue}let ve=Qn(Se);if(ve>0){ne=ve,F.executedSource||=Nt(Se);continue}F.executedSource||=Nt(Se)}return ue(),F}function dp(M){let L=M.slice(Nr(M).childStart);return It(L[0]??"")==="rm"&&ic(L)}function Ls(M,L){return(F)=>_t(Et(M,L),F.policy)}var mr=Ls("parallel.shell-dynamic",ci),c_=Ls("parallel.command-stream-dynamic",ZR),uo=Ls("parallel.command-stream-dynamic",XR),fp=Ls("parallel.rm-recursive-force-dynamic",li);function oc(M,L,F){return _t(As(Ut(M),{environment:F.environment,cwd:L,budget:F.budget,originalCwd:F.originalCwd,strict:F.strict,paranoid:F.paranoidRm,allowTmpdirVar:F.allowTmpdirVar,tmpdirWordSplittingUnsafe:Tr(F.envAssignments??new Map,F.environment),trustedTmpdirValue:no(F.envAssignments??new Map,F.environment),protectedGitMetadata:F.protectedGitMetadata,policy:F.policy}),F.policy)}function mp(M,L,F){let q={};if(M)q.envAssignments=M;if(F)return q.effectiveCwd=null,q.worktreeMode=!1,q;if(L!==void 0)q.effectiveCwd=L;return Object.keys(q).length>0?q:void 0}function pp(M,L){return M.replace(Ns,(F)=>hp(F,L))}function Ds(M,L,F,q=Ns){return F.charge("derivedTokens",M.reduce((ne,re)=>ne+1+Math.floor(re.length/64),0)),M.map((ne)=>ne.replace(q,(re)=>{let ue=hp(re,L);return F.charge("derivedTokens",Math.max(1,Math.ceil(ue.length/64))),ue}))}function gp(M,L,F){return Ds([M],L,F)[0]??""}function ip(M,L,F){return F.charge("derivedTokens",M.length+L.length),[...M,...L]}function hp(M,L){let F=/^\{(-?\d+)[^{}\s]*\}$/.exec(M)?.[1];if(F===void 0)return L[0]??"";let q=Number(F);return L[q>0?q-1:L.length+q]??""}function Nt(M){return M.search(Ns)!==-1}function yp(M){if(sc(M))return!0;for(let L of M.matchAll(Ns))if(!/^(?:\{\}|\{\d+\})$/.test(L[0]))return!0;return!1}function sc(M){let L=M.indexOf("{=");return L!==-1&&M.indexOf("=}",L+2)!==-1}function bp(M){return/^\{[^{}\s]*\}$/.test(M)}function u_(M,L,F){if(M===void 0)return;if(M==="..."||/^~|[{}$`*?[]/.test(M))return null;if(!L&&!YR(M))return null;try{return sr(L??M,M,F)}catch{return null}}function Sp(M){let L=1,F=[],q=M.length,ne=-1,re=!1,ue=!1,Se=!1,ve,He=!1,dt=M.some((gt)=>gt==="::::"||gt==="::::+"||gt===":::+");while(L<M.length){let gt=M[L];if(gt===void 0)break;if(gt===":::"){ne=L;break}if(gt==="--"){let xt=Wl(M,L+1);F.push(...xt.templateTokens),q=L+1,ne=xt.markerIndex;break}if(!gt.startsWith("-")){let xt=Wl(M,L);F.push(...xt.templateTokens),q=L,ne=xt.markerIndex;break}let yt=M[L+1],St=gt.indexOf("="),Ct=St===-1?gt:gt.slice(0,St),bt=St===-1?void 0:gt.slice(St+1);if(gt==="--dry-run"){He=!0,L++;continue}if(gt==="-I"||gt.startsWith("-I")&>.length>2){dt||=(gt==="-I"?yt:gt.slice(2))!=="{}",L+=gt==="-I"?2:1;continue}if(gt==="--replace"||gt==="-i"){dt=!0,L+=2;continue}if(Ct==="--replace"||gt.startsWith("-i")&>.length>2){let xt=Ct==="--replace"?bt:gt.slice(2);dt||=xt!==""&&xt!=="{}",L++;continue}if(gt==="-a"||t_.has(Ct)){dt=!0,L+=bt===void 0?2:1;continue}if(gt==="-q"||gt==="--quote"){ue=!0,L++;continue}if(gt==="--pipe"||gt==="--pipepart"){Se=!0,L++;continue}if(Ct==="--env"){dt=!0,L+=bt===void 0?2:1;continue}if(np.has(Ct)||gt.startsWith("-S")&>.length>2){re=!0,L+=np.has(gt)?2:1;continue}if(n_.has(Ct)){dt=!0;let xt=bt??yt;if(xt===void 0||xt===":::"||xt==="--"){L++;continue}ve=xt,L+=bt===void 0?2:1;continue}if(gt.startsWith("-j")&>.length>2&&/^\d+$/.test(gt.slice(2))){L++;continue}if(gt.startsWith("--")&&bt!==void 0){L++;continue}if(e_.has(gt)){if(yt===void 0||yt===":::"||yt==="--"){dt=!0,L++;continue}L+=2;continue}L+=gt==="-j"||gt==="--jobs"?2:1}dt||=F.some(He?sc:yp);let mt=[];if(ne!==-1){let gt=[];for(let yt=ne+1;yt<M.length;yt++){let St=M[yt];if(St===":::"){mt.push(gt),gt=[];continue}if(St!==void 0)gt.push(St)}mt.push(gt)}dt||=mt.length>1;let ft=d_(mt),pt=F.some(Nt),ht=F.length===0&&ne===-1;return{template:F,jobs:ft,childStart:q,templateHasPlaceholder:pt,runsRemotely:re,quotesCommand:ue,usesStdin:Se||ne===-1,readsCommandsFromInput:ht,unsupported:dt,workdir:ve,dryRun:He}}function d_(M){if(M.length===0||M.some((F)=>F.length===0))return[];let L=[[]];for(let[F,q]of M.entries()){if(q.length===1){let re=q[0];if(re===void 0)return[];for(let ue of L)ue.push(re);if(L.length*(F+1)>a.derivedTokens.cap)throw new s("derivedTokens");continue}let ne=[];for(let re of L)for(let ue of q){if((ne.length+1)*(F+1)>a.derivedTokens.cap)throw new s("derivedTokens");ne.push([...re,ue])}L=ne}return L}function Cp(M){return Sp(M).childStart}var f_="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",Ws="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function lc(M){return M?.parts.some((L)=>L.provenance==="command-substitution")??!1}function ac(M){return M?.parts.some((L)=>L.provenance==="literal"&&L.raw.replace(/^["']/,"").startsWith("-"))??!1}function Ep(M,L,F,q,ne=!1,re){let Se=(No(M,L)||q&&M!=="powershell"&&L[0]?.provenance==="variable")&&Yt(re,"shell.dynamic-executable",ne)?Et("shell.dynamic-executable",f_):null;return _t(Se,re)??xp(M,L,F,ne,re)}function xp(M,L,F,q,ne){if(L.length<2)return null;let re=L.flatMap((Se,ve)=>lc(Se)?[ve]:[]);if(re.length===0)return null;let ue=It(L[0]?.text??"");if(ue==="git"){let Se=te(M,L),ve=p_(Se);if(Yt(ne,"shell.dynamic-structure",q)&&re.some((mt)=>mt<=ve))return _t(Et("shell.dynamic-structure",Ws),ne);if(_t(ws(Se,{environment:F}),ne))return null;let He=L[ve]?.text.toLowerCase(),dt=Se.findIndex((mt,ft)=>ft>ve&&t(mt)==="--");if(Yt(ne,"shell.dynamic-structure",q)&&He&&ao.has(He)&&re.some((mt)=>mt>ve&&(dt===-1||mt<dt)))return _t(Et("shell.dynamic-structure",Ws),ne);return null}if(ue==="find")return Yt(ne,"shell.dynamic-structure",q)&&g_(L)?_t(Et("shell.dynamic-structure",Ws),ne):null;if(ue==="rm"){let Se=L.findIndex((He,dt)=>dt>0&&t(He)==="--"),ve=Xn(L.map(t));return Yt(ne,"shell.dynamic-structure",q)&&re.some((He)=>(Se===-1||He<Se)&&(He<L.length-1||!ve))?_t(Et("shell.dynamic-structure",Ws),ne):null}if(ue==="xargs")return vp(M,L.slice(Nr(L.map(t)).childStart),"xargs",F,q,ne);if(ue==="parallel")return vp(M,L.slice(Cp(L.map(t))),"parallel",F,q,ne);return null}function vp(M,L,F,q,ne,re){if(L.length===0)return null;let ue=m_(L,q);if(No(M,ue)){let ve=_t(Et(`${F}.shell-dynamic`,F==="xargs"?rc:ci),re);if(ve)return ve}let Se=xp(M,ue,q,ne,re);if(Se)return Se;if(ue[0]?.text==="rm"&&ue.slice(1).some((ve)=>lc(ve)&&ac(ve)))return _t(Et(`${F}.rm-recursive-force-dynamic`,F==="xargs"?nc:li),re);return null}function m_(M,L){let F=wr(M,L),q=F.rewritten?Ut(F.words.map(t)):F.words,ne=q[0];return ne&&t(ne)==="busybox"?q.slice(1):q}function p_(M){let L=1;while(L<M.length){let F=M[L],q=F?t(F):"";if(yn.has(q)){L+=2;continue}if(q.startsWith("-")){L++;continue}return L}return L}function g_(M){let L=!1,F=0,q=!1,ne=!1;for(let re=1;re<M.length;re++){let ue=M[re];if(!ue)continue;let Se=lc(ue);if(F>0){F--;continue}if(ne){if(ue.text===";"||ue.text==="+"){ne=!1,L=!0,q=!1;continue}if(Se&&(q||ac(ue)))return!0;q=!1;continue}if(!L&&!ue.text.startsWith("-")){if(Se&&(re>1||ac(ue)))return!0;continue}if(L=!0,Se)return!0;let ve=Qn(ue.text);if(ve>0){F=ve;continue}if(Bn(ue.text))ne=!0,q=!0}return!1}function cc(M,L){return M.some((F)=>{if(F.value==="-"&&(F.kind==="main-script"||F.kind==="program-file"))return!0;return!Zi(L[F.tokenIndex],F.value)})}var wp=[{heads:new Set(["rm","rmdir"]),analyze:(M)=>As(M.words,_p(M))},{heads:new Set(["git"]),analyze:(M)=>ws(M.words,uc(M))},{heads:new Set(["find"]),analyze:(M)=>lm(M.words,{..._p(M),envAssignments:M.envAssignments,analyzeTokens:M.analyzeChildTokens})},{heads:new Set(["xargs"]),analyze:(M)=>Km(M.words,{...Rp(M),analyzeChild:M.analyzeChild,analyzeNested:(L,F)=>fo(M.options.analyzeNested(L,F))})},{heads:new Set(["parallel"]),analyze:(M)=>ap(M.words,{...Rp(M),analyzeChild:M.analyzeChild,analyzeNested:(L,F)=>fo(M.options.analyzeNested(L,F))})}];function Rp(M){return{environment:M.options.environment,cwd:M.cwd,originalCwd:M.originalCwd,strict:M.options.strict,paranoidRm:M.options.paranoidRm,paranoidInterpreters:M.options.paranoidInterpreters,allowTmpdirVar:M.allowTmpdirVar,protectedGitMetadata:M.options.protectedGitMetadata,budget:M.options.budget,envAssignments:M.envAssignments,worktreeMode:M.options.worktreeMode,policy:M.options.policy}}function fo(M){return M?{id:M.ruleId,reason:M.reason,intent:M.intent??"manual_only"}:null}function _p(M){return{environment:M.options.environment,cwd:M.cwd,originalCwd:M.originalCwd,strict:M.options.strict,paranoid:M.options.paranoidRm,allowTmpdirVar:M.allowTmpdirVar,tmpdirWordSplittingUnsafe:Tr(M.envAssignments,M.options.environment),trustedTmpdirValue:no(M.envAssignments,M.options.environment),protectedGitMetadata:M.options.protectedGitMetadata,policy:M.options.policy,budget:M.options.budget}}function uc(M){return{environment:M.options.environment,cwd:M.cwd,originalCwd:M.originalCwd,dynamicArguments:M.dynamicArguments,envAssignments:M.envAssignments,shellAssignments:M.options.shellAssignments,policy:M.options.policy,worktreeMode:M.options.worktreeMode}}function Tp(M){return wp.find((L)=>L.heads.has(M))?.analyze}function po(M,L,F){let q=F.trace;if(M.length===0)return null;let ne=F.commandView?.dialect??"posix",re=(Rt)=>Rt.map((Pt)=>ne==="posix"?t(Pt):Pt.text),ue=F.child,Se=ue!==void 0&&!ue.embedded,ve=ue?.embedded===!0,He=F.effectiveCwd===null,dt=ue?ue.cwd:He?void 0:F.effectiveCwd??F.cwd,mt=ue?ue.originalCwd:He?void 0:F.cwd,ft=xe(M);if(ft.envAssignments.size>0)q?.recordSegment({type:"env-strip",input:re(M),envVars:[...ft.envAssignments.keys()],output:re(ft.words)});let pt=wr(ft.words,F.environment,dt,new Map([...F.envAssignments??[],...ft.envAssignments])),ht=pt.envSplitValues??[];if(ht.length>0){let Rt=[...ht,...re(pt.words)].join(" "),Pt=_n(Rt);if(Pt)return q?.recordSegment({type:"dangerous-text",token:Rt,matched:!0,reason:Pt.reason}),an(Pt);if(F.strict)return mn(q);let Lt=os(ht,re(pt.words));if(Lt){F.budget.charge("derivedTokens",Lt.length);let Zt=F.analyzeNested(Lt.join(" "),{effectiveCwd:pt.cwd===void 0?F.effectiveCwd:pt.cwd,envAssignments:new Map([...F.envAssignments??[],...ft.envAssignments,...pt.envAssignments])});if(Zt)return Zt}}let gt=pt.rewritten?Ut(re(pt.words)):te(ne,pt.words),yt=re(gt),St={...F,wrapperNormalizationBudget:F.wrapperNormalizationBudget??{iterations:0}};if(q&&ft.words.length>gt.length){let Rt=re(ft.words);q.recordSegment({type:"leading-tokens-stripped",input:Rt,removed:Rt.slice(0,Rt.length-gt.length),output:yt})}let Ct=new Map([...F.envAssignments??[],...ft.envAssignments,...pt.envAssignments]),bt=yt[0];if(!bt)return null;if(kr(bt))throw new s("wrapperPeelIterations");let xt=It(bt),At=pt.cwd===null?void 0:pt.cwd??dt,Tt=pt.cwd===null?void 0:mt,Ot=pt.cwd===void 0?F.effectiveCwd:pt.cwd,jt=ue?ue.allowTmpdirVar:!Xo(Ct,F.environment),sn=Ep(ne,pt.words,F.environment,L===0,F.strict,F.policy);if(sn)return q?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:sn.reason}),an(sn);let jn=Cs(yt,F.policy);if(jn){for(let Rt of[jn.childIndex,...jn.alternativeChildIndices]){Pp(St.wrapperNormalizationBudget);let Pt=gt.slice(Rt);q?.recordSegment({type:"transparent-wrapper",wrapper:jn.wrapper,output:re(Pt)});let Lt=po(Pt,L,{...St,effectiveCwd:Ot,envAssignments:Ct});if(Lt)return Lt}return null}let pn=ve?void 0:xt==="eval"?Ts(gt):xt==="trap"&&!Se?zm(gt):void 0;if(Se&&ue&&xt==="eval"){if(pn?.kind==="dynamic")return mo(ue,F.policy);if(pn?.kind==="literal"){let Rt=F.analyzeNested(pn.source,{effectiveCwd:Ot,envAssignments:Ct});if(Rt)return Rt}return go(ue,F.policy)}if(pn?.kind==="dynamic"&&(F.strict||!F.commandView||!ec(F.commandView)))return mn(q);if(pn?.kind==="literal"){q?.recordSegment({type:"recurse",reason:xt==="eval"?"shell-eval":"shell-trap",innerCommand:pn.source,depth:L+1});let Rt=F.analyzeNested(pn.source,{effectiveCwd:Ot,envAssignments:Ct,functionDefinitions:F.functionDefinitions});if(Rt)return Rt}if(Se?Ht.has(xt):kp(bt,xt)){if(Jn(yt))return null;if(Se&&ue){let Rt=Nn(yt);if(Rt){if(ue.dynamicSourceInput??ue.dynamicInput){let Lt=mo(ue,F.policy);if(Lt)return Lt}if(ai(Rt)){let Lt=mo(ue,F.policy);if(Lt)return Lt}return F.analyzeNested(Rt,{effectiveCwd:Ot,envAssignments:Ct})}let Pt=er(gt);if(Pt.kind==="dynamic")return mo(ue,F.policy);if(Pt.kind==="literal")return ue.dynamicSourceInput?mo(ue,F.policy):null;return ue.dynamicSourceInput??ue.dynamicInput?mo(ue,F.policy):null}if(ve){let Rt=Nn(yt),Pt=Rt?F.analyzeNested(Rt,{effectiveCwd:Ot,envAssignments:Ct}):er(gt).kind==="dynamic"?mn(q):null;if(Pt)return Pt}if(ue===void 0){let Rt=S_(yt,Ct,Ot,F,q,L);if(Rt)return Rt;let Pt=Nn(yt);if(Pt){let zr=Is(gt,Pt);if(zr.kind==="dynamic")return mn(q);let Zs=zr.kind==="literal"?zr.source:Bm(gt,Pt),Nc=C_(Zs);q?.recordSegment({type:"shell-wrapper",wrapper:xt,innerCommand:Nc}),q?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:Nc,depth:L+1});let Lc=F.analyzeNested(Zs,{effectiveCwd:Ot,envAssignments:Ct});if(Lc)return Lc;return ai(Zs)?mn(q):null}let Lt=er(gt,F.strict?void 0:F.shellAssignments);if(Lt.kind==="dynamic")return mn(q);if(Lt.kind==="literal")return Gs(Lt.source,Ot,Ct,F,q,L);let Zt=$m(gt,F.commandView?.redirections??[],F.hasPipelineInput??!1,F.literalShellInput);if(Zt.kind==="dynamic")return mn(q);if(Zt.kind==="literal")return q?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:Zt.source,depth:L+1}),F.analyzeNested(Zt.source,{effectiveCwd:Ot,envAssignments:Ct})}}if(!ue&&(xt==="source"||xt===".")){let Rt=yt[1]==="-p"?2:null;if(Rt!==null){let zr=F.commandView?gt[Rt]:void 0;if(!zr)return null;if(zr.provenance!=="literal")return mn(q)}let Pt=Rt===null?1:3,Lt=yt[Pt]==="--"?Pt+1:Pt,Zt=F.commandView?gt[Lt]:void 0;if(!Zt)return null;if(Zt.provenance==="literal")return Gs(Zt.text,Ot,Ct,F,q,L);if(F.strict||!F.commandView||!ec(F.commandView))return mn(q)}if(Rn.has(xt)&&!ve){if(!ue&&F.strict&&cc(ni(yt),gt))return mn(q);let Rt=Qf(yt,(Lt)=>fo(F.analyzeNested(Lt,{effectiveCwd:Ot,envAssignments:Ct}))),Pt=_t(Rt,F.policy);if(Pt)return q?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:Pt.reason}),an(Pt)}if(Tn(xt)&&!ve){if(!ue&&F.strict&&cc(es(yt),gt))return mn(q);let Rt=Yd(yt);if(Se&&ue)return y_(xt,Rt,Ot,Ct,F,ue);if(Rt){let Pt=Yt(F.policy,"interpreter.one-liner-paranoid",!!F.paranoidInterpreters);if(q?.recordSegment({type:"interpreter",interpreter:xt,codeArg:Rt,paranoidBlocked:Pt}),Pt){let Zt=_t(Et("interpreter.one-liner-paranoid",Uo),F.policy);if(Zt)return an(Zt)}if(fl(xt,Rt))return null;q?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:Rt,depth:L+1});let Lt=F.analyzeNested(Rt,{effectiveCwd:Ot,envAssignments:Ct});if(Lt&&!Ip(Lt,Rt))return Lt;if(Ho(Rt,void 0,!F.strict)){let Zt=_t(Et("interpreter.dangerous-command",Qr),F.policy);if(Zt)return q?.recordSegment({type:"dangerous-text",token:Rt,matched:!0,reason:Qr}),an(Zt)}q=void 0}}if(xt==="busybox"&&yt.length>1)return Pp(St.wrapperNormalizationBudget),q?.recordSegment({type:"busybox",subcommand:yt[1]??"unknown"}),q?.recordSegment({type:"recurse",reason:"busybox",innerCommand:yt.slice(1).join(" "),depth:L+1}),po(gt.slice(1),L,{...St,effectiveCwd:Ot,envAssignments:Ct});let Gt=ue?null:_t(om(xt,yt),F.policy);if(Gt)return q?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:Gt.reason}),an(Gt);let Mt=q===St.trace?St:{...St,trace:q},nn={words:gt,head:xt,cwd:At,originalCwd:Tt,envAssignments:Ct,allowTmpdirVar:jt,dynamicArguments:pt.words.some((Rt)=>Rt.provenance==="command-substitution"),depth:L,effectiveCwd:Ot,options:Mt,analyzeChildTokens:(Rt,Pt)=>Se&&ue?fc(Rt,L,Mt,{...ue,cwd:Pt??void 0,effectiveCwd:Pt??void 0}):fo(po(Ut(Rt),L+1,{...Mt,child:void 0,commandView:void 0,effectiveCwd:Pt,envAssignments:Ct}))??A(Rt,Mt.policy.rules),analyzeChild:(Rt,Pt)=>fc(Rt,L,Mt,Pt)},Kt=ue&&(xt==="xargs"||xt==="parallel")?void 0:Tp(xt);if(xt==="rm"||xt==="xargs"||xt==="parallel")q?.recordSegment({type:"tmpdir-check",tmpdirValue:Ct.has("TMPDIR")||F.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:jt});let qt=q&&xt==="git"?Om(nn.words,uc(nn)):void 0,gn=Ap(qt?qt.match:Kt?.(nn)??null,F.policy);if(q)v_(nn,gn,qt?.relaxation??null);if(gn)return an(gn);if(Se&&ue&&(xt==="rm"||xt==="rmdir")){if(!(xt==="rm"&&(Xn(yt)||ue.dynamicRmInput)))return null;return(ue.dynamicRmInput?go(ue,F.policy):null)??b_(ue,F.policy)}let yr=!ue&&Kt===void 0&&!Pi.has(xt),So=q&&yr?[]:void 0;if(yr)for(let Rt=1;Rt<yt.length;Rt++){let Pt=yt[Rt];if(!Pt)continue;So?.push(Pt);let Lt=Ap(h_(yt,Rt,L,Mt,At,Tt,Ot,Ct),F.policy);if(Lt)return q?.recordSegment({type:"fallback-scan",tokensScanned:So??[],embeddedCommandFound:It(Pt)}),an(Lt)}if(q?.recordSegment({type:"fallback-scan",tokensScanned:So??[]}),ve&&ue&&!ue.wrappedByTransparent)return null;let En=A(yt,F.policy.rules);if(q?.recordSegment({type:"custom-rules-check",rulesChecked:F.policy.rules.length>0,matched:!!En,reason:En?.reason}),En)return an(En);return Se&&ue?go(ue,F.policy):null}function fc(M,L,F,q){return fo(po(Ut(M),L+1,{...F,trace:void 0,commandView:void 0,hasPipelineInput:void 0,literalShellInput:void 0,functionDefinitions:void 0,cwd:q.originalCwd,effectiveCwd:q.effectiveCwd,envAssignments:q.envAssignments,worktreeMode:q.dynamicInput?!1:q.worktreeMode,wrapperNormalizationBudget:{iterations:0},child:q}))}function h_(M,L,F,q,ne,re,ue,Se){for(let ve of Dn(M.slice(L),{environment:q.environment,cwd:ne,envAssignments:Se,policy:q.policy})){let He=ve.tokens[0];if(!He)continue;let dt=It(He);if(kp(He,dt)||Tp(dt)!==void 0&&dt!=="xargs"&&dt!=="parallel"||ve.wrappedByTransparent&&q.policy.rules.length>0)q.budget.charge("derivedTokens",M.length-L);let ft=fc(ve.tokens,F,q,{embedded:!0,cwd:ve.cwd,originalCwd:ve.wrapperCwd===null?void 0:re,effectiveCwd:ve.wrapperCwd===void 0?ue:ve.wrapperCwd,envAssignments:ve.envAssignments,allowTmpdirVar:!Xo(ve.envAssignments,q.environment),worktreeMode:!1,wrappedByTransparent:ve.wrappedByTransparent});if(ft)return ft}return null}function y_(M,L,F,q,ne,re){if(!L)return go(re,ne.policy);if(Yt(ne.policy,"interpreter.one-liner-paranoid",!!ne.paranoidInterpreters)){let Se=_t(Et("interpreter.one-liner-paranoid",Uo),ne.policy);if(Se)return an(Se)}if(fl(M,L))return go(re,ne.policy);let ue=ne.analyzeNested(L,{effectiveCwd:F,envAssignments:q});if(ue&&!Ip(ue,L))return ue;if(Ho(L,void 0,!ne.strict)){let Se=_t(Et("interpreter.dangerous-command",Qr),ne.policy);if(Se)return an(Se)}return go(re,ne.policy)}function Ip(M,L){let F=M.ruleId==="raw-text.dangerous-command",q=(M.reason.startsWith(ys)||M.reason===io)&&!Ai(L);return F||q}function mo(M,L){let F=M.shellDynamicMatch?_t(M.shellDynamicMatch,L):null;return F?an(F):null}function go(M,L){let F=M.dynamicSourceInput&&M.dynamicSourceMatch?_t(M.dynamicSourceMatch,L):null;return F?an(F):null}function b_(M,L){let F=M.dynamicInput&&M.rmDynamicMatch?_t(M.rmDynamicMatch,L):null;return F?an(F):null}function S_(M,L,F,q,ne,re){let ue=am(M);if(ue.argvSource?.kind==="absent")return mn(ne);if(ue.argvSourceApplies&&ue.argvSource){let ve=Gs(ue.argvSource.value,F,L,q,ne,re,!0);if(ve)return ve}if(!ue.envSourceApplies||!ue.envName)return null;let Se=L.get(ue.envName);if(!Se)return null;return Gs(Se,F,L,q,ne,re,!0)}function Gs(M,L,F,q,ne,re,ue=!1){if(ue&&/[$`*?[\]]/.test(M))return mn(ne);let Se=$o(M,L,q.environment.paths,q.budget),ve=Se?q.literalHeredocFiles?.get(Se):void 0;if(ve===void 0)return ue?mn(ne):null;return q.budget.charge("derivedTokens",1),ne?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:ve,depth:re+1}),q.analyzeNested(ve,{effectiveCwd:L,envAssignments:F})}function C_(M){let L=M[0];return M.length>=2&&(L==='"'||L==="'")&&M.at(-1)===L?M.slice(1,-1):M}function v_(M,L,F){let q={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[M.head];if(!q)return;if(M.options.trace?.recordSegment({type:"rule-check",rule:q,matched:!!L||!!F,reason:L?.reason??F?.originalReason}),F)M.options.trace?.recordSegment({type:F.kind==="worktree"?"worktree-relaxation":"temp-root-relaxation",originalReason:F.originalReason,gitCwd:F.gitCwd})}function Pp(M){if(M.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");M.iterations++}function an(M){return{reason:M.reason,ruleId:M.id,intent:M.intent}}function mn(M){return M?.recordSegment({type:"error",message:ei}),an(E_())}function E_(){return{id:"analysis.dynamic-shell-source",reason:ei,intent:"stop_and_explain"}}function kp(M,L){return Ht.has(L)||M==="$SHELL"||M==="${SHELL}"||Ht.has(wt(L))}function Ap(M,L){return M?.id.startsWith("custom.")||M?.id==="raw-text.dangerous-command"?M:_t(M,L)}var x_=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,R_=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function __(M,L){let F=Dp(M,L);if(F.length===0)return!1;let q=F[Mp(F)];if(q==="cd"||q==="pushd"||q==="popd")return!0;return x_.test(M.join(" "))}function Op(M,L,F,q,ne){if(M.dialect==="powershell"){let bt=w_(M.words,ne);if(bt.kind==="none")return;if(!L||bt.kind==="unknown")return null;return dc(I_(bt.target),L,F.paths)}let re=M.words.map(t),ue=re.some((bt)=>/^CDPATH\+?=/.test(bt));if(!__(re,F))return ue?null:void 0;if(!L)return null;let Se=Dp(re,F,L),ve=Mp(Se);if(ve===-1||Se[ve]!=="cd")return null;let He=Se.slice(ve+1),dt=He.findIndex((bt)=>bt.length<=1||!bt.startsWith("-")||bt==="--");if((dt===-1?He:He.slice(0,dt)).some((bt)=>!/^-[LP]+$/.test(bt)))return null;let ft=dt===-1?[]:He.slice(dt),pt=ft[0]==="--"?ft.slice(1):ft;if(pt.length>1)return null;let ht=pt[0],gt=q.get("HOME")||F.home;if(ht===void 0)return dc(gt,L,F.paths);let yt=M.words.find((bt)=>bt.provenance==="variable"&&bt.text===ht),St=M.words.find((bt)=>bt.text===ht&&/^~(?:\/|$)/.test(bt.raw)),Ct=yt?$n(yt,new Map([...q,["HOME",gt]])):St?`${gt}${ht.slice(1)}`:ht;if(Ct===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(Ct)&&(ue||F.env.has("CDPATH")))return null;return dc(Ct,L,F.paths)}function dc(M,L,F){if(!M||M==="-"||M.startsWith("~")||M.includes("$")||M.includes("`"))return null;try{let q=sr(L,M,F);return F.isDirectory(q)?q:null}catch{return null}}function w_(M,L){let F=P_(M[0])?1:0,q=M[F];if(!A_(q,F===1))return{kind:"none"};let ne=q.text.toLowerCase(),re=ne.split(/[\\/]/).pop()??ne;if(!R_.has(re))return{kind:"none"};if(ne!==re||re==="pop-location"||re==="popd")return{kind:"unknown"};return T_(M.slice(F+1),L)}function P_(M){return M?.provenance==="literal"&&!M.quoted&&M.raw===M.text&&(M.text==="&"||M.text===".")}function A_(M,L){return M?.provenance==="literal"&&(L||!M.quoted&&M.raw===M.text)}function T_(M,L){let F;for(let q of M){if(q.provenance!=="literal"||F!==void 0)return{kind:"unknown"};F=q.text}if(F!==void 0)return{kind:"target",target:F};return L===void 0?{kind:"unknown"}:{kind:"target",target:L}}function I_(M){return M.includes("::")?void 0:M.replaceAll("\\","/")}function Mp(M){let L=0;if(M[0]==="builtin"&&M.length>1)L=1;if(M[L]!=="time")return L;let F=L+1;while(M[F]?.startsWith("-"))F++;return F}function Dp(M,L,F){let q=k_(M);return ar([...q],L,F)}function k_(M){let L=0;while(L<M.length){let F=M[L];if(F!=="{"&&F!=="("&&F!=="$(")break;L++}return M.slice(L)}var G_="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Lr="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.";function bc(M,L,F,q){if(L>=a.recursionDepth.cap)return F.trace?.recordSegment({type:"error",message:Gn}),{reason:Gn,segment:M,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};let ne=q??F.factStore?.getCommandProgram(M,F.shell??"auto")??h(M,F.shell);if(ne.status==="limited")return F.trace?.recordSegment({type:"error",message:Gn}),{reason:Gn,segment:M,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};if(ne.status==="invalid"){let He=ne.issues.find((dt)=>dt.code.includes("heredoc"));if(He){if(!F.strict)return yc(M,F);let dt=`${ys}: ${He.message}`;return F.trace?.recordGlobal({type:"error",message:dt}),{reason:dt,segment:M,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"}}return zp(M,F),{reason:io,segment:M,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"}}if(F.strict&&ne.status==="partial")return zp(M,F),{reason:io,segment:M,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"};if(ne.issues.some((He)=>He.code.includes("quote")))return yc(M,F);let ue=F.cwd,Se=F.effectiveCwd!==void 0?F.effectiveCwd:F.cwd,ve=Cm(F.environment.env,F.envAssignments);return Bs(ne,L,{...F,rootProgram:ne},ue,[{effectiveCwd:Se,shellGitContextState:ve,literalHeredocFiles:new Map(F.literalHeredocFiles),functionDefinitions:new Map(F.functionDefinitions),createdDirectories:new Set,compoundBodies:[]}]).result}function Bs(M,L,F,q,ne){let re=[...ne],ue,Se,ve;for(let[He,dt]of M.nodes.entries()){if(dt.kind==="connector"){Se=dt.operator;continue}let mt=M.nodes[He+1],ft=mt?.kind==="connector"?mt.operator:void 0,pt=F_(M,He,dt,Se,ft),gt=Se==="&&"||Se==="||"?ue:void 0,yt=Se==="&&"?gt?.success??re:Se==="||"?gt?.failure??re:re,St=Se==="||"?gt?.success??[]:[],Ct=Se==="&&"?gt?.failure??[]:[],bt={connector:Se,skippedSuccessStates:St,skippedFailureStates:Ct};if(pr(ft)&&!pr(Se))ve=bt;let xt=pr(ft)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:pr(Se)?ve??bt:bt,At=Wr(xt.connector)||Wr(ft);if(dt.kind==="function"){let Gt=yt.flatMap((nn)=>{let Kt=Gr(nn);return Kt.functionDefinitions.set(dt.name,dt.body),mc(nn,[Kt],pt,ft==="&",Wr(ft))}),Mt=pc(Gt,[],xt.skippedSuccessStates,xt.skippedFailureStates,xt.connector,ft);re=Mt.states,ue=Mt.conditionalStates,Se=void 0;continue}if(dt.kind==="group"){let Gt=[],Mt=[];for(let Kt of yt){let qt=Bs(dt.body,L,F,q,[Gr(Kt)]);if(qt.result)return qt;if(Gt.push(...mc(Kt,qt.states,pt,ft==="&",Wr(ft))),At)Mt.push(Kt,...pt?qt.states.map((gn)=>Fs(Kt,gn)):qt.states)}let nn=pc(Gt,Mt,xt.skippedSuccessStates,xt.skippedFailureStates,xt.connector,ft);re=nn.states,ue=nn.conditionalStates,Se=void 0;continue}if(dt.kind!=="command")continue;let Tt=lw(M.nodes[He-1]),Ot=F.trace?.flattenNested?F.trace.currentSegmentIndex:F.trace?.allocateSegment(),jt=M.nodes[He-2],sn=pr(Se)&&jt?.kind==="command"?Fm(jt)??B_(jt):void 0,jn=[],pn=[];for(let Gt of yt){let Mt=$_(dt,L,F,q,[Gr(Gt)]);if(Mt.result)return{result:Mt.result,states:re};let nn=M.dialect==="powershell"?Mt.states:Mt.states.map((Kt)=>Fs(Gt,Kt));for(let Kt of nn){let qt=Gr(Kt),gn=j_(dt,L,F.trace?{...F,trace:Bp(F.trace,Ot)}:F,q,qt,pr(Se),sn);if(gn)return{result:gn,states:re};let bo=gw(dt,qt.functionDefinitions);if(bo)F.budget.charge("derivedTokens",$s(bo));let yr=bo?L+1>=a.recursionDepth.cap?gc(dt.displayText,F,[qt]):Bs(bo,L+1,F,q,[qt]):{result:null,states:mw(dt,qt).flatMap((En)=>cw(dt,Kt,En,Tt))};if(yr.result)return yr;jn.push(...mc(Gt,yr.states,pt,ft==="&",Wr(ft)));let So=typeof qt.effectiveCwd==="string"&&qt.effectiveCwd!==Kt.effectiveCwd&&dt.redirections.every((En)=>["<",">",">>",">|"].includes(En.operator)&&En.target?.text==="/dev/null");if(At&&(Tt||!So))pn.push(Gt),pn.push(...yr.states.map((En)=>pt?Fs(Gt,En):En))}}let hr=pc(jn,pn,xt.skippedSuccessStates,xt.skippedFailureStates,xt.connector,ft);re=hr.states,ue=hr.conditionalStates,Se=void 0}return{result:null,states:re}}function F_(M,L,F,q,ne){if(F.kind==="group"&&F.style==="subshell")return!0;if(M.dialect==="posix"&&(pr(q)||pr(ne)))return!0;if(ne==="&")return!0;return M.dialect==="powershell"&&F.kind==="group"&&F.style==="brace"&&z_(M,L)}function mc(M,L,F,q,ne){let re=F?L.map((Se)=>Fs(M,Se)):[...L],ue=ne?re.flatMap((Se)=>ho(M.literalHeredocFiles,Se.literalHeredocFiles)?[Se]:[{...Se,literalHeredocFiles:new Map(M.literalHeredocFiles)},Se]):re;return q?[M,...ue]:ue}function Fs(M,L){return{...M,literalHeredocFiles:new Map(L.literalHeredocFiles),createdDirectories:new Set(L.createdDirectories)}}function z_(M,L){let F=M.nodes.slice(0,L).reverse().find((ne)=>ne.kind==="command"||ne.kind==="connector");if(!F||F.kind!=="command")return!0;let q=F.words[0]?.text.toLowerCase();if(q==="&"||q===".")return!1;if(q==="write-output"||q==="function"||q==="start-job")return!0;if(U_(F))return!0;return F.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function pr(M){return M==="|"||M==="|&"}function B_(M){if(M?.dialect!=="powershell")return;if(M.words.length===1&&M.words[0]?.quoted&&M.words[0].provenance==="literal")return M.words[0].text;if(M.words[0]?.text.toLowerCase()==="write-output"&&M.words.length===2&&M.words[1]?.provenance==="literal")return M.words[1].text;return}function Wr(M){return M==="&&"||M==="||"}function pc(M,L,F,q,ne,re){let ue={success:zs([...F,...M]),failure:zs([...q,...L])},Se=Wr(re)?ue:void 0;return{states:Wr(ne)||Se?zs([...ue.success,...ue.failure]):ue.success,conditionalStates:Se}}function Bp(M,L,F=M.flattenNested){return{currentSegmentIndex:L,flattenNested:F,allocateSegment:M.allocateSegment,getNextSegmentIndex:M.getNextSegmentIndex,recordGlobal:M.recordGlobal,recordSegment:(q,ne=L)=>M.recordSegment(q,ne)}}function $_(M,L,F,q,ne){let re=M.nested.map((ue)=>({program:ue,depth:L}));if(M.dialect==="powershell"){let ue=H_(M);if(ue){if(L+1>=a.recursionDepth.cap)return gc(ue,F,ne);let Se=h(ue,"powershell");if(Se.status==="limited")return gc(ue,F,ne);if(Se.status!=="complete")return Np(re,F,q,ne);F.budget.charge("derivedTokens",$s(Se)),re.push({program:Se,depth:L+1})}}return Np(re,F,q,ne)}function U_(M){let L=M.words[0];return L?.provenance==="variable"&&M.words.at(-1)?.text==="="?L.text.toLowerCase():void 0}function Np(M,L,F,q){let ne=[...q];for(let re of M){let ue=[];for(let Se of ne){let ve=Bs(re.program,re.depth,L,F,[Gr(Se)]);if(ve.result)return ve;ue.push(...ve.states)}ne=zs(ue)}return{result:null,states:ne}}function H_(M){let L=M.words[0]?.provenance==="literal"&&!M.words[0].quoted&&M.words[0].raw===M.words[0].text&&(M.words[0].text==="&"||M.words[0].text==="."),F=L?1:0,q=M.words[F];if(q?.provenance!=="literal"||!L&&(q.quoted||q.raw!==q.text)||!["iex","invoke-expression"].includes(q.text.toLowerCase()))return;let ne=M.words.slice(F+1),re=ne[0]&&!ne[0].quoted&&ne[0].raw===ne[0].text&&["-c","-command"].includes(ne[0].text.toLowerCase())?1:0,ue=ne[re];return ne.length===re+1&&ue?.quoted&&ue.provenance==="literal"?ue.text:void 0}function $s(M){return M.nodes.reduce((L,F)=>L+(F.kind==="command"?F.words.length+F.nested.reduce((q,ne)=>q+$s(ne),0):F.kind==="group"||F.kind==="function"?$s(F.body):0),0)}function gc(M,L,F){return L.trace?.recordSegment({type:"error",message:Gn}),{result:{reason:Gn,segment:M,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"},states:[...F]}}function j_(M,L,F,q,ne,re,ue){let Se={...F,environment:{...F.environment,env:ne.shellGitContextState.env,paths:Z_(F.environment.paths,ne.createdDirectories,F.budget)}},ve=nw(M,!Se.strict);if(ve&&Se.strict)return Se.trace?.recordSegment({type:"error",message:ve}),{reason:ve,segment:M.source,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"};$p(M,ne,"before-consumer",Se.environment.paths,Se.budget);let He=te(M.dialect,M.words),dt=He.map(t),mt=M.displayText,ft=bm(He,ne.shellGitContextState),pt=Em(ft,ne.shellGitContextState);if(M.dialect==="powershell"){let yt=_t(jf(M,re,yw(Se,ne.effectiveCwd)),Se.policy);if(Se.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!yt,reason:yt?.reason}),yt)return hw(mt,yt)}if(dt.length===1&&dt[0]?.includes(" ")&&!No(M.dialect,M.words)){let yt=_t(_n(dt[0]),Se.policy),St=yt!==null&&!Se.strict&&jd(M,Se.rootProgram);if(yt&&!St)return Se.trace?.recordSegment({type:"dangerous-text",token:dt[0],matched:!0,reason:yt.reason}),{reason:yt.reason,segment:mt,ruleId:yt.id,intent:yt.intent};Se.trace?.recordSegment({type:"dangerous-text",token:dt[0],matched:!1});let Ct=Lp(M,ve,ne,pt,ue,Se);if(Ct)return Ct;return ql(ft,ne.shellGitContextState),null}let ht=po(M.words,L,{...Se,commandView:M,cwd:q,effectiveCwd:ne.effectiveCwd,envAssignments:pt,shellAssignments:ne.shellGitContextState.shellAssignments,literalHeredocFiles:ne.literalHeredocFiles,functionDefinitions:ne.functionDefinitions,hasPipelineInput:re,literalShellInput:ue,analyzeNested:(yt,St)=>{let Ct=St&&Object.hasOwn(St,"effectiveCwd")?St.effectiveCwd:ne.effectiveCwd,bt=bc(yt,L+1,{...Se,effectiveCwd:Ct,envAssignments:St?.envAssignments??pt,literalHeredocFiles:ne.literalHeredocFiles,functionDefinitions:St?.functionDefinitions,worktreeMode:St?.worktreeMode??Se.worktreeMode,trace:Se.trace?Bp(Se.trace,Se.trace.currentSegmentIndex,!0):void 0});return bt?{reason:bt.reason,ruleId:bt.ruleId,intent:bt.intent}:null}});if(ht)return{...ht,segment:mt};let gt=Lp(M,ve,ne,pt,ue,Se);if(gt)return gt;return ql(ft,ne.shellGitContextState),null}function Lp(M,L,F,q,ne,re){let ue=rw(M,L,F,q??new Map,re);if(ue)return ue;return $p(M,F,"after-consumer",re.environment.paths,re.budget),F.literalHeredocFiles.clear(),q_(M,L,F,re.environment.paths,re.budget),X_(M,F,re.environment.paths,re.budget),sw(M,F,ne,re.environment,re.trace),null}var V_=new Set([">>","<>"]);function $p(M,L,F,q,ne){for(let ue of M.redirections){if(!(F==="before-consumer"?K_(ue):V_.has(ue.operator)))continue;Wp(ue.target,L,q,ne)}if(F!=="before-consumer"||!tn(M.words[0],"tee"))return;let re=Hp(M.words.slice(1));if(!re)return;for(let ue of re.operands)Wp(ue,L,q,ne)}function K_(M){if(M.operator===">"||M.operator===">|")return!0;return M.operator===">&"&&M.fd===void 0&&M.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(M.target.text)}function Wp(M,L,F,q){let ne=M?.provenance==="literal"?$o(M.text,L.effectiveCwd,F,q):void 0;if(!ne)return;L.literalHeredocFiles.delete(ne)}function q_(M,L,F,q,ne){if(L)return;let re=M.redirections.find((ue)=>ue.operator==="<<"||ue.operator==="<<-")?.heredoc;if(!re)return;for(let ue of Y_(M,F.shellGitContextState.shellAssignments)){let Se=$o(ue,F.effectiveCwd,q,ne);if(!Se||!qd(Se))continue;if(!F.literalHeredocFiles.has(Se)&&F.literalHeredocFiles.size>=a.trackedHeredocFiles.cap)throw new s("trackedHeredocFiles");F.literalHeredocFiles.set(Se,re.body)}}function Y_(M,L){let F=hc(ew(M.redirections)?.target,L),q=F===void 0?[]:[F];if(tn(M.words[0],"cat"))return Q_(M.words)?q:[];if(!tn(M.words[0],"tee"))return[];let ne=Hp(M.words.slice(1),L);if(!ne||ne.append||ne.hasUnsupportedOptions)return[];let re=ne.operands.map((ue)=>hc(ue,L));if(!re.every((ue)=>ue!==void 0))return[];return[...re,...q]}function hc(M,L){if(tw(M))return M.text;return(M&&$n(M,L))??void 0}function Z_(M,L,F){if(L.size===0)return M;let q=(ne)=>{let re=Dt(ne,M,F);return[...L].some((ue)=>ue===re||ue.startsWith(`${re}${W_}`))};return{realpath:(ne)=>M.realpath(ne)??(q(ne)?Dt(ne,M,F):null),entryKind:(ne)=>{let re=M.entryKind(ne);return re==="missing"&&q(ne)?"present":re},isDirectory:(ne)=>M.isDirectory(ne)||q(ne)}}function X_(M,L,F,q){if(L.shellGitContextState.bodyDepth>0||!tn(M.words[0],"mkdir"))return;let ne=M.words.slice(1).map((He)=>hc(He,L.shellGitContextState.shellAssignments));if(!ne.every((He)=>He!==void 0))return;let re=ne.findIndex((He)=>He==="--"||He==="-"||!He.startsWith("-")),ue=ne.slice(0,re);if(re===-1||!ue.every((He)=>/^(?:-[pv]+|--parents|--verbose)$/.test(He)))return;let Se=ue.some((He)=>He==="--parents"||/^-v*p/.test(He)),ve=L.effectiveCwd;for(let He of ne.slice(ne[re]==="--"?re+1:re)){if(He.split(/[\\/]/).includes("..")||!M_(He)&&!ve)continue;let dt=Dt(L_(ve??"",He),F,q);if(Se?J_(dt,F):F.isDirectory(O_(dt))&&Up(dt,F))L.createdDirectories.add(dt)}}function J_(M,L){let F=N_(M).root,q=M.slice(F.length).split(/[\\/]+/).filter(Boolean),ne=(ue)=>D_(F,...q.slice(0,ue+1)),re=q.findIndex((ue,Se)=>!L.isDirectory(ne(Se)));return re===-1||Up(ne(re),L)}function Up(M,L){try{return L.entryKind(M)==="missing"}catch{return!1}}function Q_(M){let L=!1;for(let F of M.slice(1)){if(L||F.provenance!=="literal")return!1;if(F.text==="--"){L=!0;continue}if(!/^-u+$/.test(F.text))return!1}return!0}function ew(M){let L=M.findLast((F)=>(F.fd??([">",">|",">>",">&"].includes(F.operator)?1:0))===1);return L?.operator===">"||L?.operator===">|"?L:void 0}function Hp(M,L=new Map){let F=[],q=!0,ne=!1,re=!1;for(let ue of M){if(ue.provenance!=="literal"&&$n(ue,L)===null)return;if(q&&tn(ue,"--")){q=!1;continue}if(q&&!ue.quoted&&ue.raw===ue.text&&/^-[^-]/.test(ue.text)){ne||=ue.text.slice(1).includes("a"),re||=Array.from(ue.text.slice(1)).some((Se)=>Se!=="a"&&Se!=="i");continue}if(q&&!ue.quoted&&ue.raw===ue.text&&ue.text.startsWith("--")){ne||=ue.text==="--append",re||=ue.text!=="--append"&&ue.text!=="--ignore-interrupts";continue}F.push(ue)}return{operands:F,append:ne,hasUnsupportedOptions:re}}function tw(M){if(!M||M.provenance!=="literal"||M.text.length===0)return!1;if(M.quoted||M.raw!==M.text)return!0;return!M.raw.startsWith("~")&&!/[{}]/.test(M.raw)}function tn(M,L){return M?.text===L&&M.raw===L&&M.provenance==="literal"&&!M.quoted}function Sc(M){return M.quotedDelimiter||!/[$`\\]/.test(M.body)}function nw(M,L){let F=M.redirections.filter((ve)=>ve.operator==="<<"||ve.operator==="<<-");if(F.length===0)return;if(F.length!==1)return Lr;let q=F[0];if(!q?.heredoc)return Lr;let ne=/\$\(|`/.test(q.heredoc.body);if(!Sc(q.heredoc)&&(!L||ne))return G_;if(q.fd!==void 0&&q.fd!==0)return Lr;if(M.redirections.some((ve)=>ve!==q&&["<","<<","<<-","<<<","<&","<>"].includes(ve.operator)))return Lr;let re=M.redirections.some((ve)=>ve!==q&&Gp(ve.target));if(tn(M.words[0],"cat"))return re?Lr:void 0;if(tn(M.words[0],"tee"))return re||M.words.slice(1).some(Gp)?Lr:void 0;let ue=M.words[0],Se=M.words[1];if(tn(ue,"git")&&(tn(Se,"apply")||tn(Se,"commit")))return;if(tn(ue,"gh")&&(tn(Se,"pr")||tn(Se,"issue"))&&tn(M.words[2],"create"))return;return Lr}function Gp(M){return M?.parts.some((L)=>L.provenance==="command-substitution"&&L.raw.startsWith(">("))??!1}function rw(M,L,F,q,ne){if(!L)return null;let re=M.redirections.filter((He)=>He.operator==="<<"||He.operator==="<<-"),ue=re.flatMap((He)=>He.heredoc?[He.heredoc.body]:[]);if(iw(M,re,F,q,ne))return null;let Se=ow(M,re,ne);if(Se!==void 0)return Se?{reason:Se.reason,segment:M.displayText,ruleId:Se.id,intent:Se.intent}:null;let ve=yc(ue.length===re.length?ue.join(`
|
|
41
|
+
`):M.source,ne);return ve?{...ve,segment:M.displayText}:null}function ow(M,L,F){let q=L.length===1?L[0]:void 0;if(!q?.heredoc||!Sc(q.heredoc)||q.fd!==void 0&&q.fd!==0)return;let ne=tn(M.words[0],"uv")&&tn(M.words[1],"run")?M.words.slice(2):M.words,re=ne[0];if(re?.provenance!=="literal"||!Tn(re.text))return;let ue=ne.findIndex((mt)=>tn(mt,"-"));if(!ne.slice(1,ue===-1?void 0:ue).every((mt)=>mt.provenance==="literal"&&mt.text.startsWith("-")))return;let ve=q.heredoc.body,He=Yt(F.policy,"interpreter.one-liner-paranoid",!!F.paranoidInterpreters);if(F.trace?.recordSegment({type:"interpreter",interpreter:re.text,codeArg:ve,paranoidBlocked:He}),He){let mt=_t(Et("interpreter.one-liner-paranoid",Uo),F.policy);if(mt)return mt}if(!Ho(ve,void 0,!F.strict))return null;let dt=_t(Et("interpreter.dangerous-command",Qr),F.policy);if(!dt)return null;return F.trace?.recordSegment({type:"dangerous-text",token:ve,matched:!0,reason:dt.reason}),dt}function iw(M,L,F,q,ne){let re=L.length===1?L[0]:void 0;if(!re?.heredoc||!Sc(re.heredoc)||re.fd!==void 0&&re.fd!==0)return!1;let ue=wr(M.words,ne.environment,F.effectiveCwd,q),Se=ue.words.map(t),ve=It(Se[0]??"");if((ue.envSplitValues?.length??0)>0||!Ht.has(ve)&&!Ht.has(wt(ve)))return!1;return Jn(Se)}function sw(M,L,F,q,ne){let re=Op(M,L.effectiveCwd,q,L.shellGitContextState.shellAssignments,F);if(re===null)ne?.recordSegment({type:"cwd-change",segment:M.words.map(t).join(" "),effectiveCwdNowUnknown:!0});if(re!==void 0)L.effectiveCwd=re}var aw=new Set(["fi","done","esac"]);function lw(M){return M?.kind==="command"&&M.words.length===1&&M.words[0]?.raw==="!"}function cw(M,L,F,q){let ne=M.words[0]?.text??"",re=L.shellGitContextState.bodyDepth,ue=F.shellGitContextState.bodyDepth,Se=F.compoundBodies;if(ue>re)return F.compoundBodies=[...Se.slice(0,re),{entryCwd:L.effectiveCwd,branchCwds:Se[re]?.branchCwds??[],hasElse:!1}],[F];let ve=re>0?Se[re-1]:void 0;if(ve&&(ne==="else"||ne==="elif"))return F.compoundBodies=[...Se.slice(0,re-1),{entryCwd:ve.entryCwd,branchCwds:[...ve.branchCwds,F.effectiveCwd],hasElse:ne==="else"}],F.effectiveCwd=ve.entryCwd,[F];let He=ve!==void 0&&aw.has(ne);if(He)F.compoundBodies=Se.slice(0,ue);return[...new Set([F.effectiveCwd,...He?ve.branchCwds:[],...He&&!ve.hasElse?[ve.entryCwd]:[],...q?[L.effectiveCwd]:[]])].map((mt)=>{if(mt===F.effectiveCwd)return F;let ft=Gr(F);return ft.effectiveCwd=mt,ft})}function uw(M,L){return M.length===L.length&&M.every((F,q)=>{let ne=L[q];return ne!==void 0&&F.entryCwd===ne.entryCwd&&F.hasElse===ne.hasElse&&F.branchCwds.length===ne.branchCwds.length&&F.branchCwds.every((re,ue)=>re===ne.branchCwds[ue])})}var dw=/^[A-Za-z_][A-Za-z0-9_]*$/,fw=8;function mw(M,L){let F=M.words[1]?.text;if(M.dialect!=="posix"||M.words[0]?.text!=="for"||F===void 0||!dw.test(F))return[L];let q=M.words.slice(3);if(!(M.words[2]?.text==="in"&&q.length>=1&&q.length<=fw&&q.every((re)=>re.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(re.text))))return L.shellGitContextState.shellAssignments.delete(F),[L];return q.map((re)=>{let ue=Gr(L);return ue.shellGitContextState.shellAssignments.set(F,re.text),ue})}function Gr(M){return{effectiveCwd:M.effectiveCwd,shellGitContextState:vm(M.shellGitContextState),literalHeredocFiles:new Map(M.literalHeredocFiles),functionDefinitions:new Map(M.functionDefinitions),createdDirectories:new Set(M.createdDirectories),compoundBodies:M.compoundBodies}}function zs(M){let L=[];for(let F of M){if(!L.some((q)=>pw(q,F)))L.push(F);if(L.length>a.controlFlowStates.cap)throw new s("controlFlowStates")}return L}function pw(M,L){return M.effectiveCwd===L.effectiveCwd&&uw(M.compoundBodies,L.compoundBodies)&&ho(M.shellGitContextState.env,L.shellGitContextState.env)&&ho(M.literalHeredocFiles,L.literalHeredocFiles)&&ho(M.functionDefinitions,L.functionDefinitions)&&ho(M.shellGitContextState.effectiveEnvAssignments,L.shellGitContextState.effectiveEnvAssignments)&&ho(M.shellGitContextState.shellAssignments,L.shellGitContextState.shellAssignments)&&M.shellGitContextState.bodyDepth===L.shellGitContextState.bodyDepth&&Fp(M.shellGitContextState.bodyAssignments,L.shellGitContextState.bodyAssignments)&&Fp(M.createdDirectories,L.createdDirectories)}function Fp(M,L){return M.size===L.size&&[...M].every((F)=>L.has(F))}function ho(M,L){if(M===L)return!0;if(!M||!L||M.size!==L.size)return!1;return[...M].every(([F,q])=>L.get(F)===q&&L.has(F))}function gw(M,L){let F=Lo(M);return F===void 0?void 0:L.get(F)}function hw(M,L){if(!L)return null;return{reason:L.reason,segment:M,ruleId:L.id,intent:L.intent}}function yw(M,L=M.effectiveCwd){let F=L===null;return{environment:M.environment,cwd:F?void 0:L??M.cwd,originalCwd:F?void 0:M.cwd,strict:M.strict,paranoid:M.paranoidRm,allowTmpdirVar:M.allowTmpdirVar,protectedGitMetadata:M.protectedGitMetadata,policy:M.policy,budget:M.budget}}function yc(M,L){let F=_t(_n(M),L.policy),q=L.trace?.currentSegmentIndex??L.trace?.allocateSegment(),ne={type:"dangerous-text",token:M,matched:!!F,reason:F?.reason};if(L.trace?.recordSegment(ne,q),!F&&/^(?:cd|pushd)\s/.test(M))L.trace?.recordSegment({type:"cwd-change",segment:M,effectiveCwdNowUnknown:!0},q);return F?{reason:F.reason,segment:M,ruleId:F.id,intent:F.intent}:null}function zp(M,L){let F={type:"strict-unparseable",rawCommand:M,reason:io},q=L.trace?.currentSegmentIndex;if(q===void 0)L.trace?.recordGlobal(F);if(q!==void 0)L.trace?.recordSegment(F)}var bw=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function jp(M,L,F,q){let ne=bc(M,0,{...L,...je(L),budget:L.budget??Fn(),factStore:q},F);if(!ne)return null;return{kind:"deny",reason:ne.reason,intent:ne.intent??"manual_only",ruleId:ne.ruleId,evidence:{command:M,segment:ne.segment}}}function Vp(M,L,F){try{return{decision:M()}}catch(q){let ne=Sw(q,L,F);if(!ne)throw q;return ne}}function Sw(M,L,F){if(!(M instanceof s)||!bw.has(M.kind))return null;let q=a[M.kind];if(F?.currentSegmentIndex!==void 0)F.recordSegment({type:"error",message:q.reason});if(F?.currentSegmentIndex===void 0)F?.recordGlobal({type:"error",message:q.reason});return{decision:{kind:"deny",reason:q.reason,ruleId:"analysis.derived-command-limit",intent:"stop_and_explain",evidence:{command:L,segment:L}},errorCode:q.errorCode}}var Cw=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),vc=new Set(["cc-safety-net","ccsn"]),vw=new Set(["bunx","npx","pnpx"]),Ew=new Set(["pnpm","yarn"]),xw=new Set(["npm","pnpm","yarn"]),Rw=new Set(["bun","node"]);function Hs(M,L,F={}){if(vc.has(M))return 0;if(vw.has(M)){if(F.broad)return Cc(L);let ne=L[0]==="-y"||L[0]==="--yes"?1:0;return Us(L[ne])?ne+1:null}let q=F.broad?L.findIndex((ne)=>!ne.startsWith("-")):0;if(q!==-1&&xw.has(M)&&F.broad&&L[q]==="exec"){let ne=Cc(L.slice(q+1));return ne===null?null:q+1+ne}if(Ew.has(M)){if(M==="yarn"&&!F.broad)return null;if(!F.broad)return L[0]==="dlx"&&Us(L[1])?2:null;if(q===-1||L[q]!=="dlx")return null;let ne=Cc(L.slice(q+1));return ne===null?null:q+1+ne}if(Rw.has(M)){let ne=F.broad&&q!==-1?q:0;if(Kp(L[ne]))return ne+1;if(M==="bun"&&L[ne]==="run"&&Kp(L[ne+1]))return ne+2}return null}function Cc(M){let L=M.findIndex((q)=>Us(q));if(L===-1)return null;let F=L;while(F<M.length){let q=M[F]??"";if(!q.startsWith("-")&&!Us(q))break;F++}return F}function Us(M){if(!M)return!1;let L=M.indexOf("@");if(L===-1)return vc.has(M);if(L===0)return!1;let F=M.slice(L+1);if(F===""||F.includes("/")||F.includes(":"))return!1;return vc.has(M.slice(0,L))}function Kp(M){let L=M?.replaceAll("\\","/");return[...Cw].some((F)=>L===F||L?.endsWith(`/${F}`))}var Ue="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 qp(M,L,F){let q=dn(M,"input-candidate");if(!q)return null;let ne=to(q.shell,M.invocation.context.executionCwd,L,F,{findSegmentTarget:(re)=>_w(re,L),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return ne?{target:ne}:null}function _w(M,L){let F=ar([...M],L),q=F.slice(1),ne=Hs(wt(F[0]??"").toLowerCase(),q,{broad:!0});if(ne===null)return null;let re=q.slice(ne).filter((ue)=>ue!=="-g"&&ue!=="--global");return re[0]==="policy"&&re[1]==="apply"?F.join(" "):null}import{dirname as js}from"node:path";var Ge="This path contains the protected policy config and you must not modify or delete it.",ww=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Jp(M,L,F){let q=Ow(M.invocation.context,L,F);if(M.invocation.route.kind==="patch")return Yp(M.paths,!1,M.invocation.context.executionCwd,q,L,F);let ne=dn(M,"input-candidate");if(M.invocation.route.kind==="command")return ne?Zp(ne.shell,M.invocation.context.executionCwd,q,L,F):null;if(M.invocation.route.kind==="unknown"&&ne){let re=Zp(ne.shell,M.invocation.context.executionCwd,q,L,F);if(re)return re}return Yp(M.paths,M.invocation.route.kind==="grep"||M.invocation.route.kind==="glob"||Si(M.invocation.toolName),M.invocation.context.executionCwd,q,L,F)}function Yp(M,L,F,q,ne,re){if(L)return null;let ue=M.find((Se)=>ui(Se,F,q,ne,re));return ue?{target:ue}:null}function Zp(M,L,F,q,ne){let re=to(M,L,q,ne,{findSegmentTarget:(ue,Se)=>Pw(ue,Se,F,q,ne)?.target??null,isRedirectionTarget:(ue,Se)=>ui(ue,Se.cwd,F,q,ne),findMalformedTarget:(ue)=>kw(ue,L,F,q,ne)?.target??null});return re?{target:re}:null}function Pw(M,L,F,q,ne){if(Yo(M))return null;let re=lr([...M],q),ue=wt(re[0]??"").toLowerCase(),Se=re.slice(1);if(ue==="rm"&&Aw(Se)){let ve=Tw(Se).find((He)=>Xp(un(He,L.variables),L.cwd,F,q,ne));if(ve)return{target:ve}}if(ue==="find"){if(xs(re,1)||Fl(re,q)){let He=(ri(Ut(re))??Ut(["."])).find((dt)=>{let mt=un(dt.text,L.variables);return ui(mt,L.cwd,F,q,ne)||Xp(mt,L.cwd,F,q,ne)})?.text;if(He)return{target:He}}}if(ue==="mv"){let ve=us(Se).sources.find((He)=>Mw(un(He,L.variables),L.cwd,F,q,ne));if(ve)return{target:ve}}if(Iw(re,ue))return null;for(let ve of[...M,...re])for(let He of Qp(ve))if(ui(un(He,L.variables),L.cwd,F,q,ne))return{target:He};return null}function Aw(M){return M.some((L)=>L==="--recursive"||L.startsWith("-")&&!L.startsWith("--")&&/[rR]/.test(L.slice(1)))}function Tw(M){let L=M.indexOf("--");if(L!==-1)return[...M.slice(0,L).filter((F)=>!F.startsWith("-")),...M.slice(L+1)];return M.filter((F)=>!F.startsWith("-"))}function Iw(M,L){if(!ww.has(L))return!1;if(L!=="sed")return!0;return!M.slice(1).some((F)=>F.startsWith("-i")||F==="--in-place"||F.startsWith("--in-place="))}function kw(M,L,F,q,ne){for(let re of M.split(/\s+/))for(let ue of Qp(re))if(ui(ue,L,F,q,ne))return{target:ue};return null}function Qp(M){let L=M.trim().replace(/^['"]|['"]$/g,""),F=L.indexOf("=");return F===-1||F===L.length-1?[L]:[L,L.slice(F+1)]}function Ow(M,L,F){let q=(Se)=>di(rn(Se,M.executionCwd,L,F)),ne=q(d(L)),re=[q(b(M.executionCwd)),q(b(M.configCwd))],ue=new Set(re.map((Se)=>js(Se)));for(let Se=js(ne);;Se=js(Se))if(ue.add(Se),js(Se)===Se)break;return{files:new Set([ne,...re]),directoriesAndAncestors:ue}}function ui(M,L,F,q,ne){let re=$c(M,L,q,ne,(ue)=>di(ue)===_i);return re!==null&&F.files.has(di(re))}function Xp(M,L,F,q,ne){return F.directoriesAndAncestors.has(di(rn(M,L,q,ne)))}function Mw(M,L,F,q,ne){let re=di(rn(M,L,q,ne));return F.files.has(re)||F.directoriesAndAncestors.has(re)}function di(M){return process.platform==="win32"?M.toLowerCase():M}import{isAbsolute as Vs,posix as dg,resolve as qs,win32 as Dw}from"node:path";import{fileURLToPath as Nw}from"node:url";var fg="Access to a sensitive path is not allowed.",mg=new Set(["echo","printf"]),Lw=new Set(["find"]),Ww=new Set(["!","do","elif","else","if","then","until","while"]),Gw=new Set(["-exec","-execdir"]),Fw=new Set([";","+"]),zw=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),Bw=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),pg=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),$w=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),Uw=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","fopen","popen","read","readfile","remove","rename","require","rg","rm","sed","shell","source","spawn","strings","system","tail","tar","truncate","unlink","write","xxd","zip"]),gg=new Set(["-c","-e","-r","-E","--eval","--exec"]),Hw=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"])]]),jw=new Set(["grep","rg"]),Vw=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),Kw=new Set(["commit","merge","notes","stash","tag"]),qw=new Set(["-m","--message"]),Yw=new Set(["--grep"]),eg=new Set(["jq","gojq","jaq"]),tg="f",ng="file",Zw="files",Xw=new Set(["e","f"]),Jw=new Set(["regexp","file"]),Qw=new Set(["e","f","A","B","C","m"]),eP=new Set(["regexp","file","after-context","before-context","context","max-count"]),Ec="__CC_SAFETY_NET_PIPE_INPUT__",Rc=/[\w./~@+-]*[./~][\w./~@+-]*/g,tP=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,nP=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,rP=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,rg=/\b(?:subprocess\s*\.\s*(?:run|call|Popen|check_output|check_call|getoutput|getstatusoutput)|(?:[\w$]+\s*\.\s*)*(?:exec(?:File)?(?:Sync)?|spawn(?:File)?(?:Sync)?|system|popen|shell_exec|passthru|child_process|eval))\s*\(/g,og=/\b(?:system|exec|spawn|popen)\s*$/,oP=/\b(?:eval|exec)\s*\(/g,iP=/\b(?:eval|exec)\s*$/,sP=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 ig(M,L,F,q,ne,re){for(let ue of M){let Se=ue.target;if(rA(Se,ue.cwd,L?.denyPaths??[],F,q,ne))return{target:Se,ruleId:"secret.deny-path"};if(re&&!re.has(Se))continue;let ve=tA(Se,ue.cwd,L,q,ne);if(ve){let He=re!==void 0&&!ve.startsWith("secret.home.")&&!ve.startsWith("secret.cli.");if(He&&q.paths.isDirectory(Eg(Se,ue.cwd,q,ne)))continue;if(He&&ue.isRedirectionWriteTarget===!0&&!Se.includes("$")&&!wc(Se,ue.cwd,q,ne))continue;if(He&&/\s/.test(Se)&&!Se.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(Se)&&!wc(Se,ue.cwd,q,ne))continue;if(!ve.startsWith("secret.cli.")&&oA(Se,ue.cwd,L?.allowPaths??[],F,q,ne))continue;return{target:Se,ruleId:ve}}}return null}function hg(M,L,F,q,ne={}){let re=sg(M,F,q),ue=ig(re,L,M.invocation.context.configCwd,F,q);if(ue===null||ue.ruleId==="secret.deny-path"||ne.strict!==!1)return ue;let Se=ig(re,L,M.invocation.context.configCwd,F,q,new Set(sg(M,F,q,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}).map((ve)=>ve.target)));return Se?.ruleId!=="secret.deny-path"&&aP(M,F)?null:Se}function aP(M,L){let F=dn(M,"input-candidate")??dn(M,"declared-command");if(!F)return!1;if(F.program.nodes.some((ue)=>ue.kind==="command"&&ue.nested.length>0))return!1;let q=[];for(let ue of cs(F.shell)){if(ue.kind==="operator"&&ue.boundary)return!1;if(ue.kind==="redirection")return!1;if(ue.kind==="operator")continue;q.push(Zn(ue.text,L))}let ne=nr(q);if(ne.length===0)return!1;let re=Wn(ne[0]??"").toLowerCase();if(M.invocation.route.kind==="unknown")return F.program.dialect==="powershell"&&(re==="ls"||re==="stat");return Pc(re,ne.slice(1))}function Pc(M,L){if(M==="ls"||M==="stat")return!0;if(M==="test")return L.length===2&&(L[0]==="-e"||L[0]==="-f");if(M==="[")return L.length===3&&(L[0]==="-e"||L[0]==="-f")&&L[2]==="]";if(M==="git")return L[0]==="check-ignore";if(M!=="find")return!1;return!L.some((F)=>zw.has(F))}function sg(M,L,F,q={}){let ne=M.invocation.context.executionCwd,re=M.invocation.route.kind;if(re!=="command"&&re!=="unknown")return M.paths.map((Se)=>({target:Se,cwd:ne}));let ue=dn(M,"input-candidate");return[...ue?yo(ue.shell,M.store,q,L,ne,F,lP(ue)):[],...re==="unknown"?M.paths.map((Se)=>({target:Se,cwd:ne})):[]]}function lP(M){return M.program.dialect==="powershell"}function yo(M,L,F,q,ne,re,ue=!1){if(M.status==="structural-limit")throw new y;if(M.status==="unclosed-quote")return[];if(M.status==="invalid")throw Error("Unable to parse command for secret protection");let Se=[...M.assignmentFallbacks.map((He)=>({target:He,cwd:ne})),...GP(Zn(M.source,q),L,F,q,ne,re)],ve=(He)=>Zn(SP(He,ue),q);return ls(M,ne,q,re,{word:ve,segment:(He,dt,mt,ft,pt)=>{if(He.length===0)return null;if(Se.push(...Ys(He,L,F,q,dt.cwd,re,pt)),mt!==null)Se.push(...uP(mt,He,L,F,q,dt.cwd,re));return null},redirection:(He,dt)=>{if(He.body!==void 0&&He.consumer!==void 0)Se.push(...yg(He.consumer,[He.body],L,F,q,dt.cwd,re,(mt)=>dP(He.consumer??[],mt,L,F,q,dt.cwd,re)));if(He.targetOrder==="legacy-segment")return vl;return Se.push({target:ve(He.target),cwd:dt.cwd,...He.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}}),Se}function Ac(M,L,F,q,ne,re){let ue=L.getShellSyntax(M);if(ue.status==="structural-limit")throw new y;return ue.status==="complete"?yo(ue,L,F,q,ne,re):null}function Ys(M,L,F,q,ne,re,ue){let Se=(gt)=>({target:gt,cwd:ne});if(ue?.size){let gt=M.filter((yt,St)=>!ue.has(St));if(eg.has(Wn(nr(gt)[0]??"").toLowerCase()))return[...M.filter((yt,St)=>ue.has(St)).map(Se),...Ys(gt,L,F,q,ne,re)]}let ve=bP(M).map(Se),He=nr(M);if(He.length===0)return ve;let dt=He[0]??"",mt=Wn(dt).toLowerCase(),ft=He.slice(1),pt=He.findIndex((gt)=>!Ww.has(gt));if(F.skipMetadataOnlySegments===!0&&pt!==-1&&Pc(Wn(He[pt]??"").toLowerCase(),He.slice(pt+1)))return ve;let ht=cP(dt,mt,ft);if(ht)return[...ve,...ht.map(Se)];if(mg.has(mt))return F.displayOperandsAreCapturedOutput===!0?[...ve,...bg(M).map(Se)]:ve;if(mt==="eval")return[...ve,...Ac(ft.join(" "),L,F,q,ne,re)??ft.map(Se)];if(mt==="export")return[...ve,...ft.flatMap((gt)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(gt)?[gt.slice(gt.indexOf("=")+1)]:Hn(mt,gt)).map(Se)];if(mt==="git")return[...ve,...vP(ft).map(Se)];if(mt==="gh")return[...ve,..._c(mt,ft,Vw).map(Se)];if(eg.has(mt))return[...ve,...CP(ft).map(Se)];if(jw.has(mt))return[...ve,...VP(ft).map(Se)];if(Lw.has(mt))return[...ve,..._P(ft,L,F,q,ne,re).map(Se)];if(Rn.has(mt))return[...ve,...ft.flatMap((gt)=>Hn("awk",gt)).map(Se),...ft.flatMap((gt)=>PP(gt,L,F,q,ne,re)),...ft.flatMap(AP).map(Se)];if(mt==="curl")return[...ve,...ft.flatMap((gt)=>Hn(mt,gt)).map(Se),...EP(ft).map(Se)];if(Zo(mt)){let gt=qo.has(mt)?bn([mt,...ft]):null;if(gt!==null&>.command!==null&>.commandIndex!==null){let yt=L.getShellSyntax(gt.command);if(yt.status==="structural-limit")throw new y;if(yt.status==="complete")return[...ve,...yo(yt,L,F,q,ne,re),...ft.slice(gt.commandIndex).filter((St)=>!St.startsWith("-")).map(Se)]}return[...ve,...wP(mt,ft,L,F,q,ne,re)]}return[...ve,...ft.flatMap((gt)=>Hn(mt,gt)).map(Se)]}function cP(M,L,F){let q=Hs(L,F);if(q===null||F[q]!=="explain")return null;let ne=[M,...F.slice(0,q)],re=F.slice(q+1);for(let ue=0;ue<re.length;ue++){let Se=re[ue];if(Se==="--json"||Se==="--help"||Se==="-h")continue;if(Se==="--cwd"){let ve=re[ue+1];if(ve&&!ve.startsWith("--"))ne.push(ve);ue++;continue}return ne}return ne}function uP(M,L,F,q,ne,re,ue){if(gP(L,F,q,ne,re,ue)){let Se=nr(M),ve=Pc(Wn(Se[0]??"").toLowerCase(),Se.slice(1))?Se.slice(1).filter((He)=>!He.startsWith("-")):[];return[...bg(M),...ve].map((He)=>({target:He,cwd:re}))}return yg(L,fP(M),F,q,ne,re,ue,()=>[])}function dP(M,L,F,q,ne,re,ue){let Se=nr(M);if(!Zo(Wn(Se[0]??"").toLowerCase()))return[];return Ac(L,F,q,ne,re,ue)??[{target:L,cwd:re}]}function yg(M,L,F,q,ne,re,ue,Se){let ve=hP(M);if(ve===null)return L.flatMap(Se);return L.flatMap((He)=>qo.has(ve)?yo(F.getShellSyntax(He),F,q,ne,re,ue):Ks(ve,He,F,q,ne,re,ue))}function bg(M){let L=nr(M);if(L.length===0)return[];let F=Wn(L[0]??"").toLowerCase();if(!mg.has(F))return[];let q=L[L[1]==="--"?2:1];if(F==="printf"&&q!==void 0&&!q.startsWith("-")&&!q.replaceAll("%%","").includes("%"))return[Tc(q.replaceAll("%%","%"))];return L.slice(1)}function fP(M){let L=nr(M);if(L.length===0)return[];let F=Wn(L[0]??"").toLowerCase(),q=L.slice(1);if(F==="echo"){let ne=q.findIndex((re)=>!/^-[neE]+$/.test(re));return[(ne===-1?[]:q.slice(ne)).join(" ")]}if(F==="printf")return mP(q);return[]}function mP(M){let L=M[0];if(L===void 0)return[];let F=(L.match(/%%|%[bqs]/g)??[]).filter((ne)=>ne!=="%%").length;if(F===0||M.length===1)return[Tc(L)];let q=M.slice(1);return Array.from({length:Math.ceil(q.length/F)},(ne,re)=>pP(L,q.slice(re*F,(re+1)*F)))}function pP(M,L){let F=0;return Tc(M.replace(/%%|%[bqs]/g,(q)=>{if(q==="%%")return"%";let ne=L[F]??"";return F++,ne}))}function Tc(M){return M.replace(/\\n/g,`
|
|
42
|
+
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function gP(M,L,F,q,ne,re){let ue=nr(M);if(ue.length===0||Wn(ue[0]??"").toLowerCase()!=="xargs")return!1;let Se=Nr(ue),ve=ue.slice(Se.childStart);if(ve.length===0)return!1;if(Se.replacementToken==="")return!1;let He=Se.replacementToken,dt=He===null?[...ve,Ec]:ve.map((mt)=>mt.split(He).join(Ec));return Ys(dt,L,F,q,ne,re).some((mt)=>mt.target.includes(Ec))}function hP(M){let L=nr(M);if(L.length===0)return null;let F=Wn(L[0]??"").toLowerCase();if(!Zo(F))return null;return yP(F,L.slice(1))?F:null}function yP(M,L){let F=Ic(M);for(let q=0;q<L.length;q++){let ne=L[q];if(ne===void 0)break;if(gg.has(ne)||Sg(M,ne)||/^--(?:eval|exec)=/.test(ne))return!1;if(ne==="-")return!0;if(ne.startsWith("-")){if(F==="python"&&ne==="-m")return!1;if(sP.get(F)?.has(ne))q++;continue}return!1}return!0}function Ic(M){return/^python\d/.test(M)?"python":M}function bP(M){let L=[];for(let F of M){if(vg(F))continue;let q=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(F);if(q===null)break;if(q[1]!==void 0&&q[1]!=="")L.push(q[1])}return L}var ag=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function SP(M,L){if(!L||!ag.test(M))return M;return`~${M.replace(ag,"").replace(/\\/g,"/")}`}function Hn(M,L){if(L==="--")return[];let F=[],q=L.indexOf("=");if(q>0&&q<L.length-1)F.push(L.slice(q+1));if(L.startsWith("-"))return F;if(M==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(L))return F;if(M==="zip"&&/\.zip$/i.test(L))return F;return F.push(L),F}function CP(M){let L=-1,F=!1;for(let q=0;q<M.length;q++){let ne=M[q]??"";if(!F&&ne==="--"){F=!0;continue}if(F||!/^-(?:[A-Za-z]|-)/.test(ne)){if(L===-1)L=q;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(ne)){q+=2;continue}if(ne==="--indent"||ne==="-L"){q++;continue}if(ne.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(ne)||/^--(?:slurp|raw-output0?|join-output|compact-output|color-output|monochrome-output|ascii-output|unbuffered|sort-keys|raw-input|null-input|binary|tab|seq|stream|stream-errors|exit-status|args|jsonargs|help|version|build-configuration)$/.test(ne))continue;return M.flatMap((re)=>Hn("jq",re))}return M.flatMap((q,ne)=>ne===L?[]:Hn("jq",q))}function vP(M){let L=[];for(let F=0;F<M.length;F++){let q=M[F]??"";if(q==="--"||!q.startsWith("-"))return[...L,...Kw.has(q)?_c("git",M.slice(F).map((re)=>/^-[aeinopqsv]+m$/.test(re)?"-m":re),qw):_c("git",M.slice(F),Yw)];if(L.push(...Hn("git",q)),!yn.has(q))continue;let ne=M[F+1];if(ne===void 0)break;L.push(...q==="-c"&&ne.includes("=")?[ne.slice(ne.indexOf("=")+1)]:Hn("git",ne)),F++}return L}function _c(M,L,F){let q=[];for(let ne=0;ne<L.length;ne++){let re=L[ne]??"";if(re==="--")return[...q,...L.slice(ne).flatMap((ue)=>Hn(M,ue))];if(F.has(re)){ne++;continue}if(re.includes("=")&&F.has(re.slice(0,re.indexOf("="))))continue;q.push(...Hn(M,re))}return q}function EP(M){return M.flatMap((L,F)=>{let q=RP(L);if(q!==null)return lg(q.flag,q.value);let ne=xP(M[F-1]);return ne===null?[]:lg(ne,L)})}function lg(M,L){if(M==="-F"||M==="--form"){let F=L.indexOf("="),q=F===-1?L:L.slice(F+1);if(!q.startsWith("@")&&!q.startsWith("<"))return[];return xc(q.slice(1).split(";")[0]??"")}if(M==="--data-urlencode"){let F=L.indexOf("@"),q=L.indexOf("=");if(F===-1||q!==-1&&q<F)return[];return xc(L.slice(F+1))}return L.startsWith("@")?xc(L.slice(1)):[]}function xP(M){if(M===void 0)return null;if(pg.has(M))return M;return/^-[A-Za-z]+[dF]$/.test(M)?`-${M.slice(-1)}`:null}function RP(M){let L=M.slice(0,2);if(M.length>2&&(L==="-d"||L==="-F"))return{flag:L,value:M.slice(2)};let F=M.indexOf("=");if(F===-1)return null;let q=M.slice(0,F);return pg.has(q)?{flag:q,value:M.slice(F+1)}:null}function xc(M){return M===""||M==="-"?[]:[M]}function _P(M,L,F,q,ne,re){let ue=M.findIndex((ve)=>ve.startsWith("-")||ve==="("||ve==="!"||ve===";"),Se=[...M.slice(0,ue===-1?M.length:ue),...M.flatMap((ve,He)=>ve==="-files0-from"&&M[He+1]!==void 0?[M[He+1]??""]:[])];for(let ve=0;ve<M.length;ve++){if(!Gw.has(M[ve]??""))continue;let He=M.slice(ve+1),dt=He.findIndex((pt)=>Fw.has(pt)),mt=dt===-1?He:He.slice(0,dt),ft=Ys(mt,L,F,q,ne,re).map((pt)=>pt.target);if(Se.push(...ft.filter((pt)=>pt!=="{}")),!ft.includes("{}"))continue;Se.push(...M.slice(0,ve).flatMap((pt,ht,gt)=>{if(!Bw.has(pt))return[];let yt=gt[ht+1];return yt===void 0?[]:[yt,yt.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return Se}function wP(M,L,F,q,ne,re,ue){let Se=[];for(let ve=0;ve<L.length;ve++){let He=L[ve];if(He===void 0)break;if(gg.has(He)||Sg(M,He)){let mt=L[ve+1];if(mt!==void 0)Se.push(...Ks(M,mt,F,q,ne,re,ue)),ve++;continue}let dt=/^--(?:eval|exec)=(.*)$/.exec(He);if(dt!==null&&dt[1]!==void 0){Se.push(...Ks(M,dt[1],F,q,ne,re,ue));continue}if(!He.startsWith("-"))Se.push({target:He,cwd:re})}return Se}function Sg(M,L){if(!L.startsWith("-")||L.startsWith("--")||L.length<=2)return!1;return Hw.get(L[L.length-1]??"")?.has(Ic(M))??!1}function PP(M,L,F,q,ne,re){if(!M.includes("system"))return[];return Nl(M)?.commands.flatMap((ue)=>yo(L.getShellSyntax(ue),L,F,q,ne,re))??[]}function AP(M){return Array.from(M.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((L)=>L[1]).filter((L)=>L!==void 0&&L!=="")}function TP(M){let L=Array.from(M.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((F)=>F[2]).filter((F)=>F!==void 0&&F!=="");return[...L,...L.flatMap(kc),...M.match(Rc)??[]]}function Ks(M,L,F,q,ne,re,ue){let Se=(gt)=>({target:gt,cwd:re}),ve=kP(L,IP(M));if(ve.kind==="unmaskable")return TP(L).map(Se);let He=ve.masked.match(rg)!==null||ve.literals.some((gt)=>og.test(ve.masked.slice(0,gt.start))),dt=ve.masked.match(oP)!==null||ve.literals.some((gt)=>iP.test(ve.masked.slice(0,gt.start))),mt=q.inlineLiteralsPresumedData===!0&&!qo.has(M),ft=mt&&!(NP(ve.masked)||He||dt)?[]:ve.literals,pt=mt?Array.from(ve.masked.matchAll(rg),(gt)=>{let yt=gt.index+gt[0].length;return{start:yt,end:pl(ve.masked,yt)}}):[],ht=!mt||pt.some((gt)=>gl(ve.masked,gt.start))?ve.literals:ve.literals.filter((gt)=>og.test(ve.masked.slice(0,gt.start))||pt.some((yt)=>gt.start>=yt.start&>.start<yt.end));return[...ft.map((gt)=>gt.text).filter((gt)=>gt!=="").map(Se),...ft.flatMap((gt)=>kc(gt.text)).map(Se),...mt?[]:ve.literals.flatMap((gt)=>gt.text.match(Rc)??[]).map(Se),...He?ht.flatMap((gt)=>Ac(gt.text,F,q,ne,re,ue)??[Se(gt.text)]):[],...dt?ve.literals.flatMap((gt)=>Ks(M,gt.text.replace(/\\(.)/g,(yt,St)=>St==="n"?`
|
|
43
|
+
`:St),F,q,ne,re,ue)):[],...(ve.masked.match(Rc)??[]).map(Se)]}function IP(M){let L=Ic(M);if(L==="python")return"python";if(L==="osascript")return"opaque";return L==="node"||L==="bun"||L==="deno"?"javascript":"simple"}function kP(M,L){if(L==="opaque")return{kind:"unmaskable"};let F=M.split(""),q=[];for(let ne=0;ne<M.length;ne++){let re=M[ne]??"";if(L==="simple"&&(re==="`"||re==="%"||re==="<")){if(nP.test(M.slice(ne)))return{kind:"unmaskable"}}let ue=re==="'"||re==='"'||L==="javascript"&&re==="`"?re:null;if(ue===null)continue;if(ue==="`"&&DP(M,ne))return{kind:"unmaskable"};let Se=L==="python"?OP(M,ne):"",ve=L==="python"&&M.startsWith(ue.repeat(3),ne)?ue.repeat(3):ue,He=ne+ve.length,dt=MP(M,He,ve);if(dt===null)return{kind:"unmaskable"};let mt=M.slice(He,dt);if(/[fF]/.test(Se)&&mt.includes("{"))return{kind:"unmaskable"};if(L==="simple"&&ue==='"'&&rP.test(mt))return{kind:"unmaskable"};q.push({start:He,text:mt});for(let ft=ne;ft<dt+ve.length;ft++)F[ft]=" ";ne=dt+ve.length-1}return{kind:"masked",masked:F.join(""),literals:q}}function OP(M,L){return tP.exec(M.slice(Math.max(0,L-3),L))?.[1]??""}function MP(M,L,F){let q=F==="`",ne=q||F.length===3;for(let re=L;re<M.length;re++){let ue=M[re];if(ue==="\\"){re++;continue}if(q&&ue==="$"&&M[re+1]==="{")return null;if(!ne&&(ue===`
|
|
44
|
+
`||ue==="\r"))return null;if(M.startsWith(F,re))return re}return null}function DP(M,L){for(let F=L-1;F>=0;F--){let q=M[F];if(!q||/\s/.test(q))continue;return/[\w$\])]/.test(q)}return!1}function NP(M){for(let L of M.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let F=L[0],q=L.index;if($w.has(F.toLowerCase()))return!0;let ne=F.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((re)=>re.toLowerCase());if(!ne.some((re)=>Uw.has(re)))continue;if(ne.length>1)return!0;if(LP(M,q)===".")return!0;if(WP(M,q+F.length)==="(")return!0}return!1}function LP(M,L){for(let F=L-1;F>=0;F--)if(!/\s/.test(M[F]??""))return M[F];return}function WP(M,L){for(let F=L;F<M.length;F++)if(!/\s/.test(M[F]??""))return M[F];return}function GP(M,L,F,q,ne,re){return UP(M).flatMap((ue)=>{let Se=L.getShellSyntax(ue);if(Se.status==="invalid")return[];return[...yo(Se,L,{...F,displayOperandsAreCapturedOutput:!0},q,ne,re),...FP(Se,q)?zP(Se,q).map((ve)=>({target:ve,cwd:ne})):[]]})}function FP(M,L){let F=cs(M);for(let q=0;q<F.length;q++){let ne=F[q];if(ne?.kind!=="word"||Wn(Zn(ne.text,L)).toLowerCase()!=="base64")continue;for(let re=q+1;re<F.length;re++){let ue=F[re];if(ue?.kind==="operator")break;if(ue?.kind!=="word")continue;let Se=Zn(ue.text,L);if(Se==="--decode"||!Se.startsWith("--")&&Se.startsWith("-")&&/[dD]/.test(Se))return!0}}return!1}function zP(M,L){return cs(M).flatMap((F)=>F.kind==="word"?[Zn(F.text,L)]:F.kind==="redirection"&&F.target?[Zn(F.target,L)]:[]).flatMap(kc)}function kc(M){let L=$P(M);if(L===null)return[];let F=Buffer.from(L,"base64").toString("utf8");if(F===""||BP(F))return[];return Buffer.from(F,"utf8").toString("base64").replace(/=+$/g,"")===L.replace(/=+$/g,"")?[F]:[]}function BP(M){return Array.from(M).some((L)=>{let F=L.charCodeAt(0);return F<32||F===127})}function $P(M){if(M.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(M))return null;if(/=/.test(M.replace(/=+$/g,"")))return null;let L=M.replace(/=+$/g,"");if(L.length%4===1)return null;return`${L.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-L.length%4)%4)}`}function UP(M){let L=[],F={inSingle:!1,inDouble:!1,escaped:!1};for(let q=0;q<M.length;q++){let ne=M[q];if(!ne)break;if(ko(ne,F))continue;if(Cg(M,q,F)){let re=HP(M,q+1);if(re!==null)L.push(re.body),q=re.endIndex;continue}if(!F.inSingle&&ne==="`"){let re=jP(M,q);if(re!==null)L.push(re.body),q=re.endIndex}}return L}function HP(M,L){let F={inSingle:!1,inDouble:!1,escaped:!1},q=1;for(let ne=L+1;ne<M.length;ne++){let re=M[ne];if(!re)break;if(ko(re,F))continue;if(Cg(M,ne,F)){q++,ne++;continue}if(!F.inSingle&&!F.inDouble&&re===")"){if(q--,q===0)return{body:M.slice(L+1,ne),endIndex:ne}}}return null}function jP(M,L){let F=!1;for(let q=L+1;q<M.length;q++){let ne=M[q];if(!ne)break;if(F){F=!1;continue}if(ne==="\\"){F=!0;continue}if(ne==="`")return{body:M.slice(L+1,q),endIndex:q}}return null}function Cg(M,L,F){return!F.inSingle&&M[L]==="$"&&M[L+1]==="("&&M[L+2]!=="("}function VP(M){let L=[],F=[],q=!1,ne=!1,re=!1;for(let ve=0;ve<M.length;ve++){let He=M[ve];if(He===void 0)break;if(!re&&He==="--"){re=!0;continue}if(re){F.push(He);continue}let dt=/^--([^=]+)(?:=(.*))?$/.exec(He);if(dt!==null){let mt=dt[1]??"",ft=dt[2];if(mt===Zw)ne=!0;if(Jw.has(mt))q=!0;if(ft!==void 0){if(mt===ng)L.push(ft);continue}if(eP.has(mt)){let pt=M[ve+1];if(mt===ng&&pt!==void 0)L.push(pt);ve++}continue}if(He.startsWith("-")&&He.length>1){let mt=He.slice(1),ft="",pt="";for(let gt=0;gt<mt.length;gt++){let yt=mt[gt]??"";if(Xw.has(yt))q=!0;if(Qw.has(yt)){ft=yt,pt=mt.slice(gt+1);break}}if(ft==="")continue;if(pt.length>0){if(ft===tg)L.push(pt);continue}let ht=M[ve+1];if(ft===tg&&ht!==void 0)L.push(ht);ve++;continue}F.push(He)}let Se=!q&&!ne?F.slice(1):F;return[...L,...Se]}function nr(M){let L=M.findIndex((F)=>!vg(F)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(F));return L===-1?[]:M.slice(L)}function vg(M){return M==="env"||M==="command"||M==="builtin"||M==="sudo"}var KP=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),qP=".env.",YP=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),ZP=[".env.example.",".env.sample."];function XP(M){let L;try{L=new URL(M.trim())}catch{return!1}return L.protocol!=="file:"&&L.host!==""}function JP(M){return M.length>0&&!/\s/.test(M)}function wc(M,L,F,q){let ne=Eg(M,L,F,q);return ne!==""&&F.paths.entryKind(ne)!=="missing"}function Eg(M,L,F,q){try{return pi(M,L,F,q)}catch(ne){if(ne instanceof s)throw ne;return""}}var QP=new Set(["node_modules","__pycache__"]),eA=[["vendor","bundle"],["vendor","cache"]];function tA(M,L,F,q,ne){if(XP(M))return null;let re=Un(M,L,q,ne);if(!re)return null;let ue=Ft(re.split("/").pop()??""),Se=Ft(re),ve=()=>JP(ue)||wc(M,L,q,ne);if(YP.has(ue)||ZP.some((ft)=>ue.startsWith(ft)))return null;let He=Ft(aA(M,L,q,ne));for(let ft of Ta){let pt=`~/${ft.suffixParts.join("/")}`;if((ug(Se,pt)||ug(He,pt))&&tr(ft.id,F))return ft.id}let dt=nA(re,L,F,q,ne);if(dt)return dt;if(KP.has(ue))return null;for(let ft of Aa)if(ue===ft.basename&&tr(ft.id,F))return ft.id;if(ue.startsWith(qP)&&tr(Ii.id,F)&&ve())return Ii.id;for(let ft of Ia)if(ue.length>ft.prefix.length&&ue.startsWith(ft.prefix)){let pt=ue.slice(ft.prefix.length)[0];if((pt==="-"||pt==="_")&&tr(ft.id,F)&&ve())return ft.id}for(let ft of ka)if(ue.length>ft.prefix.length&&ue.startsWith(ft.prefix)){if(ue.slice(ft.prefix.length)===ft.suffix&&tr(ft.id,F))return ft.id}if(iA(Se))return null;if(!ue.includes(".")&&Oo.pattern.test(ue)&&tr(Oo.id,F))return Oo.id;let mt=sA(ue,F);if(mt)return mt;return null}function nA(M,L,F,q,ne){return ki.find((re)=>{if(!tr(re.id,F))return!1;switch(re.id){case"secret.cli.claude-code":return Wt(M,$t(q.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",L,q,ne),[".credentials.json"]);case"secret.cli.claude-code.config":{let ue=Ft(M).split("/");return Wt(M,$t(q.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",L,q,ne),["settings.json","settings.local.json"])||mi(M,"~/.claude.json",L,q,ne)||ue.at(-1)==="settings.local.json"&&ue.at(-2)===".claude"||ue.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Wt(M,Un("~/.gemini/config",L,q,ne),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let ue=$t(q.env.get("CODEX_HOME"),"~/.codex",L,q,ne);return Wt(M,ue,["auth.json",".credentials.json"])||fi(M,ue,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let ue=$t(q.env.get("CODEX_HOME"),"~/.codex",L,q,ne),Se=Ft(M).split("/").at(-1)??"";return Wt(M,ue,["config.toml"])||Se.endsWith(".config.toml")&&Wt(M,ue,[Se])}case"secret.cli.gemini":return Wt(M,on($t(q.env.get("GEMINI_CLI_HOME"),"~",L,q,ne),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let ue=Ft(M).split("/"),Se=q.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),ve=q.env.get("ProgramData")?[on($t(q.env.get("ProgramData"),"",L,q,ne),"gemini-cli")]:[];return Wt(M,on($t(q.env.get("GEMINI_CLI_HOME"),"~",L,q,ne),".gemini"),["settings.json","google_accounts.json"])||ue.at(-1)==="settings.json"&&ue.at(-2)===".gemini"||(Se?.trim()?mi(M,Se,L,q,ne):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...ve].some((He)=>Wt(M,Un(He,L,q,ne),["settings.json"]))}case"secret.cli.copilot-cli":{let ue=$t(q.env.get("COPILOT_HOME"),"~/.copilot",L,q,ne);return Wt(M,ue,["config.json"])||fi(M,ue,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Wt(M,$t(q.env.get("COPILOT_HOME"),"~/.copilot",L,q,ne),["mcp-config.json"]);case"secret.cli.kimi-code":{let ue=$t(q.env.get("KIMI_CODE_HOME"),"~/.kimi-code",L,q,ne),Se=$t(q.env.get("KIMI_SHARE_DIR"),"~/.kimi",L,q,ne);return Wt(M,ue,["server.token"])||fi(M,ue,["credentials"])||fi(M,Se,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let ue=["config.toml","mcp.json"],Se=Ft(M).split("/");return Se.at(-1)==="mcp.json"&&Se.at(-2)===".kimi-code"||Wt(M,$t(q.env.get("KIMI_CODE_HOME"),"~/.kimi-code",L,q,ne),ue)||Wt(M,$t(q.env.get("KIMI_SHARE_DIR"),"~/.kimi",L,q,ne),[...ue,"config.json","config.json.bak"])}case"secret.cli.opencode":{let ue=on($t(q.env.get("XDG_DATA_HOME"),"~/.local/share",L,q,ne),"opencode"),Se=Ft(M).split("/").at(-1)??"",ve=q.env.get("OPENCODE_DB")?.trim(),He=ve&&ve!==":memory:"?[ve,`${ve}-wal`,`${ve}-shm`]:[];return Wt(M,ue,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Se)&&Wt(M,ue,[Se])||He.some((dt)=>mi(M,dt,L,q,ne))}case"secret.cli.opencode.config":{let ue=on($t(q.env.get("XDG_CONFIG_HOME"),"~/.config",L,q,ne),"opencode"),Se=q.env.get("ProgramData")?[on($t(q.env.get("ProgramData"),"",L,q,ne),"opencode")]:[],ve=["opencode.json","opencode.jsonc"],He=q.env.get("OPENCODE_CONFIG");return ve.includes(Ft(M).split("/").at(-1)??"")||Wt(M,ue,["config.json"])||(He?.trim()?mi(M,He,L,q,ne):!1)||["/Library/Application Support/opencode","/etc/opencode",...Se].some((dt)=>Wt(M,Un(dt,L,q,ne),ve))}case"secret.cli.pi":return Wt(M,$t(q.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",L,q,ne),["auth.json"]);case"secret.cli.pi.config":return Wt(M,$t(q.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",L,q,ne),["models.json"]);case"secret.cli.amp":{let ue=Un("~",L,q,ne);return[on($t(q.env.get("XDG_DATA_HOME"),"~/.local/share",L,q,ne),"amp"),on(ue,".local","share","amp")].some((ve)=>Wt(M,ve,["secrets.json"]))||fi(M,on(ue,".amp"),["oauth"])}case"secret.cli.amp.config":{let ue=["settings.json","settings.jsonc"],Se=[on($t(q.env.get("XDG_CONFIG_HOME"),"~/.config",L,q,ne),"amp"),on(Un("~",L,q,ne),".config","amp")],ve=Ft(M).split("/"),He=q.env.get("AMP_SETTINGS_FILE");return Se.some((dt)=>Wt(M,dt,ue))||ve.at(-2)===".amp"&&ue.includes(ve.at(-1)??"")||(He?.trim()?mi(M,He,L,q,ne):!1)}case"secret.cli.cursor":{let ue=on($t(q.env.get("XDG_CONFIG_HOME"),"~/.config",L,q,ne),"cursor"),Se=on($t(q.env.get("CURSOR_DATA_DIR"),"~/.cursor",L,q,ne),"projects");return Wt(M,Un("~/.cursor",L,q,ne),["auth.json"])||Wt(M,ue,["auth.json"])||Ft(M).split("/").at(-1)==="mcp-auth.json"&&Fr(Ft(M),Ft(Se))}case"secret.cli.cursor.config":{let ue=Ft(M).split("/");return ue.at(-1)==="mcp.json"&&ue.at(-2)===".cursor"}case"secret.cli.grok-build":return Wt(M,$t(q.env.get("GROK_HOME"),"~/.grok",L,q,ne),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let ue=Ft(M).split("/");return ue.at(-1)==="config.toml"&&ue.at(-2)===".grok"||Wt(M,$t(q.env.get("GROK_HOME"),"~/.grok",L,q,ne),["config.toml","managed_config.toml","requirements.toml"])||Wt(M,Un("/etc/grok",L,q,ne),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var cg=new WeakMap;function $t(M,L,F,q,ne){let re=cg.get(ne)??new Map;cg.set(ne,re);let ue=`${F}\x00${M??""}\x00${L}`,Se=re.get(ue);if(Se!==void 0)return Se;let ve=Un(M?.trim()?M:L,F,q,ne);return re.set(ue,ve),ve}function Wt(M,L,F){return F.some((q)=>xg(M,on(L,q)))}function fi(M,L,F){return F.some((q)=>Fr(Ft(M),Ft(on(L,q))))}function mi(M,L,F,q,ne){return xg(M,Un(L,F,q,ne))}function xg(M,L){return Ft(M)===Ft(L)}function on(M,...L){return Ln([M,...L].filter(Boolean).join("/"))}function rA(M,L,F,q,ne,re){if(F.length===0)return!1;let ue=Ft(pi(M,L,ne,re));return F.some((Se)=>Fr(ue,Ft(pi(Se,q,ne,re))))}function oA(M,L,F,q,ne,re){if(F.length===0)return!1;let ue=Ft(pi(M,L,ne,re));if(!ue)return!1;let Se=ne.env.get("HOME")??ne.home,ve=Se?Ln(Dt(hn(Se),ne.paths,re)):"",He=Ft(ve),dt=ne.env.get("CC_SAFETY_NET_HOME"),mt=Ft(dt?Ln(Dt(qs(hn(dt)),ne.paths,re)):ve&&Ln(Dt(`${ve}/.cc-safety-net`,ne.paths,re)));if(mt&&Fr(ue,mt))return!1;return F.some((ft)=>{let pt=La(ft);if(pt&&dg.basename(ue)!==Ft(pt.name))return!1;let ht=Ft(pi(pt?.root??ft,q,ne,re));if(!ht)return!1;if(He&&(He===ht||He.startsWith(ht.endsWith("/")?ht:`${ht}/`)))return!1;return Fr(ue,ht)&&!(pt&&ue===ht)})}function iA(M){let L=M.split("/");return L.some((F)=>QP.has(F))||eA.some(([F,q])=>L.some((ne,re)=>ne===F&&L[re+1]===q))}function sA(M,L){let F=M.lastIndexOf("."),q=F>0&&F<M.length-1?M.slice(F+1):"";if(q==="")return null;for(let ne of Oa)if(q===ne.extension&&tr(ne.id,L))return ne.id;for(let ne of Ma)if(ne.pattern.test(q)&&tr(ne.id,L))return ne.id;return null}function Ft(M){return M.toLowerCase()}function tr(M,L){return!L?.disabledRules?.includes(M)}function Un(M,L,F,q){let{home:ne,normalized:re}=Oc(M,F,q);if(!re)return"";if(!ne)return re;let ue=Mc(re,ne),Se=Vs(ue)?ue:Ln(qs(L,ue)),ve=Ln(Dt(Se,F.paths,q));if(!Fr(ve,ne)){if(Vs(ue))return ve;return ve===Se?re:ve}let He=ve.slice(ne.length);return He?`~${He}`:"~"}function ug(M,L){return M===L||M.startsWith(`${L}/`)}function aA(M,L,F,q){let{home:ne,normalized:re}=Oc(M,F,q);if(!re||!ne)return"";let ue=Mc(re,ne),Se=dg.normalize(Vs(ue)?ue:Ln(qs(L,ue))),ve=Ln(hn(F.env.get("HOME")??F.home)),He=(ft)=>process.platform==="win32"?ft.toLowerCase():ft,dt=[ne,ve].find((ft)=>ft!==""&&Fr(He(Se),He(ft)));if(dt===void 0)return"";let mt=Se.slice(dt.length);return mt?`~${mt}`:"~"}function pi(M,L,F,q){let{home:ne,normalized:re}=Oc(M,F,q);if(!re)return"";let ue=ne?Mc(re,ne):re;return Ln(Dt(Vs(ue)?ue:qs(L,ue),F.paths,q))}function Oc(M,L,F){let q=L.env.get("HOME")??L.home,ne=q?Ln(Dt(hn(q),L.paths,F)):"",re=Ln(hn(lA(Zn(M,L))));return{home:ne,normalized:re}}function lA(M){if(!M.trim().toLowerCase().startsWith("file:"))return M;try{return Nw(M)}catch{return M}}function Mc(M,L){if(M==="~")return L;if(M.startsWith("~/"))return on(L,M.slice(2));return M}function cA(M){if(process.platform==="win32")return!0;return Dw.parse(M).root.length>1}function Ln(M){let L=M.trim(),F=(L.includes("\\")&&cA(L)?L.replace(/\\/g,"/"):L).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(F==="/")return F;return F.replace(/\/+$/g,"")}function Fr(M,L){return M===L||M.startsWith(L.endsWith("/")?L:`${L}/`)}function Wn(M){return M.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??M}class p extends Error{stage;evaluation;name="GuardEvaluationError";constructor(M,L,F){super(`CC Safety Net ${M} dependency failed`,{cause:F});this.stage=M;this.evaluation=L}}var uA={findPolicyMutation:Jp,findGitMetadataMutation:wf,resolveGitMetadata:fA,loadPolicySnapshot:E,findSensitiveTarget:hg,analyzeCommand:jp,getModes:T},dA=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function V(M,L){let F={...uA,...L.dependencies},q=gA(M),ne=gi(M)?M.command:q,re=gr("policy-protection",ne,()=>Ef(M)),ue=dn(re,"input-candidate"),Se=dn(re,"declared-command");if(gi(M)&&M.command?.trim()&&Se?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Gn,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:M.command,segment:M.command}}};if(ue?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:Vf,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let ve=Fn(),He=gr("policy-protection",ne,()=>F.resolveGitMetadata([M.context.executionCwd,M.context.configCwd],L.environment)),dt=gr("policy-protection",ne,()=>F.findPolicyMutation(re,L.environment,ve));if(dt){let bt=ne??dt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Ge,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:bt,segment:dt.target}}}}let mt=gr("policy-protection",ne,()=>qp(re,L.environment,ve));if(mt){let bt=ne??mt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Ue,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:bt,segment:mt.target}}}}let ft=gr("policy-protection",ne,()=>F.findGitMetadataMutation(re,He,L.environment,ve));if(ft){let bt=ne??ft.target;return{stage:"policy-protection",decision:{kind:"deny",reason:k,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:bt,segment:ft.target}}}}let pt=gr("config-load",ne,()=>F.loadPolicySnapshot(L.environment,{...L.policyOptions,cwd:M.context.configCwd})),ht=pt.policy,gt=F.getModes(ht,L.environment.env),yt={level:gt.effectiveLevel,...mA(pt)},St=ht.secretProtection.enabled===!1?null:gr("secret-protection",ne,()=>F.findSensitiveTarget(re,ht.secretProtection,L.environment,ve,{strict:gi(M)||ue?.program.dialect==="powershell"?gt.strict:void 0}));if(St){let bt=ne??St.target;return{stage:"secret-protection",...yt,decision:{kind:"deny",reason:fg,intent:"hard_stop",ruleId:St.ruleId,evidence:{command:bt,segment:St.target}}}}if(!gi(M))return{stage:"non-command",...yt,decision:{kind:"allow"}};if(!M.command||M.command.trim()==="")return{...Dc("command-validation",ne),...yt};let Ct=gr("command-analysis",ne,()=>Vp(()=>F.analyzeCommand(M.command,{cwd:M.context.executionCwd,shell:M.route.shell,policySnapshot:pt,environment:L.environment,protectedGitMetadata:He,effectiveCapabilities:gt.capabilities,strict:gt.strict,paranoidRm:gt.paranoidRm,paranoidInterpreters:gt.paranoidInterpreters,worktreeMode:gt.worktreeMode,budget:ve,...L.trace?{trace:L.trace}:{}},pA(re),re.store),M.command,L.trace));if(Ct.decision){let bt=!gt.strict&&(Ct.decision.ruleId==="raw-text.dangerous-command"||Ct.decision.reason===ei&&!dA.test(Ct.decision.evidence?.segment??"")&&_n(M.command)===null);return{stage:"command-analysis",...yt,..."errorCode"in Ct?{errorCode:Ct.errorCode}:{},decision:bt?{...Ct.decision,unverifiedByStandardMode:!0}:Ct.decision}}return{stage:"command-analysis",...yt,decision:{kind:"allow"}}}function fA(M,L){let F=[...new Set(M.filter((q)=>typeof q==="string"&&q!==""))].flatMap((q)=>L.gitMetadata(q)??[]);if(F.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(F.flatMap((q)=>q.entries))]),markerFiles:Object.freeze([...new Set(F.flatMap((q)=>q.markerFiles))]),directories:Object.freeze([...new Set(F.flatMap((q)=>q.directories))]),hooksDirectories:Object.freeze([...new Set(F.flatMap((q)=>q.hooksDirectories))])})}function mA(M){if(M.state==="ready")return{};return{configFallback:{reason:M.reason}}}function pA(M){return dn(M,"declared-command")?.program}function gA(M){try{return oe(M.input)}catch(L){let F=gi(M)?M.command:void 0;throw new p("policy-protection",Dc("policy-protection",L instanceof f?void 0:F,L),L)}}function gr(M,L,F){try{return F()}catch(q){throw new p(M,Dc(M,q instanceof f?void 0:L,q),q)}}function Dc(M,L,F){let q=F instanceof s||F instanceof y;return{stage:M,decision:{kind:"deny",reason:q?Js:vo,ruleId:q?"analysis.limit":"analysis.failed-closed",intent:"stop_and_explain",...L?{evidence:{command:L,segment:L}}:{}}}}function gi(M){return M.route.kind==="command"}
|
|
45
|
+
export{a,s,K,_e,We,R,tt,Be,we,I,O,J,nt,c,n,ze,Ce,T,x,de,rt,f,_,oe,pe,ot,Ve,qe,l,Pe,o,v,i,ie,r,g,fe,j,it,st,u,me,ge,at,D,Y,se,S,ct,U,b,Ee,G,d,Z,Ke,Je,N,w,P,he,ye,Ae,lt,m,e,Ie,ke,Ye,Ze,ae,Re,ce,Oe,X,H,De,be,W,Xe,B,Q,ee,le,Qe,et,C,z,Ne,Le,Fe,Me,E,$e,Te,je,h,t,te,xe,y,k,A,ut,Ue,Ge,p,V};
|