cc-safety-net 2.6.0 → 2.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,49 @@
1
+ var ca="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Bn="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",ko="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var la={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."},Io={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,...la},processedCandidateBytes:{cap:4194304,...la},pathEnvironmentExpansion:{cap:64,...la},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,...Io},trackedHeredocFiles:{cap:64,...Io},controlFlowStates:{cap:64,...Io},wrapperPeelIterations:{cap:20,...Io},derivedCommandShape:Io});class s extends Error{kind;name="AnalysisLimit";constructor(G){super(a[G].reason);this.kind=G}}function Pn(){let G=new Map;return{counters:G,resolvedPaths:new Map,charge(U,j=1){let K=(G.get(U)??0)+j;if(G.set(U,K),K>a[U].cap)throw new s(U)}}}var Jg=[/\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 J(G){return Pe(G.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 Pe(G){return Jg.reduce((U,j)=>U.replace(j,"<redacted>"),G.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 Be(G){return Xc(G).reduceRight((U,j)=>`${U.slice(0,j.valueStart)}<redacted>${U.slice(j.valueEnd)}`,G)}function R(G){return Pe(Be(G))}function nt(G){return Xc(G).map((U)=>G.slice(U.valueStart,U.valueEnd))}function ze(G){return/[A-Za-z_][A-Za-z0-9_]*=/.test(G)}function Xc(G){return[...G.matchAll(/[A-Za-z_][A-Za-z0-9_]*=/g)].flatMap((U)=>{let j=G[U.index-1];if(U.index>0&&j&&!/[\s"'([{]/.test(j))return[];let K=U.index+U[0].length;if(K>=G.length)return[];return[{valueStart:K,valueEnd:Qg(G,K)}]})}function Qg(G,U){if(G.startsWith("$(",U))return eh(G,U);let j=G[U];if(j==='"'||j==="'"){for(let re=U+1;re<G.length;re++){if(j==='"'&&G[re]==="\\"){re++;continue}if(G[re]===j)return re+1}return G.length}let K=U;while(K<G.length&&!/\s/.test(G[K]??""))K++;return K}function eh(G,U){let j=0,K;for(let re=U;re<G.length;re++){let oe=G[re];if(K){if(K==='"'&&oe==="\\"){re++;continue}if(oe===K)K=void 0;continue}if(oe==='"'||oe==="'"){K=oe;continue}if(oe==="$"&&G[re+1]==="("){j++,re++;continue}if(oe!==")")continue;if(j--,j===0)return re+1}return G.length}var th={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 nh(G){let U=G.maxLen??200,j=G.redact??((re)=>re),K=(re)=>re.length>U?`${re.slice(0,U)}...`:re;return[G.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${j(G.reason)}`,G.ruleId?`Rule: ${G.ruleId}`:void 0,G.toolName?`Tool: ${G.toolName}`:void 0,G.command?`Command: ${K(j(G.command))}`:void 0,G.segment&&G.segment!==G.command?`Segment: ${K(j(G.segment))}`:void 0,G.cwd?`Working directory: ${K(j(G.cwd))}`:void 0,G.configWarning?`Config warning: ${j(G.configWarning)}`:void 0,G.askUser?"Approve only if you expected this command.":th[G.intent??"manual_only"]].filter((re)=>re!==void 0).join(`
2
+
3
+ `)}function Ce(G,U){if(G.decision.kind!=="deny")return;let j=U.includeEvidence?G.decision.evidence:void 0;return{reason:G.decision.reason,ruleId:G.decision.ruleId,intent:G.decision.intent,command:j?.command,segment:j?.segment,toolName:U.toolName,...G.configFallback?{configWarning:G.configFallback.reason}:{},...G.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function O(G={}){return{reason:ko,ruleId:"analysis.failed-closed",intent:"stop_and_explain",command:G.command,segment:G.segment??G.command,toolName:G.toolName}}var rh={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 D(G,U={}){return{...rh[G.directory][G.problem],command:U.command,toolName:U.toolName,cwd:G.cwd}}function Y(G){return nh({...G,redact:J})}function rt(G){return J(G instanceof Error?G.message:String(G))}import{lstatSync as Gh,realpathSync as zh,statSync as $h}from"node:fs";import{homedir as Bh,tmpdir as Uh}from"node:os";import{statSync as Lh}from"node:fs";import{join as Wh}from"node:path";import{basename as eu,dirname as oh,isAbsolute as ih,join as sh,normalize as ah,resolve as Jc}from"node:path";var lh=256,Pi=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 an(G,U=process.platform){if(U!=="win32")return G;return G.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function sr(G,U=process.platform){if(U!=="win32")return!1;return(G[0]==="/"||G[0]==="\\")&&(G[1]==="/"||G[1]==="\\")}function fa(G,U){return ua(G,0,U)}function ua(G,U,j){let K="",re=0,oe=0;while(re<G.length){if(G[re]!=="$"){K+=G[re],re++;continue}if(G[re+1]==="{"){let Se=da(G,re+2),we=ch(G,re,U);if(we===null){if(Pi.has(Se))throw new s("pathEnvironmentExpansion");if(oe++,oe>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");K+="${",re+=2;continue}let We=G.slice(re,we+1);K+=uh(We,U,j),re=we+1;continue}let de=da(G,re+1);if(!de){K+="$",re++;continue}K+=ma(de,j)??`$${de}`,re+=de.length+1}return K}function ch(G,U,j){let K=1;for(let re=U+2;re<G.length;re++){if(G[re]==="\\"){re++;continue}if(G[re]==="$"&&G[re+1]==="{"){if(K++,j+K>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");re++;continue}if(G[re]!=="}")continue;if(K--,K===0)return re}return null}function uh(G,U,j){let K=G.slice(2,-1),re=da(K,0);if(!re)return G;let oe=K.slice(re.length);if(!oe)return ma(re,j)??G;let de=[":-",":+",":=",":?","-","+","=","?"].find((We)=>oe.startsWith(We));if(!de){if(Pi.has(re))throw new s("pathEnvironmentExpansion");return G}if(!Pi.has(re))return G;if(de.endsWith("="))throw new s("pathEnvironmentExpansion");let Se=ma(re,j),we=de.startsWith(":")?Se!==null&&Se!=="":Se!==null;if(de.endsWith("?")&&!we)throw new s("pathEnvironmentExpansion");if(de.endsWith("-")||de.endsWith("?"))return we?Se??"":ua(oe.slice(de.length),U+1,j);return we?ua(oe.slice(de.length),U+1,j):""}function da(G,U){if(!/[A-Za-z_]/.test(G[U]??""))return"";let j=U+1;while(/[A-Za-z0-9_]/.test(G[j]??""))j++;return G.slice(U,j)}function ma(G,U){if(!Pi.has(G))return null;if(G==="HOME")return U.env.get("HOME")??U.home;return U.env.get(G)??null}function Nt(G,U,j){if(!G)return G;let K=j.resolvedPaths.get(G);if(K!==void 0)return K;let re=[],oe=G;while(!0){tu(j,oe);let de=U.realpath(oe);if(de!==null)return Qc(j,G,de,re);let Se=oh(oe);if(Se===oe||re.length>=lh)return Qc(j,G,oe,re);re.push(eu(oe)),oe=Se}}function Qc(G,U,j,K){let re=K.length===0?j:sh(j,...K.reverse());return G.resolvedPaths.set(U,re),re}function dh(G,U,j){let K=j.resolvedPaths.get(G);if(K!==void 0)return K;tu(j,G);let re=U.realpath(G);if(re!==null)j.resolvedPaths.set(G,re);return re}function tu(G,U){G.charge("realpathAttempts"),G.charge("processedCandidateBytes",Buffer.byteLength(U))}function ln(G,U,j,K){let re=ru(G,U,j);if(!re)return"";return Nt(re,j.paths,K).replace(/\\/g,"/")}function nu(G,U,j,K,re){let oe=ru(G,U,j);if(!oe)return null;if(re(eu(oe)))return Nt(oe,j.paths,K).replace(/\\/g,"/");let de=dh(oe,j.paths,K);return de===null?null:de.replace(/\\/g,"/")}function ru(G,U,j){let K=j.home,re=fa(G.trim(),j).replace(/\\/g,"/");if(!re)return"";let oe=re==="~"?K:re.startsWith("~/")?Jc(K,re.slice(2)):re,de=an(oe);return ah(ih(de)?de:Jc(U,de))}import{spawnSync as mh}from"node:child_process";import{existsSync as Mo,lstatSync as fh,readFileSync as Do,realpathSync as qr,statSync as Oo}from"node:fs";import{dirname as pa,isAbsolute as ga,join as Kr,resolve as Ai}from"node:path";var ph=["/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"],gh=5000;function iu(G,U=Oh(),j=gh){let K=hh(G),re=K===null?null:yh(K);if(K===null||re===null)return null;let oe=Ih(K,re,U,j);return oe===null?null:{recursiveSubmodules:oe}}function hh(G){try{let U=qr(Ai(G));return Oo(U).isDirectory()?U:null}catch{return null}}function yh(G){let U=Th(G);if(!U)return null;try{let j=fh(U);if(j.isSymbolicLink()||!j.isFile())return null;let K=ha(U);if(!K?.commonDir)return null;if(!Sh(K.gitDir,U))return null;return vh(K.gitDir,pa(U))?{gitDir:K.gitDir,commonDir:K.commonDir}:null}catch{return null}}function ha(G){try{let U=bh(G);if(!U)return null;let j=qr(ga(U)?U:Ai(pa(G),U));if(!Oo(j).isDirectory())return null;return{gitDir:j,commonDir:Ch(j)}}catch{return null}}function bh(G){let U=Do(G,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!U.startsWith("gitdir:"))return null;return U.slice(7).trim()||null}function Ch(G){try{let U=Do(Kr(G,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!U)return null;let j=qr(ga(U)?U:Ai(G,U));return Oo(j).isDirectory()?j:null}catch{return null}}function Sh(G,U){let j=Eh(G);return j===null?!1:su(G,j,U)}function vh(G,U){let j=Rh(G);return j===null?!0:su(G,j,U)}function Eh(G){let U=Kr(G,"gitdir");if(!Mo(U))return null;let j=Do(U,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return j===""?null:j}function Rh(G){let U=Kr(G,"config.worktree");return Mo(U)?_h(U):null}function su(G,U,j){try{return xh(ga(U)?U:Ai(G,U),j)}catch{return!1}}function xh(G,U){try{let j=Oo(G),K=Oo(U);if(j.ino!==0&&K.ino!==0&&j.dev===K.dev&&j.ino===K.ino)return!0}catch{}return ou(qr.native(G))===ou(qr.native(U))}function ou(G){let U=G.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),j=U.length>1&&U.endsWith("/")?U.slice(0,-1):U;return process.platform==="win32"?j.toLowerCase():j}function _h(G){let U=Do(G,"utf-8"),j=!1,K=null;for(let re of U.split(/\r?\n/)){let oe=re.trim();if(oe===""||oe.startsWith("#")||oe.startsWith(";"))continue;if(oe.startsWith("[")){j=/^\[core\]$/i.test(oe);continue}if(!j)continue;let de=oe.match(/^worktree\s*=\s*(.*)$/i);if(de)K=wh(de[1]??"")}return K}function wh(G){let U=G.trim();if(!U.startsWith('"')||!U.endsWith('"'))return U;return Ah(U.slice(1,-1))}var Ph={"\\":"\\",'"':'"',n:`
4
+ `,t:"\t",b:"\b"};function Ah(G){return G.replace(/\\(.?)/gs,(U,j)=>j===""?U:Ph[j]??U)}function Th(G){try{return ya(qr(G))}catch{return null}}function ya(G){let U=G;while(!0){let j=Kr(U,".git");if(Mo(j))return j;let K=pa(U);if(K===U)return null;U=K}}function Ih(G,U,j,K){if(kh(U))return!0;if(j===null)return!0;let re=mh(j,["config","--get","submodule.recurse"],{cwd:G,encoding:"utf8",env:Mh(process.env),stdio:["ignore","pipe","ignore"],timeout:K});if(re.error!==void 0||re.status!==0&&re.status!==1)return null;return re.status===0&&au(re.stdout.trim())}function kh(G){return[Kr(G.commonDir,"config"),Kr(G.gitDir,"config.worktree")].filter((U)=>Mo(U)).some((U)=>Dh(U))}function Oh(){return ph.find((G)=>Mo(G))??null}function No(G){return G==="GIT_CONFIG_COUNT"||G==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(G)}function Mh(G){return Object.fromEntries(Object.entries(G).filter(([U])=>!No(U)))}function Dh(G){let U;try{U=Do(G,"utf-8")}catch{return!0}let j="",K=!1;for(let re of U.split(/\r?\n/)){let oe=re.trim();if(oe===""||oe.startsWith("#")||oe.startsWith(";"))continue;let de=oe.match(/^\[([^\]]+)\]$/);if(de){j=de[1]?.trim().toLowerCase()??"";continue}let Se=oe.indexOf("="),we=(Se===-1?oe:oe.slice(0,Se)).trim().toLowerCase(),We=Se===-1?"true":oe.slice(Se+1).trim();if(Nh(j)&&we==="path")return!0;if(j==="submodule"&&we==="recurse")K=au(We)}return K}function Nh(G){return G==="include"||G.startsWith("includeif ")}function au(G){let U=G.toLowerCase();return U!=="false"&&U!=="no"&&U!=="off"&&U!=="0"}function lu(G,U){if(G==="")return null;let j=Pn(),K=ya(ln(G,G,U,j)),re=K?Fh(K,G,U,j):null;if(!re)return null;return Object.freeze({entries:Object.freeze([re.entry]),markerFiles:Object.freeze(re.markerFile?[re.markerFile]:[]),directories:Object.freeze(re.directories),hooksDirectories:Object.freeze(re.hooksDirectories)})}function Fh(G,U,j,K){try{let re=ln(G,U,j,K),oe=Lh(G),de=oe.isFile()?re:null,Se=oe.isFile()?ha(G):null,we=(oe.isDirectory()?[re]:[Se?.gitDir,Se?.commonDir]).flatMap((mt)=>mt?[Yr(ln(mt,U,j,K))]:[]),We=[...new Set(oe.isDirectory()?[Yr(G.replace(/\\/g,"/")),...we]:we)];return{entry:Yr(re),markerFile:de?Yr(de):null,directories:We,hooksDirectories:[...new Set(We.flatMap((mt)=>{let gt=Yr(Wh(mt,"hooks").replace(/\\/g,"/"));return[gt,Yr(ln(gt,U,j,K))]}))]}}catch{return null}}function Yr(G){return process.platform==="win32"?G.toLowerCase():G}var Hh={realpath:(G)=>{try{return zh(G)}catch{return null}},entryKind:(G)=>{try{let U=Gh(G,{throwIfNoEntry:!1});if(!U)return"missing";return U.isSymbolicLink()?"symlink":"present"}catch(U){if(U.code==="ENAMETOOLONG")return"missing";throw U}},isDirectory:(G)=>{try{return $h(G).isDirectory()}catch{return!1}}};function c(){return jh({env:new Map(Object.entries(process.env).flatMap(([G,U])=>U===void 0?[]:[[G,U]])),home:an(process.env.HOME||Bh()),tmpdir:Uh(),paths:Hh})}function jh(G,U={}){let j=new Map,K=new Map,re={...G,gitMetadata:(oe)=>cu(j,oe,()=>lu(oe,re)),worktreeFacts:(oe)=>cu(K,oe,()=>iu(oe)),...U};return re}function cu(G,U,j){let K=G.get(U);if(K!==void 0)return K;let re=j();return G.set(U,re),re}import{accessSync as py,constants as _u,statSync as gy}from"node:fs";import{isAbsolute as wu,relative as hy,resolve as yy,sep as by}from"node:path";import{types as Vh}from"node:util";var qh=new Set(["applypatch","patch"]),Kh=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),Yh=new Set(["grep","grepsearch","rg"]),Zh=new Set(["find","findbyname","glob"]),Xh=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),Jh=new Set(["command","diff","input","patch","patchtext"]),uu=new TextEncoder,Qh=new TextDecoder,ey=/\s/,ty=64;class f extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var Lo=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function gu(G){return G.replace(/[-_\s]/g,"").toLowerCase()}function Ii(G){return Xh.has(gu(G))}function P(G){let U=gu(G);if(qh.has(U))return"patch";if(Yh.has(U))return"grep";if(Zh.has(U))return"glob";if(Kh.has(U))return"path";return"unknown"}function ie(G){if(!G||typeof G!=="object")return;Eu(G);let U=Object.getOwnPropertyDescriptor(G,"command");if(!U){if("command"in G)Un();return}if(U.get||U.set)Un();let j=U.value;return typeof j==="string"&&j!==""?j:void 0}function hu(G,U){return yu(G,U,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function yu(G,U,j,K,re){let oe=vu(G,K,re);if(typeof G==="string")return j?[G]:[];if(!oe)return[];let de=oe.entries.flatMap(([Se,we])=>yu(we,U,oe.array?j:U.has(bu(Se)),K,re+1));return K.ancestors.delete(oe.object),de}function bu(G){return G.replace(/-/g,"_").toLowerCase()}function Cu(G){return Su(G,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(ry)}function Su(G,U,j,K){let re=vu(G,j,K);if(typeof G==="string")return U?[G]:[];if(!re)return[];let oe=re.entries.flatMap(([de,Se])=>Su(Se,re.array?U:Jh.has(bu(de)),j,K+1));return j.ancestors.delete(re.object),oe}function ny(G,U,j){if(U.nodes++,G!==null&&typeof G==="object"&&j>Lo.maxDepth||U.nodes>Lo.maxNodes)Un();if(typeof G!=="string")return;let K=Buffer.byteLength(G);if(U.stringBytes+=K,K>Lo.maxStringBytes||U.stringBytes>Lo.maxAggregateStringBytes)Un()}function vu(G,U,j){if(ny(G,U,j),!G||typeof G!=="object")return null;let K=Eu(G);if(U.ancestors.has(G))Un();let re=Reflect.ownKeys(G);if(U.keys+=re.length,U.keys>Lo.maxKeys)Un();let oe=re.flatMap((de)=>{let Se=Object.getOwnPropertyDescriptor(G,de);if(!Se||Se.get||Se.set)Un();return typeof de==="string"&&Se.enumerable?[[de,Se.value]]:[]});return U.ancestors.add(G),{object:G,array:K,entries:oe}}function Eu(G){if(Vh.isProxy(G))Un();let U=Array.isArray(G),j=Object.getPrototypeOf(G);if(U&&j!==Array.prototype||!U&&j!==Object.prototype&&j!==null)Un();return U}function Un(){throw new f}function ry(G){let U=[],j=G.split(/\r?\n/),K=!1,re=!1,oe=null,de=null,Se=()=>{re=!1,oe=null,de=null};for(let we=0;we<j.length;we++){let We=j[we]??"";if(We==="*** Begin Patch"){K=!0,Se();continue}if(We==="*** End Patch"){K=!1,Se();continue}if(We.startsWith("@@")){let mt=oy(We);if(re=!0,oe=mt?.oldLines??null,de=mt?.newLines??null,oe===0&&de===0)Se();continue}if(re&&oe!==null&&de!==null){let mt=We.startsWith(" ")||We.startsWith("-")?1:0,gt=We.startsWith(" ")||We.startsWith("+")?1:0;if(oe=Math.max(0,oe-mt),de=Math.max(0,de-gt),oe===0&&de===0)Se();continue}if(We.startsWith("*** ")){Se(),U.push(...ba(We));continue}if(re)continue;if(We.startsWith("diff --git ")){U.push(...ba(We));continue}if(We.startsWith("--- ")){let mt=j[we+1]??"";if(!mt.startsWith("+++ "))continue;U.push(...Sa(Ti(We.slice(4),!0),Ti(mt.slice(4),!0))),we++;continue}if(!K)U.push(...ba(We))}return U}function oy(G){let U=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(G);if(!U)return null;return{oldLines:Number(U[1]??1),newLines:Number(U[2]??1)}}function ba(G){let U=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(G);if(U?.[1])return pu(U[1]);let j=/^\*\*\* Move to: (.+)$/.exec(G);if(j?.[1])return pu(j[1]);if(G.startsWith("diff --git "))return iy(G.slice(11));let K=/^--- (.+)$/.exec(G);if(K?.[1])return fu(K[1]);let re=/^\+\+\+ (.+)$/.exec(G);if(re?.[1])return fu(re[1]);let oe=/^(?:rename|copy) (?:from|to) (.+)$/.exec(G);if(oe?.[1])return my(oe[1]);return[]}function iy(G){let U=sy(G);if(U.length===2&&U[0]&&U[1])return Sa(U[0],U[1]);let j=ay(G);return j?Sa(G.slice(j.oldStart,j.oldEnd),G.slice(j.newStart,j.newEnd)):[]}function sy(G){let U=[],j=0;while(j<G.length&&U.length<2){while(Er(G[j]))j++;if(j>=G.length)break;let K=G[j]==='"'||G[j]==="'"?G[j]:void 0;if(!K){let oe=j;while(j<G.length&&!Er(G[j]))j++;U.push(G.slice(oe,j));continue}let re=Ru(G,j,K);if(!re)return[];U.push(re.value),j=re.end}while(Er(G[j]))j++;return j===G.length?U:[]}function ay(G){let U=0;while(U<G.length&&Er(G[U]))U++;let j=G.length;while(j>U&&Er(G[j-1]))j--;let K=0,re=U;while(re<j){if(!Er(G[re])){re++;continue}let oe=re;while(re<j&&Er(G[re]))re++;if(oe===U||re===j)continue;if(K++,K>ty)Un();if(ly(G,U,oe,re,j))return{oldStart:U,oldEnd:oe,newStart:re,newEnd:j}}return null}function ly(G,U,j,K,re){if(Ca(G,U,j,K,re))return!0;let oe=du(G,"/",U,j),de=du(G,"/",K,re);if(oe<=U||de<=K)return!1;if(Ca(G,U,oe,K,de))return!1;return Ca(G,oe+1,j,de+1,re)}function Ca(G,U,j,K,re){if(j-U!==re-K)return!1;for(let oe=0;oe<j-U;oe++)if(G[U+oe]!==G[K+oe])return!1;return!0}function du(G,U,j,K){for(let re=j;re<K;re++)if(G[re]===U)return re;return-1}function Er(G){return G!==void 0&&ey.test(G)}function Ru(G,U,j){let K=[],re=U+1;while(re<G.length){let oe=String.fromCodePoint(G.codePointAt(re)??0);if(oe===j)return{value:Qh.decode(Uint8Array.from(K)),end:re+1};if(oe!=="\\"||j==="'"){K.push(...uu.encode(oe)),re+=oe.length;continue}let de=G.slice(re+1),Se=/^[0-7]{1,3}/.exec(de)?.[0];if(Se){K.push(Number.parseInt(Se,8)),re+=Se.length+1;continue}K.push(...uu.encode(cy(de[0]??""))),re+=2}return null}function cy(G){return{a:"\x07",b:"\b",f:"\f",n:`
5
+ `,r:"\r",t:"\t",v:"\v"}[G]??G}function uy(G){return Wo(fy(G))}function Sa(G,U){if(G==="/dev/null")return mu(U);if(U==="/dev/null")return mu(G);if(G.startsWith("a/")&&U.startsWith("b/"))return[G.slice(2),U.slice(2)].flatMap(Wo);let j=dy(G,U)??(G===U?xu(G):null);return[G,U,...j?[j]:[]].flatMap(Wo)}function mu(G){let U=xu(G);return[G,...U?[U]:[]].flatMap(Wo)}function xu(G){let U=G.indexOf("/");return U>0&&U<G.length-1?G.slice(U+1):null}function dy(G,U){let j=G.indexOf("/"),K=U.indexOf("/");if(j<1||K<1)return null;if(G.slice(0,j)===U.slice(0,K))return null;let re=G.slice(j+1);return re===U.slice(K+1)?re:null}function fu(G){return uy(Ti(G,!0))}function my(G){return Wo(Ti(G,!1))}function Ti(G,U){let j=G.trim(),K=j[0]==='"'||j[0]==="'"?j[0]:void 0;if(K){let re=Ru(j,0,K);if(re&&(U||j.slice(re.end).trim()===""))return re.value}return U?j.split("\t",1)[0]?.trim()??"":j}function fy(G){return G.startsWith("a/")||G.startsWith("b/")?G.slice(2):G}function Wo(G){return G===""||G==="/dev/null"?[]:[G]}function pu(G){let U=G.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return U===""||U==="/dev/null"?[]:[U]}function fe(G){try{if(!gy(G).isDirectory())return!1;return py(G,_u.R_OK|_u.X_OK),!0}catch{return!1}}function it(G,U,j){if(sr(G))return;let K=U.flatMap((oe)=>va(oe,j));if(!K[0])return;let re=va(wu(G)?G:yy(K[0],G),j)[0];if(!re)return;return K.some((oe)=>Cy(re,oe))?re:void 0}function Ve(G,U){return G.flatMap((j)=>va(j,U))[0]}function va(G,U){let j=U.realpath(G);if(j===null)return[];return U.isDirectory(j)?[j]:[]}function Cy(G,U){let j=hy(U,G);return j===""||j!==".."&&!j.startsWith(`..${by}`)&&!wu(j)}var Sy=8388608;async function Ke(G){let U=[],j=0;for await(let K of G){let re=typeof K==="string"?Buffer.from(K,"utf-8"):Buffer.from(K.buffer,K.byteOffset,K.byteLength);if(j+=re.byteLength,j>Sy)throw vy(G),Error("hook input byte limit exceeded");U.push(re)}return Buffer.concat(U,j).toString("utf-8")}function vy(G){let U=G.destroy??G.cancel;if(!U)return;try{Promise.resolve(U.call(G)).catch(()=>{})}catch{}}function u(G,U,j,K,re){if(j.kind!=="command")return{toolName:G,input:U,route:j,context:K};return{toolName:G,input:U,route:j,context:K,command:re}}var Zr=["fail_closed","paranoid_rm","paranoid_interpreters"],ki={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"}},Oi=["standard","strict","paranoid"];function Pu(G,U){if(!U)return G;return Oi.indexOf(U)>Oi.indexOf(G)?U:G}function Au(G){let U=pe(n.level,G);return Oi.find((j)=>j===U)}function Tu(G,U){return Pu(G,Au(U))}function Ey(G){let U=pe(n.level,G);if(!U)return;let j=Au(G);if(j)return j;console.error(`CC Safety Net: ignored invalid ${n.level.name}=${JSON.stringify(U.slice(0,40))}. Use ${Oi.join(", ")}.`);return}function qe(G){if(G===void 0||G==="all")return"all";if(G==="blocked")return"blocked";return"invalid"}function Ee(G){return qe(pe(n.auditScope,G))==="all"}function Ea(G){if(G.failClosed&&G.paranoidRm&&G.paranoidInterpreters)return"paranoid";if(G.failClosed&&!G.paranoidRm&&!G.paranoidInterpreters)return"strict";if(!G.failClosed&&!G.paranoidRm&&!G.paranoidInterpreters)return"standard";return"custom"}function T(G={},U){let j=G.safety?.level??"standard",K=Ey(U),re=Pu(j,K),oe=ki[re],de={failClosed:oe.fail_closed,paranoidRm:oe.paranoid_rm,paranoidInterpreters:oe.paranoid_interpreters},Se={failClosed:re===j?"preset":"environment",paranoidRm:re===j?"preset":"environment",paranoidInterpreters:re===j?"preset":"environment"},we={failClosed:[`policy safety.level=${j}`],paranoidRm:[`policy safety.level=${j}`],paranoidInterpreters:[`policy safety.level=${j}`]};if(re!==j)we.failClosed.push(`env ${n.level.name}=${K}`),we.paranoidRm.push(`env ${n.level.name}=${K}`),we.paranoidInterpreters.push(`env ${n.level.name}=${K}`);if(G.safety?.overrides?.failClosed!==void 0)de.failClosed=G.safety.overrides.failClosed,Se.failClosed="capability_override",we.failClosed.push("policy safety.overrides.fail_closed");if(G.safety?.overrides?.paranoidRm!==void 0)de.paranoidRm=G.safety.overrides.paranoidRm,Se.paranoidRm="capability_override",we.paranoidRm.push("policy safety.overrides.paranoid_rm");if(G.safety?.overrides?.paranoidInterpreters!==void 0)de.paranoidInterpreters=G.safety.overrides.paranoidInterpreters,Se.paranoidInterpreters="capability_override",we.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(v(n.strict,U))de.failClosed=!0,Se.failClosed="environment",we.failClosed.push(`env ${n.strict.name}`);if(v(n.paranoid,U))de.paranoidRm=!0,de.paranoidInterpreters=!0,Se.paranoidRm="environment",Se.paranoidInterpreters="environment",we.paranoidRm.push(`env ${n.paranoid.name}`),we.paranoidInterpreters.push(`env ${n.paranoid.name}`);if(v(n.paranoidRm,U))de.paranoidRm=!0,Se.paranoidRm="environment",we.paranoidRm.push(`env ${n.paranoidRm.name}`);if(v(n.paranoidInterpreters,U))de.paranoidInterpreters=!0,Se.paranoidInterpreters="environment",we.paranoidInterpreters.push(`env ${n.paranoidInterpreters.name}`);let We=!!G.worktreeMode||v(n.worktree,U);return{strict:de.failClosed,paranoidRm:de.paranoidRm,paranoidInterpreters:de.paranoidInterpreters,worktreeMode:We,effectiveLevel:Ea(de),capabilities:{fail_closed:{enabled:de.failClosed,source:Se.failClosed,sources:we.failClosed},paranoid_rm:{enabled:de.paranoidRm,source:Se.paranoidRm,sources:we.paranoidRm},paranoid_interpreters:{enabled:de.paranoidInterpreters,source:Se.paranoidInterpreters,sources:we.paranoidInterpreters}}}}function v(G,U){let j=typeof G==="string"?Fo(G,U):pe(G,U);return j==="1"||j?.toLowerCase()==="true"}function Fo(G,U){return U.get(G)}function pe(G,U){let j=Fo(G.name,U);if(j!==void 0)return j;if(G.legacyName)return Fo(G.legacyName,U);return}function ot(G,U){return Fo(G.name,U)!==void 0||!!G.legacyName&&Fo(G.legacyName,U)!==void 0}import{dirname as wr}from"node:path";import{closeSync as Ry,constants as Go,fstatSync as Ra,fsyncSync as xy,lstatSync as An,mkdirSync as Iu,openSync as ku,readdirSync as _a,readFileSync as _y,realpathSync as Xr,renameSync as wy,rmdirSync as Ou,statSync as xa,unlinkSync as wa,writeFileSync as Py}from"node:fs";import{isAbsolute as Mu,join as Rr,normalize as Ay,parse as Mi,relative as Pa,resolve as Aa,sep as Di}from"node:path";function Ie(){let G=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${G()}${G()}`}var Ty=Symbol("PolicyFilesystemScope"),Iy=Symbol("PolicyFilesystemTarget"),Du=Go.O_NOFOLLOW??0;class o extends Error{name="PolicyFilesystemError";constructor(G){super(`Unable to access ${G} filesystem safely.`)}}function S(G,U){return{[Ty]:!0,root:Aa(G),label:U}}function zo(G,U){let j=Ay(U);if(U===""||Mu(U)||j===".."||j.startsWith(`..${Di}`))throw new o(G.label);return{[Iy]:!0,scope:G,relativePath:j,path:Rr(G.root,j)}}function i(G,U){return zo(G,Pa(G.root,Aa(U)))}function se(G,U="rules policy"){let j=Aa(G),K=Mi(j).dir;return zo(S(K,U),Pa(K,j))}function r(G){return Zn(G.scope.label,()=>{if(!en(G))return null;let U=ku(G.path,Go.O_RDONLY|Du);return Lu(U,()=>{let j=Ra(U);if(!j.isFile())throw new o(G.scope.label);let K=_y(U,"utf-8"),re=An(G.path);if(!re.isFile()||re.isSymbolicLink()||j.dev!==re.dev||j.ino!==re.ino)throw new o(G.scope.label);return en(G),K})})}function g(G,U,j=384,K){let re=`${G.path}.${Ie()}.tmp`;Zn(G.scope.label,()=>{Oy(G),en(G);let oe=ku(re,Go.O_CREAT|Go.O_EXCL|Go.O_WRONLY|Du,j),de=Lu(oe,()=>{let Se=Ra(oe);if(!Se.isFile())throw new o(G.scope.label);Py(oe,U,"utf-8"),xy(oe);let we=Ra(oe);if(!we.isFile()||we.dev!==Se.dev||we.ino!==Se.ino)throw new o(G.scope.label);return we});en(G),Dy(G,re,de.dev,de.ino),wy(re,G.path),K?.(G.path),en(G)},()=>Ny(re))}function Nu(G,U){if(G.path===U.path)return!0;return Zn(G.scope.label,()=>{if(!en(G)||!en(U))return!1;let j=(K)=>Rr(Xr(Mi(K).dir),Mi(K).base);return j(G.path)===j(U.path)})}function me(G){let U=Zn(G.scope.label,()=>{if(!en(G,"directory"))return null;let j=_a(G.path);return en(G,"directory"),j});if(!U)return null;return Zn(G.scope.label,()=>{let j=U.map((K)=>{let re=zo(G.scope,Rr(G.relativePath,K)),oe=An(re.path);if(oe.isSymbolicLink()||!oe.isFile()&&!oe.isDirectory())throw new o(G.scope.label);return Ni(Ta(G.scope),Xr(re.path),G.scope.label),{name:K,kind:oe.isDirectory()?"directory":"file"}});return en(G,"directory"),j})}function H(G){Zn(G.scope.label,()=>{if(!en(G))return;wa(G.path),en(G)})}function st(G){Zn(G.scope.label,()=>{if(!ky(G))return;Fu(G),en(G,"directory")})}function at(G){Zn(G.scope.label,()=>{if(!en(G,"directory"))return;Ou(G.path),en(G,"directory")})}function ky(G){return Zn(G.scope.label,()=>{if(!en(G,"directory"))return!1;return Wu(G),!0})}function Zn(G,U,j){try{return U()}catch(K){if(j?.(),K instanceof o)throw K;throw new o(G)}}function Lu(G,U){try{return U()}finally{Ry(G)}}function en(G,U="file"){let j=Gu(G.scope);if(!j)return!1;let K=G.relativePath.split(Di);for(let re of K.keys()){let oe=Rr(G.scope.root,...K.slice(0,re+1)),de=An(oe,{throwIfNoEntry:!1});if(!de)return!1;if(de.isSymbolicLink())throw new o(G.scope.label);if(re<K.length-1&&!de.isDirectory())throw new o(G.scope.label);if(re===K.length-1&&(U==="file"?!de.isFile():!de.isDirectory()))throw new o(G.scope.label);Ni(j,Xr(oe),G.scope.label)}return!0}function Wu(G){for(let U of _a(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=An(j.path);if(K.isSymbolicLink()||!K.isDirectory()&&!K.isFile())throw new o(G.scope.label);if(K.isDirectory())Wu(j)}en(G,"directory")}function Fu(G){for(let U of _a(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=An(j.path);if(K.isSymbolicLink())throw new o(G.scope.label);if(K.isDirectory()){Fu(j);continue}if(!K.isFile())throw new o(G.scope.label);wa(j.path)}Ou(G.path)}function Oy(G){My(G.scope);let U=Ta(G.scope),j=G.relativePath.split(Di).slice(0,-1);for(let K of j.keys()){let re=Rr(G.scope.root,...j.slice(0,K+1));if(!An(re,{throwIfNoEntry:!1}))Iu(re,{mode:448});let oe=An(re);if(!oe.isDirectory()||oe.isSymbolicLink())throw new o(G.scope.label);Ni(U,Xr(re),G.scope.label)}}function My(G){if(An(G.root,{throwIfNoEntry:!1})){if(!xa(G.root).isDirectory())throw new o(G.label);return}let U=[],j=G.root;while(!An(j,{throwIfNoEntry:!1})){U.unshift(j);let K=Mi(j).dir;if(K===j)throw new o(G.label);j=K}if(!xa(j).isDirectory())throw new o(G.label);for(let K of U){Iu(K,{mode:448});let re=An(K);if(!re.isDirectory()||re.isSymbolicLink())throw new o(G.label)}}function Gu(G){if(!An(G.root,{throwIfNoEntry:!1}))return null;if(!xa(G.root).isDirectory())throw new o(G.label);return Xr(G.root)}function Ta(G){let U=Gu(G);if(!U)throw new o(G.label);return U}function Dy(G,U,j,K){let re=An(U);if(!re.isFile()||re.isSymbolicLink()||re.dev!==j||re.ino!==K)throw new o(G.scope.label);Ni(Ta(G.scope),Xr(U),G.scope.label)}function Ni(G,U,j){let K=Pa(G,U);if(K===".."||K.startsWith(`..${Di}`)||Mu(K))throw new o(j)}function Ny(G){try{wa(G)}catch{}}import{dirname as xr,isAbsolute as zy,join as _r,relative as $y,resolve as ar,sep as By}from"node:path";var d=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ge="rulebook.json",he=".cc-safety-net/rules";var zu=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,Ly=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,$u=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,Wy=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Fy="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ct=new RegExp(`^${Wy}/(${d.source.slice(1,-1)})/${Fy}$`);function Gy(G){return`.cc-safety-net/rules/${G}/rulebook.json`}function Bu(G){if(w(G))try{return N(G),null}catch(U){return U instanceof Error?U.message:String(U)}return d.test(G)?null:`Local rulebook sources must be bare names matching ${d}: ${G}`}function N(G){if(G.startsWith("github:"))throw Error(`Invalid rulebook source: ${G}`);let U=G.match(zu);if(!U?.[1]||!U[2]||!U[3])throw Error(`Invalid GitHub rulebook source: ${G}`);let j=U[3].lastIndexOf("/");if(j<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${G}`);let K=U[3].slice(0,j),re=U[3].slice(j+1);if(!K||!$u.test(K))throw Error(`GitHub rulebook refs must use valid path segments: ${G}`);if(!re||!d.test(re))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${G}`);return{owner:U[1],repo:U[2],ref:K,path:Gy(re),name:re}}function Z(G){return Ly.test(G)}function ae(G){return $u.test(G)}function w(G){return zu.test(G)}function lt(G){if(!d.test(G))throw Error(`Local rulebook sources must be bare names matching ${d}: ${G}`)}var Uu="rule.json",Li="policy.json",Hu=".cc-safety-net",Uy="rules",Hy="CC_SAFETY_NET_HOME",ju="`cc-safety-net rule update`";function jy(G){return ar(G,he)}function _(G){return _r(jy(G),Uu)}function h(G){return _r(ar(G),Hu,Li)}function ke(G,U={}){return U.userConfigDir??(U.userConfigPath?xr(U.userConfigPath):_r(Vy(G),Uy))}function Vy(G){let U=G.env.get(Hy);return U?ar(an(U)):_r(G.home,Hu)}function W(G,U={}){return _r(ke(G,U),Uu)}function l(G,U={}){return _r(xr(ke(G,U)),Li)}function L(G,U){let j=Pn();return Nt(h(U.cwd),G.paths,j)===Nt(ar(l(G,U)),G.paths,j)}function X(G,U){let j=U.userConfigPath??W(G,U),K=U.projectConfigPath??_(U.cwd),re=Je(G,U),oe=Ye(K,U.cwd);return{userConfigPath:j,projectConfigPath:K,userScope:re,projectScope:oe,userConfigTarget:i(re,j),projectConfigTarget:i(oe,K)}}function Je(G,U){let j=U.userConfigPath?xr(xr(ar(U.userConfigPath))):xr(ar(U.userConfigDir??ke(G,U)));return S(j,"user policy")}function Ye(G,U){let j=ar(U),K=ar(G),re=$y(j,K);if(re!==".."&&!re.startsWith(`..${By}`)&&!zy(re))return S(j,"project policy");return S(xr(xr(K)),"project policy")}function M(G,U){return _r(G,U,ge)}var Sn=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),C=/^[a-zA-Z][a-zA-Z0-9_-]*$/,I=256,Vt=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Vu=new Set(["python","python3","python2","node","ruby","perl"]),Wi=/^python(?:[23](?:\.\d+)*)?$/,Tn=new Set(["awk","gawk","nawk","mawk"]),Fi=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 qu="Rulebook exceeds CC Safety Net's safe validation limits.",Ku="Additional rulebook validation errors were omitted.",Dn=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Yu(G){if(Ia(G.allowed_commands,Dn.maxAllowedCommands)||Ia(G.rules,Dn.maxRules)||Ia(G.tests,Dn.maxTests))return!1;let{maxAggregateStringCodeUnits:U,maxTotalBlockArgs:j}=Dn,K=(re,oe=!1)=>{if(typeof re!=="string")return!0;if(re.length>Dn.maxStringCodeUnits||oe&&re.length>Dn.maxFixtureCommandCodeUnits||re.length>U)return!1;return U-=re.length,!0};if(!K(G.name)||!K(G.version)||!K(G.description)||!K(G.author)||!K(G.migrated_from))return!1;if(Array.isArray(G.allowed_commands)){for(let re of G.allowed_commands)if(!K(re))return!1}if(Array.isArray(G.rules))for(let re of G.rules){if(!re||typeof re!=="object")continue;let oe=re;if(!K(oe.name)||!K(oe.command)||!K(oe.subcommand)||!K(oe.reason)||!K(oe.intent))return!1;let de=oe.match&&typeof oe.match==="object"?oe.match:{};for(let Se of[oe.block_args,de.command_path,de.any_args,de.exclude_args]){if(!Array.isArray(Se))continue;if(Se.length>Dn.maxBlockArgsPerRule||Se.length>j)return!1;j-=Se.length;for(let we of Se)if(!K(we))return!1}}if(Array.isArray(G.tests))for(let re of G.tests){if(!re||typeof re!=="object")continue;let oe=re;if(!K(oe.command,!0)||!K(oe.expect)||!K(oe.rule))return!1}return!0}function Ia(G,U){return Array.isArray(G)&&G.length>U}var ka=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var ye=64,be="Rule config exceeds CC Safety Net's safe source limit.";function Mt(G){return kt(G).toLowerCase()}function kt(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}function dn(G,U){let j=new Set,K=!1;for(let re of G){if(re==="--"){K=!0;continue}if(K)continue;if(re.startsWith("-")&&!re.startsWith("--")&&re.length>1)for(let oe=1;oe<re.length;oe++){let de=re[oe];if(!de||!/[a-zA-Z]/.test(de))break;let Se=`-${de}`;if(j.add(Se),U?.shortOptsWithValue?.has(Se))break}}return j}var qy={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Oa=new Set(["--init-file","--rcfile"]);function Ma(G,U,j,K){let re=!1,oe=0,de=!1,Se=!1,we=!1;for(let We=1;We<U.length;We++){let mt=U[We];if(mt===void 0)break;if(G==="ksh"&&mt==="o"&&We+1<U.length){if(K==="argv"){let gt=U.slice(We+1);if(U[0]==="-"&&(gt==="c"||gt[0]==="-"&&gt.endsWith("c")))de=!0}break}if(G==="ksh"&&mt==="o"&&We+1===U.length&&(j?.startsWith("-")||j?.startsWith("+")))break;if(G==="zsh"&&mt==="o"&&We+1<U.length)break;if(K==="startup"&&mt==="i")re=U[0]==="-";if(K==="argv"&&U[0]==="-"&&mt==="c")de=!0;if(K==="argv"&&mt==="n")we=U[0]==="-";if(K==="argv"&&mt==="s")Se=U[0]==="-";if(!qy[G]?.includes(mt))continue;if(We+1===U.length)oe++;break}return{interactive:re,followingValues:oe,commandSelected:de,stdinMode:Se,syntaxCheck:we}}function vn(G){let U=kt(G[0]??"").toLowerCase(),j=!1,K=!1,re=!1;for(let oe=1;oe<G.length;oe++){let de=G[oe];if(de===void 0)break;if(de==="--"){let we=j&&G[oe+1]!==void 0?oe+1:null;return{command:we===null?null:G[we]??null,commandIndex:we,scriptIndex:!j&&!K&&G[oe+1]!==void 0?oe+1:null,readsStdinAsCommands:!j&&(K||G[oe+1]===void 0),syntaxCheck:re}}if(de==="-"||de[0]!=="-"&&de[0]!=="+")return{command:j?de:null,commandIndex:j?oe:null,scriptIndex:!j&&!K&&de!=="-"?oe:null,readsStdinAsCommands:!j&&(K||de==="-"),syntaxCheck:re};if(de.startsWith("--")){let we=de.split("=",1)[0]??de;if(U==="bash"&&Oa.has(we)&&!de.includes("="))oe++;continue}let Se=Ma(U,de,G[oe+1],"argv");if(Se.commandSelected)j=!0;if(Se.syntaxCheck)re=!0;if(Se.stdinMode)K=!0;oe+=Se.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!j,syntaxCheck:re}}function $o(G,U){if(U.escaped)return U.escaped=!1,!0;if(G==="\\"&&!U.inSingle)return U.escaped=!0,!0;if(G==="'"&&!U.inDouble)return U.inSingle=!U.inSingle,!0;if(G==='"'&&!U.inSingle)return U.inDouble=!U.inDouble,!0;return!1}function Gi(G){let U={inSingle:!1,inDouble:!1,escaped:!1};for(let j of Ky(G))$o(j,U);return U.inSingle||U.inDouble}function Ky(G){let U="",j={inSingle:!1,inDouble:!1,escaped:!1},K=!1,re=!0;for(let oe=0;oe<G.length;oe++){let de=G[oe];if(!de)break;if(K){if(de===`
6
+ `||de==="\r")U+=de,K=!1,j.escaped=!1;continue}if(de==="#"&&!j.inSingle&&!j.inDouble&&re){K=!0;continue}if(U+=de,!j.inSingle&&!j.inDouble&&!j.escaped)re=/[\s;&|()<>]/.test(de);$o(de,j)}return U}var Da=new Set(["rm","find","xargs","parallel"]),Yy=new Set(["git","busybox",...Da,...Vt,...Vu,...Tn]),Zy=new Set(["python","node","ruby","perl"]);function Ae(G){let U=Mt(G);return Yy.has(U)||Nn(U)}function Nn(G){return Zy.has(Xy(G))}function Xy(G){let U=kt(G).toLowerCase();return Wi.test(U)?"python":U}var ut={version:1,rules:[],overrides:{},transparent_wrappers:[]};function m(G){try{let U=r(Jy(G));if(U===null)return{config:null,errors:[]};if(!U.trim())return{config:null,errors:["Config file is empty"]};let j=JSON.parse(U),K=Ze(j);if(K.errors.length>0)return{config:null,errors:K.errors};return{config:{version:1,rules:j.rules??[],overrides:j.overrides??{},transparent_wrappers:j.transparent_wrappers??[]},errors:[]}}catch(U){if(U instanceof o)return{config:null,errors:[U.message]};let j=U instanceof Error?U.message:String(U);return{config:null,errors:[U instanceof SyntaxError?"Invalid JSON":j]}}}function Jy(G){return typeof G==="string"?se(G):G}var e=(G,U)=>({path:G,message:U,kind:"typed"}),tn=(G,U)=>({path:G,message:U,kind:"custom"});function Oe(G){let U=new Set;return G.flatMap((j,K)=>{let re=Jr(j)?j.name:void 0;if(typeof re!=="string")return[];if(U.has(re.toLowerCase()))return[tn(["rules",K,"name"],`duplicate rule name "${re}"`)];return U.add(re.toLowerCase()),[]})}var Re=`must be one of ${ka.join(", ")}`,Qy=/^[^/]+\/[^/]+$/,eb=["version","rules","overrides","transparent_wrappers"];function Ze(G){let U=tb(G);return{errors:ce(Xe(U,eb,(j)=>j.kind==="custom"),": "," "),sources:cb(G,U)}}function tb(G){if(!Jr(G))return[e([],"Config must be an object")];let U=Array.isArray(G.rules)&&G.rules.length>ye;return[...G.version===1?[]:[e(["version"],"must be 1")],...nb(G.rules,U),...ib(G.overrides),...ab(G.transparent_wrappers),...U?[]:ob(G.rules),...Jr(G.overrides)?Object.keys(G.overrides).filter((j)=>!Qy.test(j)).map((j)=>tn(["overrides",j],"must use <rulebook-name>/<rule-name>")):[],...lb(G.transparent_wrappers)]}function nb(G,U){if(G===void 0)return[];if(!Array.isArray(G))return[e(["rules"],"must be an array of rulebook source strings"),...Zu(G,ye)?[e(["rules"],be)]:[]];if(U)return[{path:["rules"],message:be,kind:"limit"}];return G.flatMap((j,K)=>{if(typeof j!=="string")return[e(["rules",K],"must be a rulebook source string"),...rb(j,1)?[e(["rules",K],"must be a non-empty rulebook source string")]:[]];return j===""?[e(["rules",K],"must be a non-empty rulebook source string")]:[]})}function Zu(G,U){let j=Xu(G);return j!==void 0&&!(j<=U)}function rb(G,U){let j=Xu(G);return j!==void 0&&!(j>=U)}function Xu(G){if(G===null||G===void 0)return;let U=G.length;return U===void 0?void 0:Number(U)}function ob(G){if(!Array.isArray(G))return[];let U=new Set;return G.flatMap((j,K)=>{if(typeof j!=="string"||j==="")return[];if(j.trim()==="")return[tn(["rules",K],"must be a non-empty rulebook source string")];let re=Bu(j);if(re)return[tn(["rules",K],re)];if(U.has(j))return[tn(["rules",K],`duplicate rulebook source "${j}"`)];return U.add(j),[]})}function ib(G){if(G===void 0)return[];if(!Jr(G))return[e(["overrides"],"must be an object if provided")];return Object.keys(G).flatMap((U)=>{let j=G[U];if(j==="off")return[];if(!Jr(j))return[e(["overrides",U],'must be "off" or an object')];return[...sb(j.reason,["overrides",U,"reason"]),...j.intent===void 0||Te(j.intent)?[]:[e(["overrides",U,"intent"],Re)]]})}function sb(G,U){if(typeof G!=="string")return[e(U,"required non-empty string"),...Zu(G,I)?[e(U,`must be at most ${I} characters`)]:[]];if(G==="")return[e(U,"required non-empty string")];return G.length>I?[e(U,`must be at most ${I} characters`)]:[]}function ab(G){if(G===void 0)return[];if(!Array.isArray(G))return[e(["transparent_wrappers"],"must be an array of command strings")];return G.flatMap((U,j)=>{if(typeof U!=="string")return[e(["transparent_wrappers",j],"must be a command string")];return C.test(U)?[]:[e(["transparent_wrappers",j],"must match command pattern")]})}function lb(G){if(!Array.isArray(G))return[];let U=new Set;return G.flatMap((j,K)=>{if(typeof j!=="string"||!C.test(j))return[];if(U.has(j))return[tn(["transparent_wrappers",K],`duplicate command "${j}"`)];if(Ae(j))return[tn(["transparent_wrappers",K],`reserved command "${j}" cannot be a wrapper`)];return U.add(j),[]})}function cb(G,U){let j=Jr(G)?G.rules:void 0;if(!Array.isArray(j))return new Set;if(U.some((re)=>re.path.length===1&&re.path[0]==="rules"))return new Set;let K=new Set(U.filter((re)=>re.path[0]==="rules"&&typeof re.path[1]==="number").map((re)=>re.path[1]));return new Set(j.filter((re,oe)=>typeof re==="string"&&!K.has(oe)))}function Xe(G,U,j){let K=G.map((de)=>de.path[1]),re=[...new Set(K.filter((de)=>typeof de==="string"))],oe=(de,Se)=>[de.path.length===0?-1:U.indexOf(String(de.path[0])),typeof Se==="number"?Se:re.indexOf(String(Se)),j(de)?0:1];return G.map((de,Se)=>({issue:de,rank:oe(de,K[Se])})).sort((de,Se)=>de.rank[0]-Se.rank[0]||de.rank[1]-Se.rank[1]||de.rank[2]-Se.rank[2]).map((de)=>de.issue)}function ce(G,U,j){return[...new Set(G.map((K)=>{let re=Na(K.path);if(K.kind==="unknownKeys")return`${re?`${re}.`:""}unknown field "${K.message}"`;if(K.kind==="key"||K.kind==="limit"||K.path.length===0)return K.message;return`${re}${K.path.length===1?j:U}${K.message}`}))]}function Na(G){return G.map((U,j)=>{if(typeof U==="number")return`[${U}]`;return j===0?String(U):`.${String(U)}`}).join("")}function Te(G){return ka.includes(G)}function Jr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function le(G){let U=mb(G);if(U.errors.length>0)throw Error(U.errors.join("; "));return G}var ub=`required non-empty string up to ${I} characters`,Ju="must be a non-empty array of unique non-empty strings",db="required non-empty array of non-empty strings";function mb(G){if(!lr(G))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Yu(G))return{errors:[qu],ruleNames:new Set};let U=[...G.rulebook_version===1||G.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ce(fb(G,G.rulebook_version===2),": ",": ")];return{errors:U.length>Dn.maxValidationErrors?[...U.slice(0,Dn.maxValidationErrors),Ku]:U,ruleNames:new Set(De(G).map((j)=>j.toLowerCase()))}}function De(G){let U=lr(G)?G.rules:void 0;return(Array.isArray(U)?U:[]).flatMap((j)=>{let K=lr(j)?j.name:void 0;return typeof K==="string"?[K]:[]})}function fb(G,U){return[...typeof G.name==="string"&&d.test(G.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof G.version==="string"&&G.version!==""?[]:[e(["version"],"required non-empty string")],...pb(G.allowed_commands),...gb(G.rules,U),...Cb(G.tests),...Sb(G),...vb(G)]}function pb(G){if(!Array.isArray(G))return[e(["allowed_commands"],"required array")];let U=new Set;return[...G.flatMap((j,K)=>typeof j==="string"&&C.test(j)?[]:[e(["allowed_commands",K],"must match command pattern")]),...G.flatMap((j,K)=>{if(typeof j!=="string"||!C.test(j))return[];if(U.has(j))return[tn(["allowed_commands",K],`duplicate command "${j}"`)];return U.add(j),[]})]}function gb(G,U){if(!Array.isArray(G))return[e(["rules"],"required array")];return[...G.flatMap((j,K)=>{if(!lr(j))return[e(["rules",K],"must be an object")];return U?yb(j,["rules",K]):hb(j,["rules",K])}),...Oe(G)]}function hb(G,U){return[...Qu(G.name,U),...ed(G.command,U),...G.subcommand===void 0||typeof G.subcommand==="string"&&C.test(G.subcommand)?[]:[e([...U,"subcommand"],"must match command pattern")],...zi(G.block_args,[...U,"block_args"],"required non-empty array",!1),...td(G.reason,U),...nd(G.intent,U)]}function yb(G,U){return[...Qu(G.name,U),...ed(G.command,U),...td(G.reason,U),...nd(G.intent,U),...bb(G.match,[...U,"match"]),...G.subcommand===void 0?[]:[e([...U,"subcommand"],"not supported in rulebook_version 2")],...G.block_args===void 0?[]:[e([...U,"block_args"],"not supported in rulebook_version 2")]]}function Qu(G,U){if(typeof G!=="string")return[e([...U,"name"],"required string")];return d.test(G)?[]:[e([...U,"name"],"must match rule name pattern")]}function ed(G,U){return typeof G==="string"&&C.test(G)?[]:[e([...U,"command"],"required string matching command pattern")]}function td(G,U){return typeof G==="string"&&G!==""&&G.length<=I?[]:[e([...U,"reason"],ub)]}function nd(G,U){return G===void 0||Te(G)?[]:[e([...U,"intent"],Re)]}function bb(G,U){if(!lr(G))return[e(U,"required object")];return[...zi(G.command_path,[...U,"command_path"],db,!1),...G.any_args===void 0?[]:zi(G.any_args,[...U,"any_args"],Ju,!0),...G.exclude_args===void 0?[]:zi(G.exclude_args,[...U,"exclude_args"],Ju,!0)]}function zi(G,U,j,K){if(!Array.isArray(G))return[e(U,j)];let re=G.flatMap((oe,de)=>{if(typeof oe!=="string")return[e([...U,de],"must be a non-empty string")];return oe===""?[tn([...U,de],"must be a non-empty string")]:[]});if(G.some((oe)=>typeof oe!=="string"))return re;return[...re,...G.length===0?[tn(U,j)]:[],...K&&new Set(G).size!==G.length?[tn(U,"must not contain duplicate values")]:[]]}function Cb(G){if(G===void 0)return[];if(!Array.isArray(G))return[e(["tests"],"must be an array if provided")];return G.flatMap((U,j)=>{if(!lr(U))return[e(["tests",j],"must be an object")];return[...typeof U.command==="string"&&U.command.trim()!==""?[]:[e(["tests",j,"command"],"required non-empty string")],...U.expect==="blocked"||U.expect==="allowed"?[]:[e(["tests",j,"expect"],'must be "blocked" or "allowed"')],...U.rule===void 0||typeof U.rule==="string"?[]:[e(["tests",j,"rule"],"must be a string if provided")],...U.expect==="blocked"&&typeof U.rule!=="string"?[tn(["tests",j,"rule"],"required string for blocked fixtures")]:[]]})}function Sb(G){if(!Array.isArray(G.tests))return[];let U=new Set(De(G));return[...new Set(G.tests.flatMap((j)=>lr(j)&&j.expect==="blocked"&&typeof j.rule==="string"?[j.rule]:[]))].filter((j)=>!U.has(j)).map((j)=>tn(["tests"],`blocked fixture references unknown rule "${j}"`))}function vb(G){if(!Array.isArray(G.allowed_commands)||!Array.isArray(G.rules))return[];let U=new Set(G.allowed_commands.filter((j)=>typeof j==="string"));return G.rules.flatMap((j,K)=>{let re=lr(j)?j.command:void 0;if(typeof re!=="string"||U.has(re))return[];return[tn(["rules",K,"command"],`"${re}" must be listed in allowed_commands`)]})}function lr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function Q(G,U){let j=X(G,U),K;try{K=Nu(j.userConfigTarget,j.projectConfigTarget)}catch(pt){if(pt instanceof o)return Ib(j,pt.message);throw pt}let re=m(j.userConfigTarget),oe=K?{config:null,errors:[]}:m(j.projectConfigTarget),de=od(j.userConfigPath,re.errors),Se=od(j.projectConfigPath,oe.errors),we=new Set,We=re.config?La(re.config,wr(j.userConfigPath),"user",j.userScope,we):id(),mt=oe.config?La(oe.config,wr(j.projectConfigPath),"project",j.projectScope,we):id(),gt=re.config?.overrides??{},ft=oe.config?.overrides??{};return{rules:[...rd(We.rules,gt),...rd(mt.rules,ft)],transparent_wrappers:Ab(re.config,oe.config),rulebooks:[...We.rulebooks,...mt.rulebooks],errors:[...de,...Se,...We.errors,...mt.errors],warnings:[...We.warnings,...mt.warnings,...We.canValidateOverrides?Wa(gt,We.knownRuleIds,j.userConfigPath):[],...We.canValidateOverrides?Tb(ft,We.knownRuleIds,j.projectConfigPath):[],...mt.canValidateOverrides?Wa(ft,mt.knownRuleIds,j.projectConfigPath):[]],userConfig:re.config??void 0,projectConfig:oe.config??void 0,...j}}function B(G,U){let j=Eb(G,U);if(!j)return[];return[...j.scope.errors,...j.scope.warnings,...Rb(j.config,j.scope,G)]}function Eb(G,U){let j=U??S(wr(wr(G)),"rules policy"),K=m(i(j,G)).config;if(!K)return null;return{config:K,scope:La(K,wr(G),"project",j)}}function Rb(G,U,j){return U.canValidateOverrides?Wa(G.overrides??{},U.knownRuleIds,j):[]}function La(G,U,j,K=S(wr(wr(U)),j==="user"?"user policy":"project policy"),re=new Set){let oe=[],de=[],Se=G.rules.flatMap((We)=>{let mt=_b(We,U,K);if(mt.errors.length>0||!mt.rulebook)return oe.push(...mt.errors),[];let gt=mt.rulebook;if(re.has(gt.name))return de.push(`duplicate active rulebook name "${gt.name}" for ${We}; 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 re.add(gt.name),[{rules:xb(gt),rulebook:{source:j,spec:We,name:gt.name,version:gt.version,rules:gt.rules.map((ft)=>`${gt.name}/${ft.name}`)}}]}),we=Se.flatMap((We)=>We.rules);return{rules:we,rulebooks:Se.map((We)=>We.rulebook),knownRuleIds:new Set(we.map((We)=>We.name)),errors:oe,warnings:de,canValidateOverrides:oe.length===0}}function xb(G){if(G.rulebook_version===2)return G.rules.map((U)=>({name:`${G.name}/${U.name}`,command:U.command,block_args:[],match:U.match,reason:U.reason,intent:U.intent}));return G.rules.map((U)=>({...U,name:`${G.name}/${U.name}`,match:void 0}))}function _b(G,U,j){let K=Ne(G),re=M(U,K),oe=Pb(re,j);if("error"in oe)return{rulebook:null,errors:[oe.error]};if(oe.content===null)return{rulebook:null,errors:[`missing rulebook file ${re} for ${G}; ${wb(G)}`]};let de=xe(oe.content);if("problem"in de)return{rulebook:null,errors:[`invalid rulebook ${re}: ${de.problem}; fix that file`]};if(de.rulebook.name!==K)return{rulebook:null,errors:[`rulebook name "${de.rulebook.name}" in ${re} must match source "${G}"; fix that file`]};return{rulebook:de.rulebook,errors:[]}}function Ne(G){return w(G)?N(G).name:G}function wb(G){return w(G)?`run ${ju} to vendor ${G}`:"create that file or remove that source from the rules config"}function Pb(G,U){try{return{content:r(i(U,G))}}catch(j){if(j instanceof o)return{error:j.message};throw j}}function xe(G){let U;try{U=JSON.parse(G)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:le(U)}}catch(j){return{problem:j instanceof Error?j.message:"invalid rulebook"}}}function Ab(G,U){return[...new Set([...G?.transparent_wrappers??[],...U?.transparent_wrappers??[]])]}function rd(G,U){return G.flatMap((j)=>{let K=U[j.name];if(K==="off")return[];if(K&&typeof K==="object")return[{...j,intent:K.intent??j.intent,reason:K.reason}];return[j]})}function Wa(G,U,j){return Object.keys(G).filter((K)=>!U.has(K)).map((K)=>`unknown override key "${K}" in ${j}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function Tb(G,U,j){return Object.keys(G).filter((K)=>U.has(K)).map((K)=>`project override cannot target user-scoped rule "${K}" in ${j}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function od(G,U){return U.map((j)=>j.startsWith("Unable to access ")?j:`${G}: ${j}`)}function Ib(G,U){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[U],warnings:[],userConfigPath:G.userConfigPath,projectConfigPath:G.projectConfigPath}}function id(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as $b,readFileSync as Bb}from"node:fs";var sd=[{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.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"mkfs device format",description:"Blocks mkfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],Fa=new Set(sd.map((G)=>G.id)),z=sd,kb=new Map(z.map((G)=>[G.id,G.intent]));function _t(G,U){return{id:G,reason:U,intent:kb.get(G)??"manual_only"}}var Ga=[{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"}],$i={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Ob=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Mb=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],za=[{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"]},...Mb.flatMap((G)=>Ob.map((U)=>({id:["secret.home",G.idSlug,U.slice(1)].join("."),category:"Home path",label:[G.label,U].join(""),description:["Blocks home ",G.label,U," credential backup files."].join(""),suffixParts:[...G.directoryParts,[G.basename,U].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 Bi=[{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"]}],ad=[{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"}],Db=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],$a=ad.map((G)=>({id:`secret.variant.${G.slug}.separator`,category:"Variant",label:`${G.label}-* / ${G.label}_*`,description:`Blocks ${G.label} variants with dash or underscore suffixes.`,prefix:G.prefix})),Ba=ad.flatMap((G)=>Db.map((U)=>({id:`secret.variant.${G.slug}.${U.slice(1)}`,category:"Variant",label:`${G.label}${U}`,description:`Blocks ${G.label}${U} private credential variants.`,prefix:G.prefix,suffix:U}))),Bo={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)$/},Ua=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((G)=>({id:`secret.ext.${G}`,category:"Extension",label:`.${G}`,description:`Blocks files with the .${G} extension.`,extension:G})),Ha=[{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?$/}],Qe=[...Ga,$i,...za,...$a,...Ba,Bo,...Ua,...Ha,...Bi].map((G)=>({id:G.id,category:G.category,label:G.label,...G.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in G?{paths:G.paths}:{description:G.description}})),Ui=new Set(Bi.flatMap((G)=>G.category==="Coding CLI config"?[G.id]:[])),ja=new Set(Qe.map((G)=>G.id));import{isAbsolute as Va,join as Nb,normalize as Lb,sep as Hi}from"node:path";var ji=process.platform==="win32",ld=/[*?]/;function qa(G){let U=G.trim(),j=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(ji?U.replaceAll("\\","/"):U);if(!j)return null;let K=j[1]??"",re=j[2]??"";if(ld.test(K)||re==="."||re==="..")return null;return{root:K||"/",name:re}}function Uo(G,U){if(G==="~")return U;if(G.startsWith("~/"))return`${U}${G.slice(1)}`;return G}function Ka(G,U){if(typeof G!=="string"||G.trim()==="")return"must be a non-empty path string";let j=Uo(G.trim(),U);if(!Va(j))return"must be an absolute path or start with ~/";return Ho(j,U)}function Ya(G,U){let j=cd(G,U);if(j===null)return"must be a non-empty path string";if(!Va(j))return null;if(Ho(j,U)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var Wb="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Fb="cannot cover the guard's own configuration";function cd(G,U){if(typeof G!=="string"||G.trim()==="")return null;let j=G.trim(),K=ji?j.replaceAll("\\","/"):j;return Uo(K.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),U)}function Za(G,U){let j=cd(G,U);if(j===null)return"must be a non-empty path string";let K=qa(j)?.root??j;if(ld.test(K))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Va(K))return null;if(Ho(K,U)!==null)return Wb;return Gb(K,U)?Fb:null}function Gb(G,U){let j=Vi(G),K=Vi(Nb(U,".cc-safety-net"));return j===K||j.startsWith(`${K}${Hi}`)}function Ho(G,U){let j=Vi(G),K=Vi(U);if(j===K)return"cannot be the home directory";let re=j.endsWith(Hi)?j:`${j}${Hi}`;if(K.startsWith(re))return"cannot contain the home directory";return null}function Vi(G){let U=Lb(G);if(ji)U=U.replace(/\//g,"\\").toLowerCase();if(U.length>(ji?3:1)&&U.endsWith(Hi))U=U.slice(0,-1);return U}var ud=30,qi=1,Ki=365;function dd(G){if(typeof G!=="number"||!Number.isInteger(G))return 30;if(G<1)return 1;return G>365?365:G}var md=new Set(z.filter((G)=>G.catastrophic).map((G)=>G.id));function Tt(G,U){if(!G)return null;if(md.has(G.id))return G;if(U?.destructiveCommandProtectionEnabled===!1)return null;let j=U?.effectiveDestructiveCommandRules[G.id];return j&&!j.enabled?null:G}function Xt(G,U,j){if(md.has(U))return!0;if(G?.destructiveCommandProtectionEnabled===!1)return!1;return G?.effectiveDestructiveCommandRules[U]?.enabled??j}function q(G,U){return Object.freeze(Object.fromEntries(z.map((j)=>{let K=j.activationCapability?U[j.activationCapability]:void 0,re=K?.enabled??!0,oe=G.destructiveCommandRuleOverrides[j.id],de=j.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...oe?{override:oe}:{}}:G.destructiveCommandProtectionEnabled?oe?{enabled:oe==="on",inheritedEnabled:re,changesInherited:oe==="on"!==re,source:"rule_override",...j.activationCapability?{activationCapability:j.activationCapability}:{},override:oe}:{enabled:re,inheritedEnabled:re,changesInherited:!1,source:K?.source??"built_in_default",...j.activationCapability?{activationCapability:j.activationCapability}:{}}:{enabled:!1,inheritedEnabled:re,changesInherited:!1,source:"master_disabled",...j.activationCapability?{activationCapability:j.activationCapability}:{},...oe?{override:oe}:{}};return[j.id,Object.freeze(de)]})))}function fd(G,U){return Object.freeze({...G,effectiveDestructiveCommandRules:q(G,U)})}var pd={standard:0,strict:1,paranoid:2};function ee(G,U,j=!1,K=G.safety.level){let re=zb(G,U,K),oe=new Set(j?re.map((mt)=>mt.field):[]),de=(mt,gt)=>oe.has(mt)?void 0:gt,Se=(mt,gt)=>Object.fromEntries(Object.entries(gt??{}).filter(([ft])=>!oe.has(`${mt}.${ft}`))),we=(mt,gt)=>gt?.filter((ft)=>!oe.has(`${mt}.${ft}`));return{policy:{version:1,safety:{level:de("safety.level",U.safety?.level)??G.safety.level,overrides:{...G.safety.overrides,...Se("safety.overrides",U.safety?.overrides)}},workflow:{worktree_mode:de("workflow.worktree_mode",U.workflow?.worktree_mode)??G.workflow.worktree_mode},destructive_command_protection:{enabled:de("destructive_command_protection.enabled",U.destructive_command_protection?.enabled)??G.destructive_command_protection.enabled,overrides:{...G.destructive_command_protection.overrides,...Se("destructive_command_protection.overrides",U.destructive_command_protection?.overrides)},allow_paths:Xa(G.destructive_command_protection.allow_paths,we("destructive_command_protection.allow_paths",U.destructive_command_protection?.allow_paths))},secret_protection:{enabled:de("secret_protection.enabled",U.secret_protection?.enabled)??G.secret_protection.enabled,overrides:{...G.secret_protection.overrides,...Se("secret_protection.overrides",U.secret_protection?.overrides)},deny_paths:Xa(G.secret_protection.deny_paths,U.secret_protection?.deny_paths),allow_paths:Xa(G.secret_protection.allow_paths,we("secret_protection.allow_paths",U.secret_protection?.allow_paths))},audit:G.audit},weakenings:re.map((mt)=>mt.message)}}function Xa(G,U){return[...new Set([...G,...U??[]])]}function zb(G,U,j){let K=U.safety?.level,re=ki[j];return[...K&&pd[K]<pd[G.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${G.safety.level} -> ${K}`}]:[],...Zr.flatMap((oe)=>U.safety?.overrides?.[oe]===!1&&(G.safety.overrides[oe]??re[oe])?[{field:`safety.overrides.${oe}`,message:`project policy disables ${oe}`}]:[]),...U.workflow?.worktree_mode===!0&&!G.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...U.destructive_command_protection?.enabled===!1&&G.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...U.secret_protection?.enabled===!1&&G.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...gd("destructive_command_protection.overrides",U.destructive_command_protection?.overrides,(oe)=>G.destructive_command_protection.enabled&&G.destructive_command_protection.overrides[oe]!=="off"),...gd("secret_protection.overrides",U.secret_protection?.overrides,(oe)=>G.secret_protection.enabled&&(G.secret_protection.overrides[oe]==="on"?!0:G.secret_protection.overrides[oe]!=="off"&&!Ui.has(oe))),...G.destructive_command_protection.enabled?hd(G.destructive_command_protection.allow_paths,U.destructive_command_protection?.allow_paths).map((oe)=>({field:`destructive_command_protection.allow_paths.${oe}`,message:`project policy adds destructive allow path: ${oe}`})):[],...G.secret_protection.enabled?hd(G.secret_protection.allow_paths,U.secret_protection?.allow_paths).map((oe)=>({field:`secret_protection.allow_paths.${oe}`,message:`project policy adds secret allow path: ${oe}`})):[]]}function gd(G,U,j){return Object.entries(U??{}).flatMap(([K,re])=>re==="off"&&j(K)?[{field:`${G}.${K}`,message:`project policy disables rule ${K}`}]:[])}function hd(G,U){return(U??[]).filter((j)=>!G.includes(j))}var el=new Set(["standard","strict","paranoid"]),te={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:ud}};function Sd(G,U){let j=Kb(l(G,U),G.home),K=L(G,U)?{exists:!1,policy:F(),errors:[]}:Me(h(U.cwd),G.home),re=ue(K.parsed,G.home),oe=v(n.projectTightenOnly,G.env),de=j.gui??te,Se=Object.keys(re.policy).length>0?ee(de,re.policy,oe,Tu(de.safety.level,G.env)):void 0,we=[...j.errors,...K.errors,...re.diagnostics],We=(j.fallback==="defaults"&&Se?"salvaged":j.fallback)??(j.gui?void 0:K.fallback)??(we.length>0?"salvaged":void 0),mt=re.policy.safety?.level&&Se?.policy.safety.level===re.policy.safety.level?"project":j.levelPresent?"user":"default";return{...Se?Qa(Se.policy):j.policy,errors:we,...We?{fallback:We}:{},...K.exists?{policyScopes:{levelScope:mt,weakenings:Se?.weakenings??[],weakeningsIgnored:oe}}:{}}}var Ub="project policy audit settings are ignored; audit is user scope only";function ue(G,U){if(!En(G))return{policy:{},diagnostics:[]};let j=En(G.safety)?G.safety:{},K=En(G.workflow)?G.workflow:{},re=En(G.destructive_command_protection)?G.destructive_command_protection:{},oe=En(G.secret_protection)?G.secret_protection:{},de={...el.has(j.level)?{level:j.level}:{},...En(j.overrides)?yd({overrides:vd(j.overrides,Zr,["safety","overrides"],Pr)}):{}},Se={...typeof re.enabled==="boolean"?{enabled:re.enabled}:{},...re.overrides!==void 0?{overrides:Yi(re.overrides,Fa,Rd,Pr)}:{},...re.allow_paths!==void 0?{allow_paths:eo(re.allow_paths,Ka,U,["destructive_command_protection","allow_paths"],Pr)}:{}},we={...typeof oe.enabled==="boolean"?{enabled:oe.enabled}:{},...oe.overrides!==void 0?{overrides:Yi(oe.overrides,ja,xd,Pr)}:{},...oe.deny_paths!==void 0?{deny_paths:eo(oe.deny_paths,Ya,U,["secret_protection","deny_paths"],Pr)}:{},...oe.allow_paths!==void 0?{allow_paths:eo(oe.allow_paths,Za,U,["secret_protection","allow_paths"],Pr)}:{}};return{policy:yd({safety:de,workflow:typeof K.worktree_mode==="boolean"?{worktree_mode:K.worktree_mode}:{},destructive_command_protection:Se,secret_protection:we}),diagnostics:G.audit===void 0?[]:[Ub]}}function vd(G,U,j,K){return Object.fromEntries(U.flatMap((re)=>{let oe=G[re];if(typeof oe==="boolean")return[[re,oe]];if(oe!==void 0)K(e([...j,re],tl));return[]}))}function yd(G){return Object.fromEntries(Object.entries(G).flatMap((U)=>Object.keys(U[1]).length>0?[U]:[]))}var Pr=()=>{return},tl="must be a boolean",nl="must be an object if provided",Ed=`must be an integer between ${qi} and ${Ki}`,Rd={path:["destructive_command_protection","overrides"],label:"destructive command"},xd={path:["secret_protection","overrides"],label:"secret protection"},et=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function tt(G,U){let j=[];return{policy:_d(G,U,(re)=>{j.push(re)}),issues:j}}function E(G,U){return _d(G,U,Pr)}function _d(G,U,j){if(!En(G))return j(e([],"Config must be an object")),F();if(G.version!==1)j(e(["version"],"must be 1"));let K=Qr(G.safety,["safety"],["level","overrides"],j),re=Qr(K.overrides,["safety","overrides"],Zr,j),oe=Qr(G.workflow,["workflow"],["worktree_mode"],j),de=Qr(G.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],j),Se=Qr(G.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],j),we=Qr(G.audit,["audit"],["retention_days"],j);return wd(G,et,[],j),{version:1,safety:{level:Hb(K.level,j),overrides:vd(re,Zr,["safety","overrides"],j)},workflow:{worktree_mode:Ja(oe.worktree_mode,["workflow","worktree_mode"],!1,j)},destructive_command_protection:{enabled:Ja(de.enabled,["destructive_command_protection","enabled"],!0,j),overrides:Yi(de.overrides,Fa,Rd,j),allow_paths:eo(de.allow_paths,Ka,U,["destructive_command_protection","allow_paths"],j)},secret_protection:{enabled:Ja(Se.enabled,["secret_protection","enabled"],!0,j),overrides:Yi(Se.overrides,ja,xd,j),deny_paths:eo(Se.deny_paths,Ya,U,["secret_protection","deny_paths"],j),allow_paths:eo(Se.allow_paths,Za,U,["secret_protection","allow_paths"],j)},audit:{retention_days:jb(we.retention_days,j)}}}function Qr(G,U,j,K){if(G===void 0)return{};if(!En(G))return K(e(U,nl)),{};return wd(G,j,U,K),G}function wd(G,U,j,K){for(let re of Object.keys(G).filter((oe)=>!U.includes(oe)))K({path:j,message:re,kind:"unknownKeys"})}function Hb(G,U){if(G===void 0)return"standard";if(el.has(G))return G;return U(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Ja(G,U,j,K){if(typeof G==="boolean")return G;if(G!==void 0)K(e(U,tl));return j}function jb(G,U){if(!(G===void 0||typeof G==="number"&&Number.isInteger(G)&&G>=qi&&G<=Ki))U(e(["audit","retention_days"],Ed));return dd(G)}function Yi(G,U,j,K){if(G===void 0)return{};if(!En(G))return K(e(j.path,nl)),{};return Object.fromEntries(Object.entries(G).flatMap(([re,oe])=>{if(!U.has(re))return K({path:[...j.path,re],message:`unknown ${j.label} rule id "${re}"`,kind:"key"}),[];if(oe==="on"||oe==="off")return[[re,oe]];return K(e([...j.path,re],'must be "on" or "off"')),[]}))}function eo(G,U,j,K,re){if(G===void 0)return[];if(!Array.isArray(G))return re(e(K,"must be an array of paths")),[];return G.flatMap((oe,de)=>{let Se=U(oe,j);if(Se===null)return[oe];return re(typeof oe==="string"?tn([...K,de],Se):e([...K,de],Se)),[]})}function En(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function F(){return structuredClone(te)}function Le(G,U){let j=T({safety:$e(G.safety)},U),K=q({destructiveCommandProtectionEnabled:G.destructive_command_protection.enabled,destructiveCommandRuleOverrides:G.destructive_command_protection.overrides},j.capabilities),re=Object.values(K),oe=re.filter((de)=>de.source!=="catastrophic");return{selectedPreset:G.safety.level,effectiveLevel:j.effectiveLevel,capabilities:j.capabilities,rules:K,counts:{enabled:oe.filter((de)=>de.enabled).length,disabled:oe.filter((de)=>!de.enabled).length,effectiveCustomizations:re.filter((de)=>de.changesInherited).length}}}function Me(G,U){if(!$b(G))return{exists:!1,policy:F(),errors:[]};try{let j=Bb(G,"utf-8");if(!j.trim())return{exists:!0,policy:F(),errors:[`${G}: Config file is empty`],fallback:"defaults"};let K=JSON.parse(j),re=tt(K,U);if(re.issues.length===0)return{exists:!0,parsed:K,policy:re.policy,errors:[]};return{exists:!0,parsed:K,policy:re.policy,errors:re.issues.map((oe)=>`${G}: ${qb(oe)}`),fallback:En(K)?"salvaged":"defaults"}}catch(j){let K=j instanceof Error?j.message:String(j);return{exists:!0,policy:F(),errors:[`${G}: ${j instanceof SyntaxError?"Invalid JSON":K}`],fallback:"defaults"}}}var Vb=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[nl,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[tl,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Ed,`not an integer between ${qi} and ${Ki}`]]);function qb(G){let U=Na(G.path);if(G.kind==="unknownKeys")return`${U===""?"":`${U}.`}${G.message}: unknown field`;if(G.kind==="key")return`${U}: unknown rule id`;let j=Vb.get(G.message)??G.message;return U===""?j:`${U}: ${j}`}function Kb(G,U){let j=Me(G,U);if(!j.exists){let K=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!En(K))return{policy:Cd(),errors:[]};let re=E(K,U);return{policy:Qa(re),gui:re,errors:[],levelPresent:bd(K)}}if(j.parsed===void 0)return{policy:Cd(),errors:j.errors,...j.fallback?{fallback:j.fallback}:{}};return{policy:Qa(j.policy),gui:j.policy,errors:j.errors,...j.fallback?{fallback:j.fallback}:{},levelPresent:bd(j.parsed)}}function bd(G){let U=En(G)&&En(G.safety)?G.safety:{};return el.has(U.level)}function Fe(G){let U=Object.entries(G),j=new Set(U.flatMap(([K,re])=>re==="on"?[K]:[]));return[...new Set([...[...Ui].filter((K)=>!j.has(K)),...U.flatMap(([K,re])=>re==="off"?[K]:[])])]}function Cd(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Fe({}),denyPaths:[],allowPaths:[]}}}function Qa(G){return{safety:$e(G.safety),worktreeMode:G.workflow.worktree_mode,destructiveCommandProtectionEnabled:G.destructive_command_protection.enabled,destructiveCommandRuleOverrides:G.destructive_command_protection.overrides,destructiveCommandAllowPaths:G.destructive_command_protection.allow_paths,secretProtection:{enabled:G.secret_protection.enabled,disabledRules:Fe(G.secret_protection.overrides),denyPaths:G.secret_protection.deny_paths,allowPaths:G.secret_protection.allow_paths}}}function $e(G){let U={...G.overrides.fail_closed!==void 0?{failClosed:G.overrides.fail_closed}:{},...G.overrides.paranoid_rm!==void 0?{paranoidRm:G.overrides.paranoid_rm}:{},...G.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:G.overrides.paranoid_interpreters}:{}};return{level:G.level,...Object.keys(U).length>0?{overrides:U}:{}}}function k(G,U){let j=Q(G,U),K=Sd(G,U),re={rules:j.rules,transparentWrappers:j.transparent_wrappers,safety:K.safety,worktreeMode:K.worktreeMode,destructiveCommandProtectionEnabled:K.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:K.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:K.destructiveCommandAllowPaths,secretProtection:{enabled:K.secretProtection.enabled??!0,disabledRules:K.secretProtection.disabledRules??[],denyPaths:K.secretProtection.denyPaths,allowPaths:K.secretProtection.allowPaths??[]}},oe={...j.userConfig?.overrides,...j.projectConfig?.overrides},de=Object.freeze(Object.fromEntries(re.rules.map((Se)=>{let we=j.rulebooks.find((mt)=>mt.rules.includes(Se.name)),We=oe[Se.name];return[Se.name,Object.freeze({id:Se.name,...we?{rulebook:Object.freeze({name:we.name,version:we.version}),...Jb(we.spec)?{source:we.spec}:{}}:{},...We&&typeof We==="object"?{override:Object.freeze({type:"reason",reason:We.reason})}:{}})]})));return _e(re,Yb(j,K),de,K.policyScopes)}function je(G){if(G.state==="ready")return{state:G.state};return{state:G.state,reason:G.reason}}function Yb(G,U){let j=Xb(U);if(G.errors.length===0&&G.warnings.length===0&&!j)return;return{diagnostics:[...G.errors,...G.warnings,...U.errors],reason:Qb(G.errors.length>0?Zb(G.errors):void 0,G.warnings.length>0?ol(G.warnings.join("; ")):void 0,j)}}function Zb(G){return`${ol(G.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Xb(G){if(G.errors.length===0)return;let U=G.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${G.errors.join("; ")}. Enforcing ${U}; the invalid values are not active. Fix the policy file manually`}function Jb(G){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(G)}function _e(G,U,j=Object.freeze({}),K){let re=rl(structuredClone(G)),oe=K?{policyScopes:rl(structuredClone(K))}:{};if(!U)return Object.freeze({state:"ready",policy:re,diagnostics:Object.freeze([]),ruleMetadata:j,...oe});return Object.freeze({state:"degraded",policy:re,diagnostics:Object.freeze([...U.diagnostics]),reason:U.reason,ruleMetadata:j,...oe})}function rl(G){if(typeof G!=="object"||G===null)return G;for(let U of Object.values(G))rl(U);return Object.freeze(G)}function Qb(...G){return ol(G.filter((U)=>!!U).join("; "))}function ol(G){return/[.!?]$/.test(G)?G:`${G}.`}function Ue(G){let U=G.effectiveCapabilities,j=G.strict??U.fail_closed.enabled,K=G.paranoidRm??U.paranoid_rm.enabled,re=G.paranoidInterpreters??U.paranoid_interpreters.enabled,oe={fail_closed:il(U.fail_closed,G.strict,"strict"),paranoid_rm:il(U.paranoid_rm,G.paranoidRm,"paranoidRm"),paranoid_interpreters:il(U.paranoid_interpreters,G.paranoidInterpreters,"paranoidInterpreters")};return{policy:fd(G.policySnapshot.policy,oe),effectiveCapabilities:oe,effectiveLevel:Ea({failClosed:j,paranoidRm:K,paranoidInterpreters:re}),strict:j,paranoidRm:K,paranoidInterpreters:re,worktreeMode:G.worktreeMode??!1}}function il(G,U,j){if(U===void 0||U===G.enabled)return G;return{enabled:U,source:"capability_override",sources:[...G.sources,`analysis options.${j}`]}}import{dirname as zw,isAbsolute as $w,join as Bw,parse as Uw,resolve as Hw,sep as jw}from"node:path";function jo(G,U){if(G!=="powershell")return U[0]?.provenance==="command-substitution";let j=U[0]?.text==="&"||U[0]?.text==="."?1:0,K=U[j]?.provenance;return K!==void 0&&K!=="literal"}var eC=/^[A-Za-z_][A-Za-z0-9_]*=/;function Zi(G,U){return G?.provenance==="literal"&&!G.quoted&&G.raw===U&&G.text===U}function Vo(G){let U=Zi(G.words[0],"time")?1:0,j=U===1&&Zi(G.words[U],"-p")?U+1:U,K=U===1&&Zi(G.words[j],"--")?j+1:j,re=Zi(G.words[K],"!")?K+1:K,oe=G.words.slice(re).find((de)=>!eC.test(de.text));return oe?.provenance==="literal"?oe.text:void 0}var cr=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Xi(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function tC(G){return Object.freeze({...G,span:Object.freeze(G.span),words:Object.freeze(G.words),redirections:Object.freeze(G.redirections.map((U)=>Object.freeze({...U,span:Object.freeze(U.span),...U.heredoc?{heredoc:Object.freeze({...U.heredoc,bodySpan:Object.freeze(U.heredoc.bodySpan),terminatorSpan:Object.freeze(U.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(G.nested.map((U)=>mn(U)))})}function Ji(G,U,j){G.push(j),U.reset()}function Qi(G){let U=[];return{parts:U,push:(j,K,re)=>{if(K<=j)return;U.push({raw:G.slice(j,K),span:{start:j,end:K},provenance:re})}}}function sl(G){let U=G.parts??[{raw:G.raw,span:G.span,provenance:G.provenance}];return Object.freeze({kind:"word",...G,span:Object.freeze(G.span),parts:Object.freeze(U.map((j)=>Object.freeze({...j,span:Object.freeze(j.span)})))})}function to(G,U,j,K,re,oe,de){return sl({text:K,raw:G.slice(U,j),span:{start:U,end:j},provenance:re,quoted:oe,...de?{parts:de}:{}})}function mn(G){return Object.freeze({...G,span:Object.freeze(G.span),issues:Object.freeze(G.issues.map((U)=>Object.freeze({...U}))),nodes:Object.freeze(G.nodes.map((U)=>{if(U.kind==="command")return tC(U);if(U.kind==="group"||U.kind==="function")return Object.freeze({...U,span:Object.freeze(U.span),body:mn(U.body)});return Object.freeze({...U,span:Object.freeze(U.span)})}))})}function al(G,U,j){if(U>=j||Ad(G[U]??""))return null;let K="",re=!1,oe=!1,de=U;while(de<j&&!Ad(G[de]??"")){let Se=G[de]??"";if(Se==="'"){re=!0;let we=Pd(G,de+1,j,"'");K+=we.text,oe||=!we.closed,de=we.next;continue}if(Se==='"'){re=!0;let we=Pd(G,de+1,j,'"');K+=we.text,oe||=!we.closed,de=we.next;continue}if(Se==="\\"){re=!0;let we=G[de+1];if(!we||we===`
7
+ `||we==="\r"){oe=!0;break}K+=we,de+=2;continue}if(Se==="`"||G.startsWith("$(",de)||G.startsWith("${",de)||G.startsWith("<(",de)||G.startsWith(">(",de))oe=!0;K+=Se,de++}return{delimiter:K,quoted:re,next:de,ambiguous:oe}}function ll(G,U,j,K){let re=[],oe=U;for(let de of K){let Se=oe,we=!1;while(oe<j){let We=nC(G,oe,j);if((de.stripTabs?We.text.replace(/^\t+/,""):We.text)===de.delimiter){de.attach({body:de.stripTabs?rC(G.slice(Se,oe)):G.slice(Se,oe),delimiter:de.delimiter,quotedDelimiter:de.quotedDelimiter,bodySpan:{start:Se,end:oe},terminatorSpan:{start:oe,end:We.contentEnd}}),oe=We.next,we=!0;break}if(We.next<=oe)break;oe=We.next}if(we)continue;return re.push({code:"unterminated-heredoc",message:`heredoc delimiter ${de.delimiter} was not found`}),{next:j,issues:re,terminated:!1}}return{next:oe,issues:re,terminated:!0}}function Pd(G,U,j,K){let re="",oe=U;while(oe<j&&G[oe]!==`
8
+ `&&G[oe]!=="\r"){let de=G[oe]??"";if(de===K)return{text:re,next:oe+1,closed:!0};if(K==='"'&&de==="\\"&&G[oe+1]){let Se=G[oe+1]??"";re+=["$","`",'"',"\\"].includes(Se)?Se:`\\${Se}`,oe+=2;continue}re+=de,oe++}return{text:re,next:oe,closed:!1}}function Ad(G){return G!=="\r"&&(/[\s;&|<>)]/u.test(G)||G==="`")}function nC(G,U,j){let K=U;while(K<j&&G[K]!==`
9
+ `)K++;let re=K>=j?j:K+1;return{text:G.slice(U,K),contentEnd:K,next:re}}function rC(G){return G.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Md=new Set(["&&","||","|","|&"]),oC=new Set(["!","do","elif","else","if","then","until","while"]);function Dd(G,U){let j={start:0,end:G.length};if(G.length>U.maxInputLength)return mn({kind:"program",dialect:"posix",source:G,span:j,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${U.maxInputLength} UTF-16 code units`}],nodes:[]});let K={wordsUsed:0,maxWords:U.maxWords,quotedExpansionEnd:1/0},re=ns(G,0,G.length,U,K,0),oe=fC(G,K.quotedExpansionEnd,re.nodes)?[...re.issues,Wd]:re.issues;return mn({kind:"program",dialect:"posix",source:G,span:j,status:os(oe,re.limited),issues:oe,nodes:re.nodes})}function ns(G,U,j,K,re,oe,de){let Se=[],we=[],We=Xi(),mt=[],gt=()=>{if(We.words.length===0&&We.redirections.length===0)return;let pt={start:We.start,end:We.end},ht=We.words.map((yt)=>yt.text);Ji(Se,We,{kind:"command",dialect:"posix",source:G.slice(pt.start,pt.end),span:pt,words:We.words,redirections:We.redirections,nested:We.nested,displayText:we.length>0&&Se.length===0?G.slice(U,j):ht.join(" ")})},ft=U;while(ft<j){let pt=G[ft];if(!pt)break;if(de&&pt===de)return gt(),Od(Se,we),{nodes:Se,issues:we,next:ft+1,closed:!0,limited:!1,pendingHeredocs:mt};if(Ko(pt)){if(pt===`
10
+ `||pt==="\r"){gt();let wt=pt==="\r"&&G[ft+1]===`
11
+ `?ft+2:ft+1,Et=Se.at(-1);if(Et?.kind!=="connector"||!Md.has(Et.operator))Se.push(Object.freeze({kind:"connector",operator:G.slice(ft,wt),span:Object.freeze({start:ft,end:wt})}));if(mt.length>0){let At=ll(G,wt,j,mt.splice(0));we.push(...At.issues),ft=At.next;continue}ft=wt;continue}ft++;continue}if(pt==="#"){while(ft<j&&G[ft]!==`
12
+ `&&G[ft]!=="\r")ft++;continue}let ht=We.start===-1?kC(G,ft,j):void 0;if(ht){if(ul(Se,we),oe>=K.maxDepth)return no(Se,we,ft,"depth-limit",K.maxDepth);if(!cl(re))return no(Se,we,ft,"word-limit",K.maxWords);let wt=ns(G,ht.braceIndex+1,j,K,re,oe+1,"}"),Et=wt.next,At={start:ht.braceIndex+1,end:wt.closed?Et-1:Et},It=Td(G,At,wt);if(Se.push({kind:"function",name:ht.name,span:{start:ft,end:Et},body:It}),we.push(...wt.issues),wt.pendingHeredocs.length>0||Yo(wt.nodes))we.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(mt.push(...wt.pendingHeredocs),wt.limited)return ts(Se,we,wt.next);if(!wt.closed)we.push({code:"unclosed-function-body",message:"function body is not closed"});ft=Et;continue}let yt=rs(G,ft);if(yt){if(gt(),!Hd(Se.at(-1)))we.push({code:"unexpected-connector",message:`connector ${yt} has no preceding command`});Se.push(Object.freeze({kind:"connector",operator:yt,span:Object.freeze({start:ft,end:ft+yt.length})})),ft+=yt.length;continue}if(pt===")"){gt(),we.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),Se.push({kind:"unknown",source:pt,span:{start:ft,end:ft+1}}),ft++;continue}if((pt==="("||pt==="{"&&bC(G,ft,j))&&We.start===-1){if(ul(Se,we),oe>=K.maxDepth)return no(Se,we,ft,"depth-limit",K.maxDepth);let wt=pt==="("?")":"}",Et=ns(G,ft+1,j,K,re,oe+1,wt),At=Et.next,It={start:ft+1,end:Et.closed?At-1:At},Kt=Td(G,It,Et);if(Se.push({kind:"group",style:pt==="("?"subshell":"brace",span:{start:ft,end:At},body:Kt}),we.push(...Et.issues),Et.pendingHeredocs.length>0||Yo(Et.nodes))we.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(mt.push(...Et.pendingHeredocs),Et.limited)return ts(Se,we,Et.next);if(!Et.closed)we.push({code:pt==="("?"unclosed-subshell":"unclosed-brace-group",message:`${pt} group is not closed`});ft=At;continue}let bt=(pt==="<"||pt===">")&&G[ft+1]!=="("?lC(G,ft):null;if(bt){let wt=We.words.at(-1),Et=wt&&wt.span.end===ft&&/^[0-9]+$/.test(wt.raw)?Number(wt.raw):void 0;if(Et!==void 0)We.words.pop();let At=Et===void 0?ft:wt?.span.start??ft;We.start=We.start===-1?ft:We.start;let It=ft+bt.length;while(It<j&&/[ \t]/.test(G[It]??""))It++;let Kt=G[It],Kn=It>ft+bt.length&&Kt==="#",bn=!Kt||Ko(Kt)||!!rs(G,It)||Kt===de||Kt===")"||Kn||(Kt==="<"||Kt===">")&&G[It+1]!=="(",Sr=bt==="<<"||bt==="<<-",$t=Sr?al(G,It,j):void 0,Wt=$t?{word:to(G,It,$t.next,$t.delimiter,"literal",$t.quoted),nested:[],issues:[],next:$t.next,limited:!1}:!bn?dl(G,It,j,K,re,oe):void 0;if(Wt){if(we.push(...Wt.issues),Wt.limited)return ts(Se,we,Wt.next);if(!cl(re))return no(Se,we,Wt.next,"word-limit",K.maxWords)}let sn=Wt?.next??ft+bt.length,Yt={kind:"redirection",operator:bt,span:{start:At,end:sn},...Et===void 0?{}:{fd:Et},...Wt?{target:Wt.word}:{}};if(We.redirections.push(Yt),Sr&&!$t)we.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if($t){if($t.ambiguous||$t.delimiter.length===0)we.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let Zt=We.nested;mt.push({delimiter:$t.delimiter,quotedDelimiter:$t.quoted,stripTabs:bt==="<<-",attach:(Cn)=>{if(Yt.heredoc=Cn,Cn.quotedDelimiter)return;let Yn=sC(G,Cn.bodySpan.start,Cn.bodySpan.end,K,re,oe+1);Zt.push(...Yn.programs),we.push(...Yn.issues)}})}if(!Sr&&!Wt)we.push({code:"missing-redirection-target",message:`redirection ${bt} requires a target word`});if(Wt)We.nested.push(...Wt.nested);We.end=sn,ft=sn;continue}let Ct=We.start===-1;if(Ct)ul(Se,we);let vt=dl(G,ft,j,K,re,oe);if(we.push(...vt.issues),vt.limited)return ts(Se,we,vt.next);let St=vC(We.words)?wC(G,vt.word,re.maxWords-re.wordsUsed,K.maxDepth,K.maxInputLength):void 0;if(St?.limitCode)return no(Se,we,vt.next,St.limitCode,St.limitCode==="word-limit"?K.maxWords:St.limitCode==="depth-limit"?K.maxDepth:K.maxInputLength);let Rt=St?.words??[vt.word];for(let wt of Rt){if(!cl(re))return no(Se,we,vt.next,"word-limit",K.maxWords);We.words.push(wt)}if(We.start=We.start===-1?ft:We.start,We.end=vt.next,We.nested.push(...vt.nested),Ct&&jd(vt.word))gt();ft=vt.next>ft?vt.next:ft+1}return gt(),Od(Se,we),we.push(...OC(mt)),{nodes:Se,issues:we,next:ft,closed:de===void 0,limited:!1,pendingHeredocs:[]}}function Td(G,U,j){return{kind:"program",dialect:"posix",source:G.slice(U.start,U.end),span:U,status:os(j.issues,j.limited),issues:j.issues,nodes:j.nodes}}function dl(G,U,j,K,re,oe){let de="",Se=U,we=!1,We="literal",mt=[],gt=[],ft=!1;while(Se<j){let pt=G[Se],ht=(pt==="<"||pt===">")&&G[Se+1]==="(";if(!pt||Ko(pt)||(pt===";"||pt==="|"||pt==="&")&&rs(G,Se)||(pt==="<"||pt===">")&&!ht)break;if(pt===")")break;if(pt==="'"){we=!0;let Ct=G.indexOf("'",Se+1);if(Ct===-1||Ct>=j){de+=G.slice(Se+1,j),gt.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),Se=j;break}de+=G.slice(Se+1,Ct),Se=Ct+1;continue}if(pt==='"'){we=!0;let Ct=iC(G,Se,j,K,re,oe);if(de+=Ct.text,mt.push(...Ct.nested),gt.push(...Ct.issues),ft||=Ct.limited,We=qo(We,Ct.provenance),Se=Ct.next,ft)break;continue}if(G.startsWith("$'",Se)){we=!0;let Ct=gC(G,Se+2,j);if(de+=Ct.text,gt.push(...Ct.issues),!Ct.closed)gt.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});Se=Ct.next;continue}if(pt==="\\"){let Ct=G[Se+1];if(!Ct){gt.push({code:"trailing-escape",message:"escape has no following character"}),Se++;break}if(Ct===`
13
+ `){Se+=2;continue}de+=Ct,Se+=2;continue}if(Tr(G,Se))gt.push(Ar);let yt=pt==="$"||pt==="<"||pt===">"||pt==="`"?Zo(G,Se,j,K,re,oe):null,bt=yt?fl(yt,mt,gt):Fd(G,Se,j,K,re,oe,mt,gt);if(bt){if(bt.provenance==="variable")de+=G.slice(Se,bt.next);if(ft||=bt.limited,We=qo(We,bt.provenance),Se=bt.next,ft)break;continue}if(pt==="$"){let Ct=zd(G,Se,j,de,We);de=Ct.text,We=Ct.provenance,Se=Ct.next;continue}if(pt==="*"||pt==="?"||pt==="[")We=qo(We,"glob");de+=pt,Se++}return{word:to(G,U,Se,de,We,we,We==="literal"?void 0:yC(G,U,Se)),nested:mt,issues:gt,next:Se,limited:ft}}function iC(G,U,j,K,re,oe){let de="",Se="literal",we=[],We=[],mt=!1,gt=U+1;while(gt<j){let ft=G[gt];if(ft==='"')return{text:de,provenance:Se,nested:we,issues:We,next:gt+1,limited:mt};if(ft==="\\"&&G[gt+1]){let yt=G[gt+1]??"";if(yt===`
14
+ `){gt+=2;continue}if(yt==="\r"&&G[gt+2]===`
15
+ `){gt+=3;continue}de+=["$","`",'"',"\\"].includes(yt)?yt:`\\${yt}`,gt+=2;continue}if(Tr(G,gt))We.push(Ar);let pt=Zo(G,gt,j,K,re,oe),ht=pt?fl(pt,we,We):Fd(G,gt,j,K,re,oe,we,We);if(ht){if(ht.provenance!=="command-substitution")de+=G.slice(gt,ht.next);if(gt=ht.next,mt||=ht.limited,Se=qo(Se,ht.provenance),mt)return{text:de,provenance:Se,nested:we,issues:We,next:gt,limited:mt};continue}if(ft==="$"){let yt=zd(G,gt,j,de,Se);de=yt.text,Se=yt.provenance,gt=yt.next;continue}de+=ft??"",gt++}return We.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:de,provenance:Se,nested:we,issues:We,next:j,limited:mt}}function Zo(G,U,j,K,re,oe){let de=Ld(G,U);if(!de)return null;let{length:Se,closing:we}=de,We=we==="))",mt=we==="`",gt=G[U]==="<"||G[U]===">",ft=pl(G,U+Se,j,we),pt=ft===-1?j:ft,ht=ft===-1?j:ft+we.length;if(oe>=K.maxDepth)return{program:IC(G,U+Se,pt,"depth-limit"),next:ht,provenance:We?"arithmetic":"command-substitution"};if(We){let Rt=[],wt=[],Et=!1,At=U+Se;while(At<pt){let It=Zo(G,At,pt,K,re,oe+1);if(!It){if(Tr(G,At))wt.push(Ar);At++;continue}if(Rt.push(...It.program.nodes),wt.push(...It.program.issues),Et||=It.program.status==="limited",At=It.next,Et)break}if(ft===-1)wt.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:mn({kind:"program",dialect:"posix",source:G.slice(U+Se,pt),span:{start:U+Se,end:pt},status:os(wt,Et),issues:wt,nodes:Rt}),next:ht,provenance:"arithmetic"}}let yt=ns(G,U+Se,pt,K,re,oe+1),bt=ft===-1?[{code:"unclosed-command-substitution",message:`${G.slice(U,U+Se)} substitution is not closed`}]:[],Ct=(mt||gt)&&Yo(yt.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[],vt=mt&&/\\[\\$`\n]/.test(G.slice(U+Se,pt))?[pC]:[],St=[...yt.issues,...bt,...Ct,...vt];return{program:mn({kind:"program",dialect:"posix",source:G.slice(U+Se,pt),span:{start:U+Se,end:pt},status:os(St,yt.limited),issues:St,nodes:yt.nodes}),next:ht,provenance:"command-substitution"}}function sC(G,U,j,K,re,oe){let de=[],Se=[],we=U;while(we<j){let We=G[we];if(We==="\\"){we+=2;continue}let mt=We==="$"||We==="`"?Zo(G,we,j,K,re,oe):null;if(!mt){if(Tr(G,we))Se.push(Ar);we++;continue}if(de.push(mt.program),cC(G,we,mt.next)&&uC(mt.program))Se.push(Ar);we=mt.next}return{programs:de,issues:Se}}function fl(G,U,j){return U.push(G.program),j.push(...G.program.issues),{provenance:G.provenance,next:G.next,limited:G.program.status==="limited"}}function pl(G,U,j,K){if(K==="`"){for(let Se=U;Se<j;Se++){if(G[Se]==="\\"){Se++;continue}if(G[Se]==="`")return Se}return-1}let re={single:!1,double:!1},oe=[],de=[];for(let Se=U;Se<j;Se++){let we=G[Se];if((we===`
16
+ `||we==="\r")&&de.length>0){let gt=we==="\r"&&G[Se+1]===`
17
+ `?Se+2:Se+1,ft=ll(G,gt,j,de.splice(0));if(!ft.terminated)return-1;Se=ft.next-1;continue}let We=Nd(G,Se,U,j,re);if(We!==null){Se=We;continue}if(!re.double&&G.startsWith("$((",Se)){let gt=aC(G,Se+3,j);if(gt===-1)return-1;Se=gt+1;continue}if(K===")"&&!re.double&&we==="<"&&G[Se+1]==="<"&&G[Se+2]!=="<"){let gt=G[Se+2]==="-",ft=Se+(gt?3:2);while(ft<j&&/[ \t]/.test(G[ft]??""))ft++;let pt=al(G,ft,j);if(pt){de.push({delimiter:pt.delimiter,quotedDelimiter:pt.quoted,stripTabs:gt,attach:()=>{return}}),Se=pt.next-1;continue}}if(G.startsWith("$(",Se)&&!G.startsWith("$((",Se)){oe.push(re),re={single:!1,double:!1},Se++;continue}if(we==="("&&!re.double){oe.push(re),re={single:!1,double:!1};continue}if(we!==")"||re.double)continue;let mt=oe.pop();if(mt){re=mt;continue}return K==="))"&&G[Se+1]!==")"?-1:Se}return-1}function aC(G,U,j){let K=1,re={single:!1,double:!1};for(let oe=U;oe<j;oe++){let de=G[oe],Se=Nd(G,oe,U,j,re);if(Se!==null){oe=Se;continue}if(G.startsWith("$(",oe)&&!G.startsWith("$((",oe)){K++,oe++;continue}if(de==="("&&!re.double)K++;if(de!==")"||re.double)continue;if(K--,K===0)return G[oe+1]===")"?oe:-1}return-1}function Nd(G,U,j,K,re){let oe=G[U];if(oe==="\\"&&!re.single)return U+1;if(!re.double&&oe==="'")re.single=!re.single;if(!re.single&&oe==='"')re.double=!re.double;if(re.single)return U;if(re.double||oe!=="#"||!MC(G,U,j))return null;let de=U;while(de+1<K&&G[de+1]!==`
18
+ `&&G[de+1]!=="\r")de++;return de}function rs(G,U){let j=G[U];if(j===";")return";";if(j==="&")return G[U+1]==="&"?"&&":"&";if(j==="|")return G[U+1]==="|"?"||":G[U+1]==="&"?"|&":"|";return null}function lC(G,U){let j=G[U];if(j===">"){if(G[U+1]===">")return">>";if(G[U+1]==="&")return">&";return G[U+1]==="|"?">|":">"}if(j!=="<")return null;if(G.startsWith("<<<",U))return"<<<";if(G.startsWith("<<-",U))return"<<-";if(G[U+1]==="<")return"<<";if(G[U+1]==="&")return"<&";if(G[U+1]===">")return"<>";return"<"}function Ko(G){let U=G.charCodeAt(0);if(U===32||U>=9&&U<=13)return!0;if(U<128)return!1;return/\s/u.test(G)}var Ar=Object.freeze({code:"unsupported-function-substitution",message:"${ list; } function substitutions run in the current shell and cannot be analyzed"});function Tr(G,U){if(G[U]!=="$")return!1;let j=Id(G,U+1);if(G[j]!=="{")return!1;let K=G[Id(G,j+1)]??"";return K==="|"||Ko(K)}function cC(G,U,j){for(let K=G.indexOf("$",U);K!==-1&&K<j;K=G.indexOf("$",K+1))if(Tr(G,K))return!0;return!1}function uC(G){return G?.status==="limited"||(G?.issues??[]).some((U)=>U.code===Ar.code)}function Id(G,U){let j=U;while(G.startsWith("\\\n",j)||G.startsWith(`\\\r
19
+ `,j))j+=G[j+1]==="\r"?3:2;return j}function Ld(G,U){if(G.startsWith("$((",U))return{length:3,closing:"))"};if(G.startsWith("$(",U)||G.startsWith("<(",U)||G.startsWith(">(",U))return{length:2,closing:")"};return G[U]==="`"?{length:1,closing:"`"}:null}var dC=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"}),Wd=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"}),mC=/\$\(|`|[<>]\(/g;function fC(G,U,j){let K=ml(j);return[...G.slice(U).matchAll(mC)].some((re)=>{let oe=U+re.index;return!K.some((de)=>oe>=de.start&&oe<de.end)})}function ml(G){return G.flatMap((U)=>{if(U.kind==="command")return[...U.redirections.flatMap((j)=>j.heredoc?[j.heredoc.bodySpan]:[]),...U.nested.flatMap((j)=>ml(j.nodes))];return U.kind==="group"||U.kind==="function"?ml(U.body.nodes):[]})}var pC=Object.freeze({code:"unsupported-backtick-escape",message:"a backslash escape inside backticks changes the command the shell runs and cannot be analyzed"});function Fd(G,U,j,K,re,oe,de,Se){if(G[U]!=="$"||G[U+1]!=="{")return null;let we=is(G,U+2,j),We=we.close===-1?j:we.close+1;if(we.close===-1)Se.push(dC);if(we.quoted&&we.substitutions.length>0||we.continued)Se.push(Wd);if(we.quoted)re.quotedExpansionEnd=Math.min(re.quotedExpansionEnd,We);let mt=we.substitutions.some((gt)=>{if(Tr(G,gt))return Se.push(Ar),!1;let ft=Zo(G,gt,We,K,re,oe);return ft!==null&&fl(ft,de,Se).limited});return{provenance:"variable",next:We,limited:mt}}function is(G,U,j){let K=[],re=!1,oe=!1,de=1,Se=U;while(Se<j){let we=G[Se];if(we==="$"&&Tr(G,Se))K.push(Se);if(we==="\\"||we==="'"||we==='"'){re=!0,oe||=we==="\\"&&G[Se+1]===`
20
+ `,Se+=we==="\\"?2:1;continue}let We=Ld(G,Se);if(We){K.push(Se);let mt=pl(G,Se+We.length,j,We.closing);if(mt===-1)break;Se=mt+We.closing.length;continue}if(we==="$"&&G[Se+1]==="{"){de++,Se+=2;continue}if(we==="}"&&--de===0)return{close:Se,substitutions:K,quoted:re,continued:oe};Se++}return{close:-1,substitutions:K,quoted:re,continued:oe}}function Gd(G,U,j){if(G[U+1]==="{"){let re=is(G,U+2,j).close;return re===-1?j:re+1}if(G[U+1]==="$")return U+2;let K=U+1;while(K<j&&/[A-Za-z0-9_?@#!*-]/.test(G[K]??""))K++;return K===U+1?U+1:K}function gC(G,U,j){let K="",re=[],oe=U;while(oe<j){let de=G[oe];if(de==="'")return{text:K,next:oe+1,closed:!0,issues:re};if(de!=="\\"){K+=de??"",oe++;continue}let Se=hC(G,oe+1,j);if(K+=Se.text,Se.invalidCodePoint!==void 0)re.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${Se.invalidCodePoint}`});oe=Se.next}return{text:K,next:j,closed:!1,issues:re}}function hC(G,U,j){let K=G[U];if(!K||U>=j)return{text:"\\",next:U};let re=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
21
+ `],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(re.has(K))return{text:re.get(K)??K,next:U+1};if(K==="x")return es(G,U+1,j,16,2,U+1);if(K==="u")return es(G,U+1,j,16,4,U+1);if(K==="U")return es(G,U+1,j,16,8,U+1);if(/[0-7]/.test(K))return es(G,U,j,8,3,U+1);return{text:K,next:U+1}}function es(G,U,j,K,re,oe){let de=K===16?/[0-9a-fA-F]/:/[0-7]/,Se="",we=U;while(we<j&&Se.length<re&&de.test(G[we]??""))Se+=G[we],we++;if(!Se)return{text:G[oe-1]??"",next:oe};let We=Number.parseInt(Se,K);return We>1114111||We>=55296&&We<=57343?{text:"�",next:we,invalidCodePoint:We}:{text:String.fromCodePoint(We),next:we}}function os(G,U=!1){if(U)return"limited";if(G.some((j)=>j.code==="invalid-ansi-c-code-point"||j.code==="missing-heredoc-delimiter"||j.code==="ambiguous-heredoc-delimiter"||j.code==="unterminated-heredoc"||j.code==="unsupported-heredoc-context"||j.code==="unsupported-function-substitution"||j.code==="unsupported-backtick-escape"||j.code==="unclosed-parameter-expansion"||j.code==="unsupported-parameter-expansion"))return"invalid";return G.length>0?"partial":"complete"}function zd(G,U,j,K,re){let oe=Gd(G,U,j);return{text:K+G.slice(U,oe),provenance:qo(re,"variable"),next:oe}}function yC(G,U,j){let K=Qi(G),re=U,oe=!1,de=!1,Se=U;while(Se<j){let we=G[Se];if(we==="\\"&&!oe){Se+=2;continue}if(!de&&we==="'"){oe=!oe,Se++;continue}if(!oe&&we==='"'){de=!de,Se++;continue}if(oe){Se++;continue}let We=G.startsWith("$((",Se),mt=G.startsWith("$(",Se)&&!We,gt=!de&&(G.startsWith("<(",Se)||G.startsWith(">(",Se)),ft=we==="`";if(We||mt||gt||ft){let pt=We?3:ft?1:2,ht=We?"))":ft?"`":")",yt=pl(G,Se+pt,j,ht),bt=yt===-1?j:yt+ht.length;K.push(re,Se,"literal"),K.push(Se,bt,We?"arithmetic":"command-substitution"),Se=bt,re=bt;continue}if(we==="$"){let pt=Gd(G,Se,j);if(pt>Se+1){K.push(re,Se,"literal"),K.push(Se,pt,"variable"),Se=pt,re=pt;continue}}if(!de&&(we==="*"||we==="?"||we==="[")){K.push(re,Se,"literal"),K.push(Se,Se+1,"glob"),Se++,re=Se;continue}Se++}return K.push(re,j,"literal"),K.parts}function qo(G,U){if(U==="command-substitution"||G==="command-substitution")return"command-substitution";if(U==="arithmetic"||G==="arithmetic")return"arithmetic";if(U==="variable"||G==="variable")return"variable";if(U==="glob"||G==="glob")return"glob";return G}function bC(G,U,j){return U+1>=j||Ko(G[U+1]??"")||rs(G,U+1)!==null}var CC=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),SC=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function vC(G){let U=0;while(U<=G.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(G[U]?.text??""))U++;if(U===G.length)return!0;let j=EC(G,U);if(j===void 0||j===null)return!1;U=j}return!1}function EC(G,U){let j=G[U]?.text.toLowerCase();if(j==="command")return RC(G,U);if(j==="env")return xC(G,U);if(j==="sudo")return _C(G,U);return}function RC(G,U){if(G[U+1]?.text==="-v")return null;for(let j=U+1;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return j+1;if(K==="-p"||K==="-v"||K==="-V"||/^-[pvV]+$/.test(K))continue;return j}return G.length}function xC(G,U){for(let j=U+1;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return j+1;if(CC.has(K)){if(G[j+1]===void 0)return null;j++;continue}if(K.startsWith("-u=")||K.startsWith("--unset=")||K.startsWith("-C")&&K.length>2||K.startsWith("--chdir=")||K.startsWith("-S")&&K.length>2||K.startsWith("--split-string=")||K.startsWith("-P"))continue;if(K.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(K))continue;return j}return G.length}function _C(G,U){for(let j=U+1;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return j+1;if(SC.has(K)){if(G[j+1]===void 0)return null;j++;continue}if(K.startsWith("-"))continue;return j}return G.length}function $d(G,U,j,K){if(G.provenance!=="literal"||!G.raw.includes("{"))return;let re=Bd(G.raw,U,j,K,!0);if(!re)return;if("limited"in re)return{limited:!0};let oe=re.values.map((de)=>Ud(de,j));if(oe.some((de)=>de===null))return{limited:!0};return{words:[...new Set(oe.filter((de)=>de!==null&&de!==""))]}}function wC(G,U,j,K,re){if(U.provenance!=="literal"||!U.raw.includes("{"))return;let oe=Bd(U.raw,j,K,re,!1);if(!oe)return;if("limited"in oe){if(oe.limited==="expansions")return{limitCode:"depth-limit"};return{limitCode:oe.limited==="length"?"brace-expansion-limit":"word-limit"}}let de=oe.values.map((Se)=>Ud(Se,K));if(de.some((Se)=>Se===null))return;return{words:de.filter((Se)=>Se!==null&&Se!=="").map((Se)=>to(G,U.span.start,U.span.end,Se,"literal",!1))}}function Bd(G,U,j,K,re){let oe=[G],de=G.length,Se=0;while(!0){let we=oe.findIndex((pt)=>kd(pt,re));if(we===-1)break;if(++Se>j)return{limited:"expansions"};let We=oe[we]??"",mt=kd(We,re);if(!mt||mt.kind==="range")return{limited:"expansions"};let gt=mt.start+We.length-mt.end,ft=mt.alternatives.reduce((pt,ht)=>pt+gt+ht.length,0);if(de-We.length+ft>K)return{limited:"length"};if(oe.length-1+mt.alternatives.length>U)return{limited:"words"};oe.splice(we,1,...PC(We,mt)),de+=ft-We.length}return Se===0?void 0:{values:oe}}function kd(G,U){let j=[],K,re=null,oe=!1;for(let de=0;de<G.length;de++){let Se=G[de];if(oe){oe=!1;continue}if(Se==="\\"&&re!=="'"){oe=!0;continue}if(Se===re){re=null;continue}if(re===null&&(Se==="'"||Se==='"')){re=Se;continue}if(re!==null)continue;if(Se==="{"){j.push({start:de,commas:[]});continue}if(Se===","&&j.length>0){j.at(-1)?.commas.push(de);continue}if(Se!=="}"||j.length===0)continue;let we=j.pop();if(!we)continue;let We=we.commas.length>0?{kind:"alternatives",start:we.start,end:de+1,commas:we.commas}:U&&TC(G.slice(we.start+1,de))?{kind:"range",start:we.start,end:de+1}:void 0;if(We&&(!K||We.start<K.start))K=We}if(!K||K.kind==="range")return K;return{kind:K.kind,start:K.start,end:K.end,alternatives:AC(G,K)}}function PC(G,U){return U.alternatives.map((j)=>`${G.slice(0,U.start)}${j}${G.slice(U.end)}`)}function AC(G,U){let j=[U.start,...U.commas,U.end-1];return j.slice(0,-1).map((K,re)=>G.slice(K+1,j[re+1]))}function TC(G){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(G)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(G)}function Ud(G,U){let j=`x${G}`,K=dl(j,0,j.length,{maxInputLength:j.length,maxWords:1,maxDepth:U},{wordsUsed:0,maxWords:1,quotedExpansionEnd:1/0},0);if(K.limited||K.issues.length>0||K.next!==j.length||K.word.provenance!=="literal")return null;return K.word.text.slice(1)}function IC(G,U,j,K){return mn({kind:"program",dialect:"posix",source:G.slice(U,j),span:{start:U,end:j},status:"limited",issues:[{code:K,message:"command structure exceeds parser limit"}],nodes:[]})}function no(G,U,j,K,re){return{nodes:G,issues:[...U,{code:K,message:`command structure exceeds parser limit ${re}`}],next:j,closed:!1,limited:!0,pendingHeredocs:[]}}function ts(G,U,j){return{nodes:G,issues:U,next:j,closed:!1,limited:!0,pendingHeredocs:[]}}function cl(G){return G.wordsUsed++,G.wordsUsed<=G.maxWords}function kC(G,U,j){let K=G.slice(U,j),re=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(K)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(K),oe=re?.[1];if(!re||!oe)return;return{name:oe,braceIndex:U+re[0].lastIndexOf("{")}}function Yo(G){return G.some((U)=>{if(U.kind==="command")return U.redirections.some((j)=>j.heredoc)||U.nested.some((j)=>Yo(j.nodes));return(U.kind==="group"||U.kind==="function")&&Yo(U.body.nodes)})}function OC(G){return G.map((U)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${U.delimiter} was not found`}))}function Hd(G){return G?.kind==="command"||G?.kind==="group"||G?.kind==="function"}function Od(G,U){let j=G.at(-1);if(j?.kind!=="connector"||!Md.has(j.operator))return;U.push({code:"missing-command-after-connector",message:`connector ${j.operator} requires a following command`})}function jd(G){return G?.provenance==="literal"&&!G.quoted&&G.raw===G.text&&oC.has(G.text)}function ul(G,U){let j=G.at(-1);if(!Hd(j))return;if(j?.kind==="command"&&jd(j.words[0]))return;U.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function MC(G,U,j){return U===j||/[\s;&|()]/u.test(G[U-1]??"")}var qd=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),DC=new Set(["gc","cat","type","cp","mv","rm"]),Kd=["-rec","-for","-path","-literalpath","-whatif"],NC=/^\$env:\w/i,LC=/^(?:\$\{?\w+\}?|~)\\./;function Yd(G,U){let j=G.toLowerCase().replaceAll("`","");if(![...qd].some((re)=>j.includes(re))&&!(j.includes("rm")&&Kd.some((re)=>j.includes(re)))&&!j.includes("<#")&&!WC(j))return!1;let K=bl(G,U);if(Zd(K))return!1;return K.issues.some((re)=>re.code==="unclosed-block-comment"||re.code==="comment-depth-limit")||yl(K).some(FC)}function Zd(G){return G.nodes.some((U)=>{if(U.kind==="group")return Zd(U.body);if(U.kind!=="command")return!1;return U.redirections.some((j)=>j.operator==="<<")})}function WC(G){if(G.includes("$env:"))return!0;return G.includes("\\")&&(G.includes("$")||G.includes("~"))}function FC(G){let U=G[0]==="&"||G[0]==="."?1:0,j=G[U]?.toLowerCase();if(j&&qd.has(j))return!0;let K=G.slice(U+1);if(j&&DC.has(j)&&K.some(GC))return!0;if(j!=="rm")return!1;return K.some((re)=>{let oe=re.toLowerCase().split(":",1)[0]??"";return Kd.some((de)=>oe.startsWith(de))})}function GC(G){return NC.test(G)||LC.test(G)}function bl(G,U){let j={start:0,end:G.length};if(G.length>U.maxInputLength)return mn({kind:"program",dialect:"powershell",source:G,span:j,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${U.maxInputLength} UTF-16 code units`}],nodes:[]});let K=Cl(G,0,G.length,U,0);return mn({kind:"program",dialect:"powershell",source:G,span:j,status:HC(K.issues,K.limited),issues:K.issues,nodes:K.nodes})}function Cl(G,U,j,K,re,oe=!1){let de=[],Se=[],we=Xi(),We=0,mt=!1,gt=()=>{if(we.words.length===0&&we.redirections.length===0)return;let pt={start:we.start,end:we.end};Ji(de,we,{kind:"command",dialect:"powershell",source:G.slice(pt.start,pt.end),span:pt,words:we.words,redirections:we.redirections,nested:we.nested,displayText:we.words.map((ht)=>ht.text).join(" ")})},ft=U;while(ft<j){let pt=G[ft];if(!pt)break;if(oe&&pt==="}")return gt(),{nodes:de,issues:Se,next:ft+1,closed:!0,words:We,limited:mt};let ht=UC(G,ft,j,K.maxDepth);if(ht){if(ht.issue)Se.push(ht.issue);if(ht.limited)return gt(),{nodes:de,issues:Se,next:ht.next,closed:!1,words:We,limited:!0};ft=ht.next;continue}if(/\s/.test(pt)){if(pt==="\r"||pt===`
22
+ `){gt();let Ct=pt==="\r"&&G[ft+1]===`
23
+ `?ft+2:ft+1;de.push(gl(G,ft,Ct)),ft=Ct;continue}ft++;continue}let yt=Qd(G,ft);if(yt){gt(),de.push(gl(G,ft,ft+yt.length)),ft+=yt.length;continue}if(pt==="{"){if(gt(),re>=K.maxDepth)return Se.push(Jd(K.maxDepth)),{nodes:de,issues:Se,next:j,closed:!1,words:We,limited:!0};let Ct=Cl(G,ft+1,j,K,re+1,!0),vt=Ct.closed?Ct.next-1:Ct.next,St=mn({kind:"program",dialect:"powershell",source:G.slice(ft+1,vt),span:{start:ft+1,end:vt},status:Ct.limited?"limited":Ct.issues.length>0?"partial":"complete",issues:Ct.issues,nodes:Ct.nodes});if(de.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:ft,end:Ct.next}),body:St})),Se.push(...Ct.issues),!Ct.closed)Se.push({code:"unclosed-script-block",message:"PowerShell script block is not closed"});We+=Ct.words,mt||=Ct.limited,ft=Ct.next;continue}if(pt==="}"){gt(),de.push(gl(G,ft,ft+1)),ft++;continue}if(pt===">"||pt==="<"){we.start=we.start===-1?ft:we.start;let Ct=G[ft+1]===pt?ft+2:ft+1,vt=Ct;while(/[ \t]/.test(G[vt]??""))vt++;let St=vt<j?Vd(G,vt,j,K,re):void 0,Rt=St?.next??Ct;if(we.redirections.push(Object.freeze({kind:"redirection",operator:G.slice(ft,Ct),span:Object.freeze({start:ft,end:Rt}),...St?{target:St.word}:{}})),St)Se.push(...St.issues),we.nested.push(...St.nested),We+=St.words,mt||=St.limited;we.end=Rt,ft=Rt;continue}if(pt===","){we.start=we.start===-1?ft:we.start,we.words.push(sl({text:",",raw:",",span:{start:ft,end:ft+1},provenance:"literal",quoted:!1})),we.end=++ft;continue}let bt=Vd(G,ft,j,K,re);if(we.start=we.start===-1?ft:we.start,we.end=bt.next,we.words.push(bt.word),Se.push(...bt.issues),we.nested.push(...bt.nested),We+=1+bt.words,mt||=bt.limited,We>K.maxWords)return Se.push({code:"word-limit",message:`command exceeds ${K.maxWords} words`}),gt(),{nodes:de,issues:Se,next:bt.next,closed:!1,words:We,limited:!0};ft=bt.next>ft?bt.next:ft+1}return gt(),{nodes:de,issues:Se,next:ft,closed:!oe,words:We,limited:mt}}function Vd(G,U,j,K,re){let oe="",de="literal",Se=!1,we=[],We=[],mt=0,gt=!1,ft=(ht)=>{let yt=zC(G,ht,j,K,re);return oe+=G.slice(ht,yt.next),We.push(yt.program),we.push(...yt.program.issues),mt+=hl(yt.program),gt||=yt.program.status==="limited",de="command-substitution",yt.next},pt=U;while(pt<j){let ht=G[pt];if(!ht||/\s/.test(ht)||Qd(G,pt)||ht===">"||ht==="<"||ht==="#")break;if(ht===",")break;if(ht==="`"){let yt=G[pt+1];if(!yt){we.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),pt++;break}oe+=yt,pt+=2;continue}if(G.startsWith("$(",pt)){pt=ft(pt);continue}if(ht==="'"){Se=!0,pt++;let yt=!1;while(pt<G.length){if(G[pt]==="'"&&G[pt+1]==="'"){oe+="'",pt+=2;continue}if(G[pt]==="'"){yt=!0,pt++;break}oe+=G[pt]??"",pt++}if(!yt)we.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(ht==='"'){Se=!0,pt++;let yt=!1;while(pt<j){let bt=G[pt];if(bt==="`"&&G[pt+1]){oe+=G[pt+1],pt+=2;continue}if(bt==='"'){yt=!0,pt++;break}if(G.startsWith("$(",pt)){pt=ft(pt);continue}if(bt==="$")de=G[pt+1]==="("?"command-substitution":"variable";oe+=bt??"",pt++}if(!yt)we.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(ht==="$")de=G[pt+1]==="("?"command-substitution":"variable";if(ht==="@"&&pt===U)de="variable";oe+=ht,pt++}return{word:to(G,U,pt,oe,de,Se,de==="literal"?void 0:$C(G,U,pt)),next:pt,issues:we,nested:We,words:mt,limited:gt}}function zC(G,U,j,K,re){let oe=Xd(G,U+2,j),de=oe===-1?j:oe,Se=oe===-1?j:oe+1;if(re>=K.maxDepth)return{program:mn({kind:"program",dialect:"powershell",source:G.slice(U+2,de),span:{start:U+2,end:de},status:"limited",issues:[Jd(K.maxDepth)],nodes:[]}),next:Se};let we=Cl(G,U+2,de,K,re+1),We=oe===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:mn({kind:"program",dialect:"powershell",source:G.slice(U+2,de),span:{start:U+2,end:de},status:we.limited?"limited":we.issues.length+We.length>0?"partial":"complete",issues:[...we.issues,...We],nodes:we.nodes}),next:Se}}function Xd(G,U,j){let K=1,re=!1,oe=!1;for(let de=U;de<j;de++){let Se=G[de];if(Se==="`"){de++;continue}if(!oe&&Se==="'"){if(re&&G[de+1]==="'"){de++;continue}re=!re;continue}if(!re&&Se==='"'){oe=!oe;continue}if(re)continue;if(G.startsWith("$(",de)){K++,de++;continue}if(!oe&&Se==="(")K++;if(Se!==")")continue;if(K--,K===0)return de}return-1}function hl(G){let U=0;for(let j of G.nodes){if(j.kind==="group")U+=hl(j.body);if(j.kind==="command"){U+=j.words.length;for(let K of j.nested)U+=hl(K)}}return U}function $C(G,U,j){let K=Qi(G),re=U,oe=!1,de=U;while(de<j){let Se=G[de];if(Se==="`"){de+=2;continue}if(Se==="'"){if(oe&&G[de+1]==="'"){de+=2;continue}oe=!oe,de++;continue}if(oe){de++;continue}if(G.startsWith("$(",de)){let we=Xd(G,de+2,j),We=we===-1?j:we+1;K.push(re,de,"literal"),K.push(de,We,"command-substitution"),de=We,re=We;continue}if(Se==="$"||Se==="@"&&de===U){let we=BC(G,de+1,j);K.push(re,de,"literal"),K.push(de,we,"variable"),de=we,re=we;continue}de++}return K.push(re,j,"literal"),K.parts}function BC(G,U,j){if(G[U]==="{"){let re=G.indexOf("}",U+1);return re===-1||re>=j?j:re+1}let K=U;while(K<j&&/[A-Za-z0-9_:?]/.test(G[K]??""))K++;return K}function Jd(G){return{code:"depth-limit",message:`command structure exceeds parser limit ${G}`}}function yl(G){return G.nodes.flatMap((U)=>{if(U.kind==="group")return yl(U.body);if(U.kind!=="command")return[];return[[...U.words,...U.redirections.flatMap((j)=>j.target?[j.target]:[])].sort((j,K)=>j.span.start-K.span.start).filter((j)=>j.text!==""&&j.raw!==",").map((j)=>j.text),...U.nested.flatMap(yl)]})}function Qd(G,U){for(let j of["&&","||",";","|"])if(G.startsWith(j,U))return j;return null}function UC(G,U,j,K){if(G[U]==="#"&&G[U+1]!==">"){let de=U+1;while(de<j&&G[de]!=="\r"&&G[de]!==`
24
+ `)de++;return{next:de,limited:!1}}if(!G.startsWith("<#",U))return null;let re=1,oe=U+2;while(oe<j){if(G.startsWith("<#",oe)){if(re++,re>K)return{next:j,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${K}`},limited:!0};oe+=2;continue}if(G.startsWith("#>",oe)){if(re--,oe+=2,re===0)return{next:oe,limited:!1};continue}oe++}return{next:j,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function HC(G,U){if(U)return"limited";if(G.some((j)=>j.code==="unclosed-block-comment"))return"invalid";return G.length>0?"partial":"complete"}function gl(G,U,j){return Object.freeze({kind:"connector",operator:G.slice(U,j),span:Object.freeze({start:U,end:j})})}function y(G,U="auto",j=cr){if(U==="powershell"||U==="auto"&&Yd(G.slice(0,j.maxInputLength),j))return bl(G,j);return Dd(G,j)}function t(G){return G.provenance==="command-substitution"?G.raw:G.text}function ne(G,U){return G==="posix"?U:jt(U.map((j)=>j.text))}function ro(G,U){return G&&G.provenance!=="unknown"?G.provenance==="literal":!/[$`*?[\]]/.test(U)}function jt(G){return G.map((U)=>({kind:"word",text:U,raw:U,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function Sl(G,U){return{value:G,work:U}}function xt(G,U){if(G.work)G.work.units=Math.min(Number.MAX_SAFE_INTEGER,G.work.units+1);return G.value[U]}function qt(G){return G.value.length}function Xo(G,U,j=1){if(G)G.units=Math.min(Number.MAX_SAFE_INTEGER,G.units+U.length*j)}function Rn(G,U){Xo(G,U)}function Ir(G){if(!G)return!1;let U=G.charCodeAt(0);return U>=48&&U<=57||U>=65&&U<=90||U===95||U>=97&&U<=122}function Ut(G){if(!G)return!1;let U=G.charCodeAt(0);return U===9||U===10||U===11||U===12||U===13||U===32||U===160||U===65279||U===5760||U>=8192&&U<=8202||U===8232||U===8233||U===8239||U===8287||U===12288}function vl(G){return G===`
25
+ `||G==="\r"||G==="\u2028"||G==="\u2029"}function Ht(G,U,j){if(U+j.length>qt(G))return!1;for(let K=0;K<j.length;K++)if(xt(G,U+K)!==j[K])return!1;return!0}function Xn(G,U,j){return!Ir(xt(G,U-1))&&Ht(G,U,j)&&!Ir(xt(G,U+j.length))}function Jn(G,U){return Ir(xt(G,U-1))!==Ir(xt(G,U))}function nn(G){return G===`
26
+ `||G===";"||G==="&"||G==="|"}function oo(G){return G==="|"||G===";"}function ss(G,U,j){let K=Sl(G,j);if(U==="rm")return jC(K);if(U==="dd")return qC(K);return im(K,!0)}function as(G,U,j){let K=Sl(G,j);if(U==="rm")return KC(K);if(U==="reset-hard")return rm(K,"--ha","rd");if(U==="reset-merge")return rm(K,"--me","rge");if(U==="clean")return JC(K);if(U==="checkout")return eS(K);if(U==="push-force")return tS(K);if(U==="push-refspec")return nS(K);if(U==="push-delete")return rS(K);if(U==="branch")return oS(K);if(U==="tag")return aS(K);if(U==="restore")return lS(K);return im(K,!1)}function jC(G){let U=!1,j=!1,K=!1,re=-1;for(let oe=0;oe<=qt(G);oe++){let de=xt(G,oe);if(!U){let we=xt(G,oe+2);if(Xn(G,oe,"rm")&&Ut(we)&&we!==`
27
+ `)U=!0,oe++;continue}let Se=VC(G,oe);if(de===`
28
+ `||Se!==-1){if(U=!1,j=!1,K=!1,re=-1,Se!==-1)oe=Se-1;continue}if(de===";"||de==="&"||de==="|"||oe===qt(G)){if(re>=0){let we=em(G,re,oe);j||=we.recursive,K||=we.force}if(j&&K)return!0;U=!1,j=!1,K=!1,re=-1;continue}if(Ut(de)){if(re<0)continue;if(Ht(G,re,"--")&&oe-re===2){U=!1,j=!1,K=!1,re=-1;continue}let we=em(G,re,oe);if(j||=we.recursive,K||=we.force,j&&K)return!0;re=-1;continue}if(re<0)re=oe}return!1}function VC(G,U){if(xt(G,U)!=="\\"||xt(G,U-1)==="\\")return-1;if(Ht(G,U,String.raw`\n`))return U+2;if(Ht(G,U,String.raw`\x0a`)||Ht(G,U,String.raw`\x0A`))return U+5;if(Ht(G,U,String.raw`\u000a`)||Ht(G,U,String.raw`\u000A`))return U+7;return Ht(G,U,String.raw`\012`)?U+4:-1}function em(G,U,j){if(tm(G,U,j,"recursive"))return{recursive:!0,force:!1};if(tm(G,U,j,"force"))return{recursive:!1,force:!0};if(xt(G,U)!=="-"||xt(G,U+1)==="-")return{recursive:!1,force:!1};let K=!1,re=!1;for(let oe=U+1;oe<j;oe++){let de=xt(G,oe);K||=de==="r"||de==="R",re||=de==="f"||de==="F"}return{recursive:K,force:re}}function tm(G,U,j,K){let re=j-U-2;if(re<1||re>K.length||!Ht(G,U,"--"))return!1;for(let oe=0;oe<re;oe++)if(xt(G,U+oe+2)!==K[oe])return!1;return!0}function qC(G){let U=!1;for(let j=0;j<qt(G);j++){if(nn(xt(G,j))){U=!1;continue}if(Xn(G,j,"dd")){U=!0,j++;continue}if(!U||!Xn(G,j,"of")||!Ht(G,j,"of=/dev/"))continue;let K=j+8;if(K<qt(G)&&!Ut(xt(G,K))&&xt(G,K)!=="'"&&xt(G,K)!=='"')return!0}return!1}function KC(G){let U=!1,j=!1,K=!1;for(let re=0;re<=qt(G);){let oe=xt(G,re);if(re===qt(G)||nn(oe)){U=!1,j=!1,K=!1,re++;continue}let de=ZC(G,re);if(de>=0){if(YC(G,de))return!0;let Se=de,we=!1;while(Ut(xt(G,Se)))we||=xt(G,Se)===`
29
+ `,Se++;if(we)j=!1,K=!1;U=!0,re=Se;continue}if(!U){re++;continue}if(Ht(G,re,"--")&&(re===0||Ut(xt(G,re-1)))&&(!xt(G,re+2)||Ut(xt(G,re+2))||nn(xt(G,re+2)))){U=!1,j=!1,K=!1,re+=2;continue}if(j||=Ht(G,re,"--recursive")&&Jn(G,re+11)||El(G,re,"recursive"),K||=Ht(G,re,"--force")&&Jn(G,re+7)||El(G,re,"force"),j&&K)return!0;re++}return!1}function El(G,U,j){if(!Ht(G,U,"--"))return!1;let K=0;while(K<=j.length){let re=xt(G,U+K+2);if(!re||Ut(re)||nn(re))break;if(re!==j[K])return!1;K++}return K>0&&Jn(G,U+K+2)}function YC(G,U){let j=U,K=!1,re=!1;while(j<qt(G)){while(Ut(xt(G,j)))j++;let oe=j;while(j<qt(G)&&!Ut(xt(G,j)))j++;if(xt(G,oe)!=="-"||j-oe===2&&Ht(G,oe,"--"))return!1;let de=nm(G,oe,"recursive"),Se=nm(G,oe,"force");if(K&&Se||re&&de)return!0;if(K||=de,re||=Se,xt(G,oe+1)==="-")continue;let we=XC(G,oe,j);if(we.combined||K&&we.forceAtBoundary||re&&we.recursiveAtBoundary)return!0;K||=we.recursive,re||=we.force}return!1}function nm(G,U,j){return Ht(G,U,`--${j}`)&&Jn(G,U+j.length+2)||El(G,U,j)}function ZC(G,U){if(U>0&&Ir(xt(G,U-1)))return-1;let j=U;if(xt(G,j)==="\\")j++;if(xt(G,j)!=="r")return-1;if(j++,xt(G,j)==="\\")j++;if(xt(G,j)!=="m"||!Ut(xt(G,j+1)))return-1;return j+1}function XC(G,U,j){let K=!1,re=!1,oe=!1,de=!1,Se=!1;if(xt(G,U)!=="-")return{recursive:K,force:re,recursiveAtBoundary:oe,forceAtBoundary:de,combined:Se};let we="";for(let We=U+1;We<j;We++){let mt=xt(G,We)??"",gt=(mt==="r"||mt==="f")&&Jn(G,We+1);K||=mt==="r",re||=mt==="f",oe||=mt==="r"&&gt,de||=mt==="f"&&gt,Se||=(we==="r"&&mt==="f"||we==="f"&&mt==="r")&&gt,we=mt}return{recursive:K,force:re,recursiveAtBoundary:oe,forceAtBoundary:de,combined:Se}}function rm(G,U,j){return Qo(G,"reset",oo,!0,(K)=>xt(G,K)==="-"&&io(G,K,U,j)?!0:K)}function JC(G){return Qo(G,"clean",oo,!0,(U)=>{if(xt(G,U)!=="-")return U;if(io(G,U,"--fo","rce"))return!0;let j=Jo(G,U,oo);for(let K=U+1;K<j;K++)if(xt(G,K)==="f")return!0;return j-1})}function ls(G,U,j){if(!Xn(G,U,"git"))return null;let K=U+3;if(!Ut(xt(G,K)))return{commandEnd:-1,next:K};while(Ut(xt(G,K)))K++;while(K<qt(G)){if(nn(xt(G,K)))return{commandEnd:-1,next:K};let re=Jo(G,K,nn);if(Xn(G,K,j))return{commandEnd:K+j.length,next:re};if(xt(G,K)!=="-")return{commandEnd:-1,next:re};let oe=re-K===2&&Ht(G,K,"--"),de=QC(G,K,re);K=re;while(Ut(xt(G,K)))K++;if(oe)return{commandEnd:Xn(G,K,j)?K+j.length:-1,next:Jo(G,K,nn)};if(!de)continue;if(K>=qt(G)||nn(xt(G,K)))return{commandEnd:-1,next:K};K=Jo(G,K,nn);while(Ut(xt(G,K)))K++}return{commandEnd:-1,next:K}}function QC(G,U,j){for(let K of Sn)if(j-U===K.length&&Ht(G,U,K))return!0;return!1}function eS(G){return om(G,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function tS(G){return Qo(G,"push",oo,!0,(U)=>{if(xt(G,U)!=="-")return U;if(xt(G,U+1)==="f"&&!Ir(xt(G,U+2))&&!Ht(G,U+2,"-with-lease"))return!0;let j=sm(G,U,"--fo","rce");if(j>=0&&!Ht(G,j,"-with-lease"))return!0;return U})}function nS(G){return Qo(G,"push",nn,!1,(U)=>{if(Ut(xt(G,U))&&xt(G,U+1)==="+"&&U+2<qt(G)&&!nn(xt(G,U+2))&&!Ut(xt(G,U+2)))return!0;if(xt(G,U)===":"&&xt(G,U+1)==="+")return!0;return U})}function rS(G){return Qo(G,"push",nn,!1,(U)=>{if(xt(G,U)==="-"&&io(G,U,"--de","lete"))return!0;if(Ut(xt(G,U))&&xt(G,U+1)===":"&&U+2<qt(G)&&!Ut(xt(G,U+2))&&!nn(xt(G,U+2)))return!0;return U})}function oS(G){let U=!1,j=!1,K=!1;for(let re=0;re<=qt(G);re++){if(re===qt(G)||nn(xt(G,re))){if(j&&K)return!0;U=!1,j=!1,K=!1;continue}if(!U){let Se=ls(G,re,"branch");if(Se){U=Se.commandEnd>=0,re=Math.max(re,(U?Se.commandEnd:Se.next)-1);continue}}if(!U||xt(G,re)!=="-")continue;let oe=Jo(G,re,nn),de=iS(G,re,oe);if(j||=de.deletion,K||=de.force,j&&K)return!0;re=oe-1}return!1}function iS(G,U,j){let K=!1,re=!1;for(let oe=U;oe<j;oe++){if(xt(G,oe)!=="-")continue;if(io(G,oe,"--de","lete"))K=!0;if(io(G,oe,"--fo","rce"))re=!0;if(xt(G,oe+1)==="-")continue;let de=oe+1,Se=!1,we=!1,We=!1;while(de<j&&sS(xt(G,de))){let mt=xt(G,de);Se||=mt==="d"||mt==="D",we||=mt==="f",We||=mt==="D",de++}if(!Jn(G,de))continue;K||=Se,re||=we||We}return{deletion:K,force:re}}function sS(G){if(!G)return!1;let U=G.charCodeAt(0);return U>=65&&U<=90||U>=97&&U<=122}function aS(G){return om(G,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function om(G,U){let j=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let K=0;K<qt(G);K++){let re=xt(G,K),oe=j[j.length-1];if(!oe)return!1;let de=oe.escaped;if(oe.escaped=!de&&oe.quote!=="'"&&re==="\\",!de&&re==="'"&&oe.quote!=='"')oe.quote=oe.quote==="'"?"":"'";if(!de&&re==='"'&&oe.quote!=="'")oe.quote=oe.quote==='"'?"":'"';if(re==="$"&&xt(G,K+1)==="("&&(j.length===1||!de&&oe.quote!=="'")){j.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),K++;continue}if(!de&&!oe.quote&&j.length>1&&re==="("){oe.depth++;continue}if(!de&&!oe.quote&&j.length>1&&re===")"){if(oe.depth--,oe.depth===0)j.pop();continue}if(Ut(re))oe.shortActive=!1,oe.hasShortFlag=!1;if(!oe.outerActive){let Se=ls(G,K,U.command);if(Se){oe.outerActive=Se.commandEnd>=0&&Ut(xt(G,Se.commandEnd)),oe.shortActive=!1,oe.hasShortFlag=!1,K=Math.max(K,(oe.outerActive?Se.commandEnd:Se.next)-1);continue}}if(oe.outerActive&&re==="-"){if(io(G,K,U.longPrefix,U.longOptional))return!0;oe.shortActive||=!U.excludedShortStarts.includes(xt(G,K+1)??"")}if(oe.hasShortFlag||=oe.shortActive&&re===U.shortFlag,oe.hasShortFlag&&Jn(G,K+1))return!0;if(oo(re))oe.outerActive=!1}return!1}function Qo(G,U,j,K,re){let oe=!1;for(let de=0;de<qt(G);de++){let Se=xt(G,de),we=j(Se);if(!oe&&!we){let We=ls(G,de,U);if(We){oe=We.commandEnd>=0&&(!K||Ut(xt(G,We.commandEnd))),de=Math.max(de,(oe?We.commandEnd:We.next)-1);continue}}if(oe){let We=re(de);if(We===!0)return!0;for(let mt=de;mt<=We;mt++)if(j(xt(G,mt)))oe=!1;de=We}if(we)oe=!1}return!1}function lS(G){let U=!1;for(let j=0;j<qt(G);j++){if(vl(xt(G,j))){if(U)return!0;U=!1;continue}if(!U){let K=ls(G,j,"restore");if(K){U=K.commandEnd>=0,j=Math.max(j,(U?K.commandEnd:K.next)-1);continue}}if(U&&xt(G,j)==="-"&&xt(G,j+1)==="-"&&(Ht(G,j+2,"staged")||Ht(G,j+2,"help")))U=!1}return U}function im(G,U){let j=!1;for(let K=0;K<qt(G);K++){let re=xt(G,K),oe=U?vl(re):nn(re);if(j&&Ut(re)&&xt(G,K+1)==="-"&&Xn(G,K+2,"delete"))return!0;if(oe){j=!1;continue}if(Xn(G,K,"find"))j=!0,K+=3}return!1}function Jo(G,U,j){let K=U;while(K<qt(G)&&!Ut(xt(G,K))&&!j(xt(G,K)))K++;return K}function sm(G,U,j,K){if(!Ht(G,U,j))return-1;let re=U+j.length;for(let oe=0;oe<K.length&&xt(G,re)===K[oe];oe++)re++;return Jn(G,re)?re:-1}function io(G,U,j,K){return sm(G,U,j,K)>=0}function In(G,U){Xo(U,G,2);let j=G.toLowerCase(),K=j.trimStart(),re=K.startsWith("echo ")||K.startsWith("rg "),oe=[{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 de of oe){if(de.skipForEchoRg&&re)continue;let Se=de.caseSensitive?G:j;if(de.regex)Rn(U,Se);if((de.regex?.test(Se)??!1)||de.scan&&as(Se,de.scan,U))return _t("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${de.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var cS=/^[A-Za-z_][A-Za-z0-9_]*=/;function lm(G,U,j){let K=G.words[0];if(!U||!K||G.words.length!==1||G.dialect!=="posix")return!1;if(!K.quoted||K.provenance!=="literal")return!1;let re=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(K.text)?.[1];if(!re)return!1;Xo(j,U.source,2);let oe={anchored:new RegExp(`^\\$\\{?${re}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${re}(?![A-Za-z0-9_])`)};return cm(U.nodes,K,oe)}function cm(G,U,j){return G.every((K)=>{if(K.kind==="connector")return!0;if(K.kind==="group"||K.kind==="function")return cm(K.body.nodes,U,j);if(K.kind==="unknown")return!j.loose.test(K.source);return uS(K,U,j)})}function uS(G,U,j){if(G.nested.some((re)=>j.loose.test(re.source)))return!1;let K=G.words.findIndex((re)=>!cS.test(re.text));return G.words.every((re,oe)=>re===U||am(re.raw,j.anchored,oe!==K))&&G.redirections.every((re)=>(!re.heredoc||re.heredoc.quotedDelimiter||!j.loose.test(re.heredoc.body))&&(!re.target||am(re.target.raw,j.anchored,!0)))}function am(G,U,j){let K=!1,re=!1;for(let oe=0;oe<G.length;oe++){let de=G[oe];if(de==="\\"&&!K){oe++;continue}if(!re&&de==="'"){K=!K;continue}if(!K&&de==='"'){re=!re;continue}if(K||de!=="$")continue;if(!U.test(G.slice(oe)))continue;if(!re||!j)return!1}return!0}import{isAbsolute as dS,resolve as um}from"node:path";function ei(G,U,j,K){let re=dS(G)?um(G):U?um(U,G):void 0;if(!re)return;try{return Nt(re,j,K)}catch{return re}}function dm(G){return!["/dev","/proc","/sys"].some((U)=>G===U||G.startsWith(`${U}/`))}var so="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",ti="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.",xl=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),mS=new Set(["-p","--print"]),fS=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),pS=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"])]]),gS=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),hS=new Map([["python",new Set(["m"])]]),yS=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"])]]),bS=new Set(["always","default","never"]),CS=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),SS=/\\\r?\n/g,vS=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 mm(G){return us(G).code}function cs(G){return us(G).sources}function fm(G){return vS.get(wl(G))??[]}function us(G){let U=wl(G[0]??"");if(!xl.has(U))return{code:null,sources:[],optionsOpen:!1};let j=[],K=[],re=!0;for(let oe=1;oe<G.length;oe++){let de=G[oe];if(de===void 0)break;if(de==="--")return Ln(U,j,K,re,G[oe+1]===void 0?void 0:oe+1,G[oe+1]);if(de===""||de==="-"||!de.startsWith("-"))return Ln(U,j,K,re,oe,de);if(U==="node"&&mS.has(de)){let gt=G[oe+1];if(gt===void 0)return Ln(U,j,K,re);if(gt.startsWith("-"))continue;j.push({tokenIndex:oe+1,value:gt}),K.push({tokenIndex:oe+1,kind:"inline-code",value:gt}),oe++;continue}if(RS(U,de)){let gt=G[oe+1];if(gt===void 0)return Ln(U,j,K,re);if(j.push({tokenIndex:oe+1,value:gt}),K.push({tokenIndex:oe+1,kind:"inline-code",value:gt}),U==="python")return Ln(U,j,K,re);oe++;continue}let Se=/^--eval=(.*)$/s.exec(de);if(xS(U)&&Se){let gt=Se[1]??"";j.push({tokenIndex:oe,value:gt}),K.push({tokenIndex:oe,kind:"inline-code",value:gt});continue}if(U==="node"){let gt=ES(de);if(gt){if(gt.attached){if(re&&=gt.value!=="",gt.value!=="")K.push({tokenIndex:oe,kind:"module-file",value:gt.value});continue}let ft=G[oe+1];if(ft===void 0||ft.startsWith("-"))return re=!1,Ln(U,j,K,re);K.push({tokenIndex:oe+1,kind:"module-file",value:ft}),oe++;continue}}if(U==="python"&&de.startsWith("--check-hash-based-pycs=")||U==="node"&&(de==="--conditions="||de==="--diagnostic-dir="||de==="--title=")||U==="ruby"&&(de==="--disable="||de==="--enable="))return Ln(U,j,K,re);if(yS.get(U)?.has(de)){let gt=G[oe+1];if(gt===void 0||gt.startsWith("-")&&!(U==="ruby"&&CS.has(de))||U==="python"&&!bS.has(gt))return Ln(U,j,K,re);oe++;continue}if(de.startsWith("--"))continue;let we,We=!1;for(let gt=1;gt<de.length;gt++){let ft=de[gt];if(ft===void 0)break;if(hS.get(U)?.has(ft)){let pt=de.slice(gt+1),ht=pt||G[oe+1];if(ht!==void 0)K.push({tokenIndex:pt?oe:oe+1,kind:"module-file",value:ht});return Ln(U,j,K,re)}if(fS.get(U)?.has(ft)){we=de.slice(gt+1)||G[oe+1],We=gt+1===de.length;break}if(U==="node"&&ft==="r"){if(re&&=de==="-r",de==="-r"){let pt=G[oe+1];if(re&&=pt!==void 0&&!pt.startsWith("-"),re&&pt!==void 0)K.push({tokenIndex:oe+1,kind:"module-file",value:pt});oe++}break}if(U==="ruby"&&ft==="r"){let pt=de.slice(gt+1),ht=pt||G[oe+1];if(re&&=ht!==void 0,ht!==void 0)K.push({tokenIndex:pt?oe:oe+1,kind:"module-file",value:ht});if(!pt)oe++;break}if(U==="perl"&&(ft==="M"||ft==="m")){let pt=de.slice(gt+1);if(!pt){if(re=!1,gt+1===de.length)oe++;break}K.push({tokenIndex:oe,kind:"module-file",value:pt});break}if(pS.get(U)?.has(ft)){if(gt+1===de.length)oe++;break}if(gS.get(U)?.has(ft)&&gt+1<de.length)break}if(we===void 0)continue;let mt=We?oe+1:oe;if(j.push({tokenIndex:mt,value:we}),K.push({tokenIndex:mt,kind:"inline-code",value:we}),U==="python")return Ln(U,j,K,re);if(We)oe++}return Ln(U,j,K,re,void 0,void 0,!0)}function Ln(G,U,j,K,re,oe,de=!1){let Se=G==="node"?U.slice(-1):U,we=new Set(Se.map((mt)=>mt.tokenIndex)),We=j.filter((mt)=>mt.kind!=="inline-code"||we.has(mt.tokenIndex));if(K&&U.length===0&&re!==void 0&&oe!==void 0)We.push({tokenIndex:re,kind:"main-script",value:oe});return{code:(G==="node"?Se[0]?.value:Se.map((mt)=>mt.value).join(`
30
+ `))||null,sources:K?We:[],optionsOpen:K&&de}}function ES(G){for(let U of["--import","--loader","--experimental-loader","--require"]){if(G===U)return{attached:!1,value:""};if(G.startsWith(`${U}=`))return{attached:!0,value:G.slice(U.length+1)}}return}function _l(G,U){return wl(G)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(U)}function wl(G){let U=kt(G).toLowerCase();return Wi.test(U)?"python":U}function RS(G,U){return xl.get(G)?.has(U)??!1}function xS(G){return xl.get(G)?.has("--eval")??!1}function ni(G,U,j=!1){let K=PS(G,U);if(!Rl(K,U))return!1;Rn(U,K);let re=wS(K);if(Rl(re,U))return!0;if(Rn(U,re),!pm.test(re))return!1;return!j||_S(K,U)}function _S(G,U){if(/`|%x|\bqx\b/.test(G))return!0;let K=G.split(""),re=[];for(let we=0;we<G.length;we++){let We=G[we];if(We!=="'"&&We!=='"')continue;let mt=G.startsWith(We.repeat(3),we)?We.repeat(3):We,gt=we+mt.length,ft=gt;while(ft<G.length&&!G.startsWith(mt,ft))ft+=G[ft]==="\\"?2:1;if(ft>=G.length)return!0;re.push({start:gt,text:G.slice(gt,ft)}),K.fill(" ",we,ft+mt.length),we=ft+mt.length-1}let oe=K.join(""),de=Array.from(oe.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((we)=>pm.test(we[1]??"")).map((we)=>{let We=we.index+we[0].length;return{start:We,end:ds(oe,We)}});if(de.some((we)=>Pl(oe,we.start)))return!0;return re.some((we)=>{let We=/\b(?:system|exec|spawn|popen)\s*$/.test(oe.slice(0,we.start)),mt=de.some((gt)=>we.start>=gt.start&&we.start<gt.end);return(We||mt)&&Rl(we.text,U)})}function ds(G,U){let j=1;for(let K=U;K<G.length;K++){if(G[K]==="(")j++;if(G[K]===")")j--;if(j===0)return K}return G.length}function Pl(G,U){let j=0;for(let K=U;K<G.length;K++){let re=G[K]??"";if("([{".includes(re))j++;if(")]}".includes(re)&&j--===0)return!1;if(re===","&&j===0)return!1;if(/[A-Za-z_$]/.test(re))return!0}return!1}var pm=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function wS(G){let U=[],j=0,K=0;while(K<G.length){let re=G[K];if(re!=="'"&&re!=='"'){K++;continue}let oe=G.startsWith(re.repeat(3),K)?re.repeat(3):re,de=K+oe.length;while(de<G.length&&!G.startsWith(oe,de))de+=G[de]==="\\"?2:1;if(de>=G.length)break;U.push(G.slice(j,K)," "),K=de+oe.length,j=K}return U.push(G.slice(j)),U.join("")}function Rl(G,U){if(ss(G,"rm",U))return!0;for(let K of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(Rn(U,G),K.test(G))return!0;if(ss(G,"dd",U))return!0;for(let K of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(Rn(U,G),K.test(G))return!0;if(ss(G,"find",U))return!0;let j=G.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((K)=>(Rn(U,G),j.some((re)=>as(re,K))))}function PS(G,U){return Rn(U,G),G.replace(SS,"")}import{lstatSync as Rv,readdirSync as xv}from"node:fs";import{basename as _v,isAbsolute as $m,join as wv,relative as Bm}from"node:path";import{isAbsolute as vm,parse as WS}from"node:path";import{dirname as AS,isAbsolute as TS,parse as IS,sep as kS}from"node:path";function ur(G,U,j){if(sr(U))throw Error("Unsupported Windows namespace path");let K=TS(U)?IS(U).root:"",re=K||G;for(let oe of MS(K?U.slice(K.length):U)){if(oe===""||oe===".")continue;if(oe===".."){re=AS(re);continue}let de=OS(re,oe),Se=j.entryKind(de),we=Se==="symlink"?j.realpath(de):de;if(Se==="missing"||we===null)throw Error(`Cannot resolve path component: ${de}`);re=we}return re}function OS(G,U){return G.endsWith("/")||G.endsWith("\\")?`${G}${U}`:`${G}${kS}${U}`}function MS(G){let U=process.platform==="win32"?/[\\/]+/:/\/+/;return G.split(U)}var Al=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],DS=new Set(Al),NS=1024,gm=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),hm=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),LS=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ms(G){return DS.has(G)}function Tl(G){return ms(G)||gm.has(G)||hm.has(G)||No(G)}function Qn(G,U,j){return j?.has(G)?j.get(G):U.get(G)}function ym(G,U){let j=Qn("GIT_CONFIG_COUNT",G,U);if(j===void 0)return{state:"absent"};if(j==="")return{state:"valid",count:0};if(!/^\d+$/.test(j))return{state:"invalid"};let K=Number(j);return Number.isSafeInteger(K)&&K<=NS?{state:"valid",count:K}:{state:"invalid"}}function fs(G,U,j){let re=G.match(LS)?.[1];if(!re||!Tl(re))return null;let oe=G.indexOf("=");return{name:re,value:`${Qn(re,U,j)??""}${G.slice(oe+1)}`}}function bm(G){return Sm(G,hm)}function Cm(G){return Sm(G,gm)}function Sm(G,U){if(!G)return!1;for(let j of G.keys())if(U.has(j))return!0;return!1}var Rm=/^[A-Za-z_][A-Za-z0-9_]*=/;function kn(G){if(!Rm.test(G))return null;let U=G.indexOf("=");return{name:G.slice(0,U),value:G.slice(U+1)}}function ve(G){let U=new Map,j=0;while(j<G.length){let K=G[j];if(!K)break;let re=kn(t(K));if(!re)break;U.set(re.name,re.value),j++}return{words:G.slice(j),envAssignments:U}}function xm(G){let U=Mt(G);return G.includes("=")||U==="sudo"||U==="env"||U==="command"||U==="builtin"}function kr(G,U,j,K){if(!xm(ao(G)))return{words:G,envAssignments:new Map,cwd:j,rewritten:!1};let re=new Set(G),oe=G,de=new Map,Se=new Map(K??[]),we=[],We=j;for(let gt=0;gt<a.wrapperPeelIterations.cap;gt++){let ft=Em(oe),pt=ve(oe);for(let[yt,bt]of pt.envAssignments)de.set(yt,bt),Se.set(yt,bt);if(oe=pt.words,oe.length===0)break;while(oe.length>0&&ao(oe).includes("=")&&!GS(oe)){let yt=zS(ao(oe),Se,U.env)??fs(ao(oe),U.env,Se);if(yt)de.set(yt.name,yt.value),Se.set(yt.name,yt.value);oe=oe.slice(1)}if(oe.length===0)break;let ht=Mt(ao(oe));if(ht!=="sudo"&&ht!=="env"&&ht!=="command"&&ht!=="builtin")break;if(ht==="sudo"){let yt=BS(oe,U.paths,We);if(oe=yt.words,yt.cwd!==void 0)We=yt.cwd}if(ht==="env"){let yt=jS(oe,We,Se,U);if(we.push(...yt.envSplitValues??[]),oe=yt.words,yt.cwd!==void 0)We=yt.cwd;for(let[bt,Ct]of yt.envAssignments)de.set(bt,Ct),Se.set(bt,Ct)}if(ht==="command")oe=VS(oe);if(ht==="builtin")oe=oe.slice(Wn(oe,1)==="--"?2:1);if(Em(oe)===ft)break}let mt=ve(oe);for(let[gt,ft]of mt.envAssignments)de.set(gt,ft),Se.set(gt,ft);return{words:mt.words,envAssignments:de,cwd:We,envSplitValues:we.length>0?we:void 0,rewritten:FS(mt.words,re)}}function FS(G,U){return G.some((j)=>!U.has(j))}function Em(G){return G.map(t).join(" ")}function ao(G){let U=G[0];return U?t(U):""}function Wn(G,U){let j=G[U];return j?t(j):void 0}function GS(G){return Rm.test(ao(G))}function zS(G,U,j){if(!G.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${U.get("TMPDIR")??j.get("TMPDIR")??""}${G.slice(8)}`}}var $S=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function BS(G,U,j){let K=1,re=j;while(K<G.length){let oe=Wn(G,K);if(!oe)break;if(oe==="--")return{words:G.slice(K+1),cwd:re};if(!oe.startsWith("-"))break;if(oe==="-D"||oe==="--chdir"){let de=Wn(G,K+1);re=de?ri(re,de,U):null,K+=2;continue}if(oe.startsWith("--chdir=")){re=ri(re,oe.slice(8),U),K++;continue}if(oe.startsWith("-D")&&oe.length>2){re=ri(re,oe.slice(2),U),K++;continue}if(oe==="-i"||oe==="--login"){re=null,K++;continue}if($S.has(oe)){K+=2;continue}K++}return{words:G.slice(K),cwd:re}}var US=new Set(["-i","-0","--null"]),HS=new Set(["-u","--unset","-C","--chdir","-P"]);function jS(G,U,j,K){let re=new Map,oe=[],de=U,Se=1,we=(We)=>({words:G.slice(We),envAssignments:re,cwd:de,envSplitValues:oe.length>0?oe:void 0});while(Se<G.length){let We=Wn(G,Se);if(!We)break;if(We==="--")return we(Se+1);if(We==="-i"||We==="--ignore-environment"||We==="-"){re.clear();for(let gt of j.keys())re.set(gt,"");re.set("TMPDIR",""),Se++;continue}if(US.has(We)){Se++;continue}if(We==="-u"||We==="--unset"){let gt=Wn(G,Se+1);if(gt!==void 0)re.set(gt,"");Se+=2;continue}if(We.startsWith("-u")&&We.length>2&&!We.startsWith("-u=")){re.set(We.slice(2),""),Se++;continue}if(We.startsWith("--unset=")){re.set(We.slice(8),""),Se++;continue}let mt=We==="-S"||We==="--split-string"?{value:Wn(G,Se+1),consumed:2}:We.startsWith("-S")&&We.length>2?{value:We.slice(2),consumed:1}:We.startsWith("--split-string=")?{value:We.slice(15),consumed:1}:null;if(mt){if(mt.value!==void 0)oe.push(mt.value);return de=null,we(Se+mt.consumed)}if(HS.has(We)){if(We==="-C"||We==="--chdir"){let gt=Wn(G,Se+1);de=gt?ri(de,gt,K.paths):null}Se+=2;continue}if(We.startsWith("-u=")){Se++;continue}if(We.startsWith("-C")&&We.length>2||We.startsWith("--chdir=")){let gt=We.startsWith("--chdir=")?We.slice(8):We.startsWith("-C=")?We.slice(3):We.slice(2);de=ri(de,gt,K.paths),Se++;continue}if(We.startsWith("-P")){Se++;continue}if(We.startsWith("-")){Se++;continue}if(!kn(We))break;while(Se<G.length){let gt=kn(Wn(G,Se)??"");if(!gt)break;re.set(gt.name,gt.value),Se++}if(Wn(G,Se)==="--")Se++;return we(Se)}return we(Se)}function ri(G,U,j){if(U==="")return null;if(!G&&!vm(U))return null;let K=vm(U)?WS(U).root:j.realpath(G??"/");if(K===null)return null;try{return ur(K,U,j)}catch{return null}}function VS(G){if(Wn(G,1)==="-v")return[...jt(["type"]),...G.slice(2)];let U=1;while(U<G.length){let j=Wn(G,U);if(!j)break;if(j==="-p"||j==="-v"||j==="-V"){U++;continue}if(j==="--")return G.slice(U+1);if(j.startsWith("-")&&!j.startsWith("--")&&j.length>1){if(!/^[pvV]+$/.test(j.slice(1)))break;U++;continue}break}return G.slice(U)}var qS=/['"\\$`{}#]/;function ps(G,U){if(G.some((K)=>qS.test(K)))return null;let j=[...G.flatMap((K)=>K.split(/\s+/).filter((re)=>re.length>0)),...U];return j.length<=64?j:null}function dr(G,U,j){return gs(G,U,j).tokens}function KS(G){let U=[],j="",K=0;while(K<G.length){let re=G.charAt(K);if(re==='"'||re==="'"){let oe=G.indexOf(re,K+1);if(oe===-1)return G.split(/\s+/).map((de)=>de.replace(/["']/g,"")).filter((de)=>de.length>0);j+=G.slice(K+1,oe),K=oe+1;continue}if(/\s/.test(re)){if(j.length>0)U.push(j);j="",K++;continue}j+=re,K++}if(j.length>0)U.push(j);return U}function mr(G,U,j,K=0){let re=gs(G,U,j),oe=(re.envSplitValues??[]).flatMap(KS);if(oe.length===0)return re.tokens;let de=[...oe,...re.tokens];if(K>=8)return de;return mr(de,U,j,K+1)}function gs(G,U,j,K){if(!xm(G[0]??""))return{tokens:[...G],envAssignments:new Map,cwd:j};let re=kr(jt(G),U,j,K);return{tokens:re.words.map(t),envAssignments:re.envAssignments,cwd:re.cwd,envSplitValues:re.envSplitValues}}var Ol=Symbol("adopt-as-operand"),YS=new Set(["env","sudo","command","builtin"]),ZS=new Set(["&&","||","|&","|","&",";"]),XS=new Set(["<<","<<<",">|"]),_m=new Set(["|","|&"]),JS=/[*@#?$!_-]/,QS=/^\w+(?::\w+)*/,ev=Object.freeze([]),oi=Object.freeze({kind:"scope",edge:"enter"}),ii=Object.freeze({kind:"scope",edge:"exit"}),tv=Object.freeze([]),nv=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),si=new Set(["bash","sh","zsh","dash","ksh"]),rv=256,Im=new WeakMap;function km(G,U){let j=U.status==="complete"?new Set(kl(U)):new Set,K=sv(G,j);if(Gi(K))return hs("unclosed-quote",K,U);let re={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},oe=Or(U,{source:K,suppressed:j,flags:re,depth:0,functions:new Map,powershell:U.dialect==="powershell"});if(re.limited)return hs("structural-limit",K,U);if(re.invalid)return hs("invalid",K,U);let de=hs("complete",K,U,re.assignmentFallbacks);return Im.set(de,Object.freeze(oe)),de}function Cs(G,U,j,K,re){let oe=re.word??((ht)=>ht),de={cwd:U,variables:new Map,previous:null},Se=[],we=new Set,We=null,mt=[],gt=Om(G),ft=gt.findLastIndex((ht)=>ht.kind==="operator"&&_m.has(ht.operator)),pt=ft!==-1&&gt.some((ht)=>ht.kind==="redirection"&&ht.operator==="<<"&&ht.body===void 0);for(let[ht,yt]of gt.entries()){let bt=pt||ht<=ft;if(yt.kind==="scope"){if(yt.edge==="enter"){mt.push({state:de,segment:[...Se],shellWords:new Set(we),pipeProducer:We});continue}let Ct=re.segment(Se,de,We,null,we,bt);if(Ct)return Ct;let vt=mt.pop();if(vt===void 0)throw Error("scope exit without a matching enter");de=vt.state,Se=vt.segment,we=vt.shellWords,We=vt.pipeProducer;continue}if(yt.kind==="operator"){if(!yt.boundary)continue;let Ct=re.segment(Se,de,We,yt.operator,we,bt);if(Ct)return Ct;de=ov(Se,de,j,K),We=Se.length>0&&_m.has(yt.operator)?Se:null,Se=[],we=new Set;continue}if(yt.kind==="redirection"){if(yt.fd!==void 0)we.add(Se.length-1);if(yt.target===void 0)continue;let Ct=re.redirection({operator:yt.operator,role:yt.role,targetOrder:yt.targetOrder,target:yt.target,...yt.body===void 0?{}:{body:yt.body,consumer:yt.consumer}},de,bt);if(Ct===Ol){we.add(Se.length),Se.push(oe(yt.target));continue}if(Ct)return Ct;continue}Se.push(oe(yt.text))}return re.segment(Se,de,We,null,we,pt)}function Ss(G){return Om(G).flatMap((U)=>{if(U.kind==="word")return[{kind:"word",text:U.text}];if(U.kind==="operator")return[{kind:"operator",boundary:U.boundary}];if(U.kind==="redirection")return[{kind:"redirection",target:U.target}];return[]})}function fn(G,U){return G.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(j,K,re,oe)=>{let de=U.get(K);if(de===void 0)return j;let Se=re.startsWith(":")?de!=="":!0;if(re.endsWith("-"))return Se?de:fn(oe,U);return Se?fn(oe,U):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(j,K)=>U.get(K)??j).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(j,K)=>U.get(K)??j)}function ai(G){return G.length>0&&G.every((U)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(U))}function ov(G,U,j,K){let re=ai(G)?new Map([...U.variables,...iv(G,U.variables)]):U.variables,oe=dr([...G],j),de=kt(oe[0]??"").toLowerCase()==="cd"?oe[1]:void 0;if(!de)return{...U,variables:re};if(de==="-"){if(U.previous===null)return{...U,variables:re};return{cwd:U.previous,variables:re,previous:U.cwd}}return{cwd:ln(fn(de,re),U.cwd,j,K),variables:re,previous:U.cwd}}function iv(G,U){return G.flatMap((j)=>{let K=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(j),re=K?.[2]?.startsWith("=")?K[2].slice(1):void 0;return K?.[1]!==void 0&&re!==void 0?[[K[1],fn(re,U)]]:[]})}function Om(G){return Im.get(G)??ev}function sv(G,U){return[...U].reduce((j,K)=>j.slice(0,K.start)+" ".repeat(K.end-K.start)+j.slice(K.end),G)}function hs(G,U,j,K=tv){return Object.freeze({status:G,source:U,program:j,assignmentFallbacks:Object.freeze(K)})}function Or(G,U){return G.nodes.flatMap((j,K)=>av(j,G,K,U)).sort((j,K)=>j.start-K.start).flatMap((j)=>[...j.events])}function av(G,U,j,K){if(G.kind==="connector")return[{start:G.span.start,events:[Fn(mv(G.operator))]}];if(G.kind==="unknown")return[{start:G.span.start,events:[Fn(G.source)]}];if(G.kind==="function")return K.functions.set(G.name,G.body),[];if(G.kind==="group"){let oe=G.style!=="subshell",de=K.source[G.span.end-1]===(oe?"}":")"),Se=oe?K:{...K,functions:new Map(K.functions)};return[{start:G.span.start,events:oe?[ys("{"),...Or(G.body,Se),...de?[ys("}")]:[]]:[oi,Fn("("),...Or(G.body,Se),...de?[Fn(")")]:[],ii]}]}let re=hv(G,K.functions);if(re){if(K.depth>=cr.maxDepth||++K.flags.expansions>rv)return K.flags.limited=!0,[];return[{start:G.span.start,events:[...wm(G,K),ys(";"),...Or(re,{...K,depth:K.depth+1}),ys(";")]},...Pm(G,U,j,K)]}return[{start:G.span.start,events:wm(G,K)},...Pm(G,U,j,K)]}function wm(G,U){return[...G.words.map((j)=>({start:j.span.start,events:Dm(j,G,U,!1)})),...G.redirections.map((j)=>({start:j.span.start,events:lv(j,G,U)}))].sort((j,K)=>j.start-K.start).flatMap((j)=>j.events)}function lv(G,U,j){let K=G.operator==="<<-"?"<<":G.operator,re=G.target?Dm(G.target,U,j,!0):[],oe=re[0],de=oe?.kind==="word"?oe.text:void 0;return[...G.fd===void 0?[]:[Ml(String(G.fd))],Object.freeze({kind:"redirection",operator:K,...G.fd===void 0?{}:{fd:G.fd},role:fv(K),targetOrder:XS.has(K)?"legacy-segment":"immediate",...de===void 0?{}:{target:de},...G.heredoc&&j.suppressed.has(G.heredoc.bodySpan)?{body:G.heredoc.body,consumer:Lm(U)}:{}}),...de===void 0?re:re.slice(1)]}function Pm(G,U,j,K){let re=G.redirections.filter((oe)=>oe.operator==="<<"||oe.operator==="<<-");return[...re.flatMap((oe)=>{let de=oe.heredoc;if(!de)return[];let Se=[Ml(de.delimiter),.../[\r\n]/.test(K.source[de.terminatorSpan.end]??"")?[Fn(";")]:[]];if(K.suppressed.has(de.bodySpan))return[{start:de.bodySpan.start,events:Se}];return[{start:de.bodySpan.start,events:[...Mm(K.source.slice(de.bodySpan.start,de.bodySpan.end),K),...Se]}]}),...re.some((oe)=>!oe.heredoc&&oe.target)?cv(U,j,K):[]]}function cv(G,U,j){let K=G.nodes.slice(U+1).find((re)=>re.kind==="connector");if(!K||K.span.end>=G.span.end)return[];return[{start:K.span.end,events:Mm(j.source.slice(K.span.end,G.span.end),j)}]}function Mm(G,U){if(U.depth>=cr.maxDepth)return U.flags.limited=!0,[];let j=y(G,"posix");if(j.status==="limited")return U.flags.limited=!0,[];let K={invalid:!1,limited:!1,expansions:U.flags.expansions,assignmentFallbacks:U.flags.assignmentFallbacks},re=Or(j,{source:G,suppressed:new Set,flags:K,depth:U.depth+1,functions:new Map,powershell:!1});return U.flags.limited||=K.limited,U.flags.expansions=K.expansions,re}function Dm(G,U,j,K){let re=[],oe={single:!1,double:!1},de="",Se=!1,we=()=>{let We=Se&&!K?Fn("glob"):de!==""||G.quoted&&re.length===0?Ml(de):void 0;if(We)re.push(We);de="",Se=!1};for(let We of G.parts){if(We.provenance!=="command-substitution"&&We.provenance!=="arithmetic"){for(let pt of Il(We.raw,oe,j.flags,j.powershell)){if(typeof pt==="string"){we(),re.push(Fn(pt));continue}de+=pt.text,Se||=pt.glob}continue}let mt=U.nested.find((pt)=>pt.span.start>=We.span.start&&pt.span.end<=We.span.end);if(oe.double){let pt=j.source.slice(We.span.start,We.span.end);de+=Il(pt,{single:!1,double:!0},j.flags,j.powershell).map((yt)=>typeof yt==="string"?yt:yt.text).join("");let ht=mt?Or(mt,j).filter((yt)=>yt.kind==="redirection"&&yt.body!==void 0):[];if(ht.length>0)re.push(oi,...ht,ii);continue}let gt=mt?Or(mt,j):[];if(We.raw.startsWith("`")){de+="${}",we(),re.push(oi,...gt,ii);continue}if(We.raw.startsWith("<(")||We.raw.startsWith(">(")){we(),re.push(We.raw.startsWith("<(")?Fn("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),oi,...gt,...We.raw.endsWith(")")?[Fn(")")]:[],ii);continue}let ft=We.raw.startsWith("$((")?2:1;de+="${}",we(),re.push(...Array.from({length:ft},()=>Fn("(")),...ft===1?[oi]:[],...gt,...We.raw.endsWith(")".repeat(ft))?Array.from({length:ft},()=>Fn(")")):[],...ft===1?[ii]:[])}return we(),re}function Il(G,U,j,K){let re=[],oe="",de=!1,Se=0;while(Se<G.length){let we=G[Se]??"";if(!U.single&&!U.double&&(we==="("||we===")")){re.push({text:oe,glob:de},we),oe="",de=!1,Se++;continue}if(K&&we==="`"&&!U.single){oe+=G[Se+1]??"",Se+=2;continue}if(U.single&&we==="'"){U.single=!1,Se++;continue}if(U.single){oe+=we,Se++;continue}if(U.double){if(we==='"'){U.double=!1,Se++;continue}if(!K&&we==="\\"){let We=G[Se+1]??"";oe+=['"',"\\","$"].includes(We)?We:`\\${We}`,Se+=2;continue}if(we==="$"){let We=Am(G,Se,U,j,K);oe+=We.text,Se=We.next;continue}oe+=we,Se++;continue}if(we==="'"||we==='"'){U.single=we==="'",U.double=we==='"',Se++;continue}if(!K&&we==="\\"){let We=G[Se+1]??"";de||=We==="*"||We==="?",oe+=We,Se+=2;continue}if(we==="$"){let We=Am(G,Se,U,j,K);oe+=We.text,Se=We.next;continue}de||=we==="*"||we==="?",oe+=we,Se++}return[...re,{text:oe,glob:de}]}function Am(G,U,j,K,re){let oe=G[U+1];if(oe==="{"){let Se=re?dv(G,U+2):is(G,U+2,G.length).close;if(Se===-1)return K.invalid=!0,{text:"",next:G.length};let we=G.slice(U,Se+1);return uv(we,j,K,re),{text:we,next:Se+1}}if(oe!==void 0&&JS.test(oe))return{text:`\${${oe}}`,next:U+2};let de=(re?QS:/^\w*/).exec(G.slice(U+1))?.[0]??"";return{text:`\${${de}}`,next:U+1+de.length}}function uv(G,U,j,K){let re=G.slice(2,-1),oe=/^[A-Za-z_][A-Za-z0-9_]*/.exec(re)?.[0];if(!oe)return;let de=re.slice(oe.length),Se=[":=","="].find((We)=>de.startsWith(We));if(!Se)return;let we=Il(de.slice(Se.length),{...U},j,K);j.assignmentFallbacks.push(...we.flatMap((We)=>typeof We==="string"||!We.text?[]:[We.text]))}function dv(G,U){let j=1,K=U;while(j>0&&K<G.length){if(G[K]==="{"&&G[K-1]==="$")j++;if(G[K]==="}")j--;K++}return j===0?K-1:-1}function mv(G){return/^[\r\n]+$/.test(G)?";":G}function Fn(G){return Object.freeze({kind:"operator",operator:G,boundary:ZS.has(G)})}function ys(G){return Object.freeze({kind:"operator",operator:G,boundary:!0})}function Ml(G){return Object.freeze({kind:"word",text:G})}function fv(G){if(G==="<<"||G==="<<<")return"here-data";if(G==="<"||G==="<&")return"file-read";return"file-write"}function lo(G){return nv.has(G)||/^python\d/.test(G)}var pv=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 Nm(G,U){let j=U[0];if(j===void 0||!j.startsWith("-"))return U;let K=pv.get(G)?.has(j)??!1;return Nm(G,U.slice(K?2:1))}function bs(G){let U=G[0];if(U===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(U))return bs(G.slice(1));if(U==="uv"&&G[1]==="run")return bs(G.slice(2));if(!YS.has(U))return[...G];return bs(Nm(U,G.slice(1)))}function Lm(G){let U=Vo(G),j=G.words.findIndex((K)=>K.provenance==="literal"&&K.text===U);return bs(j<0?[]:G.words.slice(j).map((K)=>K.text))}function gv(G){let U=Lm(G)[0];if(U===void 0)return!1;let j=kt(U).toLowerCase();return lo(j)&&!si.has(j)}function kl(G){return G.nodes.flatMap((U,j)=>{if(U.kind==="group"||U.kind==="function")return kl(U.body);if(U.kind!=="command")return[];let K=U.nested.flatMap((Se)=>kl(Se)),re=U.redirections.flatMap((Se)=>Se.heredoc?.quotedDelimiter?[Se.heredoc.bodySpan]:[]);if(gv(U))return[...K,...re];let oe=G.nodes[j+1];if(oe?.kind==="connector"&&(oe.operator==="|"||oe.operator==="|&")||!bv(U))return K;return[...K,...re]})}function hv(G,U){let j=Vo(G);return j===void 0?void 0:U.get(j)}function fr(G,U){return G!==void 0&&G.provenance==="literal"&&!G.quoted&&G.raw===G.text&&G.text===U}function yv(G){if(fr(G.words[0],"git"))return fr(G.words[1],"commit");if(!fr(G.words[0],"gh")||!fr(G.words[2],"create"))return!1;return fr(G.words[1],"pr")||fr(G.words[1],"issue")}function bv(G){return(fr(G.words[0],"cat")||fr(G.words[0],"tee")||yv(G))&&!G.words.some(Tm)&&!G.redirections.some((j)=>Tm(j.target))}function Tm(G){return G?.parts.some((U)=>U.provenance==="command-substitution"&&U.raw.startsWith(">("))??!1}var Wm=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Fm=new Set([...Wm,"glob"]),Cv=new Set([...Fm,"folder","pattern","patterns"]);class b extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Gm(G){let U=Sv(),j=ie(G.input),K=[];if((G.route.kind==="command"||G.route.kind==="unknown")&&j)K.push({usage:"input-candidate",source:j});if(G.route.kind==="command"&&"command"in G&&G.command)K.push({usage:"declared-command",source:G.command});let re=K.reduce((oe,de)=>{let Se=oe.findIndex((mt)=>mt.source===de.source);if(Se!==-1){let mt=oe[Se];if(!mt)return oe;return oe[Se]={...mt,usages:[...mt.usages,de.usage]},oe}let we=G.route.kind==="command"?G.route.shell:process.platform==="win32"?"powershell":"posix",We=U.getCommandProgram(de.source,we);return oe.push({usages:[de.usage],source:de.source,program:We,shell:U.getShellSyntax(de.source,We)}),oe},[]);return{invocation:{toolName:G.toolName,route:G.route,context:G.context},commands:re,paths:vv(G),store:U}}function pn(G,U){return G.commands.find((j)=>j.usages.includes(U))}function er(G,U){if(!G.includes("$"))return G;return fa(G,U)}function Sv(){let G=new Map,U=new Map,j=new WeakMap,K=(oe,de)=>{let Se=`${de}\x00${oe}`,we=U.get(Se);if(we)return we;let We=y(oe,de);return U.set(Se,We),We};return{getShellSyntax:(oe,de)=>{if(de&&de.source!==oe)throw TypeError("Shell syntax source does not match command program source.");let Se=de??K(oe,"posix");if(Se.status==="limited"){let mt=j.get(Se);if(mt)return mt;let gt={status:"structural-limit",source:oe,program:Se,assignmentFallbacks:[]};return j.set(Se,gt),gt}let we=G.get(oe);if(we)return we;let We=km(oe,Se);return G.set(oe,We),We},getCommandProgram:K}}function vv(G){let U=G.route.kind==="grep"?Fm:G.route.kind==="glob"?Cv:Wm;return[...hu(G.input,U),...G.route.kind==="patch"||typeof G.input==="string"?Cu(G.input):[]]}var Ev=new Set(["-S","--suffix"]);function co(G,U,j,K,re){if(G.status==="structural-limit")throw new b;if(G.status!=="complete")return re.findMalformedTarget(G.source);return Cs(G,U,j,K,{segment:(oe,de)=>re.findSegmentTarget(oe,de),redirection:(oe,de)=>oe.role==="file-write"&&re.isRedirectionTarget(fn(oe.target,de.variables),de)?oe.target:null})}function vs(G){let U=[],j=null,K=!1;for(let re=0;re<G.length;re++){let oe=G[re];if(oe===void 0)break;if(!K&&oe==="--"){K=!0;continue}if(!K&&(oe==="-t"||oe==="--target-directory")){j=G[++re]??null;continue}if(!K&&oe.startsWith("--target-directory=")){j=oe.slice(19);continue}if(!K&&oe.startsWith("-t")&&oe.length>2){j=oe.slice(2);continue}if(!K&&Ev.has(oe)){re++;continue}if(!K&&(oe.startsWith("--suffix=")||oe.startsWith("--backup=")))continue;if(!K&&oe.startsWith("-"))continue;U.push(oe)}return j?{sources:U,destination:j}:{sources:U.slice(0,-1),destination:U.at(-1)??null}}var x="Git metadata and hooks are protected. Ask the user before modifying them.";function Um(G,U,j,K){let re=G.invocation.context.executionCwd;if(!U)return null;if(G.invocation.route.kind==="patch"||G.invocation.route.kind==="path"||G.invocation.route.kind==="unknown"){if(Ii(G.invocation.toolName))return null;let Se=G.paths.find((we)=>zm(we,re,U,j,K,U.entries));return Se?{target:Se}:null}if(G.invocation.route.kind!=="command")return null;let oe=pn(G,"input-candidate");if(!oe)return null;let de=co(oe.shell,re,j,K,{findSegmentTarget:(Se,we)=>Ov(Se,we,U,j,K),isRedirectionTarget:(Se,we)=>zm(Se,we.cwd,U,j,K,U.markerFiles),findMalformedTarget:()=>null});return de?{target:de}:null}function Mr(G,U,j,K,re,oe,de=!1){if(!j)return!1;let Se=Rs(ln(G,U,re,oe)),we=Se.replace(/(\/\.?\*+)+$/,"");if(we!==Se&&we!==""){if(Dl(we,j))return!0;let We=de||Se.slice(we.length).includes("/."),mt=(gt)=>We?Es(gt,we):Pv(gt,we);if(j.markerFiles.some(mt))return!0;return K&&Nl(j).some(mt)}if(Dl(Se,j))return!0;return K&&Nl(j).some((We)=>Es(We,Se))}function Pv(G,U){let j=Bm(U,G);if(j===""||j.startsWith("..")||$m(j))return!1;return!j.split(/[\\/]/)[0]?.startsWith(".")}function Av(G,U,j,K,re){return Mr(G,U,j,!0,K,re)}function Tv(G,U,j,K,re){if(!j)return!1;return Dl(Rs(ln(G,U,K,re)),j)}function zm(G,U,j,K,re,oe){let de=Rs(ln(G,U,K,re));return oe.includes(de)||jm(de,j)}function Hm(G,U,j,K,re){if(!j)return!1;return j.hooksDirectories.some((oe)=>G.some((de)=>Es(oe,Rs(ln(de,U,K,re)))))}function Dl(G,U){return U.entries.includes(G)||U.directories.includes(G)||jm(G,U)}function jm(G,U){return U.hooksDirectories.some((j)=>Es(G,j))}var Iv=50000;function Vm(G,U){let j=[...new Set(Nl(G))];if(j.some((re)=>U(_v(re))))return!0;let K=0;while(j.length>0){let re=j.pop()??"",oe=kv(re);if(!oe)return!0;if(K+=oe.length,K>Iv)return!0;if(oe.some((de)=>U(de.name)))return!0;j.push(...oe.filter((de)=>de.isDirectory()).map((de)=>wv(re,de.name)))}return!1}function kv(G){try{let U=Rv(G,{throwIfNoEntry:!1});if(!U)return[];if(!U.isDirectory())return U.isSymbolicLink()?null:[];return xv(G,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function Nl(G){return[...G.entries,...G.directories,...G.hooksDirectories]}function Es(G,U){let j=Bm(U,G);return j===""||!/^\.\.(?:[\\/]|$)/.test(j)&&!$m(j)}function Rs(G){return process.platform==="win32"?G.toLowerCase():G}function Ov(G,U,j,K,re){if(ai(G))return null;let oe=mr([...G],K);if(kt(oe[0]??"").toLowerCase()!=="mv")return null;let de=vs(oe.slice(1)),Se=de.sources.find((we)=>Av(fn(we,U.variables),U.cwd,j,K,re));if(Se)return Se;return de.destination&&Tv(fn(de.destination,U.variables),U.cwd,j,K,re)?de.destination:null}import{isAbsolute as Ps,normalize as zv,parse as $v,posix as ef,resolve as Nr,sep as Gl}from"node:path";import{isAbsolute as Mv,join as qm,normalize as Zm,parse as Dv,sep as Km}from"node:path";var Nv=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],Lv=`
31
+ `;function li(G,U){if(Dr(G,U))return!0;if(!G.has("TMPDIR"))return!1;return!Ll(G.get("TMPDIR")??"",U)}function uo(G,U){if(G.has("TMPDIR"))return Ll(G.get("TMPDIR")??"",U);let j=Wl(G,U);if(j===void 0)return!0;return Ll(j,U)}function Wl(G,U){return Jm(G,U,"TMPDIR")}function Ll(G,U){if(!G)return!1;if(Fv(G))return!1;return mo(G,U)}function Dr(G,U){let j=Jm(G,U,"IFS");return j!==void 0&&j!==""&&j!==Lv}function mo(G,U){let j=xs(G,U.paths);if(j===null)return!1;return Xm(U).some((K)=>fo(j,K))}function ws(G,U){let j=xs(G,U.paths);if(j===null)return!1;return Xm(U).some((K)=>_s(K)===_s(j))}var Ym=new WeakMap;function Xm(G){let U=Ym.get(G);if(U)return U;let j=Wv(G);return Ym.set(G,j),j}function Wv(G){let U=Nv.map((K)=>xs(K,G.paths)??Zm(K)),j=xs(G.tmpdir,G.paths);if(!j)return U;if(process.platform==="win32")return[...U,j];if(process.platform==="darwin"&&Gv(j))return[...U,j];return U}function Fv(G){return/[\s$`*?[]/.test(G)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(G)||/[+@!]\([^)]*\)/.test(G)}function Jm(G,U,j){return G.has(j)?G.get(j):U.env.get(j)}function Gv(G){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(G)}function xs(G,U){try{let j=Zm(G);if(!Mv(j))return j;let K=Dv(j).root,re=j.slice(K.length).split(/[\\/]+/).filter(Boolean),oe=K;for(let de=0;de<re.length;de++){let Se=qm(oe,re[de]??"");if(U.entryKind(Se)==="missing")return qm(Se,...re.slice(de+1));let we=U.realpath(Se);if(we===null)return null;oe=we}return oe}catch{return null}}function fo(G,U){let j=_s(G),K=_s(U);if(j===K)return!0;let re=K.endsWith(Km)?K:`${K}${Km}`;return j.startsWith(re)}function _s(G){return process.platform==="win32"?G.toLowerCase():G}var Bv=process.platform==="win32",Qm=64,Uv=16384;function Lr(G,U,j,K){if(G.kind==="temp_target")return null;let re=K[G.kind];if(G.kind==="dynamic_target"&&!Xt(j,re.id,U.strict))return null;if(G.kind==="within_anchored_cwd"&&!Xt(j,re.id,U.paranoid))return null;return _t(re.id,re.reason)}function ci(G){let U=$d(G,Qm,Qm,Uv);return{expandedTargets:U&&"words"in U?U.words:void 0,unsafeBraceExpansion:U!==void 0&&"limited"in U,targetIsLiteral:U===void 0&&G.provenance==="literal"&&(G.quoted||G.raw!==G.text),tmpdirWordSplittingProtected:Hv(G)}}function Hv(G){let U=G.parts.filter((j)=>j.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(j.raw));return U.length>0&&U.every((j)=>jv(G.raw,j.span.start-G.span.start))}function jv(G,U){let j=null,K=!1;for(let re=0;re<U;re++){let oe=G[re];if(K){K=!1;continue}if(oe==="\\"&&j!=="'"){K=!0;continue}if(j===oe){j=null;continue}if(j===null&&(oe==="'"||oe==='"'))j=oe}return j==='"'}function Hn(G){let U=G.environment.home,j=G.environment.paths,K=G.budget??Pn();return{anchoredCwd:G.originalCwd??G.cwd??null,resolvedCwd:G.cwd??null,strict:G.strict??!1,paranoid:G.paranoid??!1,trustTmpdirVar:G.allowTmpdirVar??!0,posixShell:G.posixShell??!1,tmpdirWordSplittingUnsafe:G.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:G.trustedTmpdirValue??G.allowTmpdirVar??!0,environment:G.environment,allowRoots:Xv(G.allowPaths,U,j,K),protectedGitMetadata:G.protectedGitMetadata,budget:K}}function xn(G,U,j={}){let K=j.targetIsLiteral??!1;if(!K&&U.tmpdirWordSplittingUnsafe&&!j.tmpdirWordSplittingProtected&&Qv(G))return{kind:"outside_anchored_cwd"};let re=!K&&nf(G,U.posixShell);if(sr(G))return{kind:"outside_anchored_cwd"};if(zl(G,K))return{kind:"root_or_home_target"};if(qv(G,U,K))return{kind:"root_or_home_target"};if(U.resolvedCwd&&Mr(G,U.resolvedCwd,U.protectedGitMetadata,!0,U.environment,U.budget,!U.posixShell))return{kind:"git_metadata_target"};if(Kv(G,U.trustTmpdirVar,U.posixShell,re,K,j.tmpdirWordSplittingProtected??!1,U.trustedTmpdirValue,U.environment))return{kind:"temp_target"};if(re)return{kind:"dynamic_target"};if(Jv(G,U,K))return{kind:"temp_target"};let oe=U.anchoredCwd;if(oe){if(!j.skipHomeCwd&&rE(oe,U.environment.home,U.environment.paths,U.budget))return{kind:"home_cwd_target"};if(!j.skipCwdSelf&&[U.resolvedCwd??oe,oe].some((de)=>oE(G,U.resolvedCwd??oe,U.environment.paths,U.budget,de)))return{kind:"cwd_self_target"};if(iE(G,oe,U.resolvedCwd??oe,re,K,U.environment.paths,U.budget))return{kind:"within_anchored_cwd"}}if(Vv(G,U,re))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function Vv(G,U,j){let K=G.trim();if(j||!U.resolvedCwd||!U.anchoredCwd||!K)return!1;if(Ps(K)||K.startsWith("~"))return!1;if($l(K))return!1;if(rf(U.resolvedCwd,U.anchoredCwd,U.environment.paths,U.budget))return!1;return mo(Nr(U.resolvedCwd,K),U.environment)}function tf(G,U,j={}){let{containmentTarget:K,...re}=j;if(xn(G,U,re).kind!=="temp_target")return!1;let oe=G.trim();if(Zv(oe))return!1;if(ws(oe,U.environment))return!1;return![U.anchoredCwd,U.resolvedCwd].some((de)=>rf(K??oe,de,U.environment.paths,U.budget))}function zl(G,U=!1){let j=G.trim(),K=ef.normalize(j),re=j.replace(/\\/g,"/"),oe=K==="/"?K:K.replace(/\/+$/,"");if(oe==="/"||oe.startsWith("/")&&oe.slice(1).split("/").every((de)=>/^\*+$/.test(de)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(re)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(re))return!0;if(!U&&(K==="~"||K==="~/"||K==="~/*"))return!0;if(!U&&(K==="$HOME"||K==="$HOME/"||K==="$HOME/*"))return!0;if(!U&&(K==="${HOME}"||K==="${HOME}/"||K==="${HOME}/*"))return!0;return!1}function qv(G,U,j){let K=G.trim(),re=j?K:K==="*"?".":K.endsWith("/*")?K.slice(0,-2):K;if(!re)return!1;try{let oe=Ps(re)?re:U.resolvedCwd?Nr(U.resolvedCwd,re):null;if(!oe)return!1;let de=gn(Nt(oe,U.environment.paths,U.budget));if(de===$v(de).root)return!0;return de===gn(Nt(U.environment.home,U.environment.paths,U.budget))}catch{return!1}}function gn(G){let U=zv(G);if(Bv){if(U=U.replace(/\//g,"\\").toLowerCase(),U.length>3&&U.endsWith("\\"))U=U.slice(0,-1);return U}if(U.length>1&&U.endsWith("/"))U=U.slice(0,-1);return U}function Kv(G,U,j,K,re,oe,de,Se){let we=G.trim();if($l(we))return!1;if(!K&&mo(we,Se))return!0;return(U||oe&&de)&&j&&!re&&Yv(we,j)}function Yv(G,U){return["$TMPDIR","${TMPDIR}"].some((j)=>{if(G===j)return!0;if(!G.startsWith(`${j}/`))return!1;return!nf(G.slice(j.length+1),U)})}function Zv(G){let U=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(G);if(!U)return!1;return ef.normalize(`/${U[1]??""}`)==="/"}function $l(G){return G.split(/[\\/]+/).includes("..")}function Xv(G,U,j,K){if(!G?.length)return[];return G.flatMap((re)=>{let oe=Uo(re.trim(),U);if(!Ps(oe))return[];try{let de=Nt(oe,j,K);if(Ho(de,Nt(U,j,K)))return[];return[gn(de)]}catch{return[]}})}function Jv(G,U,j){if(U.allowRoots.length===0)return!1;let K=G.trim();if($l(K))return!1;let re=j?K:Uo(K,U.environment.home),oe=U.resolvedCwd??U.anchoredCwd,de=Ps(re)?re:oe?Nr(oe,re):null;if(!de)return!1;try{let Se=gn(Nt(de,U.environment.paths,U.budget));return U.allowRoots.some((we)=>Se===we||Se.startsWith(we.endsWith(Gl)?we:`${we}${Gl}`))}catch{return!1}}function Qv(G){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(G)}function nf(G,U=!1){return G.includes("$")||G.includes("`")||eE(G)||U&&tE(G)}function eE(G){let U=!1;for(let j of G){if(U){U=!1;continue}if(j==="\\"){U=!0;continue}if(j==="*"||j==="?"||j==="[")return!0}return!1}function tE(G){let U=!1;for(let j=0;j<G.length;j++){let K=G[j];if(U){U=!1;continue}if(K==="\\"){U=!0;continue}if(K==="{"&&nE(G,j)||(K==="+"||K==="@"||K==="!")&&G[j+1]==="(")return!0}return!1}function nE(G,U){let j=G.indexOf("}",U+1);if(j===-1)return!1;let K=G.slice(U+1,j);return K.includes(",")||K.includes("..")}function rE(G,U,j,K){try{return gn(Nt(G,j,K))===gn(Nt(U,j,K))}catch{try{return gn(G)===gn(U)}catch{return!1}}}function oE(G,U,j,K,re=U){if(re===U&&(G==="."||G==="./"||G===".\\"))return!0;try{return gn(Nt(Nr(U,G),j,K))===gn(Nt(re,j,K))}catch{try{return gn(Nr(U,G))===gn(re)}catch{return!1}}}function iE(G,U,j,K,re,oe,de){let Se=j??U;if(!re&&(G.startsWith("~")||G.startsWith("$HOME")||G.startsWith("${HOME}")))return!1;if(K)return!1;if(G.startsWith("/")||/^[A-Za-z]:[\\/]/.test(G))try{return Fl(G,U,oe,de)}catch{return!1}if(G.startsWith("./")||G.startsWith(".\\")||!G.includes("/")&&!G.includes("\\"))try{return Fl(Nr(Se,G),U,oe,de)}catch{return!1}if(G.startsWith("../"))return!1;try{return Fl(Nr(Se,G),U,oe,de)}catch{return!1}}function Fl(G,U,j,K){try{return of(Nt(G,j,K),Nt(U,j,K))}catch{return!1}}function rf(G,U,j,K){if(!U)return!1;try{return of(Nt(U,j,K),Nt(G,j,K))}catch{return!0}}function of(G,U){let j=gn(G),K=gn(U);return j.startsWith(`${K}${Gl}`)||j===K}var sE=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),sf="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",aE="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.",af="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",lf="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",lE="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",cE="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",uE={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:lf},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:x},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:af},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:lE},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:sf},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:aE},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:sf}};function cf(G,U,j){return dE(G.words.map((K)=>({kind:"word",text:K.text,dynamic:K.provenance!=="literal"})),U,Hn({...j,allowPaths:j.policy?.destructiveCommandAllowPaths}),j.policy)}function dE(G,U,j,K){let re=G.filter((we)=>we.kind==="word"),oe=fE(re),de=re[oe];if(!de||!sE.has(EE(de.text)))return null;let Se=mE(re.slice(oe+1));if(Se.whatIfProtected)return null;if(Xt(K,"powershell.remove-item-pipeline-dynamic-target",j.strict)&&U&&(Se.targets.length===0||Se.recursive))return _t("powershell.remove-item-pipeline-dynamic-target",cE);for(let we of Se.targets)if(!sr(we.text)&&zl(ui(we.text)))return _t(Se.recursive&&Se.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",lf);for(let we of Se.targets)if(j.resolvedCwd&&Mr(ui(we.text),j.resolvedCwd,j.protectedGitMetadata,Se.recursive,j.environment,j.budget,!0))return _t("powershell.remove-item-git-metadata",x);if(!Se.recursive||!Se.force)return null;if(Xt(K,"powershell.remove-item-recursive-force-dynamic-target",j.strict)&&(Se.hasDynamicTarget||Se.targets.length===0))return _t("powershell.remove-item-recursive-force-dynamic-target",af);for(let we of Se.targets){let We=Lr(xn(ui(we.text),j),j,K,uE);if(We)return We}return null}function mE(G){let U=[],j=!1,K=!1,re=!1,oe=!1,de=!1;for(let Se=0;Se<G.length;Se++){let we=G[Se];if(!we||we.kind!=="word")continue;if(pE(we))continue;if(de){U.push(Bl(we)),oe=oe||we.dynamic;continue}if(we.text==="--"){de=!0;continue}let We=hE(we.text);if(!We){U.push(Bl(we)),oe=oe||we.dynamic;continue}if(yE(We.name)){let mt=We.value?gE(We.value,we):G[++Se];if(mt?.kind==="word"){U.push(Bl(mt)),oe=oe||mt.dynamic;continue}oe=!0;continue}if(bE(We.name)){j=!0;continue}if(CE(We.name)){K=!0;continue}if(SE(We.name))re=vE(We.value)}return{targets:U,recursive:j,force:K,whatIfProtected:re,hasDynamicTarget:oe}}function fE(G){let U=G[0];if(U?.kind==="word"&&U.text==="&"||U?.text===".")return G.length>1?1:0;return 0}function Bl(G){return{text:G.kind==="word"?G.text:"",dynamic:G.kind==="word"&&G.dynamic}}function pE(G){return G.kind==="word"&&G.text===","}function ui(G){let U=G.replace(/\\/g,"/"),j=/^(?:\$env:(?:userprofile|home)|\$home|\$\{home\})(?=$|\/)/i.exec(U);return j?`$HOME${U.slice(j[0].length)}`:U}function gE(G,U){return{kind:"word",text:G,dynamic:U.kind==="word"&&(U.dynamic||G.includes("$"))}}function hE(G){if(!G.startsWith("-")||G==="-")return null;let U=G.slice(1),j=U.indexOf(":");if(j===-1)return{name:U.toLowerCase()};return{name:U.slice(0,j).toLowerCase(),value:U.slice(j+1)}}function yE(G){return"path".startsWith(G)||"literalpath".startsWith(G)}function bE(G){return"recurse".startsWith(G)}function CE(G){return G.length>=2&&"force".startsWith(G)}function SE(G){return G==="wi"||"whatif".startsWith(G)}function vE(G){if(G===void 0||G==="")return!0;let U=G.toLowerCase();return U==="$true"||U==="true"}function EE(G){return G.toLowerCase()}var po="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",As="Unsupported heredoc syntax",di="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function go(){return{id:"analysis.dynamic-shell-source",reason:di,intent:"stop_and_explain"}}var uf="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var RE=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),xE=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),_E=new Set(["-o","--output","--query","--subscription"]),wE=new Set;function df(G){if(G==="aws")return RE;if(G==="gcloud")return xE;if(G==="az")return _E;return wE}var PE=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),AE=new Set;function mf(G){if(G==="git")return Sn;if(G==="docker")return PE;return AE}function A(G,U){if(G.length===0||U.length===0)return null;let j=Mt(G[0]??""),K=dn(G);for(let re of U){if(!kE(j,re.command))continue;if(re.match){if(TE(j,G,re.match))return ff(re);continue}if(!OE(j,G,re.subcommand))continue;if(DE(G,new Set(re.block_args),K))return ff(re)}return null}function ff(G){return{id:`custom.${G.name}`,reason:`[${G.name}] ${G.reason}`,intent:G.intent??"manual_only"}}function TE(G,U,j){let K=U.slice(1);if(j.exclude_args?.some((re)=>K.includes(re)))return!1;if(j.any_args&&!j.any_args.some((re)=>K.includes(re)))return!1;return IE(K,j.command_path,df(G))}function IE(G,U,j){let K=0,re=!1;for(let oe of G){if(K>=U.length)return!0;if(re){re=!1;continue}if(oe.startsWith("-")){re=!oe.includes("=")&&j.has(oe);continue}if(oe!==U[K])return!1;K++}return K>=U.length}function kE(G,U){return G===Mt(U)}function OE(G,U,j){if(!j)return!0;return pf(U,1,j,mf(G))}function pf(G,U,j,K){let re=!1;for(let oe=U;oe<G.length;oe++){let de=G[oe];if(!de)continue;if(re){re=!1;continue}if(de==="--"){let Se=G[oe+1];if(Se&&!Se.startsWith("-"))return Se===j;return!1}if(K.has(de)){re=!0;continue}if(de.startsWith("-")){if(!de.includes("=")&&ME(G,oe,j,K))return!0;continue}return de===j}return!1}function ME(G,U,j,K){let re=G[U+1];if(!re||re.startsWith("-"))return!1;return pf(G,U+2,j,K)}function DE(G,U,j){return G.some((K)=>U.has(K))||[...j].some((K)=>U.has(K))}var NE=new Set(["-e","--source"]),LE=new Set(["-F","-v","--assign","--field-separator"]),gf=new Set(["-f","--file"]),WE=new Set(["print","printf","return"]),hf=[{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"}],FE="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 yf(G,U,j){let K=!1;for(let re of GE(G)){let oe=zE(re,j);if(!oe)continue;for(let de of oe.commands){let Se=U(de);if(Se)return Se;if(de.includes("{}")||/[$`]/.test(de))K=!0}K||=oe.dynamic}return K?_t("awk.system-dynamic",FE):null}function Hl(G){let U=[],j=!1,K=!1,re=!0,oe=!0;for(let de=1;de<G.length;de++){let Se=G[de];if(Se===void 0)break;if(re&&Se==="--"){re=!1;continue}if(re&&NE.has(Se)){j=!0;let we=G[de+1];if(oe&&=we!==void 0,we!==void 0)U.push({tokenIndex:de+1,kind:"inline-code",value:we});de++;continue}if(re&&Se.startsWith("--source=")){j=!0,U.push({tokenIndex:de,kind:"inline-code",value:Se.slice(9)});continue}if(re&&Se.startsWith("-e")&&Se.length>2){j=!0,U.push({tokenIndex:de,kind:"inline-code",value:Se.slice(2)});continue}if(re&&(LE.has(Se)||gf.has(Se))){let we=G[de+1];if(oe&&=we!==void 0,gf.has(Se)){if(K=!0,we!==void 0)U.push({tokenIndex:de+1,kind:"program-file",value:we})}de++;continue}if(re&&(Se.startsWith("-F")||Se.startsWith("-v")&&Se.slice(2).includes("=")))continue;if(re&&Se.startsWith("-f")&&Se.length>2){K=!0,U.push({tokenIndex:de,kind:"program-file",value:Se.slice(2)});continue}if(re&&(Se.startsWith("--assign=")||Se.startsWith("--field-separator=")))continue;if(re&&Se.startsWith("--file=")){K=!0,U.push({tokenIndex:de,kind:"program-file",value:Se.slice(7)});continue}if(re&&Se.startsWith("-")&&Se!=="-")continue;if(!j&&!K)U.push({tokenIndex:de,kind:"main-program",value:Se});return{sources:U,optionsOpen:!1}}return{sources:oe?U:[],optionsOpen:re&&oe}}function fi(G){return Hl(G).sources}function GE(G){return fi(G).filter((U)=>U.kind!=="program-file").map((U)=>U.value)}function zE(G,U){Rn(U,G);let j=G.includes("system")?jl(G,U):null,K=$E(G,U);if(!j&&!K)return null;return{dynamic:!!j?.dynamic||!!K?.dynamic,commands:[...j?.commands??[],...K?.commands??[]]}}function jl(G,U){Rn(U,G);let j=[],K=!1,re=!1,oe=0;while(oe<G.length){let de=G[oe];if(de==='"'||de==="'"){oe=Is(G,oe,de)?.endIndex??oe+1;continue}if(de==="#"){oe=bf(G,oe+1);continue}if(de==="/"&&Cf(G,oe)){oe=Sf(G,oe+1)??oe+1;continue}if(!G.startsWith("system",oe)){oe++;continue}let Se=oe;if(oe+=6,mi(G[Se-1])||mi(G[oe]))continue;let we=Ts(G,oe);if(G[we]!=="(")continue;we=Ts(G,we+1);let We=G[we];if(We!=='"'&&We!=="'"){K=!0,re=!0;continue}let mt=Is(G,we,We);if(!mt){K=!0,re=!0;continue}if(we=Ts(G,mt.endIndex),K=!0,G[we]!==")"){re=!0,oe=mt.endIndex;continue}j.push(mt.value),oe=we+1}if(!K)return null;return{dynamic:re,commands:j}}function $E(G,U){Rn(U,G);let j=[],K=!1,re=!1,oe=0,de=0,Se=null,we=null,We=0;while(oe<G.length){let mt=G[oe];if(!mt)break;if(mt==='"'||mt==="'"){let pt=Is(G,oe,mt);if(pt&&We===de)we={...pt,startIndex:oe};We=pt?.endIndex??oe+1,oe=pt?.endIndex??oe+1;continue}if(mt==="#"){oe=bf(G,oe+1),de=oe,Se=null,we=null,We=oe;continue}if(mt==="/"&&Cf(G,oe)){let pt=Sf(G,oe+1);We=pt??oe+1,oe=pt??oe+1;continue}if(`;
32
+ {}`.includes(mt)){oe++,de=oe,Se=null,we=null,We=oe;continue}if(Se===null&&(Ul(G,oe,"print")||Ul(G,oe,"printf")))Se=oe;if(mt!=="|"||G[oe-1]==="|"||G[oe+1]==="|"){if(!/\s/.test(mt))We=oe+1;oe++;continue}let gt=G[oe+1]==="&"?oe+2:oe+1,ft=Ts(G,gt);if(Ul(G,ft,"getline")){re=!0;let pt=HE(de,we,We);if(K||=pt===null,pt!==null)j.push(pt);We=gt,oe=gt;continue}if(VE(de,Se)){re=!0;let pt=UE(G,ft);if(!pt){K=!0,We=gt,oe=gt;continue}if(!BE(G,pt.endIndex)){K=!0,We=pt.endIndex,oe=pt.endIndex;continue}j.push(pt.value),We=pt.endIndex,oe=pt.endIndex;continue}We=gt,oe++}if(!re)return null;return{dynamic:K,commands:j}}function mi(G){return!!G&&/[A-Za-z0-9_]/.test(G)}function Ts(G,U){let j=U;while(/\s/.test(G[j]??""))j++;return j}function BE(G,U){let j=U;while(/[\t\f\v\r ]/.test(G[j]??""))j++;let K=G[j];return!K||`;
33
+ }#`.includes(K)}function Is(G,U,j){let K="",re=!1;for(let oe=U+1;oe<G.length;oe++){let de=G[oe];if(!de)break;if(re){let Se=jE(G,oe);if(!Se)return null;K+=Se.value,oe=Se.endIndex,re=!1;continue}if(de==="\\"){re=!0;continue}if(de===j)return{value:K,endIndex:oe+1};K+=de}return null}function UE(G,U){let j=G[U];if(j!=='"'&&j!=="'")return null;return Is(G,U,j)}function HE(G,U,j){if(!U)return null;return U.startIndex>=G&&U.endIndex===j?U.value:null}function jE(G,U){let j=G[U];if(!j)return null;if(j==="x"){let re=G.slice(U+1,U+3);if(!/^[0-9A-Fa-f]{2}$/.test(re))return null;return{value:String.fromCharCode(Number.parseInt(re,16)),endIndex:U+2}}if(/[0-7]/.test(j)){let re=/^[0-7]{1,3}/.exec(G.slice(U));if(!re)return null;return{value:String.fromCharCode(Number.parseInt(re[0],8)),endIndex:U+re[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
34
+ `,r:"\r",t:"\t",v:"\v"}[j]??j,endIndex:U}}function Ul(G,U,j){return G.startsWith(j,U)&&!mi(G[U-1])&&!mi(G[U+j.length])}function VE(G,U){return U!==null&&U>=G}function bf(G,U){let j=G.indexOf(`
35
+ `,U);return j===-1?G.length:j+1}function Cf(G,U){let j=qE(G,U);if(j===-1)return!0;if("{([,;!~=".includes(G[j]??""))return!0;let K=j;while(mi(G[K-1]))K--;return WE.has(G.slice(K,j+1))}function qE(G,U){for(let j=U-1;j>=0;j--)if(!/\s/.test(G[j]??""))return j;return-1}function Sf(G,U){let j=!1;for(let K=U;K<G.length;K++){let re=G[K];if(!re)break;if(j){j=!1;continue}if(re==="\\"){j=!0;continue}if(re==="/")return K+1}return null}var KE="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",YE="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",ZE="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function vf(G){return G==="dd"||G==="shred"||G==="mkfs"||G.startsWith("mkfs.")}function Ef(G,U){let j=U.slice(1);if(G==="dd"&&j.some((K)=>/^of=\/dev\/.+/.test(K)))return _t("dd.device-write",KE);if((G==="mkfs"||G.startsWith("mkfs."))&&j.some((K)=>K.startsWith("/dev/")))return _t("mkfs.device",YE);if(G==="shred"&&j.length>0)return _t("shred.target",ZE);return null}var XE=new Set(["sudo","env","command","builtin"]),JE=new Set(["caffeinate","exec","nice","nohup","setsid","stdbuf","time","timeout"]);function ks(G,U){let j=G[0];if(!j||!Rf(kt(j),U))return null;let K=kt(j),re=G[1]==="--"?2:1,oe=QE(G,re,K,U),de=oe[0];if(de===void 0)return null;return{wrapper:K,tokens:G.slice(de),childIndex:de,alternativeChildIndices:oe.slice(1)}}function QE(G,U,j,K){let re=G[1]==="--",oe=[];for(let de=U;de<G.length;de++){let Se=G[de];if(!Se)continue;let we=kt(Se)!==j&&eR(Se,K);if(we)oe.push(de);if(!we&&Fi.has(Mt(Se)))break;if(re)break}return oe}function eR(G,U){let j=kt(G),K=Mt(G);return K==="git"||j==="busybox"||Wr(G)||Da.has(j)||vf(K)||Rf(j,U)||Vt.has(K)||G==="$SHELL"||Nn(K)||Tn.has(K)||U.rules.some((re)=>re.command===j)}function Rf(G,U){return JE.has(G)||U.transparentWrappers.includes(G)}function Wr(G){return XE.has(G.toLowerCase())}function Fr(G,U){return{embedded:!1,cwd:G.cwd,originalCwd:U.originalCwd,effectiveCwd:G.cwd,envAssignments:G.envAssignments,allowTmpdirVar:U.allowTmpdirVar,worktreeMode:U.worktreeMode,wrappedByTransparent:!1}}function Gn(G,U){let j=U.policy??{rules:[],transparentWrappers:[]};return Os([...G],U.environment,U.cwd,U.cwd,new Map,new Map(U.envAssignments??[]),j,{iterations:0},!1)}function*Os(G,U,j,K,re,oe,de,Se,we){let We=gs(G,U,j,oe);for(let[pt,ht]of We.envAssignments)oe.set(pt,ht),re.set(pt,ht);let{tokens:mt,cwd:gt}=We;if(We.envSplitValues){let pt=ps(We.envSplitValues,mt);if(!pt)throw new s("derivedCommandShape");Vl(Se),yield*Os(pt,U,gt,K,re,oe,de,Se,we);return}if(Wr(mt[0]??""))throw new s("wrapperPeelIterations");let ft=ks(mt,de);if(ft){for(let pt of[ft.childIndex,...ft.alternativeChildIndices])Vl(Se),yield*Os(pt===ft.childIndex?ft.tokens:mt.slice(pt),U,gt,K,new Map(re),new Map(oe),de,Se,!0);return}if(nR(mt)){Vl(Se),yield*Os(mt.slice(1),U,gt,K,re,oe,de,Se,we);return}yield tR(mt,gt,K,re,oe,we)}function tR(G,U,j,K,re,oe){return{tokens:G,cwd:U===null?void 0:U??j,wrapperCwd:U,wrapperEnvAssignments:K,envAssignments:re,head:kt(G[0]??"").toLowerCase(),wrappedByTransparent:oe}}function Vl(G){if(G.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");G.iterations++}function nR(G){return kt(G[0]??"").toLowerCase()==="busybox"&&G.length>1}function ql(G,U){let j=[],K=U;while(K<G.length){let re=G[K];if(re===void 0||re===":::")break;j.push(re),K++}return{markerIndex:K<G.length&&G[K]===":::"?K:-1,templateTokens:j}}function tr(G){let U=!1,j=!1;for(let K of G){if(K==="--")break;if(K==="-r"||K==="-R"||Kl(K,"recursive")){U=!0;continue}if(K==="-f"||Kl(K,"force")){j=!0;continue}if(K.startsWith("-")&&!K.startsWith("--")){if(K.includes("r")||K.includes("R"))U=!0;if(K.includes("f"))j=!0}}return U&&j}function Ms(G){let U=G.indexOf("--");return G.slice(1,U===-1?void 0:U).some((j)=>Kl(j,"recursive")||/^-[A-Za-z]+$/.test(j)&&/[rR]/.test(j.slice(1)))}function Kl(G,U){return G.length>2&&G.startsWith("--")&&U.startsWith(G.slice(2))}var rR=["--init-file","--rcfile"],oR=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function zn(G){for(let U=1;U<G.length;U++){let j=G[U];if(!j)continue;if(j==="-c")return xf(G,U,!0);if(j.startsWith("-")&&j.includes("c")&&!j.startsWith("--")){let K=xf(G,U,!1);if(K!==null)return K}}return null}function nr(G){let U=kt(G[0]??"").toLowerCase();if(U==="zsh"||U==="ksh")return vn(G).syntaxCheck;let j=!1;for(let K of G.slice(1)){if(K==="--")return j;if(K.startsWith("+")&&!K.startsWith("++")){if(K.slice(1).includes("n"))j=!1;continue}if(!K.startsWith("-")||K.startsWith("--"))return j;let re=K.slice(1);if(re.includes("n"))j=!0;if(re.includes("c"))return j}return j}function xf(G,U,j){if(G[U+1]==="--")return G[U+2]||null;let K=G[U+1];if(!K||!j&&K.startsWith("-"))return null;return K}function _f(G){let U=kt(G[0]??"").toLowerCase(),j=iR(G,U),K=oR.get(U)??null,re=j.argvSource?.kind!=="absent";return{argvSource:U==="bash"?j.argvSource:null,argvSourceApplies:U==="bash"&&j.interactive&&j.argvSource?.kind==="literal",envName:K,envSourceApplies:re&&(K==="BASH_ENV"?!j.interactive:K==="ENV"&&j.interactive)}}function iR(G,U){let j=vn(G),K=j.commandIndex??j.scriptIndex??G.length,re=[],oe=!1,de=!0;for(let Se=1;Se<K;Se++){let we=G[Se];if(we===void 0||we==="--"||we==="-"||we[0]!=="-"&&we[0]!=="+")break;if(we.startsWith("--")){if(U==="bash"&&de?rR.find((ft)=>we===ft):void 0){let ft=G[Se+1];re.push(ft===void 0?{kind:"absent"}:{kind:"literal",value:ft}),Se++;continue}let gt=we.split("=",1)[0]??we;if(U==="bash"&&Oa.has(gt)&&!we.includes("="))Se++;continue}if(U==="bash")de=!1;let We=Ma(U,we,G[Se+1],"startup");if(We.interactive)oe=we[0]==="-";Se+=We.followingValues}return{argvSource:re.at(-1)??null,interactive:oe}}var sR="find -delete permanently removes files. Use -print first to preview.",aR="find -exec rm -rf is dangerous. Use explicit file list instead.",lR=new Set(["-exec","-execdir","-ok","-okdir"]),cR=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((G)=>[G,1]),["-fprintf",2]]);function wf(G,U){let j=G.map(t),K=uR(G,j,U);if(K)return K;if(Ds(j,1)&&!hR(G,j,U)){let de=Tt(_t("find.delete",sR),U.policy);if(de)return de}let re=U.budget??Pn(),oe=0;while(oe<j.length){let de=j[oe],Se=rr(de??"");if(Se>0){oe+=Se+1;continue}if(!jn(de)){oe++;continue}re.charge("derivedTokens",j.length-oe-1);let we=ho(j,oe);oe=we.nextIndex;let We=bR(we.tokens,U.environment);if(We){let pt=Tt(We,U.policy);if(pt)return pt}let mt=de==="-execdir"||de==="-okdir",gt=U.analyzeTokens?.(we.tokens,mt?null:U.cwd)??null,ft=gt?.id.startsWith("custom.")?gt:Tt(gt,U.policy);if(ft)return ft}return null}function uR(G,U,j){if(!Ds(U,1)&&!Yl(U,j.environment))return null;let re=pi(G)??jt(["."]),oe=Hn({...j,allowPaths:j.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let de of re){let Se=ci(de);for(let we of Se.expandedTargets??[t(de)]){let We=xn(we,oe,{targetIsLiteral:Se.expandedTargets!==void 0||Se.targetIsLiteral,tmpdirWordSplittingProtected:Se.tmpdirWordSplittingProtected});if(We.kind==="root_or_home_target")return _t("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(We.kind==="git_metadata_target"&&!dR(G,oe.protectedGitMetadata,j.environment))return _t("find.delete-git-metadata",x)}}if(gR(U)&&oe.resolvedCwd&&Hm(re.map(t),oe.resolvedCwd,oe.protectedGitMetadata,oe.environment,oe.budget))return _t("find.delete-git-metadata",x);return null}function dR(G,U,j){if(!U)return!1;let K=G.map(t),re=[],oe=!1,de=pi(G)?.at(-1),Se=de?G.indexOf(de)+1:1;while(Se<K.length){let we=K[Se]??"";if(jn(we)){let We=ho(K,Se),mt=mr([...We.tokens],j),gt=Ms(mt),ft=Vt.has(kt(mt[0]??"").toLowerCase()),pt=We.tokens.some((yt)=>yt!=="{}"&&yt.includes("{}")),ht=(we==="-execdir"||we==="-okdir")&&mt.slice(1).some((yt)=>yt!=="{}"&&!yt.startsWith("-"));if(gt||ft||pt||ht)return!1;oe=!0,Se=We.nextIndex;continue}if(we==="-delete"){oe=!0,Se++;continue}if(we==="-name"||we==="-iname"){let We=G[Se+1];if(!(We?.provenance==="literal"&&!/[[\\]/.test(We.text)))return!1;if(!oe)re.push(fR(We.text,we==="-iname"));Se+=2;continue}if(!mR.has(we))return!1;Se+=1+rr(we)}return re.length>0&&!Vm(U,(we)=>re.every((We)=>We.test(we)))}var mR=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function fR(G,U){let j=G.replace(/[*?]|[.+^${}()|\]/]/g,(K)=>K==="*"?".*":K==="?"?".":`\\${K}`);return new RegExp(`^${j}$`,U?"isu":"su")}var pR=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function Yl(G,U){let j=0;while(j<G.length){if(!jn(G[j])){j++;continue}let K=ho(G,j),re=mr([...K.tokens],U),oe=kt(re[0]??"").toLowerCase(),de=Vt.has(oe)&&pR.test((zn(re)??"").replace(/["'\\]/g,""));if((oe==="rm"||oe==="rmdir"||de)&&re.some((we)=>we.includes("{}")))return!0;j=K.nextIndex}return!1}function gR(G){return G.some((U,j)=>{if(!["-name","-iname"].includes(U))return!1;return G[j+1]?.toLowerCase()==="hooks"})}function hR(G,U,j){if(U.includes("-L")||U.includes("-f")||U.includes("-follow"))return!1;let K=pi(G);if(!K)return!1;let re=j.envAssignments??new Map,oe=Wl(re,j.environment),de=j.trustedTmpdirValue??uo(re,j.environment),Se=j.allowTmpdirVar??!li(re,j.environment),we={environment:j.environment,protectedGitMetadata:j.protectedGitMetadata,cwd:j.cwd,originalCwd:j.originalCwd,strict:j.strict,allowTmpdirVar:Se&&de&&Boolean(oe),allowPaths:j.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:j.tmpdirWordSplittingUnsafe??Dr(re,j.environment),trustedTmpdirValue:de,budget:j.budget},We=Hn(we),mt=Hn({...we,cwd:j.originalCwd??j.cwd}),gt=j.originalCwd&&j.environment.paths.realpath(j.originalCwd),ft=j.cwd&&j.environment.paths.realpath(j.cwd),pt=gt&&ft&&!fo(ft,gt)?j.cwd:void 0;return K.every((ht)=>{let yt=ci(ht);if(yt.unsafeBraceExpansion)return!1;return(yt.expandedTargets??[t(ht)]).every((bt)=>{let Ct=/^\.\/*$/.test(bt)?pt:void 0,vt=Ct??bt,St={targetIsLiteral:yt.expandedTargets!==void 0||yt.targetIsLiteral,tmpdirWordSplittingProtected:yt.tmpdirWordSplittingProtected};if(!Xt(j.policy,"rm.recursive-force-paranoid",j.paranoid??!1)&&!Ct&&xn(vt,We,St).kind==="within_anchored_cwd")return!0;return tf(vt,Ct?mt:We,{...St,containmentTarget:yR(vt,oe)})})})}function yR(G,U){if(!U)return G;return G.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>U)}function pi(G){let U=(re)=>{let oe=G[re];return oe?t(oe):void 0},j=1;while(U(j)==="-H"||U(j)==="-P")j++;if(U(j)==="--")j++;let K=[];while(j<G.length){let re=U(j),oe=G[j];if(!re||!oe||re.startsWith("-")||["!","(",")"].includes(re))break;K.push(oe),j++}return K.length>0?K:null}function bR(G,U){let j=dr([...G],U);if(j.length===0)return null;let K=kt(j[0]??"");if(K==="busybox"&&j.length>1)j=j.slice(1),K=kt(j[0]??"");if(K==="rm"&&tr(j))return _t("find.exec-rm-recursive-force",aR);return null}function ho(G,U){let j=U+1;while(j<G.length&&G[j]!==";"&&!(G[j]==="+"&&G[j-1]==="{}"))j++;return{tokens:G.slice(U+1,j),nextIndex:Math.min(j+1,G.length)}}function Ds(G,U){let j=U;while(j<G.length){let K=G[j];if(!K){j++;continue}if(jn(K)){j=ho(G,j).nextIndex;continue}let re=rr(K);if(re>0){j+=re+1;continue}if(K==="-delete")return!0;j++}return!1}function rr(G){return cR.get(G)??(/^-newer[A-Za-z]{2}$/.test(G)?1:0)}function jn(G){return G!==void 0&&lR.has(G)}import{resolve as qx}from"node:path";function*Zl(G){for(let U of G.nodes)yield*SR(U)}function CR(G){return Object.freeze([...Zl(G)])}function dt(G){return Object.freeze(CR(G).map((U)=>Object.freeze(U.words.map((j)=>j.text))))}function gi(G){let U=y(G,"posix");if(U.status!=="complete"||U.nodes.length!==1)return null;let j=U.nodes[0];if(j?.kind!=="command")return null;if(j.redirections.length>0||j.nested.length>0)return null;if(j.words.some((K)=>K.provenance==="command-substitution"))return null;return j.words.map((K)=>K.text)}function*SR(G){if(G.kind==="command"){yield G;for(let U of G.nested)yield*Zl(U);return}if(G.kind==="group")yield*Zl(G.body)}var vR=5,Xl="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 rn(G){let U=G.indexOf("--");if(U===-1)return{index:-1,before:G,after:[]};return{index:U,before:G.slice(0,U),after:G.slice(U+1)}}function Af(G,U,j){let K=Ns(G,U,j),re=ER(K.entries);if(re.size===0)return{blockedReason:K.blockedReason,expanded:!1,tokens:G};let oe=G,de=!1;for(let Se=0;Se<vR;Se++){let{subcommand:we,rest:We}=_n(oe),mt=we?.toLowerCase();if(!mt||!re.has(mt))return{blockedReason:K.blockedReason,expanded:de,tokens:oe};let gt=re.get(mt),ft=PR(gt);if(ft===null||ft.length===0)return{blockedReason:Xl,expanded:!0,tokens:oe};oe=["git",...ft,...We],de=!0}return{blockedReason:Xl,expanded:!0,tokens:oe}}function Tf(G,U,j){return Ns(G,U,j).entries.some((K)=>K.key.toLowerCase()==="core.sshcommand")}function _n(G){if(G.length===0)return{subcommand:null,rest:[]};let U=G[0];if((U?kt(U).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let K=1;while(K<G.length){let re=G[K];if(!re)break;if(re==="--"){let oe=G[K+1];if(oe&&!oe.startsWith("-"))return{subcommand:oe,rest:G.slice(K+2)};return{subcommand:null,rest:G.slice(K+1)}}if(!re.startsWith("-"))return{subcommand:re,rest:G.slice(K+1)};K+=Sn.has(re)?2:1}return{subcommand:null,rest:[]}}function ER(G){let U=new Map;for(let j of G){let K=j.key.toLowerCase();if(!K.startsWith("alias."))continue;let re=K.slice(6);if(re!=="")U.set(re,j.value)}return U}function Ns(G,U,j){if(G.length===0)return{blockedReason:null,entries:[]};let K=G[0];if((K?kt(K).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let oe=xR(U,j);return{blockedReason:oe.blockedReason,entries:[...oe.entries,...RR(G,U,j)]}}function RR(G,U,j){let K=[],re=1;while(re<G.length){let oe=G[re];if(!oe||oe==="--"||!oe.startsWith("-"))return K;if(oe==="-c"){let de=Jl(G[re+1]);if(de)K.push(de);re+=2;continue}if(oe.startsWith("-c")&&oe.length>2){let de=Jl(oe.slice(2));if(de)K.push(de);re++;continue}if(oe==="--config-env"){let de=Pf(G[re+1],U,j);if(de)K.push(de);re+=2;continue}if(oe.startsWith("--config-env=")){let de=Pf(oe.slice(13),U,j);if(de)K.push(de);re++;continue}if(Sn.has(oe)){re+=2;continue}re++}return K}function xR(G,U){let j=_R(G,U),K=wR(G,U);return{blockedReason:j===null||K===null?Xl:null,entries:[...j??[],...K??[]]}}function _R(G,U){let j=Qn("GIT_CONFIG_PARAMETERS",G,U);if(j===void 0)return[];let K=[],re=gi(j);if(!re)return null;for(let oe of re){let de=Jl(oe);if(!de)return null;K.push(de)}return K}function wR(G,U){let j=ym(G,U);if(j.state==="absent")return[];if(j.state==="invalid")return null;let K=[];for(let re=0;re<j.count;re++){let oe=Qn(`GIT_CONFIG_KEY_${re}`,G,U)?.trim(),de=Qn(`GIT_CONFIG_VALUE_${re}`,G,U);if(!oe||de===void 0)return null;K.push({key:oe,value:de})}return K}function Jl(G){if(!G)return null;let U=G.indexOf("=");return{key:(U===-1?G:G.slice(0,U)).trim(),value:U===-1?void 0:G.slice(U+1)}}function Pf(G,U,j){let K=G?.indexOf("=")??-1;if(!G||K===-1)return null;return{key:G.slice(0,K).trim(),value:Qn(G.slice(K+1),U,j)}}function PR(G){let U=G?.trimStart();if(!U||U.startsWith("!"))return null;return gi(U)}var AR="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",TR="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",IR="git checkout --force discards uncommitted changes. Use 'git stash' first.",kR="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",OR="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",MR="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",DR="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",NR="git switch --force discards uncommitted changes. Use 'git stash' first.",LR="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",WR="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",FR="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",GR="git reset --merge can lose uncommitted changes. Use 'git stash' first.",zR="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",$R="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.",BR="git push --force destroys remote history. Use --force-with-lease for safer force push.",UR="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",HR="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",jR="git branch -D force-deletes without merge check. Use -d for safe delete.",VR="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",qR="git merge --abort discards merge conflict resolutions. Use 'git status' first.",KR="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",YR="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",ZR="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",XR="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",JR="git worktree remove --force can delete uncommitted changes. Remove --force flag.",QR=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),ex=new Set(["--recurse-submodules","--track","-t"]),Ql=new Set(["-b","-B","-U"]),ec=new Set(["-c","-C"]),tx=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function Dt(G,U){let j=G.split("=",1)[0]??G;return j.length>=4&&U.startsWith(j)&&j.startsWith("--")&&j.slice(2).length>=2}var yo=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function kf(G,U){let{subcommand:j,rest:K}=_n(G);if(!j)return null;switch(j.toLowerCase()){case"checkout":return pr(nx(K,U));case"switch":return pr(ox(K));case"restore":return pr(sx(K));case"reset":return lx(K);case"clean":return pr(ux(K));case"rm":return pr(dx(K));case"push":return Gr(mx(K));case"branch":return Gr(gx(K));case"stash":return Gr(Sx(K));case"worktree":return Gr(vx(K));case"rebase":return pr(hx(K));case"merge":return pr(yx(K));case"tag":return Gr(bx(K));case"reflog":return Gr(Cx(K));default:return null}}function pr(G){return G?{...G,localDiscard:!0}:null}function Gr(G){return G?{...G,localDiscard:!1}:null}function nx(G,U){let{index:j,before:K}=rn(G),re=dn(K,{shortOptsWithValue:Ql});if(K.some((Se)=>Dt(Se,"--force"))||re.has("-f"))return _t("git.checkout-force",IR);for(let Se of G){if(Se==="-b"||Se==="-B"||Se==="--orphan")return null;if(Dt(Se,"--pathspec-from-file"))return _t("git.checkout-pathspec-from-file",OR)}if(j!==-1){if(K.some((we)=>!we.startsWith("-")))return _t("git.checkout-ref-path",kR);return _t("git.checkout-double-dash",AR)}let oe=ix(G);if(oe.length>=2)return _t("git.checkout-ambiguous",MR);let de=oe[0];if(de===void 0||re.has("-d")||re.has("-t")||G.some((Se)=>Dt(Se,"--detach")||Dt(Se,"--track")))return null;if(rx(de)||U(de))return _t("git.checkout-double-dash",TR);return null}function rx(G){return G==="."||G===".."||/^\.\.?[/\\]/.test(G)||/^([/\\]|[A-Za-z]:[/\\])/.test(G)||G.endsWith("/")||G.startsWith(":")||/[*?[]/.test(G)}function ox(G){let{before:U}=rn(G);if(U.some((K)=>Dt(K,"--discard-changes")))return _t("git.switch-discard-changes",DR);let j=dn(U,{shortOptsWithValue:ec});if(U.some((K)=>Dt(K,"--force"))||j.has("-f"))return _t("git.switch-force",NR);return null}function ix(G){let U=[],j=0;while(j<G.length){let K=G[j];if(!K)break;if(K==="--")break;if(!K.startsWith("-")){U.push(K),j++;continue}if(QR.has(K)){j+=2;continue}if(ex.has(K)){let re=G[j+1],oe=K==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"];j+=re&&!re.startsWith("-")&&oe.includes(re)?2:1;continue}j++}return U}function sx(G){let U=ax(G);if(U.isTerminal||!U.hasPathspec&&!U.hasPatch||!U.hasWorktree)return null;return U.hasExplicitLocation?_t("git.restore-worktree",WR):_t("git.restore-unstaged",LR)}function ax(G){let U=!1,j=!1,K=!0,re=!1,oe=(de)=>{if(!re)K=!1,re=!0;if(de!==void 0)K=de};for(let de=0;de<G.length;de++){let Se=G[de];if(Se===void 0)break;if(Se==="--"){U||=de+1<G.length;break}if(Se==="--pathspec-from-file"){U=!0,de++;continue}if(Se.startsWith("--pathspec-from-file=")){U=!0;continue}if(Se==="-h"||Se==="--help"||Se==="--version")return{hasPathspec:U,hasPatch:j,hasWorktree:K,hasExplicitLocation:re,isTerminal:!0};if(Se==="--staged"){oe();continue}if(Se==="--no-staged"){oe();continue}if(Se==="--worktree"){oe(!0);continue}if(Se==="--no-worktree"){oe(!1);continue}if(Se==="--patch"){j=!0;continue}if(Se==="--no-patch"){j=!1;continue}if(tx.has(Se)){de++;continue}if(Se.startsWith("--"))continue;if(Se==="-"){U=!0;continue}if(!Se.startsWith("-")){U=!0;continue}for(let we=1;we<Se.length;we++){let We=Se.charAt(we);if(We==="h")return{hasPathspec:U,hasPatch:j,hasWorktree:K,hasExplicitLocation:re,isTerminal:!0};if(We==="S"){oe();continue}if(We==="W"){oe(!0);continue}if(We==="p"){j=!0;continue}if(We==="s"||We==="U"){if(we===Se.length-1)de++;break}}}return{hasPathspec:U,hasPatch:j,hasWorktree:K,hasExplicitLocation:re,isTerminal:!1}}function lx(G){let U=null;for(let j of G){if(Dt(j,"--hard")){U=_t("git.reset-hard",FR);break}if(Dt(j,"--merge")){U=_t("git.reset-merge",GR);break}}if(!U)return null;return cx(G)?Gr(U):pr(U)}function cx(G){for(let U of G){if(U==="--")return!1;if(!U.startsWith("-"))return!0}return!1}function ux(G){for(let j of G)if(j==="-n"||Dt(j,"--dry-run"))return null;let U=dn(G.filter((j)=>j!=="--"));if(G.some((j)=>Dt(j,"--force"))||U.has("-f"))return _t("git.clean-force",zR);return null}function dx(G){let U=!1,j=!1,K=!1;for(let re of rn(G).before){if(Dt(re,"--no-force")){U=!1;continue}if(Dt(re,"--force")){U=!0;continue}if(Dt(re,"--no-cached")){j=!1;continue}if(Dt(re,"--cached")){j=!0;continue}if(Dt(re,"--no-dry-run")){K=!1;continue}if(Dt(re,"--dry-run")){K=!0;continue}let oe=dn([re]);U||=oe.has("-f"),K||=oe.has("-n")}return U&&!j&&!K?_t("git.rm-force",$R):null}function mx(G){let{before:U,after:j}=rn(G),K=dn(U);if(U.some((de)=>Dt(de,"--mirror")))return _t("git.push-mirror",HR);if(U.some((de)=>Dt(de,"--force"))||K.has("-f")||If(U,j).some(fx))return _t("git.push-force",BR);if(U.some((de)=>Dt(de,"--delete"))||K.has("-d")||If(U,j).some(px))return _t("git.push-delete",UR);return null}function If(G,U){return[...G.filter((j)=>j!==""&&!j.startsWith("-")),...U]}function fx(G){return G.startsWith("+")||G.includes(":+")}function px(G){return G.length>1&&G.startsWith(":")}function gx(G){let{before:U}=rn(G),j=dn(U),K=j.has("-D")||j.has("-d")||U.some((oe)=>Dt(oe,"--delete")),re=j.has("-D")||j.has("-f")||U.some((oe)=>Dt(oe,"--force"));if(K&&re)return _t("git.branch-force-delete",jR);return null}function hx(G){let{before:U}=rn(G);return U.some((j)=>Dt(j,"--abort"))?_t("git.rebase-abort",VR):null}function yx(G){let{before:U}=rn(G);return U.some((j)=>Dt(j,"--abort"))?_t("git.merge-abort",qR):null}function bx(G){let{before:U}=rn(G);return dn(U).has("-d")||U.some((K)=>Dt(K,"--delete"))?_t("git.tag-delete",KR):null}function Cx(G){return G[0]==="delete"?_t("git.reflog-delete",YR):null}function Sx(G){for(let U of G){if(U==="drop")return _t("git.stash-drop",ZR);if(U==="clear")return _t("git.stash-clear",XR)}return null}function vx(G){let{before:U}=rn(G);if(!U.includes("remove"))return null;let K=dn(U);if(U.some((re)=>Dt(re,"--force"))||K.has("-f"))return _t("git.worktree-remove-force",JR);return null}import{dirname as Bx,isAbsolute as Ux,join as Vf,resolve as Hx}from"node:path";var nc="TMPDIR",rc="IFS",Mf=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Df=/^[A-Za-z_][A-Za-z0-9_]*$/,Nf=new Set(["export","typeset","declare","readonly"]),Ex=new Set(["builtin","command","time"]),Rx=new Set(["do","then","else"]),xx=new Set(["do","then","case"]),Of=new Set(["done","fi","esac"]),_x=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function Lf(G,U){return G.map((j)=>j.provenance==="variable"&&Uf(j.text)?Wf(j.text,U.shellAssignments):t(j))}function Wf(G,U){return G.replace(_x,(j,K,re)=>U.get(K??re??"")??j)}function Vn(G,U){let j=G.parts.every((re)=>re.provenance!=="literal"||!/[$`]/.test(re.raw));if(G.provenance!=="variable"||!j)return null;let K=Wf(G.text,U);return/^[~-]/.test(K)||/[\s$`*?[]/.test(K)?null:K}function Ff(G,U){return{env:G,effectiveEnvAssignments:Tx(G,U),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function Gf(G){return{env:G.env,effectiveEnvAssignments:G.effectiveEnvAssignments?new Map(G.effectiveEnvAssignments):void 0,shellAssignments:new Map(G.shellAssignments),bodyDepth:G.bodyDepth,bodyAssignments:new Set(G.bodyAssignments)}}function oc(G,U){let j=$f(G,U),K=G[0]??"";if(xx.has(K))U.bodyDepth+=1;if(K==="elif"||Of.has(K))U.bodyDepth=Math.max(0,U.bodyDepth-1);if(Of.has(K)&&U.bodyDepth===0)U.bodyAssignments.forEach((Se)=>{U.shellAssignments.delete(Se)}),U.bodyAssignments.clear();j.assignments.filter((Se)=>Se.persists).forEach((Se)=>{if(U.shellAssignments.set(Se.name,Se.value),U.bodyDepth>0)U.bodyAssignments.add(Se.name);ic(U,Se)});let re=j.commandIndex;if(re!==-1&&Nf.has(G[re]??""))G.filter((Se)=>Df.test(Se)&&tc(Se)).forEach((Se)=>{Ix(U,Se)});let oe=re===-1?-1:Bf(G,re);if(oe===-1||G[oe]!=="unset")return;let de=Ox(G,oe);if(de===null)return;G.slice(de).forEach((Se)=>{if(U.bodyDepth>0){U.shellAssignments.set(Se,"");return}kx(U,Se)})}function zf(G,U){let j=$f(G,U).assignments;if(j.length===0)return U.effectiveEnvAssignments;let K=new Map(U.effectiveEnvAssignments??[]);return j.forEach((re)=>{K.set(re.name,re.value)}),K}function $f(G,U){let j=Rx.has(G[0]??"")?1:0,K=G.findIndex((Se,we)=>we>=j&&!Uf(Se)),re=K!==-1&&Nf.has(G[Bf(G,K)]??""),oe=Ax(U);return{assignments:G.flatMap((Se,we)=>{let We=wx(Se,oe,U.env);if(!We)return[];if(K!==-1&&we>K&&!re&&!ms(We.name))return[];return oe.set(We.name,We.value),[{...We,persists:K===-1||re}]}),commandIndex:K}}function Bf(G,U){let j=U;while(Ex.has(G[j]??"")){j+=1;while(G[j]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(G[j]??""))return U;j+=1}}return j}function Uf(G){return kn(G)!==null||Mf.test(G)}function wx(G,U,j){return kn(G)??Px(G,U,j)}function Px(G,U,j){let K=fs(G,j,U);if(K)return K;let re=G.match(Mf)?.[1];if(!re)return null;let oe=G.indexOf("=");return{name:re,value:`${U.has(re)?U.get(re):j.get(re)??""}${G.slice(oe+1)}`}}function tc(G){return G===nc||G===rc||Tl(G)}function Ax(G){return new Map([...G.effectiveEnvAssignments??[],...G.shellAssignments])}function Tx(G,U){let j=[nc,rc].map((K)=>{let re=G.get(K);return re===void 0?null:[K,re]}).filter((K)=>K!==null);if(j.length===0)return U;return new Map([...j,...U??[]])}function ic(G,U){let j=new Map(G.effectiveEnvAssignments??[]);j.set(U.name,U.value),G.effectiveEnvAssignments=j}function Ix(G,U){ic(G,{name:U,value:G.shellAssignments.get(U)??G.effectiveEnvAssignments?.get(U)??G.env.get(U)??""})}function kx(G,U){if(!tc(U)&&!Df.test(U))return;if(G.shellAssignments.set(U,""),ms(U)&&G.env.has(U)){let K=new Map(G.env);K.delete(U),G.env=K}if(!tc(U)||U===nc||U===rc||No(U)){ic(G,{name:U,value:""});return}if(!G.effectiveEnvAssignments?.has(U))return;let j=new Map(G.effectiveEnvAssignments);j.delete(U),G.effectiveEnvAssignments=j.size===0?void 0:j}function Ox(G,U){let j=U+1;while(j<G.length){let K=G[j];if(!K)return null;if(K==="--")return j+1;if(K==="-v"){j++;continue}if(K.startsWith("-"))return null;return j}return j}import{resolve as Mx}from"node:path";function Ls(G,U){return Al.some((j)=>U?.has(j)||G.has(j))}function bo(G,U,j){if(!U)return{gitCwd:null,hasExplicitGitContext:!1};let K=j.realpath(Mx(U));if(K===null||!j.isDirectory(K))return{gitCwd:null,hasExplicitGitContext:!1};let re=K,oe=!1,de=1;while(de<G.length){let Se=G[de];if(!Se)break;if(Se==="--")break;if(!Se.startsWith("-"))break;if(Se==="-C"){let we=G[de+1];if(!we)return{gitCwd:null,hasExplicitGitContext:oe};let We=Hf(re,we,j);if(!We)return{gitCwd:null,hasExplicitGitContext:oe};re=We,de+=2;continue}if(Se.startsWith("-C")&&Se.length>2){let we=Hf(re,Se.slice(2),j);if(!we)return{gitCwd:null,hasExplicitGitContext:oe};re=we,de++;continue}if(Se==="--git-dir"||Se==="--work-tree"){oe=!0,de+=2;continue}if(Se.startsWith("--git-dir=")||Se.startsWith("--work-tree=")){oe=!0,de++;continue}de+=Sn.has(Se)?2:1}return{gitCwd:re,hasExplicitGitContext:oe}}function Hf(G,U,j){try{let K=ur(G,U,j);return j.isDirectory(K)?K:null}catch{return null}}function jf(G,U,j){if(!U.localDiscard||!j.worktreeMode||Ls(j.environment.env,j.envAssignments))return null;let K=bo(G,j.cwd,j.environment.paths);if(!K.gitCwd||K.hasExplicitGitContext)return null;let re=j.environment.worktreeFacts(K.gitCwd);if(!re)return null;if(sc(G,j,re))return null;return{kind:"worktree",originalReason:U.reason,gitCwd:K.gitCwd}}function sc(G,U,j){let{subcommand:K,rest:re}=_n(G),oe=K?.toLowerCase();if(U.dynamicArguments||Dx(re)||Gx(G,U.environment.env,U.envAssignments,j)||Wx(re)||Nx(oe,re))return!0;return oe==="clean"&&Fx(re)>1}function Dx(G){return G.some((U)=>/[$*?[]/.test(U))}function Nx(G,U){if(G==="checkout"){let{before:j}=rn(U),K=dn(j,{shortOptsWithValue:Ql}),re=j.some((de)=>Dt(de,"--force"))||K.has("-f"),oe=K.has("-B")||j.some((de)=>de==="-B"||de.startsWith("-B"));return re&&oe}if(G==="switch"){let{before:j}=rn(U),K=dn(j,{shortOptsWithValue:ec}),re=j.some((de)=>Dt(de,"--force"))||j.some((de)=>Dt(de,"--discard-changes"))||K.has("-f"),oe=j.some((de)=>de==="-C"||de.startsWith("-C")||Lx(de))||K.has("-C");return re&&oe}return!1}function Lx(G){let U=G.split("=",1)[0]??G;return U==="--force-create"||U.length>=9&&"--force-create".startsWith(U)}function Wx(G){return G.some((U)=>U.startsWith("--recurse-sub"))}function Fx(G){let U=0;for(let j of G){if(j==="--force"){U++;continue}if(j.startsWith("-")&&!j.startsWith("--")){for(let K of j.slice(1))if(K==="f")U++}}return U}function Gx(G,U,j,K){if(Qn("GIT_CONFIG_PARAMETERS",U,j)!==void 0)return!0;let re=Ns(G,U,j);if(re.blockedReason!==null)return!0;let oe=re.entries.map((Se)=>({key:Se.key.toLowerCase(),value:Se.value}));if(oe.some((Se)=>$x(Se.key)))return!0;let de=oe.filter((Se)=>Se.key==="submodule.recurse").at(-1);if(de)return de.value===void 0||zx(de.value);if(Cm(j))return!0;return K.recursiveSubmodules}function zx(G){let U=G.toLowerCase();return U!=="false"&&U!=="no"&&U!=="off"&&U!=="0"}function $x(G){return G==="include.path"||G.startsWith("includeif.")&&G.endsWith(".path")}function qf(G,U,j){let K=G.map((we)=>Vn(we,j.shellAssignments??new Map)??t(we)),re=j.environment.paths,oe=bo(K,j.cwd,re),de=j.originalCwd?re.realpath(Hx(j.originalCwd)):null;if(U.id.startsWith("git.push-")||de===null||oe.gitCwd===null||oe.hasExplicitGitContext||Ls(j.environment.env,j.envAssignments))return null;let Se=U.id==="git.worktree-remove-force"?Vx(G,j.shellAssignments,re):Kf(oe.gitCwd,re);if(Se===null||U.id!=="git.worktree-remove-force"&&!jx(Se,K,U,j)||!mo(Se,j.environment)||ws(Se,j.environment)||fo(de,Se)||fo(Se,de))return null;return{kind:"temp-root",originalReason:U.reason,gitCwd:oe.gitCwd}}function jx(G,U,j,K){let re=K.environment.paths,oe=Vf(G,".git");if(re.entryKind(oe)!=="present")return!1;if(re.isDirectory(oe))return!0;if(!j.localDiscard)return!1;let Se=K.environment.worktreeFacts(G);return Se!==null&&!sc(U,K,Se)}function Vx(G,U,j){let K=_n(G.map(t)).rest,{before:re,after:oe}=rn(K.slice(K.indexOf("remove")+1)),de=[...re.filter((mt)=>!mt.startsWith("-")),...oe],Se=de.length===1?de[0]??"":"",we=G.find((mt)=>mt.text===Se),We=(we&&Vn(we,U??new Map))??Se;if(!Ux(We)||/[\s$`*?[]/.test(We)||j.entryKind(We)!=="present"||!j.isDirectory(We))return null;return j.realpath(We)}function Kf(G,U){if(U.entryKind(Vf(G,".git"))!=="missing")return G;let j=Bx(G);return j===G?null:Kf(j,U)}var Kx="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.",Yx=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function Ws(G,U){return Yf(G,U)}function Yf(G,U,j){let K=G.map(t),re=Af(K,U.environment.env,U.envAssignments),oe=re.blockedReason?Tt(_t("git.alias-config",re.blockedReason),U.policy):null;if(oe)return oe;let de=re.tokens;if((bm(U.envAssignments)||Tf(K,U.environment.env,U.envAssignments))&&Zx(de))return _t("git.ssh-env",Kx);let Se=kf(de,(We)=>{let mt=bo(K,U.cwd,U.environment.paths).gitCwd;return mt!==null&&U.environment.paths.entryKind(qx(mt,We))!=="missing"});if(!Se)return null;if(re.expanded||re.blockedReason)return Se;let we=jf(K,Se,U)??qf(G,Se,U);if(!we)return Se;return j?.(we),null}function Zf(G,U){let j=null;return{match:Yf(G,U,(re)=>{j=re}),relaxation:j}}function Zx(G){let{subcommand:U,rest:j}=_n(G),K=U?.toLowerCase();if(!K)return!1;if(Yx.has(K))return!0;if(K==="archive")return rn(j).before.some((re)=>Dt(re,"--remote"));return K==="remote"&&Xx(j)}function Xx(G){return G.find((U)=>!Jx(U))?.toLowerCase()==="update"}function Jx(G){return G==="-v"||Dt(G,"--verbose")||Dt(G,"--no-verbose")}import{isAbsolute as A_}from"node:path";function Xf(G,U,j,K){let re=G.slice(0,U),oe=G.slice(U+j);return K.startsWith(re)&&K.endsWith(oe)?K.slice(re.length,K.length-oe.length):null}function Fs(G,U,j){let K=(oe)=>`${oe.tokenIndex}\x00${oe.kind}\x00${oe.value}`,re=new Set(G.map(K));return Array.from(U).some((oe)=>j(oe).some((de)=>!re.has(K(de))))}var Jf="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Qx="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.",e_="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",t_="rm -rf targeting root or home directory is extremely dangerous and always blocked.",n_="rm -rf in home directory is dangerous. Change to a project directory first.",Qf={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:t_},git_metadata_target:{id:"rm.git-metadata",reason:x},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:e_},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:n_},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:Jf},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:Qx},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:Jf}};function Gs(G,U){let j=Hn({...U,allowPaths:U.policy?.destructiveCommandAllowPaths,posixShell:!0}),K=G.map(t),re=Ms(K),oe=o_(G);for(let de of oe){let Se=ci(de.word);if(re&&Se.unsafeBraceExpansion){let we=Tt(Lr({kind:"outside_anchored_cwd"},j,U.policy,Qf),U.policy);if(we)return we;continue}for(let we of Se.expandedTargets??[de.text]){let We=an(we),mt={targetIsLiteral:Se.expandedTargets!==void 0||Se.targetIsLiteral,tmpdirWordSplittingProtected:Se.tmpdirWordSplittingProtected};if(!re&&j.resolvedCwd&&Mr(We,j.resolvedCwd,j.protectedGitMetadata,re,j.environment,j.budget))return _t("rm.git-metadata",x);if(!re)continue;for(let gt of r_(We,j,mt)){let ft=Lr(gt,j,U.policy,Qf),pt=Tt(ft,U.policy);if(pt)return pt}}}return null}function r_(G,U,j){let K=xn(G,U,j);if(K.kind==="cwd_self_target")return[K,xn(G,U,{...j,skipCwdSelf:!0})];if(K.kind!=="home_cwd_target")return[K];let re=xn(G,U,{...j,skipHomeCwd:!0});if(re.kind!=="cwd_self_target")return[K,re];return[K,re,xn(G,U,{...j,skipHomeCwd:!0,skipCwdSelf:!0})]}function o_(G){let U=[],j=!1;for(let K of G.slice(1)){let re=t(K);if(!re)continue;if(re==="--"){j=!0;continue}if(j){U.push({text:re,word:K});continue}if(!re.startsWith("-"))U.push({text:re,word:K})}return U}var gr={kind:"none"},zr={kind:"dynamic"},i_=new Set(["<","<<","<<-","<<<","<&","<>"]),tp=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,s_=/^(?:[0-9]+|[@*])$/,a_=cr.maxWords,np=cr.maxInputLength;function rp(G){if(!G||kt(Mt(G.words[0]?.text??""))!=="printf")return;if(G.words.some((re)=>re.provenance!=="literal"))return;let U=G.words.slice(G.words[1]?.text==="--"?2:1),j=U[0]?.text;if(j===void 0)return"";let K=U.slice(1).map((re)=>re.text);if(j==="%s")return K.join("");if(j==="%s\\n"||j===`%s
36
+ `)return`${K.join(`
37
+ `)}
38
+ `;if(j.includes("%")||/\\(?![\\nrt])/.test(j))return;return j.replaceAll("\\n",`
39
+ `).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function zs(G){let U=Co(G[1])==="--"?2:1;if(G.length<=U)return gr;let j=G.slice(U);if(!j.every(yi))return zr;return{kind:"literal",source:j.map(t).join(" ")}}function op(G){let U=Co(G[1])==="--"?2:1,j=G[U],K=Co(j);if(j===void 0||G.length<=U+1||K==="-"||K===""||K==="-l"||K==="-p")return gr;if(!yi(j))return zr;return{kind:"literal",source:K}}function $s(G,U){let j=ap(G);if(j===-1)return gr;let K=c_(U);if(!K)return gr;let re=[],oe=K.command?.length??0;for(let de of K.references){let Se=d_(de,G,j,K.ifs);if(!Se)return zr;if(oe+=Se.reduce((we,We)=>we+We.length+3,0),re.length+Se.length>a_||oe>np)return zr;re.push(...Se)}if(K.command==="eval")return{kind:"literal",source:re.join(" ")};if(re.length===0||/\s/.test(re[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[K.command,K.command&&K.optionTerminator?"--":null,...re.map(Bs)].filter((de)=>de!==null).join(" ")}}function ip(G,U){let j=ap(G),K=G.slice(j+1),re=/\bIFS\b/.test(U);if(j===-1||!K.every(yi)||re)return U;let oe=K.map(Co),de="",Se=null,we=0;while(we<U.length){let We=U[we]??"",mt=Se==="'"?null:/^\$(?:\{([0-9]+|[@*])\}|([0-9@*]))/.exec(U.slice(we));if(mt){let gt=mt[1]??mt[2],ft=gt==="@"||gt==="*"?oe.slice(1):[oe[Number(gt)]??""];if(Se!=='"'&&ft.some((ht)=>/[*?[]/.test(ht)))return U;if(de+=Se==='"'?ft.map((ht)=>ht.replace(/["$`\\]/g,"\\$&")).join(gt==="@"?'" "':" "):ft.map((ht)=>ht.split(/[ \t\n]+/).map((yt)=>yt?Bs(yt):"").join(" ")).join(" "),de.length>np)return U;we+=mt[0].length;continue}if(We==="\\"&&Se!=="'"){de+=U.slice(we,we+2),we+=2;continue}if(We==="'"&&Se!=='"'||We==='"'&&Se!=="'")Se=Se?null:We;de+=We,we++}return de}function sp(G,U,j,K){if(!vn(G.map(t)).readsStdinAsCommands)return gr;let re=U.filter((oe)=>(oe.fd===void 0||oe.fd===0)&&i_.has(oe.operator)).at(-1);if(re){if(re.operator==="<<"||re.operator==="<<-")return gr;if(re.operator!=="<<<"||re.target?.provenance!=="literal")return zr;return{kind:"literal",source:re.target.text}}if(!j)return gr;return K===void 0?zr:{kind:"literal",source:K}}function or(G,U=new Map){let j=vn(G.map(t)).scriptIndex;if(j===null)return gr;let K=G[j],re=Co(K);if(ro(K,re))return{kind:"literal",source:re};let oe=K?Vn(K,U):null;return oe===null?zr:{kind:"literal",source:oe}}var l_=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function uc(G){if(G.words.length!==2||G.redirections.length!==0||G.nested.length!==1)return!1;let U=G.words[0],j=G.words[1];if(!U||U.provenance!=="literal"||U.quoted||U.raw!==U.text||!j)return!1;if(!(U.text==="eval"&&j.quoted&&j.parts.length===3&&j.parts[0]?.raw==='"'&&j.parts[1]?.provenance==="command-substitution"&&j.parts[1].raw.startsWith("$(")&&j.parts[2]?.raw==='"'||U.text==="eval"&&!j.quoted&&j.parts.length===1&&j.parts[0]?.provenance==="command-substitution"&&j.parts[0].raw.startsWith("$(")||(U.text==="source"||U.text===".")&&!j.quoted&&j.parts.length===1&&j.parts[0]?.provenance==="command-substitution"&&j.parts[0].raw.startsWith("<(")))return!1;let re=G.nested[0];if(re?.status!=="complete"||re.nodes.length!==1)return!1;let oe=re.nodes[0];if(oe?.kind!=="command"||oe.redirections.length!==0||oe.nested.length!==0||oe.words.some((we)=>we.provenance!=="literal"||we.parts.some((We)=>We.provenance!=="literal")))return!1;let de=oe.words[0]?.text;if(de===void 0||kn(de)!==null)return!1;let Se=kt(Mt(de));return!l_.has(Se)&&!Vt.has(Se)&&!Wr(Se)}function ap(G){return vn(G.map(t)).commandIndex??-1}function c_(G){let U=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(G.trim()),j=U?.[4]??G.trim(),K=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(j),re=(K?.[3]??j).split(/\s+/).map(u_);if(re.length===0||re.some((oe)=>oe===null))return null;return{command:K?.[1]??null,optionTerminator:K?.[2]!==void 0,references:re.filter((oe)=>!!oe),ifs:U?U[1]??U[2]??U[3]??"":`
40
+ `}}function u_(G){let U=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(G),j=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(G),K=U??j;if(!K)return null;let re=K[1]??K[2];return{parameter:re==="@"||re==="*"?re:Number(re),quoted:U!==null}}function d_(G,U,j,K){let re=U.slice(j+2);if(G.parameter==="@")return G.quoted?ac(re):m_(re,K);if(G.parameter==="*"){let Se=ac(re);if(!Se)return;let we=Se.join(K[0]??"");return G.quoted?[we]:lc(we,K)}let oe=U[j+1+G.parameter];if(oe&&!yi(oe))return;let de=Co(oe);return G.quoted?[de]:lc(de,K)}function ac(G){return G.every(yi)?G.map(t):void 0}function m_(G,U){let j=ac(G);if(!j)return;let K=j.map((re)=>lc(re,U));return K.some((re)=>re===void 0)?void 0:K.flatMap((re)=>re??[])}function lc(G,U){if(["*","?","[","]"].some((j)=>G.includes(j)))return;if(U==="")return G===""?[]:[G];if(U===`
41
+ `)return G.trim().split(/\s+/).filter(Boolean);if(U.length!==1)return;return U===" "||U==="\t"||U===`
42
+ `?G.trim().split(/\s+/).filter(Boolean):G.split(U).filter(Boolean)}function yi(G){if(!G)return!0;return G.provenance==="unknown"?!/[$`]/.test(t(G)):G.provenance==="literal"}function Co(G){return G?t(G):""}function Bs(G){return`'${G.replaceAll("'",`'"'"'`)}'`}function dc(G,U){return cc(y(G,"posix"),U)}function bi(G){return dc(G,new Set(Array.from(G.matchAll(tp)).flatMap((U)=>{let j=U[1]??U[2];return j===void 0?[]:[j]})))}function cc(G,U){if(G.status==="invalid"||G.status==="limited")return!1;let j=new Set(U);for(let K of G.nodes){if(K.kind==="group"){if(cc(K.body,j))return!0;continue}if(K.kind!=="command")continue;if(K.nested.some((re)=>cc(re,j))||lp(K.words,j))return!0;y_(K,j)}return!1}function lp(G,U){let j=G.findIndex((de)=>kn(de.text)===null);if(j===-1)return!1;let K=G[j];if(!K)return!1;if(hi(K,U))return!0;let re=Mt(K.text);if(re==="source"||re==="."){let de=G[j+1]?.text==="--"?j+2:j+1;return ep(G[de],U)}if(Vt.has(re)){let de=G.slice(j),Se=vn(de.map((We)=>We.text)),we=Se.commandIndex??Se.scriptIndex;return!Se.syntaxCheck&&we!==null&&ep(de[we],U)}let oe=f_(G,j,U);if(oe===null)return!1;if(oe===-1)return!0;return lp(G.slice(oe),U)}function f_(G,U,j){let K=Mt(G[U]?.text??"");if(K==="command")return p_(G,U+1);if(K==="exec")return g_(G,U+1);if(K==="env")return h_(G,U+1,j);return null}function p_(G,U){for(let j=U;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return G[j+1]?j+1:null;if(/^-[p]*[vV][pvV]*$/.test(K))return null;if(/^-p+$/.test(K))continue;return j}return null}function g_(G,U){for(let j=U;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return G[j+1]?j+1:null;if(K==="-a"){j++;continue}if(/^-a.+/.test(K)||/^-[cl]+$/.test(K))continue;return j}return null}function h_(G,U,j){for(let K=U;K<G.length;K++){let re=G[K],oe=re?.text??"";if(oe==="--")return G[K+1]?K+1:null;if(oe==="-S"||oe==="--split-string")return hi(G[K+1],j)?-1:K+2;if(oe.startsWith("-S")||oe.startsWith("--split-string="))return hi(re,j)?-1:K+1;if(oe==="-u"||oe==="--unset"||oe==="-C"||oe==="--chdir"||oe==="-P"){K++;continue}if(oe==="-i"||oe==="-0"||oe==="--null"||oe.startsWith("-u=")||oe.startsWith("--unset=")||oe.startsWith("-C")||oe.startsWith("--chdir=")||oe.startsWith("-P"))continue;if(oe.startsWith("-"))continue;if(kn(oe))continue;return K}return null}function y_(G,U){if(!G.words.every((j)=>kn(j.text)!==null))return;for(let j of G.words){let K=kn(j.text);if(!K)continue;if(hi(j,U))U.add(K.name)}}function hi(G,U){if(!G)return!1;return G.parts.filter((j)=>j.provenance==="variable").some((j)=>Array.from(j.raw.matchAll(tp)).some((K)=>{let re=K[1]??K[2];return re!==void 0&&(s_.test(re)||U.has(re))}))}function ep(G,U){return!!G&&(G.parts.some((j)=>j.provenance!=="literal"&&j.provenance!=="variable")||hi(G,U))}var mc="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",fc="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",b_="__CC_SAFETY_NET_XARGS_INPUT__",Us="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",Hs="rm",C_=/(?:^|[;&|]\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,S_=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,v_=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,E_=/^(?:[0-9]+|[@*])$/;function dp(G,U){let j=G.map(t),{childStart:K,replacementToken:re}=$r(j),oe=j.slice(K),de=_t("xargs.shell-dynamic",fc);if(x_(oe,re,U)&&Tt(de,U.policy))return Tt(de,U.policy);for(let Se of Gn(oe,U)){let we=Se.tokens,We=re!==null&&we[0]!==oe[0]&&(we[0]?.includes(re)??!1)?Tt(de,U.policy):null;if(We)return We;let mt=yp(we,re,Se.wrapperEnvAssignments),gt=Se.head==="rm"&&re!==null&&gp(we,re),ft=U.analyzeChild(we,{...Fr(Se,U),dynamicInput:mt,dynamicSourceInput:gt||fp(we,Se.head,re,Se.wrapperEnvAssignments,mt,U.environment,U.strict?void 0:U.analyzeNested),dynamicRmInput:gt,shellDynamicMatch:de,dynamicSourceMatch:de,rmDynamicMatch:_t("xargs.rm-recursive-force-dynamic",mc)});if(ft)return ft;let pt=R_(we,re,U.policy?.rules??[],Tt(de,U.policy));if(pt)return pt;if(Se.head==="git"){let yt=re===null?[...we,b_]:we,bt=re!==null&&(we.some((vt)=>vt.includes(re))||Array.from(Se.envAssignments.values()).some((vt)=>vt.includes(re))),Ct=U.analyzeChild(yt,{...Fr(Se,U),worktreeMode:re===null||bt?!1:U.worktreeMode});if(Ct)return Ct}let ht=A(we,U.policy?.rules??[]);if(ht)return ht}return null}function R_(G,U,j,K){if(j.length===0)return null;if(U===null){for(let oe of j){let de=A([...G,...oe.subcommand?[oe.subcommand]:[],...oe.block_args],j);if(de)return de}return null}let re=Mt(G[0]??"");if(!j.some((oe)=>Mt(oe.command)===re))return null;return G.slice(1).some((oe)=>oe.includes(U))?K:null}function mp(G,U,j){let K=G.indexOf(U);if(K===-1||G.indexOf(U,K+U.length)!==-1)return[];let re=Xf(G,K,U.length,j);return re===null?[]:[re]}function fp(G,U,j,K,re,oe,de){if(Vt.has(U)){if(nr(G))return!1;if(j!==null&&__(G,j,de))return!0;let Se=zn(G);if(!Se){let we=or(jt(G));if(we.kind==="literal")return j!==null&&we.source.includes(j);return we.kind==="none"&&re}if(j!==null&&Se.includes(j)&&!pp(Se,j,de))return!0;if(In(Se))return!0;return w_(Se,j,K)}if(Nn(U))return cp(G,j,us,fm(U));if(Tn.has(U))return cp(G,j,Hl,hf);if(U==="eval"){let Se=zs(jt(G));if(Se.kind==="dynamic")return!0;if(j!==null)return Se.kind==="literal"&&Se.source.includes(j);return re}if(U==="find")return P_(G,j,oe);if(U==="git"){let Se=_n(G);return j===null?Se.subcommand===null:(Se.subcommand?.includes(j)??!1)||Se.subcommand!==null&&yo.has(Se.subcommand.toLowerCase())&&hp(Se.rest,j).some((we)=>we.includes(j))}return!1}function pp(G,U,j){if(j===void 0)return!1;let K=U.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+)*["']?${K}`).test(G)||/\bcase\b/.test(G))return!1;let oe=G.replaceAll(U,"/");return In(oe)===null&&j(oe)===null}function cp(G,U,j,K){let re=j(G);if(U===null)return re.optionsOpen||j([...G,Us]).sources.some((Se)=>Se.value===Us);if(re.sources.some((Se)=>Se.value.includes(U)))return!0;let oe=K.flatMap((Se)=>[Se.selector,...Se.valueForm==="attached-only"||Se.valueForm==="attached-or-separate"?[`${Se.selector}${Us}`]:[],...Se.valueForm==="equals-or-separate"?[`${Se.selector}=${Us}`]:[]]),de=new Set(oe.flatMap((Se)=>G.flatMap((we)=>mp(we,U,Se))));return Fs(re.sources,de,(Se)=>j(G.map((we)=>we.replaceAll(U,Se))).sources)}function x_(G,U,j){if(G.length===0||(G[0]??"").toLowerCase()==="command")return!1;let K=new Set(Array.from(Gn(G,j),(oe)=>oe.head)),re=U===null?[...G,Hs]:G.map((oe,de)=>de===0?oe:oe.replaceAll(U,Hs));return Array.from(Gn(re,j)).some((oe)=>oe.head===Hs&&!K.has(Hs))}function gp(G,U){return hp(G.slice(1),U).some((j)=>j.includes(U)&&(j.startsWith("-")||j.startsWith(U)))}function hp(G,U){let j=G.findIndex((K)=>K==="--"&&!K.includes(U));return j===-1?G:G.slice(0,j)}function yp(G,U,j){if(U===null)return!0;return G.some((K)=>K.includes(U))||Array.from(j.values()).some((K)=>K.includes(U))}function __(G,U,j){let K=vn(G),re=K.commandIndex===null?"":G[K.commandIndex]??"";if(re.includes(U)&&!pp(re,U,j)||K.scriptIndex!==null&&(G[K.scriptIndex]??"").includes(U))return!0;return["-c","-nc","-cn",`--${U}`,U].some((de)=>G.some((Se,we)=>{if(we===0||!Se.includes(U))return!1;return mp(Se,U,de).some((mt)=>{let gt=G.map((pt,ht)=>ht===we?pt.replaceAll(U,mt):pt),ft=vn(gt);if(ft.commandIndex===null&&ft.scriptIndex===null)return!1;if(K.commandIndex===null&&ft.commandIndex!==null)return!0;if(K.scriptIndex===null&&ft.scriptIndex!==null)return!0;if(ft.commandIndex!==null&&(gt[ft.commandIndex]??"").includes(mt))return!0;return ft.scriptIndex!==null&&(gt[ft.scriptIndex]??"").includes(mt)})}))}function w_(G,U,j){let K=new Set(U===null?[]:Array.from(j).filter(([,re])=>re.includes(U)).map(([re])=>re));for(let re of G.matchAll(C_))if(up(re,K))return!0;for(let re of G.matchAll(S_))for(let oe of(re[1]??"").matchAll(v_))if(up(oe,K))return!0;return dc(G,K)}function up(G,U){let j=G[1]??G[2];return j!==void 0&&(E_.test(j)||U.has(j))}function P_(G,U,j){if(U===null)return!0;let K=!1,re=0;for(let oe=1;oe<G.length;oe++){let de=G[oe]??"";if(!K&&!de.startsWith("-")&&de!=="!"&&de!=="("){if(de.indexOf(U)===0)return!0;continue}if(K=!0,re>0){re--;continue}if(jn(de)){let we=ho(G,oe);oe=we.nextIndex-1;for(let We of Gn(we.tokens,{environment:j,cwd:void 0})){let mt=yp(We.tokens,U,We.wrapperEnvAssignments);if(We.head==="rm"&&gp(We.tokens,U)||fp(We.tokens,We.head,U,We.wrapperEnvAssignments,mt,j))return!0}continue}let Se=rr(de);if(Se>0){if(re=Se,de.includes(U))return!0;continue}if(de.includes(U))return!0}return!1}function $r(G){let U=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"]),j=null,K=1;while(K<G.length){let re=G[K];if(!re)break;if(re==="--")return{childStart:K+1,replacementToken:j};if(!re.startsWith("-"))return{childStart:K,replacementToken:j};if(re==="-I"){j=G[K+1]??"{}",K+=2;continue}if(re.startsWith("-I")&&re.length>2){j=re.slice(2),K++;continue}if(re==="--replace"){j="{}",K++;continue}if(re.startsWith("--replace=")){let oe=re.slice(10);j=oe===""?"{}":oe,K++;continue}if(re==="-J"){j=G[K+1]??"{}",K+=2;continue}K+=U.has(re)?2:1}return{childStart:G.length,replacementToken:j}}var Ci="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",Si="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",T_="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",I_="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Vs=/\{[^{}\s]*\}/g,bp=/\{\}|\{-?\d+\}/g,Cp=/[\s;&|<>()$`\\"']/,k_=["e","f","source","file","-e","-f","--source","--file"],O_=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],M_=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),D_=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),Sp=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),N_=new Set(["--workdir","--wd"]),vp="__CC_SAFETY_NET_PARALLEL_SOURCE__";function On(G,U){for(let j of G){let K=U(j);if(K)return K}return null}function xp(G){return On([...G],(U)=>In(U))}function _p(G,U){let j=G.map(t);if((U.envAssignments?.has("PARALLEL")?U.envAssignments.get("PARALLEL"):U.environment.env.get("PARALLEL"))?.trim()){let ht=So(U);if(ht)return ht}if(j.length===2&&(j[1]==="--version"||j[1]==="--help"))return null;let re=Wp(j),{template:oe,jobs:de,runsRemotely:Se,readsCommandsFromInput:we,unsupported:We,workdir:mt,dryRun:gt}=re;if(We){let ht=So(U);if(ht)return ht;let yt=xp(U.envAssignments?.values()??[]);if(yt)return yt}if(we){let ht=B_(U);if(ht)return ht}if(mt!==void 0&&Se){let ht=So(U);if(ht)return ht}let ft=U_(mt,U.cwd,U.environment.paths);if(ft===null){let ht=So(U);if(ht)return ht}let pt=Se?{...U,cwd:void 0,originalCwd:void 0}:ft===null||ft===void 0||ft===U.cwd?U:{...U,cwd:ft};if(gt){if([...Gn(oe,pt)].flatMap((yt)=>[...yt.envAssignments.values()]).some(hc)){let yt=So(U);if(yt)return yt}return null}if(oe.length===0){let ht=de.map((bt)=>bt[0]??"");U.budget.charge("derivedTokens",ht.length);let yt=kp(pt.envAssignments,pt.cwd,Se);return On(ht,(bt)=>U.analyzeNested(bt,yt))}return On(Gn(oe,pt),(ht)=>L_(ht,re,U,pt))}function L_(G,U,j,K){let{templateHasPlaceholder:re,runsRemotely:oe,usesStdin:de}=U,Se=G.tokens,we=[...G.envAssignments.values()];if(we.some(Np)){let Rt=So(j);if(Rt)return Rt}let We=xp(we);if(We)return We;let mt=we.some(Ft),gt=re||mt,ft=de&&gt,pt=kp(G.envAssignments,G.wrapperCwd,oe||ft),ht=gt?{...pt,worktreeMode:!1}:pt,yt=Se.join(" "),bt=Ft(yt.split(/[ \t\n=]/,1)[0]??""),Ct=!U.quotesCommand&&(bt||Se.some((Rt)=>Cp.test(Rt))),vt=bt||Cp.test(Se[0]??""),St=Ct&&vt&&U.jobs.length>0?null:W_(G,U,j,K,ht,mt);if(St||!Ct)return St;return wp(Ft(yt)?yt:`${yt} {}`,!bt,G,U,j,K,ht)}function W_(G,U,j,K,re,oe){let{jobs:de,templateHasPlaceholder:Se,runsRemotely:we,usesStdin:We}=U,mt=G.tokens,gt=Se||oe;if(Vt.has(G.head)){let pt=()=>{if(!Se||de.length===0)return null;return On(de,(bt)=>j.analyzeChild(js(mt,bt,j.budget),Fr(G,K)))};if(nr(mt))return pt();let ht=zn(mt);if(ht){if(Lp(ht)){let St=hr(j);if(St)return St;if(de.length===0)return null;return On(de,(Rt)=>j.analyzeNested(Mp(ht,Rt,j.budget),re))}if(Ft(ht))return wp(ht,!1,G,U,j,K,re);let bt=!oe&&(!Se||de.length>0)?(de.length>0?de:[void 0]).map((St)=>$s(jt(St===void 0?mt:Se?mt.map((Rt)=>Op(Rt,St)):[...mt,...St]),ht)):[];if(bt.some((St)=>St.kind==="dynamic")){let St=hr(j);if(St)return St}let Ct=bt.flatMap((St)=>St.kind==="literal"?[St.source]:[]);if(Ct.length>0)return j.budget.charge("derivedTokens",Ct.length),On(Ct,(St)=>j.analyzeNested(St,re));if(bi(ht)){let St=hr(j);if(St)return St}let vt=j.analyzeNested(ht,re);if(vt)return vt;if(gt)return hr(j);return null}let yt=or(jt(mt));if(yt.kind==="dynamic"||yt.kind==="literal"&&Ft(yt.source))return hr(j)??pt();if(yt.kind==="literal")return pt();if(de.length>0){let bt=hr(j);if(bt)return bt;let Ct=pt();if(Ct)return Ct;if(Se)return null;let vt=de.flatMap((St)=>St[0]===void 0?[]:[St[0]]);return j.budget.charge("derivedTokens",vt.length),On(vt,(St)=>j.analyzeNested(St,re))}if(gt||We)return hr(j)??pt();return null}if(G.head==="rm"&&tr(mt)){if(Se&&de.length>0)return On(de,(ht)=>pc(js(mt,ht,j.budget,bp),G.cwd,K));if(de.length>0)return On(de,(ht)=>pc(Rp(mt,ht,j.budget),G.cwd,K));let pt=pc(mt.flatMap((ht,yt)=>{if(yt===0||!Ft(ht))return[ht];return ht.startsWith("-")?[ht.replace(bp,"")]:[]}),G.cwd,K);if(pt)return pt;return Ip(j)}let ft=de.length>0?de:[void 0];return On(ft,(pt)=>{let ht=pt===void 0?mt:Se?js(mt,pt,j.budget):Rp(mt,pt,j.budget),yt=_t("parallel.shell-dynamic",Si),bt=We&&G.head==="find"?$_(ht,K):null,Ct=Ap(ht,We,j)??bt?.customResult??null,vt=Mt(G.head),St=We&&(vt==="rm"&&gc(ht)||vt==="xargs"&&Tp(ht)||bt?.rmOptions===!0),Rt=We&&(St||bt?.executedSource===!0||bt===null&&Pp(ht,vt)),wt=j.analyzeChild(ht,{...Fr(G,K),worktreeMode:we||We||gt?!1:j.worktreeMode,dynamicInput:We||gt,dynamicRmInput:St,dynamicSourceInput:Ct!==null||Rt,shellDynamicMatch:yt,dynamicSourceMatch:yt,rmDynamicMatch:_t("parallel.rm-recursive-force-dynamic",Ci)});if(Rt){let Et=Tt(yt,j.policy);if(Et)return Et}return wt??Ct??A(ht,j.policy?.rules??[])})}function wp(G,U,j,K,re,oe,de){if(K.jobs.length>0)return On(K.jobs,(We)=>re.analyzeNested(Mp(G,U?We.map(Bs):We,re.budget),de));let Se=gi(G);if(Se?.[0]&&Mt(Se[0])==="rm"&&tr(Se)){let We=Ip(re);if(We)return We}return(Se?re.analyzeChild(Se,{...Fr(j,oe),dynamicInput:K.usesStdin,shellDynamicMatch:_t("parallel.shell-dynamic",Si),rmDynamicMatch:_t("parallel.rm-recursive-force-dynamic",Ci)}):null)??re.analyzeNested(G,de)}function Pp(G,U){if(Ft(G[0]??""))return!0;if(U==="eval"||U==="source"||U===".")return!0;if(U==="parallel"||U==="xargs")return!0;if(Vt.has(U))return z_(G);if(U==="git")return F_(G);if(U==="find")return!0;if(Tn.has(U))return Ep(G,k_,fi);if(Nn(U))return Ep(G,O_,cs);return!1}function gc(G){let U=G.indexOf("--"),j=G.slice(1,U===-1?void 0:U);if(!G.some(Ft))return U===-1;return j.some((re)=>Ft(re)&&(re.startsWith("-")||Lp(re)))}function F_(G){if(G_(G))return!0;let U=_n(G);if(U.subcommand===null||Ft(U.subcommand))return!0;if(!yo.has(U.subcommand.toLowerCase()))return!1;let j=U.rest.indexOf("--"),K=U.rest.slice(0,j===-1?void 0:j);if(!G.some(Ft))return j===-1;return K.some(Ft)}function G_(G){for(let U=1;U<G.length;U++){let j=G[U];if(!j||j==="--"||!j.startsWith("-"))return!1;if(j==="-c"||j==="--config-env"){if(Ft(G[U+1]??""))return!0;U++;continue}if(j.startsWith("-c")&&j.length>2||j.startsWith("--config-env=")){if(Ft(j))return!0;continue}if(Ft(j))return!0}return!1}function z_(G){if(nr(G))return!1;let U=zn(G);if(U!==null)return Ft(U);let j=or(jt(G));if(j.kind==="literal")return Ft(j.source);if(j.kind==="dynamic")return!0;return!G.some(Ft)}function Ep(G,U,j){let K=j(G);if(K.some((re)=>Ft(re.value)))return!0;if(!G.some(Ft))return j([...G,vp]).some((re)=>re.value===vp);return Fs(K,U,(re)=>j(G.map((oe)=>Op(oe,[re]))))}function Ap(G,U,j){let K=j.policy?.rules??[];if(!U||K.length===0)return null;let re=K.filter((oe)=>Mt(oe.command)===Mt(G[0]??""));if(re.length===0)return null;if(G.slice(1).some(Ft))return hr(j);return On(re,(oe)=>A([...G,...oe.subcommand?[oe.subcommand]:[],...oe.block_args],[oe]))}function $_(G,U){let j={customResult:null,executedSource:!G.some(Ft),rmOptions:!1},K=!1,re=0,oe=null,de=()=>{if(!oe?.some(Ft))return;for(let Se of Gn(oe,U))j.executedSource||=Pp(Se.tokens,Se.head),j.rmOptions||=Se.head==="rm"&&gc(Se.tokens)||Se.head==="xargs"&&Tp(Se.tokens),j.customResult??=Ap(Se.tokens,!0,U)};for(let Se of G.slice(1)){if(!K&&!Se.startsWith("-")&&Se!=="!"&&Se!=="("){j.executedSource||=Ft(Se);continue}if(K=!0,oe){if(Se===";"||Se==="+"){de(),oe=null;continue}oe.push(Se);continue}if(re>0){re--;continue}if(jn(Se)){oe=[],j.executedSource||=Ft(Se);continue}let we=rr(Se);if(we>0){re=we,j.executedSource||=Ft(Se);continue}j.executedSource||=Ft(Se)}return de(),j}function Tp(G){let U=G.slice($r(G).childStart);return Mt(U[0]??"")==="rm"&&gc(U)}function qs(G,U){return(j)=>Tt(_t(G,U),j.policy)}var hr=qs("parallel.shell-dynamic",Si),B_=qs("parallel.command-stream-dynamic",T_),So=qs("parallel.command-stream-dynamic",I_),Ip=qs("parallel.rm-recursive-force-dynamic",Ci);function pc(G,U,j){return Tt(Gs(jt(G),{environment:j.environment,cwd:U,budget:j.budget,originalCwd:j.originalCwd,strict:j.strict,paranoid:j.paranoidRm,allowTmpdirVar:j.allowTmpdirVar,tmpdirWordSplittingUnsafe:Dr(j.envAssignments??new Map,j.environment),trustedTmpdirValue:uo(j.envAssignments??new Map,j.environment),protectedGitMetadata:j.protectedGitMetadata,policy:j.policy}),j.policy)}function kp(G,U,j){let K={};if(G)K.envAssignments=G;if(j)return K.effectiveCwd=null,K.worktreeMode=!1,K;if(U!==void 0)K.effectiveCwd=U;return Object.keys(K).length>0?K:void 0}function Op(G,U){return G.replace(Vs,(j)=>Dp(j,U))}function js(G,U,j,K=Vs){return j.charge("derivedTokens",G.reduce((re,oe)=>re+1+Math.floor(oe.length/64),0)),G.map((re)=>re.replace(K,(oe)=>{let de=Dp(oe,U);return j.charge("derivedTokens",Math.max(1,Math.ceil(de.length/64))),de}))}function Mp(G,U,j){return js([G],U,j)[0]??""}function Rp(G,U,j){return j.charge("derivedTokens",G.length+U.length),[...G,...U]}function Dp(G,U){let j=/^\{(-?\d+)[^{}\s]*\}$/.exec(G)?.[1];if(j===void 0)return U[0]??"";let K=Number(j);return U[K>0?K-1:U.length+K]??""}function Ft(G){return G.search(Vs)!==-1}function Np(G){if(hc(G))return!0;for(let U of G.matchAll(Vs))if(!/^(?:\{\}|\{\d+\})$/.test(U[0]))return!0;return!1}function hc(G){let U=G.indexOf("{=");return U!==-1&&G.indexOf("=}",U+2)!==-1}function Lp(G){return/^\{[^{}\s]*\}$/.test(G)}function U_(G,U,j){if(G===void 0)return;if(G==="..."||/^~|[{}$`*?[]/.test(G))return null;if(!U&&!A_(G))return null;try{return ur(U??G,G,j)}catch{return null}}function Wp(G){let U=1,j=[],K=G.length,re=-1,oe=!1,de=!1,Se=!1,we,We=!1,mt=G.some((yt)=>yt==="::::"||yt==="::::+"||yt===":::+");while(U<G.length){let yt=G[U];if(yt===void 0)break;if(yt===":::"){re=U;break}if(yt==="--"){let Rt=ql(G,U+1);j.push(...Rt.templateTokens),K=U+1,re=Rt.markerIndex;break}if(!yt.startsWith("-")){let Rt=ql(G,U);j.push(...Rt.templateTokens),K=U,re=Rt.markerIndex;break}let bt=G[U+1],Ct=yt.indexOf("="),vt=Ct===-1?yt:yt.slice(0,Ct),St=Ct===-1?void 0:yt.slice(Ct+1);if(yt==="--dry-run"){We=!0,U++;continue}if(yt==="-I"||yt.startsWith("-I")&&yt.length>2){mt||=(yt==="-I"?bt:yt.slice(2))!=="{}",U+=yt==="-I"?2:1;continue}if(yt==="--replace"||yt==="-i"){mt=!0,U+=2;continue}if(vt==="--replace"||yt.startsWith("-i")&&yt.length>2){let Rt=vt==="--replace"?St:yt.slice(2);mt||=Rt!==""&&Rt!=="{}",U++;continue}if(yt==="-a"||D_.has(vt)){mt=!0,U+=St===void 0?2:1;continue}if(yt==="-q"||yt==="--quote"){de=!0,U++;continue}if(yt==="--pipe"||yt==="--pipepart"){Se=!0,U++;continue}if(vt==="--env"){mt=!0,U+=St===void 0?2:1;continue}if(Sp.has(vt)||yt.startsWith("-S")&&yt.length>2){oe=!0,U+=Sp.has(yt)?2:1;continue}if(N_.has(vt)){mt=!0;let Rt=St??bt;if(Rt===void 0||Rt===":::"||Rt==="--"){U++;continue}we=Rt,U+=St===void 0?2:1;continue}if(yt.startsWith("-j")&&yt.length>2&&/^\d+$/.test(yt.slice(2))){U++;continue}if(yt.startsWith("--")&&St!==void 0){U++;continue}if(M_.has(yt)){if(bt===void 0||bt===":::"||bt==="--"){mt=!0,U++;continue}U+=2;continue}U+=yt==="-j"||yt==="--jobs"?2:1}mt||=j.some(We?hc:Np);let gt=[];if(re!==-1){let yt=[];for(let bt=re+1;bt<G.length;bt++){let Ct=G[bt];if(Ct===":::"){gt.push(yt),yt=[];continue}if(Ct!==void 0)yt.push(Ct)}gt.push(yt)}mt||=gt.length>1;let ft=H_(gt),pt=j.some(Ft),ht=j.length===0&&re===-1;return{template:j,jobs:ft,childStart:K,templateHasPlaceholder:pt,runsRemotely:oe,quotesCommand:de,usesStdin:Se||re===-1,readsCommandsFromInput:ht,unsupported:mt,workdir:we,dryRun:We}}function H_(G){if(G.length===0||G.some((j)=>j.length===0))return[];let U=[[]];for(let[j,K]of G.entries()){if(K.length===1){let oe=K[0];if(oe===void 0)return[];for(let de of U)de.push(oe);if(U.length*(j+1)>a.derivedTokens.cap)throw new s("derivedTokens");continue}let re=[];for(let oe of U)for(let de of K){if((re.length+1)*(j+1)>a.derivedTokens.cap)throw new s("derivedTokens");re.push([...oe,de])}U=re}return U}function Fp(G){return Wp(G).childStart}var j_="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",Ks="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function bc(G){return G?.parts.some((U)=>U.provenance==="command-substitution")??!1}function yc(G){return G?.parts.some((U)=>U.provenance==="literal"&&U.raw.replace(/^["']/,"").startsWith("-"))??!1}function zp(G,U,j,K,re=!1,oe){let Se=(jo(G,U)||K&&G!=="powershell"&&U[0]?.provenance==="variable")&&Xt(oe,"shell.dynamic-executable",re)?_t("shell.dynamic-executable",j_):null;return Tt(Se,oe)??$p(G,U,j,re,oe)}function $p(G,U,j,K,re){if(U.length<2)return null;let oe=U.flatMap((Se,we)=>bc(Se)?[we]:[]);if(oe.length===0)return null;let de=Mt(U[0]?.text??"");if(de==="git"){let Se=ne(G,U),we=q_(Se);if(Xt(re,"shell.dynamic-structure",K)&&oe.some((gt)=>gt<=we))return Tt(_t("shell.dynamic-structure",Ks),re);if(Tt(Ws(Se,{environment:j}),re))return null;let We=U[we]?.text.toLowerCase(),mt=Se.findIndex((gt,ft)=>ft>we&&t(gt)==="--");if(Xt(re,"shell.dynamic-structure",K)&&We&&yo.has(We)&&oe.some((gt)=>gt>we&&(mt===-1||gt<mt)))return Tt(_t("shell.dynamic-structure",Ks),re);return null}if(de==="find")return Xt(re,"shell.dynamic-structure",K)&&K_(U)?Tt(_t("shell.dynamic-structure",Ks),re):null;if(de==="rm"){let Se=U.findIndex((We,mt)=>mt>0&&t(We)==="--"),we=tr(U.map(t));return Xt(re,"shell.dynamic-structure",K)&&oe.some((We)=>(Se===-1||We<Se)&&(We<U.length-1||!we))?Tt(_t("shell.dynamic-structure",Ks),re):null}if(de==="xargs")return Gp(G,U.slice($r(U.map(t)).childStart),"xargs",j,K,re);if(de==="parallel")return Gp(G,U.slice(Fp(U.map(t))),"parallel",j,K,re);return null}function Gp(G,U,j,K,re,oe){if(U.length===0)return null;let de=V_(U,K);if(jo(G,de)){let we=Tt(_t(`${j}.shell-dynamic`,j==="xargs"?fc:Si),oe);if(we)return we}let Se=$p(G,de,K,re,oe);if(Se)return Se;if(de[0]?.text==="rm"&&de.slice(1).some((we)=>bc(we)&&yc(we)))return Tt(_t(`${j}.rm-recursive-force-dynamic`,j==="xargs"?mc:Ci),oe);return null}function V_(G,U){let j=kr(G,U),K=j.rewritten?jt(j.words.map(t)):j.words,re=K[0];return re&&t(re)==="busybox"?K.slice(1):K}function q_(G){let U=1;while(U<G.length){let j=G[U],K=j?t(j):"";if(Sn.has(K)){U+=2;continue}if(K.startsWith("-")){U++;continue}return U}return U}function K_(G){let U=!1,j=0,K=!1,re=!1;for(let oe=1;oe<G.length;oe++){let de=G[oe];if(!de)continue;let Se=bc(de);if(j>0){j--;continue}if(re){if(de.text===";"||de.text==="+"){re=!1,U=!0,K=!1;continue}if(Se&&(K||yc(de)))return!0;K=!1;continue}if(!U&&!de.text.startsWith("-")){if(Se&&(oe>1||yc(de)))return!0;continue}if(U=!0,Se)return!0;let we=rr(de.text);if(we>0){j=we;continue}if(jn(de.text))re=!0,K=!0}return!1}function Cc(G,U){return G.some((j)=>{if(j.value==="-"&&(j.kind==="main-script"||j.kind==="program-file"))return!0;return!ro(U[j.tokenIndex],j.value)})}var Bp="cmd rmdir /s or del /s outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Y_="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.",Z_="cmd rmdir /s or del /s target contains wildcards or variables that cannot be verified safely. Use literal paths within cwd.",X_="cmd rmdir /s or del /s targeting root or home directory is extremely dangerous and always blocked.",J_="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.",Q_="cmd rmdir /s or del /s in home directory is dangerous. Change to a project directory first.",ew={root_or_home_target:{id:"cmd.recursive-delete-root-or-home",reason:X_},git_metadata_target:{id:"cmd.recursive-delete-git-metadata",reason:x},dynamic_target:{id:"cmd.recursive-delete-dynamic-target",reason:Z_},home_cwd_target:{id:"cmd.recursive-delete-home-cwd",reason:Q_},cwd_self_target:{id:"cmd.recursive-delete-cwd-self",reason:Bp},within_anchored_cwd:{id:"cmd.recursive-delete-paranoid",reason:Y_},outside_anchored_cwd:{id:"cmd.recursive-delete-outside-cwd",reason:Bp}},tw=/^\/\/?[ck]$/i,Up=/[&|]+/,nw=/(?:"[^"]*"|[^\s"])+/g,rw=/[\^%!]/,ow=/\\"./s,iw=/(^|\/)[*.]*\*[*.]*$/,sw=/^"?[\\/]+[?.][\\/]/,aw=new Set(["rmdir","rd","del","erase"]),lw=/(?<![\w-])(?:rmdir|rd|del|erase)(?!\w)/i,cw=/\/s(?!\w)/i,uw=/(?<![\w-])(?:cd|chdir|pushd|popd)(?!\w)/i;function Hp(G,U){let j=G.map(t),K=j.findIndex((ft)=>tw.test(ft));if(K===-1)return null;let re=j.slice(K+1).join(" "),oe=/^".*"$/s.test(re)?re.slice(1,-1):re,de=oe.split(Up).map((ft)=>{let pt=ft.match(nw)??[],ht=pt.findIndex((bt)=>aw.has(bt.replace(/^@/,"").toLowerCase())),yt=ht===-1?[]:pt.slice(ht);return{piece:ft,tokens:pt,deleteTokens:yt,recursiveDelete:yt.slice(1).some((bt)=>bt.startsWith("/")&&bt.toLowerCase().split("/").includes("s"))}}),Se=de.filter((ft)=>ft.recursiveDelete),we=Se.length>0||lw.test(oe)&&cw.test(oe);if(we&&(oe.includes("\\\"")||U.gitBashEscapesBodyQuotes&&oe.includes('"')||U.powerShellRawWords.some((ft)=>ow.test(ft))||Se.some((ft)=>ft.tokens.some((pt)=>sw.test(pt)))))return _t("cmd.recursive-delete-escaped-quote",J_);let We=Hn({...U,allowPaths:U.policy?.destructiveCommandAllowPaths}),mt=de.reduce((ft,pt)=>ft??(pt.recursiveDelete?dw(pt.deleteTokens,We,U.policy):U.analyzeNested(pt.piece)),null),gt=we&&(Se.length===0||rw.test(oe)||uw.test(oe)||oe.includes('"')&&Up.test(oe));return mt??(gt?go():null)}function dw(G,U,j){return G.slice(1).filter((K)=>!K.startsWith("/")).reduce((K,re)=>K??Tt(Lr(xn(ui(re.replaceAll('"',"")).replace(iw,"$1*"),U),U,j,ew),j),null)}var mw="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.",fw=/^-(?:noprofile|nop|noninteractive|noni|nologo)$/i,pw=/^-(?:executionpolicy|ep)$/i,gw=/^-(?:command|c)$/i,hw=/^(?:--?|[/\u2013\u2014\u2015])(\w+)$/,yw="encodedcommand",bw=/(?<![\w-])(?:remove-item|ri|rm|rmdir|rd|del|erase)(?![\w-])/i,Cw=/(?<![\w-])(?:[-\u2013\u2014\u2015]{1,2}r(?:e(?:c(?:u(?:r(?:s(?:e|ive?)?)?)?)?)?)?(?!\w)|-[dfipvwx]*r[dfipvwx]*(?!\w))|\/s(?!\w)/i,Sw=/[$`]/,vw="--%";function jp(G,U){let j=G.map(t),K=j.every((de,Se)=>Se===0||de!==vw&&Ew(G[Se],de))?Sc(j,1):void 0,re=K===void 0?[]:j.slice(K+1);if(re.length>0)return U(re.join(" "));if(j.some(Rw))return go();let oe=j.join(" ");return bw.test(oe)&&Cw.test(oe)?_t("powershell.nested-recursive-delete-unread",mw):null}function Sc(G,U){let j=G[U]??"";if(gw.test(j))return U;if(fw.test(j))return Sc(G,U+1);return pw.test(j)?Sc(G,U+2):void 0}function Ew(G,U){return G?.provenance==="unknown"?!Sw.test(U):ro(G,U)}function Rw(G){let U=hw.exec(G)?.[1]?.toLowerCase();return U!==void 0&&(U==="ec"||yw.startsWith(U))}var qp=[{heads:new Set(["rm","rmdir"]),analyze:(G)=>Gs(G.words,vc(G))},{heads:new Set(["cmd"]),analyze:(G)=>Hp(G.words,{...vc(G),powerShellRawWords:G.options.commandView?.dialect==="powershell"?G.options.commandView.words.map((U)=>U.raw):[],gitBashEscapesBodyQuotes:G.options.commandView?.dialect!=="powershell",analyzeNested:(U)=>yr(G.options.analyzeNested(U,{effectiveCwd:G.effectiveCwd,envAssignments:G.envAssignments}))})},{heads:new Set(["powershell","pwsh"]),analyze:(G)=>jp(G.parsedWords,(U)=>yr(G.options.analyzeNested(U,{effectiveCwd:G.effectiveCwd,envAssignments:G.envAssignments,shell:"powershell"})))},{heads:new Set(["git"]),analyze:(G)=>Ws(G.words,Ec(G))},{heads:new Set(["find"]),analyze:(G)=>wf(G.words,{...vc(G),envAssignments:G.envAssignments,analyzeTokens:G.analyzeChildTokens})},{heads:new Set(["xargs"]),analyze:(G)=>dp(G.words,{...Vp(G),analyzeChild:G.analyzeChild,analyzeNested:(U,j)=>yr(G.options.analyzeNested(U,j))})},{heads:new Set(["parallel"]),analyze:(G)=>_p(G.words,{...Vp(G),analyzeChild:G.analyzeChild,analyzeNested:(U,j)=>yr(G.options.analyzeNested(U,j))})}];function Vp(G){return{environment:G.options.environment,cwd:G.cwd,originalCwd:G.originalCwd,strict:G.options.strict,paranoidRm:G.options.paranoidRm,paranoidInterpreters:G.options.paranoidInterpreters,allowTmpdirVar:G.allowTmpdirVar,protectedGitMetadata:G.options.protectedGitMetadata,budget:G.options.budget,envAssignments:G.envAssignments,worktreeMode:G.options.worktreeMode,policy:G.options.policy}}function yr(G){return G?{id:G.ruleId,reason:G.reason,intent:G.intent??"manual_only"}:null}function vc(G){return{environment:G.options.environment,cwd:G.cwd,originalCwd:G.originalCwd,strict:G.options.strict,paranoid:G.options.paranoidRm,allowTmpdirVar:G.allowTmpdirVar,tmpdirWordSplittingUnsafe:Dr(G.envAssignments,G.options.environment),trustedTmpdirValue:uo(G.envAssignments,G.options.environment),protectedGitMetadata:G.options.protectedGitMetadata,policy:G.options.policy,budget:G.options.budget}}function Ec(G){return{environment:G.options.environment,cwd:G.cwd,originalCwd:G.originalCwd,dynamicArguments:G.dynamicArguments,envAssignments:G.envAssignments,shellAssignments:G.options.shellAssignments,policy:G.options.policy,worktreeMode:G.options.worktreeMode}}function Zp(G){return qp.find((U)=>U.heads.has(G))?.analyze}function Eo(G,U,j){let K=j.trace;if(G.length===0)return null;let re=j.commandView?.dialect??"posix",oe=(Pt)=>Pt.map((Ot)=>re==="posix"?t(Ot):Ot.text),de=j.child,Se=de!==void 0&&!de.embedded,we=de?.embedded===!0,We=j.effectiveCwd===null,mt=de?de.cwd:We?void 0:j.effectiveCwd??j.cwd,gt=de?de.originalCwd:We?void 0:j.cwd,ft=ve(G);if(ft.envAssignments.size>0)K?.recordSegment({type:"env-strip",input:oe(G),envVars:[...ft.envAssignments.keys()],output:oe(ft.words)});let pt=kr(ft.words,j.environment,mt,new Map([...j.envAssignments??[],...ft.envAssignments])),ht=pt.envSplitValues??[];if(ht.length>0){let Pt=[...ht,...oe(pt.words)].join(" "),Ot=In(Pt);if(Ot)return K?.recordSegment({type:"dangerous-text",token:Pt,matched:!0,reason:Ot.reason}),cn(Ot);if(j.strict)return hn(K);let Gt=ps(ht,oe(pt.words));if(Gt){j.budget.charge("derivedTokens",Gt.length);let Qt=j.analyzeNested(Gt.join(" "),{effectiveCwd:pt.cwd===void 0?j.effectiveCwd:pt.cwd,envAssignments:new Map([...j.envAssignments??[],...ft.envAssignments,...pt.envAssignments])});if(Qt)return Qt}}let yt=pt.rewritten?jt(oe(pt.words)):ne(re,pt.words),bt=oe(yt),Ct={...j,wrapperNormalizationBudget:j.wrapperNormalizationBudget??{iterations:0}};if(K&&ft.words.length>yt.length){let Pt=oe(ft.words);K.recordSegment({type:"leading-tokens-stripped",input:Pt,removed:Pt.slice(0,Pt.length-yt.length),output:bt})}let vt=new Map([...j.envAssignments??[],...ft.envAssignments,...pt.envAssignments]),St=bt[0];if(!St)return null;if(Wr(St))throw new s("wrapperPeelIterations");let Rt=Mt(St),wt=pt.cwd===null?void 0:pt.cwd??mt,Et=pt.cwd===null?void 0:gt,At=pt.cwd===void 0?j.effectiveCwd:pt.cwd,It=de?de.allowTmpdirVar:!li(vt,j.environment),Kt=zp(re,pt.words,j.environment,U===0,j.strict,j.policy);if(Kt)return K?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:Kt.reason}),cn(Kt);let Kn=ks(bt,j.policy);if(Kn){for(let Pt of[Kn.childIndex,...Kn.alternativeChildIndices]){Kp(Ct.wrapperNormalizationBudget);let Ot=yt.slice(Pt);K?.recordSegment({type:"transparent-wrapper",wrapper:Kn.wrapper,output:oe(Ot)});let Gt=Eo(Ot,U,{...Ct,effectiveCwd:At,envAssignments:vt});if(Gt)return Gt}return null}let bn=we?void 0:Rt==="eval"?zs(yt):Rt==="trap"&&!Se?op(yt):void 0;if(Se&&de&&Rt==="eval"){if(bn?.kind==="dynamic")return vo(de,j.policy);if(bn?.kind==="literal"){let Pt=j.analyzeNested(bn.source,{effectiveCwd:At,envAssignments:vt});if(Pt)return Pt}return Ro(de,j.policy)}if(bn?.kind==="dynamic"&&(j.strict||!j.commandView||!uc(j.commandView)))return hn(K);if(bn?.kind==="literal"){K?.recordSegment({type:"recurse",reason:Rt==="eval"?"shell-eval":"shell-trap",innerCommand:bn.source,depth:U+1});let Pt=j.analyzeNested(bn.source,{effectiveCwd:At,envAssignments:vt,functionDefinitions:j.functionDefinitions});if(Pt)return Pt}if(Se?Vt.has(Rt):Jp(St,Rt)){if(nr(bt))return null;if(Se&&de){let Pt=zn(bt);if(Pt){if(de.dynamicSourceInput??de.dynamicInput){let Gt=vo(de,j.policy);if(Gt)return Gt}if(bi(Pt)){let Gt=vo(de,j.policy);if(Gt)return Gt}return j.analyzeNested(Pt,{effectiveCwd:At,envAssignments:vt})}let Ot=or(yt);if(Ot.kind==="dynamic")return vo(de,j.policy);if(Ot.kind==="literal")return de.dynamicSourceInput?vo(de,j.policy):null;return de.dynamicSourceInput??de.dynamicInput?vo(de,j.policy):null}if(we){let Pt=zn(bt),Ot=Pt?j.analyzeNested(Pt,{effectiveCwd:At,envAssignments:vt}):or(yt).kind==="dynamic"?hn(K):null;if(Ot)return Ot}if(de===void 0){let Pt=Pw(bt,vt,At,j,K,U);if(Pt)return Pt;let Ot=zn(bt);if(Ot){let Vr=$s(yt,Ot);if(Vr.kind==="dynamic")return hn(K);let aa=Vr.kind==="literal"?Vr.source:ip(yt,Ot),Yc=Aw(aa);K?.recordSegment({type:"shell-wrapper",wrapper:Rt,innerCommand:Yc}),K?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:Yc,depth:U+1});let Zc=j.analyzeNested(aa,{effectiveCwd:At,envAssignments:vt});if(Zc)return Zc;return bi(aa)?hn(K):null}let Gt=or(yt,j.strict?void 0:j.shellAssignments);if(Gt.kind==="dynamic")return hn(K);if(Gt.kind==="literal")return Ys(Gt.source,At,vt,j,K,U);let Qt=sp(yt,j.commandView?.redirections??[],j.hasPipelineInput??!1,j.literalShellInput);if(Qt.kind==="dynamic")return hn(K);if(Qt.kind==="literal")return K?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:Qt.source,depth:U+1}),j.analyzeNested(Qt.source,{effectiveCwd:At,envAssignments:vt})}}if(!de&&(Rt==="source"||Rt===".")){let Pt=bt[1]==="-p"?2:null;if(Pt!==null){let Vr=j.commandView?yt[Pt]:void 0;if(!Vr)return null;if(Vr.provenance!=="literal")return hn(K)}let Ot=Pt===null?1:3,Gt=bt[Ot]==="--"?Ot+1:Ot,Qt=j.commandView?yt[Gt]:void 0;if(!Qt)return null;if(Qt.provenance==="literal")return Ys(Qt.text,At,vt,j,K,U);if(j.strict||!j.commandView||!uc(j.commandView))return hn(K)}if(Tn.has(Rt)&&!we){if(!de&&j.strict&&Cc(fi(bt),yt))return hn(K);let Pt=yf(bt,(Gt)=>yr(j.analyzeNested(Gt,{effectiveCwd:At,envAssignments:vt}))),Ot=Tt(Pt,j.policy);if(Ot)return K?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:Ot.reason}),cn(Ot)}if(Nn(Rt)&&!we){if(!de&&j.strict&&Cc(cs(bt),yt))return hn(K);let Pt=mm(bt);if(Se&&de)return _w(Rt,Pt,At,vt,j,de);if(Pt){let Ot=Xt(j.policy,"interpreter.one-liner-paranoid",!!j.paranoidInterpreters);if(K?.recordSegment({type:"interpreter",interpreter:Rt,codeArg:Pt,paranoidBlocked:Ot}),Ot){let Qt=Tt(_t("interpreter.one-liner-paranoid",ti),j.policy);if(Qt)return cn(Qt)}if(_l(Rt,Pt))return null;K?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:Pt,depth:U+1});let Gt=j.analyzeNested(Pt,{effectiveCwd:At,envAssignments:vt});if(Gt&&!Xp(Gt,Pt))return Gt;if(ni(Pt,void 0,!j.strict)){let Qt=Tt(_t("interpreter.dangerous-command",so),j.policy);if(Qt)return K?.recordSegment({type:"dangerous-text",token:Pt,matched:!0,reason:so}),cn(Qt)}K=void 0}}if(Rt==="busybox"&&bt.length>1)return Kp(Ct.wrapperNormalizationBudget),K?.recordSegment({type:"busybox",subcommand:bt[1]??"unknown"}),K?.recordSegment({type:"recurse",reason:"busybox",innerCommand:bt.slice(1).join(" "),depth:U+1}),Eo(yt.slice(1),U,{...Ct,effectiveCwd:At,envAssignments:vt});let $t=de?null:Tt(Ef(Rt,bt),j.policy);if($t)return K?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:$t.reason}),cn($t);let Wt=K===Ct.trace?Ct:{...Ct,trace:K},sn={words:yt,parsedWords:pt.words,head:Rt,cwd:wt,originalCwd:Et,envAssignments:vt,allowTmpdirVar:It,dynamicArguments:pt.words.some((Pt)=>Pt.provenance==="command-substitution"),depth:U,effectiveCwd:At,options:Wt,analyzeChildTokens:(Pt,Ot)=>Se&&de?xc(Pt,U,Wt,{...de,cwd:Ot??void 0,effectiveCwd:Ot??void 0}):yr(Eo(jt(Pt),U+1,{...Wt,child:void 0,commandView:void 0,effectiveCwd:Ot,envAssignments:vt}))??A(Pt,Wt.policy.rules),analyzeChild:(Pt,Ot)=>xc(Pt,U,Wt,Ot)},Yt=de&&(Rt==="xargs"||Rt==="parallel")?void 0:Zp(Rt);if(Rt==="rm"||Rt==="xargs"||Rt==="parallel")K?.recordSegment({type:"tmpdir-check",tmpdirValue:vt.has("TMPDIR")||j.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:It});let Zt=K&&Rt==="git"?Zf(sn.words,Ec(sn)):void 0,Cn=Yp(Zt?Zt.match:Yt?.(sn)??null,j.policy);if(K)Tw(sn,Cn,Zt?.relaxation??null);if(Cn)return cn(Cn);if(Se&&de&&(Rt==="rm"||Rt==="rmdir")){if(!(Rt==="rm"&&(tr(bt)||de.dynamicRmInput)))return null;return(de.dynamicRmInput?Ro(de,j.policy):null)??ww(de,j.policy)}let Yn=Yt!==void 0&&!kw.has(Rt),vr=!de&&!Yn&&!Fi.has(Rt),To=K&&vr?[]:void 0;if(vr)for(let Pt=1;Pt<bt.length;Pt++){let Ot=bt[Pt];if(!Ot)continue;To?.push(Ot);let Gt=Yp(xw(bt,Pt,U,Wt,wt,Et,At,vt),j.policy);if(Gt)return K?.recordSegment({type:"fallback-scan",tokensScanned:To??[],embeddedCommandFound:Mt(Ot)}),cn(Gt)}if(K?.recordSegment({type:"fallback-scan",tokensScanned:To??[]}),we&&de&&!de.wrappedByTransparent)return null;let wn=A(bt,j.policy.rules);if(K?.recordSegment({type:"custom-rules-check",rulesChecked:j.policy.rules.length>0,matched:!!wn,reason:wn?.reason}),wn)return cn(wn);return Se&&de?Ro(de,j.policy):null}function xc(G,U,j,K){return yr(Eo(jt(G),U+1,{...j,trace:void 0,commandView:void 0,hasPipelineInput:void 0,literalShellInput:void 0,functionDefinitions:void 0,cwd:K.originalCwd,effectiveCwd:K.effectiveCwd,envAssignments:K.envAssignments,worktreeMode:K.dynamicInput?!1:K.worktreeMode,wrapperNormalizationBudget:{iterations:0},child:K}))}function xw(G,U,j,K,re,oe,de,Se){for(let we of Gn(G.slice(U),{environment:K.environment,cwd:re,envAssignments:Se,policy:K.policy})){let We=we.tokens[0];if(!We)continue;let mt=Mt(We);if(Jp(We,mt)||Zp(mt)!==void 0&&mt!=="xargs"&&mt!=="parallel"||we.wrappedByTransparent&&K.policy.rules.length>0)K.budget.charge("derivedTokens",G.length-U);let ft=xc(we.tokens,j,K,{embedded:!0,cwd:we.cwd,originalCwd:we.wrapperCwd===null?void 0:oe,effectiveCwd:we.wrapperCwd===void 0?de:we.wrapperCwd,envAssignments:we.envAssignments,allowTmpdirVar:!li(we.envAssignments,K.environment),worktreeMode:!1,wrappedByTransparent:we.wrappedByTransparent});if(ft)return ft}return null}function _w(G,U,j,K,re,oe){if(!U)return Ro(oe,re.policy);if(Xt(re.policy,"interpreter.one-liner-paranoid",!!re.paranoidInterpreters)){let Se=Tt(_t("interpreter.one-liner-paranoid",ti),re.policy);if(Se)return cn(Se)}if(_l(G,U))return Ro(oe,re.policy);let de=re.analyzeNested(U,{effectiveCwd:j,envAssignments:K});if(de&&!Xp(de,U))return de;if(ni(U,void 0,!re.strict)){let Se=Tt(_t("interpreter.dangerous-command",so),re.policy);if(Se)return cn(Se)}return Ro(oe,re.policy)}function Xp(G,U){let j=G.ruleId==="raw-text.dangerous-command",K=(G.reason.startsWith(As)||G.reason===po)&&!Gi(U);return j||K}function vo(G,U){let j=G.shellDynamicMatch?Tt(G.shellDynamicMatch,U):null;return j?cn(j):null}function Ro(G,U){let j=G.dynamicSourceInput&&G.dynamicSourceMatch?Tt(G.dynamicSourceMatch,U):null;return j?cn(j):null}function ww(G,U){let j=G.dynamicInput&&G.rmDynamicMatch?Tt(G.rmDynamicMatch,U):null;return j?cn(j):null}function Pw(G,U,j,K,re,oe){let de=_f(G);if(de.argvSource?.kind==="absent")return hn(re);if(de.argvSourceApplies&&de.argvSource){let we=Ys(de.argvSource.value,j,U,K,re,oe,!0);if(we)return we}if(!de.envSourceApplies||!de.envName)return null;let Se=U.get(de.envName);if(!Se)return null;return Ys(Se,j,U,K,re,oe,!0)}function Ys(G,U,j,K,re,oe,de=!1){if(de&&/[$`*?[\]]/.test(G))return hn(re);let Se=ei(G,U,K.environment.paths,K.budget),we=Se?K.literalHeredocFiles?.get(Se):void 0;if(we===void 0)return de?hn(re):null;return K.budget.charge("derivedTokens",1),re?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:we,depth:oe+1}),K.analyzeNested(we,{effectiveCwd:U,envAssignments:j})}function Aw(G){let U=G[0];return G.length>=2&&(U==='"'||U==="'")&&G.at(-1)===U?G.slice(1,-1):G}function Tw(G,U,j){let K={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"}[G.head];if(!K)return;if(G.options.trace?.recordSegment({type:"rule-check",rule:K,matched:!!U||!!j,reason:U?.reason??j?.originalReason}),j)G.options.trace?.recordSegment({type:j.kind==="worktree"?"worktree-relaxation":"temp-root-relaxation",originalReason:j.originalReason,gitCwd:j.gitCwd})}function Kp(G){if(G.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");G.iterations++}function cn(G){return{reason:G.reason,ruleId:G.id,intent:G.intent}}function hn(G){return G?.recordSegment({type:"error",message:di}),cn(go())}function Jp(G,U){return Vt.has(U)||G==="$SHELL"||G==="${SHELL}"||Vt.has(kt(U))}function Yp(G,U){return G?.id.startsWith("custom.")||G?.id==="raw-text.dangerous-command"?G:Tt(G,U)}var Iw=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,kw=new Set(["powershell","pwsh"]),Ow=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function Mw(G,U){let j=tg(G,U);if(j.length===0)return!1;let K=j[eg(j)];if(K==="cd"||K==="pushd"||K==="popd")return!0;return Iw.test(G.join(" "))}function Qp(G,U,j,K,re){if(G.dialect==="powershell"){let St=Dw(G.words,re);if(St.kind==="none")return;if(!U||St.kind==="unknown")return null;return Rc(Fw(St.target),U,j.paths)}let oe=G.words.map(t),de=oe.some((St)=>/^CDPATH\+?=/.test(St));if(!Mw(oe,j))return de?null:void 0;if(!U)return null;let Se=tg(oe,j,U),we=eg(Se);if(we===-1||Se[we]!=="cd")return null;let We=Se.slice(we+1),mt=We.findIndex((St)=>St.length<=1||!St.startsWith("-")||St==="--");if((mt===-1?We:We.slice(0,mt)).some((St)=>!/^-[LP]+$/.test(St)))return null;let ft=mt===-1?[]:We.slice(mt),pt=ft[0]==="--"?ft.slice(1):ft;if(pt.length>1)return null;let ht=pt[0],yt=K.get("HOME")||j.home;if(ht===void 0)return Rc(an(yt),U,j.paths);let bt=G.words.find((St)=>St.provenance==="variable"&&St.text===ht),Ct=G.words.find((St)=>St.text===ht&&/^~(?:\/|$)/.test(St.raw)),vt=bt?Vn(bt,new Map([...K,["HOME",yt]])):Ct?`${yt}${ht.slice(1)}`:ht;if(vt===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(vt)&&(de||j.env.has("CDPATH")))return null;return Rc(an(vt),U,j.paths)}function Rc(G,U,j){if(!G||G==="-"||G.startsWith("~")||G.includes("$")||G.includes("`"))return null;try{let K=ur(U,G,j);return j.isDirectory(K)?K:null}catch{return null}}function Dw(G,U){let j=Nw(G[0])?1:0,K=G[j];if(!Lw(K,j===1))return{kind:"none"};let re=K.text.toLowerCase(),oe=re.split(/[\\/]/).pop()??re;if(!Ow.has(oe))return{kind:"none"};if(re!==oe||oe==="pop-location"||oe==="popd")return{kind:"unknown"};return Ww(G.slice(j+1),U)}function Nw(G){return G?.provenance==="literal"&&!G.quoted&&G.raw===G.text&&(G.text==="&"||G.text===".")}function Lw(G,U){return G?.provenance==="literal"&&(U||!G.quoted&&G.raw===G.text)}function Ww(G,U){let j;for(let K of G){if(K.provenance!=="literal"||j!==void 0)return{kind:"unknown"};j=K.text}if(j!==void 0)return{kind:"target",target:j};return U===void 0?{kind:"unknown"}:{kind:"target",target:U}}function Fw(G){return G.includes("::")?void 0:G.replaceAll("\\","/")}function eg(G){let U=0;if(G[0]==="builtin"&&G.length>1)U=1;if(G[U]!=="time")return U;let j=U+1;while(G[j]?.startsWith("-"))j++;return j}function tg(G,U,j){let K=Gw(G);return dr([...K],U,j)}function Gw(G){let U=0;while(U<G.length){let j=G[U];if(j!=="{"&&j!=="("&&j!=="$(")break;U++}return G.slice(U)}var Vw="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Br="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 Ic(G,U,j,K){if(U>=a.recursionDepth.cap)return j.trace?.recordSegment({type:"error",message:Bn}),{reason:Bn,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};let re=K??j.factStore?.getCommandProgram(G,j.shell??"auto")??y(G,j.shell);if(re.status==="limited")return j.trace?.recordSegment({type:"error",message:Bn}),{reason:Bn,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};if(re.status==="invalid"){let We=re.issues.find((mt)=>mt.code.includes("heredoc"));if(We){if(!j.strict)return Tc(G,j);let mt=`${As}: ${We.message}`;return j.trace?.recordGlobal({type:"error",message:mt}),{reason:mt,segment:G,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"}}return ag(G,j),{reason:po,segment:G,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"}}if(j.strict&&re.status==="partial")return ag(G,j),{reason:po,segment:G,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"};if(re.issues.some((We)=>We.code.includes("quote")))return Tc(G,j);let de=j.cwd,Se=j.effectiveCwd!==void 0?j.effectiveCwd:j.cwd,we=Ff(j.environment.env,j.envAssignments);return Js(re,U,{...j,rootProgram:re},de,[{effectiveCwd:Se,shellGitContextState:we,literalHeredocFiles:new Map(j.literalHeredocFiles),functionDefinitions:new Map(j.functionDefinitions),createdDirectories:new Set,compoundBodies:[]}]).result}function Js(G,U,j,K,re){let oe=[...re],de,Se,we;for(let[We,mt]of G.nodes.entries()){if(mt.kind==="connector"){Se=mt.operator;continue}let gt=G.nodes[We+1],ft=gt?.kind==="connector"?gt.operator:void 0,pt=qw(G,We,mt,Se,ft),yt=Se==="&&"||Se==="||"?de:void 0,bt=Se==="&&"?yt?.success??oe:Se==="||"?yt?.failure??oe:oe,Ct=Se==="||"?yt?.success??[]:[],vt=Se==="&&"?yt?.failure??[]:[],St={connector:Se,skippedSuccessStates:Ct,skippedFailureStates:vt};if(br(ft)&&!br(Se))we=St;let Rt=br(ft)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:br(Se)?we??St:St,wt=Ur(Rt.connector)||Ur(ft);if(mt.kind==="function"){let $t=bt.flatMap((sn)=>{let Yt=Hr(sn);return Yt.functionDefinitions.set(mt.name,mt.body),_c(sn,[Yt],pt,ft==="&",Ur(ft))}),Wt=wc($t,[],Rt.skippedSuccessStates,Rt.skippedFailureStates,Rt.connector,ft);oe=Wt.states,de=Wt.conditionalStates,Se=void 0;continue}if(mt.kind==="group"){let $t=[],Wt=[];for(let Yt of bt){let Zt=Js(mt.body,U,j,K,[Hr(Yt)]);if(Zt.result)return Zt;if($t.push(..._c(Yt,Zt.states,pt,ft==="&",Ur(ft))),wt)Wt.push(Yt,...pt?Zt.states.map((Cn)=>Zs(Yt,Cn)):Zt.states)}let sn=wc($t,Wt,Rt.skippedSuccessStates,Rt.skippedFailureStates,Rt.connector,ft);oe=sn.states,de=sn.conditionalStates,Se=void 0;continue}if(mt.kind!=="command")continue;let Et=hP(G.nodes[We-1]),At=j.trace?.flattenNested?j.trace.currentSegmentIndex:j.trace?.allocateSegment(),It=G.nodes[We-2],Kt=br(Se)&&It?.kind==="command"?rp(It)??Yw(It):void 0,Kn=[],bn=[];for(let $t of bt){let Wt=Zw(mt,U,j,K,[Hr($t)]);if(Wt.result)return{result:Wt.result,states:oe};let sn=G.dialect==="powershell"?Wt.states:Wt.states.map((Yt)=>Zs($t,Yt));for(let Yt of sn){let Zt=Hr(Yt),Cn=Qw(mt,U,j.trace?{...j,trace:lg(j.trace,At)}:j,K,Zt,br(Se),Kt);if(Cn)return{result:Cn,states:oe};let Yn=RP(mt,Zt.functionDefinitions);if(Yn)j.budget.charge("derivedTokens",Qs(Yn));let vr=Yn?U+1>=a.recursionDepth.cap?Pc(mt.displayText,j,[Zt]):Js(Yn,U+1,j,K,[Zt]):{result:null,states:vP(mt,Zt).flatMap((wn)=>yP(mt,Yt,wn,Et))};if(vr.result)return vr;Kn.push(..._c($t,vr.states,pt,ft==="&",Ur(ft)));let To=typeof Zt.effectiveCwd==="string"&&Zt.effectiveCwd!==Yt.effectiveCwd&&mt.redirections.every((wn)=>["<",">",">>",">|"].includes(wn.operator)&&wn.target?.text==="/dev/null");if(wt&&(Et||!To))bn.push($t),bn.push(...vr.states.map((wn)=>pt?Zs($t,wn):wn))}}let Sr=wc(Kn,bn,Rt.skippedSuccessStates,Rt.skippedFailureStates,Rt.connector,ft);oe=Sr.states,de=Sr.conditionalStates,Se=void 0}return{result:null,states:oe}}function qw(G,U,j,K,re){if(j.kind==="group"&&j.style==="subshell")return!0;if(G.dialect==="posix"&&(br(K)||br(re)))return!0;if(re==="&")return!0;return G.dialect==="powershell"&&j.kind==="group"&&j.style==="brace"&&Kw(G,U)}function _c(G,U,j,K,re){let oe=j?U.map((Se)=>Zs(G,Se)):[...U],de=re?oe.flatMap((Se)=>xo(G.literalHeredocFiles,Se.literalHeredocFiles)?[Se]:[{...Se,literalHeredocFiles:new Map(G.literalHeredocFiles)},Se]):oe;return K?[G,...de]:de}function Zs(G,U){return{...G,literalHeredocFiles:new Map(U.literalHeredocFiles),createdDirectories:new Set(U.createdDirectories)}}function Kw(G,U){let j=G.nodes.slice(0,U).reverse().find((re)=>re.kind==="command"||re.kind==="connector");if(!j||j.kind!=="command")return!0;let K=j.words[0]?.text.toLowerCase();if(K==="&"||K===".")return!1;if(K==="write-output"||K==="function"||K==="start-job")return!0;if(Xw(j))return!0;return j.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function br(G){return G==="|"||G==="|&"}function Yw(G){if(G?.dialect!=="powershell")return;if(G.words.length===1&&G.words[0]?.quoted&&G.words[0].provenance==="literal")return G.words[0].text;if(G.words[0]?.text.toLowerCase()==="write-output"&&G.words.length===2&&G.words[1]?.provenance==="literal")return G.words[1].text;return}function Ur(G){return G==="&&"||G==="||"}function wc(G,U,j,K,re,oe){let de={success:Xs([...j,...G]),failure:Xs([...K,...U])},Se=Ur(oe)?de:void 0;return{states:Ur(re)||Se?Xs([...de.success,...de.failure]):de.success,conditionalStates:Se}}function lg(G,U,j=G.flattenNested){return{currentSegmentIndex:U,flattenNested:j,allocateSegment:G.allocateSegment,getNextSegmentIndex:G.getNextSegmentIndex,recordGlobal:G.recordGlobal,recordSegment:(K,re=U)=>G.recordSegment(K,re)}}function Zw(G,U,j,K,re){let oe=G.nested.map((de)=>({program:de,depth:U}));if(G.dialect==="powershell"){let de=Jw(G);if(de){if(U+1>=a.recursionDepth.cap)return Pc(de,j,re);let Se=y(de,"powershell");if(Se.status==="limited")return Pc(de,j,re);if(Se.status!=="complete")return ng(oe,j,K,re);j.budget.charge("derivedTokens",Qs(Se)),oe.push({program:Se,depth:U+1})}}return ng(oe,j,K,re)}function Xw(G){let U=G.words[0];return U?.provenance==="variable"&&G.words.at(-1)?.text==="="?U.text.toLowerCase():void 0}function ng(G,U,j,K){let re=[...K];for(let oe of G){let de=[];for(let Se of re){let we=Js(oe.program,oe.depth,U,j,[Hr(Se)]);if(we.result)return we;de.push(...we.states)}re=Xs(de)}return{result:null,states:re}}function Jw(G){let U=G.words[0]?.provenance==="literal"&&!G.words[0].quoted&&G.words[0].raw===G.words[0].text&&(G.words[0].text==="&"||G.words[0].text==="."),j=U?1:0,K=G.words[j];if(K?.provenance!=="literal"||!U&&(K.quoted||K.raw!==K.text)||!["iex","invoke-expression"].includes(K.text.toLowerCase()))return;let re=G.words.slice(j+1),oe=re[0]&&!re[0].quoted&&re[0].raw===re[0].text&&["-c","-command"].includes(re[0].text.toLowerCase())?1:0,de=re[oe];return re.length===oe+1&&de?.quoted&&de.provenance==="literal"?de.text:void 0}function Qs(G){return G.nodes.reduce((U,j)=>U+(j.kind==="command"?j.words.length+j.nested.reduce((K,re)=>K+Qs(re),0):j.kind==="group"||j.kind==="function"?Qs(j.body):0),0)}function Pc(G,U,j){return U.trace?.recordSegment({type:"error",message:Bn}),{result:{reason:Bn,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"},states:[...j]}}function Qw(G,U,j,K,re,oe,de){let Se={...j,environment:{...j.environment,env:re.shellGitContextState.env,paths:oP(j.environment.paths,re.createdDirectories,j.budget)}},we=uP(G,!Se.strict);if(we&&Se.strict)return Se.trace?.recordSegment({type:"error",message:we}),{reason:we,segment:G.source,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"};cg(G,re,"before-consumer",Se.environment.paths,Se.budget);let We=ne(G.dialect,G.words),mt=We.map(t),gt=G.displayText,ft=Lf(We,re.shellGitContextState),pt=zf(ft,re.shellGitContextState);if(G.dialect==="powershell"){let bt=Tt(cf(G,oe,_P(Se,re.effectiveCwd)),Se.policy);if(Se.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!bt,reason:bt?.reason}),bt)return xP(gt,bt)}if(mt.length===1&&mt[0]?.includes(" ")&&!jo(G.dialect,G.words)){let bt=Tt(In(mt[0]),Se.policy),Ct=bt!==null&&!Se.strict&&lm(G,Se.rootProgram);if(bt&&!Ct)return Se.trace?.recordSegment({type:"dangerous-text",token:mt[0],matched:!0,reason:bt.reason}),{reason:bt.reason,segment:gt,ruleId:bt.id,intent:bt.intent};Se.trace?.recordSegment({type:"dangerous-text",token:mt[0],matched:!1});let vt=rg(G,we,re,pt,de,Se);if(vt)return vt;return oc(ft,re.shellGitContextState),null}let ht=Eo(G.words,U,{...Se,commandView:G,cwd:K,effectiveCwd:re.effectiveCwd,envAssignments:pt,shellAssignments:re.shellGitContextState.shellAssignments,literalHeredocFiles:re.literalHeredocFiles,functionDefinitions:re.functionDefinitions,hasPipelineInput:oe,literalShellInput:de,analyzeNested:(bt,Ct)=>{let vt=Ct&&Object.hasOwn(Ct,"effectiveCwd")?Ct.effectiveCwd:re.effectiveCwd,St=Ic(bt,U+1,{...Se,effectiveCwd:vt,envAssignments:Ct?.envAssignments??pt,literalHeredocFiles:re.literalHeredocFiles,functionDefinitions:Ct?.functionDefinitions,worktreeMode:Ct?.worktreeMode??Se.worktreeMode,shell:Ct?.shell??Se.shell,trace:Se.trace?lg(Se.trace,Se.trace.currentSegmentIndex,!0):void 0});return St?{reason:St.reason,ruleId:St.ruleId,intent:St.intent}:null}});if(ht)return{...ht,segment:gt};let yt=rg(G,we,re,pt,de,Se);if(yt)return yt;return oc(ft,re.shellGitContextState),null}function rg(G,U,j,K,re,oe){let de=dP(G,U,j,K??new Map,oe);if(de)return de;return cg(G,j,"after-consumer",oe.environment.paths,oe.budget),j.literalHeredocFiles.clear(),nP(G,U,j,oe.environment.paths,oe.budget),iP(G,j,oe.environment.paths,oe.budget),pP(G,j,re,oe.environment,oe.trace),null}var eP=new Set([">>","<>"]);function cg(G,U,j,K,re){for(let de of G.redirections){if(!(j==="before-consumer"?tP(de):eP.has(de.operator)))continue;og(de.target,U,K,re)}if(j!=="before-consumer"||!on(G.words[0],"tee"))return;let oe=dg(G.words.slice(1));if(!oe)return;for(let de of oe.operands)og(de,U,K,re)}function tP(G){if(G.operator===">"||G.operator===">|")return!0;return G.operator===">&"&&G.fd===void 0&&G.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(G.target.text)}function og(G,U,j,K){let re=G?.provenance==="literal"?ei(G.text,U.effectiveCwd,j,K):void 0;if(!re)return;U.literalHeredocFiles.delete(re)}function nP(G,U,j,K,re){if(U)return;let oe=G.redirections.find((de)=>de.operator==="<<"||de.operator==="<<-")?.heredoc;if(!oe)return;for(let de of rP(G,j.shellGitContextState.shellAssignments)){let Se=ei(de,j.effectiveCwd,K,re);if(!Se||!dm(Se))continue;if(!j.literalHeredocFiles.has(Se)&&j.literalHeredocFiles.size>=a.trackedHeredocFiles.cap)throw new s("trackedHeredocFiles");j.literalHeredocFiles.set(Se,oe.body)}}function rP(G,U){let j=Ac(lP(G.redirections)?.target,U),K=j===void 0?[]:[j];if(on(G.words[0],"cat"))return aP(G.words)?K:[];if(!on(G.words[0],"tee"))return[];let re=dg(G.words.slice(1),U);if(!re||re.append||re.hasUnsupportedOptions)return[];let oe=re.operands.map((de)=>Ac(de,U));if(!oe.every((de)=>de!==void 0))return[];return[...oe,...K]}function Ac(G,U){if(cP(G))return G.text;return(G&&Vn(G,U))??void 0}function oP(G,U,j){if(U.size===0)return G;let K=(re)=>{let oe=Nt(re,G,j);return[...U].some((de)=>de===oe||de.startsWith(`${oe}${jw}`))};return{realpath:(re)=>G.realpath(re)??(K(re)?Nt(re,G,j):null),entryKind:(re)=>{let oe=G.entryKind(re);return oe==="missing"&&K(re)?"present":oe},isDirectory:(re)=>G.isDirectory(re)||K(re)}}function iP(G,U,j,K){if(U.shellGitContextState.bodyDepth>0||!on(G.words[0],"mkdir"))return;let re=G.words.slice(1).map((We)=>Ac(We,U.shellGitContextState.shellAssignments));if(!re.every((We)=>We!==void 0))return;let oe=re.findIndex((We)=>We==="--"||We==="-"||!We.startsWith("-")),de=re.slice(0,oe);if(oe===-1||!de.every((We)=>/^(?:-[pv]+|--parents|--verbose)$/.test(We)))return;let Se=de.some((We)=>We==="--parents"||/^-v*p/.test(We)),we=U.effectiveCwd;for(let We of re.slice(re[oe]==="--"?oe+1:oe)){if(We.split(/[\\/]/).includes("..")||!$w(We)&&!we)continue;let mt=Nt(Hw(we??"",We),j,K);if(Se?sP(mt,j):j.isDirectory(zw(mt))&&ug(mt,j))U.createdDirectories.add(mt)}}function sP(G,U){let j=Uw(G).root,K=G.slice(j.length).split(/[\\/]+/).filter(Boolean),re=(de)=>Bw(j,...K.slice(0,de+1)),oe=K.findIndex((de,Se)=>!U.isDirectory(re(Se)));return oe===-1||ug(re(oe),U)}function ug(G,U){try{return U.entryKind(G)==="missing"}catch{return!1}}function aP(G){let U=!1;for(let j of G.slice(1)){if(U||j.provenance!=="literal")return!1;if(j.text==="--"){U=!0;continue}if(!/^-u+$/.test(j.text))return!1}return!0}function lP(G){let U=G.findLast((j)=>(j.fd??([">",">|",">>",">&"].includes(j.operator)?1:0))===1);return U?.operator===">"||U?.operator===">|"?U:void 0}function dg(G,U=new Map){let j=[],K=!0,re=!1,oe=!1;for(let de of G){if(de.provenance!=="literal"&&Vn(de,U)===null)return;if(K&&on(de,"--")){K=!1;continue}if(K&&!de.quoted&&de.raw===de.text&&/^-[^-]/.test(de.text)){re||=de.text.slice(1).includes("a"),oe||=Array.from(de.text.slice(1)).some((Se)=>Se!=="a"&&Se!=="i");continue}if(K&&!de.quoted&&de.raw===de.text&&de.text.startsWith("--")){re||=de.text==="--append",oe||=de.text!=="--append"&&de.text!=="--ignore-interrupts";continue}j.push(de)}return{operands:j,append:re,hasUnsupportedOptions:oe}}function cP(G){if(!G||G.provenance!=="literal"||G.text.length===0)return!1;if(G.quoted||G.raw!==G.text)return!0;return!G.raw.startsWith("~")&&!/[{}]/.test(G.raw)}function on(G,U){return G?.text===U&&G.raw===U&&G.provenance==="literal"&&!G.quoted}function kc(G){return G.quotedDelimiter||!/[$`\\]/.test(G.body)}function uP(G,U){let j=G.redirections.filter((we)=>we.operator==="<<"||we.operator==="<<-");if(j.length===0)return;if(j.length!==1)return Br;let K=j[0];if(!K?.heredoc)return Br;let re=/\$\(|`/.test(K.heredoc.body);if(!kc(K.heredoc)&&(!U||re))return Vw;if(K.fd!==void 0&&K.fd!==0)return Br;if(G.redirections.some((we)=>we!==K&&["<","<<","<<-","<<<","<&","<>"].includes(we.operator)))return Br;let oe=G.redirections.some((we)=>we!==K&&ig(we.target));if(on(G.words[0],"cat"))return oe?Br:void 0;if(on(G.words[0],"tee"))return oe||G.words.slice(1).some(ig)?Br:void 0;let de=G.words[0],Se=G.words[1];if(on(de,"git")&&(on(Se,"apply")||on(Se,"commit")))return;if(on(de,"gh")&&(on(Se,"pr")||on(Se,"issue"))&&on(G.words[2],"create"))return;return Br}function ig(G){return G?.parts.some((U)=>U.provenance==="command-substitution"&&U.raw.startsWith(">("))??!1}function dP(G,U,j,K,re){if(!U)return null;let oe=G.redirections.filter((We)=>We.operator==="<<"||We.operator==="<<-"),de=oe.flatMap((We)=>We.heredoc?[We.heredoc.body]:[]);if(fP(G,oe,j,K,re))return null;let Se=mP(G,oe,re);if(Se!==void 0)return Se?{reason:Se.reason,segment:G.displayText,ruleId:Se.id,intent:Se.intent}:null;let we=Tc(de.length===oe.length?de.join(`
43
+ `):G.source,re);return we?{...we,segment:G.displayText}:null}function mP(G,U,j){let K=U.length===1?U[0]:void 0;if(!K?.heredoc||!kc(K.heredoc)||K.fd!==void 0&&K.fd!==0)return;let re=on(G.words[0],"uv")&&on(G.words[1],"run")?G.words.slice(2):G.words,oe=re[0];if(oe?.provenance!=="literal"||!Nn(oe.text))return;let de=re.findIndex((gt)=>on(gt,"-"));if(!re.slice(1,de===-1?void 0:de).every((gt)=>gt.provenance==="literal"&&gt.text.startsWith("-")))return;let we=K.heredoc.body,We=Xt(j.policy,"interpreter.one-liner-paranoid",!!j.paranoidInterpreters);if(j.trace?.recordSegment({type:"interpreter",interpreter:oe.text,codeArg:we,paranoidBlocked:We}),We){let gt=Tt(_t("interpreter.one-liner-paranoid",ti),j.policy);if(gt)return gt}if(!ni(we,void 0,!j.strict))return null;let mt=Tt(_t("interpreter.dangerous-command",so),j.policy);if(!mt)return null;return j.trace?.recordSegment({type:"dangerous-text",token:we,matched:!0,reason:mt.reason}),mt}function fP(G,U,j,K,re){let oe=U.length===1?U[0]:void 0;if(!oe?.heredoc||!kc(oe.heredoc)||oe.fd!==void 0&&oe.fd!==0)return!1;let de=kr(G.words,re.environment,j.effectiveCwd,K),Se=de.words.map(t),we=Mt(Se[0]??"");if((de.envSplitValues?.length??0)>0||!Vt.has(we)&&!Vt.has(kt(we)))return!1;return nr(Se)}function pP(G,U,j,K,re){let oe=Qp(G,U.effectiveCwd,K,U.shellGitContextState.shellAssignments,j);if(oe===null)re?.recordSegment({type:"cwd-change",segment:G.words.map(t).join(" "),effectiveCwdNowUnknown:!0});if(oe!==void 0)U.effectiveCwd=oe}var gP=new Set(["fi","done","esac"]);function hP(G){return G?.kind==="command"&&G.words.length===1&&G.words[0]?.raw==="!"}function yP(G,U,j,K){let re=G.words[0]?.text??"",oe=U.shellGitContextState.bodyDepth,de=j.shellGitContextState.bodyDepth,Se=j.compoundBodies;if(de>oe)return j.compoundBodies=[...Se.slice(0,oe),{entryCwd:U.effectiveCwd,branchCwds:Se[oe]?.branchCwds??[],hasElse:!1}],[j];let we=oe>0?Se[oe-1]:void 0;if(we&&(re==="else"||re==="elif"))return j.compoundBodies=[...Se.slice(0,oe-1),{entryCwd:we.entryCwd,branchCwds:[...we.branchCwds,j.effectiveCwd],hasElse:re==="else"}],j.effectiveCwd=we.entryCwd,[j];let We=we!==void 0&&gP.has(re);if(We)j.compoundBodies=Se.slice(0,de);return[...new Set([j.effectiveCwd,...We?we.branchCwds:[],...We&&!we.hasElse?[we.entryCwd]:[],...K?[U.effectiveCwd]:[]])].map((gt)=>{if(gt===j.effectiveCwd)return j;let ft=Hr(j);return ft.effectiveCwd=gt,ft})}function bP(G,U){return G.length===U.length&&G.every((j,K)=>{let re=U[K];return re!==void 0&&j.entryCwd===re.entryCwd&&j.hasElse===re.hasElse&&j.branchCwds.length===re.branchCwds.length&&j.branchCwds.every((oe,de)=>oe===re.branchCwds[de])})}var CP=/^[A-Za-z_][A-Za-z0-9_]*$/,SP=8;function vP(G,U){let j=G.words[1]?.text;if(G.dialect!=="posix"||G.words[0]?.text!=="for"||j===void 0||!CP.test(j))return[U];let K=G.words.slice(3);if(!(G.words[2]?.text==="in"&&K.length>=1&&K.length<=SP&&K.every((oe)=>oe.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(oe.text))))return U.shellGitContextState.shellAssignments.delete(j),[U];return K.map((oe)=>{let de=Hr(U);return de.shellGitContextState.shellAssignments.set(j,oe.text),de})}function Hr(G){return{effectiveCwd:G.effectiveCwd,shellGitContextState:Gf(G.shellGitContextState),literalHeredocFiles:new Map(G.literalHeredocFiles),functionDefinitions:new Map(G.functionDefinitions),createdDirectories:new Set(G.createdDirectories),compoundBodies:G.compoundBodies}}function Xs(G){let U=[];for(let j of G){if(!U.some((K)=>EP(K,j)))U.push(j);if(U.length>a.controlFlowStates.cap)throw new s("controlFlowStates")}return U}function EP(G,U){return G.effectiveCwd===U.effectiveCwd&&bP(G.compoundBodies,U.compoundBodies)&&xo(G.shellGitContextState.env,U.shellGitContextState.env)&&xo(G.literalHeredocFiles,U.literalHeredocFiles)&&xo(G.functionDefinitions,U.functionDefinitions)&&xo(G.shellGitContextState.effectiveEnvAssignments,U.shellGitContextState.effectiveEnvAssignments)&&xo(G.shellGitContextState.shellAssignments,U.shellGitContextState.shellAssignments)&&G.shellGitContextState.bodyDepth===U.shellGitContextState.bodyDepth&&sg(G.shellGitContextState.bodyAssignments,U.shellGitContextState.bodyAssignments)&&sg(G.createdDirectories,U.createdDirectories)}function sg(G,U){return G.size===U.size&&[...G].every((j)=>U.has(j))}function xo(G,U){if(G===U)return!0;if(!G||!U||G.size!==U.size)return!1;return[...G].every(([j,K])=>U.get(j)===K&&U.has(j))}function RP(G,U){let j=Vo(G);return j===void 0?void 0:U.get(j)}function xP(G,U){if(!U)return null;return{reason:U.reason,segment:G,ruleId:U.id,intent:U.intent}}function _P(G,U=G.effectiveCwd){let j=U===null;return{environment:G.environment,cwd:j?void 0:U??G.cwd,originalCwd:j?void 0:G.cwd,strict:G.strict,paranoid:G.paranoidRm,allowTmpdirVar:G.allowTmpdirVar,protectedGitMetadata:G.protectedGitMetadata,policy:G.policy,budget:G.budget}}function Tc(G,U){let j=Tt(In(G),U.policy),K=U.trace?.currentSegmentIndex??U.trace?.allocateSegment(),re={type:"dangerous-text",token:G,matched:!!j,reason:j?.reason};if(U.trace?.recordSegment(re,K),!j&&/^(?:cd|pushd)\s/.test(G))U.trace?.recordSegment({type:"cwd-change",segment:G,effectiveCwdNowUnknown:!0},K);return j?{reason:j.reason,segment:G,ruleId:j.id,intent:j.intent}:null}function ag(G,U){let j={type:"strict-unparseable",rawCommand:G,reason:po},K=U.trace?.currentSegmentIndex;if(K===void 0)U.trace?.recordGlobal(j);if(K!==void 0)U.trace?.recordSegment(j)}var wP=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function mg(G,U,j,K){let re=Ic(G,0,{...U,...Ue(U),budget:U.budget??Pn(),factStore:K},j);if(!re)return null;return{kind:"deny",reason:re.reason,intent:re.intent??"manual_only",ruleId:re.ruleId,evidence:{command:G,segment:re.segment}}}function fg(G,U,j){try{return{decision:G()}}catch(K){let re=PP(K,U,j);if(!re)throw K;return re}}function PP(G,U,j){if(!(G instanceof s)||!wP.has(G.kind))return null;let K=a[G.kind];if(j?.currentSegmentIndex!==void 0)j.recordSegment({type:"error",message:K.reason});if(j?.currentSegmentIndex===void 0)j?.recordGlobal({type:"error",message:K.reason});return{decision:{kind:"deny",reason:K.reason,ruleId:"analysis.derived-command-limit",intent:"stop_and_explain",evidence:{command:U,segment:U}},errorCode:K.errorCode}}var AP=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),Mc=new Set(["cc-safety-net","ccsn"]),TP=new Set(["bunx","npx","pnpx"]),IP=new Set(["pnpm","yarn"]),kP=new Set(["npm","pnpm","yarn"]),OP=new Set(["bun","node"]);function ta(G,U,j={}){if(Mc.has(G))return 0;if(TP.has(G)){if(j.broad)return Oc(U);let re=U[0]==="-y"||U[0]==="--yes"?1:0;return ea(U[re])?re+1:null}let K=j.broad?U.findIndex((re)=>!re.startsWith("-")):0;if(K!==-1&&kP.has(G)&&j.broad&&U[K]==="exec"){let re=Oc(U.slice(K+1));return re===null?null:K+1+re}if(IP.has(G)){if(G==="yarn"&&!j.broad)return null;if(!j.broad)return U[0]==="dlx"&&ea(U[1])?2:null;if(K===-1||U[K]!=="dlx")return null;let re=Oc(U.slice(K+1));return re===null?null:K+1+re}if(OP.has(G)){let re=j.broad&&K!==-1?K:0;if(pg(U[re]))return re+1;if(G==="bun"&&U[re]==="run"&&pg(U[re+1]))return re+2}return null}function Oc(G){let U=G.findIndex((K)=>ea(K));if(U===-1)return null;let j=U;while(j<G.length){let K=G[j]??"";if(!K.startsWith("-")&&!ea(K))break;j++}return j}function ea(G){if(!G)return!1;let U=G.indexOf("@");if(U===-1)return Mc.has(G);if(U===0)return!1;let j=G.slice(U+1);if(j===""||j.includes("/")||j.includes(":"))return!1;return Mc.has(G.slice(0,U))}function pg(G){let U=G?.replaceAll("\\","/");return[...AP].some((j)=>U===j||U?.endsWith(`/${j}`))}var Ge="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 gg(G,U,j){let K=pn(G,"input-candidate");if(!K)return null;let re=co(K.shell,G.invocation.context.executionCwd,U,j,{findSegmentTarget:(oe)=>MP(oe,U),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return re?{target:re}:null}function MP(G,U){let j=dr([...G],U),K=j.slice(1),re=ta(kt(j[0]??"").toLowerCase(),K,{broad:!0});if(re===null)return null;let oe=K.slice(re).filter((de)=>de!=="-g"&&de!=="--global");return oe[0]==="policy"&&oe[1]==="apply"?j.join(" "):null}import{dirname as na}from"node:path";var He="This path contains the protected policy config and you must not modify or delete it.",DP=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Cg(G,U,j){let K=zP(G.invocation.context,U,j);if(G.invocation.route.kind==="patch")return hg(G.paths,!1,G.invocation.context.executionCwd,K,U,j);let re=pn(G,"input-candidate");if(G.invocation.route.kind==="command")return re?yg(re.shell,G.invocation.context.executionCwd,K,U,j):null;if(G.invocation.route.kind==="unknown"&&re){let oe=yg(re.shell,G.invocation.context.executionCwd,K,U,j);if(oe)return oe}return hg(G.paths,G.invocation.route.kind==="grep"||G.invocation.route.kind==="glob"||Ii(G.invocation.toolName),G.invocation.context.executionCwd,K,U,j)}function hg(G,U,j,K,re,oe){if(U)return null;let de=G.find((Se)=>vi(Se,j,K,re,oe));return de?{target:de}:null}function yg(G,U,j,K,re){let oe=co(G,U,K,re,{findSegmentTarget:(de,Se)=>NP(de,Se,j,K,re)?.target??null,isRedirectionTarget:(de,Se)=>vi(de,Se.cwd,j,K,re),findMalformedTarget:(de)=>GP(de,U,j,K,re)?.target??null});return oe?{target:oe}:null}function NP(G,U,j,K,re){if(ai(G))return null;let oe=mr([...G],K),de=kt(oe[0]??"").toLowerCase(),Se=oe.slice(1);if(de==="rm"&&LP(Se)){let we=WP(Se).find((We)=>bg(fn(We,U.variables),U.cwd,j,K,re));if(we)return{target:we}}if(de==="find"){if(Ds(oe,1)||Yl(oe,K)){let We=(pi(jt(oe))??jt(["."])).find((mt)=>{let gt=fn(mt.text,U.variables);return vi(gt,U.cwd,j,K,re)||bg(gt,U.cwd,j,K,re)})?.text;if(We)return{target:We}}}if(de==="mv"){let we=vs(Se).sources.find((We)=>$P(fn(We,U.variables),U.cwd,j,K,re));if(we)return{target:we}}if(FP(oe,de))return null;for(let we of[...G,...oe])for(let We of Sg(we))if(vi(fn(We,U.variables),U.cwd,j,K,re))return{target:We};return null}function LP(G){return G.some((U)=>U==="--recursive"||U.startsWith("-")&&!U.startsWith("--")&&/[rR]/.test(U.slice(1)))}function WP(G){let U=G.indexOf("--");if(U!==-1)return[...G.slice(0,U).filter((j)=>!j.startsWith("-")),...G.slice(U+1)];return G.filter((j)=>!j.startsWith("-"))}function FP(G,U){if(!DP.has(U))return!1;if(U!=="sed")return!0;return!G.slice(1).some((j)=>j.startsWith("-i")||j==="--in-place"||j.startsWith("--in-place="))}function GP(G,U,j,K,re){for(let oe of G.split(/\s+/))for(let de of Sg(oe))if(vi(de,U,j,K,re))return{target:de};return null}function Sg(G){let U=G.trim().replace(/^['"]|['"]$/g,""),j=U.indexOf("=");return j===-1||j===U.length-1?[U]:[U,U.slice(j+1)]}function zP(G,U,j){let K=(Se)=>Ei(ln(Se,G.executionCwd,U,j)),re=K(l(U)),oe=[K(h(G.executionCwd)),K(h(G.configCwd))],de=new Set(oe.map((Se)=>na(Se)));for(let Se=na(re);;Se=na(Se))if(de.add(Se),na(Se)===Se)break;return{files:new Set([re,...oe]),directoriesAndAncestors:de}}function vi(G,U,j,K,re){let oe=nu(G,U,K,re,(de)=>Ei(de)===Li);return oe!==null&&j.files.has(Ei(oe))}function bg(G,U,j,K,re){return j.directoriesAndAncestors.has(Ei(ln(G,U,K,re)))}function $P(G,U,j,K,re){let oe=Ei(ln(G,U,K,re));return j.files.has(oe)||j.directoriesAndAncestors.has(oe)}function Ei(G){return process.platform==="win32"?G.toLowerCase():G}import{isAbsolute as ra,posix as Og,resolve as sa,win32 as BP}from"node:path";import{fileURLToPath as UP}from"node:url";var Mg="Access to a sensitive path is not allowed.",Dg=new Set(["echo","printf"]),HP=new Set(["find"]),jP=new Set(["!","do","elif","else","if","then","until","while"]),VP=new Set(["-exec","-execdir"]),qP=new Set([";","+"]),KP=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),YP=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Ng=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),ZP=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),XP=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"]),Fc=new Set(["-c","-e","-r","-E","--eval","--exec"]),JP=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"])]]),Gc=new Set(["grep","rg"]),Lg=new Set(["files-with-matches","files-without-match","count","quiet"]),QP=new Set([...Lg,"ignore-case","fixed-strings","hidden"]),eA=new Set(["wc",...Gc]),tA=new Set(["cd","grep","head","openssl","tail","tailscale"]),nA=/^(?:-[lwcm]+|--(?:lines|words|bytes|chars))$/,rA=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),oA=new Set(["commit","merge","notes","stash","tag"]),iA=new Set(["-m","--message"]),sA=new Set(["--grep"]),vg=new Set(["jq","gojq","jaq"]),Eg="f",Rg="file",aA="files",lA=new Set(["e","f"]),cA=new Set(["regexp","file"]),uA=new Set(["e","f","A","B","C","m"]),dA=new Set(["regexp","file","after-context","before-context","context","max-count"]),Dc="__CC_SAFETY_NET_PIPE_INPUT__",Lc=/[\w./~@+-]*[./~][\w./~@+-]*/g,mA=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,fA=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,pA=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,xg=/\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,_g=/\b(?:system|exec|spawn|popen)\s*$/,gA=/\b(?:eval|exec)\s*\(/g,hA=/\b(?:eval|exec)\s*$/,yA=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 wg(G,U,j,K,re,oe){for(let de of G){let Se=de.target;if(OT(Se,de.cwd,U?.denyPaths??[],j,K,re))return{target:Se,ruleId:"secret.deny-path"};if(oe&&!oe.has(Se))continue;let we=IT(Se,de.cwd,U,K,re);if(we){let We=oe!==void 0&&!we.startsWith("secret.home.")&&!we.startsWith("secret.cli.");if(We&&K.paths.isDirectory(Zg(Se,de.cwd,K,re)))continue;if(We&&oe?.get(Se)==="data")continue;if(We&&(de.isRedirectionWriteTarget===!0||oe?.get(Se)==="write")&&!Se.includes("$")&&!ia(Se,de.cwd,K,re))continue;if(We&&(de.isCreatedPath===!0||de.isCertificateInput===!0))continue;if(We&&/\s/.test(Se)&&!Se.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(Se)&&!ia(Se,de.cwd,K,re))continue;if(!we.startsWith("secret.cli.")&&MT(Se,de.cwd,U?.allowPaths??[],j,K,re))continue;return{target:Se,ruleId:we}}}return null}function Wg(G,U,j,K,re={}){let oe=Pg(G,j,K),de=wg(oe,U,G.invocation.context.configCwd,j,K);if(de===null||de.ruleId==="secret.deny-path"||re.strict!==!1)return de;let Se=Pg(G,j,K,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}),we=new Map;Se.forEach((ht)=>Fg(ht.target).forEach((yt)=>we.set(yt,(we.get(yt)??new Set).add(ht.loopVariable))));let We=(ht,yt)=>(we.get(ht)?.size??0)>(we.get(ht)?.has(yt)?1:0),mt=Se.filter(({loopVariable:ht})=>ht===void 0||We(ht,ht)||We("!",ht)),gt=new Set(mt.filter((ht)=>ht.literalRole===void 0).map((ht)=>ht.target)),ft=new Set(mt.filter((ht)=>ht.literalRole==="write").map((ht)=>ht.target)),pt=wg(oe,U,G.invocation.context.configCwd,j,K,new Map(mt.map((ht)=>[ht.target,gt.has(ht.target)?"path":ft.has(ht.target)?"write":"data"])));return pt?.ruleId!=="secret.deny-path"&&bA(G,j)?null:pt}function bA(G,U){let j=pn(G,"input-candidate")??pn(G,"declared-command");if(!j)return!1;if(j.program.nodes.some((de)=>de.kind==="command"&&de.nested.length>0))return!1;let K=[];for(let de of Ss(j.shell)){if(de.kind==="operator"&&de.boundary)return!1;if(de.kind==="redirection")return!1;if(de.kind==="operator")continue;K.push(er(de.text,U))}let re=qn(K);if(re.length===0)return!1;let oe=un(re[0]??"").toLowerCase();if(G.invocation.route.kind==="unknown")return j.program.dialect==="powershell"&&(oe==="ls"||oe==="stat");return zc(oe,re.slice(1))}function zc(G,U){if(G==="ls"||G==="stat")return!0;if(G==="test")return U.length===2&&(U[0]==="-e"||U[0]==="-f");if(G==="[")return U.length===3&&(U[0]==="-e"||U[0]==="-f")&&U[2]==="]";if(G==="git")return U[0]==="check-ignore";if(G==="wc")return U.every((j)=>!j.startsWith("-")||nA.test(j));if(Gc.has(G))return CA(G,U);if(G!=="find")return!1;return!U.some((j)=>KP.has(j))}function CA(G,U){let j=U.includes("--")?U.slice(0,U.indexOf("--")):U;if(j.some((We)=>/^--(?:(?:file|pre)(?:=|$)|json|format)/.test(We)||/^-[^-]*f/.test(We)))return!1;let K=G==="rg"?/[ABCEMTdegjmrt]/:/[ABCDdefm]/,re=G==="rg"?/[clq]/:/[Lclq]/,oe=(We)=>/^-[^-]/.test(We),de=(We)=>{let mt=j[We-1]??"";return/^--[^=]+$/.test(mt)&&!QP.has(mt.slice(2))||oe(mt)&&mt.slice(1).search(K)===mt.length-2},Se=j.findIndex((We,mt)=>!We.startsWith("-")&&!de(mt));return(G==="grep"&&Se>=0?j.slice(0,Se):j).some((We,mt)=>{if(de(mt))return!1;if(We.startsWith("--"))return Lg.has(We.slice(2));return oe(We)&&re.test(We.slice(1).split(K)[0]??"")})}function Pg(G,U,j,K={}){let re=G.invocation.context.executionCwd,oe=G.invocation.route.kind;if(oe!=="command"&&oe!=="unknown")return G.paths.map((Se)=>({target:Se,cwd:re}));let de=pn(G,"input-candidate");return[...de?Ao(de.shell,G.store,K,U,re,j,SA(de)):[],...oe==="unknown"?G.paths.map((Se)=>({target:Se,cwd:re})):[]]}function SA(G){return G.program.dialect==="powershell"}function Ao(G,U,j,K,re,oe,de=!1){if(G.status==="structural-limit")throw new b;if(G.status==="unclosed-quote")return[];if(G.status==="invalid")throw Error("Unable to parse command for secret protection");let Se=[...G.assignmentFallbacks.map((bt)=>({target:bt,cwd:re})),...mT(er(G.source,K),U,j,K,re,oe)],we=(bt)=>er(OA(bt,de),K),We=/[<>=]\(/.test(G.source),mt=/\bcoproc\b|\|&/.test(G.source),gt=[],ft=[],pt=(bt)=>({...j,commandHoldsPipe:j.commandHoldsPipe===!0||bt||mt});Cs(G,re,K,oe,{word:we,segment:(bt,Ct,vt,St,Rt,wt)=>{if(bt.length===0)return null;let Et=pt(wt);if(Et.commandHoldsPipe)gt.push(...bt);if(ft.push(un(Gg(qn(bt))[0]??"").toLowerCase()),Se.push(...xi(bt,U,We||St==="|"||St==="|&"?{...Et,segmentMayFeedReader:!0}:Et,K,Ct.cwd,oe,Rt)),vt!==null)Se.push(...RA(vt,bt,U,Et,K,Ct.cwd,oe));return null},redirection:(bt,Ct,vt)=>{if(bt.body!==void 0&&bt.consumer!==void 0){let St=pt(vt);Se.push(...zg(bt.consumer,[bt.body],U,St,K,Ct.cwd,oe,(Rt)=>xA(bt.consumer??[],Rt,U,St,K,Ct.cwd,oe)))}if(bt.targetOrder==="legacy-segment")return Ol;return Se.push({target:we(bt.target),cwd:Ct.cwd,...bt.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}});let ht=new Set(gt.flatMap(Fg)),yt=We||/\$\(|`/.test(G.source)||!ft.every((bt)=>tA.has(bt));return Se.map(({loopVariable:bt,...Ct})=>{if(Ct.certificateOutputMayFeedReader===!0&&yt)return{target:Ct.target,cwd:Ct.cwd};return bt===void 0||We||ht.has(bt)||ht.has("!")?Ct:{...Ct,loopVariable:bt}})}function Fg(G){return[.../^[A-Za-z_][A-Za-z0-9_]*$/.test(G)?[G]:[],...Array.from(G.matchAll(/\$(?:\{(!)|\{?([A-Za-z_][A-Za-z0-9_]*))/g),(U)=>U[1]??U[2]??"")]}function $c(G,U,j,K,re,oe){let de=U.getShellSyntax(G);if(de.status==="structural-limit")throw new b;return de.status==="complete"?Ao(de,U,j,K,re,oe):null}function xi(G,U,j,K,re,oe,de){let Se=(Et)=>({target:Et,cwd:re}),we=G.findIndex((Et)=>!jP.has(Et));if(j.skipMetadataOnlySegments===!0&&we>0)return xi(G.slice(we),U,j,K,re,oe,new Set([...de??[]].map((Et)=>Et-we)));let We=G[1]??"";if(j.skipMetadataOnlySegments===!0&&G[0]==="for"&&G[2]==="in"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(We))return G.slice(3).flatMap((Et)=>Mn("for",Et)).map((Et)=>({...Se(Et),loopVariable:We}));if(de?.size){let Et=G.filter((At,It)=>!de.has(It));if(vg.has(un(qn(Et)[0]??"").toLowerCase()))return[...G.filter((At,It)=>de.has(It)).map(Se),...xi(Et,U,j,K,re,oe)]}let mt=kA(G).map(Se),gt=qn(G);if(gt.length===0)return mt;let ft=gt[0]??"",pt=un(ft).toLowerCase(),ht=gt.slice(1),yt=j.segmentMayFeedReader===!0||j.commandHoldsPipe===!0||j.displayOperandsAreCapturedOutput===!0,bt=yt&&eA.has(pt);if(j.skipMetadataOnlySegments===!0&&!bt&&zc(pt,ht))return mt;let Ct=EA(ft,pt,ht);if(Ct)return[...mt,...Ct.map(Se)];if(Dg.has(pt))return j.displayOperandsAreCapturedOutput===!0?[...mt,...$g(G).map(Se)]:mt;if(pt==="eval")return[...mt,...$c(ht.join(" "),U,j,K,re,oe)??ht.map(Se)];if(pt==="export")return[...mt,...ht.flatMap((Et)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(Et)?[Et.slice(Et.indexOf("=")+1)]:Mn(pt,Et)).map(Se)];if(pt==="git")return[...mt,...DA(ht).map(Se)];if(pt==="gh")return[...mt,...Wc(pt,ht,rA).map(Se)];if(vg.has(pt))return[...mt,...MA(ht).map(Se)];if(Gc.has(pt))return[...mt,...ST(ht).map(Se)];if(HP.has(pt))return[...mt,...LA(ht,U,j,K,re,oe).map(Se)];if(pt==="mkdir"||pt==="touch"){let Et=new Set(G.filter((It,Kt)=>de?.has(Kt))),At=j.segmentMayFeedReader!==!0&&!(pt==="touch"&&ht.some((It)=>/^(?:--r|-[^-]*r)/.test(It)));return[...mt,...ht.flatMap((It)=>Mn(pt,It).map((Kt)=>At&&!It.startsWith("-")&&!Et.has(It)?{...Se(Kt),isCreatedPath:!0}:Se(Kt)))]}if(Tn.has(pt))return[...mt,...ht.flatMap((Et)=>Mn("awk",Et)).map(Se),...ht.flatMap((Et)=>FA(Et,U,j,K,re,oe)),...ht.flatMap(GA).map(Se)];if(pt==="curl")return[...mt,...ht.filter((Et,At)=>Ug(Et)===null&&Bg(ht[At-1])===null).flatMap((Et)=>Mn(pt,Et)).map(Se),...NA(ht).map(Se)];if(lo(pt)){let Et=si.has(pt)?vn([pt,...ht]):null;if(Et!==null&&Et.command!==null&&Et.commandIndex!==null){let At=U.getShellSyntax(Et.command);if(At.status==="structural-limit")throw new b;if(At.status==="complete")return[...mt,...Ao(At,U,j,K,re,oe),...ht.slice(Et.commandIndex).filter((It)=>!It.startsWith("-")).map(Se)]}return[...mt,...WA(pt,ht,U,j,K,re,oe)]}let vt=(Et,At)=>new RegExp(`^--?${Et}=`).test(ht[At]??"")||new RegExp(`^--?${Et}$`).test(ht[At-1]??""),St=vA(gt),Rt=pt==="openssl"&&ht[0]==="x509",wt=yt?{certificateOutputMayFeedReader:!0}:{};return[...mt,...ht.flatMap((Et,At)=>Mn(pt,Et).map((It)=>St&&vt("(?:cert|key)-file",At)?{...Se(It),isCreatedPath:!0,...wt}:Rt&&vt("in",At)?{...Se(It),isCertificateInput:!0,...wt}:Se(It)))]}function Gg(G){return un(G[0]??"").toLowerCase()==="timeout"?G.slice(2):G}function vA(G){let U=Gg(G);return un(U[0]??"").toLowerCase()==="tailscale"&&U[1]==="cert"}function EA(G,U,j){let K=ta(U,j);if(K===null||j[K]!=="explain")return null;let re=[G,...j.slice(0,K)],oe=j.slice(K+1);for(let de=0;de<oe.length;de++){let Se=oe[de];if(Se==="--json"||Se==="--help"||Se==="-h")continue;if(Se==="--cwd"){let we=oe[de+1];if(we&&!we.startsWith("--"))re.push(we);de++;continue}return re}return re}function RA(G,U,j,K,re,oe,de){if(AA(U,j,K,re,oe,de)){let Se=qn(G),we=zc(un(Se[0]??"").toLowerCase(),Se.slice(1))?Se.slice(1).filter((We)=>!We.startsWith("-")):[];return[...$g(G),...we].map((We)=>({target:We,cwd:oe}))}return zg(U,_A(G),j,K,re,oe,de,()=>[])}function xA(G,U,j,K,re,oe,de){let Se=qn(G);if(!lo(un(Se[0]??"").toLowerCase()))return[];return $c(U,j,K,re,oe,de)??[{target:U,cwd:oe}]}function zg(G,U,j,K,re,oe,de,Se){let we=TA(G);if(we===null)return U.flatMap(Se);return U.flatMap((We)=>si.has(we)?Ao(j.getShellSyntax(We),j,K,re,oe,de):oa(we,We,j,K,re,oe,de))}function $g(G){let U=qn(G);if(U.length===0)return[];let j=un(U[0]??"").toLowerCase();if(!Dg.has(j))return[];let K=U[U[1]==="--"?2:1];if(j==="printf"&&K!==void 0&&!K.startsWith("-")&&!K.replaceAll("%%","").includes("%"))return[Bc(K.replaceAll("%%","%"))];return U.slice(1)}function _A(G){let U=qn(G);if(U.length===0)return[];let j=un(U[0]??"").toLowerCase(),K=U.slice(1);if(j==="echo"){let re=K.findIndex((oe)=>!/^-[neE]+$/.test(oe));return[(re===-1?[]:K.slice(re)).join(" ")]}if(j==="printf")return wA(K);return[]}function wA(G){let U=G[0];if(U===void 0)return[];let j=(U.match(/%%|%[bqs]/g)??[]).filter((re)=>re!=="%%").length;if(j===0||G.length===1)return[Bc(U)];let K=G.slice(1);return Array.from({length:Math.ceil(K.length/j)},(re,oe)=>PA(U,K.slice(oe*j,(oe+1)*j)))}function PA(G,U){let j=0;return Bc(G.replace(/%%|%[bqs]/g,(K)=>{if(K==="%%")return"%";let re=U[j]??"";return j++,re}))}function Bc(G){return G.replace(/\\n/g,`
44
+ `).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function AA(G,U,j,K,re,oe){let de=qn(G);if(de.length===0||un(de[0]??"").toLowerCase()!=="xargs")return!1;let Se=$r(de),we=de.slice(Se.childStart);if(we.length===0)return!1;if(Se.replacementToken==="")return!1;let We=Se.replacementToken,mt=We===null?[...we,Dc]:we.map((gt)=>gt.split(We).join(Dc));return xi(mt,U,j,K,re,oe).some((gt)=>gt.target.includes(Dc))}function TA(G){let U=qn(G);if(U.length===0)return null;let j=un(U[0]??"").toLowerCase();if(!lo(j))return null;return IA(j,U.slice(1))?j:null}function IA(G,U){let j=Uc(G);for(let K=0;K<U.length;K++){let re=U[K];if(re===void 0)break;if(Fc.has(re)||Hg(G,re)||/^--(?:eval|exec)=/.test(re))return!1;if(re==="-")return!0;if(re.startsWith("-")){if(j==="python"&&re==="-m")return!1;if(yA.get(j)?.has(re))K++;continue}return!1}return!0}function Uc(G){return/^python\d/.test(G)?"python":G}function kA(G){let U=[];for(let j of G){if(Yg(j))continue;let K=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(j);if(K===null)break;if(K[1]!==void 0&&K[1]!=="")U.push(K[1])}return U}var Ag=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function OA(G,U){if(!U||!Ag.test(G))return G;return`~${G.replace(Ag,"").replace(/\\/g,"/")}`}function Mn(G,U){if(U==="--")return[];let j=[],K=U.indexOf("=");if(K>0&&K<U.length-1&&!U.slice(0,K).includes("?"))j.push(U.slice(K+1));if(U.startsWith("-"))return j;if(G==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(U))return j;if(G==="zip"&&/\.zip$/i.test(U))return j;return j.push(U),j}function MA(G){let U=-1,j=!1;for(let K=0;K<G.length;K++){let re=G[K]??"";if(!j&&re==="--"){j=!0;continue}if(j||!/^-(?:[A-Za-z]|-)/.test(re)){if(U===-1)U=K;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(re)){K+=2;continue}if(re==="--indent"||re==="-L"){K++;continue}if(re.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(re)||/^--(?: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(re))continue;return G.flatMap((oe)=>Mn("jq",oe))}return G.flatMap((K,re)=>re===U?[]:Mn("jq",K))}function DA(G){let U=[];for(let j=0;j<G.length;j++){let K=G[j]??"";if(K==="--"||!K.startsWith("-"))return[...U,...oA.has(K)?Wc("git",G.slice(j).map((oe)=>/^-[aeinopqsv]+m$/.test(oe)?"-m":oe),iA):Wc("git",G.slice(j),sA)];if(U.push(...Mn("git",K)),!Sn.has(K))continue;let re=G[j+1];if(re===void 0)break;U.push(...K==="-c"&&re.includes("=")?[re.slice(re.indexOf("=")+1)]:Mn("git",re)),j++}return U}function Wc(G,U,j){let K=[];for(let re=0;re<U.length;re++){let oe=U[re]??"";if(oe==="--")return[...K,...U.slice(re).flatMap((de)=>Mn(G,de))];if(j.has(oe)){re++;continue}if(oe.includes("=")&&j.has(oe.slice(0,oe.indexOf("="))))continue;K.push(...Mn(G,oe))}return K}function NA(G){return G.flatMap((U,j)=>{let K=Ug(U);if(K!==null)return Tg(K.flag,K.value);let re=Bg(G[j-1]);return re===null?[]:Tg(re,U)})}function Tg(G,U){if(G==="-F"||G==="--form"){let j=U.indexOf("="),K=j===-1?U:U.slice(j+1);if(!K.startsWith("@")&&!K.startsWith("<"))return[];return Nc(K.slice(1).split(";")[0]??"")}if(G==="--data-urlencode"){let j=U.indexOf("@"),K=U.indexOf("=");if(j===-1||K!==-1&&K<j)return[];return Nc(U.slice(j+1))}return U.startsWith("@")?Nc(U.slice(1)):[]}function Bg(G){if(G===void 0)return null;if(Ng.has(G))return G;return/^-[A-Za-z]+[dF]$/.test(G)?`-${G.slice(-1)}`:null}function Ug(G){let U=G.slice(0,2);if(G.length>2&&(U==="-d"||U==="-F"))return{flag:U,value:G.slice(2)};let j=G.indexOf("=");if(j===-1)return null;let K=G.slice(0,j);return Ng.has(K)?{flag:K,value:G.slice(j+1)}:null}function Nc(G){return G===""||G==="-"?[]:[G]}function LA(G,U,j,K,re,oe){let de=G.findIndex((we)=>we.startsWith("-")||we==="("||we==="!"||we===";"),Se=[...G.slice(0,de===-1?G.length:de),...G.flatMap((we,We)=>we==="-files0-from"&&G[We+1]!==void 0?[G[We+1]??""]:[])];for(let we=0;we<G.length;we++){if(!VP.has(G[we]??""))continue;let We=G.slice(we+1),mt=We.findIndex((pt)=>qP.has(pt)),gt=mt===-1?We:We.slice(0,mt),ft=xi(gt,U,j,K,re,oe).map((pt)=>pt.target);if(Se.push(...ft.filter((pt)=>pt!=="{}")),!ft.includes("{}"))continue;Se.push(...G.slice(0,we).flatMap((pt,ht,yt)=>{if(!YP.has(pt))return[];let bt=yt[ht+1];return bt===void 0?[]:[bt,bt.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return Se}function WA(G,U,j,K,re,oe,de){let Se=[];for(let we=0;we<U.length;we++){let We=U[we];if(We===void 0)break;if(Fc.has(We)||Hg(G,We)){let gt=U[we+1];if(gt!==void 0)Se.push(...oa(G,gt,j,K,re,oe,de)),we++;continue}let mt=/^--(?:eval|exec)=(.*)$/.exec(We);if(mt!==null&&mt[1]!==void 0){Se.push(...oa(G,mt[1],j,K,re,oe,de));continue}if(!We.startsWith("-"))Se.push({target:We,cwd:oe})}return Se}function Hg(G,U){if(!U.startsWith("-")||U.startsWith("--")||U.length<=2)return!1;return JP.get(U[U.length-1]??"")?.has(Uc(G))??!1}function FA(G,U,j,K,re,oe){if(!G.includes("system"))return[];return jl(G)?.commands.flatMap((de)=>Ao(U.getShellSyntax(de),U,j,K,re,oe))??[]}function GA(G){return Array.from(G.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((U)=>U[1]).filter((U)=>U!==void 0&&U!=="")}function zA(G){let U=Array.from(G.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((j)=>j[2]).filter((j)=>j!==void 0&&j!=="");return[...U,...U.flatMap(jc),...G.match(Lc)??[]]}function oa(G,U,j,K,re,oe,de){let Se=(wt)=>({target:wt,cwd:oe}),we=oT(G),We=sT(U,we);if(We.kind==="unmaskable")return zA(U).map(Se);let mt=We.masked.match(xg)!==null||We.literals.some((wt)=>_g.test(We.masked.slice(0,wt.start))),gt=We.masked.match(gA)!==null||We.literals.some((wt)=>hA.test(We.masked.slice(0,wt.start))),ft=K.inlineLiteralsPresumedData===!0&&!si.has(G),pt=ft&&(we==="python"||we==="javascript"),ht=ft&&!(dT(We.masked)||mt||gt)?[]:We.literals,yt=ft?Array.from(We.masked.matchAll(xg),(wt)=>{let Et=wt.index+wt[0].length;return{start:Et,end:ds(We.masked,Et)}}):[],bt=!ft||yt.some((wt)=>Pl(We.masked,wt.start)&&!qA(We,wt.start))?We.literals:We.literals.filter((wt)=>_g.test(We.masked.slice(0,wt.start))||yt.some((Et)=>wt.start>=Et.start&&wt.start<Et.end)),Ct=new Set(mt?bt:[]),vt=pt&&ht.length>0&&!HA(We.masked,we==="python"?"#":"//"),St=vt?KA(We.masked):[],Rt=vt&&jA(We.masked);return[...ht.filter((wt)=>wt.text!=="").map((wt)=>{if(!vt||Ct.has(wt))return Se(wt.text);if(YA(We.masked,wt,St,Rt))return{...Se(wt.text),literalRole:"data"};return tT(We,wt,St)?{...Se(wt.text),literalRole:"write"}:Se(wt.text)}),...ht.flatMap((wt)=>jc(wt.text)).map(Se),...ft?[]:We.literals.flatMap((wt)=>wt.text.match(Lc)??[]).map(Se),...mt?bt.flatMap((wt)=>$c(wt.text,j,{...K,commandHoldsPipe:!0},re,oe,de)??[Se(wt.text)]):[],...gt?We.literals.flatMap((wt)=>oa(G,wt.text.replace(/\\(.)/g,(Et,At)=>At==="n"?`
45
+ `:At),j,K,re,oe,de)):[],...pt?[]:(We.masked.match(Lc)??[]).map(Se),...ft?(U.match(/\$\{[^}]*\}|\$[A-Za-z_]\w*/g)??[]).map(Se):[]]}var Hc={"(":")","[":"]","{":"}"},jg="and|elif|else|if|in|is|not|of|or|return|while|yield",$A=new RegExp(`(?:^|[^\\w$])(?:${jg})$`),BA=new RegExp(`(?:\\*|\\.\\.\\.)\\s*[([{]|\\.\\s*(?:${jg})\\s*\\(|/\\*`),UA=/^(?:exec|spawn)|^(?:popen|system|subprocess)$/;function HA(G,U){return BA.test(G)||G.split(`
46
+ `).some((j)=>{let K=j.indexOf(U);return K>=0&&/[()[\]{}]/.test(j.slice(K))})}function jA(G){return Array.from(G.matchAll(/[A-Za-z_$][\w$]*/g),(U)=>qg(U[0])).some((U)=>U.some((j)=>UA.test(j)))}var VA=new Set(["cmd","powershell","pwsh"]);function qA(G,U){let j=Po(G.masked,U),K=Hc[G.masked[j]??""];if(K===void 0||K==="}")return!1;let re=G.masked.indexOf(K,j+1),oe=G.masked.slice(j+1,re);return re!==-1&&/^\s*,[\w\s,]*$/.test(oe)&&/^[,)]/.test(G.masked.slice(Po(G.masked,re+1)))&&!G.literals.some((de)=>de.tokenStart>j&&de.tokenStart<re&&(Fc.has(de.text)||lo(un(de.text).toLowerCase())||VA.has(un(de.text).toLowerCase().replace(/\.exe$/,""))))}function KA(G){let U=[];return G.split("").map((j,K)=>{let re=U.at(-1)??-1;if(j in Hc)U.push(K);if(j===")"||j==="]"||j==="}")U.pop();return re})}function YA(G,U,j,K){let re=j[U.tokenStart]??-1,oe=G[re]??"",de=wo(G,U.tokenStart),Se=Po(G,U.tokenEnd);if(/(?:^|[^\w$])in$|[=!]=$/.test(G.slice(Math.max(0,de-3),de+1)))return!0;if(/^(?:(?:not\s+)?in(?![\w$])|[=!]=)/.test(G.slice(Se,Se+8)))return!0;if(K&&(oe==="["||oe==="("))return!1;let we=G[de],We=G[Se];if(oe==="{"&&we===":")return nT(G,de);let mt=(we===oe||we===",")&&(We===","||We===Hc[oe]||oe==="{"&&We===":");if(oe!=="(")return mt&&oe!=="";return mt&&(we===","||We===",")&&rT(G,re)}var ZA=/(?:^|[^\w$.])(?:pathlib\s*\.\s*)?Path\s*$/,XA=/^\s*\.\s*write_(?:text|bytes)\s*\(/,JA=/(?:^|[^\w$.])open\s*$/,QA=/^[bt]*[awx][abtwx]*$/,eT=/(?:^|[^\w$])(?:writeFile|writeFileSync|appendFile|appendFileSync|Bun\s*\.\s*write)\s*$/;function tT(G,U,j){let K=j[U.tokenStart]??-1;if(G.masked[K]!=="(")return!1;let re=wo(G.masked,U.tokenStart),oe=Po(G.masked,U.tokenEnd),de=G.masked[oe],Se=G.masked.slice(Math.max(0,K-40),K);if(ZA.test(Se))return(re===K||G.masked[re]===",")&&(de===","||de===")")&&!G.literals.some((We)=>We.tokenStart>K&&We.tokenStart<U.tokenStart)&&XA.test(G.masked.slice(ds(G.masked,K+1)+1));if(re!==K||de!==",")return!1;if(eT.test(Se))return!0;if(!JA.test(Se))return!1;let we=G.literals.find((We)=>/^,\s*(?:mode\s*=\s*)?$/.test(G.masked.slice(oe,We.tokenStart)));return we!==void 0&&QA.test(we.text)&&/^[,)]/.test(G.masked.slice(Po(G.masked,we.tokenEnd)))}function nT(G,U){let j=wo(G,U),K=/[\w$]*$/.exec(G.slice(Math.max(0,j-63),j+1))?.[0]??"",re=G[wo(G,j+1-K.length)];return re==="{"||re===","}function rT(G,U){let j=wo(G,U),K=G.slice(Math.max(0,j-7),j+1);return!/[\w$)\]]$/.test(K)||$A.test(K)}function oT(G){let U=Uc(G);if(U==="python")return"python";if(U==="osascript")return"opaque";return U==="node"||U==="bun"||U==="deno"?"javascript":"simple"}var iT={python:"#",javascript:"/"};function sT(G,U){if(U==="opaque")return{kind:"unmaskable"};let j={masked:G.split(""),literals:[]};return Vg(G,0,U,j,!1)===null?{kind:"unmaskable"}:{kind:"masked",masked:j.masked.join(""),literals:j.literals}}function Vg(G,U,j,K,re){let oe=0;for(let de=U;de<G.length;de++){let Se=G[de]??"";if(re&&Se==="}"&&oe===0)return de;if(re&&Se===iT[j])return null;if(Se==="{")oe++;if(Se==="}")oe--;if(j==="simple"&&(Se==="`"||Se==="%"||Se==="<")){if(fA.test(G.slice(de)))return null}let we=Se==="'"||Se==='"'||j==="javascript"&&Se==="`"?Se:null;if(we===null)continue;if(we==="`"&&uT(G,de))return null;let We=j==="python"?lT(G,de):"",mt=j==="python"&&G.startsWith(we.repeat(3),de)?we.repeat(3):we,gt=de+mt.length,ft=we==="`"||/[fF]/.test(We),pt=de-We.length,ht=ft?aT(G,pt,gt,mt,j,K):cT(G,gt,mt);if(ht===null)return null;if(!ft){let yt=G.slice(gt,ht);if(j==="simple"&&we==='"'&&pA.test(yt))return null;K.literals.push({start:gt,text:yt,tokenStart:pt,tokenEnd:ht+mt.length}),K.masked.fill(" ",gt,ht)}K.masked.fill(" ",de,gt),K.masked.fill(" ",ht,ht+mt.length),de=ht+mt.length-1}return re?null:G.length}function aT(G,U,j,K,re,oe){let de=re==="python"?"{":"${",Se=K==="`"||K.length===3,we="";for(let We=j;We<G.length;We++){let mt=G[We]??"";if(G.startsWith(K,We))return oe.literals.push({start:j,text:we,tokenStart:U,tokenEnd:We+K.length}),We;if(!Se&&(mt===`
47
+ `||mt==="\r"))return null;let gt=re==="python"&&(mt==="{"||mt==="}")&&G[We+1]===mt;if(!gt&&G.startsWith(de,We)){let ht=Vg(G,We+de.length,re,oe,!0);if(ht===null)return null;we+=`${de}}`,oe.masked.fill(" ",We,We+de.length),oe.masked[ht]=" ",We=ht;continue}let pt=mt==="\\"&&!(re==="python"&&G[We+1]==="{")||gt?2:1;we+=G.slice(We,We+pt),oe.masked.fill(" ",We,We+pt),We+=pt-1}return null}function lT(G,U){return mA.exec(G.slice(Math.max(0,U-3),U))?.[1]??""}function cT(G,U,j){let K=j.length===3;for(let re=U;re<G.length;re++){let oe=G[re];if(oe==="\\"){re++;continue}if(!K&&(oe===`
48
+ `||oe==="\r"))return null;if(G.startsWith(j,re))return re}return null}function uT(G,U){for(let j=U-1;j>=0;j--){let K=G[j];if(!K||/\s/.test(K))continue;return/[\w$\])]/.test(K)}return!1}function dT(G){for(let U of G.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let j=U[0],K=U.index;if(ZP.has(j.toLowerCase()))return!0;let re=qg(j);if(!re.some((oe)=>XP.has(oe)))continue;if(re.length>1)return!0;if(G[wo(G,K)]===".")return!0;if(G[Po(G,K+j.length)]==="(")return!0}return!1}function qg(G){return G.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((U)=>U.toLowerCase())}function wo(G,U){for(let j=U-1;j>=0;j--)if(!/\s/.test(G[j]??""))return j;return-1}function Po(G,U){for(let j=U;j<G.length;j++)if(!/\s/.test(G[j]??""))return j;return G.length}function mT(G,U,j,K,re,oe){return yT(G).flatMap((de)=>{let Se=U.getShellSyntax(de);if(Se.status==="invalid")return[];return[...Ao(Se,U,{...j,displayOperandsAreCapturedOutput:!0},K,re,oe),...fT(Se,K)?pT(Se,K).map((we)=>({target:we,cwd:re})):[]]})}function fT(G,U){let j=Ss(G);for(let K=0;K<j.length;K++){let re=j[K];if(re?.kind!=="word"||un(er(re.text,U)).toLowerCase()!=="base64")continue;for(let oe=K+1;oe<j.length;oe++){let de=j[oe];if(de?.kind==="operator")break;if(de?.kind!=="word")continue;let Se=er(de.text,U);if(Se==="--decode"||!Se.startsWith("--")&&Se.startsWith("-")&&/[dD]/.test(Se))return!0}}return!1}function pT(G,U){return Ss(G).flatMap((j)=>j.kind==="word"?[er(j.text,U)]:j.kind==="redirection"&&j.target?[er(j.target,U)]:[]).flatMap(jc)}function jc(G){let U=hT(G);if(U===null)return[];let j=Buffer.from(U,"base64").toString("utf8");if(j===""||gT(j))return[];return Buffer.from(j,"utf8").toString("base64").replace(/=+$/g,"")===U.replace(/=+$/g,"")?[j]:[]}function gT(G){return Array.from(G).some((U)=>{let j=U.charCodeAt(0);return j<32||j===127})}function hT(G){if(G.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(G))return null;if(/=/.test(G.replace(/=+$/g,"")))return null;let U=G.replace(/=+$/g,"");if(U.length%4===1)return null;return`${U.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-U.length%4)%4)}`}function yT(G){let U=[],j={inSingle:!1,inDouble:!1,escaped:!1};for(let K=0;K<G.length;K++){let re=G[K];if(!re)break;if($o(re,j))continue;if(Kg(G,K,j)){let oe=bT(G,K+1);if(oe!==null)U.push(oe.body),K=oe.endIndex;continue}if(!j.inSingle&&re==="`"){let oe=CT(G,K);if(oe!==null)U.push(oe.body),K=oe.endIndex}}return U}function bT(G,U){let j={inSingle:!1,inDouble:!1,escaped:!1},K=1;for(let re=U+1;re<G.length;re++){let oe=G[re];if(!oe)break;if($o(oe,j))continue;if(Kg(G,re,j)){K++,re++;continue}if(!j.inSingle&&!j.inDouble&&oe===")"){if(K--,K===0)return{body:G.slice(U+1,re),endIndex:re}}}return null}function CT(G,U){let j=!1;for(let K=U+1;K<G.length;K++){let re=G[K];if(!re)break;if(j){j=!1;continue}if(re==="\\"){j=!0;continue}if(re==="`")return{body:G.slice(U+1,K),endIndex:K}}return null}function Kg(G,U,j){return!j.inSingle&&G[U]==="$"&&G[U+1]==="("&&G[U+2]!=="("}function ST(G){let U=[],j=[],K=!1,re=!1,oe=!1;for(let we=0;we<G.length;we++){let We=G[we];if(We===void 0)break;if(!oe&&We==="--"){oe=!0;continue}if(oe){j.push(We);continue}let mt=/^--([^=]+)(?:=(.*))?$/.exec(We);if(mt!==null){let gt=mt[1]??"",ft=mt[2];if(gt===aA)re=!0;if(cA.has(gt))K=!0;if(ft!==void 0){if(gt===Rg)U.push(ft);continue}if(dA.has(gt)){let pt=G[we+1];if(gt===Rg&&pt!==void 0)U.push(pt);we++}continue}if(We.startsWith("-")&&We.length>1){let gt=We.slice(1),ft="",pt="";for(let yt=0;yt<gt.length;yt++){let bt=gt[yt]??"";if(lA.has(bt))K=!0;if(uA.has(bt)){ft=bt,pt=gt.slice(yt+1);break}}if(ft==="")continue;if(pt.length>0){if(ft===Eg)U.push(pt);continue}let ht=G[we+1];if(ft===Eg&&ht!==void 0)U.push(ht);we++;continue}j.push(We)}let Se=!K&&!re?j.slice(1):j;return[...U,...Se]}function qn(G){let U=G.findIndex((j)=>!Yg(j)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(j));return U===-1?[]:G.slice(U)}function Yg(G){return G==="env"||G==="command"||G==="builtin"||G==="sudo"}var vT=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),ET=".env.",RT=new Set([".env.example",".env.sample",".env.template",".env.tpl",".env.defaults"]),xT=[".env.example.",".env.sample."];function _T(G){let U;try{U=new URL(G.trim())}catch{return!1}return U.protocol!=="file:"&&U.host!==""}function wT(G){return G.length>0&&!/\s/.test(G)}function ia(G,U,j,K){let re=Zg(G,U,j,K);return re!==""&&j.paths.entryKind(re)!=="missing"}function Zg(G,U,j,K){try{return _i(G,U,j,K)}catch(re){if(re instanceof s)throw re;return""}}var PT=/[?&][^?&=/]+=/,AT=new Set(["node_modules","__pycache__"]),TT=[["vendor","bundle"],["vendor","cache"]];function IT(G,U,j,K,re){if(_T(G))return null;let oe=yn(G,U,K,re);if(!oe)return null;let de=zt(oe.split("/").pop()??""),Se=zt(oe),we=()=>wT(de)||ia(G,U,K,re),We=zt(LT(G,U,K,re));for(let ft of za){let pt=`~/${ft.suffixParts.join("/")}`;if((kg(Se,pt)||kg(We,pt))&&ir(ft.id,j))return ft.id}if(RT.has(de)||xT.some((ft)=>de.startsWith(ft)))return null;let mt=kT(oe,U,j,K,re);if(mt)return mt;if(vT.has(de))return null;for(let ft of Ga)if(de===ft.basename&&ir(ft.id,j))return ft.id;if(de.startsWith(ET)&&ir($i.id,j)&&we())return $i.id;for(let ft of $a)if(de.length>ft.prefix.length&&de.startsWith(ft.prefix)){let pt=de.slice(ft.prefix.length)[0];if((pt==="-"||pt==="_")&&ir(ft.id,j)&&we())return ft.id}for(let ft of Ba)if(de.length>ft.prefix.length&&de.startsWith(ft.prefix)){if(de.slice(ft.prefix.length)===ft.suffix&&ir(ft.id,j))return ft.id}if(DT(Se))return null;if(!de.includes(".")&&Bo.pattern.test(de)&&ir(Bo.id,j))return Bo.id;if(PT.test(G)&&!ia(G,U,K,re))return null;let gt=NT(de,j);if(gt)return gt;return null}function kT(G,U,j,K,re){return Bi.find((oe)=>{if(!ir(oe.id,j))return!1;switch(oe.id){case"secret.cli.claude-code":return Lt(G,Bt(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),[".credentials.json"]);case"secret.cli.claude-code.config":{let de=zt(G).split("/");return Lt(G,Bt(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),["settings.json","settings.local.json"])||Ri(G,"~/.claude.json",U,K,re)||de.at(-1)==="settings.local.json"&&de.at(-2)===".claude"||de.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Lt(G,yn("~/.gemini/config",U,K,re),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let de=Bt(K.env.get("CODEX_HOME"),"~/.codex",U,K,re);return Lt(G,de,["auth.json",".credentials.json"])||_o(G,de,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let de=Bt(K.env.get("CODEX_HOME"),"~/.codex",U,K,re),Se=zt(G).split("/").at(-1)??"";return Lt(G,de,["config.toml"])||Se.endsWith(".config.toml")&&Lt(G,de,[Se])}case"secret.cli.gemini":return Lt(G,Jt(Bt(K.env.get("GEMINI_CLI_HOME"),"~",U,K,re),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let de=zt(G).split("/"),Se=K.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),we=K.env.get("ProgramData")?[Jt(Bt(K.env.get("ProgramData"),"",U,K,re),"gemini-cli")]:[];return Lt(G,Jt(Bt(K.env.get("GEMINI_CLI_HOME"),"~",U,K,re),".gemini"),["settings.json","google_accounts.json"])||de.at(-1)==="settings.json"&&de.at(-2)===".gemini"||(Se?.trim()?Ri(G,Se,U,K,re):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...we].some((We)=>Lt(G,yn(We,U,K,re),["settings.json"]))}case"secret.cli.copilot-cli":{let de=Bt(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re);return Lt(G,de,["config.json"])||_o(G,de,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Lt(G,Bt(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re),["mcp-config.json"]);case"secret.cli.kimi-code":{let de=Bt(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),Se=Bt(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re);return Lt(G,de,["server.token"])||_o(G,de,["credentials"])||_o(G,Se,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let de=["config.toml","mcp.json"],Se=zt(G).split("/");return Se.at(-1)==="mcp.json"&&Se.at(-2)===".kimi-code"||Lt(G,Bt(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),de)||Lt(G,Bt(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re),[...de,"config.json","config.json.bak"])}case"secret.cli.opencode":{let de=Jt(Bt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"opencode"),Se=zt(G).split("/").at(-1)??"",we=K.env.get("OPENCODE_DB")?.trim(),We=we&&we!==":memory:"?[we,`${we}-wal`,`${we}-shm`]:[];return Lt(G,de,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Se)&&Lt(G,de,[Se])||We.some((mt)=>Ri(G,mt,U,K,re))}case"secret.cli.opencode.config":{let de=Jt(Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"opencode"),Se=K.env.get("ProgramData")?[Jt(Bt(K.env.get("ProgramData"),"",U,K,re),"opencode")]:[],we=["opencode.json","opencode.jsonc"],We=K.env.get("OPENCODE_CONFIG");return we.includes(zt(G).split("/").at(-1)??"")||Lt(G,de,["config.json"])||(We?.trim()?Ri(G,We,U,K,re):!1)||["/Library/Application Support/opencode","/etc/opencode",...Se].some((mt)=>Lt(G,yn(mt,U,K,re),we))}case"secret.cli.pi":return Lt(G,Bt(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["auth.json"]);case"secret.cli.pi.config":return Lt(G,Bt(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["models.json"]);case"secret.cli.amp":{let de=yn("~",U,K,re);return[Jt(Bt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"amp"),Jt(de,".local","share","amp")].some((we)=>Lt(G,we,["secrets.json"]))||_o(G,Jt(de,".amp"),["oauth"])}case"secret.cli.amp.config":{let de=["settings.json","settings.jsonc"],Se=[Jt(Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"amp"),Jt(yn("~",U,K,re),".config","amp")],we=zt(G).split("/"),We=K.env.get("AMP_SETTINGS_FILE");return Se.some((mt)=>Lt(G,mt,de))||we.at(-2)===".amp"&&de.includes(we.at(-1)??"")||(We?.trim()?Ri(G,We,U,K,re):!1)}case"secret.cli.cursor":{let de=Jt(Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"cursor"),Se=Jt(Bt(K.env.get("CURSOR_DATA_DIR"),"~/.cursor",U,K,re),"projects");return Lt(G,yn("~/.cursor",U,K,re),["auth.json"])||Lt(G,de,["auth.json"])||zt(G).split("/").at(-1)==="mcp-auth.json"&&jr(zt(G),zt(Se))}case"secret.cli.cursor.config":{let de=zt(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".cursor"}case"secret.cli.grok-build":return Lt(G,Bt(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let de=zt(G).split("/");return de.at(-1)==="config.toml"&&de.at(-2)===".grok"||Lt(G,Bt(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["config.toml","managed_config.toml","requirements.toml"])||Lt(G,yn("/etc/grok",U,K,re),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return Lt(G,yn("~/.factory",U,K,re),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let de=zt(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".factory"||Lt(G,yn("~/.factory",U,K,re),["settings.json","hooks.json"])}case"secret.cli.devin":return[Bt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),yn("~/.local/share",U,K,re)].some((de)=>Lt(G,Jt(de,"devin"),["credentials.toml"])||_o(G,Jt(de,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[Bt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),yn("~/.config",U,K,re)].some((de)=>Lt(G,Jt(de,"devin"),["config.json"]));default:return!1}})?.id??null}var Ig=new WeakMap;function Bt(G,U,j,K,re){let oe=Ig.get(re)??new Map;Ig.set(re,oe);let de=`${j}\x00${G??""}\x00${U}`,Se=oe.get(de);if(Se!==void 0)return Se;let we=yn(G?.trim()?G:U,j,K,re);return oe.set(de,we),we}function Lt(G,U,j){return j.some((K)=>Xg(G,Jt(U,K)))}function _o(G,U,j){return j.some((K)=>jr(zt(G),zt(Jt(U,K))))}function Ri(G,U,j,K,re){return Xg(G,yn(U,j,K,re))}function Xg(G,U){return zt(G)===zt(U)}function Jt(G,...U){return $n([G,...U].filter(Boolean).join("/"))}function OT(G,U,j,K,re,oe){if(j.length===0)return!1;let de=zt(_i(G,U,re,oe));return j.some((Se)=>jr(de,zt(_i(Se,K,re,oe))))}function MT(G,U,j,K,re,oe){if(j.length===0)return!1;let de=zt(_i(G,U,re,oe));if(!de)return!1;let Se=re.env.get("HOME")??re.home,we=Se?$n(Nt(an(Se),re.paths,oe)):"",We=zt(we),mt=re.env.get("CC_SAFETY_NET_HOME"),gt=zt(mt?$n(Nt(sa(an(mt)),re.paths,oe)):we&&$n(Nt(`${we}/.cc-safety-net`,re.paths,oe)));if(gt&&jr(de,gt))return!1;return j.some((ft)=>{let pt=qa(ft);if(pt&&Og.basename(de)!==zt(pt.name))return!1;let ht=zt(_i(pt?.root??ft,K,re,oe));if(!ht)return!1;if(We&&(We===ht||We.startsWith(ht.endsWith("/")?ht:`${ht}/`)))return!1;return jr(de,ht)&&!(pt&&de===ht)})}function DT(G){let U=G.split("/");return U.some((j)=>AT.has(j))||TT.some(([j,K])=>U.some((re,oe)=>re===j&&U[oe+1]===K))}function NT(G,U){let j=G.lastIndexOf("."),K=j>0&&j<G.length-1?G.slice(j+1):"";if(K==="")return null;for(let re of Ua)if(K===re.extension&&ir(re.id,U))return re.id;for(let re of Ha)if(re.pattern.test(K)&&ir(re.id,U))return re.id;return null}function zt(G){return G.toLowerCase()}function ir(G,U){return!U?.disabledRules?.includes(G)}function yn(G,U,j,K){let{home:re,normalized:oe}=Vc(G,j,K);if(!oe)return"";if(!re)return oe;let de=qc(oe,re),Se=ra(de)?de:$n(sa(U,de)),we=$n(Nt(Se,j.paths,K));if(!jr(we,re)){if(ra(de))return we;return we===Se?oe:we}let We=we.slice(re.length);return We?`~${We}`:"~"}function kg(G,U){return G===U||G.startsWith(`${U}/`)}function LT(G,U,j,K){let{home:re,normalized:oe}=Vc(G,j,K);if(!oe||!re)return"";let de=qc(oe,re),Se=Og.normalize(ra(de)?de:$n(sa(U,de))),we=$n(an(j.env.get("HOME")??j.home)),We=(ft)=>process.platform==="win32"?ft.toLowerCase():ft,mt=[re,we].find((ft)=>ft!==""&&jr(We(Se),We(ft)));if(mt===void 0)return"";let gt=Se.slice(mt.length);return gt?`~${gt}`:"~"}function _i(G,U,j,K){let{home:re,normalized:oe}=Vc(G,j,K);if(!oe)return"";let de=re?qc(oe,re):oe;return $n(Nt(ra(de)?de:sa(U,de),j.paths,K))}function Vc(G,U,j){let K=U.env.get("HOME")??U.home,re=K?$n(Nt(an(K),U.paths,j)):"",oe=$n(an(WT(er(G,U))));return{home:re,normalized:oe}}function WT(G){if(!G.trim().toLowerCase().startsWith("file:"))return G;try{return UP(G)}catch{return G}}function qc(G,U){if(G==="~")return U;if(G.startsWith("~/"))return Jt(U,G.slice(2));return G}function FT(G){if(process.platform==="win32")return!0;return BP.parse(G).root.length>1}function $n(G){let U=G.trim(),j=(U.includes("\\")&&FT(U)?U.replace(/\\/g,"/"):U).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(j==="/")return j;return j.replace(/\/+$/g,"")}function jr(G,U){return G===U||G.startsWith(U.endsWith("/")?U:`${U}/`)}function un(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}class p extends Error{stage;evaluation;name="GuardEvaluationError";constructor(G,U,j){super(`CC Safety Net ${G} dependency failed`,{cause:j});this.stage=G;this.evaluation=U}}var GT={findPolicyMutation:Cg,findGitMetadataMutation:Um,resolveGitMetadata:$T,loadPolicySnapshot:k,findSensitiveTarget:Wg,analyzeCommand:mg,getModes:T},zT=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function V(G,U){let j={...GT,...U.dependencies},K=HT(G),re=wi(G)?G.command:K,oe=Cr("policy-protection",re,()=>Gm(G)),de=pn(oe,"input-candidate"),Se=pn(oe,"declared-command");if(wi(G)&&G.command?.trim()&&Se?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Bn,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:G.command,segment:G.command}}};if(de?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:uf,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let we=Pn(),We=Cr("policy-protection",re,()=>j.resolveGitMetadata([G.context.executionCwd,G.context.configCwd],U.environment)),mt=Cr("policy-protection",re,()=>j.findPolicyMutation(oe,U.environment,we));if(mt){let St=re??mt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:He,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:St,segment:mt.target}}}}let gt=Cr("policy-protection",re,()=>gg(oe,U.environment,we));if(gt){let St=re??gt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Ge,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:St,segment:gt.target}}}}let ft=Cr("policy-protection",re,()=>j.findGitMetadataMutation(oe,We,U.environment,we));if(ft){let St=re??ft.target;return{stage:"policy-protection",decision:{kind:"deny",reason:x,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:St,segment:ft.target}}}}let pt=Cr("config-load",re,()=>j.loadPolicySnapshot(U.environment,{...U.policyOptions,cwd:G.context.configCwd})),ht=pt.policy,yt=j.getModes(ht,U.environment.env),bt={level:yt.effectiveLevel,...BT(pt)},Ct=ht.secretProtection.enabled===!1?null:Cr("secret-protection",re,()=>j.findSensitiveTarget(oe,ht.secretProtection,U.environment,we,{strict:wi(G)||de?.program.dialect==="powershell"?yt.strict:void 0}));if(Ct){let St=re??Ct.target;return{stage:"secret-protection",...bt,decision:{kind:"deny",reason:Mg,intent:"hard_stop",ruleId:Ct.ruleId,evidence:{command:St,segment:Ct.target}}}}if(!wi(G))return{stage:"non-command",...bt,decision:{kind:"allow"}};if(!G.command||G.command.trim()==="")return{...Kc("command-validation",re),...bt};let vt=Cr("command-analysis",re,()=>fg(()=>j.analyzeCommand(G.command,{cwd:G.context.executionCwd,shell:G.route.shell,policySnapshot:pt,environment:U.environment,protectedGitMetadata:We,effectiveCapabilities:yt.capabilities,strict:yt.strict,paranoidRm:yt.paranoidRm,paranoidInterpreters:yt.paranoidInterpreters,worktreeMode:yt.worktreeMode,budget:we,...U.trace?{trace:U.trace}:{}},UT(oe),oe.store),G.command,U.trace));if(vt.decision){let St=!yt.strict&&(vt.decision.ruleId==="raw-text.dangerous-command"||vt.decision.reason===di&&!zT.test(vt.decision.evidence?.segment??"")&&In(G.command)===null);return{stage:"command-analysis",...bt,..."errorCode"in vt?{errorCode:vt.errorCode}:{},decision:St?{...vt.decision,unverifiedByStandardMode:!0}:vt.decision}}return{stage:"command-analysis",...bt,decision:{kind:"allow"}}}function $T(G,U){let j=[...new Set(G.filter((K)=>typeof K==="string"&&K!==""))].flatMap((K)=>U.gitMetadata(K)??[]);if(j.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(j.flatMap((K)=>K.entries))]),markerFiles:Object.freeze([...new Set(j.flatMap((K)=>K.markerFiles))]),directories:Object.freeze([...new Set(j.flatMap((K)=>K.directories))]),hooksDirectories:Object.freeze([...new Set(j.flatMap((K)=>K.hooksDirectories))])})}function BT(G){if(G.state==="ready")return{};return{configFallback:{reason:G.reason}}}function UT(G){return pn(G,"declared-command")?.program}function HT(G){try{return ie(G.input)}catch(U){let j=wi(G)?G.command:void 0;throw new p("policy-protection",Kc("policy-protection",U instanceof f?void 0:j,U),U)}}function Cr(G,U,j){try{return j()}catch(K){throw new p(G,Kc(G,K instanceof f?void 0:U,K),K)}}function Kc(G,U,j){let K=j instanceof s||j instanceof b;return{stage:G,decision:{kind:"deny",reason:K?ca:ko,ruleId:K?"analysis.limit":"analysis.failed-closed",intent:"stop_and_explain",...U?{evidence:{command:U,segment:U}}:{}}}}function wi(G){return G.route.kind==="command"}
49
+ export{a,s,J,Pe,Be,R,nt,ze,Ce,O,D,Y,rt,c,n,qe,Ee,T,v,pe,ot,f,P,ie,fe,it,Ve,Ke,u,Ie,o,S,i,se,r,g,me,H,st,at,d,ge,he,ct,N,Z,ae,w,lt,_,h,ke,W,l,L,X,Je,Ye,M,C,I,ye,be,Ae,ut,m,e,Oe,Re,Ze,Xe,ce,Te,le,De,Q,B,Ne,xe,z,Qe,q,ee,te,ue,et,tt,E,F,Le,Me,Fe,$e,k,je,_e,Ue,y,t,ne,ve,b,x,A,dt,Ge,He,p,V};