cc-safety-net 2.6.7 → 2.6.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/amp/cc-safety-net/index.ts +44 -44
- package/dist/api.js +1 -1
- package/dist/bin/hook.js +43 -43
- package/dist/chunks/{index-d2fyjccr.js → index-0d9zqgyg.js} +2 -2
- package/dist/chunks/index-j7c6979z.js +49 -0
- package/dist/chunks/{index-dyrr0c57.js → index-zwavdh1s.js} +1 -1
- package/dist/cli.js +3 -3
- package/dist/deepseek-harness/index.js +1 -1
- package/dist/index.js +1 -1
- package/dist/openclaw/cc-safety-net/index.js +44 -44
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunks/index-bbhtr799.js +0 -49
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
var ua="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Un="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 ca={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,...ca},processedCandidateBytes:{cap:4194304,...ca},pathEnvironmentExpansion:{cap:64,...ca},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 An(){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 Qg=[/\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 Qg.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 Jc(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 Jc(G).map((U)=>G.slice(U.valueStart,U.valueEnd))}function ze(G){return/[A-Za-z_][A-Za-z0-9_]*=/.test(G)}function Jc(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:eh(G,K)}]})}function eh(G,U){if(G.startsWith("$(",U))return th(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 th(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 nh={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 rh(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.":nh[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 oh={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{...oh[G.directory][G.problem],command:U.command,toolName:U.toolName,cwd:G.cwd}}function Y(G){return rh({...G,redact:J})}function rt(G){return J(G instanceof Error?G.message:String(G))}import{lstatSync as zh,realpathSync as $h,statSync as Bh}from"node:fs";import{homedir as Uh,tmpdir as Hh}from"node:os";import{statSync as Wh}from"node:fs";import{join as Fh}from"node:path";import{basename as tu,dirname as ih,isAbsolute as sh,join as ah,normalize as lh,resolve as Qc}from"node:path";var ch=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 cn(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 pa(G,U){return da(G,0,U)}function da(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=ma(G,re+2),we=uh(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+=dh(We,U,j),re=we+1;continue}let de=ma(G,re+1);if(!de){K+="$",re++;continue}K+=fa(de,j)??`$${de}`,re+=de.length+1}return K}function uh(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 dh(G,U,j){let K=G.slice(2,-1),re=ma(K,0);if(!re)return G;let oe=K.slice(re.length);if(!oe)return fa(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=fa(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??"":da(oe.slice(de.length),U+1,j);return we?da(oe.slice(de.length),U+1,j):""}function ma(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 fa(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){nu(j,oe);let de=U.realpath(oe);if(de!==null)return eu(j,G,de,re);let Se=ih(oe);if(Se===oe||re.length>=ch)return eu(j,G,oe,re);re.push(tu(oe)),oe=Se}}function eu(G,U,j,K){let re=K.length===0?j:ah(j,...K.reverse());return G.resolvedPaths.set(U,re),re}function mh(G,U,j){let K=j.resolvedPaths.get(G);if(K!==void 0)return K;nu(j,G);let re=U.realpath(G);if(re!==null)j.resolvedPaths.set(G,re);return re}function nu(G,U){G.charge("realpathAttempts"),G.charge("processedCandidateBytes",Buffer.byteLength(U))}function un(G,U,j,K){let re=ou(G,U,j);if(!re)return"";return Nt(re,j.paths,K).replace(/\\/g,"/")}function ru(G,U,j,K,re){let oe=ou(G,U,j);if(!oe)return null;if(re(tu(oe)))return Nt(oe,j.paths,K).replace(/\\/g,"/");let de=mh(oe,j.paths,K);return de===null?null:de.replace(/\\/g,"/")}function ou(G,U,j){let K=j.home,re=pa(G.trim(),j).replace(/\\/g,"/");if(!re)return"";let oe=re==="~"?K:re.startsWith("~/")?Qc(K,re.slice(2)):re,de=cn(oe);return lh(sh(de)?de:Qc(U,de))}import{spawnSync as fh}from"node:child_process";import{existsSync as Mo,lstatSync as ph,readFileSync as Do,realpathSync as qr,statSync as Oo}from"node:fs";import{dirname as ga,isAbsolute as ha,join as Kr,resolve as Ai}from"node:path";var gh=["/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"],hh=5000;function su(G,U=Mh(),j=hh){let K=yh(G),re=K===null?null:bh(K);if(K===null||re===null)return null;let oe=kh(K,re,U,j);return oe===null?null:{recursiveSubmodules:oe}}function yh(G){try{let U=qr(Ai(G));return Oo(U).isDirectory()?U:null}catch{return null}}function bh(G){let U=Ih(G);if(!U)return null;try{let j=ph(U);if(j.isSymbolicLink()||!j.isFile())return null;let K=ya(U);if(!K?.commonDir)return null;if(!vh(K.gitDir,U))return null;return Eh(K.gitDir,ga(U))?{gitDir:K.gitDir,commonDir:K.commonDir}:null}catch{return null}}function ya(G){try{let U=Ch(G);if(!U)return null;let j=qr(ha(U)?U:Ai(ga(G),U));if(!Oo(j).isDirectory())return null;return{gitDir:j,commonDir:Sh(j)}}catch{return null}}function Ch(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 Sh(G){try{let U=Do(Kr(G,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!U)return null;let j=qr(ha(U)?U:Ai(G,U));return Oo(j).isDirectory()?j:null}catch{return null}}function vh(G,U){let j=Rh(G);return j===null?!1:au(G,j,U)}function Eh(G,U){let j=xh(G);return j===null?!0:au(G,j,U)}function Rh(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 xh(G){let U=Kr(G,"config.worktree");return Mo(U)?wh(U):null}function au(G,U,j){try{return _h(ha(U)?U:Ai(G,U),j)}catch{return!1}}function _h(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 iu(qr.native(G))===iu(qr.native(U))}function iu(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 wh(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=Ph(de[1]??"")}return K}function Ph(G){let U=G.trim();if(!U.startsWith('"')||!U.endsWith('"'))return U;return Th(U.slice(1,-1))}var Ah={"\\":"\\",'"':'"',n:`
|
|
4
|
-
`,t:"\t",b:"\b"};function Th(G){return G.replace(/\\(.?)/gs,(U,j)=>j===""?U:Ah[j]??U)}function Ih(G){try{return ba(qr(G))}catch{return null}}function ba(G){let U=G;while(!0){let j=Kr(U,".git");if(Mo(j))return j;let K=ga(U);if(K===U)return null;U=K}}function kh(G,U,j,K){if(Oh(U))return!0;if(j===null)return!0;let re=fh(j,["config","--get","submodule.recurse"],{cwd:G,encoding:"utf8",env:Dh(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&&lu(re.stdout.trim())}function Oh(G){return[Kr(G.commonDir,"config"),Kr(G.gitDir,"config.worktree")].filter((U)=>Mo(U)).some((U)=>Nh(U))}function Mh(){return gh.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 Dh(G){return Object.fromEntries(Object.entries(G).filter(([U])=>!No(U)))}function Nh(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(Lh(j)&&we==="path")return!0;if(j==="submodule"&&we==="recurse")K=lu(We)}return K}function Lh(G){return G==="include"||G.startsWith("includeif ")}function lu(G){let U=G.toLowerCase();return U!=="false"&&U!=="no"&&U!=="off"&&U!=="0"}function cu(G,U){if(G==="")return null;let j=An(),K=ba(un(G,G,U,j)),re=K?Gh(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 Gh(G,U,j,K){try{let re=un(G,U,j,K),oe=Wh(G),de=oe.isFile()?re:null,Se=oe.isFile()?ya(G):null,we=(oe.isDirectory()?[re]:[Se?.gitDir,Se?.commonDir]).flatMap((mt)=>mt?[Yr(un(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(Fh(mt,"hooks").replace(/\\/g,"/"));return[gt,Yr(un(gt,U,j,K))]}))]}}catch{return null}}function Yr(G){return process.platform==="win32"?G.toLowerCase():G}var jh={realpath:(G)=>{try{return $h(G)}catch{return null}},entryKind:(G)=>{try{let U=zh(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 Bh(G).isDirectory()}catch{return!1}}};function c(){return Vh({env:new Map(Object.entries(process.env).flatMap(([G,U])=>U===void 0?[]:[[G,U]])),home:cn(process.env.HOME||Uh()),tmpdir:Hh(),paths:jh})}function Vh(G,U={}){let j=new Map,K=new Map,re={...G,gitMetadata:(oe)=>uu(j,oe,()=>cu(oe,re)),worktreeFacts:(oe)=>uu(K,oe,()=>su(oe)),...U};return re}function uu(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 gy,constants as wu,statSync as hy}from"node:fs";import{isAbsolute as Pu,relative as yy,resolve as by,sep as Cy}from"node:path";import{types as qh}from"node:util";var Kh=new Set(["applypatch","patch"]),Yh=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),Zh=new Set(["grep","grepsearch","rg"]),Xh=new Set(["find","findbyname","glob"]),Jh=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),Qh=new Set(["command","diff","input","patch","patchtext"]),du=new TextEncoder,ey=new TextDecoder,ty=/\s/,ny=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 hu(G){return G.replace(/[-_\s]/g,"").toLowerCase()}function Ii(G){return Jh.has(hu(G))}function P(G){let U=hu(G);if(Kh.has(U))return"patch";if(Zh.has(U))return"grep";if(Xh.has(U))return"glob";if(Yh.has(U))return"path";return"unknown"}function ie(G){if(!G||typeof G!=="object")return;Ru(G);let U=Object.getOwnPropertyDescriptor(G,"command");if(!U){if("command"in G)Hn();return}if(U.get||U.set)Hn();let j=U.value;return typeof j==="string"&&j!==""?j:void 0}function yu(G,U){return bu(G,U,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function bu(G,U,j,K,re){let oe=Eu(G,K,re);if(typeof G==="string")return j?[G]:[];if(!oe)return[];let de=oe.entries.flatMap(([Se,we])=>bu(we,U,oe.array?j:U.has(Cu(Se)),K,re+1));return K.ancestors.delete(oe.object),de}function Cu(G){return G.replace(/-/g,"_").toLowerCase()}function Su(G){return vu(G,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(oy)}function vu(G,U,j,K){let re=Eu(G,j,K);if(typeof G==="string")return U?[G]:[];if(!re)return[];let oe=re.entries.flatMap(([de,Se])=>vu(Se,re.array?U:Qh.has(Cu(de)),j,K+1));return j.ancestors.delete(re.object),oe}function ry(G,U,j){if(U.nodes++,G!==null&&typeof G==="object"&&j>Lo.maxDepth||U.nodes>Lo.maxNodes)Hn();if(typeof G!=="string")return;let K=Buffer.byteLength(G);if(U.stringBytes+=K,K>Lo.maxStringBytes||U.stringBytes>Lo.maxAggregateStringBytes)Hn()}function Eu(G,U,j){if(ry(G,U,j),!G||typeof G!=="object")return null;let K=Ru(G);if(U.ancestors.has(G))Hn();let re=Reflect.ownKeys(G);if(U.keys+=re.length,U.keys>Lo.maxKeys)Hn();let oe=re.flatMap((de)=>{let Se=Object.getOwnPropertyDescriptor(G,de);if(!Se||Se.get||Se.set)Hn();return typeof de==="string"&&Se.enumerable?[[de,Se.value]]:[]});return U.ancestors.add(G),{object:G,array:K,entries:oe}}function Ru(G){if(qh.isProxy(G))Hn();let U=Array.isArray(G),j=Object.getPrototypeOf(G);if(U&&j!==Array.prototype||!U&&j!==Object.prototype&&j!==null)Hn();return U}function Hn(){throw new f}function oy(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=iy(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(...Ca(We));continue}if(re)continue;if(We.startsWith("diff --git ")){U.push(...Ca(We));continue}if(We.startsWith("--- ")){let mt=j[we+1]??"";if(!mt.startsWith("+++ "))continue;U.push(...va(Ti(We.slice(4),!0),Ti(mt.slice(4),!0))),we++;continue}if(!K)U.push(...Ca(We))}return U}function iy(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 Ca(G){let U=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(G);if(U?.[1])return gu(U[1]);let j=/^\*\*\* Move to: (.+)$/.exec(G);if(j?.[1])return gu(j[1]);if(G.startsWith("diff --git "))return sy(G.slice(11));let K=/^--- (.+)$/.exec(G);if(K?.[1])return pu(K[1]);let re=/^\+\+\+ (.+)$/.exec(G);if(re?.[1])return pu(re[1]);let oe=/^(?:rename|copy) (?:from|to) (.+)$/.exec(G);if(oe?.[1])return fy(oe[1]);return[]}function sy(G){let U=ay(G);if(U.length===2&&U[0]&&U[1])return va(U[0],U[1]);let j=ly(G);return j?va(G.slice(j.oldStart,j.oldEnd),G.slice(j.newStart,j.newEnd)):[]}function ay(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=xu(G,j,K);if(!re)return[];U.push(re.value),j=re.end}while(Er(G[j]))j++;return j===G.length?U:[]}function ly(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>ny)Hn();if(cy(G,U,oe,re,j))return{oldStart:U,oldEnd:oe,newStart:re,newEnd:j}}return null}function cy(G,U,j,K,re){if(Sa(G,U,j,K,re))return!0;let oe=mu(G,"/",U,j),de=mu(G,"/",K,re);if(oe<=U||de<=K)return!1;if(Sa(G,U,oe,K,de))return!1;return Sa(G,oe+1,j,de+1,re)}function Sa(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 mu(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&&ty.test(G)}function xu(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:ey.decode(Uint8Array.from(K)),end:re+1};if(oe!=="\\"||j==="'"){K.push(...du.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(...du.encode(uy(de[0]??""))),re+=2}return null}function uy(G){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
5
|
-
`,r:"\r",t:"\t",v:"\v"}[G]??G}function dy(G){return Wo(py(G))}function va(G,U){if(G==="/dev/null")return fu(U);if(U==="/dev/null")return fu(G);if(G.startsWith("a/")&&U.startsWith("b/"))return[G.slice(2),U.slice(2)].flatMap(Wo);let j=my(G,U)??(G===U?_u(G):null);return[G,U,...j?[j]:[]].flatMap(Wo)}function fu(G){let U=_u(G);return[G,...U?[U]:[]].flatMap(Wo)}function _u(G){let U=G.indexOf("/");return U>0&&U<G.length-1?G.slice(U+1):null}function my(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 pu(G){return dy(Ti(G,!0))}function fy(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=xu(j,0,K);if(re&&(U||j.slice(re.end).trim()===""))return re.value}return U?j.split("\t",1)[0]?.trim()??"":j}function py(G){return G.startsWith("a/")||G.startsWith("b/")?G.slice(2):G}function Wo(G){return G===""||G==="/dev/null"?[]:[G]}function gu(G){let U=G.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return U===""||U==="/dev/null"?[]:[U]}function fe(G){try{if(!hy(G).isDirectory())return!1;return gy(G,wu.R_OK|wu.X_OK),!0}catch{return!1}}function it(G,U,j){if(sr(G))return;let K=U.flatMap((oe)=>Ea(oe,j));if(!K[0])return;let re=Ea(Pu(G)?G:by(K[0],G),j)[0];if(!re)return;return K.some((oe)=>Sy(re,oe))?re:void 0}function qe(G,U){return G.flatMap((j)=>Ea(j,U))[0]}function Ea(G,U){let j=U.realpath(G);if(j===null)return[];return U.isDirectory(j)?[j]:[]}function Sy(G,U){let j=yy(U,G);return j===""||j!==".."&&!j.startsWith(`..${Cy}`)&&!Pu(j)}var vy=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>vy)throw Ey(G),Error("hook input byte limit exceeded");U.push(re)}return Buffer.concat(U,j).toString("utf-8")}function Ey(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 Au(G,U){if(!U)return G;return Oi.indexOf(U)>Oi.indexOf(G)?U:G}function Tu(G){let U=pe(n.level,G);return Oi.find((j)=>j===U)}function Iu(G,U){return Au(G,Tu(U))}function Ry(G){let U=pe(n.level,G);if(!U)return;let j=Tu(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 Ve(G){if(G===void 0||G==="all")return"all";if(G==="blocked")return"blocked";return"invalid"}function Ee(G){return Ve(pe(n.auditScope,G))==="all"}function Ra(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=Ry(U),re=Au(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:Ra(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 xy,constants as Go,fstatSync as xa,fsyncSync as _y,lstatSync as Tn,mkdirSync as ku,openSync as Ou,readdirSync as wa,readFileSync as wy,realpathSync as Xr,renameSync as Py,rmdirSync as Mu,statSync as _a,unlinkSync as Pa,writeFileSync as Ay}from"node:fs";import{isAbsolute as Du,join as Rr,normalize as Ty,parse as Mi,relative as Aa,resolve as Ta,sep as Di}from"node:path";function Ie(){let G=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${G()}${G()}`}var Iy=Symbol("PolicyFilesystemScope"),ky=Symbol("PolicyFilesystemTarget"),Nu=Go.O_NOFOLLOW??0;class o extends Error{name="PolicyFilesystemError";constructor(G){super(`Unable to access ${G} filesystem safely.`)}}function S(G,U){return{[Iy]:!0,root:Ta(G),label:U}}function zo(G,U){let j=Ty(U);if(U===""||Du(U)||j===".."||j.startsWith(`..${Di}`))throw new o(G.label);return{[ky]:!0,scope:G,relativePath:j,path:Rr(G.root,j)}}function i(G,U){return zo(G,Aa(G.root,Ta(U)))}function se(G,U="rules policy"){let j=Ta(G),K=Mi(j).dir;return zo(S(K,U),Aa(K,j))}function r(G){return Zn(G.scope.label,()=>{if(!nn(G))return null;let U=Ou(G.path,Go.O_RDONLY|Nu);return Wu(U,()=>{let j=xa(U);if(!j.isFile())throw new o(G.scope.label);let K=wy(U,"utf-8"),re=Tn(G.path);if(!re.isFile()||re.isSymbolicLink()||j.dev!==re.dev||j.ino!==re.ino)throw new o(G.scope.label);return nn(G),K})})}function g(G,U,j=384,K){let re=`${G.path}.${Ie()}.tmp`;Zn(G.scope.label,()=>{My(G),nn(G);let oe=Ou(re,Go.O_CREAT|Go.O_EXCL|Go.O_WRONLY|Nu,j),de=Wu(oe,()=>{let Se=xa(oe);if(!Se.isFile())throw new o(G.scope.label);Ay(oe,U,"utf-8"),_y(oe);let we=xa(oe);if(!we.isFile()||we.dev!==Se.dev||we.ino!==Se.ino)throw new o(G.scope.label);return we});nn(G),Ny(G,re,de.dev,de.ino),Py(re,G.path),K?.(G.path),nn(G)},()=>Ly(re))}function Lu(G,U){if(G.path===U.path)return!0;return Zn(G.scope.label,()=>{if(!nn(G)||!nn(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(!nn(G,"directory"))return null;let j=wa(G.path);return nn(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=Tn(re.path);if(oe.isSymbolicLink()||!oe.isFile()&&!oe.isDirectory())throw new o(G.scope.label);return Ni(Ia(G.scope),Xr(re.path),G.scope.label),{name:K,kind:oe.isDirectory()?"directory":"file"}});return nn(G,"directory"),j})}function H(G){Zn(G.scope.label,()=>{if(!nn(G))return;Pa(G.path),nn(G)})}function st(G){Zn(G.scope.label,()=>{if(!Oy(G))return;Gu(G),nn(G,"directory")})}function at(G){Zn(G.scope.label,()=>{if(!nn(G,"directory"))return;Mu(G.path),nn(G,"directory")})}function Oy(G){return Zn(G.scope.label,()=>{if(!nn(G,"directory"))return!1;return Fu(G),!0})}function Zn(G,U,j){try{return U()}catch(K){if(j?.(),K instanceof o)throw K;throw new o(G)}}function Wu(G,U){try{return U()}finally{xy(G)}}function nn(G,U="file"){let j=zu(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=Tn(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 Fu(G){for(let U of wa(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=Tn(j.path);if(K.isSymbolicLink()||!K.isDirectory()&&!K.isFile())throw new o(G.scope.label);if(K.isDirectory())Fu(j)}nn(G,"directory")}function Gu(G){for(let U of wa(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=Tn(j.path);if(K.isSymbolicLink())throw new o(G.scope.label);if(K.isDirectory()){Gu(j);continue}if(!K.isFile())throw new o(G.scope.label);Pa(j.path)}Mu(G.path)}function My(G){Dy(G.scope);let U=Ia(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(!Tn(re,{throwIfNoEntry:!1}))ku(re,{mode:448});let oe=Tn(re);if(!oe.isDirectory()||oe.isSymbolicLink())throw new o(G.scope.label);Ni(U,Xr(re),G.scope.label)}}function Dy(G){if(Tn(G.root,{throwIfNoEntry:!1})){if(!_a(G.root).isDirectory())throw new o(G.label);return}let U=[],j=G.root;while(!Tn(j,{throwIfNoEntry:!1})){U.unshift(j);let K=Mi(j).dir;if(K===j)throw new o(G.label);j=K}if(!_a(j).isDirectory())throw new o(G.label);for(let K of U){ku(K,{mode:448});let re=Tn(K);if(!re.isDirectory()||re.isSymbolicLink())throw new o(G.label)}}function zu(G){if(!Tn(G.root,{throwIfNoEntry:!1}))return null;if(!_a(G.root).isDirectory())throw new o(G.label);return Xr(G.root)}function Ia(G){let U=zu(G);if(!U)throw new o(G.label);return U}function Ny(G,U,j,K){let re=Tn(U);if(!re.isFile()||re.isSymbolicLink()||re.dev!==j||re.ino!==K)throw new o(G.scope.label);Ni(Ia(G.scope),Xr(U),G.scope.label)}function Ni(G,U,j){let K=Aa(G,U);if(K===".."||K.startsWith(`..${Di}`)||Du(K))throw new o(j)}function Ly(G){try{Pa(G)}catch{}}import{dirname as xr,isAbsolute as $y,join as _r,relative as By,resolve as ar,sep as Uy}from"node:path";var d=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ge="rulebook.json",he=".cc-safety-net/rules";var $u=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,Wy=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,Bu=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,Fy=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Gy="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ct=new RegExp(`^${Fy}/(${d.source.slice(1,-1)})/${Gy}$`);function zy(G){return`.cc-safety-net/rules/${G}/rulebook.json`}function Uu(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($u);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||!Bu.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:zy(re),name:re}}function Z(G){return Wy.test(G)}function ae(G){return Bu.test(G)}function w(G){return $u.test(G)}function lt(G){if(!d.test(G))throw Error(`Local rulebook sources must be bare names matching ${d}: ${G}`)}var Hu="rule.json",Li="policy.json",ju=".cc-safety-net",Hy="rules",jy="CC_SAFETY_NET_HOME",Vu="`cc-safety-net rule update`";function Vy(G){return ar(G,he)}function _(G){return _r(Vy(G),Hu)}function h(G){return _r(ar(G),ju,Li)}function ke(G,U={}){return U.userConfigDir??(U.userConfigPath?xr(U.userConfigPath):_r(qy(G),Hy))}function qy(G){let U=G.env.get(jy);return U?ar(cn(U)):_r(G.home,ju)}function W(G,U={}){return _r(ke(G,U),Hu)}function l(G,U={}){return _r(xr(ke(G,U)),Li)}function L(G,U){let j=An();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=By(j,K);if(re!==".."&&!re.startsWith(`..${Uy}`)&&!$y(re))return S(j,"project policy");return S(xr(xr(K)),"project policy")}function M(G,U){return _r(G,U,ge)}var vn=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),C=/^[a-zA-Z][a-zA-Z0-9_-]*$/,I=256,Kt=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),qu=new Set(["python","python3","python2","node","ruby","perl"]),Wi=/^python(?:[23](?:\.\d+)*)?$/,In=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 Ku="Rulebook exceeds CC Safety Net's safe validation limits.",Yu="Additional rulebook validation errors were omitted.",Nn=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Zu(G){if(ka(G.allowed_commands,Nn.maxAllowedCommands)||ka(G.rules,Nn.maxRules)||ka(G.tests,Nn.maxTests))return!1;let{maxAggregateStringCodeUnits:U,maxTotalBlockArgs:j}=Nn,K=(re,oe=!1)=>{if(typeof re!=="string")return!0;if(re.length>Nn.maxStringCodeUnits||oe&&re.length>Nn.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>Nn.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 ka(G,U){return Array.isArray(G)&&G.length>U}var Oa=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 fn(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 Ky={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Ma=new Set(["--init-file","--rcfile"]);function Da(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]==="-"&>.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(!Ky[G]?.includes(mt))continue;if(We+1===U.length)oe++;break}return{interactive:re,followingValues:oe,commandSelected:de,stdinMode:Se,syntaxCheck:we}}function En(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"&&Ma.has(we)&&!de.includes("="))oe++;continue}let Se=Da(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 Yy(G))$o(j,U);return U.inSingle||U.inDouble}function Yy(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 Na=new Set(["rm","find","xargs","parallel"]),Zy=new Set(["git","busybox",...Na,...Kt,...qu,...In]),Xy=new Set(["python","node","ruby","perl"]);function Ae(G){let U=Mt(G);return Zy.has(U)||Ln(U)}function Ln(G){return Xy.has(Jy(G))}function Jy(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(Qy(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 Qy(G){return typeof G==="string"?se(G):G}var e=(G,U)=>({path:G,message:U,kind:"typed"}),rn=(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[rn(["rules",K,"name"],`duplicate rule name "${re}"`)];return U.add(re.toLowerCase()),[]})}var Re=`must be one of ${Oa.join(", ")}`,eb=/^[^/]+\/[^/]+$/,tb=["version","rules","overrides","transparent_wrappers"];function Ze(G){let U=nb(G);return{errors:ce(Xe(U,tb,(j)=>j.kind==="custom"),": "," "),sources:ub(G,U)}}function nb(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")],...rb(G.rules,U),...sb(G.overrides),...lb(G.transparent_wrappers),...U?[]:ib(G.rules),...Jr(G.overrides)?Object.keys(G.overrides).filter((j)=>!eb.test(j)).map((j)=>rn(["overrides",j],"must use <rulebook-name>/<rule-name>")):[],...cb(G.transparent_wrappers)]}function rb(G,U){if(G===void 0)return[];if(!Array.isArray(G))return[e(["rules"],"must be an array of rulebook source strings"),...Xu(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"),...ob(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 Xu(G,U){let j=Ju(G);return j!==void 0&&!(j<=U)}function ob(G,U){let j=Ju(G);return j!==void 0&&!(j>=U)}function Ju(G){if(G===null||G===void 0)return;let U=G.length;return U===void 0?void 0:Number(U)}function ib(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[rn(["rules",K],"must be a non-empty rulebook source string")];let re=Uu(j);if(re)return[rn(["rules",K],re)];if(U.has(j))return[rn(["rules",K],`duplicate rulebook source "${j}"`)];return U.add(j),[]})}function sb(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[...ab(j.reason,["overrides",U,"reason"]),...j.intent===void 0||Te(j.intent)?[]:[e(["overrides",U,"intent"],Re)]]})}function ab(G,U){if(typeof G!=="string")return[e(U,"required non-empty string"),...Xu(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 lb(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 cb(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[rn(["transparent_wrappers",K],`duplicate command "${j}"`)];if(Ae(j))return[rn(["transparent_wrappers",K],`reserved command "${j}" cannot be a wrapper`)];return U.add(j),[]})}function ub(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=La(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 La(G){return G.map((U,j)=>{if(typeof U==="number")return`[${U}]`;return j===0?String(U):`.${String(U)}`}).join("")}function Te(G){return Oa.includes(G)}function Jr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function le(G){let U=fb(G);if(U.errors.length>0)throw Error(U.errors.join("; "));return G}var db=`required non-empty string up to ${I} characters`,Qu="must be a non-empty array of unique non-empty strings",mb="required non-empty array of non-empty strings";function fb(G){if(!lr(G))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Zu(G))return{errors:[Ku],ruleNames:new Set};let U=[...G.rulebook_version===1||G.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ce(pb(G,G.rulebook_version===2),": ",": ")];return{errors:U.length>Nn.maxValidationErrors?[...U.slice(0,Nn.maxValidationErrors),Yu]: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 pb(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")],...gb(G.allowed_commands),...hb(G.rules,U),...Sb(G.tests),...vb(G),...Eb(G)]}function gb(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[rn(["allowed_commands",K],`duplicate command "${j}"`)];return U.add(j),[]})]}function hb(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?bb(j,["rules",K]):yb(j,["rules",K])}),...Oe(G)]}function yb(G,U){return[...ed(G.name,U),...td(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),...nd(G.reason,U),...rd(G.intent,U)]}function bb(G,U){return[...ed(G.name,U),...td(G.command,U),...nd(G.reason,U),...rd(G.intent,U),...Cb(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 ed(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 td(G,U){return typeof G==="string"&&C.test(G)?[]:[e([...U,"command"],"required string matching command pattern")]}function nd(G,U){return typeof G==="string"&&G!==""&&G.length<=I?[]:[e([...U,"reason"],db)]}function rd(G,U){return G===void 0||Te(G)?[]:[e([...U,"intent"],Re)]}function Cb(G,U){if(!lr(G))return[e(U,"required object")];return[...zi(G.command_path,[...U,"command_path"],mb,!1),...G.any_args===void 0?[]:zi(G.any_args,[...U,"any_args"],Qu,!0),...G.exclude_args===void 0?[]:zi(G.exclude_args,[...U,"exclude_args"],Qu,!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===""?[rn([...U,de],"must be a non-empty string")]:[]});if(G.some((oe)=>typeof oe!=="string"))return re;return[...re,...G.length===0?[rn(U,j)]:[],...K&&new Set(G).size!==G.length?[rn(U,"must not contain duplicate values")]:[]]}function Sb(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"?[rn(["tests",j,"rule"],"required string for blocked fixtures")]:[]]})}function vb(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)=>rn(["tests"],`blocked fixture references unknown rule "${j}"`))}function Eb(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[rn(["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=Lu(j.userConfigTarget,j.projectConfigTarget)}catch(pt){if(pt instanceof o)return kb(j,pt.message);throw pt}let re=m(j.userConfigTarget),oe=K?{config:null,errors:[]}:m(j.projectConfigTarget),de=id(j.userConfigPath,re.errors),Se=id(j.projectConfigPath,oe.errors),we=new Set,We=re.config?Wa(re.config,wr(j.userConfigPath),"user",j.userScope,we):sd(),mt=oe.config?Wa(oe.config,wr(j.projectConfigPath),"project",j.projectScope,we):sd(),gt=re.config?.overrides??{},ft=oe.config?.overrides??{};return{rules:[...od(We.rules,gt),...od(mt.rules,ft)],transparent_wrappers:Tb(re.config,oe.config),rulebooks:[...We.rulebooks,...mt.rulebooks],errors:[...de,...Se,...We.errors,...mt.errors],warnings:[...We.warnings,...mt.warnings,...We.canValidateOverrides?Fa(gt,We.knownRuleIds,j.userConfigPath):[],...We.canValidateOverrides?Ib(ft,We.knownRuleIds,j.projectConfigPath):[],...mt.canValidateOverrides?Fa(ft,mt.knownRuleIds,j.projectConfigPath):[]],userConfig:re.config??void 0,projectConfig:oe.config??void 0,...j}}function B(G,U){let j=Rb(G,U);if(!j)return[];return[...j.scope.errors,...j.scope.warnings,...xb(j.config,j.scope,G)]}function Rb(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:Wa(K,wr(G),"project",j)}}function xb(G,U,j){return U.canValidateOverrides?Fa(G.overrides??{},U.knownRuleIds,j):[]}function Wa(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=wb(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:_b(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 _b(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 wb(G,U,j){let K=Ne(G),re=M(U,K),oe=Ab(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}; ${Pb(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 Pb(G){return w(G)?`run ${Vu} to vendor ${G}`:"create that file or remove that source from the rules config"}function Ab(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 Tb(G,U){return[...new Set([...G?.transparent_wrappers??[],...U?.transparent_wrappers??[]])]}function od(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 Fa(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 Ib(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 id(G,U){return U.map((j)=>j.startsWith("Unable to access ")?j:`${G}: ${j}`)}function kb(G,U){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[U],warnings:[],userConfigPath:G.userConfigPath,projectConfigPath:G.projectConfigPath}}function sd(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as Bb,readFileSync as Ub}from"node:fs";var ad=[{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"}],Ga=new Set(ad.map((G)=>G.id)),z=ad,Ob=new Map(z.map((G)=>[G.id,G.intent]));function xt(G,U){return{id:G,reason:U,intent:Ob.get(G)??"manual_only"}}var za=[{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."},Mb=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Db=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],$a=[{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"]},...Db.flatMap((G)=>Mb.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"]}],ld=[{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"}],Nb=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Ba=ld.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})),Ua=ld.flatMap((G)=>Nb.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)$/},Ha=["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})),ja=[{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=[...za,$i,...$a,...Ba,...Ua,Bo,...Ha,...ja,...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]:[])),Va=new Set(Qe.map((G)=>G.id));import{isAbsolute as qa,join as Lb,normalize as Wb,sep as Hi}from"node:path";var ji=process.platform==="win32",cd=/[*?]/;function Ka(G){let U=G.trim(),j=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(ji?U.replaceAll("\\","/"):U);if(!j)return null;let K=j[1]??"",re=j[2]??"";if(cd.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 Ya(G,U){if(typeof G!=="string"||G.trim()==="")return"must be a non-empty path string";let j=Uo(G.trim(),U);if(!qa(j))return"must be an absolute path or start with ~/";return Ho(j,U)}function Za(G,U){let j=ud(G,U);if(j===null)return"must be a non-empty path string";if(!qa(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 Fb="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Gb="cannot cover the guard's own configuration";function ud(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 Xa(G,U){let j=ud(G,U);if(j===null)return"must be a non-empty path string";let K=Ka(j)?.root??j;if(cd.test(K))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!qa(K))return null;if(Ho(K,U)!==null)return Fb;return zb(K,U)?Gb:null}function zb(G,U){let j=Vi(G),K=Vi(Lb(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=Wb(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 dd=30,qi=1,Ki=365;function md(G){if(typeof G!=="number"||!Number.isInteger(G))return 30;if(G<1)return 1;return G>365?365:G}var fd=new Set(z.filter((G)=>G.catastrophic).map((G)=>G.id));function Tt(G,U){if(!G)return null;if(fd.has(G.id))return G;if(U?.destructiveCommandProtectionEnabled===!1)return null;let j=U?.effectiveDestructiveCommandRules[G.id];return j&&!j.enabled?null:G}function Jt(G,U,j){if(fd.has(U))return!0;if(G?.destructiveCommandProtectionEnabled===!1)return!1;return G?.effectiveDestructiveCommandRules[U]?.enabled??j}function V(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 pd(G,U){return Object.freeze({...G,effectiveDestructiveCommandRules:V(G,U)})}var gd={standard:0,strict:1,paranoid:2};function ee(G,U,j=!1,K=G.safety.level){let re=$b(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:Ja(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:Ja(G.secret_protection.deny_paths,U.secret_protection?.deny_paths),allow_paths:Ja(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 Ja(G,U){return[...new Set([...G,...U??[]])]}function $b(G,U,j){let K=U.safety?.level,re=ki[j];return[...K&&gd[K]<gd[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"}]:[],...hd("destructive_command_protection.overrides",U.destructive_command_protection?.overrides,(oe)=>G.destructive_command_protection.enabled&&G.destructive_command_protection.overrides[oe]!=="off"),...hd("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?yd(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?yd(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 hd(G,U,j){return Object.entries(U??{}).flatMap(([K,re])=>re==="off"&&j(K)?[{field:`${G}.${K}`,message:`project policy disables rule ${K}`}]:[])}function yd(G,U){return(U??[]).filter((j)=>!G.includes(j))}var tl=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:dd}};function vd(G,U){let j=Yb(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,Iu(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?el(Se.policy):j.policy,errors:we,...We?{fallback:We}:{},...K.exists?{policyScopes:{levelScope:mt,weakenings:Se?.weakenings??[],weakeningsIgnored:oe}}:{}}}var Hb="project policy audit settings are ignored; audit is user scope only";function ue(G,U){if(!Rn(G))return{policy:{},diagnostics:[]};let j=Rn(G.safety)?G.safety:{},K=Rn(G.workflow)?G.workflow:{},re=Rn(G.destructive_command_protection)?G.destructive_command_protection:{},oe=Rn(G.secret_protection)?G.secret_protection:{},de={...tl.has(j.level)?{level:j.level}:{},...Rn(j.overrides)?bd({overrides:Ed(j.overrides,Zr,["safety","overrides"],Pr)}):{}},Se={...typeof re.enabled==="boolean"?{enabled:re.enabled}:{},...re.overrides!==void 0?{overrides:Yi(re.overrides,Ga,xd,Pr)}:{},...re.allow_paths!==void 0?{allow_paths:eo(re.allow_paths,Ya,U,["destructive_command_protection","allow_paths"],Pr)}:{}},we={...typeof oe.enabled==="boolean"?{enabled:oe.enabled}:{},...oe.overrides!==void 0?{overrides:Yi(oe.overrides,Va,_d,Pr)}:{},...oe.deny_paths!==void 0?{deny_paths:eo(oe.deny_paths,Za,U,["secret_protection","deny_paths"],Pr)}:{},...oe.allow_paths!==void 0?{allow_paths:eo(oe.allow_paths,Xa,U,["secret_protection","allow_paths"],Pr)}:{}};return{policy:bd({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?[]:[Hb]}}function Ed(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],nl));return[]}))}function bd(G){return Object.fromEntries(Object.entries(G).flatMap((U)=>Object.keys(U[1]).length>0?[U]:[]))}var Pr=()=>{return},nl="must be a boolean",rl="must be an object if provided",Rd=`must be an integer between ${qi} and ${Ki}`,xd={path:["destructive_command_protection","overrides"],label:"destructive command"},_d={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:wd(G,U,(re)=>{j.push(re)}),issues:j}}function E(G,U){return wd(G,U,Pr)}function wd(G,U,j){if(!Rn(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 Pd(G,et,[],j),{version:1,safety:{level:jb(K.level,j),overrides:Ed(re,Zr,["safety","overrides"],j)},workflow:{worktree_mode:Qa(oe.worktree_mode,["workflow","worktree_mode"],!1,j)},destructive_command_protection:{enabled:Qa(de.enabled,["destructive_command_protection","enabled"],!0,j),overrides:Yi(de.overrides,Ga,xd,j),allow_paths:eo(de.allow_paths,Ya,U,["destructive_command_protection","allow_paths"],j)},secret_protection:{enabled:Qa(Se.enabled,["secret_protection","enabled"],!0,j),overrides:Yi(Se.overrides,Va,_d,j),deny_paths:eo(Se.deny_paths,Za,U,["secret_protection","deny_paths"],j),allow_paths:eo(Se.allow_paths,Xa,U,["secret_protection","allow_paths"],j)},audit:{retention_days:Vb(we.retention_days,j)}}}function Qr(G,U,j,K){if(G===void 0)return{};if(!Rn(G))return K(e(U,rl)),{};return Pd(G,j,U,K),G}function Pd(G,U,j,K){for(let re of Object.keys(G).filter((oe)=>!U.includes(oe)))K({path:j,message:re,kind:"unknownKeys"})}function jb(G,U){if(G===void 0)return"standard";if(tl.has(G))return G;return U(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Qa(G,U,j,K){if(typeof G==="boolean")return G;if(G!==void 0)K(e(U,nl));return j}function Vb(G,U){if(!(G===void 0||typeof G==="number"&&Number.isInteger(G)&&G>=qi&&G<=Ki))U(e(["audit","retention_days"],Rd));return md(G)}function Yi(G,U,j,K){if(G===void 0)return{};if(!Rn(G))return K(e(j.path,rl)),{};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"?rn([...K,de],Se):e([...K,de],Se)),[]})}function Rn(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=V({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(!Bb(G))return{exists:!1,policy:F(),errors:[]};try{let j=Ub(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}: ${Kb(oe)}`),fallback:Rn(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 qb=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[rl,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[nl,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Rd,`not an integer between ${qi} and ${Ki}`]]);function Kb(G){let U=La(G.path);if(G.kind==="unknownKeys")return`${U===""?"":`${U}.`}${G.message}: unknown field`;if(G.kind==="key")return`${U}: unknown rule id`;let j=qb.get(G.message)??G.message;return U===""?j:`${U}: ${j}`}function Yb(G,U){let j=Me(G,U);if(!j.exists){let K=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!Rn(K))return{policy:Sd(),errors:[]};let re=E(K,U);return{policy:el(re),gui:re,errors:[],levelPresent:Cd(K)}}if(j.parsed===void 0)return{policy:Sd(),errors:j.errors,...j.fallback?{fallback:j.fallback}:{}};return{policy:el(j.policy),gui:j.policy,errors:j.errors,...j.fallback?{fallback:j.fallback}:{},levelPresent:Cd(j.parsed)}}function Cd(G){let U=Rn(G)&&Rn(G.safety)?G.safety:{};return tl.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 Sd(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Fe({}),denyPaths:[],allowPaths:[]}}}function el(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=vd(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}),...Qb(we.spec)?{source:we.spec}:{}}:{},...We&&typeof We==="object"?{override:Object.freeze({type:"reason",reason:We.reason})}:{}})]})));return _e(re,Zb(j,K),de,K.policyScopes)}function je(G){if(G.state==="ready")return{state:G.state};return{state:G.state,reason:G.reason}}function Zb(G,U){let j=Jb(U);if(G.errors.length===0&&G.warnings.length===0&&!j)return;return{diagnostics:[...G.errors,...G.warnings,...U.errors],reason:eC(G.errors.length>0?Xb(G.errors):void 0,G.warnings.length>0?il(G.warnings.join("; ")):void 0,j)}}function Xb(G){return`${il(G.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Jb(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 Qb(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=ol(structuredClone(G)),oe=K?{policyScopes:ol(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 ol(G){if(typeof G!=="object"||G===null)return G;for(let U of Object.values(G))ol(U);return Object.freeze(G)}function eC(...G){return il(G.filter((U)=>!!U).join("; "))}function il(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:sl(U.fail_closed,G.strict,"strict"),paranoid_rm:sl(U.paranoid_rm,G.paranoidRm,"paranoidRm"),paranoid_interpreters:sl(U.paranoid_interpreters,G.paranoidInterpreters,"paranoidInterpreters")};return{policy:pd(G.policySnapshot.policy,oe),effectiveCapabilities:oe,effectiveLevel:Ra({failClosed:j,paranoidRm:K,paranoidInterpreters:re}),strict:j,paranoidRm:K,paranoidInterpreters:re,worktreeMode:G.worktreeMode??!1}}function sl(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 $w,isAbsolute as Bw,join as Uw,parse as Hw,resolve as jw,sep as Vw}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 tC=/^[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)=>!tC.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 nC(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)=>pn(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 al(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 al({text:K,raw:G.slice(U,j),span:{start:U,end:j},provenance:re,quoted:oe,...de?{parts:de}:{}})}function pn(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 nC(U);if(U.kind==="group"||U.kind==="function")return Object.freeze({...U,span:Object.freeze(U.span),body:pn(U.body)});return Object.freeze({...U,span:Object.freeze(U.span)})}))})}function ll(G,U,j){if(U>=j||Td(G[U]??""))return null;let K="",re=!1,oe=!1,de=U;while(de<j&&!Td(G[de]??"")){let Se=G[de]??"";if(Se==="'"){re=!0;let we=Ad(G,de+1,j,"'");K+=we.text,oe||=!we.closed,de=we.next;continue}if(Se==='"'){re=!0;let we=Ad(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 cl(G,U,j,K){let re=[],oe=U;for(let de of K){let Se=oe,we=!1;while(oe<j){let We=rC(G,oe,j);if((de.stripTabs?We.text.replace(/^\t+/,""):We.text)===de.delimiter){de.attach({body:de.stripTabs?oC(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 Ad(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 Td(G){return G!=="\r"&&(/[\s;&|<>)]/u.test(G)||G==="`")}function rC(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 oC(G){return G.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Dd=new Set(["&&","||","|","|&"]),iC=new Set(["!","do","elif","else","if","then","until","while"]);function Nd(G,U){let j={start:0,end:G.length};if(G.length>U.maxInputLength)return pn({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=pC(G,K.quotedExpansionEnd,re.nodes)?[...re.issues,Fd]:re.issues;return pn({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(),Md(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 _t=pt==="\r"&&G[ft+1]===`
|
|
11
|
-
`?ft+2:ft+1,At=Se.at(-1);if(At?.kind!=="connector"||!Dd.has(At.operator))Se.push(Object.freeze({kind:"connector",operator:G.slice(ft,_t),span:Object.freeze({start:ft,end:_t})}));if(mt.length>0){let It=cl(G,_t,j,mt.splice(0));we.push(...It.issues),ft=It.next;continue}ft=_t;continue}ft++;continue}if(pt==="#"){while(ft<j&&G[ft]!==`
|
|
12
|
-
`&&G[ft]!=="\r")ft++;continue}let ht=We.start===-1?OC(G,ft,j):void 0;if(ht){if(dl(Se,we),oe>=K.maxDepth)return no(Se,we,ft,"depth-limit",K.maxDepth);if(!ul(re))return no(Se,we,ft,"word-limit",K.maxWords);let _t=ns(G,ht.braceIndex+1,j,K,re,oe+1,"}"),At=_t.next,It={start:ht.braceIndex+1,end:_t.closed?At-1:At},wt=Id(G,It,_t);if(Se.push({kind:"function",name:ht.name,span:{start:ft,end:At},body:wt}),we.push(..._t.issues),_t.pendingHeredocs.length>0||Yo(_t.nodes))we.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(mt.push(..._t.pendingHeredocs),_t.limited)return ts(Se,we,_t.next);if(!_t.closed)we.push({code:"unclosed-function-body",message:"function body is not closed"});ft=At;continue}let yt=rs(G,ft);if(yt){if(gt(),!jd(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==="{"&&CC(G,ft,j))&&We.start===-1){if(dl(Se,we),oe>=K.maxDepth)return no(Se,we,ft,"depth-limit",K.maxDepth);let _t=pt==="("?")":"}",At=ns(G,ft+1,j,K,re,oe+1,_t),It=At.next,wt={start:ft+1,end:At.closed?It-1:It},Lt=Id(G,wt,At);if(Se.push({kind:"group",style:pt==="("?"subshell":"brace",span:{start:ft,end:It},body:Lt}),we.push(...At.issues),At.pendingHeredocs.length>0||Yo(At.nodes))we.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(mt.push(...At.pendingHeredocs),At.limited)return ts(Se,we,At.next);if(!At.closed)we.push({code:pt==="("?"unclosed-subshell":"unclosed-brace-group",message:`${pt} group is not closed`});ft=It;continue}let bt=(pt==="<"||pt===">")&&G[ft+1]!=="("?cC(G,ft):null;if(bt){let _t=We.words.at(-1),At=_t&&_t.span.end===ft&&/^[0-9]+$/.test(_t.raw)?Number(_t.raw):void 0;if(At!==void 0)We.words.pop();let It=At===void 0?ft:_t?.span.start??ft;We.start=We.start===-1?ft:We.start;let wt=ft+bt.length;while(wt<j&&/[ \t]/.test(G[wt]??""))wt++;let Lt=G[wt],Bt=wt>ft+bt.length&&Lt==="#",en=!Lt||Ko(Lt)||!!rs(G,wt)||Lt===de||Lt===")"||Bt||(Lt==="<"||Lt===">")&&G[wt+1]!=="(",Sr=bt==="<<"||bt==="<<-",Ut=Sr?ll(G,wt,j):void 0,Ft=Ut?{word:to(G,wt,Ut.next,Ut.delimiter,"literal",Ut.quoted),nested:[],issues:[],next:Ut.next,limited:!1}:!en?ml(G,wt,j,K,re,oe):void 0;if(Ft){if(we.push(...Ft.issues),Ft.limited)return ts(Se,we,Ft.next);if(!ul(re))return no(Se,we,Ft.next,"word-limit",K.maxWords)}let ln=Ft?.next??ft+bt.length,Zt={kind:"redirection",operator:bt,span:{start:It,end:ln},...At===void 0?{}:{fd:At},...Ft?{target:Ft.word}:{}};if(We.redirections.push(Zt),Sr&&!Ut)we.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if(Ut){if(Ut.ambiguous||Ut.delimiter.length===0)we.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let Xt=We.nested;mt.push({delimiter:Ut.delimiter,quotedDelimiter:Ut.quoted,stripTabs:bt==="<<-",attach:(Sn)=>{if(Zt.heredoc=Sn,Sn.quotedDelimiter)return;let Yn=aC(G,Sn.bodySpan.start,Sn.bodySpan.end,K,re,oe+1);Xt.push(...Yn.programs),we.push(...Yn.issues)}})}if(!Sr&&!Ft)we.push({code:"missing-redirection-target",message:`redirection ${bt} requires a target word`});if(Ft)We.nested.push(...Ft.nested);We.end=ln,ft=ln;continue}let Ct=We.start===-1;if(Ct)dl(Se,we);let vt=ml(G,ft,j,K,re,oe);if(we.push(...vt.issues),vt.limited)return ts(Se,we,vt.next);let St=EC(We.words)?PC(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 Et=St?.words??[vt.word];for(let _t of Et){if(!ul(re))return no(Se,we,vt.next,"word-limit",K.maxWords);We.words.push(_t)}if(We.start=We.start===-1?ft:We.start,We.end=vt.next,We.nested.push(...vt.nested),Ct&&Vd(vt.word))gt();ft=vt.next>ft?vt.next:ft+1}return gt(),Md(Se,we),we.push(...MC(mt)),{nodes:Se,issues:we,next:ft,closed:de===void 0,limited:!1,pendingHeredocs:[]}}function Id(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 ml(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=sC(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=hC(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?pl(yt,mt,gt):Gd(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=$d(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:bC(G,U,Se)),nested:mt,issues:gt,next:Se,limited:ft}}function sC(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?pl(pt,we,We):Gd(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=$d(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=Wd(G,U);if(!de)return null;let{length:Se,closing:we}=de,We=we==="))",mt=we==="`",gt=G[U]==="<"||G[U]===">",ft=gl(G,U+Se,j,we),pt=ft===-1?j:ft,ht=ft===-1?j:ft+we.length;if(oe>=K.maxDepth)return{program:kC(G,U+Se,pt,"depth-limit"),next:ht,provenance:We?"arithmetic":"command-substitution"};if(We){let Et=[],_t=[],At=!1,It=U+Se;while(It<pt){let wt=Zo(G,It,pt,K,re,oe+1);if(!wt){if(Tr(G,It))_t.push(Ar);It++;continue}if(Et.push(...wt.program.nodes),_t.push(...wt.program.issues),At||=wt.program.status==="limited",It=wt.next,At)break}if(ft===-1)_t.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:pn({kind:"program",dialect:"posix",source:G.slice(U+Se,pt),span:{start:U+Se,end:pt},status:os(_t,At),issues:_t,nodes:Et}),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))?[gC]:[],St=[...yt.issues,...bt,...Ct,...vt];return{program:pn({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 aC(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),uC(G,we,mt.next)&&dC(mt.program))Se.push(Ar);we=mt.next}return{programs:de,issues:Se}}function pl(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 gl(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=cl(G,gt,j,de.splice(0));if(!ft.terminated)return-1;Se=ft.next-1;continue}let We=Ld(G,Se,U,j,re);if(We!==null){Se=We;continue}if(!re.double&&G.startsWith("$((",Se)){let gt=lC(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=ll(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 lC(G,U,j){let K=1,re={single:!1,double:!1};for(let oe=U;oe<j;oe++){let de=G[oe],Se=Ld(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 Ld(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!=="#"||!DC(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 cC(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=kd(G,U+1);if(G[j]!=="{")return!1;let K=G[kd(G,j+1)]??"";return K==="|"||Ko(K)}function uC(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 dC(G){return G?.status==="limited"||(G?.issues??[]).some((U)=>U.code===Ar.code)}function kd(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 Wd(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 mC=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"}),Fd=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"}),fC=/\$\(|`|[<>]\(/g;function pC(G,U,j){let K=fl(j);return[...G.slice(U).matchAll(fC)].some((re)=>{let oe=U+re.index;return!K.some((de)=>oe>=de.start&&oe<de.end)})}function fl(G){return G.flatMap((U)=>{if(U.kind==="command")return[...U.redirections.flatMap((j)=>j.heredoc?[j.heredoc.bodySpan]:[]),...U.nested.flatMap((j)=>fl(j.nodes))];return U.kind==="group"||U.kind==="function"?fl(U.body.nodes):[]})}var gC=Object.freeze({code:"unsupported-backtick-escape",message:"a backslash escape inside backticks changes the command the shell runs and cannot be analyzed"});function Gd(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(mC);if(we.quoted&&we.substitutions.length>0||we.continued)Se.push(Fd);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&&pl(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=Wd(G,Se);if(We){K.push(Se);let mt=gl(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 zd(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 hC(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=yC(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 yC(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 $d(G,U,j,K,re){let oe=zd(G,U,j);return{text:K+G.slice(U,oe),provenance:qo(re,"variable"),next:oe}}function bC(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=gl(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=zd(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 CC(G,U,j){return U+1>=j||Ko(G[U+1]??"")||rs(G,U+1)!==null}var SC=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),vC=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function EC(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=RC(G,U);if(j===void 0||j===null)return!1;U=j}return!1}function RC(G,U){let j=G[U]?.text.toLowerCase();if(j==="command")return xC(G,U);if(j==="env")return _C(G,U);if(j==="sudo")return wC(G,U);return}function xC(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 _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("-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 wC(G,U){for(let j=U+1;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return j+1;if(vC.has(K)){if(G[j+1]===void 0)return null;j++;continue}if(K.startsWith("-"))continue;return j}return G.length}function Bd(G,U,j,K){if(G.provenance!=="literal"||!G.raw.includes("{"))return;let re=Ud(G.raw,U,j,K,!0);if(!re)return;if("limited"in re)return{limited:!0};let oe=re.values.map((de)=>Hd(de,j));if(oe.some((de)=>de===null))return{limited:!0};return{words:[...new Set(oe.filter((de)=>de!==null&&de!==""))]}}function PC(G,U,j,K,re){if(U.provenance!=="literal"||!U.raw.includes("{"))return;let oe=Ud(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)=>Hd(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 Ud(G,U,j,K,re){let oe=[G],de=G.length,Se=0;while(!0){let we=oe.findIndex((pt)=>Od(pt,re));if(we===-1)break;if(++Se>j)return{limited:"expansions"};let We=oe[we]??"",mt=Od(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,...AC(We,mt)),de+=ft-We.length}return Se===0?void 0:{values:oe}}function Od(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&&IC(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:TC(G,K)}}function AC(G,U){return U.alternatives.map((j)=>`${G.slice(0,U.start)}${j}${G.slice(U.end)}`)}function TC(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 IC(G){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(G)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(G)}function Hd(G,U){let j=`x${G}`,K=ml(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 kC(G,U,j,K){return pn({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 ul(G){return G.wordsUsed++,G.wordsUsed<=G.maxWords}function OC(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 MC(G){return G.map((U)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${U.delimiter} was not found`}))}function jd(G){return G?.kind==="command"||G?.kind==="group"||G?.kind==="function"}function Md(G,U){let j=G.at(-1);if(j?.kind!=="connector"||!Dd.has(j.operator))return;U.push({code:"missing-command-after-connector",message:`connector ${j.operator} requires a following command`})}function Vd(G){return G?.provenance==="literal"&&!G.quoted&&G.raw===G.text&&iC.has(G.text)}function dl(G,U){let j=G.at(-1);if(!jd(j))return;if(j?.kind==="command"&&Vd(j.words[0]))return;U.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function DC(G,U,j){return U===j||/[\s;&|()]/u.test(G[U-1]??"")}var Kd=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),NC=new Set(["gc","cat","type","cp","mv","rm"]),Yd=["-rec","-for","-path","-literalpath","-whatif"],LC=/^\$env:\w/i,WC=/^(?:\$\{?\w+\}?|~)\\./;function Zd(G,U){let j=G.toLowerCase().replaceAll("`","");if(![...Kd].some((re)=>j.includes(re))&&!(j.includes("rm")&&Yd.some((re)=>j.includes(re)))&&!j.includes("<#")&&!FC(j))return!1;let K=Cl(G,U);if(Xd(K))return!1;return K.issues.some((re)=>re.code==="unclosed-block-comment"||re.code==="comment-depth-limit")||bl(K).some(GC)}function Xd(G){return G.nodes.some((U)=>{if(U.kind==="group")return Xd(U.body);if(U.kind!=="command")return!1;return U.redirections.some((j)=>j.operator==="<<")})}function FC(G){if(G.includes("$env:"))return!0;return G.includes("\\")&&(G.includes("$")||G.includes("~"))}function GC(G){let U=G[0]==="&"||G[0]==="."?1:0,j=G[U]?.toLowerCase();if(j&&Kd.has(j))return!0;let K=G.slice(U+1);if(j&&NC.has(j)&&K.some(zC))return!0;if(j!=="rm")return!1;return K.some((re)=>{let oe=re.toLowerCase().split(":",1)[0]??"";return Yd.some((de)=>oe.startsWith(de))})}function zC(G){return LC.test(G)||WC.test(G)}function Cl(G,U){let j={start:0,end:G.length};if(G.length>U.maxInputLength)return pn({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=Sl(G,0,G.length,U,0);return pn({kind:"program",dialect:"powershell",source:G,span:j,status:jC(K.issues,K.limited),issues:K.issues,nodes:K.nodes})}function Sl(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=HC(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(hl(G,ft,Ct)),ft=Ct;continue}ft++;continue}let yt=em(G,ft);if(yt){gt(),de.push(hl(G,ft,ft+yt.length)),ft+=yt.length;continue}if(pt==="{"){if(gt(),re>=K.maxDepth)return Se.push(Qd(K.maxDepth)),{nodes:de,issues:Se,next:j,closed:!1,words:We,limited:!0};let Ct=Sl(G,ft+1,j,K,re+1,!0),vt=Ct.closed?Ct.next-1:Ct.next,St=pn({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(hl(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?qd(G,vt,j,K,re):void 0,Et=St?.next??Ct;if(we.redirections.push(Object.freeze({kind:"redirection",operator:G.slice(ft,Ct),span:Object.freeze({start:ft,end:Et}),...St?{target:St.word}:{}})),St)Se.push(...St.issues),we.nested.push(...St.nested),We+=St.words,mt||=St.limited;we.end=Et,ft=Et;continue}if(pt===","){we.start=we.start===-1?ft:we.start,we.words.push(al({text:",",raw:",",span:{start:ft,end:ft+1},provenance:"literal",quoted:!1})),we.end=++ft;continue}let bt=qd(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 qd(G,U,j,K,re){let oe="",de="literal",Se=!1,we=[],We=[],mt=0,gt=!1,ft=(ht)=>{let yt=$C(G,ht,j,K,re);return oe+=G.slice(ht,yt.next),We.push(yt.program),we.push(...yt.program.issues),mt+=yl(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)||em(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:BC(G,U,pt)),next:pt,issues:we,nested:We,words:mt,limited:gt}}function $C(G,U,j,K,re){let oe=Jd(G,U+2,j),de=oe===-1?j:oe,Se=oe===-1?j:oe+1;if(re>=K.maxDepth)return{program:pn({kind:"program",dialect:"powershell",source:G.slice(U+2,de),span:{start:U+2,end:de},status:"limited",issues:[Qd(K.maxDepth)],nodes:[]}),next:Se};let we=Sl(G,U+2,de,K,re+1),We=oe===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:pn({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 Jd(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 yl(G){let U=0;for(let j of G.nodes){if(j.kind==="group")U+=yl(j.body);if(j.kind==="command"){U+=j.words.length;for(let K of j.nested)U+=yl(K)}}return U}function BC(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=Jd(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=UC(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 UC(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 Qd(G){return{code:"depth-limit",message:`command structure exceeds parser limit ${G}`}}function bl(G){return G.nodes.flatMap((U)=>{if(U.kind==="group")return bl(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(bl)]})}function em(G,U){for(let j of["&&","||",";","|"])if(G.startsWith(j,U))return j;return null}function HC(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 jC(G,U){if(U)return"limited";if(G.some((j)=>j.code==="unclosed-block-comment"))return"invalid";return G.length>0?"partial":"complete"}function hl(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"&&Zd(G.slice(0,j.maxInputLength),j))return Cl(G,j);return Nd(G,j)}function t(G){return G.provenance==="command-substitution"?G.raw:G.text}function ne(G,U){return G==="posix"?U:qt(U.map((j)=>j.text))}function ro(G,U){return G&&G.provenance!=="unknown"?G.provenance==="literal":!/[$`*?[\]]/.test(U)}function qt(G){return G.map((U)=>({kind:"word",text:U,raw:U,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function vl(G,U){return{value:G,work:U}}function Rt(G,U){if(G.work)G.work.units=Math.min(Number.MAX_SAFE_INTEGER,G.work.units+1);return G.value[U]}function Yt(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 xn(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 jt(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 El(G){return G===`
|
|
25
|
-
`||G==="\r"||G==="\u2028"||G==="\u2029"}function Vt(G,U,j){if(U+j.length>Yt(G))return!1;for(let K=0;K<j.length;K++)if(Rt(G,U+K)!==j[K])return!1;return!0}function Xn(G,U,j){return!Ir(Rt(G,U-1))&&Vt(G,U,j)&&!Ir(Rt(G,U+j.length))}function Jn(G,U){return Ir(Rt(G,U-1))!==Ir(Rt(G,U))}function on(G){return G===`
|
|
26
|
-
`||G===";"||G==="&"||G==="|"}function oo(G){return G==="|"||G===";"}function ss(G,U,j){let K=vl(G,j);if(U==="rm")return VC(K);if(U==="dd")return KC(K);return sm(K,!0)}function as(G,U,j){let K=vl(G,j);if(U==="rm")return YC(K);if(U==="reset-hard")return om(K,"--ha","rd");if(U==="reset-merge")return om(K,"--me","rge");if(U==="clean")return QC(K);if(U==="checkout")return tS(K);if(U==="push-force")return nS(K);if(U==="push-refspec")return rS(K);if(U==="push-delete")return oS(K);if(U==="branch")return iS(K);if(U==="tag")return lS(K);if(U==="restore")return cS(K);return sm(K,!1)}function VC(G){let U=!1,j=!1,K=!1,re=-1;for(let oe=0;oe<=Yt(G);oe++){let de=Rt(G,oe);if(!U){let we=Rt(G,oe+2);if(Xn(G,oe,"rm")&&jt(we)&&we!==`
|
|
27
|
-
`)U=!0,oe++;continue}let Se=qC(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===Yt(G)){if(re>=0){let we=tm(G,re,oe);j||=we.recursive,K||=we.force}if(j&&K)return!0;U=!1,j=!1,K=!1,re=-1;continue}if(jt(de)){if(re<0)continue;if(Vt(G,re,"--")&&oe-re===2){U=!1,j=!1,K=!1,re=-1;continue}let we=tm(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 qC(G,U){if(Rt(G,U)!=="\\"||Rt(G,U-1)==="\\")return-1;if(Vt(G,U,String.raw`\n`))return U+2;if(Vt(G,U,String.raw`\x0a`)||Vt(G,U,String.raw`\x0A`))return U+5;if(Vt(G,U,String.raw`\u000a`)||Vt(G,U,String.raw`\u000A`))return U+7;return Vt(G,U,String.raw`\012`)?U+4:-1}function tm(G,U,j){if(nm(G,U,j,"recursive"))return{recursive:!0,force:!1};if(nm(G,U,j,"force"))return{recursive:!1,force:!0};if(Rt(G,U)!=="-"||Rt(G,U+1)==="-")return{recursive:!1,force:!1};let K=!1,re=!1;for(let oe=U+1;oe<j;oe++){let de=Rt(G,oe);K||=de==="r"||de==="R",re||=de==="f"||de==="F"}return{recursive:K,force:re}}function nm(G,U,j,K){let re=j-U-2;if(re<1||re>K.length||!Vt(G,U,"--"))return!1;for(let oe=0;oe<re;oe++)if(Rt(G,U+oe+2)!==K[oe])return!1;return!0}function KC(G){let U=!1;for(let j=0;j<Yt(G);j++){if(on(Rt(G,j))){U=!1;continue}if(Xn(G,j,"dd")){U=!0,j++;continue}if(!U||!Xn(G,j,"of")||!Vt(G,j,"of=/dev/"))continue;let K=j+8;if(K<Yt(G)&&!jt(Rt(G,K))&&Rt(G,K)!=="'"&&Rt(G,K)!=='"')return!0}return!1}function YC(G){let U=!1,j=!1,K=!1;for(let re=0;re<=Yt(G);){let oe=Rt(G,re);if(re===Yt(G)||on(oe)){U=!1,j=!1,K=!1,re++;continue}let de=XC(G,re);if(de>=0){if(ZC(G,de))return!0;let Se=de,we=!1;while(jt(Rt(G,Se)))we||=Rt(G,Se)===`
|
|
29
|
-
`,Se++;if(we)j=!1,K=!1;U=!0,re=Se;continue}if(!U){re++;continue}if(Vt(G,re,"--")&&(re===0||jt(Rt(G,re-1)))&&(!Rt(G,re+2)||jt(Rt(G,re+2))||on(Rt(G,re+2)))){U=!1,j=!1,K=!1,re+=2;continue}if(j||=Vt(G,re,"--recursive")&&Jn(G,re+11)||Rl(G,re,"recursive"),K||=Vt(G,re,"--force")&&Jn(G,re+7)||Rl(G,re,"force"),j&&K)return!0;re++}return!1}function Rl(G,U,j){if(!Vt(G,U,"--"))return!1;let K=0;while(K<=j.length){let re=Rt(G,U+K+2);if(!re||jt(re)||on(re))break;if(re!==j[K])return!1;K++}return K>0&&Jn(G,U+K+2)}function ZC(G,U){let j=U,K=!1,re=!1;while(j<Yt(G)){while(jt(Rt(G,j)))j++;let oe=j;while(j<Yt(G)&&!jt(Rt(G,j)))j++;if(Rt(G,oe)!=="-"||j-oe===2&&Vt(G,oe,"--"))return!1;let de=rm(G,oe,"recursive"),Se=rm(G,oe,"force");if(K&&Se||re&&de)return!0;if(K||=de,re||=Se,Rt(G,oe+1)==="-")continue;let we=JC(G,oe,j);if(we.combined||K&&we.forceAtBoundary||re&&we.recursiveAtBoundary)return!0;K||=we.recursive,re||=we.force}return!1}function rm(G,U,j){return Vt(G,U,`--${j}`)&&Jn(G,U+j.length+2)||Rl(G,U,j)}function XC(G,U){if(U>0&&Ir(Rt(G,U-1)))return-1;let j=U;if(Rt(G,j)==="\\")j++;if(Rt(G,j)!=="r")return-1;if(j++,Rt(G,j)==="\\")j++;if(Rt(G,j)!=="m"||!jt(Rt(G,j+1)))return-1;return j+1}function JC(G,U,j){let K=!1,re=!1,oe=!1,de=!1,Se=!1;if(Rt(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=Rt(G,We)??"",gt=(mt==="r"||mt==="f")&&Jn(G,We+1);K||=mt==="r",re||=mt==="f",oe||=mt==="r"&>,de||=mt==="f"&>,Se||=(we==="r"&&mt==="f"||we==="f"&&mt==="r")&>,we=mt}return{recursive:K,force:re,recursiveAtBoundary:oe,forceAtBoundary:de,combined:Se}}function om(G,U,j){return Qo(G,"reset",oo,!0,(K)=>Rt(G,K)==="-"&&io(G,K,U,j)?!0:K)}function QC(G){return Qo(G,"clean",oo,!0,(U)=>{if(Rt(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(Rt(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(!jt(Rt(G,K)))return{commandEnd:-1,next:K};while(jt(Rt(G,K)))K++;while(K<Yt(G)){if(on(Rt(G,K)))return{commandEnd:-1,next:K};let re=Jo(G,K,on);if(Xn(G,K,j))return{commandEnd:K+j.length,next:re};if(Rt(G,K)!=="-")return{commandEnd:-1,next:re};let oe=re-K===2&&Vt(G,K,"--"),de=eS(G,K,re);K=re;while(jt(Rt(G,K)))K++;if(oe)return{commandEnd:Xn(G,K,j)?K+j.length:-1,next:Jo(G,K,on)};if(!de)continue;if(K>=Yt(G)||on(Rt(G,K)))return{commandEnd:-1,next:K};K=Jo(G,K,on);while(jt(Rt(G,K)))K++}return{commandEnd:-1,next:K}}function eS(G,U,j){for(let K of vn)if(j-U===K.length&&Vt(G,U,K))return!0;return!1}function tS(G){return im(G,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function nS(G){return Qo(G,"push",oo,!0,(U)=>{if(Rt(G,U)!=="-")return U;if(Rt(G,U+1)==="f"&&!Ir(Rt(G,U+2))&&!Vt(G,U+2,"-with-lease"))return!0;let j=am(G,U,"--fo","rce");if(j>=0&&!Vt(G,j,"-with-lease"))return!0;return U})}function rS(G){return Qo(G,"push",on,!1,(U)=>{if(jt(Rt(G,U))&&Rt(G,U+1)==="+"&&U+2<Yt(G)&&!on(Rt(G,U+2))&&!jt(Rt(G,U+2)))return!0;if(Rt(G,U)===":"&&Rt(G,U+1)==="+")return!0;return U})}function oS(G){return Qo(G,"push",on,!1,(U)=>{if(Rt(G,U)==="-"&&io(G,U,"--de","lete"))return!0;if(jt(Rt(G,U))&&Rt(G,U+1)===":"&&U+2<Yt(G)&&!jt(Rt(G,U+2))&&!on(Rt(G,U+2)))return!0;return U})}function iS(G){let U=!1,j=!1,K=!1;for(let re=0;re<=Yt(G);re++){if(re===Yt(G)||on(Rt(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||Rt(G,re)!=="-")continue;let oe=Jo(G,re,on),de=sS(G,re,oe);if(j||=de.deletion,K||=de.force,j&&K)return!0;re=oe-1}return!1}function sS(G,U,j){let K=!1,re=!1;for(let oe=U;oe<j;oe++){if(Rt(G,oe)!=="-")continue;if(io(G,oe,"--de","lete"))K=!0;if(io(G,oe,"--fo","rce"))re=!0;if(Rt(G,oe+1)==="-")continue;let de=oe+1,Se=!1,we=!1,We=!1;while(de<j&&aS(Rt(G,de))){let mt=Rt(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 aS(G){if(!G)return!1;let U=G.charCodeAt(0);return U>=65&&U<=90||U>=97&&U<=122}function lS(G){return im(G,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function im(G,U){let j=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let K=0;K<Yt(G);K++){let re=Rt(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==="$"&&Rt(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(jt(re))oe.shortActive=!1,oe.hasShortFlag=!1;if(!oe.outerActive){let Se=ls(G,K,U.command);if(Se){oe.outerActive=Se.commandEnd>=0&&jt(Rt(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(Rt(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<Yt(G);de++){let Se=Rt(G,de),we=j(Se);if(!oe&&!we){let We=ls(G,de,U);if(We){oe=We.commandEnd>=0&&(!K||jt(Rt(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(Rt(G,mt)))oe=!1;de=We}if(we)oe=!1}return!1}function cS(G){let U=!1;for(let j=0;j<Yt(G);j++){if(El(Rt(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&&Rt(G,j)==="-"&&Rt(G,j+1)==="-"&&(Vt(G,j+2,"staged")||Vt(G,j+2,"help")))U=!1}return U}function sm(G,U){let j=!1;for(let K=0;K<Yt(G);K++){let re=Rt(G,K),oe=U?El(re):on(re);if(j&&jt(re)&&Rt(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<Yt(G)&&!jt(Rt(G,K))&&!j(Rt(G,K)))K++;return K}function am(G,U,j,K){if(!Vt(G,U,j))return-1;let re=U+j.length;for(let oe=0;oe<K.length&&Rt(G,re)===K[oe];oe++)re++;return Jn(G,re)?re:-1}function io(G,U,j,K){return am(G,U,j,K)>=0}function kn(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)xn(U,Se);if((de.regex?.test(Se)??!1)||de.scan&&as(Se,de.scan,U))return xt("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 uS=/^[A-Za-z_][A-Za-z0-9_]*=/;function cm(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 um(U.nodes,K,oe)}function um(G,U,j){return G.every((K)=>{if(K.kind==="connector")return!0;if(K.kind==="group"||K.kind==="function")return um(K.body.nodes,U,j);if(K.kind==="unknown")return!j.loose.test(K.source);return dS(K,U,j)})}function dS(G,U,j){if(G.nested.some((re)=>j.loose.test(re.source)))return!1;let K=G.words.findIndex((re)=>!uS.test(re.text));return G.words.every((re,oe)=>re===U||lm(re.raw,j.anchored,oe!==K))&&G.redirections.every((re)=>(!re.heredoc||re.heredoc.quotedDelimiter||!j.loose.test(re.heredoc.body))&&(!re.target||lm(re.target.raw,j.anchored,!0)))}function lm(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 mS,resolve as dm}from"node:path";function ei(G,U,j,K){let re=mS(G)?dm(G):U?dm(U,G):void 0;if(!re)return;try{return Nt(re,j,K)}catch{return re}}function mm(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.",_l=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),fS=new Set(["-p","--print"]),pS=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),gS=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"])]]),hS=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),yS=new Map([["python",new Set(["m"])]]),bS=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"])]]),CS=new Set(["always","default","never"]),SS=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),vS=/\\\r?\n/g,ES=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 fm(G){return us(G).code}function cs(G){return us(G).sources}function pm(G){return ES.get(Pl(G))??[]}function us(G){let U=Pl(G[0]??"");if(!_l.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 Wn(U,j,K,re,G[oe+1]===void 0?void 0:oe+1,G[oe+1]);if(de===""||de==="-"||!de.startsWith("-"))return Wn(U,j,K,re,oe,de);if(U==="node"&&fS.has(de)){let gt=G[oe+1];if(gt===void 0)return Wn(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(xS(U,de)){let gt=G[oe+1];if(gt===void 0)return Wn(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 Wn(U,j,K,re);oe++;continue}let Se=/^--eval=(.*)$/s.exec(de);if(_S(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=RS(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,Wn(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 Wn(U,j,K,re);if(bS.get(U)?.has(de)){let gt=G[oe+1];if(gt===void 0||gt.startsWith("-")&&!(U==="ruby"&&SS.has(de))||U==="python"&&!CS.has(gt))return Wn(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(yS.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 Wn(U,j,K,re)}if(pS.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(gS.get(U)?.has(ft)){if(gt+1===de.length)oe++;break}if(hS.get(U)?.has(ft)&>+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 Wn(U,j,K,re);if(We)oe++}return Wn(U,j,K,re,void 0,void 0,!0)}function Wn(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 RS(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 wl(G,U){return Pl(G)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(U)}function Pl(G){let U=kt(G).toLowerCase();return Wi.test(U)?"python":U}function xS(G,U){return _l.get(G)?.has(U)??!1}function _S(G){return _l.get(G)?.has("--eval")??!1}function ni(G,U,j=!1){let K=AS(G,U);if(!xl(K,U))return!1;xn(U,K);let re=PS(K);if(xl(re,U))return!0;if(xn(U,re),!gm.test(re))return!1;return!j||wS(K,U)}function wS(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)=>gm.test(we[1]??"")).map((we)=>{let We=we.index+we[0].length;return{start:We,end:ds(oe,We)}});if(de.some((we)=>Al(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)&&xl(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 Al(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 gm=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function PS(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 xl(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(xn(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(xn(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)=>(xn(U,G),j.some((re)=>as(re,K))))}function AS(G,U){return xn(U,G),G.replace(vS,"")}import{lstatSync as xv,readdirSync as _v}from"node:fs";import{basename as wv,isAbsolute as Bm,join as Pv,relative as Um}from"node:path";import{isAbsolute as Em,parse as FS}from"node:path";import{dirname as TS,isAbsolute as IS,parse as kS,sep as OS}from"node:path";function ur(G,U,j){if(sr(U))throw Error("Unsupported Windows namespace path");let K=IS(U)?kS(U).root:"",re=K||G;for(let oe of DS(K?U.slice(K.length):U)){if(oe===""||oe===".")continue;if(oe===".."){re=TS(re);continue}let de=MS(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 MS(G,U){return G.endsWith("/")||G.endsWith("\\")?`${G}${U}`:`${G}${OS}${U}`}function DS(G){let U=process.platform==="win32"?/[\\/]+/:/\/+/;return G.split(U)}var Tl=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],NS=new Set(Tl),LS=1024,hm=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),ym=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),WS=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ms(G){return NS.has(G)}function Il(G){return ms(G)||hm.has(G)||ym.has(G)||No(G)}function Qn(G,U,j){return j?.has(G)?j.get(G):U.get(G)}function bm(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<=LS?{state:"valid",count:K}:{state:"invalid"}}function fs(G,U,j){let re=G.match(WS)?.[1];if(!re||!Il(re))return null;let oe=G.indexOf("=");return{name:re,value:`${Qn(re,U,j)??""}${G.slice(oe+1)}`}}function Cm(G){return vm(G,ym)}function Sm(G){return vm(G,hm)}function vm(G,U){if(!G)return!1;for(let j of G.keys())if(U.has(j))return!0;return!1}var xm=/^[A-Za-z_][A-Za-z0-9_]*=/;function On(G){if(!xm.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=On(t(K));if(!re)break;U.set(re.name,re.value),j++}return{words:G.slice(j),envAssignments:U}}function _m(G){let U=Mt(G);return G.includes("=")||U==="sudo"||U==="env"||U==="command"||U==="builtin"}function kr(G,U,j,K){if(!_m(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=Rm(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("=")&&!zS(oe)){let yt=$S(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=US(oe,U.paths,We);if(oe=yt.words,yt.cwd!==void 0)We=yt.cwd}if(ht==="env"){let yt=VS(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=qS(oe);if(ht==="builtin")oe=oe.slice(Fn(oe,1)==="--"?2:1);if(Rm(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:GS(mt.words,re)}}function GS(G,U){return G.some((j)=>!U.has(j))}function Rm(G){return G.map(t).join(" ")}function ao(G){let U=G[0];return U?t(U):""}function Fn(G,U){let j=G[U];return j?t(j):void 0}function zS(G){return xm.test(ao(G))}function $S(G,U,j){if(!G.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${U.get("TMPDIR")??j.get("TMPDIR")??""}${G.slice(8)}`}}var BS=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function US(G,U,j){let K=1,re=j;while(K<G.length){let oe=Fn(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=Fn(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(BS.has(oe)){K+=2;continue}K++}return{words:G.slice(K),cwd:re}}var HS=new Set(["-i","-0","--null"]),jS=new Set(["-u","--unset","-C","--chdir","-P"]);function VS(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=Fn(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(HS.has(We)){Se++;continue}if(We==="-u"||We==="--unset"){let gt=Fn(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:Fn(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(jS.has(We)){if(We==="-C"||We==="--chdir"){let gt=Fn(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(!On(We))break;while(Se<G.length){let gt=On(Fn(G,Se)??"");if(!gt)break;re.set(gt.name,gt.value),Se++}if(Fn(G,Se)==="--")Se++;return we(Se)}return we(Se)}function ri(G,U,j){if(U==="")return null;if(!G&&!Em(U))return null;let K=Em(U)?FS(U).root:j.realpath(G??"/");if(K===null)return null;try{return ur(K,U,j)}catch{return null}}function qS(G){if(Fn(G,1)==="-v")return[...qt(["type"]),...G.slice(2)];let U=1;while(U<G.length){let j=Fn(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 KS=/['"\\$`{}#]/;function ps(G,U){if(G.some((K)=>KS.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 YS(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(YS);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(!_m(G[0]??""))return{tokens:[...G],envAssignments:new Map,cwd:j};let re=kr(qt(G),U,j,K);return{tokens:re.words.map(t),envAssignments:re.envAssignments,cwd:re.cwd,envSplitValues:re.envSplitValues}}var Ml=Symbol("adopt-as-operand"),ZS=new Set(["env","sudo","command","builtin"]),XS=new Set(["&&","||","|&","|","&",";"]),JS=new Set(["<<","<<<",">|"]),wm=new Set(["|","|&"]),QS=/[*@#?$!_-]/,ev=/^\w+(?::\w+)*/,tv=Object.freeze([]),oi=Object.freeze({kind:"scope",edge:"enter"}),ii=Object.freeze({kind:"scope",edge:"exit"}),nv=Object.freeze([]),rv=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"]),ov=256,km=new WeakMap;function Om(G,U){let j=U.status==="complete"?new Set(Ol(U)):new Set,K=av(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 km.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=Mm(G),ft=gt.findLastIndex((ht)=>ht.kind==="operator"&&wm.has(ht.operator)),pt=ft!==-1&>.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=iv(Se,de,j,K),We=Se.length>0&&wm.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===Ml){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 Mm(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 gn(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:gn(oe,U);return Se?gn(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 iv(G,U,j,K){let re=ai(G)?new Map([...U.variables,...sv(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:un(gn(de,re),U.cwd,j,K),variables:re,previous:U.cwd}}function sv(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],gn(re,U)]]:[]})}function Mm(G){return km.get(G)??tv}function av(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=nv){return Object.freeze({status:G,source:U,program:j,assignmentFallbacks:Object.freeze(K)})}function Or(G,U){return G.nodes.flatMap((j,K)=>lv(j,G,K,U)).sort((j,K)=>j.start-K.start).flatMap((j)=>[...j.events])}function lv(G,U,j,K){if(G.kind==="connector")return[{start:G.span.start,events:[Gn(fv(G.operator))]}];if(G.kind==="unknown")return[{start:G.span.start,events:[Gn(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,Gn("("),...Or(G.body,Se),...de?[Gn(")")]:[],ii]}]}let re=yv(G,K.functions);if(re){if(K.depth>=cr.maxDepth||++K.flags.expansions>ov)return K.flags.limited=!0,[];return[{start:G.span.start,events:[...Pm(G,K),ys(";"),...Or(re,{...K,depth:K.depth+1}),ys(";")]},...Am(G,U,j,K)]}return[{start:G.span.start,events:Pm(G,K)},...Am(G,U,j,K)]}function Pm(G,U){return[...G.words.map((j)=>({start:j.span.start,events:Nm(j,G,U,!1)})),...G.redirections.map((j)=>({start:j.span.start,events:cv(j,G,U)}))].sort((j,K)=>j.start-K.start).flatMap((j)=>j.events)}function cv(G,U,j){let K=G.operator==="<<-"?"<<":G.operator,re=G.target?Nm(G.target,U,j,!0):[],oe=re[0],de=oe?.kind==="word"?oe.text:void 0;return[...G.fd===void 0?[]:[Dl(String(G.fd))],Object.freeze({kind:"redirection",operator:K,...G.fd===void 0?{}:{fd:G.fd},role:pv(K),targetOrder:JS.has(K)?"legacy-segment":"immediate",...de===void 0?{}:{target:de},...G.heredoc&&j.suppressed.has(G.heredoc.bodySpan)?{body:G.heredoc.body,consumer:Wm(U)}:{}}),...de===void 0?re:re.slice(1)]}function Am(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=[Dl(de.delimiter),.../[\r\n]/.test(K.source[de.terminatorSpan.end]??"")?[Gn(";")]:[]];if(K.suppressed.has(de.bodySpan))return[{start:de.bodySpan.start,events:Se}];return[{start:de.bodySpan.start,events:[...Dm(K.source.slice(de.bodySpan.start,de.bodySpan.end),K),...Se]}]}),...re.some((oe)=>!oe.heredoc&&oe.target)?uv(U,j,K):[]]}function uv(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:Dm(j.source.slice(K.span.end,G.span.end),j)}]}function Dm(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 Nm(G,U,j,K){let re=[],oe={single:!1,double:!1},de="",Se=!1,we=()=>{let We=Se&&!K?Gn("glob"):de!==""||G.quoted&&re.length===0?Dl(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 kl(We.raw,oe,j.flags,j.powershell)){if(typeof pt==="string"){we(),re.push(Gn(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+=kl(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("<(")?Gn("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),oi,...gt,...We.raw.endsWith(")")?[Gn(")")]:[],ii);continue}let ft=We.raw.startsWith("$((")?2:1;de+="${}",we(),re.push(...Array.from({length:ft},()=>Gn("(")),...ft===1?[oi]:[],...gt,...We.raw.endsWith(")".repeat(ft))?Array.from({length:ft},()=>Gn(")")):[],...ft===1?[ii]:[])}return we(),re}function kl(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=Tm(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=Tm(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 Tm(G,U,j,K,re){let oe=G[U+1];if(oe==="{"){let Se=re?mv(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 dv(we,j,K,re),{text:we,next:Se+1}}if(oe!==void 0&&QS.test(oe))return{text:`\${${oe}}`,next:U+2};let de=(re?ev:/^\w*/).exec(G.slice(U+1))?.[0]??"";return{text:`\${${de}}`,next:U+1+de.length}}function dv(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=kl(de.slice(Se.length),{...U},j,K);j.assignmentFallbacks.push(...we.flatMap((We)=>typeof We==="string"||!We.text?[]:[We.text]))}function mv(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 fv(G){return/^[\r\n]+$/.test(G)?";":G}function Gn(G){return Object.freeze({kind:"operator",operator:G,boundary:XS.has(G)})}function ys(G){return Object.freeze({kind:"operator",operator:G,boundary:!0})}function Dl(G){return Object.freeze({kind:"word",text:G})}function pv(G){if(G==="<<"||G==="<<<")return"here-data";if(G==="<"||G==="<&")return"file-read";return"file-write"}function lo(G){return rv.has(G)||/^python\d/.test(G)}var gv=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 Lm(G,U){let j=U[0];if(j===void 0||!j.startsWith("-"))return U;let K=gv.get(G)?.has(j)??!1;return Lm(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(!ZS.has(U))return[...G];return bs(Lm(U,G.slice(1)))}function Wm(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 hv(G){let U=Wm(G)[0];if(U===void 0)return!1;let j=kt(U).toLowerCase();return lo(j)&&!si.has(j)}function Ol(G){return G.nodes.flatMap((U,j)=>{if(U.kind==="group"||U.kind==="function")return Ol(U.body);if(U.kind!=="command")return[];let K=U.nested.flatMap((Se)=>Ol(Se)),re=U.redirections.flatMap((Se)=>Se.heredoc?.quotedDelimiter?[Se.heredoc.bodySpan]:[]);if(hv(U))return[...K,...re];let oe=G.nodes[j+1];if(oe?.kind==="connector"&&(oe.operator==="|"||oe.operator==="|&")||!Cv(U))return K;return[...K,...re]})}function yv(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 bv(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 Cv(G){return(fr(G.words[0],"cat")||fr(G.words[0],"tee")||bv(G))&&!G.words.some(Im)&&!G.redirections.some((j)=>Im(j.target))}function Im(G){return G?.parts.some((U)=>U.provenance==="command-substitution"&&U.raw.startsWith(">("))??!1}var Fm=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Gm=new Set([...Fm,"glob"]),Sv=new Set([...Gm,"folder","pattern","patterns"]);class b extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function zm(G){let U=vv(),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:Ev(G),store:U}}function hn(G,U){return G.commands.find((j)=>j.usages.includes(U))}function er(G,U){if(!G.includes("$"))return G;return pa(G,U)}function vv(){let G=new Map,U=new WeakMap,j=(re,oe)=>{let de=`${oe}\x00${re}`,Se=G.get(de);if(Se)return Se;let we=y(re,oe);return G.set(de,we),we};return{getShellSyntax:(re,oe)=>{if(oe&&oe.source!==re)throw TypeError("Shell syntax source does not match command program source.");let de=oe??j(re,"posix"),Se=U.get(de);if(Se)return Se;let we=de.status==="limited"?{status:"structural-limit",source:re,program:de,assignmentFallbacks:[]}:Om(re,de);return U.set(de,we),we},getCommandProgram:j}}function Ev(G){let U=G.route.kind==="grep"?Gm:G.route.kind==="glob"?Sv:Fm;return[...yu(G.input,U),...G.route.kind==="patch"||typeof G.input==="string"?Su(G.input):[]]}var Rv=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(gn(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&&Rv.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 Hm(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)=>$m(we,re,U,j,K,U.entries));return Se?{target:Se}:null}if(G.invocation.route.kind!=="command")return null;let oe=hn(G,"input-candidate");if(!oe)return null;let de=co(oe.shell,re,j,K,{findSegmentTarget:(Se,we)=>Mv(Se,we,U,j,K),isRedirectionTarget:(Se,we)=>$m(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(un(G,U,re,oe)),we=Se.replace(/(\/\.?\*+)+$/,"");if(we!==Se&&we!==""){if(Nl(we,j))return!0;let We=de||Se.slice(we.length).includes("/."),mt=(gt)=>We?Es(gt,we):Av(gt,we);if(j.markerFiles.some(mt))return!0;return K&&Ll(j).some(mt)}if(Nl(Se,j))return!0;return K&&Ll(j).some((We)=>Es(We,Se))}function Av(G,U){let j=Um(U,G);if(j===""||j.startsWith("..")||Bm(j))return!1;return!j.split(/[\\/]/)[0]?.startsWith(".")}function Tv(G,U,j,K,re){return Mr(G,U,j,!0,K,re)}function Iv(G,U,j,K,re){if(!j)return!1;return Nl(Rs(un(G,U,K,re)),j)}function $m(G,U,j,K,re,oe){let de=Rs(un(G,U,K,re));return oe.includes(de)||Vm(de,j)}function jm(G,U,j,K,re){if(!j)return!1;return j.hooksDirectories.some((oe)=>G.some((de)=>Es(oe,Rs(un(de,U,K,re)))))}function Nl(G,U){return U.entries.includes(G)||U.directories.includes(G)||Vm(G,U)}function Vm(G,U){return U.hooksDirectories.some((j)=>Es(G,j))}var kv=50000;function qm(G,U){let j=[...new Set(Ll(G))];if(j.some((re)=>U(wv(re))))return!0;let K=0;while(j.length>0){let re=j.pop()??"",oe=Ov(re);if(!oe)return!0;if(K+=oe.length,K>kv)return!0;if(oe.some((de)=>U(de.name)))return!0;j.push(...oe.filter((de)=>de.isDirectory()).map((de)=>Pv(re,de.name)))}return!1}function Ov(G){try{let U=xv(G,{throwIfNoEntry:!1});if(!U)return[];if(!U.isDirectory())return U.isSymbolicLink()?null:[];return _v(G,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function Ll(G){return[...G.entries,...G.directories,...G.hooksDirectories]}function Es(G,U){let j=Um(U,G);return j===""||!/^\.\.(?:[\\/]|$)/.test(j)&&!Bm(j)}function Rs(G){return process.platform==="win32"?G.toLowerCase():G}function Mv(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)=>Tv(gn(we,U.variables),U.cwd,j,K,re));if(Se)return Se;return de.destination&&Iv(gn(de.destination,U.variables),U.cwd,j,K,re)?de.destination:null}import{isAbsolute as Ps,normalize as $v,parse as Bv,posix as tf,resolve as Nr,sep as zl}from"node:path";import{isAbsolute as Dv,join as Km,normalize as Xm,parse as Nv,sep as Ym}from"node:path";var Lv=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],Wv=`
|
|
31
|
-
`;function li(G,U){if(Dr(G,U))return!0;if(!G.has("TMPDIR"))return!1;return!Wl(G.get("TMPDIR")??"",U)}function uo(G,U){if(G.has("TMPDIR"))return Wl(G.get("TMPDIR")??"",U);let j=Fl(G,U);if(j===void 0)return!0;return Wl(j,U)}function Fl(G,U){return Qm(G,U,"TMPDIR")}function Wl(G,U){if(!G)return!1;if(Gv(G))return!1;return mo(G,U)}function Dr(G,U){let j=Qm(G,U,"IFS");return j!==void 0&&j!==""&&j!==Wv}function mo(G,U){let j=xs(G,U.paths);if(j===null)return!1;return Jm(U).some((K)=>fo(j,K))}function ws(G,U){let j=xs(G,U.paths);if(j===null)return!1;return Jm(U).some((K)=>_s(K)===_s(j))}var Zm=new WeakMap;function Jm(G){let U=Zm.get(G);if(U)return U;let j=Fv(G);return Zm.set(G,j),j}function Fv(G){let U=Lv.map((K)=>xs(K,G.paths)??Xm(K)),j=xs(G.tmpdir,G.paths);if(!j)return U;if(process.platform==="win32")return[...U,j];if(process.platform==="darwin"&&zv(j))return[...U,j];return U}function Gv(G){return/[\s$`*?[]/.test(G)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(G)||/[+@!]\([^)]*\)/.test(G)}function Qm(G,U,j){return G.has(j)?G.get(j):U.env.get(j)}function zv(G){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(G)}function xs(G,U){try{let j=Xm(G);if(!Dv(j))return j;let K=Nv(j).root,re=j.slice(K.length).split(/[\\/]+/).filter(Boolean),oe=K;for(let de=0;de<re.length;de++){let Se=Km(oe,re[de]??"");if(U.entryKind(Se)==="missing")return Km(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(Ym)?K:`${K}${Ym}`;return j.startsWith(re)}function _s(G){return process.platform==="win32"?G.toLowerCase():G}var Uv=process.platform==="win32",ef=64,Hv=16384;function Lr(G,U,j,K){if(G.kind==="temp_target")return null;let re=K[G.kind];if(G.kind==="dynamic_target"&&!Jt(j,re.id,U.strict))return null;if(G.kind==="within_anchored_cwd"&&!Jt(j,re.id,U.paranoid))return null;return xt(re.id,re.reason)}function ci(G){let U=Bd(G,ef,ef,Hv);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:jv(G)}}function jv(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)=>Vv(G.raw,j.span.start-G.span.start))}function Vv(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 jn(G){let U=G.environment.home,j=G.environment.paths,K=G.budget??An();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:Jv(G.allowPaths,U,j,K),protectedGitMetadata:G.protectedGitMetadata,budget:K}}function _n(G,U,j={}){let K=j.targetIsLiteral??!1;if(!K&&U.tmpdirWordSplittingUnsafe&&!j.tmpdirWordSplittingProtected&&eE(G))return{kind:"outside_anchored_cwd"};let re=!K&&rf(G,U.posixShell);if(sr(G))return{kind:"outside_anchored_cwd"};if($l(G,K))return{kind:"root_or_home_target"};if(Kv(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(Yv(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(Qv(G,U,K))return{kind:"temp_target"};let oe=U.anchoredCwd;if(oe){if(!j.skipHomeCwd&&oE(oe,U.environment.home,U.environment.paths,U.budget))return{kind:"home_cwd_target"};if(!j.skipCwdSelf&&[U.resolvedCwd??oe,oe].some((de)=>iE(G,U.resolvedCwd??oe,U.environment.paths,U.budget,de)))return{kind:"cwd_self_target"};if(sE(G,oe,U.resolvedCwd??oe,re,K,U.environment.paths,U.budget))return{kind:"within_anchored_cwd"}}if(qv(G,U,re))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function qv(G,U,j){let K=G.trim();if(j||!U.resolvedCwd||!U.anchoredCwd||!K)return!1;if(Ps(K)||K.startsWith("~"))return!1;if(Bl(K))return!1;if(of(U.resolvedCwd,U.anchoredCwd,U.environment.paths,U.budget))return!1;return mo(Nr(U.resolvedCwd,K),U.environment)}function nf(G,U,j={}){let{containmentTarget:K,...re}=j;if(_n(G,U,re).kind!=="temp_target")return!1;let oe=G.trim();if(Xv(oe))return!1;if(ws(oe,U.environment))return!1;return![U.anchoredCwd,U.resolvedCwd].some((de)=>of(K??oe,de,U.environment.paths,U.budget))}function $l(G,U=!1){let j=G.trim(),K=tf.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 Kv(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=yn(Nt(oe,U.environment.paths,U.budget));if(de===Bv(de).root)return!0;return de===yn(Nt(U.environment.home,U.environment.paths,U.budget))}catch{return!1}}function yn(G){let U=$v(G);if(Uv){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 Yv(G,U,j,K,re,oe,de,Se){let we=G.trim();if(Bl(we))return!1;if(!K&&mo(we,Se))return!0;return(U||oe&&de)&&j&&!re&&Zv(we,j)}function Zv(G,U){return["$TMPDIR","${TMPDIR}"].some((j)=>{if(G===j)return!0;if(!G.startsWith(`${j}/`))return!1;return!rf(G.slice(j.length+1),U)})}function Xv(G){let U=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(G);if(!U)return!1;return tf.normalize(`/${U[1]??""}`)==="/"}function Bl(G){return G.split(/[\\/]+/).includes("..")}function Jv(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[yn(de)]}catch{return[]}})}function Qv(G,U,j){if(U.allowRoots.length===0)return!1;let K=G.trim();if(Bl(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=yn(Nt(de,U.environment.paths,U.budget));return U.allowRoots.some((we)=>Se===we||Se.startsWith(we.endsWith(zl)?we:`${we}${zl}`))}catch{return!1}}function eE(G){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(G)}function rf(G,U=!1){return G.includes("$")||G.includes("`")||tE(G)||U&&nE(G)}function tE(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 nE(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==="{"&&rE(G,j)||(K==="+"||K==="@"||K==="!")&&G[j+1]==="(")return!0}return!1}function rE(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 oE(G,U,j,K){try{return yn(Nt(G,j,K))===yn(Nt(U,j,K))}catch{try{return yn(G)===yn(U)}catch{return!1}}}function iE(G,U,j,K,re=U){if(re===U&&(G==="."||G==="./"||G===".\\"))return!0;try{return yn(Nt(Nr(U,G),j,K))===yn(Nt(re,j,K))}catch{try{return yn(Nr(U,G))===yn(re)}catch{return!1}}}function sE(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 Gl(G,U,oe,de)}catch{return!1}if(G.startsWith("./")||G.startsWith(".\\")||!G.includes("/")&&!G.includes("\\"))try{return Gl(Nr(Se,G),U,oe,de)}catch{return!1}if(G.startsWith("../"))return!1;try{return Gl(Nr(Se,G),U,oe,de)}catch{return!1}}function Gl(G,U,j,K){try{return sf(Nt(G,j,K),Nt(U,j,K))}catch{return!1}}function of(G,U,j,K){if(!U)return!1;try{return sf(Nt(U,j,K),Nt(G,j,K))}catch{return!0}}function sf(G,U){let j=yn(G),K=yn(U);return j.startsWith(`${K}${zl}`)||j===K}var aE=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),af="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",lE="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.",lf="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",cf="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",cE="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",uE="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",dE={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:cf},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:x},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:lf},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:cE},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:af},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:lE},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:af}};function uf(G,U,j){return mE(G.words.map((K)=>({kind:"word",text:K.text,dynamic:K.provenance!=="literal"})),U,jn({...j,allowPaths:j.policy?.destructiveCommandAllowPaths}),j.policy)}function mE(G,U,j,K){let re=G.filter((we)=>we.kind==="word"),oe=pE(re),de=re[oe];if(!de||!aE.has(RE(de.text)))return null;let Se=fE(re.slice(oe+1));if(Se.whatIfProtected)return null;if(Jt(K,"powershell.remove-item-pipeline-dynamic-target",j.strict)&&U&&(Se.targets.length===0||Se.recursive))return xt("powershell.remove-item-pipeline-dynamic-target",uE);for(let we of Se.targets)if(!sr(we.text)&&$l(ui(we.text)))return xt(Se.recursive&&Se.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",cf);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 xt("powershell.remove-item-git-metadata",x);if(!Se.recursive||!Se.force)return null;if(Jt(K,"powershell.remove-item-recursive-force-dynamic-target",j.strict)&&(Se.hasDynamicTarget||Se.targets.length===0))return xt("powershell.remove-item-recursive-force-dynamic-target",lf);for(let we of Se.targets){let We=Lr(_n(ui(we.text),j),j,K,dE);if(We)return We}return null}function fE(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(gE(we))continue;if(de){U.push(Ul(we)),oe=oe||we.dynamic;continue}if(we.text==="--"){de=!0;continue}let We=yE(we.text);if(!We){U.push(Ul(we)),oe=oe||we.dynamic;continue}if(bE(We.name)){let mt=We.value?hE(We.value,we):G[++Se];if(mt?.kind==="word"){U.push(Ul(mt)),oe=oe||mt.dynamic;continue}oe=!0;continue}if(CE(We.name)){j=!0;continue}if(SE(We.name)){K=!0;continue}if(vE(We.name))re=EE(We.value)}return{targets:U,recursive:j,force:K,whatIfProtected:re,hasDynamicTarget:oe}}function pE(G){let U=G[0];if(U?.kind==="word"&&U.text==="&"||U?.text===".")return G.length>1?1:0;return 0}function Ul(G){return{text:G.kind==="word"?G.text:"",dynamic:G.kind==="word"&&G.dynamic}}function gE(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 hE(G,U){return{kind:"word",text:G,dynamic:U.kind==="word"&&(U.dynamic||G.includes("$"))}}function yE(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 bE(G){return"path".startsWith(G)||"literalpath".startsWith(G)}function CE(G){return"recurse".startsWith(G)}function SE(G){return G.length>=2&&"force".startsWith(G)}function vE(G){return G==="wi"||"whatif".startsWith(G)}function EE(G){if(G===void 0||G==="")return!0;let U=G.toLowerCase();return U==="$true"||U==="true"}function RE(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 df="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var xE=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),_E=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),wE=new Set(["-o","--output","--query","--subscription"]),PE=new Set;function mf(G){if(G==="aws")return xE;if(G==="gcloud")return _E;if(G==="az")return wE;return PE}var AE=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),TE=new Set;function ff(G){if(G==="git")return vn;if(G==="docker")return AE;return TE}function A(G,U){if(G.length===0||U.length===0)return null;let j=Mt(G[0]??""),K=fn(G);for(let re of U){if(!OE(j,re.command))continue;if(re.match){if(IE(j,G,re.match))return pf(re);continue}if(!ME(j,G,re.subcommand))continue;if(NE(G,new Set(re.block_args),K))return pf(re)}return null}function pf(G){return{id:`custom.${G.name}`,reason:`[${G.name}] ${G.reason}`,intent:G.intent??"manual_only"}}function IE(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 kE(K,j.command_path,mf(G))}function kE(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 OE(G,U){return G===Mt(U)}function ME(G,U,j){if(!j)return!0;return gf(U,1,j,ff(G))}function gf(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("=")&&DE(G,oe,j,K))return!0;continue}return de===j}return!1}function DE(G,U,j,K){let re=G[U+1];if(!re||re.startsWith("-"))return!1;return gf(G,U+2,j,K)}function NE(G,U,j){return G.some((K)=>U.has(K))||[...j].some((K)=>U.has(K))}var LE=new Set(["-e","--source"]),WE=new Set(["-F","-v","--assign","--field-separator"]),hf=new Set(["-f","--file"]),FE=new Set(["print","printf","return"]),yf=[{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"}],GE="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 bf(G,U,j){let K=!1;for(let re of zE(G)){let oe=$E(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?xt("awk.system-dynamic",GE):null}function jl(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&&LE.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&&(WE.has(Se)||hf.has(Se))){let we=G[de+1];if(oe&&=we!==void 0,hf.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 jl(G).sources}function zE(G){return fi(G).filter((U)=>U.kind!=="program-file").map((U)=>U.value)}function $E(G,U){xn(U,G);let j=G.includes("system")?Vl(G,U):null,K=BE(G,U);if(!j&&!K)return null;return{dynamic:!!j?.dynamic||!!K?.dynamic,commands:[...j?.commands??[],...K?.commands??[]]}}function Vl(G,U){xn(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=Cf(G,oe+1);continue}if(de==="/"&&Sf(G,oe)){oe=vf(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 BE(G,U){xn(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=Cf(G,oe+1),de=oe,Se=null,we=null,We=oe;continue}if(mt==="/"&&Sf(G,oe)){let pt=vf(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&&(Hl(G,oe,"print")||Hl(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(Hl(G,ft,"getline")){re=!0;let pt=jE(de,we,We);if(K||=pt===null,pt!==null)j.push(pt);We=gt,oe=gt;continue}if(qE(de,Se)){re=!0;let pt=HE(G,ft);if(!pt){K=!0,We=gt,oe=gt;continue}if(!UE(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 UE(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=VE(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 HE(G,U){let j=G[U];if(j!=='"'&&j!=="'")return null;return Is(G,U,j)}function jE(G,U,j){if(!U)return null;return U.startIndex>=G&&U.endIndex===j?U.value:null}function VE(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 Hl(G,U,j){return G.startsWith(j,U)&&!mi(G[U-1])&&!mi(G[U+j.length])}function qE(G,U){return U!==null&&U>=G}function Cf(G,U){let j=G.indexOf(`
|
|
35
|
-
`,U);return j===-1?G.length:j+1}function Sf(G,U){let j=KE(G,U);if(j===-1)return!0;if("{([,;!~=".includes(G[j]??""))return!0;let K=j;while(mi(G[K-1]))K--;return FE.has(G.slice(K,j+1))}function KE(G,U){for(let j=U-1;j>=0;j--)if(!/\s/.test(G[j]??""))return j;return-1}function vf(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 YE="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",ZE="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",XE="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function Ef(G){return G==="dd"||G==="shred"||G==="mkfs"||G.startsWith("mkfs.")}function Rf(G,U){let j=U.slice(1);if(G==="dd"&&j.some((K)=>/^of=\/dev\/.+/.test(K)))return xt("dd.device-write",YE);if((G==="mkfs"||G.startsWith("mkfs."))&&j.some((K)=>K.startsWith("/dev/")))return xt("mkfs.device",ZE);if(G==="shred"&&j.length>0)return xt("shred.target",XE);return null}var JE=new Set(["sudo","env","command","builtin"]),QE=new Set(["caffeinate","exec","nice","nohup","setsid","stdbuf","time","timeout"]);function ks(G,U){let j=G[0];if(!j||!xf(kt(j),U))return null;let K=kt(j),re=G[1]==="--"?2:1,oe=eR(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 eR(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&&tR(Se,K);if(we)oe.push(de);if(!we&&Fi.has(Mt(Se)))break;if(re)break}return oe}function tR(G,U){let j=kt(G),K=Mt(G);return K==="git"||j==="busybox"||Wr(G)||Na.has(j)||Ef(K)||xf(j,U)||Kt.has(K)||G==="$SHELL"||Ln(K)||In.has(K)||U.rules.some((re)=>re.command===j)}function xf(G,U){return QE.has(G)||U.transparentWrappers.includes(G)}function Wr(G){return JE.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 zn(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");ql(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])ql(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(rR(mt)){ql(Se),yield*Os(mt.slice(1),U,gt,K,re,oe,de,Se,we);return}yield nR(mt,gt,K,re,oe,we)}function nR(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 ql(G){if(G.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");G.iterations++}function rR(G){return kt(G[0]??"").toLowerCase()==="busybox"&&G.length>1}function Kl(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"||Yl(K,"recursive")){U=!0;continue}if(K==="-f"||Yl(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)=>Yl(j,"recursive")||/^-[A-Za-z]+$/.test(j)&&/[rR]/.test(j.slice(1)))}function Yl(G,U){return G.length>2&&G.startsWith("--")&&U.startsWith(G.slice(2))}var oR=["--init-file","--rcfile"],iR=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function $n(G){for(let U=1;U<G.length;U++){let j=G[U];if(!j)continue;if(j==="-c")return _f(G,U,!0);if(j.startsWith("-")&&j.includes("c")&&!j.startsWith("--")){let K=_f(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 En(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 _f(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 wf(G){let U=kt(G[0]??"").toLowerCase(),j=sR(G,U),K=iR.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 sR(G,U){let j=En(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?oR.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"&&Ma.has(gt)&&!we.includes("="))Se++;continue}if(U==="bash")de=!1;let We=Da(U,we,G[Se+1],"startup");if(We.interactive)oe=we[0]==="-";Se+=We.followingValues}return{argvSource:re.at(-1)??null,interactive:oe}}var aR="find -delete permanently removes files. Use -print first to preview.",lR="find -exec rm -rf is dangerous. Use explicit file list instead.",cR=new Set(["-exec","-execdir","-ok","-okdir"]),uR=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 Pf(G,U){let j=G.map(t),K=dR(G,j,U);if(K)return K;if(Ds(j,1)&&!yR(G,j,U)){let de=Tt(xt("find.delete",aR),U.policy);if(de)return de}let re=U.budget??An(),oe=0;while(oe<j.length){let de=j[oe],Se=rr(de??"");if(Se>0){oe+=Se+1;continue}if(!Vn(de)){oe++;continue}re.charge("derivedTokens",j.length-oe-1);let we=ho(j,oe);oe=we.nextIndex;let We=CR(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 dR(G,U,j){if(!Ds(U,1)&&!Zl(U,j.environment))return null;let re=pi(G)??qt(["."]),oe=jn({...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=_n(we,oe,{targetIsLiteral:Se.expandedTargets!==void 0||Se.targetIsLiteral,tmpdirWordSplittingProtected:Se.tmpdirWordSplittingProtected});if(We.kind==="root_or_home_target")return xt("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"&&!mR(G,oe.protectedGitMetadata,j.environment))return xt("find.delete-git-metadata",x)}}if(hR(U)&&oe.resolvedCwd&&jm(re.map(t),oe.resolvedCwd,oe.protectedGitMetadata,oe.environment,oe.budget))return xt("find.delete-git-metadata",x);return null}function mR(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(Vn(we)){let We=ho(K,Se),mt=mr([...We.tokens],j),gt=Ms(mt),ft=Kt.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(pR(We.text,we==="-iname"));Se+=2;continue}if(!fR.has(we))return!1;Se+=1+rr(we)}return re.length>0&&!qm(U,(we)=>re.every((We)=>We.test(we)))}var fR=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function pR(G,U){let j=G.replace(/[*?]|[.+^${}()|\]/]/g,(K)=>K==="*"?".*":K==="?"?".":`\\${K}`);return new RegExp(`^${j}$`,U?"isu":"su")}var gR=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function Zl(G,U){let j=0;while(j<G.length){if(!Vn(G[j])){j++;continue}let K=ho(G,j),re=mr([...K.tokens],U),oe=kt(re[0]??"").toLowerCase(),de=Kt.has(oe)&&gR.test(($n(re)??"").replace(/["'\\]/g,""));if((oe==="rm"||oe==="rmdir"||de)&&re.some((we)=>we.includes("{}")))return!0;j=K.nextIndex}return!1}function hR(G){return G.some((U,j)=>{if(!["-name","-iname"].includes(U))return!1;return G[j+1]?.toLowerCase()==="hooks"})}function yR(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=Fl(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=jn(we),mt=jn({...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(!Jt(j.policy,"rm.recursive-force-paranoid",j.paranoid??!1)&&!Ct&&_n(vt,We,St).kind==="within_anchored_cwd")return!0;return nf(vt,Ct?mt:We,{...St,containmentTarget:bR(vt,oe)})})})}function bR(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 CR(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 xt("find.exec-rm-recursive-force",lR);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(Vn(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 uR.get(G)??(/^-newer[A-Za-z]{2}$/.test(G)?1:0)}function Vn(G){return G!==void 0&&cR.has(G)}import{resolve as Kx}from"node:path";function*Xl(G){for(let U of G.nodes)yield*vR(U)}function SR(G){return Object.freeze([...Xl(G)])}function dt(G){return Object.freeze(SR(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*vR(G){if(G.kind==="command"){yield G;for(let U of G.nested)yield*Xl(U);return}if(G.kind==="group")yield*Xl(G.body)}var ER=5,Jl="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 sn(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 Tf(G,U,j){let K=Ns(G,U,j),re=RR(K.entries);if(re.size===0)return{blockedReason:K.blockedReason,expanded:!1,tokens:G};let oe=G,de=!1;for(let Se=0;Se<ER;Se++){let{subcommand:we,rest:We}=wn(oe),mt=we?.toLowerCase();if(!mt||!re.has(mt))return{blockedReason:K.blockedReason,expanded:de,tokens:oe};let gt=re.get(mt),ft=AR(gt);if(ft===null||ft.length===0)return{blockedReason:Jl,expanded:!0,tokens:oe};oe=["git",...ft,...We],de=!0}return{blockedReason:Jl,expanded:!0,tokens:oe}}function If(G,U,j){return Ns(G,U,j).entries.some((K)=>K.key.toLowerCase()==="core.sshcommand")}function wn(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+=vn.has(re)?2:1}return{subcommand:null,rest:[]}}function RR(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=_R(U,j);return{blockedReason:oe.blockedReason,entries:[...oe.entries,...xR(G,U,j)]}}function xR(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=Ql(G[re+1]);if(de)K.push(de);re+=2;continue}if(oe.startsWith("-c")&&oe.length>2){let de=Ql(oe.slice(2));if(de)K.push(de);re++;continue}if(oe==="--config-env"){let de=Af(G[re+1],U,j);if(de)K.push(de);re+=2;continue}if(oe.startsWith("--config-env=")){let de=Af(oe.slice(13),U,j);if(de)K.push(de);re++;continue}if(vn.has(oe)){re+=2;continue}re++}return K}function _R(G,U){let j=wR(G,U),K=PR(G,U);return{blockedReason:j===null||K===null?Jl:null,entries:[...j??[],...K??[]]}}function wR(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=Ql(oe);if(!de)return null;K.push(de)}return K}function PR(G,U){let j=bm(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 Ql(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 Af(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 AR(G){let U=G?.trimStart();if(!U||U.startsWith("!"))return null;return gi(U)}var TR="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",IR="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",kR="git checkout --force discards uncommitted changes. Use 'git stash' first.",OR="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",MR="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",DR="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",NR="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",LR="git switch --force discards uncommitted changes. Use 'git stash' first.",WR="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",FR="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",GR="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",zR="git reset --merge can lose uncommitted changes. Use 'git stash' first.",$R="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",BR="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.",UR="git push --force destroys remote history. Use --force-with-lease for safer force push.",HR="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",jR="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",VR="git branch -D force-deletes without merge check. Use -d for safe delete.",qR="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",KR="git merge --abort discards merge conflict resolutions. Use 'git status' first.",YR="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",ZR="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",XR="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",JR="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",QR="git worktree remove --force can delete uncommitted changes. Remove --force flag.",ex=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),tx=new Set(["--recurse-submodules","--track","-t"]),ec=new Set(["-b","-B","-U"]),tc=new Set(["-c","-C"]),nx=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 Of(G,U){let{subcommand:j,rest:K}=wn(G);if(!j)return null;switch(j.toLowerCase()){case"checkout":return pr(rx(K,U));case"switch":return pr(ix(K));case"restore":return pr(ax(K));case"reset":return cx(K);case"clean":return pr(dx(K));case"rm":return pr(mx(K));case"push":return Gr(fx(K));case"branch":return Gr(hx(K));case"stash":return Gr(vx(K));case"worktree":return Gr(Ex(K));case"rebase":return pr(yx(K));case"merge":return pr(bx(K));case"tag":return Gr(Cx(K));case"reflog":return Gr(Sx(K));default:return null}}function pr(G){return G?{...G,localDiscard:!0}:null}function Gr(G){return G?{...G,localDiscard:!1}:null}function rx(G,U){let{index:j,before:K}=sn(G),re=fn(K,{shortOptsWithValue:ec});if(K.some((Se)=>Dt(Se,"--force"))||re.has("-f"))return xt("git.checkout-force",kR);for(let Se of G){if(Se==="-b"||Se==="-B"||Se==="--orphan")return null;if(Dt(Se,"--pathspec-from-file"))return xt("git.checkout-pathspec-from-file",MR)}if(j!==-1){if(K.some((we)=>!we.startsWith("-")))return xt("git.checkout-ref-path",OR);return xt("git.checkout-double-dash",TR)}let oe=sx(G);if(oe.length>=2)return xt("git.checkout-ambiguous",DR);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(ox(de)||U(de))return xt("git.checkout-double-dash",IR);return null}function ox(G){return G==="."||G===".."||/^\.\.?[/\\]/.test(G)||/^([/\\]|[A-Za-z]:[/\\])/.test(G)||G.endsWith("/")||G.startsWith(":")||/[*?[]/.test(G)}function ix(G){let{before:U}=sn(G);if(U.some((K)=>Dt(K,"--discard-changes")))return xt("git.switch-discard-changes",NR);let j=fn(U,{shortOptsWithValue:tc});if(U.some((K)=>Dt(K,"--force"))||j.has("-f"))return xt("git.switch-force",LR);return null}function sx(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(ex.has(K)){j+=2;continue}if(tx.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 ax(G){let U=lx(G);if(U.isTerminal||!U.hasPathspec&&!U.hasPatch||!U.hasWorktree)return null;return U.hasExplicitLocation?xt("git.restore-worktree",FR):xt("git.restore-unstaged",WR)}function lx(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(nx.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 cx(G){let U=null;for(let j of G){if(Dt(j,"--hard")){U=xt("git.reset-hard",GR);break}if(Dt(j,"--merge")){U=xt("git.reset-merge",zR);break}}if(!U)return null;return ux(G)?Gr(U):pr(U)}function ux(G){for(let U of G){if(U==="--")return!1;if(!U.startsWith("-"))return!0}return!1}function dx(G){for(let j of G)if(j==="-n"||Dt(j,"--dry-run"))return null;let U=fn(G.filter((j)=>j!=="--"));if(G.some((j)=>Dt(j,"--force"))||U.has("-f"))return xt("git.clean-force",$R);return null}function mx(G){let U=!1,j=!1,K=!1;for(let re of sn(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=fn([re]);U||=oe.has("-f"),K||=oe.has("-n")}return U&&!j&&!K?xt("git.rm-force",BR):null}function fx(G){let{before:U,after:j}=sn(G),K=fn(U);if(U.some((de)=>Dt(de,"--mirror")))return xt("git.push-mirror",jR);if(U.some((de)=>Dt(de,"--force"))||K.has("-f")||kf(U,j).some(px))return xt("git.push-force",UR);if(U.some((de)=>Dt(de,"--delete"))||K.has("-d")||kf(U,j).some(gx))return xt("git.push-delete",HR);return null}function kf(G,U){return[...G.filter((j)=>j!==""&&!j.startsWith("-")),...U]}function px(G){return G.startsWith("+")||G.includes(":+")}function gx(G){return G.length>1&&G.startsWith(":")}function hx(G){let{before:U}=sn(G),j=fn(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 xt("git.branch-force-delete",VR);return null}function yx(G){let{before:U}=sn(G);return U.some((j)=>Dt(j,"--abort"))?xt("git.rebase-abort",qR):null}function bx(G){let{before:U}=sn(G);return U.some((j)=>Dt(j,"--abort"))?xt("git.merge-abort",KR):null}function Cx(G){let{before:U}=sn(G);return fn(U).has("-d")||U.some((K)=>Dt(K,"--delete"))?xt("git.tag-delete",YR):null}function Sx(G){return G[0]==="delete"?xt("git.reflog-delete",ZR):null}function vx(G){for(let U of G){if(U==="drop")return xt("git.stash-drop",XR);if(U==="clear")return xt("git.stash-clear",JR)}return null}function Ex(G){let{before:U}=sn(G);if(!U.includes("remove"))return null;let K=fn(U);if(U.some((re)=>Dt(re,"--force"))||K.has("-f"))return xt("git.worktree-remove-force",QR);return null}import{dirname as Ux,isAbsolute as Hx,join as qf,resolve as jx}from"node:path";var rc="TMPDIR",oc="IFS",Df=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Nf=/^[A-Za-z_][A-Za-z0-9_]*$/,Lf=new Set(["export","typeset","declare","readonly"]),Rx=new Set(["builtin","command","time"]),xx=new Set(["do","then","else"]),_x=new Set(["do","then","case"]),Mf=new Set(["done","fi","esac"]),wx=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function Wf(G,U){return G.map((j)=>j.provenance==="variable"&&Hf(j.text)?Ff(j.text,U.shellAssignments):t(j))}function Ff(G,U){return G.replace(wx,(j,K,re)=>U.get(K??re??"")??j)}function qn(G,U){let j=G.parts.every((re)=>re.provenance!=="literal"||!/[$`]/.test(re.raw));if(G.provenance!=="variable"||!j)return null;let K=Ff(G.text,U);return/^[~-]/.test(K)||/[\s$`*?[]/.test(K)?null:K}function Gf(G,U){return{env:G,effectiveEnvAssignments:Ix(G,U),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function zf(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 ic(G,U){let j=Bf(G,U),K=G[0]??"";if(_x.has(K))U.bodyDepth+=1;if(K==="elif"||Mf.has(K))U.bodyDepth=Math.max(0,U.bodyDepth-1);if(Mf.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);sc(U,Se)});let re=j.commandIndex;if(re!==-1&&Lf.has(G[re]??""))G.filter((Se)=>Nf.test(Se)&&nc(Se)).forEach((Se)=>{kx(U,Se)});let oe=re===-1?-1:Uf(G,re);if(oe===-1||G[oe]!=="unset")return;let de=Mx(G,oe);if(de===null)return;G.slice(de).forEach((Se)=>{if(U.bodyDepth>0){U.shellAssignments.set(Se,"");return}Ox(U,Se)})}function $f(G,U){let j=Bf(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 Bf(G,U){let j=xx.has(G[0]??"")?1:0,K=G.findIndex((Se,we)=>we>=j&&!Hf(Se)),re=K!==-1&&Lf.has(G[Uf(G,K)]??""),oe=Tx(U);return{assignments:G.flatMap((Se,we)=>{let We=Px(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 Uf(G,U){let j=U;while(Rx.has(G[j]??"")){j+=1;while(G[j]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(G[j]??""))return U;j+=1}}return j}function Hf(G){return On(G)!==null||Df.test(G)}function Px(G,U,j){return On(G)??Ax(G,U,j)}function Ax(G,U,j){let K=fs(G,j,U);if(K)return K;let re=G.match(Df)?.[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 nc(G){return G===rc||G===oc||Il(G)}function Tx(G){return new Map([...G.effectiveEnvAssignments??[],...G.shellAssignments])}function Ix(G,U){let j=[rc,oc].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 sc(G,U){let j=new Map(G.effectiveEnvAssignments??[]);j.set(U.name,U.value),G.effectiveEnvAssignments=j}function kx(G,U){sc(G,{name:U,value:G.shellAssignments.get(U)??G.effectiveEnvAssignments?.get(U)??G.env.get(U)??""})}function Ox(G,U){if(!nc(U)&&!Nf.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(!nc(U)||U===rc||U===oc||No(U)){sc(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 Mx(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 Dx}from"node:path";function Ls(G,U){return Tl.some((j)=>U?.has(j)||G.has(j))}function bo(G,U,j){if(!U)return{gitCwd:null,hasExplicitGitContext:!1};let K=j.realpath(Dx(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=jf(re,we,j);if(!We)return{gitCwd:null,hasExplicitGitContext:oe};re=We,de+=2;continue}if(Se.startsWith("-C")&&Se.length>2){let we=jf(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+=vn.has(Se)?2:1}return{gitCwd:re,hasExplicitGitContext:oe}}function jf(G,U,j){try{let K=ur(G,U,j);return j.isDirectory(K)?K:null}catch{return null}}function Vf(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(ac(G,j,re))return null;return{kind:"worktree",originalReason:U.reason,gitCwd:K.gitCwd}}function ac(G,U,j){let{subcommand:K,rest:re}=wn(G),oe=K?.toLowerCase();if(U.dynamicArguments||Nx(re)||zx(G,U.environment.env,U.envAssignments,j)||Fx(re)||Lx(oe,re))return!0;return oe==="clean"&&Gx(re)>1}function Nx(G){return G.some((U)=>/[$*?[]/.test(U))}function Lx(G,U){if(G==="checkout"){let{before:j}=sn(U),K=fn(j,{shortOptsWithValue:ec}),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}=sn(U),K=fn(j,{shortOptsWithValue:tc}),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")||Wx(de))||K.has("-C");return re&&oe}return!1}function Wx(G){let U=G.split("=",1)[0]??G;return U==="--force-create"||U.length>=9&&"--force-create".startsWith(U)}function Fx(G){return G.some((U)=>U.startsWith("--recurse-sub"))}function Gx(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 zx(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)=>Bx(Se.key)))return!0;let de=oe.filter((Se)=>Se.key==="submodule.recurse").at(-1);if(de)return de.value===void 0||$x(de.value);if(Sm(j))return!0;return K.recursiveSubmodules}function $x(G){let U=G.toLowerCase();return U!=="false"&&U!=="no"&&U!=="off"&&U!=="0"}function Bx(G){return G==="include.path"||G.startsWith("includeif.")&&G.endsWith(".path")}function Kf(G,U,j){let K=G.map((we)=>qn(we,j.shellAssignments??new Map)??t(we)),re=j.environment.paths,oe=bo(K,j.cwd,re),de=j.originalCwd?re.realpath(jx(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"?qx(G,j.shellAssignments,re):Yf(oe.gitCwd,re);if(Se===null||U.id!=="git.worktree-remove-force"&&!Vx(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 Vx(G,U,j,K){let re=K.environment.paths,oe=qf(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&&!ac(U,K,Se)}function qx(G,U,j){let K=wn(G.map(t)).rest,{before:re,after:oe}=sn(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&&qn(we,U??new Map))??Se;if(!Hx(We)||/[\s$`*?[]/.test(We)||j.entryKind(We)!=="present"||!j.isDirectory(We))return null;return j.realpath(We)}function Yf(G,U){if(U.entryKind(qf(G,".git"))!=="missing")return G;let j=Ux(G);return j===G?null:Yf(j,U)}var Yx="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.",Zx=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function Ws(G,U){return Zf(G,U)}function Zf(G,U,j){let K=G.map(t),re=Tf(K,U.environment.env,U.envAssignments),oe=re.blockedReason?Tt(xt("git.alias-config",re.blockedReason),U.policy):null;if(oe)return oe;let de=re.tokens;if((Cm(U.envAssignments)||If(K,U.environment.env,U.envAssignments))&&Xx(de))return xt("git.ssh-env",Yx);let Se=Of(de,(We)=>{let mt=bo(K,U.cwd,U.environment.paths).gitCwd;return mt!==null&&U.environment.paths.entryKind(Kx(mt,We))!=="missing"});if(!Se)return null;if(re.expanded||re.blockedReason)return Se;let we=Vf(K,Se,U)??Kf(G,Se,U);if(!we)return Se;return j?.(we),null}function Xf(G,U){let j=null;return{match:Zf(G,U,(re)=>{j=re}),relaxation:j}}function Xx(G){let{subcommand:U,rest:j}=wn(G),K=U?.toLowerCase();if(!K)return!1;if(Zx.has(K))return!0;if(K==="archive")return sn(j).before.some((re)=>Dt(re,"--remote"));return K==="remote"&&Jx(j)}function Jx(G){return G.find((U)=>!Qx(U))?.toLowerCase()==="update"}function Qx(G){return G==="-v"||Dt(G,"--verbose")||Dt(G,"--no-verbose")}import{isAbsolute as T_}from"node:path";function Jf(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 Qf="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",e_="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.",t_="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",n_="rm -rf targeting root or home directory is extremely dangerous and always blocked.",r_="rm -rf in home directory is dangerous. Change to a project directory first.",ep={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:n_},git_metadata_target:{id:"rm.git-metadata",reason:x},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:t_},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:r_},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:Qf},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:e_},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:Qf}};function Gs(G,U){let j=jn({...U,allowPaths:U.policy?.destructiveCommandAllowPaths,posixShell:!0}),K=G.map(t),re=Ms(K),oe=i_(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,ep),U.policy);if(we)return we;continue}for(let we of Se.expandedTargets??[de.text]){let We=cn(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 xt("rm.git-metadata",x);if(!re)continue;for(let gt of o_(We,j,mt)){let ft=Lr(gt,j,U.policy,ep),pt=Tt(ft,U.policy);if(pt)return pt}}}return null}function o_(G,U,j){let K=_n(G,U,j);if(K.kind==="cwd_self_target")return[K,_n(G,U,{...j,skipCwdSelf:!0})];if(K.kind!=="home_cwd_target")return[K];let re=_n(G,U,{...j,skipHomeCwd:!0});if(re.kind!=="cwd_self_target")return[K,re];return[K,re,_n(G,U,{...j,skipHomeCwd:!0,skipCwdSelf:!0})]}function i_(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"},s_=new Set(["<","<<","<<-","<<<","<&","<>"]),np=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,a_=/^(?:[0-9]+|[@*])$/,l_=cr.maxWords,rp=cr.maxInputLength;function op(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 ip(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=lp(G);if(j===-1)return gr;let K=u_(U);if(!K)return gr;let re=[],oe=K.command?.length??0;for(let de of K.references){let Se=m_(de,G,j,K.ifs);if(!Se)return zr;if(oe+=Se.reduce((we,We)=>we+We.length+3,0),re.length+Se.length>l_||oe>rp)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 sp(G,U){let j=lp(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>rp)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 ap(G,U,j,K){if(!En(G.map(t)).readsStdinAsCommands)return gr;let re=U.filter((oe)=>(oe.fd===void 0||oe.fd===0)&&s_.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=En(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?qn(K,U):null;return oe===null?zr:{kind:"literal",source:oe}}var c_=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function dc(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||On(de)!==null)return!1;let Se=kt(Mt(de));return!c_.has(Se)&&!Kt.has(Se)&&!Wr(Se)}function lp(G){return En(G.map(t)).commandIndex??-1}function u_(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(d_);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 d_(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 m_(G,U,j,K){let re=U.slice(j+2);if(G.parameter==="@")return G.quoted?lc(re):f_(re,K);if(G.parameter==="*"){let Se=lc(re);if(!Se)return;let we=Se.join(K[0]??"");return G.quoted?[we]:cc(we,K)}let oe=U[j+1+G.parameter];if(oe&&!yi(oe))return;let de=Co(oe);return G.quoted?[de]:cc(de,K)}function lc(G){return G.every(yi)?G.map(t):void 0}function f_(G,U){let j=lc(G);if(!j)return;let K=j.map((re)=>cc(re,U));return K.some((re)=>re===void 0)?void 0:K.flatMap((re)=>re??[])}function cc(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 mc(G,U){return uc(y(G,"posix"),U)}function bi(G){return mc(G,new Set(Array.from(G.matchAll(np)).flatMap((U)=>{let j=U[1]??U[2];return j===void 0?[]:[j]})))}function uc(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(uc(K.body,j))return!0;continue}if(K.kind!=="command")continue;if(K.nested.some((re)=>uc(re,j))||cp(K.words,j))return!0;b_(K,j)}return!1}function cp(G,U){let j=G.findIndex((de)=>On(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 tp(G[de],U)}if(Kt.has(re)){let de=G.slice(j),Se=En(de.map((We)=>We.text)),we=Se.commandIndex??Se.scriptIndex;return!Se.syntaxCheck&&we!==null&&tp(de[we],U)}let oe=p_(G,j,U);if(oe===null)return!1;if(oe===-1)return!0;return cp(G.slice(oe),U)}function p_(G,U,j){let K=Mt(G[U]?.text??"");if(K==="command")return g_(G,U+1);if(K==="exec")return h_(G,U+1);if(K==="env")return y_(G,U+1,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(/^-[p]*[vV][pvV]*$/.test(K))return null;if(/^-p+$/.test(K))continue;return j}return null}function h_(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 y_(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(On(oe))continue;return K}return null}function b_(G,U){if(!G.words.every((j)=>On(j.text)!==null))return;for(let j of G.words){let K=On(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(np)).some((K)=>{let re=K[1]??K[2];return re!==void 0&&(a_.test(re)||U.has(re))}))}function tp(G,U){return!!G&&(G.parts.some((j)=>j.provenance!=="literal"&&j.provenance!=="variable")||hi(G,U))}var fc="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",pc="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",C_="__CC_SAFETY_NET_XARGS_INPUT__",Us="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",Hs="rm",S_=/(?:^|[;&|]\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,v_=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,E_=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,R_=/^(?:[0-9]+|[@*])$/;function mp(G,U){let j=G.map(t),{childStart:K,replacementToken:re}=$r(j),oe=j.slice(K),de=xt("xargs.shell-dynamic",pc);if(__(oe,re,U)&&Tt(de,U.policy))return Tt(de,U.policy);for(let Se of zn(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=bp(we,re,Se.wrapperEnvAssignments),gt=Se.head==="rm"&&re!==null&&hp(we,re),ft=U.analyzeChild(we,{...Fr(Se,U),dynamicInput:mt,dynamicSourceInput:gt||pp(we,Se.head,re,Se.wrapperEnvAssignments,mt,U.environment,U.strict?void 0:U.analyzeNested),dynamicRmInput:gt,shellDynamicMatch:de,dynamicSourceMatch:de,rmDynamicMatch:xt("xargs.rm-recursive-force-dynamic",fc)});if(ft)return ft;let pt=x_(we,re,U.policy?.rules??[],Tt(de,U.policy));if(pt)return pt;if(Se.head==="git"){let yt=re===null?[...we,C_]: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 x_(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 fp(G,U,j){let K=G.indexOf(U);if(K===-1||G.indexOf(U,K+U.length)!==-1)return[];let re=Jf(G,K,U.length,j);return re===null?[]:[re]}function pp(G,U,j,K,re,oe,de){if(Kt.has(U)){if(nr(G))return!1;if(j!==null&&w_(G,j,de))return!0;let Se=$n(G);if(!Se){let we=or(qt(G));if(we.kind==="literal")return j!==null&&we.source.includes(j);return we.kind==="none"&&re}if(j!==null&&Se.includes(j)&&!gp(Se,j,de))return!0;if(kn(Se))return!0;return P_(Se,j,K)}if(Ln(U))return up(G,j,us,pm(U));if(In.has(U))return up(G,j,jl,yf);if(U==="eval"){let Se=zs(qt(G));if(Se.kind==="dynamic")return!0;if(j!==null)return Se.kind==="literal"&&Se.source.includes(j);return re}if(U==="find")return A_(G,j,oe);if(U==="git"){let Se=wn(G);return j===null?Se.subcommand===null:(Se.subcommand?.includes(j)??!1)||Se.subcommand!==null&&yo.has(Se.subcommand.toLowerCase())&&yp(Se.rest,j).some((we)=>we.includes(j))}return!1}function gp(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 kn(oe)===null&&j(oe)===null}function up(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)=>fp(we,U,Se))));return Fs(re.sources,de,(Se)=>j(G.map((we)=>we.replaceAll(U,Se))).sources)}function __(G,U,j){if(G.length===0||(G[0]??"").toLowerCase()==="command")return!1;let K=new Set(Array.from(zn(G,j),(oe)=>oe.head)),re=U===null?[...G,Hs]:G.map((oe,de)=>de===0?oe:oe.replaceAll(U,Hs));return Array.from(zn(re,j)).some((oe)=>oe.head===Hs&&!K.has(Hs))}function hp(G,U){return yp(G.slice(1),U).some((j)=>j.includes(U)&&(j.startsWith("-")||j.startsWith(U)))}function yp(G,U){let j=G.findIndex((K)=>K==="--"&&!K.includes(U));return j===-1?G:G.slice(0,j)}function bp(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 w_(G,U,j){let K=En(G),re=K.commandIndex===null?"":G[K.commandIndex]??"";if(re.includes(U)&&!gp(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 fp(Se,U,de).some((mt)=>{let gt=G.map((pt,ht)=>ht===we?pt.replaceAll(U,mt):pt),ft=En(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 P_(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(S_))if(dp(re,K))return!0;for(let re of G.matchAll(v_))for(let oe of(re[1]??"").matchAll(E_))if(dp(oe,K))return!0;return mc(G,K)}function dp(G,U){let j=G[1]??G[2];return j!==void 0&&(R_.test(j)||U.has(j))}function A_(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(Vn(de)){let we=ho(G,oe);oe=we.nextIndex-1;for(let We of zn(we.tokens,{environment:j,cwd:void 0})){let mt=bp(We.tokens,U,We.wrapperEnvAssignments);if(We.head==="rm"&&hp(We.tokens,U)||pp(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.",I_="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",k_="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Vs=/\{[^{}\s]*\}/g,Cp=/\{\}|\{-?\d+\}/g,Sp=/[\s;&|<>()$`\\"']/,O_=["e","f","source","file","-e","-f","--source","--file"],M_=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],D_=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),N_=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),vp=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),L_=new Set(["--workdir","--wd"]),Ep="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Mn(G,U){for(let j of G){let K=U(j);if(K)return K}return null}function _p(G){return Mn([...G],(U)=>kn(U))}function wp(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=Fp(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=_p(U.envAssignments?.values()??[]);if(yt)return yt}if(we){let ht=U_(U);if(ht)return ht}if(mt!==void 0&&Se){let ht=So(U);if(ht)return ht}let ft=H_(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([...zn(oe,pt)].flatMap((yt)=>[...yt.envAssignments.values()]).some(yc)){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=Op(pt.envAssignments,pt.cwd,Se);return Mn(ht,(bt)=>U.analyzeNested(bt,yt))}return Mn(zn(oe,pt),(ht)=>W_(ht,re,U,pt))}function W_(G,U,j,K){let{templateHasPlaceholder:re,runsRemotely:oe,usesStdin:de}=U,Se=G.tokens,we=[...G.envAssignments.values()];if(we.some(Lp)){let Et=So(j);if(Et)return Et}let We=_p(we);if(We)return We;let mt=we.some(Gt),gt=re||mt,ft=de&>,pt=Op(G.envAssignments,G.wrapperCwd,oe||ft),ht=gt?{...pt,worktreeMode:!1}:pt,yt=Se.join(" "),bt=Gt(yt.split(/[ \t\n=]/,1)[0]??""),Ct=!U.quotesCommand&&(bt||Se.some((Et)=>Sp.test(Et))),vt=bt||Sp.test(Se[0]??""),St=Ct&&vt&&U.jobs.length>0?null:F_(G,U,j,K,ht,mt);if(St||!Ct)return St;return Pp(Gt(yt)?yt:`${yt} {}`,!bt,G,U,j,K,ht)}function F_(G,U,j,K,re,oe){let{jobs:de,templateHasPlaceholder:Se,runsRemotely:we,usesStdin:We}=U,mt=G.tokens,gt=Se||oe;if(Kt.has(G.head)){let pt=()=>{if(!Se||de.length===0)return null;return Mn(de,(bt)=>j.analyzeChild(js(mt,bt,j.budget),Fr(G,K)))};if(nr(mt))return pt();let ht=$n(mt);if(ht){if(Wp(ht)){let St=hr(j);if(St)return St;if(de.length===0)return null;return Mn(de,(Et)=>j.analyzeNested(Dp(ht,Et,j.budget),re))}if(Gt(ht))return Pp(ht,!1,G,U,j,K,re);let bt=!oe&&(!Se||de.length>0)?(de.length>0?de:[void 0]).map((St)=>$s(qt(St===void 0?mt:Se?mt.map((Et)=>Mp(Et,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),Mn(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(qt(mt));if(yt.kind==="dynamic"||yt.kind==="literal"&&Gt(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),Mn(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 Mn(de,(ht)=>gc(js(mt,ht,j.budget,Cp),G.cwd,K));if(de.length>0)return Mn(de,(ht)=>gc(xp(mt,ht,j.budget),G.cwd,K));let pt=gc(mt.flatMap((ht,yt)=>{if(yt===0||!Gt(ht))return[ht];return ht.startsWith("-")?[ht.replace(Cp,"")]:[]}),G.cwd,K);if(pt)return pt;return kp(j)}let ft=de.length>0?de:[void 0];return Mn(ft,(pt)=>{let ht=pt===void 0?mt:Se?js(mt,pt,j.budget):xp(mt,pt,j.budget),yt=xt("parallel.shell-dynamic",Si),bt=We&&G.head==="find"?B_(ht,K):null,Ct=Tp(ht,We,j)??bt?.customResult??null,vt=Mt(G.head),St=We&&(vt==="rm"&&hc(ht)||vt==="xargs"&&Ip(ht)||bt?.rmOptions===!0),Et=We&&(St||bt?.executedSource===!0||bt===null&&Ap(ht,vt)),_t=j.analyzeChild(ht,{...Fr(G,K),worktreeMode:we||We||gt?!1:j.worktreeMode,dynamicInput:We||gt,dynamicRmInput:St,dynamicSourceInput:Ct!==null||Et,shellDynamicMatch:yt,dynamicSourceMatch:yt,rmDynamicMatch:xt("parallel.rm-recursive-force-dynamic",Ci)});if(Et){let At=Tt(yt,j.policy);if(At)return At}return _t??Ct??A(ht,j.policy?.rules??[])})}function Pp(G,U,j,K,re,oe,de){if(K.jobs.length>0)return Mn(K.jobs,(We)=>re.analyzeNested(Dp(G,U?We.map(Bs):We,re.budget),de));let Se=gi(G);if(Se?.[0]&&Mt(Se[0])==="rm"&&tr(Se)){let We=kp(re);if(We)return We}return(Se?re.analyzeChild(Se,{...Fr(j,oe),dynamicInput:K.usesStdin,shellDynamicMatch:xt("parallel.shell-dynamic",Si),rmDynamicMatch:xt("parallel.rm-recursive-force-dynamic",Ci)}):null)??re.analyzeNested(G,de)}function Ap(G,U){if(Gt(G[0]??""))return!0;if(U==="eval"||U==="source"||U===".")return!0;if(U==="parallel"||U==="xargs")return!0;if(Kt.has(U))return $_(G);if(U==="git")return G_(G);if(U==="find")return!0;if(In.has(U))return Rp(G,O_,fi);if(Ln(U))return Rp(G,M_,cs);return!1}function hc(G){let U=G.indexOf("--"),j=G.slice(1,U===-1?void 0:U);if(!G.some(Gt))return U===-1;return j.some((re)=>Gt(re)&&(re.startsWith("-")||Wp(re)))}function G_(G){if(z_(G))return!0;let U=wn(G);if(U.subcommand===null||Gt(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(Gt))return j===-1;return K.some(Gt)}function z_(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(Gt(G[U+1]??""))return!0;U++;continue}if(j.startsWith("-c")&&j.length>2||j.startsWith("--config-env=")){if(Gt(j))return!0;continue}if(Gt(j))return!0}return!1}function $_(G){if(nr(G))return!1;let U=$n(G);if(U!==null)return Gt(U);let j=or(qt(G));if(j.kind==="literal")return Gt(j.source);if(j.kind==="dynamic")return!0;return!G.some(Gt)}function Rp(G,U,j){let K=j(G);if(K.some((re)=>Gt(re.value)))return!0;if(!G.some(Gt))return j([...G,Ep]).some((re)=>re.value===Ep);return Fs(K,U,(re)=>j(G.map((oe)=>Mp(oe,[re]))))}function Tp(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(Gt))return hr(j);return Mn(re,(oe)=>A([...G,...oe.subcommand?[oe.subcommand]:[],...oe.block_args],[oe]))}function B_(G,U){let j={customResult:null,executedSource:!G.some(Gt),rmOptions:!1},K=!1,re=0,oe=null,de=()=>{if(!oe?.some(Gt))return;for(let Se of zn(oe,U))j.executedSource||=Ap(Se.tokens,Se.head),j.rmOptions||=Se.head==="rm"&&hc(Se.tokens)||Se.head==="xargs"&&Ip(Se.tokens),j.customResult??=Tp(Se.tokens,!0,U)};for(let Se of G.slice(1)){if(!K&&!Se.startsWith("-")&&Se!=="!"&&Se!=="("){j.executedSource||=Gt(Se);continue}if(K=!0,oe){if(Se===";"||Se==="+"){de(),oe=null;continue}oe.push(Se);continue}if(re>0){re--;continue}if(Vn(Se)){oe=[],j.executedSource||=Gt(Se);continue}let we=rr(Se);if(we>0){re=we,j.executedSource||=Gt(Se);continue}j.executedSource||=Gt(Se)}return de(),j}function Ip(G){let U=G.slice($r(G).childStart);return Mt(U[0]??"")==="rm"&&hc(U)}function qs(G,U){return(j)=>Tt(xt(G,U),j.policy)}var hr=qs("parallel.shell-dynamic",Si),U_=qs("parallel.command-stream-dynamic",I_),So=qs("parallel.command-stream-dynamic",k_),kp=qs("parallel.rm-recursive-force-dynamic",Ci);function gc(G,U,j){return Tt(Gs(qt(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 Op(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 Mp(G,U){return G.replace(Vs,(j)=>Np(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=Np(oe,U);return j.charge("derivedTokens",Math.max(1,Math.ceil(de.length/64))),de}))}function Dp(G,U,j){return js([G],U,j)[0]??""}function xp(G,U,j){return j.charge("derivedTokens",G.length+U.length),[...G,...U]}function Np(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 Gt(G){return G.search(Vs)!==-1}function Lp(G){if(yc(G))return!0;for(let U of G.matchAll(Vs))if(!/^(?:\{\}|\{\d+\})$/.test(U[0]))return!0;return!1}function yc(G){let U=G.indexOf("{=");return U!==-1&&G.indexOf("=}",U+2)!==-1}function Wp(G){return/^\{[^{}\s]*\}$/.test(G)}function H_(G,U,j){if(G===void 0)return;if(G==="..."||/^~|[{}$`*?[]/.test(G))return null;if(!U&&!T_(G))return null;try{return ur(U??G,G,j)}catch{return null}}function Fp(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 Et=Kl(G,U+1);j.push(...Et.templateTokens),K=U+1,re=Et.markerIndex;break}if(!yt.startsWith("-")){let Et=Kl(G,U);j.push(...Et.templateTokens),K=U,re=Et.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 Et=vt==="--replace"?St:yt.slice(2);mt||=Et!==""&&Et!=="{}",U++;continue}if(yt==="-a"||N_.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(vp.has(vt)||yt.startsWith("-S")&&yt.length>2){oe=!0,U+=vp.has(yt)?2:1;continue}if(L_.has(vt)){mt=!0;let Et=St??bt;if(Et===void 0||Et===":::"||Et==="--"){U++;continue}we=Et,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(D_.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?yc:Lp);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=j_(gt),pt=j.some(Gt),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 j_(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 Gp(G){return Fp(G).childStart}var V_="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 Cc(G){return G?.parts.some((U)=>U.provenance==="command-substitution")??!1}function bc(G){return G?.parts.some((U)=>U.provenance==="literal"&&U.raw.replace(/^["']/,"").startsWith("-"))??!1}function $p(G,U,j,K,re=!1,oe){let Se=(jo(G,U)||K&&G!=="powershell"&&U[0]?.provenance==="variable")&&Jt(oe,"shell.dynamic-executable",re)?xt("shell.dynamic-executable",V_):null;return Tt(Se,oe)??Bp(G,U,j,re,oe)}function Bp(G,U,j,K,re){if(U.length<2)return null;let oe=U.flatMap((Se,we)=>Cc(Se)?[we]:[]);if(oe.length===0)return null;let de=Mt(U[0]?.text??"");if(de==="git"){let Se=ne(G,U),we=K_(Se);if(Jt(re,"shell.dynamic-structure",K)&&oe.some((gt)=>gt<=we))return Tt(xt("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(Jt(re,"shell.dynamic-structure",K)&&We&&yo.has(We)&&oe.some((gt)=>gt>we&&(mt===-1||gt<mt)))return Tt(xt("shell.dynamic-structure",Ks),re);return null}if(de==="find")return Jt(re,"shell.dynamic-structure",K)&&Y_(U)?Tt(xt("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 Jt(re,"shell.dynamic-structure",K)&&oe.some((We)=>(Se===-1||We<Se)&&(We<U.length-1||!we))?Tt(xt("shell.dynamic-structure",Ks),re):null}if(de==="xargs")return zp(G,U.slice($r(U.map(t)).childStart),"xargs",j,K,re);if(de==="parallel")return zp(G,U.slice(Gp(U.map(t))),"parallel",j,K,re);return null}function zp(G,U,j,K,re,oe){if(U.length===0)return null;let de=q_(U,K);if(jo(G,de)){let we=Tt(xt(`${j}.shell-dynamic`,j==="xargs"?pc:Si),oe);if(we)return we}let Se=Bp(G,de,K,re,oe);if(Se)return Se;if(de[0]?.text==="rm"&&de.slice(1).some((we)=>Cc(we)&&bc(we)))return Tt(xt(`${j}.rm-recursive-force-dynamic`,j==="xargs"?fc:Ci),oe);return null}function q_(G,U){let j=kr(G,U),K=j.rewritten?qt(j.words.map(t)):j.words,re=K[0];return re&&t(re)==="busybox"?K.slice(1):K}function K_(G){let U=1;while(U<G.length){let j=G[U],K=j?t(j):"";if(vn.has(K)){U+=2;continue}if(K.startsWith("-")){U++;continue}return U}return U}function Y_(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=Cc(de);if(j>0){j--;continue}if(re){if(de.text===";"||de.text==="+"){re=!1,U=!0,K=!1;continue}if(Se&&(K||bc(de)))return!0;K=!1;continue}if(!U&&!de.text.startsWith("-")){if(Se&&(oe>1||bc(de)))return!0;continue}if(U=!0,Se)return!0;let we=rr(de.text);if(we>0){j=we;continue}if(Vn(de.text))re=!0,K=!0}return!1}function Sc(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 Up="cmd rmdir /s or del /s outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Z_="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.",X_="cmd rmdir /s or del /s target contains wildcards or variables that cannot be verified safely. Use literal paths within cwd.",J_="cmd rmdir /s or del /s targeting root or home directory is extremely dangerous and always blocked.",Q_="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.",ew="cmd rmdir /s or del /s in home directory is dangerous. Change to a project directory first.",tw={root_or_home_target:{id:"cmd.recursive-delete-root-or-home",reason:J_},git_metadata_target:{id:"cmd.recursive-delete-git-metadata",reason:x},dynamic_target:{id:"cmd.recursive-delete-dynamic-target",reason:X_},home_cwd_target:{id:"cmd.recursive-delete-home-cwd",reason:ew},cwd_self_target:{id:"cmd.recursive-delete-cwd-self",reason:Up},within_anchored_cwd:{id:"cmd.recursive-delete-paranoid",reason:Z_},outside_anchored_cwd:{id:"cmd.recursive-delete-outside-cwd",reason:Up}},nw=/^\/\/?[ck]$/i,Hp=/[&|]+/,rw=/(?:"[^"]*"|[^\s"])+/g,ow=/[\^%!]/,iw=/\\"./s,sw=/(^|\/)[*.]*\*[*.]*$/,aw=/^"?[\\/]+[?.][\\/]/,lw=new Set(["rmdir","rd","del","erase"]),cw=/(?<![\w-])(?:rmdir|rd|del|erase)(?!\w)/i,uw=/\/s(?!\w)/i,dw=/(?<![\w-])(?:cd|chdir|pushd|popd)(?!\w)/i;function jp(G,U){let j=G.map(t),K=j.findIndex((ft)=>nw.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(Hp).map((ft)=>{let pt=ft.match(rw)??[],ht=pt.findIndex((bt)=>lw.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||cw.test(oe)&&uw.test(oe);if(we&&(oe.includes("\\\"")||U.gitBashEscapesBodyQuotes&&oe.includes('"')||U.powerShellRawWords.some((ft)=>iw.test(ft))||Se.some((ft)=>ft.tokens.some((pt)=>aw.test(pt)))))return xt("cmd.recursive-delete-escaped-quote",Q_);let We=jn({...U,allowPaths:U.policy?.destructiveCommandAllowPaths}),mt=de.reduce((ft,pt)=>ft??(pt.recursiveDelete?mw(pt.deleteTokens,We,U.policy):U.analyzeNested(pt.piece)),null),gt=we&&(Se.length===0||ow.test(oe)||dw.test(oe)||oe.includes('"')&&Hp.test(oe));return mt??(gt?go():null)}function mw(G,U,j){return G.slice(1).filter((K)=>!K.startsWith("/")).reduce((K,re)=>K??Tt(Lr(_n(ui(re.replaceAll('"',"")).replace(sw,"$1*"),U),U,j,tw),j),null)}var fw="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.",pw=/^-(?:noprofile|nop|noninteractive|noni|nologo)$/i,gw=/^-(?:executionpolicy|ep)$/i,hw=/^-(?:command|c)$/i,yw=/^(?:--?|[/\u2013\u2014\u2015])(\w+)$/,bw="encodedcommand",Cw=/(?<![\w-])(?:remove-item|ri|rm|rmdir|rd|del|erase)(?![\w-])/i,Sw=/(?<![\w-])(?:[-\u2013\u2014\u2015]{1,2}r(?:e(?:c(?:u(?:r(?:s(?:e|ive?)?)?)?)?)?)?(?!\w)|-[dfipvwx]*r[dfipvwx]*(?!\w))|\/s(?!\w)/i,vw=/[$`]/,Ew="--%";function Vp(G,U){let j=G.map(t),K=j.every((oe,de)=>de===0||oe!==Ew&&Rw(G[de],oe))?Ec(j):void 0;if(K!==void 0)return U(K);if(j.some(xw))return go();let re=j.join(" ");return Cw.test(re)&&Sw.test(re)?xt("powershell.nested-recursive-delete-unread",fw):null}function Ec(G){let U=vc(G,1),j=U===void 0?[]:G.slice(U+1);return j.length>0?j.join(" "):void 0}function vc(G,U){let j=G[U]??"";if(hw.test(j))return U;if(pw.test(j))return vc(G,U+1);return gw.test(j)?vc(G,U+2):void 0}function Rw(G,U){return G?.provenance==="unknown"?!vw.test(U):ro(G,U)}function xw(G){let U=yw.exec(G)?.[1]?.toLowerCase();return U!==void 0&&(U==="ec"||bw.startsWith(U))}var Kp=[{heads:new Set(["rm","rmdir"]),analyze:(G)=>Gs(G.words,Rc(G))},{heads:new Set(["cmd"]),analyze:(G)=>jp(G.words,{...Rc(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)=>Vp(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,xc(G))},{heads:new Set(["find"]),analyze:(G)=>Pf(G.words,{...Rc(G),envAssignments:G.envAssignments,analyzeTokens:G.analyzeChildTokens})},{heads:new Set(["xargs"]),analyze:(G)=>mp(G.words,{...qp(G),analyzeChild:G.analyzeChild,analyzeNested:(U,j)=>yr(G.options.analyzeNested(U,j))})},{heads:new Set(["parallel"]),analyze:(G)=>wp(G.words,{...qp(G),analyzeChild:G.analyzeChild,analyzeNested:(U,j)=>yr(G.options.analyzeNested(U,j))})}];function qp(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 Rc(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 xc(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 Xp(G){return Kp.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=kn(Pt);if(Ot)return K?.recordSegment({type:"dangerous-text",token:Pt,matched:!0,reason:Ot.reason}),dn(Ot);if(j.strict)return bn(K);let zt=ps(ht,oe(pt.words));if(zt){j.budget.charge("derivedTokens",zt.length);let tn=j.analyzeNested(zt.join(" "),{effectiveCwd:pt.cwd===void 0?j.effectiveCwd:pt.cwd,envAssignments:new Map([...j.envAssignments??[],...ft.envAssignments,...pt.envAssignments])});if(tn)return tn}}let yt=pt.rewritten?qt(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 Et=Mt(St),_t=pt.cwd===null?void 0:pt.cwd??mt,At=pt.cwd===null?void 0:gt,It=pt.cwd===void 0?j.effectiveCwd:pt.cwd,wt=de?de.allowTmpdirVar:!li(vt,j.environment),Lt=$p(re,pt.words,j.environment,U===0,j.strict,j.policy);if(Lt)return K?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:Lt.reason}),dn(Lt);let Bt=ks(bt,j.policy);if(Bt){for(let Pt of[Bt.childIndex,...Bt.alternativeChildIndices]){Yp(Ct.wrapperNormalizationBudget);let Ot=yt.slice(Pt);K?.recordSegment({type:"transparent-wrapper",wrapper:Bt.wrapper,output:oe(Ot)});let zt=Eo(Ot,U,{...Ct,effectiveCwd:It,envAssignments:vt});if(zt)return zt}return null}let en=we?void 0:Et==="eval"?zs(yt):Et==="trap"&&!Se?ip(yt):void 0;if(Se&&de&&Et==="eval"){if(en?.kind==="dynamic")return vo(de,j.policy);if(en?.kind==="literal"){let Pt=j.analyzeNested(en.source,{effectiveCwd:It,envAssignments:vt});if(Pt)return Pt}return Ro(de,j.policy)}if(en?.kind==="dynamic"&&(j.strict||!j.commandView||!dc(j.commandView)))return bn(K);if(en?.kind==="literal"){K?.recordSegment({type:"recurse",reason:Et==="eval"?"shell-eval":"shell-trap",innerCommand:en.source,depth:U+1});let Pt=j.analyzeNested(en.source,{effectiveCwd:It,envAssignments:vt,functionDefinitions:j.functionDefinitions});if(Pt)return Pt}if(Se?Kt.has(Et):Qp(St,Et)){if(nr(bt))return null;if(Se&&de){let Pt=$n(bt);if(Pt){if(de.dynamicSourceInput??de.dynamicInput){let zt=vo(de,j.policy);if(zt)return zt}if(bi(Pt)){let zt=vo(de,j.policy);if(zt)return zt}return j.analyzeNested(Pt,{effectiveCwd:It,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=$n(bt),Ot=Pt?j.analyzeNested(Pt,{effectiveCwd:It,envAssignments:vt}):or(yt).kind==="dynamic"?bn(K):null;if(Ot)return Ot}if(de===void 0){let Pt=Aw(bt,vt,It,j,K,U);if(Pt)return Pt;let Ot=$n(bt);if(Ot){let Vr=$s(yt,Ot);if(Vr.kind==="dynamic")return bn(K);let la=Vr.kind==="literal"?Vr.source:sp(yt,Ot),Zc=Tw(la);K?.recordSegment({type:"shell-wrapper",wrapper:Et,innerCommand:Zc}),K?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:Zc,depth:U+1});let Xc=j.analyzeNested(la,{effectiveCwd:It,envAssignments:vt});if(Xc)return Xc;return bi(la)?bn(K):null}let zt=or(yt,j.strict?void 0:j.shellAssignments);if(zt.kind==="dynamic")return bn(K);if(zt.kind==="literal")return Ys(zt.source,It,vt,j,K,U);let tn=ap(yt,j.commandView?.redirections??[],j.hasPipelineInput??!1,j.literalShellInput);if(tn.kind==="dynamic")return bn(K);if(tn.kind==="literal")return K?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:tn.source,depth:U+1}),j.analyzeNested(tn.source,{effectiveCwd:It,envAssignments:vt})}}if(!de&&(Et==="source"||Et===".")){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 bn(K)}let Ot=Pt===null?1:3,zt=bt[Ot]==="--"?Ot+1:Ot,tn=j.commandView?yt[zt]:void 0;if(!tn)return null;if(tn.provenance==="literal")return Ys(tn.text,It,vt,j,K,U);if(j.strict||!j.commandView||!dc(j.commandView))return bn(K)}if(In.has(Et)&&!we){if(!de&&j.strict&&Sc(fi(bt),yt))return bn(K);let Pt=bf(bt,(zt)=>yr(j.analyzeNested(zt,{effectiveCwd:It,envAssignments:vt}))),Ot=Tt(Pt,j.policy);if(Ot)return K?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:Ot.reason}),dn(Ot)}if(Ln(Et)&&!we){if(!de&&j.strict&&Sc(cs(bt),yt))return bn(K);let Pt=fm(bt);if(Se&&de)return ww(Et,Pt,It,vt,j,de);if(Pt){let Ot=Jt(j.policy,"interpreter.one-liner-paranoid",!!j.paranoidInterpreters);if(K?.recordSegment({type:"interpreter",interpreter:Et,codeArg:Pt,paranoidBlocked:Ot}),Ot){let tn=Tt(xt("interpreter.one-liner-paranoid",ti),j.policy);if(tn)return dn(tn)}if(wl(Et,Pt))return null;K?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:Pt,depth:U+1});let zt=j.analyzeNested(Pt,{effectiveCwd:It,envAssignments:vt});if(zt&&!Jp(zt,Pt))return zt;if(ni(Pt,void 0,!j.strict)){let tn=Tt(xt("interpreter.dangerous-command",so),j.policy);if(tn)return K?.recordSegment({type:"dangerous-text",token:Pt,matched:!0,reason:so}),dn(tn)}K=void 0}}if(Et==="busybox"&&bt.length>1)return Yp(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:It,envAssignments:vt});let Ut=de?null:Tt(Rf(Et,bt),j.policy);if(Ut)return K?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:Ut.reason}),dn(Ut);let Ft=K===Ct.trace?Ct:{...Ct,trace:K},ln={words:yt,parsedWords:pt.words,head:Et,cwd:_t,originalCwd:At,envAssignments:vt,allowTmpdirVar:wt,dynamicArguments:pt.words.some((Pt)=>Pt.provenance==="command-substitution"),depth:U,effectiveCwd:It,options:Ft,analyzeChildTokens:(Pt,Ot)=>Se&&de?wc(Pt,U,Ft,{...de,cwd:Ot??void 0,effectiveCwd:Ot??void 0}):yr(Eo(qt(Pt),U+1,{...Ft,child:void 0,commandView:void 0,effectiveCwd:Ot,envAssignments:vt}))??A(Pt,Ft.policy.rules),analyzeChild:(Pt,Ot)=>wc(Pt,U,Ft,Ot)},Zt=de&&(Et==="xargs"||Et==="parallel")?void 0:Xp(Et);if(Et==="rm"||Et==="xargs"||Et==="parallel")K?.recordSegment({type:"tmpdir-check",tmpdirValue:vt.has("TMPDIR")||j.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:wt});let Xt=K&&Et==="git"?Xf(ln.words,xc(ln)):void 0,Sn=Zp(Xt?Xt.match:Zt?.(ln)??null,j.policy);if(K)Iw(ln,Sn,Xt?.relaxation??null);if(Sn)return dn(Sn);if(Se&&de&&(Et==="rm"||Et==="rmdir")){if(!(Et==="rm"&&(tr(bt)||de.dynamicRmInput)))return null;return(de.dynamicRmInput?Ro(de,j.policy):null)??Pw(de,j.policy)}let Yn=Zt!==void 0&&!Ow.has(Et),vr=!de&&!Yn&&!Fi.has(Et),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 zt=Zp(_w(bt,Pt,U,Ft,_t,At,It,vt),j.policy);if(zt)return K?.recordSegment({type:"fallback-scan",tokensScanned:To??[],embeddedCommandFound:Mt(Ot)}),dn(zt)}if(K?.recordSegment({type:"fallback-scan",tokensScanned:To??[]}),we&&de&&!de.wrappedByTransparent)return null;let Pn=A(bt,j.policy.rules);if(K?.recordSegment({type:"custom-rules-check",rulesChecked:j.policy.rules.length>0,matched:!!Pn,reason:Pn?.reason}),Pn)return dn(Pn);return Se&&de?Ro(de,j.policy):null}function wc(G,U,j,K){return yr(Eo(qt(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 _w(G,U,j,K,re,oe,de,Se){for(let we of zn(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(Qp(We,mt)||Xp(mt)!==void 0&&mt!=="xargs"&&mt!=="parallel"||we.wrappedByTransparent&&K.policy.rules.length>0)K.budget.charge("derivedTokens",G.length-U);let ft=wc(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 ww(G,U,j,K,re,oe){if(!U)return Ro(oe,re.policy);if(Jt(re.policy,"interpreter.one-liner-paranoid",!!re.paranoidInterpreters)){let Se=Tt(xt("interpreter.one-liner-paranoid",ti),re.policy);if(Se)return dn(Se)}if(wl(G,U))return Ro(oe,re.policy);let de=re.analyzeNested(U,{effectiveCwd:j,envAssignments:K});if(de&&!Jp(de,U))return de;if(ni(U,void 0,!re.strict)){let Se=Tt(xt("interpreter.dangerous-command",so),re.policy);if(Se)return dn(Se)}return Ro(oe,re.policy)}function Jp(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?dn(j):null}function Ro(G,U){let j=G.dynamicSourceInput&&G.dynamicSourceMatch?Tt(G.dynamicSourceMatch,U):null;return j?dn(j):null}function Pw(G,U){let j=G.dynamicInput&&G.rmDynamicMatch?Tt(G.rmDynamicMatch,U):null;return j?dn(j):null}function Aw(G,U,j,K,re,oe){let de=wf(G);if(de.argvSource?.kind==="absent")return bn(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 bn(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?bn(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 Tw(G){let U=G[0];return G.length>=2&&(U==='"'||U==="'")&&G.at(-1)===U?G.slice(1,-1):G}function Iw(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 Yp(G){if(G.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");G.iterations++}function dn(G){return{reason:G.reason,ruleId:G.id,intent:G.intent}}function bn(G){return G?.recordSegment({type:"error",message:di}),dn(go())}function Qp(G,U){return Kt.has(U)||G==="$SHELL"||G==="${SHELL}"||Kt.has(kt(U))}function Zp(G,U){return G?.id.startsWith("custom.")||G?.id==="raw-text.dangerous-command"?G:Tt(G,U)}var kw=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,Ow=new Set(["powershell","pwsh"]),Mw=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function Dw(G,U){let j=ng(G,U);if(j.length===0)return!1;let K=j[tg(j)];if(K==="cd"||K==="pushd"||K==="popd")return!0;return kw.test(G.join(" "))}function eg(G,U,j,K,re){if(G.dialect==="powershell"){let St=Nw(G.words,re);if(St.kind==="none")return;if(!U||St.kind==="unknown")return null;return _c(Gw(St.target),U,j.paths)}let oe=G.words.map(t),de=oe.some((St)=>/^CDPATH\+?=/.test(St));if(!Dw(oe,j))return de?null:void 0;if(!U)return null;let Se=ng(oe,j,U),we=tg(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 _c(cn(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?qn(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 _c(cn(vt),U,j.paths)}function _c(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 Nw(G,U){let j=Lw(G[0])?1:0,K=G[j];if(!Ww(K,j===1))return{kind:"none"};let re=K.text.toLowerCase(),oe=re.split(/[\\/]/).pop()??re;if(!Mw.has(oe))return{kind:"none"};if(re!==oe||oe==="pop-location"||oe==="popd")return{kind:"unknown"};return Fw(G.slice(j+1),U)}function Lw(G){return G?.provenance==="literal"&&!G.quoted&&G.raw===G.text&&(G.text==="&"||G.text===".")}function Ww(G,U){return G?.provenance==="literal"&&(U||!G.quoted&&G.raw===G.text)}function Fw(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 Gw(G){return G.includes("::")?void 0:G.replaceAll("\\","/")}function tg(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 ng(G,U,j){let K=zw(G);return dr([...K],U,j)}function zw(G){let U=0;while(U<G.length){let j=G[U];if(j!=="{"&&j!=="("&&j!=="$(")break;U++}return G.slice(U)}var qw="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 Oc(G,U,j,K){if(U>=a.recursionDepth.cap)return j.trace?.recordSegment({type:"error",message:Un}),{reason:Un,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:Un}),{reason:Un,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 kc(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 lg(G,j),{reason:po,segment:G,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"}}if(j.strict&&re.status==="partial")return lg(G,j),{reason:po,segment:G,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"};if(re.issues.some((We)=>We.code.includes("quote")))return kc(G,j);let de=j.cwd,Se=j.effectiveCwd!==void 0?j.effectiveCwd:j.cwd,we=Gf(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=Kw(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 Et=br(ft)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:br(Se)?we??St:St,_t=Ur(Et.connector)||Ur(ft);if(mt.kind==="function"){let Ut=bt.flatMap((ln)=>{let Zt=Hr(ln);return Zt.functionDefinitions.set(mt.name,mt.body),Pc(ln,[Zt],pt,ft==="&",Ur(ft))}),Ft=Ac(Ut,[],Et.skippedSuccessStates,Et.skippedFailureStates,Et.connector,ft);oe=Ft.states,de=Ft.conditionalStates,Se=void 0;continue}if(mt.kind==="group"){let Ut=[],Ft=[];for(let Zt of bt){let Xt=Js(mt.body,U,j,K,[Hr(Zt)]);if(Xt.result)return Xt;if(Ut.push(...Pc(Zt,Xt.states,pt,ft==="&",Ur(ft))),_t)Ft.push(Zt,...pt?Xt.states.map((Sn)=>Zs(Zt,Sn)):Xt.states)}let ln=Ac(Ut,Ft,Et.skippedSuccessStates,Et.skippedFailureStates,Et.connector,ft);oe=ln.states,de=ln.conditionalStates,Se=void 0;continue}if(mt.kind!=="command")continue;let At=yP(G.nodes[We-1]),It=j.trace?.flattenNested?j.trace.currentSegmentIndex:j.trace?.allocateSegment(),wt=G.nodes[We-2],Lt=br(Se)&&wt?.kind==="command"?op(wt)??Zw(wt):void 0,Bt=[],en=[];for(let Ut of bt){let Ft=Xw(mt,U,j,K,[Hr(Ut)]);if(Ft.result)return{result:Ft.result,states:oe};let ln=G.dialect==="powershell"?Ft.states:Ft.states.map((Zt)=>Zs(Ut,Zt));for(let Zt of ln){let Xt=Hr(Zt),Sn=eP(mt,U,j.trace?{...j,trace:cg(j.trace,It)}:j,K,Xt,br(Se),Lt);if(Sn)return{result:Sn,states:oe};let Yn=xP(mt,Xt.functionDefinitions);if(Yn)j.budget.charge("derivedTokens",Qs(Yn));let vr=Yn?U+1>=a.recursionDepth.cap?Tc(mt.displayText,j,[Xt]):Js(Yn,U+1,j,K,[Xt]):{result:null,states:EP(mt,Xt).flatMap((Pn)=>bP(mt,Zt,Pn,At))};if(vr.result)return vr;Bt.push(...Pc(Ut,vr.states,pt,ft==="&",Ur(ft)));let To=typeof Xt.effectiveCwd==="string"&&Xt.effectiveCwd!==Zt.effectiveCwd&&mt.redirections.every((Pn)=>["<",">",">>",">|"].includes(Pn.operator)&&Pn.target?.text==="/dev/null");if(_t&&(At||!To))en.push(Ut),en.push(...vr.states.map((Pn)=>pt?Zs(Ut,Pn):Pn))}}let Sr=Ac(Bt,en,Et.skippedSuccessStates,Et.skippedFailureStates,Et.connector,ft);oe=Sr.states,de=Sr.conditionalStates,Se=void 0}return{result:null,states:oe}}function Kw(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"&&Yw(G,U)}function Pc(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 Yw(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(Jw(j))return!0;return j.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function br(G){return G==="|"||G==="|&"}function Zw(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 Ac(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 cg(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 Xw(G,U,j,K,re){let oe=G.nested.map((de)=>({program:de,depth:U}));if(G.dialect==="powershell"){let de=Qw(G);if(de){if(U+1>=a.recursionDepth.cap)return Tc(de,j,re);let Se=y(de,"powershell");if(Se.status==="limited")return Tc(de,j,re);if(Se.status!=="complete")return rg(oe,j,K,re);j.budget.charge("derivedTokens",Qs(Se)),oe.push({program:Se,depth:U+1})}}return rg(oe,j,K,re)}function Jw(G){let U=G.words[0];return U?.provenance==="variable"&&G.words.at(-1)?.text==="="?U.text.toLowerCase():void 0}function rg(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 Qw(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 Tc(G,U,j){return U.trace?.recordSegment({type:"error",message:Un}),{result:{reason:Un,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"},states:[...j]}}function eP(G,U,j,K,re,oe,de){let Se={...j,environment:{...j.environment,env:re.shellGitContextState.env,paths:iP(j.environment.paths,re.createdDirectories,j.budget)}},we=dP(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"};ug(G,re,"before-consumer",Se.environment.paths,Se.budget);let We=ne(G.dialect,G.words),mt=We.map(t),gt=G.displayText,ft=Wf(We,re.shellGitContextState),pt=$f(ft,re.shellGitContextState);if(G.dialect==="powershell"){let bt=Tt(uf(G,oe,wP(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 _P(gt,bt)}if(mt.length===1&&mt[0]?.includes(" ")&&!jo(G.dialect,G.words)){let bt=Tt(kn(mt[0]),Se.policy),Ct=bt!==null&&!Se.strict&&cm(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=og(G,we,re,pt,de,Se);if(vt)return vt;return ic(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=Oc(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?cg(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=og(G,we,re,pt,de,Se);if(yt)return yt;return ic(ft,re.shellGitContextState),null}function og(G,U,j,K,re,oe){let de=mP(G,U,j,K??new Map,oe);if(de)return de;return ug(G,j,"after-consumer",oe.environment.paths,oe.budget),j.literalHeredocFiles.clear(),rP(G,U,j,oe.environment.paths,oe.budget),sP(G,j,oe.environment.paths,oe.budget),gP(G,j,re,oe.environment,oe.trace),null}var tP=new Set([">>","<>"]);function ug(G,U,j,K,re){for(let de of G.redirections){if(!(j==="before-consumer"?nP(de):tP.has(de.operator)))continue;ig(de.target,U,K,re)}if(j!=="before-consumer"||!an(G.words[0],"tee"))return;let oe=mg(G.words.slice(1));if(!oe)return;for(let de of oe.operands)ig(de,U,K,re)}function nP(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 ig(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 rP(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 oP(G,j.shellGitContextState.shellAssignments)){let Se=ei(de,j.effectiveCwd,K,re);if(!Se||!mm(Se))continue;if(!j.literalHeredocFiles.has(Se)&&j.literalHeredocFiles.size>=a.trackedHeredocFiles.cap)throw new s("trackedHeredocFiles");j.literalHeredocFiles.set(Se,oe.body)}}function oP(G,U){let j=Ic(cP(G.redirections)?.target,U),K=j===void 0?[]:[j];if(an(G.words[0],"cat"))return lP(G.words)?K:[];if(!an(G.words[0],"tee"))return[];let re=mg(G.words.slice(1),U);if(!re||re.append||re.hasUnsupportedOptions)return[];let oe=re.operands.map((de)=>Ic(de,U));if(!oe.every((de)=>de!==void 0))return[];return[...oe,...K]}function Ic(G,U){if(uP(G))return G.text;return(G&&qn(G,U))??void 0}function iP(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}${Vw}`))};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 sP(G,U,j,K){if(U.shellGitContextState.bodyDepth>0||!an(G.words[0],"mkdir"))return;let re=G.words.slice(1).map((We)=>Ic(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("..")||!Bw(We)&&!we)continue;let mt=Nt(jw(we??"",We),j,K);if(Se?aP(mt,j):j.isDirectory($w(mt))&&dg(mt,j))U.createdDirectories.add(mt)}}function aP(G,U){let j=Hw(G).root,K=G.slice(j.length).split(/[\\/]+/).filter(Boolean),re=(de)=>Uw(j,...K.slice(0,de+1)),oe=K.findIndex((de,Se)=>!U.isDirectory(re(Se)));return oe===-1||dg(re(oe),U)}function dg(G,U){try{return U.entryKind(G)==="missing"}catch{return!1}}function lP(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 cP(G){let U=G.findLast((j)=>(j.fd??([">",">|",">>",">&"].includes(j.operator)?1:0))===1);return U?.operator===">"||U?.operator===">|"?U:void 0}function mg(G,U=new Map){let j=[],K=!0,re=!1,oe=!1;for(let de of G){if(de.provenance!=="literal"&&qn(de,U)===null)return;if(K&&an(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 uP(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 an(G,U){return G?.text===U&&G.raw===U&&G.provenance==="literal"&&!G.quoted}function Mc(G){return G.quotedDelimiter||!/[$`\\]/.test(G.body)}function dP(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(!Mc(K.heredoc)&&(!U||re))return qw;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&&sg(we.target));if(an(G.words[0],"cat"))return oe?Br:void 0;if(an(G.words[0],"tee"))return oe||G.words.slice(1).some(sg)?Br:void 0;let de=G.words[0],Se=G.words[1];if(an(de,"git")&&(an(Se,"apply")||an(Se,"commit")))return;if(an(de,"gh")&&(an(Se,"pr")||an(Se,"issue"))&&an(G.words[2],"create"))return;return Br}function sg(G){return G?.parts.some((U)=>U.provenance==="command-substitution"&&U.raw.startsWith(">("))??!1}function mP(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(pP(G,oe,j,K,re))return null;let Se=fP(G,oe,re);if(Se!==void 0)return Se?{reason:Se.reason,segment:G.displayText,ruleId:Se.id,intent:Se.intent}:null;let we=kc(de.length===oe.length?de.join(`
|
|
43
|
-
`):G.source,re);return we?{...we,segment:G.displayText}:null}function fP(G,U,j){let K=U.length===1?U[0]:void 0;if(!K?.heredoc||!Mc(K.heredoc)||K.fd!==void 0&&K.fd!==0)return;let re=an(G.words[0],"uv")&&an(G.words[1],"run")?G.words.slice(2):G.words,oe=re[0];if(oe?.provenance!=="literal"||!Ln(oe.text))return;let de=re.findIndex((gt)=>an(gt,"-"));if(!re.slice(1,de===-1?void 0:de).every((gt)=>gt.provenance==="literal"&>.text.startsWith("-")))return;let we=K.heredoc.body,We=Jt(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(xt("interpreter.one-liner-paranoid",ti),j.policy);if(gt)return gt}if(!ni(we,void 0,!j.strict))return null;let mt=Tt(xt("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 pP(G,U,j,K,re){let oe=U.length===1?U[0]:void 0;if(!oe?.heredoc||!Mc(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||!Kt.has(we)&&!Kt.has(kt(we)))return!1;return nr(Se)}function gP(G,U,j,K,re){let oe=eg(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 hP=new Set(["fi","done","esac"]);function yP(G){return G?.kind==="command"&&G.words.length===1&&G.words[0]?.raw==="!"}function bP(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&&hP.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 CP(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 SP=/^[A-Za-z_][A-Za-z0-9_]*$/,vP=8;function EP(G,U){let j=G.words[1]?.text;if(G.dialect!=="posix"||G.words[0]?.text!=="for"||j===void 0||!SP.test(j))return[U];let K=G.words.slice(3);if(!(G.words[2]?.text==="in"&&K.length>=1&&K.length<=vP&&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:zf(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)=>RP(K,j)))U.push(j);if(U.length>a.controlFlowStates.cap)throw new s("controlFlowStates")}return U}function RP(G,U){return G.effectiveCwd===U.effectiveCwd&&CP(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&&ag(G.shellGitContextState.bodyAssignments,U.shellGitContextState.bodyAssignments)&&ag(G.createdDirectories,U.createdDirectories)}function ag(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 xP(G,U){let j=Vo(G);return j===void 0?void 0:U.get(j)}function _P(G,U){if(!U)return null;return{reason:U.reason,segment:G,ruleId:U.id,intent:U.intent}}function wP(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 kc(G,U){let j=Tt(kn(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 lg(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 PP=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function fg(G,U,j,K){let re=Oc(G,0,{...U,...Ue(U),budget:U.budget??An(),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 pg(G,U,j){try{return{decision:G()}}catch(K){let re=AP(K,U,j);if(!re)throw K;return re}}function AP(G,U,j){if(!(G instanceof s)||!PP.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 TP=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),Nc=new Set(["cc-safety-net","ccsn"]),IP=new Set(["bunx","npx","pnpx"]),kP=new Set(["pnpm","yarn"]),OP=new Set(["npm","pnpm","yarn"]),MP=new Set(["bun","node"]);function ta(G,U,j={}){if(Nc.has(G))return 0;if(IP.has(G)){if(j.broad)return Dc(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&&OP.has(G)&&j.broad&&U[K]==="exec"){let re=Dc(U.slice(K+1));return re===null?null:K+1+re}if(kP.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=Dc(U.slice(K+1));return re===null?null:K+1+re}if(MP.has(G)){let re=j.broad&&K!==-1?K:0;if(gg(U[re]))return re+1;if(G==="bun"&&U[re]==="run"&&gg(U[re+1]))return re+2}return null}function Dc(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 Nc.has(G);if(U===0)return!1;let j=G.slice(U+1);if(j===""||j.includes("/")||j.includes(":"))return!1;return Nc.has(G.slice(0,U))}function gg(G){let U=G?.replaceAll("\\","/");return[...TP].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 hg(G,U,j){let K=hn(G,"input-candidate");if(!K)return null;let re=co(K.shell,G.invocation.context.executionCwd,U,j,{findSegmentTarget:(oe)=>DP(oe,U),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return re?{target:re}:null}function DP(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.",NP=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Sg(G,U,j){let K=$P(G.invocation.context,U,j);if(G.invocation.route.kind==="patch")return yg(G.paths,!1,G.invocation.context.executionCwd,K,U,j);let re=hn(G,"input-candidate");if(G.invocation.route.kind==="command")return re?bg(re.shell,G.invocation.context.executionCwd,K,U,j):null;if(G.invocation.route.kind==="unknown"&&re){let oe=bg(re.shell,G.invocation.context.executionCwd,K,U,j);if(oe)return oe}return yg(G.paths,G.invocation.route.kind==="grep"||G.invocation.route.kind==="glob"||Ii(G.invocation.toolName),G.invocation.context.executionCwd,K,U,j)}function yg(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 bg(G,U,j,K,re){let oe=co(G,U,K,re,{findSegmentTarget:(de,Se)=>LP(de,Se,j,K,re)?.target??null,isRedirectionTarget:(de,Se)=>vi(de,Se.cwd,j,K,re),findMalformedTarget:(de)=>zP(de,U,j,K,re)?.target??null});return oe?{target:oe}:null}function LP(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"&&WP(Se)){let we=FP(Se).find((We)=>Cg(gn(We,U.variables),U.cwd,j,K,re));if(we)return{target:we}}if(de==="find"){if(Ds(oe,1)||Zl(oe,K)){let We=(pi(qt(oe))??qt(["."])).find((mt)=>{let gt=gn(mt.text,U.variables);return vi(gt,U.cwd,j,K,re)||Cg(gt,U.cwd,j,K,re)})?.text;if(We)return{target:We}}}if(de==="mv"){let we=vs(Se).sources.find((We)=>BP(gn(We,U.variables),U.cwd,j,K,re));if(we)return{target:we}}if(GP(oe,de))return null;for(let we of[...G,...oe])for(let We of vg(we))if(vi(gn(We,U.variables),U.cwd,j,K,re))return{target:We};return null}function WP(G){return G.some((U)=>U==="--recursive"||U.startsWith("-")&&!U.startsWith("--")&&/[rR]/.test(U.slice(1)))}function FP(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 GP(G,U){if(!NP.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 zP(G,U,j,K,re){for(let oe of G.split(/\s+/))for(let de of vg(oe))if(vi(de,U,j,K,re))return{target:de};return null}function vg(G){let U=G.trim().replace(/^['"]|['"]$/g,""),j=U.indexOf("=");return j===-1||j===U.length-1?[U]:[U,U.slice(j+1)]}function $P(G,U,j){let K=(Se)=>Ei(un(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=ru(G,U,K,re,(de)=>Ei(de)===Li);return oe!==null&&j.files.has(Ei(oe))}function Cg(G,U,j,K,re){return j.directoriesAndAncestors.has(Ei(un(G,U,K,re)))}function BP(G,U,j,K,re){let oe=Ei(un(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 Mg,resolve as aa,win32 as UP}from"node:path";import{fileURLToPath as HP}from"node:url";var Dg="Access to a sensitive path is not allowed.",Ng=new Set(["echo","printf"]),jP=new Set(["find"]),VP=new Set(["!","do","elif","else","if","then","until","while"]),qP=new Set(["-exec","-execdir"]),KP=new Set([";","+"]),YP=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),ZP=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Lg=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),XP=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),JP=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"]),zc=new Set(["-c","-e","-r","-E","--eval","--exec"]),QP=new Map([["c",new Set(["bash","sh","zsh","dash","ksh","python"])],["e",new Set(["node","deno","bun","ruby","perl","rscript","osascript"])],["E",new Set(["perl"])],["r",new Set(["php"])]]),$c=new Set(["grep","rg"]),Wg=new Set(["files-with-matches","files-without-match","count","quiet"]),eA=new Set([...Wg,"ignore-case","fixed-strings","hidden"]),tA=new Set(["wc",...$c]),nA=new Set(["cd","grep","head","openssl","tail","tailscale"]),rA=/^(?:-[lwcm]+|--(?:lines|words|bytes|chars))$/,oA=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),iA=new Set(["commit","merge","notes","stash","tag"]),sA=new Set(["-m","--message"]),aA=new Set(["--grep"]),lA=new Set(["powershell","pwsh"]),Eg=new Set(["jq","gojq","jaq"]),Rg="f",xg="file",cA="files",uA=new Set(["e","f"]),dA=new Set(["regexp","file"]),mA=new Set(["e","f","A","B","C","m"]),fA=new Set(["regexp","file","after-context","before-context","context","max-count"]),Lc="__CC_SAFETY_NET_PIPE_INPUT__",Fc=/[\w./~@+-]*[./~][\w./~@+-]*/g,pA=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,gA=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,hA=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,_g=/\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,wg=/\b(?:system|exec|spawn|popen)\s*$/,yA=/\b(?:eval|exec)\s*\(/g,bA=/\b(?:eval|exec)\s*$/,CA=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 Pg(G,U,j,K,re,oe){for(let de of G){let Se=de.target;if(DT(Se,de.cwd,U?.denyPaths??[],j,K,re))return{target:Se,ruleId:"secret.deny-path"};if(oe&&!oe.has(Se))continue;let we=OT(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(Xg(Se,de.cwd,K,re)))continue;if(We&&oe?.get(Se)==="data")continue;if(We&&(de.isRedirectionWriteTarget===!0||oe?.get(Se)==="write")&&!Se.includes("$")&&!sa(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)&&!sa(Se,de.cwd,K,re))continue;if(!we.startsWith("secret.cli.")&&NT(Se,de.cwd,U?.allowPaths??[],j,K,re))continue;return{target:Se,ruleId:we}}}return null}function Fg(G,U,j,K,re={}){let oe=Ag(G,j,K),de=Pg(oe,U,G.invocation.context.configCwd,j,K);if(de===null||de.ruleId==="secret.deny-path"||re.strict!==!1)return de;let Se=Ag(G,j,K,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}),we=new Map;Se.forEach((ht)=>Gg(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=Pg(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"&&SA(G,j)?null:pt}function SA(G,U){let j=hn(G,"input-candidate")??hn(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=Kn(K);if(re.length===0)return!1;let oe=mn(re[0]??"").toLowerCase();if(G.invocation.route.kind==="unknown")return j.program.dialect==="powershell"&&(oe==="ls"||oe==="stat");return Bc(oe,re.slice(1))}function Bc(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("-")||rA.test(j));if($c.has(G))return vA(G,U);if(G!=="find")return!1;return!U.some((j)=>YP.has(j))}function vA(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)&&!eA.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 Wg.has(We.slice(2));return oe(We)&&re.test(We.slice(1).split(K)[0]??"")})}function Ag(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=hn(G,"input-candidate");return[...de?Ao(de.shell,G.store,K,U,re,j,EA(de)):[],...oe==="unknown"?G.paths.map((Se)=>({target:Se,cwd:re})):[]]}function EA(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})),...pT(er(G.source,K),U,j,K,re,oe)],we=(bt)=>er(DA(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,Et,_t)=>{if(bt.length===0)return null;let At=pt(_t);if(At.commandHoldsPipe)gt.push(...bt);if(ft.push(mn(zg(Kn(bt))[0]??"").toLowerCase()),Se.push(...xi(bt,U,We||St==="|"||St==="|&"?{...At,segmentMayFeedReader:!0}:At,K,Ct.cwd,oe,Et)),vt!==null)Se.push(..._A(vt,bt,U,At,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(...$g(bt.consumer,[bt.body],U,St,K,Ct.cwd,oe,(Et)=>wA(bt.consumer??[],Et,U,St,K,Ct.cwd,oe)))}if(bt.targetOrder==="legacy-segment")return Ml;return Se.push({target:we(bt.target),cwd:Ct.cwd,...bt.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}});let ht=new Set(gt.flatMap(Gg)),yt=We||/\$\(|`/.test(G.source)||!ft.every((bt)=>nA.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 Gg(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 oa(G,U,j,K,re,oe,de=!1){let Se=U.getShellSyntax(G,de?U.getCommandProgram(G,"powershell"):void 0);if(Se.status==="structural-limit")throw new b;return Se.status==="complete"?Ao(Se,U,j,K,re,oe,de):null}function xi(G,U,j,K,re,oe,de){let Se=(wt)=>({target:wt,cwd:re}),we=G.findIndex((wt)=>!VP.has(wt));if(j.skipMetadataOnlySegments===!0&&we>0)return xi(G.slice(we),U,j,K,re,oe,new Set([...de??[]].map((wt)=>wt-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((wt)=>Dn("for",wt)).map((wt)=>({...Se(wt),loopVariable:We}));if(de?.size){let wt=G.filter((Lt,Bt)=>!de.has(Bt));if(Eg.has(mn(Kn(wt)[0]??"").toLowerCase()))return[...G.filter((Lt,Bt)=>de.has(Bt)).map(Se),...xi(wt,U,j,K,re,oe)]}let mt=MA(G).map(Se),gt=Kn(G);if(gt.length===0)return mt;let ft=gt[0]??"",pt=mn(ft).toLowerCase(),ht=gt.slice(1),yt=j.segmentMayFeedReader===!0||j.commandHoldsPipe===!0||j.displayOperandsAreCapturedOutput===!0,bt=yt&&tA.has(pt);if(j.skipMetadataOnlySegments===!0&&!bt&&Bc(pt,ht))return mt;let Ct=xA(ft,pt,ht);if(Ct)return[...mt,...Ct.map(Se)];if(Ng.has(pt))return j.displayOperandsAreCapturedOutput===!0?[...mt,...Bg(G).map(Se)]:mt;if(pt==="eval")return[...mt,...oa(ht.join(" "),U,j,K,re,oe)??ht.map(Se)];let vt=lA.has(Mt(ft))?Ec(gt):void 0;if(vt!==void 0)oe.charge("derivedTokens",gt.length);let St=vt===void 0?null:oa(vt,U,j,K,re,oe,!0);if(St?.length)return[...mt,...St];if(pt==="export")return[...mt,...ht.flatMap((wt)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(wt)?[wt.slice(wt.indexOf("=")+1)]:Dn(pt,wt)).map(Se)];if(pt==="git")return[...mt,...LA(ht).map(Se)];if(pt==="gh")return[...mt,...Gc(pt,ht,oA).map(Se)];if(Eg.has(pt))return[...mt,...NA(ht).map(Se)];if($c.has(pt))return[...mt,...ET(ht).map(Se)];if(jP.has(pt))return[...mt,...FA(ht,U,j,K,re,oe).map(Se)];if(pt==="mkdir"||pt==="touch"){let wt=new Set(G.filter((Bt,en)=>de?.has(en))),Lt=j.segmentMayFeedReader!==!0&&!(pt==="touch"&&ht.some((Bt)=>/^(?:--r|-[^-]*r)/.test(Bt)));return[...mt,...ht.flatMap((Bt)=>Dn(pt,Bt).map((en)=>Lt&&!Bt.startsWith("-")&&!wt.has(Bt)?{...Se(en),isCreatedPath:!0}:Se(en)))]}if(In.has(pt))return[...mt,...ht.flatMap((wt)=>Dn("awk",wt)).map(Se),...ht.flatMap((wt)=>zA(wt,U,j,K,re,oe)),...ht.flatMap($A).map(Se)];if(pt==="curl")return[...mt,...ht.filter((wt,Lt)=>Hg(wt)===null&&Ug(ht[Lt-1])===null).flatMap((wt)=>Dn(pt,wt)).map(Se),...WA(ht).map(Se)];if(lo(pt)){let wt=si.has(pt)?En([pt,...ht]):null;if(wt!==null&&wt.command!==null&&wt.commandIndex!==null){let Lt=U.getShellSyntax(wt.command);if(Lt.status==="structural-limit")throw new b;if(Lt.status==="complete")return[...mt,...Ao(Lt,U,j,K,re,oe),...ht.slice(wt.commandIndex).filter((Bt)=>!Bt.startsWith("-")).map(Se)]}return[...mt,...GA(pt,ht,U,j,K,re,oe)]}let Et=(wt,Lt)=>new RegExp(`^--?${wt}=`).test(ht[Lt]??"")||new RegExp(`^--?${wt}$`).test(ht[Lt-1]??""),_t=RA(gt),At=pt==="openssl"&&ht[0]==="x509",It=yt?{certificateOutputMayFeedReader:!0}:{};return[...mt,...ht.flatMap((wt,Lt)=>Dn(pt,wt).map((Bt)=>_t&&Et("(?:cert|key)-file",Lt)?{...Se(Bt),isCreatedPath:!0,...It}:At&&Et("in",Lt)?{...Se(Bt),isCertificateInput:!0,...It}:Se(Bt)))]}function zg(G){return mn(G[0]??"").toLowerCase()==="timeout"?G.slice(2):G}function RA(G){let U=zg(G);return mn(U[0]??"").toLowerCase()==="tailscale"&&U[1]==="cert"}function xA(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 _A(G,U,j,K,re,oe,de){if(IA(U,j,K,re,oe,de)){let Se=Kn(G),we=Bc(mn(Se[0]??"").toLowerCase(),Se.slice(1))?Se.slice(1).filter((We)=>!We.startsWith("-")):[];return[...Bg(G),...we].map((We)=>({target:We,cwd:oe}))}return $g(U,PA(G),j,K,re,oe,de,()=>[])}function wA(G,U,j,K,re,oe,de){let Se=Kn(G);if(!lo(mn(Se[0]??"").toLowerCase()))return[];return oa(U,j,K,re,oe,de)??[{target:U,cwd:oe}]}function $g(G,U,j,K,re,oe,de,Se){let we=kA(G);if(we===null)return U.flatMap(Se);return U.flatMap((We)=>si.has(we)?Ao(j.getShellSyntax(We),j,K,re,oe,de):ia(we,We,j,K,re,oe,de))}function Bg(G){let U=Kn(G);if(U.length===0)return[];let j=mn(U[0]??"").toLowerCase();if(!Ng.has(j))return[];let K=U[U[1]==="--"?2:1];if(j==="printf"&&K!==void 0&&!K.startsWith("-")&&!K.replaceAll("%%","").includes("%"))return[Uc(K.replaceAll("%%","%"))];return U.slice(1)}function PA(G){let U=Kn(G);if(U.length===0)return[];let j=mn(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 AA(K);return[]}function AA(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[Uc(U)];let K=G.slice(1);return Array.from({length:Math.ceil(K.length/j)},(re,oe)=>TA(U,K.slice(oe*j,(oe+1)*j)))}function TA(G,U){let j=0;return Uc(G.replace(/%%|%[bqs]/g,(K)=>{if(K==="%%")return"%";let re=U[j]??"";return j++,re}))}function Uc(G){return G.replace(/\\n/g,`
|
|
44
|
-
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function IA(G,U,j,K,re,oe){let de=Kn(G);if(de.length===0||mn(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,Lc]:we.map((gt)=>gt.split(We).join(Lc));return xi(mt,U,j,K,re,oe).some((gt)=>gt.target.includes(Lc))}function kA(G){let U=Kn(G);if(U.length===0)return null;let j=mn(U[0]??"").toLowerCase();if(!lo(j))return null;return OA(j,U.slice(1))?j:null}function OA(G,U){let j=Hc(G);for(let K=0;K<U.length;K++){let re=U[K];if(re===void 0)break;if(zc.has(re)||jg(G,re)||/^--(?:eval|exec)=/.test(re))return!1;if(re==="-")return!0;if(re.startsWith("-")){if(j==="python"&&re==="-m")return!1;if(CA.get(j)?.has(re))K++;continue}return!1}return!0}function Hc(G){return/^python\d/.test(G)?"python":G}function MA(G){let U=[];for(let j of G){if(Zg(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 Tg=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function DA(G,U){if(!U||!Tg.test(G))return G;return`~${G.replace(Tg,"").replace(/\\/g,"/")}`}function Dn(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 NA(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)=>Dn("jq",oe))}return G.flatMap((K,re)=>re===U?[]:Dn("jq",K))}function LA(G){let U=[];for(let j=0;j<G.length;j++){let K=G[j]??"";if(K==="--"||!K.startsWith("-"))return[...U,...iA.has(K)?Gc("git",G.slice(j).map((oe)=>/^-[aeinopqsv]+m$/.test(oe)?"-m":oe),sA):Gc("git",G.slice(j),aA)];if(U.push(...Dn("git",K)),!vn.has(K))continue;let re=G[j+1];if(re===void 0)break;U.push(...K==="-c"&&re.includes("=")?[re.slice(re.indexOf("=")+1)]:Dn("git",re)),j++}return U}function Gc(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)=>Dn(G,de))];if(j.has(oe)){re++;continue}if(oe.includes("=")&&j.has(oe.slice(0,oe.indexOf("="))))continue;K.push(...Dn(G,oe))}return K}function WA(G){return G.flatMap((U,j)=>{let K=Hg(U);if(K!==null)return Ig(K.flag,K.value);let re=Ug(G[j-1]);return re===null?[]:Ig(re,U)})}function Ig(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 Wc(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 Wc(U.slice(j+1))}return U.startsWith("@")?Wc(U.slice(1)):[]}function Ug(G){if(G===void 0)return null;if(Lg.has(G))return G;return/^-[A-Za-z]+[dF]$/.test(G)?`-${G.slice(-1)}`:null}function Hg(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 Lg.has(K)?{flag:K,value:G.slice(j+1)}:null}function Wc(G){return G===""||G==="-"?[]:[G]}function FA(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(!qP.has(G[we]??""))continue;let We=G.slice(we+1),mt=We.findIndex((pt)=>KP.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(!ZP.has(pt))return[];let bt=yt[ht+1];return bt===void 0?[]:[bt,bt.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return Se}function GA(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(zc.has(We)||jg(G,We)){let gt=U[we+1];if(gt!==void 0)Se.push(...ia(G,gt,j,K,re,oe,de)),we++;continue}let mt=/^--(?:eval|exec)=(.*)$/.exec(We);if(mt!==null&&mt[1]!==void 0){Se.push(...ia(G,mt[1],j,K,re,oe,de));continue}if(!We.startsWith("-"))Se.push({target:We,cwd:oe})}return Se}function jg(G,U){if(!U.startsWith("-")||U.startsWith("--")||U.length<=2)return!1;return QP.get(U[U.length-1]??"")?.has(Hc(G))??!1}function zA(G,U,j,K,re,oe){if(!G.includes("system"))return[];return Vl(G)?.commands.flatMap((de)=>Ao(U.getShellSyntax(de),U,j,K,re,oe))??[]}function $A(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 BA(G){let U=Array.from(G.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((j)=>j[2]).filter((j)=>j!==void 0&&j!=="");return[...U,...U.flatMap(Vc),...G.match(Fc)??[]]}function ia(G,U,j,K,re,oe,de){let Se=(_t)=>({target:_t,cwd:oe}),we=sT(G),We=lT(U,we);if(We.kind==="unmaskable")return BA(U).map(Se);let mt=We.masked.match(_g)!==null||We.literals.some((_t)=>wg.test(We.masked.slice(0,_t.start))),gt=We.masked.match(yA)!==null||We.literals.some((_t)=>bA.test(We.masked.slice(0,_t.start))),ft=K.inlineLiteralsPresumedData===!0&&!si.has(G),pt=ft&&(we==="python"||we==="javascript"),ht=ft&&!(fT(We.masked)||mt||gt)?[]:We.literals,yt=ft?Array.from(We.masked.matchAll(_g),(_t)=>{let At=_t.index+_t[0].length;return{start:At,end:ds(We.masked,At)}}):[],bt=!ft||yt.some((_t)=>Al(We.masked,_t.start)&&!YA(We,_t.start))?We.literals:We.literals.filter((_t)=>wg.test(We.masked.slice(0,_t.start))||yt.some((At)=>_t.start>=At.start&&_t.start<At.end)),Ct=new Set(mt?bt:[]),vt=pt&&ht.length>0&&!VA(We.masked,we==="python"?"#":"//"),St=vt?ZA(We.masked):[],Et=vt&&qA(We.masked);return[...ht.filter((_t)=>_t.text!=="").map((_t)=>{if(!vt||Ct.has(_t))return Se(_t.text);if(XA(We.masked,_t,St,Et))return{...Se(_t.text),literalRole:"data"};return rT(We,_t,St)?{...Se(_t.text),literalRole:"write"}:Se(_t.text)}),...ht.flatMap((_t)=>Vc(_t.text)).map(Se),...ft?[]:We.literals.flatMap((_t)=>_t.text.match(Fc)??[]).map(Se),...mt?bt.flatMap((_t)=>oa(_t.text,j,{...K,commandHoldsPipe:!0},re,oe,de)??[Se(_t.text)]):[],...gt?We.literals.flatMap((_t)=>ia(G,_t.text.replace(/\\(.)/g,(At,It)=>It==="n"?`
|
|
45
|
-
`:It),j,K,re,oe,de)):[],...pt?[]:(We.masked.match(Fc)??[]).map(Se),...ft?(U.match(/\$\{[^}]*\}|\$[A-Za-z_]\w*/g)??[]).map(Se):[]]}var jc={"(":")","[":"]","{":"}"},Vg="and|elif|else|if|in|is|not|of|or|return|while|yield",UA=new RegExp(`(?:^|[^\\w$])(?:${Vg})$`),HA=new RegExp(`(?:\\*|\\.\\.\\.)\\s*[([{]|\\.\\s*(?:${Vg})\\s*\\(|/\\*`),jA=/^(?:exec|spawn)|^(?:popen|system|subprocess)$/;function VA(G,U){return HA.test(G)||G.split(`
|
|
46
|
-
`).some((j)=>{let K=j.indexOf(U);return K>=0&&/[()[\]{}]/.test(j.slice(K))})}function qA(G){return Array.from(G.matchAll(/[A-Za-z_$][\w$]*/g),(U)=>Kg(U[0])).some((U)=>U.some((j)=>jA.test(j)))}var KA=new Set(["cmd","powershell","pwsh"]);function YA(G,U){let j=Po(G.masked,U),K=jc[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&&(zc.has(de.text)||lo(mn(de.text).toLowerCase())||KA.has(mn(de.text).toLowerCase().replace(/\.exe$/,""))))}function ZA(G){let U=[];return G.split("").map((j,K)=>{let re=U.at(-1)??-1;if(j in jc)U.push(K);if(j===")"||j==="]"||j==="}")U.pop();return re})}function XA(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 oT(G,de);let mt=(we===oe||we===",")&&(We===","||We===jc[oe]||oe==="{"&&We===":");if(oe!=="(")return mt&&oe!=="";return mt&&(we===","||We===",")&&iT(G,re)}var JA=/(?:^|[^\w$.])(?:pathlib\s*\.\s*)?Path\s*$/,QA=/^\s*\.\s*write_(?:text|bytes)\s*\(/,eT=/(?:^|[^\w$.])open\s*$/,tT=/^[bt]*[awx][abtwx]*$/,nT=/(?:^|[^\w$])(?:writeFile|writeFileSync|appendFile|appendFileSync|Bun\s*\.\s*write)\s*$/;function rT(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(JA.test(Se))return(re===K||G.masked[re]===",")&&(de===","||de===")")&&!G.literals.some((We)=>We.tokenStart>K&&We.tokenStart<U.tokenStart)&&QA.test(G.masked.slice(ds(G.masked,K+1)+1));if(re!==K||de!==",")return!1;if(nT.test(Se))return!0;if(!eT.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&&tT.test(we.text)&&/^[,)]/.test(G.masked.slice(Po(G.masked,we.tokenEnd)))}function oT(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 iT(G,U){let j=wo(G,U),K=G.slice(Math.max(0,j-7),j+1);return!/[\w$)\]]$/.test(K)||UA.test(K)}function sT(G){let U=Hc(G);if(U==="python")return"python";if(U==="osascript")return"opaque";return U==="node"||U==="bun"||U==="deno"?"javascript":"simple"}var aT={python:"#",javascript:"/"};function lT(G,U){if(U==="opaque")return{kind:"unmaskable"};let j={masked:G.split(""),literals:[]};return qg(G,0,U,j,!1)===null?{kind:"unmaskable"}:{kind:"masked",masked:j.masked.join(""),literals:j.literals}}function qg(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===aT[j])return null;if(Se==="{")oe++;if(Se==="}")oe--;if(j==="simple"&&(Se==="`"||Se==="%"||Se==="<")){if(gA.test(G.slice(de)))return null}let we=Se==="'"||Se==='"'||j==="javascript"&&Se==="`"?Se:null;if(we===null)continue;if(we==="`"&&mT(G,de))return null;let We=j==="python"?uT(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?cT(G,pt,gt,mt,j,K):dT(G,gt,mt);if(ht===null)return null;if(!ft){let yt=G.slice(gt,ht);if(j==="simple"&&we==='"'&&hA.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 cT(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=qg(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 uT(G,U){return pA.exec(G.slice(Math.max(0,U-3),U))?.[1]??""}function dT(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 mT(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 fT(G){for(let U of G.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let j=U[0],K=U.index;if(XP.has(j.toLowerCase()))return!0;let re=Kg(j);if(!re.some((oe)=>JP.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 Kg(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 pT(G,U,j,K,re,oe){return CT(G).flatMap((de)=>{let Se=U.getShellSyntax(de);if(Se.status==="invalid")return[];return[...Ao(Se,U,{...j,displayOperandsAreCapturedOutput:!0},K,re,oe),...gT(Se,K)?hT(Se,K).map((we)=>({target:we,cwd:re})):[]]})}function gT(G,U){let j=Ss(G);for(let K=0;K<j.length;K++){let re=j[K];if(re?.kind!=="word"||mn(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 hT(G,U){return Ss(G).flatMap((j)=>j.kind==="word"?[er(j.text,U)]:j.kind==="redirection"&&j.target?[er(j.target,U)]:[]).flatMap(Vc)}function Vc(G){let U=bT(G);if(U===null)return[];let j=Buffer.from(U,"base64").toString("utf8");if(j===""||yT(j))return[];return Buffer.from(j,"utf8").toString("base64").replace(/=+$/g,"")===U.replace(/=+$/g,"")?[j]:[]}function yT(G){return Array.from(G).some((U)=>{let j=U.charCodeAt(0);return j<32||j===127})}function bT(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 CT(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(Yg(G,K,j)){let oe=ST(G,K+1);if(oe!==null)U.push(oe.body),K=oe.endIndex;continue}if(!j.inSingle&&re==="`"){let oe=vT(G,K);if(oe!==null)U.push(oe.body),K=oe.endIndex}}return U}function ST(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(Yg(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 vT(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 Yg(G,U,j){return!j.inSingle&&G[U]==="$"&&G[U+1]==="("&&G[U+2]!=="("}function ET(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===cA)re=!0;if(dA.has(gt))K=!0;if(ft!==void 0){if(gt===xg)U.push(ft);continue}if(fA.has(gt)){let pt=G[we+1];if(gt===xg&&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(uA.has(bt))K=!0;if(mA.has(bt)){ft=bt,pt=gt.slice(yt+1);break}}if(ft==="")continue;if(pt.length>0){if(ft===Rg)U.push(pt);continue}let ht=G[we+1];if(ft===Rg&&ht!==void 0)U.push(ht);we++;continue}j.push(We)}let Se=!K&&!re?j.slice(1):j;return[...U,...Se]}function Kn(G){let U=G.findIndex((j)=>!Zg(j)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(j));return U===-1?[]:G.slice(U)}function Zg(G){return G==="env"||G==="command"||G==="builtin"||G==="sudo"}var RT=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),xT=".env.",_T=new Set([".env.example",".env.sample",".env.template",".env.tpl",".env.defaults"]),wT=[".env.example.",".env.sample."];function PT(G){let U;try{U=new URL(G.trim())}catch{return!1}return U.protocol!=="file:"&&U.host!==""}function AT(G){return G.length>0&&!/\s/.test(G)}function sa(G,U,j,K){let re=Xg(G,U,j,K);return re!==""&&j.paths.entryKind(re)!=="missing"}function Xg(G,U,j,K){try{return _i(G,U,j,K)}catch(re){if(re instanceof s)throw re;return""}}var TT=/[?&][^?&=/]+=/,IT=new Set(["node_modules","__pycache__"]),kT=[["vendor","bundle"],["vendor","cache"]];function OT(G,U,j,K,re){if(PT(G))return null;let oe=Cn(G,U,K,re);if(!oe)return null;let de=$t(oe.split("/").pop()??""),Se=$t(oe),we=()=>AT(de)||sa(G,U,K,re),We=$t(FT(G,U,K,re));for(let ft of $a){let pt=`~/${ft.suffixParts.join("/")}`;if((Og(Se,pt)||Og(We,pt))&&ir(ft.id,j))return ft.id}if(_T.has(de)||wT.some((ft)=>de.startsWith(ft)))return null;let mt=MT(oe,U,j,K,re);if(mt)return mt;if(RT.has(de))return null;for(let ft of za)if(de===ft.basename&&ir(ft.id,j))return ft.id;if(de.startsWith(xT)&&ir($i.id,j)&&we())return $i.id;for(let ft of Ba)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 Ua)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(LT(Se))return null;if(!de.includes(".")&&Bo.pattern.test(de)&&ir(Bo.id,j))return Bo.id;if(TT.test(G)&&!sa(G,U,K,re))return null;let gt=WT(de,j);if(gt)return gt;return null}function MT(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 Wt(G,Ht(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),[".credentials.json"]);case"secret.cli.claude-code.config":{let de=$t(G).split("/");return Wt(G,Ht(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 Wt(G,Cn("~/.gemini/config",U,K,re),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let de=Ht(K.env.get("CODEX_HOME"),"~/.codex",U,K,re);return Wt(G,de,["auth.json",".credentials.json"])||_o(G,de,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let de=Ht(K.env.get("CODEX_HOME"),"~/.codex",U,K,re),Se=$t(G).split("/").at(-1)??"";return Wt(G,de,["config.toml"])||Se.endsWith(".config.toml")&&Wt(G,de,[Se])}case"secret.cli.gemini":return Wt(G,Qt(Ht(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=$t(G).split("/"),Se=K.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),we=K.env.get("ProgramData")?[Qt(Ht(K.env.get("ProgramData"),"",U,K,re),"gemini-cli")]:[];return Wt(G,Qt(Ht(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)=>Wt(G,Cn(We,U,K,re),["settings.json"]))}case"secret.cli.copilot-cli":{let de=Ht(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re);return Wt(G,de,["config.json"])||_o(G,de,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Wt(G,Ht(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re),["mcp-config.json"]);case"secret.cli.kimi-code":{let de=Ht(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),Se=Ht(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re);return Wt(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=$t(G).split("/");return Se.at(-1)==="mcp.json"&&Se.at(-2)===".kimi-code"||Wt(G,Ht(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),de)||Wt(G,Ht(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re),[...de,"config.json","config.json.bak"])}case"secret.cli.opencode":{let de=Qt(Ht(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"opencode"),Se=$t(G).split("/").at(-1)??"",we=K.env.get("OPENCODE_DB")?.trim(),We=we&&we!==":memory:"?[we,`${we}-wal`,`${we}-shm`]:[];return Wt(G,de,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Se)&&Wt(G,de,[Se])||We.some((mt)=>Ri(G,mt,U,K,re))}case"secret.cli.opencode.config":{let de=Qt(Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"opencode"),Se=K.env.get("ProgramData")?[Qt(Ht(K.env.get("ProgramData"),"",U,K,re),"opencode")]:[],we=["opencode.json","opencode.jsonc"],We=K.env.get("OPENCODE_CONFIG");return we.includes($t(G).split("/").at(-1)??"")||Wt(G,de,["config.json"])||(We?.trim()?Ri(G,We,U,K,re):!1)||["/Library/Application Support/opencode","/etc/opencode",...Se].some((mt)=>Wt(G,Cn(mt,U,K,re),we))}case"secret.cli.pi":return Wt(G,Ht(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["auth.json"]);case"secret.cli.pi.config":return Wt(G,Ht(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["models.json"]);case"secret.cli.amp":{let de=Cn("~",U,K,re);return[Qt(Ht(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"amp"),Qt(de,".local","share","amp")].some((we)=>Wt(G,we,["secrets.json"]))||_o(G,Qt(de,".amp"),["oauth"])}case"secret.cli.amp.config":{let de=["settings.json","settings.jsonc"],Se=[Qt(Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"amp"),Qt(Cn("~",U,K,re),".config","amp")],we=$t(G).split("/"),We=K.env.get("AMP_SETTINGS_FILE");return Se.some((mt)=>Wt(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=Qt(Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"cursor"),Se=Qt(Ht(K.env.get("CURSOR_DATA_DIR"),"~/.cursor",U,K,re),"projects");return Wt(G,Cn("~/.cursor",U,K,re),["auth.json"])||Wt(G,de,["auth.json"])||$t(G).split("/").at(-1)==="mcp-auth.json"&&jr($t(G),$t(Se))}case"secret.cli.cursor.config":{let de=$t(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".cursor"}case"secret.cli.grok-build":return Wt(G,Ht(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let de=$t(G).split("/");return de.at(-1)==="config.toml"&&de.at(-2)===".grok"||Wt(G,Ht(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["config.toml","managed_config.toml","requirements.toml"])||Wt(G,Cn("/etc/grok",U,K,re),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return Wt(G,Cn("~/.factory",U,K,re),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let de=$t(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".factory"||Wt(G,Cn("~/.factory",U,K,re),["settings.json","hooks.json"])}case"secret.cli.devin":return[Ht(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),Cn("~/.local/share",U,K,re)].some((de)=>Wt(G,Qt(de,"devin"),["credentials.toml"])||_o(G,Qt(de,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),Cn("~/.config",U,K,re)].some((de)=>Wt(G,Qt(de,"devin"),["config.json"]));default:return!1}})?.id??null}var kg=new WeakMap;function Ht(G,U,j,K,re){let oe=kg.get(re)??new Map;kg.set(re,oe);let de=`${j}\x00${G??""}\x00${U}`,Se=oe.get(de);if(Se!==void 0)return Se;let we=Cn(G?.trim()?G:U,j,K,re);return oe.set(de,we),we}function Wt(G,U,j){return j.some((K)=>Jg(G,Qt(U,K)))}function _o(G,U,j){return j.some((K)=>jr($t(G),$t(Qt(U,K))))}function Ri(G,U,j,K,re){return Jg(G,Cn(U,j,K,re))}function Jg(G,U){return $t(G)===$t(U)}function Qt(G,...U){return Bn([G,...U].filter(Boolean).join("/"))}function DT(G,U,j,K,re,oe){if(j.length===0)return!1;let de=$t(_i(G,U,re,oe));return j.some((Se)=>jr(de,$t(_i(Se,K,re,oe))))}function NT(G,U,j,K,re,oe){if(j.length===0)return!1;let de=$t(_i(G,U,re,oe));if(!de)return!1;let Se=re.env.get("HOME")??re.home,we=Se?Bn(Nt(cn(Se),re.paths,oe)):"",We=$t(we),mt=re.env.get("CC_SAFETY_NET_HOME"),gt=$t(mt?Bn(Nt(aa(cn(mt)),re.paths,oe)):we&&Bn(Nt(`${we}/.cc-safety-net`,re.paths,oe)));if(gt&&jr(de,gt))return!1;return j.some((ft)=>{let pt=Ka(ft);if(pt&&Mg.basename(de)!==$t(pt.name))return!1;let ht=$t(_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 LT(G){let U=G.split("/");return U.some((j)=>IT.has(j))||kT.some(([j,K])=>U.some((re,oe)=>re===j&&U[oe+1]===K))}function WT(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 Ha)if(K===re.extension&&ir(re.id,U))return re.id;for(let re of ja)if(re.pattern.test(K)&&ir(re.id,U))return re.id;return null}function $t(G){return G.toLowerCase()}function ir(G,U){return!U?.disabledRules?.includes(G)}function Cn(G,U,j,K){let{home:re,normalized:oe}=qc(G,j,K);if(!oe)return"";if(!re)return oe;let de=Kc(oe,re),Se=ra(de)?de:Bn(aa(U,de)),we=Bn(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 Og(G,U){return G===U||G.startsWith(`${U}/`)}function FT(G,U,j,K){let{home:re,normalized:oe}=qc(G,j,K);if(!oe||!re)return"";let de=Kc(oe,re),Se=Mg.normalize(ra(de)?de:Bn(aa(U,de))),we=Bn(cn(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}=qc(G,j,K);if(!oe)return"";let de=re?Kc(oe,re):oe;return Bn(Nt(ra(de)?de:aa(U,de),j.paths,K))}function qc(G,U,j){let K=U.env.get("HOME")??U.home,re=K?Bn(Nt(cn(K),U.paths,j)):"",oe=Bn(cn(GT(er(G,U))));return{home:re,normalized:oe}}function GT(G){if(!G.trim().toLowerCase().startsWith("file:"))return G;try{return HP(G)}catch{return G}}function Kc(G,U){if(G==="~")return U;if(G.startsWith("~/"))return Qt(U,G.slice(2));return G}function zT(G){if(process.platform==="win32")return!0;return UP.parse(G).root.length>1}function Bn(G){let U=G.trim(),j=(U.includes("\\")&&zT(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 mn(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 $T={findPolicyMutation:Sg,findGitMetadataMutation:Hm,resolveGitMetadata:UT,loadPolicySnapshot:k,findSensitiveTarget:Fg,analyzeCommand:fg,getModes:T},BT=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function q(G,U){let j={...$T,...U.dependencies},K=VT(G),re=wi(G)?G.command:K,oe=Cr("policy-protection",re,()=>zm(G)),de=hn(oe,"input-candidate"),Se=hn(oe,"declared-command");if(wi(G)&&G.command?.trim()&&Se?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Un,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:df,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let we=An(),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,()=>hg(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,...HT(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:Dg,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{...Yc("command-validation",re),...bt};let vt=Cr("command-analysis",re,()=>pg(()=>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}:{}},jT(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&&!BT.test(vt.decision.evidence?.segment??"")&&kn(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 UT(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 HT(G){if(G.state==="ready")return{};return{configFallback:{reason:G.reason}}}function jT(G){return hn(G,"declared-command")?.program}function VT(G){try{return ie(G.input)}catch(U){let j=wi(G)?G.command:void 0;throw new p("policy-protection",Yc("policy-protection",U instanceof f?void 0:j,U),U)}}function Cr(G,U,j){try{return j()}catch(K){throw new p(G,Yc(G,K instanceof f?void 0:U,K),K)}}function Yc(G,U,j){let K=j instanceof s||j instanceof b;return{stage:G,decision:{kind:"deny",reason:K?ua: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,Ve,Ee,T,v,pe,ot,f,P,ie,fe,it,qe,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,V,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,q};
|