cc-safety-net 2.6.13 → 2.6.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,49 @@
1
+ var wa="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Xn="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",zo="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var xa={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."},Fo={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,...xa},processedCandidateBytes:{cap:4194304,...xa},pathEnvironmentExpansion:{cap:64,...xa},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,...Fo},trackedHeredocFiles:{cap:64,...Fo},controlFlowStates:{cap:64,...Fo},wrapperPeelIterations:{cap:20,...Fo},derivedCommandShape:Fo});class s extends Error{kind;name="AnalysisLimit";constructor(W){super(a[W].reason);this.kind=W}}function In(){let W=new Map;return{counters:W,resolvedPaths:new Map,charge(G,H=1){let J=(W.get(G)??0)+H;if(W.set(G,J),J>a[G].cap)throw new s(G)}}}var _h=[/\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 Y(W){return Me(W.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 Me(W){return _h.reduce((G,H)=>G.replace(H,"<redacted>"),W.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 nt(W){return md(W).reduceRight((G,H)=>`${G.slice(0,H.valueStart)}<redacted>${G.slice(H.valueEnd)}`,W)}function T(W){return Me(nt(W))}function bt(W){return md(W).map((G)=>W.slice(G.valueStart,G.valueEnd))}function rt(W){return/[A-Za-z_][A-Za-z0-9_]*=/.test(W)}function md(W){return[...W.matchAll(/[A-Za-z_][A-Za-z0-9_]*=/g)].flatMap((G)=>{let H=W[G.index-1];if(G.index>0&&H&&!/[\s"'([{]/.test(H))return[];let J=G.index+G[0].length;if(J>=W.length)return[];return[{valueStart:J,valueEnd:xh(W,J)}]})}function xh(W,G){if(W.startsWith("$(",G))return wh(W,G);let H=W[G];if(H==='"'||H==="'"){for(let oe=G+1;oe<W.length;oe++){if(H==='"'&&W[oe]==="\\"){oe++;continue}if(W[oe]===H)return oe+1}return W.length}let J=G;while(J<W.length&&!/\s/.test(W[J]??""))J++;return J}function wh(W,G){let H=0,J;for(let oe=G;oe<W.length;oe++){let ie=W[oe];if(J){if(J==='"'&&ie==="\\"){oe++;continue}if(ie===J)J=void 0;continue}if(ie==='"'||ie==="'"){J=ie;continue}if(ie==="$"&&W[oe+1]==="("){H++,oe++;continue}if(ie!==")")continue;if(H--,H===0)return oe+1}return W.length}var Ah={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 Ph(W){let G=W.maxLen??200,H=W.redact??((oe)=>oe),J=(oe)=>oe.length>G?`${oe.slice(0,G)}...`:oe;return[W.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${H(W.reason)}`,W.ruleId?`Rule: ${W.ruleId}`:void 0,W.toolName?`Tool: ${W.toolName}`:void 0,W.command?`Command: ${J(H(W.command))}`:void 0,W.segment&&W.segment!==W.command?`Segment: ${J(H(W.segment))}`:void 0,W.cwd?`Working directory: ${J(H(W.cwd))}`:void 0,W.configWarning?`Config warning: ${H(W.configWarning)}`:void 0,W.askUser?"Approve only if you expected this command.":Ah[W.intent??"manual_only"]].filter((oe)=>oe!==void 0).join(`
2
+
3
+ `)}function _e(W,G){if(W.decision.kind!=="deny")return;let H=G.includeEvidence?W.decision.evidence:void 0;return{reason:W.decision.reason,ruleId:W.decision.ruleId,intent:W.decision.intent,command:H?.command,segment:H?.segment,toolName:G.toolName,...W.configFallback?{configWarning:W.configFallback.reason}:{},...W.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function L(W={}){return{reason:zo,ruleId:"analysis.failed-closed",intent:"stop_and_explain",command:W.command,segment:W.segment??W.command,toolName:W.toolName}}var Th={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 _(W,G={}){return{...Th[W.directory][W.problem],command:G.command,toolName:G.toolName,cwd:W.cwd}}function Z(W){return Ph({...W,redact:Y})}function xt(W){return Y(W instanceof Error?W.message:String(W))}import{spawnSync as dy}from"node:child_process";import{lstatSync as uy,realpathSync as my,statSync as fy}from"node:fs";import{homedir as py,tmpdir as gy}from"node:os";import{statSync as ay}from"node:fs";import{join as ly}from"node:path";import{basename as gd,dirname as Ih,isAbsolute as kh,join as Oh,normalize as Mh,resolve as fd}from"node:path";var Dh=256,Fi=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 fn(W,G=process.platform){if(G!=="win32")return W;return W.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function rr(W,G=process.platform){if(G!=="win32")return!1;return(W[0]==="/"||W[0]==="\\")&&(W[1]==="/"||W[1]==="\\")}function Ia(W,G){return Aa(W,0,G)}function Aa(W,G,H){let J="",oe=0,ie=0;while(oe<W.length){if(W[oe]!=="$"){J+=W[oe],oe++;continue}if(W[oe+1]==="{"){let Re=Pa(W,oe+2),Te=Nh(W,oe,G);if(Te===null){if(Fi.has(Re))throw new s("pathEnvironmentExpansion");if(ie++,ie>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");J+="${",oe+=2;continue}let ke=W.slice(oe,Te+1);J+=Lh(ke,G,H),oe=Te+1;continue}let fe=Pa(W,oe+1);if(!fe){J+="$",oe++;continue}J+=Ta(fe,H)??`$${fe}`,oe+=fe.length+1}return J}function Nh(W,G,H){let J=1;for(let oe=G+2;oe<W.length;oe++){if(W[oe]==="\\"){oe++;continue}if(W[oe]==="$"&&W[oe+1]==="{"){if(J++,H+J>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");oe++;continue}if(W[oe]!=="}")continue;if(J--,J===0)return oe}return null}function Lh(W,G,H){let J=W.slice(2,-1),oe=Pa(J,0);if(!oe)return W;let ie=J.slice(oe.length);if(!ie)return Ta(oe,H)??W;let fe=[":-",":+",":=",":?","-","+","=","?"].find((ke)=>ie.startsWith(ke));if(!fe){if(Fi.has(oe))throw new s("pathEnvironmentExpansion");return W}if(!Fi.has(oe))return W;if(fe.endsWith("="))throw new s("pathEnvironmentExpansion");let Re=Ta(oe,H),Te=fe.startsWith(":")?Re!==null&&Re!=="":Re!==null;if(fe.endsWith("?")&&!Te)throw new s("pathEnvironmentExpansion");if(fe.endsWith("-")||fe.endsWith("?"))return Te?Re??"":Aa(ie.slice(fe.length),G+1,H);return Te?Aa(ie.slice(fe.length),G+1,H):""}function Pa(W,G){if(!/[A-Za-z_]/.test(W[G]??""))return"";let H=G+1;while(/[A-Za-z0-9_]/.test(W[H]??""))H++;return W.slice(G,H)}function Ta(W,G){if(!Fi.has(W))return null;if(W==="HOME")return G.env.get("HOME")??G.home;return G.env.get(W)??null}function Bt(W,G,H){if(!W)return W;let J=H.resolvedPaths.get(W);if(J!==void 0)return J;let oe=[],ie=W;while(!0){hd(H,ie);let fe=G.realpath(ie);if(fe!==null)return pd(H,W,fe,oe);let Re=Ih(ie);if(Re===ie||oe.length>=Dh)return pd(H,W,ie,oe);oe.push(gd(ie)),ie=Re}}function pd(W,G,H,J){let oe=J.length===0?H:Oh(H,...J.reverse());return W.resolvedPaths.set(G,oe),oe}function Wh(W,G,H){let J=H.resolvedPaths.get(W);if(J!==void 0)return J;hd(H,W);let oe=G.realpath(W);if(oe!==null)H.resolvedPaths.set(W,oe);return oe}function hd(W,G){W.charge("realpathAttempts"),W.charge("processedCandidateBytes",Buffer.byteLength(G))}function pn(W,G,H,J){let oe=Sd(W,G,H);if(!oe)return"";return Bt(oe,H.paths,J).replace(/\\/g,"/")}function yd(W,G,H,J,oe){let ie=Sd(W,G,H);if(!ie)return null;if(oe(gd(ie)))return Bt(ie,H.paths,J).replace(/\\/g,"/");let fe=Wh(ie,H.paths,J);return fe===null?null:fe.replace(/\\/g,"/")}function Sd(W,G,H){let J=H.home,oe=Ia(W.trim(),H).replace(/\\/g,"/");if(!oe)return"";let ie=oe==="~"?J:oe.startsWith("~/")?fd(J,oe.slice(2)):oe,fe=fn(ie);return Mh(kh(fe)?fe:fd(G,fe))}import{spawnSync as Gh}from"node:child_process";import{accessSync as bd,constants as Cd,existsSync as $o,lstatSync as Fh,opendirSync as zh,readFileSync as Bo,realpathSync as oo,statSync as io}from"node:fs";import{dirname as Rd,isAbsolute as ka,join as kn,resolve as zi}from"node:path";var $h=["/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"],Bh=5000;function _d(W,G=ry(),H=Bh){let J=Uh(W),oe=J===null?null:Hh(J);if(J===null||oe===null)return null;let ie=ty(J,oe,G,H);return ie===null?null:{recursiveSubmodules:ie}}function Uh(W){try{let G=oo(zi(W));return io(G).isDirectory()?G:null}catch{return null}}function Hh(W){let G=ey(W);if(!G)return null;try{let H=Fh(G);if(H.isSymbolicLink()||!H.isFile())return null;let J=Oa(G);if(!J?.commonDir)return null;if(!Kh(J.gitDir,G))return null;return Ad(J.gitDir,J.commonDir)?null:{gitDir:J.gitDir,commonDir:J.commonDir}}catch{return null}}function Oa(W){try{let G=jh(W);if(!G)return null;let H=oo(ka(G)?G:zi(Rd(W),G));if(!io(H).isDirectory())return null;return{gitDir:H,commonDir:Vh(H)}}catch{return null}}function jh(W){let G=Bo(W,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!G.startsWith("gitdir:"))return null;return G.slice(7).trim()||null}function Vh(W){try{let G=Bo(kn(W,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!G)return null;let H=oo(ka(G)?G:zi(W,G));return io(H).isDirectory()?H:null}catch{return null}}function Kh(W,G){let H=qh(W);return H===null?!1:Yh(W,H,G)}function qh(W){let G=kn(W,"gitdir");if(!$o(G))return null;let H=Bo(G,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return H===""?null:H}function Yh(W,G,H){try{return Zh(ka(G)?G:zi(W,G),H)}catch{return!1}}function Zh(W,G){try{let H=io(W),J=io(G);if(H.ino!==0&&J.ino!==0&&H.dev===J.dev&&H.ino===J.ino)return!0}catch{}return vd(oo.native(W))===vd(oo.native(G))}function vd(W){let G=W.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),H=G.length>1&&G.endsWith("/")?G.slice(0,-1):G;return process.platform==="win32"?H.toLowerCase():H}function xd(W){try{return bd(kn(W,"objects"),Cd.X_OK),bd(kn(W,"refs"),Cd.X_OK),/^(?:ref:[\t\n\r ]*refs\/|[0-9a-fA-F]{40})/.test(Pd(kn(W,"HEAD")))}catch{return!1}}function wd(W){return $o(kn(W,"commondir"))||Ad(W,W)}function Ad(W,G){return[kn(G,"config"),kn(W,"config.worktree")].some(Xh)||Qh(W)}var Ed=1048576;function Pd(W){let G=io(W);if(!G.isFile()||G.size>Ed)throw Error(`${W} is not a regular file within ${Ed} bytes`);return Bo(W,"utf-8")}function Xh(W){try{return/(?:^|[\s\]])worktree\s*=/i.test(Pd(W))}catch(G){return G.code!=="ENOENT"}}var Jh=1e4;function Qh(W){let G=[W],H=0;try{while(G.length>0){let J=G.pop(),oe=zh(J);try{for(let ie=oe.readSync();ie!==null;ie=oe.readSync()){if(H++,ie.isSymbolicLink()||ie.isFIFO()||H>Jh)return!0;let fe=J===W&&ie.name==="objects";if(ie.isDirectory()&&!fe)G.push(kn(J,ie.name))}}finally{oe.closeSync()}}return!1}catch(J){return J.code!=="ENOENT"}}function ey(W){try{return Ma(oo(W))}catch{return null}}function Ma(W){let G=W;while(!0){let H=kn(G,".git");if($o(H))return H;let J=Rd(G);if(J===G)return null;G=J}}function ty(W,G,H,J){if(ny(G))return!0;if(H===null)return!0;let oe=Gh(H,["config","--get","submodule.recurse"],{cwd:W,encoding:"utf8",env:oy(process.env),stdio:["ignore","pipe","ignore"],timeout:J});if(oe.error!==void 0||oe.status!==0&&oe.status!==1)return null;return oe.status===0&&Td(oe.stdout.trim())}function ny(W){return[kn(W.commonDir,"config"),kn(W.gitDir,"config.worktree")].filter((G)=>$o(G)).some((G)=>iy(G))}function ry(){return $h.find((W)=>$o(W))??null}function Uo(W){return W==="GIT_CONFIG_COUNT"||W==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(W)}function oy(W){return Object.fromEntries(Object.entries(W).filter(([G])=>!Uo(G)))}function iy(W){let G;try{G=Bo(W,"utf-8")}catch{return!0}let H="",J=!1;for(let oe of G.split(/\r?\n/)){let ie=oe.trim();if(ie===""||ie.startsWith("#")||ie.startsWith(";"))continue;let fe=ie.match(/^\[([^\]]+)\]$/);if(fe){H=fe[1]?.trim().toLowerCase()??"";continue}let Re=ie.indexOf("="),Te=(Re===-1?ie:ie.slice(0,Re)).trim().toLowerCase(),ke=Re===-1?"true":ie.slice(Re+1).trim();if(sy(H)&&Te==="path")return!0;if(H==="submodule"&&Te==="recurse")J=Td(ke)}return J}function sy(W){return W==="include"||W.startsWith("includeif ")}function Td(W){let G=W.toLowerCase();return G!=="false"&&G!=="no"&&G!=="off"&&G!=="0"}function Id(W,G){if(W==="")return null;let H=In(),J=Ma(pn(W,W,G,H)),oe=J?cy(J,W,G,H):null;if(!oe)return null;return Object.freeze({entries:Object.freeze([oe.entry]),markerFiles:Object.freeze(oe.markerFile?[oe.markerFile]:[]),directories:Object.freeze(oe.directories),hooksDirectories:Object.freeze(oe.hooksDirectories)})}function cy(W,G,H,J){try{let oe=pn(W,G,H,J),ie=ay(W),fe=ie.isFile()?oe:null,Re=ie.isFile()?Oa(W):null,Te=(ie.isDirectory()?[oe]:[Re?.gitDir,Re?.commonDir]).flatMap((Le)=>Le?[so(pn(Le,G,H,J))]:[]),ke=[...new Set(ie.isDirectory()?[so(W.replace(/\\/g,"/")),...Te]:Te)];return{entry:so(oe),markerFile:fe?so(fe):null,directories:ke,hooksDirectories:[...new Set(ke.flatMap((Le)=>{let Xe=so(ly(Le,"hooks").replace(/\\/g,"/"));return[Xe,so(pn(Xe,G,H,J))]}))]}}catch{return null}}function so(W){return process.platform==="win32"?W.toLowerCase():W}var hy={realpath:(W)=>{try{return my(W)}catch{return null}},entryKind:(W)=>{try{let G=uy(W,{throwIfNoEntry:!1});if(!G)return"missing";return G.isSymbolicLink()?"symlink":"present"}catch(G){if(G.code==="ENAMETOOLONG")return"missing";throw G}},isDirectory:(W)=>{try{return fy(W).isDirectory()}catch{return!1}}};function c(){let W=new Map;return Sy({env:new Map(Object.entries(process.env).flatMap(([G,H])=>H===void 0?[]:[[G,H]])),home:fn(process.env.HOME||py()),tmpdir:gy(),darwinUserTempDir:()=>$i(W,"",yy),paths:hy})}function yy(){if(process.platform!=="darwin")return null;let W=dy("/usr/bin/getconf",["DARWIN_USER_TEMP_DIR"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000}),G=W.stdout?.replace(/\n$/,"");return W.status===0&&G?.startsWith("/")?G:null}function Sy(W,G={}){let H=new Map,J=new Map,oe=new Map,ie={...W,gitMetadata:(fe)=>$i(H,fe,()=>Id(fe,ie)),worktreeFacts:(fe)=>$i(J,fe,()=>_d(fe)),isGitDirectory:xd,gitDirectoryRedirects:(fe)=>$i(oe,fe,()=>wd(fe)),...G};return ie}function $i(W,G,H){let J=W.get(G);if(J!==void 0)return J;let oe=H();return W.set(G,oe),oe}import{accessSync as $y,constants as jd,statSync as By}from"node:fs";import{isAbsolute as Wa,relative as Uy,resolve as Vd,sep as Hy}from"node:path";import{types as by}from"node:util";var Cy=new Set(["applypatch","patch"]),vy=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),Ey=new Set(["grep","grepsearch","rg"]),Ry=new Set(["find","findbyname","glob"]),_y=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),xy=new Set(["command","diff","input","patch","patchtext"]),kd=new TextEncoder,wy=new TextDecoder,Ay=/\s/,Py=64;class m extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var Ho=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Ie(W){return W.replace(/[-_\s]/g,"").toLowerCase()}function Ui(W){return _y.has(Ie(W))}function x(W){let G=Ie(W);if(Cy.has(G))return"patch";if(Ey.has(G))return"grep";if(Ry.has(G))return"glob";if(vy.has(G))return"path";return"unknown"}function se(W){if(!W||typeof W!=="object")return;Bd(W);let G=Object.getOwnPropertyDescriptor(W,"command");if(!G){if("command"in W)Jn();return}if(G.get||G.set)Jn();let H=G.value;return typeof H==="string"&&H!==""?H:void 0}function Ld(W,G){return Wd(W,G,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Wd(W,G,H,J,oe){let ie=$d(W,J,oe);if(typeof W==="string")return H?[W]:[];if(!ie)return[];let fe=ie.entries.flatMap(([Re,Te])=>Wd(Te,G,ie.array?H:G.has(Gd(Re)),J,oe+1));return J.ancestors.delete(ie.object),fe}function Gd(W){return W.replace(/-/g,"_").toLowerCase()}function Fd(W){return zd(W,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Iy)}function zd(W,G,H,J){let oe=$d(W,H,J);if(typeof W==="string")return G?[W]:[];if(!oe)return[];let ie=oe.entries.flatMap(([fe,Re])=>zd(Re,oe.array?G:xy.has(Gd(fe)),H,J+1));return H.ancestors.delete(oe.object),ie}function Ty(W,G,H){if(G.nodes++,W!==null&&typeof W==="object"&&H>Ho.maxDepth||G.nodes>Ho.maxNodes)Jn();if(typeof W!=="string")return;let J=Buffer.byteLength(W);if(G.stringBytes+=J,J>Ho.maxStringBytes||G.stringBytes>Ho.maxAggregateStringBytes)Jn()}function $d(W,G,H){if(Ty(W,G,H),!W||typeof W!=="object")return null;let J=Bd(W);if(G.ancestors.has(W))Jn();let oe=Reflect.ownKeys(W);if(G.keys+=oe.length,G.keys>Ho.maxKeys)Jn();let ie=oe.flatMap((fe)=>{let Re=Object.getOwnPropertyDescriptor(W,fe);if(!Re||Re.get||Re.set)Jn();return typeof fe==="string"&&Re.enumerable?[[fe,Re.value]]:[]});return G.ancestors.add(W),{object:W,array:J,entries:ie}}function Bd(W){if(by.isProxy(W))Jn();let G=Array.isArray(W),H=Object.getPrototypeOf(W);if(G&&H!==Array.prototype||!G&&H!==Object.prototype&&H!==null)Jn();return G}function Jn(){throw new m}function Iy(W){let G=[],H=W.split(/\r?\n/),J=!1,oe=!1,ie=null,fe=null,Re=()=>{oe=!1,ie=null,fe=null};for(let Te=0;Te<H.length;Te++){let ke=H[Te]??"";if(ke==="*** Begin Patch"){J=!0,Re();continue}if(ke==="*** End Patch"){J=!1,Re();continue}if(ke.startsWith("@@")){let Le=ky(ke);if(oe=!0,ie=Le?.oldLines??null,fe=Le?.newLines??null,ie===0&&fe===0)Re();continue}if(oe&&ie!==null&&fe!==null){let Le=ke.startsWith(" ")||ke.startsWith("-")?1:0,Xe=ke.startsWith(" ")||ke.startsWith("+")?1:0;if(ie=Math.max(0,ie-Le),fe=Math.max(0,fe-Xe),ie===0&&fe===0)Re();continue}if(ke.startsWith("*** ")){Re(),G.push(...Da(ke));continue}if(oe)continue;if(ke.startsWith("diff --git ")){G.push(...Da(ke));continue}if(ke.startsWith("--- ")){let Le=H[Te+1]??"";if(!Le.startsWith("+++ "))continue;G.push(...La(Bi(ke.slice(4),!0),Bi(Le.slice(4),!0))),Te++;continue}if(!J)G.push(...Da(ke))}return G}function ky(W){let G=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(W);if(!G)return null;return{oldLines:Number(G[1]??1),newLines:Number(G[2]??1)}}function Da(W){let G=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(W);if(G?.[1])return Nd(G[1]);let H=/^\*\*\* Move to: (.+)$/.exec(W);if(H?.[1])return Nd(H[1]);if(W.startsWith("diff --git "))return Oy(W.slice(11));let J=/^--- (.+)$/.exec(W);if(J?.[1])return Dd(J[1]);let oe=/^\+\+\+ (.+)$/.exec(W);if(oe?.[1])return Dd(oe[1]);let ie=/^(?:rename|copy) (?:from|to) (.+)$/.exec(W);if(ie?.[1])return Fy(ie[1]);return[]}function Oy(W){let G=My(W);if(G.length===2&&G[0]&&G[1])return La(G[0],G[1]);let H=Dy(W);return H?La(W.slice(H.oldStart,H.oldEnd),W.slice(H.newStart,H.newEnd)):[]}function My(W){let G=[],H=0;while(H<W.length&&G.length<2){while(Ir(W[H]))H++;if(H>=W.length)break;let J=W[H]==='"'||W[H]==="'"?W[H]:void 0;if(!J){let ie=H;while(H<W.length&&!Ir(W[H]))H++;G.push(W.slice(ie,H));continue}let oe=Ud(W,H,J);if(!oe)return[];G.push(oe.value),H=oe.end}while(Ir(W[H]))H++;return H===W.length?G:[]}function Dy(W){let G=0;while(G<W.length&&Ir(W[G]))G++;let H=W.length;while(H>G&&Ir(W[H-1]))H--;let J=0,oe=G;while(oe<H){if(!Ir(W[oe])){oe++;continue}let ie=oe;while(oe<H&&Ir(W[oe]))oe++;if(ie===G||oe===H)continue;if(J++,J>Py)Jn();if(Ny(W,G,ie,oe,H))return{oldStart:G,oldEnd:ie,newStart:oe,newEnd:H}}return null}function Ny(W,G,H,J,oe){if(Na(W,G,H,J,oe))return!0;let ie=Od(W,"/",G,H),fe=Od(W,"/",J,oe);if(ie<=G||fe<=J)return!1;if(Na(W,G,ie,J,fe))return!1;return Na(W,ie+1,H,fe+1,oe)}function Na(W,G,H,J,oe){if(H-G!==oe-J)return!1;for(let ie=0;ie<H-G;ie++)if(W[G+ie]!==W[J+ie])return!1;return!0}function Od(W,G,H,J){for(let oe=H;oe<J;oe++)if(W[oe]===G)return oe;return-1}function Ir(W){return W!==void 0&&Ay.test(W)}function Ud(W,G,H){let J=[],oe=G+1;while(oe<W.length){let ie=String.fromCodePoint(W.codePointAt(oe)??0);if(ie===H)return{value:wy.decode(Uint8Array.from(J)),end:oe+1};if(ie!=="\\"||H==="'"){J.push(...kd.encode(ie)),oe+=ie.length;continue}let fe=W.slice(oe+1),Re=/^[0-7]{1,3}/.exec(fe)?.[0];if(Re){J.push(Number.parseInt(Re,8)),oe+=Re.length+1;continue}J.push(...kd.encode(Ly(fe[0]??""))),oe+=2}return null}function Ly(W){return{a:"\x07",b:"\b",f:"\f",n:`
4
+ `,r:"\r",t:"\t",v:"\v"}[W]??W}function Wy(W){return jo(zy(W))}function La(W,G){if(W==="/dev/null")return Md(G);if(G==="/dev/null")return Md(W);if(W.startsWith("a/")&&G.startsWith("b/"))return[W.slice(2),G.slice(2)].flatMap(jo);let H=Gy(W,G)??(W===G?Hd(W):null);return[W,G,...H?[H]:[]].flatMap(jo)}function Md(W){let G=Hd(W);return[W,...G?[G]:[]].flatMap(jo)}function Hd(W){let G=W.indexOf("/");return G>0&&G<W.length-1?W.slice(G+1):null}function Gy(W,G){let H=W.indexOf("/"),J=G.indexOf("/");if(H<1||J<1)return null;if(W.slice(0,H)===G.slice(0,J))return null;let oe=W.slice(H+1);return oe===G.slice(J+1)?oe:null}function Dd(W){return Wy(Bi(W,!0))}function Fy(W){return jo(Bi(W,!1))}function Bi(W,G){let H=W.trim(),J=H[0]==='"'||H[0]==="'"?H[0]:void 0;if(J){let oe=Ud(H,0,J);if(oe&&(G||H.slice(oe.end).trim()===""))return oe.value}return G?H.split("\t",1)[0]?.trim()??"":H}function zy(W){return W.startsWith("a/")||W.startsWith("b/")?W.slice(2):W}function jo(W){return W===""||W==="/dev/null"?[]:[W]}function Nd(W){let G=W.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return G===""||G==="/dev/null"?[]:[G]}function ge(W){try{if(!By(W).isDirectory())return!1;return $y(W,jd.R_OK|jd.X_OK),!0}catch{return!1}}function St(W,G,H){if(rr(W))return;let J=G.flatMap((ie)=>Hi(ie,H));if(!J[0])return;let oe=Hi(Wa(W)?W:Vd(J[0],W),H)[0];if(!oe)return;return J.some((ie)=>jy(oe,ie))?oe:void 0}function Kd(W,G,H){if(rr(W))return;return Hi(Wa(W)?W:Vd(G,W),H)[0]}function it(W,G){return W.flatMap((H)=>Hi(H,G))[0]}function Hi(W,G){let H=G.realpath(W);if(H===null)return[];return G.isDirectory(H)?[H]:[]}function jy(W,G){let H=Uy(G,W);return H===""||H!==".."&&!H.startsWith(`..${Hy}`)&&!Wa(H)}var Vy=8388608;async function st(W){let G=[],H=0;for await(let J of W){let oe=typeof J==="string"?Buffer.from(J,"utf-8"):Buffer.from(J.buffer,J.byteOffset,J.byteLength);if(H+=oe.byteLength,H>Vy)throw Ky(W),Error("hook input byte limit exceeded");G.push(oe)}return Buffer.concat(G,H).toString("utf-8")}function Ky(W){let G=W.destroy??W.cancel;if(!G)return;try{Promise.resolve(G.call(W)).catch(()=>{})}catch{}}function l(W,G,H,J,oe){if(H.kind!=="command")return{toolName:W,input:G,route:H,context:J};return{toolName:W,input:G,route:H,context:J,command:oe}}var ao=["fail_closed","paranoid_rm","paranoid_interpreters"],ji={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 qd(W,G){if(!G)return W;return Vi.indexOf(G)>Vi.indexOf(W)?G:W}function Yd(W){let G=me(n.level,W);return Vi.find((H)=>H===G)}function Zd(W,G){return qd(W,Yd(G))}function qy(W){let G=me(n.level,W);if(!G)return;let H=Yd(W);if(H)return H;console.error(`CC Safety Net: ignored invalid ${n.level.name}=${JSON.stringify(G.slice(0,40))}. Use ${Vi.join(", ")}.`);return}function ot(W){if(W===void 0||W==="all")return"all";if(W==="blocked")return"blocked";return"invalid"}function Pe(W){return ot(me(n.auditScope,W))==="all"}function Ga(W){if(W.failClosed&&W.paranoidRm&&W.paranoidInterpreters)return"paranoid";if(W.failClosed&&!W.paranoidRm&&!W.paranoidInterpreters)return"strict";if(!W.failClosed&&!W.paranoidRm&&!W.paranoidInterpreters)return"standard";return"custom"}function P(W={},G){let H=W.safety?.level??"standard",J=qy(G),oe=qd(H,J),ie=ji[oe],fe={failClosed:ie.fail_closed,paranoidRm:ie.paranoid_rm,paranoidInterpreters:ie.paranoid_interpreters},Re={failClosed:oe===H?"preset":"environment",paranoidRm:oe===H?"preset":"environment",paranoidInterpreters:oe===H?"preset":"environment"},Te={failClosed:[`policy safety.level=${H}`],paranoidRm:[`policy safety.level=${H}`],paranoidInterpreters:[`policy safety.level=${H}`]};if(oe!==H)Te.failClosed.push(`env ${n.level.name}=${J}`),Te.paranoidRm.push(`env ${n.level.name}=${J}`),Te.paranoidInterpreters.push(`env ${n.level.name}=${J}`);if(W.safety?.overrides?.failClosed!==void 0)fe.failClosed=W.safety.overrides.failClosed,Re.failClosed="capability_override",Te.failClosed.push("policy safety.overrides.fail_closed");if(W.safety?.overrides?.paranoidRm!==void 0)fe.paranoidRm=W.safety.overrides.paranoidRm,Re.paranoidRm="capability_override",Te.paranoidRm.push("policy safety.overrides.paranoid_rm");if(W.safety?.overrides?.paranoidInterpreters!==void 0)fe.paranoidInterpreters=W.safety.overrides.paranoidInterpreters,Re.paranoidInterpreters="capability_override",Te.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(S(n.strict,G))fe.failClosed=!0,Re.failClosed="environment",Te.failClosed.push(`env ${n.strict.name}`);if(S(n.paranoid,G))fe.paranoidRm=!0,fe.paranoidInterpreters=!0,Re.paranoidRm="environment",Re.paranoidInterpreters="environment",Te.paranoidRm.push(`env ${n.paranoid.name}`),Te.paranoidInterpreters.push(`env ${n.paranoid.name}`);if(S(n.paranoidRm,G))fe.paranoidRm=!0,Re.paranoidRm="environment",Te.paranoidRm.push(`env ${n.paranoidRm.name}`);if(S(n.paranoidInterpreters,G))fe.paranoidInterpreters=!0,Re.paranoidInterpreters="environment",Te.paranoidInterpreters.push(`env ${n.paranoidInterpreters.name}`);let ke=!!W.worktreeMode||S(n.worktree,G);return{strict:fe.failClosed,paranoidRm:fe.paranoidRm,paranoidInterpreters:fe.paranoidInterpreters,worktreeMode:ke,effectiveLevel:Ga(fe),capabilities:{fail_closed:{enabled:fe.failClosed,source:Re.failClosed,sources:Te.failClosed},paranoid_rm:{enabled:fe.paranoidRm,source:Re.paranoidRm,sources:Te.paranoidRm},paranoid_interpreters:{enabled:fe.paranoidInterpreters,source:Re.paranoidInterpreters,sources:Te.paranoidInterpreters}}}}function S(W,G){let H=typeof W==="string"?Vo(W,G):me(W,G);return H==="1"||H?.toLowerCase()==="true"}function Vo(W,G){return G.get(W)}function me(W,G){let H=Vo(W.name,G);if(H!==void 0)return H;if(W.legacyName)return Vo(W.legacyName,G);return}function vt(W,G){return Vo(W.name,G)!==void 0||!!W.legacyName&&Vo(W.legacyName,G)!==void 0}import{dirname as Nr}from"node:path";import{closeSync as Yy,constants as Ko,fstatSync as Fa,fsyncSync as Zy,lstatSync as On,mkdirSync as Xd,openSync as Jd,readdirSync as $a,readFileSync as Xy,realpathSync as lo,renameSync as Jy,rmdirSync as Qd,statSync as za,unlinkSync as Ba,writeFileSync as Qy}from"node:fs";import{isAbsolute as eu,join as kr,normalize as eS,parse as Ki,relative as Ua,resolve as Ha,sep as qi}from"node:path";function Fe(){let W=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${W()}${W()}`}var tS=Symbol("PolicyFilesystemScope"),nS=Symbol("PolicyFilesystemTarget"),tu=Ko.O_NOFOLLOW??0;class o extends Error{name="PolicyFilesystemError";constructor(W){super(`Unable to access ${W} filesystem safely.`)}}function w(W,G){return{[tS]:!0,root:Ha(W),label:G}}function qo(W,G){let H=eS(G);if(G===""||eu(G)||H===".."||H.startsWith(`..${qi}`))throw new o(W.label);return{[nS]:!0,scope:W,relativePath:H,path:kr(W.root,H)}}function i(W,G){return qo(W,Ua(W.root,Ha(G)))}function ae(W,G="rules policy"){let H=Ha(W),J=Ki(H).dir;return qo(w(J,G),Ua(J,H))}function r(W){return or(W.scope.label,()=>{if(!ln(W))return null;let G=Jd(W.path,Ko.O_RDONLY|tu);return ru(G,()=>{let H=Fa(G);if(!H.isFile())throw new o(W.scope.label);let J=Xy(G,"utf-8"),oe=On(W.path);if(!oe.isFile()||oe.isSymbolicLink()||H.dev!==oe.dev||H.ino!==oe.ino)throw new o(W.scope.label);return ln(W),J})})}function g(W,G,H=384,J){let oe=`${W.path}.${Fe()}.tmp`;or(W.scope.label,()=>{oS(W),ln(W);let ie=Jd(oe,Ko.O_CREAT|Ko.O_EXCL|Ko.O_WRONLY|tu,H),fe=ru(ie,()=>{let Re=Fa(ie);if(!Re.isFile())throw new o(W.scope.label);Qy(ie,G,"utf-8"),Zy(ie);let Te=Fa(ie);if(!Te.isFile()||Te.dev!==Re.dev||Te.ino!==Re.ino)throw new o(W.scope.label);return Te});ln(W),sS(W,oe,fe.dev,fe.ino),Jy(oe,W.path),J?.(W.path),ln(W)},()=>aS(oe))}function nu(W,G){if(W.path===G.path)return!0;return or(W.scope.label,()=>{if(!ln(W)||!ln(G))return!1;let H=(J)=>kr(lo(Ki(J).dir),Ki(J).base);return H(W.path)===H(G.path)})}function he(W){let G=or(W.scope.label,()=>{if(!ln(W,"directory"))return null;let H=$a(W.path);return ln(W,"directory"),H});if(!G)return null;return or(W.scope.label,()=>{let H=G.map((J)=>{let oe=qo(W.scope,kr(W.relativePath,J)),ie=On(oe.path);if(ie.isSymbolicLink()||!ie.isFile()&&!ie.isDirectory())throw new o(W.scope.label);return Yi(ja(W.scope),lo(oe.path),W.scope.label),{name:J,kind:ie.isDirectory()?"directory":"file"}});return ln(W,"directory"),H})}function B(W){or(W.scope.label,()=>{if(!ln(W))return;Ba(W.path),ln(W)})}function wt(W){or(W.scope.label,()=>{if(!rS(W))return;iu(W),ln(W,"directory")})}function Ct(W){or(W.scope.label,()=>{if(!ln(W,"directory"))return;Qd(W.path),ln(W,"directory")})}function rS(W){return or(W.scope.label,()=>{if(!ln(W,"directory"))return!1;return ou(W),!0})}function or(W,G,H){try{return G()}catch(J){if(H?.(),J instanceof o)throw J;throw new o(W)}}function ru(W,G){try{return G()}finally{Yy(W)}}function ln(W,G="file"){let H=su(W.scope);if(!H)return!1;let J=W.relativePath.split(qi);for(let oe of J.keys()){let ie=kr(W.scope.root,...J.slice(0,oe+1)),fe=On(ie,{throwIfNoEntry:!1});if(!fe)return!1;if(fe.isSymbolicLink())throw new o(W.scope.label);if(oe<J.length-1&&!fe.isDirectory())throw new o(W.scope.label);if(oe===J.length-1&&(G==="file"?!fe.isFile():!fe.isDirectory()))throw new o(W.scope.label);Yi(H,lo(ie),W.scope.label)}return!0}function ou(W){for(let G of $a(W.path)){let H=qo(W.scope,kr(W.relativePath,G)),J=On(H.path);if(J.isSymbolicLink()||!J.isDirectory()&&!J.isFile())throw new o(W.scope.label);if(J.isDirectory())ou(H)}ln(W,"directory")}function iu(W){for(let G of $a(W.path)){let H=qo(W.scope,kr(W.relativePath,G)),J=On(H.path);if(J.isSymbolicLink())throw new o(W.scope.label);if(J.isDirectory()){iu(H);continue}if(!J.isFile())throw new o(W.scope.label);Ba(H.path)}Qd(W.path)}function oS(W){iS(W.scope);let G=ja(W.scope),H=W.relativePath.split(qi).slice(0,-1);for(let J of H.keys()){let oe=kr(W.scope.root,...H.slice(0,J+1));if(!On(oe,{throwIfNoEntry:!1}))Xd(oe,{mode:448});let ie=On(oe);if(!ie.isDirectory()||ie.isSymbolicLink())throw new o(W.scope.label);Yi(G,lo(oe),W.scope.label)}}function iS(W){if(On(W.root,{throwIfNoEntry:!1})){if(!za(W.root).isDirectory())throw new o(W.label);return}let G=[],H=W.root;while(!On(H,{throwIfNoEntry:!1})){G.unshift(H);let J=Ki(H).dir;if(J===H)throw new o(W.label);H=J}if(!za(H).isDirectory())throw new o(W.label);for(let J of G){Xd(J,{mode:448});let oe=On(J);if(!oe.isDirectory()||oe.isSymbolicLink())throw new o(W.label)}}function su(W){if(!On(W.root,{throwIfNoEntry:!1}))return null;if(!za(W.root).isDirectory())throw new o(W.label);return lo(W.root)}function ja(W){let G=su(W);if(!G)throw new o(W.label);return G}function sS(W,G,H,J){let oe=On(G);if(!oe.isFile()||oe.isSymbolicLink()||oe.dev!==H||oe.ino!==J)throw new o(W.scope.label);Yi(ja(W.scope),lo(G),W.scope.label)}function Yi(W,G,H){let J=Ua(W,G);if(J===".."||J.startsWith(`..${qi}`)||eu(J))throw new o(H)}function aS(W){try{Ba(W)}catch{}}import{dirname as Or,isAbsolute as mS,join as Mr,relative as fS,resolve as gr,sep as pS}from"node:path";var p=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ye="rulebook.json",be=".cc-safety-net/rules";var au=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,lS=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,lu=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,cS=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),dS="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Et=new RegExp(`^${cS}/(${p.source.slice(1,-1)})/${dS}$`);function uS(W){return`.cc-safety-net/rules/${W}/rulebook.json`}function cu(W){if(C(W))try{return M(W),null}catch(G){return G instanceof Error?G.message:String(G)}return p.test(W)?null:`Local rulebook sources must be bare names matching ${p}: ${W}`}function M(W){if(W.startsWith("github:"))throw Error(`Invalid rulebook source: ${W}`);let G=W.match(au);if(!G?.[1]||!G[2]||!G[3])throw Error(`Invalid GitHub rulebook source: ${W}`);let H=G[3].lastIndexOf("/");if(H<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${W}`);let J=G[3].slice(0,H),oe=G[3].slice(H+1);if(!J||!lu.test(J))throw Error(`GitHub rulebook refs must use valid path segments: ${W}`);if(!oe||!p.test(oe))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${W}`);return{owner:G[1],repo:G[2],ref:J,path:uS(oe),name:oe}}function X(W){return lS.test(W)}function ce(W){return lu.test(W)}function C(W){return au.test(W)}function kt(W){if(!p.test(W))throw Error(`Local rulebook sources must be bare names matching ${p}: ${W}`)}var du="rule.json",Zi="policy.json",uu=".cc-safety-net",gS="rules",hS="CC_SAFETY_NET_HOME",mu="`cc-safety-net rule update`";function yS(W){return gr(W,be)}function I(W){return Mr(yS(W),du)}function h(W){return Mr(gr(W),uu,Zi)}function Ae(W,G={}){return G.userConfigDir??(G.userConfigPath?Or(G.userConfigPath):Mr(SS(W),gS))}function SS(W){let G=W.env.get(hS);return G?gr(fn(G)):Mr(W.home,uu)}function z(W,G={}){return Mr(Ae(W,G),du)}function u(W,G={}){return Mr(Or(Ae(W,G)),Zi)}function O(W,G){let H=In();return Bt(h(G.cwd),W.paths,H)===Bt(gr(u(W,G)),W.paths,H)}function Q(W,G){let H=G.userConfigPath??z(W,G),J=G.projectConfigPath??I(G.cwd),oe=at(W,G),ie=ct(J,G.cwd);return{userConfigPath:H,projectConfigPath:J,userScope:oe,projectScope:ie,userConfigTarget:i(oe,H),projectConfigTarget:i(ie,J)}}function at(W,G){let H=G.userConfigPath?Or(Or(gr(G.userConfigPath))):Or(gr(G.userConfigDir??Ae(W,G)));return w(H,"user policy")}function ct(W,G){let H=gr(G),J=gr(W),oe=fS(H,J);if(oe!==".."&&!oe.startsWith(`..${pS}`)&&!mS(oe))return w(H,"project policy");return w(Or(Or(J)),"project policy")}function F(W,G){return Mr(W,G,ye)}var _n=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),E=/^[a-zA-Z][a-zA-Z0-9_-]*$/,D=256,tn=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),fu=new Set(["python","python3","python2","node","ruby","perl"]),Xi=/^python(?:[23](?:\.\d+)*)?$/,Mn=new Set(["awk","gawk","nawk","mawk"]),Ji=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 pu="Rulebook exceeds CC Safety Net's safe validation limits.",gu="Additional rulebook validation errors were omitted.",$n=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function hu(W){if(Va(W.allowed_commands,$n.maxAllowedCommands)||Va(W.rules,$n.maxRules)||Va(W.tests,$n.maxTests))return!1;let{maxAggregateStringCodeUnits:G,maxTotalBlockArgs:H}=$n,J=(oe,ie=!1)=>{if(typeof oe!=="string")return!0;if(oe.length>$n.maxStringCodeUnits||ie&&oe.length>$n.maxFixtureCommandCodeUnits||oe.length>G)return!1;return G-=oe.length,!0};if(!J(W.name)||!J(W.version)||!J(W.description)||!J(W.author)||!J(W.migrated_from))return!1;if(Array.isArray(W.allowed_commands)){for(let oe of W.allowed_commands)if(!J(oe))return!1}if(Array.isArray(W.rules))for(let oe of W.rules){if(!oe||typeof oe!=="object")continue;let ie=oe;if(!J(ie.name)||!J(ie.command)||!J(ie.subcommand)||!J(ie.reason)||!J(ie.intent))return!1;let fe=ie.match&&typeof ie.match==="object"?ie.match:{};for(let Re of[ie.block_args,fe.command_path,fe.any_args,fe.exclude_args]){if(!Array.isArray(Re))continue;if(Re.length>$n.maxBlockArgsPerRule||Re.length>H)return!1;H-=Re.length;for(let Te of Re)if(!J(Te))return!1}}if(Array.isArray(W.tests))for(let oe of W.tests){if(!oe||typeof oe!=="object")continue;let ie=oe;if(!J(ie.command,!0)||!J(ie.expect)||!J(ie.rule))return!1}return!0}function Va(W,G){return Array.isArray(W)&&W.length>G}var Ka=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var xe=64,ve="Rule config exceeds CC Safety Net's safe source limit.";function zt(W){return Ft(W).toLowerCase()}function Ft(W){return W.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??W}function Cn(W,G){let H=new Set,J=!1;for(let oe of W){if(oe==="--"){J=!0;continue}if(J)continue;if(oe.startsWith("-")&&!oe.startsWith("--")&&oe.length>1)for(let ie=1;ie<oe.length;ie++){let fe=oe[ie];if(!fe||!/[a-zA-Z]/.test(fe))break;let Re=`-${fe}`;if(H.add(Re),G?.shortOptsWithValue?.has(Re))break}}return H}var bS={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},qa=new Set(["--init-file","--rcfile"]);function Ya(W,G,H,J){let oe=!1,ie=0,fe=!1,Re=!1;for(let Te=1;Te<G.length;Te++){let ke=G[Te];if(ke===void 0)break;if(W==="ksh"&&ke==="o"&&Te+1<G.length){if(J==="argv"){let Le=G.slice(Te+1);if(G[0]==="-"&&(Le==="c"||Le[0]==="-"&&Le.endsWith("c")))fe=!0}break}if(W==="ksh"&&ke==="o"&&Te+1===G.length&&(H?.startsWith("-")||H?.startsWith("+")))break;if(W==="zsh"&&ke==="o"&&Te+1<G.length)break;if(J==="startup"&&ke==="i")oe=G[0]==="-";if(J==="argv"&&G[0]==="-"&&ke==="c")fe=!0;if(J==="argv"&&ke==="s")Re=G[0]==="-";if(!bS[W]?.includes(ke))continue;if(Te+1===G.length)ie++;break}return{interactive:oe,followingValues:ie,commandSelected:fe,stdinMode:Re}}function Dn(W){let G=Ft(W[0]??"").toLowerCase(),H=!1,J=!1;for(let oe=1;oe<W.length;oe++){let ie=W[oe];if(ie===void 0)break;if(ie==="--"){let Re=H&&W[oe+1]!==void 0?oe+1:null;return{command:Re===null?null:W[Re]??null,commandIndex:Re,scriptIndex:!H&&!J&&W[oe+1]!==void 0?oe+1:null,readsStdinAsCommands:!H&&(J||W[oe+1]===void 0)}}if(ie==="-"||ie[0]!=="-"&&ie[0]!=="+")return{command:H?ie:null,commandIndex:H?oe:null,scriptIndex:!H&&!J&&ie!=="-"?oe:null,readsStdinAsCommands:!H&&(J||ie==="-")};if(ie.startsWith("--")){let Re=ie.split("=",1)[0]??ie;if(G==="bash"&&qa.has(Re)&&!ie.includes("="))oe++;continue}let fe=Ya(G,ie,W[oe+1],"argv");if(fe.commandSelected)H=!0;if(fe.stdinMode)J=!0;oe+=fe.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!H}}function Yo(W,G){if(G.escaped)return G.escaped=!1,!0;if(W==="\\"&&!G.inSingle)return G.escaped=!0,!0;if(W==="'"&&!G.inDouble)return G.inSingle=!G.inSingle,!0;if(W==='"'&&!G.inSingle)return G.inDouble=!G.inDouble,!0;return!1}function Qi(W){let G={inSingle:!1,inDouble:!1,escaped:!1};for(let H of CS(W))Yo(H,G);return G.inSingle||G.inDouble}function CS(W){let G="",H={inSingle:!1,inDouble:!1,escaped:!1},J=!1,oe=!0;for(let ie=0;ie<W.length;ie++){let fe=W[ie];if(!fe)break;if(J){if(fe===`
5
+ `||fe==="\r")G+=fe,J=!1,H.escaped=!1;continue}if(fe==="#"&&!H.inSingle&&!H.inDouble&&oe){J=!0;continue}if(G+=fe,!H.inSingle&&!H.inDouble&&!H.escaped)oe=/[\s;&|()<>]/.test(fe);Yo(fe,H)}return G}var Za=new Set(["rm","find","xargs","parallel"]),vS=new Set(["git","busybox",...Za,...tn,...fu,...Mn]),ES=new Set(["python","node","ruby","perl"]);function $e(W){let G=zt(W);return vS.has(G)||Bn(G)}function Bn(W){return ES.has(RS(W))}function RS(W){let G=Ft(W).toLowerCase();return Xi.test(G)?"python":G}var le={version:1,rules:[],overrides:{},transparent_wrappers:[]};function d(W){try{let G=r(_S(W));if(G===null)return{config:null,errors:[]};if(!G.trim())return{config:null,errors:["Config file is empty"]};let H=JSON.parse(G),J=lt(H);if(J.errors.length>0)return{config:null,errors:J.errors};return{config:{version:1,rules:H.rules??[],overrides:H.overrides??{},transparent_wrappers:H.transparent_wrappers??[],...H.command_tools?{command_tools:H.command_tools}:{}},errors:[]}}catch(G){if(G instanceof o)return{config:null,errors:[G.message]};let H=G instanceof Error?G.message:String(G);return{config:null,errors:[G instanceof SyntaxError?"Invalid JSON":H]}}}function _S(W){return typeof W==="string"?ae(W):W}var e=(W,G)=>({path:W,message:G,kind:"typed"}),an=(W,G)=>({path:W,message:G,kind:"custom"});function Ue(W){let G=new Set;return W.flatMap((H,J)=>{let oe=Dr(H)?H.name:void 0;if(typeof oe!=="string")return[];if(G.has(oe.toLowerCase()))return[an(["rules",J,"name"],`duplicate rule name "${oe}"`)];return G.add(oe.toLowerCase()),[]})}var Oe=`must be one of ${Ka.join(", ")}`,xS=/^[^/]+\/[^/]+$/,wS=["version","rules","overrides","transparent_wrappers","command_tools"],je=/^[^\s\p{Cc}]{1,256}$/u,Se="non-empty, at most 256 characters, no whitespace or control characters";function lt(W){let G=AS(W);return{errors:ue(ut(G,wS,(H)=>H.kind==="custom"),": "," "),sources:LS(W,G)}}function AS(W){if(!Dr(W))return[e([],"Config must be an object")];let G=Array.isArray(W.rules)&&W.rules.length>xe;return[...W.version===1?[]:[e(["version"],"must be 1")],...PS(W.rules,G),...kS(W.overrides),...MS(W.transparent_wrappers),...G?[]:IS(W.rules),...Dr(W.overrides)?Object.keys(W.overrides).filter((H)=>!xS.test(H)).map((H)=>an(["overrides",H],"must use <rulebook-name>/<rule-name>")):[],...DS(W.transparent_wrappers),...NS(W.command_tools)]}function PS(W,G){if(W===void 0)return[];if(!Array.isArray(W))return[e(["rules"],"must be an array of rulebook source strings"),...yu(W,xe)?[e(["rules"],ve)]:[]];if(G)return[{path:["rules"],message:ve,kind:"limit"}];return W.flatMap((H,J)=>{if(typeof H!=="string")return[e(["rules",J],"must be a rulebook source string"),...TS(H,1)?[e(["rules",J],"must be a non-empty rulebook source string")]:[]];return H===""?[e(["rules",J],"must be a non-empty rulebook source string")]:[]})}function yu(W,G){let H=Su(W);return H!==void 0&&!(H<=G)}function TS(W,G){let H=Su(W);return H!==void 0&&!(H>=G)}function Su(W){if(W===null||W===void 0)return;let G=W.length;return G===void 0?void 0:Number(G)}function IS(W){if(!Array.isArray(W))return[];let G=new Set;return W.flatMap((H,J)=>{if(typeof H!=="string"||H==="")return[];if(H.trim()==="")return[an(["rules",J],"must be a non-empty rulebook source string")];let oe=cu(H);if(oe)return[an(["rules",J],oe)];if(G.has(H))return[an(["rules",J],`duplicate rulebook source "${H}"`)];return G.add(H),[]})}function kS(W){if(W===void 0)return[];if(!Dr(W))return[e(["overrides"],"must be an object if provided")];return Object.keys(W).flatMap((G)=>{let H=W[G];if(H==="off")return[];if(!Dr(H))return[e(["overrides",G],'must be "off" or an object')];return[...OS(H.reason,["overrides",G,"reason"]),...H.intent===void 0||De(H.intent)?[]:[e(["overrides",G,"intent"],Oe)]]})}function OS(W,G){if(typeof W!=="string")return[e(G,"required non-empty string"),...yu(W,D)?[e(G,`must be at most ${D} characters`)]:[]];if(W==="")return[e(G,"required non-empty string")];return W.length>D?[e(G,`must be at most ${D} characters`)]:[]}function MS(W){if(W===void 0)return[];if(!Array.isArray(W))return[e(["transparent_wrappers"],"must be an array of command strings")];return W.flatMap((G,H)=>{if(typeof G!=="string")return[e(["transparent_wrappers",H],"must be a command string")];return E.test(G)?[]:[e(["transparent_wrappers",H],"must match command pattern")]})}function DS(W){if(!Array.isArray(W))return[];let G=new Set;return W.flatMap((H,J)=>{if(typeof H!=="string"||!E.test(H))return[];if(G.has(H))return[an(["transparent_wrappers",J],`duplicate command "${H}"`)];if($e(H))return[an(["transparent_wrappers",J],`reserved command "${H}" cannot be a wrapper`)];return G.add(H),[]})}function NS(W){if(W===void 0)return[];if(!Array.isArray(W))return[e(["command_tools"],"must be an array of tool names or {name, cwd} objects")];let G=new Set,H=(J,oe)=>{if(G.has(J))return[an(["command_tools",oe],`duplicate tool "${J}"`)];return G.add(J),[]};return W.flatMap((J,oe)=>{if(typeof J==="string")return Xa(J)?H(J,oe):[e(["command_tools",oe],`must be a tool name: ${Se}`)];if(!Dr(J))return[e(["command_tools",oe],"must be a tool name or a {name, cwd} object")];let ie=[...Xa(J.name)?[]:[e(["command_tools",oe,"name"],`must be a tool name: ${Se}`)],...J.cwd===void 0||Xa(J.cwd)?[]:[e(["command_tools",oe,"cwd"],`must be an argument name: ${Se}`)]];return ie.length>0?ie:H(J.name,oe)})}function Xa(W){return typeof W==="string"&&je.test(W)}function LS(W,G){let H=Dr(W)?W.rules:void 0;if(!Array.isArray(H))return new Set;if(G.some((oe)=>oe.path.length===1&&oe.path[0]==="rules"))return new Set;let J=new Set(G.filter((oe)=>oe.path[0]==="rules"&&typeof oe.path[1]==="number").map((oe)=>oe.path[1]));return new Set(H.filter((oe,ie)=>typeof oe==="string"&&!J.has(ie)))}function ut(W,G,H){let J=W.map((fe)=>fe.path[1]),oe=[...new Set(J.filter((fe)=>typeof fe==="string"))],ie=(fe,Re)=>[fe.path.length===0?-1:G.indexOf(String(fe.path[0])),typeof Re==="number"?Re:oe.indexOf(String(Re)),H(fe)?0:1];return W.map((fe,Re)=>({issue:fe,rank:ie(fe,J[Re])})).sort((fe,Re)=>fe.rank[0]-Re.rank[0]||fe.rank[1]-Re.rank[1]||fe.rank[2]-Re.rank[2]).map((fe)=>fe.issue)}function ue(W,G,H){return[...new Set(W.map((J)=>{let oe=Ja(J.path);if(J.kind==="unknownKeys")return`${oe?`${oe}.`:""}unknown field "${J.message}"`;if(J.kind==="key"||J.kind==="limit"||J.path.length===0)return J.message;return`${oe}${J.path.length===1?H:G}${J.message}`}))]}function Ja(W){return W.map((G,H)=>{if(typeof G==="number")return`[${G}]`;return H===0?String(G):`.${String(G)}`}).join("")}function De(W){return Ka.includes(W)}function Dr(W){return!!W&&typeof W==="object"&&!Array.isArray(W)}function de(W){let G=FS(W);if(G.errors.length>0)throw Error(G.errors.join("; "));return W}var WS=`required non-empty string up to ${D} characters`,bu="must be a non-empty array of unique non-empty strings",GS="required non-empty array of non-empty strings";function FS(W){if(!hr(W))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!hu(W))return{errors:[pu],ruleNames:new Set};let G=[...W.rulebook_version===1||W.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ue(zS(W,W.rulebook_version===2),": ",": ")];return{errors:G.length>$n.maxValidationErrors?[...G.slice(0,$n.maxValidationErrors),gu]:G,ruleNames:new Set(Ge(W).map((H)=>H.toLowerCase()))}}function Ge(W){let G=hr(W)?W.rules:void 0;return(Array.isArray(G)?G:[]).flatMap((H)=>{let J=hr(H)?H.name:void 0;return typeof J==="string"?[J]:[]})}function zS(W,G){return[...typeof W.name==="string"&&p.test(W.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof W.version==="string"&&W.version!==""?[]:[e(["version"],"required non-empty string")],...$S(W.allowed_commands),...BS(W.rules,G),...VS(W.tests),...KS(W),...qS(W)]}function $S(W){if(!Array.isArray(W))return[e(["allowed_commands"],"required array")];let G=new Set;return[...W.flatMap((H,J)=>typeof H==="string"&&E.test(H)?[]:[e(["allowed_commands",J],"must match command pattern")]),...W.flatMap((H,J)=>{if(typeof H!=="string"||!E.test(H))return[];if(G.has(H))return[an(["allowed_commands",J],`duplicate command "${H}"`)];return G.add(H),[]})]}function BS(W,G){if(!Array.isArray(W))return[e(["rules"],"required array")];return[...W.flatMap((H,J)=>{if(!hr(H))return[e(["rules",J],"must be an object")];return G?HS(H,["rules",J]):US(H,["rules",J])}),...Ue(W)]}function US(W,G){return[...Cu(W.name,G),...vu(W.command,G),...W.subcommand===void 0||typeof W.subcommand==="string"&&E.test(W.subcommand)?[]:[e([...G,"subcommand"],"must match command pattern")],...es(W.block_args,[...G,"block_args"],"required non-empty array",!1),...Eu(W.reason,G),...Ru(W.intent,G)]}function HS(W,G){return[...Cu(W.name,G),...vu(W.command,G),...Eu(W.reason,G),...Ru(W.intent,G),...jS(W.match,[...G,"match"]),...W.subcommand===void 0?[]:[e([...G,"subcommand"],"not supported in rulebook_version 2")],...W.block_args===void 0?[]:[e([...G,"block_args"],"not supported in rulebook_version 2")]]}function Cu(W,G){if(typeof W!=="string")return[e([...G,"name"],"required string")];return p.test(W)?[]:[e([...G,"name"],"must match rule name pattern")]}function vu(W,G){return typeof W==="string"&&E.test(W)?[]:[e([...G,"command"],"required string matching command pattern")]}function Eu(W,G){return typeof W==="string"&&W!==""&&W.length<=D?[]:[e([...G,"reason"],WS)]}function Ru(W,G){return W===void 0||De(W)?[]:[e([...G,"intent"],Oe)]}function jS(W,G){if(!hr(W))return[e(G,"required object")];return[...es(W.command_path,[...G,"command_path"],GS,!1),...W.any_args===void 0?[]:es(W.any_args,[...G,"any_args"],bu,!0),...W.exclude_args===void 0?[]:es(W.exclude_args,[...G,"exclude_args"],bu,!0)]}function es(W,G,H,J){if(!Array.isArray(W))return[e(G,H)];let oe=W.flatMap((ie,fe)=>{if(typeof ie!=="string")return[e([...G,fe],"must be a non-empty string")];return ie===""?[an([...G,fe],"must be a non-empty string")]:[]});if(W.some((ie)=>typeof ie!=="string"))return oe;return[...oe,...W.length===0?[an(G,H)]:[],...J&&new Set(W).size!==W.length?[an(G,"must not contain duplicate values")]:[]]}function VS(W){if(W===void 0)return[];if(!Array.isArray(W))return[e(["tests"],"must be an array if provided")];return W.flatMap((G,H)=>{if(!hr(G))return[e(["tests",H],"must be an object")];return[...typeof G.command==="string"&&G.command.trim()!==""?[]:[e(["tests",H,"command"],"required non-empty string")],...G.expect==="blocked"||G.expect==="allowed"?[]:[e(["tests",H,"expect"],'must be "blocked" or "allowed"')],...G.rule===void 0||typeof G.rule==="string"?[]:[e(["tests",H,"rule"],"must be a string if provided")],...G.expect==="blocked"&&typeof G.rule!=="string"?[an(["tests",H,"rule"],"required string for blocked fixtures")]:[]]})}function KS(W){if(!Array.isArray(W.tests))return[];let G=new Set(Ge(W));return[...new Set(W.tests.flatMap((H)=>hr(H)&&H.expect==="blocked"&&typeof H.rule==="string"?[H.rule]:[]))].filter((H)=>!G.has(H)).map((H)=>an(["tests"],`blocked fixture references unknown rule "${H}"`))}function qS(W){if(!Array.isArray(W.allowed_commands)||!Array.isArray(W.rules))return[];let G=new Set(W.allowed_commands.filter((H)=>typeof H==="string"));return W.rules.flatMap((H,J)=>{let oe=hr(H)?H.command:void 0;if(typeof oe!=="string"||G.has(oe))return[];return[an(["rules",J,"command"],`"${oe}" must be listed in allowed_commands`)]})}function hr(W){return!!W&&typeof W==="object"&&!Array.isArray(W)}function ee(W,G){let H=Q(W,G),J;try{J=nu(H.userConfigTarget,H.projectConfigTarget)}catch(Ze){if(Ze instanceof o)return ob(H,Ze.message);throw Ze}let oe=d(H.userConfigTarget),ie=J?{config:null,errors:[]}:d(H.projectConfigTarget),fe=wu(H.userConfigPath,oe.errors),Re=wu(H.projectConfigPath,ie.errors),Te=new Set,ke=oe.config?Qa(oe.config,Nr(H.userConfigPath),"user",H.userScope,Te):Au(),Le=ie.config?Qa(ie.config,Nr(H.projectConfigPath),"project",H.projectScope,Te):Au(),Xe=oe.config?.overrides??{},Ye=ie.config?.overrides??{};return{rules:[...xu(ke.rules,Xe),...xu(Le.rules,Ye)],transparent_wrappers:tb(oe.config,ie.config),command_tools:nb(oe.config,ie.config),rulebooks:[...ke.rulebooks,...Le.rulebooks],errors:[...fe,...Re,...ke.errors,...Le.errors],warnings:[...ke.warnings,...Le.warnings,...ke.canValidateOverrides?el(Xe,ke.knownRuleIds,H.userConfigPath):[],...ke.canValidateOverrides?rb(Ye,ke.knownRuleIds,H.projectConfigPath):[],...Le.canValidateOverrides?el(Ye,Le.knownRuleIds,H.projectConfigPath):[]],userConfig:oe.config??void 0,projectConfig:ie.config??void 0,...H}}function V(W,G){let H=YS(W,G);if(!H)return[];return[...H.scope.errors,...H.scope.warnings,...ZS(H.config,H.scope,W)]}function YS(W,G){let H=G??w(Nr(Nr(W)),"rules policy"),J=d(i(H,W)).config;if(!J)return null;return{config:J,scope:Qa(J,Nr(W),"project",H)}}function ZS(W,G,H){return G.canValidateOverrides?el(W.overrides??{},G.knownRuleIds,H):[]}function Qa(W,G,H,J=w(Nr(Nr(G)),H==="user"?"user policy":"project policy"),oe=new Set){let ie=[],fe=[],Re=W.rules.flatMap((ke)=>{let Le=JS(ke,G,J);if(Le.errors.length>0||!Le.rulebook)return ie.push(...Le.errors),[];let Xe=Le.rulebook;if(oe.has(Xe.name))return fe.push(`duplicate active rulebook name "${Xe.name}" for ${ke}; 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 oe.add(Xe.name),[{rules:XS(Xe),rulebook:{source:H,spec:ke,name:Xe.name,version:Xe.version,rules:Xe.rules.map((Ye)=>`${Xe.name}/${Ye.name}`)}}]}),Te=Re.flatMap((ke)=>ke.rules);return{rules:Te,rulebooks:Re.map((ke)=>ke.rulebook),knownRuleIds:new Set(Te.map((ke)=>ke.name)),errors:ie,warnings:fe,canValidateOverrides:ie.length===0}}function XS(W){if(W.rulebook_version===2)return W.rules.map((G)=>({name:`${W.name}/${G.name}`,command:G.command,block_args:[],match:G.match,reason:G.reason,intent:G.intent}));return W.rules.map((G)=>({...G,name:`${W.name}/${G.name}`,match:void 0}))}function JS(W,G,H){let J=He(W),oe=F(G,J),ie=eb(oe,H);if("error"in ie)return{rulebook:null,errors:[ie.error]};if(ie.content===null)return{rulebook:null,errors:[`missing rulebook file ${oe} for ${W}; ${QS(W)}`]};let fe=we(ie.content);if("problem"in fe)return{rulebook:null,errors:[`invalid rulebook ${oe}: ${fe.problem}; fix that file`]};if(fe.rulebook.name!==J)return{rulebook:null,errors:[`rulebook name "${fe.rulebook.name}" in ${oe} must match source "${W}"; fix that file`]};return{rulebook:fe.rulebook,errors:[]}}function He(W){return C(W)?M(W).name:W}function QS(W){return C(W)?`run ${mu} to vendor ${W}`:"create that file or remove that source from the rules config"}function eb(W,G){try{return{content:r(i(G,W))}}catch(H){if(H instanceof o)return{error:H.message};throw H}}function we(W){let G;try{G=JSON.parse(W)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:de(G)}}catch(H){return{problem:H instanceof Error?H.message:"invalid rulebook"}}}function tb(W,G){return[...new Set([...W?.transparent_wrappers??[],...G?.transparent_wrappers??[]])]}function nb(W,G){let H=(W?.command_tools??[]).map(_u),J=(G?.command_tools??[]).map(_u);return[...H,...J.filter((oe)=>!H.some((ie)=>ie.name===oe.name))]}function _u(W){if(typeof W==="string")return{name:W};return W.cwd===void 0?{name:W.name}:{name:W.name,cwd:W.cwd}}function xu(W,G){return W.flatMap((H)=>{let J=G[H.name];if(J==="off")return[];if(J&&typeof J==="object")return[{...H,intent:J.intent??H.intent,reason:J.reason}];return[H]})}function el(W,G,H){return Object.keys(W).filter((J)=>!G.has(J)).map((J)=>`unknown override key "${J}" in ${H}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function rb(W,G,H){return Object.keys(W).filter((J)=>G.has(J)).map((J)=>`project override cannot target user-scoped rule "${J}" in ${H}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function wu(W,G){return G.map((H)=>H.startsWith("Unable to access ")?H:`${W}: ${H}`)}function ob(W,G){return{rules:[],transparent_wrappers:[],command_tools:[],rulebooks:[],errors:[G],warnings:[],userConfigPath:W.userConfigPath,projectConfigPath:W.projectConfigPath}}function Au(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as gb,readFileSync as hb}from"node:fs";var Pu=[{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:"powershell.nested-recursive-delete-unread",category:"PowerShell",label:"Nested PowerShell recursive delete not read",description:"Blocks a recursive delete handed to powershell or pwsh in any form other than literal -Command script words.",example:"pwsh -WorkingDirectory C:\\ -c 'Remove-Item -Recurse -Force *'",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-root-or-home",category:"Command Prompt",label:"cmd recursive delete root or home",description:"Blocks cmd rmdir /s or del /s of root or home paths.",example:"cmd /c rmdir /s /q C:\\",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-escaped-quote",category:"Command Prompt",label:"cmd recursive delete with escaped quotes",description:"Blocks cmd rmdir /s or del /s whose quoting can reach cmd as \\\" and split the target down to the drive root.",example:'cmd /c "rmdir /s /q \\"build output\\""',intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-git-metadata",category:"Command Prompt",label:"cmd recursive delete Git metadata",description:"Blocks cmd rmdir /s or del /s of protected Git metadata and hooks.",example:"cmd /c rmdir /s /q .git",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-dynamic-target",category:"Command Prompt",label:"cmd recursive delete dynamic target",description:"Blocks cmd rmdir /s or del /s with wildcard or variable targets in strict mode.",example:"cmd /c del /s /q *.log",intent:"scope_down",activationCapability:"fail_closed"},{id:"cmd.recursive-delete-home-cwd",category:"Command Prompt",label:"cmd recursive delete from home cwd",description:"Blocks cmd rmdir /s or del /s while working in home.",example:"Set-Location $HOME; cmd /c rmdir /s /q build",intent:"scope_down"},{id:"cmd.recursive-delete-cwd-self",category:"Command Prompt",label:"cmd recursive delete current directory",description:"Blocks cmd rmdir /s or del /s of the current directory.",example:"cmd /c rmdir /s /q .",intent:"scope_down"},{id:"cmd.recursive-delete-outside-cwd",category:"Command Prompt",label:"cmd recursive delete outside cwd",description:"Blocks cmd rmdir /s or del /s outside the original cwd.",example:"cmd /c rmdir /s /q ..\\outside",intent:"scope_down"},{id:"cmd.recursive-delete-paranoid",category:"Command Prompt",label:"cmd recursive delete paranoid mode",description:"Blocks non-temp cmd rmdir /s or del /s when paranoid rm is enabled.",example:"cmd /c rmdir /s /q build",intent:"scope_down",activationCapability:"paranoid_rm"},{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 other than /dev/null, /dev/zero, or /dev/full.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"Filesystem format on a device",description:"Blocks mkfs, mke2fs, and newfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"disk.erase",category:"Filesystem",label:"Disk erase or repartition",description:"Blocks diskutil erase and partition verbs, wipefs -a/-o, sgdisk writes, and parted label or partition edits on a /dev device.",example:"diskutil eraseDisk APFS Untitled disk4",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:"redirect.block-device",category:"Filesystem",label:"Redirect onto a disk device",description:"Blocks output redirects whose literal target is a disk device path under /dev.",example:"cat disk.img > /dev/sda",intent:"manual_only"},{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"}],tl=new Set(Pu.map((W)=>W.id)),q=Pu,ib=new Map(q.map((W)=>[W.id,W.intent]));function Pt(W,G){return{id:W,reason:G,intent:ib.get(W)??"manual_only"}}var nl=[{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"}],ts={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},sb=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],ab=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],rl=[{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"]},...ab.flatMap((W)=>sb.map((G)=>({id:["secret.home",W.idSlug,G.slice(1)].join("."),category:"Home path",label:[W.label,G].join(""),description:["Blocks home ",W.label,G," credential backup files."].join(""),suffixParts:[...W.directoryParts,[W.basename,G].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 ns=[{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"]},{id:"secret.cli.droid",category:"Coding CLI credential",label:"Factory Droid credentials",paths:["~/.factory/auth.encrypted","~/.factory/auth.v2.file","~/.factory/auth.v2.key","~/.factory/auth.v2.loginkeychain"]},{id:"secret.cli.droid.config",category:"Coding CLI config",label:"Factory Droid config",paths:["~/.factory/settings.json","~/.factory/hooks.json","~/.factory/mcp.json","<project>/.factory/mcp.json"]},{id:"secret.cli.devin",category:"Coding CLI credential",label:"Devin CLI credentials",paths:["~/.local/share/devin/credentials.toml","~/.local/share/devin/mcp/oauth"]},{id:"secret.cli.devin.config",category:"Coding CLI config",label:"Devin CLI config",paths:["~/.config/devin/config.json"]}],Tu=[{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"}],lb=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],ol=Tu.map((W)=>({id:`secret.variant.${W.slug}.separator`,category:"Variant",label:`${W.label}-* / ${W.label}_*`,description:`Blocks ${W.label} variants with dash or underscore suffixes.`,prefix:W.prefix})),il=Tu.flatMap((W)=>lb.map((G)=>({id:`secret.variant.${W.slug}.${G.slice(1)}`,category:"Variant",label:`${W.label}${G}`,description:`Blocks ${W.label}${G} private credential variants.`,prefix:W.prefix,suffix:G}))),Zo={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)$/},sl=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((W)=>({id:`secret.ext.${W}`,category:"Extension",label:`.${W}`,description:`Blocks files with the .${W} extension.`,extension:W})),al=[{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?$/}],dt=[...nl,ts,...rl,...ol,...il,Zo,...sl,...al,...ns].map((W)=>({id:W.id,category:W.category,label:W.label,...W.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in W?{paths:W.paths}:{description:W.description}})),rs=new Set(ns.flatMap((W)=>W.category==="Coding CLI config"?[W.id]:[])),ll=new Set(dt.map((W)=>W.id));import{isAbsolute as cl,join as cb,normalize as db,sep as os}from"node:path";var is=process.platform==="win32",Iu=/[*?]/;function dl(W){let G=W.trim(),H=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(is?G.replaceAll("\\","/"):G);if(!H)return null;let J=H[1]??"",oe=H[2]??"";if(Iu.test(J)||oe==="."||oe==="..")return null;return{root:J||"/",name:oe}}function Xo(W,G){if(W==="~")return G;if(W.startsWith("~/"))return`${G}${W.slice(1)}`;return W}function ul(W,G){if(typeof W!=="string"||W.trim()==="")return"must be a non-empty path string";let H=Xo(W.trim(),G);if(!cl(H))return"must be an absolute path or start with ~/";return Jo(H,G)}function ml(W,G){let H=ku(W,G);if(H===null)return"must be a non-empty path string";if(!cl(H))return null;if(Jo(H,G)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var ub="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",mb="cannot cover the guard's own configuration";function ku(W,G){if(typeof W!=="string"||W.trim()==="")return null;let H=W.trim(),J=is?H.replaceAll("\\","/"):H;return Xo(J.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),G)}function fl(W,G){let H=ku(W,G);if(H===null)return"must be a non-empty path string";let J=dl(H)?.root??H;if(Iu.test(J))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!cl(J))return null;if(Jo(J,G)!==null)return ub;return fb(J,G)?mb:null}function fb(W,G){let H=ss(W),J=ss(cb(G,".cc-safety-net"));return H===J||H.startsWith(`${J}${os}`)}function Jo(W,G){let H=ss(W),J=ss(G);if(H===J)return"cannot be the home directory";let oe=H.endsWith(os)?H:`${H}${os}`;if(J.startsWith(oe))return"cannot contain the home directory";return null}function ss(W){let G=db(W);if(is)G=G.replace(/\//g,"\\").toLowerCase();if(G.length>(is?3:1)&&G.endsWith(os))G=G.slice(0,-1);return G}var Ou=30,as=1,ls=365;function Mu(W){if(typeof W!=="number"||!Number.isInteger(W))return 30;if(W<1)return 1;return W>365?365:W}var Du=new Set(q.filter((W)=>W.catastrophic).map((W)=>W.id));function Lt(W,G){if(!W)return null;if(Du.has(W.id))return W;if(G?.destructiveCommandProtectionEnabled===!1)return null;let H=G?.effectiveDestructiveCommandRules[W.id];return H&&!H.enabled?null:W}function on(W,G,H){if(Du.has(G))return!0;if(W?.destructiveCommandProtectionEnabled===!1)return!1;return W?.effectiveDestructiveCommandRules[G]?.enabled??H}function K(W,G){return Object.freeze(Object.fromEntries(q.map((H)=>{let J=H.activationCapability?G[H.activationCapability]:void 0,oe=J?.enabled??!0,ie=W.destructiveCommandRuleOverrides[H.id],fe=H.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...ie?{override:ie}:{}}:W.destructiveCommandProtectionEnabled?ie?{enabled:ie==="on",inheritedEnabled:oe,changesInherited:ie==="on"!==oe,source:"rule_override",...H.activationCapability?{activationCapability:H.activationCapability}:{},override:ie}:{enabled:oe,inheritedEnabled:oe,changesInherited:!1,source:J?.source??"built_in_default",...H.activationCapability?{activationCapability:H.activationCapability}:{}}:{enabled:!1,inheritedEnabled:oe,changesInherited:!1,source:"master_disabled",...H.activationCapability?{activationCapability:H.activationCapability}:{},...ie?{override:ie}:{}};return[H.id,Object.freeze(fe)]})))}function Nu(W,G){return Object.freeze({...W,effectiveDestructiveCommandRules:K(W,G)})}var Lu={standard:0,strict:1,paranoid:2};function te(W,G,H=!1,J=W.safety.level){let oe=pb(W,G,J),ie=new Set(H?oe.map((Le)=>Le.field):[]),fe=(Le,Xe)=>ie.has(Le)?void 0:Xe,Re=(Le,Xe)=>Object.fromEntries(Object.entries(Xe??{}).filter(([Ye])=>!ie.has(`${Le}.${Ye}`))),Te=(Le,Xe)=>Xe?.filter((Ye)=>!ie.has(`${Le}.${Ye}`));return{policy:{version:1,safety:{level:fe("safety.level",G.safety?.level)??W.safety.level,overrides:{...W.safety.overrides,...Re("safety.overrides",G.safety?.overrides)}},workflow:{worktree_mode:fe("workflow.worktree_mode",G.workflow?.worktree_mode)??W.workflow.worktree_mode},destructive_command_protection:{enabled:fe("destructive_command_protection.enabled",G.destructive_command_protection?.enabled)??W.destructive_command_protection.enabled,overrides:{...W.destructive_command_protection.overrides,...Re("destructive_command_protection.overrides",G.destructive_command_protection?.overrides)},allow_paths:pl(W.destructive_command_protection.allow_paths,Te("destructive_command_protection.allow_paths",G.destructive_command_protection?.allow_paths))},secret_protection:{enabled:fe("secret_protection.enabled",G.secret_protection?.enabled)??W.secret_protection.enabled,overrides:{...W.secret_protection.overrides,...Re("secret_protection.overrides",G.secret_protection?.overrides)},deny_paths:pl(W.secret_protection.deny_paths,G.secret_protection?.deny_paths),allow_paths:pl(W.secret_protection.allow_paths,Te("secret_protection.allow_paths",G.secret_protection?.allow_paths))},audit:W.audit},weakenings:oe.map((Le)=>Le.message)}}function pl(W,G){return[...new Set([...W,...G??[]])]}function pb(W,G,H){let J=G.safety?.level,oe=ji[H];return[...J&&Lu[J]<Lu[W.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${W.safety.level} -> ${J}`}]:[],...ao.flatMap((ie)=>G.safety?.overrides?.[ie]===!1&&(W.safety.overrides[ie]??oe[ie])?[{field:`safety.overrides.${ie}`,message:`project policy disables ${ie}`}]:[]),...G.workflow?.worktree_mode===!0&&!W.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...G.destructive_command_protection?.enabled===!1&&W.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...G.secret_protection?.enabled===!1&&W.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...Wu("destructive_command_protection.overrides",G.destructive_command_protection?.overrides,(ie)=>W.destructive_command_protection.enabled&&W.destructive_command_protection.overrides[ie]!=="off"),...Wu("secret_protection.overrides",G.secret_protection?.overrides,(ie)=>W.secret_protection.enabled&&(W.secret_protection.overrides[ie]==="on"?!0:W.secret_protection.overrides[ie]!=="off"&&!rs.has(ie))),...W.destructive_command_protection.enabled?Gu(W.destructive_command_protection.allow_paths,G.destructive_command_protection?.allow_paths).map((ie)=>({field:`destructive_command_protection.allow_paths.${ie}`,message:`project policy adds destructive allow path: ${ie}`})):[],...W.secret_protection.enabled?Gu(W.secret_protection.allow_paths,G.secret_protection?.allow_paths).map((ie)=>({field:`secret_protection.allow_paths.${ie}`,message:`project policy adds secret allow path: ${ie}`})):[]]}function Wu(W,G,H){return Object.entries(G??{}).flatMap(([J,oe])=>oe==="off"&&H(J)?[{field:`${W}.${J}`,message:`project policy disables rule ${J}`}]:[])}function Gu(W,G){return(G??[]).filter((H)=>!W.includes(H))}var hl=new Set(["standard","strict","paranoid"]),ne={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:Ou}};function $u(W,G){let H=Eb(u(W,G),W.home),J=O(W,G)?{exists:!1,policy:A(),errors:[]}:Be(h(G.cwd),W.home),oe=pe(J.parsed,W.home),ie=S(n.projectTightenOnly,W.env),fe=H.gui??ne,Re=Object.keys(oe.policy).length>0?te(fe,oe.policy,ie,Zd(fe.safety.level,W.env)):void 0,Te=[...H.errors,...J.errors,...oe.diagnostics],ke=(H.fallback==="defaults"&&Re?"salvaged":H.fallback)??(H.gui?void 0:J.fallback)??(Te.length>0?"salvaged":void 0),Le=oe.policy.safety?.level&&Re?.policy.safety.level===oe.policy.safety.level?"project":H.levelPresent?"user":"default";return{...Re?Qo(Re.policy):H.policy,errors:Te,...ke?{fallback:ke}:{},...J.exists?{policyScopes:{levelScope:Le,weakenings:Re?.weakenings??[],weakeningsIgnored:ie}}:{}}}var yb="project policy audit settings are ignored; audit is user scope only";function pe(W,G){if(!xn(W))return{policy:{},diagnostics:[]};let H=xn(W.safety)?W.safety:{},J=xn(W.workflow)?W.workflow:{},oe=xn(W.destructive_command_protection)?W.destructive_command_protection:{},ie=xn(W.secret_protection)?W.secret_protection:{},fe={...hl.has(H.level)?{level:H.level}:{},...xn(H.overrides)?Fu({overrides:Bu(H.overrides,ao,["safety","overrides"],Lr)}):{}},Re={...typeof oe.enabled==="boolean"?{enabled:oe.enabled}:{},...oe.overrides!==void 0?{overrides:cs(oe.overrides,tl,Hu,Lr)}:{},...oe.allow_paths!==void 0?{allow_paths:uo(oe.allow_paths,ul,G,["destructive_command_protection","allow_paths"],Lr)}:{}},Te={...typeof ie.enabled==="boolean"?{enabled:ie.enabled}:{},...ie.overrides!==void 0?{overrides:cs(ie.overrides,ll,ju,Lr)}:{},...ie.deny_paths!==void 0?{deny_paths:uo(ie.deny_paths,ml,G,["secret_protection","deny_paths"],Lr)}:{},...ie.allow_paths!==void 0?{allow_paths:uo(ie.allow_paths,fl,G,["secret_protection","allow_paths"],Lr)}:{}};return{policy:Fu({safety:fe,workflow:typeof J.worktree_mode==="boolean"?{worktree_mode:J.worktree_mode}:{},destructive_command_protection:Re,secret_protection:Te}),diagnostics:W.audit===void 0?[]:[yb]}}function Bu(W,G,H,J){return Object.fromEntries(G.flatMap((oe)=>{let ie=W[oe];if(typeof ie==="boolean")return[[oe,ie]];if(ie!==void 0)J(e([...H,oe],yl));return[]}))}function Fu(W){return Object.fromEntries(Object.entries(W).flatMap((G)=>Object.keys(G[1]).length>0?[G]:[]))}var Lr=()=>{return},yl="must be a boolean",Sl="must be an object if provided",Uu=`must be an integer between ${as} and ${ls}`,Hu={path:["destructive_command_protection","overrides"],label:"destructive command"},ju={path:["secret_protection","overrides"],label:"secret protection"},pt=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function ft(W,G){let H=[];return{policy:Vu(W,G,(oe)=>{H.push(oe)}),issues:H}}function k(W,G){return Vu(W,G,Lr)}function Vu(W,G,H){if(!xn(W))return H(e([],"Config must be an object")),A();if(W.version!==1)H(e(["version"],"must be 1"));let J=co(W.safety,["safety"],["level","overrides"],H),oe=co(J.overrides,["safety","overrides"],ao,H),ie=co(W.workflow,["workflow"],["worktree_mode"],H),fe=co(W.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],H),Re=co(W.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],H),Te=co(W.audit,["audit"],["retention_days"],H);return Ku(W,pt,[],H),{version:1,safety:{level:Sb(J.level,H),overrides:Bu(oe,ao,["safety","overrides"],H)},workflow:{worktree_mode:gl(ie.worktree_mode,["workflow","worktree_mode"],!1,H)},destructive_command_protection:{enabled:gl(fe.enabled,["destructive_command_protection","enabled"],!0,H),overrides:cs(fe.overrides,tl,Hu,H),allow_paths:uo(fe.allow_paths,ul,G,["destructive_command_protection","allow_paths"],H)},secret_protection:{enabled:gl(Re.enabled,["secret_protection","enabled"],!0,H),overrides:cs(Re.overrides,ll,ju,H),deny_paths:uo(Re.deny_paths,ml,G,["secret_protection","deny_paths"],H),allow_paths:uo(Re.allow_paths,fl,G,["secret_protection","allow_paths"],H)},audit:{retention_days:bb(Te.retention_days,H)}}}function co(W,G,H,J){if(W===void 0)return{};if(!xn(W))return J(e(G,Sl)),{};return Ku(W,H,G,J),W}function Ku(W,G,H,J){for(let oe of Object.keys(W).filter((ie)=>!G.includes(ie)))J({path:H,message:oe,kind:"unknownKeys"})}function Sb(W,G){if(W===void 0)return"standard";if(hl.has(W))return W;return G(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function gl(W,G,H,J){if(typeof W==="boolean")return W;if(W!==void 0)J(e(G,yl));return H}function bb(W,G){if(!(W===void 0||typeof W==="number"&&Number.isInteger(W)&&W>=as&&W<=ls))G(e(["audit","retention_days"],Uu));return Mu(W)}function cs(W,G,H,J){if(W===void 0)return{};if(!xn(W))return J(e(H.path,Sl)),{};return Object.fromEntries(Object.entries(W).flatMap(([oe,ie])=>{if(!G.has(oe))return J({path:[...H.path,oe],message:`unknown ${H.label} rule id "${oe}"`,kind:"key"}),[];if(ie==="on"||ie==="off")return[[oe,ie]];return J(e([...H.path,oe],'must be "on" or "off"')),[]}))}function uo(W,G,H,J,oe){if(W===void 0)return[];if(!Array.isArray(W))return oe(e(J,"must be an array of paths")),[];return W.flatMap((ie,fe)=>{let Re=G(ie,H);if(Re===null)return[ie];return oe(typeof ie==="string"?an([...J,fe],Re):e([...J,fe],Re)),[]})}function xn(W){return!!W&&typeof W==="object"&&!Array.isArray(W)}function A(){return structuredClone(ne)}function We(W,G){let H=P({safety:ze(W.safety)},G),J=K({destructiveCommandProtectionEnabled:W.destructive_command_protection.enabled,destructiveCommandRuleOverrides:W.destructive_command_protection.overrides},H.capabilities),oe=Object.values(J),ie=oe.filter((fe)=>fe.source!=="catastrophic");return{selectedPreset:W.safety.level,effectiveLevel:H.effectiveLevel,capabilities:H.capabilities,rules:J,counts:{enabled:ie.filter((fe)=>fe.enabled).length,disabled:ie.filter((fe)=>!fe.enabled).length,effectiveCustomizations:oe.filter((fe)=>fe.changesInherited).length}}}function Be(W,G){if(!gb(W))return{exists:!1,policy:A(),errors:[]};try{let H=hb(W,"utf-8");if(!H.trim())return{exists:!0,policy:A(),errors:[`${W}: Config file is empty`],fallback:"defaults"};let J=JSON.parse(H),oe=ft(J,G);if(oe.issues.length===0)return{exists:!0,parsed:J,policy:oe.policy,errors:[]};return{exists:!0,parsed:J,policy:oe.policy,errors:oe.issues.map((ie)=>`${W}: ${vb(ie)}`),fallback:xn(J)?"salvaged":"defaults"}}catch(H){let J=H instanceof Error?H.message:String(H);return{exists:!0,policy:A(),errors:[`${W}: ${H instanceof SyntaxError?"Invalid JSON":J}`],fallback:"defaults"}}}var Cb=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[Sl,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[yl,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Uu,`not an integer between ${as} and ${ls}`]]);function vb(W){let G=Ja(W.path);if(W.kind==="unknownKeys")return`${G===""?"":`${G}.`}${W.message}: unknown field`;if(W.kind==="key")return`${G}: unknown rule id`;let H=Cb.get(W.message)??W.message;return G===""?H:`${G}: ${H}`}function Eb(W,G){let H=Be(W,G);if(!H.exists){let J=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!xn(J))return{policy:Qo(A()),errors:[]};let oe=k(J,G);return{policy:Qo(oe),gui:oe,errors:[],levelPresent:zu(J)}}if(H.parsed===void 0)return{policy:Qo(A()),errors:H.errors,...H.fallback?{fallback:H.fallback}:{}};return{policy:Qo(H.policy),gui:H.policy,errors:H.errors,...H.fallback?{fallback:H.fallback}:{},levelPresent:zu(H.parsed)}}function zu(W){let G=xn(W)&&xn(W.safety)?W.safety:{};return hl.has(G.level)}function mt(W){let G=Object.entries(W),H=new Set(G.flatMap(([J,oe])=>oe==="on"?[J]:[]));return[...new Set([...[...rs].filter((J)=>!H.has(J)),...G.flatMap(([J,oe])=>oe==="off"?[J]:[])])]}function Qo(W){return{safety:ze(W.safety),worktreeMode:W.workflow.worktree_mode,destructiveCommandProtectionEnabled:W.destructive_command_protection.enabled,destructiveCommandRuleOverrides:W.destructive_command_protection.overrides,destructiveCommandAllowPaths:W.destructive_command_protection.allow_paths,secretProtection:{enabled:W.secret_protection.enabled,disabledRules:mt(W.secret_protection.overrides),denyPaths:W.secret_protection.deny_paths,allowPaths:W.secret_protection.allow_paths}}}function ze(W){let G={...W.overrides.fail_closed!==void 0?{failClosed:W.overrides.fail_closed}:{},...W.overrides.paranoid_rm!==void 0?{paranoidRm:W.overrides.paranoid_rm}:{},...W.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:W.overrides.paranoid_interpreters}:{}};return{level:W.level,...Object.keys(G).length>0?{overrides:G}:{}}}function R(W,G){let H=ee(W,G),J=$u(W,G),oe={rules:H.rules,transparentWrappers:H.transparent_wrappers,commandTools:H.command_tools,safety:J.safety,worktreeMode:J.worktreeMode,destructiveCommandProtectionEnabled:J.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:J.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:J.destructiveCommandAllowPaths,secretProtection:{enabled:J.secretProtection.enabled??!0,disabledRules:J.secretProtection.disabledRules??[],denyPaths:J.secretProtection.denyPaths,allowPaths:J.secretProtection.allowPaths??[]}},ie={...H.userConfig?.overrides,...H.projectConfig?.overrides},fe=Object.freeze(Object.fromEntries(oe.rules.map((Re)=>{let Te=H.rulebooks.find((Le)=>Le.rules.includes(Re.name)),ke=ie[Re.name];return[Re.name,Object.freeze({id:Re.name,...Te?{rulebook:Object.freeze({name:Te.name,version:Te.version}),...wb(Te.spec)?{source:Te.spec}:{}}:{},...ke&&typeof ke==="object"?{override:Object.freeze({type:"reason",reason:ke.reason})}:{}})]})));return Ne(oe,Rb(H,J),fe,J.policyScopes)}function Ve(W){if(W.state==="ready")return{state:W.state};return{state:W.state,reason:W.reason}}function Rb(W,G){let H=xb(G);if(W.errors.length===0&&W.warnings.length===0&&!H)return;return{diagnostics:[...W.errors,...W.warnings,...G.errors],reason:Ab(W.errors.length>0?_b(W.errors):void 0,W.warnings.length>0?Cl(W.warnings.join("; ")):void 0,H)}}function _b(W){return`${Cl(W.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function xb(W){if(W.errors.length===0)return;let G=W.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${W.errors.join("; ")}. Enforcing ${G}; the invalid values are not active. Fix the policy file manually`}function wb(W){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(W)}function Ne(W,G,H=Object.freeze({}),J){let oe=bl(structuredClone(W)),ie=J?{policyScopes:bl(structuredClone(J))}:{};if(!G)return Object.freeze({state:"ready",policy:oe,diagnostics:Object.freeze([]),ruleMetadata:H,...ie});return Object.freeze({state:"degraded",policy:oe,diagnostics:Object.freeze([...G.diagnostics]),reason:G.reason,ruleMetadata:H,...ie})}function bl(W){if(typeof W!=="object"||W===null)return W;for(let G of Object.values(W))bl(G);return Object.freeze(W)}function Ab(...W){return Cl(W.filter((G)=>!!G).join("; "))}function Cl(W){return/[.!?]$/.test(W)?W:`${W}.`}function qe(W){let G=W.effectiveCapabilities,H=G.fail_closed.enabled,J=G.paranoid_rm.enabled,oe=G.paranoid_interpreters.enabled;return{policy:Nu(W.policySnapshot.policy,G),effectiveCapabilities:G,effectiveLevel:Ga({failClosed:H,paranoidRm:J,paranoidInterpreters:oe}),strict:H,paranoidRm:J,paranoidInterpreters:oe,worktreeMode:W.worktreeMode??!1}}import{dirname as NA,isAbsolute as LA,join as WA,parse as GA,resolve as FA,sep as zA}from"node:path";function ei(W,G){if(W!=="powershell")return G[0]?.provenance==="command-substitution";let H=G[0]?.text==="&"||G[0]?.text==="."?1:0,J=G[H]?.provenance;return J!==void 0&&J!=="literal"}var Pb=/^[A-Za-z_][A-Za-z0-9_]*=/;function ds(W,G){return W?.provenance==="literal"&&!W.quoted&&W.raw===G&&W.text===G}function ti(W){let G=ds(W.words[0],"time")?1:0,H=G===1&&ds(W.words[G],"-p")?G+1:G,J=G===1&&ds(W.words[H],"--")?H+1:H,oe=ds(W.words[J],"!")?J+1:J,ie=W.words.slice(oe).find((fe)=>!Pb.test(fe.text));return ie?.provenance==="literal"?ie.text:void 0}var yr=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function us(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function ms(W,G,H){W.push(H),G.reset()}function fs(W){let G=[];return{parts:G,push:(H,J,oe)=>{if(J<=H)return;G.push({raw:W.slice(H,J),span:{start:H,end:J},provenance:oe})}}}function vl(W){let G=W.parts??[{raw:W.raw,span:W.span,provenance:W.provenance}];return{kind:"word",...W,parts:G}}function mo(W,G,H,J,oe,ie,fe){return vl({text:J,raw:W.slice(G,H),span:{start:G,end:H},provenance:oe,quoted:ie,...fe?{parts:fe}:{}})}function El(W,G,H){if(G>=H||Yu(W[G]??""))return null;let J="",oe=!1,ie=!1,fe=G;while(fe<H&&!Yu(W[fe]??"")){let Re=W[fe]??"";if(Re==="'"){oe=!0;let Te=qu(W,fe+1,H,"'");J+=Te.text,ie||=!Te.closed,fe=Te.next;continue}if(Re==='"'){oe=!0;let Te=qu(W,fe+1,H,'"');J+=Te.text,ie||=!Te.closed,fe=Te.next;continue}if(Re==="\\"){oe=!0;let Te=W[fe+1];if(!Te||Te===`
6
+ `||Te==="\r"){ie=!0;break}J+=Te,fe+=2;continue}if(Re==="`"||W.startsWith("$(",fe)||W.startsWith("${",fe)||W.startsWith("<(",fe)||W.startsWith(">(",fe))ie=!0;J+=Re,fe++}return{delimiter:J,quoted:oe,next:fe,ambiguous:ie}}function Rl(W,G,H,J){let oe=[],ie=G;for(let fe of J){let Re=ie,Te=!1;while(ie<H){let ke=Tb(W,ie,H);if((fe.stripTabs?ke.text.replace(/^\t+/,""):ke.text)===fe.delimiter){fe.attach({body:fe.stripTabs?Ib(W.slice(Re,ie)):W.slice(Re,ie),delimiter:fe.delimiter,quotedDelimiter:fe.quotedDelimiter,bodySpan:{start:Re,end:ie},terminatorSpan:{start:ie,end:ke.contentEnd}}),ie=ke.next,Te=!0;break}if(ke.next<=ie)break;ie=ke.next}if(Te)continue;return oe.push({code:"unterminated-heredoc",message:`heredoc delimiter ${fe.delimiter} was not found`}),{next:H,issues:oe,terminated:!1}}return{next:ie,issues:oe,terminated:!0}}function qu(W,G,H,J){let oe="",ie=G;while(ie<H&&W[ie]!==`
7
+ `&&W[ie]!=="\r"){let fe=W[ie]??"";if(fe===J)return{text:oe,next:ie+1,closed:!0};if(J==='"'&&fe==="\\"&&W[ie+1]){let Re=W[ie+1]??"";oe+=["$","`",'"',"\\"].includes(Re)?Re:`\\${Re}`,ie+=2;continue}oe+=fe,ie++}return{text:oe,next:ie,closed:!1}}function Yu(W){return W!=="\r"&&(/[\s;&|<>)]/u.test(W)||W==="`")}function Tb(W,G,H){let J=G;while(J<H&&W[J]!==`
8
+ `)J++;let oe=J>=H?H:J+1;return{text:W.slice(G,J),contentEnd:J,next:oe}}function Ib(W){return W.replace(/(^|\r\n?|\n)\t+/g,"$1")}var em=new Set(["&&","||","|","|&"]),kb=new Set(["!","do","elif","else","if","then","until","while"]);function tm(W,G){let H={start:0,end:W.length};if(W.length>G.maxInputLength)return{kind:"program",dialect:"posix",source:W,span:H,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${G.maxInputLength} UTF-16 code units`}],nodes:[]};let J={wordsUsed:0,maxWords:G.maxWords,quotedExpansionEnd:1/0},oe=hs(W,0,W.length,G,J,0),ie=[...oe.issues,...$b(W,J.quotedExpansionEnd,oe.nodes)?[im]:[],...Fb.test(W)?[om]:[]];return{kind:"program",dialect:"posix",source:W,span:H,status:Ss(ie,oe.limited),issues:ie,nodes:oe.nodes}}function hs(W,G,H,J,oe,ie,fe){let Re=[],Te=[],ke=us(),Le=[],Xe=()=>{if(ke.words.length===0&&ke.redirections.length===0)return;let Ze={start:ke.start,end:ke.end},Qe=ke.words.map((et)=>et.text);ms(Re,ke,{kind:"command",dialect:"posix",source:W.slice(Ze.start,Ze.end),span:Ze,words:ke.words,redirections:ke.redirections,nested:ke.nested,displayText:Te.length>0&&Re.length===0?W.slice(G,H):Qe.join(" ")})},Ye=G;while(Ye<H){let Ze=W[Ye];if(!Ze)break;if(fe&&Ze===fe)return Xe(),Qu(Re,Te),{nodes:Re,issues:Te,next:Ye+1,closed:!0,limited:!1,pendingHeredocs:Le};if(ri(Ze)){if(Ze.charCodeAt(0)>127)Te.push(om);if(Ze===`
9
+ `||Ze==="\r"){Xe();let Ot=Ze==="\r"&&W[Ye+1]===`
10
+ `?Ye+2:Ye+1,Mt=Re.at(-1);if(Mt?.kind!=="connector"||!em.has(Mt.operator))Re.push({kind:"connector",operator:W.slice(Ye,Ot),span:{start:Ye,end:Ot}});if(Le.length>0){let Nt=Rl(W,Ot,H,Le.splice(0));Te.push(...Nt.issues),Ye=Nt.next;continue}Ye=Ot;continue}Ye++;continue}if(Ze==="#"){while(Ye<H&&W[Ye]!==`
11
+ `&&W[Ye]!=="\r")Ye++;continue}let Qe=ke.start===-1?iC(W,Ye,H):void 0;if(Qe){if(xl(Re,Te),ie>=J.maxDepth)return fo(Re,Te,Ye,"depth-limit",J.maxDepth);if(!_l(oe))return fo(Re,Te,Ye,"word-limit",J.maxWords);let Ot=hs(W,Qe.braceIndex+1,H,J,oe,ie+1,"}"),Mt=Ot.next,Nt={start:Qe.braceIndex+1,end:Ot.closed?Mt-1:Mt},ht=Zu(W,Nt,Ot);if(Re.push({kind:"function",name:Qe.name,span:{start:Ye,end:Mt},body:ht}),Te.push(...Ot.issues),Ot.pendingHeredocs.length>0||oi(Ot.nodes))Te.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(Le.push(...Ot.pendingHeredocs),Ot.limited)return gs(Re,Te,Ot.next);if(!Ot.closed)Te.push({code:"unclosed-function-body",message:"function body is not closed"});Ye=Mt;continue}let et=ys(W,Ye);if(et){if(Xe(),!mm(Re.at(-1)))Te.push({code:"unexpected-connector",message:`connector ${et} has no preceding command`});Re.push({kind:"connector",operator:et,span:{start:Ye,end:Ye+et.length}}),Ye+=et.length;continue}if(Ze===")"){Xe(),Te.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),Re.push({kind:"unknown",source:Ze,span:{start:Ye,end:Ye+1}}),Ye++;continue}if((Ze==="("||Ze==="{"&&Vb(W,Ye,H))&&ke.start===-1){if(xl(Re,Te),ie>=J.maxDepth)return fo(Re,Te,Ye,"depth-limit",J.maxDepth);let Ot=Ze==="("?")":"}",Mt=hs(W,Ye+1,H,J,oe,ie+1,Ot),Nt=Mt.next,ht={start:Ye+1,end:Mt.closed?Nt-1:Nt},Wt=Zu(W,ht,Mt);if(Re.push({kind:"group",style:Ze==="("?"subshell":"brace",span:{start:Ye,end:Nt},body:Wt}),Te.push(...Mt.issues),Mt.pendingHeredocs.length>0||oi(Mt.nodes))Te.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(Le.push(...Mt.pendingHeredocs),Mt.limited)return gs(Re,Te,Mt.next);if(!Mt.closed)Te.push({code:Ze==="("?"unclosed-subshell":"unclosed-brace-group",message:`${Ze} group is not closed`});Ye=Nt;continue}let tt=(Ze==="<"||Ze===">")&&W[Ye+1]!=="("?Nb(W,Ye):null;if(tt){let Ot=ke.words.at(-1),Mt=Ot&&Ot.span.end===Ye&&/^[0-9]+$/.test(Ot.raw)?Number(Ot.raw):void 0;if(Mt!==void 0)ke.words.pop();let Nt=Mt===void 0?Ye:Ot?.span.start??Ye;ke.start=ke.start===-1?Ye:ke.start;let ht=Ye+tt.length;while(ht<H&&/[ \t]/.test(W[ht]??""))ht++;let Wt=W[ht],Dt=ht>Ye+tt.length&&Wt==="#",en=!Wt||ri(Wt)||!!ys(W,ht)||Wt===fe||Wt===")"||Dt||(Wt==="<"||Wt===">")&&W[ht+1]!=="(",bn=tt==="<<"||tt==="<<-",Xt=bn?El(W,ht,H):void 0,qt=Xt?{word:mo(W,ht,Xt.next,Xt.delimiter,"literal",Xt.quoted),nested:[],issues:[],next:Xt.next,limited:!1}:!en?wl(W,ht,H,J,oe,ie):void 0;if(qt){if(Te.push(...qt.issues),qt.limited)return gs(Re,Te,qt.next);if(!_l(oe))return fo(Re,Te,qt.next,"word-limit",J.maxWords)}let gn=qt?.next??Ye+tt.length,Jt={kind:"redirection",operator:tt,span:{start:Nt,end:gn},...Mt===void 0?{}:{fd:Mt},...qt?{target:qt.word}:{}};if(ke.redirections.push(Jt),bn&&!Xt)Te.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if(Xt){if(Xt.ambiguous||Xt.delimiter.length===0)Te.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let rn=ke.nested;Le.push({delimiter:Xt.delimiter,quotedDelimiter:Xt.quoted,stripTabs:tt==="<<-",attach:(Tn)=>{if(Jt.heredoc=Tn,Tn.quotedDelimiter)return;let zn=Mb(W,Tn.bodySpan.start,Tn.bodySpan.end,J,oe,ie+1);rn.push(...zn.programs),Te.push(...zn.issues)}})}if(!bn&&!qt)Te.push({code:"missing-redirection-target",message:`redirection ${tt} requires a target word`});if(qt)ke.nested.push(...qt.nested);ke.end=gn,Ye=gn;continue}let gt=ke.start===-1;if(gt)xl(Re,Te);let _t=wl(W,Ye,H,J,oe,ie);if(Te.push(..._t.issues),_t.limited)return gs(Re,Te,_t.next);let yt=Yb(ke.words)?eC(W,_t.word,oe.maxWords-oe.wordsUsed,J.maxDepth,J.maxInputLength):void 0;if(yt?.limitCode)return fo(Re,Te,_t.next,yt.limitCode,yt.limitCode==="word-limit"?J.maxWords:yt.limitCode==="depth-limit"?J.maxDepth:J.maxInputLength);let At=yt?.words??[_t.word];for(let Ot of At){if(!_l(oe))return fo(Re,Te,_t.next,"word-limit",J.maxWords);ke.words.push(Ot)}if(ke.start=ke.start===-1?Ye:ke.start,ke.end=_t.next,ke.nested.push(..._t.nested),gt&&fm(_t.word))Xe();Ye=_t.next>Ye?_t.next:Ye+1}return Xe(),Qu(Re,Te),Te.push(...sC(Le)),{nodes:Re,issues:Te,next:Ye,closed:fe===void 0,limited:!1,pendingHeredocs:[]}}function Zu(W,G,H){return{kind:"program",dialect:"posix",source:W.slice(G.start,G.end),span:G,status:Ss(H.issues,H.limited),issues:H.issues,nodes:H.nodes}}function wl(W,G,H,J,oe,ie){let fe="",Re=G,Te=!1,ke="literal",Le=[],Xe=[],Ye=!1;while(Re<H){let Ze=W[Re],Qe=(Ze==="<"||Ze===">")&&W[Re+1]==="(";if(!Ze||ri(Ze)||(Ze===";"||Ze==="|"||Ze==="&")&&ys(W,Re)||(Ze==="<"||Ze===">")&&!Qe)break;if(Ze===")")break;if(Ze==="'"){Te=!0;let gt=W.indexOf("'",Re+1);if(gt===-1||gt>=H){fe+=W.slice(Re+1,H),Xe.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),Re=H;break}fe+=W.slice(Re+1,gt),Re=gt+1;continue}if(Ze==='"'){Te=!0;let gt=Ob(W,Re,H,J,oe,ie);if(fe+=gt.text,Le.push(...gt.nested),Xe.push(...gt.issues),Ye||=gt.limited,ke=ni(ke,gt.provenance),Re=gt.next,Ye)break;continue}if(W.startsWith("$'",Re)){Te=!0;let gt=Ub(W,Re+2,H);if(fe+=gt.text,Xe.push(...gt.issues),!gt.closed)Xe.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});Re=gt.next;continue}if(Ze==="\\"){let gt=W[Re+1];if(!gt){Xe.push({code:"trailing-escape",message:"escape has no following character"}),Re++;break}if(gt===`
12
+ `){Re+=2;continue}fe+=gt,Re+=2;continue}if(Gr(W,Re))Xe.push(Wr);let et=Ze==="$"||Ze==="<"||Ze===">"||Ze==="`"?ii(W,Re,H,J,oe,ie):null,tt=et?Pl(et,Le,Xe):sm(W,Re,H,J,oe,ie,Le,Xe);if(tt){if(tt.provenance==="variable")fe+=W.slice(Re,tt.next);if(Ye||=tt.limited,ke=ni(ke,tt.provenance),Re=tt.next,Ye)break;continue}if(Ze==="$"){let gt=lm(W,Re,H,fe,ke);fe=gt.text,ke=gt.provenance,Re=gt.next;continue}if(Ze==="*"||Ze==="?"||Ze==="[")ke=ni(ke,"glob");fe+=Ze,Re++}return{word:mo(W,G,Re,fe,ke,Te,ke==="literal"?void 0:jb(W,G,Re)),nested:Le,issues:Xe,next:Re,limited:Ye}}function Ob(W,G,H,J,oe,ie){let fe="",Re="literal",Te=[],ke=[],Le=!1,Xe=G+1;while(Xe<H){let Ye=W[Xe];if(Ye==='"')return{text:fe,provenance:Re,nested:Te,issues:ke,next:Xe+1,limited:Le};if(Ye==="\\"&&W[Xe+1]){let et=W[Xe+1]??"";if(et===`
13
+ `){Xe+=2;continue}if(et==="\r"&&W[Xe+2]===`
14
+ `){Xe+=3;continue}fe+=["$","`",'"',"\\"].includes(et)?et:`\\${et}`,Xe+=2;continue}if(Gr(W,Xe))ke.push(Wr);let Ze=ii(W,Xe,H,J,oe,ie),Qe=Ze?Pl(Ze,Te,ke):sm(W,Xe,H,J,oe,ie,Te,ke);if(Qe){if(Qe.provenance!=="command-substitution")fe+=W.slice(Xe,Qe.next);if(Xe=Qe.next,Le||=Qe.limited,Re=ni(Re,Qe.provenance),Le)return{text:fe,provenance:Re,nested:Te,issues:ke,next:Xe,limited:Le};continue}if(Ye==="$"){let et=lm(W,Xe,H,fe,Re);fe=et.text,Re=et.provenance,Xe=et.next;continue}fe+=Ye??"",Xe++}return ke.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:fe,provenance:Re,nested:Te,issues:ke,next:H,limited:Le}}function ii(W,G,H,J,oe,ie){let fe=rm(W,G);if(!fe)return null;let{length:Re,closing:Te}=fe,ke=Te==="))",Le=Te==="`",Xe=W[G]==="<"||W[G]===">",Ye=Tl(W,G+Re,H,Te),Ze=Ye===-1?H:Ye,Qe=Ye===-1?H:Ye+Te.length;if(ie>=J.maxDepth)return{program:oC(W,G+Re,Ze,"depth-limit"),next:Qe,provenance:ke?"arithmetic":"command-substitution"};if(ke){let At=[],Ot=[],Mt=!1,Nt=G+Re;while(Nt<Ze){let ht=ii(W,Nt,Ze,J,oe,ie+1);if(!ht){if(Gr(W,Nt))Ot.push(Wr);Nt++;continue}if(At.push(...ht.program.nodes),Ot.push(...ht.program.issues),Mt||=ht.program.status==="limited",Nt=ht.next,Mt)break}if(Ye===-1)Ot.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:{kind:"program",dialect:"posix",source:W.slice(G+Re,Ze),span:{start:G+Re,end:Ze},status:Ss(Ot,Mt),issues:Ot,nodes:At},next:Qe,provenance:"arithmetic"}}let et=hs(W,G+Re,Ze,J,oe,ie+1),tt=Ye===-1?[{code:"unclosed-command-substitution",message:`${W.slice(G,G+Re)} substitution is not closed`}]:[],gt=(Le||Xe)&&oi(et.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[],_t=Le&&/\\[\\$`\n]/.test(W.slice(G+Re,Ze))?[Bb]:[],yt=[...et.issues,...tt,...gt,..._t];return{program:{kind:"program",dialect:"posix",source:W.slice(G+Re,Ze),span:{start:G+Re,end:Ze},status:Ss(yt,et.limited),issues:yt,nodes:et.nodes},next:Qe,provenance:"command-substitution"}}function Mb(W,G,H,J,oe,ie){let fe=[],Re=[],Te=G;while(Te<H){let ke=W[Te];if(ke==="\\"){Te+=2;continue}let Le=ke==="$"||ke==="`"?ii(W,Te,H,J,oe,ie):null;if(!Le){if(Gr(W,Te))Re.push(Wr);Te++;continue}if(fe.push(Le.program),Lb(W,Te,Le.next)&&Wb(Le.program))Re.push(Wr);Te=Le.next}return{programs:fe,issues:Re}}function Pl(W,G,H){return G.push(W.program),H.push(...W.program.issues),{provenance:W.provenance,next:W.next,limited:W.program.status==="limited"}}function Tl(W,G,H,J){if(J==="`"){for(let Re=G;Re<H;Re++){if(W[Re]==="\\"){Re++;continue}if(W[Re]==="`")return Re}return-1}let oe={single:!1,double:!1},ie=[],fe=[];for(let Re=G;Re<H;Re++){let Te=W[Re];if((Te===`
15
+ `||Te==="\r")&&fe.length>0){let Xe=Te==="\r"&&W[Re+1]===`
16
+ `?Re+2:Re+1,Ye=Rl(W,Xe,H,fe.splice(0));if(!Ye.terminated)return-1;Re=Ye.next-1;continue}let ke=nm(W,Re,G,H,oe);if(ke!==null){Re=ke;continue}if(!oe.double&&W.startsWith("$((",Re)){let Xe=Db(W,Re+3,H);if(Xe===-1)return-1;Re=Xe+1;continue}if(J===")"&&!oe.double&&Te==="<"&&W[Re+1]==="<"&&W[Re+2]!=="<"){let Xe=W[Re+2]==="-",Ye=Re+(Xe?3:2);while(Ye<H&&/[ \t]/.test(W[Ye]??""))Ye++;let Ze=El(W,Ye,H);if(Ze){fe.push({delimiter:Ze.delimiter,quotedDelimiter:Ze.quoted,stripTabs:Xe,attach:()=>{return}}),Re=Ze.next-1;continue}}if(W.startsWith("$(",Re)&&!W.startsWith("$((",Re)){ie.push(oe),oe={single:!1,double:!1},Re++;continue}if(Te==="("&&!oe.double){ie.push(oe),oe={single:!1,double:!1};continue}if(Te!==")"||oe.double)continue;let Le=ie.pop();if(Le){oe=Le;continue}return J==="))"&&W[Re+1]!==")"?-1:Re}return-1}function Db(W,G,H){let J=1,oe={single:!1,double:!1};for(let ie=G;ie<H;ie++){let fe=W[ie],Re=nm(W,ie,G,H,oe);if(Re!==null){ie=Re;continue}if(W.startsWith("$(",ie)&&!W.startsWith("$((",ie)){J++,ie++;continue}if(fe==="("&&!oe.double)J++;if(fe!==")"||oe.double)continue;if(J--,J===0)return W[ie+1]===")"?ie:-1}return-1}function nm(W,G,H,J,oe){let ie=W[G];if(ie==="\\"&&!oe.single)return G+1;if(!oe.double&&ie==="'")oe.single=!oe.single;if(!oe.single&&ie==='"')oe.double=!oe.double;if(oe.single)return G;if(oe.double||ie!=="#"||!aC(W,G,H))return null;let fe=G;while(fe+1<J&&W[fe+1]!==`
17
+ `&&W[fe+1]!=="\r")fe++;return fe}function ys(W,G){let H=W[G];if(H===";")return";";if(H==="&")return W[G+1]==="&"?"&&":"&";if(H==="|")return W[G+1]==="|"?"||":W[G+1]==="&"?"|&":"|";return null}function Nb(W,G){let H=W[G];if(H===">"){if(W[G+1]===">")return">>";if(W[G+1]==="&")return">&";return W[G+1]==="|"?">|":">"}if(H!=="<")return null;if(W.startsWith("<<<",G))return"<<<";if(W.startsWith("<<-",G))return"<<-";if(W[G+1]==="<")return"<<";if(W[G+1]==="&")return"<&";if(W[G+1]===">")return"<>";return"<"}function ri(W){let G=W.charCodeAt(0);if(G===32||G>=9&&G<=13)return!0;if(G<128)return!1;return/\s/u.test(W)}var Wr=Object.freeze({code:"unsupported-function-substitution",message:"${ list; } function substitutions run in the current shell and cannot be analyzed"});function Gr(W,G){if(W[G]!=="$")return!1;let H=Xu(W,G+1);if(W[H]!=="{")return!1;let J=W[Xu(W,H+1)]??"";return J==="|"||ri(J)}function Lb(W,G,H){for(let J=W.indexOf("$",G);J!==-1&&J<H;J=W.indexOf("$",J+1))if(Gr(W,J))return!0;return!1}function Wb(W){return W?.status==="limited"||(W?.issues??[]).some((G)=>G.code===Wr.code)}function Xu(W,G){let H=G;while(W.startsWith("\\\n",H)||W.startsWith(`\\\r
18
+ `,H))H+=W[H+1]==="\r"?3:2;return H}function rm(W,G){if(W.startsWith("$((",G))return{length:3,closing:"))"};if(W.startsWith("$(",G)||W.startsWith("<(",G)||W.startsWith(">(",G))return{length:2,closing:")"};return W[G]==="`"?{length:1,closing:"`"}:null}var Gb=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"}),Fb=/[\v\f\r]/,om=Object.freeze({code:"unsupported-blank",message:"a vertical tab, form feed, carriage return or Unicode space is part of a word in bash and zsh, not a separator"}),im=Object.freeze({code:"unsupported-parameter-expansion",message:"a line continuation inside ${ }, or a quote or backslash inside ${ } with a substitution in or after it, cannot be analyzed"}),zb=/\$\(|`|[<>]\(/g;function $b(W,G,H){let J=Al(H);return[...W.slice(G).matchAll(zb)].some((oe)=>{let ie=G+oe.index;return!J.some((fe)=>ie>=fe.start&&ie<fe.end)})}function Al(W){return W.flatMap((G)=>{if(G.kind==="command")return[...G.redirections.flatMap((H)=>H.heredoc?[H.heredoc.bodySpan]:[]),...G.nested.flatMap((H)=>Al(H.nodes))];return G.kind==="group"||G.kind==="function"?Al(G.body.nodes):[]})}var Bb=Object.freeze({code:"unsupported-backtick-escape",message:"a backslash escape inside backticks changes the command the shell runs and cannot be analyzed"});function sm(W,G,H,J,oe,ie,fe,Re){if(W[G]!=="$"||W[G+1]!=="{")return null;let Te=bs(W,G+2,H),ke=Te.close===-1?H:Te.close+1;if(Te.close===-1)Re.push(Gb);if(Te.quoted&&Te.substitutions.length>0||Te.continued)Re.push(im);if(Te.quoted)oe.quotedExpansionEnd=Math.min(oe.quotedExpansionEnd,ke);let Le=Te.substitutions.some((Xe)=>{if(Gr(W,Xe))return Re.push(Wr),!1;let Ye=ii(W,Xe,ke,J,oe,ie);return Ye!==null&&Pl(Ye,fe,Re).limited});return{provenance:"variable",next:ke,limited:Le}}function bs(W,G,H){let J=[],oe=!1,ie=!1,fe=1,Re=G;while(Re<H){let Te=W[Re];if(Te==="$"&&Gr(W,Re))J.push(Re);if(Te==="\\"||Te==="'"||Te==='"'){oe=!0,ie||=Te==="\\"&&W[Re+1]===`
19
+ `,Re+=Te==="\\"?2:1;continue}let ke=rm(W,Re);if(ke){J.push(Re);let Le=Tl(W,Re+ke.length,H,ke.closing);if(Le===-1)break;Re=Le+ke.closing.length;continue}if(Te==="$"&&W[Re+1]==="{"){fe++,Re+=2;continue}if(Te==="}"&&--fe===0)return{close:Re,substitutions:J,quoted:oe,continued:ie};Re++}return{close:-1,substitutions:J,quoted:oe,continued:ie}}function am(W,G,H){if(W[G+1]==="{"){let oe=bs(W,G+2,H).close;return oe===-1?H:oe+1}if(W[G+1]==="$")return G+2;let J=G+1;while(J<H&&/[A-Za-z0-9_?@#!*-]/.test(W[J]??""))J++;return J===G+1?G+1:J}function Ub(W,G,H){let J="",oe=[],ie=G;while(ie<H){let fe=W[ie];if(fe==="'")return{text:J,next:ie+1,closed:!0,issues:oe};if(fe!=="\\"){J+=fe??"",ie++;continue}let Re=Hb(W,ie+1,H);if(J+=Re.text,Re.invalidCodePoint!==void 0)oe.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${Re.invalidCodePoint}`});ie=Re.next}return{text:J,next:H,closed:!1,issues:oe}}function Hb(W,G,H){let J=W[G];if(!J||G>=H)return{text:"\\",next:G};let oe=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
20
+ `],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(oe.has(J))return{text:oe.get(J)??J,next:G+1};if(J==="x")return ps(W,G+1,H,16,2,G+1);if(J==="u")return ps(W,G+1,H,16,4,G+1);if(J==="U")return ps(W,G+1,H,16,8,G+1);if(/[0-7]/.test(J))return ps(W,G,H,8,3,G+1);return{text:J,next:G+1}}function ps(W,G,H,J,oe,ie){let fe=J===16?/[0-9a-fA-F]/:/[0-7]/,Re="",Te=G;while(Te<H&&Re.length<oe&&fe.test(W[Te]??""))Re+=W[Te],Te++;if(!Re)return{text:W[ie-1]??"",next:ie};let ke=Number.parseInt(Re,J);return ke>1114111||ke>=55296&&ke<=57343?{text:"�",next:Te,invalidCodePoint:ke}:{text:String.fromCodePoint(ke),next:Te}}function Ss(W,G=!1){if(G)return"limited";if(W.some((H)=>H.code==="invalid-ansi-c-code-point"||H.code==="missing-heredoc-delimiter"||H.code==="ambiguous-heredoc-delimiter"||H.code==="unterminated-heredoc"||H.code==="unsupported-heredoc-context"||H.code==="unsupported-function-substitution"||H.code==="unsupported-backtick-escape"||H.code==="unclosed-parameter-expansion"||H.code==="unsupported-parameter-expansion"||H.code==="unsupported-blank"))return"invalid";return W.length>0?"partial":"complete"}function lm(W,G,H,J,oe){let ie=am(W,G,H);return{text:J+W.slice(G,ie),provenance:ni(oe,"variable"),next:ie}}function jb(W,G,H){let J=fs(W),oe=G,ie=!1,fe=!1,Re=G;while(Re<H){let Te=W[Re];if(Te==="\\"&&!ie){Re+=2;continue}if(!fe&&Te==="'"){ie=!ie,Re++;continue}if(!ie&&Te==='"'){fe=!fe,Re++;continue}if(ie){Re++;continue}let ke=W.startsWith("$((",Re),Le=W.startsWith("$(",Re)&&!ke,Xe=!fe&&(W.startsWith("<(",Re)||W.startsWith(">(",Re)),Ye=Te==="`";if(ke||Le||Xe||Ye){let Ze=ke?3:Ye?1:2,Qe=ke?"))":Ye?"`":")",et=Tl(W,Re+Ze,H,Qe),tt=et===-1?H:et+Qe.length;J.push(oe,Re,"literal"),J.push(Re,tt,ke?"arithmetic":"command-substitution"),Re=tt,oe=tt;continue}if(Te==="$"){let Ze=am(W,Re,H);if(Ze>Re+1){J.push(oe,Re,"literal"),J.push(Re,Ze,"variable"),Re=Ze,oe=Ze;continue}}if(!fe&&(Te==="*"||Te==="?"||Te==="[")){J.push(oe,Re,"literal"),J.push(Re,Re+1,"glob"),Re++,oe=Re;continue}Re++}return J.push(oe,H,"literal"),J.parts}function ni(W,G){if(G==="command-substitution"||W==="command-substitution")return"command-substitution";if(G==="arithmetic"||W==="arithmetic")return"arithmetic";if(G==="variable"||W==="variable")return"variable";if(G==="glob"||W==="glob")return"glob";return W}function Vb(W,G,H){return G+1>=H||ri(W[G+1]??"")||ys(W,G+1)!==null}var Kb=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),qb=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function Yb(W){let G=0;while(G<=W.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(W[G]?.text??""))G++;if(G===W.length)return!0;let H=Zb(W,G);if(H===void 0||H===null)return!1;G=H}return!1}function Zb(W,G){let H=W[G]?.text.toLowerCase();if(H==="command")return Xb(W,G);if(H==="env")return Jb(W,G);if(H==="sudo")return Qb(W,G);return}function Xb(W,G){if(W[G+1]?.text==="-v")return null;for(let H=G+1;H<W.length;H++){let J=W[H]?.text??"";if(J==="--")return H+1;if(J==="-p"||J==="-v"||J==="-V"||/^-[pvV]+$/.test(J))continue;return H}return W.length}function Jb(W,G){for(let H=G+1;H<W.length;H++){let J=W[H]?.text??"";if(J==="--")return H+1;if(Kb.has(J)){if(W[H+1]===void 0)return null;H++;continue}if(J.startsWith("-u=")||J.startsWith("--unset=")||J.startsWith("-C")&&J.length>2||J.startsWith("--chdir=")||J.startsWith("-S")&&J.length>2||J.startsWith("--split-string=")||J.startsWith("-P"))continue;if(J.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(J))continue;return H}return W.length}function Qb(W,G){for(let H=G+1;H<W.length;H++){let J=W[H]?.text??"";if(J==="--")return H+1;if(qb.has(J)){if(W[H+1]===void 0)return null;H++;continue}if(J.startsWith("-"))continue;return H}return W.length}function cm(W,G,H,J){if(W.provenance!=="literal"||!W.raw.includes("{"))return;let oe=dm(W.raw,G,H,J,!0);if(!oe)return;if("limited"in oe)return{limited:!0};let ie=oe.values.map((fe)=>um(fe,H));if(ie.some((fe)=>fe===null))return{limited:!0};return{words:[...new Set(ie.filter((fe)=>fe!==null&&fe!==""))]}}function eC(W,G,H,J,oe){if(G.provenance!=="literal"||!G.raw.includes("{"))return;let ie=dm(G.raw,H,J,oe,!1);if(!ie)return;if("limited"in ie){if(ie.limited==="expansions")return{limitCode:"depth-limit"};return{limitCode:ie.limited==="length"?"brace-expansion-limit":"word-limit"}}let fe=ie.values.map((Re)=>um(Re,J));if(fe.some((Re)=>Re===null))return;return{words:fe.filter((Re)=>Re!==null&&Re!=="").map((Re)=>mo(W,G.span.start,G.span.end,Re,"literal",!1))}}function dm(W,G,H,J,oe){let ie=[W],fe=W.length,Re=0;while(!0){let Te=ie.findIndex((Ze)=>Ju(Ze,oe));if(Te===-1)break;if(++Re>H)return{limited:"expansions"};let ke=ie[Te]??"",Le=Ju(ke,oe);if(!Le||Le.kind==="range")return{limited:"expansions"};let Xe=Le.start+ke.length-Le.end,Ye=Le.alternatives.reduce((Ze,Qe)=>Ze+Xe+Qe.length,0);if(fe-ke.length+Ye>J)return{limited:"length"};if(ie.length-1+Le.alternatives.length>G)return{limited:"words"};ie.splice(Te,1,...tC(ke,Le)),fe+=Ye-ke.length}return Re===0?void 0:{values:ie}}function Ju(W,G){let H=[],J,oe=null,ie=!1;for(let fe=0;fe<W.length;fe++){let Re=W[fe];if(ie){ie=!1;continue}if(Re==="\\"&&oe!=="'"){ie=!0;continue}if(Re===oe){oe=null;continue}if(oe===null&&(Re==="'"||Re==='"')){oe=Re;continue}if(oe!==null)continue;if(Re==="{"){H.push({start:fe,commas:[]});continue}if(Re===","&&H.length>0){H.at(-1)?.commas.push(fe);continue}if(Re!=="}"||H.length===0)continue;let Te=H.pop();if(!Te)continue;let ke=Te.commas.length>0?{kind:"alternatives",start:Te.start,end:fe+1,commas:Te.commas}:G&&rC(W.slice(Te.start+1,fe))?{kind:"range",start:Te.start,end:fe+1}:void 0;if(ke&&(!J||ke.start<J.start))J=ke}if(!J||J.kind==="range")return J;return{kind:J.kind,start:J.start,end:J.end,alternatives:nC(W,J)}}function tC(W,G){return G.alternatives.map((H)=>`${W.slice(0,G.start)}${H}${W.slice(G.end)}`)}function nC(W,G){let H=[G.start,...G.commas,G.end-1];return H.slice(0,-1).map((J,oe)=>W.slice(J+1,H[oe+1]))}function rC(W){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(W)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(W)}function um(W,G){let H=`x${W}`,J=wl(H,0,H.length,{maxInputLength:H.length,maxWords:1,maxDepth:G},{wordsUsed:0,maxWords:1,quotedExpansionEnd:1/0},0);if(J.limited||J.issues.length>0||J.next!==H.length||J.word.provenance!=="literal")return null;return J.word.text.slice(1)}function oC(W,G,H,J){return{kind:"program",dialect:"posix",source:W.slice(G,H),span:{start:G,end:H},status:"limited",issues:[{code:J,message:"command structure exceeds parser limit"}],nodes:[]}}function fo(W,G,H,J,oe){return{nodes:W,issues:[...G,{code:J,message:`command structure exceeds parser limit ${oe}`}],next:H,closed:!1,limited:!0,pendingHeredocs:[]}}function gs(W,G,H){return{nodes:W,issues:G,next:H,closed:!1,limited:!0,pendingHeredocs:[]}}function _l(W){return W.wordsUsed++,W.wordsUsed<=W.maxWords}function iC(W,G,H){let J=W.slice(G,H),oe=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(J)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(J),ie=oe?.[1];if(!oe||!ie)return;return{name:ie,braceIndex:G+oe[0].lastIndexOf("{")}}function oi(W){return W.some((G)=>{if(G.kind==="command")return G.redirections.some((H)=>H.heredoc)||G.nested.some((H)=>oi(H.nodes));return(G.kind==="group"||G.kind==="function")&&oi(G.body.nodes)})}function sC(W){return W.map((G)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${G.delimiter} was not found`}))}function mm(W){return W?.kind==="command"||W?.kind==="group"||W?.kind==="function"}function Qu(W,G){let H=W.at(-1);if(H?.kind!=="connector"||!em.has(H.operator))return;G.push({code:"missing-command-after-connector",message:`connector ${H.operator} requires a following command`})}function fm(W){return W?.provenance==="literal"&&!W.quoted&&W.raw===W.text&&kb.has(W.text)}function xl(W,G){let H=W.at(-1);if(!mm(H))return;if(H?.kind==="command"&&fm(H.words[0]))return;G.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function aC(W,G,H){return G===H||/[\s;&|()]/u.test(W[G-1]??"")}var gm=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item","foreach-object","where-object"]),lC=new Set(["gc","cat","type","cp","mv","rm"]),hm=["-rec","-for","-path","-literalpath","-whatif"],cC=/^\$env:\w/i,dC=/^(?:\$\{?\w+\}?|~)\\./;function ym(W,G){let H=W.toLowerCase().replaceAll("`","");if(![...gm].some((oe)=>H.includes(oe))&&!(H.includes("rm")&&hm.some((oe)=>H.includes(oe)))&&!H.includes("<#")&&!uC(H))return!1;let J=Ml(W,G);if(Sm(J))return!1;return J.issues.some((oe)=>oe.code==="unclosed-block-comment"||oe.code==="comment-depth-limit")||Ol(J).some(mC)}function Sm(W){return W.nodes.some((G)=>{if(G.kind==="group")return Sm(G.body);if(G.kind!=="command")return!1;return G.redirections.some((H)=>H.operator==="<<")})}function uC(W){if(W.includes("$env:"))return!0;return W.includes("\\")&&(W.includes("$")||W.includes("~"))}function mC(W){let G=W[0]==="&"||W[0]==="."?1:0,H=W[G]?.toLowerCase();if(H&&gm.has(H))return!0;let J=W.slice(G+1);if(H&&lC.has(H)&&J.some(fC))return!0;if(H!=="rm")return!1;return J.some((oe)=>{let ie=oe.toLowerCase().split(":",1)[0]??"";return hm.some((fe)=>ie.startsWith(fe))})}function fC(W){return cC.test(W)||dC.test(W)}function Ml(W,G){let H={start:0,end:W.length};if(W.length>G.maxInputLength)return{kind:"program",dialect:"powershell",source:W,span:H,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${G.maxInputLength} UTF-16 code units`}],nodes:[]};let J=Dl(W,0,W.length,G,0);return{kind:"program",dialect:"powershell",source:W,span:H,status:SC(J.issues,J.limited),issues:J.issues,nodes:J.nodes}}function Dl(W,G,H,J,oe,ie=!1){let fe=[],Re=[],Te=us(),ke=0,Le=!1,Xe=()=>{if(Te.words.length===0&&Te.redirections.length===0)return;let Ze={start:Te.start,end:Te.end};ms(fe,Te,{kind:"command",dialect:"powershell",source:W.slice(Ze.start,Ze.end),span:Ze,words:Te.words,redirections:Te.redirections,nested:Te.nested,displayText:Te.words.map((Qe)=>Qe.text).join(" ")})},Ye=G;while(Ye<H){let Ze=W[Ye];if(!Ze)break;if(ie&&Ze==="}")return Xe(),{nodes:fe,issues:Re,next:Ye+1,closed:!0,words:ke,limited:Le};let Qe=yC(W,Ye,H,J.maxDepth);if(Qe){if(Qe.issue)Re.push(Qe.issue);if(Qe.limited)return Xe(),{nodes:fe,issues:Re,next:Qe.next,closed:!1,words:ke,limited:!0};Ye=Qe.next;continue}if(/\s/.test(Ze)){if(Ze==="\r"||Ze===`
21
+ `){Xe();let gt=Ze==="\r"&&W[Ye+1]===`
22
+ `?Ye+2:Ye+1;fe.push(Il(W,Ye,gt)),Ye=gt;continue}Ye++;continue}let et=vm(W,Ye);if(et){Xe(),fe.push(Il(W,Ye,Ye+et.length)),Ye+=et.length;continue}if(Ze==="{"){if(Xe(),oe>=J.maxDepth)return Re.push(Cm(J.maxDepth)),{nodes:fe,issues:Re,next:H,closed:!1,words:ke,limited:!0};let gt=Dl(W,Ye+1,H,J,oe+1,!0),_t=gt.closed?gt.next-1:gt.next,yt={kind:"program",dialect:"powershell",source:W.slice(Ye+1,_t),span:{start:Ye+1,end:_t},status:gt.limited?"limited":gt.issues.length>0?"partial":"complete",issues:gt.issues,nodes:gt.nodes};if(fe.push({kind:"group",style:"brace",span:{start:Ye,end:gt.next},body:yt}),Re.push(...gt.issues),!gt.closed)Re.push({code:"unclosed-script-block",message:"PowerShell script block is not closed"});ke+=gt.words,Le||=gt.limited,Ye=gt.next;continue}if(Ze==="}"){Xe(),fe.push(Il(W,Ye,Ye+1)),Ye++;continue}if(Ze===">"||Ze==="<"){Te.start=Te.start===-1?Ye:Te.start;let gt=W[Ye+1]===Ze?Ye+2:Ye+1,_t=gt;while(/[ \t]/.test(W[_t]??""))_t++;let yt=_t<H?pm(W,_t,H,J,oe):void 0,At=yt?.next??gt;if(Te.redirections.push({kind:"redirection",operator:W.slice(Ye,gt),span:{start:Ye,end:At},...yt?{target:yt.word}:{}}),yt)Re.push(...yt.issues),Te.nested.push(...yt.nested),ke+=yt.words,Le||=yt.limited;Te.end=At,Ye=At;continue}if(Ze===","){Te.start=Te.start===-1?Ye:Te.start,Te.words.push(vl({text:",",raw:",",span:{start:Ye,end:Ye+1},provenance:"literal",quoted:!1})),Te.end=++Ye;continue}let tt=pm(W,Ye,H,J,oe);if(Te.start=Te.start===-1?Ye:Te.start,Te.end=tt.next,Te.words.push(tt.word),Re.push(...tt.issues),Te.nested.push(...tt.nested),ke+=1+tt.words,Le||=tt.limited,ke>J.maxWords)return Re.push({code:"word-limit",message:`command exceeds ${J.maxWords} words`}),Xe(),{nodes:fe,issues:Re,next:tt.next,closed:!1,words:ke,limited:!0};Ye=tt.next>Ye?tt.next:Ye+1}return Xe(),{nodes:fe,issues:Re,next:Ye,closed:!ie,words:ke,limited:Le}}function pm(W,G,H,J,oe){let ie="",fe="literal",Re=!1,Te=[],ke=[],Le=0,Xe=!1,Ye=(Qe)=>{let et=pC(W,Qe,H,J,oe);return ie+=W.slice(Qe,et.next),ke.push(et.program),Te.push(...et.program.issues),Le+=kl(et.program),Xe||=et.program.status==="limited",fe="command-substitution",et.next},Ze=G;while(Ze<H){let Qe=W[Ze];if(!Qe||/\s/.test(Qe)||vm(W,Ze)||Qe===">"||Qe==="<"||Qe==="#")break;if(Qe===",")break;if(Qe==="`"){let et=W[Ze+1];if(!et){Te.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),Ze++;break}ie+=et,Ze+=2;continue}if(W.startsWith("$(",Ze)){Ze=Ye(Ze);continue}if(Qe==="'"){Re=!0,Ze++;let et=!1;while(Ze<W.length){if(W[Ze]==="'"&&W[Ze+1]==="'"){ie+="'",Ze+=2;continue}if(W[Ze]==="'"){et=!0,Ze++;break}ie+=W[Ze]??"",Ze++}if(!et)Te.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(Qe==='"'){Re=!0,Ze++;let et=!1;while(Ze<H){let tt=W[Ze];if(tt==="`"&&W[Ze+1]){ie+=W[Ze+1],Ze+=2;continue}if(tt==='"'){et=!0,Ze++;break}if(W.startsWith("$(",Ze)){Ze=Ye(Ze);continue}if(tt==="$")fe=W[Ze+1]==="("?"command-substitution":"variable";ie+=tt??"",Ze++}if(!et)Te.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(Qe==="$")fe=W[Ze+1]==="("?"command-substitution":"variable";if(Qe==="@"&&Ze===G)fe="variable";ie+=Qe,Ze++}return{word:mo(W,G,Ze,ie,fe,Re,fe==="literal"?void 0:gC(W,G,Ze)),next:Ze,issues:Te,nested:ke,words:Le,limited:Xe}}function pC(W,G,H,J,oe){let ie=bm(W,G+2,H),fe=ie===-1?H:ie,Re=ie===-1?H:ie+1;if(oe>=J.maxDepth)return{program:{kind:"program",dialect:"powershell",source:W.slice(G+2,fe),span:{start:G+2,end:fe},status:"limited",issues:[Cm(J.maxDepth)],nodes:[]},next:Re};let Te=Dl(W,G+2,fe,J,oe+1),ke=ie===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:{kind:"program",dialect:"powershell",source:W.slice(G+2,fe),span:{start:G+2,end:fe},status:Te.limited?"limited":Te.issues.length+ke.length>0?"partial":"complete",issues:[...Te.issues,...ke],nodes:Te.nodes},next:Re}}function bm(W,G,H){let J=1,oe=!1,ie=!1;for(let fe=G;fe<H;fe++){let Re=W[fe];if(Re==="`"){fe++;continue}if(!ie&&Re==="'"){if(oe&&W[fe+1]==="'"){fe++;continue}oe=!oe;continue}if(!oe&&Re==='"'){ie=!ie;continue}if(oe)continue;if(W.startsWith("$(",fe)){J++,fe++;continue}if(!ie&&Re==="(")J++;if(Re!==")")continue;if(J--,J===0)return fe}return-1}function kl(W){let G=0;for(let H of W.nodes){if(H.kind==="group")G+=kl(H.body);if(H.kind==="command"){G+=H.words.length;for(let J of H.nested)G+=kl(J)}}return G}function gC(W,G,H){let J=fs(W),oe=G,ie=!1,fe=G;while(fe<H){let Re=W[fe];if(Re==="`"){fe+=2;continue}if(Re==="'"){if(ie&&W[fe+1]==="'"){fe+=2;continue}ie=!ie,fe++;continue}if(ie){fe++;continue}if(W.startsWith("$(",fe)){let Te=bm(W,fe+2,H),ke=Te===-1?H:Te+1;J.push(oe,fe,"literal"),J.push(fe,ke,"command-substitution"),fe=ke,oe=ke;continue}if(Re==="$"||Re==="@"&&fe===G){let Te=hC(W,fe+1,H);J.push(oe,fe,"literal"),J.push(fe,Te,"variable"),fe=Te,oe=Te;continue}fe++}return J.push(oe,H,"literal"),J.parts}function hC(W,G,H){if(W[G]==="{"){let oe=W.indexOf("}",G+1);return oe===-1||oe>=H?H:oe+1}let J=G;while(J<H&&/[A-Za-z0-9_:?]/.test(W[J]??""))J++;return J}function Cm(W){return{code:"depth-limit",message:`command structure exceeds parser limit ${W}`}}function Ol(W){return W.nodes.flatMap((G)=>{if(G.kind==="group")return Ol(G.body);if(G.kind!=="command")return[];return[[...G.words,...G.redirections.flatMap((H)=>H.target?[H.target]:[])].sort((H,J)=>H.span.start-J.span.start).filter((H)=>H.text!==""&&H.raw!==",").map((H)=>H.text),...G.nested.flatMap(Ol)]})}function vm(W,G){for(let H of["&&","||",";","|"])if(W.startsWith(H,G))return H;return null}function yC(W,G,H,J){if(W[G]==="#"&&W[G+1]!==">"){let fe=G+1;while(fe<H&&W[fe]!=="\r"&&W[fe]!==`
23
+ `)fe++;return{next:fe,limited:!1}}if(!W.startsWith("<#",G))return null;let oe=1,ie=G+2;while(ie<H){if(W.startsWith("<#",ie)){if(oe++,oe>J)return{next:H,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${J}`},limited:!0};ie+=2;continue}if(W.startsWith("#>",ie)){if(oe--,ie+=2,oe===0)return{next:ie,limited:!1};continue}ie++}return{next:H,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function SC(W,G){if(G)return"limited";if(W.some((H)=>H.code==="unclosed-block-comment"))return"invalid";return W.length>0?"partial":"complete"}function Il(W,G,H){return{kind:"connector",operator:W.slice(G,H),span:{start:G,end:H}}}function y(W,G="auto",H=yr){if(G==="powershell"||G==="auto"&&ym(W.slice(0,H.maxInputLength),H))return Ml(W,H);return tm(W,H)}function t(W){return W.provenance==="command-substitution"?W.raw:W.text}function re(W,G){return W==="posix"?G:Qt(G.map((H)=>H.text))}function po(W,G){return W&&W.provenance!=="unknown"?W.provenance==="literal":!/[$`*?[\]]/.test(G)}function Qt(W){return W.map((G)=>({kind:"word",text:G,raw:G,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function Nl(W,G){return{value:W,work:G}}function Tt(W,G){if(W.work)W.work.units=Math.min(Number.MAX_SAFE_INTEGER,W.work.units+1);return W.value[G]}function nn(W){return W.value.length}function si(W,G,H=1){if(W)W.units=Math.min(Number.MAX_SAFE_INTEGER,W.units+G.length*H)}function wn(W,G){si(W,G)}function Fr(W){if(!W)return!1;let G=W.charCodeAt(0);return G>=48&&G<=57||G>=65&&G<=90||G===95||G>=97&&G<=122}function Yt(W){if(!W)return!1;let G=W.charCodeAt(0);return G===9||G===10||G===11||G===12||G===13||G===32||G===160||G===65279||G===5760||G>=8192&&G<=8202||G===8232||G===8233||G===8239||G===8287||G===12288}function Ll(W){return W===`
24
+ `||W==="\r"||W==="\u2028"||W==="\u2029"}function Zt(W,G,H){if(G+H.length>nn(W))return!1;for(let J=0;J<H.length;J++)if(Tt(W,G+J)!==H[J])return!1;return!0}function ir(W,G,H){return!Fr(Tt(W,G-1))&&Zt(W,G,H)&&!Fr(Tt(W,G+H.length))}function sr(W,G){return Fr(Tt(W,G-1))!==Fr(Tt(W,G))}function cn(W){return W===`
25
+ `||W===";"||W==="&"||W==="|"}function go(W){return W==="|"||W===";"}function Cs(W,G,H){let J=Nl(W,H);if(G==="rm")return bC(J);if(G==="dd")return vC(J);return Am(J,!0)}function vs(W,G,H){let J=Nl(W,H);if(G==="rm")return EC(J);if(G==="reset-hard")return xm(J,"--ha","rd");if(G==="reset-merge")return xm(J,"--me","rge");if(G==="clean")return wC(J);if(G==="checkout")return PC(J);if(G==="push-force")return TC(J);if(G==="push-refspec")return IC(J);if(G==="push-delete")return kC(J);if(G==="branch")return OC(J);if(G==="tag")return NC(J);if(G==="restore")return LC(J);return Am(J,!1)}function bC(W){let G=!1,H=!1,J=!1,oe=-1;for(let ie=0;ie<=nn(W);ie++){let fe=Tt(W,ie);if(!G){let Te=Tt(W,ie+2);if(ir(W,ie,"rm")&&Yt(Te)&&Te!==`
26
+ `)G=!0,ie++;continue}let Re=CC(W,ie);if(fe===`
27
+ `||Re!==-1){if(G=!1,H=!1,J=!1,oe=-1,Re!==-1)ie=Re-1;continue}if(fe===";"||fe==="&"||fe==="|"||ie===nn(W)){if(oe>=0){let Te=Em(W,oe,ie);H||=Te.recursive,J||=Te.force}if(H&&J)return!0;G=!1,H=!1,J=!1,oe=-1;continue}if(Yt(fe)){if(oe<0)continue;if(Zt(W,oe,"--")&&ie-oe===2){G=!1,H=!1,J=!1,oe=-1;continue}let Te=Em(W,oe,ie);if(H||=Te.recursive,J||=Te.force,H&&J)return!0;oe=-1;continue}if(oe<0)oe=ie}return!1}function CC(W,G){if(Tt(W,G)!=="\\"||Tt(W,G-1)==="\\")return-1;if(Zt(W,G,String.raw`\n`))return G+2;if(Zt(W,G,String.raw`\x0a`)||Zt(W,G,String.raw`\x0A`))return G+5;if(Zt(W,G,String.raw`\u000a`)||Zt(W,G,String.raw`\u000A`))return G+7;return Zt(W,G,String.raw`\012`)?G+4:-1}function Em(W,G,H){if(Rm(W,G,H,"recursive"))return{recursive:!0,force:!1};if(Rm(W,G,H,"force"))return{recursive:!1,force:!0};if(Tt(W,G)!=="-"||Tt(W,G+1)==="-")return{recursive:!1,force:!1};let J=!1,oe=!1;for(let ie=G+1;ie<H;ie++){let fe=Tt(W,ie);J||=fe==="r"||fe==="R",oe||=fe==="f"||fe==="F"}return{recursive:J,force:oe}}function Rm(W,G,H,J){let oe=H-G-2;if(oe<1||oe>J.length||!Zt(W,G,"--"))return!1;for(let ie=0;ie<oe;ie++)if(Tt(W,G+ie+2)!==J[ie])return!1;return!0}function vC(W){let G=!1;for(let H=0;H<nn(W);H++){if(cn(Tt(W,H))){G=!1;continue}if(ir(W,H,"dd")){G=!0,H++;continue}if(!G||!ir(W,H,"of")||!Zt(W,H,"of=/dev/"))continue;let J=H+8;if(J<nn(W)&&!Yt(Tt(W,J))&&Tt(W,J)!=="'"&&Tt(W,J)!=='"')return!0}return!1}function EC(W){let G=!1,H=!1,J=!1;for(let oe=0;oe<=nn(W);){let ie=Tt(W,oe);if(oe===nn(W)||cn(ie)){G=!1,H=!1,J=!1,oe++;continue}let fe=_C(W,oe);if(fe>=0){if(RC(W,fe))return!0;let Re=fe,Te=!1;while(Yt(Tt(W,Re)))Te||=Tt(W,Re)===`
28
+ `,Re++;if(Te)H=!1,J=!1;G=!0,oe=Re;continue}if(!G){oe++;continue}if(Zt(W,oe,"--")&&(oe===0||Yt(Tt(W,oe-1)))&&(!Tt(W,oe+2)||Yt(Tt(W,oe+2))||cn(Tt(W,oe+2)))){G=!1,H=!1,J=!1,oe+=2;continue}if(H||=Zt(W,oe,"--recursive")&&sr(W,oe+11)||Wl(W,oe,"recursive"),J||=Zt(W,oe,"--force")&&sr(W,oe+7)||Wl(W,oe,"force"),H&&J)return!0;oe++}return!1}function Wl(W,G,H){if(!Zt(W,G,"--"))return!1;let J=0;while(J<=H.length){let oe=Tt(W,G+J+2);if(!oe||Yt(oe)||cn(oe))break;if(oe!==H[J])return!1;J++}return J>0&&sr(W,G+J+2)}function RC(W,G){let H=G,J=!1,oe=!1;while(H<nn(W)){while(Yt(Tt(W,H)))H++;let ie=H;while(H<nn(W)&&!Yt(Tt(W,H)))H++;if(Tt(W,ie)!=="-"||H-ie===2&&Zt(W,ie,"--"))return!1;let fe=_m(W,ie,"recursive"),Re=_m(W,ie,"force");if(J&&Re||oe&&fe)return!0;if(J||=fe,oe||=Re,Tt(W,ie+1)==="-")continue;let Te=xC(W,ie,H);if(Te.combined||J&&Te.forceAtBoundary||oe&&Te.recursiveAtBoundary)return!0;J||=Te.recursive,oe||=Te.force}return!1}function _m(W,G,H){return Zt(W,G,`--${H}`)&&sr(W,G+H.length+2)||Wl(W,G,H)}function _C(W,G){if(G>0&&Fr(Tt(W,G-1)))return-1;let H=G;if(Tt(W,H)==="\\")H++;if(Tt(W,H)!=="r")return-1;if(H++,Tt(W,H)==="\\")H++;if(Tt(W,H)!=="m"||!Yt(Tt(W,H+1)))return-1;return H+1}function xC(W,G,H){let J=!1,oe=!1,ie=!1,fe=!1,Re=!1;if(Tt(W,G)!=="-")return{recursive:J,force:oe,recursiveAtBoundary:ie,forceAtBoundary:fe,combined:Re};let Te="";for(let ke=G+1;ke<H;ke++){let Le=Tt(W,ke)??"",Xe=(Le==="r"||Le==="f")&&sr(W,ke+1);J||=Le==="r",oe||=Le==="f",ie||=Le==="r"&&Xe,fe||=Le==="f"&&Xe,Re||=(Te==="r"&&Le==="f"||Te==="f"&&Le==="r")&&Xe,Te=Le}return{recursive:J,force:oe,recursiveAtBoundary:ie,forceAtBoundary:fe,combined:Re}}function xm(W,G,H){return li(W,"reset",go,!0,(J)=>Tt(W,J)==="-"&&ho(W,J,G,H)?!0:J)}function wC(W){return li(W,"clean",go,!0,(G)=>{if(Tt(W,G)!=="-")return G;if(ho(W,G,"--fo","rce"))return!0;let H=ai(W,G,go);for(let J=G+1;J<H;J++)if(Tt(W,J)==="f")return!0;return H-1})}function Es(W,G,H){if(!ir(W,G,"git"))return null;let J=G+3;if(!Yt(Tt(W,J)))return{commandEnd:-1,next:J};while(Yt(Tt(W,J)))J++;while(J<nn(W)){if(cn(Tt(W,J)))return{commandEnd:-1,next:J};let oe=ai(W,J,cn);if(ir(W,J,H))return{commandEnd:J+H.length,next:oe};if(Tt(W,J)!=="-")return{commandEnd:-1,next:oe};let ie=oe-J===2&&Zt(W,J,"--"),fe=AC(W,J,oe);J=oe;while(Yt(Tt(W,J)))J++;if(ie)return{commandEnd:ir(W,J,H)?J+H.length:-1,next:ai(W,J,cn)};if(!fe)continue;if(J>=nn(W)||cn(Tt(W,J)))return{commandEnd:-1,next:J};J=ai(W,J,cn);while(Yt(Tt(W,J)))J++}return{commandEnd:-1,next:J}}function AC(W,G,H){for(let J of _n)if(H-G===J.length&&Zt(W,G,J))return!0;return!1}function PC(W){return wm(W,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function TC(W){return li(W,"push",go,!0,(G)=>{if(Tt(W,G)!=="-")return G;if(Tt(W,G+1)==="f"&&!Fr(Tt(W,G+2))&&!Zt(W,G+2,"-with-lease"))return!0;let H=Pm(W,G,"--fo","rce");if(H>=0&&!Zt(W,H,"-with-lease"))return!0;return G})}function IC(W){return li(W,"push",cn,!1,(G)=>{if(Yt(Tt(W,G))&&Tt(W,G+1)==="+"&&G+2<nn(W)&&!cn(Tt(W,G+2))&&!Yt(Tt(W,G+2)))return!0;if(Tt(W,G)===":"&&Tt(W,G+1)==="+")return!0;return G})}function kC(W){return li(W,"push",cn,!1,(G)=>{if(Tt(W,G)==="-"&&ho(W,G,"--de","lete"))return!0;if(Yt(Tt(W,G))&&Tt(W,G+1)===":"&&G+2<nn(W)&&!Yt(Tt(W,G+2))&&!cn(Tt(W,G+2)))return!0;return G})}function OC(W){let G=!1,H=!1,J=!1;for(let oe=0;oe<=nn(W);oe++){if(oe===nn(W)||cn(Tt(W,oe))){if(H&&J)return!0;G=!1,H=!1,J=!1;continue}if(!G){let Re=Es(W,oe,"branch");if(Re){G=Re.commandEnd>=0,oe=Math.max(oe,(G?Re.commandEnd:Re.next)-1);continue}}if(!G||Tt(W,oe)!=="-")continue;let ie=ai(W,oe,cn),fe=MC(W,oe,ie);if(H||=fe.deletion,J||=fe.force,H&&J)return!0;oe=ie-1}return!1}function MC(W,G,H){let J=!1,oe=!1;for(let ie=G;ie<H;ie++){if(Tt(W,ie)!=="-")continue;if(ho(W,ie,"--de","lete"))J=!0;if(ho(W,ie,"--fo","rce"))oe=!0;if(Tt(W,ie+1)==="-")continue;let fe=ie+1,Re=!1,Te=!1,ke=!1;while(fe<H&&DC(Tt(W,fe))){let Le=Tt(W,fe);Re||=Le==="d"||Le==="D",Te||=Le==="f",ke||=Le==="D",fe++}if(!sr(W,fe))continue;J||=Re,oe||=Te||ke}return{deletion:J,force:oe}}function DC(W){if(!W)return!1;let G=W.charCodeAt(0);return G>=65&&G<=90||G>=97&&G<=122}function NC(W){return wm(W,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function wm(W,G){let H=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let J=0;J<nn(W);J++){let oe=Tt(W,J),ie=H[H.length-1];if(!ie)return!1;let fe=ie.escaped;if(ie.escaped=!fe&&ie.quote!=="'"&&oe==="\\",!fe&&oe==="'"&&ie.quote!=='"')ie.quote=ie.quote==="'"?"":"'";if(!fe&&oe==='"'&&ie.quote!=="'")ie.quote=ie.quote==='"'?"":'"';if(oe==="$"&&Tt(W,J+1)==="("&&(H.length===1||!fe&&ie.quote!=="'")){H.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),J++;continue}if(!fe&&!ie.quote&&H.length>1&&oe==="("){ie.depth++;continue}if(!fe&&!ie.quote&&H.length>1&&oe===")"){if(ie.depth--,ie.depth===0)H.pop();continue}if(Yt(oe))ie.shortActive=!1,ie.hasShortFlag=!1;if(!ie.outerActive){let Re=Es(W,J,G.command);if(Re){ie.outerActive=Re.commandEnd>=0&&Yt(Tt(W,Re.commandEnd)),ie.shortActive=!1,ie.hasShortFlag=!1,J=Math.max(J,(ie.outerActive?Re.commandEnd:Re.next)-1);continue}}if(ie.outerActive&&oe==="-"){if(ho(W,J,G.longPrefix,G.longOptional))return!0;ie.shortActive||=!G.excludedShortStarts.includes(Tt(W,J+1)??"")}if(ie.hasShortFlag||=ie.shortActive&&oe===G.shortFlag,ie.hasShortFlag&&sr(W,J+1))return!0;if(go(oe))ie.outerActive=!1}return!1}function li(W,G,H,J,oe){let ie=!1;for(let fe=0;fe<nn(W);fe++){let Re=Tt(W,fe),Te=H(Re);if(!ie&&!Te){let ke=Es(W,fe,G);if(ke){ie=ke.commandEnd>=0&&(!J||Yt(Tt(W,ke.commandEnd))),fe=Math.max(fe,(ie?ke.commandEnd:ke.next)-1);continue}}if(ie){let ke=oe(fe);if(ke===!0)return!0;for(let Le=fe;Le<=ke;Le++)if(H(Tt(W,Le)))ie=!1;fe=ke}if(Te)ie=!1}return!1}function LC(W){let G=!1;for(let H=0;H<nn(W);H++){if(Ll(Tt(W,H))){if(G)return!0;G=!1;continue}if(!G){let J=Es(W,H,"restore");if(J){G=J.commandEnd>=0,H=Math.max(H,(G?J.commandEnd:J.next)-1);continue}}if(G&&Tt(W,H)==="-"&&Tt(W,H+1)==="-"&&(Zt(W,H+2,"staged")||Zt(W,H+2,"help")))G=!1}return G}function Am(W,G){let H=!1;for(let J=0;J<nn(W);J++){let oe=Tt(W,J),ie=G?Ll(oe):cn(oe);if(H&&Yt(oe)&&Tt(W,J+1)==="-"&&ir(W,J+2,"delete"))return!0;if(ie){H=!1;continue}if(ir(W,J,"find"))H=!0,J+=3}return!1}function ai(W,G,H){let J=G;while(J<nn(W)&&!Yt(Tt(W,J))&&!H(Tt(W,J)))J++;return J}function Pm(W,G,H,J){if(!Zt(W,G,H))return-1;let oe=G+H.length;for(let ie=0;ie<J.length&&Tt(W,oe)===J[ie];ie++)oe++;return sr(W,oe)?oe:-1}function ho(W,G,H,J){return Pm(W,G,H,J)>=0}function Nn(W,G){si(G,W,2);let H=W.toLowerCase(),J=H.trimStart(),oe=J.startsWith("echo ")||J.startsWith("rg "),ie=[{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 fe of ie){if(fe.skipForEchoRg&&oe)continue;let Re=fe.caseSensitive?W:H;if(fe.regex)wn(G,Re);if((fe.regex?.test(Re)??!1)||fe.scan&&vs(Re,fe.scan,G))return Pt("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${fe.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var WC=/^[A-Za-z_][A-Za-z0-9_]*=/;function Im(W,G,H){let J=W.words[0];if(!G||!J||W.words.length!==1||W.dialect!=="posix")return!1;if(!J.quoted||J.provenance!=="literal")return!1;let oe=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(J.text)?.[1];if(!oe)return!1;si(H,G.source,2);let ie={anchored:new RegExp(`^\\$\\{?${oe}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${oe}(?![A-Za-z0-9_])`)};return km(G.nodes,J,ie)}function km(W,G,H){return W.every((J)=>{if(J.kind==="connector")return!0;if(J.kind==="group"||J.kind==="function")return km(J.body.nodes,G,H);if(J.kind==="unknown")return!H.loose.test(J.source);return GC(J,G,H)})}function GC(W,G,H){if(W.nested.some((oe)=>H.loose.test(oe.source)))return!1;let J=W.words.findIndex((oe)=>!WC.test(oe.text));return W.words.every((oe,ie)=>oe===G||Tm(oe.raw,H.anchored,ie!==J))&&W.redirections.every((oe)=>(!oe.heredoc||oe.heredoc.quotedDelimiter||!H.loose.test(oe.heredoc.body))&&(!oe.target||Tm(oe.target.raw,H.anchored,!0)))}function Tm(W,G,H){let J=!1,oe=!1;for(let ie=0;ie<W.length;ie++){let fe=W[ie];if(fe==="\\"&&!J){ie++;continue}if(!oe&&fe==="'"){J=!J;continue}if(!J&&fe==='"'){oe=!oe;continue}if(J||fe!=="$")continue;if(!G.test(W.slice(ie)))continue;if(!oe||!H)return!1}return!0}var FC="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",zC="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",$C="This erases or repartitions a disk. Run disk erase and partition commands manually after confirming the target.",BC="This output redirect overwrites a disk device. Run device writes manually after confirming the target.",UC="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.",HC=new Set(["of=/dev/null","of=/dev/zero","of=/dev/full"]),Om=/^(?:mkfs(?:\..+)?|mke2fs|newfs(?:_.+)?)$/,jC=new Set(["diskutil","wipefs","sgdisk","parted"]),VC=new Set(["erasedisk","erasevolume","reformat","partitiondisk","zerodisk","randomdisk","secureerase"]),KC=/^(?:-[^-]*[ao]|--all$|--offset(?:=|$))/,qC=new Set(["-p","--print","-i","--info","-v","--verify","-O","--print-mbr","-E","--end-of-largest","-F","--first-in-largest","-f","--first-aligned-in-largest","-D","--display-alignment","-L","--list-types","-P","--pretend","-b","--backup","-V","--version","-?","--help","--usage"]),YC=new Set(["p","v","O","E","F","f","D","L","P","V","?"]),ZC=new Set(["i","b"]),XC=/^\/dev\/(?:r?disk\d|sd[a-z]|hd[a-z]|vd[a-z]|xvd[a-z]|nvme\d|mmcblk\d|md\d|dm-\d|loop\d|mapper\/|disk\/)/,JC=new Set([">",">|",">>","<>",">&"]),QC=new Set(["mklabel","mktable","mkpart","rm","resizepart"]);function Mm(W){return W==="dd"||W==="shred"||Om.test(W)||jC.has(W)}function ev(W,G){let H=G.some((J)=>J.startsWith("/dev/"));if(W==="diskutil"){let J=G.find((oe)=>!oe.startsWith("-"));return J!==void 0&&VC.has(J.toLowerCase())}if(W==="wipefs")return H&&G.some((J)=>KC.test(J));if(W==="sgdisk")return H&&G.some((J)=>J.startsWith("-")&&!tv(J));return W==="parted"&&H&&G.some((J)=>QC.has(J.toLowerCase()))}function tv(W){if(qC.has(W.split("=",1)[0]??W))return!0;if(W.startsWith("--"))return!1;let G=W.slice(1).split("");return ZC.has(G[0]??"")||G.every((H)=>YC.has(H))}function Dm(W,G){let H=G.slice(1);if(W==="dd"&&H.some((J)=>/^of=\/dev\/.+/.test(J)&&!HC.has(J)))return Pt("dd.device-write",FC);if(Om.test(W)&&H.some((J)=>J.startsWith("/dev/")))return Pt("mkfs.device",zC);if(ev(W,H))return Pt("disk.erase",$C);if(W==="shred"&&H.length>0)return Pt("shred.target",UC);return null}function Nm(W){return W.some((G)=>JC.has(G.operator)&&G.target?.provenance==="literal"&&XC.test(G.target.text))?Pt("redirect.block-device",BC):null}import{isAbsolute as nv,resolve as Lm}from"node:path";function ci(W,G,H,J){let oe=nv(W)?Lm(W):G?Lm(G,W):void 0;if(!oe)return;try{return Bt(oe,H,J)}catch{return oe}}function Wm(W){return!["/dev","/proc","/sys"].some((G)=>W===G||W.startsWith(`${G}/`))}var yo="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",di="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.",Fl=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),rv=new Set(["-p","--print"]),ov=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),iv=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"])]]),sv=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),av=new Map([["python",new Set(["m"])]]),lv=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"])]]),cv=new Set(["always","default","never"]),dv=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),uv=/\\\r?\n/g,mv=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 Gm(W){return _s(W).code}function Rs(W){return _s(W).sources}function Fm(W){return mv.get($l(W))??[]}function _s(W){let G=$l(W[0]??"");if(!Fl.has(G))return{code:null,sources:[],optionsOpen:!1};let H=[],J=[],oe=!0;for(let ie=1;ie<W.length;ie++){let fe=W[ie];if(fe===void 0)break;if(fe==="--")return Un(G,H,J,oe,W[ie+1]===void 0?void 0:ie+1,W[ie+1]);if(fe===""||fe==="-"||!fe.startsWith("-"))return Un(G,H,J,oe,ie,fe);if(G==="node"&&rv.has(fe)){let Xe=W[ie+1];if(Xe===void 0)return Un(G,H,J,oe);if(Xe.startsWith("-"))continue;H.push({tokenIndex:ie+1,value:Xe}),J.push({tokenIndex:ie+1,kind:"inline-code",value:Xe}),ie++;continue}if(pv(G,fe)){let Xe=W[ie+1];if(Xe===void 0)return Un(G,H,J,oe);if(H.push({tokenIndex:ie+1,value:Xe}),J.push({tokenIndex:ie+1,kind:"inline-code",value:Xe}),G==="python")return Un(G,H,J,oe);ie++;continue}let Re=/^--eval=(.*)$/s.exec(fe);if(gv(G)&&Re){let Xe=Re[1]??"";H.push({tokenIndex:ie,value:Xe}),J.push({tokenIndex:ie,kind:"inline-code",value:Xe});continue}if(G==="node"){let Xe=fv(fe);if(Xe){if(Xe.attached){if(oe&&=Xe.value!=="",Xe.value!=="")J.push({tokenIndex:ie,kind:"module-file",value:Xe.value});continue}let Ye=W[ie+1];if(Ye===void 0||Ye.startsWith("-"))return oe=!1,Un(G,H,J,oe);J.push({tokenIndex:ie+1,kind:"module-file",value:Ye}),ie++;continue}}if(G==="python"&&fe.startsWith("--check-hash-based-pycs=")||G==="node"&&(fe==="--conditions="||fe==="--diagnostic-dir="||fe==="--title=")||G==="ruby"&&(fe==="--disable="||fe==="--enable="))return Un(G,H,J,oe);if(lv.get(G)?.has(fe)){let Xe=W[ie+1];if(Xe===void 0||Xe.startsWith("-")&&!(G==="ruby"&&dv.has(fe))||G==="python"&&!cv.has(Xe))return Un(G,H,J,oe);ie++;continue}if(fe.startsWith("--"))continue;let Te,ke=!1;for(let Xe=1;Xe<fe.length;Xe++){let Ye=fe[Xe];if(Ye===void 0)break;if(av.get(G)?.has(Ye)){let Ze=fe.slice(Xe+1),Qe=Ze||W[ie+1];if(Qe!==void 0)J.push({tokenIndex:Ze?ie:ie+1,kind:"module-file",value:Qe});return Un(G,H,J,oe)}if(ov.get(G)?.has(Ye)){Te=fe.slice(Xe+1)||W[ie+1],ke=Xe+1===fe.length;break}if(G==="node"&&Ye==="r"){if(oe&&=fe==="-r",fe==="-r"){let Ze=W[ie+1];if(oe&&=Ze!==void 0&&!Ze.startsWith("-"),oe&&Ze!==void 0)J.push({tokenIndex:ie+1,kind:"module-file",value:Ze});ie++}break}if(G==="ruby"&&Ye==="r"){let Ze=fe.slice(Xe+1),Qe=Ze||W[ie+1];if(oe&&=Qe!==void 0,Qe!==void 0)J.push({tokenIndex:Ze?ie:ie+1,kind:"module-file",value:Qe});if(!Ze)ie++;break}if(G==="perl"&&(Ye==="M"||Ye==="m")){let Ze=fe.slice(Xe+1);if(!Ze){if(oe=!1,Xe+1===fe.length)ie++;break}J.push({tokenIndex:ie,kind:"module-file",value:Ze});break}if(iv.get(G)?.has(Ye)){if(Xe+1===fe.length)ie++;break}if(sv.get(G)?.has(Ye)&&Xe+1<fe.length)break}if(Te===void 0)continue;let Le=ke?ie+1:ie;if(H.push({tokenIndex:Le,value:Te}),J.push({tokenIndex:Le,kind:"inline-code",value:Te}),G==="python")return Un(G,H,J,oe);if(ke)ie++}return Un(G,H,J,oe,void 0,void 0,!0)}function Un(W,G,H,J,oe,ie,fe=!1){let Re=W==="node"?G.slice(-1):G,Te=new Set(Re.map((Le)=>Le.tokenIndex)),ke=H.filter((Le)=>Le.kind!=="inline-code"||Te.has(Le.tokenIndex));if(J&&G.length===0&&oe!==void 0&&ie!==void 0)ke.push({tokenIndex:oe,kind:"main-script",value:ie});return{code:(W==="node"?Re[0]?.value:Re.map((Le)=>Le.value).join(`
29
+ `))||null,sources:J?ke:[],optionsOpen:J&&fe}}function fv(W){for(let G of["--import","--loader","--experimental-loader","--require"]){if(W===G)return{attached:!1,value:""};if(W.startsWith(`${G}=`))return{attached:!0,value:W.slice(G.length+1)}}return}function zl(W,G){return $l(W)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(G)}function $l(W){let G=Ft(W).toLowerCase();return Xi.test(G)?"python":G}function pv(W,G){return Fl.get(W)?.has(G)??!1}function gv(W){return Fl.get(W)?.has("--eval")??!1}function ui(W,G,H=!1){let J=Sv(W,G);if(!Gl(J,G))return!1;wn(G,J);let oe=yv(J);if(Gl(oe,G))return!0;if(wn(G,oe),!zm.test(oe))return!1;return!H||hv(J,G)}function hv(W,G){if(/`|%x|\bqx\b/.test(W))return!0;let J=W.split(""),oe=[];for(let Te=0;Te<W.length;Te++){let ke=W[Te];if(ke!=="'"&&ke!=='"')continue;let Le=W.startsWith(ke.repeat(3),Te)?ke.repeat(3):ke,Xe=Te+Le.length,Ye=Xe;while(Ye<W.length&&!W.startsWith(Le,Ye))Ye+=W[Ye]==="\\"?2:1;if(Ye>=W.length)return!0;oe.push({start:Xe,text:W.slice(Xe,Ye)}),J.fill(" ",Te,Ye+Le.length),Te=Ye+Le.length-1}let ie=J.join(""),fe=Array.from(ie.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((Te)=>zm.test(Te[1]??"")).map((Te)=>{let ke=Te.index+Te[0].length;return{start:ke,end:xs(ie,ke)}});if(fe.some((Te)=>Bl(ie,Te.start)))return!0;return oe.some((Te)=>{let ke=/\b(?:system|exec|spawn|popen)\s*$/.test(ie.slice(0,Te.start)),Le=fe.some((Xe)=>Te.start>=Xe.start&&Te.start<Xe.end);return(ke||Le)&&Gl(Te.text,G)})}function xs(W,G){let H=1;for(let J=G;J<W.length;J++){if(W[J]==="(")H++;if(W[J]===")")H--;if(H===0)return J}return W.length}function Bl(W,G){let H=0;for(let J=G;J<W.length;J++){let oe=W[J]??"";if("([{".includes(oe))H++;if(")]}".includes(oe)&&H--===0)return!1;if(oe===","&&H===0)return!1;if(/[A-Za-z_$]/.test(oe))return!0}return!1}var zm=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function yv(W){let G=[],H=0,J=0;while(J<W.length){let oe=W[J];if(oe!=="'"&&oe!=='"'){J++;continue}let ie=W.startsWith(oe.repeat(3),J)?oe.repeat(3):oe,fe=J+ie.length;while(fe<W.length&&!W.startsWith(ie,fe))fe+=W[fe]==="\\"?2:1;if(fe>=W.length)break;G.push(W.slice(H,J)," "),J=fe+ie.length,H=J}return G.push(W.slice(H)),G.join("")}function Gl(W,G){if(Cs(W,"rm",G))return!0;for(let J of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(wn(G,W),J.test(W))return!0;if(Cs(W,"dd",G))return!0;for(let J of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(wn(G,W),J.test(W))return!0;if(Cs(W,"find",G))return!0;let H=W.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((J)=>(wn(G,W),H.some((oe)=>vs(oe,J))))}function Sv(W,G){return wn(G,W),W.replace(uv,"")}import{lstatSync as gE,readdirSync as hE}from"node:fs";import{basename as yE,isAbsolute as ff,join as SE,relative as pf}from"node:path";import{isAbsolute as Km,parse as Pv}from"node:path";import{dirname as bv,isAbsolute as Cv,parse as vv,sep as Ev}from"node:path";function Sr(W,G,H){if(rr(G))throw Error("Unsupported Windows namespace path");let J=Cv(G)?vv(G).root:"",oe=J||W;for(let ie of _v(J?G.slice(J.length):G)){if(ie===""||ie===".")continue;if(ie===".."){oe=bv(oe);continue}let fe=Rv(oe,ie),Re=H.entryKind(fe),Te=Re==="symlink"?H.realpath(fe):fe;if(Re==="missing"||Te===null)throw Error(`Cannot resolve path component: ${fe}`);oe=Te}return oe}function Rv(W,G){return W.endsWith("/")||W.endsWith("\\")?`${W}${G}`:`${W}${Ev}${G}`}function _v(W){let G=process.platform==="win32"?/[\\/]+/:/\/+/;return W.split(G)}var Ul=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],xv=new Set(Ul),wv=1024,$m=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),Bm=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),Av=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ws(W){return xv.has(W)}function Hl(W){return ws(W)||$m.has(W)||Bm.has(W)||Uo(W)}function ar(W,G,H){return H?.has(W)?H.get(W):G.get(W)}function Um(W,G){let H=ar("GIT_CONFIG_COUNT",W,G);if(H===void 0)return{state:"absent"};if(H==="")return{state:"valid",count:0};if(!/^\d+$/.test(H))return{state:"invalid"};let J=Number(H);return Number.isSafeInteger(J)&&J<=wv?{state:"valid",count:J}:{state:"invalid"}}function As(W,G,H){let oe=W.match(Av)?.[1];if(!oe||!Hl(oe))return null;let ie=W.indexOf("=");return{name:oe,value:`${ar(oe,G,H)??""}${W.slice(ie+1)}`}}function Hm(W){return Vm(W,Bm)}function jm(W){return Vm(W,$m)}function Vm(W,G){if(!W)return!1;for(let H of W.keys())if(G.has(H))return!0;return!1}var Ym=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ln(W){if(!Ym.test(W))return null;let G=W.indexOf("=");return{name:W.slice(0,G),value:W.slice(G+1)}}function Ce(W){let G=new Map,H=0;while(H<W.length){let J=W[H];if(!J)break;let oe=Ln(t(J));if(!oe)break;G.set(oe.name,oe.value),H++}return{words:W.slice(H),envAssignments:G}}function Zm(W){let G=zt(W);return W.includes("=")||G==="sudo"||G==="env"||G==="command"||G==="builtin"}function zr(W,G,H,J){if(!Zm(So(W)))return{words:W,envAssignments:new Map,cwd:H,rewritten:!1};let oe=new Set(W),ie=W,fe=new Map,Re=new Map(J??[]),Te=[],ke=H;for(let Xe=0;Xe<a.wrapperPeelIterations.cap;Xe++){let Ye=qm(ie),Ze=Ce(ie);for(let[et,tt]of Ze.envAssignments)fe.set(et,tt),Re.set(et,tt);if(ie=Ze.words,ie.length===0)break;while(ie.length>0&&So(ie).includes("=")&&!Iv(ie)){let et=kv(So(ie),Re,G.env)??As(So(ie),G.env,Re);if(et)fe.set(et.name,et.value),Re.set(et.name,et.value);ie=ie.slice(1)}if(ie.length===0)break;let Qe=zt(So(ie));if(Qe!=="sudo"&&Qe!=="env"&&Qe!=="command"&&Qe!=="builtin")break;if(Qe==="sudo"){let et=Mv(ie,G.paths,ke);if(ie=et.words,et.cwd!==void 0)ke=et.cwd}if(Qe==="env"){let et=Lv(ie,ke,Re,G);if(Te.push(...et.envSplitValues??[]),ie=et.words,et.cwd!==void 0)ke=et.cwd;for(let[tt,gt]of et.envAssignments)fe.set(tt,gt),Re.set(tt,gt)}if(Qe==="command")ie=Wv(ie);if(Qe==="builtin")ie=ie.slice(Hn(ie,1)==="--"?2:1);if(qm(ie)===Ye)break}let Le=Ce(ie);for(let[Xe,Ye]of Le.envAssignments)fe.set(Xe,Ye),Re.set(Xe,Ye);return{words:Le.words,envAssignments:fe,cwd:ke,envSplitValues:Te.length>0?Te:void 0,rewritten:Tv(Le.words,oe)}}function Tv(W,G){return W.some((H)=>!G.has(H))}function qm(W){return W.map(t).join(" ")}function So(W){let G=W[0];return G?t(G):""}function Hn(W,G){let H=W[G];return H?t(H):void 0}function Iv(W){return Ym.test(So(W))}function kv(W,G,H){if(!W.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${G.get("TMPDIR")??H.get("TMPDIR")??""}${W.slice(8)}`}}var Ov=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function Mv(W,G,H){let J=1,oe=H;while(J<W.length){let ie=Hn(W,J);if(!ie)break;if(ie==="--")return{words:W.slice(J+1),cwd:oe};if(!ie.startsWith("-"))break;if(ie==="-D"||ie==="--chdir"){let fe=Hn(W,J+1);oe=fe?mi(oe,fe,G):null,J+=2;continue}if(ie.startsWith("--chdir=")){oe=mi(oe,ie.slice(8),G),J++;continue}if(ie.startsWith("-D")&&ie.length>2){oe=mi(oe,ie.slice(2),G),J++;continue}if(ie==="-i"||ie==="--login"){oe=null,J++;continue}if(Ov.has(ie)){J+=2;continue}J++}return{words:W.slice(J),cwd:oe}}var Dv=new Set(["-i","-0","--null"]),Nv=new Set(["-u","--unset","-C","--chdir","-P"]);function Lv(W,G,H,J){let oe=new Map,ie=[],fe=G,Re=1,Te=(ke)=>({words:W.slice(ke),envAssignments:oe,cwd:fe,envSplitValues:ie.length>0?ie:void 0});while(Re<W.length){let ke=Hn(W,Re);if(!ke)break;if(ke==="--")return Te(Re+1);if(ke==="-i"||ke==="--ignore-environment"||ke==="-"){oe.clear();for(let Xe of H.keys())oe.set(Xe,"");oe.set("TMPDIR",""),Re++;continue}if(Dv.has(ke)){Re++;continue}if(ke==="-u"||ke==="--unset"){let Xe=Hn(W,Re+1);if(Xe!==void 0)oe.set(Xe,"");Re+=2;continue}if(ke.startsWith("-u")&&ke.length>2&&!ke.startsWith("-u=")){oe.set(ke.slice(2),""),Re++;continue}if(ke.startsWith("--unset=")){oe.set(ke.slice(8),""),Re++;continue}let Le=ke==="-S"||ke==="--split-string"?{value:Hn(W,Re+1),consumed:2}:ke.startsWith("-S")&&ke.length>2?{value:ke.slice(2),consumed:1}:ke.startsWith("--split-string=")?{value:ke.slice(15),consumed:1}:null;if(Le){if(Le.value!==void 0)ie.push(Le.value);return fe=null,Te(Re+Le.consumed)}if(Nv.has(ke)){if(ke==="-C"||ke==="--chdir"){let Xe=Hn(W,Re+1);fe=Xe?mi(fe,Xe,J.paths):null}Re+=2;continue}if(ke.startsWith("-u=")){Re++;continue}if(ke.startsWith("-C")&&ke.length>2||ke.startsWith("--chdir=")){let Xe=ke.startsWith("--chdir=")?ke.slice(8):ke.startsWith("-C=")?ke.slice(3):ke.slice(2);fe=mi(fe,Xe,J.paths),Re++;continue}if(ke.startsWith("-P")){Re++;continue}if(ke.startsWith("-")){Re++;continue}if(!Ln(ke))break;while(Re<W.length){let Xe=Ln(Hn(W,Re)??"");if(!Xe)break;oe.set(Xe.name,Xe.value),Re++}if(Hn(W,Re)==="--")Re++;return Te(Re)}return Te(Re)}function mi(W,G,H){if(G==="")return null;if(!W&&!Km(G))return null;let J=Km(G)?Pv(G).root:H.realpath(W??"/");if(J===null)return null;try{return Sr(J,G,H)}catch{return null}}function Wv(W){if(Hn(W,1)==="-v")return[...Qt(["type"]),...W.slice(2)];let G=1;while(G<W.length){let H=Hn(W,G);if(!H)break;if(H==="-p"||H==="-v"||H==="-V"){G++;continue}if(H==="--")return W.slice(G+1);if(H.startsWith("-")&&!H.startsWith("--")&&H.length>1){if(!/^[pvV]+$/.test(H.slice(1)))break;G++;continue}break}return W.slice(G)}var Gv=/['"\\$`{}#]/;function Ps(W,G){if(W.some((J)=>Gv.test(J)))return null;let H=[...W.flatMap((J)=>J.split(/\s+/).filter((oe)=>oe.length>0)),...G];return H.length<=64?H:null}function br(W,G,H){return Ts(W,G,H).tokens}function Fv(W){let G=[],H="",J=0;while(J<W.length){let oe=W.charAt(J);if(oe==='"'||oe==="'"){let ie=W.indexOf(oe,J+1);if(ie===-1)return W.split(/\s+/).map((fe)=>fe.replace(/["']/g,"")).filter((fe)=>fe.length>0);H+=W.slice(J+1,ie),J=ie+1;continue}if(/\s/.test(oe)){if(H.length>0)G.push(H);H="",J++;continue}H+=oe,J++}if(H.length>0)G.push(H);return G}function Cr(W,G,H,J=0){let oe=Ts(W,G,H),ie=(oe.envSplitValues??[]).flatMap(Fv);if(ie.length===0)return oe.tokens;let fe=[...ie,...oe.tokens];if(J>=8)return fe;return Cr(fe,G,H,J+1)}function Ts(W,G,H,J){if(!Zm(W[0]??""))return{tokens:[...W],envAssignments:new Map,cwd:H};let oe=zr(Qt(W),G,H,J);return{tokens:oe.words.map(t),envAssignments:oe.envAssignments,cwd:oe.cwd,envSplitValues:oe.envSplitValues}}var Kl=Symbol("adopt-as-operand"),zv=new Set(["env","sudo","command","builtin"]),$v=new Set(["&&","||","|&","|","&",";"]),Bv=new Set(["<<","<<<",">|"]),Xm=new Set(["|","|&"]),Uv=/[*@#?$!_-]/,Hv=/^\w+(?::\w+)*/,jv=Object.freeze([]),fi=Object.freeze({kind:"scope",edge:"enter"}),pi=Object.freeze({kind:"scope",edge:"exit"}),Vv=Object.freeze([]),Kv=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),gi=new Set(["bash","sh","zsh","dash","ksh"]),qv=256,nf=new WeakMap;function rf(W,G){let H=G.status==="complete"?new Set(Vl(G)):new Set,J=Xv(W,H);if(Qi(J))return Is("unclosed-quote",J,G);let oe={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},ie=$r(G,{source:J,suppressed:H,flags:oe,depth:0,functions:new Map,powershell:G.dialect==="powershell"});if(oe.limited)return Is("structural-limit",J,G);if(oe.invalid)return Is("invalid",J,G);let fe=Is("complete",J,G,oe.assignmentFallbacks);return nf.set(fe,Object.freeze(ie)),fe}function Ms(W,G,H,J,oe){let ie=oe.word??((Qe)=>Qe),fe={cwd:G,variables:new Map,previous:null},Re=[],Te=new Set,ke=null,Le=[],Xe=of(W),Ye=Xe.findLastIndex((Qe)=>Qe.kind==="operator"&&Xm.has(Qe.operator)),Ze=Ye!==-1&&Xe.some((Qe)=>Qe.kind==="redirection"&&Qe.operator==="<<"&&Qe.body===void 0);for(let[Qe,et]of Xe.entries()){let tt=Ze||Qe<=Ye;if(et.kind==="scope"){if(et.edge==="enter"){Le.push({state:fe,segment:[...Re],shellWords:new Set(Te),pipeProducer:ke});continue}let gt=oe.segment(Re,fe,ke,null,Te,tt);if(gt)return gt;let _t=Le.pop();if(_t===void 0)throw Error("scope exit without a matching enter");fe=_t.state,Re=_t.segment,Te=_t.shellWords,ke=_t.pipeProducer;continue}if(et.kind==="operator"){if(!et.boundary)continue;let gt=oe.segment(Re,fe,ke,et.operator,Te,tt);if(gt)return gt;fe=Yv(Re,fe,H,J),ke=Re.length>0&&Xm.has(et.operator)?Re:null,Re=[],Te=new Set;continue}if(et.kind==="redirection"){if(et.fd!==void 0)Te.add(Re.length-1);if(et.target===void 0)continue;let gt=oe.redirection({operator:et.operator,role:et.role,targetOrder:et.targetOrder,target:et.target,...et.body===void 0?{}:{body:et.body,consumer:et.consumer}},fe,tt);if(gt===Kl){Te.add(Re.length),Re.push(ie(et.target));continue}if(gt)return gt;continue}Re.push(ie(et.text))}return oe.segment(Re,fe,ke,null,Te,Ze)}function Ds(W){return of(W).flatMap((G)=>{if(G.kind==="word")return[{kind:"word",text:G.text}];if(G.kind==="operator")return[{kind:"operator",boundary:G.boundary}];if(G.kind==="redirection")return[{kind:"redirection",target:G.target}];return[]})}function vn(W,G){return W.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(H,J,oe,ie)=>{let fe=G.get(J);if(fe===void 0)return H;let Re=oe.startsWith(":")?fe!=="":!0;if(oe.endsWith("-"))return Re?fe:vn(ie,G);return Re?vn(ie,G):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(H,J)=>G.get(J)??H).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(H,J)=>G.get(J)??H)}function hi(W){return W.length>0&&W.every((G)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(G))}function Yv(W,G,H,J){let oe=hi(W)?new Map([...G.variables,...Zv(W,G.variables)]):G.variables,ie=br([...W],H),fe=Ft(ie[0]??"").toLowerCase()==="cd"?ie[1]:void 0;if(!fe)return{...G,variables:oe};if(fe==="-"){if(G.previous===null)return{...G,variables:oe};return{cwd:G.previous,variables:oe,previous:G.cwd}}return{cwd:pn(vn(fe,oe),G.cwd,H,J),variables:oe,previous:G.cwd}}function Zv(W,G){return W.flatMap((H)=>{let J=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(H),oe=J?.[2]?.startsWith("=")?J[2].slice(1):void 0;return J?.[1]!==void 0&&oe!==void 0?[[J[1],vn(oe,G)]]:[]})}function of(W){return nf.get(W)??jv}function Xv(W,G){return[...G].reduce((H,J)=>H.slice(0,J.start)+" ".repeat(J.end-J.start)+H.slice(J.end),W)}function Is(W,G,H,J=Vv){return Object.freeze({status:W,source:G,program:H,assignmentFallbacks:Object.freeze(J)})}function $r(W,G){return W.nodes.flatMap((H,J)=>Jv(H,W,J,G)).sort((H,J)=>H.start-J.start).flatMap((H)=>[...H.events])}function Jv(W,G,H,J){if(W.kind==="connector")return[{start:W.span.start,events:[jn(rE(W.operator))]}];if(W.kind==="unknown")return[{start:W.span.start,events:[jn(W.source)]}];if(W.kind==="function")return J.functions.set(W.name,W.body),[];if(W.kind==="group"){let ie=W.style!=="subshell",fe=J.source[W.span.end-1]===(ie?"}":")"),Re=ie?J:{...J,functions:new Map(J.functions)};return[{start:W.span.start,events:ie?[ks("{"),...$r(W.body,Re),...fe?[ks("}")]:[]]:[fi,jn("("),...$r(W.body,Re),...fe?[jn(")")]:[],pi]}]}let oe=aE(W,J.functions);if(oe){if(J.depth>=yr.maxDepth||++J.flags.expansions>qv)return J.flags.limited=!0,[];return[{start:W.span.start,events:[...Jm(W,J),ks(";"),...$r(oe,{...J,depth:J.depth+1}),ks(";")]},...Qm(W,G,H,J)]}return[{start:W.span.start,events:Jm(W,J)},...Qm(W,G,H,J)]}function Jm(W,G){return[...W.words.map((H)=>({start:H.span.start,events:af(H,W,G,!1)})),...W.redirections.map((H)=>({start:H.span.start,events:Qv(H,W,G)}))].sort((H,J)=>H.start-J.start).flatMap((H)=>H.events)}function Qv(W,G,H){let J=W.operator==="<<-"?"<<":W.operator,oe=W.target?af(W.target,G,H,!0):[],ie=oe[0],fe=ie?.kind==="word"?ie.text:void 0;return[...W.fd===void 0?[]:[ql(String(W.fd))],Object.freeze({kind:"redirection",operator:J,...W.fd===void 0?{}:{fd:W.fd},role:oE(J),targetOrder:Bv.has(J)?"legacy-segment":"immediate",...fe===void 0?{}:{target:fe},...W.heredoc&&H.suppressed.has(W.heredoc.bodySpan)?{body:W.heredoc.body,consumer:cf(G)}:{}}),...fe===void 0?oe:oe.slice(1)]}function Qm(W,G,H,J){let oe=W.redirections.filter((ie)=>ie.operator==="<<"||ie.operator==="<<-");return[...oe.flatMap((ie)=>{let fe=ie.heredoc;if(!fe)return[];let Re=[ql(fe.delimiter),.../[\r\n]/.test(J.source[fe.terminatorSpan.end]??"")?[jn(";")]:[]];if(J.suppressed.has(fe.bodySpan))return[{start:fe.bodySpan.start,events:Re}];return[{start:fe.bodySpan.start,events:[...sf(J.source.slice(fe.bodySpan.start,fe.bodySpan.end),J),...Re]}]}),...oe.some((ie)=>!ie.heredoc&&ie.target)?eE(G,H,J):[]]}function eE(W,G,H){let J=W.nodes.slice(G+1).find((oe)=>oe.kind==="connector");if(!J||J.span.end>=W.span.end)return[];return[{start:J.span.end,events:sf(H.source.slice(J.span.end,W.span.end),H)}]}function sf(W,G){if(G.depth>=yr.maxDepth)return G.flags.limited=!0,[];let H=y(W,"posix");if(H.status==="limited")return G.flags.limited=!0,[];let J={invalid:!1,limited:!1,expansions:G.flags.expansions,assignmentFallbacks:G.flags.assignmentFallbacks},oe=$r(H,{source:W,suppressed:new Set,flags:J,depth:G.depth+1,functions:new Map,powershell:!1});return G.flags.limited||=J.limited,G.flags.expansions=J.expansions,oe}function af(W,G,H,J){let oe=[],ie={single:!1,double:!1},fe="",Re=!1,Te=()=>{let ke=Re&&!J?jn("glob"):fe!==""||W.quoted&&oe.length===0?ql(fe):void 0;if(ke)oe.push(ke);fe="",Re=!1};for(let ke of W.parts){if(ke.provenance!=="command-substitution"&&ke.provenance!=="arithmetic"){for(let Ze of jl(ke.raw,ie,H.flags,H.powershell)){if(typeof Ze==="string"){Te(),oe.push(jn(Ze));continue}fe+=Ze.text,Re||=Ze.glob}continue}let Le=G.nested.find((Ze)=>Ze.span.start>=ke.span.start&&Ze.span.end<=ke.span.end);if(ie.double){let Ze=H.source.slice(ke.span.start,ke.span.end);fe+=jl(Ze,{single:!1,double:!0},H.flags,H.powershell).map((et)=>typeof et==="string"?et:et.text).join("");let Qe=Le?$r(Le,H).filter((et)=>et.kind==="redirection"&&et.body!==void 0):[];if(Qe.length>0)oe.push(fi,...Qe,pi);continue}let Xe=Le?$r(Le,H):[];if(ke.raw.startsWith("`")){fe+="${}",Te(),oe.push(fi,...Xe,pi);continue}if(ke.raw.startsWith("<(")||ke.raw.startsWith(">(")){Te(),oe.push(ke.raw.startsWith("<(")?jn("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),fi,...Xe,...ke.raw.endsWith(")")?[jn(")")]:[],pi);continue}let Ye=ke.raw.startsWith("$((")?2:1;fe+="${}",Te(),oe.push(...Array.from({length:Ye},()=>jn("(")),...Ye===1?[fi]:[],...Xe,...ke.raw.endsWith(")".repeat(Ye))?Array.from({length:Ye},()=>jn(")")):[],...Ye===1?[pi]:[])}return Te(),oe}function jl(W,G,H,J){let oe=[],ie="",fe=!1,Re=0;while(Re<W.length){let Te=W[Re]??"";if(!G.single&&!G.double&&(Te==="("||Te===")")){oe.push({text:ie,glob:fe},Te),ie="",fe=!1,Re++;continue}if(J&&Te==="`"&&!G.single){ie+=W[Re+1]??"",Re+=2;continue}if(G.single&&Te==="'"){G.single=!1,Re++;continue}if(G.single){ie+=Te,Re++;continue}if(G.double){if(Te==='"'){G.double=!1,Re++;continue}if(!J&&Te==="\\"){let ke=W[Re+1]??"";ie+=['"',"\\","$"].includes(ke)?ke:`\\${ke}`,Re+=2;continue}if(Te==="$"){let ke=ef(W,Re,G,H,J);ie+=ke.text,Re=ke.next;continue}ie+=Te,Re++;continue}if(Te==="'"||Te==='"'){G.single=Te==="'",G.double=Te==='"',Re++;continue}if(!J&&Te==="\\"){let ke=W[Re+1]??"";fe||=ke==="*"||ke==="?",ie+=ke,Re+=2;continue}if(Te==="$"){let ke=ef(W,Re,G,H,J);ie+=ke.text,Re=ke.next;continue}fe||=Te==="*"||Te==="?",ie+=Te,Re++}return[...oe,{text:ie,glob:fe}]}function ef(W,G,H,J,oe){let ie=W[G+1];if(ie==="{"){let Re=oe?nE(W,G+2):bs(W,G+2,W.length).close;if(Re===-1)return J.invalid=!0,{text:"",next:W.length};let Te=W.slice(G,Re+1);return tE(Te,H,J,oe),{text:Te,next:Re+1}}if(ie!==void 0&&Uv.test(ie))return{text:`\${${ie}}`,next:G+2};let fe=(oe?Hv:/^\w*/).exec(W.slice(G+1))?.[0]??"";return{text:`\${${fe}}`,next:G+1+fe.length}}function tE(W,G,H,J){let oe=W.slice(2,-1),ie=/^[A-Za-z_][A-Za-z0-9_]*/.exec(oe)?.[0];if(!ie)return;let fe=oe.slice(ie.length),Re=[":=","="].find((ke)=>fe.startsWith(ke));if(!Re)return;let Te=jl(fe.slice(Re.length),{...G},H,J);H.assignmentFallbacks.push(...Te.flatMap((ke)=>typeof ke==="string"||!ke.text?[]:[ke.text]))}function nE(W,G){let H=1,J=G;while(H>0&&J<W.length){if(W[J]==="{"&&W[J-1]==="$")H++;if(W[J]==="}")H--;J++}return H===0?J-1:-1}function rE(W){return/^[\r\n]+$/.test(W)?";":W}function jn(W){return Object.freeze({kind:"operator",operator:W,boundary:$v.has(W)})}function ks(W){return Object.freeze({kind:"operator",operator:W,boundary:!0})}function ql(W){return Object.freeze({kind:"word",text:W})}function oE(W){if(W==="<<"||W==="<<<")return"here-data";if(W==="<"||W==="<&")return"file-read";return"file-write"}function bo(W){return Kv.has(W)||/^python\d/.test(W)}var iE=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 lf(W,G){let H=G[0];if(H===void 0||!H.startsWith("-"))return G;let J=iE.get(W)?.has(H)??!1;return lf(W,G.slice(J?2:1))}function Os(W){let G=W[0];if(G===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(G))return Os(W.slice(1));if(G==="uv"&&W[1]==="run")return Os(W.slice(2));if(!zv.has(G))return[...W];return Os(lf(G,W.slice(1)))}function cf(W){let G=ti(W),H=W.words.findIndex((J)=>J.provenance==="literal"&&J.text===G);return Os(H<0?[]:W.words.slice(H).map((J)=>J.text))}function sE(W){let G=cf(W)[0];if(G===void 0)return!1;let H=Ft(G).toLowerCase();return bo(H)&&!gi.has(H)}function Vl(W){return W.nodes.flatMap((G,H)=>{if(G.kind==="group"||G.kind==="function")return Vl(G.body);if(G.kind!=="command")return[];let J=G.nested.flatMap((Re)=>Vl(Re)),oe=G.redirections.flatMap((Re)=>Re.heredoc?.quotedDelimiter?[Re.heredoc.bodySpan]:[]);if(sE(G))return[...J,...oe];let ie=W.nodes[H+1];if(ie?.kind==="connector"&&(ie.operator==="|"||ie.operator==="|&")||!cE(G))return J;return[...J,...oe]})}function aE(W,G){let H=ti(W);return H===void 0?void 0:G.get(H)}function vr(W,G){return W!==void 0&&W.provenance==="literal"&&!W.quoted&&W.raw===W.text&&W.text===G}function lE(W){if(vr(W.words[0],"git"))return vr(W.words[1],"commit");if(!vr(W.words[0],"gh")||!vr(W.words[2],"create"))return!1;return vr(W.words[1],"pr")||vr(W.words[1],"issue")}function cE(W){return(vr(W.words[0],"cat")||vr(W.words[0],"tee")||lE(W))&&!W.words.some(tf)&&!W.redirections.some((H)=>tf(H.target))}function tf(W){return W?.parts.some((G)=>G.provenance==="command-substitution"&&G.raw.startsWith(">("))??!1}var Qn="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",Ns="Unsupported heredoc syntax",yi="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function Er(){return{id:"analysis.dynamic-shell-source",reason:yi,intent:"stop_and_explain"}}var df="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var Yl=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),dE=new Set([...Yl,"dir_path","glob","glob_pattern","include_pattern"]),uE=new Set([...Yl,"folder","glob","pattern","patterns"]);class b extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}class U extends Error{name="UnparseableCommandError";constructor(){super(Qn)}}function uf(W){let G=mE(),H=se(W.input),J=[];if((W.route.kind==="command"||W.route.kind==="unknown")&&H)J.push({usage:"input-candidate",source:H});if(W.route.kind==="command"&&"command"in W&&W.command)J.push({usage:"declared-command",source:W.command});let oe=J.reduce((ie,fe)=>{let Re=ie.findIndex((Le)=>Le.source===fe.source);if(Re!==-1){let Le=ie[Re];if(!Le)return ie;return ie[Re]={...Le,usages:[...Le.usages,fe.usage]},ie}let Te=W.route.kind==="command"?W.route.shell:process.platform==="win32"?"powershell":"posix",ke=G.getCommandProgram(fe.source,Te);return ie.push({usages:[fe.usage],source:fe.source,program:ke,shell:G.getShellSyntax(fe.source,ke)}),ie},[]);return{invocation:{toolName:W.toolName,route:W.route,context:W.context},commands:oe,paths:fE(W),store:G}}function Co(W,G){return W.commands.find((H)=>H.usages.includes(G))}function lr(W){return Co(W,"declared-command")??Co(W,"input-candidate")}function cr(W,G){if(!W.includes("$"))return W;return Ia(W,G)}function mE(){let W=new Map,G=new WeakMap,H=(oe,ie)=>{let fe=`${ie}\x00${oe}`,Re=W.get(fe);if(Re)return Re;let Te=y(oe,ie);return W.set(fe,Te),Te};return{getShellSyntax:(oe,ie)=>{if(ie&&ie.source!==oe)throw TypeError("Shell syntax source does not match command program source.");let fe=ie??H(oe,"posix"),Re=G.get(fe);if(Re)return Re;let Te=fe.status==="limited"?{status:"structural-limit",source:oe,program:fe,assignmentFallbacks:[]}:rf(oe,fe);return G.set(fe,Te),Te},getCommandProgram:H,readsAutoAsPowerShell:()=>[...W].some(([oe,ie])=>oe.startsWith("auto\x00")&&ie.dialect==="powershell")}}function fE(W){let G=W.route.kind==="grep"?dE:W.route.kind==="glob"?uE:Yl;return[...Ld(W.input,G),...W.route.kind==="patch"||typeof W.input==="string"?Fd(W.input):[]]}var pE=new Set(["-S","--suffix"]);function vo(W,G,H,J,oe){if(W.status==="structural-limit")throw new b;if(W.status!=="complete")return oe.findMalformedTarget(W.source);return Ms(W,G,H,J,{segment:(ie,fe)=>oe.findSegmentTarget(ie,fe),redirection:(ie,fe)=>ie.role==="file-write"&&oe.isRedirectionTarget(vn(ie.target,fe.variables),fe)?ie.target:null})}function Ls(W){let G=[],H=null,J=!1;for(let oe=0;oe<W.length;oe++){let ie=W[oe];if(ie===void 0)break;if(!J&&ie==="--"){J=!0;continue}if(!J&&(ie==="-t"||ie==="--target-directory")){H=W[++oe]??null;continue}if(!J&&ie.startsWith("--target-directory=")){H=ie.slice(19);continue}if(!J&&ie.startsWith("-t")&&ie.length>2){H=ie.slice(2);continue}if(!J&&pE.has(ie)){oe++;continue}if(!J&&(ie.startsWith("--suffix=")||ie.startsWith("--backup=")))continue;if(!J&&ie.startsWith("-"))continue;G.push(ie)}return H?{sources:G,destination:H}:{sources:G.slice(0,-1),destination:G.at(-1)??null}}var v="Git metadata and hooks are protected. Ask the user before modifying them.";function gf(W,G,H,J){let oe=W.invocation.context.executionCwd;if(!G)return null;if(W.invocation.route.kind==="patch"||W.invocation.route.kind==="path"||W.invocation.route.kind==="unknown"){if(Ui(W.invocation.toolName))return null;let Re=W.paths.find((Te)=>mf(Te,oe,G,H,J,G.entries));return Re?{target:Re}:null}if(W.invocation.route.kind!=="command")return null;let ie=lr(W);if(!ie)return null;let fe=vo(ie.shell,oe,H,J,{findSegmentTarget:(Re,Te)=>_E(Re,Te,G,H,J),isRedirectionTarget:(Re,Te)=>mf(Re,Te.cwd,G,H,J,G.markerFiles),findMalformedTarget:()=>null});return fe?{target:fe}:null}function Br(W,G,H,J,oe,ie,fe=!1){if(!H)return!1;let Re=Gs(pn(W,G,oe,ie)),Te=Re.replace(/(\/\.?\*+)+$/,"");if(Te!==Re&&Te!==""){if(Zl(Te,H))return!0;let ke=fe||Re.slice(Te.length).includes("/."),Le=(Xe)=>ke?Ws(Xe,Te):bE(Xe,Te);if(H.markerFiles.some(Le))return!0;return J&&Xl(H).some(Le)}if(Zl(Re,H))return!0;return J&&Xl(H).some((ke)=>Ws(ke,Re))}function bE(W,G){let H=pf(G,W);if(H===""||H.startsWith("..")||ff(H))return!1;return!H.split(/[\\/]/)[0]?.startsWith(".")}function CE(W,G,H,J,oe){return Br(W,G,H,!0,J,oe)}function vE(W,G,H,J,oe){if(!H)return!1;return Zl(Gs(pn(W,G,J,oe)),H)}function mf(W,G,H,J,oe,ie){let fe=Gs(pn(W,G,J,oe));return ie.includes(fe)||yf(fe,H)}function hf(W,G,H,J,oe){if(!H)return!1;return H.hooksDirectories.some((ie)=>W.some((fe)=>Ws(ie,Gs(pn(fe,G,J,oe)))))}function Zl(W,G){return G.entries.includes(W)||G.directories.includes(W)||yf(W,G)}function yf(W,G){return G.hooksDirectories.some((H)=>Ws(W,H))}var EE=50000;function Sf(W,G){let H=[...new Set(Xl(W))];if(H.some((oe)=>G(yE(oe))))return!0;let J=0;while(H.length>0){let oe=H.pop()??"",ie=RE(oe);if(!ie)return!0;if(J+=ie.length,J>EE)return!0;if(ie.some((fe)=>G(fe.name)))return!0;H.push(...ie.filter((fe)=>fe.isDirectory()).map((fe)=>SE(oe,fe.name)))}return!1}function RE(W){try{let G=gE(W,{throwIfNoEntry:!1});if(!G)return[];if(!G.isDirectory())return G.isSymbolicLink()?null:[];return hE(W,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function Xl(W){return[...W.entries,...W.directories,...W.hooksDirectories]}function Ws(W,G){let H=pf(G,W);return H===""||!/^\.\.(?:[\\/]|$)/.test(H)&&!ff(H)}function Gs(W){return process.platform==="win32"?W.toLowerCase():W}function _E(W,G,H,J,oe){if(hi(W))return null;let ie=Cr([...W],J);if(Ft(ie[0]??"").toLowerCase()!=="mv")return null;let fe=Ls(ie.slice(1)),Re=fe.sources.find((Te)=>CE(vn(Te,G.variables),G.cwd,H,J,oe));if(Re)return Re;return fe.destination&&vE(vn(fe.destination,G.variables),G.cwd,H,J,oe)?fe.destination:null}import{isAbsolute as Bs,normalize as OE,parse as ME,posix as wf,resolve as Hr,sep as tc}from"node:path";import{isAbsolute as xE,join as bf,normalize as Ef,parse as wE,sep as Cf}from"node:path";var AE=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],PE=`
30
+ `;function Si(W,G){if(Ur(W,G))return!0;if(!W.has("TMPDIR"))return!1;return!Jl(W.get("TMPDIR")??"",G)}function Eo(W,G){if(W.has("TMPDIR"))return Jl(W.get("TMPDIR")??"",G);let H=Ql(W,G);if(H===void 0)return!0;return Jl(H,G)}function Ql(W,G){return _f(W,G,"TMPDIR")}function Jl(W,G){if(!W)return!1;if(IE(W))return!1;return Ro(W,G)}function Ur(W,G){let H=_f(W,G,"IFS");return H!==void 0&&H!==""&&H!==PE}function Ro(W,G){let H=Fs(W,G.paths);if(H===null)return!1;return Rf(G).some((J)=>Rr(H,J))}function $s(W,G){let H=Fs(W,G.paths);if(H===null)return!1;return Rf(G).some((J)=>zs(J)===zs(H))}var vf=new WeakMap;function Rf(W){let G=vf.get(W);if(G)return G;let H=TE(W);return vf.set(W,H),H}function TE(W){let G=AE.map((J)=>Fs(J,W.paths)??Ef(J)),H=Fs(W.tmpdir,W.paths);if(!H)return G;if(process.platform==="win32")return[...G,H];if(process.platform==="darwin"&&kE(H))return[...G,H];return G}function IE(W){return/[\s$`*?[]/.test(W)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(W)||/[+@!]\([^)]*\)/.test(W)}function _f(W,G,H){return W.has(H)?W.get(H):G.env.get(H)}function kE(W){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(W)}function Fs(W,G){try{let H=Ef(W);if(!xE(H))return H;let J=wE(H).root,oe=H.slice(J.length).split(/[\\/]+/).filter(Boolean),ie=J;for(let fe=0;fe<oe.length;fe++){let Re=bf(ie,oe[fe]??"");if(G.entryKind(Re)==="missing")return bf(Re,...oe.slice(fe+1));let Te=G.realpath(Re);if(Te===null)return null;ie=Te}return ie}catch{return null}}function Rr(W,G){let H=zs(W),J=zs(G);if(H===J)return!0;let oe=J.endsWith(Cf)?J:`${J}${Cf}`;return H.startsWith(oe)}function zs(W){return process.platform==="win32"?W.toLowerCase():W}var DE=process.platform==="win32",xf=64,NE=16384;function jr(W,G,H,J){if(W.kind==="temp_target")return null;let oe=J[W.kind];if(W.kind==="dynamic_target"&&!on(H,oe.id,G.strict))return null;if(W.kind==="within_anchored_cwd"&&!on(H,oe.id,G.paranoid))return null;return Pt(oe.id,oe.reason)}function bi(W){let G=cm(W,xf,xf,NE);return{expandedTargets:G&&"words"in G?G.words:void 0,unsafeBraceExpansion:G!==void 0&&"limited"in G,targetIsLiteral:G===void 0&&W.provenance==="literal"&&(W.quoted||W.raw!==W.text),tmpdirWordSplittingProtected:LE(W)}}function LE(W){let G=W.parts.filter((H)=>H.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(H.raw));return G.length>0&&G.every((H)=>WE(W.raw,H.span.start-W.span.start))}function WE(W,G){let H=null,J=!1;for(let oe=0;oe<G;oe++){let ie=W[oe];if(J){J=!1;continue}if(ie==="\\"&&H!=="'"){J=!0;continue}if(H===ie){H=null;continue}if(H===null&&(ie==="'"||ie==='"'))H=ie}return H==='"'}function er(W){let G=W.environment.home,H=W.environment.paths,J=W.budget??In();return{anchoredCwd:W.originalCwd??W.cwd??null,resolvedCwd:W.cwd??null,strict:W.strict??!1,paranoid:W.paranoid??!1,trustTmpdirVar:W.allowTmpdirVar??!0,posixShell:W.posixShell??!1,tmpdirWordSplittingUnsafe:W.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:W.trustedTmpdirValue??W.allowTmpdirVar??!0,environment:W.environment,allowRoots:UE(W.allowPaths,G,H,J),protectedGitMetadata:W.protectedGitMetadata,budget:J}}function An(W,G,H={}){let J=H.targetIsLiteral??!1;if(!J&&G.tmpdirWordSplittingUnsafe&&!H.tmpdirWordSplittingProtected&&jE(W))return{kind:"outside_anchored_cwd"};let oe=!J&&Pf(W,G.posixShell);if(rr(W))return{kind:"outside_anchored_cwd"};if(nc(W,J))return{kind:"root_or_home_target"};if(FE(W,G,J))return{kind:"root_or_home_target"};if(G.resolvedCwd&&Br(W,G.resolvedCwd,G.protectedGitMetadata,!0,G.environment,G.budget,!G.posixShell))return{kind:"git_metadata_target"};if(zE(W,G.trustTmpdirVar,G.posixShell,oe,J,H.tmpdirWordSplittingProtected??!1,G.trustedTmpdirValue,G.environment))return{kind:"temp_target"};if(oe)return{kind:"dynamic_target"};if(HE(W,G,J))return{kind:"temp_target"};let ie=G.anchoredCwd;if(ie){if(!H.skipHomeCwd&&YE(ie,G.environment.home,G.environment.paths,G.budget))return{kind:"home_cwd_target"};if(!H.skipCwdSelf&&[G.resolvedCwd??ie,ie].some((fe)=>ZE(W,G.resolvedCwd??ie,G.environment.paths,G.budget,fe)))return{kind:"cwd_self_target"};if(XE(W,ie,G.resolvedCwd??ie,oe,J,G.environment.paths,G.budget))return{kind:"within_anchored_cwd"}}if(GE(W,G,oe))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function GE(W,G,H){let J=W.trim();if(H||!G.resolvedCwd||!G.anchoredCwd||!J)return!1;if(Bs(J)||J.startsWith("~"))return!1;if(rc(J))return!1;if(Tf(G.resolvedCwd,G.anchoredCwd,G.environment.paths,G.budget))return!1;return Ro(Hr(G.resolvedCwd,J),G.environment)}function Af(W,G,H={}){let{containmentTarget:J,...oe}=H;if(An(W,G,oe).kind!=="temp_target")return!1;let ie=W.trim();if(BE(ie))return!1;if($s(ie,G.environment))return!1;return![G.anchoredCwd,G.resolvedCwd].some((fe)=>Tf(J??ie,fe,G.environment.paths,G.budget))}function nc(W,G=!1){let H=W.trim(),J=wf.normalize(H),oe=H.replace(/\\/g,"/"),ie=J==="/"?J:J.replace(/\/+$/,"");if(ie==="/"||ie.startsWith("/")&&ie.slice(1).split("/").every((fe)=>/^\*+$/.test(fe)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(oe)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(oe))return!0;if(!G&&(J==="~"||J==="~/"||J==="~/*"))return!0;if(!G&&(J==="$HOME"||J==="$HOME/"||J==="$HOME/*"))return!0;if(!G&&(J==="${HOME}"||J==="${HOME}/"||J==="${HOME}/*"))return!0;return!1}function FE(W,G,H){let J=W.trim(),oe=H?J:J==="*"?".":J.endsWith("/*")?J.slice(0,-2):J;if(!oe)return!1;try{let ie=Bs(oe)?oe:G.resolvedCwd?Hr(G.resolvedCwd,oe):null;if(!ie)return!1;let fe=En(Bt(ie,G.environment.paths,G.budget));if(fe===ME(fe).root)return!0;return fe===En(Bt(G.environment.home,G.environment.paths,G.budget))}catch{return!1}}function En(W){let G=OE(W);if(DE){if(G=G.replace(/\//g,"\\").toLowerCase(),G.length>3&&G.endsWith("\\"))G=G.slice(0,-1);return G}if(G.length>1&&G.endsWith("/"))G=G.slice(0,-1);return G}function zE(W,G,H,J,oe,ie,fe,Re){let Te=W.trim();if(rc(Te))return!1;if(!J&&Ro(Te,Re))return!0;return(G||ie&&fe)&&H&&!oe&&$E(Te,H)}function $E(W,G){return["$TMPDIR","${TMPDIR}"].some((H)=>{if(W===H)return!0;if(!W.startsWith(`${H}/`))return!1;return!Pf(W.slice(H.length+1),G)})}function BE(W){let G=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(W);if(!G)return!1;return wf.normalize(`/${G[1]??""}`)==="/"}function rc(W){return W.split(/[\\/]+/).includes("..")}function UE(W,G,H,J){if(!W?.length)return[];return W.flatMap((oe)=>{let ie=Xo(oe.trim(),G);if(!Bs(ie))return[];try{let fe=Bt(ie,H,J);if(Jo(fe,Bt(G,H,J)))return[];return[En(fe)]}catch{return[]}})}function HE(W,G,H){if(G.allowRoots.length===0)return!1;let J=W.trim();if(rc(J))return!1;let oe=H?J:Xo(J,G.environment.home),ie=G.resolvedCwd??G.anchoredCwd,fe=Bs(oe)?oe:ie?Hr(ie,oe):null;if(!fe)return!1;try{let Re=En(Bt(fe,G.environment.paths,G.budget));return G.allowRoots.some((Te)=>Re===Te||Re.startsWith(Te.endsWith(tc)?Te:`${Te}${tc}`))}catch{return!1}}function jE(W){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(W)}function Pf(W,G=!1){return W.includes("$")||W.includes("`")||VE(W)||G&&KE(W)}function VE(W){let G=!1;for(let H of W){if(G){G=!1;continue}if(H==="\\"){G=!0;continue}if(H==="*"||H==="?"||H==="[")return!0}return!1}function KE(W){let G=!1;for(let H=0;H<W.length;H++){let J=W[H];if(G){G=!1;continue}if(J==="\\"){G=!0;continue}if(J==="{"&&qE(W,H)||(J==="+"||J==="@"||J==="!")&&W[H+1]==="(")return!0}return!1}function qE(W,G){let H=W.indexOf("}",G+1);if(H===-1)return!1;let J=W.slice(G+1,H);return J.includes(",")||J.includes("..")}function YE(W,G,H,J){try{return En(Bt(W,H,J))===En(Bt(G,H,J))}catch{try{return En(W)===En(G)}catch{return!1}}}function ZE(W,G,H,J,oe=G){if(oe===G&&(W==="."||W==="./"||W===".\\"))return!0;try{return En(Bt(Hr(G,W),H,J))===En(Bt(oe,H,J))}catch{try{return En(Hr(G,W))===En(oe)}catch{return!1}}}function XE(W,G,H,J,oe,ie,fe){let Re=H??G;if(!oe&&(W.startsWith("~")||W.startsWith("$HOME")||W.startsWith("${HOME}")))return!1;if(J)return!1;if(W.startsWith("/")||/^[A-Za-z]:[\\/]/.test(W))try{return ec(W,G,ie,fe)}catch{return!1}if(W.startsWith("./")||W.startsWith(".\\")||!W.includes("/")&&!W.includes("\\"))try{return ec(Hr(Re,W),G,ie,fe)}catch{return!1}if(W.startsWith("../"))return!1;try{return ec(Hr(Re,W),G,ie,fe)}catch{return!1}}function ec(W,G,H,J){try{return If(Bt(W,H,J),Bt(G,H,J))}catch{return!1}}function Tf(W,G,H,J){if(!G)return!1;try{return If(Bt(G,H,J),Bt(W,H,J))}catch{return!0}}function If(W,G){let H=En(W),J=En(G);return H.startsWith(`${J}${tc}`)||H===J}var JE=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),kf="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",QE="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.",Of="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",Mf="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",eR="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",tR="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",nR={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:Mf},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:v},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:Of},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:eR},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:kf},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:QE},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:kf}};function Df(W,G,H){return rR(W.words.map((J)=>({kind:"word",text:J.text,dynamic:J.provenance!=="literal"})),G,er({...H,allowPaths:H.policy?.destructiveCommandAllowPaths}),H.policy)}function rR(W,G,H,J){let oe=W.filter((Te)=>Te.kind==="word"),ie=iR(oe),fe=oe[ie];if(!fe||!JE.has(pR(fe.text)))return null;let Re=oR(oe.slice(ie+1));if(Re.whatIfProtected)return null;if(on(J,"powershell.remove-item-pipeline-dynamic-target",H.strict)&&G&&(Re.targets.length===0||Re.recursive))return Pt("powershell.remove-item-pipeline-dynamic-target",tR);for(let Te of Re.targets)if(!rr(Te.text)&&nc(Ci(Te.text)))return Pt(Re.recursive&&Re.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Mf);for(let Te of Re.targets)if(H.resolvedCwd&&Br(Ci(Te.text),H.resolvedCwd,H.protectedGitMetadata,Re.recursive,H.environment,H.budget,!0))return Pt("powershell.remove-item-git-metadata",v);if(!Re.recursive||!Re.force)return null;if(on(J,"powershell.remove-item-recursive-force-dynamic-target",H.strict)&&(Re.hasDynamicTarget||Re.targets.length===0))return Pt("powershell.remove-item-recursive-force-dynamic-target",Of);for(let Te of Re.targets){let ke=jr(An(Ci(Te.text),H),H,J,nR);if(ke)return ke}return null}function oR(W){let G=[],H=!1,J=!1,oe=!1,ie=!1,fe=!1;for(let Re=0;Re<W.length;Re++){let Te=W[Re];if(!Te||Te.kind!=="word")continue;if(sR(Te))continue;if(fe){G.push(oc(Te)),ie=ie||Te.dynamic;continue}if(Te.text==="--"){fe=!0;continue}let ke=lR(Te.text);if(!ke){G.push(oc(Te)),ie=ie||Te.dynamic;continue}if(cR(ke.name)){let Le=ke.value?aR(ke.value,Te):W[++Re];if(Le?.kind==="word"){G.push(oc(Le)),ie=ie||Le.dynamic;continue}ie=!0;continue}if(dR(ke.name)){H=!0;continue}if(uR(ke.name)){J=!0;continue}if(mR(ke.name))oe=fR(ke.value)}return{targets:G,recursive:H,force:J,whatIfProtected:oe,hasDynamicTarget:ie}}function iR(W){let G=W[0];if(G?.kind==="word"&&G.text==="&"||G?.text===".")return W.length>1?1:0;return 0}function oc(W){return{text:W.kind==="word"?W.text:"",dynamic:W.kind==="word"&&W.dynamic}}function sR(W){return W.kind==="word"&&W.text===","}function Ci(W){let G=W.replace(/\\/g,"/"),H=/^(?:\$env:(?:userprofile|home)|\$home|\$\{home\})(?=$|\/)/i.exec(G);return H?`$HOME${G.slice(H[0].length)}`:G}function aR(W,G){return{kind:"word",text:W,dynamic:G.kind==="word"&&(G.dynamic||W.includes("$"))}}function lR(W){if(!W.startsWith("-")||W==="-")return null;let G=W.slice(1),H=G.indexOf(":");if(H===-1)return{name:G.toLowerCase()};return{name:G.slice(0,H).toLowerCase(),value:G.slice(H+1)}}function cR(W){return"path".startsWith(W)||"literalpath".startsWith(W)}function dR(W){return"recurse".startsWith(W)}function uR(W){return W.length>=2&&"force".startsWith(W)}function mR(W){return W==="wi"||"whatif".startsWith(W)}function fR(W){if(W===void 0||W==="")return!0;let G=W.toLowerCase();return G==="$true"||G==="true"}function pR(W){return W.toLowerCase()}var gR=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),hR=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),yR=new Set(["-o","--output","--query","--subscription"]),SR=new Set;function Nf(W){if(W==="aws")return gR;if(W==="gcloud")return hR;if(W==="az")return yR;return SR}var bR=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),CR=new Set;function Lf(W){if(W==="git")return _n;if(W==="docker")return bR;return CR}function N(W,G){if(W.length===0||G.length===0)return null;let H=zt(W[0]??""),J=Cn(W);for(let oe of G){if(!RR(H,oe.command))continue;if(oe.match){if(vR(H,W,oe.match))return Wf(oe);continue}if(!_R(H,W,oe.subcommand))continue;if(wR(W,new Set(oe.block_args),J))return Wf(oe)}return null}function Wf(W){return{id:`custom.${W.name}`,reason:`[${W.name}] ${W.reason}`,intent:W.intent??"manual_only"}}function vR(W,G,H){let J=G.slice(1);if(H.exclude_args?.some((oe)=>J.includes(oe)))return!1;if(H.any_args&&!H.any_args.some((oe)=>J.includes(oe)))return!1;return ER(J,H.command_path,Nf(W))}function ER(W,G,H){let J=0,oe=!1;for(let ie of W){if(J>=G.length)return!0;if(oe){oe=!1;continue}if(ie.startsWith("-")){oe=!ie.includes("=")&&H.has(ie);continue}if(ie!==G[J])return!1;J++}return J>=G.length}function RR(W,G){return W===zt(G)}function _R(W,G,H){if(!H)return!0;return Gf(G,1,H,Lf(W))}function Gf(W,G,H,J){let oe=!1;for(let ie=G;ie<W.length;ie++){let fe=W[ie];if(!fe)continue;if(oe){oe=!1;continue}if(fe==="--"){let Re=W[ie+1];if(Re&&!Re.startsWith("-"))return Re===H;return!1}if(J.has(fe)){oe=!0;continue}if(fe.startsWith("-")){if(!fe.includes("=")&&xR(W,ie,H,J))return!0;continue}return fe===H}return!1}function xR(W,G,H,J){let oe=W[G+1];if(!oe||oe.startsWith("-"))return!1;return Gf(W,G+2,H,J)}function wR(W,G,H){return W.some((J)=>G.has(J))||[...H].some((J)=>G.has(J))}var AR=new Set(["-e","--source"]),PR=new Set(["-F","-v","--assign","--field-separator"]),Ff=new Set(["-f","--file"]),TR=new Set(["print","printf","return"]),zf=[{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"}],IR="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 $f(W,G,H){let J=!1;for(let oe of kR(W)){let ie=OR(oe,H);if(!ie)continue;for(let fe of ie.commands){let Re=G(fe);if(Re)return Re;if(fe.includes("{}")||/[$`]/.test(fe))J=!0}J||=ie.dynamic}return J?Pt("awk.system-dynamic",IR):null}function sc(W){let G=[],H=!1,J=!1,oe=!0,ie=!0;for(let fe=1;fe<W.length;fe++){let Re=W[fe];if(Re===void 0)break;if(oe&&Re==="--"){oe=!1;continue}if(oe&&AR.has(Re)){H=!0;let Te=W[fe+1];if(ie&&=Te!==void 0,Te!==void 0)G.push({tokenIndex:fe+1,kind:"inline-code",value:Te});fe++;continue}if(oe&&Re.startsWith("--source=")){H=!0,G.push({tokenIndex:fe,kind:"inline-code",value:Re.slice(9)});continue}if(oe&&Re.startsWith("-e")&&Re.length>2){H=!0,G.push({tokenIndex:fe,kind:"inline-code",value:Re.slice(2)});continue}if(oe&&(PR.has(Re)||Ff.has(Re))){let Te=W[fe+1];if(ie&&=Te!==void 0,Ff.has(Re)){if(J=!0,Te!==void 0)G.push({tokenIndex:fe+1,kind:"program-file",value:Te})}fe++;continue}if(oe&&(Re.startsWith("-F")||Re.startsWith("-v")&&Re.slice(2).includes("=")))continue;if(oe&&Re.startsWith("-f")&&Re.length>2){J=!0,G.push({tokenIndex:fe,kind:"program-file",value:Re.slice(2)});continue}if(oe&&(Re.startsWith("--assign=")||Re.startsWith("--field-separator=")))continue;if(oe&&Re.startsWith("--file=")){J=!0,G.push({tokenIndex:fe,kind:"program-file",value:Re.slice(7)});continue}if(oe&&Re.startsWith("-")&&Re!=="-")continue;if(!H&&!J)G.push({tokenIndex:fe,kind:"main-program",value:Re});return{sources:G,optionsOpen:!1}}return{sources:ie?G:[],optionsOpen:oe&&ie}}function Ei(W){return sc(W).sources}function kR(W){return Ei(W).filter((G)=>G.kind!=="program-file").map((G)=>G.value)}function OR(W,G){wn(G,W);let H=W.includes("system")?ac(W,G):null,J=MR(W,G);if(!H&&!J)return null;return{dynamic:!!H?.dynamic||!!J?.dynamic,commands:[...H?.commands??[],...J?.commands??[]]}}function ac(W,G){wn(G,W);let H=[],J=!1,oe=!1,ie=0;while(ie<W.length){let fe=W[ie];if(fe==='"'||fe==="'"){ie=Hs(W,ie,fe)?.endIndex??ie+1;continue}if(fe==="#"){ie=Bf(W,ie+1);continue}if(fe==="/"&&Uf(W,ie)){ie=Hf(W,ie+1)??ie+1;continue}if(!W.startsWith("system",ie)){ie++;continue}let Re=ie;if(ie+=6,vi(W[Re-1])||vi(W[ie]))continue;let Te=Us(W,ie);if(W[Te]!=="(")continue;Te=Us(W,Te+1);let ke=W[Te];if(ke!=='"'&&ke!=="'"){J=!0,oe=!0;continue}let Le=Hs(W,Te,ke);if(!Le){J=!0,oe=!0;continue}if(Te=Us(W,Le.endIndex),J=!0,W[Te]!==")"){oe=!0,ie=Le.endIndex;continue}H.push(Le.value),ie=Te+1}if(!J)return null;return{dynamic:oe,commands:H}}function MR(W,G){wn(G,W);let H=[],J=!1,oe=!1,ie=0,fe=0,Re=null,Te=null,ke=0;while(ie<W.length){let Le=W[ie];if(!Le)break;if(Le==='"'||Le==="'"){let Ze=Hs(W,ie,Le);if(Ze&&ke===fe)Te={...Ze,startIndex:ie};ke=Ze?.endIndex??ie+1,ie=Ze?.endIndex??ie+1;continue}if(Le==="#"){ie=Bf(W,ie+1),fe=ie,Re=null,Te=null,ke=ie;continue}if(Le==="/"&&Uf(W,ie)){let Ze=Hf(W,ie+1);ke=Ze??ie+1,ie=Ze??ie+1;continue}if(`;
31
+ {}`.includes(Le)){ie++,fe=ie,Re=null,Te=null,ke=ie;continue}if(Re===null&&(ic(W,ie,"print")||ic(W,ie,"printf")))Re=ie;if(Le!=="|"||W[ie-1]==="|"||W[ie+1]==="|"){if(!/\s/.test(Le))ke=ie+1;ie++;continue}let Xe=W[ie+1]==="&"?ie+2:ie+1,Ye=Us(W,Xe);if(ic(W,Ye,"getline")){oe=!0;let Ze=LR(fe,Te,ke);if(J||=Ze===null,Ze!==null)H.push(Ze);ke=Xe,ie=Xe;continue}if(GR(fe,Re)){oe=!0;let Ze=NR(W,Ye);if(!Ze){J=!0,ke=Xe,ie=Xe;continue}if(!DR(W,Ze.endIndex)){J=!0,ke=Ze.endIndex,ie=Ze.endIndex;continue}H.push(Ze.value),ke=Ze.endIndex,ie=Ze.endIndex;continue}ke=Xe,ie++}if(!oe)return null;return{dynamic:J,commands:H}}function vi(W){return!!W&&/[A-Za-z0-9_]/.test(W)}function Us(W,G){let H=G;while(/\s/.test(W[H]??""))H++;return H}function DR(W,G){let H=G;while(/[\t\f\v\r ]/.test(W[H]??""))H++;let J=W[H];return!J||`;
32
+ }#`.includes(J)}function Hs(W,G,H){let J="",oe=!1;for(let ie=G+1;ie<W.length;ie++){let fe=W[ie];if(!fe)break;if(oe){let Re=WR(W,ie);if(!Re)return null;J+=Re.value,ie=Re.endIndex,oe=!1;continue}if(fe==="\\"){oe=!0;continue}if(fe===H)return{value:J,endIndex:ie+1};J+=fe}return null}function NR(W,G){let H=W[G];if(H!=='"'&&H!=="'")return null;return Hs(W,G,H)}function LR(W,G,H){if(!G)return null;return G.startIndex>=W&&G.endIndex===H?G.value:null}function WR(W,G){let H=W[G];if(!H)return null;if(H==="x"){let oe=W.slice(G+1,G+3);if(!/^[0-9A-Fa-f]{2}$/.test(oe))return null;return{value:String.fromCharCode(Number.parseInt(oe,16)),endIndex:G+2}}if(/[0-7]/.test(H)){let oe=/^[0-7]{1,3}/.exec(W.slice(G));if(!oe)return null;return{value:String.fromCharCode(Number.parseInt(oe[0],8)),endIndex:G+oe[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
33
+ `,r:"\r",t:"\t",v:"\v"}[H]??H,endIndex:G}}function ic(W,G,H){return W.startsWith(H,G)&&!vi(W[G-1])&&!vi(W[G+H.length])}function GR(W,G){return G!==null&&G>=W}function Bf(W,G){let H=W.indexOf(`
34
+ `,G);return H===-1?W.length:H+1}function Uf(W,G){let H=FR(W,G);if(H===-1)return!0;if("{([,;!~=".includes(W[H]??""))return!0;let J=H;while(vi(W[J-1]))J--;return TR.has(W.slice(J,H+1))}function FR(W,G){for(let H=G-1;H>=0;H--)if(!/\s/.test(W[H]??""))return H;return-1}function Hf(W,G){let H=!1;for(let J=G;J<W.length;J++){let oe=W[J];if(!oe)break;if(H){H=!1;continue}if(oe==="\\"){H=!0;continue}if(oe==="/")return J+1}return null}var zR=new Set(["sudo","env","command","builtin"]),$R=new Set(["caffeinate","exec","nice","nohup","setsid","stdbuf","time","timeout"]);function js(W,G){let H=W[0];if(!H||!jf(Ft(H),G))return null;let J=Ft(H),oe=W[1]==="--"?2:1,ie=BR(W,oe,J,G),fe=ie[0];if(fe===void 0)return null;return{wrapper:J,tokens:W.slice(fe),childIndex:fe,alternativeChildIndices:ie.slice(1)}}function BR(W,G,H,J){let oe=W[1]==="--",ie=[];for(let fe=G;fe<W.length;fe++){let Re=W[fe];if(!Re)continue;let Te=Ft(Re)!==H&&UR(Re,J);if(Te)ie.push(fe);if(!Te&&Ji.has(zt(Re)))break;if(oe)break}return ie}function UR(W,G){let H=Ft(W),J=zt(W);return J==="git"||H==="busybox"||Vr(W)||Za.has(H)||Mm(J)||jf(H,G)||tn.has(J)||W==="$SHELL"||Bn(J)||Mn.has(J)||G.rules.some((oe)=>oe.command===H)}function jf(W,G){return $R.has(W)||G.transparentWrappers.includes(W)}function Vr(W){return zR.has(W.toLowerCase())}function Kr(W,G){return{embedded:!1,cwd:W.cwd,originalCwd:G.originalCwd,effectiveCwd:W.cwd,envAssignments:W.envAssignments,allowTmpdirVar:G.allowTmpdirVar,worktreeMode:G.worktreeMode,wrappedByTransparent:!1}}function Vn(W,G){let H=G.policy??{rules:[],transparentWrappers:[]};return Vs([...W],G.environment,G.cwd,G.cwd,new Map,new Map(G.envAssignments??[]),H,{iterations:0},!1)}function*Vs(W,G,H,J,oe,ie,fe,Re,Te){let ke=Ts(W,G,H,ie);for(let[Ze,Qe]of ke.envAssignments)ie.set(Ze,Qe),oe.set(Ze,Qe);let{tokens:Le,cwd:Xe}=ke;if(ke.envSplitValues){let Ze=Ps(ke.envSplitValues,Le);if(!Ze)throw new s("derivedCommandShape");lc(Re),yield*Vs(Ze,G,Xe,J,oe,ie,fe,Re,Te);return}if(Vr(Le[0]??""))throw new s("wrapperPeelIterations");let Ye=js(Le,fe);if(Ye){for(let Ze of[Ye.childIndex,...Ye.alternativeChildIndices])lc(Re),yield*Vs(Ze===Ye.childIndex?Ye.tokens:Le.slice(Ze),G,Xe,J,new Map(oe),new Map(ie),fe,Re,!0);return}if(jR(Le)){lc(Re),yield*Vs(Le.slice(1),G,Xe,J,oe,ie,fe,Re,Te);return}yield HR(Le,Xe,J,oe,ie,Te)}function HR(W,G,H,J,oe,ie){return{tokens:W,cwd:G===null?void 0:G??H,wrapperCwd:G,wrapperEnvAssignments:J,envAssignments:oe,head:Ft(W[0]??"").toLowerCase(),wrappedByTransparent:ie}}function lc(W){if(W.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");W.iterations++}function jR(W){return Ft(W[0]??"").toLowerCase()==="busybox"&&W.length>1}function cc(W,G){let H=[],J=G;while(J<W.length){let oe=W[J];if(oe===void 0||oe===":::")break;H.push(oe),J++}return{markerIndex:J<W.length&&W[J]===":::"?J:-1,templateTokens:H}}function dr(W){let G=!1,H=!1;for(let J of W){if(J==="--")break;if(J==="-r"||J==="-R"||dc(J,"recursive")){G=!0;continue}if(J==="-f"||dc(J,"force")){H=!0;continue}if(J.startsWith("-")&&!J.startsWith("--")){if(J.includes("r")||J.includes("R"))G=!0;if(J.includes("f"))H=!0}}return G&&H}function Ks(W){let G=W.indexOf("--");return W.slice(1,G===-1?void 0:G).some((H)=>dc(H,"recursive")||/^-[A-Za-z]+$/.test(H)&&/[rR]/.test(H.slice(1)))}function dc(W,G){return W.length>2&&W.startsWith("--")&&G.startsWith(W.slice(2))}var VR=["--init-file","--rcfile"],KR=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function Wn(W){for(let G=1;G<W.length;G++){let H=W[G];if(!H)continue;if(H==="-c")return Kf(W,G,!0);if(H.startsWith("-")&&H.includes("c")&&!H.startsWith("--")){let J=Kf(W,G,!1);if(J!==null)return J}}return null}var Vf=/^-[cn]+$/;function Kn(W){let G=W.slice(1);if(G.some((J)=>/^[-+]./.test(J)&&J!=="--"&&!Vf.test(J)))return!1;let H=G.findIndex((J)=>!Vf.test(J));return G.slice(0,H===-1?void 0:H).some((J)=>J.includes("n"))}var qR=/^-[abcefhiklmnprstuvx]+$/;function qs(W){let G=W.findIndex((ie,fe)=>fe>0&&!qR.test(ie)),H=G===-1||/^[-+]/.test(W[G]??"")?W.slice(1):W.slice(1,G+1);if(H.some((ie)=>ie.startsWith("+")))return!0;let J=H.filter((ie)=>ie.startsWith("-")&&!ie.startsWith("--")&&ie.includes("c"));if(J.length===0)return!1;let oe=Wn(W);if(oe===null)return H.some((ie)=>ie.startsWith("-")&&!J.includes(ie));return/^[-+]/.test(oe)||J.some((ie)=>/[oO]/.test(ie))}function Kf(W,G,H){if(W[G+1]==="--")return W[G+2]||null;let J=W[G+1];if(!J||!H&&J.startsWith("-"))return null;return J}function qf(W){let G=Ft(W[0]??"").toLowerCase(),H=YR(W,G),J=KR.get(G)??null,oe=H.argvSource?.kind!=="absent";return{argvSource:G==="bash"?H.argvSource:null,argvSourceApplies:G==="bash"&&H.interactive&&H.argvSource?.kind==="literal",envName:J,envSourceApplies:oe&&(J==="BASH_ENV"?!H.interactive:J==="ENV"&&H.interactive)}}function YR(W,G){let H=Dn(W),J=H.commandIndex??H.scriptIndex??W.length,oe=[],ie=!1,fe=!0;for(let Re=1;Re<J;Re++){let Te=W[Re];if(Te===void 0||Te==="--"||Te==="-"||Te[0]!=="-"&&Te[0]!=="+")break;if(Te.startsWith("--")){if(G==="bash"&&fe?VR.find((Ye)=>Te===Ye):void 0){let Ye=W[Re+1];oe.push(Ye===void 0?{kind:"absent"}:{kind:"literal",value:Ye}),Re++;continue}let Xe=Te.split("=",1)[0]??Te;if(G==="bash"&&qa.has(Xe)&&!Te.includes("="))Re++;continue}if(G==="bash")fe=!1;let ke=Ya(G,Te,W[Re+1],"startup");if(ke.interactive)ie=Te[0]==="-";Re+=ke.followingValues}return{argvSource:oe.at(-1)??null,interactive:ie}}var ZR="find -delete permanently removes files. Use -print first to preview.",XR="find -exec rm -rf is dangerous. Use explicit file list instead.",JR=new Set(["-exec","-execdir","-ok","-okdir"]),QR=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((W)=>[W,1]),["-fprintf",2]]);function Yf(W,G){let H=W.map(t),J=e_(W,H,G);if(J)return J;if(Ys(H,1)&&!s_(W,H,G)){let fe=Lt(Pt("find.delete",ZR),G.policy);if(fe)return fe}let oe=G.budget??In(),ie=0;while(ie<H.length){let fe=H[ie],Re=ur(fe??"");if(Re>0){ie+=Re+1;continue}if(!tr(fe)){ie++;continue}oe.charge("derivedTokens",H.length-ie-1);let Te=_o(H,ie);ie=Te.nextIndex;let ke=l_(Te.tokens,G.environment);if(ke){let Ze=Lt(ke,G.policy);if(Ze)return Ze}let Le=fe==="-execdir"||fe==="-okdir",Xe=G.analyzeTokens?.(Te.tokens,Le?null:G.cwd)??null,Ye=Xe?.id.startsWith("custom.")?Xe:Lt(Xe,G.policy);if(Ye)return Ye}return null}function e_(W,G,H){if(!Ys(G,1)&&!uc(G,H.environment))return null;let oe=Ri(W)??Qt(["."]),ie=er({...H,allowPaths:H.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let fe of oe){let Re=bi(fe);for(let Te of Re.expandedTargets??[t(fe)]){let ke=An(Te,ie,{targetIsLiteral:Re.expandedTargets!==void 0||Re.targetIsLiteral,tmpdirWordSplittingProtected:Re.tmpdirWordSplittingProtected});if(ke.kind==="root_or_home_target")return Pt("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(ke.kind==="git_metadata_target"&&!t_(W,ie.protectedGitMetadata,H.environment))return Pt("find.delete-git-metadata",v)}}if(i_(G)&&ie.resolvedCwd&&hf(oe.map(t),ie.resolvedCwd,ie.protectedGitMetadata,ie.environment,ie.budget))return Pt("find.delete-git-metadata",v);return null}function t_(W,G,H){if(!G)return!1;let J=W.map(t),oe=[],ie=!1,fe=Ri(W)?.at(-1),Re=fe?W.indexOf(fe)+1:1;while(Re<J.length){let Te=J[Re]??"";if(tr(Te)){let ke=_o(J,Re),Le=Cr([...ke.tokens],H),Xe=Ks(Le),Ye=tn.has(Ft(Le[0]??"").toLowerCase()),Ze=ke.tokens.some((et)=>et!=="{}"&&et.includes("{}")),Qe=(Te==="-execdir"||Te==="-okdir")&&Le.slice(1).some((et)=>et!=="{}"&&!et.startsWith("-"));if(Xe||Ye||Ze||Qe)return!1;ie=!0,Re=ke.nextIndex;continue}if(Te==="-delete"){ie=!0,Re++;continue}if(Te==="-name"||Te==="-iname"){let ke=W[Re+1];if(!(ke?.provenance==="literal"&&!/[[\\]/.test(ke.text)))return!1;if(!ie)oe.push(r_(ke.text,Te==="-iname"));Re+=2;continue}if(!n_.has(Te))return!1;Re+=1+ur(Te)}return oe.length>0&&!Sf(G,(Te)=>oe.every((ke)=>ke.test(Te)))}var n_=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function r_(W,G){let H=W.replace(/[*?]|[.+^${}()|\]/]/g,(J)=>J==="*"?".*":J==="?"?".":`\\${J}`);return new RegExp(`^${H}$`,G?"isu":"su")}var o_=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function uc(W,G){let H=0;while(H<W.length){if(!tr(W[H])){H++;continue}let J=_o(W,H),oe=Cr([...J.tokens],G),ie=Ft(oe[0]??"").toLowerCase(),fe=tn.has(ie)&&o_.test((Wn(oe)??"").replace(/["'\\]/g,""));if((ie==="rm"||ie==="rmdir"||fe)&&oe.some((Te)=>Te.includes("{}")))return!0;H=J.nextIndex}return!1}function i_(W){return W.some((G,H)=>{if(!["-name","-iname"].includes(G))return!1;return W[H+1]?.toLowerCase()==="hooks"})}function s_(W,G,H){if(G.includes("-L")||G.includes("-f")||G.includes("-follow"))return!1;let J=Ri(W);if(!J)return!1;let oe=H.envAssignments??new Map,ie=Ql(oe,H.environment),fe=H.trustedTmpdirValue??Eo(oe,H.environment),Re=H.allowTmpdirVar??!Si(oe,H.environment),Te={environment:H.environment,protectedGitMetadata:H.protectedGitMetadata,cwd:H.cwd,originalCwd:H.originalCwd,strict:H.strict,allowTmpdirVar:Re&&fe&&Boolean(ie),allowPaths:H.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:H.tmpdirWordSplittingUnsafe??Ur(oe,H.environment),trustedTmpdirValue:fe,budget:H.budget},ke=er(Te),Le=er({...Te,cwd:H.originalCwd??H.cwd}),Xe=H.originalCwd&&H.environment.paths.realpath(H.originalCwd),Ye=H.cwd&&H.environment.paths.realpath(H.cwd),Ze=Xe&&Ye&&!Rr(Ye,Xe)?H.cwd:void 0;return J.every((Qe)=>{let et=bi(Qe);if(et.unsafeBraceExpansion)return!1;return(et.expandedTargets??[t(Qe)]).every((tt)=>{let gt=/^\.\/*$/.test(tt)?Ze:void 0,_t=gt??tt,yt={targetIsLiteral:et.expandedTargets!==void 0||et.targetIsLiteral,tmpdirWordSplittingProtected:et.tmpdirWordSplittingProtected};if(!on(H.policy,"rm.recursive-force-paranoid",H.paranoid??!1)&&!gt&&An(_t,ke,yt).kind==="within_anchored_cwd")return!0;return Af(_t,gt?Le:ke,{...yt,containmentTarget:a_(_t,ie)})})})}function a_(W,G){if(!G)return W;return W.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>G)}function Ri(W){let G=(oe)=>{let ie=W[oe];return ie?t(ie):void 0},H=1;while(G(H)==="-H"||G(H)==="-P")H++;if(G(H)==="--")H++;let J=[];while(H<W.length){let oe=G(H),ie=W[H];if(!oe||!ie||oe.startsWith("-")||["!","(",")"].includes(oe))break;J.push(ie),H++}return J.length>0?J:null}function l_(W,G){let H=br([...W],G);if(H.length===0)return null;let J=Ft(H[0]??"");if(J==="busybox"&&H.length>1)H=H.slice(1),J=Ft(H[0]??"");if(J==="rm"&&dr(H))return Pt("find.exec-rm-recursive-force",XR);return null}function _o(W,G){let H=G+1;while(H<W.length&&W[H]!==";"&&!(W[H]==="+"&&W[H-1]==="{}"))H++;return{tokens:W.slice(G+1,H),nextIndex:Math.min(H+1,W.length)}}function Ys(W,G){let H=G;while(H<W.length){let J=W[H];if(!J){H++;continue}if(tr(J)){H=_o(W,H).nextIndex;continue}let oe=ur(J);if(oe>0){H+=oe+1;continue}if(J==="-delete")return!0;H++}return!1}function ur(W){return QR.get(W)??(/^-newer[A-Za-z]{2}$/.test(W)?1:0)}function tr(W){return W!==void 0&&JR.has(W)}import{resolve as zx}from"node:path";function*mc(W){for(let G of W.nodes)yield*d_(G)}function c_(W){return[...mc(W)]}function Rt(W){return c_(W).map((G)=>G.words.map((H)=>H.text))}function _i(W){let G=y(W,"posix");if(G.status!=="complete"||G.nodes.length!==1)return null;let H=G.nodes[0];if(H?.kind!=="command")return null;if(H.redirections.length>0||H.nested.length>0)return null;if(H.words.some((J)=>J.provenance==="command-substitution"))return null;return H.words.map((J)=>J.text)}function*d_(W){if(W.kind==="command"){yield W;for(let G of W.nested)yield*mc(G);return}if(W.kind==="group")yield*mc(W.body)}var u_=5,fc="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 dn(W){let G=W.indexOf("--");if(G===-1)return{index:-1,before:W,after:[]};return{index:G,before:W.slice(0,G),after:W.slice(G+1)}}function Xf(W,G,H){let J=xo(W,G,H),oe=m_(J.entries);if(oe.size===0)return{blockedReason:J.blockedReason,expanded:!1,tokens:W};let ie=W,fe=!1;for(let Re=0;Re<u_;Re++){let{subcommand:Te,rest:ke}=Pn(ie),Le=Te?.toLowerCase();if(!Le||!oe.has(Le))return{blockedReason:J.blockedReason,expanded:fe,tokens:ie};let Xe=oe.get(Le),Ye=y_(Xe);if(Ye===null||Ye.length===0)return{blockedReason:fc,expanded:!0,tokens:ie};ie=["git",...Ye,...ke],fe=!0}return{blockedReason:fc,expanded:!0,tokens:ie}}function Jf(W,G,H){return xo(W,G,H).entries.some((J)=>J.key.toLowerCase()==="core.sshcommand")}function Pn(W){if(W.length===0)return{subcommand:null,rest:[]};let G=W[0];if((G?Ft(G).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let J=1;while(J<W.length){let oe=W[J];if(!oe)break;if(oe==="--"){let ie=W[J+1];if(ie&&!ie.startsWith("-"))return{subcommand:ie,rest:W.slice(J+2)};return{subcommand:null,rest:W.slice(J+1)}}if(!oe.startsWith("-"))return{subcommand:oe,rest:W.slice(J+1)};J+=_n.has(oe)?2:1}return{subcommand:null,rest:[]}}function m_(W){let G=new Map;for(let H of W){let J=H.key.toLowerCase();if(!J.startsWith("alias."))continue;let oe=J.slice(6);if(oe!=="")G.set(oe,H.value)}return G}function xo(W,G,H){if(W.length===0)return{blockedReason:null,entries:[]};let J=W[0];if((J?Ft(J).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let ie=p_(G,H);return{blockedReason:ie.blockedReason,entries:[...ie.entries,...f_(W,G,H)]}}function f_(W,G,H){let J=[],oe=1;while(oe<W.length){let ie=W[oe];if(!ie||ie==="--"||!ie.startsWith("-"))return J;if(ie==="-c"){let fe=pc(W[oe+1]);if(fe)J.push(fe);oe+=2;continue}if(ie.startsWith("-c")&&ie.length>2){let fe=pc(ie.slice(2));if(fe)J.push(fe);oe++;continue}if(ie==="--config-env"){let fe=Zf(W[oe+1],G,H);if(fe)J.push(fe);oe+=2;continue}if(ie.startsWith("--config-env=")){let fe=Zf(ie.slice(13),G,H);if(fe)J.push(fe);oe++;continue}if(_n.has(ie)){oe+=2;continue}oe++}return J}function p_(W,G){let H=g_(W,G),J=h_(W,G);return{blockedReason:H===null||J===null?fc:null,entries:[...H??[],...J??[]]}}function g_(W,G){let H=ar("GIT_CONFIG_PARAMETERS",W,G);if(H===void 0)return[];let J=[],oe=_i(H);if(!oe)return null;for(let ie of oe){let fe=pc(ie);if(!fe)return null;J.push(fe)}return J}function h_(W,G){let H=Um(W,G);if(H.state==="absent")return[];if(H.state==="invalid")return null;let J=[];for(let oe=0;oe<H.count;oe++){let ie=ar(`GIT_CONFIG_KEY_${oe}`,W,G)?.trim(),fe=ar(`GIT_CONFIG_VALUE_${oe}`,W,G);if(!ie||fe===void 0)return null;J.push({key:ie,value:fe})}return J}function pc(W){if(!W)return null;let G=W.indexOf("=");return{key:(G===-1?W:W.slice(0,G)).trim(),value:G===-1?void 0:W.slice(G+1)}}function Zf(W,G,H){let J=W?.indexOf("=")??-1;if(!W||J===-1)return null;return{key:W.slice(0,J).trim(),value:ar(W.slice(J+1),G,H)}}function y_(W){let G=W?.trimStart();if(!G||G.startsWith("!"))return null;return _i(G)}var S_="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",b_="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",C_="git checkout --force discards uncommitted changes. Use 'git stash' first.",v_="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",E_="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",R_="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",__="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",x_="git switch --force discards uncommitted changes. Use 'git stash' first.",w_="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",A_="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",P_="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",T_="git reset --merge can lose uncommitted changes. Use 'git stash' first.",I_="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",k_="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.",O_="git push --force destroys remote history. Use --force-with-lease for safer force push.",M_="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",D_="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",N_="git branch -D force-deletes without merge check. Use -d for safe delete.",L_="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",W_="git merge --abort discards merge conflict resolutions. Use 'git status' first.",G_="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",F_="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",z_="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",$_="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",B_="git worktree remove --force can delete uncommitted changes. Remove --force flag.",U_=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),H_=new Set(["--recurse-submodules","--track","-t"]),gc=new Set(["-b","-B","-U"]),hc=new Set(["-c","-C"]),j_=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function $t(W,G){let H=W.split("=",1)[0]??W;return H.length>=4&&G.startsWith(H)&&H.startsWith("--")&&H.slice(2).length>=2}var wo=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function ep(W,G){let{subcommand:H,rest:J}=Pn(W);if(!H)return null;switch(H.toLowerCase()){case"checkout":return _r(V_(J,G));case"switch":return _r(q_(J));case"restore":return _r(Z_(J));case"reset":return J_(J);case"clean":return _r(ex(J));case"rm":return _r(tx(J));case"push":return qr(nx(J));case"branch":return qr(ix(J));case"stash":return qr(dx(J));case"worktree":return qr(ux(J));case"rebase":return _r(sx(J));case"merge":return _r(ax(J));case"tag":return qr(lx(J));case"reflog":return qr(cx(J));default:return null}}function _r(W){return W?{...W,localDiscard:!0}:null}function qr(W){return W?{...W,localDiscard:!1}:null}function V_(W,G){let{index:H,before:J}=dn(W),oe=Cn(J,{shortOptsWithValue:gc});if(J.some((Re)=>$t(Re,"--force"))||oe.has("-f"))return Pt("git.checkout-force",C_);for(let Re of W){if(Re==="-b"||Re==="-B"||Re==="--orphan")return null;if($t(Re,"--pathspec-from-file"))return Pt("git.checkout-pathspec-from-file",E_)}if(H!==-1){if(J.some((Te)=>!Te.startsWith("-")))return Pt("git.checkout-ref-path",v_);return Pt("git.checkout-double-dash",S_)}let ie=Y_(W);if(ie.length>=2)return Pt("git.checkout-ambiguous",R_);let fe=ie[0];if(fe===void 0||oe.has("-d")||oe.has("-t")||W.some((Re)=>$t(Re,"--detach")||$t(Re,"--track")))return null;if(K_(fe)||G(fe))return Pt("git.checkout-double-dash",b_);return null}function K_(W){return W==="."||W===".."||/^\.\.?[/\\]/.test(W)||/^([/\\]|[A-Za-z]:[/\\])/.test(W)||W.endsWith("/")||W.startsWith(":")||/[*?[]/.test(W)}function q_(W){let{before:G}=dn(W);if(G.some((J)=>$t(J,"--discard-changes")))return Pt("git.switch-discard-changes",__);let H=Cn(G,{shortOptsWithValue:hc});if(G.some((J)=>$t(J,"--force"))||H.has("-f"))return Pt("git.switch-force",x_);return null}function Y_(W){let G=[],H=0;while(H<W.length){let J=W[H];if(!J)break;if(J==="--")break;if(!J.startsWith("-")){G.push(J),H++;continue}if(U_.has(J)){H+=2;continue}if(H_.has(J)){let oe=W[H+1],ie=J==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"];H+=oe&&!oe.startsWith("-")&&ie.includes(oe)?2:1;continue}H++}return G}function Z_(W){let G=X_(W);if(G.isTerminal||!G.hasPathspec&&!G.hasPatch||!G.hasWorktree)return null;return G.hasExplicitLocation?Pt("git.restore-worktree",A_):Pt("git.restore-unstaged",w_)}function X_(W){let G=!1,H=!1,J=!0,oe=!1,ie=(fe)=>{if(!oe)J=!1,oe=!0;if(fe!==void 0)J=fe};for(let fe=0;fe<W.length;fe++){let Re=W[fe];if(Re===void 0)break;if(Re==="--"){G||=fe+1<W.length;break}if(Re==="--pathspec-from-file"){G=!0,fe++;continue}if(Re.startsWith("--pathspec-from-file=")){G=!0;continue}if(Re==="-h"||Re==="--help"||Re==="--version")return{hasPathspec:G,hasPatch:H,hasWorktree:J,hasExplicitLocation:oe,isTerminal:!0};if(Re==="--staged"){ie();continue}if(Re==="--no-staged"){ie();continue}if(Re==="--worktree"){ie(!0);continue}if(Re==="--no-worktree"){ie(!1);continue}if(Re==="--patch"){H=!0;continue}if(Re==="--no-patch"){H=!1;continue}if(j_.has(Re)){fe++;continue}if(Re.startsWith("--"))continue;if(Re==="-"){G=!0;continue}if(!Re.startsWith("-")){G=!0;continue}for(let Te=1;Te<Re.length;Te++){let ke=Re.charAt(Te);if(ke==="h")return{hasPathspec:G,hasPatch:H,hasWorktree:J,hasExplicitLocation:oe,isTerminal:!0};if(ke==="S"){ie();continue}if(ke==="W"){ie(!0);continue}if(ke==="p"){H=!0;continue}if(ke==="s"||ke==="U"){if(Te===Re.length-1)fe++;break}}}return{hasPathspec:G,hasPatch:H,hasWorktree:J,hasExplicitLocation:oe,isTerminal:!1}}function J_(W){let G=null;for(let H of W){if($t(H,"--hard")){G=Pt("git.reset-hard",P_);break}if($t(H,"--merge")){G=Pt("git.reset-merge",T_);break}}if(!G)return null;return Q_(W)?qr(G):_r(G)}function Q_(W){for(let G of W){if(G==="--")return!1;if(!G.startsWith("-"))return!0}return!1}function ex(W){for(let H of W)if(H==="-n"||$t(H,"--dry-run"))return null;let G=Cn(W.filter((H)=>H!=="--"));if(W.some((H)=>$t(H,"--force"))||G.has("-f"))return Pt("git.clean-force",I_);return null}function tx(W){let G=!1,H=!1,J=!1;for(let oe of dn(W).before){if($t(oe,"--no-force")){G=!1;continue}if($t(oe,"--force")){G=!0;continue}if($t(oe,"--no-cached")){H=!1;continue}if($t(oe,"--cached")){H=!0;continue}if($t(oe,"--no-dry-run")){J=!1;continue}if($t(oe,"--dry-run")){J=!0;continue}let ie=Cn([oe]);G||=ie.has("-f"),J||=ie.has("-n")}return G&&!H&&!J?Pt("git.rm-force",k_):null}function nx(W){let{before:G,after:H}=dn(W),J=Cn(G);if(G.some((fe)=>$t(fe,"--mirror")))return Pt("git.push-mirror",D_);if(G.some((fe)=>$t(fe,"--force"))||J.has("-f")||Qf(G,H).some(rx))return Pt("git.push-force",O_);if(G.some((fe)=>$t(fe,"--delete"))||J.has("-d")||Qf(G,H).some(ox))return Pt("git.push-delete",M_);return null}function Qf(W,G){return[...W.filter((H)=>H!==""&&!H.startsWith("-")),...G]}function rx(W){return W.startsWith("+")||W.includes(":+")}function ox(W){return W.length>1&&W.startsWith(":")}function ix(W){let{before:G}=dn(W),H=Cn(G),J=H.has("-D")||H.has("-d")||G.some((ie)=>$t(ie,"--delete")),oe=H.has("-D")||H.has("-f")||G.some((ie)=>$t(ie,"--force"));if(J&&oe)return Pt("git.branch-force-delete",N_);return null}function sx(W){let{before:G}=dn(W);return G.some((H)=>$t(H,"--abort"))?Pt("git.rebase-abort",L_):null}function ax(W){let{before:G}=dn(W);return G.some((H)=>$t(H,"--abort"))?Pt("git.merge-abort",W_):null}function lx(W){let{before:G}=dn(W);return Cn(G).has("-d")||G.some((J)=>$t(J,"--delete"))?Pt("git.tag-delete",G_):null}function cx(W){return W[0]==="delete"?Pt("git.reflog-delete",F_):null}function dx(W){for(let G of W){if(G==="drop")return Pt("git.stash-drop",z_);if(G==="clear")return Pt("git.stash-clear",$_)}return null}function ux(W){let{before:G}=dn(W);if(!G.includes("remove"))return null;let J=Cn(G);if(G.some((oe)=>$t(oe,"--force"))||J.has("-f"))return Pt("git.worktree-remove-force",B_);return null}import{isAbsolute as Nx,join as Lx,resolve as Wx}from"node:path";var Sc="TMPDIR",bc="IFS",np=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,rp=/^[A-Za-z_][A-Za-z0-9_]*$/,op=new Set(["export","typeset","declare","readonly"]),mx=new Set(["builtin","command","time"]),fx=new Set(["do","then","else"]),px=new Set(["do","then","case"]),tp=new Set(["done","fi","esac"]),gx=/^[A-Za-z_][A-Za-z0-9_]*=~(?:\/|$)/,hx=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function Ao(W,G){return new Map([["HOME",G.home],...typeof G.cwd==="string"?[["PWD",G.cwd]]:[],...W])}function Po(W,G){return W.provenance==="literal"&&!W.quoted&&W.raw===W.text&&W.raw.startsWith("~/")?`${G}${W.raw.slice(1)}`:null}function ip(W,G,H){let J=Ao(G.shellAssignments,H);return W.map((oe)=>{if(!mp(oe.text))return t(oe);if(oe.provenance==="variable")return sp(oe.text,J);if(oe.provenance==="command-substitution")return Sx(oe,H.darwinUserTempDir)??t(oe);return oe.provenance==="literal"&&gx.test(oe.raw)?oe.text.replace("=~",`=${J.get("HOME")}`):t(oe)})}function sp(W,G){return W.replace(hx,(H,J,oe)=>G.get(J??oe??"")??H)}var yx=new Set(["$(getconf DARWIN_USER_TEMP_DIR)","`getconf DARWIN_USER_TEMP_DIR`"]);function Sx(W,G){if(W.provenance!=="command-substitution")return null;let H=W.parts.map((oe)=>{if(oe.provenance==="command-substitution")return yx.has(oe.raw)?G():null;return oe.provenance==="literal"&&!/[$`\\']/.test(oe.raw)?oe.raw.replaceAll('"',""):null});if(!H.every((oe)=>oe!==null))return null;let J=H.join("");return/[\s$`*?[]/.test(J)?null:J}function qn(W,G){let H=W.parts.every((oe)=>oe.provenance!=="literal"||!/[$`]/.test(oe.raw));if(W.provenance!=="variable"||!H)return null;let J=sp(W.text,G);return/^[~-]/.test(J)||/[\s$`*?[]/.test(J)?null:J}function ap(W,G){return{env:W,effectiveEnvAssignments:Ex(W,G),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function lp(W){return{env:W.env,effectiveEnvAssignments:W.effectiveEnvAssignments?new Map(W.effectiveEnvAssignments):void 0,shellAssignments:new Map(W.shellAssignments),bodyDepth:W.bodyDepth,bodyAssignments:new Set(W.bodyAssignments)}}function Cc(W,G){let H=dp(W,G),J=W[0]??"";if(px.has(J))G.bodyDepth+=1;if(J==="elif"||tp.has(J))G.bodyDepth=Math.max(0,G.bodyDepth-1);if(tp.has(J)&&G.bodyDepth===0)G.bodyAssignments.forEach((Re)=>{G.shellAssignments.delete(Re)}),G.bodyAssignments.clear();H.assignments.filter((Re)=>Re.persists).forEach((Re)=>{if(G.shellAssignments.set(Re.name,Re.value),G.bodyDepth>0)G.bodyAssignments.add(Re.name);vc(G,Re)});let oe=H.commandIndex;if(oe!==-1&&op.has(W[oe]??""))W.filter((Re)=>rp.test(Re)&&yc(Re)).forEach((Re)=>{Rx(G,Re)});let ie=oe===-1?-1:up(W,oe);if(ie===-1||W[ie]!=="unset")return;let fe=xx(W,ie);if(fe===null)return;W.slice(fe).forEach((Re)=>{if(G.bodyDepth>0){G.shellAssignments.set(Re,"");return}_x(G,Re)})}function cp(W,G){let H=dp(W,G).assignments;if(H.length===0)return G.effectiveEnvAssignments;let J=new Map(G.effectiveEnvAssignments??[]);return H.forEach((oe)=>{J.set(oe.name,oe.value)}),J}function dp(W,G){let H=fx.has(W[0]??"")?1:0,J=W.findIndex((Re,Te)=>Te>=H&&!mp(Re)),oe=J!==-1&&op.has(W[up(W,J)]??""),ie=vx(G);return{assignments:W.flatMap((Re,Te)=>{let ke=bx(Re,ie,G.env);if(!ke)return[];if(J!==-1&&Te>J&&!oe&&!ws(ke.name))return[];return ie.set(ke.name,ke.value),[{...ke,persists:J===-1||oe}]}),commandIndex:J}}function up(W,G){let H=G;while(mx.has(W[H]??"")){H+=1;while(W[H]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(W[H]??""))return G;H+=1}}return H}function mp(W){return Ln(W)!==null||np.test(W)}function bx(W,G,H){return Ln(W)??Cx(W,G,H)}function Cx(W,G,H){let J=As(W,H,G);if(J)return J;let oe=W.match(np)?.[1];if(!oe)return null;let ie=W.indexOf("=");return{name:oe,value:`${G.has(oe)?G.get(oe):H.get(oe)??""}${W.slice(ie+1)}`}}function yc(W){return W===Sc||W===bc||Hl(W)}function vx(W){return new Map([...W.effectiveEnvAssignments??[],...W.shellAssignments])}function Ex(W,G){let H=[Sc,bc].map((J)=>{let oe=W.get(J);return oe===void 0?null:[J,oe]}).filter((J)=>J!==null);if(H.length===0)return G;return new Map([...H,...G??[]])}function vc(W,G){let H=new Map(W.effectiveEnvAssignments??[]);H.set(G.name,G.value),W.effectiveEnvAssignments=H}function Rx(W,G){vc(W,{name:G,value:W.shellAssignments.get(G)??W.effectiveEnvAssignments?.get(G)??W.env.get(G)??""})}function _x(W,G){if(!yc(G)&&!rp.test(G))return;if(W.shellAssignments.set(G,""),ws(G)&&W.env.has(G)){let J=new Map(W.env);J.delete(G),W.env=J}if(!yc(G)||G===Sc||G===bc||Uo(G)){vc(W,{name:G,value:""});return}if(!W.effectiveEnvAssignments?.has(G))return;let H=new Map(W.effectiveEnvAssignments);H.delete(G),W.effectiveEnvAssignments=H.size===0?void 0:H}function xx(W,G){let H=G+1;while(H<W.length){let J=W[H];if(!J)return null;if(J==="--")return H+1;if(J==="-v"){H++;continue}if(J.startsWith("-"))return null;return H}return H}import{dirname as pp,join as Zs,resolve as wx}from"node:path";function Xs(W,G){return Ul.some((H)=>G?.has(H)||W.has(H))}function To(W,G,H){if(!G)return{gitCwd:null,hasExplicitGitContext:!1};let J=H.realpath(wx(G));if(J===null||!H.isDirectory(J))return{gitCwd:null,hasExplicitGitContext:!1};let oe=J,ie=!1,fe=1;while(fe<W.length){let Re=W[fe];if(!Re)break;if(Re==="--")break;if(!Re.startsWith("-"))break;if(Re==="-C"){let Te=W[fe+1];if(!Te)return{gitCwd:null,hasExplicitGitContext:ie};let ke=fp(oe,Te,H);if(!ke)return{gitCwd:null,hasExplicitGitContext:ie};oe=ke,fe+=2;continue}if(Re.startsWith("-C")&&Re.length>2){let Te=fp(oe,Re.slice(2),H);if(!Te)return{gitCwd:null,hasExplicitGitContext:ie};oe=Te,fe++;continue}if(Re==="--git-dir"||Re==="--work-tree"){ie=!0,fe+=2;continue}if(Re.startsWith("--git-dir=")||Re.startsWith("--work-tree=")){ie=!0,fe++;continue}fe+=_n.has(Re)?2:1}return{gitCwd:oe,hasExplicitGitContext:ie}}function fp(W,G,H){try{let J=Sr(W,G,H);return H.isDirectory(J)?J:null}catch{return null}}function xi(W,G){if(G.entryKind(Zs(W,".git"))!=="missing")return W;let H=pp(W);return H===W?null:xi(H,G)}function Js(W,G,H,J,oe){let ie=J.paths,fe=Zs(H,".git"),Re=ie.isDirectory(fe),Te=Re&&!J.isGitDirectory(fe),ke=gp(G).filter((Le)=>Te||Le!==H&&Rr(Le,H));return xo(W,J.env,oe).entries.some((Le)=>Le.key.toLowerCase()==="core.worktree")||ke.some((Le)=>ie.entryKind(Zs(Le,"HEAD"))!=="missing"||Le!==H&&ie.entryKind(Zs(Le,".git"))!=="missing")||Re&&J.gitDirectoryRedirects(fe)}function gp(W){let G=pp(W);return G===W?[W]:[W,...gp(G)]}function hp(W,G,H){if(!G.localDiscard||!H.worktreeMode||Xs(H.environment.env,H.envAssignments))return null;let J=To(W,H.cwd,H.environment.paths);if(!J.gitCwd||J.hasExplicitGitContext)return null;let oe=H.environment.worktreeFacts(J.gitCwd),ie=xi(J.gitCwd,H.environment.paths);if(!oe||ie===null||Js(W,J.gitCwd,ie,H.environment,H.envAssignments))return null;if(Ec(W,H,oe))return null;return{kind:"worktree",originalReason:G.reason,gitCwd:J.gitCwd}}function Ec(W,G,H){let{subcommand:J,rest:oe}=Pn(W),ie=J?.toLowerCase();if(G.dynamicArguments||Ax(oe)||Ox(W,G.environment.env,G.envAssignments,H)||Ix(oe)||Px(ie,oe))return!0;return ie==="clean"&&kx(oe)>1}function Ax(W){return W.some((G)=>/[$*?[]/.test(G))}function Px(W,G){if(W==="checkout"){let{before:H}=dn(G),J=Cn(H,{shortOptsWithValue:gc}),oe=H.some((fe)=>$t(fe,"--force"))||J.has("-f"),ie=J.has("-B")||H.some((fe)=>fe==="-B"||fe.startsWith("-B"));return oe&&ie}if(W==="switch"){let{before:H}=dn(G),J=Cn(H,{shortOptsWithValue:hc}),oe=H.some((fe)=>$t(fe,"--force"))||H.some((fe)=>$t(fe,"--discard-changes"))||J.has("-f"),ie=H.some((fe)=>fe==="-C"||fe.startsWith("-C")||Tx(fe))||J.has("-C");return oe&&ie}return!1}function Tx(W){let G=W.split("=",1)[0]??W;return G==="--force-create"||G.length>=9&&"--force-create".startsWith(G)}function Ix(W){return W.some((G)=>G.startsWith("--recurse-sub"))}function kx(W){let G=0;for(let H of W){if(H==="--force"){G++;continue}if(H.startsWith("-")&&!H.startsWith("--")){for(let J of H.slice(1))if(J==="f")G++}}return G}function Ox(W,G,H,J){if(ar("GIT_CONFIG_PARAMETERS",G,H)!==void 0)return!0;let oe=xo(W,G,H);if(oe.blockedReason!==null)return!0;let ie=oe.entries.map((Re)=>({key:Re.key.toLowerCase(),value:Re.value}));if(ie.some((Re)=>Dx(Re.key)))return!0;let fe=ie.filter((Re)=>Re.key==="submodule.recurse").at(-1);if(fe)return fe.value===void 0||Mx(fe.value);if(jm(H))return!0;return J.recursiveSubmodules}function Mx(W){let G=W.toLowerCase();return G!=="false"&&G!=="no"&&G!=="off"&&G!=="0"}function Dx(W){return W==="include.path"||W.startsWith("includeif.")&&W.endsWith(".path")}function yp(W,G,H){let J=W.map((Te)=>qn(Te,H.shellAssignments??new Map)??t(Te)),oe=H.environment.paths,ie=To(J,H.cwd,oe),fe=H.originalCwd?oe.realpath(Wx(H.originalCwd)):null;if(G.id.startsWith("git.push-")||fe===null||ie.gitCwd===null||ie.hasExplicitGitContext||Xs(H.environment.env,H.envAssignments))return null;let Re=G.id==="git.worktree-remove-force"?Fx(W,H.shellAssignments,oe):xi(ie.gitCwd,oe);if(Re===null||G.id!=="git.worktree-remove-force"&&!Gx(Re,ie.gitCwd,J,G,H)||!Ro(Re,H.environment)||$s(Re,H.environment)||Rr(fe,Re)||Rr(Re,fe))return null;return{kind:"temp-root",originalReason:G.reason,gitCwd:ie.gitCwd}}function Gx(W,G,H,J,oe){let ie=oe.environment.paths,fe=Lx(W,".git");if(ie.entryKind(fe)!=="present"||Js(H,G,W,oe.environment,oe.envAssignments))return!1;if(ie.isDirectory(fe))return!0;if(!J.localDiscard)return!1;let Te=oe.environment.worktreeFacts(W);return Te!==null&&!Ec(H,oe,Te)}function Fx(W,G,H){let J=Pn(W.map(t)).rest,{before:oe,after:ie}=dn(J.slice(J.indexOf("remove")+1)),fe=[...oe.filter((Le)=>!Le.startsWith("-")),...ie],Re=fe.length===1?fe[0]??"":"",Te=W.find((Le)=>Le.text===Re),ke=(Te&&qn(Te,G??new Map))??Re;if(!Nx(ke)||/[\s$`*?[]/.test(ke)||H.entryKind(ke)!=="present"||!H.isDirectory(ke))return null;return H.realpath(ke)}var $x="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.",Bx=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function Qs(W,G){return Sp(W,G)}function Sp(W,G,H){let J=W.map(t),oe=Xf(J,G.environment.env,G.envAssignments),ie=oe.blockedReason?Lt(Pt("git.alias-config",oe.blockedReason),G.policy):null;if(ie)return ie;let fe=oe.tokens;if((Hm(G.envAssignments)||Jf(J,G.environment.env,G.envAssignments))&&Ux(fe))return Pt("git.ssh-env",$x);let Re=ep(fe,(ke)=>{let Le=To(J,G.cwd,G.environment.paths).gitCwd;return Le!==null&&G.environment.paths.entryKind(zx(Le,ke))!=="missing"});if(!Re)return null;if(oe.expanded||oe.blockedReason)return Re;let Te=hp(J,Re,G)??yp(W,Re,G);if(!Te)return Re;return H?.(Te),null}function bp(W,G){let H=null;return{match:Sp(W,G,(oe)=>{H=oe}),relaxation:H}}function Ux(W){let{subcommand:G,rest:H}=Pn(W),J=G?.toLowerCase();if(!J)return!1;if(Bx.has(J))return!0;if(J==="archive")return dn(H).before.some((oe)=>$t(oe,"--remote"));return J==="remote"&&Hx(H)}function Hx(W){return W.find((G)=>!jx(G))?.toLowerCase()==="update"}function jx(W){return W==="-v"||$t(W,"--verbose")||$t(W,"--no-verbose")}import{isAbsolute as vw}from"node:path";function Cp(W,G,H,J){let oe=W.slice(0,G),ie=W.slice(G+H);return J.startsWith(oe)&&J.endsWith(ie)?J.slice(oe.length,J.length-ie.length):null}function ea(W,G,H){let J=(ie)=>`${ie.tokenIndex}\x00${ie.kind}\x00${ie.value}`,oe=new Set(W.map(J));return Array.from(G).some((ie)=>H(ie).some((fe)=>!oe.has(J(fe))))}var vp="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Vx="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.",Kx="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",qx="rm -rf targeting root or home directory is extremely dangerous and always blocked.",Yx="rm -rf in home directory is dangerous. Change to a project directory first.",Ep={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:qx},git_metadata_target:{id:"rm.git-metadata",reason:v},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:Kx},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:Yx},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:vp},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:Vx},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:vp}};function ta(W,G){let H=er({...G,allowPaths:G.policy?.destructiveCommandAllowPaths,posixShell:!0}),J=W.map(t),oe=Ks(J),ie=Xx(W);for(let fe of ie){let Re=bi(fe.word);if(oe&&Re.unsafeBraceExpansion){let Te=Lt(jr({kind:"outside_anchored_cwd"},H,G.policy,Ep),G.policy);if(Te)return Te;continue}for(let Te of Re.expandedTargets??[fe.text]){let ke=fn(Te),Le={targetIsLiteral:Re.expandedTargets!==void 0||Re.targetIsLiteral,tmpdirWordSplittingProtected:Re.tmpdirWordSplittingProtected};if(!oe&&H.resolvedCwd&&Br(ke,H.resolvedCwd,H.protectedGitMetadata,oe,H.environment,H.budget))return Pt("rm.git-metadata",v);if(!oe)continue;for(let Xe of Zx(ke,H,Le)){let Ye=jr(Xe,H,G.policy,Ep),Ze=Lt(Ye,G.policy);if(Ze)return Ze}}}return null}function Zx(W,G,H){let J=An(W,G,H);if(J.kind==="cwd_self_target")return[J,An(W,G,{...H,skipCwdSelf:!0})];if(J.kind!=="home_cwd_target")return[J];let oe=An(W,G,{...H,skipHomeCwd:!0});if(oe.kind!=="cwd_self_target")return[J,oe];return[J,oe,An(W,G,{...H,skipHomeCwd:!0,skipCwdSelf:!0})]}function Xx(W){let G=[],H=!1;for(let J of W.slice(1)){let oe=t(J);if(!oe)continue;if(oe==="--"){H=!0;continue}if(H){G.push({text:oe,word:J});continue}if(!oe.startsWith("-"))G.push({text:oe,word:J})}return G}var xr={kind:"none"},Yr={kind:"dynamic"},Jx=new Set(["<","<<","<<-","<<<","<&","<>"]),_p=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,Qx=/^(?:[0-9]+|[@*])$/,ew=yr.maxWords,xp=yr.maxInputLength;function wp(W){if(!W||Ft(zt(W.words[0]?.text??""))!=="printf")return;if(W.words.some((oe)=>oe.provenance!=="literal"))return;let G=W.words.slice(W.words[1]?.text==="--"?2:1),H=G[0]?.text;if(H===void 0)return"";let J=G.slice(1).map((oe)=>oe.text);if(H==="%s")return J.join("");if(H==="%s\\n"||H===`%s
35
+ `)return`${J.join(`
36
+ `)}
37
+ `;if(H.includes("%")||/\\(?![\\nrt])/.test(H))return;return H.replaceAll("\\n",`
38
+ `).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function na(W){let G=Io(W[1])==="--"?2:1;if(W.length<=G)return xr;let H=W.slice(G);if(!H.every(Ai))return Yr;return{kind:"literal",source:H.map(t).join(" ")}}function Ap(W){let G=Io(W[1])==="--"?2:1,H=W[G],J=Io(H);if(H===void 0||W.length<=G+1||J==="-"||J===""||J==="-l"||J==="-p")return xr;if(!Ai(H))return Yr;return{kind:"literal",source:J}}function ra(W,G){let H=Ip(W);if(H===-1)return xr;let J=nw(G);if(!J)return xr;let oe=[],ie=J.command?.length??0;for(let fe of J.references){let Re=ow(fe,W,H,J.ifs);if(!Re)return Yr;if(ie+=Re.reduce((Te,ke)=>Te+ke.length+3,0),oe.length+Re.length>ew||ie>xp)return Yr;oe.push(...Re)}if(J.command==="eval")return{kind:"literal",source:oe.join(" ")};if(oe.length===0||/\s/.test(oe[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[J.command,J.command&&J.optionTerminator?"--":null,...oe.map(Ee)].filter((fe)=>fe!==null).join(" ")}}function Pp(W,G){let H=Ip(W),J=W.slice(H+1),oe=/\bIFS\b/.test(G);if(H===-1||!J.every(Ai)||oe)return G;let ie=J.map(Io),fe="",Re=null,Te=0;while(Te<G.length){let ke=G[Te]??"",Le=Re==="'"?null:/^\$(?:\{([0-9]+|[@*])\}|([0-9@*]))/.exec(G.slice(Te));if(Le){let Xe=Le[1]??Le[2],Ye=Xe==="@"||Xe==="*"?ie.slice(1):[ie[Number(Xe)]??""];if(Re!=='"'&&Ye.some((Qe)=>/[*?[]/.test(Qe)))return G;if(fe+=Re==='"'?Ye.map((Qe)=>Qe.replace(/["$`\\]/g,"\\$&")).join(Xe==="@"?'" "':" "):Ye.map((Qe)=>Qe.split(/[ \t\n]+/).map((et)=>et?Ee(et):"").join(" ")).join(" "),fe.length>xp)return G;Te+=Le[0].length;continue}if(ke==="\\"&&Re!=="'"){fe+=G.slice(Te,Te+2),Te+=2;continue}if(ke==="'"&&Re!=='"'||ke==='"'&&Re!=="'")Re=Re?null:ke;fe+=ke,Te++}return fe}function Tp(W,G,H,J){if(!Dn(W.map(t)).readsStdinAsCommands)return xr;let oe=G.filter((ie)=>(ie.fd===void 0||ie.fd===0)&&Jx.has(ie.operator)).at(-1);if(oe){if(oe.operator==="<<"||oe.operator==="<<-")return xr;if(oe.operator!=="<<<"||oe.target?.provenance!=="literal")return Yr;return{kind:"literal",source:oe.target.text}}if(!H)return xr;return J===void 0?Yr:{kind:"literal",source:J}}function mr(W,G,H=new Map){let J=Dn(W.map(t)).scriptIndex;if(J===null)return xr;let oe=W[J],ie=oe&&G!==void 0?Po(oe,G):null;if(ie!==null)return{kind:"literal",source:ie};let fe=Io(oe);if(po(oe,fe))return{kind:"literal",source:fe};let Re=oe?qn(oe,H):null;return Re===null?Yr:{kind:"literal",source:Re}}var tw=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function wc(W){if(W.words.length!==2||W.redirections.length!==0||W.nested.length!==1)return!1;let G=W.words[0],H=W.words[1];if(!G||G.provenance!=="literal"||G.quoted||G.raw!==G.text||!H)return!1;if(!(G.text==="eval"&&H.quoted&&H.parts.length===3&&H.parts[0]?.raw==='"'&&H.parts[1]?.provenance==="command-substitution"&&H.parts[1].raw.startsWith("$(")&&H.parts[2]?.raw==='"'||G.text==="eval"&&!H.quoted&&H.parts.length===1&&H.parts[0]?.provenance==="command-substitution"&&H.parts[0].raw.startsWith("$(")||(G.text==="source"||G.text===".")&&!H.quoted&&H.parts.length===1&&H.parts[0]?.provenance==="command-substitution"&&H.parts[0].raw.startsWith("<(")))return!1;let oe=W.nested[0];if(oe?.status!=="complete"||oe.nodes.length!==1)return!1;let ie=oe.nodes[0];if(ie?.kind!=="command"||ie.redirections.length!==0||ie.nested.length!==0||ie.words.some((Te)=>Te.provenance!=="literal"||Te.parts.some((ke)=>ke.provenance!=="literal")))return!1;let fe=ie.words[0]?.text;if(fe===void 0||Ln(fe)!==null)return!1;let Re=Ft(zt(fe));return!tw.has(Re)&&!tn.has(Re)&&!Vr(Re)}function Ip(W){return Dn(W.map(t)).commandIndex??-1}function nw(W){let G=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(W.trim()),H=G?.[4]??W.trim(),J=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(H),oe=(J?.[3]??H).split(/\s+/).map(rw);if(oe.length===0||oe.some((ie)=>ie===null))return null;return{command:J?.[1]??null,optionTerminator:J?.[2]!==void 0,references:oe.filter((ie)=>!!ie),ifs:G?G[1]??G[2]??G[3]??"":`
39
+ `}}function rw(W){let G=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(W),H=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(W),J=G??H;if(!J)return null;let oe=J[1]??J[2];return{parameter:oe==="@"||oe==="*"?oe:Number(oe),quoted:G!==null}}function ow(W,G,H,J){let oe=G.slice(H+2);if(W.parameter==="@")return W.quoted?Rc(oe):iw(oe,J);if(W.parameter==="*"){let Re=Rc(oe);if(!Re)return;let Te=Re.join(J[0]??"");return W.quoted?[Te]:_c(Te,J)}let ie=G[H+1+W.parameter];if(ie&&!Ai(ie))return;let fe=Io(ie);return W.quoted?[fe]:_c(fe,J)}function Rc(W){return W.every(Ai)?W.map(t):void 0}function iw(W,G){let H=Rc(W);if(!H)return;let J=H.map((oe)=>_c(oe,G));return J.some((oe)=>oe===void 0)?void 0:J.flatMap((oe)=>oe??[])}function _c(W,G){if(["*","?","[","]"].some((H)=>W.includes(H)))return;if(G==="")return W===""?[]:[W];if(G===`
40
+ `)return W.trim().split(/\s+/).filter(Boolean);if(G.length!==1)return;return G===" "||G==="\t"||G===`
41
+ `?W.trim().split(/\s+/).filter(Boolean):W.split(G).filter(Boolean)}function Ai(W){if(!W)return!0;return W.provenance==="unknown"?!/[$`]/.test(t(W)):W.provenance==="literal"}function Io(W){return W?t(W):""}function Ee(W){return`'${W.replaceAll("'",`'"'"'`)}'`}function Ac(W,G){return xc(y(W,"posix"),G)}function Pi(W){return Ac(W,new Set(Array.from(W.matchAll(_p)).flatMap((G)=>{let H=G[1]??G[2];return H===void 0?[]:[H]})))}function xc(W,G){if(W.status==="invalid"||W.status==="limited")return!1;let H=new Set(G);for(let J of W.nodes){if(J.kind==="group"){if(xc(J.body,H))return!0;continue}if(J.kind!=="command")continue;if(J.nested.some((oe)=>xc(oe,H))||kp(J.words,H))return!0;dw(J,H)}return!1}function kp(W,G){let H=W.findIndex((fe)=>Ln(fe.text)===null);if(H===-1)return!1;let J=W[H];if(!J)return!1;if(wi(J,G))return!0;let oe=zt(J.text);if(oe==="source"||oe==="."){let fe=W[H+1]?.text==="--"?H+2:H+1;return Rp(W[fe],G)}if(tn.has(oe)){let fe=W.slice(H),Re=fe.map((Le)=>Le.text),Te=Dn(Re),ke=Te.commandIndex??Te.scriptIndex;return!Kn(Re)&&ke!==null&&Rp(fe[ke],G)}let ie=sw(W,H,G);if(ie===null)return!1;if(ie===-1)return!0;return kp(W.slice(ie),G)}function sw(W,G,H){let J=zt(W[G]?.text??"");if(J==="command")return aw(W,G+1);if(J==="exec")return lw(W,G+1);if(J==="env")return cw(W,G+1,H);return null}function aw(W,G){for(let H=G;H<W.length;H++){let J=W[H]?.text??"";if(J==="--")return W[H+1]?H+1:null;if(/^-[p]*[vV][pvV]*$/.test(J))return null;if(/^-p+$/.test(J))continue;return H}return null}function lw(W,G){for(let H=G;H<W.length;H++){let J=W[H]?.text??"";if(J==="--")return W[H+1]?H+1:null;if(J==="-a"){H++;continue}if(/^-a.+/.test(J)||/^-[cl]+$/.test(J))continue;return H}return null}function cw(W,G,H){for(let J=G;J<W.length;J++){let oe=W[J],ie=oe?.text??"";if(ie==="--")return W[J+1]?J+1:null;if(ie==="-S"||ie==="--split-string")return wi(W[J+1],H)?-1:J+2;if(ie.startsWith("-S")||ie.startsWith("--split-string="))return wi(oe,H)?-1:J+1;if(ie==="-u"||ie==="--unset"||ie==="-C"||ie==="--chdir"||ie==="-P"){J++;continue}if(ie==="-i"||ie==="-0"||ie==="--null"||ie.startsWith("-u=")||ie.startsWith("--unset=")||ie.startsWith("-C")||ie.startsWith("--chdir=")||ie.startsWith("-P"))continue;if(ie.startsWith("-"))continue;if(Ln(ie))continue;return J}return null}function dw(W,G){if(!W.words.every((H)=>Ln(H.text)!==null))return;for(let H of W.words){let J=Ln(H.text);if(!J)continue;if(wi(H,G))G.add(J.name)}}function wi(W,G){if(!W)return!1;return W.parts.filter((H)=>H.provenance==="variable").some((H)=>Array.from(H.raw.matchAll(_p)).some((J)=>{let oe=J[1]??J[2];return oe!==void 0&&(Qx.test(oe)||G.has(oe))}))}function Rp(W,G){return!!W&&(W.parts.some((H)=>H.provenance!=="literal"&&H.provenance!=="variable")||wi(W,G))}var Pc="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",Tc="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",uw="__CC_SAFETY_NET_XARGS_INPUT__",oa="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",ia="rm",mw=/(?:^|[;&|]\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,fw=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,pw=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,gw=/^(?:[0-9]+|[@*])$/;function Dp(W,G){let H=W.map(t),{childStart:J,replacementToken:oe}=Zr(H),ie=H.slice(J),fe=Pt("xargs.shell-dynamic",Tc);if(yw(ie,oe,G)&&Lt(fe,G.policy))return Lt(fe,G.policy);for(let Re of Vn(ie,G)){let Te=Re.tokens,ke=oe!==null&&Te[0]!==ie[0]&&(Te[0]?.includes(oe)??!1)?Lt(fe,G.policy):null;if(ke)return ke;let Le=zp(Te,oe,Re.wrapperEnvAssignments),Xe=Re.head==="rm"&&oe!==null&&Gp(Te,oe),Ye=G.analyzeChild(Te,{...Kr(Re,G),dynamicInput:Le,dynamicSourceInput:Xe||Lp(Te,Re.head,oe,Re.wrapperEnvAssignments,Le,G.environment,G.strict?void 0:G.analyzeNested),dynamicRmInput:Xe,shellDynamicMatch:fe,dynamicSourceMatch:fe,rmDynamicMatch:Pt("xargs.rm-recursive-force-dynamic",Pc)});if(Ye)return Ye;let Ze=hw(Te,oe,G.policy?.rules??[],Lt(fe,G.policy));if(Ze)return Ze;if(Re.head==="git"){let et=oe===null?[...Te,uw]:Te,tt=oe!==null&&(Te.some((_t)=>_t.includes(oe))||Array.from(Re.envAssignments.values()).some((_t)=>_t.includes(oe))),gt=G.analyzeChild(et,{...Kr(Re,G),worktreeMode:oe===null||tt?!1:G.worktreeMode});if(gt)return gt}let Qe=N(Te,G.policy?.rules??[]);if(Qe)return Qe}return null}function hw(W,G,H,J){if(H.length===0)return null;if(G===null){for(let ie of H){let fe=N([...W,...ie.subcommand?[ie.subcommand]:[],...ie.block_args],H);if(fe)return fe}return null}let oe=zt(W[0]??"");if(!H.some((ie)=>zt(ie.command)===oe))return null;return W.slice(1).some((ie)=>ie.includes(G))?J:null}function Np(W,G,H){let J=W.indexOf(G);if(J===-1||W.indexOf(G,J+G.length)!==-1)return[];let oe=Cp(W,J,G.length,H);return oe===null?[]:[oe]}function Lp(W,G,H,J,oe,ie,fe){if(tn.has(G)){if(Kn(W))return!1;if(H!==null&&Sw(W,H,fe))return!0;let Re=Wn(W);if(!Re){let Te=mr(Qt(W));if(Te.kind==="literal")return H!==null&&Te.source.includes(H);return Te.kind==="none"&&oe}if(H!==null&&Re.includes(H)&&!Wp(Re,H,fe))return!0;if(Nn(Re))return!0;return bw(Re,H,J)}if(Bn(G))return Op(W,H,_s,Fm(G));if(Mn.has(G))return Op(W,H,sc,zf);if(G==="eval"){let Re=na(Qt(W));if(Re.kind==="dynamic")return!0;if(H!==null)return Re.kind==="literal"&&Re.source.includes(H);return oe}if(G==="find")return Cw(W,H,ie);if(G==="git"){let Re=Pn(W);return H===null?Re.subcommand===null:(Re.subcommand?.includes(H)??!1)||Re.subcommand!==null&&wo.has(Re.subcommand.toLowerCase())&&Fp(Re.rest,H).some((Te)=>Te.includes(H))}return!1}function Wp(W,G,H){if(H===void 0)return!1;let J=G.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+)*["']?${J}`).test(W)||/\bcase\b/.test(W))return!1;let ie=W.replaceAll(G,"/");return Nn(ie)===null&&H(ie)===null}function Op(W,G,H,J){let oe=H(W);if(G===null)return oe.optionsOpen||H([...W,oa]).sources.some((Re)=>Re.value===oa);if(oe.sources.some((Re)=>Re.value.includes(G)))return!0;let ie=J.flatMap((Re)=>[Re.selector,...Re.valueForm==="attached-only"||Re.valueForm==="attached-or-separate"?[`${Re.selector}${oa}`]:[],...Re.valueForm==="equals-or-separate"?[`${Re.selector}=${oa}`]:[]]),fe=new Set(ie.flatMap((Re)=>W.flatMap((Te)=>Np(Te,G,Re))));return ea(oe.sources,fe,(Re)=>H(W.map((Te)=>Te.replaceAll(G,Re))).sources)}function yw(W,G,H){if(W.length===0||(W[0]??"").toLowerCase()==="command")return!1;let J=new Set(Array.from(Vn(W,H),(ie)=>ie.head)),oe=G===null?[...W,ia]:W.map((ie,fe)=>fe===0?ie:ie.replaceAll(G,ia));return Array.from(Vn(oe,H)).some((ie)=>ie.head===ia&&!J.has(ia))}function Gp(W,G){return Fp(W.slice(1),G).some((H)=>H.includes(G)&&(H.startsWith("-")||H.startsWith(G)))}function Fp(W,G){let H=W.findIndex((J)=>J==="--"&&!J.includes(G));return H===-1?W:W.slice(0,H)}function zp(W,G,H){if(G===null)return!0;return W.some((J)=>J.includes(G))||Array.from(H.values()).some((J)=>J.includes(G))}function Sw(W,G,H){let J=Dn(W),oe=J.commandIndex===null?"":W[J.commandIndex]??"";if(oe.includes(G)&&!Wp(oe,G,H)||J.scriptIndex!==null&&(W[J.scriptIndex]??"").includes(G))return!0;return["-c","-nc","-cn",`--${G}`,G].some((fe)=>W.some((Re,Te)=>{if(Te===0||!Re.includes(G))return!1;return Np(Re,G,fe).some((Le)=>{let Xe=W.map((Ze,Qe)=>Qe===Te?Ze.replaceAll(G,Le):Ze),Ye=Dn(Xe);if(Ye.commandIndex===null&&Ye.scriptIndex===null)return!1;if(J.commandIndex===null&&Ye.commandIndex!==null)return!0;if(J.scriptIndex===null&&Ye.scriptIndex!==null)return!0;if(Ye.commandIndex!==null&&(Xe[Ye.commandIndex]??"").includes(Le))return!0;return Ye.scriptIndex!==null&&(Xe[Ye.scriptIndex]??"").includes(Le)})}))}function bw(W,G,H){let J=new Set(G===null?[]:Array.from(H).filter(([,oe])=>oe.includes(G)).map(([oe])=>oe));for(let oe of W.matchAll(mw))if(Mp(oe,J))return!0;for(let oe of W.matchAll(fw))for(let ie of(oe[1]??"").matchAll(pw))if(Mp(ie,J))return!0;return Ac(W,J)}function Mp(W,G){let H=W[1]??W[2];return H!==void 0&&(gw.test(H)||G.has(H))}function Cw(W,G,H){if(G===null)return!0;let J=!1,oe=0;for(let ie=1;ie<W.length;ie++){let fe=W[ie]??"";if(!J&&!fe.startsWith("-")&&fe!=="!"&&fe!=="("){if(fe.indexOf(G)===0)return!0;continue}if(J=!0,oe>0){oe--;continue}if(tr(fe)){let Te=_o(W,ie);ie=Te.nextIndex-1;for(let ke of Vn(Te.tokens,{environment:H,cwd:void 0})){let Le=zp(ke.tokens,G,ke.wrapperEnvAssignments);if(ke.head==="rm"&&Gp(ke.tokens,G)||Lp(ke.tokens,ke.head,G,ke.wrapperEnvAssignments,Le,H))return!0}continue}let Re=ur(fe);if(Re>0){if(oe=Re,fe.includes(G))return!0;continue}if(fe.includes(G))return!0}return!1}function Zr(W){let G=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"]),H=null,J=1;while(J<W.length){let oe=W[J];if(!oe)break;if(oe==="--")return{childStart:J+1,replacementToken:H};if(!oe.startsWith("-"))return{childStart:J,replacementToken:H};if(oe==="-I"){H=W[J+1]??"{}",J+=2;continue}if(oe.startsWith("-I")&&oe.length>2){H=oe.slice(2),J++;continue}if(oe==="--replace"){H="{}",J++;continue}if(oe.startsWith("--replace=")){let ie=oe.slice(10);H=ie===""?"{}":ie,J++;continue}if(oe==="-J"){H=W[J+1]??"{}",J+=2;continue}J+=G.has(oe)?2:1}return{childStart:W.length,replacementToken:H}}var Ti="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",Ii="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",Ew="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",Rw="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",aa=/\{[^{}\s]*\}/g,$p=/\{\}|\{-?\d+\}/g,Bp=/[\s;&|<>()$`\\"']/,_w=["e","f","source","file","-e","-f","--source","--file"],xw=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],ww=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),Aw=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),Up=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),Pw=new Set(["--workdir","--wd"]),Hp="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Gn(W,G){for(let H of W){let J=G(H);if(J)return J}return null}function Kp(W){return Gn([...W],(G)=>Nn(G))}function qp(W,G){let H=W.map(t);if((G.envAssignments?.has("PARALLEL")?G.envAssignments.get("PARALLEL"):G.environment.env.get("PARALLEL"))?.trim()){let Qe=ko(G);if(Qe)return Qe}if(H.length===2&&(H[1]==="--version"||H[1]==="--help"))return null;let oe=sg(H),{template:ie,jobs:fe,runsRemotely:Re,readsCommandsFromInput:Te,unsupported:ke,workdir:Le,dryRun:Xe}=oe;if(ke){let Qe=ko(G);if(Qe)return Qe;let et=Kp(G.envAssignments?.values()??[]);if(et)return et}if(Te){let Qe=Nw(G);if(Qe)return Qe}if(Le!==void 0&&Re){let Qe=ko(G);if(Qe)return Qe}let Ye=Lw(Le,G.cwd,G.environment.paths);if(Ye===null){let Qe=ko(G);if(Qe)return Qe}let Ze=Re?{...G,cwd:void 0,originalCwd:void 0}:Ye===null||Ye===void 0||Ye===G.cwd?G:{...G,cwd:Ye};if(Xe){if([...Vn(ie,Ze)].flatMap((et)=>[...et.envAssignments.values()]).some(Oc)){let et=ko(G);if(et)return et}return null}if(ie.length===0){let Qe=fe.map((tt)=>tt[0]??"");G.budget.charge("derivedTokens",Qe.length);let et=eg(Ze.envAssignments,Ze.cwd,Re);return Gn(Qe,(tt)=>G.analyzeNested(tt,et))}return Gn(Vn(ie,Ze),(Qe)=>Tw(Qe,oe,G,Ze))}function Tw(W,G,H,J){let{templateHasPlaceholder:oe,runsRemotely:ie,usesStdin:fe}=G,Re=W.tokens,Te=[...W.envAssignments.values()];if(Te.some(og)){let At=ko(H);if(At)return At}let ke=Kp(Te);if(ke)return ke;let Le=Te.some(Ht),Xe=oe||Le,Ye=fe&&Xe,Ze=eg(W.envAssignments,W.wrapperCwd,ie||Ye),Qe=Xe?{...Ze,worktreeMode:!1}:Ze,et=Re.join(" "),tt=Ht(et.split(/[ \t\n=]/,1)[0]??""),gt=!G.quotesCommand&&(tt||Re.some((At)=>Bp.test(At))),_t=tt||Bp.test(Re[0]??""),yt=gt&&_t&&G.jobs.length>0?null:Iw(W,G,H,J,Qe,Le);if(yt||!gt)return yt;return Yp(Ht(et)?et:`${et} {}`,!tt,W,G,H,J,Qe)}function Iw(W,G,H,J,oe,ie){let{jobs:fe,templateHasPlaceholder:Re,runsRemotely:Te,usesStdin:ke}=G,Le=W.tokens,Xe=Re||ie;if(tn.has(W.head)){let Ze=()=>{if(!Re||fe.length===0)return null;return Gn(fe,(tt)=>H.analyzeChild(sa(Le,tt,H.budget),Kr(W,J)))};if(Kn(Le))return Ze();if(qs(Le))return Er();let Qe=Wn(Le);if(Qe){if(ig(Qe)){let yt=wr(H);if(yt)return yt;if(fe.length===0)return null;return Gn(fe,(At)=>H.analyzeNested(ng(Qe,At,H.budget),oe))}if(Ht(Qe))return Yp(Qe,!1,W,G,H,J,oe);let tt=!ie&&(!Re||fe.length>0)?(fe.length>0?fe:[void 0]).map((yt)=>ra(Qt(yt===void 0?Le:Re?Le.map((At)=>tg(At,yt)):[...Le,...yt]),Qe)):[];if(tt.some((yt)=>yt.kind==="dynamic")){let yt=wr(H);if(yt)return yt}let gt=tt.flatMap((yt)=>yt.kind==="literal"?[yt.source]:[]);if(gt.length>0)return H.budget.charge("derivedTokens",gt.length),Gn(gt,(yt)=>H.analyzeNested(yt,oe));if(Pi(Qe)){let yt=wr(H);if(yt)return yt}let _t=H.analyzeNested(Qe,oe);if(_t)return _t;if(Xe)return wr(H);return null}let et=mr(Qt(Le));if(et.kind==="dynamic"||et.kind==="literal"&&Ht(et.source))return wr(H)??Ze();if(et.kind==="literal")return Ze();if(fe.length>0){let tt=wr(H);if(tt)return tt;let gt=Ze();if(gt)return gt;if(Re)return null;let _t=fe.flatMap((yt)=>yt[0]===void 0?[]:[yt[0]]);return H.budget.charge("derivedTokens",_t.length),Gn(_t,(yt)=>H.analyzeNested(yt,oe))}if(Xe||ke)return wr(H)??Ze();return null}if(W.head==="rm"&&dr(Le)){if(Re&&fe.length>0)return Gn(fe,(Qe)=>Ic(sa(Le,Qe,H.budget,$p),W.cwd,J));if(fe.length>0)return Gn(fe,(Qe)=>Ic(Vp(Le,Qe,H.budget),W.cwd,J));let Ze=Ic(Le.flatMap((Qe,et)=>{if(et===0||!Ht(Qe))return[Qe];return Qe.startsWith("-")?[Qe.replace($p,"")]:[]}),W.cwd,J);if(Ze)return Ze;return Qp(H)}let Ye=fe.length>0?fe:[void 0];return Gn(Ye,(Ze)=>{let Qe=Ze===void 0?Le:Re?sa(Le,Ze,H.budget):Vp(Le,Ze,H.budget),et=Pt("parallel.shell-dynamic",Ii),tt=ke&&W.head==="find"?Dw(Qe,J):null,gt=Xp(Qe,ke,H)??tt?.customResult??null,_t=zt(W.head),yt=ke&&(_t==="rm"&&kc(Qe)||_t==="xargs"&&Jp(Qe)||tt?.rmOptions===!0),At=ke&&(yt||tt?.executedSource===!0||tt===null&&Zp(Qe,_t)),Ot=H.analyzeChild(Qe,{...Kr(W,J),worktreeMode:Te||ke||Xe?!1:H.worktreeMode,dynamicInput:ke||Xe,dynamicRmInput:yt,dynamicSourceInput:gt!==null||At,shellDynamicMatch:et,dynamicSourceMatch:et,rmDynamicMatch:Pt("parallel.rm-recursive-force-dynamic",Ti)});if(At){let Mt=Lt(et,H.policy);if(Mt)return Mt}return Ot??gt??N(Qe,H.policy?.rules??[])})}function Yp(W,G,H,J,oe,ie,fe){if(J.jobs.length>0)return Gn(J.jobs,(ke)=>oe.analyzeNested(ng(W,G?ke.map(Ee):ke,oe.budget),fe));let Re=_i(W);if(Re?.[0]&&zt(Re[0])==="rm"&&dr(Re)){let ke=Qp(oe);if(ke)return ke}return(Re?oe.analyzeChild(Re,{...Kr(H,ie),dynamicInput:J.usesStdin,shellDynamicMatch:Pt("parallel.shell-dynamic",Ii),rmDynamicMatch:Pt("parallel.rm-recursive-force-dynamic",Ti)}):null)??oe.analyzeNested(W,fe)}function Zp(W,G){if(Ht(W[0]??""))return!0;if(G==="eval"||G==="source"||G===".")return!0;if(G==="parallel"||G==="xargs")return!0;if(tn.has(G))return Mw(W);if(G==="git")return kw(W);if(G==="find")return!0;if(Mn.has(G))return jp(W,_w,Ei);if(Bn(G))return jp(W,xw,Rs);return!1}function kc(W){let G=W.indexOf("--"),H=W.slice(1,G===-1?void 0:G);if(!W.some(Ht))return G===-1;return H.some((oe)=>Ht(oe)&&(oe.startsWith("-")||ig(oe)))}function kw(W){if(Ow(W))return!0;let G=Pn(W);if(G.subcommand===null||Ht(G.subcommand))return!0;if(!wo.has(G.subcommand.toLowerCase()))return!1;let H=G.rest.indexOf("--"),J=G.rest.slice(0,H===-1?void 0:H);if(!W.some(Ht))return H===-1;return J.some(Ht)}function Ow(W){for(let G=1;G<W.length;G++){let H=W[G];if(!H||H==="--"||!H.startsWith("-"))return!1;if(H==="-c"||H==="--config-env"){if(Ht(W[G+1]??""))return!0;G++;continue}if(H.startsWith("-c")&&H.length>2||H.startsWith("--config-env=")){if(Ht(H))return!0;continue}if(Ht(H))return!0}return!1}function Mw(W){if(Kn(W))return!1;let G=Wn(W);if(G!==null)return Ht(G);let H=mr(Qt(W));if(H.kind==="literal")return Ht(H.source);if(H.kind==="dynamic")return!0;return!W.some(Ht)}function jp(W,G,H){let J=H(W);if(J.some((oe)=>Ht(oe.value)))return!0;if(!W.some(Ht))return H([...W,Hp]).some((oe)=>oe.value===Hp);return ea(J,G,(oe)=>H(W.map((ie)=>tg(ie,[oe]))))}function Xp(W,G,H){let J=H.policy?.rules??[];if(!G||J.length===0)return null;let oe=J.filter((ie)=>zt(ie.command)===zt(W[0]??""));if(oe.length===0)return null;if(W.slice(1).some(Ht))return wr(H);return Gn(oe,(ie)=>N([...W,...ie.subcommand?[ie.subcommand]:[],...ie.block_args],[ie]))}function Dw(W,G){let H={customResult:null,executedSource:!W.some(Ht),rmOptions:!1},J=!1,oe=0,ie=null,fe=()=>{if(!ie?.some(Ht))return;for(let Re of Vn(ie,G))H.executedSource||=Zp(Re.tokens,Re.head),H.rmOptions||=Re.head==="rm"&&kc(Re.tokens)||Re.head==="xargs"&&Jp(Re.tokens),H.customResult??=Xp(Re.tokens,!0,G)};for(let Re of W.slice(1)){if(!J&&!Re.startsWith("-")&&Re!=="!"&&Re!=="("){H.executedSource||=Ht(Re);continue}if(J=!0,ie){if(Re===";"||Re==="+"){fe(),ie=null;continue}ie.push(Re);continue}if(oe>0){oe--;continue}if(tr(Re)){ie=[],H.executedSource||=Ht(Re);continue}let Te=ur(Re);if(Te>0){oe=Te,H.executedSource||=Ht(Re);continue}H.executedSource||=Ht(Re)}return fe(),H}function Jp(W){let G=W.slice(Zr(W).childStart);return zt(G[0]??"")==="rm"&&kc(G)}function la(W,G){return(H)=>Lt(Pt(W,G),H.policy)}var wr=la("parallel.shell-dynamic",Ii),Nw=la("parallel.command-stream-dynamic",Ew),ko=la("parallel.command-stream-dynamic",Rw),Qp=la("parallel.rm-recursive-force-dynamic",Ti);function Ic(W,G,H){return Lt(ta(Qt(W),{environment:H.environment,cwd:G,budget:H.budget,originalCwd:H.originalCwd,strict:H.strict,paranoid:H.paranoidRm,allowTmpdirVar:H.allowTmpdirVar,tmpdirWordSplittingUnsafe:Ur(H.envAssignments??new Map,H.environment),trustedTmpdirValue:Eo(H.envAssignments??new Map,H.environment),protectedGitMetadata:H.protectedGitMetadata,policy:H.policy}),H.policy)}function eg(W,G,H){let J={};if(W)J.envAssignments=W;if(H)return J.effectiveCwd=null,J.worktreeMode=!1,J;if(G!==void 0)J.effectiveCwd=G;return Object.keys(J).length>0?J:void 0}function tg(W,G){return W.replace(aa,(H)=>rg(H,G))}function sa(W,G,H,J=aa){return H.charge("derivedTokens",W.reduce((oe,ie)=>oe+1+Math.floor(ie.length/64),0)),W.map((oe)=>oe.replace(J,(ie)=>{let fe=rg(ie,G);return H.charge("derivedTokens",Math.max(1,Math.ceil(fe.length/64))),fe}))}function ng(W,G,H){return sa([W],G,H)[0]??""}function Vp(W,G,H){return H.charge("derivedTokens",W.length+G.length),[...W,...G]}function rg(W,G){let H=/^\{(-?\d+)[^{}\s]*\}$/.exec(W)?.[1];if(H===void 0)return G[0]??"";let J=Number(H);return G[J>0?J-1:G.length+J]??""}function Ht(W){return W.search(aa)!==-1}function og(W){if(Oc(W))return!0;for(let G of W.matchAll(aa))if(!/^(?:\{\}|\{\d+\})$/.test(G[0]))return!0;return!1}function Oc(W){let G=W.indexOf("{=");return G!==-1&&W.indexOf("=}",G+2)!==-1}function ig(W){return/^\{[^{}\s]*\}$/.test(W)}function Lw(W,G,H){if(W===void 0)return;if(W==="..."||/^~|[{}$`*?[]/.test(W))return null;if(!G&&!vw(W))return null;try{return Sr(G??W,W,H)}catch{return null}}function sg(W){let G=1,H=[],J=W.length,oe=-1,ie=!1,fe=!1,Re=!1,Te,ke=!1,Le=W.some((et)=>et==="::::"||et==="::::+"||et===":::+");while(G<W.length){let et=W[G];if(et===void 0)break;if(et===":::"){oe=G;break}if(et==="--"){let At=cc(W,G+1);H.push(...At.templateTokens),J=G+1,oe=At.markerIndex;break}if(!et.startsWith("-")){let At=cc(W,G);H.push(...At.templateTokens),J=G,oe=At.markerIndex;break}let tt=W[G+1],gt=et.indexOf("="),_t=gt===-1?et:et.slice(0,gt),yt=gt===-1?void 0:et.slice(gt+1);if(et==="--dry-run"){ke=!0,G++;continue}if(et==="-I"||et.startsWith("-I")&&et.length>2){Le||=(et==="-I"?tt:et.slice(2))!=="{}",G+=et==="-I"?2:1;continue}if(et==="--replace"||et==="-i"){Le=!0,G+=2;continue}if(_t==="--replace"||et.startsWith("-i")&&et.length>2){let At=_t==="--replace"?yt:et.slice(2);Le||=At!==""&&At!=="{}",G++;continue}if(et==="-a"||Aw.has(_t)){Le=!0,G+=yt===void 0?2:1;continue}if(et==="-q"||et==="--quote"){fe=!0,G++;continue}if(et==="--pipe"||et==="--pipepart"){Re=!0,G++;continue}if(_t==="--env"){Le=!0,G+=yt===void 0?2:1;continue}if(Up.has(_t)||et.startsWith("-S")&&et.length>2){ie=!0,G+=Up.has(et)?2:1;continue}if(Pw.has(_t)){Le=!0;let At=yt??tt;if(At===void 0||At===":::"||At==="--"){G++;continue}Te=At,G+=yt===void 0?2:1;continue}if(et.startsWith("-j")&&et.length>2&&/^\d+$/.test(et.slice(2))){G++;continue}if(et.startsWith("--")&&yt!==void 0){G++;continue}if(ww.has(et)){if(tt===void 0||tt===":::"||tt==="--"){Le=!0,G++;continue}G+=2;continue}G+=et==="-j"||et==="--jobs"?2:1}Le||=H.some(ke?Oc:og);let Xe=[];if(oe!==-1){let et=[];for(let tt=oe+1;tt<W.length;tt++){let gt=W[tt];if(gt===":::"){Xe.push(et),et=[];continue}if(gt!==void 0)et.push(gt)}Xe.push(et)}Le||=Xe.length>1;let Ye=Ww(Xe),Ze=H.some(Ht),Qe=H.length===0&&oe===-1;return{template:H,jobs:Ye,childStart:J,templateHasPlaceholder:Ze,runsRemotely:ie,quotesCommand:fe,usesStdin:Re||oe===-1,readsCommandsFromInput:Qe,unsupported:Le,workdir:Te,dryRun:ke}}function Ww(W){if(W.length===0||W.some((H)=>H.length===0))return[];let G=[[]];for(let[H,J]of W.entries()){if(J.length===1){let ie=J[0];if(ie===void 0)return[];for(let fe of G)fe.push(ie);if(G.length*(H+1)>a.derivedTokens.cap)throw new s("derivedTokens");continue}let oe=[];for(let ie of G)for(let fe of J){if((oe.length+1)*(H+1)>a.derivedTokens.cap)throw new s("derivedTokens");oe.push([...ie,fe])}G=oe}return G}function ag(W){return sg(W).childStart}var Gw="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",ca="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function Dc(W){return W?.parts.some((G)=>G.provenance==="command-substitution")??!1}function Mc(W){return W?.parts.some((G)=>G.provenance==="literal"&&G.raw.replace(/^["']/,"").startsWith("-"))??!1}function cg(W,G,H,J,oe=!1,ie){let Re=(ei(W,G)||J&&W!=="powershell"&&G[0]?.provenance==="variable")&&on(ie,"shell.dynamic-executable",oe)?Pt("shell.dynamic-executable",Gw):null;return Lt(Re,ie)??dg(W,G,H,oe,ie)}function dg(W,G,H,J,oe){if(G.length<2)return null;let ie=G.flatMap((Re,Te)=>Dc(Re)?[Te]:[]);if(ie.length===0)return null;let fe=zt(G[0]?.text??"");if(fe==="git"){let Re=re(W,G),Te=zw(Re);if(on(oe,"shell.dynamic-structure",J)&&ie.some((Xe)=>Xe<=Te))return Lt(Pt("shell.dynamic-structure",ca),oe);if(Lt(Qs(Re,{environment:H}),oe))return null;let ke=G[Te]?.text.toLowerCase(),Le=Re.findIndex((Xe,Ye)=>Ye>Te&&t(Xe)==="--");if(on(oe,"shell.dynamic-structure",J)&&ke&&wo.has(ke)&&ie.some((Xe)=>Xe>Te&&(Le===-1||Xe<Le)))return Lt(Pt("shell.dynamic-structure",ca),oe);return null}if(fe==="find")return on(oe,"shell.dynamic-structure",J)&&$w(G)?Lt(Pt("shell.dynamic-structure",ca),oe):null;if(fe==="rm"){let Re=G.findIndex((ke,Le)=>Le>0&&t(ke)==="--"),Te=dr(G.map(t));return on(oe,"shell.dynamic-structure",J)&&ie.some((ke)=>(Re===-1||ke<Re)&&(ke<G.length-1||!Te))?Lt(Pt("shell.dynamic-structure",ca),oe):null}if(fe==="xargs")return lg(W,G.slice(Zr(G.map(t)).childStart),"xargs",H,J,oe);if(fe==="parallel")return lg(W,G.slice(ag(G.map(t))),"parallel",H,J,oe);return null}function lg(W,G,H,J,oe,ie){if(G.length===0)return null;let fe=Fw(G,J);if(ei(W,fe)){let Te=Lt(Pt(`${H}.shell-dynamic`,H==="xargs"?Tc:Ii),ie);if(Te)return Te}let Re=dg(W,fe,J,oe,ie);if(Re)return Re;if(fe[0]?.text==="rm"&&fe.slice(1).some((Te)=>Dc(Te)&&Mc(Te)))return Lt(Pt(`${H}.rm-recursive-force-dynamic`,H==="xargs"?Pc:Ti),ie);return null}function Fw(W,G){let H=zr(W,G),J=H.rewritten?Qt(H.words.map(t)):H.words,oe=J[0];return oe&&t(oe)==="busybox"?J.slice(1):J}function zw(W){let G=1;while(G<W.length){let H=W[G],J=H?t(H):"";if(_n.has(J)){G+=2;continue}if(J.startsWith("-")){G++;continue}return G}return G}function $w(W){let G=!1,H=0,J=!1,oe=!1;for(let ie=1;ie<W.length;ie++){let fe=W[ie];if(!fe)continue;let Re=Dc(fe);if(H>0){H--;continue}if(oe){if(fe.text===";"||fe.text==="+"){oe=!1,G=!0,J=!1;continue}if(Re&&(J||Mc(fe)))return!0;J=!1;continue}if(!G&&!fe.text.startsWith("-")){if(Re&&(ie>1||Mc(fe)))return!0;continue}if(G=!0,Re)return!0;let Te=ur(fe.text);if(Te>0){H=Te;continue}if(tr(fe.text))oe=!0,J=!0}return!1}function Nc(W,G){return W.some((H)=>{if(H.value==="-"&&(H.kind==="main-script"||H.kind==="program-file"))return!0;return!po(G[H.tokenIndex],H.value)})}var ug="cmd rmdir /s or del /s outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Bw="cmd rmdir /s or del /s 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.",Uw="cmd rmdir /s or del /s target contains wildcards or variables that cannot be verified safely. Use literal paths within cwd.",Hw="cmd rmdir /s or del /s targeting root or home directory is extremely dangerous and always blocked.",jw="cmd rmdir /s or del /s with \\\" quoting or a \\\\?\\ path is blocked: cmd does not treat \\\" as an escape, so the target can split down to the root of the drive. Pass each path as its own quoted argument, or use Remove-Item -LiteralPath.",Vw="cmd rmdir /s or del /s in home directory is dangerous. Change to a project directory first.",Kw={root_or_home_target:{id:"cmd.recursive-delete-root-or-home",reason:Hw},git_metadata_target:{id:"cmd.recursive-delete-git-metadata",reason:v},dynamic_target:{id:"cmd.recursive-delete-dynamic-target",reason:Uw},home_cwd_target:{id:"cmd.recursive-delete-home-cwd",reason:Vw},cwd_self_target:{id:"cmd.recursive-delete-cwd-self",reason:ug},within_anchored_cwd:{id:"cmd.recursive-delete-paranoid",reason:Bw},outside_anchored_cwd:{id:"cmd.recursive-delete-outside-cwd",reason:ug}},qw=/^\/\/?[ck]$/i,mg=/[&|]+/,Yw=/(?:"[^"]*"|[^\s"])+/g,Zw=/[\^%!]/,Xw=/\\"./s,Jw=/(^|\/)[*.]*\*[*.]*$/,Qw=/^"?[\\/]+[?.][\\/]/,eA=new Set(["rmdir","rd","del","erase"]),tA=/(?<![\w-])(?:rmdir|rd|del|erase)(?!\w)/i,nA=/\/s(?!\w)/i,rA=/(?<![\w-])(?:cd|chdir|pushd|popd)(?!\w)/i;function fg(W,G){let H=W.map(t),J=H.findIndex((Ye)=>qw.test(Ye));if(J===-1)return null;let oe=H.slice(J+1).join(" "),ie=/^".*"$/s.test(oe)?oe.slice(1,-1):oe,fe=ie.split(mg).map((Ye)=>{let Ze=Ye.match(Yw)??[],Qe=Ze.findIndex((tt)=>eA.has(tt.replace(/^@/,"").toLowerCase())),et=Qe===-1?[]:Ze.slice(Qe);return{piece:Ye,tokens:Ze,deleteTokens:et,recursiveDelete:et.slice(1).some((tt)=>tt.startsWith("/")&&tt.toLowerCase().split("/").includes("s"))}}),Re=fe.filter((Ye)=>Ye.recursiveDelete),Te=Re.length>0||tA.test(ie)&&nA.test(ie);if(Te&&(ie.includes("\\\"")||G.gitBashEscapesBodyQuotes&&ie.includes('"')||G.powerShellRawWords.some((Ye)=>Xw.test(Ye))||Re.some((Ye)=>Ye.tokens.some((Ze)=>Qw.test(Ze)))))return Pt("cmd.recursive-delete-escaped-quote",jw);let ke=er({...G,allowPaths:G.policy?.destructiveCommandAllowPaths}),Le=fe.reduce((Ye,Ze)=>Ye??(Ze.recursiveDelete?oA(Ze.deleteTokens,ke,G.policy):G.analyzeNested(Ze.piece)),null),Xe=Te&&(Re.length===0||Zw.test(ie)||rA.test(ie)||ie.includes('"')&&mg.test(ie));return Le??(Xe?Er():null)}function oA(W,G,H){return W.slice(1).filter((J)=>!J.startsWith("/")).reduce((J,oe)=>J??Lt(jr(An(Ci(oe.replaceAll('"',"")).replace(Jw,"$1*"),G),G,H,Kw),H),null)}var iA="Recursive delete handed to powershell or pwsh in a form CC Safety Net does not read is blocked: pass the script as a single -Command with literal paths, after only -NoProfile, -NonInteractive, -NoLogo, or -ExecutionPolicy.",sA=/^-(?:noprofile|nop|noninteractive|noni|nologo)$/i,aA=/^-(?:executionpolicy|ep)$/i,lA=/^-(?:command|c)$/i,cA=/^(?:--?|[/\u2013\u2014\u2015])(\w+)$/,dA="encodedcommand",uA=/(?<![\w-])(?:remove-item|ri|rm|rmdir|rd|del|erase)(?![\w-])/i,mA=/(?<![\w-])(?:[-\u2013\u2014\u2015]{1,2}r(?:e(?:c(?:u(?:r(?:s(?:e|ive?)?)?)?)?)?)?(?!\w)|-[dfipvwx]*r[dfipvwx]*(?!\w))|\/s(?!\w)/i,fA=/[$`]/,pA="--%";function pg(W,G){let H=W.map(t),J=H.every((ie,fe)=>fe===0||ie!==pA&&gA(W[fe],ie))?Wc(H):void 0;if(J!==void 0)return G(J);if(H.some(hA))return Er();let oe=H.join(" ");return uA.test(oe)&&mA.test(oe)?Pt("powershell.nested-recursive-delete-unread",iA):null}function Wc(W){let G=Lc(W,1),H=G===void 0?[]:W.slice(G+1);return H.length>0?H.join(" "):void 0}function Lc(W,G){let H=W[G]??"";if(lA.test(H))return G;if(sA.test(H))return Lc(W,G+1);return aA.test(H)?Lc(W,G+2):void 0}function gA(W,G){return W?.provenance==="unknown"?!fA.test(G):po(W,G)}function hA(W){let G=cA.exec(W)?.[1]?.toLowerCase();return G!==void 0&&(G==="ec"||dA.startsWith(G))}var hg=[{heads:new Set(["rm","rmdir"]),analyze:(W)=>ta(W.words,Gc(W))},{heads:new Set(["cmd"]),analyze:(W)=>fg(W.words,{...Gc(W),powerShellRawWords:W.options.commandView?.dialect==="powershell"?W.options.commandView.words.map((G)=>G.raw):[],gitBashEscapesBodyQuotes:W.options.commandView?.dialect!=="powershell",analyzeNested:(G)=>Ar(W.options.analyzeNested(G,{effectiveCwd:W.effectiveCwd,envAssignments:W.envAssignments}))})},{heads:new Set(["powershell","pwsh"]),analyze:(W)=>pg(W.parsedWords,(G)=>Ar(W.options.analyzeNested(G,{effectiveCwd:W.effectiveCwd,envAssignments:W.envAssignments,shell:"powershell"})))},{heads:new Set(["git"]),analyze:(W)=>Qs(W.words,Fc(W))},{heads:new Set(["find"]),analyze:(W)=>Yf(W.words,{...Gc(W),envAssignments:W.envAssignments,analyzeTokens:W.analyzeChildTokens})},{heads:new Set(["xargs"]),analyze:(W)=>Dp(W.words,{...gg(W),analyzeChild:W.analyzeChild,analyzeNested:(G,H)=>Ar(W.options.analyzeNested(G,H))})},{heads:new Set(["parallel"]),analyze:(W)=>qp(W.words,{...gg(W),analyzeChild:W.analyzeChild,analyzeNested:(G,H)=>Ar(W.options.analyzeNested(G,H))})}];function gg(W){return{environment:W.options.environment,cwd:W.cwd,originalCwd:W.originalCwd,strict:W.options.strict,paranoidRm:W.options.paranoidRm,paranoidInterpreters:W.options.paranoidInterpreters,allowTmpdirVar:W.allowTmpdirVar,protectedGitMetadata:W.options.protectedGitMetadata,budget:W.options.budget,envAssignments:W.envAssignments,worktreeMode:W.options.worktreeMode,policy:W.options.policy}}function Ar(W){return W?{id:W.ruleId,reason:W.reason,intent:W.intent??"manual_only"}:null}function Gc(W){return{environment:W.options.environment,cwd:W.cwd,originalCwd:W.originalCwd,strict:W.options.strict,paranoid:W.options.paranoidRm,allowTmpdirVar:W.allowTmpdirVar,tmpdirWordSplittingUnsafe:Ur(W.envAssignments,W.options.environment),trustedTmpdirValue:Eo(W.envAssignments,W.options.environment),protectedGitMetadata:W.options.protectedGitMetadata,policy:W.options.policy,budget:W.options.budget}}function Fc(W){return{environment:W.options.environment,cwd:W.cwd,originalCwd:W.originalCwd,dynamicArguments:W.dynamicArguments,envAssignments:W.envAssignments,shellAssignments:W.options.shellAssignments,policy:W.options.policy,worktreeMode:W.options.worktreeMode}}function Cg(W){return hg.find((G)=>G.heads.has(W))?.analyze}function Mo(W,G,H){let J=H.trace;if(W.length===0)return null;let oe=H.commandView?.dialect??"posix",ie=(It)=>It.map((Gt)=>oe==="posix"?t(Gt):Gt.text),fe=H.child,Re=fe!==void 0&&!fe.embedded,Te=fe?.embedded===!0,ke=H.effectiveCwd===null,Le=fe?fe.cwd:ke?void 0:H.effectiveCwd??H.cwd,Xe=fe?fe.originalCwd:ke?void 0:H.cwd,Ye=Ce(W);if(Ye.envAssignments.size>0)J?.recordSegment({type:"env-strip",input:ie(W),envVars:[...Ye.envAssignments.keys()],output:ie(Ye.words)});let Ze=zr(Ye.words,H.environment,Le,new Map([...H.envAssignments??[],...Ye.envAssignments])),Qe=Ze.envSplitValues??[];if(Qe.length>0){let It=[...Qe,...ie(Ze.words)].join(" "),Gt=Nn(It);if(Gt)return J?.recordSegment({type:"dangerous-text",token:It,matched:!0,reason:Gt.reason}),yn(Gt);if(H.strict)return hn(J);let jt=Ps(Qe,ie(Ze.words));if(jt){H.budget.charge("derivedTokens",jt.length);let mn=H.analyzeNested(jt.join(" "),{effectiveCwd:Ze.cwd===void 0?H.effectiveCwd:Ze.cwd,envAssignments:new Map([...H.envAssignments??[],...Ye.envAssignments,...Ze.envAssignments])});if(mn)return mn}}let et=Ze.rewritten?Qt(ie(Ze.words)):re(oe,Ze.words),tt=ie(et),gt={...H,wrapperNormalizationBudget:H.wrapperNormalizationBudget??{iterations:0}};if(J&&Ye.words.length>et.length){let It=ie(Ye.words);J.recordSegment({type:"leading-tokens-stripped",input:It,removed:It.slice(0,It.length-et.length),output:tt})}let _t=new Map([...H.envAssignments??[],...Ye.envAssignments,...Ze.envAssignments]),yt=tt[0];if(!yt)return null;if(Vr(yt))throw new s("wrapperPeelIterations");let At=zt(yt),Ot=Ze.cwd===null?void 0:Ze.cwd??Le,Mt=Ze.cwd===null?void 0:Xe,Nt=Ze.cwd===void 0?H.effectiveCwd:Ze.cwd,ht=Ze.cwd===void 0?H.effectiveCwd:null,Wt=fe?fe.allowTmpdirVar:!Si(_t,H.environment),Dt=cg(oe,Ze.words,H.environment,G===0,H.strict,H.policy);if(Dt)return J?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:Dt.reason}),yn(Dt);let en=js(tt,H.policy);if(en){for(let It of[en.childIndex,...en.alternativeChildIndices]){Sg(gt.wrapperNormalizationBudget);let Gt=et.slice(It);J?.recordSegment({type:"transparent-wrapper",wrapper:en.wrapper,output:ie(Gt)});let jt=Mo(Gt,G,{...gt,effectiveCwd:Nt,envAssignments:_t});if(jt)return jt}return null}let bn=Te?void 0:At==="eval"?na(et):At==="trap"&&!Re?Ap(et):void 0;if(Re&&fe&&At==="eval"){if(bn?.kind==="dynamic")return Oo(fe,H.policy);if(bn?.kind==="literal"){let It=H.analyzeNested(bn.source,{effectiveCwd:Nt,envAssignments:_t});if(It)return It}return Do(fe,H.policy)}if(bn?.kind==="dynamic"&&(H.strict||!H.commandView||!wc(H.commandView)))return hn(J);if(bn?.kind==="literal"){J?.recordSegment({type:"recurse",reason:At==="eval"?"shell-eval":"shell-trap",innerCommand:bn.source,depth:G+1});let It=H.analyzeNested(bn.source,{effectiveCwd:Nt,envAssignments:_t,functionDefinitions:H.functionDefinitions});if(It)return It}if(Re?tn.has(At):Eg(yt,At)){if(Kn(tt))return null;if(qs(tt))return hn(J);if(Re&&fe){let It=Wn(tt);if(It){if(fe.dynamicSourceInput??fe.dynamicInput){let jt=Oo(fe,H.policy);if(jt)return jt}if(Pi(It)){let jt=Oo(fe,H.policy);if(jt)return jt}return H.analyzeNested(It,{effectiveCwd:Nt,envAssignments:_t})}let Gt=mr(et);if(Gt.kind==="dynamic")return Oo(fe,H.policy);if(Gt.kind==="literal")return fe.dynamicSourceInput?Oo(fe,H.policy):null;return fe.dynamicSourceInput??fe.dynamicInput?Oo(fe,H.policy):null}if(Te){let It=Wn(tt),Gt=It?H.analyzeNested(It,{effectiveCwd:Nt,envAssignments:_t}):mr(et).kind==="dynamic"?hn(J):null;if(Gt)return Gt}if(fe===void 0){let It=CA(tt,_t,Nt,H,J,G);if(It)return It;let Gt=Wn(tt);if(Gt){let no=ra(et,Gt);if(no.kind==="dynamic")return hn(J);let ro=no.kind==="literal"?no.source:Pp(et,Gt),dd=RA(ro);J?.recordSegment({type:"shell-wrapper",wrapper:At,innerCommand:dd}),J?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:dd,depth:G+1});let ud=H.analyzeNested(ro,{effectiveCwd:Nt,envAssignments:_t});if(ud)return ud;return Pi(ro)?hn(J):null}let jt=mr(et,H.environment.home,H.strict?void 0:Ao(H.shellAssignments??new Map,{home:H.environment.home,cwd:ht}));if(jt.kind==="dynamic")return hn(J);if(jt.kind==="literal")return ki(jt.source,Nt,_t,H,J,G);let mn=Tp(et,H.commandView?.redirections??[],H.hasPipelineInput??!1,H.literalShellInput);if(mn.kind==="dynamic")return hn(J);if(mn.kind==="literal")return J?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:mn.source,depth:G+1}),H.analyzeNested(mn.source,{effectiveCwd:Nt,envAssignments:_t})}}if(!fe&&(At==="source"||At===".")){let It=tt[1]==="-p"?2:null;if(It!==null){let ro=H.commandView?et[It]:void 0;if(!ro)return null;if(ro.provenance!=="literal")return hn(J)}let Gt=It===null?1:3,jt=tt[Gt]==="--"?Gt+1:Gt,mn=H.commandView?et[jt]:void 0;if(!mn)return null;let no=yg(mn,H,ht);if(no!==null)return ki(no,Nt,_t,H,J,G);if(H.strict||!H.commandView||!wc(H.commandView))return hn(J)}let qt=et[0];if(!fe&&qt&&yt.includes("/")&&H.literalHeredocFiles?.size){let It=yg(qt,H,ht),Gt=It===null?null:ki(It,Nt,_t,H,J,G,!1,!0);if(Gt)return Gt}if(Mn.has(At)&&!Te){if(!fe&&H.strict&&Nc(Ei(tt),et))return hn(J);let It=$f(tt,(jt)=>Ar(H.analyzeNested(jt,{effectiveCwd:Nt,envAssignments:_t}))),Gt=Lt(It,H.policy);if(Gt)return J?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:Gt.reason}),yn(Gt)}if(Bn(At)&&!Te){if(!fe&&H.strict&&Nc(Rs(tt),et))return hn(J);let It=Gm(tt);if(Re&&fe)return SA(At,It,Nt,_t,H,fe);if(It){let Gt=on(H.policy,"interpreter.one-liner-paranoid",!!H.paranoidInterpreters);if(J?.recordSegment({type:"interpreter",interpreter:At,codeArg:It,paranoidBlocked:Gt}),Gt){let mn=Lt(Pt("interpreter.one-liner-paranoid",di),H.policy);if(mn)return yn(mn)}if(zl(At,It))return null;J?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:It,depth:G+1});let jt=H.analyzeNested(It,{effectiveCwd:Nt,envAssignments:_t});if(jt&&!vg(jt,It))return jt;if(ui(It,void 0,!H.strict)){let mn=Lt(Pt("interpreter.dangerous-command",yo),H.policy);if(mn)return J?.recordSegment({type:"dangerous-text",token:It,matched:!0,reason:yo}),yn(mn)}J=void 0}}if(At==="busybox"&&tt.length>1)return Sg(gt.wrapperNormalizationBudget),J?.recordSegment({type:"busybox",subcommand:tt[1]??"unknown"}),J?.recordSegment({type:"recurse",reason:"busybox",innerCommand:tt.slice(1).join(" "),depth:G+1}),Mo(et.slice(1),G,{...gt,effectiveCwd:Nt,envAssignments:_t});let gn=fe?null:Lt(Dm(At,tt),H.policy);if(gn)return J?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:gn.reason}),yn(gn);let Jt=J===gt.trace?gt:{...gt,trace:J},rn={words:et,parsedWords:Ze.words,head:At,cwd:Ot,originalCwd:Mt,envAssignments:_t,allowTmpdirVar:Wt,dynamicArguments:Ze.words.some((It)=>It.provenance==="command-substitution"),depth:G,effectiveCwd:Nt,options:Jt,analyzeChildTokens:(It,Gt)=>Re&&fe?$c(It,G,Jt,{...fe,cwd:Gt??void 0,effectiveCwd:Gt??void 0}):Ar(Mo(Qt(It),G+1,{...Jt,child:void 0,commandView:void 0,effectiveCwd:Gt,envAssignments:_t}))??N(It,Jt.policy.rules),analyzeChild:(It,Gt)=>$c(It,G,Jt,Gt)},Tn=fe&&(At==="xargs"||At==="parallel")?void 0:Cg(At);if(At==="rm"||At==="xargs"||At==="parallel")J?.recordSegment({type:"tmpdir-check",tmpdirValue:_t.has("TMPDIR")||H.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:Wt});let zn=J&&At==="git"?bp(rn.words,Fc(rn)):void 0,pr=bg(zn?zn.match:Tn?.(rn)??null,H.policy);if(J)_A(rn,pr,zn?.relaxation??null);if(pr)return yn(pr);if(Re&&fe&&(At==="rm"||At==="rmdir")){if(!(At==="rm"&&(dr(tt)||fe.dynamicRmInput)))return null;return(fe.dynamicRmInput?Do(fe,H.policy):null)??bA(fe,H.policy)}let Ra=Tn!==void 0&&!wA.has(At),Zn=!fe&&!Ra&&!Ji.has(At),_a=J&&Zn?[]:void 0;if(Zn)for(let It=1;It<tt.length;It++){let Gt=tt[It];if(!Gt)continue;_a?.push(Gt);let jt=bg(yA(tt,It,G,Jt,Ot,Mt,Nt,_t),H.policy);if(jt)return J?.recordSegment({type:"fallback-scan",tokensScanned:_a??[],embeddedCommandFound:zt(Gt)}),yn(jt)}if(J?.recordSegment({type:"fallback-scan",tokensScanned:_a??[]}),Te&&fe&&!fe.wrappedByTransparent)return null;let Gi=N(tt,H.policy.rules);if(J?.recordSegment({type:"custom-rules-check",rulesChecked:H.policy.rules.length>0,matched:!!Gi,reason:Gi?.reason}),Gi)return yn(Gi);return Re&&fe?Do(fe,H.policy):null}function $c(W,G,H,J){return Ar(Mo(Qt(W),G+1,{...H,trace:void 0,commandView:void 0,hasPipelineInput:void 0,literalShellInput:void 0,functionDefinitions:void 0,cwd:J.originalCwd,effectiveCwd:J.effectiveCwd,envAssignments:J.envAssignments,worktreeMode:J.dynamicInput?!1:J.worktreeMode,wrapperNormalizationBudget:{iterations:0},child:J}))}function yA(W,G,H,J,oe,ie,fe,Re){for(let Te of Vn(W.slice(G),{environment:J.environment,cwd:oe,envAssignments:Re,policy:J.policy})){let ke=Te.tokens[0];if(!ke)continue;let Le=zt(ke);if(Eg(ke,Le)||Cg(Le)!==void 0&&Le!=="xargs"&&Le!=="parallel"||Te.wrappedByTransparent&&J.policy.rules.length>0)J.budget.charge("derivedTokens",W.length-G);let Ye=$c(Te.tokens,H,J,{embedded:!0,cwd:Te.cwd,originalCwd:Te.wrapperCwd===null?void 0:ie,effectiveCwd:Te.wrapperCwd===void 0?fe:Te.wrapperCwd,envAssignments:Te.envAssignments,allowTmpdirVar:!Si(Te.envAssignments,J.environment),worktreeMode:!1,wrappedByTransparent:Te.wrappedByTransparent});if(Ye)return Ye}return null}function SA(W,G,H,J,oe,ie){if(!G)return Do(ie,oe.policy);if(on(oe.policy,"interpreter.one-liner-paranoid",!!oe.paranoidInterpreters)){let Re=Lt(Pt("interpreter.one-liner-paranoid",di),oe.policy);if(Re)return yn(Re)}if(zl(W,G))return Do(ie,oe.policy);let fe=oe.analyzeNested(G,{effectiveCwd:H,envAssignments:J});if(fe&&!vg(fe,G))return fe;if(ui(G,void 0,!oe.strict)){let Re=Lt(Pt("interpreter.dangerous-command",yo),oe.policy);if(Re)return yn(Re)}return Do(ie,oe.policy)}function vg(W,G){let H=W.ruleId==="raw-text.dangerous-command",J=(W.reason.startsWith(Ns)||W.reason===Qn)&&!Qi(G);return H||J}function Oo(W,G){let H=W.shellDynamicMatch?Lt(W.shellDynamicMatch,G):null;return H?yn(H):null}function Do(W,G){let H=W.dynamicSourceInput&&W.dynamicSourceMatch?Lt(W.dynamicSourceMatch,G):null;return H?yn(H):null}function bA(W,G){let H=W.dynamicInput&&W.rmDynamicMatch?Lt(W.rmDynamicMatch,G):null;return H?yn(H):null}function CA(W,G,H,J,oe,ie){let fe=qf(W);if(fe.argvSource?.kind==="absent")return hn(oe);if(fe.argvSourceApplies&&fe.argvSource){let Te=ki(fe.argvSource.value,H,G,J,oe,ie,!0);if(Te)return Te}if(!fe.envSourceApplies||!fe.envName)return null;let Re=G.get(fe.envName);if(!Re)return null;return ki(Re,H,G,J,oe,ie,!0)}function yg(W,G,H){let J=G.environment.home,oe=Po(W,J);if(oe!==null)return oe;if(W.provenance==="literal")return W.text;return G.strict?null:qn(W,Ao(G.shellAssignments??new Map,{home:J,cwd:H}))}var vA=/^#!\s*(?:\S*\/)?(?:env\s+(?:-\S+\s+)*)?(?:ba|z|da|k)?sh(?:\s|$)/;function ki(W,G,H,J,oe,ie,fe=!1,Re=!1){if(fe&&/[$`*?[\]]/.test(W))return hn(oe);let Te=ci(W,G,J.environment.paths,J.budget),ke=Te?J.literalHeredocFiles?.get(Te):void 0;if(ke===void 0)return fe?hn(oe):null;if(Re&&ke.startsWith("#!")&&!vA.test(ke))return null;if(J.budget.charge("derivedTokens",1),oe?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:ke,depth:ie+1}),!Re)return J.analyzeNested(ke,{effectiveCwd:G,envAssignments:H});let Le=EA(()=>J.analyzeNested(ke,{effectiveCwd:G,envAssignments:H}));return Le?.intent==="stop_and_explain"?null:Le}function EA(W){try{return W()}catch(G){if(G instanceof s)return null;throw G}}function RA(W){let G=W[0];return W.length>=2&&(G==='"'||G==="'")&&W.at(-1)===G?W.slice(1,-1):W}function _A(W,G,H){let J={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",cmd:"analyzer/cmd.ts:analyzeCmdMatch",powershell:"analyzer/powershell-wrapper.ts:analyzePowerShellWrapperMatch",pwsh:"analyzer/powershell-wrapper.ts:analyzePowerShellWrapperMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[W.head];if(!J)return;if(W.options.trace?.recordSegment({type:"rule-check",rule:J,matched:!!G||!!H,reason:G?.reason??H?.originalReason}),H)W.options.trace?.recordSegment({type:H.kind==="worktree"?"worktree-relaxation":"temp-root-relaxation",originalReason:H.originalReason,gitCwd:H.gitCwd})}function Sg(W){if(W.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");W.iterations++}function yn(W){return{reason:W.reason,ruleId:W.id,intent:W.intent}}function hn(W){return W?.recordSegment({type:"error",message:yi}),yn(Er())}function Eg(W,G){return tn.has(G)||W==="$SHELL"||W==="${SHELL}"||tn.has(Ft(G))}function bg(W,G){return W?.id.startsWith("custom.")||W?.id==="raw-text.dangerous-command"?W:Lt(W,G)}var xA=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,wA=new Set(["powershell","pwsh"]),AA=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function PA(W,G){let H=xg(W,G);if(H.length===0)return!1;let J=H[_g(H)];if(J==="cd"||J==="pushd"||J==="popd")return!0;return xA.test(W.join(" "))}function Rg(W,G,H,J,oe){if(W.dialect==="powershell"){let yt=TA(W.words,oe);if(yt.kind==="none")return;if(!G||yt.kind==="unknown")return null;return zc(MA(yt.target),G,H.paths)}let ie=W.words.map(t),fe=ie.some((yt)=>/^CDPATH\+?=/.test(yt));if(!PA(ie,H))return fe?null:void 0;if(!G)return null;let Re=xg(ie,H,G),Te=_g(Re);if(Te===-1||Re[Te]!=="cd")return null;let ke=Re.slice(Te+1),Le=ke.findIndex((yt)=>yt.length<=1||!yt.startsWith("-")||yt==="--");if((Le===-1?ke:ke.slice(0,Le)).some((yt)=>!/^-[LP]+$/.test(yt)))return null;let Ye=Le===-1?[]:ke.slice(Le),Ze=Ye[0]==="--"?Ye.slice(1):Ye;if(Ze.length>1)return null;let Qe=Ze[0],et=J.get("HOME")||H.home;if(Qe===void 0)return zc(fn(et),G,H.paths);let tt=W.words.find((yt)=>yt.provenance==="variable"&&yt.text===Qe),gt=W.words.find((yt)=>yt.text===Qe&&/^~(?:\/|$)/.test(yt.raw)),_t=tt?qn(tt,new Map([...J,["HOME",et]])):gt?`${et}${Qe.slice(1)}`:Qe;if(_t===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(_t)&&(fe||H.env.has("CDPATH")))return null;return zc(fn(_t),G,H.paths)}function zc(W,G,H){if(!W||W==="-"||W.startsWith("~")||W.includes("$")||W.includes("`"))return null;try{let J=Sr(G,W,H);return H.isDirectory(J)?J:null}catch{return null}}function TA(W,G){let H=IA(W[0])?1:0,J=W[H];if(!kA(J,H===1))return{kind:"none"};let oe=J.text.toLowerCase(),ie=oe.split(/[\\/]/).pop()??oe;if(!AA.has(ie))return{kind:"none"};if(oe!==ie||ie==="pop-location"||ie==="popd")return{kind:"unknown"};return OA(W.slice(H+1),G)}function IA(W){return W?.provenance==="literal"&&!W.quoted&&W.raw===W.text&&(W.text==="&"||W.text===".")}function kA(W,G){return W?.provenance==="literal"&&(G||!W.quoted&&W.raw===W.text)}function OA(W,G){let H;for(let J of W){if(J.provenance!=="literal"||H!==void 0)return{kind:"unknown"};H=J.text}if(H!==void 0)return{kind:"target",target:H};return G===void 0?{kind:"unknown"}:{kind:"target",target:G}}function MA(W){return W.includes("::")?void 0:W.replaceAll("\\","/")}function _g(W){let G=0;if(W[0]==="builtin"&&W.length>1)G=1;if(W[G]!=="time")return G;let H=G+1;while(W[H]?.startsWith("-"))H++;return H}function xg(W,G,H){let J=DA(W);return br([...J],G,H)}function DA(W){let G=0;while(G<W.length){let H=W[G];if(H!=="{"&&H!=="("&&H!=="$(")break;G++}return W.slice(G)}var $A="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Xr="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 Kc(W,G,H,J){if(G>=a.recursionDepth.cap)return H.trace?.recordSegment({type:"error",message:Xn}),{reason:Xn,segment:W,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};let oe=J??H.factStore?.getCommandProgram(W,H.shell??"auto")??y(W,H.shell);if(oe.status==="limited")return H.trace?.recordSegment({type:"error",message:Xn}),{reason:Xn,segment:W,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};if(oe.status==="invalid"){let ke=oe.issues.find((Le)=>Le.code.includes("heredoc"));if(ke){if(!H.strict)return Vc(W,H);let Le=`${Ns}: ${ke.message}`;return H.trace?.recordGlobal({type:"error",message:Le}),{reason:Le,segment:W,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"}}return Og(W,H),{reason:Qn,segment:W,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"}}if(H.strict&&oe.status==="partial")return Og(W,H),{reason:Qn,segment:W,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"};if(oe.issues.some((ke)=>ke.code.includes("quote")))return Vc(W,H);let fe=H.cwd,Re=H.effectiveCwd!==void 0?H.effectiveCwd:H.cwd,Te=ap(H.environment.env,H.envAssignments);return ma(oe,G,{...H,rootProgram:oe},fe,[{effectiveCwd:Re,shellGitContextState:Te,literalHeredocFiles:new Map(H.literalHeredocFiles),functionDefinitions:new Map(H.functionDefinitions),createdDirectories:new Set,compoundBodies:[]}]).result}function ma(W,G,H,J,oe){let ie=[...oe],fe,Re,Te;for(let[ke,Le]of W.nodes.entries()){if(Le.kind==="connector"){Re=Le.operator;continue}let Xe=W.nodes[ke+1],Ye=Xe?.kind==="connector"?Xe.operator:void 0,Ze=BA(W,ke,Le,Re,Ye),et=Re==="&&"||Re==="||"?fe:void 0,tt=Re==="&&"?et?.success??ie:Re==="||"?et?.failure??ie:ie,gt=Re==="||"?et?.success??[]:[],_t=Re==="&&"?et?.failure??[]:[],yt={connector:Re,skippedSuccessStates:gt,skippedFailureStates:_t};if(Pr(Ye)&&!Pr(Re))Te=yt;let At=Pr(Ye)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:Pr(Re)?Te??yt:yt,Ot=Jr(At.connector)||Jr(Ye);if(Le.kind==="function"){let Xt=tt.flatMap((gn)=>{let Jt=Qr(gn);return Jt.functionDefinitions.set(Le.name,Le.body),Bc(gn,[Jt],Ze,Ye==="&",Jr(Ye))}),qt=Uc(Xt,[],At.skippedSuccessStates,At.skippedFailureStates,At.connector,Ye);ie=qt.states,fe=qt.conditionalStates,Re=void 0;continue}if(Le.kind==="group"){let Xt=[],qt=[];for(let Jt of tt){let rn=ma(Le.body,G,H,J,[Qr(Jt)]);if(rn.result)return rn;if(Xt.push(...Bc(Jt,rn.states,Ze,Ye==="&",Jr(Ye))),Ot)qt.push(Jt,...Ze?rn.states.map((Tn)=>da(Jt,Tn)):rn.states)}let gn=Uc(Xt,qt,At.skippedSuccessStates,At.skippedFailureStates,At.connector,Ye);ie=gn.states,fe=gn.conditionalStates,Re=void 0;continue}if(Le.kind!=="command")continue;let Mt=fP(W.nodes[ke-1]),Nt=H.trace?.flattenNested?H.trace.currentSegmentIndex:H.trace?.allocateSegment(),ht=W.nodes[ke-2],Wt=Pr(Re)&&ht?.kind==="command"?wp(ht)??HA(ht):void 0,Dt=[],en=[];for(let Xt of tt){let qt=jA(Le,G,H,J,[Qr(Xt)]);if(qt.result)return{result:qt.result,states:ie};let gn=W.dialect==="powershell"?qt.states:qt.states.map((Jt)=>da(Xt,Jt));for(let Jt of gn){let rn=Qr(Jt),Tn=qA(Le,G,H.trace?{...H,trace:Mg(H.trace,Nt)}:H,J,rn,Pr(Re),Wt);if(Tn)return{result:Tn,states:ie};let zn=CP(Le,rn.functionDefinitions);if(zn)H.budget.charge("derivedTokens",fa(zn));let pr=zn?G+1>=a.recursionDepth.cap?Hc(Le.displayText,H,[rn]):ma(zn,G+1,H,J,[rn]):{result:null,states:SP(Le,rn).flatMap((Zn)=>pP(Le,Jt,Zn,Mt))};if(pr.result)return pr;Dt.push(...Bc(Xt,pr.states,Ze,Ye==="&",Jr(Ye)));let Ra=typeof rn.effectiveCwd==="string"&&rn.effectiveCwd!==Jt.effectiveCwd&&Le.redirections.every((Zn)=>["<",">",">>",">|"].includes(Zn.operator)&&Zn.target?.text==="/dev/null");if(Ot&&(Mt||!Ra))en.push(Xt),en.push(...pr.states.map((Zn)=>Ze?da(Xt,Zn):Zn))}}let bn=Uc(Dt,en,At.skippedSuccessStates,At.skippedFailureStates,At.connector,Ye);ie=bn.states,fe=bn.conditionalStates,Re=void 0}return{result:null,states:ie}}function BA(W,G,H,J,oe){if(H.kind==="group"&&H.style==="subshell")return!0;if(W.dialect==="posix"&&(Pr(J)||Pr(oe)))return!0;if(oe==="&")return!0;return W.dialect==="powershell"&&H.kind==="group"&&H.style==="brace"&&UA(W,G)}function Bc(W,G,H,J,oe){let ie=H?G.map((Re)=>da(W,Re)):[...G],fe=oe?ie.flatMap((Re)=>No(W.literalHeredocFiles,Re.literalHeredocFiles)?[Re]:[{...Re,literalHeredocFiles:new Map(W.literalHeredocFiles)},Re]):ie;return J?[W,...fe]:fe}function da(W,G){return{...W,literalHeredocFiles:new Map(G.literalHeredocFiles),createdDirectories:new Set(G.createdDirectories)}}function UA(W,G){let H=W.nodes.slice(0,G).reverse().find((oe)=>oe.kind==="command"||oe.kind==="connector");if(!H||H.kind!=="command")return!0;let J=H.words[0]?.text.toLowerCase();if(J==="&"||J===".")return!1;if(J==="write-output"||J==="function"||J==="start-job")return!0;if(VA(H))return!0;return H.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function Pr(W){return W==="|"||W==="|&"}function HA(W){if(W?.dialect!=="powershell")return;if(W.words.length===1&&W.words[0]?.quoted&&W.words[0].provenance==="literal")return W.words[0].text;if(W.words[0]?.text.toLowerCase()==="write-output"&&W.words.length===2&&W.words[1]?.provenance==="literal")return W.words[1].text;return}function Jr(W){return W==="&&"||W==="||"}function Uc(W,G,H,J,oe,ie){let fe={success:ua([...H,...W]),failure:ua([...J,...G])},Re=Jr(ie)?fe:void 0;return{states:Jr(oe)||Re?ua([...fe.success,...fe.failure]):fe.success,conditionalStates:Re}}function Mg(W,G,H=W.flattenNested){return{currentSegmentIndex:G,flattenNested:H,allocateSegment:W.allocateSegment,getNextSegmentIndex:W.getNextSegmentIndex,branch:W.branch,recordGlobal:W.recordGlobal,recordSegment:(J,oe=G)=>W.recordSegment(J,oe)}}function jA(W,G,H,J,oe){let ie=W.nested.map((fe)=>({program:fe,depth:G}));if(W.dialect==="powershell"){let fe=KA(W);if(fe){if(G+1>=a.recursionDepth.cap)return Hc(fe,H,oe);let Re=y(fe,"powershell");if(Re.status==="limited")return Hc(fe,H,oe);if(Re.status!=="complete")return wg(ie,H,J,oe);H.budget.charge("derivedTokens",fa(Re)),ie.push({program:Re,depth:G+1})}}return wg(ie,H,J,oe)}function VA(W){let G=W.words[0];return G?.provenance==="variable"&&W.words.at(-1)?.text==="="?G.text.toLowerCase():void 0}function wg(W,G,H,J){let oe=[...J];for(let ie of W){let fe=[];for(let Re of oe){let Te=ma(ie.program,ie.depth,G,H,[Qr(Re)]);if(Te.result)return Te;fe.push(...Te.states)}oe=ua(fe)}return{result:null,states:oe}}function KA(W){let G=W.words[0]?.provenance==="literal"&&!W.words[0].quoted&&W.words[0].raw===W.words[0].text&&(W.words[0].text==="&"||W.words[0].text==="."),H=G?1:0,J=W.words[H];if(J?.provenance!=="literal"||!G&&(J.quoted||J.raw!==J.text)||!["iex","invoke-expression"].includes(J.text.toLowerCase()))return;let oe=W.words.slice(H+1),ie=oe[0]&&!oe[0].quoted&&oe[0].raw===oe[0].text&&["-c","-command"].includes(oe[0].text.toLowerCase())?1:0,fe=oe[ie];return oe.length===ie+1&&fe?.quoted&&fe.provenance==="literal"?fe.text:void 0}function fa(W){return W.nodes.reduce((G,H)=>G+(H.kind==="command"?H.words.length+H.nested.reduce((J,oe)=>J+fa(oe),0):H.kind==="group"||H.kind==="function"?fa(H.body):0),0)}function Hc(W,G,H){return G.trace?.recordSegment({type:"error",message:Xn}),{result:{reason:Xn,segment:W,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"},states:[...H]}}function qA(W,G,H,J,oe,ie,fe){let Re={...H,environment:{...H.environment,env:oe.shellGitContextState.env,paths:tP(H.environment.paths,oe.createdDirectories,H.budget)}},Te=aP(W,!Re.strict);if(Te&&Re.strict)return Re.trace?.recordSegment({type:"error",message:Te}),{reason:Te,segment:W.source,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"};Dg(W,oe,"before-consumer",Re.environment.paths,Re.budget);let ke=re(W.dialect,W.words),Le=ke.map(t),Xe=W.displayText,Ye=ip(ke,oe.shellGitContextState,{home:Re.environment.home,cwd:oe.effectiveCwd,darwinUserTempDir:Re.environment.darwinUserTempDir}),Ze=cp(Ye,oe.shellGitContextState);if(W.dialect==="powershell"){let gt=Lt(Df(W,ie,vP(Re,oe.effectiveCwd)),Re.policy);if(Re.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!gt,reason:gt?.reason}),gt)return kg(Xe,gt)}let Qe=Lt(Nm(W.redirections),Re.policy);if(Qe)return Re.trace?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceRedirectionMatch",matched:!0,reason:Qe.reason}),kg(Xe,Qe);if(Le.length===1&&Le[0]?.includes(" ")&&!ei(W.dialect,W.words)){let gt=Lt(Nn(Le[0]),Re.policy),_t=gt!==null&&!Re.strict&&Im(W,Re.rootProgram);if(gt&&!_t)return Re.trace?.recordSegment({type:"dangerous-text",token:Le[0],matched:!0,reason:gt.reason}),{reason:gt.reason,segment:Xe,ruleId:gt.id,intent:gt.intent};Re.trace?.recordSegment({type:"dangerous-text",token:Le[0],matched:!1});let yt=Ag(W,Te,oe,Ze,fe,Re);if(yt)return yt;return Cc(Ye,oe.shellGitContextState),null}let et=Mo(W.words,G,{...Re,commandView:W,cwd:J,effectiveCwd:oe.effectiveCwd,envAssignments:Ze,shellAssignments:oe.shellGitContextState.shellAssignments,literalHeredocFiles:oe.literalHeredocFiles,functionDefinitions:oe.functionDefinitions,hasPipelineInput:ie,literalShellInput:fe,analyzeNested:(gt,_t)=>{let yt=_t&&Object.hasOwn(_t,"effectiveCwd")?_t.effectiveCwd:oe.effectiveCwd,At=Kc(gt,G+1,{...Re,effectiveCwd:yt,envAssignments:_t?.envAssignments??Ze,literalHeredocFiles:oe.literalHeredocFiles,functionDefinitions:_t?.functionDefinitions,worktreeMode:_t?.worktreeMode??Re.worktreeMode,shell:_t?.shell??Re.shell,trace:Re.trace?Mg(Re.trace,Re.trace.currentSegmentIndex,!0):void 0});return At?{reason:At.reason,ruleId:At.ruleId,intent:At.intent}:null}});if(et)return{...et,segment:Xe};let tt=Ag(W,Te,oe,Ze,fe,Re);if(tt)return tt;return Cc(Ye,oe.shellGitContextState),null}function Ag(W,G,H,J,oe,ie){let fe=lP(W,G,H,J??new Map,ie);if(fe)return fe;if(Dg(W,H,"after-consumer",ie.environment.paths,ie.budget),!XA(W))H.literalHeredocFiles.clear();return QA(W,G,H,ie.environment.paths,ie.budget,ie.environment.home),nP(W,H,ie.environment.paths,ie.budget,ie.environment.home),uP(W,H,oe,ie.environment,ie.trace),null}var YA=new Set([">>","<>"]),ZA=/^[A-Za-z_][A-Za-z0-9_]*\+?=/;function XA(W){return W.nested.length===0&&W.redirections.length===0&&W.words.length>0&&W.words.every((G)=>ZA.test(G.raw))}function Dg(W,G,H,J,oe){for(let fe of W.redirections){if(!(H==="before-consumer"?JA(fe):YA.has(fe.operator)))continue;Pg(fe.target,G,J,oe)}if(H!=="before-consumer"||!un(W.words[0],"tee"))return;let ie=Lg(W.words.slice(1));if(!ie)return;for(let fe of ie.operands)Pg(fe,G,J,oe)}function JA(W){if(W.operator===">"||W.operator===">|")return!0;return W.operator===">&"&&W.fd===void 0&&W.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(W.target.text)}function Pg(W,G,H,J){let oe=W?.provenance==="literal"?ci(W.text,G.effectiveCwd,H,J):void 0;if(!oe)return;G.literalHeredocFiles.delete(oe)}function QA(W,G,H,J,oe,ie){if(G)return;let fe=W.redirections.find((Re)=>Re.operator==="<<"||Re.operator==="<<-")?.heredoc;if(!fe)return;for(let Re of eP(W,Ao(H.shellGitContextState.shellAssignments,{home:ie,cwd:H.effectiveCwd}),ie)){let Te=ci(Re,H.effectiveCwd,J,oe);if(!Te||!Wm(Te))continue;if(!H.literalHeredocFiles.has(Te)&&H.literalHeredocFiles.size>=a.trackedHeredocFiles.cap)throw new s("trackedHeredocFiles");H.literalHeredocFiles.set(Te,fe.body)}}function eP(W,G,H){let J=jc(iP(W.redirections)?.target,G,H),oe=J===void 0?[]:[J];if(un(W.words[0],"cat"))return oP(W.words)?oe:[];if(!un(W.words[0],"tee"))return[];let ie=Lg(W.words.slice(1),G);if(!ie||ie.append||ie.hasUnsupportedOptions)return[];let fe=ie.operands.map((Re)=>jc(Re,G,H));if(!fe.every((Re)=>Re!==void 0))return[];return[...fe,...oe]}function jc(W,G,H){if(sP(W))return W.text;if(!W)return;return Po(W,H)??qn(W,G)??void 0}function tP(W,G,H){if(G.size===0)return W;let J=(oe)=>{let ie=Bt(oe,W,H);return[...G].some((fe)=>fe===ie||fe.startsWith(`${ie}${zA}`))};return{realpath:(oe)=>W.realpath(oe)??(J(oe)?Bt(oe,W,H):null),entryKind:(oe)=>{let ie=W.entryKind(oe);return ie==="missing"&&J(oe)?"present":ie},isDirectory:(oe)=>W.isDirectory(oe)||J(oe)}}function nP(W,G,H,J,oe){if(G.shellGitContextState.bodyDepth>0||!un(W.words[0],"mkdir"))return;let ie=W.words.slice(1).map((Le)=>jc(Le,G.shellGitContextState.shellAssignments,oe));if(!ie.every((Le)=>Le!==void 0))return;let fe=ie.findIndex((Le)=>Le==="--"||Le==="-"||!Le.startsWith("-")),Re=ie.slice(0,fe);if(fe===-1||!Re.every((Le)=>/^(?:-[pv]+|--parents|--verbose)$/.test(Le)))return;let Te=Re.some((Le)=>Le==="--parents"||/^-v*p/.test(Le)),ke=G.effectiveCwd;for(let Le of ie.slice(ie[fe]==="--"?fe+1:fe)){if(Le.split(/[\\/]/).includes("..")||!LA(Le)&&!ke)continue;let Xe=Bt(FA(ke??"",Le),H,J);if(Te?rP(Xe,H):H.isDirectory(NA(Xe))&&Ng(Xe,H))G.createdDirectories.add(Xe)}}function rP(W,G){let H=GA(W).root,J=W.slice(H.length).split(/[\\/]+/).filter(Boolean),oe=(fe)=>WA(H,...J.slice(0,fe+1)),ie=J.findIndex((fe,Re)=>!G.isDirectory(oe(Re)));return ie===-1||Ng(oe(ie),G)}function Ng(W,G){try{return G.entryKind(W)==="missing"}catch{return!1}}function oP(W){let G=!1;for(let H of W.slice(1)){if(G||H.provenance!=="literal")return!1;if(H.text==="--"){G=!0;continue}if(!/^-u+$/.test(H.text))return!1}return!0}function iP(W){let G=W.findLast((H)=>(H.fd??([">",">|",">>",">&"].includes(H.operator)?1:0))===1);return G?.operator===">"||G?.operator===">|"?G:void 0}function Lg(W,G=new Map){let H=[],J=!0,oe=!1,ie=!1;for(let fe of W){if(fe.provenance!=="literal"&&qn(fe,G)===null)return;if(J&&un(fe,"--")){J=!1;continue}if(J&&!fe.quoted&&fe.raw===fe.text&&/^-[^-]/.test(fe.text)){oe||=fe.text.slice(1).includes("a"),ie||=Array.from(fe.text.slice(1)).some((Re)=>Re!=="a"&&Re!=="i");continue}if(J&&!fe.quoted&&fe.raw===fe.text&&fe.text.startsWith("--")){oe||=fe.text==="--append",ie||=fe.text!=="--append"&&fe.text!=="--ignore-interrupts";continue}H.push(fe)}return{operands:H,append:oe,hasUnsupportedOptions:ie}}function sP(W){if(!W||W.provenance!=="literal"||W.text.length===0)return!1;if(W.quoted||W.raw!==W.text)return!0;return!W.raw.startsWith("~")&&!/[{}]/.test(W.raw)}function un(W,G){return W?.text===G&&W.raw===G&&W.provenance==="literal"&&!W.quoted}function qc(W){return W.quotedDelimiter||!/[$`\\]/.test(W.body)}function aP(W,G){let H=W.redirections.filter((Te)=>Te.operator==="<<"||Te.operator==="<<-");if(H.length===0)return;if(H.length!==1)return Xr;let J=H[0];if(!J?.heredoc)return Xr;let oe=/\$\(|`/.test(J.heredoc.body);if(!qc(J.heredoc)&&(!G||oe))return $A;if(J.fd!==void 0&&J.fd!==0)return Xr;if(W.redirections.some((Te)=>Te!==J&&["<","<<","<<-","<<<","<&","<>"].includes(Te.operator)))return Xr;let ie=W.redirections.some((Te)=>Te!==J&&Tg(Te.target));if(un(W.words[0],"cat"))return ie?Xr:void 0;if(un(W.words[0],"tee"))return ie||W.words.slice(1).some(Tg)?Xr:void 0;let fe=W.words[0],Re=W.words[1];if(un(fe,"git")&&(un(Re,"apply")||un(Re,"commit")))return;if(un(fe,"gh")&&(un(Re,"pr")||un(Re,"issue"))&&un(W.words[2],"create"))return;return Xr}function Tg(W){return W?.parts.some((G)=>G.provenance==="command-substitution"&&G.raw.startsWith(">("))??!1}function lP(W,G,H,J,oe){if(!G)return null;let ie=W.redirections.filter((ke)=>ke.operator==="<<"||ke.operator==="<<-"),fe=ie.flatMap((ke)=>ke.heredoc?[ke.heredoc.body]:[]);if(dP(W,ie,H,J,oe))return null;let Re=cP(W,ie,oe);if(Re!==void 0)return Re?{reason:Re.reason,segment:W.displayText,ruleId:Re.id,intent:Re.intent}:null;let Te=Vc(fe.length===ie.length?fe.join(`
42
+ `):W.source,oe);return Te?{...Te,segment:W.displayText}:null}function cP(W,G,H){let J=G.length===1?G[0]:void 0;if(!J?.heredoc||!qc(J.heredoc)||J.fd!==void 0&&J.fd!==0)return;let oe=un(W.words[0],"uv")&&un(W.words[1],"run")?W.words.slice(2):W.words,ie=oe[0];if(ie?.provenance!=="literal"||!Bn(ie.text))return;let fe=oe.findIndex((Xe)=>un(Xe,"-"));if(!oe.slice(1,fe===-1?void 0:fe).every((Xe)=>Xe.provenance==="literal"&&Xe.text.startsWith("-")))return;let Te=J.heredoc.body,ke=on(H.policy,"interpreter.one-liner-paranoid",!!H.paranoidInterpreters);if(H.trace?.recordSegment({type:"interpreter",interpreter:ie.text,codeArg:Te,paranoidBlocked:ke}),ke){let Xe=Lt(Pt("interpreter.one-liner-paranoid",di),H.policy);if(Xe)return Xe}if(!ui(Te,void 0,!H.strict))return null;let Le=Lt(Pt("interpreter.dangerous-command",yo),H.policy);if(!Le)return null;return H.trace?.recordSegment({type:"dangerous-text",token:Te,matched:!0,reason:Le.reason}),Le}function dP(W,G,H,J,oe){let ie=G.length===1?G[0]:void 0;if(!ie?.heredoc||!qc(ie.heredoc)||ie.fd!==void 0&&ie.fd!==0)return!1;let fe=zr(W.words,oe.environment,H.effectiveCwd,J),Re=fe.words.map(t),Te=zt(Re[0]??"");if((fe.envSplitValues?.length??0)>0||!tn.has(Te)&&!tn.has(Ft(Te)))return!1;return Kn(Re)}function uP(W,G,H,J,oe){let ie=Rg(W,G.effectiveCwd,J,G.shellGitContextState.shellAssignments,H);if(ie===null)oe?.recordSegment({type:"cwd-change",segment:W.words.map(t).join(" "),effectiveCwdNowUnknown:!0});if(ie!==void 0)G.effectiveCwd=ie}var mP=new Set(["fi","done","esac"]);function fP(W){return W?.kind==="command"&&W.words.length===1&&W.words[0]?.raw==="!"}function pP(W,G,H,J){let oe=W.words[0]?.text??"",ie=G.shellGitContextState.bodyDepth,fe=H.shellGitContextState.bodyDepth,Re=H.compoundBodies;if(fe>ie)return H.compoundBodies=[...Re.slice(0,ie),{entryCwd:G.effectiveCwd,branchCwds:Re[ie]?.branchCwds??[],hasElse:!1}],[H];let Te=ie>0?Re[ie-1]:void 0;if(Te&&(oe==="else"||oe==="elif"))return H.compoundBodies=[...Re.slice(0,ie-1),{entryCwd:Te.entryCwd,branchCwds:[...Te.branchCwds,H.effectiveCwd],hasElse:oe==="else"}],H.effectiveCwd=Te.entryCwd,[H];let ke=Te!==void 0&&mP.has(oe);if(ke)H.compoundBodies=Re.slice(0,fe);return[...new Set([H.effectiveCwd,...ke?Te.branchCwds:[],...ke&&!Te.hasElse?[Te.entryCwd]:[],...J?[G.effectiveCwd]:[]])].map((Xe)=>{if(Xe===H.effectiveCwd)return H;let Ye=Qr(H);return Ye.effectiveCwd=Xe,Ye})}function gP(W,G){return W.length===G.length&&W.every((H,J)=>{let oe=G[J];return oe!==void 0&&H.entryCwd===oe.entryCwd&&H.hasElse===oe.hasElse&&H.branchCwds.length===oe.branchCwds.length&&H.branchCwds.every((ie,fe)=>ie===oe.branchCwds[fe])})}var hP=/^[A-Za-z_][A-Za-z0-9_]*$/,yP=8;function SP(W,G){let H=W.words[1]?.text;if(W.dialect!=="posix"||W.words[0]?.text!=="for"||H===void 0||!hP.test(H))return[G];let J=W.words.slice(3);if(!(W.words[2]?.text==="in"&&J.length>=1&&J.length<=yP&&J.every((ie)=>ie.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(ie.text))))return G.shellGitContextState.shellAssignments.delete(H),[G];return J.map((ie)=>{let fe=Qr(G);return fe.shellGitContextState.shellAssignments.set(H,ie.text),fe})}function Qr(W){return{effectiveCwd:W.effectiveCwd,shellGitContextState:lp(W.shellGitContextState),literalHeredocFiles:new Map(W.literalHeredocFiles),functionDefinitions:new Map(W.functionDefinitions),createdDirectories:new Set(W.createdDirectories),compoundBodies:W.compoundBodies}}function ua(W){let G=[];for(let H of W){if(!G.some((J)=>bP(J,H)))G.push(H);if(G.length>a.controlFlowStates.cap)throw new s("controlFlowStates")}return G}function bP(W,G){return W.effectiveCwd===G.effectiveCwd&&gP(W.compoundBodies,G.compoundBodies)&&No(W.shellGitContextState.env,G.shellGitContextState.env)&&No(W.literalHeredocFiles,G.literalHeredocFiles)&&No(W.functionDefinitions,G.functionDefinitions)&&No(W.shellGitContextState.effectiveEnvAssignments,G.shellGitContextState.effectiveEnvAssignments)&&No(W.shellGitContextState.shellAssignments,G.shellGitContextState.shellAssignments)&&W.shellGitContextState.bodyDepth===G.shellGitContextState.bodyDepth&&Ig(W.shellGitContextState.bodyAssignments,G.shellGitContextState.bodyAssignments)&&Ig(W.createdDirectories,G.createdDirectories)}function Ig(W,G){return W.size===G.size&&[...W].every((H)=>G.has(H))}function No(W,G){if(W===G)return!0;if(!W||!G||W.size!==G.size)return!1;return[...W].every(([H,J])=>G.get(H)===J&&G.has(H))}function CP(W,G){let H=ti(W);return H===void 0?void 0:G.get(H)}function kg(W,G){if(!G)return null;return{reason:G.reason,segment:W,ruleId:G.id,intent:G.intent}}function vP(W,G=W.effectiveCwd){let H=G===null;return{environment:W.environment,cwd:H?void 0:G??W.cwd,originalCwd:H?void 0:W.cwd,strict:W.strict,paranoid:W.paranoidRm,allowTmpdirVar:W.allowTmpdirVar,protectedGitMetadata:W.protectedGitMetadata,policy:W.policy,budget:W.budget}}function Vc(W,G){let H=Lt(Nn(W),G.policy),J=G.trace?.currentSegmentIndex??G.trace?.allocateSegment(),oe={type:"dangerous-text",token:W,matched:!!H,reason:H?.reason};if(G.trace?.recordSegment(oe,J),!H&&/^(?:cd|pushd)\s/.test(W))G.trace?.recordSegment({type:"cwd-change",segment:W,effectiveCwdNowUnknown:!0},J);return H?{reason:H.reason,segment:W,ruleId:H.id,intent:H.intent}:null}function Og(W,G){let H={type:"strict-unparseable",rawCommand:W,reason:Qn},J=G.trace?.currentSegmentIndex;if(J===void 0)G.trace?.recordGlobal(H);if(J!==void 0)G.trace?.recordSegment(H)}var EP=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function Wg(W,G,H,J){let oe=Kc(W,0,{...G,...qe(G),budget:G.budget??In(),factStore:J},H);if(!oe)return null;return{kind:"deny",reason:oe.reason,intent:oe.intent??"manual_only",ruleId:oe.ruleId,evidence:{command:W,segment:oe.segment}}}function Gg(W,G,H){try{return{decision:W()}}catch(J){let oe=RP(J,G,H);if(!oe)throw J;return oe}}function RP(W,G,H){if(!(W instanceof s)||!EP.has(W.kind))return null;let J=a[W.kind];if(H?.currentSegmentIndex!==void 0)H.recordSegment({type:"error",message:J.reason});if(H?.currentSegmentIndex===void 0)H?.recordGlobal({type:"error",message:J.reason});return{decision:{kind:"deny",reason:J.reason,ruleId:"analysis.derived-command-limit",intent:"stop_and_explain",evidence:{command:G,segment:G}},errorCode:J.errorCode}}var _P=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),Zc=new Set(["cc-safety-net","ccsn"]),xP=new Set(["bunx","npx","pnpx"]),wP=new Set(["pnpm","yarn"]),AP=new Set(["npm","pnpm","yarn"]),PP=new Set(["bun","node"]);function ga(W,G,H={}){if(Zc.has(W))return 0;if(xP.has(W)){if(H.broad)return Yc(G);let oe=G[0]==="-y"||G[0]==="--yes"?1:0;return pa(G[oe])?oe+1:null}let J=H.broad?G.findIndex((oe)=>!oe.startsWith("-")):0;if(J!==-1&&AP.has(W)&&H.broad&&G[J]==="exec"){let oe=Yc(G.slice(J+1));return oe===null?null:J+1+oe}if(wP.has(W)){if(W==="yarn"&&!H.broad)return null;if(!H.broad)return G[0]==="dlx"&&pa(G[1])?2:null;if(J===-1||G[J]!=="dlx")return null;let oe=Yc(G.slice(J+1));return oe===null?null:J+1+oe}if(PP.has(W)){let oe=H.broad&&J!==-1?J:0;if(Fg(G[oe]))return oe+1;if(W==="bun"&&G[oe]==="run"&&Fg(G[oe+1]))return oe+2}return null}function Yc(W){let G=W.findIndex((J)=>pa(J));if(G===-1)return null;let H=G;while(H<W.length){let J=W[H]??"";if(!J.startsWith("-")&&!pa(J))break;H++}return H}function pa(W){if(!W)return!1;let G=W.indexOf("@");if(G===-1)return Zc.has(W);if(G===0)return!1;let H=W.slice(G+1);if(H===""||H.includes("/")||H.includes(":"))return!1;return Zc.has(W.slice(0,G))}function Fg(W){let G=W?.replaceAll("\\","/");return[..._P].some((H)=>G===H||G?.endsWith(`/${H}`))}var Ke="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 zg(W,G,H){let J=lr(W);if(!J)return null;let oe=vo(J.shell,W.invocation.context.executionCwd,G,H,{findSegmentTarget:(ie)=>TP(ie,G),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return oe?{target:oe}:null}function TP(W,G){let H=br([...W],G),J=H.slice(1),oe=ga(Ft(H[0]??"").toLowerCase(),J,{broad:!0});if(oe===null)return null;let ie=J.slice(oe).filter((fe)=>fe!=="-g"&&fe!=="--global");return ie[0]==="policy"&&ie[1]==="apply"?H.join(" "):null}import{dirname as ha}from"node:path";var Je="This path contains the protected policy config and you must not modify or delete it.",IP=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Hg(W,G,H){let J=LP(W.invocation.context,G,H);if(W.invocation.route.kind==="patch")return $g(W.paths,!1,W.invocation.context.executionCwd,J,G,H);let oe=lr(W);if(W.invocation.route.kind==="command")return oe?Bg(oe.shell,W.invocation.context.executionCwd,J,G,H):null;if(W.invocation.route.kind==="unknown"&&oe){let ie=Bg(oe.shell,W.invocation.context.executionCwd,J,G,H);if(ie)return ie}return $g(W.paths,W.invocation.route.kind==="grep"||W.invocation.route.kind==="glob"||Ui(W.invocation.toolName),W.invocation.context.executionCwd,J,G,H)}function $g(W,G,H,J,oe,ie){if(G)return null;let fe=W.find((Re)=>Oi(Re,H,J,oe,ie));return fe?{target:fe}:null}function Bg(W,G,H,J,oe){let ie=vo(W,G,J,oe,{findSegmentTarget:(fe,Re)=>kP(fe,Re,H,J,oe)?.target??null,isRedirectionTarget:(fe,Re)=>Oi(fe,Re.cwd,H,J,oe),findMalformedTarget:(fe)=>NP(fe,G,H,J,oe)?.target??null});return ie?{target:ie}:null}function kP(W,G,H,J,oe){if(hi(W))return null;let ie=Cr([...W],J),fe=Ft(ie[0]??"").toLowerCase(),Re=ie.slice(1);if(fe==="rm"&&OP(Re)){let Te=MP(Re).find((ke)=>Ug(vn(ke,G.variables),G.cwd,H,J,oe));if(Te)return{target:Te}}if(fe==="find"){if(Ys(ie,1)||uc(ie,J)){let ke=(Ri(Qt(ie))??Qt(["."])).find((Le)=>{let Xe=vn(Le.text,G.variables);return Oi(Xe,G.cwd,H,J,oe)||Ug(Xe,G.cwd,H,J,oe)})?.text;if(ke)return{target:ke}}}if(fe==="mv"){let Te=Ls(Re).sources.find((ke)=>WP(vn(ke,G.variables),G.cwd,H,J,oe));if(Te)return{target:Te}}if(DP(ie,fe))return null;for(let Te of[...W,...ie])for(let ke of jg(Te))if(Oi(vn(ke,G.variables),G.cwd,H,J,oe))return{target:ke};return null}function OP(W){return W.some((G)=>G==="--recursive"||G.startsWith("-")&&!G.startsWith("--")&&/[rR]/.test(G.slice(1)))}function MP(W){let G=W.indexOf("--");if(G!==-1)return[...W.slice(0,G).filter((H)=>!H.startsWith("-")),...W.slice(G+1)];return W.filter((H)=>!H.startsWith("-"))}function DP(W,G){if(!IP.has(G))return!1;if(G!=="sed")return!0;return!W.slice(1).some((H)=>H.startsWith("-i")||H==="--in-place"||H.startsWith("--in-place="))}function NP(W,G,H,J,oe){for(let ie of W.split(/\s+/))for(let fe of jg(ie))if(Oi(fe,G,H,J,oe))return{target:fe};return null}function jg(W){let G=W.trim().replace(/^['"]|['"]$/g,""),H=G.indexOf("=");return H===-1||H===G.length-1?[G]:[G,G.slice(H+1)]}function LP(W,G,H){let J=(Re)=>Mi(pn(Re,W.executionCwd,G,H)),oe=J(u(G)),ie=[J(h(W.executionCwd)),J(h(W.configCwd))],fe=new Set(ie.map((Re)=>ha(Re)));for(let Re=ha(oe);;Re=ha(Re))if(fe.add(Re),ha(Re)===Re)break;return{files:new Set([oe,...ie]),directoriesAndAncestors:fe}}function Oi(W,G,H,J,oe){let ie=yd(W,G,J,oe,(fe)=>Mi(fe)===Zi);return ie!==null&&H.files.has(Mi(ie))}function Ug(W,G,H,J,oe){return H.directoriesAndAncestors.has(Mi(pn(W,G,J,oe)))}function WP(W,G,H,J,oe){let ie=Mi(pn(W,G,J,oe));return H.files.has(ie)||H.directoriesAndAncestors.has(ie)}function Mi(W){return process.platform==="win32"?W.toLowerCase():W}import{isAbsolute as ya,posix as oh,resolve as va,win32 as GP}from"node:path";import{fileURLToPath as FP}from"node:url";var ih="Access to a sensitive path is not allowed.",sh=new Set(["echo","printf"]),zP=new Set(["find"]),$P=new Set(["!","do","elif","else","if","then","until","while"]),BP=new Set(["-exec","-execdir"]),UP=new Set([";","+"]),HP=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),jP=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),ah=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),VP=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),KP=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"]),td=new Set(["-c","-e","-r","-E","--eval","--exec"]),qP=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"])]]),nd=new Set(["grep","rg"]),lh=new Set(["files-with-matches","files-without-match","count","quiet"]),YP=new Set([...lh,"ignore-case","fixed-strings","hidden"]),ZP=new Set(["wc",...nd]),XP=new Set(["cd","grep","head","openssl","tail","tailscale"]),JP=/^(?:-[lwcm]+|--(?:lines|words|bytes|chars))$/,QP=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),eT=new Set(["commit","merge","notes","stash","tag"]),tT=new Set(["-m","--message"]),nT=new Set(["--grep"]),rT=new Set(["powershell","pwsh"]),Vg=new Set(["jq","gojq","jaq"]),Kg="f",qg="file",oT="files",iT=new Set(["e","f"]),sT=new Set(["regexp","file"]),aT=new Set(["e","f","A","B","C","m"]),lT=new Set(["regexp","file","after-context","before-context","context","max-count"]),Xc="__CC_SAFETY_NET_PIPE_INPUT__",Qc=/[\w./~@+-]*[./~][\w./~@+-]*/g,cT=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,dT=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,uT=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,Yg=/\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,Zg=/\b(?:system|exec|spawn|popen)\s*$/,mT=/\b(?:eval|exec)\s*\(/g,fT=/\b(?:eval|exec)\s*$/,pT=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 Xg(W,G,H,J,oe,ie){for(let fe of W){let Re=fe.target;if(DI(Re,fe.cwd,G?.denyPaths??[],H,J,oe))return{target:Re,ruleId:"secret.deny-path"};if(ie&&!ie.has(Re))continue;let Te=OI(Re,fe.cwd,G,J,oe);if(Te){let ke=ie!==void 0&&!Te.startsWith("secret.home.")&&!Te.startsWith("secret.cli.");if(ke&&J.paths.isDirectory(Eh(Re,fe.cwd,J,oe)))continue;if(ke&&ie?.get(Re)==="data")continue;if(ke&&(fe.isRedirectionWriteTarget===!0||ie?.get(Re)==="write")&&!Re.includes("$")&&!Ca(Re,fe.cwd,J,oe))continue;if(ke&&(fe.isCreatedPath===!0||fe.isCertificateInput===!0))continue;if(ke&&/\s/.test(Re)&&!Re.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(Re)&&!Ca(Re,fe.cwd,J,oe))continue;if(!Te.startsWith("secret.cli.")&&NI(Re,fe.cwd,G?.allowPaths??[],H,J,oe))continue;return{target:Re,ruleId:Te}}}return null}function ch(W,G,H,J,oe={}){let ie=Jg(W,H,J),fe=Xg(ie,G,W.invocation.context.configCwd,H,J);if(fe===null||fe.ruleId==="secret.deny-path"||oe.strict!==!1)return fe;let Re=Jg(W,H,J,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}),Te=new Map;Re.forEach((Qe)=>dh(Qe.target).forEach((et)=>Te.set(et,(Te.get(et)??new Set).add(Qe.loopVariable))));let ke=(Qe,et)=>(Te.get(Qe)?.size??0)>(Te.get(Qe)?.has(et)?1:0),Le=Re.filter(({loopVariable:Qe})=>Qe===void 0||ke(Qe,Qe)||ke("!",Qe)),Xe=new Set(Le.filter((Qe)=>Qe.literalRole===void 0).map((Qe)=>Qe.target)),Ye=new Set(Le.filter((Qe)=>Qe.literalRole==="write").map((Qe)=>Qe.target)),Ze=Xg(ie,G,W.invocation.context.configCwd,H,J,new Map(Le.map((Qe)=>[Qe.target,Xe.has(Qe.target)?"path":Ye.has(Qe.target)?"write":"data"])));return Ze?.ruleId!=="secret.deny-path"&&gT(W,H)?null:Ze}function gT(W,G){let H=lr(W);if(!H)return!1;if(H.program.nodes.some((fe)=>fe.kind==="command"&&fe.nested.length>0))return!1;let J=[];for(let fe of Ds(H.shell)){if(fe.kind==="operator"&&fe.boundary)return!1;if(fe.kind==="redirection")return!1;if(fe.kind==="operator")continue;J.push(cr(fe.text,G))}let oe=nr(J);if(oe.length===0)return!1;let ie=Sn(oe[0]??"").toLowerCase();if(W.invocation.route.kind==="unknown")return H.program.dialect==="powershell"&&(ie==="ls"||ie==="stat");return rd(ie,oe.slice(1))}function rd(W,G){if(W==="ls"||W==="stat")return!0;if(W==="test")return G.length===2&&(G[0]==="-e"||G[0]==="-f");if(W==="[")return G.length===3&&(G[0]==="-e"||G[0]==="-f")&&G[2]==="]";if(W==="git")return G[0]==="check-ignore";if(W==="wc")return G.every((H)=>!H.startsWith("-")||JP.test(H));if(nd.has(W))return hT(W,G);if(W!=="find")return!1;return!G.some((H)=>HP.has(H))}function hT(W,G){let H=G.includes("--")?G.slice(0,G.indexOf("--")):G;if(H.some((ke)=>/^--(?:(?:file|pre)(?:=|$)|json|format)/.test(ke)||/^-[^-]*f/.test(ke)))return!1;let J=W==="rg"?/[ABCEMTdegjmrt]/:/[ABCDdefm]/,oe=W==="rg"?/[clq]/:/[Lclq]/,ie=(ke)=>/^-[^-]/.test(ke),fe=(ke)=>{let Le=H[ke-1]??"";return/^--[^=]+$/.test(Le)&&!YP.has(Le.slice(2))||ie(Le)&&Le.slice(1).search(J)===Le.length-2},Re=H.findIndex((ke,Le)=>!ke.startsWith("-")&&!fe(Le));return(W==="grep"&&Re>=0?H.slice(0,Re):H).some((ke,Le)=>{if(fe(Le))return!1;if(ke.startsWith("--"))return lh.has(ke.slice(2));return ie(ke)&&oe.test(ke.slice(1).split(J)[0]??"")})}function Jg(W,G,H,J={}){let oe=W.invocation.context.executionCwd,ie=W.invocation.route.kind;if(ie!=="command"&&ie!=="unknown")return W.paths.map((Re)=>({target:Re,cwd:oe}));let fe=lr(W);return[...fe?Go(fe.shell,W.store,J,G,oe,H,yT(fe)):[],...ie==="unknown"?W.paths.map((Re)=>({target:Re,cwd:oe})):[]]}function yT(W){return W.program.dialect==="powershell"}function Go(W,G,H,J,oe,ie,fe=!1){if(W.status==="structural-limit")throw new b;if(W.status==="unclosed-quote")return[];if(W.status==="invalid")throw new U;let Re=[...W.assignmentFallbacks.map((tt)=>({target:tt,cwd:oe})),...pI(cr(W.source,J),G,H,J,oe,ie)],Te=(tt)=>cr(TT(tt,fe),J),ke=/[<>=]\(/.test(W.source),Le=/\bcoproc\b|\|&/.test(W.source),Xe=[],Ye=[],Ze=(tt)=>({...H,commandHoldsPipe:H.commandHoldsPipe===!0||tt||Le});Ms(W,oe,J,ie,{word:Te,segment:(tt,gt,_t,yt,At,Ot)=>{if(tt.length===0)return null;let Mt=Ze(Ot);if(Mt.commandHoldsPipe)Xe.push(...tt);if(Ye.push(Sn(uh(nr(tt))[0]??"").toLowerCase()),Re.push(...Ni(tt,G,ke||yt==="|"||yt==="|&"?{...Mt,segmentMayFeedReader:!0}:Mt,J,gt.cwd,ie,At)),_t!==null)Re.push(...CT(_t,tt,G,Mt,J,gt.cwd,ie));return null},redirection:(tt,gt,_t)=>{if(tt.body!==void 0&&tt.consumer!==void 0){let yt=Ze(_t);Re.push(...mh(tt.consumer,[tt.body],G,yt,J,gt.cwd,ie,(At)=>vT(tt.consumer??[],At,G,yt,J,gt.cwd,ie)))}if(tt.targetOrder==="legacy-segment")return Kl;return Re.push({target:Te(tt.target),cwd:gt.cwd,...tt.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}});let Qe=new Set(Xe.flatMap(dh)),et=ke||/\$\(|`/.test(W.source)||!Ye.every((tt)=>XP.has(tt));return Re.map(({loopVariable:tt,...gt})=>{if(gt.certificateOutputMayFeedReader===!0&&et)return{target:gt.target,cwd:gt.cwd};return tt===void 0||ke||Qe.has(tt)||Qe.has("!")?gt:{...gt,loopVariable:tt}})}function dh(W){return[.../^[A-Za-z_][A-Za-z0-9_]*$/.test(W)?[W]:[],...Array.from(W.matchAll(/\$(?:\{(!)|\{?([A-Za-z_][A-Za-z0-9_]*))/g),(G)=>G[1]??G[2]??"")]}function Sa(W,G,H,J,oe,ie,fe=!1){let Re=G.getShellSyntax(W,fe?G.getCommandProgram(W,"powershell"):void 0);if(Re.status==="structural-limit")throw new b;return Re.status==="complete"?Go(Re,G,H,J,oe,ie,fe):null}function Ni(W,G,H,J,oe,ie,fe){let Re=(ht)=>({target:ht,cwd:oe}),Te=W.findIndex((ht)=>!$P.has(ht));if(H.skipMetadataOnlySegments===!0&&Te>0)return Ni(W.slice(Te),G,H,J,oe,ie,new Set([...fe??[]].map((ht)=>ht-Te)));let ke=W[1]??"";if(H.skipMetadataOnlySegments===!0&&W[0]==="for"&&W[2]==="in"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(ke))return W.slice(3).flatMap((ht)=>Fn("for",ht)).map((ht)=>({...Re(ht),loopVariable:ke}));if(fe?.size){let ht=W.filter((Wt,Dt)=>!fe.has(Dt));if(Vg.has(Sn(nr(ht)[0]??"").toLowerCase()))return[...W.filter((Wt,Dt)=>fe.has(Dt)).map(Re),...Ni(ht,G,H,J,oe,ie)]}let Le=PT(W).map(Re),Xe=nr(W);if(Xe.length===0)return Le;let Ye=Xe[0]??"",Ze=Sn(Ye).toLowerCase(),Qe=Xe.slice(1),et=H.segmentMayFeedReader===!0||H.commandHoldsPipe===!0||H.displayOperandsAreCapturedOutput===!0,tt=et&&ZP.has(Ze);if(H.skipMetadataOnlySegments===!0&&!tt&&rd(Ze,Qe))return Le;let gt=bT(Ye,Ze,Qe);if(gt)return[...Le,...gt.map(Re)];if(sh.has(Ze))return H.displayOperandsAreCapturedOutput===!0?[...Le,...fh(W).map(Re)]:Le;if(Ze==="eval")return[...Le,...Sa(Qe.join(" "),G,H,J,oe,ie)??Qe.map(Re)];let _t=rT.has(zt(Ye))?Wc(Xe):void 0;if(_t!==void 0)ie.charge("derivedTokens",Xe.length);let yt=_t===void 0?null:Sa(_t,G,H,J,oe,ie,!0);if(yt?.length)return[...Le,...yt];if(Ze==="export")return[...Le,...Qe.flatMap((ht)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(ht)?[ht.slice(ht.indexOf("=")+1)]:Fn(Ze,ht)).map(Re)];if(Ze==="git")return[...Le,...kT(Qe).map(Re)];if(Ze==="gh")return[...Le,...ed(Ze,Qe,QP).map(Re)];if(Vg.has(Ze))return[...Le,...IT(Qe).map(Re)];if(nd.has(Ze))return[...Le,...EI(Qe).map(Re)];if(zP.has(Ze))return[...Le,...MT(Qe,G,H,J,oe,ie).map(Re)];if(Ze==="mkdir"||Ze==="touch"){let ht=new Set(W.filter((Dt,en)=>fe?.has(en))),Wt=H.segmentMayFeedReader!==!0&&!(Ze==="touch"&&Qe.some((Dt)=>/^(?:--r|-[^-]*r)/.test(Dt)));return[...Le,...Qe.flatMap((Dt)=>Fn(Ze,Dt).map((en)=>Wt&&!Dt.startsWith("-")&&!ht.has(Dt)?{...Re(en),isCreatedPath:!0}:Re(en)))]}if(Mn.has(Ze))return[...Le,...Qe.flatMap((ht)=>Fn("awk",ht)).map(Re),...Qe.flatMap((ht)=>NT(ht,G,H,J,oe,ie)),...Qe.flatMap(LT).map(Re)];if(Ze==="curl")return[...Le,...Qe.filter((ht,Wt)=>gh(ht)===null&&ph(Qe[Wt-1])===null).flatMap((ht)=>Fn(Ze,ht)).map(Re),...OT(Qe).map(Re)];if(bo(Ze)){let ht=gi.has(Ze)?Dn([Ze,...Qe]):null;if(ht!==null&&ht.command!==null&&ht.commandIndex!==null){let Wt=G.getShellSyntax(ht.command);if(Wt.status==="structural-limit")throw new b;if(Wt.status==="complete")return[...Le,...Go(Wt,G,H,J,oe,ie),...Qe.slice(ht.commandIndex).filter((Dt)=>!Dt.startsWith("-")).map(Re)]}return[...Le,...DT(Ze,Qe,G,H,J,oe,ie)]}let At=(ht,Wt)=>new RegExp(`^--?${ht}=`).test(Qe[Wt]??"")||new RegExp(`^--?${ht}$`).test(Qe[Wt-1]??""),Ot=ST(Xe),Mt=Ze==="openssl"&&Qe[0]==="x509",Nt=et?{certificateOutputMayFeedReader:!0}:{};return[...Le,...Qe.flatMap((ht,Wt)=>Fn(Ze,ht).map((Dt)=>Ot&&At("(?:cert|key)-file",Wt)?{...Re(Dt),isCreatedPath:!0,...Nt}:Mt&&At("in",Wt)?{...Re(Dt),isCertificateInput:!0,...Nt}:Re(Dt)))]}function uh(W){return Sn(W[0]??"").toLowerCase()==="timeout"?W.slice(2):W}function ST(W){let G=uh(W);return Sn(G[0]??"").toLowerCase()==="tailscale"&&G[1]==="cert"}function bT(W,G,H){let J=ga(G,H);if(J===null||H[J]!=="explain")return null;let oe=[W,...H.slice(0,J)],ie=H.slice(J+1);for(let fe=0;fe<ie.length;fe++){let Re=ie[fe];if(Re==="--json"||Re==="--help"||Re==="-h")continue;if(Re==="--cwd"){let Te=ie[fe+1];if(Te&&!Te.startsWith("--"))oe.push(Te);fe++;continue}return oe}return oe}function CT(W,G,H,J,oe,ie,fe){if(xT(G,H,J,oe,ie,fe)){let Re=nr(W),Te=rd(Sn(Re[0]??"").toLowerCase(),Re.slice(1))?Re.slice(1).filter((ke)=>!ke.startsWith("-")):[];return[...fh(W),...Te].map((ke)=>({target:ke,cwd:ie}))}return mh(G,ET(W),H,J,oe,ie,fe,()=>[])}function vT(W,G,H,J,oe,ie,fe){let Re=nr(W);if(!bo(Sn(Re[0]??"").toLowerCase()))return[];return Sa(G,H,J,oe,ie,fe)??[{target:G,cwd:ie}]}function mh(W,G,H,J,oe,ie,fe,Re){let Te=wT(W);if(Te===null)return G.flatMap(Re);return G.flatMap((ke)=>gi.has(Te)?Go(H.getShellSyntax(ke),H,J,oe,ie,fe):ba(Te,ke,H,J,oe,ie,fe))}function fh(W){let G=nr(W);if(G.length===0)return[];let H=Sn(G[0]??"").toLowerCase();if(!sh.has(H))return[];let J=G[G[1]==="--"?2:1];if(H==="printf"&&J!==void 0&&!J.startsWith("-")&&!J.replaceAll("%%","").includes("%"))return[od(J.replaceAll("%%","%"))];return G.slice(1)}function ET(W){let G=nr(W);if(G.length===0)return[];let H=Sn(G[0]??"").toLowerCase(),J=G.slice(1);if(H==="echo"){let oe=J.findIndex((ie)=>!/^-[neE]+$/.test(ie));return[(oe===-1?[]:J.slice(oe)).join(" ")]}if(H==="printf")return RT(J);return[]}function RT(W){let G=W[0];if(G===void 0)return[];let H=(G.match(/%%|%[bqs]/g)??[]).filter((oe)=>oe!=="%%").length;if(H===0||W.length===1)return[od(G)];let J=W.slice(1);return Array.from({length:Math.ceil(J.length/H)},(oe,ie)=>_T(G,J.slice(ie*H,(ie+1)*H)))}function _T(W,G){let H=0;return od(W.replace(/%%|%[bqs]/g,(J)=>{if(J==="%%")return"%";let oe=G[H]??"";return H++,oe}))}function od(W){return W.replace(/\\n/g,`
43
+ `).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function xT(W,G,H,J,oe,ie){let fe=nr(W);if(fe.length===0||Sn(fe[0]??"").toLowerCase()!=="xargs")return!1;let Re=Zr(fe),Te=fe.slice(Re.childStart);if(Te.length===0)return!1;if(Re.replacementToken==="")return!1;let ke=Re.replacementToken,Le=ke===null?[...Te,Xc]:Te.map((Xe)=>Xe.split(ke).join(Xc));return Ni(Le,G,H,J,oe,ie).some((Xe)=>Xe.target.includes(Xc))}function wT(W){let G=nr(W);if(G.length===0)return null;let H=Sn(G[0]??"").toLowerCase();if(!bo(H))return null;return AT(H,G.slice(1))?H:null}function AT(W,G){let H=id(W);for(let J=0;J<G.length;J++){let oe=G[J];if(oe===void 0)break;if(td.has(oe)||hh(W,oe)||/^--(?:eval|exec)=/.test(oe))return!1;if(oe==="-")return!0;if(oe.startsWith("-")){if(H==="python"&&oe==="-m")return!1;if(pT.get(H)?.has(oe))J++;continue}return!1}return!0}function id(W){return/^python\d/.test(W)?"python":W}function PT(W){let G=[];for(let H of W){if(vh(H))continue;let J=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(H);if(J===null)break;if(J[1]!==void 0&&J[1]!=="")G.push(J[1])}return G}var Qg=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function TT(W,G){if(!G||!Qg.test(W))return W;return`~${W.replace(Qg,"").replace(/\\/g,"/")}`}function Fn(W,G){if(G==="--")return[];let H=[],J=G.indexOf("=");if(J>0&&J<G.length-1&&!G.slice(0,J).includes("?"))H.push(G.slice(J+1));if(G.startsWith("-"))return H;if(W==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(G))return H;if(W==="zip"&&/\.zip$/i.test(G))return H;return H.push(G),H}function IT(W){let G=-1,H=!1;for(let J=0;J<W.length;J++){let oe=W[J]??"";if(!H&&oe==="--"){H=!0;continue}if(H||!/^-(?:[A-Za-z]|-)/.test(oe)){if(G===-1)G=J;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(oe)){J+=2;continue}if(oe==="--indent"||oe==="-L"){J++;continue}if(oe.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(oe)||/^--(?: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(oe))continue;return W.flatMap((ie)=>Fn("jq",ie))}return W.flatMap((J,oe)=>oe===G?[]:Fn("jq",J))}function kT(W){let G=[];for(let H=0;H<W.length;H++){let J=W[H]??"";if(J==="--"||!J.startsWith("-"))return[...G,...eT.has(J)?ed("git",W.slice(H).map((ie)=>/^-[aeinopqsv]+m$/.test(ie)?"-m":ie),tT):ed("git",W.slice(H),nT)];if(G.push(...Fn("git",J)),!_n.has(J))continue;let oe=W[H+1];if(oe===void 0)break;G.push(...J==="-c"&&oe.includes("=")?[oe.slice(oe.indexOf("=")+1)]:Fn("git",oe)),H++}return G}function ed(W,G,H){let J=[];for(let oe=0;oe<G.length;oe++){let ie=G[oe]??"";if(ie==="--")return[...J,...G.slice(oe).flatMap((fe)=>Fn(W,fe))];if(H.has(ie)){oe++;continue}if(ie.includes("=")&&H.has(ie.slice(0,ie.indexOf("="))))continue;J.push(...Fn(W,ie))}return J}function OT(W){return W.flatMap((G,H)=>{let J=gh(G);if(J!==null)return eh(J.flag,J.value);let oe=ph(W[H-1]);return oe===null?[]:eh(oe,G)})}function eh(W,G){if(W==="-F"||W==="--form"){let H=G.indexOf("="),J=H===-1?G:G.slice(H+1);if(!J.startsWith("@")&&!J.startsWith("<"))return[];return Jc(J.slice(1).split(";")[0]??"")}if(W==="--data-urlencode"){let H=G.indexOf("@"),J=G.indexOf("=");if(H===-1||J!==-1&&J<H)return[];return Jc(G.slice(H+1))}return G.startsWith("@")?Jc(G.slice(1)):[]}function ph(W){if(W===void 0)return null;if(ah.has(W))return W;return/^-[A-Za-z]+[dF]$/.test(W)?`-${W.slice(-1)}`:null}function gh(W){let G=W.slice(0,2);if(W.length>2&&(G==="-d"||G==="-F"))return{flag:G,value:W.slice(2)};let H=W.indexOf("=");if(H===-1)return null;let J=W.slice(0,H);return ah.has(J)?{flag:J,value:W.slice(H+1)}:null}function Jc(W){return W===""||W==="-"?[]:[W]}function MT(W,G,H,J,oe,ie){let fe=W.findIndex((Te)=>Te.startsWith("-")||Te==="("||Te==="!"||Te===";"),Re=[...W.slice(0,fe===-1?W.length:fe),...W.flatMap((Te,ke)=>Te==="-files0-from"&&W[ke+1]!==void 0?[W[ke+1]??""]:[])];for(let Te=0;Te<W.length;Te++){if(!BP.has(W[Te]??""))continue;let ke=W.slice(Te+1),Le=ke.findIndex((Ze)=>UP.has(Ze)),Xe=Le===-1?ke:ke.slice(0,Le),Ye=Ni(Xe,G,H,J,oe,ie).map((Ze)=>Ze.target);if(Re.push(...Ye.filter((Ze)=>Ze!=="{}")),!Ye.includes("{}"))continue;Re.push(...W.slice(0,Te).flatMap((Ze,Qe,et)=>{if(!jP.has(Ze))return[];let tt=et[Qe+1];return tt===void 0?[]:[tt,tt.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return Re}function DT(W,G,H,J,oe,ie,fe){let Re=[];for(let Te=0;Te<G.length;Te++){let ke=G[Te];if(ke===void 0)break;if(td.has(ke)||hh(W,ke)){let Xe=G[Te+1];if(Xe!==void 0)Re.push(...ba(W,Xe,H,J,oe,ie,fe)),Te++;continue}let Le=/^--(?:eval|exec)=(.*)$/.exec(ke);if(Le!==null&&Le[1]!==void 0){Re.push(...ba(W,Le[1],H,J,oe,ie,fe));continue}if(!ke.startsWith("-"))Re.push({target:ke,cwd:ie})}return Re}function hh(W,G){if(!G.startsWith("-")||G.startsWith("--")||G.length<=2)return!1;return qP.get(G[G.length-1]??"")?.has(id(W))??!1}function NT(W,G,H,J,oe,ie){if(!W.includes("system"))return[];return ac(W)?.commands.flatMap((fe)=>Go(G.getShellSyntax(fe),G,H,J,oe,ie))??[]}function LT(W){return Array.from(W.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((G)=>G[1]).filter((G)=>G!==void 0&&G!=="")}function WT(W){let G=Array.from(W.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((H)=>H[2]).filter((H)=>H!==void 0&&H!=="");return[...G,...G.flatMap(ad),...W.match(Qc)??[]]}function ba(W,G,H,J,oe,ie,fe){let Re=(ht)=>({target:ht,cwd:ie}),Te=sI(W),ke=lI(G,Te);if(ke.kind==="unmaskable")return WT(G).map(Re);let Le=ke.masked.match(Yg)!==null||ke.literals.some((ht)=>Zg.test(ke.masked.slice(0,ht.start))),Xe=ke.masked.match(mT)!==null||ke.literals.some((ht)=>fT.test(ke.masked.slice(0,ht.start))),Ye=J.inlineLiteralsPresumedData===!0&&!gi.has(W),Ze=Ye&&(Te==="python"||Te==="javascript"),Qe=Ye&&!(fI(ke.masked)||Le||Xe)?[]:ke.literals,et=Ye?Array.from(ke.masked.matchAll(Yg),(ht)=>{let Wt=ht.index+ht[0].length;return{start:Wt,end:xs(ke.masked,Wt)}}):[],tt=!Ye||et.some((ht)=>Bl(ke.masked,ht.start)&&!jT(ke,ht.start))?ke.literals:ke.literals.filter((ht)=>Zg.test(ke.masked.slice(0,ht.start))||et.some((Wt)=>ht.start>=Wt.start&&ht.start<Wt.end)),gt=new Set(Le?tt:[]),_t=Ze&&Qe.length>0&&!$T(ke.masked,Te==="python"?"#":"//"),yt=_t?VT(ke.masked):[],At=_t?Array.from(ke.masked.matchAll(/[A-Za-z_$][\w$]*/g),(ht)=>({name:ht[0],index:ht.index})):[],Ot=UT(At),Mt=!BT(ke.masked,At),Nt=At.filter((ht)=>!th(ke.masked,{start:ht.index,text:ht.name,tokenStart:ht.index,tokenEnd:ht.index+ht.name.length},yt,Ot,Mt)).reduce((ht,Wt)=>{let Dt=ht.get(Wt.name)??[];return Dt.push(Wt.index),ht.set(Wt.name,Dt)},new Map);return[...Qe.filter((ht)=>ht.text!=="").map((ht)=>{if(!_t||gt.has(ht))return Re(ht.text);if(th(ke.masked,ht,yt,Ot,Mt)||KT(ke.masked,ht,yt,Nt))return{...Re(ht.text),literalRole:"data"};return rI(ke,ht,yt)?{...Re(ht.text),literalRole:"write"}:Re(ht.text)}),...Qe.flatMap((ht)=>ad(ht.text)).map(Re),...Ye?[]:ke.literals.flatMap((ht)=>ht.text.match(Qc)??[]).map(Re),...Le?tt.flatMap((ht)=>Sa(ht.text,H,{...J,commandHoldsPipe:!0},oe,ie,fe)??[Re(ht.text)]):[],...Xe?ke.literals.flatMap((ht)=>ba(W,ht.text.replace(/\\(.)/g,(Wt,Dt)=>Dt==="n"?`
44
+ `:Dt),H,J,oe,ie,fe)):[],...Ze?[]:(ke.masked.match(Qc)??[]).map(Re),...Ye?(G.match(/\$\{[^}]*\}|\$[A-Za-z_]\w*/g)??[]).map(Re):[]]}var sd={"(":")","[":"]","{":"}"},yh="and|elif|else|if|in|is|not|of|or|return|while|yield",GT=new RegExp(`(?:^|[^\\w$])(?:${yh})$`),FT=new RegExp(`(?:\\*|\\.\\.\\.)\\s*[([{]|\\.\\s*(?:${yh})\\s*\\(|/\\*`),zT=/^(?:exec|spawn)|^(?:popen|system|subprocess)$/;function $T(W,G){return FT.test(W)||W.split(`
45
+ `).some((H)=>{let J=H.indexOf(G);return J>=0&&/[()[\]{}]/.test(H.slice(J))})}function BT(W,G){return ZT.test(W)||G.some((H)=>{let J=YT.get(H.name),oe=H.index+H.name.length;return J!==void 0&&!J.test(W.slice(oe,oe+40))})}function UT(W){return W.some((G)=>bh(G.name).some((H)=>zT.test(H)))}var HT=new Set(["cmd","powershell","pwsh"]);function jT(W,G){let H=eo(W.masked,G),J=sd[W.masked[H]??""];if(J===void 0||J==="}")return!1;let oe=W.masked.indexOf(J,H+1),ie=W.masked.slice(H+1,oe);return oe!==-1&&/^\s*,[\w\s,]*$/.test(ie)&&/^[,)]/.test(W.masked.slice(eo(W.masked,oe+1)))&&!W.literals.some((fe)=>fe.tokenStart>H&&fe.tokenStart<oe&&(td.has(fe.text)||bo(Sn(fe.text).toLowerCase())||HT.has(Sn(fe.text).toLowerCase().replace(/\.exe$/,""))))}function VT(W){let G=[];return W.split("").map((H,J)=>{let oe=G.at(-1)??-1;if(H in sd)G.push(J);if(H===")"||H==="]"||H==="}")G.pop();return oe})}function th(W,G,H,J,oe){let ie=H[G.tokenStart]??-1,fe=W[ie]??"",Re=Wo(W,G.tokenStart),Te=eo(W,G.tokenEnd);if(/(?:^|[^\w$])in$|[=!]=$/.test(W.slice(Math.max(0,Re-3),Re+1)))return!0;if(/^(?:(?:not\s+)?in(?![\w$])|[=!]=)/.test(W.slice(Te,Te+8)))return!0;if(J&&(fe==="["||fe==="("))return!1;let ke=W[Re],Le=W[Te];if(fe==="{"&&ke===":")return oI(W,Re);let Xe=(ke===fe||ke===",")&&(Le===","||Le===sd[fe]||fe==="{"&&Le===":");if(fe!=="(")return Xe&&fe!=="";return Xe&&(oe&&qT.test(W.slice(Math.max(0,ie-20),ie))||(ke===","||Le===",")&&iI(W,ie))}function KT(W,G,H,J){let oe=Math.max(0,G.tokenStart-80),ie=`${oe===0?`
46
+ `:""}${W.slice(oe,G.tokenStart)}`,fe=XT.exec(ie)?.[1],Re=W[H[G.tokenStart]??-1];if(fe===void 0||Re==="("||Re==="[")return!1;let Te=eo(W,G.tokenEnd)+1;if(!/^\s*(?:[;\n]|$)/.test(W.slice(G.tokenEnd,Te)))return!1;let ke=G.tokenStart-ie.length+ie.lastIndexOf(fe);return(J.get(fe)??[]).every((Le)=>Le===ke)}var qT=/(?:^|[^\w$.])(?:print|console\s*\.\s*log)\s*$/,YT=new Map([["print",/^\s*\(/],["console",/^\s*\.\s*[\w$]+\s*\(/]]),ZT=/(?:^|[^\w$])(?:as|class|const|def|function|import|let|var)\s+(?:print|console)(?![\w$])/,XT=/[;\n{]\s*(?:(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*=\s*$/,JT=/(?:^|[^\w$.])(?:pathlib\s*\.\s*)?Path\s*$/,QT=/^\s*\.\s*write_(?:text|bytes)\s*\(/,eI=/(?:^|[^\w$.])open\s*$/,tI=/^[bt]*[awx][abtwx]*$/,nI=/(?:^|[^\w$])(?:writeFile|writeFileSync|appendFile|appendFileSync|Bun\s*\.\s*write)\s*$/;function rI(W,G,H){let J=H[G.tokenStart]??-1;if(W.masked[J]!=="(")return!1;let oe=Wo(W.masked,G.tokenStart),ie=eo(W.masked,G.tokenEnd),fe=W.masked[ie],Re=W.masked.slice(Math.max(0,J-40),J);if(JT.test(Re))return(oe===J||W.masked[oe]===",")&&(fe===","||fe===")")&&!W.literals.some((ke)=>ke.tokenStart>J&&ke.tokenStart<G.tokenStart)&&QT.test(W.masked.slice(xs(W.masked,J+1)+1));if(oe!==J||fe!==",")return!1;if(nI.test(Re))return!0;if(!eI.test(Re))return!1;let Te=W.literals.find((ke)=>/^,\s*(?:mode\s*=\s*)?$/.test(W.masked.slice(ie,ke.tokenStart)));return Te!==void 0&&tI.test(Te.text)&&/^[,)]/.test(W.masked.slice(eo(W.masked,Te.tokenEnd)))}function oI(W,G){let H=Wo(W,G),J=/[\w$]*$/.exec(W.slice(Math.max(0,H-63),H+1))?.[0]??"",oe=W[Wo(W,H+1-J.length)];return oe==="{"||oe===","}function iI(W,G){let H=Wo(W,G),J=W.slice(Math.max(0,H-7),H+1);return!/[\w$)\]]$/.test(J)||GT.test(J)}function sI(W){let G=id(W);if(G==="python")return"python";if(G==="osascript")return"opaque";return G==="node"||G==="bun"||G==="deno"?"javascript":"simple"}var aI={python:"#",javascript:"/"};function lI(W,G){if(G==="opaque")return{kind:"unmaskable"};let H={masked:W.split(""),literals:[]};return Sh(W,0,G,H,!1)===null?{kind:"unmaskable"}:{kind:"masked",masked:H.masked.join(""),literals:H.literals}}function Sh(W,G,H,J,oe){let ie=0;for(let fe=G;fe<W.length;fe++){let Re=W[fe]??"";if(oe&&Re==="}"&&ie===0)return fe;if(oe&&Re===aI[H])return null;if(Re==="{")ie++;if(Re==="}")ie--;if(H==="simple"&&(Re==="`"||Re==="%"||Re==="<")){if(dT.test(W.slice(fe)))return null}let Te=Re==="'"||Re==='"'||H==="javascript"&&Re==="`"?Re:null;if(Te===null)continue;if(Te==="`"&&mI(W,fe))return null;let ke=H==="python"?dI(W,fe):"",Le=H==="python"&&W.startsWith(Te.repeat(3),fe)?Te.repeat(3):Te,Xe=fe+Le.length,Ye=Te==="`"||/[fF]/.test(ke),Ze=fe-ke.length,Qe=Ye?cI(W,Ze,Xe,Le,H,J):uI(W,Xe,Le);if(Qe===null)return null;if(!Ye){let et=W.slice(Xe,Qe);if(H==="simple"&&Te==='"'&&uT.test(et))return null;J.literals.push({start:Xe,text:et,tokenStart:Ze,tokenEnd:Qe+Le.length}),J.masked.fill(" ",Xe,Qe)}J.masked.fill(" ",fe,Xe),J.masked.fill(" ",Qe,Qe+Le.length),fe=Qe+Le.length-1}return oe?null:W.length}function cI(W,G,H,J,oe,ie){let fe=oe==="python"?"{":"${",Re=J==="`"||J.length===3,Te="";for(let ke=H;ke<W.length;ke++){let Le=W[ke]??"";if(W.startsWith(J,ke))return ie.literals.push({start:H,text:Te,tokenStart:G,tokenEnd:ke+J.length}),ke;if(!Re&&(Le===`
47
+ `||Le==="\r"))return null;let Xe=oe==="python"&&(Le==="{"||Le==="}")&&W[ke+1]===Le;if(!Xe&&W.startsWith(fe,ke)){let Qe=Sh(W,ke+fe.length,oe,ie,!0);if(Qe===null)return null;Te+=`${fe}}`,ie.masked.fill(" ",ke,ke+fe.length),ie.masked[Qe]=" ",ke=Qe;continue}let Ze=Le==="\\"&&!(oe==="python"&&W[ke+1]==="{")||Xe?2:1;Te+=W.slice(ke,ke+Ze),ie.masked.fill(" ",ke,ke+Ze),ke+=Ze-1}return null}function dI(W,G){return cT.exec(W.slice(Math.max(0,G-3),G))?.[1]??""}function uI(W,G,H){let J=H.length===3;for(let oe=G;oe<W.length;oe++){let ie=W[oe];if(ie==="\\"){oe++;continue}if(!J&&(ie===`
48
+ `||ie==="\r"))return null;if(W.startsWith(H,oe))return oe}return null}function mI(W,G){for(let H=G-1;H>=0;H--){let J=W[H];if(!J||/\s/.test(J))continue;return/[\w$\])]/.test(J)}return!1}function fI(W){for(let G of W.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let H=G[0],J=G.index;if(VP.has(H.toLowerCase()))return!0;let oe=bh(H);if(!oe.some((ie)=>KP.has(ie)))continue;if(oe.length>1)return!0;if(W[Wo(W,J)]===".")return!0;if(W[eo(W,J+H.length)]==="(")return!0}return!1}function bh(W){return W.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((G)=>G.toLowerCase())}function Wo(W,G){for(let H=G-1;H>=0;H--)if(!/\s/.test(W[H]??""))return H;return-1}function eo(W,G){for(let H=G;H<W.length;H++)if(!/\s/.test(W[H]??""))return H;return W.length}function pI(W,G,H,J,oe,ie){return bI(W).flatMap((fe)=>{let Re=G.getShellSyntax(fe);if(Re.status==="invalid")return[];return[...Go(Re,G,{...H,displayOperandsAreCapturedOutput:!0},J,oe,ie),...gI(Re,J)?hI(Re,J).map((Te)=>({target:Te,cwd:oe})):[]]})}function gI(W,G){let H=Ds(W);for(let J=0;J<H.length;J++){let oe=H[J];if(oe?.kind!=="word"||Sn(cr(oe.text,G)).toLowerCase()!=="base64")continue;for(let ie=J+1;ie<H.length;ie++){let fe=H[ie];if(fe?.kind==="operator")break;if(fe?.kind!=="word")continue;let Re=cr(fe.text,G);if(Re==="--decode"||!Re.startsWith("--")&&Re.startsWith("-")&&/[dD]/.test(Re))return!0}}return!1}function hI(W,G){return Ds(W).flatMap((H)=>H.kind==="word"?[cr(H.text,G)]:H.kind==="redirection"&&H.target?[cr(H.target,G)]:[]).flatMap(ad)}function ad(W){let G=SI(W);if(G===null)return[];let H=Buffer.from(G,"base64").toString("utf8");if(H===""||yI(H))return[];return Buffer.from(H,"utf8").toString("base64").replace(/=+$/g,"")===G.replace(/=+$/g,"")?[H]:[]}function yI(W){return Array.from(W).some((G)=>{let H=G.charCodeAt(0);return H<32||H===127})}function SI(W){if(W.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(W))return null;if(/=/.test(W.replace(/=+$/g,"")))return null;let G=W.replace(/=+$/g,"");if(G.length%4===1)return null;return`${G.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-G.length%4)%4)}`}function bI(W){let G=[],H={inSingle:!1,inDouble:!1,escaped:!1};for(let J=0;J<W.length;J++){let oe=W[J];if(!oe)break;if(Yo(oe,H))continue;if(Ch(W,J,H)){let ie=CI(W,J+1);if(ie!==null)G.push(ie.body),J=ie.endIndex;continue}if(!H.inSingle&&oe==="`"){let ie=vI(W,J);if(ie!==null)G.push(ie.body),J=ie.endIndex}}return G}function CI(W,G){let H={inSingle:!1,inDouble:!1,escaped:!1},J=1;for(let oe=G+1;oe<W.length;oe++){let ie=W[oe];if(!ie)break;if(Yo(ie,H))continue;if(Ch(W,oe,H)){J++,oe++;continue}if(!H.inSingle&&!H.inDouble&&ie===")"){if(J--,J===0)return{body:W.slice(G+1,oe),endIndex:oe}}}return null}function vI(W,G){let H=!1;for(let J=G+1;J<W.length;J++){let oe=W[J];if(!oe)break;if(H){H=!1;continue}if(oe==="\\"){H=!0;continue}if(oe==="`")return{body:W.slice(G+1,J),endIndex:J}}return null}function Ch(W,G,H){return!H.inSingle&&W[G]==="$"&&W[G+1]==="("&&W[G+2]!=="("}function EI(W){let G=[],H=[],J=!1,oe=!1,ie=!1;for(let Te=0;Te<W.length;Te++){let ke=W[Te];if(ke===void 0)break;if(!ie&&ke==="--"){ie=!0;continue}if(ie){H.push(ke);continue}let Le=/^--([^=]+)(?:=(.*))?$/.exec(ke);if(Le!==null){let Xe=Le[1]??"",Ye=Le[2];if(Xe===oT)oe=!0;if(sT.has(Xe))J=!0;if(Ye!==void 0){if(Xe===qg)G.push(Ye);continue}if(lT.has(Xe)){let Ze=W[Te+1];if(Xe===qg&&Ze!==void 0)G.push(Ze);Te++}continue}if(ke.startsWith("-")&&ke.length>1){let Xe=ke.slice(1),Ye="",Ze="";for(let et=0;et<Xe.length;et++){let tt=Xe[et]??"";if(iT.has(tt))J=!0;if(aT.has(tt)){Ye=tt,Ze=Xe.slice(et+1);break}}if(Ye==="")continue;if(Ze.length>0){if(Ye===Kg)G.push(Ze);continue}let Qe=W[Te+1];if(Ye===Kg&&Qe!==void 0)G.push(Qe);Te++;continue}H.push(ke)}let Re=!J&&!oe?H.slice(1):H;return[...G,...Re]}function nr(W){let G=W.findIndex((H)=>!vh(H)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(H));return G===-1?[]:W.slice(G)}function vh(W){return W==="env"||W==="command"||W==="builtin"||W==="sudo"}var RI=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),_I=".env.",xI=new Set([".env.example",".env.sample",".env.template",".env.tpl",".env.defaults"]),wI=[".env.example.",".env.sample."];function AI(W){let G;try{G=new URL(W.trim())}catch{return!1}return G.protocol!=="file:"&&G.host!==""}function PI(W){return W.length>0&&!/\s/.test(W)}function Ca(W,G,H,J){let oe=Eh(W,G,H,J);return oe!==""&&H.paths.entryKind(oe)!=="missing"}function Eh(W,G,H,J){try{return Li(W,G,H,J)}catch(oe){if(oe instanceof s)throw oe;return""}}var TI=/[?&][^?&=/]+=/,II=new Set(["node_modules","__pycache__"]),kI=[["vendor","bundle"],["vendor","cache"]];function OI(W,G,H,J,oe){if(AI(W))return null;let ie=Rn(W,G,J,oe);if(!ie)return null;let fe=Vt(ie.split("/").pop()??""),Re=Vt(ie),Te=()=>PI(fe)||Ca(W,G,J,oe),ke=Vt(GI(W,G,J,oe));for(let Ye of rl){let Ze=`~/${Ye.suffixParts.join("/")}`;if((rh(Re,Ze)||rh(ke,Ze))&&fr(Ye.id,H))return Ye.id}if(xI.has(fe)||wI.some((Ye)=>fe.startsWith(Ye)))return null;let Le=MI(ie,G,H,J,oe);if(Le)return Le;if(RI.has(fe))return null;for(let Ye of nl)if(fe===Ye.basename&&fr(Ye.id,H))return Ye.id;if(fe.startsWith(_I)&&fr(ts.id,H)&&Te())return ts.id;for(let Ye of ol)if(fe.length>Ye.prefix.length&&fe.startsWith(Ye.prefix)){let Ze=fe.slice(Ye.prefix.length)[0];if((Ze==="-"||Ze==="_")&&fr(Ye.id,H)&&Te())return Ye.id}for(let Ye of il)if(fe.length>Ye.prefix.length&&fe.startsWith(Ye.prefix)){if(fe.slice(Ye.prefix.length)===Ye.suffix&&fr(Ye.id,H))return Ye.id}if(LI(Re))return null;if(!fe.includes(".")&&Zo.pattern.test(fe)&&fr(Zo.id,H))return Zo.id;if(TI.test(W)&&!Ca(W,G,J,oe))return null;let Xe=WI(fe,H);if(Xe)return Xe;return null}function MI(W,G,H,J,oe){return ns.find((ie)=>{if(!fr(ie.id,H))return!1;switch(ie.id){case"secret.cli.claude-code":return Ut(W,Kt(J.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",G,J,oe),[".credentials.json"]);case"secret.cli.claude-code.config":{let fe=Vt(W).split("/");return Ut(W,Kt(J.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",G,J,oe),["settings.json","settings.local.json"])||Di(W,"~/.claude.json",G,J,oe)||fe.at(-1)==="settings.local.json"&&fe.at(-2)===".claude"||fe.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Ut(W,Rn("~/.gemini/config",G,J,oe),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let fe=Kt(J.env.get("CODEX_HOME"),"~/.codex",G,J,oe);return Ut(W,fe,["auth.json",".credentials.json"])||Lo(W,fe,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let fe=Kt(J.env.get("CODEX_HOME"),"~/.codex",G,J,oe),Re=Vt(W).split("/").at(-1)??"";return Ut(W,fe,["config.toml"])||Re.endsWith(".config.toml")&&Ut(W,fe,[Re])}case"secret.cli.gemini":return Ut(W,sn(Kt(J.env.get("GEMINI_CLI_HOME"),"~",G,J,oe),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let fe=Vt(W).split("/"),Re=J.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),Te=J.env.get("ProgramData")?[sn(Kt(J.env.get("ProgramData"),"",G,J,oe),"gemini-cli")]:[];return Ut(W,sn(Kt(J.env.get("GEMINI_CLI_HOME"),"~",G,J,oe),".gemini"),["settings.json","google_accounts.json"])||fe.at(-1)==="settings.json"&&fe.at(-2)===".gemini"||(Re?.trim()?Di(W,Re,G,J,oe):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...Te].some((ke)=>Ut(W,Rn(ke,G,J,oe),["settings.json"]))}case"secret.cli.copilot-cli":{let fe=Kt(J.env.get("COPILOT_HOME"),"~/.copilot",G,J,oe);return Ut(W,fe,["config.json"])||Lo(W,fe,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Ut(W,Kt(J.env.get("COPILOT_HOME"),"~/.copilot",G,J,oe),["mcp-config.json"]);case"secret.cli.kimi-code":{let fe=Kt(J.env.get("KIMI_CODE_HOME"),"~/.kimi-code",G,J,oe),Re=Kt(J.env.get("KIMI_SHARE_DIR"),"~/.kimi",G,J,oe);return Ut(W,fe,["server.token"])||Lo(W,fe,["credentials"])||Lo(W,Re,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let fe=["config.toml","mcp.json"],Re=Vt(W).split("/");return Re.at(-1)==="mcp.json"&&Re.at(-2)===".kimi-code"||Ut(W,Kt(J.env.get("KIMI_CODE_HOME"),"~/.kimi-code",G,J,oe),fe)||Ut(W,Kt(J.env.get("KIMI_SHARE_DIR"),"~/.kimi",G,J,oe),[...fe,"config.json","config.json.bak"])}case"secret.cli.opencode":{let fe=sn(Kt(J.env.get("XDG_DATA_HOME"),"~/.local/share",G,J,oe),"opencode"),Re=Vt(W).split("/").at(-1)??"",Te=J.env.get("OPENCODE_DB")?.trim(),ke=Te&&Te!==":memory:"?[Te,`${Te}-wal`,`${Te}-shm`]:[];return Ut(W,fe,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Re)&&Ut(W,fe,[Re])||ke.some((Le)=>Di(W,Le,G,J,oe))}case"secret.cli.opencode.config":{let fe=sn(Kt(J.env.get("XDG_CONFIG_HOME"),"~/.config",G,J,oe),"opencode"),Re=J.env.get("ProgramData")?[sn(Kt(J.env.get("ProgramData"),"",G,J,oe),"opencode")]:[],Te=["opencode.json","opencode.jsonc"],ke=J.env.get("OPENCODE_CONFIG");return Te.includes(Vt(W).split("/").at(-1)??"")||Ut(W,fe,["config.json"])||(ke?.trim()?Di(W,ke,G,J,oe):!1)||["/Library/Application Support/opencode","/etc/opencode",...Re].some((Le)=>Ut(W,Rn(Le,G,J,oe),Te))}case"secret.cli.pi":return Ut(W,Kt(J.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",G,J,oe),["auth.json"]);case"secret.cli.pi.config":return Ut(W,Kt(J.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",G,J,oe),["models.json"]);case"secret.cli.amp":{let fe=Rn("~",G,J,oe);return[sn(Kt(J.env.get("XDG_DATA_HOME"),"~/.local/share",G,J,oe),"amp"),sn(fe,".local","share","amp")].some((Te)=>Ut(W,Te,["secrets.json"]))||Lo(W,sn(fe,".amp"),["oauth"])}case"secret.cli.amp.config":{let fe=["settings.json","settings.jsonc"],Re=[sn(Kt(J.env.get("XDG_CONFIG_HOME"),"~/.config",G,J,oe),"amp"),sn(Rn("~",G,J,oe),".config","amp")],Te=Vt(W).split("/"),ke=J.env.get("AMP_SETTINGS_FILE");return Re.some((Le)=>Ut(W,Le,fe))||Te.at(-2)===".amp"&&fe.includes(Te.at(-1)??"")||(ke?.trim()?Di(W,ke,G,J,oe):!1)}case"secret.cli.cursor":{let fe=sn(Kt(J.env.get("XDG_CONFIG_HOME"),"~/.config",G,J,oe),"cursor"),Re=sn(Kt(J.env.get("CURSOR_DATA_DIR"),"~/.cursor",G,J,oe),"projects");return Ut(W,Rn("~/.cursor",G,J,oe),["auth.json"])||Ut(W,fe,["auth.json"])||Vt(W).split("/").at(-1)==="mcp-auth.json"&&to(Vt(W),Vt(Re))}case"secret.cli.cursor.config":{let fe=Vt(W).split("/");return fe.at(-1)==="mcp.json"&&fe.at(-2)===".cursor"}case"secret.cli.grok-build":return Ut(W,Kt(J.env.get("GROK_HOME"),"~/.grok",G,J,oe),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let fe=Vt(W).split("/");return fe.at(-1)==="config.toml"&&fe.at(-2)===".grok"||Ut(W,Kt(J.env.get("GROK_HOME"),"~/.grok",G,J,oe),["config.toml","managed_config.toml","requirements.toml"])||Ut(W,Rn("/etc/grok",G,J,oe),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return Ut(W,Rn("~/.factory",G,J,oe),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let fe=Vt(W).split("/");return fe.at(-1)==="mcp.json"&&fe.at(-2)===".factory"||Ut(W,Rn("~/.factory",G,J,oe),["settings.json","hooks.json"])}case"secret.cli.devin":return[Kt(J.env.get("XDG_DATA_HOME"),"~/.local/share",G,J,oe),Rn("~/.local/share",G,J,oe)].some((fe)=>Ut(W,sn(fe,"devin"),["credentials.toml"])||Lo(W,sn(fe,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[Kt(J.env.get("XDG_CONFIG_HOME"),"~/.config",G,J,oe),Rn("~/.config",G,J,oe)].some((fe)=>Ut(W,sn(fe,"devin"),["config.json"]));default:return!1}})?.id??null}var nh=new WeakMap;function Kt(W,G,H,J,oe){let ie=nh.get(oe)??new Map;nh.set(oe,ie);let fe=`${H}\x00${W??""}\x00${G}`,Re=ie.get(fe);if(Re!==void 0)return Re;let Te=Rn(W?.trim()?W:G,H,J,oe);return ie.set(fe,Te),Te}function Ut(W,G,H){return H.some((J)=>Rh(W,sn(G,J)))}function Lo(W,G,H){return H.some((J)=>to(Vt(W),Vt(sn(G,J))))}function Di(W,G,H,J,oe){return Rh(W,Rn(G,H,J,oe))}function Rh(W,G){return Vt(W)===Vt(G)}function sn(W,...G){return Yn([W,...G].filter(Boolean).join("/"))}function DI(W,G,H,J,oe,ie){if(H.length===0)return!1;let fe=Vt(Li(W,G,oe,ie));return H.some((Re)=>to(fe,Vt(Li(Re,J,oe,ie))))}function NI(W,G,H,J,oe,ie){if(H.length===0)return!1;let fe=Vt(Li(W,G,oe,ie));if(!fe)return!1;let Re=oe.env.get("HOME")??oe.home,Te=Re?Yn(Bt(fn(Re),oe.paths,ie)):"",ke=Vt(Te),Le=oe.env.get("CC_SAFETY_NET_HOME"),Xe=Vt(Le?Yn(Bt(va(fn(Le)),oe.paths,ie)):Te&&Yn(Bt(`${Te}/.cc-safety-net`,oe.paths,ie)));if(Xe&&to(fe,Xe))return!1;return H.some((Ye)=>{let Ze=dl(Ye);if(Ze&&oh.basename(fe)!==Vt(Ze.name))return!1;let Qe=Vt(Li(Ze?.root??Ye,J,oe,ie));if(!Qe)return!1;if(ke&&(ke===Qe||ke.startsWith(Qe.endsWith("/")?Qe:`${Qe}/`)))return!1;return to(fe,Qe)&&!(Ze&&fe===Qe)})}function LI(W){let G=W.split("/");return G.some((H)=>II.has(H))||kI.some(([H,J])=>G.some((oe,ie)=>oe===H&&G[ie+1]===J))}function WI(W,G){let H=W.lastIndexOf("."),J=H>0&&H<W.length-1?W.slice(H+1):"";if(J==="")return null;for(let oe of sl)if(J===oe.extension&&fr(oe.id,G))return oe.id;for(let oe of al)if(oe.pattern.test(J)&&fr(oe.id,G))return oe.id;return null}function Vt(W){return W.toLowerCase()}function fr(W,G){return!G?.disabledRules?.includes(W)}function Rn(W,G,H,J){let{home:oe,normalized:ie}=ld(W,H,J);if(!ie)return"";if(!oe)return ie;let fe=cd(ie,oe),Re=ya(fe)?fe:Yn(va(G,fe)),Te=Yn(Bt(Re,H.paths,J));if(!to(Te,oe)){if(ya(fe))return Te;return Te===Re?ie:Te}let ke=Te.slice(oe.length);return ke?`~${ke}`:"~"}function rh(W,G){return W===G||W.startsWith(`${G}/`)}function GI(W,G,H,J){let{home:oe,normalized:ie}=ld(W,H,J);if(!ie||!oe)return"";let fe=cd(ie,oe),Re=oh.normalize(ya(fe)?fe:Yn(va(G,fe))),Te=Yn(fn(H.env.get("HOME")??H.home)),ke=(Ye)=>process.platform==="win32"?Ye.toLowerCase():Ye,Le=[oe,Te].find((Ye)=>Ye!==""&&to(ke(Re),ke(Ye)));if(Le===void 0)return"";let Xe=Re.slice(Le.length);return Xe?`~${Xe}`:"~"}function Li(W,G,H,J){let{home:oe,normalized:ie}=ld(W,H,J);if(!ie)return"";let fe=oe?cd(ie,oe):ie;return Yn(Bt(ya(fe)?fe:va(G,fe),H.paths,J))}function ld(W,G,H){let J=G.env.get("HOME")??G.home,oe=J?Yn(Bt(fn(J),G.paths,H)):"",ie=Yn(fn(FI(cr(W,G))));return{home:oe,normalized:ie}}function FI(W){if(!W.trim().toLowerCase().startsWith("file:"))return W;try{return FP(W)}catch{return W}}function cd(W,G){if(W==="~")return G;if(W.startsWith("~/"))return sn(G,W.slice(2));return W}function zI(W){if(process.platform==="win32")return!0;return GP.parse(W).root.length>1}function Yn(W){let G=W.trim(),H=(G.includes("\\")&&zI(G)?G.replace(/\\/g,"/"):G).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(H==="/")return H;return H.replace(/\/+$/g,"")}function to(W,G){return W===G||W.startsWith(G.endsWith("/")?G:`${G}/`)}function Sn(W){return W.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??W}class f extends Error{stage;evaluation;name="GuardEvaluationError";constructor(W,G,H){super(`CC Safety Net ${W} dependency failed`,{cause:H});this.stage=W;this.evaluation=G}}var $I={findPolicyMutation:Hg,findGitMetadataMutation:gf,resolveGitMetadata:jI,loadPolicySnapshot:R,findSensitiveTarget:ch,analyzeCommand:Wg,getModes:P},BI=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/,UI=["workdir","cwd","working_directory"];function j(W,G){let H={...$I,...G.dependencies},J=qI(W),oe=()=>Tr("config-load",J,()=>H.loadPolicySnapshot(G.environment,{...G.policyOptions,cwd:W.context.configCwd})),ie=W.route.kind==="unknown"&&J?oe():void 0,fe=ie?.policy.commandTools.find((Dt)=>Dt.name===W.toolName),Re=fe&&J?HI(W,J,fe.cwd,G.environment.paths):W;if("decision"in Re)return Re;let Te=Re,ke=Te===W?{}:{promotedInvocation:Te},Le=Wi(Te)?Te.command:J,Xe=Tr("policy-protection",Le,()=>uf(Te)),Ye=Co(Xe,"input-candidate"),Ze=Co(Xe,"declared-command");if(Wi(Te)&&Te.command?.trim()&&Ze?.program.status==="limited")return{stage:"command-analysis",...ke,decision:{kind:"deny",reason:Xn,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:Te.command,segment:Te.command}}};if(Ye?.program.status==="limited")return{stage:"command-validation",...ke,decision:{kind:"deny",reason:df,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let Qe=In(),et=Tr("policy-protection",Le,()=>H.resolveGitMetadata([Te.context.executionCwd,Te.context.configCwd],G.environment)),tt=Tr("policy-protection",Le,()=>H.findPolicyMutation(Xe,G.environment,Qe));if(tt){let Dt=Le??tt.target;return{stage:"policy-protection",...ke,decision:{kind:"deny",reason:Je,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:Dt,segment:tt.target}}}}let gt=Tr("policy-protection",Le,()=>zg(Xe,G.environment,Qe));if(gt){let Dt=Le??gt.target;return{stage:"policy-protection",...ke,decision:{kind:"deny",reason:Ke,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:Dt,segment:gt.target}}}}let _t=Tr("policy-protection",Le,()=>H.findGitMetadataMutation(Xe,et,G.environment,Qe));if(_t){let Dt=Le??_t.target;return{stage:"policy-protection",...ke,decision:{kind:"deny",reason:v,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:Dt,segment:_t.target}}}}let yt=ie??oe(),At=yt.policy,Ot=H.getModes(At,G.environment.env),Mt={level:Ot.effectiveLevel,...VI(yt),...ke},Nt=At.secretProtection.enabled===!1?null:Tr("secret-protection",Le,()=>H.findSensitiveTarget(Xe,At.secretProtection,G.environment,Qe,{strict:Wi(Te)||Ye?.program.dialect==="powershell"?Ot.strict:void 0}));if(Nt){let Dt=Le??Nt.target;return{stage:"secret-protection",...Mt,decision:{kind:"deny",reason:ih,intent:"hard_stop",ruleId:Nt.ruleId,evidence:{command:Dt,segment:Nt.target}}}}if(!Wi(Te))return{stage:"non-command",...Mt,decision:{kind:"allow"}};if(!Te.command||Te.command.trim()==="")return{...Ea("command-validation",Le),...Mt};let ht=Tr("command-analysis",Le,()=>Gg(()=>H.analyzeCommand(Te.command,{cwd:Te.context.executionCwd,shell:Te.route.shell,policySnapshot:yt,environment:G.environment,protectedGitMetadata:et,effectiveCapabilities:Ot.capabilities,worktreeMode:Ot.worktreeMode,budget:Qe,...G.trace?{trace:G.trace}:{}},KI(Xe),Xe.store),Te.command,G.trace)),Wt=Te.route.shell==="auto"&&Xe.store.readsAutoAsPowerShell()?()=>{let Dt=G.trace?.branch(),en={...j({...Te,route:{kind:"command",shell:"posix"}},{...G,...Dt?{trace:Dt.trace}:{},dependencies:{...G.dependencies,loadPolicySnapshot:()=>yt,resolveGitMetadata:()=>et}}),...ke};return{decision:en.decision,withItsTrace:()=>(Dt?.adopt(),en)}}:void 0;if(ht.decision){let Dt=!Ot.strict&&(ht.decision.ruleId==="raw-text.dangerous-command"||ht.decision.reason===yi&&!BI.test(ht.decision.evidence?.segment??"")&&Nn(Te.command)===null),en=Dt?Wt?.():void 0;if(en?.decision.kind==="deny"&&!en.decision.unverifiedByStandardMode)return en.withItsTrace();return{stage:"command-analysis",...Mt,..."errorCode"in ht?{errorCode:ht.errorCode}:{},decision:Dt?{...ht.decision,unverifiedByStandardMode:!0}:ht.decision}}return Wt?.().withItsTrace()??{stage:"command-analysis",...Mt,decision:{kind:"allow"}}}function HI(W,G,H,J){let oe=[...new Set((H?[H]:UI).flatMap((Te)=>{let ke=Object.getOwnPropertyDescriptor(W.input,Te);return ke?[ke.value]:[]}))],ie=oe.filter((Te)=>typeof Te==="string"&&Te.trim()!=="");if(oe.length>1||ie.length!==oe.length)return Ea("command-validation",G);let fe=ie[0],Re=fe===void 0?W.context.configCwd:Kd(fe,W.context.configCwd,J);if(!Re){let Te=_({directory:"requested",problem:"unusable",cwd:fe??""});return{stage:"command-validation",decision:{kind:"deny",reason:Te.reason,ruleId:Te.ruleId,intent:Te.intent,evidence:{command:G,segment:G}}}}return l(W.toolName,W.input,{kind:"command",shell:"auto"},{configCwd:W.context.configCwd,executionCwd:Re},G)}function jI(W,G){let H=[...new Set(W.filter((J)=>typeof J==="string"&&J!==""))].flatMap((J)=>G.gitMetadata(J)??[]);if(H.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(H.flatMap((J)=>J.entries))]),markerFiles:Object.freeze([...new Set(H.flatMap((J)=>J.markerFiles))]),directories:Object.freeze([...new Set(H.flatMap((J)=>J.directories))]),hooksDirectories:Object.freeze([...new Set(H.flatMap((J)=>J.hooksDirectories))])})}function VI(W){if(W.state==="ready")return{};return{configFallback:{reason:W.reason}}}function KI(W){return Co(W,"declared-command")?.program}function qI(W){try{return se(W.input)}catch(G){let H=Wi(W)?W.command:void 0;throw new f("policy-protection",Ea("policy-protection",G instanceof m?void 0:H,G),G)}}function Tr(W,G,H){try{return H()}catch(J){throw new f(W,Ea(W,J instanceof m?void 0:G,J),J)}}function Ea(W,G,H){let J=H instanceof U?{reason:Qn,ruleId:"analysis.strict-unparseable"}:H instanceof s||H instanceof b?{reason:wa,ruleId:"analysis.limit"}:{reason:zo,ruleId:"analysis.failed-closed"};return{stage:W,decision:{kind:"deny",...J,intent:"stop_and_explain",...G?{evidence:{command:G,segment:G}}:{}}}}function Wi(W){return W.route.kind==="command"}
49
+ export{a,s,Y,Me,nt,T,bt,rt,_e,L,_,Z,xt,c,n,ot,Pe,P,S,me,vt,m,Ie,x,se,ge,St,it,st,l,Fe,o,w,i,ae,r,g,he,B,wt,Ct,p,ye,be,Et,M,X,ce,C,kt,I,h,Ae,z,u,O,Q,at,ct,F,E,D,xe,ve,$e,le,d,e,Ue,Oe,je,Se,lt,ut,ue,De,de,Ge,ee,V,He,we,q,dt,K,te,ne,pe,pt,ft,k,A,We,Be,mt,ze,R,Ve,Ne,qe,y,t,re,Ce,b,U,v,N,Rt,Ee,Ke,Je,f,j};