cc-safety-net 2.6.8 → 2.6.10
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 -43
- package/dist/api.js +1 -1
- package/dist/bin/hook.js +43 -42
- package/dist/chunks/index-0m5hdtv4.js +2 -0
- package/dist/chunks/index-ba8pkj4y.js +2 -0
- package/dist/chunks/index-ezd6m8rs.js +2 -0
- package/dist/chunks/index-g4mrvgys.js +2 -0
- package/dist/chunks/{index-0d9zqgyg.js → index-nkbb32a2.js} +4 -4
- package/dist/chunks/index-szahvnh8.js +50 -0
- package/dist/cli.js +121 -121
- package/dist/deepseek-harness/index.js +1 -1
- package/dist/index.js +8 -8
- package/dist/openclaw/cc-safety-net/index.js +44 -43
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +2 -2
- package/package.json +2 -2
- package/dist/chunks/index-j7c6979z.js +0 -49
- package/dist/chunks/index-zwavdh1s.js +0 -2
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
var ga="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Vn="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",Do="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var pa={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."},Mo={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,...pa},processedCandidateBytes:{cap:4194304,...pa},pathEnvironmentExpansion:{cap:64,...pa},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,...Mo},trackedHeredocFiles:{cap:64,...Mo},controlFlowStates:{cap:64,...Mo},wrapperPeelIterations:{cap:20,...Mo},derivedCommandShape:Mo});class s extends Error{kind;name="AnalysisLimit";constructor(G){super(a[G].reason);this.kind=G}}function kn(){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 ch=[/\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 De(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 De(G){return ch.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 et(G){return rd(G).reduceRight((U,j)=>`${U.slice(0,j.valueStart)}<redacted>${U.slice(j.valueEnd)}`,G)}function T(G){return De(et(G))}function gt(G){return rd(G).map((U)=>G.slice(U.valueStart,U.valueEnd))}function tt(G){return/[A-Za-z_][A-Za-z0-9_]*=/.test(G)}function rd(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:dh(G,K)}]})}function dh(G,U){if(G.startsWith("$(",U))return uh(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 uh(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 mh={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 fh(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.":mh[G.intent??"manual_only"]].filter((re)=>re!==void 0).join(`
|
|
2
|
+
|
|
3
|
+
`)}function ke(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 N(G={}){return{reason:Do,ruleId:"analysis.failed-closed",intent:"stop_and_explain",command:G.command,segment:G.segment??G.command,toolName:G.toolName}}var ph={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 _(G,U={}){return{...ph[G.directory][G.problem],command:U.command,toolName:U.toolName,cwd:G.cwd}}function Y(G){return fh({...G,redact:J})}function ht(G){return J(G instanceof Error?G.message:String(G))}import{lstatSync as Zh,realpathSync as Xh,statSync as Jh}from"node:fs";import{homedir as Qh,tmpdir as ey}from"node:os";import{statSync as Kh}from"node:fs";import{join as qh}from"node:path";import{basename as sd,dirname as gh,isAbsolute as hh,join as yh,normalize as bh,resolve as od}from"node:path";var Ch=256,Ii=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 mn(G,U=process.platform){if(U!=="win32")return G;return G.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function Qn(G,U=process.platform){if(U!=="win32")return!1;return(G[0]==="/"||G[0]==="\\")&&(G[1]==="/"||G[1]==="\\")}function Ca(G,U){return ha(G,0,U)}function ha(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 Ce=ya(G,re+2),Ee=Sh(G,re,U);if(Ee===null){if(Ii.has(Ce))throw new s("pathEnvironmentExpansion");if(oe++,oe>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");K+="${",re+=2;continue}let we=G.slice(re,Ee+1);K+=vh(we,U,j),re=Ee+1;continue}let de=ya(G,re+1);if(!de){K+="$",re++;continue}K+=ba(de,j)??`$${de}`,re+=de.length+1}return K}function Sh(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 vh(G,U,j){let K=G.slice(2,-1),re=ya(K,0);if(!re)return G;let oe=K.slice(re.length);if(!oe)return ba(re,j)??G;let de=[":-",":+",":=",":?","-","+","=","?"].find((we)=>oe.startsWith(we));if(!de){if(Ii.has(re))throw new s("pathEnvironmentExpansion");return G}if(!Ii.has(re))return G;if(de.endsWith("="))throw new s("pathEnvironmentExpansion");let Ce=ba(re,j),Ee=de.startsWith(":")?Ce!==null&&Ce!=="":Ce!==null;if(de.endsWith("?")&&!Ee)throw new s("pathEnvironmentExpansion");if(de.endsWith("-")||de.endsWith("?"))return Ee?Ce??"":ha(oe.slice(de.length),U+1,j);return Ee?ha(oe.slice(de.length),U+1,j):""}function ya(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 ba(G,U){if(!Ii.has(G))return null;if(G==="HOME")return U.env.get("HOME")??U.home;return U.env.get(G)??null}function zt(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){ad(j,oe);let de=U.realpath(oe);if(de!==null)return id(j,G,de,re);let Ce=gh(oe);if(Ce===oe||re.length>=Ch)return id(j,G,oe,re);re.push(sd(oe)),oe=Ce}}function id(G,U,j,K){let re=K.length===0?j:yh(j,...K.reverse());return G.resolvedPaths.set(U,re),re}function Eh(G,U,j){let K=j.resolvedPaths.get(G);if(K!==void 0)return K;ad(j,G);let re=U.realpath(G);if(re!==null)j.resolvedPaths.set(G,re);return re}function ad(G,U){G.charge("realpathAttempts"),G.charge("processedCandidateBytes",Buffer.byteLength(U))}function fn(G,U,j,K){let re=cd(G,U,j);if(!re)return"";return zt(re,j.paths,K).replace(/\\/g,"/")}function ld(G,U,j,K,re){let oe=cd(G,U,j);if(!oe)return null;if(re(sd(oe)))return zt(oe,j.paths,K).replace(/\\/g,"/");let de=Eh(oe,j.paths,K);return de===null?null:de.replace(/\\/g,"/")}function cd(G,U,j){let K=j.home,re=Ca(G.trim(),j).replace(/\\/g,"/");if(!re)return"";let oe=re==="~"?K:re.startsWith("~/")?od(K,re.slice(2)):re,de=mn(oe);return bh(hh(de)?de:od(U,de))}import{spawnSync as Rh}from"node:child_process";import{existsSync as Lo,lstatSync as _h,readFileSync as Wo,realpathSync as Jr,statSync as No}from"node:fs";import{dirname as Sa,isAbsolute as va,join as Qr,resolve as ki}from"node:path";var xh=["/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"],wh=5000;function ud(G,U=Uh(),j=wh){let K=Ah(G),re=K===null?null:Ph(K);if(K===null||re===null)return null;let oe=$h(K,re,U,j);return oe===null?null:{recursiveSubmodules:oe}}function Ah(G){try{let U=Jr(ki(G));return No(U).isDirectory()?U:null}catch{return null}}function Ph(G){let U=zh(G);if(!U)return null;try{let j=_h(U);if(j.isSymbolicLink()||!j.isFile())return null;let K=Ea(U);if(!K?.commonDir)return null;if(!kh(K.gitDir,U))return null;return Oh(K.gitDir,Sa(U))?{gitDir:K.gitDir,commonDir:K.commonDir}:null}catch{return null}}function Ea(G){try{let U=Th(G);if(!U)return null;let j=Jr(va(U)?U:ki(Sa(G),U));if(!No(j).isDirectory())return null;return{gitDir:j,commonDir:Ih(j)}}catch{return null}}function Th(G){let U=Wo(G,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!U.startsWith("gitdir:"))return null;return U.slice(7).trim()||null}function Ih(G){try{let U=Wo(Qr(G,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!U)return null;let j=Jr(va(U)?U:ki(G,U));return No(j).isDirectory()?j:null}catch{return null}}function kh(G,U){let j=Mh(G);return j===null?!1:md(G,j,U)}function Oh(G,U){let j=Dh(G);return j===null?!0:md(G,j,U)}function Mh(G){let U=Qr(G,"gitdir");if(!Lo(U))return null;let j=Wo(U,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return j===""?null:j}function Dh(G){let U=Qr(G,"config.worktree");return Lo(U)?Lh(U):null}function md(G,U,j){try{return Nh(va(U)?U:ki(G,U),j)}catch{return!1}}function Nh(G,U){try{let j=No(G),K=No(U);if(j.ino!==0&&K.ino!==0&&j.dev===K.dev&&j.ino===K.ino)return!0}catch{}return dd(Jr.native(G))===dd(Jr.native(U))}function dd(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 Lh(G){let U=Wo(G,"utf-8"),j=!1,K=null;for(let re of U.split(/\r?\n/)){let oe=re.trim();if(oe===""||oe.startsWith("#")||oe.startsWith(";"))continue;if(oe.startsWith("[")){j=/^\[core\]$/i.test(oe);continue}if(!j)continue;let de=oe.match(/^worktree\s*=\s*(.*)$/i);if(de)K=Wh(de[1]??"")}return K}function Wh(G){let U=G.trim();if(!U.startsWith('"')||!U.endsWith('"'))return U;return Fh(U.slice(1,-1))}var Gh={"\\":"\\",'"':'"',n:`
|
|
4
|
+
`,t:"\t",b:"\b"};function Fh(G){return G.replace(/\\(.?)/gs,(U,j)=>j===""?U:Gh[j]??U)}function zh(G){try{return Ra(Jr(G))}catch{return null}}function Ra(G){let U=G;while(!0){let j=Qr(U,".git");if(Lo(j))return j;let K=Sa(U);if(K===U)return null;U=K}}function $h(G,U,j,K){if(Bh(U))return!0;if(j===null)return!0;let re=Rh(j,["config","--get","submodule.recurse"],{cwd:G,encoding:"utf8",env:Hh(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&&fd(re.stdout.trim())}function Bh(G){return[Qr(G.commonDir,"config"),Qr(G.gitDir,"config.worktree")].filter((U)=>Lo(U)).some((U)=>jh(U))}function Uh(){return xh.find((G)=>Lo(G))??null}function Go(G){return G==="GIT_CONFIG_COUNT"||G==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(G)}function Hh(G){return Object.fromEntries(Object.entries(G).filter(([U])=>!Go(U)))}function jh(G){let U;try{U=Wo(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 Ce=oe.indexOf("="),Ee=(Ce===-1?oe:oe.slice(0,Ce)).trim().toLowerCase(),we=Ce===-1?"true":oe.slice(Ce+1).trim();if(Vh(j)&&Ee==="path")return!0;if(j==="submodule"&&Ee==="recurse")K=fd(we)}return K}function Vh(G){return G==="include"||G.startsWith("includeif ")}function fd(G){let U=G.toLowerCase();return U!=="false"&&U!=="no"&&U!=="off"&&U!=="0"}function pd(G,U){if(G==="")return null;let j=kn(),K=Ra(fn(G,G,U,j)),re=K?Yh(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 Yh(G,U,j,K){try{let re=fn(G,U,j,K),oe=Kh(G),de=oe.isFile()?re:null,Ce=oe.isFile()?Ea(G):null,Ee=(oe.isDirectory()?[re]:[Ce?.gitDir,Ce?.commonDir]).flatMap((Oe)=>Oe?[eo(fn(Oe,U,j,K))]:[]),we=[...new Set(oe.isDirectory()?[eo(G.replace(/\\/g,"/")),...Ee]:Ee)];return{entry:eo(re),markerFile:de?eo(de):null,directories:we,hooksDirectories:[...new Set(we.flatMap((Oe)=>{let Ze=eo(qh(Oe,"hooks").replace(/\\/g,"/"));return[Ze,eo(fn(Ze,U,j,K))]}))]}}catch{return null}}function eo(G){return process.platform==="win32"?G.toLowerCase():G}var ty={realpath:(G)=>{try{return Xh(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 Jh(G).isDirectory()}catch{return!1}}};function c(){return ny({env:new Map(Object.entries(process.env).flatMap(([G,U])=>U===void 0?[]:[[G,U]])),home:mn(process.env.HOME||Qh()),tmpdir:ey(),paths:ty})}function ny(G,U={}){let j=new Map,K=new Map,re={...G,gitMetadata:(oe)=>gd(j,oe,()=>pd(oe,re)),worktreeFacts:(oe)=>gd(K,oe,()=>ud(oe)),...U};return re}function gd(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 xy,constants as Id,statSync as wy}from"node:fs";import{isAbsolute as Aa,relative as Ay,resolve as kd,sep as Py}from"node:path";import{types as ry}from"node:util";var oy=new Set(["applypatch","patch"]),iy=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),sy=new Set(["grep","grepsearch","rg"]),ay=new Set(["find","findbyname","glob"]),ly=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),cy=new Set(["command","diff","input","patch","patchtext"]),hd=new TextEncoder,dy=new TextDecoder,uy=/\s/,my=64;class m extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var Fo=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Te(G){return G.replace(/[-_\s]/g,"").toLowerCase()}function Mi(G){return ly.has(Te(G))}function x(G){let U=Te(G);if(oy.has(U))return"patch";if(sy.has(U))return"grep";if(ay.has(U))return"glob";if(iy.has(U))return"path";return"unknown"}function ie(G){if(!G||typeof G!=="object")return;Ad(G);let U=Object.getOwnPropertyDescriptor(G,"command");if(!U){if("command"in G)Kn();return}if(U.get||U.set)Kn();let j=U.value;return typeof j==="string"&&j!==""?j:void 0}function vd(G,U){return Ed(G,U,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Ed(G,U,j,K,re){let oe=wd(G,K,re);if(typeof G==="string")return j?[G]:[];if(!oe)return[];let de=oe.entries.flatMap(([Ce,Ee])=>Ed(Ee,U,oe.array?j:U.has(Rd(Ce)),K,re+1));return K.ancestors.delete(oe.object),de}function Rd(G){return G.replace(/-/g,"_").toLowerCase()}function _d(G){return xd(G,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(py)}function xd(G,U,j,K){let re=wd(G,j,K);if(typeof G==="string")return U?[G]:[];if(!re)return[];let oe=re.entries.flatMap(([de,Ce])=>xd(Ce,re.array?U:cy.has(Rd(de)),j,K+1));return j.ancestors.delete(re.object),oe}function fy(G,U,j){if(U.nodes++,G!==null&&typeof G==="object"&&j>Fo.maxDepth||U.nodes>Fo.maxNodes)Kn();if(typeof G!=="string")return;let K=Buffer.byteLength(G);if(U.stringBytes+=K,K>Fo.maxStringBytes||U.stringBytes>Fo.maxAggregateStringBytes)Kn()}function wd(G,U,j){if(fy(G,U,j),!G||typeof G!=="object")return null;let K=Ad(G);if(U.ancestors.has(G))Kn();let re=Reflect.ownKeys(G);if(U.keys+=re.length,U.keys>Fo.maxKeys)Kn();let oe=re.flatMap((de)=>{let Ce=Object.getOwnPropertyDescriptor(G,de);if(!Ce||Ce.get||Ce.set)Kn();return typeof de==="string"&&Ce.enumerable?[[de,Ce.value]]:[]});return U.ancestors.add(G),{object:G,array:K,entries:oe}}function Ad(G){if(ry.isProxy(G))Kn();let U=Array.isArray(G),j=Object.getPrototypeOf(G);if(U&&j!==Array.prototype||!U&&j!==Object.prototype&&j!==null)Kn();return U}function Kn(){throw new m}function py(G){let U=[],j=G.split(/\r?\n/),K=!1,re=!1,oe=null,de=null,Ce=()=>{re=!1,oe=null,de=null};for(let Ee=0;Ee<j.length;Ee++){let we=j[Ee]??"";if(we==="*** Begin Patch"){K=!0,Ce();continue}if(we==="*** End Patch"){K=!1,Ce();continue}if(we.startsWith("@@")){let Oe=gy(we);if(re=!0,oe=Oe?.oldLines??null,de=Oe?.newLines??null,oe===0&&de===0)Ce();continue}if(re&&oe!==null&&de!==null){let Oe=we.startsWith(" ")||we.startsWith("-")?1:0,Ze=we.startsWith(" ")||we.startsWith("+")?1:0;if(oe=Math.max(0,oe-Oe),de=Math.max(0,de-Ze),oe===0&&de===0)Ce();continue}if(we.startsWith("*** ")){Ce(),U.push(..._a(we));continue}if(re)continue;if(we.startsWith("diff --git ")){U.push(..._a(we));continue}if(we.startsWith("--- ")){let Oe=j[Ee+1]??"";if(!Oe.startsWith("+++ "))continue;U.push(...wa(Oi(we.slice(4),!0),Oi(Oe.slice(4),!0))),Ee++;continue}if(!K)U.push(..._a(we))}return U}function gy(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 _a(G){let U=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(G);if(U?.[1])return Sd(U[1]);let j=/^\*\*\* Move to: (.+)$/.exec(G);if(j?.[1])return Sd(j[1]);if(G.startsWith("diff --git "))return hy(G.slice(11));let K=/^--- (.+)$/.exec(G);if(K?.[1])return Cd(K[1]);let re=/^\+\+\+ (.+)$/.exec(G);if(re?.[1])return Cd(re[1]);let oe=/^(?:rename|copy) (?:from|to) (.+)$/.exec(G);if(oe?.[1])return Ry(oe[1]);return[]}function hy(G){let U=yy(G);if(U.length===2&&U[0]&&U[1])return wa(U[0],U[1]);let j=by(G);return j?wa(G.slice(j.oldStart,j.oldEnd),G.slice(j.newStart,j.newEnd)):[]}function yy(G){let U=[],j=0;while(j<G.length&&U.length<2){while(xr(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&&!xr(G[j]))j++;U.push(G.slice(oe,j));continue}let re=Pd(G,j,K);if(!re)return[];U.push(re.value),j=re.end}while(xr(G[j]))j++;return j===G.length?U:[]}function by(G){let U=0;while(U<G.length&&xr(G[U]))U++;let j=G.length;while(j>U&&xr(G[j-1]))j--;let K=0,re=U;while(re<j){if(!xr(G[re])){re++;continue}let oe=re;while(re<j&&xr(G[re]))re++;if(oe===U||re===j)continue;if(K++,K>my)Kn();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(xa(G,U,j,K,re))return!0;let oe=yd(G,"/",U,j),de=yd(G,"/",K,re);if(oe<=U||de<=K)return!1;if(xa(G,U,oe,K,de))return!1;return xa(G,oe+1,j,de+1,re)}function xa(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 yd(G,U,j,K){for(let re=j;re<K;re++)if(G[re]===U)return re;return-1}function xr(G){return G!==void 0&&uy.test(G)}function Pd(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:dy.decode(Uint8Array.from(K)),end:re+1};if(oe!=="\\"||j==="'"){K.push(...hd.encode(oe)),re+=oe.length;continue}let de=G.slice(re+1),Ce=/^[0-7]{1,3}/.exec(de)?.[0];if(Ce){K.push(Number.parseInt(Ce,8)),re+=Ce.length+1;continue}K.push(...hd.encode(Sy(de[0]??""))),re+=2}return null}function Sy(G){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
5
|
+
`,r:"\r",t:"\t",v:"\v"}[G]??G}function vy(G){return zo(_y(G))}function wa(G,U){if(G==="/dev/null")return bd(U);if(U==="/dev/null")return bd(G);if(G.startsWith("a/")&&U.startsWith("b/"))return[G.slice(2),U.slice(2)].flatMap(zo);let j=Ey(G,U)??(G===U?Td(G):null);return[G,U,...j?[j]:[]].flatMap(zo)}function bd(G){let U=Td(G);return[G,...U?[U]:[]].flatMap(zo)}function Td(G){let U=G.indexOf("/");return U>0&&U<G.length-1?G.slice(U+1):null}function Ey(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 Cd(G){return vy(Oi(G,!0))}function Ry(G){return zo(Oi(G,!1))}function Oi(G,U){let j=G.trim(),K=j[0]==='"'||j[0]==="'"?j[0]:void 0;if(K){let re=Pd(j,0,K);if(re&&(U||j.slice(re.end).trim()===""))return re.value}return U?j.split("\t",1)[0]?.trim()??"":j}function _y(G){return G.startsWith("a/")||G.startsWith("b/")?G.slice(2):G}function zo(G){return G===""||G==="/dev/null"?[]:[G]}function Sd(G){let U=G.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return U===""||U==="/dev/null"?[]:[U]}function fe(G){try{if(!wy(G).isDirectory())return!1;return xy(G,Id.R_OK|Id.X_OK),!0}catch{return!1}}function bt(G,U,j){if(Qn(G))return;let K=U.flatMap((oe)=>Di(oe,j));if(!K[0])return;let re=Di(Aa(G)?G:kd(K[0],G),j)[0];if(!re)return;return K.some((oe)=>Ty(re,oe))?re:void 0}function Od(G,U,j){if(Qn(G))return;return Di(Aa(G)?G:kd(U,G),j)[0]}function rt(G,U){return G.flatMap((j)=>Di(j,U))[0]}function Di(G,U){let j=U.realpath(G);if(j===null)return[];return U.isDirectory(j)?[j]:[]}function Ty(G,U){let j=Ay(U,G);return j===""||j!==".."&&!j.startsWith(`..${Py}`)&&!Aa(j)}var Iy=8388608;async function ot(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>Iy)throw ky(G),Error("hook input byte limit exceeded");U.push(re)}return Buffer.concat(U,j).toString("utf-8")}function ky(G){let U=G.destroy??G.cancel;if(!U)return;try{Promise.resolve(U.call(G)).catch(()=>{})}catch{}}function l(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 to=["fail_closed","paranoid_rm","paranoid_interpreters"],Ni={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"}},Li=["standard","strict","paranoid"];function Md(G,U){if(!U)return G;return Li.indexOf(U)>Li.indexOf(G)?U:G}function Dd(G){let U=pe(n.level,G);return Li.find((j)=>j===U)}function Nd(G,U){return Md(G,Dd(U))}function Oy(G){let U=pe(n.level,G);if(!U)return;let j=Dd(G);if(j)return j;console.error(`CC Safety Net: ignored invalid ${n.level.name}=${JSON.stringify(U.slice(0,40))}. Use ${Li.join(", ")}.`);return}function nt(G){if(G===void 0||G==="all")return"all";if(G==="blocked")return"blocked";return"invalid"}function Re(G){return nt(pe(n.auditScope,G))==="all"}function Pa(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 P(G={},U){let j=G.safety?.level??"standard",K=Oy(U),re=Md(j,K),oe=Ni[re],de={failClosed:oe.fail_closed,paranoidRm:oe.paranoid_rm,paranoidInterpreters:oe.paranoid_interpreters},Ce={failClosed:re===j?"preset":"environment",paranoidRm:re===j?"preset":"environment",paranoidInterpreters:re===j?"preset":"environment"},Ee={failClosed:[`policy safety.level=${j}`],paranoidRm:[`policy safety.level=${j}`],paranoidInterpreters:[`policy safety.level=${j}`]};if(re!==j)Ee.failClosed.push(`env ${n.level.name}=${K}`),Ee.paranoidRm.push(`env ${n.level.name}=${K}`),Ee.paranoidInterpreters.push(`env ${n.level.name}=${K}`);if(G.safety?.overrides?.failClosed!==void 0)de.failClosed=G.safety.overrides.failClosed,Ce.failClosed="capability_override",Ee.failClosed.push("policy safety.overrides.fail_closed");if(G.safety?.overrides?.paranoidRm!==void 0)de.paranoidRm=G.safety.overrides.paranoidRm,Ce.paranoidRm="capability_override",Ee.paranoidRm.push("policy safety.overrides.paranoid_rm");if(G.safety?.overrides?.paranoidInterpreters!==void 0)de.paranoidInterpreters=G.safety.overrides.paranoidInterpreters,Ce.paranoidInterpreters="capability_override",Ee.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(S(n.strict,U))de.failClosed=!0,Ce.failClosed="environment",Ee.failClosed.push(`env ${n.strict.name}`);if(S(n.paranoid,U))de.paranoidRm=!0,de.paranoidInterpreters=!0,Ce.paranoidRm="environment",Ce.paranoidInterpreters="environment",Ee.paranoidRm.push(`env ${n.paranoid.name}`),Ee.paranoidInterpreters.push(`env ${n.paranoid.name}`);if(S(n.paranoidRm,U))de.paranoidRm=!0,Ce.paranoidRm="environment",Ee.paranoidRm.push(`env ${n.paranoidRm.name}`);if(S(n.paranoidInterpreters,U))de.paranoidInterpreters=!0,Ce.paranoidInterpreters="environment",Ee.paranoidInterpreters.push(`env ${n.paranoidInterpreters.name}`);let we=!!G.worktreeMode||S(n.worktree,U);return{strict:de.failClosed,paranoidRm:de.paranoidRm,paranoidInterpreters:de.paranoidInterpreters,worktreeMode:we,effectiveLevel:Pa(de),capabilities:{fail_closed:{enabled:de.failClosed,source:Ce.failClosed,sources:Ee.failClosed},paranoid_rm:{enabled:de.paranoidRm,source:Ce.paranoidRm,sources:Ee.paranoidRm},paranoid_interpreters:{enabled:de.paranoidInterpreters,source:Ce.paranoidInterpreters,sources:Ee.paranoidInterpreters}}}}function S(G,U){let j=typeof G==="string"?$o(G,U):pe(G,U);return j==="1"||j?.toLowerCase()==="true"}function $o(G,U){return U.get(G)}function pe(G,U){let j=$o(G.name,U);if(j!==void 0)return j;if(G.legacyName)return $o(G.legacyName,U);return}function yt(G,U){return $o(G.name,U)!==void 0||!!G.legacyName&&$o(G.legacyName,U)!==void 0}import{dirname as Ir}from"node:path";import{closeSync as My,constants as Bo,fstatSync as Ta,fsyncSync as Dy,lstatSync as On,mkdirSync as Ld,openSync as Wd,readdirSync as ka,readFileSync as Ny,realpathSync as no,renameSync as Ly,rmdirSync as Gd,statSync as Ia,unlinkSync as Oa,writeFileSync as Wy}from"node:fs";import{isAbsolute as Fd,join as wr,normalize as Gy,parse as Wi,relative as Ma,resolve as Da,sep as Gi}from"node:path";function Ne(){let G=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${G()}${G()}`}var Fy=Symbol("PolicyFilesystemScope"),zy=Symbol("PolicyFilesystemTarget"),zd=Bo.O_NOFOLLOW??0;class o extends Error{name="PolicyFilesystemError";constructor(G){super(`Unable to access ${G} filesystem safely.`)}}function w(G,U){return{[Fy]:!0,root:Da(G),label:U}}function Uo(G,U){let j=Gy(U);if(U===""||Fd(U)||j===".."||j.startsWith(`..${Gi}`))throw new o(G.label);return{[zy]:!0,scope:G,relativePath:j,path:wr(G.root,j)}}function i(G,U){return Uo(G,Ma(G.root,Da(U)))}function se(G,U="rules policy"){let j=Da(G),K=Wi(j).dir;return Uo(w(K,U),Ma(K,j))}function r(G){return er(G.scope.label,()=>{if(!an(G))return null;let U=Wd(G.path,Bo.O_RDONLY|zd);return Bd(U,()=>{let j=Ta(U);if(!j.isFile())throw new o(G.scope.label);let K=Ny(U,"utf-8"),re=On(G.path);if(!re.isFile()||re.isSymbolicLink()||j.dev!==re.dev||j.ino!==re.ino)throw new o(G.scope.label);return an(G),K})})}function g(G,U,j=384,K){let re=`${G.path}.${Ne()}.tmp`;er(G.scope.label,()=>{By(G),an(G);let oe=Wd(re,Bo.O_CREAT|Bo.O_EXCL|Bo.O_WRONLY|zd,j),de=Bd(oe,()=>{let Ce=Ta(oe);if(!Ce.isFile())throw new o(G.scope.label);Wy(oe,U,"utf-8"),Dy(oe);let Ee=Ta(oe);if(!Ee.isFile()||Ee.dev!==Ce.dev||Ee.ino!==Ce.ino)throw new o(G.scope.label);return Ee});an(G),Hy(G,re,de.dev,de.ino),Ly(re,G.path),K?.(G.path),an(G)},()=>jy(re))}function $d(G,U){if(G.path===U.path)return!0;return er(G.scope.label,()=>{if(!an(G)||!an(U))return!1;let j=(K)=>wr(no(Wi(K).dir),Wi(K).base);return j(G.path)===j(U.path)})}function me(G){let U=er(G.scope.label,()=>{if(!an(G,"directory"))return null;let j=ka(G.path);return an(G,"directory"),j});if(!U)return null;return er(G.scope.label,()=>{let j=U.map((K)=>{let re=Uo(G.scope,wr(G.relativePath,K)),oe=On(re.path);if(oe.isSymbolicLink()||!oe.isFile()&&!oe.isDirectory())throw new o(G.scope.label);return Fi(Na(G.scope),no(re.path),G.scope.label),{name:K,kind:oe.isDirectory()?"directory":"file"}});return an(G,"directory"),j})}function H(G){er(G.scope.label,()=>{if(!an(G))return;Oa(G.path),an(G)})}function xt(G){er(G.scope.label,()=>{if(!$y(G))return;Hd(G),an(G,"directory")})}function vt(G){er(G.scope.label,()=>{if(!an(G,"directory"))return;Gd(G.path),an(G,"directory")})}function $y(G){return er(G.scope.label,()=>{if(!an(G,"directory"))return!1;return Ud(G),!0})}function er(G,U,j){try{return U()}catch(K){if(j?.(),K instanceof o)throw K;throw new o(G)}}function Bd(G,U){try{return U()}finally{My(G)}}function an(G,U="file"){let j=jd(G.scope);if(!j)return!1;let K=G.relativePath.split(Gi);for(let re of K.keys()){let oe=wr(G.scope.root,...K.slice(0,re+1)),de=On(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);Fi(j,no(oe),G.scope.label)}return!0}function Ud(G){for(let U of ka(G.path)){let j=Uo(G.scope,wr(G.relativePath,U)),K=On(j.path);if(K.isSymbolicLink()||!K.isDirectory()&&!K.isFile())throw new o(G.scope.label);if(K.isDirectory())Ud(j)}an(G,"directory")}function Hd(G){for(let U of ka(G.path)){let j=Uo(G.scope,wr(G.relativePath,U)),K=On(j.path);if(K.isSymbolicLink())throw new o(G.scope.label);if(K.isDirectory()){Hd(j);continue}if(!K.isFile())throw new o(G.scope.label);Oa(j.path)}Gd(G.path)}function By(G){Uy(G.scope);let U=Na(G.scope),j=G.relativePath.split(Gi).slice(0,-1);for(let K of j.keys()){let re=wr(G.scope.root,...j.slice(0,K+1));if(!On(re,{throwIfNoEntry:!1}))Ld(re,{mode:448});let oe=On(re);if(!oe.isDirectory()||oe.isSymbolicLink())throw new o(G.scope.label);Fi(U,no(re),G.scope.label)}}function Uy(G){if(On(G.root,{throwIfNoEntry:!1})){if(!Ia(G.root).isDirectory())throw new o(G.label);return}let U=[],j=G.root;while(!On(j,{throwIfNoEntry:!1})){U.unshift(j);let K=Wi(j).dir;if(K===j)throw new o(G.label);j=K}if(!Ia(j).isDirectory())throw new o(G.label);for(let K of U){Ld(K,{mode:448});let re=On(K);if(!re.isDirectory()||re.isSymbolicLink())throw new o(G.label)}}function jd(G){if(!On(G.root,{throwIfNoEntry:!1}))return null;if(!Ia(G.root).isDirectory())throw new o(G.label);return no(G.root)}function Na(G){let U=jd(G);if(!U)throw new o(G.label);return U}function Hy(G,U,j,K){let re=On(U);if(!re.isFile()||re.isSymbolicLink()||re.dev!==j||re.ino!==K)throw new o(G.scope.label);Fi(Na(G.scope),no(U),G.scope.label)}function Fi(G,U,j){let K=Ma(G,U);if(K===".."||K.startsWith(`..${Gi}`)||Fd(K))throw new o(j)}function jy(G){try{Oa(G)}catch{}}import{dirname as Ar,isAbsolute as Zy,join as Pr,relative as Xy,resolve as dr,sep as Jy}from"node:path";var p=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ge="rulebook.json",he=".cc-safety-net/rules";var Vd=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,Vy=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,Kd=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,Ky=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),qy="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),St=new RegExp(`^${Ky}/(${p.source.slice(1,-1)})/${qy}$`);function Yy(G){return`.cc-safety-net/rules/${G}/rulebook.json`}function qd(G){if(C(G))try{return L(G),null}catch(U){return U instanceof Error?U.message:String(U)}return p.test(G)?null:`Local rulebook sources must be bare names matching ${p}: ${G}`}function L(G){if(G.startsWith("github:"))throw Error(`Invalid rulebook source: ${G}`);let U=G.match(Vd);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||!Kd.test(K))throw Error(`GitHub rulebook refs must use valid path segments: ${G}`);if(!re||!p.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:Yy(re),name:re}}function Z(G){return Vy.test(G)}function ae(G){return Kd.test(G)}function C(G){return Vd.test(G)}function wt(G){if(!p.test(G))throw Error(`Local rulebook sources must be bare names matching ${p}: ${G}`)}var Yd="rule.json",zi="policy.json",Zd=".cc-safety-net",Qy="rules",eb="CC_SAFETY_NET_HOME",Xd="`cc-safety-net rule update`";function tb(G){return dr(G,he)}function I(G){return Pr(tb(G),Yd)}function h(G){return Pr(dr(G),Zd,zi)}function _e(G,U={}){return U.userConfigDir??(U.userConfigPath?Ar(U.userConfigPath):Pr(nb(G),Qy))}function nb(G){let U=G.env.get(eb);return U?dr(mn(U)):Pr(G.home,Zd)}function W(G,U={}){return Pr(_e(G,U),Yd)}function u(G,U={}){return Pr(Ar(_e(G,U)),zi)}function A(G,U){let j=kn();return zt(h(U.cwd),G.paths,j)===zt(dr(u(G,U)),G.paths,j)}function X(G,U){let j=U.userConfigPath??W(G,U),K=U.projectConfigPath??I(U.cwd),re=it(G,U),oe=st(K,U.cwd);return{userConfigPath:j,projectConfigPath:K,userScope:re,projectScope:oe,userConfigTarget:i(re,j),projectConfigTarget:i(oe,K)}}function it(G,U){let j=U.userConfigPath?Ar(Ar(dr(U.userConfigPath))):Ar(dr(U.userConfigDir??_e(G,U)));return w(j,"user policy")}function st(G,U){let j=dr(U),K=dr(G),re=Xy(j,K);if(re!==".."&&!re.startsWith(`..${Jy}`)&&!Zy(re))return w(j,"project policy");return w(Ar(Ar(K)),"project policy")}function M(G,U){return Pr(G,U,ge)}var _n=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),E=/^[a-zA-Z][a-zA-Z0-9_-]*$/,O=256,Xt=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Jd=new Set(["python","python3","python2","node","ruby","perl"]),$i=/^python(?:[23](?:\.\d+)*)?$/,Mn=new Set(["awk","gawk","nawk","mawk"]),Bi=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 Qd="Rulebook exceeds CC Safety Net's safe validation limits.",eu="Additional rulebook validation errors were omitted.",Gn=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function tu(G){if(La(G.allowed_commands,Gn.maxAllowedCommands)||La(G.rules,Gn.maxRules)||La(G.tests,Gn.maxTests))return!1;let{maxAggregateStringCodeUnits:U,maxTotalBlockArgs:j}=Gn,K=(re,oe=!1)=>{if(typeof re!=="string")return!0;if(re.length>Gn.maxStringCodeUnits||oe&&re.length>Gn.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 Ce of[oe.block_args,de.command_path,de.any_args,de.exclude_args]){if(!Array.isArray(Ce))continue;if(Ce.length>Gn.maxBlockArgsPerRule||Ce.length>j)return!1;j-=Ce.length;for(let Ee of Ce)if(!K(Ee))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 La(G,U){return Array.isArray(G)&&G.length>U}var Wa=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 Wt(G){return Nt(G).toLowerCase()}function Nt(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}function hn(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 Ce=`-${de}`;if(j.add(Ce),U?.shortOptsWithValue?.has(Ce))break}}return j}var rb={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Ga=new Set(["--init-file","--rcfile"]);function Fa(G,U,j,K){let re=!1,oe=0,de=!1,Ce=!1,Ee=!1;for(let we=1;we<U.length;we++){let Oe=U[we];if(Oe===void 0)break;if(G==="ksh"&&Oe==="o"&&we+1<U.length){if(K==="argv"){let Ze=U.slice(we+1);if(U[0]==="-"&&(Ze==="c"||Ze[0]==="-"&&Ze.endsWith("c")))de=!0}break}if(G==="ksh"&&Oe==="o"&&we+1===U.length&&(j?.startsWith("-")||j?.startsWith("+")))break;if(G==="zsh"&&Oe==="o"&&we+1<U.length)break;if(K==="startup"&&Oe==="i")re=U[0]==="-";if(K==="argv"&&U[0]==="-"&&Oe==="c")de=!0;if(K==="argv"&&Oe==="n")Ee=U[0]==="-";if(K==="argv"&&Oe==="s")Ce=U[0]==="-";if(!rb[G]?.includes(Oe))continue;if(we+1===U.length)oe++;break}return{interactive:re,followingValues:oe,commandSelected:de,stdinMode:Ce,syntaxCheck:Ee}}function xn(G){let U=Nt(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 Ee=j&&G[oe+1]!==void 0?oe+1:null;return{command:Ee===null?null:G[Ee]??null,commandIndex:Ee,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 Ee=de.split("=",1)[0]??de;if(U==="bash"&&Ga.has(Ee)&&!de.includes("="))oe++;continue}let Ce=Fa(U,de,G[oe+1],"argv");if(Ce.commandSelected)j=!0;if(Ce.syntaxCheck)re=!0;if(Ce.stdinMode)K=!0;oe+=Ce.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!j,syntaxCheck:re}}function Ho(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 Ui(G){let U={inSingle:!1,inDouble:!1,escaped:!1};for(let j of ob(G))Ho(j,U);return U.inSingle||U.inDouble}function ob(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);Ho(de,j)}return U}var za=new Set(["rm","find","xargs","parallel"]),ib=new Set(["git","busybox",...za,...Xt,...Jd,...Mn]),sb=new Set(["python","node","ruby","perl"]);function Le(G){let U=Wt(G);return ib.has(U)||Fn(U)}function Fn(G){return sb.has(ab(G))}function ab(G){let U=Nt(G).toLowerCase();return $i.test(U)?"python":U}var Ct={version:1,rules:[],overrides:{},transparent_wrappers:[]};function d(G){try{let U=r(lb(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=at(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??[],...j.command_tools?{command_tools:j.command_tools}:{}},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 lb(G){return typeof G==="string"?se(G):G}var e=(G,U)=>({path:G,message:U,kind:"typed"}),on=(G,U)=>({path:G,message:U,kind:"custom"});function Me(G){let U=new Set;return G.flatMap((j,K)=>{let re=Tr(j)?j.name:void 0;if(typeof re!=="string")return[];if(U.has(re.toLowerCase()))return[on(["rules",K,"name"],`duplicate rule name "${re}"`)];return U.add(re.toLowerCase()),[]})}var Pe=`must be one of ${Wa.join(", ")}`,cb=/^[^/]+\/[^/]+$/,db=["version","rules","overrides","transparent_wrappers","command_tools"],Fe=/^[^\s\p{Cc}]{1,256}$/u,xe="non-empty, at most 256 characters, no whitespace or control characters";function at(G){let U=ub(G);return{errors:ce(ct(U,db,(j)=>j.kind==="custom"),": "," "),sources:Sb(G,U)}}function ub(G){if(!Tr(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")],...mb(G.rules,U),...gb(G.overrides),...yb(G.transparent_wrappers),...U?[]:pb(G.rules),...Tr(G.overrides)?Object.keys(G.overrides).filter((j)=>!cb.test(j)).map((j)=>on(["overrides",j],"must use <rulebook-name>/<rule-name>")):[],...bb(G.transparent_wrappers),...Cb(G.command_tools)]}function mb(G,U){if(G===void 0)return[];if(!Array.isArray(G))return[e(["rules"],"must be an array of rulebook source strings"),...nu(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"),...fb(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 nu(G,U){let j=ru(G);return j!==void 0&&!(j<=U)}function fb(G,U){let j=ru(G);return j!==void 0&&!(j>=U)}function ru(G){if(G===null||G===void 0)return;let U=G.length;return U===void 0?void 0:Number(U)}function pb(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[on(["rules",K],"must be a non-empty rulebook source string")];let re=qd(j);if(re)return[on(["rules",K],re)];if(U.has(j))return[on(["rules",K],`duplicate rulebook source "${j}"`)];return U.add(j),[]})}function gb(G){if(G===void 0)return[];if(!Tr(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(!Tr(j))return[e(["overrides",U],'must be "off" or an object')];return[...hb(j.reason,["overrides",U,"reason"]),...j.intent===void 0||Ie(j.intent)?[]:[e(["overrides",U,"intent"],Pe)]]})}function hb(G,U){if(typeof G!=="string")return[e(U,"required non-empty string"),...nu(G,O)?[e(U,`must be at most ${O} characters`)]:[]];if(G==="")return[e(U,"required non-empty string")];return G.length>O?[e(U,`must be at most ${O} characters`)]:[]}function yb(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 E.test(U)?[]:[e(["transparent_wrappers",j],"must match command pattern")]})}function bb(G){if(!Array.isArray(G))return[];let U=new Set;return G.flatMap((j,K)=>{if(typeof j!=="string"||!E.test(j))return[];if(U.has(j))return[on(["transparent_wrappers",K],`duplicate command "${j}"`)];if(Le(j))return[on(["transparent_wrappers",K],`reserved command "${j}" cannot be a wrapper`)];return U.add(j),[]})}function Cb(G){if(G===void 0)return[];if(!Array.isArray(G))return[e(["command_tools"],"must be an array of tool names or {name, cwd} objects")];let U=new Set,j=(K,re)=>{if(U.has(K))return[on(["command_tools",re],`duplicate tool "${K}"`)];return U.add(K),[]};return G.flatMap((K,re)=>{if(typeof K==="string")return $a(K)?j(K,re):[e(["command_tools",re],`must be a tool name: ${xe}`)];if(!Tr(K))return[e(["command_tools",re],"must be a tool name or a {name, cwd} object")];let oe=[...$a(K.name)?[]:[e(["command_tools",re,"name"],`must be a tool name: ${xe}`)],...K.cwd===void 0||$a(K.cwd)?[]:[e(["command_tools",re,"cwd"],`must be an argument name: ${xe}`)]];return oe.length>0?oe:j(K.name,re)})}function $a(G){return typeof G==="string"&&Fe.test(G)}function Sb(G,U){let j=Tr(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 ct(G,U,j){let K=G.map((de)=>de.path[1]),re=[...new Set(K.filter((de)=>typeof de==="string"))],oe=(de,Ce)=>[de.path.length===0?-1:U.indexOf(String(de.path[0])),typeof Ce==="number"?Ce:re.indexOf(String(Ce)),j(de)?0:1];return G.map((de,Ce)=>({issue:de,rank:oe(de,K[Ce])})).sort((de,Ce)=>de.rank[0]-Ce.rank[0]||de.rank[1]-Ce.rank[1]||de.rank[2]-Ce.rank[2]).map((de)=>de.issue)}function ce(G,U,j){return[...new Set(G.map((K)=>{let re=Ba(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 Ba(G){return G.map((U,j)=>{if(typeof U==="number")return`[${U}]`;return j===0?String(U):`.${String(U)}`}).join("")}function Ie(G){return Wa.includes(G)}function Tr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function le(G){let U=Rb(G);if(U.errors.length>0)throw Error(U.errors.join("; "));return G}var vb=`required non-empty string up to ${O} characters`,ou="must be a non-empty array of unique non-empty strings",Eb="required non-empty array of non-empty strings";function Rb(G){if(!ur(G))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!tu(G))return{errors:[Qd],ruleNames:new Set};let U=[...G.rulebook_version===1||G.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ce(_b(G,G.rulebook_version===2),": ",": ")];return{errors:U.length>Gn.maxValidationErrors?[...U.slice(0,Gn.maxValidationErrors),eu]:U,ruleNames:new Set($e(G).map((j)=>j.toLowerCase()))}}function $e(G){let U=ur(G)?G.rules:void 0;return(Array.isArray(U)?U:[]).flatMap((j)=>{let K=ur(j)?j.name:void 0;return typeof K==="string"?[K]:[]})}function _b(G,U){return[...typeof G.name==="string"&&p.test(G.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof G.version==="string"&&G.version!==""?[]:[e(["version"],"required non-empty string")],...xb(G.allowed_commands),...wb(G.rules,U),...Ib(G.tests),...kb(G),...Ob(G)]}function xb(G){if(!Array.isArray(G))return[e(["allowed_commands"],"required array")];let U=new Set;return[...G.flatMap((j,K)=>typeof j==="string"&&E.test(j)?[]:[e(["allowed_commands",K],"must match command pattern")]),...G.flatMap((j,K)=>{if(typeof j!=="string"||!E.test(j))return[];if(U.has(j))return[on(["allowed_commands",K],`duplicate command "${j}"`)];return U.add(j),[]})]}function wb(G,U){if(!Array.isArray(G))return[e(["rules"],"required array")];return[...G.flatMap((j,K)=>{if(!ur(j))return[e(["rules",K],"must be an object")];return U?Pb(j,["rules",K]):Ab(j,["rules",K])}),...Me(G)]}function Ab(G,U){return[...iu(G.name,U),...su(G.command,U),...G.subcommand===void 0||typeof G.subcommand==="string"&&E.test(G.subcommand)?[]:[e([...U,"subcommand"],"must match command pattern")],...Hi(G.block_args,[...U,"block_args"],"required non-empty array",!1),...au(G.reason,U),...lu(G.intent,U)]}function Pb(G,U){return[...iu(G.name,U),...su(G.command,U),...au(G.reason,U),...lu(G.intent,U),...Tb(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 iu(G,U){if(typeof G!=="string")return[e([...U,"name"],"required string")];return p.test(G)?[]:[e([...U,"name"],"must match rule name pattern")]}function su(G,U){return typeof G==="string"&&E.test(G)?[]:[e([...U,"command"],"required string matching command pattern")]}function au(G,U){return typeof G==="string"&&G!==""&&G.length<=O?[]:[e([...U,"reason"],vb)]}function lu(G,U){return G===void 0||Ie(G)?[]:[e([...U,"intent"],Pe)]}function Tb(G,U){if(!ur(G))return[e(U,"required object")];return[...Hi(G.command_path,[...U,"command_path"],Eb,!1),...G.any_args===void 0?[]:Hi(G.any_args,[...U,"any_args"],ou,!0),...G.exclude_args===void 0?[]:Hi(G.exclude_args,[...U,"exclude_args"],ou,!0)]}function Hi(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===""?[on([...U,de],"must be a non-empty string")]:[]});if(G.some((oe)=>typeof oe!=="string"))return re;return[...re,...G.length===0?[on(U,j)]:[],...K&&new Set(G).size!==G.length?[on(U,"must not contain duplicate values")]:[]]}function Ib(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(!ur(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"?[on(["tests",j,"rule"],"required string for blocked fixtures")]:[]]})}function kb(G){if(!Array.isArray(G.tests))return[];let U=new Set($e(G));return[...new Set(G.tests.flatMap((j)=>ur(j)&&j.expect==="blocked"&&typeof j.rule==="string"?[j.rule]:[]))].filter((j)=>!U.has(j)).map((j)=>on(["tests"],`blocked fixture references unknown rule "${j}"`))}function Ob(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=ur(j)?j.command:void 0;if(typeof re!=="string"||U.has(re))return[];return[on(["rules",K,"command"],`"${re}" must be listed in allowed_commands`)]})}function ur(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function Q(G,U){let j=X(G,U),K;try{K=$d(j.userConfigTarget,j.projectConfigTarget)}catch(Ye){if(Ye instanceof o)return Bb(j,Ye.message);throw Ye}let re=d(j.userConfigTarget),oe=K?{config:null,errors:[]}:d(j.projectConfigTarget),de=uu(j.userConfigPath,re.errors),Ce=uu(j.projectConfigPath,oe.errors),Ee=new Set,we=re.config?Ua(re.config,Ir(j.userConfigPath),"user",j.userScope,Ee):mu(),Oe=oe.config?Ua(oe.config,Ir(j.projectConfigPath),"project",j.projectScope,Ee):mu(),Ze=re.config?.overrides??{},Ke=oe.config?.overrides??{};return{rules:[...du(we.rules,Ze),...du(Oe.rules,Ke)],transparent_wrappers:Fb(re.config,oe.config),command_tools:zb(re.config,oe.config),rulebooks:[...we.rulebooks,...Oe.rulebooks],errors:[...de,...Ce,...we.errors,...Oe.errors],warnings:[...we.warnings,...Oe.warnings,...we.canValidateOverrides?Ha(Ze,we.knownRuleIds,j.userConfigPath):[],...we.canValidateOverrides?$b(Ke,we.knownRuleIds,j.projectConfigPath):[],...Oe.canValidateOverrides?Ha(Ke,Oe.knownRuleIds,j.projectConfigPath):[]],userConfig:re.config??void 0,projectConfig:oe.config??void 0,...j}}function B(G,U){let j=Mb(G,U);if(!j)return[];return[...j.scope.errors,...j.scope.warnings,...Db(j.config,j.scope,G)]}function Mb(G,U){let j=U??w(Ir(Ir(G)),"rules policy"),K=d(i(j,G)).config;if(!K)return null;return{config:K,scope:Ua(K,Ir(G),"project",j)}}function Db(G,U,j){return U.canValidateOverrides?Ha(G.overrides??{},U.knownRuleIds,j):[]}function Ua(G,U,j,K=w(Ir(Ir(U)),j==="user"?"user policy":"project policy"),re=new Set){let oe=[],de=[],Ce=G.rules.flatMap((we)=>{let Oe=Lb(we,U,K);if(Oe.errors.length>0||!Oe.rulebook)return oe.push(...Oe.errors),[];let Ze=Oe.rulebook;if(re.has(Ze.name))return de.push(`duplicate active rulebook name "${Ze.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(Ze.name),[{rules:Nb(Ze),rulebook:{source:j,spec:we,name:Ze.name,version:Ze.version,rules:Ze.rules.map((Ke)=>`${Ze.name}/${Ke.name}`)}}]}),Ee=Ce.flatMap((we)=>we.rules);return{rules:Ee,rulebooks:Ce.map((we)=>we.rulebook),knownRuleIds:new Set(Ee.map((we)=>we.name)),errors:oe,warnings:de,canValidateOverrides:oe.length===0}}function Nb(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 Lb(G,U,j){let K=je(G),re=M(U,K),oe=Gb(re,j);if("error"in oe)return{rulebook:null,errors:[oe.error]};if(oe.content===null)return{rulebook:null,errors:[`missing rulebook file ${re} for ${G}; ${Wb(G)}`]};let de=ve(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 je(G){return C(G)?L(G).name:G}function Wb(G){return C(G)?`run ${Xd} to vendor ${G}`:"create that file or remove that source from the rules config"}function Gb(G,U){try{return{content:r(i(U,G))}}catch(j){if(j instanceof o)return{error:j.message};throw j}}function ve(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 Fb(G,U){return[...new Set([...G?.transparent_wrappers??[],...U?.transparent_wrappers??[]])]}function zb(G,U){let j=(G?.command_tools??[]).map(cu),K=(U?.command_tools??[]).map(cu);return[...j,...K.filter((re)=>!j.some((oe)=>oe.name===re.name))]}function cu(G){if(typeof G==="string")return{name:G};return G.cwd===void 0?{name:G.name}:{name:G.name,cwd:G.cwd}}function du(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 Ha(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 $b(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 uu(G,U){return U.map((j)=>j.startsWith("Unable to access ")?j:`${G}: ${j}`)}function Bb(G,U){return{rules:[],transparent_wrappers:[],command_tools:[],rulebooks:[],errors:[U],warnings:[],userConfigPath:G.userConfigPath,projectConfigPath:G.projectConfigPath}}function mu(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as Qb,readFileSync as eC}from"node:fs";var fu=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores, with or without --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.nested-recursive-delete-unread",category:"PowerShell",label:"Nested PowerShell recursive delete not read",description:"Blocks a recursive delete handed to powershell or pwsh in any form other than literal -Command script words.",example:"pwsh -WorkingDirectory C:\\ -c 'Remove-Item -Recurse -Force *'",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-root-or-home",category:"Command Prompt",label:"cmd recursive delete root or home",description:"Blocks cmd rmdir /s or del /s of root or home paths.",example:"cmd /c rmdir /s /q C:\\",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-escaped-quote",category:"Command Prompt",label:"cmd recursive delete with escaped quotes",description:"Blocks cmd rmdir /s or del /s whose quoting can reach cmd as \\\" and split the target down to the drive root.",example:'cmd /c "rmdir /s /q \\"build output\\""',intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-git-metadata",category:"Command Prompt",label:"cmd recursive delete Git metadata",description:"Blocks cmd rmdir /s or del /s of protected Git metadata and hooks.",example:"cmd /c rmdir /s /q .git",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-dynamic-target",category:"Command Prompt",label:"cmd recursive delete dynamic target",description:"Blocks cmd rmdir /s or del /s with wildcard or variable targets in strict mode.",example:"cmd /c del /s /q *.log",intent:"scope_down",activationCapability:"fail_closed"},{id:"cmd.recursive-delete-home-cwd",category:"Command Prompt",label:"cmd recursive delete from home cwd",description:"Blocks cmd rmdir /s or del /s while working in home.",example:"Set-Location $HOME; cmd /c rmdir /s /q build",intent:"scope_down"},{id:"cmd.recursive-delete-cwd-self",category:"Command Prompt",label:"cmd recursive delete current directory",description:"Blocks cmd rmdir /s or del /s of the current directory.",example:"cmd /c rmdir /s /q .",intent:"scope_down"},{id:"cmd.recursive-delete-outside-cwd",category:"Command Prompt",label:"cmd recursive delete outside cwd",description:"Blocks cmd rmdir /s or del /s outside the original cwd.",example:"cmd /c rmdir /s /q ..\\outside",intent:"scope_down"},{id:"cmd.recursive-delete-paranoid",category:"Command Prompt",label:"cmd recursive delete paranoid mode",description:"Blocks non-temp cmd rmdir /s or del /s when paranoid rm is enabled.",example:"cmd /c rmdir /s /q build",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"find.delete",category:"Filesystem",label:"find delete",description:"Blocks unsafe find -delete operations.",example:"find . -delete",intent:"scope_down"},{id:"find.delete-git-metadata",category:"Filesystem",label:"find delete Git metadata",description:"Blocks find -delete operations selecting protected Git metadata and hooks.",example:"find .git -delete",intent:"hard_stop",catastrophic:!0},{id:"find.exec-rm-recursive-force",category:"Filesystem",label:"find exec rm -rf",description:"Blocks find -exec rm -rf operations.",example:"find . -exec rm -rf {} +",intent:"scope_down"},{id:"dd.device-write",category:"Filesystem",label:"dd device write",description:"Blocks dd writing to a /dev device other than /dev/null, /dev/zero, or /dev/full.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"Filesystem format on a device",description:"Blocks mkfs, mke2fs, and newfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"disk.erase",category:"Filesystem",label:"Disk erase or repartition",description:"Blocks diskutil erase and partition verbs, wipefs -a/-o, sgdisk writes, and parted label or partition edits on a /dev device.",example:"diskutil eraseDisk APFS Untitled disk4",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"redirect.block-device",category:"Filesystem",label:"Redirect onto a disk device",description:"Blocks output redirects whose literal target is a disk device path under /dev.",example:"cat disk.img > /dev/sda",intent:"manual_only"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],ja=new Set(fu.map((G)=>G.id)),z=fu,Ub=new Map(z.map((G)=>[G.id,G.intent]));function At(G,U){return{id:G,reason:U,intent:Ub.get(G)??"manual_only"}}var Va=[{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"}],ji={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Hb=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],jb=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Ka=[{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"]},...jb.flatMap((G)=>Hb.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 Vi=[{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"]}],pu=[{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"}],Vb=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],qa=pu.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})),Ya=pu.flatMap((G)=>Vb.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}))),jo={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)$/},Za=["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})),Xa=[{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?$/}],lt=[...Va,ji,...Ka,...qa,...Ya,jo,...Za,...Xa,...Vi].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}})),Ki=new Set(Vi.flatMap((G)=>G.category==="Coding CLI config"?[G.id]:[])),Ja=new Set(lt.map((G)=>G.id));import{isAbsolute as Qa,join as Kb,normalize as qb,sep as qi}from"node:path";var Yi=process.platform==="win32",gu=/[*?]/;function el(G){let U=G.trim(),j=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(Yi?U.replaceAll("\\","/"):U);if(!j)return null;let K=j[1]??"",re=j[2]??"";if(gu.test(K)||re==="."||re==="..")return null;return{root:K||"/",name:re}}function Vo(G,U){if(G==="~")return U;if(G.startsWith("~/"))return`${U}${G.slice(1)}`;return G}function tl(G,U){if(typeof G!=="string"||G.trim()==="")return"must be a non-empty path string";let j=Vo(G.trim(),U);if(!Qa(j))return"must be an absolute path or start with ~/";return Ko(j,U)}function nl(G,U){let j=hu(G,U);if(j===null)return"must be a non-empty path string";if(!Qa(j))return null;if(Ko(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 Yb="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Zb="cannot cover the guard's own configuration";function hu(G,U){if(typeof G!=="string"||G.trim()==="")return null;let j=G.trim(),K=Yi?j.replaceAll("\\","/"):j;return Vo(K.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),U)}function rl(G,U){let j=hu(G,U);if(j===null)return"must be a non-empty path string";let K=el(j)?.root??j;if(gu.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(Ko(K,U)!==null)return Yb;return Xb(K,U)?Zb:null}function Xb(G,U){let j=Zi(G),K=Zi(Kb(U,".cc-safety-net"));return j===K||j.startsWith(`${K}${qi}`)}function Ko(G,U){let j=Zi(G),K=Zi(U);if(j===K)return"cannot be the home directory";let re=j.endsWith(qi)?j:`${j}${qi}`;if(K.startsWith(re))return"cannot contain the home directory";return null}function Zi(G){let U=qb(G);if(Yi)U=U.replace(/\//g,"\\").toLowerCase();if(U.length>(Yi?3:1)&&U.endsWith(qi))U=U.slice(0,-1);return U}var yu=30,Xi=1,Ji=365;function bu(G){if(typeof G!=="number"||!Number.isInteger(G))return 30;if(G<1)return 1;return G>365?365:G}var Cu=new Set(z.filter((G)=>G.catastrophic).map((G)=>G.id));function Mt(G,U){if(!G)return null;if(Cu.has(G.id))return G;if(U?.destructiveCommandProtectionEnabled===!1)return null;let j=U?.effectiveDestructiveCommandRules[G.id];return j&&!j.enabled?null:G}function tn(G,U,j){if(Cu.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 Su(G,U){return Object.freeze({...G,effectiveDestructiveCommandRules:V(G,U)})}var vu={standard:0,strict:1,paranoid:2};function ee(G,U,j=!1,K=G.safety.level){let re=Jb(G,U,K),oe=new Set(j?re.map((Oe)=>Oe.field):[]),de=(Oe,Ze)=>oe.has(Oe)?void 0:Ze,Ce=(Oe,Ze)=>Object.fromEntries(Object.entries(Ze??{}).filter(([Ke])=>!oe.has(`${Oe}.${Ke}`))),Ee=(Oe,Ze)=>Ze?.filter((Ke)=>!oe.has(`${Oe}.${Ke}`));return{policy:{version:1,safety:{level:de("safety.level",U.safety?.level)??G.safety.level,overrides:{...G.safety.overrides,...Ce("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,...Ce("destructive_command_protection.overrides",U.destructive_command_protection?.overrides)},allow_paths:ol(G.destructive_command_protection.allow_paths,Ee("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,...Ce("secret_protection.overrides",U.secret_protection?.overrides)},deny_paths:ol(G.secret_protection.deny_paths,U.secret_protection?.deny_paths),allow_paths:ol(G.secret_protection.allow_paths,Ee("secret_protection.allow_paths",U.secret_protection?.allow_paths))},audit:G.audit},weakenings:re.map((Oe)=>Oe.message)}}function ol(G,U){return[...new Set([...G,...U??[]])]}function Jb(G,U,j){let K=U.safety?.level,re=Ni[j];return[...K&&vu[K]<vu[G.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${G.safety.level} -> ${K}`}]:[],...to.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"}]:[],...Eu("destructive_command_protection.overrides",U.destructive_command_protection?.overrides,(oe)=>G.destructive_command_protection.enabled&&G.destructive_command_protection.overrides[oe]!=="off"),...Eu("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"&&!Ki.has(oe))),...G.destructive_command_protection.enabled?Ru(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?Ru(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 Eu(G,U,j){return Object.entries(U??{}).flatMap(([K,re])=>re==="off"&&j(K)?[{field:`${G}.${K}`,message:`project policy disables rule ${K}`}]:[])}function Ru(G,U){return(U??[]).filter((j)=>!G.includes(j))}var al=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:yu}};function Au(G,U){let j=sC(u(G,U),G.home),K=A(G,U)?{exists:!1,policy:F(),errors:[]}:Ge(h(U.cwd),G.home),re=ue(K.parsed,G.home),oe=S(n.projectTightenOnly,G.env),de=j.gui??te,Ce=Object.keys(re.policy).length>0?ee(de,re.policy,oe,Nd(de.safety.level,G.env)):void 0,Ee=[...j.errors,...K.errors,...re.diagnostics],we=(j.fallback==="defaults"&&Ce?"salvaged":j.fallback)??(j.gui?void 0:K.fallback)??(Ee.length>0?"salvaged":void 0),Oe=re.policy.safety?.level&&Ce?.policy.safety.level===re.policy.safety.level?"project":j.levelPresent?"user":"default";return{...Ce?sl(Ce.policy):j.policy,errors:Ee,...we?{fallback:we}:{},...K.exists?{policyScopes:{levelScope:Oe,weakenings:Ce?.weakenings??[],weakeningsIgnored:oe}}:{}}}var tC="project policy audit settings are ignored; audit is user scope only";function ue(G,U){if(!wn(G))return{policy:{},diagnostics:[]};let j=wn(G.safety)?G.safety:{},K=wn(G.workflow)?G.workflow:{},re=wn(G.destructive_command_protection)?G.destructive_command_protection:{},oe=wn(G.secret_protection)?G.secret_protection:{},de={...al.has(j.level)?{level:j.level}:{},...wn(j.overrides)?_u({overrides:Pu(j.overrides,to,["safety","overrides"],kr)}):{}},Ce={...typeof re.enabled==="boolean"?{enabled:re.enabled}:{},...re.overrides!==void 0?{overrides:Qi(re.overrides,ja,Iu,kr)}:{},...re.allow_paths!==void 0?{allow_paths:oo(re.allow_paths,tl,U,["destructive_command_protection","allow_paths"],kr)}:{}},Ee={...typeof oe.enabled==="boolean"?{enabled:oe.enabled}:{},...oe.overrides!==void 0?{overrides:Qi(oe.overrides,Ja,ku,kr)}:{},...oe.deny_paths!==void 0?{deny_paths:oo(oe.deny_paths,nl,U,["secret_protection","deny_paths"],kr)}:{},...oe.allow_paths!==void 0?{allow_paths:oo(oe.allow_paths,rl,U,["secret_protection","allow_paths"],kr)}:{}};return{policy:_u({safety:de,workflow:typeof K.worktree_mode==="boolean"?{worktree_mode:K.worktree_mode}:{},destructive_command_protection:Ce,secret_protection:Ee}),diagnostics:G.audit===void 0?[]:[tC]}}function Pu(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],ll));return[]}))}function _u(G){return Object.fromEntries(Object.entries(G).flatMap((U)=>Object.keys(U[1]).length>0?[U]:[]))}var kr=()=>{return},ll="must be a boolean",cl="must be an object if provided",Tu=`must be an integer between ${Xi} and ${Ji}`,Iu={path:["destructive_command_protection","overrides"],label:"destructive command"},ku={path:["secret_protection","overrides"],label:"secret protection"},ut=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function dt(G,U){let j=[];return{policy:Ou(G,U,(re)=>{j.push(re)}),issues:j}}function k(G,U){return Ou(G,U,kr)}function Ou(G,U,j){if(!wn(G))return j(e([],"Config must be an object")),F();if(G.version!==1)j(e(["version"],"must be 1"));let K=ro(G.safety,["safety"],["level","overrides"],j),re=ro(K.overrides,["safety","overrides"],to,j),oe=ro(G.workflow,["workflow"],["worktree_mode"],j),de=ro(G.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],j),Ce=ro(G.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],j),Ee=ro(G.audit,["audit"],["retention_days"],j);return Mu(G,ut,[],j),{version:1,safety:{level:nC(K.level,j),overrides:Pu(re,to,["safety","overrides"],j)},workflow:{worktree_mode:il(oe.worktree_mode,["workflow","worktree_mode"],!1,j)},destructive_command_protection:{enabled:il(de.enabled,["destructive_command_protection","enabled"],!0,j),overrides:Qi(de.overrides,ja,Iu,j),allow_paths:oo(de.allow_paths,tl,U,["destructive_command_protection","allow_paths"],j)},secret_protection:{enabled:il(Ce.enabled,["secret_protection","enabled"],!0,j),overrides:Qi(Ce.overrides,Ja,ku,j),deny_paths:oo(Ce.deny_paths,nl,U,["secret_protection","deny_paths"],j),allow_paths:oo(Ce.allow_paths,rl,U,["secret_protection","allow_paths"],j)},audit:{retention_days:rC(Ee.retention_days,j)}}}function ro(G,U,j,K){if(G===void 0)return{};if(!wn(G))return K(e(U,cl)),{};return Mu(G,j,U,K),G}function Mu(G,U,j,K){for(let re of Object.keys(G).filter((oe)=>!U.includes(oe)))K({path:j,message:re,kind:"unknownKeys"})}function nC(G,U){if(G===void 0)return"standard";if(al.has(G))return G;return U(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function il(G,U,j,K){if(typeof G==="boolean")return G;if(G!==void 0)K(e(U,ll));return j}function rC(G,U){if(!(G===void 0||typeof G==="number"&&Number.isInteger(G)&&G>=Xi&&G<=Ji))U(e(["audit","retention_days"],Tu));return bu(G)}function Qi(G,U,j,K){if(G===void 0)return{};if(!wn(G))return K(e(j.path,cl)),{};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 oo(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 Ce=U(oe,j);if(Ce===null)return[oe];return re(typeof oe==="string"?on([...K,de],Ce):e([...K,de],Ce)),[]})}function wn(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function F(){return structuredClone(te)}function Ue(G,U){let j=P({safety:We(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 Ge(G,U){if(!Qb(G))return{exists:!1,policy:F(),errors:[]};try{let j=eC(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=dt(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}: ${iC(oe)}`),fallback:wn(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 oC=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[cl,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[ll,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Tu,`not an integer between ${Xi} and ${Ji}`]]);function iC(G){let U=Ba(G.path);if(G.kind==="unknownKeys")return`${U===""?"":`${U}.`}${G.message}: unknown field`;if(G.kind==="key")return`${U}: unknown rule id`;let j=oC.get(G.message)??G.message;return U===""?j:`${U}: ${j}`}function sC(G,U){let j=Ge(G,U);if(!j.exists){let K=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!wn(K))return{policy:wu(),errors:[]};let re=k(K,U);return{policy:sl(re),gui:re,errors:[],levelPresent:xu(K)}}if(j.parsed===void 0)return{policy:wu(),errors:j.errors,...j.fallback?{fallback:j.fallback}:{}};return{policy:sl(j.policy),gui:j.policy,errors:j.errors,...j.fallback?{fallback:j.fallback}:{},levelPresent:xu(j.parsed)}}function xu(G){let U=wn(G)&&wn(G.safety)?G.safety:{};return al.has(U.level)}function He(G){let U=Object.entries(G),j=new Set(U.flatMap(([K,re])=>re==="on"?[K]:[]));return[...new Set([...[...Ki].filter((K)=>!j.has(K)),...U.flatMap(([K,re])=>re==="off"?[K]:[])])]}function wu(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:He({}),denyPaths:[],allowPaths:[]}}}function sl(G){return{safety:We(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:He(G.secret_protection.overrides),denyPaths:G.secret_protection.deny_paths,allowPaths:G.secret_protection.allow_paths}}}function We(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 R(G,U){let j=Q(G,U),K=Au(G,U),re={rules:j.rules,transparentWrappers:j.transparent_wrappers,commandTools:j.command_tools,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((Ce)=>{let Ee=j.rulebooks.find((Oe)=>Oe.rules.includes(Ce.name)),we=oe[Ce.name];return[Ce.name,Object.freeze({id:Ce.name,...Ee?{rulebook:Object.freeze({name:Ee.name,version:Ee.version}),...dC(Ee.spec)?{source:Ee.spec}:{}}:{},...we&&typeof we==="object"?{override:Object.freeze({type:"reason",reason:we.reason})}:{}})]})));return Ae(re,aC(j,K),de,K.policyScopes)}function Be(G){if(G.state==="ready")return{state:G.state};return{state:G.state,reason:G.reason}}function aC(G,U){let j=cC(U);if(G.errors.length===0&&G.warnings.length===0&&!j)return;return{diagnostics:[...G.errors,...G.warnings,...U.errors],reason:uC(G.errors.length>0?lC(G.errors):void 0,G.warnings.length>0?ul(G.warnings.join("; ")):void 0,j)}}function lC(G){return`${ul(G.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function cC(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 dC(G){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(G)}function Ae(G,U,j=Object.freeze({}),K){let re=dl(structuredClone(G)),oe=K?{policyScopes:dl(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 dl(G){if(typeof G!=="object"||G===null)return G;for(let U of Object.values(G))dl(U);return Object.freeze(G)}function uC(...G){return ul(G.filter((U)=>!!U).join("; "))}function ul(G){return/[.!?]$/.test(G)?G:`${G}.`}function ze(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:ml(U.fail_closed,G.strict,"strict"),paranoid_rm:ml(U.paranoid_rm,G.paranoidRm,"paranoidRm"),paranoid_interpreters:ml(U.paranoid_interpreters,G.paranoidInterpreters,"paranoidInterpreters")};return{policy:Su(G.policySnapshot.policy,oe),effectiveCapabilities:oe,effectiveLevel:Pa({failClosed:j,paranoidRm:K,paranoidInterpreters:re}),strict:j,paranoidRm:K,paranoidInterpreters:re,worktreeMode:G.worktreeMode??!1}}function ml(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 mA,isAbsolute as fA,join as pA,parse as gA,resolve as hA,sep as yA}from"node:path";function qo(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 mC=/^[A-Za-z_][A-Za-z0-9_]*=/;function es(G,U){return G?.provenance==="literal"&&!G.quoted&&G.raw===U&&G.text===U}function Yo(G){let U=es(G.words[0],"time")?1:0,j=U===1&&es(G.words[U],"-p")?U+1:U,K=U===1&&es(G.words[j],"--")?j+1:j,re=es(G.words[K],"!")?K+1:K,oe=G.words.slice(re).find((de)=>!mC.test(de.text));return oe?.provenance==="literal"?oe.text:void 0}var mr=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function ts(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function fC(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)=>yn(U)))})}function ns(G,U,j){G.push(j),U.reset()}function rs(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 fl(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 io(G,U,j,K,re,oe,de){return fl({text:K,raw:G.slice(U,j),span:{start:U,end:j},provenance:re,quoted:oe,...de?{parts:de}:{}})}function yn(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 fC(U);if(U.kind==="group"||U.kind==="function")return Object.freeze({...U,span:Object.freeze(U.span),body:yn(U.body)});return Object.freeze({...U,span:Object.freeze(U.span)})}))})}function pl(G,U,j){if(U>=j||Nu(G[U]??""))return null;let K="",re=!1,oe=!1,de=U;while(de<j&&!Nu(G[de]??"")){let Ce=G[de]??"";if(Ce==="'"){re=!0;let Ee=Du(G,de+1,j,"'");K+=Ee.text,oe||=!Ee.closed,de=Ee.next;continue}if(Ce==='"'){re=!0;let Ee=Du(G,de+1,j,'"');K+=Ee.text,oe||=!Ee.closed,de=Ee.next;continue}if(Ce==="\\"){re=!0;let Ee=G[de+1];if(!Ee||Ee===`
|
|
7
|
+
`||Ee==="\r"){oe=!0;break}K+=Ee,de+=2;continue}if(Ce==="`"||G.startsWith("$(",de)||G.startsWith("${",de)||G.startsWith("<(",de)||G.startsWith(">(",de))oe=!0;K+=Ce,de++}return{delimiter:K,quoted:re,next:de,ambiguous:oe}}function gl(G,U,j,K){let re=[],oe=U;for(let de of K){let Ce=oe,Ee=!1;while(oe<j){let we=pC(G,oe,j);if((de.stripTabs?we.text.replace(/^\t+/,""):we.text)===de.delimiter){de.attach({body:de.stripTabs?gC(G.slice(Ce,oe)):G.slice(Ce,oe),delimiter:de.delimiter,quotedDelimiter:de.quotedDelimiter,bodySpan:{start:Ce,end:oe},terminatorSpan:{start:oe,end:we.contentEnd}}),oe=we.next,Ee=!0;break}if(we.next<=oe)break;oe=we.next}if(Ee)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 Du(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 Ce=G[oe+1]??"";re+=["$","`",'"',"\\"].includes(Ce)?Ce:`\\${Ce}`,oe+=2;continue}re+=de,oe++}return{text:re,next:oe,closed:!1}}function Nu(G){return G!=="\r"&&(/[\s;&|<>)]/u.test(G)||G==="`")}function pC(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 gC(G){return G.replace(/(^|\r\n?|\n)\t+/g,"$1")}var zu=new Set(["&&","||","|","|&"]),hC=new Set(["!","do","elif","else","if","then","until","while"]);function $u(G,U){let j={start:0,end:G.length};if(G.length>U.maxInputLength)return yn({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=ss(G,0,G.length,U,K,0),oe=xC(G,K.quotedExpansionEnd,re.nodes)?[...re.issues,Hu]:re.issues;return yn({kind:"program",dialect:"posix",source:G,span:j,status:ls(oe,re.limited),issues:oe,nodes:re.nodes})}function ss(G,U,j,K,re,oe,de){let Ce=[],Ee=[],we=ts(),Oe=[],Ze=()=>{if(we.words.length===0&&we.redirections.length===0)return;let Ye={start:we.start,end:we.end},Xe=we.words.map((Je)=>Je.text);ns(Ce,we,{kind:"command",dialect:"posix",source:G.slice(Ye.start,Ye.end),span:Ye,words:we.words,redirections:we.redirections,nested:we.nested,displayText:Ee.length>0&&Ce.length===0?G.slice(U,j):Xe.join(" ")})},Ke=U;while(Ke<j){let Ye=G[Ke];if(!Ye)break;if(de&&Ye===de)return Ze(),Fu(Ce,Ee),{nodes:Ce,issues:Ee,next:Ke+1,closed:!0,limited:!1,pendingHeredocs:Oe};if(Xo(Ye)){if(Ye===`
|
|
10
|
+
`||Ye==="\r"){Ze();let It=Ye==="\r"&&G[Ke+1]===`
|
|
11
|
+
`?Ke+2:Ke+1,Ot=Ce.at(-1);if(Ot?.kind!=="connector"||!zu.has(Ot.operator))Ce.push(Object.freeze({kind:"connector",operator:G.slice(Ke,It),span:Object.freeze({start:Ke,end:It})}));if(Oe.length>0){let Dt=gl(G,It,j,Oe.splice(0));Ee.push(...Dt.issues),Ke=Dt.next;continue}Ke=It;continue}Ke++;continue}if(Ye==="#"){while(Ke<j&&G[Ke]!==`
|
|
12
|
+
`&&G[Ke]!=="\r")Ke++;continue}let Xe=we.start===-1?UC(G,Ke,j):void 0;if(Xe){if(yl(Ce,Ee),oe>=K.maxDepth)return so(Ce,Ee,Ke,"depth-limit",K.maxDepth);if(!hl(re))return so(Ce,Ee,Ke,"word-limit",K.maxWords);let It=ss(G,Xe.braceIndex+1,j,K,re,oe+1,"}"),Ot=It.next,Dt={start:Xe.braceIndex+1,end:It.closed?Ot-1:Ot},ft=Lu(G,Dt,It);if(Ce.push({kind:"function",name:Xe.name,span:{start:Ke,end:Ot},body:ft}),Ee.push(...It.issues),It.pendingHeredocs.length>0||Jo(It.nodes))Ee.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(Oe.push(...It.pendingHeredocs),It.limited)return is(Ce,Ee,It.next);if(!It.closed)Ee.push({code:"unclosed-function-body",message:"function body is not closed"});Ke=Ot;continue}let Je=as(G,Ke);if(Je){if(Ze(),!Xu(Ce.at(-1)))Ee.push({code:"unexpected-connector",message:`connector ${Je} has no preceding command`});Ce.push(Object.freeze({kind:"connector",operator:Je,span:Object.freeze({start:Ke,end:Ke+Je.length})})),Ke+=Je.length;continue}if(Ye===")"){Ze(),Ee.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),Ce.push({kind:"unknown",source:Ye,span:{start:Ke,end:Ke+1}}),Ke++;continue}if((Ye==="("||Ye==="{"&&IC(G,Ke,j))&&we.start===-1){if(yl(Ce,Ee),oe>=K.maxDepth)return so(Ce,Ee,Ke,"depth-limit",K.maxDepth);let It=Ye==="("?")":"}",Ot=ss(G,Ke+1,j,K,re,oe+1,It),Dt=Ot.next,ft={start:Ke+1,end:Ot.closed?Dt-1:Dt},kt=Lu(G,ft,Ot);if(Ce.push({kind:"group",style:Ye==="("?"subshell":"brace",span:{start:Ke,end:Dt},body:kt}),Ee.push(...Ot.issues),Ot.pendingHeredocs.length>0||Jo(Ot.nodes))Ee.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(Oe.push(...Ot.pendingHeredocs),Ot.limited)return is(Ce,Ee,Ot.next);if(!Ot.closed)Ee.push({code:Ye==="("?"unclosed-subshell":"unclosed-brace-group",message:`${Ye} group is not closed`});Ke=Dt;continue}let Qe=(Ye==="<"||Ye===">")&&G[Ke+1]!=="("?SC(G,Ke):null;if(Qe){let It=we.words.at(-1),Ot=It&&It.span.end===Ke&&/^[0-9]+$/.test(It.raw)?Number(It.raw):void 0;if(Ot!==void 0)we.words.pop();let Dt=Ot===void 0?Ke:It?.span.start??Ke;we.start=we.start===-1?Ke:we.start;let ft=Ke+Qe.length;while(ft<j&&/[ \t]/.test(G[ft]??""))ft++;let kt=G[ft],Ft=ft>Ke+Qe.length&&kt==="#",rn=!kt||Xo(kt)||!!as(G,ft)||kt===de||kt===")"||Ft||(kt==="<"||kt===">")&&G[ft+1]!=="(",Rr=Qe==="<<"||Qe==="<<-",Vt=Rr?pl(G,ft,j):void 0,Bt=Vt?{word:io(G,ft,Vt.next,Vt.delimiter,"literal",Vt.quoted),nested:[],issues:[],next:Vt.next,limited:!1}:!rn?bl(G,ft,j,K,re,oe):void 0;if(Bt){if(Ee.push(...Bt.issues),Bt.limited)return is(Ce,Ee,Bt.next);if(!hl(re))return so(Ce,Ee,Bt.next,"word-limit",K.maxWords)}let un=Bt?.next??Ke+Qe.length,Qt={kind:"redirection",operator:Qe,span:{start:Dt,end:un},...Ot===void 0?{}:{fd:Ot},...Bt?{target:Bt.word}:{}};if(we.redirections.push(Qt),Rr&&!Vt)Ee.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if(Vt){if(Vt.ambiguous||Vt.delimiter.length===0)Ee.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let en=we.nested;Oe.push({delimiter:Vt.delimiter,quotedDelimiter:Vt.quoted,stripTabs:Qe==="<<-",attach:(Rn)=>{if(Qt.heredoc=Rn,Rn.quotedDelimiter)return;let Jn=bC(G,Rn.bodySpan.start,Rn.bodySpan.end,K,re,oe+1);en.push(...Jn.programs),Ee.push(...Jn.issues)}})}if(!Rr&&!Bt)Ee.push({code:"missing-redirection-target",message:`redirection ${Qe} requires a target word`});if(Bt)we.nested.push(...Bt.nested);we.end=un,Ke=un;continue}let mt=we.start===-1;if(mt)yl(Ce,Ee);let Rt=bl(G,Ke,j,K,re,oe);if(Ee.push(...Rt.issues),Rt.limited)return is(Ce,Ee,Rt.next);let pt=MC(we.words)?GC(G,Rt.word,re.maxWords-re.wordsUsed,K.maxDepth,K.maxInputLength):void 0;if(pt?.limitCode)return so(Ce,Ee,Rt.next,pt.limitCode,pt.limitCode==="word-limit"?K.maxWords:pt.limitCode==="depth-limit"?K.maxDepth:K.maxInputLength);let _t=pt?.words??[Rt.word];for(let It of _t){if(!hl(re))return so(Ce,Ee,Rt.next,"word-limit",K.maxWords);we.words.push(It)}if(we.start=we.start===-1?Ke:we.start,we.end=Rt.next,we.nested.push(...Rt.nested),mt&&Ju(Rt.word))Ze();Ke=Rt.next>Ke?Rt.next:Ke+1}return Ze(),Fu(Ce,Ee),Ee.push(...HC(Oe)),{nodes:Ce,issues:Ee,next:Ke,closed:de===void 0,limited:!1,pendingHeredocs:[]}}function Lu(G,U,j){return{kind:"program",dialect:"posix",source:G.slice(U.start,U.end),span:U,status:ls(j.issues,j.limited),issues:j.issues,nodes:j.nodes}}function bl(G,U,j,K,re,oe){let de="",Ce=U,Ee=!1,we="literal",Oe=[],Ze=[],Ke=!1;while(Ce<j){let Ye=G[Ce],Xe=(Ye==="<"||Ye===">")&&G[Ce+1]==="(";if(!Ye||Xo(Ye)||(Ye===";"||Ye==="|"||Ye==="&")&&as(G,Ce)||(Ye==="<"||Ye===">")&&!Xe)break;if(Ye===")")break;if(Ye==="'"){Ee=!0;let mt=G.indexOf("'",Ce+1);if(mt===-1||mt>=j){de+=G.slice(Ce+1,j),Ze.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),Ce=j;break}de+=G.slice(Ce+1,mt),Ce=mt+1;continue}if(Ye==='"'){Ee=!0;let mt=yC(G,Ce,j,K,re,oe);if(de+=mt.text,Oe.push(...mt.nested),Ze.push(...mt.issues),Ke||=mt.limited,we=Zo(we,mt.provenance),Ce=mt.next,Ke)break;continue}if(G.startsWith("$'",Ce)){Ee=!0;let mt=AC(G,Ce+2,j);if(de+=mt.text,Ze.push(...mt.issues),!mt.closed)Ze.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});Ce=mt.next;continue}if(Ye==="\\"){let mt=G[Ce+1];if(!mt){Ze.push({code:"trailing-escape",message:"escape has no following character"}),Ce++;break}if(mt===`
|
|
13
|
+
`){Ce+=2;continue}de+=mt,Ce+=2;continue}if(Mr(G,Ce))Ze.push(Or);let Je=Ye==="$"||Ye==="<"||Ye===">"||Ye==="`"?Qo(G,Ce,j,K,re,oe):null,Qe=Je?Sl(Je,Oe,Ze):ju(G,Ce,j,K,re,oe,Oe,Ze);if(Qe){if(Qe.provenance==="variable")de+=G.slice(Ce,Qe.next);if(Ke||=Qe.limited,we=Zo(we,Qe.provenance),Ce=Qe.next,Ke)break;continue}if(Ye==="$"){let mt=Ku(G,Ce,j,de,we);de=mt.text,we=mt.provenance,Ce=mt.next;continue}if(Ye==="*"||Ye==="?"||Ye==="[")we=Zo(we,"glob");de+=Ye,Ce++}return{word:io(G,U,Ce,de,we,Ee,we==="literal"?void 0:TC(G,U,Ce)),nested:Oe,issues:Ze,next:Ce,limited:Ke}}function yC(G,U,j,K,re,oe){let de="",Ce="literal",Ee=[],we=[],Oe=!1,Ze=U+1;while(Ze<j){let Ke=G[Ze];if(Ke==='"')return{text:de,provenance:Ce,nested:Ee,issues:we,next:Ze+1,limited:Oe};if(Ke==="\\"&&G[Ze+1]){let Je=G[Ze+1]??"";if(Je===`
|
|
14
|
+
`){Ze+=2;continue}if(Je==="\r"&&G[Ze+2]===`
|
|
15
|
+
`){Ze+=3;continue}de+=["$","`",'"',"\\"].includes(Je)?Je:`\\${Je}`,Ze+=2;continue}if(Mr(G,Ze))we.push(Or);let Ye=Qo(G,Ze,j,K,re,oe),Xe=Ye?Sl(Ye,Ee,we):ju(G,Ze,j,K,re,oe,Ee,we);if(Xe){if(Xe.provenance!=="command-substitution")de+=G.slice(Ze,Xe.next);if(Ze=Xe.next,Oe||=Xe.limited,Ce=Zo(Ce,Xe.provenance),Oe)return{text:de,provenance:Ce,nested:Ee,issues:we,next:Ze,limited:Oe};continue}if(Ke==="$"){let Je=Ku(G,Ze,j,de,Ce);de=Je.text,Ce=Je.provenance,Ze=Je.next;continue}de+=Ke??"",Ze++}return we.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:de,provenance:Ce,nested:Ee,issues:we,next:j,limited:Oe}}function Qo(G,U,j,K,re,oe){let de=Uu(G,U);if(!de)return null;let{length:Ce,closing:Ee}=de,we=Ee==="))",Oe=Ee==="`",Ze=G[U]==="<"||G[U]===">",Ke=vl(G,U+Ce,j,Ee),Ye=Ke===-1?j:Ke,Xe=Ke===-1?j:Ke+Ee.length;if(oe>=K.maxDepth)return{program:BC(G,U+Ce,Ye,"depth-limit"),next:Xe,provenance:we?"arithmetic":"command-substitution"};if(we){let _t=[],It=[],Ot=!1,Dt=U+Ce;while(Dt<Ye){let ft=Qo(G,Dt,Ye,K,re,oe+1);if(!ft){if(Mr(G,Dt))It.push(Or);Dt++;continue}if(_t.push(...ft.program.nodes),It.push(...ft.program.issues),Ot||=ft.program.status==="limited",Dt=ft.next,Ot)break}if(Ke===-1)It.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:yn({kind:"program",dialect:"posix",source:G.slice(U+Ce,Ye),span:{start:U+Ce,end:Ye},status:ls(It,Ot),issues:It,nodes:_t}),next:Xe,provenance:"arithmetic"}}let Je=ss(G,U+Ce,Ye,K,re,oe+1),Qe=Ke===-1?[{code:"unclosed-command-substitution",message:`${G.slice(U,U+Ce)} substitution is not closed`}]:[],mt=(Oe||Ze)&&Jo(Je.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[],Rt=Oe&&/\\[\\$`\n]/.test(G.slice(U+Ce,Ye))?[wC]:[],pt=[...Je.issues,...Qe,...mt,...Rt];return{program:yn({kind:"program",dialect:"posix",source:G.slice(U+Ce,Ye),span:{start:U+Ce,end:Ye},status:ls(pt,Je.limited),issues:pt,nodes:Je.nodes}),next:Xe,provenance:"command-substitution"}}function bC(G,U,j,K,re,oe){let de=[],Ce=[],Ee=U;while(Ee<j){let we=G[Ee];if(we==="\\"){Ee+=2;continue}let Oe=we==="$"||we==="`"?Qo(G,Ee,j,K,re,oe):null;if(!Oe){if(Mr(G,Ee))Ce.push(Or);Ee++;continue}if(de.push(Oe.program),vC(G,Ee,Oe.next)&&EC(Oe.program))Ce.push(Or);Ee=Oe.next}return{programs:de,issues:Ce}}function Sl(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 vl(G,U,j,K){if(K==="`"){for(let Ce=U;Ce<j;Ce++){if(G[Ce]==="\\"){Ce++;continue}if(G[Ce]==="`")return Ce}return-1}let re={single:!1,double:!1},oe=[],de=[];for(let Ce=U;Ce<j;Ce++){let Ee=G[Ce];if((Ee===`
|
|
16
|
+
`||Ee==="\r")&&de.length>0){let Ze=Ee==="\r"&&G[Ce+1]===`
|
|
17
|
+
`?Ce+2:Ce+1,Ke=gl(G,Ze,j,de.splice(0));if(!Ke.terminated)return-1;Ce=Ke.next-1;continue}let we=Bu(G,Ce,U,j,re);if(we!==null){Ce=we;continue}if(!re.double&&G.startsWith("$((",Ce)){let Ze=CC(G,Ce+3,j);if(Ze===-1)return-1;Ce=Ze+1;continue}if(K===")"&&!re.double&&Ee==="<"&&G[Ce+1]==="<"&&G[Ce+2]!=="<"){let Ze=G[Ce+2]==="-",Ke=Ce+(Ze?3:2);while(Ke<j&&/[ \t]/.test(G[Ke]??""))Ke++;let Ye=pl(G,Ke,j);if(Ye){de.push({delimiter:Ye.delimiter,quotedDelimiter:Ye.quoted,stripTabs:Ze,attach:()=>{return}}),Ce=Ye.next-1;continue}}if(G.startsWith("$(",Ce)&&!G.startsWith("$((",Ce)){oe.push(re),re={single:!1,double:!1},Ce++;continue}if(Ee==="("&&!re.double){oe.push(re),re={single:!1,double:!1};continue}if(Ee!==")"||re.double)continue;let Oe=oe.pop();if(Oe){re=Oe;continue}return K==="))"&&G[Ce+1]!==")"?-1:Ce}return-1}function CC(G,U,j){let K=1,re={single:!1,double:!1};for(let oe=U;oe<j;oe++){let de=G[oe],Ce=Bu(G,oe,U,j,re);if(Ce!==null){oe=Ce;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 Bu(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!=="#"||!jC(G,U,j))return null;let de=U;while(de+1<K&&G[de+1]!==`
|
|
18
|
+
`&&G[de+1]!=="\r")de++;return de}function as(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 SC(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 Xo(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 Or=Object.freeze({code:"unsupported-function-substitution",message:"${ list; } function substitutions run in the current shell and cannot be analyzed"});function Mr(G,U){if(G[U]!=="$")return!1;let j=Wu(G,U+1);if(G[j]!=="{")return!1;let K=G[Wu(G,j+1)]??"";return K==="|"||Xo(K)}function vC(G,U,j){for(let K=G.indexOf("$",U);K!==-1&&K<j;K=G.indexOf("$",K+1))if(Mr(G,K))return!0;return!1}function EC(G){return G?.status==="limited"||(G?.issues??[]).some((U)=>U.code===Or.code)}function Wu(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 Uu(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 RC=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"}),Hu=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"}),_C=/\$\(|`|[<>]\(/g;function xC(G,U,j){let K=Cl(j);return[...G.slice(U).matchAll(_C)].some((re)=>{let oe=U+re.index;return!K.some((de)=>oe>=de.start&&oe<de.end)})}function Cl(G){return G.flatMap((U)=>{if(U.kind==="command")return[...U.redirections.flatMap((j)=>j.heredoc?[j.heredoc.bodySpan]:[]),...U.nested.flatMap((j)=>Cl(j.nodes))];return U.kind==="group"||U.kind==="function"?Cl(U.body.nodes):[]})}var wC=Object.freeze({code:"unsupported-backtick-escape",message:"a backslash escape inside backticks changes the command the shell runs and cannot be analyzed"});function ju(G,U,j,K,re,oe,de,Ce){if(G[U]!=="$"||G[U+1]!=="{")return null;let Ee=cs(G,U+2,j),we=Ee.close===-1?j:Ee.close+1;if(Ee.close===-1)Ce.push(RC);if(Ee.quoted&&Ee.substitutions.length>0||Ee.continued)Ce.push(Hu);if(Ee.quoted)re.quotedExpansionEnd=Math.min(re.quotedExpansionEnd,we);let Oe=Ee.substitutions.some((Ze)=>{if(Mr(G,Ze))return Ce.push(Or),!1;let Ke=Qo(G,Ze,we,K,re,oe);return Ke!==null&&Sl(Ke,de,Ce).limited});return{provenance:"variable",next:we,limited:Oe}}function cs(G,U,j){let K=[],re=!1,oe=!1,de=1,Ce=U;while(Ce<j){let Ee=G[Ce];if(Ee==="$"&&Mr(G,Ce))K.push(Ce);if(Ee==="\\"||Ee==="'"||Ee==='"'){re=!0,oe||=Ee==="\\"&&G[Ce+1]===`
|
|
20
|
+
`,Ce+=Ee==="\\"?2:1;continue}let we=Uu(G,Ce);if(we){K.push(Ce);let Oe=vl(G,Ce+we.length,j,we.closing);if(Oe===-1)break;Ce=Oe+we.closing.length;continue}if(Ee==="$"&&G[Ce+1]==="{"){de++,Ce+=2;continue}if(Ee==="}"&&--de===0)return{close:Ce,substitutions:K,quoted:re,continued:oe};Ce++}return{close:-1,substitutions:K,quoted:re,continued:oe}}function Vu(G,U,j){if(G[U+1]==="{"){let re=cs(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 AC(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 Ce=PC(G,oe+1,j);if(K+=Ce.text,Ce.invalidCodePoint!==void 0)re.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${Ce.invalidCodePoint}`});oe=Ce.next}return{text:K,next:j,closed:!1,issues:re}}function PC(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 os(G,U+1,j,16,2,U+1);if(K==="u")return os(G,U+1,j,16,4,U+1);if(K==="U")return os(G,U+1,j,16,8,U+1);if(/[0-7]/.test(K))return os(G,U,j,8,3,U+1);return{text:K,next:U+1}}function os(G,U,j,K,re,oe){let de=K===16?/[0-9a-fA-F]/:/[0-7]/,Ce="",Ee=U;while(Ee<j&&Ce.length<re&&de.test(G[Ee]??""))Ce+=G[Ee],Ee++;if(!Ce)return{text:G[oe-1]??"",next:oe};let we=Number.parseInt(Ce,K);return we>1114111||we>=55296&&we<=57343?{text:"�",next:Ee,invalidCodePoint:we}:{text:String.fromCodePoint(we),next:Ee}}function ls(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 Ku(G,U,j,K,re){let oe=Vu(G,U,j);return{text:K+G.slice(U,oe),provenance:Zo(re,"variable"),next:oe}}function TC(G,U,j){let K=rs(G),re=U,oe=!1,de=!1,Ce=U;while(Ce<j){let Ee=G[Ce];if(Ee==="\\"&&!oe){Ce+=2;continue}if(!de&&Ee==="'"){oe=!oe,Ce++;continue}if(!oe&&Ee==='"'){de=!de,Ce++;continue}if(oe){Ce++;continue}let we=G.startsWith("$((",Ce),Oe=G.startsWith("$(",Ce)&&!we,Ze=!de&&(G.startsWith("<(",Ce)||G.startsWith(">(",Ce)),Ke=Ee==="`";if(we||Oe||Ze||Ke){let Ye=we?3:Ke?1:2,Xe=we?"))":Ke?"`":")",Je=vl(G,Ce+Ye,j,Xe),Qe=Je===-1?j:Je+Xe.length;K.push(re,Ce,"literal"),K.push(Ce,Qe,we?"arithmetic":"command-substitution"),Ce=Qe,re=Qe;continue}if(Ee==="$"){let Ye=Vu(G,Ce,j);if(Ye>Ce+1){K.push(re,Ce,"literal"),K.push(Ce,Ye,"variable"),Ce=Ye,re=Ye;continue}}if(!de&&(Ee==="*"||Ee==="?"||Ee==="[")){K.push(re,Ce,"literal"),K.push(Ce,Ce+1,"glob"),Ce++,re=Ce;continue}Ce++}return K.push(re,j,"literal"),K.parts}function Zo(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 IC(G,U,j){return U+1>=j||Xo(G[U+1]??"")||as(G,U+1)!==null}var kC=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),OC=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function MC(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=DC(G,U);if(j===void 0||j===null)return!1;U=j}return!1}function DC(G,U){let j=G[U]?.text.toLowerCase();if(j==="command")return NC(G,U);if(j==="env")return LC(G,U);if(j==="sudo")return WC(G,U);return}function NC(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 LC(G,U){for(let j=U+1;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return j+1;if(kC.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(OC.has(K)){if(G[j+1]===void 0)return null;j++;continue}if(K.startsWith("-"))continue;return j}return G.length}function qu(G,U,j,K){if(G.provenance!=="literal"||!G.raw.includes("{"))return;let re=Yu(G.raw,U,j,K,!0);if(!re)return;if("limited"in re)return{limited:!0};let oe=re.values.map((de)=>Zu(de,j));if(oe.some((de)=>de===null))return{limited:!0};return{words:[...new Set(oe.filter((de)=>de!==null&&de!==""))]}}function GC(G,U,j,K,re){if(U.provenance!=="literal"||!U.raw.includes("{"))return;let oe=Yu(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((Ce)=>Zu(Ce,K));if(de.some((Ce)=>Ce===null))return;return{words:de.filter((Ce)=>Ce!==null&&Ce!=="").map((Ce)=>io(G,U.span.start,U.span.end,Ce,"literal",!1))}}function Yu(G,U,j,K,re){let oe=[G],de=G.length,Ce=0;while(!0){let Ee=oe.findIndex((Ye)=>Gu(Ye,re));if(Ee===-1)break;if(++Ce>j)return{limited:"expansions"};let we=oe[Ee]??"",Oe=Gu(we,re);if(!Oe||Oe.kind==="range")return{limited:"expansions"};let Ze=Oe.start+we.length-Oe.end,Ke=Oe.alternatives.reduce((Ye,Xe)=>Ye+Ze+Xe.length,0);if(de-we.length+Ke>K)return{limited:"length"};if(oe.length-1+Oe.alternatives.length>U)return{limited:"words"};oe.splice(Ee,1,...FC(we,Oe)),de+=Ke-we.length}return Ce===0?void 0:{values:oe}}function Gu(G,U){let j=[],K,re=null,oe=!1;for(let de=0;de<G.length;de++){let Ce=G[de];if(oe){oe=!1;continue}if(Ce==="\\"&&re!=="'"){oe=!0;continue}if(Ce===re){re=null;continue}if(re===null&&(Ce==="'"||Ce==='"')){re=Ce;continue}if(re!==null)continue;if(Ce==="{"){j.push({start:de,commas:[]});continue}if(Ce===","&&j.length>0){j.at(-1)?.commas.push(de);continue}if(Ce!=="}"||j.length===0)continue;let Ee=j.pop();if(!Ee)continue;let we=Ee.commas.length>0?{kind:"alternatives",start:Ee.start,end:de+1,commas:Ee.commas}:U&&$C(G.slice(Ee.start+1,de))?{kind:"range",start:Ee.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:zC(G,K)}}function FC(G,U){return U.alternatives.map((j)=>`${G.slice(0,U.start)}${j}${G.slice(U.end)}`)}function zC(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 $C(G){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(G)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(G)}function Zu(G,U){let j=`x${G}`,K=bl(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 BC(G,U,j,K){return yn({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 so(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 is(G,U,j){return{nodes:G,issues:U,next:j,closed:!1,limited:!0,pendingHeredocs:[]}}function hl(G){return G.wordsUsed++,G.wordsUsed<=G.maxWords}function UC(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 Jo(G){return G.some((U)=>{if(U.kind==="command")return U.redirections.some((j)=>j.heredoc)||U.nested.some((j)=>Jo(j.nodes));return(U.kind==="group"||U.kind==="function")&&Jo(U.body.nodes)})}function HC(G){return G.map((U)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${U.delimiter} was not found`}))}function Xu(G){return G?.kind==="command"||G?.kind==="group"||G?.kind==="function"}function Fu(G,U){let j=G.at(-1);if(j?.kind!=="connector"||!zu.has(j.operator))return;U.push({code:"missing-command-after-connector",message:`connector ${j.operator} requires a following command`})}function Ju(G){return G?.provenance==="literal"&&!G.quoted&&G.raw===G.text&&hC.has(G.text)}function yl(G,U){let j=G.at(-1);if(!Xu(j))return;if(j?.kind==="command"&&Ju(j.words[0]))return;U.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function jC(G,U,j){return U===j||/[\s;&|()]/u.test(G[U-1]??"")}var em=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item","foreach-object","where-object"]),VC=new Set(["gc","cat","type","cp","mv","rm"]),tm=["-rec","-for","-path","-literalpath","-whatif"],KC=/^\$env:\w/i,qC=/^(?:\$\{?\w+\}?|~)\\./;function nm(G,U){let j=G.toLowerCase().replaceAll("`","");if(![...em].some((re)=>j.includes(re))&&!(j.includes("rm")&&tm.some((re)=>j.includes(re)))&&!j.includes("<#")&&!YC(j))return!1;let K=xl(G,U);if(rm(K))return!1;return K.issues.some((re)=>re.code==="unclosed-block-comment"||re.code==="comment-depth-limit")||_l(K).some(ZC)}function rm(G){return G.nodes.some((U)=>{if(U.kind==="group")return rm(U.body);if(U.kind!=="command")return!1;return U.redirections.some((j)=>j.operator==="<<")})}function YC(G){if(G.includes("$env:"))return!0;return G.includes("\\")&&(G.includes("$")||G.includes("~"))}function ZC(G){let U=G[0]==="&"||G[0]==="."?1:0,j=G[U]?.toLowerCase();if(j&&em.has(j))return!0;let K=G.slice(U+1);if(j&&VC.has(j)&&K.some(XC))return!0;if(j!=="rm")return!1;return K.some((re)=>{let oe=re.toLowerCase().split(":",1)[0]??"";return tm.some((de)=>oe.startsWith(de))})}function XC(G){return KC.test(G)||qC.test(G)}function xl(G,U){let j={start:0,end:G.length};if(G.length>U.maxInputLength)return yn({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=wl(G,0,G.length,U,0);return yn({kind:"program",dialect:"powershell",source:G,span:j,status:nS(K.issues,K.limited),issues:K.issues,nodes:K.nodes})}function wl(G,U,j,K,re,oe=!1){let de=[],Ce=[],Ee=ts(),we=0,Oe=!1,Ze=()=>{if(Ee.words.length===0&&Ee.redirections.length===0)return;let Ye={start:Ee.start,end:Ee.end};ns(de,Ee,{kind:"command",dialect:"powershell",source:G.slice(Ye.start,Ye.end),span:Ye,words:Ee.words,redirections:Ee.redirections,nested:Ee.nested,displayText:Ee.words.map((Xe)=>Xe.text).join(" ")})},Ke=U;while(Ke<j){let Ye=G[Ke];if(!Ye)break;if(oe&&Ye==="}")return Ze(),{nodes:de,issues:Ce,next:Ke+1,closed:!0,words:we,limited:Oe};let Xe=tS(G,Ke,j,K.maxDepth);if(Xe){if(Xe.issue)Ce.push(Xe.issue);if(Xe.limited)return Ze(),{nodes:de,issues:Ce,next:Xe.next,closed:!1,words:we,limited:!0};Ke=Xe.next;continue}if(/\s/.test(Ye)){if(Ye==="\r"||Ye===`
|
|
22
|
+
`){Ze();let mt=Ye==="\r"&&G[Ke+1]===`
|
|
23
|
+
`?Ke+2:Ke+1;de.push(El(G,Ke,mt)),Ke=mt;continue}Ke++;continue}let Je=sm(G,Ke);if(Je){Ze(),de.push(El(G,Ke,Ke+Je.length)),Ke+=Je.length;continue}if(Ye==="{"){if(Ze(),re>=K.maxDepth)return Ce.push(im(K.maxDepth)),{nodes:de,issues:Ce,next:j,closed:!1,words:we,limited:!0};let mt=wl(G,Ke+1,j,K,re+1,!0),Rt=mt.closed?mt.next-1:mt.next,pt=yn({kind:"program",dialect:"powershell",source:G.slice(Ke+1,Rt),span:{start:Ke+1,end:Rt},status:mt.limited?"limited":mt.issues.length>0?"partial":"complete",issues:mt.issues,nodes:mt.nodes});if(de.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:Ke,end:mt.next}),body:pt})),Ce.push(...mt.issues),!mt.closed)Ce.push({code:"unclosed-script-block",message:"PowerShell script block is not closed"});we+=mt.words,Oe||=mt.limited,Ke=mt.next;continue}if(Ye==="}"){Ze(),de.push(El(G,Ke,Ke+1)),Ke++;continue}if(Ye===">"||Ye==="<"){Ee.start=Ee.start===-1?Ke:Ee.start;let mt=G[Ke+1]===Ye?Ke+2:Ke+1,Rt=mt;while(/[ \t]/.test(G[Rt]??""))Rt++;let pt=Rt<j?Qu(G,Rt,j,K,re):void 0,_t=pt?.next??mt;if(Ee.redirections.push(Object.freeze({kind:"redirection",operator:G.slice(Ke,mt),span:Object.freeze({start:Ke,end:_t}),...pt?{target:pt.word}:{}})),pt)Ce.push(...pt.issues),Ee.nested.push(...pt.nested),we+=pt.words,Oe||=pt.limited;Ee.end=_t,Ke=_t;continue}if(Ye===","){Ee.start=Ee.start===-1?Ke:Ee.start,Ee.words.push(fl({text:",",raw:",",span:{start:Ke,end:Ke+1},provenance:"literal",quoted:!1})),Ee.end=++Ke;continue}let Qe=Qu(G,Ke,j,K,re);if(Ee.start=Ee.start===-1?Ke:Ee.start,Ee.end=Qe.next,Ee.words.push(Qe.word),Ce.push(...Qe.issues),Ee.nested.push(...Qe.nested),we+=1+Qe.words,Oe||=Qe.limited,we>K.maxWords)return Ce.push({code:"word-limit",message:`command exceeds ${K.maxWords} words`}),Ze(),{nodes:de,issues:Ce,next:Qe.next,closed:!1,words:we,limited:!0};Ke=Qe.next>Ke?Qe.next:Ke+1}return Ze(),{nodes:de,issues:Ce,next:Ke,closed:!oe,words:we,limited:Oe}}function Qu(G,U,j,K,re){let oe="",de="literal",Ce=!1,Ee=[],we=[],Oe=0,Ze=!1,Ke=(Xe)=>{let Je=JC(G,Xe,j,K,re);return oe+=G.slice(Xe,Je.next),we.push(Je.program),Ee.push(...Je.program.issues),Oe+=Rl(Je.program),Ze||=Je.program.status==="limited",de="command-substitution",Je.next},Ye=U;while(Ye<j){let Xe=G[Ye];if(!Xe||/\s/.test(Xe)||sm(G,Ye)||Xe===">"||Xe==="<"||Xe==="#")break;if(Xe===",")break;if(Xe==="`"){let Je=G[Ye+1];if(!Je){Ee.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),Ye++;break}oe+=Je,Ye+=2;continue}if(G.startsWith("$(",Ye)){Ye=Ke(Ye);continue}if(Xe==="'"){Ce=!0,Ye++;let Je=!1;while(Ye<G.length){if(G[Ye]==="'"&&G[Ye+1]==="'"){oe+="'",Ye+=2;continue}if(G[Ye]==="'"){Je=!0,Ye++;break}oe+=G[Ye]??"",Ye++}if(!Je)Ee.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(Xe==='"'){Ce=!0,Ye++;let Je=!1;while(Ye<j){let Qe=G[Ye];if(Qe==="`"&&G[Ye+1]){oe+=G[Ye+1],Ye+=2;continue}if(Qe==='"'){Je=!0,Ye++;break}if(G.startsWith("$(",Ye)){Ye=Ke(Ye);continue}if(Qe==="$")de=G[Ye+1]==="("?"command-substitution":"variable";oe+=Qe??"",Ye++}if(!Je)Ee.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(Xe==="$")de=G[Ye+1]==="("?"command-substitution":"variable";if(Xe==="@"&&Ye===U)de="variable";oe+=Xe,Ye++}return{word:io(G,U,Ye,oe,de,Ce,de==="literal"?void 0:QC(G,U,Ye)),next:Ye,issues:Ee,nested:we,words:Oe,limited:Ze}}function JC(G,U,j,K,re){let oe=om(G,U+2,j),de=oe===-1?j:oe,Ce=oe===-1?j:oe+1;if(re>=K.maxDepth)return{program:yn({kind:"program",dialect:"powershell",source:G.slice(U+2,de),span:{start:U+2,end:de},status:"limited",issues:[im(K.maxDepth)],nodes:[]}),next:Ce};let Ee=wl(G,U+2,de,K,re+1),we=oe===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:yn({kind:"program",dialect:"powershell",source:G.slice(U+2,de),span:{start:U+2,end:de},status:Ee.limited?"limited":Ee.issues.length+we.length>0?"partial":"complete",issues:[...Ee.issues,...we],nodes:Ee.nodes}),next:Ce}}function om(G,U,j){let K=1,re=!1,oe=!1;for(let de=U;de<j;de++){let Ce=G[de];if(Ce==="`"){de++;continue}if(!oe&&Ce==="'"){if(re&&G[de+1]==="'"){de++;continue}re=!re;continue}if(!re&&Ce==='"'){oe=!oe;continue}if(re)continue;if(G.startsWith("$(",de)){K++,de++;continue}if(!oe&&Ce==="(")K++;if(Ce!==")")continue;if(K--,K===0)return de}return-1}function Rl(G){let U=0;for(let j of G.nodes){if(j.kind==="group")U+=Rl(j.body);if(j.kind==="command"){U+=j.words.length;for(let K of j.nested)U+=Rl(K)}}return U}function QC(G,U,j){let K=rs(G),re=U,oe=!1,de=U;while(de<j){let Ce=G[de];if(Ce==="`"){de+=2;continue}if(Ce==="'"){if(oe&&G[de+1]==="'"){de+=2;continue}oe=!oe,de++;continue}if(oe){de++;continue}if(G.startsWith("$(",de)){let Ee=om(G,de+2,j),we=Ee===-1?j:Ee+1;K.push(re,de,"literal"),K.push(de,we,"command-substitution"),de=we,re=we;continue}if(Ce==="$"||Ce==="@"&&de===U){let Ee=eS(G,de+1,j);K.push(re,de,"literal"),K.push(de,Ee,"variable"),de=Ee,re=Ee;continue}de++}return K.push(re,j,"literal"),K.parts}function eS(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 im(G){return{code:"depth-limit",message:`command structure exceeds parser limit ${G}`}}function _l(G){return G.nodes.flatMap((U)=>{if(U.kind==="group")return _l(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(_l)]})}function sm(G,U){for(let j of["&&","||",";","|"])if(G.startsWith(j,U))return j;return null}function tS(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 nS(G,U){if(U)return"limited";if(G.some((j)=>j.code==="unclosed-block-comment"))return"invalid";return G.length>0?"partial":"complete"}function El(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=mr){if(U==="powershell"||U==="auto"&&nm(G.slice(0,j.maxInputLength),j))return xl(G,j);return $u(G,j)}function t(G){return G.provenance==="command-substitution"?G.raw:G.text}function ne(G,U){return G==="posix"?U:Zt(U.map((j)=>j.text))}function ao(G,U){return G&&G.provenance!=="unknown"?G.provenance==="literal":!/[$`*?[\]]/.test(U)}function Zt(G){return G.map((U)=>({kind:"word",text:U,raw:U,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function Al(G,U){return{value:G,work:U}}function Pt(G,U){if(G.work)G.work.units=Math.min(Number.MAX_SAFE_INTEGER,G.work.units+1);return G.value[U]}function Jt(G){return G.value.length}function ei(G,U,j=1){if(G)G.units=Math.min(Number.MAX_SAFE_INTEGER,G.units+U.length*j)}function An(G,U){ei(G,U)}function Dr(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 qt(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 Pl(G){return G===`
|
|
25
|
+
`||G==="\r"||G==="\u2028"||G==="\u2029"}function Yt(G,U,j){if(U+j.length>Jt(G))return!1;for(let K=0;K<j.length;K++)if(Pt(G,U+K)!==j[K])return!1;return!0}function tr(G,U,j){return!Dr(Pt(G,U-1))&&Yt(G,U,j)&&!Dr(Pt(G,U+j.length))}function nr(G,U){return Dr(Pt(G,U-1))!==Dr(Pt(G,U))}function ln(G){return G===`
|
|
26
|
+
`||G===";"||G==="&"||G==="|"}function lo(G){return G==="|"||G===";"}function ds(G,U,j){let K=Al(G,j);if(U==="rm")return rS(K);if(U==="dd")return iS(K);return mm(K,!0)}function us(G,U,j){let K=Al(G,j);if(U==="rm")return sS(K);if(U==="reset-hard")return dm(K,"--ha","rd");if(U==="reset-merge")return dm(K,"--me","rge");if(U==="clean")return dS(K);if(U==="checkout")return mS(K);if(U==="push-force")return fS(K);if(U==="push-refspec")return pS(K);if(U==="push-delete")return gS(K);if(U==="branch")return hS(K);if(U==="tag")return CS(K);if(U==="restore")return SS(K);return mm(K,!1)}function rS(G){let U=!1,j=!1,K=!1,re=-1;for(let oe=0;oe<=Jt(G);oe++){let de=Pt(G,oe);if(!U){let Ee=Pt(G,oe+2);if(tr(G,oe,"rm")&&qt(Ee)&&Ee!==`
|
|
27
|
+
`)U=!0,oe++;continue}let Ce=oS(G,oe);if(de===`
|
|
28
|
+
`||Ce!==-1){if(U=!1,j=!1,K=!1,re=-1,Ce!==-1)oe=Ce-1;continue}if(de===";"||de==="&"||de==="|"||oe===Jt(G)){if(re>=0){let Ee=am(G,re,oe);j||=Ee.recursive,K||=Ee.force}if(j&&K)return!0;U=!1,j=!1,K=!1,re=-1;continue}if(qt(de)){if(re<0)continue;if(Yt(G,re,"--")&&oe-re===2){U=!1,j=!1,K=!1,re=-1;continue}let Ee=am(G,re,oe);if(j||=Ee.recursive,K||=Ee.force,j&&K)return!0;re=-1;continue}if(re<0)re=oe}return!1}function oS(G,U){if(Pt(G,U)!=="\\"||Pt(G,U-1)==="\\")return-1;if(Yt(G,U,String.raw`\n`))return U+2;if(Yt(G,U,String.raw`\x0a`)||Yt(G,U,String.raw`\x0A`))return U+5;if(Yt(G,U,String.raw`\u000a`)||Yt(G,U,String.raw`\u000A`))return U+7;return Yt(G,U,String.raw`\012`)?U+4:-1}function am(G,U,j){if(lm(G,U,j,"recursive"))return{recursive:!0,force:!1};if(lm(G,U,j,"force"))return{recursive:!1,force:!0};if(Pt(G,U)!=="-"||Pt(G,U+1)==="-")return{recursive:!1,force:!1};let K=!1,re=!1;for(let oe=U+1;oe<j;oe++){let de=Pt(G,oe);K||=de==="r"||de==="R",re||=de==="f"||de==="F"}return{recursive:K,force:re}}function lm(G,U,j,K){let re=j-U-2;if(re<1||re>K.length||!Yt(G,U,"--"))return!1;for(let oe=0;oe<re;oe++)if(Pt(G,U+oe+2)!==K[oe])return!1;return!0}function iS(G){let U=!1;for(let j=0;j<Jt(G);j++){if(ln(Pt(G,j))){U=!1;continue}if(tr(G,j,"dd")){U=!0,j++;continue}if(!U||!tr(G,j,"of")||!Yt(G,j,"of=/dev/"))continue;let K=j+8;if(K<Jt(G)&&!qt(Pt(G,K))&&Pt(G,K)!=="'"&&Pt(G,K)!=='"')return!0}return!1}function sS(G){let U=!1,j=!1,K=!1;for(let re=0;re<=Jt(G);){let oe=Pt(G,re);if(re===Jt(G)||ln(oe)){U=!1,j=!1,K=!1,re++;continue}let de=lS(G,re);if(de>=0){if(aS(G,de))return!0;let Ce=de,Ee=!1;while(qt(Pt(G,Ce)))Ee||=Pt(G,Ce)===`
|
|
29
|
+
`,Ce++;if(Ee)j=!1,K=!1;U=!0,re=Ce;continue}if(!U){re++;continue}if(Yt(G,re,"--")&&(re===0||qt(Pt(G,re-1)))&&(!Pt(G,re+2)||qt(Pt(G,re+2))||ln(Pt(G,re+2)))){U=!1,j=!1,K=!1,re+=2;continue}if(j||=Yt(G,re,"--recursive")&&nr(G,re+11)||Tl(G,re,"recursive"),K||=Yt(G,re,"--force")&&nr(G,re+7)||Tl(G,re,"force"),j&&K)return!0;re++}return!1}function Tl(G,U,j){if(!Yt(G,U,"--"))return!1;let K=0;while(K<=j.length){let re=Pt(G,U+K+2);if(!re||qt(re)||ln(re))break;if(re!==j[K])return!1;K++}return K>0&&nr(G,U+K+2)}function aS(G,U){let j=U,K=!1,re=!1;while(j<Jt(G)){while(qt(Pt(G,j)))j++;let oe=j;while(j<Jt(G)&&!qt(Pt(G,j)))j++;if(Pt(G,oe)!=="-"||j-oe===2&&Yt(G,oe,"--"))return!1;let de=cm(G,oe,"recursive"),Ce=cm(G,oe,"force");if(K&&Ce||re&&de)return!0;if(K||=de,re||=Ce,Pt(G,oe+1)==="-")continue;let Ee=cS(G,oe,j);if(Ee.combined||K&&Ee.forceAtBoundary||re&&Ee.recursiveAtBoundary)return!0;K||=Ee.recursive,re||=Ee.force}return!1}function cm(G,U,j){return Yt(G,U,`--${j}`)&&nr(G,U+j.length+2)||Tl(G,U,j)}function lS(G,U){if(U>0&&Dr(Pt(G,U-1)))return-1;let j=U;if(Pt(G,j)==="\\")j++;if(Pt(G,j)!=="r")return-1;if(j++,Pt(G,j)==="\\")j++;if(Pt(G,j)!=="m"||!qt(Pt(G,j+1)))return-1;return j+1}function cS(G,U,j){let K=!1,re=!1,oe=!1,de=!1,Ce=!1;if(Pt(G,U)!=="-")return{recursive:K,force:re,recursiveAtBoundary:oe,forceAtBoundary:de,combined:Ce};let Ee="";for(let we=U+1;we<j;we++){let Oe=Pt(G,we)??"",Ze=(Oe==="r"||Oe==="f")&&nr(G,we+1);K||=Oe==="r",re||=Oe==="f",oe||=Oe==="r"&&Ze,de||=Oe==="f"&&Ze,Ce||=(Ee==="r"&&Oe==="f"||Ee==="f"&&Oe==="r")&&Ze,Ee=Oe}return{recursive:K,force:re,recursiveAtBoundary:oe,forceAtBoundary:de,combined:Ce}}function dm(G,U,j){return ni(G,"reset",lo,!0,(K)=>Pt(G,K)==="-"&&co(G,K,U,j)?!0:K)}function dS(G){return ni(G,"clean",lo,!0,(U)=>{if(Pt(G,U)!=="-")return U;if(co(G,U,"--fo","rce"))return!0;let j=ti(G,U,lo);for(let K=U+1;K<j;K++)if(Pt(G,K)==="f")return!0;return j-1})}function ms(G,U,j){if(!tr(G,U,"git"))return null;let K=U+3;if(!qt(Pt(G,K)))return{commandEnd:-1,next:K};while(qt(Pt(G,K)))K++;while(K<Jt(G)){if(ln(Pt(G,K)))return{commandEnd:-1,next:K};let re=ti(G,K,ln);if(tr(G,K,j))return{commandEnd:K+j.length,next:re};if(Pt(G,K)!=="-")return{commandEnd:-1,next:re};let oe=re-K===2&&Yt(G,K,"--"),de=uS(G,K,re);K=re;while(qt(Pt(G,K)))K++;if(oe)return{commandEnd:tr(G,K,j)?K+j.length:-1,next:ti(G,K,ln)};if(!de)continue;if(K>=Jt(G)||ln(Pt(G,K)))return{commandEnd:-1,next:K};K=ti(G,K,ln);while(qt(Pt(G,K)))K++}return{commandEnd:-1,next:K}}function uS(G,U,j){for(let K of _n)if(j-U===K.length&&Yt(G,U,K))return!0;return!1}function mS(G){return um(G,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function fS(G){return ni(G,"push",lo,!0,(U)=>{if(Pt(G,U)!=="-")return U;if(Pt(G,U+1)==="f"&&!Dr(Pt(G,U+2))&&!Yt(G,U+2,"-with-lease"))return!0;let j=fm(G,U,"--fo","rce");if(j>=0&&!Yt(G,j,"-with-lease"))return!0;return U})}function pS(G){return ni(G,"push",ln,!1,(U)=>{if(qt(Pt(G,U))&&Pt(G,U+1)==="+"&&U+2<Jt(G)&&!ln(Pt(G,U+2))&&!qt(Pt(G,U+2)))return!0;if(Pt(G,U)===":"&&Pt(G,U+1)==="+")return!0;return U})}function gS(G){return ni(G,"push",ln,!1,(U)=>{if(Pt(G,U)==="-"&&co(G,U,"--de","lete"))return!0;if(qt(Pt(G,U))&&Pt(G,U+1)===":"&&U+2<Jt(G)&&!qt(Pt(G,U+2))&&!ln(Pt(G,U+2)))return!0;return U})}function hS(G){let U=!1,j=!1,K=!1;for(let re=0;re<=Jt(G);re++){if(re===Jt(G)||ln(Pt(G,re))){if(j&&K)return!0;U=!1,j=!1,K=!1;continue}if(!U){let Ce=ms(G,re,"branch");if(Ce){U=Ce.commandEnd>=0,re=Math.max(re,(U?Ce.commandEnd:Ce.next)-1);continue}}if(!U||Pt(G,re)!=="-")continue;let oe=ti(G,re,ln),de=yS(G,re,oe);if(j||=de.deletion,K||=de.force,j&&K)return!0;re=oe-1}return!1}function yS(G,U,j){let K=!1,re=!1;for(let oe=U;oe<j;oe++){if(Pt(G,oe)!=="-")continue;if(co(G,oe,"--de","lete"))K=!0;if(co(G,oe,"--fo","rce"))re=!0;if(Pt(G,oe+1)==="-")continue;let de=oe+1,Ce=!1,Ee=!1,we=!1;while(de<j&&bS(Pt(G,de))){let Oe=Pt(G,de);Ce||=Oe==="d"||Oe==="D",Ee||=Oe==="f",we||=Oe==="D",de++}if(!nr(G,de))continue;K||=Ce,re||=Ee||we}return{deletion:K,force:re}}function bS(G){if(!G)return!1;let U=G.charCodeAt(0);return U>=65&&U<=90||U>=97&&U<=122}function CS(G){return um(G,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function um(G,U){let j=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let K=0;K<Jt(G);K++){let re=Pt(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==="$"&&Pt(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(qt(re))oe.shortActive=!1,oe.hasShortFlag=!1;if(!oe.outerActive){let Ce=ms(G,K,U.command);if(Ce){oe.outerActive=Ce.commandEnd>=0&&qt(Pt(G,Ce.commandEnd)),oe.shortActive=!1,oe.hasShortFlag=!1,K=Math.max(K,(oe.outerActive?Ce.commandEnd:Ce.next)-1);continue}}if(oe.outerActive&&re==="-"){if(co(G,K,U.longPrefix,U.longOptional))return!0;oe.shortActive||=!U.excludedShortStarts.includes(Pt(G,K+1)??"")}if(oe.hasShortFlag||=oe.shortActive&&re===U.shortFlag,oe.hasShortFlag&&nr(G,K+1))return!0;if(lo(re))oe.outerActive=!1}return!1}function ni(G,U,j,K,re){let oe=!1;for(let de=0;de<Jt(G);de++){let Ce=Pt(G,de),Ee=j(Ce);if(!oe&&!Ee){let we=ms(G,de,U);if(we){oe=we.commandEnd>=0&&(!K||qt(Pt(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 Oe=de;Oe<=we;Oe++)if(j(Pt(G,Oe)))oe=!1;de=we}if(Ee)oe=!1}return!1}function SS(G){let U=!1;for(let j=0;j<Jt(G);j++){if(Pl(Pt(G,j))){if(U)return!0;U=!1;continue}if(!U){let K=ms(G,j,"restore");if(K){U=K.commandEnd>=0,j=Math.max(j,(U?K.commandEnd:K.next)-1);continue}}if(U&&Pt(G,j)==="-"&&Pt(G,j+1)==="-"&&(Yt(G,j+2,"staged")||Yt(G,j+2,"help")))U=!1}return U}function mm(G,U){let j=!1;for(let K=0;K<Jt(G);K++){let re=Pt(G,K),oe=U?Pl(re):ln(re);if(j&&qt(re)&&Pt(G,K+1)==="-"&&tr(G,K+2,"delete"))return!0;if(oe){j=!1;continue}if(tr(G,K,"find"))j=!0,K+=3}return!1}function ti(G,U,j){let K=U;while(K<Jt(G)&&!qt(Pt(G,K))&&!j(Pt(G,K)))K++;return K}function fm(G,U,j,K){if(!Yt(G,U,j))return-1;let re=U+j.length;for(let oe=0;oe<K.length&&Pt(G,re)===K[oe];oe++)re++;return nr(G,re)?re:-1}function co(G,U,j,K){return fm(G,U,j,K)>=0}function Dn(G,U){ei(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 Ce=de.caseSensitive?G:j;if(de.regex)An(U,Ce);if((de.regex?.test(Ce)??!1)||de.scan&&us(Ce,de.scan,U))return At("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 vS=/^[A-Za-z_][A-Za-z0-9_]*=/;function gm(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;ei(j,U.source,2);let oe={anchored:new RegExp(`^\\$\\{?${re}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${re}(?![A-Za-z0-9_])`)};return hm(U.nodes,K,oe)}function hm(G,U,j){return G.every((K)=>{if(K.kind==="connector")return!0;if(K.kind==="group"||K.kind==="function")return hm(K.body.nodes,U,j);if(K.kind==="unknown")return!j.loose.test(K.source);return ES(K,U,j)})}function ES(G,U,j){if(G.nested.some((re)=>j.loose.test(re.source)))return!1;let K=G.words.findIndex((re)=>!vS.test(re.text));return G.words.every((re,oe)=>re===U||pm(re.raw,j.anchored,oe!==K))&&G.redirections.every((re)=>(!re.heredoc||re.heredoc.quotedDelimiter||!j.loose.test(re.heredoc.body))&&(!re.target||pm(re.target.raw,j.anchored,!0)))}function pm(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}var RS="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",_S="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",xS="This erases or repartitions a disk. Run disk erase and partition commands manually after confirming the target.",wS="This output redirect overwrites a disk device. Run device writes manually after confirming the target.",AS="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.",PS=new Set(["of=/dev/null","of=/dev/zero","of=/dev/full"]),ym=/^(?:mkfs(?:\..+)?|mke2fs|newfs(?:_.+)?)$/,TS=new Set(["diskutil","wipefs","sgdisk","parted"]),IS=new Set(["erasedisk","erasevolume","reformat","partitiondisk","zerodisk","randomdisk","secureerase"]),kS=/^(?:-[^-]*[ao]|--all$|--offset(?:=|$))/,OS=new Set(["-p","--print","-i","--info","-v","--verify","-O","--print-mbr","-E","--end-of-largest","-F","--first-in-largest","-f","--first-aligned-in-largest","-D","--display-alignment","-L","--list-types","-P","--pretend","-b","--backup","-V","--version","-?","--help","--usage"]),MS=new Set(["p","v","O","E","F","f","D","L","P","V","?"]),DS=new Set(["i","b"]),NS=/^\/dev\/(?:r?disk\d|sd[a-z]|hd[a-z]|vd[a-z]|xvd[a-z]|nvme\d|mmcblk\d|md\d|dm-\d|loop\d|mapper\/|disk\/)/,LS=new Set([">",">|",">>","<>",">&"]),WS=new Set(["mklabel","mktable","mkpart","rm","resizepart"]);function bm(G){return G==="dd"||G==="shred"||ym.test(G)||TS.has(G)}function GS(G,U){let j=U.some((K)=>K.startsWith("/dev/"));if(G==="diskutil"){let K=U.find((re)=>!re.startsWith("-"));return K!==void 0&&IS.has(K.toLowerCase())}if(G==="wipefs")return j&&U.some((K)=>kS.test(K));if(G==="sgdisk")return j&&U.some((K)=>K.startsWith("-")&&!FS(K));return G==="parted"&&j&&U.some((K)=>WS.has(K.toLowerCase()))}function FS(G){if(OS.has(G.split("=",1)[0]??G))return!0;if(G.startsWith("--"))return!1;let U=G.slice(1).split("");return DS.has(U[0]??"")||U.every((j)=>MS.has(j))}function Cm(G,U){let j=U.slice(1);if(G==="dd"&&j.some((K)=>/^of=\/dev\/.+/.test(K)&&!PS.has(K)))return At("dd.device-write",RS);if(ym.test(G)&&j.some((K)=>K.startsWith("/dev/")))return At("mkfs.device",_S);if(GS(G,j))return At("disk.erase",xS);if(G==="shred"&&j.length>0)return At("shred.target",AS);return null}function Sm(G){return G.some((U)=>LS.has(U.operator)&&U.target?.provenance==="literal"&&NS.test(U.target.text))?At("redirect.block-device",wS):null}import{isAbsolute as zS,resolve as vm}from"node:path";function ri(G,U,j,K){let re=zS(G)?vm(G):U?vm(U,G):void 0;if(!re)return;try{return zt(re,j,K)}catch{return re}}function Em(G){return!["/dev","/proc","/sys"].some((U)=>G===U||G.startsWith(`${U}/`))}var uo="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",oi="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.",kl=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),$S=new Set(["-p","--print"]),BS=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),US=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"])]]),jS=new Map([["python",new Set(["m"])]]),VS=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"])]]),KS=new Set(["always","default","never"]),qS=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),YS=/\\\r?\n/g,ZS=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 Rm(G){return ps(G).code}function fs(G){return ps(G).sources}function _m(G){return ZS.get(Ml(G))??[]}function ps(G){let U=Ml(G[0]??"");if(!kl.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 zn(U,j,K,re,G[oe+1]===void 0?void 0:oe+1,G[oe+1]);if(de===""||de==="-"||!de.startsWith("-"))return zn(U,j,K,re,oe,de);if(U==="node"&&$S.has(de)){let Ze=G[oe+1];if(Ze===void 0)return zn(U,j,K,re);if(Ze.startsWith("-"))continue;j.push({tokenIndex:oe+1,value:Ze}),K.push({tokenIndex:oe+1,kind:"inline-code",value:Ze}),oe++;continue}if(JS(U,de)){let Ze=G[oe+1];if(Ze===void 0)return zn(U,j,K,re);if(j.push({tokenIndex:oe+1,value:Ze}),K.push({tokenIndex:oe+1,kind:"inline-code",value:Ze}),U==="python")return zn(U,j,K,re);oe++;continue}let Ce=/^--eval=(.*)$/s.exec(de);if(QS(U)&&Ce){let Ze=Ce[1]??"";j.push({tokenIndex:oe,value:Ze}),K.push({tokenIndex:oe,kind:"inline-code",value:Ze});continue}if(U==="node"){let Ze=XS(de);if(Ze){if(Ze.attached){if(re&&=Ze.value!=="",Ze.value!=="")K.push({tokenIndex:oe,kind:"module-file",value:Ze.value});continue}let Ke=G[oe+1];if(Ke===void 0||Ke.startsWith("-"))return re=!1,zn(U,j,K,re);K.push({tokenIndex:oe+1,kind:"module-file",value:Ke}),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 zn(U,j,K,re);if(VS.get(U)?.has(de)){let Ze=G[oe+1];if(Ze===void 0||Ze.startsWith("-")&&!(U==="ruby"&&qS.has(de))||U==="python"&&!KS.has(Ze))return zn(U,j,K,re);oe++;continue}if(de.startsWith("--"))continue;let Ee,we=!1;for(let Ze=1;Ze<de.length;Ze++){let Ke=de[Ze];if(Ke===void 0)break;if(jS.get(U)?.has(Ke)){let Ye=de.slice(Ze+1),Xe=Ye||G[oe+1];if(Xe!==void 0)K.push({tokenIndex:Ye?oe:oe+1,kind:"module-file",value:Xe});return zn(U,j,K,re)}if(BS.get(U)?.has(Ke)){Ee=de.slice(Ze+1)||G[oe+1],we=Ze+1===de.length;break}if(U==="node"&&Ke==="r"){if(re&&=de==="-r",de==="-r"){let Ye=G[oe+1];if(re&&=Ye!==void 0&&!Ye.startsWith("-"),re&&Ye!==void 0)K.push({tokenIndex:oe+1,kind:"module-file",value:Ye});oe++}break}if(U==="ruby"&&Ke==="r"){let Ye=de.slice(Ze+1),Xe=Ye||G[oe+1];if(re&&=Xe!==void 0,Xe!==void 0)K.push({tokenIndex:Ye?oe:oe+1,kind:"module-file",value:Xe});if(!Ye)oe++;break}if(U==="perl"&&(Ke==="M"||Ke==="m")){let Ye=de.slice(Ze+1);if(!Ye){if(re=!1,Ze+1===de.length)oe++;break}K.push({tokenIndex:oe,kind:"module-file",value:Ye});break}if(US.get(U)?.has(Ke)){if(Ze+1===de.length)oe++;break}if(HS.get(U)?.has(Ke)&&Ze+1<de.length)break}if(Ee===void 0)continue;let Oe=we?oe+1:oe;if(j.push({tokenIndex:Oe,value:Ee}),K.push({tokenIndex:Oe,kind:"inline-code",value:Ee}),U==="python")return zn(U,j,K,re);if(we)oe++}return zn(U,j,K,re,void 0,void 0,!0)}function zn(G,U,j,K,re,oe,de=!1){let Ce=G==="node"?U.slice(-1):U,Ee=new Set(Ce.map((Oe)=>Oe.tokenIndex)),we=j.filter((Oe)=>Oe.kind!=="inline-code"||Ee.has(Oe.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"?Ce[0]?.value:Ce.map((Oe)=>Oe.value).join(`
|
|
30
|
+
`))||null,sources:K?we:[],optionsOpen:K&&de}}function XS(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 Ol(G,U){return Ml(G)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(U)}function Ml(G){let U=Nt(G).toLowerCase();return $i.test(U)?"python":U}function JS(G,U){return kl.get(G)?.has(U)??!1}function QS(G){return kl.get(G)?.has("--eval")??!1}function ii(G,U,j=!1){let K=nv(G,U);if(!Il(K,U))return!1;An(U,K);let re=tv(K);if(Il(re,U))return!0;if(An(U,re),!xm.test(re))return!1;return!j||ev(K,U)}function ev(G,U){if(/`|%x|\bqx\b/.test(G))return!0;let K=G.split(""),re=[];for(let Ee=0;Ee<G.length;Ee++){let we=G[Ee];if(we!=="'"&&we!=='"')continue;let Oe=G.startsWith(we.repeat(3),Ee)?we.repeat(3):we,Ze=Ee+Oe.length,Ke=Ze;while(Ke<G.length&&!G.startsWith(Oe,Ke))Ke+=G[Ke]==="\\"?2:1;if(Ke>=G.length)return!0;re.push({start:Ze,text:G.slice(Ze,Ke)}),K.fill(" ",Ee,Ke+Oe.length),Ee=Ke+Oe.length-1}let oe=K.join(""),de=Array.from(oe.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((Ee)=>xm.test(Ee[1]??"")).map((Ee)=>{let we=Ee.index+Ee[0].length;return{start:we,end:gs(oe,we)}});if(de.some((Ee)=>Dl(oe,Ee.start)))return!0;return re.some((Ee)=>{let we=/\b(?:system|exec|spawn|popen)\s*$/.test(oe.slice(0,Ee.start)),Oe=de.some((Ze)=>Ee.start>=Ze.start&&Ee.start<Ze.end);return(we||Oe)&&Il(Ee.text,U)})}function gs(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 Dl(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 xm=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function tv(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 Il(G,U){if(ds(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(An(U,G),K.test(G))return!0;if(ds(G,"dd",U))return!0;for(let K of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(An(U,G),K.test(G))return!0;if(ds(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)=>(An(U,G),j.some((re)=>us(re,K))))}function nv(G,U){return An(U,G),G.replace(YS,"")}import{lstatSync as Jv,readdirSync as Qv}from"node:fs";import{basename as eE,isAbsolute as Jm,join as tE,relative as Qm}from"node:path";import{isAbsolute as Om,parse as mv}from"node:path";import{dirname as rv,isAbsolute as ov,parse as iv,sep as sv}from"node:path";function fr(G,U,j){if(Qn(U))throw Error("Unsupported Windows namespace path");let K=ov(U)?iv(U).root:"",re=K||G;for(let oe of lv(K?U.slice(K.length):U)){if(oe===""||oe===".")continue;if(oe===".."){re=rv(re);continue}let de=av(re,oe),Ce=j.entryKind(de),Ee=Ce==="symlink"?j.realpath(de):de;if(Ce==="missing"||Ee===null)throw Error(`Cannot resolve path component: ${de}`);re=Ee}return re}function av(G,U){return G.endsWith("/")||G.endsWith("\\")?`${G}${U}`:`${G}${sv}${U}`}function lv(G){let U=process.platform==="win32"?/[\\/]+/:/\/+/;return G.split(U)}var Nl=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],cv=new Set(Nl),dv=1024,wm=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),Am=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),uv=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function hs(G){return cv.has(G)}function Ll(G){return hs(G)||wm.has(G)||Am.has(G)||Go(G)}function rr(G,U,j){return j?.has(G)?j.get(G):U.get(G)}function Pm(G,U){let j=rr("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<=dv?{state:"valid",count:K}:{state:"invalid"}}function ys(G,U,j){let re=G.match(uv)?.[1];if(!re||!Ll(re))return null;let oe=G.indexOf("=");return{name:re,value:`${rr(re,U,j)??""}${G.slice(oe+1)}`}}function Tm(G){return km(G,Am)}function Im(G){return km(G,wm)}function km(G,U){if(!G)return!1;for(let j of G.keys())if(U.has(j))return!0;return!1}var Dm=/^[A-Za-z_][A-Za-z0-9_]*=/;function Nn(G){if(!Dm.test(G))return null;let U=G.indexOf("=");return{name:G.slice(0,U),value:G.slice(U+1)}}function Se(G){let U=new Map,j=0;while(j<G.length){let K=G[j];if(!K)break;let re=Nn(t(K));if(!re)break;U.set(re.name,re.value),j++}return{words:G.slice(j),envAssignments:U}}function Nm(G){let U=Wt(G);return G.includes("=")||U==="sudo"||U==="env"||U==="command"||U==="builtin"}function Nr(G,U,j,K){if(!Nm(mo(G)))return{words:G,envAssignments:new Map,cwd:j,rewritten:!1};let re=new Set(G),oe=G,de=new Map,Ce=new Map(K??[]),Ee=[],we=j;for(let Ze=0;Ze<a.wrapperPeelIterations.cap;Ze++){let Ke=Mm(oe),Ye=Se(oe);for(let[Je,Qe]of Ye.envAssignments)de.set(Je,Qe),Ce.set(Je,Qe);if(oe=Ye.words,oe.length===0)break;while(oe.length>0&&mo(oe).includes("=")&&!pv(oe)){let Je=gv(mo(oe),Ce,U.env)??ys(mo(oe),U.env,Ce);if(Je)de.set(Je.name,Je.value),Ce.set(Je.name,Je.value);oe=oe.slice(1)}if(oe.length===0)break;let Xe=Wt(mo(oe));if(Xe!=="sudo"&&Xe!=="env"&&Xe!=="command"&&Xe!=="builtin")break;if(Xe==="sudo"){let Je=yv(oe,U.paths,we);if(oe=Je.words,Je.cwd!==void 0)we=Je.cwd}if(Xe==="env"){let Je=Sv(oe,we,Ce,U);if(Ee.push(...Je.envSplitValues??[]),oe=Je.words,Je.cwd!==void 0)we=Je.cwd;for(let[Qe,mt]of Je.envAssignments)de.set(Qe,mt),Ce.set(Qe,mt)}if(Xe==="command")oe=vv(oe);if(Xe==="builtin")oe=oe.slice($n(oe,1)==="--"?2:1);if(Mm(oe)===Ke)break}let Oe=Se(oe);for(let[Ze,Ke]of Oe.envAssignments)de.set(Ze,Ke),Ce.set(Ze,Ke);return{words:Oe.words,envAssignments:de,cwd:we,envSplitValues:Ee.length>0?Ee:void 0,rewritten:fv(Oe.words,re)}}function fv(G,U){return G.some((j)=>!U.has(j))}function Mm(G){return G.map(t).join(" ")}function mo(G){let U=G[0];return U?t(U):""}function $n(G,U){let j=G[U];return j?t(j):void 0}function pv(G){return Dm.test(mo(G))}function gv(G,U,j){if(!G.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${U.get("TMPDIR")??j.get("TMPDIR")??""}${G.slice(8)}`}}var hv=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function yv(G,U,j){let K=1,re=j;while(K<G.length){let oe=$n(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=$n(G,K+1);re=de?si(re,de,U):null,K+=2;continue}if(oe.startsWith("--chdir=")){re=si(re,oe.slice(8),U),K++;continue}if(oe.startsWith("-D")&&oe.length>2){re=si(re,oe.slice(2),U),K++;continue}if(oe==="-i"||oe==="--login"){re=null,K++;continue}if(hv.has(oe)){K+=2;continue}K++}return{words:G.slice(K),cwd:re}}var bv=new Set(["-i","-0","--null"]),Cv=new Set(["-u","--unset","-C","--chdir","-P"]);function Sv(G,U,j,K){let re=new Map,oe=[],de=U,Ce=1,Ee=(we)=>({words:G.slice(we),envAssignments:re,cwd:de,envSplitValues:oe.length>0?oe:void 0});while(Ce<G.length){let we=$n(G,Ce);if(!we)break;if(we==="--")return Ee(Ce+1);if(we==="-i"||we==="--ignore-environment"||we==="-"){re.clear();for(let Ze of j.keys())re.set(Ze,"");re.set("TMPDIR",""),Ce++;continue}if(bv.has(we)){Ce++;continue}if(we==="-u"||we==="--unset"){let Ze=$n(G,Ce+1);if(Ze!==void 0)re.set(Ze,"");Ce+=2;continue}if(we.startsWith("-u")&&we.length>2&&!we.startsWith("-u=")){re.set(we.slice(2),""),Ce++;continue}if(we.startsWith("--unset=")){re.set(we.slice(8),""),Ce++;continue}let Oe=we==="-S"||we==="--split-string"?{value:$n(G,Ce+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(Oe){if(Oe.value!==void 0)oe.push(Oe.value);return de=null,Ee(Ce+Oe.consumed)}if(Cv.has(we)){if(we==="-C"||we==="--chdir"){let Ze=$n(G,Ce+1);de=Ze?si(de,Ze,K.paths):null}Ce+=2;continue}if(we.startsWith("-u=")){Ce++;continue}if(we.startsWith("-C")&&we.length>2||we.startsWith("--chdir=")){let Ze=we.startsWith("--chdir=")?we.slice(8):we.startsWith("-C=")?we.slice(3):we.slice(2);de=si(de,Ze,K.paths),Ce++;continue}if(we.startsWith("-P")){Ce++;continue}if(we.startsWith("-")){Ce++;continue}if(!Nn(we))break;while(Ce<G.length){let Ze=Nn($n(G,Ce)??"");if(!Ze)break;re.set(Ze.name,Ze.value),Ce++}if($n(G,Ce)==="--")Ce++;return Ee(Ce)}return Ee(Ce)}function si(G,U,j){if(U==="")return null;if(!G&&!Om(U))return null;let K=Om(U)?mv(U).root:j.realpath(G??"/");if(K===null)return null;try{return fr(K,U,j)}catch{return null}}function vv(G){if($n(G,1)==="-v")return[...Zt(["type"]),...G.slice(2)];let U=1;while(U<G.length){let j=$n(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 Ev=/['"\\$`{}#]/;function bs(G,U){if(G.some((K)=>Ev.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 pr(G,U,j){return Cs(G,U,j).tokens}function Rv(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 gr(G,U,j,K=0){let re=Cs(G,U,j),oe=(re.envSplitValues??[]).flatMap(Rv);if(oe.length===0)return re.tokens;let de=[...oe,...re.tokens];if(K>=8)return de;return gr(de,U,j,K+1)}function Cs(G,U,j,K){if(!Nm(G[0]??""))return{tokens:[...G],envAssignments:new Map,cwd:j};let re=Nr(Zt(G),U,j,K);return{tokens:re.words.map(t),envAssignments:re.envAssignments,cwd:re.cwd,envSplitValues:re.envSplitValues}}var Fl=Symbol("adopt-as-operand"),_v=new Set(["env","sudo","command","builtin"]),xv=new Set(["&&","||","|&","|","&",";"]),wv=new Set(["<<","<<<",">|"]),Lm=new Set(["|","|&"]),Av=/[*@#?$!_-]/,Pv=/^\w+(?::\w+)*/,Tv=Object.freeze([]),ai=Object.freeze({kind:"scope",edge:"enter"}),li=Object.freeze({kind:"scope",edge:"exit"}),Iv=Object.freeze([]),kv=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),ci=new Set(["bash","sh","zsh","dash","ksh"]),Ov=256,$m=new WeakMap;function Bm(G,U){let j=U.status==="complete"?new Set(Gl(U)):new Set,K=Nv(G,j);if(Ui(K))return Ss("unclosed-quote",K,U);let re={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},oe=Lr(U,{source:K,suppressed:j,flags:re,depth:0,functions:new Map,powershell:U.dialect==="powershell"});if(re.limited)return Ss("structural-limit",K,U);if(re.invalid)return Ss("invalid",K,U);let de=Ss("complete",K,U,re.assignmentFallbacks);return $m.set(de,Object.freeze(oe)),de}function Rs(G,U,j,K,re){let oe=re.word??((Xe)=>Xe),de={cwd:U,variables:new Map,previous:null},Ce=[],Ee=new Set,we=null,Oe=[],Ze=Um(G),Ke=Ze.findLastIndex((Xe)=>Xe.kind==="operator"&&Lm.has(Xe.operator)),Ye=Ke!==-1&&Ze.some((Xe)=>Xe.kind==="redirection"&&Xe.operator==="<<"&&Xe.body===void 0);for(let[Xe,Je]of Ze.entries()){let Qe=Ye||Xe<=Ke;if(Je.kind==="scope"){if(Je.edge==="enter"){Oe.push({state:de,segment:[...Ce],shellWords:new Set(Ee),pipeProducer:we});continue}let mt=re.segment(Ce,de,we,null,Ee,Qe);if(mt)return mt;let Rt=Oe.pop();if(Rt===void 0)throw Error("scope exit without a matching enter");de=Rt.state,Ce=Rt.segment,Ee=Rt.shellWords,we=Rt.pipeProducer;continue}if(Je.kind==="operator"){if(!Je.boundary)continue;let mt=re.segment(Ce,de,we,Je.operator,Ee,Qe);if(mt)return mt;de=Mv(Ce,de,j,K),we=Ce.length>0&&Lm.has(Je.operator)?Ce:null,Ce=[],Ee=new Set;continue}if(Je.kind==="redirection"){if(Je.fd!==void 0)Ee.add(Ce.length-1);if(Je.target===void 0)continue;let mt=re.redirection({operator:Je.operator,role:Je.role,targetOrder:Je.targetOrder,target:Je.target,...Je.body===void 0?{}:{body:Je.body,consumer:Je.consumer}},de,Qe);if(mt===Fl){Ee.add(Ce.length),Ce.push(oe(Je.target));continue}if(mt)return mt;continue}Ce.push(oe(Je.text))}return re.segment(Ce,de,we,null,Ee,Ye)}function _s(G){return Um(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 bn(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 Ce=re.startsWith(":")?de!=="":!0;if(re.endsWith("-"))return Ce?de:bn(oe,U);return Ce?bn(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 di(G){return G.length>0&&G.every((U)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(U))}function Mv(G,U,j,K){let re=di(G)?new Map([...U.variables,...Dv(G,U.variables)]):U.variables,oe=pr([...G],j),de=Nt(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:fn(bn(de,re),U.cwd,j,K),variables:re,previous:U.cwd}}function Dv(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],bn(re,U)]]:[]})}function Um(G){return $m.get(G)??Tv}function Nv(G,U){return[...U].reduce((j,K)=>j.slice(0,K.start)+" ".repeat(K.end-K.start)+j.slice(K.end),G)}function Ss(G,U,j,K=Iv){return Object.freeze({status:G,source:U,program:j,assignmentFallbacks:Object.freeze(K)})}function Lr(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:[Bn($v(G.operator))]}];if(G.kind==="unknown")return[{start:G.span.start,events:[Bn(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?"}":")"),Ce=oe?K:{...K,functions:new Map(K.functions)};return[{start:G.span.start,events:oe?[vs("{"),...Lr(G.body,Ce),...de?[vs("}")]:[]]:[ai,Bn("("),...Lr(G.body,Ce),...de?[Bn(")")]:[],li]}]}let re=jv(G,K.functions);if(re){if(K.depth>=mr.maxDepth||++K.flags.expansions>Ov)return K.flags.limited=!0,[];return[{start:G.span.start,events:[...Wm(G,K),vs(";"),...Lr(re,{...K,depth:K.depth+1}),vs(";")]},...Gm(G,U,j,K)]}return[{start:G.span.start,events:Wm(G,K)},...Gm(G,U,j,K)]}function Wm(G,U){return[...G.words.map((j)=>({start:j.span.start,events:jm(j,G,U,!1)})),...G.redirections.map((j)=>({start:j.span.start,events:Wv(j,G,U)}))].sort((j,K)=>j.start-K.start).flatMap((j)=>j.events)}function Wv(G,U,j){let K=G.operator==="<<-"?"<<":G.operator,re=G.target?jm(G.target,U,j,!0):[],oe=re[0],de=oe?.kind==="word"?oe.text:void 0;return[...G.fd===void 0?[]:[zl(String(G.fd))],Object.freeze({kind:"redirection",operator:K,...G.fd===void 0?{}:{fd:G.fd},role:Bv(K),targetOrder:wv.has(K)?"legacy-segment":"immediate",...de===void 0?{}:{target:de},...G.heredoc&&j.suppressed.has(G.heredoc.bodySpan)?{body:G.heredoc.body,consumer:Km(U)}:{}}),...de===void 0?re:re.slice(1)]}function Gm(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 Ce=[zl(de.delimiter),.../[\r\n]/.test(K.source[de.terminatorSpan.end]??"")?[Bn(";")]:[]];if(K.suppressed.has(de.bodySpan))return[{start:de.bodySpan.start,events:Ce}];return[{start:de.bodySpan.start,events:[...Hm(K.source.slice(de.bodySpan.start,de.bodySpan.end),K),...Ce]}]}),...re.some((oe)=>!oe.heredoc&&oe.target)?Gv(U,j,K):[]]}function Gv(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:Hm(j.source.slice(K.span.end,G.span.end),j)}]}function Hm(G,U){if(U.depth>=mr.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=Lr(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 jm(G,U,j,K){let re=[],oe={single:!1,double:!1},de="",Ce=!1,Ee=()=>{let we=Ce&&!K?Bn("glob"):de!==""||G.quoted&&re.length===0?zl(de):void 0;if(we)re.push(we);de="",Ce=!1};for(let we of G.parts){if(we.provenance!=="command-substitution"&&we.provenance!=="arithmetic"){for(let Ye of Wl(we.raw,oe,j.flags,j.powershell)){if(typeof Ye==="string"){Ee(),re.push(Bn(Ye));continue}de+=Ye.text,Ce||=Ye.glob}continue}let Oe=U.nested.find((Ye)=>Ye.span.start>=we.span.start&&Ye.span.end<=we.span.end);if(oe.double){let Ye=j.source.slice(we.span.start,we.span.end);de+=Wl(Ye,{single:!1,double:!0},j.flags,j.powershell).map((Je)=>typeof Je==="string"?Je:Je.text).join("");let Xe=Oe?Lr(Oe,j).filter((Je)=>Je.kind==="redirection"&&Je.body!==void 0):[];if(Xe.length>0)re.push(ai,...Xe,li);continue}let Ze=Oe?Lr(Oe,j):[];if(we.raw.startsWith("`")){de+="${}",Ee(),re.push(ai,...Ze,li);continue}if(we.raw.startsWith("<(")||we.raw.startsWith(">(")){Ee(),re.push(we.raw.startsWith("<(")?Bn("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),ai,...Ze,...we.raw.endsWith(")")?[Bn(")")]:[],li);continue}let Ke=we.raw.startsWith("$((")?2:1;de+="${}",Ee(),re.push(...Array.from({length:Ke},()=>Bn("(")),...Ke===1?[ai]:[],...Ze,...we.raw.endsWith(")".repeat(Ke))?Array.from({length:Ke},()=>Bn(")")):[],...Ke===1?[li]:[])}return Ee(),re}function Wl(G,U,j,K){let re=[],oe="",de=!1,Ce=0;while(Ce<G.length){let Ee=G[Ce]??"";if(!U.single&&!U.double&&(Ee==="("||Ee===")")){re.push({text:oe,glob:de},Ee),oe="",de=!1,Ce++;continue}if(K&&Ee==="`"&&!U.single){oe+=G[Ce+1]??"",Ce+=2;continue}if(U.single&&Ee==="'"){U.single=!1,Ce++;continue}if(U.single){oe+=Ee,Ce++;continue}if(U.double){if(Ee==='"'){U.double=!1,Ce++;continue}if(!K&&Ee==="\\"){let we=G[Ce+1]??"";oe+=['"',"\\","$"].includes(we)?we:`\\${we}`,Ce+=2;continue}if(Ee==="$"){let we=Fm(G,Ce,U,j,K);oe+=we.text,Ce=we.next;continue}oe+=Ee,Ce++;continue}if(Ee==="'"||Ee==='"'){U.single=Ee==="'",U.double=Ee==='"',Ce++;continue}if(!K&&Ee==="\\"){let we=G[Ce+1]??"";de||=we==="*"||we==="?",oe+=we,Ce+=2;continue}if(Ee==="$"){let we=Fm(G,Ce,U,j,K);oe+=we.text,Ce=we.next;continue}de||=Ee==="*"||Ee==="?",oe+=Ee,Ce++}return[...re,{text:oe,glob:de}]}function Fm(G,U,j,K,re){let oe=G[U+1];if(oe==="{"){let Ce=re?zv(G,U+2):cs(G,U+2,G.length).close;if(Ce===-1)return K.invalid=!0,{text:"",next:G.length};let Ee=G.slice(U,Ce+1);return Fv(Ee,j,K,re),{text:Ee,next:Ce+1}}if(oe!==void 0&&Av.test(oe))return{text:`\${${oe}}`,next:U+2};let de=(re?Pv:/^\w*/).exec(G.slice(U+1))?.[0]??"";return{text:`\${${de}}`,next:U+1+de.length}}function Fv(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),Ce=[":=","="].find((we)=>de.startsWith(we));if(!Ce)return;let Ee=Wl(de.slice(Ce.length),{...U},j,K);j.assignmentFallbacks.push(...Ee.flatMap((we)=>typeof we==="string"||!we.text?[]:[we.text]))}function zv(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 $v(G){return/^[\r\n]+$/.test(G)?";":G}function Bn(G){return Object.freeze({kind:"operator",operator:G,boundary:xv.has(G)})}function vs(G){return Object.freeze({kind:"operator",operator:G,boundary:!0})}function zl(G){return Object.freeze({kind:"word",text:G})}function Bv(G){if(G==="<<"||G==="<<<")return"here-data";if(G==="<"||G==="<&")return"file-read";return"file-write"}function fo(G){return kv.has(G)||/^python\d/.test(G)}var Uv=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 Vm(G,U){let j=U[0];if(j===void 0||!j.startsWith("-"))return U;let K=Uv.get(G)?.has(j)??!1;return Vm(G,U.slice(K?2:1))}function Es(G){let U=G[0];if(U===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(U))return Es(G.slice(1));if(U==="uv"&&G[1]==="run")return Es(G.slice(2));if(!_v.has(U))return[...G];return Es(Vm(U,G.slice(1)))}function Km(G){let U=Yo(G),j=G.words.findIndex((K)=>K.provenance==="literal"&&K.text===U);return Es(j<0?[]:G.words.slice(j).map((K)=>K.text))}function Hv(G){let U=Km(G)[0];if(U===void 0)return!1;let j=Nt(U).toLowerCase();return fo(j)&&!ci.has(j)}function Gl(G){return G.nodes.flatMap((U,j)=>{if(U.kind==="group"||U.kind==="function")return Gl(U.body);if(U.kind!=="command")return[];let K=U.nested.flatMap((Ce)=>Gl(Ce)),re=U.redirections.flatMap((Ce)=>Ce.heredoc?.quotedDelimiter?[Ce.heredoc.bodySpan]:[]);if(Hv(U))return[...K,...re];let oe=G.nodes[j+1];if(oe?.kind==="connector"&&(oe.operator==="|"||oe.operator==="|&")||!Kv(U))return K;return[...K,...re]})}function jv(G,U){let j=Yo(G);return j===void 0?void 0:U.get(j)}function hr(G,U){return G!==void 0&&G.provenance==="literal"&&!G.quoted&&G.raw===G.text&&G.text===U}function Vv(G){if(hr(G.words[0],"git"))return hr(G.words[1],"commit");if(!hr(G.words[0],"gh")||!hr(G.words[2],"create"))return!1;return hr(G.words[1],"pr")||hr(G.words[1],"issue")}function Kv(G){return(hr(G.words[0],"cat")||hr(G.words[0],"tee")||Vv(G))&&!G.words.some(zm)&&!G.redirections.some((j)=>zm(j.target))}function zm(G){return G?.parts.some((U)=>U.provenance==="command-substitution"&&U.raw.startsWith(">("))??!1}var qm=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Ym=new Set([...qm,"glob"]),qv=new Set([...Ym,"folder","pattern","patterns"]);class b extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Zm(G){let U=Yv(),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 Ce=oe.findIndex((Oe)=>Oe.source===de.source);if(Ce!==-1){let Oe=oe[Ce];if(!Oe)return oe;return oe[Ce]={...Oe,usages:[...Oe.usages,de.usage]},oe}let Ee=G.route.kind==="command"?G.route.shell:process.platform==="win32"?"powershell":"posix",we=U.getCommandProgram(de.source,Ee);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:Zv(G),store:U}}function Cn(G,U){return G.commands.find((j)=>j.usages.includes(U))}function or(G,U){if(!G.includes("$"))return G;return Ca(G,U)}function Yv(){let G=new Map,U=new WeakMap,j=(re,oe)=>{let de=`${oe}\x00${re}`,Ce=G.get(de);if(Ce)return Ce;let Ee=y(re,oe);return G.set(de,Ee),Ee};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"),Ce=U.get(de);if(Ce)return Ce;let Ee=de.status==="limited"?{status:"structural-limit",source:re,program:de,assignmentFallbacks:[]}:Bm(re,de);return U.set(de,Ee),Ee},getCommandProgram:j}}function Zv(G){let U=G.route.kind==="grep"?Ym:G.route.kind==="glob"?qv:qm;return[...vd(G.input,U),...G.route.kind==="patch"||typeof G.input==="string"?_d(G.input):[]]}var Xv=new Set(["-S","--suffix"]);function po(G,U,j,K,re){if(G.status==="structural-limit")throw new b;if(G.status!=="complete")return re.findMalformedTarget(G.source);return Rs(G,U,j,K,{segment:(oe,de)=>re.findSegmentTarget(oe,de),redirection:(oe,de)=>oe.role==="file-write"&&re.isRedirectionTarget(bn(oe.target,de.variables),de)?oe.target:null})}function xs(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&&Xv.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 v="Git metadata and hooks are protected. Ask the user before modifying them.";function ef(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(Mi(G.invocation.toolName))return null;let Ce=G.paths.find((Ee)=>Xm(Ee,re,U,j,K,U.entries));return Ce?{target:Ce}:null}if(G.invocation.route.kind!=="command")return null;let oe=Cn(G,"input-candidate");if(!oe)return null;let de=po(oe.shell,re,j,K,{findSegmentTarget:(Ce,Ee)=>aE(Ce,Ee,U,j,K),isRedirectionTarget:(Ce,Ee)=>Xm(Ce,Ee.cwd,U,j,K,U.markerFiles),findMalformedTarget:()=>null});return de?{target:de}:null}function Wr(G,U,j,K,re,oe,de=!1){if(!j)return!1;let Ce=As(fn(G,U,re,oe)),Ee=Ce.replace(/(\/\.?\*+)+$/,"");if(Ee!==Ce&&Ee!==""){if($l(Ee,j))return!0;let we=de||Ce.slice(Ee.length).includes("/."),Oe=(Ze)=>we?ws(Ze,Ee):nE(Ze,Ee);if(j.markerFiles.some(Oe))return!0;return K&&Bl(j).some(Oe)}if($l(Ce,j))return!0;return K&&Bl(j).some((we)=>ws(we,Ce))}function nE(G,U){let j=Qm(U,G);if(j===""||j.startsWith("..")||Jm(j))return!1;return!j.split(/[\\/]/)[0]?.startsWith(".")}function rE(G,U,j,K,re){return Wr(G,U,j,!0,K,re)}function oE(G,U,j,K,re){if(!j)return!1;return $l(As(fn(G,U,K,re)),j)}function Xm(G,U,j,K,re,oe){let de=As(fn(G,U,K,re));return oe.includes(de)||nf(de,j)}function tf(G,U,j,K,re){if(!j)return!1;return j.hooksDirectories.some((oe)=>G.some((de)=>ws(oe,As(fn(de,U,K,re)))))}function $l(G,U){return U.entries.includes(G)||U.directories.includes(G)||nf(G,U)}function nf(G,U){return U.hooksDirectories.some((j)=>ws(G,j))}var iE=50000;function rf(G,U){let j=[...new Set(Bl(G))];if(j.some((re)=>U(eE(re))))return!0;let K=0;while(j.length>0){let re=j.pop()??"",oe=sE(re);if(!oe)return!0;if(K+=oe.length,K>iE)return!0;if(oe.some((de)=>U(de.name)))return!0;j.push(...oe.filter((de)=>de.isDirectory()).map((de)=>tE(re,de.name)))}return!1}function sE(G){try{let U=Jv(G,{throwIfNoEntry:!1});if(!U)return[];if(!U.isDirectory())return U.isSymbolicLink()?null:[];return Qv(G,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function Bl(G){return[...G.entries,...G.directories,...G.hooksDirectories]}function ws(G,U){let j=Qm(U,G);return j===""||!/^\.\.(?:[\\/]|$)/.test(j)&&!Jm(j)}function As(G){return process.platform==="win32"?G.toLowerCase():G}function aE(G,U,j,K,re){if(di(G))return null;let oe=gr([...G],K);if(Nt(oe[0]??"").toLowerCase()!=="mv")return null;let de=xs(oe.slice(1)),Ce=de.sources.find((Ee)=>rE(bn(Ee,U.variables),U.cwd,j,K,re));if(Ce)return Ce;return de.destination&&oE(bn(de.destination,U.variables),U.cwd,j,K,re)?de.destination:null}import{isAbsolute as ks,normalize as gE,parse as hE,posix as mf,resolve as Fr,sep as Vl}from"node:path";import{isAbsolute as lE,join as of,normalize as lf,parse as cE,sep as sf}from"node:path";var dE=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],uE=`
|
|
31
|
+
`;function ui(G,U){if(Gr(G,U))return!0;if(!G.has("TMPDIR"))return!1;return!Ul(G.get("TMPDIR")??"",U)}function go(G,U){if(G.has("TMPDIR"))return Ul(G.get("TMPDIR")??"",U);let j=Hl(G,U);if(j===void 0)return!0;return Ul(j,U)}function Hl(G,U){return df(G,U,"TMPDIR")}function Ul(G,U){if(!G)return!1;if(fE(G))return!1;return ho(G,U)}function Gr(G,U){let j=df(G,U,"IFS");return j!==void 0&&j!==""&&j!==uE}function ho(G,U){let j=Ps(G,U.paths);if(j===null)return!1;return cf(U).some((K)=>yo(j,K))}function Is(G,U){let j=Ps(G,U.paths);if(j===null)return!1;return cf(U).some((K)=>Ts(K)===Ts(j))}var af=new WeakMap;function cf(G){let U=af.get(G);if(U)return U;let j=mE(G);return af.set(G,j),j}function mE(G){let U=dE.map((K)=>Ps(K,G.paths)??lf(K)),j=Ps(G.tmpdir,G.paths);if(!j)return U;if(process.platform==="win32")return[...U,j];if(process.platform==="darwin"&&pE(j))return[...U,j];return U}function fE(G){return/[\s$`*?[]/.test(G)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(G)||/[+@!]\([^)]*\)/.test(G)}function df(G,U,j){return G.has(j)?G.get(j):U.env.get(j)}function pE(G){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(G)}function Ps(G,U){try{let j=lf(G);if(!lE(j))return j;let K=cE(j).root,re=j.slice(K.length).split(/[\\/]+/).filter(Boolean),oe=K;for(let de=0;de<re.length;de++){let Ce=of(oe,re[de]??"");if(U.entryKind(Ce)==="missing")return of(Ce,...re.slice(de+1));let Ee=U.realpath(Ce);if(Ee===null)return null;oe=Ee}return oe}catch{return null}}function yo(G,U){let j=Ts(G),K=Ts(U);if(j===K)return!0;let re=K.endsWith(sf)?K:`${K}${sf}`;return j.startsWith(re)}function Ts(G){return process.platform==="win32"?G.toLowerCase():G}var yE=process.platform==="win32",uf=64,bE=16384;function zr(G,U,j,K){if(G.kind==="temp_target")return null;let re=K[G.kind];if(G.kind==="dynamic_target"&&!tn(j,re.id,U.strict))return null;if(G.kind==="within_anchored_cwd"&&!tn(j,re.id,U.paranoid))return null;return At(re.id,re.reason)}function mi(G){let U=qu(G,uf,uf,bE);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:CE(G)}}function CE(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)=>SE(G.raw,j.span.start-G.span.start))}function SE(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 qn(G){let U=G.environment.home,j=G.environment.paths,K=G.budget??kn();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:wE(G.allowPaths,U,j,K),protectedGitMetadata:G.protectedGitMetadata,budget:K}}function Pn(G,U,j={}){let K=j.targetIsLiteral??!1;if(!K&&U.tmpdirWordSplittingUnsafe&&!j.tmpdirWordSplittingProtected&&PE(G))return{kind:"outside_anchored_cwd"};let re=!K&&pf(G,U.posixShell);if(Qn(G))return{kind:"outside_anchored_cwd"};if(Kl(G,K))return{kind:"root_or_home_target"};if(EE(G,U,K))return{kind:"root_or_home_target"};if(U.resolvedCwd&&Wr(G,U.resolvedCwd,U.protectedGitMetadata,!0,U.environment,U.budget,!U.posixShell))return{kind:"git_metadata_target"};if(RE(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(AE(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)=>ME(G,U.resolvedCwd??oe,U.environment.paths,U.budget,de)))return{kind:"cwd_self_target"};if(DE(G,oe,U.resolvedCwd??oe,re,K,U.environment.paths,U.budget))return{kind:"within_anchored_cwd"}}if(vE(G,U,re))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function vE(G,U,j){let K=G.trim();if(j||!U.resolvedCwd||!U.anchoredCwd||!K)return!1;if(ks(K)||K.startsWith("~"))return!1;if(ql(K))return!1;if(gf(U.resolvedCwd,U.anchoredCwd,U.environment.paths,U.budget))return!1;return ho(Fr(U.resolvedCwd,K),U.environment)}function ff(G,U,j={}){let{containmentTarget:K,...re}=j;if(Pn(G,U,re).kind!=="temp_target")return!1;let oe=G.trim();if(xE(oe))return!1;if(Is(oe,U.environment))return!1;return![U.anchoredCwd,U.resolvedCwd].some((de)=>gf(K??oe,de,U.environment.paths,U.budget))}function Kl(G,U=!1){let j=G.trim(),K=mf.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 EE(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=ks(re)?re:U.resolvedCwd?Fr(U.resolvedCwd,re):null;if(!oe)return!1;let de=Sn(zt(oe,U.environment.paths,U.budget));if(de===hE(de).root)return!0;return de===Sn(zt(U.environment.home,U.environment.paths,U.budget))}catch{return!1}}function Sn(G){let U=gE(G);if(yE){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 RE(G,U,j,K,re,oe,de,Ce){let Ee=G.trim();if(ql(Ee))return!1;if(!K&&ho(Ee,Ce))return!0;return(U||oe&&de)&&j&&!re&&_E(Ee,j)}function _E(G,U){return["$TMPDIR","${TMPDIR}"].some((j)=>{if(G===j)return!0;if(!G.startsWith(`${j}/`))return!1;return!pf(G.slice(j.length+1),U)})}function xE(G){let U=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(G);if(!U)return!1;return mf.normalize(`/${U[1]??""}`)==="/"}function ql(G){return G.split(/[\\/]+/).includes("..")}function wE(G,U,j,K){if(!G?.length)return[];return G.flatMap((re)=>{let oe=Vo(re.trim(),U);if(!ks(oe))return[];try{let de=zt(oe,j,K);if(Ko(de,zt(U,j,K)))return[];return[Sn(de)]}catch{return[]}})}function AE(G,U,j){if(U.allowRoots.length===0)return!1;let K=G.trim();if(ql(K))return!1;let re=j?K:Vo(K,U.environment.home),oe=U.resolvedCwd??U.anchoredCwd,de=ks(re)?re:oe?Fr(oe,re):null;if(!de)return!1;try{let Ce=Sn(zt(de,U.environment.paths,U.budget));return U.allowRoots.some((Ee)=>Ce===Ee||Ce.startsWith(Ee.endsWith(Vl)?Ee:`${Ee}${Vl}`))}catch{return!1}}function PE(G){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(G)}function pf(G,U=!1){return G.includes("$")||G.includes("`")||TE(G)||U&&IE(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 IE(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==="{"&&kE(G,j)||(K==="+"||K==="@"||K==="!")&&G[j+1]==="(")return!0}return!1}function kE(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 Sn(zt(G,j,K))===Sn(zt(U,j,K))}catch{try{return Sn(G)===Sn(U)}catch{return!1}}}function ME(G,U,j,K,re=U){if(re===U&&(G==="."||G==="./"||G===".\\"))return!0;try{return Sn(zt(Fr(U,G),j,K))===Sn(zt(re,j,K))}catch{try{return Sn(Fr(U,G))===Sn(re)}catch{return!1}}}function DE(G,U,j,K,re,oe,de){let Ce=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 jl(G,U,oe,de)}catch{return!1}if(G.startsWith("./")||G.startsWith(".\\")||!G.includes("/")&&!G.includes("\\"))try{return jl(Fr(Ce,G),U,oe,de)}catch{return!1}if(G.startsWith("../"))return!1;try{return jl(Fr(Ce,G),U,oe,de)}catch{return!1}}function jl(G,U,j,K){try{return hf(zt(G,j,K),zt(U,j,K))}catch{return!1}}function gf(G,U,j,K){if(!U)return!1;try{return hf(zt(U,j,K),zt(G,j,K))}catch{return!0}}function hf(G,U){let j=Sn(G),K=Sn(U);return j.startsWith(`${K}${Vl}`)||j===K}var NE=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),yf="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.",bf="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.",WE="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",GE="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",FE={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:v},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:bf},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:WE},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:yf},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:LE},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:yf}};function Sf(G,U,j){return zE(G.words.map((K)=>({kind:"word",text:K.text,dynamic:K.provenance!=="literal"})),U,qn({...j,allowPaths:j.policy?.destructiveCommandAllowPaths}),j.policy)}function zE(G,U,j,K){let re=G.filter((Ee)=>Ee.kind==="word"),oe=BE(re),de=re[oe];if(!de||!NE.has(XE(de.text)))return null;let Ce=$E(re.slice(oe+1));if(Ce.whatIfProtected)return null;if(tn(K,"powershell.remove-item-pipeline-dynamic-target",j.strict)&&U&&(Ce.targets.length===0||Ce.recursive))return At("powershell.remove-item-pipeline-dynamic-target",GE);for(let Ee of Ce.targets)if(!Qn(Ee.text)&&Kl(fi(Ee.text)))return At(Ce.recursive&&Ce.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Cf);for(let Ee of Ce.targets)if(j.resolvedCwd&&Wr(fi(Ee.text),j.resolvedCwd,j.protectedGitMetadata,Ce.recursive,j.environment,j.budget,!0))return At("powershell.remove-item-git-metadata",v);if(!Ce.recursive||!Ce.force)return null;if(tn(K,"powershell.remove-item-recursive-force-dynamic-target",j.strict)&&(Ce.hasDynamicTarget||Ce.targets.length===0))return At("powershell.remove-item-recursive-force-dynamic-target",bf);for(let Ee of Ce.targets){let we=zr(Pn(fi(Ee.text),j),j,K,FE);if(we)return we}return null}function $E(G){let U=[],j=!1,K=!1,re=!1,oe=!1,de=!1;for(let Ce=0;Ce<G.length;Ce++){let Ee=G[Ce];if(!Ee||Ee.kind!=="word")continue;if(UE(Ee))continue;if(de){U.push(Yl(Ee)),oe=oe||Ee.dynamic;continue}if(Ee.text==="--"){de=!0;continue}let we=jE(Ee.text);if(!we){U.push(Yl(Ee)),oe=oe||Ee.dynamic;continue}if(VE(we.name)){let Oe=we.value?HE(we.value,Ee):G[++Ce];if(Oe?.kind==="word"){U.push(Yl(Oe)),oe=oe||Oe.dynamic;continue}oe=!0;continue}if(KE(we.name)){j=!0;continue}if(qE(we.name)){K=!0;continue}if(YE(we.name))re=ZE(we.value)}return{targets:U,recursive:j,force:K,whatIfProtected:re,hasDynamicTarget:oe}}function BE(G){let U=G[0];if(U?.kind==="word"&&U.text==="&"||U?.text===".")return G.length>1?1:0;return 0}function Yl(G){return{text:G.kind==="word"?G.text:"",dynamic:G.kind==="word"&&G.dynamic}}function UE(G){return G.kind==="word"&&G.text===","}function fi(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 jE(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 VE(G){return"path".startsWith(G)||"literalpath".startsWith(G)}function KE(G){return"recurse".startsWith(G)}function qE(G){return G.length>=2&&"force".startsWith(G)}function YE(G){return G==="wi"||"whatif".startsWith(G)}function ZE(G){if(G===void 0||G==="")return!0;let U=G.toLowerCase();return U==="$true"||U==="true"}function XE(G){return G.toLowerCase()}var bo="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",Os="Unsupported heredoc syntax",pi="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function Co(){return{id:"analysis.dynamic-shell-source",reason:pi,intent:"stop_and_explain"}}var vf="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var JE=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),QE=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),eR=new Set(["-o","--output","--query","--subscription"]),tR=new Set;function Ef(G){if(G==="aws")return JE;if(G==="gcloud")return QE;if(G==="az")return eR;return tR}var nR=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),rR=new Set;function Rf(G){if(G==="git")return _n;if(G==="docker")return nR;return rR}function D(G,U){if(G.length===0||U.length===0)return null;let j=Wt(G[0]??""),K=hn(G);for(let re of U){if(!sR(j,re.command))continue;if(re.match){if(oR(j,G,re.match))return _f(re);continue}if(!aR(j,G,re.subcommand))continue;if(cR(G,new Set(re.block_args),K))return _f(re)}return null}function _f(G){return{id:`custom.${G.name}`,reason:`[${G.name}] ${G.reason}`,intent:G.intent??"manual_only"}}function oR(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 iR(K,j.command_path,Ef(G))}function iR(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 sR(G,U){return G===Wt(U)}function aR(G,U,j){if(!j)return!0;return xf(U,1,j,Rf(G))}function xf(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 Ce=G[oe+1];if(Ce&&!Ce.startsWith("-"))return Ce===j;return!1}if(K.has(de)){re=!0;continue}if(de.startsWith("-")){if(!de.includes("=")&&lR(G,oe,j,K))return!0;continue}return de===j}return!1}function lR(G,U,j,K){let re=G[U+1];if(!re||re.startsWith("-"))return!1;return xf(G,U+2,j,K)}function cR(G,U,j){return G.some((K)=>U.has(K))||[...j].some((K)=>U.has(K))}var dR=new Set(["-e","--source"]),uR=new Set(["-F","-v","--assign","--field-separator"]),wf=new Set(["-f","--file"]),mR=new Set(["print","printf","return"]),Af=[{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"}],fR="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 Pf(G,U,j){let K=!1;for(let re of pR(G)){let oe=gR(re,j);if(!oe)continue;for(let de of oe.commands){let Ce=U(de);if(Ce)return Ce;if(de.includes("{}")||/[$`]/.test(de))K=!0}K||=oe.dynamic}return K?At("awk.system-dynamic",fR):null}function Xl(G){let U=[],j=!1,K=!1,re=!0,oe=!0;for(let de=1;de<G.length;de++){let Ce=G[de];if(Ce===void 0)break;if(re&&Ce==="--"){re=!1;continue}if(re&&dR.has(Ce)){j=!0;let Ee=G[de+1];if(oe&&=Ee!==void 0,Ee!==void 0)U.push({tokenIndex:de+1,kind:"inline-code",value:Ee});de++;continue}if(re&&Ce.startsWith("--source=")){j=!0,U.push({tokenIndex:de,kind:"inline-code",value:Ce.slice(9)});continue}if(re&&Ce.startsWith("-e")&&Ce.length>2){j=!0,U.push({tokenIndex:de,kind:"inline-code",value:Ce.slice(2)});continue}if(re&&(uR.has(Ce)||wf.has(Ce))){let Ee=G[de+1];if(oe&&=Ee!==void 0,wf.has(Ce)){if(K=!0,Ee!==void 0)U.push({tokenIndex:de+1,kind:"program-file",value:Ee})}de++;continue}if(re&&(Ce.startsWith("-F")||Ce.startsWith("-v")&&Ce.slice(2).includes("=")))continue;if(re&&Ce.startsWith("-f")&&Ce.length>2){K=!0,U.push({tokenIndex:de,kind:"program-file",value:Ce.slice(2)});continue}if(re&&(Ce.startsWith("--assign=")||Ce.startsWith("--field-separator=")))continue;if(re&&Ce.startsWith("--file=")){K=!0,U.push({tokenIndex:de,kind:"program-file",value:Ce.slice(7)});continue}if(re&&Ce.startsWith("-")&&Ce!=="-")continue;if(!j&&!K)U.push({tokenIndex:de,kind:"main-program",value:Ce});return{sources:U,optionsOpen:!1}}return{sources:oe?U:[],optionsOpen:re&&oe}}function hi(G){return Xl(G).sources}function pR(G){return hi(G).filter((U)=>U.kind!=="program-file").map((U)=>U.value)}function gR(G,U){An(U,G);let j=G.includes("system")?Jl(G,U):null,K=hR(G,U);if(!j&&!K)return null;return{dynamic:!!j?.dynamic||!!K?.dynamic,commands:[...j?.commands??[],...K?.commands??[]]}}function Jl(G,U){An(U,G);let j=[],K=!1,re=!1,oe=0;while(oe<G.length){let de=G[oe];if(de==='"'||de==="'"){oe=Ds(G,oe,de)?.endIndex??oe+1;continue}if(de==="#"){oe=Tf(G,oe+1);continue}if(de==="/"&&If(G,oe)){oe=kf(G,oe+1)??oe+1;continue}if(!G.startsWith("system",oe)){oe++;continue}let Ce=oe;if(oe+=6,gi(G[Ce-1])||gi(G[oe]))continue;let Ee=Ms(G,oe);if(G[Ee]!=="(")continue;Ee=Ms(G,Ee+1);let we=G[Ee];if(we!=='"'&&we!=="'"){K=!0,re=!0;continue}let Oe=Ds(G,Ee,we);if(!Oe){K=!0,re=!0;continue}if(Ee=Ms(G,Oe.endIndex),K=!0,G[Ee]!==")"){re=!0,oe=Oe.endIndex;continue}j.push(Oe.value),oe=Ee+1}if(!K)return null;return{dynamic:re,commands:j}}function hR(G,U){An(U,G);let j=[],K=!1,re=!1,oe=0,de=0,Ce=null,Ee=null,we=0;while(oe<G.length){let Oe=G[oe];if(!Oe)break;if(Oe==='"'||Oe==="'"){let Ye=Ds(G,oe,Oe);if(Ye&&we===de)Ee={...Ye,startIndex:oe};we=Ye?.endIndex??oe+1,oe=Ye?.endIndex??oe+1;continue}if(Oe==="#"){oe=Tf(G,oe+1),de=oe,Ce=null,Ee=null,we=oe;continue}if(Oe==="/"&&If(G,oe)){let Ye=kf(G,oe+1);we=Ye??oe+1,oe=Ye??oe+1;continue}if(`;
|
|
32
|
+
{}`.includes(Oe)){oe++,de=oe,Ce=null,Ee=null,we=oe;continue}if(Ce===null&&(Zl(G,oe,"print")||Zl(G,oe,"printf")))Ce=oe;if(Oe!=="|"||G[oe-1]==="|"||G[oe+1]==="|"){if(!/\s/.test(Oe))we=oe+1;oe++;continue}let Ze=G[oe+1]==="&"?oe+2:oe+1,Ke=Ms(G,Ze);if(Zl(G,Ke,"getline")){re=!0;let Ye=CR(de,Ee,we);if(K||=Ye===null,Ye!==null)j.push(Ye);we=Ze,oe=Ze;continue}if(vR(de,Ce)){re=!0;let Ye=bR(G,Ke);if(!Ye){K=!0,we=Ze,oe=Ze;continue}if(!yR(G,Ye.endIndex)){K=!0,we=Ye.endIndex,oe=Ye.endIndex;continue}j.push(Ye.value),we=Ye.endIndex,oe=Ye.endIndex;continue}we=Ze,oe++}if(!re)return null;return{dynamic:K,commands:j}}function gi(G){return!!G&&/[A-Za-z0-9_]/.test(G)}function Ms(G,U){let j=U;while(/\s/.test(G[j]??""))j++;return j}function yR(G,U){let j=U;while(/[\t\f\v\r ]/.test(G[j]??""))j++;let K=G[j];return!K||`;
|
|
33
|
+
}#`.includes(K)}function Ds(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 Ce=SR(G,oe);if(!Ce)return null;K+=Ce.value,oe=Ce.endIndex,re=!1;continue}if(de==="\\"){re=!0;continue}if(de===j)return{value:K,endIndex:oe+1};K+=de}return null}function bR(G,U){let j=G[U];if(j!=='"'&&j!=="'")return null;return Ds(G,U,j)}function CR(G,U,j){if(!U)return null;return U.startIndex>=G&&U.endIndex===j?U.value:null}function SR(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 Zl(G,U,j){return G.startsWith(j,U)&&!gi(G[U-1])&&!gi(G[U+j.length])}function vR(G,U){return U!==null&&U>=G}function Tf(G,U){let j=G.indexOf(`
|
|
35
|
+
`,U);return j===-1?G.length:j+1}function If(G,U){let j=ER(G,U);if(j===-1)return!0;if("{([,;!~=".includes(G[j]??""))return!0;let K=j;while(gi(G[K-1]))K--;return mR.has(G.slice(K,j+1))}function ER(G,U){for(let j=U-1;j>=0;j--)if(!/\s/.test(G[j]??""))return j;return-1}function kf(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 RR=new Set(["sudo","env","command","builtin"]),_R=new Set(["caffeinate","exec","nice","nohup","setsid","stdbuf","time","timeout"]);function Ns(G,U){let j=G[0];if(!j||!Of(Nt(j),U))return null;let K=Nt(j),re=G[1]==="--"?2:1,oe=xR(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 xR(G,U,j,K){let re=G[1]==="--",oe=[];for(let de=U;de<G.length;de++){let Ce=G[de];if(!Ce)continue;let Ee=Nt(Ce)!==j&&wR(Ce,K);if(Ee)oe.push(de);if(!Ee&&Bi.has(Wt(Ce)))break;if(re)break}return oe}function wR(G,U){let j=Nt(G),K=Wt(G);return K==="git"||j==="busybox"||$r(G)||za.has(j)||bm(K)||Of(j,U)||Xt.has(K)||G==="$SHELL"||Fn(K)||Mn.has(K)||U.rules.some((re)=>re.command===j)}function Of(G,U){return _R.has(G)||U.transparentWrappers.includes(G)}function $r(G){return RR.has(G.toLowerCase())}function Br(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 Un(G,U){let j=U.policy??{rules:[],transparentWrappers:[]};return Ls([...G],U.environment,U.cwd,U.cwd,new Map,new Map(U.envAssignments??[]),j,{iterations:0},!1)}function*Ls(G,U,j,K,re,oe,de,Ce,Ee){let we=Cs(G,U,j,oe);for(let[Ye,Xe]of we.envAssignments)oe.set(Ye,Xe),re.set(Ye,Xe);let{tokens:Oe,cwd:Ze}=we;if(we.envSplitValues){let Ye=bs(we.envSplitValues,Oe);if(!Ye)throw new s("derivedCommandShape");Ql(Ce),yield*Ls(Ye,U,Ze,K,re,oe,de,Ce,Ee);return}if($r(Oe[0]??""))throw new s("wrapperPeelIterations");let Ke=Ns(Oe,de);if(Ke){for(let Ye of[Ke.childIndex,...Ke.alternativeChildIndices])Ql(Ce),yield*Ls(Ye===Ke.childIndex?Ke.tokens:Oe.slice(Ye),U,Ze,K,new Map(re),new Map(oe),de,Ce,!0);return}if(PR(Oe)){Ql(Ce),yield*Ls(Oe.slice(1),U,Ze,K,re,oe,de,Ce,Ee);return}yield AR(Oe,Ze,K,re,oe,Ee)}function AR(G,U,j,K,re,oe){return{tokens:G,cwd:U===null?void 0:U??j,wrapperCwd:U,wrapperEnvAssignments:K,envAssignments:re,head:Nt(G[0]??"").toLowerCase(),wrappedByTransparent:oe}}function Ql(G){if(G.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");G.iterations++}function PR(G){return Nt(G[0]??"").toLowerCase()==="busybox"&&G.length>1}function ec(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 ir(G){let U=!1,j=!1;for(let K of G){if(K==="--")break;if(K==="-r"||K==="-R"||tc(K,"recursive")){U=!0;continue}if(K==="-f"||tc(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 Ws(G){let U=G.indexOf("--");return G.slice(1,U===-1?void 0:U).some((j)=>tc(j,"recursive")||/^-[A-Za-z]+$/.test(j)&&/[rR]/.test(j.slice(1)))}function tc(G,U){return G.length>2&&G.startsWith("--")&&U.startsWith(G.slice(2))}var TR=["--init-file","--rcfile"],IR=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function Hn(G){for(let U=1;U<G.length;U++){let j=G[U];if(!j)continue;if(j==="-c")return Mf(G,U,!0);if(j.startsWith("-")&&j.includes("c")&&!j.startsWith("--")){let K=Mf(G,U,!1);if(K!==null)return K}}return null}function sr(G){let U=Nt(G[0]??"").toLowerCase();if(U==="zsh"||U==="ksh")return xn(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 Mf(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 Df(G){let U=Nt(G[0]??"").toLowerCase(),j=kR(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 kR(G,U){let j=xn(G),K=j.commandIndex??j.scriptIndex??G.length,re=[],oe=!1,de=!0;for(let Ce=1;Ce<K;Ce++){let Ee=G[Ce];if(Ee===void 0||Ee==="--"||Ee==="-"||Ee[0]!=="-"&&Ee[0]!=="+")break;if(Ee.startsWith("--")){if(U==="bash"&&de?TR.find((Ke)=>Ee===Ke):void 0){let Ke=G[Ce+1];re.push(Ke===void 0?{kind:"absent"}:{kind:"literal",value:Ke}),Ce++;continue}let Ze=Ee.split("=",1)[0]??Ee;if(U==="bash"&&Ga.has(Ze)&&!Ee.includes("="))Ce++;continue}if(U==="bash")de=!1;let we=Fa(U,Ee,G[Ce+1],"startup");if(we.interactive)oe=Ee[0]==="-";Ce+=we.followingValues}return{argvSource:re.at(-1)??null,interactive:oe}}var OR="find -delete permanently removes files. Use -print first to preview.",MR="find -exec rm -rf is dangerous. Use explicit file list instead.",DR=new Set(["-exec","-execdir","-ok","-okdir"]),NR=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 Nf(G,U){let j=G.map(t),K=LR(G,j,U);if(K)return K;if(Gs(j,1)&&!BR(G,j,U)){let de=Mt(At("find.delete",OR),U.policy);if(de)return de}let re=U.budget??kn(),oe=0;while(oe<j.length){let de=j[oe],Ce=ar(de??"");if(Ce>0){oe+=Ce+1;continue}if(!Yn(de)){oe++;continue}re.charge("derivedTokens",j.length-oe-1);let Ee=So(j,oe);oe=Ee.nextIndex;let we=HR(Ee.tokens,U.environment);if(we){let Ye=Mt(we,U.policy);if(Ye)return Ye}let Oe=de==="-execdir"||de==="-okdir",Ze=U.analyzeTokens?.(Ee.tokens,Oe?null:U.cwd)??null,Ke=Ze?.id.startsWith("custom.")?Ze:Mt(Ze,U.policy);if(Ke)return Ke}return null}function LR(G,U,j){if(!Gs(U,1)&&!nc(U,j.environment))return null;let re=yi(G)??Zt(["."]),oe=qn({...j,allowPaths:j.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let de of re){let Ce=mi(de);for(let Ee of Ce.expandedTargets??[t(de)]){let we=Pn(Ee,oe,{targetIsLiteral:Ce.expandedTargets!==void 0||Ce.targetIsLiteral,tmpdirWordSplittingProtected:Ce.tmpdirWordSplittingProtected});if(we.kind==="root_or_home_target")return At("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"&&!WR(G,oe.protectedGitMetadata,j.environment))return At("find.delete-git-metadata",v)}}if($R(U)&&oe.resolvedCwd&&tf(re.map(t),oe.resolvedCwd,oe.protectedGitMetadata,oe.environment,oe.budget))return At("find.delete-git-metadata",v);return null}function WR(G,U,j){if(!U)return!1;let K=G.map(t),re=[],oe=!1,de=yi(G)?.at(-1),Ce=de?G.indexOf(de)+1:1;while(Ce<K.length){let Ee=K[Ce]??"";if(Yn(Ee)){let we=So(K,Ce),Oe=gr([...we.tokens],j),Ze=Ws(Oe),Ke=Xt.has(Nt(Oe[0]??"").toLowerCase()),Ye=we.tokens.some((Je)=>Je!=="{}"&&Je.includes("{}")),Xe=(Ee==="-execdir"||Ee==="-okdir")&&Oe.slice(1).some((Je)=>Je!=="{}"&&!Je.startsWith("-"));if(Ze||Ke||Ye||Xe)return!1;oe=!0,Ce=we.nextIndex;continue}if(Ee==="-delete"){oe=!0,Ce++;continue}if(Ee==="-name"||Ee==="-iname"){let we=G[Ce+1];if(!(we?.provenance==="literal"&&!/[[\\]/.test(we.text)))return!1;if(!oe)re.push(FR(we.text,Ee==="-iname"));Ce+=2;continue}if(!GR.has(Ee))return!1;Ce+=1+ar(Ee)}return re.length>0&&!rf(U,(Ee)=>re.every((we)=>we.test(Ee)))}var GR=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function FR(G,U){let j=G.replace(/[*?]|[.+^${}()|\]/]/g,(K)=>K==="*"?".*":K==="?"?".":`\\${K}`);return new RegExp(`^${j}$`,U?"isu":"su")}var zR=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function nc(G,U){let j=0;while(j<G.length){if(!Yn(G[j])){j++;continue}let K=So(G,j),re=gr([...K.tokens],U),oe=Nt(re[0]??"").toLowerCase(),de=Xt.has(oe)&&zR.test((Hn(re)??"").replace(/["'\\]/g,""));if((oe==="rm"||oe==="rmdir"||de)&&re.some((Ee)=>Ee.includes("{}")))return!0;j=K.nextIndex}return!1}function $R(G){return G.some((U,j)=>{if(!["-name","-iname"].includes(U))return!1;return G[j+1]?.toLowerCase()==="hooks"})}function BR(G,U,j){if(U.includes("-L")||U.includes("-f")||U.includes("-follow"))return!1;let K=yi(G);if(!K)return!1;let re=j.envAssignments??new Map,oe=Hl(re,j.environment),de=j.trustedTmpdirValue??go(re,j.environment),Ce=j.allowTmpdirVar??!ui(re,j.environment),Ee={environment:j.environment,protectedGitMetadata:j.protectedGitMetadata,cwd:j.cwd,originalCwd:j.originalCwd,strict:j.strict,allowTmpdirVar:Ce&&de&&Boolean(oe),allowPaths:j.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:j.tmpdirWordSplittingUnsafe??Gr(re,j.environment),trustedTmpdirValue:de,budget:j.budget},we=qn(Ee),Oe=qn({...Ee,cwd:j.originalCwd??j.cwd}),Ze=j.originalCwd&&j.environment.paths.realpath(j.originalCwd),Ke=j.cwd&&j.environment.paths.realpath(j.cwd),Ye=Ze&&Ke&&!yo(Ke,Ze)?j.cwd:void 0;return K.every((Xe)=>{let Je=mi(Xe);if(Je.unsafeBraceExpansion)return!1;return(Je.expandedTargets??[t(Xe)]).every((Qe)=>{let mt=/^\.\/*$/.test(Qe)?Ye:void 0,Rt=mt??Qe,pt={targetIsLiteral:Je.expandedTargets!==void 0||Je.targetIsLiteral,tmpdirWordSplittingProtected:Je.tmpdirWordSplittingProtected};if(!tn(j.policy,"rm.recursive-force-paranoid",j.paranoid??!1)&&!mt&&Pn(Rt,we,pt).kind==="within_anchored_cwd")return!0;return ff(Rt,mt?Oe:we,{...pt,containmentTarget:UR(Rt,oe)})})})}function UR(G,U){if(!U)return G;return G.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>U)}function yi(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 HR(G,U){let j=pr([...G],U);if(j.length===0)return null;let K=Nt(j[0]??"");if(K==="busybox"&&j.length>1)j=j.slice(1),K=Nt(j[0]??"");if(K==="rm"&&ir(j))return At("find.exec-rm-recursive-force",MR);return null}function So(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 Gs(G,U){let j=U;while(j<G.length){let K=G[j];if(!K){j++;continue}if(Yn(K)){j=So(G,j).nextIndex;continue}let re=ar(K);if(re>0){j+=re+1;continue}if(K==="-delete")return!0;j++}return!1}function ar(G){return NR.get(G)??(/^-newer[A-Za-z]{2}$/.test(G)?1:0)}function Yn(G){return G!==void 0&&DR.has(G)}import{resolve as Cx}from"node:path";function*rc(G){for(let U of G.nodes)yield*VR(U)}function jR(G){return Object.freeze([...rc(G)])}function Et(G){return Object.freeze(jR(G).map((U)=>Object.freeze(U.words.map((j)=>j.text))))}function bi(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*rc(U);return}if(G.kind==="group")yield*rc(G.body)}var KR=5,oc="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 cn(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 Wf(G,U,j){let K=Fs(G,U,j),re=qR(K.entries);if(re.size===0)return{blockedReason:K.blockedReason,expanded:!1,tokens:G};let oe=G,de=!1;for(let Ce=0;Ce<KR;Ce++){let{subcommand:Ee,rest:we}=Tn(oe),Oe=Ee?.toLowerCase();if(!Oe||!re.has(Oe))return{blockedReason:K.blockedReason,expanded:de,tokens:oe};let Ze=re.get(Oe),Ke=QR(Ze);if(Ke===null||Ke.length===0)return{blockedReason:oc,expanded:!0,tokens:oe};oe=["git",...Ke,...we],de=!0}return{blockedReason:oc,expanded:!0,tokens:oe}}function Gf(G,U,j){return Fs(G,U,j).entries.some((K)=>K.key.toLowerCase()==="core.sshcommand")}function Tn(G){if(G.length===0)return{subcommand:null,rest:[]};let U=G[0];if((U?Nt(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+=_n.has(re)?2:1}return{subcommand:null,rest:[]}}function qR(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 Fs(G,U,j){if(G.length===0)return{blockedReason:null,entries:[]};let K=G[0];if((K?Nt(K).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let oe=ZR(U,j);return{blockedReason:oe.blockedReason,entries:[...oe.entries,...YR(G,U,j)]}}function YR(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=ic(G[re+1]);if(de)K.push(de);re+=2;continue}if(oe.startsWith("-c")&&oe.length>2){let de=ic(oe.slice(2));if(de)K.push(de);re++;continue}if(oe==="--config-env"){let de=Lf(G[re+1],U,j);if(de)K.push(de);re+=2;continue}if(oe.startsWith("--config-env=")){let de=Lf(oe.slice(13),U,j);if(de)K.push(de);re++;continue}if(_n.has(oe)){re+=2;continue}re++}return K}function ZR(G,U){let j=XR(G,U),K=JR(G,U);return{blockedReason:j===null||K===null?oc:null,entries:[...j??[],...K??[]]}}function XR(G,U){let j=rr("GIT_CONFIG_PARAMETERS",G,U);if(j===void 0)return[];let K=[],re=bi(j);if(!re)return null;for(let oe of re){let de=ic(oe);if(!de)return null;K.push(de)}return K}function JR(G,U){let j=Pm(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=rr(`GIT_CONFIG_KEY_${re}`,G,U)?.trim(),de=rr(`GIT_CONFIG_VALUE_${re}`,G,U);if(!oe||de===void 0)return null;K.push({key:oe,value:de})}return K}function ic(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 Lf(G,U,j){let K=G?.indexOf("=")??-1;if(!G||K===-1)return null;return{key:G.slice(0,K).trim(),value:rr(G.slice(K+1),U,j)}}function QR(G){let U=G?.trimStart();if(!U||U.startsWith("!"))return null;return bi(U)}var e_="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",t_="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",n_="git checkout --force discards uncommitted changes. Use 'git stash' first.",r_="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",o_="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",i_="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",s_="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",a_="git switch --force discards uncommitted changes. Use 'git stash' first.",l_="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",c_="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",d_="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",u_="git reset --merge can lose uncommitted changes. Use 'git stash' first.",m_="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",f_="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.",p_="git push --force destroys remote history. Use --force-with-lease for safer force push.",g_="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",h_="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",y_="git branch -D force-deletes without merge check. Use -d for safe delete.",b_="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",C_="git merge --abort discards merge conflict resolutions. Use 'git status' first.",S_="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",v_="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",E_="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",R_="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",__="git worktree remove --force can delete uncommitted changes. Remove --force flag.",x_=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),w_=new Set(["--recurse-submodules","--track","-t"]),sc=new Set(["-b","-B","-U"]),ac=new Set(["-c","-C"]),A_=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function Gt(G,U){let j=G.split("=",1)[0]??G;return j.length>=4&&U.startsWith(j)&&j.startsWith("--")&&j.slice(2).length>=2}var vo=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function zf(G,U){let{subcommand:j,rest:K}=Tn(G);if(!j)return null;switch(j.toLowerCase()){case"checkout":return yr(P_(K,U));case"switch":return yr(I_(K));case"restore":return yr(O_(K));case"reset":return D_(K);case"clean":return yr(L_(K));case"rm":return yr(W_(K));case"push":return Ur(G_(K));case"branch":return Ur($_(K));case"stash":return Ur(V_(K));case"worktree":return Ur(K_(K));case"rebase":return yr(B_(K));case"merge":return yr(U_(K));case"tag":return Ur(H_(K));case"reflog":return Ur(j_(K));default:return null}}function yr(G){return G?{...G,localDiscard:!0}:null}function Ur(G){return G?{...G,localDiscard:!1}:null}function P_(G,U){let{index:j,before:K}=cn(G),re=hn(K,{shortOptsWithValue:sc});if(K.some((Ce)=>Gt(Ce,"--force"))||re.has("-f"))return At("git.checkout-force",n_);for(let Ce of G){if(Ce==="-b"||Ce==="-B"||Ce==="--orphan")return null;if(Gt(Ce,"--pathspec-from-file"))return At("git.checkout-pathspec-from-file",o_)}if(j!==-1){if(K.some((Ee)=>!Ee.startsWith("-")))return At("git.checkout-ref-path",r_);return At("git.checkout-double-dash",e_)}let oe=k_(G);if(oe.length>=2)return At("git.checkout-ambiguous",i_);let de=oe[0];if(de===void 0||re.has("-d")||re.has("-t")||G.some((Ce)=>Gt(Ce,"--detach")||Gt(Ce,"--track")))return null;if(T_(de)||U(de))return At("git.checkout-double-dash",t_);return null}function T_(G){return G==="."||G===".."||/^\.\.?[/\\]/.test(G)||/^([/\\]|[A-Za-z]:[/\\])/.test(G)||G.endsWith("/")||G.startsWith(":")||/[*?[]/.test(G)}function I_(G){let{before:U}=cn(G);if(U.some((K)=>Gt(K,"--discard-changes")))return At("git.switch-discard-changes",s_);let j=hn(U,{shortOptsWithValue:ac});if(U.some((K)=>Gt(K,"--force"))||j.has("-f"))return At("git.switch-force",a_);return null}function k_(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(x_.has(K)){j+=2;continue}if(w_.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 O_(G){let U=M_(G);if(U.isTerminal||!U.hasPathspec&&!U.hasPatch||!U.hasWorktree)return null;return U.hasExplicitLocation?At("git.restore-worktree",c_):At("git.restore-unstaged",l_)}function M_(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 Ce=G[de];if(Ce===void 0)break;if(Ce==="--"){U||=de+1<G.length;break}if(Ce==="--pathspec-from-file"){U=!0,de++;continue}if(Ce.startsWith("--pathspec-from-file=")){U=!0;continue}if(Ce==="-h"||Ce==="--help"||Ce==="--version")return{hasPathspec:U,hasPatch:j,hasWorktree:K,hasExplicitLocation:re,isTerminal:!0};if(Ce==="--staged"){oe();continue}if(Ce==="--no-staged"){oe();continue}if(Ce==="--worktree"){oe(!0);continue}if(Ce==="--no-worktree"){oe(!1);continue}if(Ce==="--patch"){j=!0;continue}if(Ce==="--no-patch"){j=!1;continue}if(A_.has(Ce)){de++;continue}if(Ce.startsWith("--"))continue;if(Ce==="-"){U=!0;continue}if(!Ce.startsWith("-")){U=!0;continue}for(let Ee=1;Ee<Ce.length;Ee++){let we=Ce.charAt(Ee);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(Ee===Ce.length-1)de++;break}}}return{hasPathspec:U,hasPatch:j,hasWorktree:K,hasExplicitLocation:re,isTerminal:!1}}function D_(G){let U=null;for(let j of G){if(Gt(j,"--hard")){U=At("git.reset-hard",d_);break}if(Gt(j,"--merge")){U=At("git.reset-merge",u_);break}}if(!U)return null;return N_(G)?Ur(U):yr(U)}function N_(G){for(let U of G){if(U==="--")return!1;if(!U.startsWith("-"))return!0}return!1}function L_(G){for(let j of G)if(j==="-n"||Gt(j,"--dry-run"))return null;let U=hn(G.filter((j)=>j!=="--"));if(G.some((j)=>Gt(j,"--force"))||U.has("-f"))return At("git.clean-force",m_);return null}function W_(G){let U=!1,j=!1,K=!1;for(let re of cn(G).before){if(Gt(re,"--no-force")){U=!1;continue}if(Gt(re,"--force")){U=!0;continue}if(Gt(re,"--no-cached")){j=!1;continue}if(Gt(re,"--cached")){j=!0;continue}if(Gt(re,"--no-dry-run")){K=!1;continue}if(Gt(re,"--dry-run")){K=!0;continue}let oe=hn([re]);U||=oe.has("-f"),K||=oe.has("-n")}return U&&!j&&!K?At("git.rm-force",f_):null}function G_(G){let{before:U,after:j}=cn(G),K=hn(U);if(U.some((de)=>Gt(de,"--mirror")))return At("git.push-mirror",h_);if(U.some((de)=>Gt(de,"--force"))||K.has("-f")||Ff(U,j).some(F_))return At("git.push-force",p_);if(U.some((de)=>Gt(de,"--delete"))||K.has("-d")||Ff(U,j).some(z_))return At("git.push-delete",g_);return null}function Ff(G,U){return[...G.filter((j)=>j!==""&&!j.startsWith("-")),...U]}function F_(G){return G.startsWith("+")||G.includes(":+")}function z_(G){return G.length>1&&G.startsWith(":")}function $_(G){let{before:U}=cn(G),j=hn(U),K=j.has("-D")||j.has("-d")||U.some((oe)=>Gt(oe,"--delete")),re=j.has("-D")||j.has("-f")||U.some((oe)=>Gt(oe,"--force"));if(K&&re)return At("git.branch-force-delete",y_);return null}function B_(G){let{before:U}=cn(G);return U.some((j)=>Gt(j,"--abort"))?At("git.rebase-abort",b_):null}function U_(G){let{before:U}=cn(G);return U.some((j)=>Gt(j,"--abort"))?At("git.merge-abort",C_):null}function H_(G){let{before:U}=cn(G);return hn(U).has("-d")||U.some((K)=>Gt(K,"--delete"))?At("git.tag-delete",S_):null}function j_(G){return G[0]==="delete"?At("git.reflog-delete",v_):null}function V_(G){for(let U of G){if(U==="drop")return At("git.stash-drop",E_);if(U==="clear")return At("git.stash-clear",R_)}return null}function K_(G){let{before:U}=cn(G);if(!U.includes("remove"))return null;let K=hn(U);if(U.some((re)=>Gt(re,"--force"))||K.has("-f"))return At("git.worktree-remove-force",__);return null}import{dirname as px,isAbsolute as gx,join as tp,resolve as hx}from"node:path";var cc="TMPDIR",dc="IFS",Bf=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Uf=/^[A-Za-z_][A-Za-z0-9_]*$/,Hf=new Set(["export","typeset","declare","readonly"]),q_=new Set(["builtin","command","time"]),Y_=new Set(["do","then","else"]),Z_=new Set(["do","then","case"]),$f=new Set(["done","fi","esac"]),X_=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function jf(G,U){return G.map((j)=>j.provenance==="variable"&&Jf(j.text)?Vf(j.text,U.shellAssignments):t(j))}function Vf(G,U){return G.replace(X_,(j,K,re)=>U.get(K??re??"")??j)}function Zn(G,U){let j=G.parts.every((re)=>re.provenance!=="literal"||!/[$`]/.test(re.raw));if(G.provenance!=="variable"||!j)return null;let K=Vf(G.text,U);return/^[~-]/.test(K)||/[\s$`*?[]/.test(K)?null:K}function Kf(G,U){return{env:G,effectiveEnvAssignments:tx(G,U),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function qf(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 uc(G,U){let j=Zf(G,U),K=G[0]??"";if(Z_.has(K))U.bodyDepth+=1;if(K==="elif"||$f.has(K))U.bodyDepth=Math.max(0,U.bodyDepth-1);if($f.has(K)&&U.bodyDepth===0)U.bodyAssignments.forEach((Ce)=>{U.shellAssignments.delete(Ce)}),U.bodyAssignments.clear();j.assignments.filter((Ce)=>Ce.persists).forEach((Ce)=>{if(U.shellAssignments.set(Ce.name,Ce.value),U.bodyDepth>0)U.bodyAssignments.add(Ce.name);mc(U,Ce)});let re=j.commandIndex;if(re!==-1&&Hf.has(G[re]??""))G.filter((Ce)=>Uf.test(Ce)&&lc(Ce)).forEach((Ce)=>{nx(U,Ce)});let oe=re===-1?-1:Xf(G,re);if(oe===-1||G[oe]!=="unset")return;let de=ox(G,oe);if(de===null)return;G.slice(de).forEach((Ce)=>{if(U.bodyDepth>0){U.shellAssignments.set(Ce,"");return}rx(U,Ce)})}function Yf(G,U){let j=Zf(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 Zf(G,U){let j=Y_.has(G[0]??"")?1:0,K=G.findIndex((Ce,Ee)=>Ee>=j&&!Jf(Ce)),re=K!==-1&&Hf.has(G[Xf(G,K)]??""),oe=ex(U);return{assignments:G.flatMap((Ce,Ee)=>{let we=J_(Ce,oe,U.env);if(!we)return[];if(K!==-1&&Ee>K&&!re&&!hs(we.name))return[];return oe.set(we.name,we.value),[{...we,persists:K===-1||re}]}),commandIndex:K}}function Xf(G,U){let j=U;while(q_.has(G[j]??"")){j+=1;while(G[j]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(G[j]??""))return U;j+=1}}return j}function Jf(G){return Nn(G)!==null||Bf.test(G)}function J_(G,U,j){return Nn(G)??Q_(G,U,j)}function Q_(G,U,j){let K=ys(G,j,U);if(K)return K;let re=G.match(Bf)?.[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 lc(G){return G===cc||G===dc||Ll(G)}function ex(G){return new Map([...G.effectiveEnvAssignments??[],...G.shellAssignments])}function tx(G,U){let j=[cc,dc].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 mc(G,U){let j=new Map(G.effectiveEnvAssignments??[]);j.set(U.name,U.value),G.effectiveEnvAssignments=j}function nx(G,U){mc(G,{name:U,value:G.shellAssignments.get(U)??G.effectiveEnvAssignments?.get(U)??G.env.get(U)??""})}function rx(G,U){if(!lc(U)&&!Uf.test(U))return;if(G.shellAssignments.set(U,""),hs(U)&&G.env.has(U)){let K=new Map(G.env);K.delete(U),G.env=K}if(!lc(U)||U===cc||U===dc||Go(U)){mc(G,{name:U,value:""});return}if(!G.effectiveEnvAssignments?.has(U))return;let j=new Map(G.effectiveEnvAssignments);j.delete(U),G.effectiveEnvAssignments=j.size===0?void 0:j}function ox(G,U){let j=U+1;while(j<G.length){let K=G[j];if(!K)return null;if(K==="--")return j+1;if(K==="-v"){j++;continue}if(K.startsWith("-"))return null;return j}return j}import{resolve as ix}from"node:path";function zs(G,U){return Nl.some((j)=>U?.has(j)||G.has(j))}function Eo(G,U,j){if(!U)return{gitCwd:null,hasExplicitGitContext:!1};let K=j.realpath(ix(U));if(K===null||!j.isDirectory(K))return{gitCwd:null,hasExplicitGitContext:!1};let re=K,oe=!1,de=1;while(de<G.length){let Ce=G[de];if(!Ce)break;if(Ce==="--")break;if(!Ce.startsWith("-"))break;if(Ce==="-C"){let Ee=G[de+1];if(!Ee)return{gitCwd:null,hasExplicitGitContext:oe};let we=Qf(re,Ee,j);if(!we)return{gitCwd:null,hasExplicitGitContext:oe};re=we,de+=2;continue}if(Ce.startsWith("-C")&&Ce.length>2){let Ee=Qf(re,Ce.slice(2),j);if(!Ee)return{gitCwd:null,hasExplicitGitContext:oe};re=Ee,de++;continue}if(Ce==="--git-dir"||Ce==="--work-tree"){oe=!0,de+=2;continue}if(Ce.startsWith("--git-dir=")||Ce.startsWith("--work-tree=")){oe=!0,de++;continue}de+=_n.has(Ce)?2:1}return{gitCwd:re,hasExplicitGitContext:oe}}function Qf(G,U,j){try{let K=fr(G,U,j);return j.isDirectory(K)?K:null}catch{return null}}function ep(G,U,j){if(!U.localDiscard||!j.worktreeMode||zs(j.environment.env,j.envAssignments))return null;let K=Eo(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(fc(G,j,re))return null;return{kind:"worktree",originalReason:U.reason,gitCwd:K.gitCwd}}function fc(G,U,j){let{subcommand:K,rest:re}=Tn(G),oe=K?.toLowerCase();if(U.dynamicArguments||sx(re)||ux(G,U.environment.env,U.envAssignments,j)||cx(re)||ax(oe,re))return!0;return oe==="clean"&&dx(re)>1}function sx(G){return G.some((U)=>/[$*?[]/.test(U))}function ax(G,U){if(G==="checkout"){let{before:j}=cn(U),K=hn(j,{shortOptsWithValue:sc}),re=j.some((de)=>Gt(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}=cn(U),K=hn(j,{shortOptsWithValue:ac}),re=j.some((de)=>Gt(de,"--force"))||j.some((de)=>Gt(de,"--discard-changes"))||K.has("-f"),oe=j.some((de)=>de==="-C"||de.startsWith("-C")||lx(de))||K.has("-C");return re&&oe}return!1}function lx(G){let U=G.split("=",1)[0]??G;return U==="--force-create"||U.length>=9&&"--force-create".startsWith(U)}function cx(G){return G.some((U)=>U.startsWith("--recurse-sub"))}function dx(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 ux(G,U,j,K){if(rr("GIT_CONFIG_PARAMETERS",U,j)!==void 0)return!0;let re=Fs(G,U,j);if(re.blockedReason!==null)return!0;let oe=re.entries.map((Ce)=>({key:Ce.key.toLowerCase(),value:Ce.value}));if(oe.some((Ce)=>fx(Ce.key)))return!0;let de=oe.filter((Ce)=>Ce.key==="submodule.recurse").at(-1);if(de)return de.value===void 0||mx(de.value);if(Im(j))return!0;return K.recursiveSubmodules}function mx(G){let U=G.toLowerCase();return U!=="false"&&U!=="no"&&U!=="off"&&U!=="0"}function fx(G){return G==="include.path"||G.startsWith("includeif.")&&G.endsWith(".path")}function np(G,U,j){let K=G.map((Ee)=>Zn(Ee,j.shellAssignments??new Map)??t(Ee)),re=j.environment.paths,oe=Eo(K,j.cwd,re),de=j.originalCwd?re.realpath(hx(j.originalCwd)):null;if(U.id.startsWith("git.push-")||de===null||oe.gitCwd===null||oe.hasExplicitGitContext||zs(j.environment.env,j.envAssignments))return null;let Ce=U.id==="git.worktree-remove-force"?bx(G,j.shellAssignments,re):rp(oe.gitCwd,re);if(Ce===null||U.id!=="git.worktree-remove-force"&&!yx(Ce,K,U,j)||!ho(Ce,j.environment)||Is(Ce,j.environment)||yo(de,Ce)||yo(Ce,de))return null;return{kind:"temp-root",originalReason:U.reason,gitCwd:oe.gitCwd}}function yx(G,U,j,K){let re=K.environment.paths,oe=tp(G,".git");if(re.entryKind(oe)!=="present")return!1;if(re.isDirectory(oe))return!0;if(!j.localDiscard)return!1;let Ce=K.environment.worktreeFacts(G);return Ce!==null&&!fc(U,K,Ce)}function bx(G,U,j){let K=Tn(G.map(t)).rest,{before:re,after:oe}=cn(K.slice(K.indexOf("remove")+1)),de=[...re.filter((Oe)=>!Oe.startsWith("-")),...oe],Ce=de.length===1?de[0]??"":"",Ee=G.find((Oe)=>Oe.text===Ce),we=(Ee&&Zn(Ee,U??new Map))??Ce;if(!gx(we)||/[\s$`*?[]/.test(we)||j.entryKind(we)!=="present"||!j.isDirectory(we))return null;return j.realpath(we)}function rp(G,U){if(U.entryKind(tp(G,".git"))!=="missing")return G;let j=px(G);return j===G?null:rp(j,U)}var Sx="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.",vx=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function $s(G,U){return op(G,U)}function op(G,U,j){let K=G.map(t),re=Wf(K,U.environment.env,U.envAssignments),oe=re.blockedReason?Mt(At("git.alias-config",re.blockedReason),U.policy):null;if(oe)return oe;let de=re.tokens;if((Tm(U.envAssignments)||Gf(K,U.environment.env,U.envAssignments))&&Ex(de))return At("git.ssh-env",Sx);let Ce=zf(de,(we)=>{let Oe=Eo(K,U.cwd,U.environment.paths).gitCwd;return Oe!==null&&U.environment.paths.entryKind(Cx(Oe,we))!=="missing"});if(!Ce)return null;if(re.expanded||re.blockedReason)return Ce;let Ee=ep(K,Ce,U)??np(G,Ce,U);if(!Ee)return Ce;return j?.(Ee),null}function ip(G,U){let j=null;return{match:op(G,U,(re)=>{j=re}),relaxation:j}}function Ex(G){let{subcommand:U,rest:j}=Tn(G),K=U?.toLowerCase();if(!K)return!1;if(vx.has(K))return!0;if(K==="archive")return cn(j).before.some((re)=>Gt(re,"--remote"));return K==="remote"&&Rx(j)}function Rx(G){return G.find((U)=>!_x(U))?.toLowerCase()==="update"}function _x(G){return G==="-v"||Gt(G,"--verbose")||Gt(G,"--no-verbose")}import{isAbsolute as ew}from"node:path";function sp(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 Bs(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 ap="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",xx="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.",wx="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",Ax="rm -rf targeting root or home directory is extremely dangerous and always blocked.",Px="rm -rf in home directory is dangerous. Change to a project directory first.",lp={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:Ax},git_metadata_target:{id:"rm.git-metadata",reason:v},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:wx},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:Px},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:ap},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:xx},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:ap}};function Us(G,U){let j=qn({...U,allowPaths:U.policy?.destructiveCommandAllowPaths,posixShell:!0}),K=G.map(t),re=Ws(K),oe=Ix(G);for(let de of oe){let Ce=mi(de.word);if(re&&Ce.unsafeBraceExpansion){let Ee=Mt(zr({kind:"outside_anchored_cwd"},j,U.policy,lp),U.policy);if(Ee)return Ee;continue}for(let Ee of Ce.expandedTargets??[de.text]){let we=mn(Ee),Oe={targetIsLiteral:Ce.expandedTargets!==void 0||Ce.targetIsLiteral,tmpdirWordSplittingProtected:Ce.tmpdirWordSplittingProtected};if(!re&&j.resolvedCwd&&Wr(we,j.resolvedCwd,j.protectedGitMetadata,re,j.environment,j.budget))return At("rm.git-metadata",v);if(!re)continue;for(let Ze of Tx(we,j,Oe)){let Ke=zr(Ze,j,U.policy,lp),Ye=Mt(Ke,U.policy);if(Ye)return Ye}}}return null}function Tx(G,U,j){let K=Pn(G,U,j);if(K.kind==="cwd_self_target")return[K,Pn(G,U,{...j,skipCwdSelf:!0})];if(K.kind!=="home_cwd_target")return[K];let re=Pn(G,U,{...j,skipHomeCwd:!0});if(re.kind!=="cwd_self_target")return[K,re];return[K,re,Pn(G,U,{...j,skipHomeCwd:!0,skipCwdSelf:!0})]}function Ix(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 br={kind:"none"},Hr={kind:"dynamic"},kx=new Set(["<","<<","<<-","<<<","<&","<>"]),dp=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,Ox=/^(?:[0-9]+|[@*])$/,Mx=mr.maxWords,up=mr.maxInputLength;function mp(G){if(!G||Nt(Wt(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 Hs(G){let U=Ro(G[1])==="--"?2:1;if(G.length<=U)return br;let j=G.slice(U);if(!j.every(Si))return Hr;return{kind:"literal",source:j.map(t).join(" ")}}function fp(G){let U=Ro(G[1])==="--"?2:1,j=G[U],K=Ro(j);if(j===void 0||G.length<=U+1||K==="-"||K===""||K==="-l"||K==="-p")return br;if(!Si(j))return Hr;return{kind:"literal",source:K}}function js(G,U){let j=hp(G);if(j===-1)return br;let K=Nx(U);if(!K)return br;let re=[],oe=K.command?.length??0;for(let de of K.references){let Ce=Wx(de,G,j,K.ifs);if(!Ce)return Hr;if(oe+=Ce.reduce((Ee,we)=>Ee+we.length+3,0),re.length+Ce.length>Mx||oe>up)return Hr;re.push(...Ce)}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(Vs)].filter((de)=>de!==null).join(" ")}}function pp(G,U){let j=hp(G),K=G.slice(j+1),re=/\bIFS\b/.test(U);if(j===-1||!K.every(Si)||re)return U;let oe=K.map(Ro),de="",Ce=null,Ee=0;while(Ee<U.length){let we=U[Ee]??"",Oe=Ce==="'"?null:/^\$(?:\{([0-9]+|[@*])\}|([0-9@*]))/.exec(U.slice(Ee));if(Oe){let Ze=Oe[1]??Oe[2],Ke=Ze==="@"||Ze==="*"?oe.slice(1):[oe[Number(Ze)]??""];if(Ce!=='"'&&Ke.some((Xe)=>/[*?[]/.test(Xe)))return U;if(de+=Ce==='"'?Ke.map((Xe)=>Xe.replace(/["$`\\]/g,"\\$&")).join(Ze==="@"?'" "':" "):Ke.map((Xe)=>Xe.split(/[ \t\n]+/).map((Je)=>Je?Vs(Je):"").join(" ")).join(" "),de.length>up)return U;Ee+=Oe[0].length;continue}if(we==="\\"&&Ce!=="'"){de+=U.slice(Ee,Ee+2),Ee+=2;continue}if(we==="'"&&Ce!=='"'||we==='"'&&Ce!=="'")Ce=Ce?null:we;de+=we,Ee++}return de}function gp(G,U,j,K){if(!xn(G.map(t)).readsStdinAsCommands)return br;let re=U.filter((oe)=>(oe.fd===void 0||oe.fd===0)&&kx.has(oe.operator)).at(-1);if(re){if(re.operator==="<<"||re.operator==="<<-")return br;if(re.operator!=="<<<"||re.target?.provenance!=="literal")return Hr;return{kind:"literal",source:re.target.text}}if(!j)return br;return K===void 0?Hr:{kind:"literal",source:K}}function lr(G,U=new Map){let j=xn(G.map(t)).scriptIndex;if(j===null)return br;let K=G[j],re=Ro(K);if(ao(K,re))return{kind:"literal",source:re};let oe=K?Zn(K,U):null;return oe===null?Hr:{kind:"literal",source:oe}}var Dx=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function yc(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((Ee)=>Ee.provenance!=="literal"||Ee.parts.some((we)=>we.provenance!=="literal")))return!1;let de=oe.words[0]?.text;if(de===void 0||Nn(de)!==null)return!1;let Ce=Nt(Wt(de));return!Dx.has(Ce)&&!Xt.has(Ce)&&!$r(Ce)}function hp(G){return xn(G.map(t)).commandIndex??-1}function Nx(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(Lx);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 Lx(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 Wx(G,U,j,K){let re=U.slice(j+2);if(G.parameter==="@")return G.quoted?pc(re):Gx(re,K);if(G.parameter==="*"){let Ce=pc(re);if(!Ce)return;let Ee=Ce.join(K[0]??"");return G.quoted?[Ee]:gc(Ee,K)}let oe=U[j+1+G.parameter];if(oe&&!Si(oe))return;let de=Ro(oe);return G.quoted?[de]:gc(de,K)}function pc(G){return G.every(Si)?G.map(t):void 0}function Gx(G,U){let j=pc(G);if(!j)return;let K=j.map((re)=>gc(re,U));return K.some((re)=>re===void 0)?void 0:K.flatMap((re)=>re??[])}function gc(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 Si(G){if(!G)return!0;return G.provenance==="unknown"?!/[$`]/.test(t(G)):G.provenance==="literal"}function Ro(G){return G?t(G):""}function Vs(G){return`'${G.replaceAll("'",`'"'"'`)}'`}function bc(G,U){return hc(y(G,"posix"),U)}function vi(G){return bc(G,new Set(Array.from(G.matchAll(dp)).flatMap((U)=>{let j=U[1]??U[2];return j===void 0?[]:[j]})))}function hc(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(hc(K.body,j))return!0;continue}if(K.kind!=="command")continue;if(K.nested.some((re)=>hc(re,j))||yp(K.words,j))return!0;Ux(K,j)}return!1}function yp(G,U){let j=G.findIndex((de)=>Nn(de.text)===null);if(j===-1)return!1;let K=G[j];if(!K)return!1;if(Ci(K,U))return!0;let re=Wt(K.text);if(re==="source"||re==="."){let de=G[j+1]?.text==="--"?j+2:j+1;return cp(G[de],U)}if(Xt.has(re)){let de=G.slice(j),Ce=xn(de.map((we)=>we.text)),Ee=Ce.commandIndex??Ce.scriptIndex;return!Ce.syntaxCheck&&Ee!==null&&cp(de[Ee],U)}let oe=Fx(G,j,U);if(oe===null)return!1;if(oe===-1)return!0;return yp(G.slice(oe),U)}function Fx(G,U,j){let K=Wt(G[U]?.text??"");if(K==="command")return zx(G,U+1);if(K==="exec")return $x(G,U+1);if(K==="env")return Bx(G,U+1,j);return null}function zx(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 $x(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 Bx(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 Ci(G[K+1],j)?-1:K+2;if(oe.startsWith("-S")||oe.startsWith("--split-string="))return Ci(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(Nn(oe))continue;return K}return null}function Ux(G,U){if(!G.words.every((j)=>Nn(j.text)!==null))return;for(let j of G.words){let K=Nn(j.text);if(!K)continue;if(Ci(j,U))U.add(K.name)}}function Ci(G,U){if(!G)return!1;return G.parts.filter((j)=>j.provenance==="variable").some((j)=>Array.from(j.raw.matchAll(dp)).some((K)=>{let re=K[1]??K[2];return re!==void 0&&(Ox.test(re)||U.has(re))}))}function cp(G,U){return!!G&&(G.parts.some((j)=>j.provenance!=="literal"&&j.provenance!=="variable")||Ci(G,U))}var Cc="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",Sc="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",Hx="__CC_SAFETY_NET_XARGS_INPUT__",Ks="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",qs="rm",jx=/(?:^|[;&|]\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,Vx=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,Kx=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,qx=/^(?:[0-9]+|[@*])$/;function Sp(G,U){let j=G.map(t),{childStart:K,replacementToken:re}=jr(j),oe=j.slice(K),de=At("xargs.shell-dynamic",Sc);if(Zx(oe,re,U)&&Mt(de,U.policy))return Mt(de,U.policy);for(let Ce of Un(oe,U)){let Ee=Ce.tokens,we=re!==null&&Ee[0]!==oe[0]&&(Ee[0]?.includes(re)??!1)?Mt(de,U.policy):null;if(we)return we;let Oe=wp(Ee,re,Ce.wrapperEnvAssignments),Ze=Ce.head==="rm"&&re!==null&&_p(Ee,re),Ke=U.analyzeChild(Ee,{...Br(Ce,U),dynamicInput:Oe,dynamicSourceInput:Ze||Ep(Ee,Ce.head,re,Ce.wrapperEnvAssignments,Oe,U.environment,U.strict?void 0:U.analyzeNested),dynamicRmInput:Ze,shellDynamicMatch:de,dynamicSourceMatch:de,rmDynamicMatch:At("xargs.rm-recursive-force-dynamic",Cc)});if(Ke)return Ke;let Ye=Yx(Ee,re,U.policy?.rules??[],Mt(de,U.policy));if(Ye)return Ye;if(Ce.head==="git"){let Je=re===null?[...Ee,Hx]:Ee,Qe=re!==null&&(Ee.some((Rt)=>Rt.includes(re))||Array.from(Ce.envAssignments.values()).some((Rt)=>Rt.includes(re))),mt=U.analyzeChild(Je,{...Br(Ce,U),worktreeMode:re===null||Qe?!1:U.worktreeMode});if(mt)return mt}let Xe=D(Ee,U.policy?.rules??[]);if(Xe)return Xe}return null}function Yx(G,U,j,K){if(j.length===0)return null;if(U===null){for(let oe of j){let de=D([...G,...oe.subcommand?[oe.subcommand]:[],...oe.block_args],j);if(de)return de}return null}let re=Wt(G[0]??"");if(!j.some((oe)=>Wt(oe.command)===re))return null;return G.slice(1).some((oe)=>oe.includes(U))?K:null}function vp(G,U,j){let K=G.indexOf(U);if(K===-1||G.indexOf(U,K+U.length)!==-1)return[];let re=sp(G,K,U.length,j);return re===null?[]:[re]}function Ep(G,U,j,K,re,oe,de){if(Xt.has(U)){if(sr(G))return!1;if(j!==null&&Xx(G,j,de))return!0;let Ce=Hn(G);if(!Ce){let Ee=lr(Zt(G));if(Ee.kind==="literal")return j!==null&&Ee.source.includes(j);return Ee.kind==="none"&&re}if(j!==null&&Ce.includes(j)&&!Rp(Ce,j,de))return!0;if(Dn(Ce))return!0;return Jx(Ce,j,K)}if(Fn(U))return bp(G,j,ps,_m(U));if(Mn.has(U))return bp(G,j,Xl,Af);if(U==="eval"){let Ce=Hs(Zt(G));if(Ce.kind==="dynamic")return!0;if(j!==null)return Ce.kind==="literal"&&Ce.source.includes(j);return re}if(U==="find")return Qx(G,j,oe);if(U==="git"){let Ce=Tn(G);return j===null?Ce.subcommand===null:(Ce.subcommand?.includes(j)??!1)||Ce.subcommand!==null&&vo.has(Ce.subcommand.toLowerCase())&&xp(Ce.rest,j).some((Ee)=>Ee.includes(j))}return!1}function Rp(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 Dn(oe)===null&&j(oe)===null}function bp(G,U,j,K){let re=j(G);if(U===null)return re.optionsOpen||j([...G,Ks]).sources.some((Ce)=>Ce.value===Ks);if(re.sources.some((Ce)=>Ce.value.includes(U)))return!0;let oe=K.flatMap((Ce)=>[Ce.selector,...Ce.valueForm==="attached-only"||Ce.valueForm==="attached-or-separate"?[`${Ce.selector}${Ks}`]:[],...Ce.valueForm==="equals-or-separate"?[`${Ce.selector}=${Ks}`]:[]]),de=new Set(oe.flatMap((Ce)=>G.flatMap((Ee)=>vp(Ee,U,Ce))));return Bs(re.sources,de,(Ce)=>j(G.map((Ee)=>Ee.replaceAll(U,Ce))).sources)}function Zx(G,U,j){if(G.length===0||(G[0]??"").toLowerCase()==="command")return!1;let K=new Set(Array.from(Un(G,j),(oe)=>oe.head)),re=U===null?[...G,qs]:G.map((oe,de)=>de===0?oe:oe.replaceAll(U,qs));return Array.from(Un(re,j)).some((oe)=>oe.head===qs&&!K.has(qs))}function _p(G,U){return xp(G.slice(1),U).some((j)=>j.includes(U)&&(j.startsWith("-")||j.startsWith(U)))}function xp(G,U){let j=G.findIndex((K)=>K==="--"&&!K.includes(U));return j===-1?G:G.slice(0,j)}function wp(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 Xx(G,U,j){let K=xn(G),re=K.commandIndex===null?"":G[K.commandIndex]??"";if(re.includes(U)&&!Rp(re,U,j)||K.scriptIndex!==null&&(G[K.scriptIndex]??"").includes(U))return!0;return["-c","-nc","-cn",`--${U}`,U].some((de)=>G.some((Ce,Ee)=>{if(Ee===0||!Ce.includes(U))return!1;return vp(Ce,U,de).some((Oe)=>{let Ze=G.map((Ye,Xe)=>Xe===Ee?Ye.replaceAll(U,Oe):Ye),Ke=xn(Ze);if(Ke.commandIndex===null&&Ke.scriptIndex===null)return!1;if(K.commandIndex===null&&Ke.commandIndex!==null)return!0;if(K.scriptIndex===null&&Ke.scriptIndex!==null)return!0;if(Ke.commandIndex!==null&&(Ze[Ke.commandIndex]??"").includes(Oe))return!0;return Ke.scriptIndex!==null&&(Ze[Ke.scriptIndex]??"").includes(Oe)})}))}function Jx(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(jx))if(Cp(re,K))return!0;for(let re of G.matchAll(Vx))for(let oe of(re[1]??"").matchAll(Kx))if(Cp(oe,K))return!0;return bc(G,K)}function Cp(G,U){let j=G[1]??G[2];return j!==void 0&&(qx.test(j)||U.has(j))}function Qx(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(Yn(de)){let Ee=So(G,oe);oe=Ee.nextIndex-1;for(let we of Un(Ee.tokens,{environment:j,cwd:void 0})){let Oe=wp(we.tokens,U,we.wrapperEnvAssignments);if(we.head==="rm"&&_p(we.tokens,U)||Ep(we.tokens,we.head,U,we.wrapperEnvAssignments,Oe,j))return!0}continue}let Ce=ar(de);if(Ce>0){if(re=Ce,de.includes(U))return!0;continue}if(de.includes(U))return!0}return!1}function jr(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 Ei="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",Ri="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",tw="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",nw="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Zs=/\{[^{}\s]*\}/g,Ap=/\{\}|\{-?\d+\}/g,Pp=/[\s;&|<>()$`\\"']/,rw=["e","f","source","file","-e","-f","--source","--file"],ow=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],iw=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),sw=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),Tp=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),aw=new Set(["--workdir","--wd"]),Ip="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Ln(G,U){for(let j of G){let K=U(j);if(K)return K}return null}function Mp(G){return Ln([...G],(U)=>Dn(U))}function Dp(G,U){let j=G.map(t);if((U.envAssignments?.has("PARALLEL")?U.envAssignments.get("PARALLEL"):U.environment.env.get("PARALLEL"))?.trim()){let Xe=_o(U);if(Xe)return Xe}if(j.length===2&&(j[1]==="--version"||j[1]==="--help"))return null;let re=Vp(j),{template:oe,jobs:de,runsRemotely:Ce,readsCommandsFromInput:Ee,unsupported:we,workdir:Oe,dryRun:Ze}=re;if(we){let Xe=_o(U);if(Xe)return Xe;let Je=Mp(U.envAssignments?.values()??[]);if(Je)return Je}if(Ee){let Xe=pw(U);if(Xe)return Xe}if(Oe!==void 0&&Ce){let Xe=_o(U);if(Xe)return Xe}let Ke=gw(Oe,U.cwd,U.environment.paths);if(Ke===null){let Xe=_o(U);if(Xe)return Xe}let Ye=Ce?{...U,cwd:void 0,originalCwd:void 0}:Ke===null||Ke===void 0||Ke===U.cwd?U:{...U,cwd:Ke};if(Ze){if([...Un(oe,Ye)].flatMap((Je)=>[...Je.envAssignments.values()]).some(Rc)){let Je=_o(U);if(Je)return Je}return null}if(oe.length===0){let Xe=de.map((Qe)=>Qe[0]??"");U.budget.charge("derivedTokens",Xe.length);let Je=zp(Ye.envAssignments,Ye.cwd,Ce);return Ln(Xe,(Qe)=>U.analyzeNested(Qe,Je))}return Ln(Un(oe,Ye),(Xe)=>lw(Xe,re,U,Ye))}function lw(G,U,j,K){let{templateHasPlaceholder:re,runsRemotely:oe,usesStdin:de}=U,Ce=G.tokens,Ee=[...G.envAssignments.values()];if(Ee.some(Hp)){let _t=_o(j);if(_t)return _t}let we=Mp(Ee);if(we)return we;let Oe=Ee.some(Ut),Ze=re||Oe,Ke=de&&Ze,Ye=zp(G.envAssignments,G.wrapperCwd,oe||Ke),Xe=Ze?{...Ye,worktreeMode:!1}:Ye,Je=Ce.join(" "),Qe=Ut(Je.split(/[ \t\n=]/,1)[0]??""),mt=!U.quotesCommand&&(Qe||Ce.some((_t)=>Pp.test(_t))),Rt=Qe||Pp.test(Ce[0]??""),pt=mt&&Rt&&U.jobs.length>0?null:cw(G,U,j,K,Xe,Oe);if(pt||!mt)return pt;return Np(Ut(Je)?Je:`${Je} {}`,!Qe,G,U,j,K,Xe)}function cw(G,U,j,K,re,oe){let{jobs:de,templateHasPlaceholder:Ce,runsRemotely:Ee,usesStdin:we}=U,Oe=G.tokens,Ze=Ce||oe;if(Xt.has(G.head)){let Ye=()=>{if(!Ce||de.length===0)return null;return Ln(de,(Qe)=>j.analyzeChild(Ys(Oe,Qe,j.budget),Br(G,K)))};if(sr(Oe))return Ye();let Xe=Hn(Oe);if(Xe){if(jp(Xe)){let pt=Cr(j);if(pt)return pt;if(de.length===0)return null;return Ln(de,(_t)=>j.analyzeNested(Bp(Xe,_t,j.budget),re))}if(Ut(Xe))return Np(Xe,!1,G,U,j,K,re);let Qe=!oe&&(!Ce||de.length>0)?(de.length>0?de:[void 0]).map((pt)=>js(Zt(pt===void 0?Oe:Ce?Oe.map((_t)=>$p(_t,pt)):[...Oe,...pt]),Xe)):[];if(Qe.some((pt)=>pt.kind==="dynamic")){let pt=Cr(j);if(pt)return pt}let mt=Qe.flatMap((pt)=>pt.kind==="literal"?[pt.source]:[]);if(mt.length>0)return j.budget.charge("derivedTokens",mt.length),Ln(mt,(pt)=>j.analyzeNested(pt,re));if(vi(Xe)){let pt=Cr(j);if(pt)return pt}let Rt=j.analyzeNested(Xe,re);if(Rt)return Rt;if(Ze)return Cr(j);return null}let Je=lr(Zt(Oe));if(Je.kind==="dynamic"||Je.kind==="literal"&&Ut(Je.source))return Cr(j)??Ye();if(Je.kind==="literal")return Ye();if(de.length>0){let Qe=Cr(j);if(Qe)return Qe;let mt=Ye();if(mt)return mt;if(Ce)return null;let Rt=de.flatMap((pt)=>pt[0]===void 0?[]:[pt[0]]);return j.budget.charge("derivedTokens",Rt.length),Ln(Rt,(pt)=>j.analyzeNested(pt,re))}if(Ze||we)return Cr(j)??Ye();return null}if(G.head==="rm"&&ir(Oe)){if(Ce&&de.length>0)return Ln(de,(Xe)=>vc(Ys(Oe,Xe,j.budget,Ap),G.cwd,K));if(de.length>0)return Ln(de,(Xe)=>vc(Op(Oe,Xe,j.budget),G.cwd,K));let Ye=vc(Oe.flatMap((Xe,Je)=>{if(Je===0||!Ut(Xe))return[Xe];return Xe.startsWith("-")?[Xe.replace(Ap,"")]:[]}),G.cwd,K);if(Ye)return Ye;return Fp(j)}let Ke=de.length>0?de:[void 0];return Ln(Ke,(Ye)=>{let Xe=Ye===void 0?Oe:Ce?Ys(Oe,Ye,j.budget):Op(Oe,Ye,j.budget),Je=At("parallel.shell-dynamic",Ri),Qe=we&&G.head==="find"?fw(Xe,K):null,mt=Wp(Xe,we,j)??Qe?.customResult??null,Rt=Wt(G.head),pt=we&&(Rt==="rm"&&Ec(Xe)||Rt==="xargs"&&Gp(Xe)||Qe?.rmOptions===!0),_t=we&&(pt||Qe?.executedSource===!0||Qe===null&&Lp(Xe,Rt)),It=j.analyzeChild(Xe,{...Br(G,K),worktreeMode:Ee||we||Ze?!1:j.worktreeMode,dynamicInput:we||Ze,dynamicRmInput:pt,dynamicSourceInput:mt!==null||_t,shellDynamicMatch:Je,dynamicSourceMatch:Je,rmDynamicMatch:At("parallel.rm-recursive-force-dynamic",Ei)});if(_t){let Ot=Mt(Je,j.policy);if(Ot)return Ot}return It??mt??D(Xe,j.policy?.rules??[])})}function Np(G,U,j,K,re,oe,de){if(K.jobs.length>0)return Ln(K.jobs,(we)=>re.analyzeNested(Bp(G,U?we.map(Vs):we,re.budget),de));let Ce=bi(G);if(Ce?.[0]&&Wt(Ce[0])==="rm"&&ir(Ce)){let we=Fp(re);if(we)return we}return(Ce?re.analyzeChild(Ce,{...Br(j,oe),dynamicInput:K.usesStdin,shellDynamicMatch:At("parallel.shell-dynamic",Ri),rmDynamicMatch:At("parallel.rm-recursive-force-dynamic",Ei)}):null)??re.analyzeNested(G,de)}function Lp(G,U){if(Ut(G[0]??""))return!0;if(U==="eval"||U==="source"||U===".")return!0;if(U==="parallel"||U==="xargs")return!0;if(Xt.has(U))return mw(G);if(U==="git")return dw(G);if(U==="find")return!0;if(Mn.has(U))return kp(G,rw,hi);if(Fn(U))return kp(G,ow,fs);return!1}function Ec(G){let U=G.indexOf("--"),j=G.slice(1,U===-1?void 0:U);if(!G.some(Ut))return U===-1;return j.some((re)=>Ut(re)&&(re.startsWith("-")||jp(re)))}function dw(G){if(uw(G))return!0;let U=Tn(G);if(U.subcommand===null||Ut(U.subcommand))return!0;if(!vo.has(U.subcommand.toLowerCase()))return!1;let j=U.rest.indexOf("--"),K=U.rest.slice(0,j===-1?void 0:j);if(!G.some(Ut))return j===-1;return K.some(Ut)}function uw(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(Ut(G[U+1]??""))return!0;U++;continue}if(j.startsWith("-c")&&j.length>2||j.startsWith("--config-env=")){if(Ut(j))return!0;continue}if(Ut(j))return!0}return!1}function mw(G){if(sr(G))return!1;let U=Hn(G);if(U!==null)return Ut(U);let j=lr(Zt(G));if(j.kind==="literal")return Ut(j.source);if(j.kind==="dynamic")return!0;return!G.some(Ut)}function kp(G,U,j){let K=j(G);if(K.some((re)=>Ut(re.value)))return!0;if(!G.some(Ut))return j([...G,Ip]).some((re)=>re.value===Ip);return Bs(K,U,(re)=>j(G.map((oe)=>$p(oe,[re]))))}function Wp(G,U,j){let K=j.policy?.rules??[];if(!U||K.length===0)return null;let re=K.filter((oe)=>Wt(oe.command)===Wt(G[0]??""));if(re.length===0)return null;if(G.slice(1).some(Ut))return Cr(j);return Ln(re,(oe)=>D([...G,...oe.subcommand?[oe.subcommand]:[],...oe.block_args],[oe]))}function fw(G,U){let j={customResult:null,executedSource:!G.some(Ut),rmOptions:!1},K=!1,re=0,oe=null,de=()=>{if(!oe?.some(Ut))return;for(let Ce of Un(oe,U))j.executedSource||=Lp(Ce.tokens,Ce.head),j.rmOptions||=Ce.head==="rm"&&Ec(Ce.tokens)||Ce.head==="xargs"&&Gp(Ce.tokens),j.customResult??=Wp(Ce.tokens,!0,U)};for(let Ce of G.slice(1)){if(!K&&!Ce.startsWith("-")&&Ce!=="!"&&Ce!=="("){j.executedSource||=Ut(Ce);continue}if(K=!0,oe){if(Ce===";"||Ce==="+"){de(),oe=null;continue}oe.push(Ce);continue}if(re>0){re--;continue}if(Yn(Ce)){oe=[],j.executedSource||=Ut(Ce);continue}let Ee=ar(Ce);if(Ee>0){re=Ee,j.executedSource||=Ut(Ce);continue}j.executedSource||=Ut(Ce)}return de(),j}function Gp(G){let U=G.slice(jr(G).childStart);return Wt(U[0]??"")==="rm"&&Ec(U)}function Xs(G,U){return(j)=>Mt(At(G,U),j.policy)}var Cr=Xs("parallel.shell-dynamic",Ri),pw=Xs("parallel.command-stream-dynamic",tw),_o=Xs("parallel.command-stream-dynamic",nw),Fp=Xs("parallel.rm-recursive-force-dynamic",Ei);function vc(G,U,j){return Mt(Us(Zt(G),{environment:j.environment,cwd:U,budget:j.budget,originalCwd:j.originalCwd,strict:j.strict,paranoid:j.paranoidRm,allowTmpdirVar:j.allowTmpdirVar,tmpdirWordSplittingUnsafe:Gr(j.envAssignments??new Map,j.environment),trustedTmpdirValue:go(j.envAssignments??new Map,j.environment),protectedGitMetadata:j.protectedGitMetadata,policy:j.policy}),j.policy)}function zp(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 $p(G,U){return G.replace(Zs,(j)=>Up(j,U))}function Ys(G,U,j,K=Zs){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=Up(oe,U);return j.charge("derivedTokens",Math.max(1,Math.ceil(de.length/64))),de}))}function Bp(G,U,j){return Ys([G],U,j)[0]??""}function Op(G,U,j){return j.charge("derivedTokens",G.length+U.length),[...G,...U]}function Up(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 Ut(G){return G.search(Zs)!==-1}function Hp(G){if(Rc(G))return!0;for(let U of G.matchAll(Zs))if(!/^(?:\{\}|\{\d+\})$/.test(U[0]))return!0;return!1}function Rc(G){let U=G.indexOf("{=");return U!==-1&&G.indexOf("=}",U+2)!==-1}function jp(G){return/^\{[^{}\s]*\}$/.test(G)}function gw(G,U,j){if(G===void 0)return;if(G==="..."||/^~|[{}$`*?[]/.test(G))return null;if(!U&&!ew(G))return null;try{return fr(U??G,G,j)}catch{return null}}function Vp(G){let U=1,j=[],K=G.length,re=-1,oe=!1,de=!1,Ce=!1,Ee,we=!1,Oe=G.some((Je)=>Je==="::::"||Je==="::::+"||Je===":::+");while(U<G.length){let Je=G[U];if(Je===void 0)break;if(Je===":::"){re=U;break}if(Je==="--"){let _t=ec(G,U+1);j.push(..._t.templateTokens),K=U+1,re=_t.markerIndex;break}if(!Je.startsWith("-")){let _t=ec(G,U);j.push(..._t.templateTokens),K=U,re=_t.markerIndex;break}let Qe=G[U+1],mt=Je.indexOf("="),Rt=mt===-1?Je:Je.slice(0,mt),pt=mt===-1?void 0:Je.slice(mt+1);if(Je==="--dry-run"){we=!0,U++;continue}if(Je==="-I"||Je.startsWith("-I")&&Je.length>2){Oe||=(Je==="-I"?Qe:Je.slice(2))!=="{}",U+=Je==="-I"?2:1;continue}if(Je==="--replace"||Je==="-i"){Oe=!0,U+=2;continue}if(Rt==="--replace"||Je.startsWith("-i")&&Je.length>2){let _t=Rt==="--replace"?pt:Je.slice(2);Oe||=_t!==""&&_t!=="{}",U++;continue}if(Je==="-a"||sw.has(Rt)){Oe=!0,U+=pt===void 0?2:1;continue}if(Je==="-q"||Je==="--quote"){de=!0,U++;continue}if(Je==="--pipe"||Je==="--pipepart"){Ce=!0,U++;continue}if(Rt==="--env"){Oe=!0,U+=pt===void 0?2:1;continue}if(Tp.has(Rt)||Je.startsWith("-S")&&Je.length>2){oe=!0,U+=Tp.has(Je)?2:1;continue}if(aw.has(Rt)){Oe=!0;let _t=pt??Qe;if(_t===void 0||_t===":::"||_t==="--"){U++;continue}Ee=_t,U+=pt===void 0?2:1;continue}if(Je.startsWith("-j")&&Je.length>2&&/^\d+$/.test(Je.slice(2))){U++;continue}if(Je.startsWith("--")&&pt!==void 0){U++;continue}if(iw.has(Je)){if(Qe===void 0||Qe===":::"||Qe==="--"){Oe=!0,U++;continue}U+=2;continue}U+=Je==="-j"||Je==="--jobs"?2:1}Oe||=j.some(we?Rc:Hp);let Ze=[];if(re!==-1){let Je=[];for(let Qe=re+1;Qe<G.length;Qe++){let mt=G[Qe];if(mt===":::"){Ze.push(Je),Je=[];continue}if(mt!==void 0)Je.push(mt)}Ze.push(Je)}Oe||=Ze.length>1;let Ke=hw(Ze),Ye=j.some(Ut),Xe=j.length===0&&re===-1;return{template:j,jobs:Ke,childStart:K,templateHasPlaceholder:Ye,runsRemotely:oe,quotesCommand:de,usesStdin:Ce||re===-1,readsCommandsFromInput:Xe,unsupported:Oe,workdir:Ee,dryRun:we}}function hw(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 Kp(G){return Vp(G).childStart}var yw="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",Js="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function xc(G){return G?.parts.some((U)=>U.provenance==="command-substitution")??!1}function _c(G){return G?.parts.some((U)=>U.provenance==="literal"&&U.raw.replace(/^["']/,"").startsWith("-"))??!1}function Yp(G,U,j,K,re=!1,oe){let Ce=(qo(G,U)||K&&G!=="powershell"&&U[0]?.provenance==="variable")&&tn(oe,"shell.dynamic-executable",re)?At("shell.dynamic-executable",yw):null;return Mt(Ce,oe)??Zp(G,U,j,re,oe)}function Zp(G,U,j,K,re){if(U.length<2)return null;let oe=U.flatMap((Ce,Ee)=>xc(Ce)?[Ee]:[]);if(oe.length===0)return null;let de=Wt(U[0]?.text??"");if(de==="git"){let Ce=ne(G,U),Ee=Cw(Ce);if(tn(re,"shell.dynamic-structure",K)&&oe.some((Ze)=>Ze<=Ee))return Mt(At("shell.dynamic-structure",Js),re);if(Mt($s(Ce,{environment:j}),re))return null;let we=U[Ee]?.text.toLowerCase(),Oe=Ce.findIndex((Ze,Ke)=>Ke>Ee&&t(Ze)==="--");if(tn(re,"shell.dynamic-structure",K)&&we&&vo.has(we)&&oe.some((Ze)=>Ze>Ee&&(Oe===-1||Ze<Oe)))return Mt(At("shell.dynamic-structure",Js),re);return null}if(de==="find")return tn(re,"shell.dynamic-structure",K)&&Sw(U)?Mt(At("shell.dynamic-structure",Js),re):null;if(de==="rm"){let Ce=U.findIndex((we,Oe)=>Oe>0&&t(we)==="--"),Ee=ir(U.map(t));return tn(re,"shell.dynamic-structure",K)&&oe.some((we)=>(Ce===-1||we<Ce)&&(we<U.length-1||!Ee))?Mt(At("shell.dynamic-structure",Js),re):null}if(de==="xargs")return qp(G,U.slice(jr(U.map(t)).childStart),"xargs",j,K,re);if(de==="parallel")return qp(G,U.slice(Kp(U.map(t))),"parallel",j,K,re);return null}function qp(G,U,j,K,re,oe){if(U.length===0)return null;let de=bw(U,K);if(qo(G,de)){let Ee=Mt(At(`${j}.shell-dynamic`,j==="xargs"?Sc:Ri),oe);if(Ee)return Ee}let Ce=Zp(G,de,K,re,oe);if(Ce)return Ce;if(de[0]?.text==="rm"&&de.slice(1).some((Ee)=>xc(Ee)&&_c(Ee)))return Mt(At(`${j}.rm-recursive-force-dynamic`,j==="xargs"?Cc:Ei),oe);return null}function bw(G,U){let j=Nr(G,U),K=j.rewritten?Zt(j.words.map(t)):j.words,re=K[0];return re&&t(re)==="busybox"?K.slice(1):K}function Cw(G){let U=1;while(U<G.length){let j=G[U],K=j?t(j):"";if(_n.has(K)){U+=2;continue}if(K.startsWith("-")){U++;continue}return U}return U}function Sw(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 Ce=xc(de);if(j>0){j--;continue}if(re){if(de.text===";"||de.text==="+"){re=!1,U=!0,K=!1;continue}if(Ce&&(K||_c(de)))return!0;K=!1;continue}if(!U&&!de.text.startsWith("-")){if(Ce&&(oe>1||_c(de)))return!0;continue}if(U=!0,Ce)return!0;let Ee=ar(de.text);if(Ee>0){j=Ee;continue}if(Yn(de.text))re=!0,K=!0}return!1}function wc(G,U){return G.some((j)=>{if(j.value==="-"&&(j.kind==="main-script"||j.kind==="program-file"))return!0;return!ao(U[j.tokenIndex],j.value)})}var Xp="cmd rmdir /s or del /s outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",vw="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.",Ew="cmd rmdir /s or del /s target contains wildcards or variables that cannot be verified safely. Use literal paths within cwd.",Rw="cmd rmdir /s or del /s targeting root or home directory is extremely dangerous and always blocked.",_w="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.",xw="cmd rmdir /s or del /s in home directory is dangerous. Change to a project directory first.",ww={root_or_home_target:{id:"cmd.recursive-delete-root-or-home",reason:Rw},git_metadata_target:{id:"cmd.recursive-delete-git-metadata",reason:v},dynamic_target:{id:"cmd.recursive-delete-dynamic-target",reason:Ew},home_cwd_target:{id:"cmd.recursive-delete-home-cwd",reason:xw},cwd_self_target:{id:"cmd.recursive-delete-cwd-self",reason:Xp},within_anchored_cwd:{id:"cmd.recursive-delete-paranoid",reason:vw},outside_anchored_cwd:{id:"cmd.recursive-delete-outside-cwd",reason:Xp}},Aw=/^\/\/?[ck]$/i,Jp=/[&|]+/,Pw=/(?:"[^"]*"|[^\s"])+/g,Tw=/[\^%!]/,Iw=/\\"./s,kw=/(^|\/)[*.]*\*[*.]*$/,Ow=/^"?[\\/]+[?.][\\/]/,Mw=new Set(["rmdir","rd","del","erase"]),Dw=/(?<![\w-])(?:rmdir|rd|del|erase)(?!\w)/i,Nw=/\/s(?!\w)/i,Lw=/(?<![\w-])(?:cd|chdir|pushd|popd)(?!\w)/i;function Qp(G,U){let j=G.map(t),K=j.findIndex((Ke)=>Aw.test(Ke));if(K===-1)return null;let re=j.slice(K+1).join(" "),oe=/^".*"$/s.test(re)?re.slice(1,-1):re,de=oe.split(Jp).map((Ke)=>{let Ye=Ke.match(Pw)??[],Xe=Ye.findIndex((Qe)=>Mw.has(Qe.replace(/^@/,"").toLowerCase())),Je=Xe===-1?[]:Ye.slice(Xe);return{piece:Ke,tokens:Ye,deleteTokens:Je,recursiveDelete:Je.slice(1).some((Qe)=>Qe.startsWith("/")&&Qe.toLowerCase().split("/").includes("s"))}}),Ce=de.filter((Ke)=>Ke.recursiveDelete),Ee=Ce.length>0||Dw.test(oe)&&Nw.test(oe);if(Ee&&(oe.includes("\\\"")||U.gitBashEscapesBodyQuotes&&oe.includes('"')||U.powerShellRawWords.some((Ke)=>Iw.test(Ke))||Ce.some((Ke)=>Ke.tokens.some((Ye)=>Ow.test(Ye)))))return At("cmd.recursive-delete-escaped-quote",_w);let we=qn({...U,allowPaths:U.policy?.destructiveCommandAllowPaths}),Oe=de.reduce((Ke,Ye)=>Ke??(Ye.recursiveDelete?Ww(Ye.deleteTokens,we,U.policy):U.analyzeNested(Ye.piece)),null),Ze=Ee&&(Ce.length===0||Tw.test(oe)||Lw.test(oe)||oe.includes('"')&&Jp.test(oe));return Oe??(Ze?Co():null)}function Ww(G,U,j){return G.slice(1).filter((K)=>!K.startsWith("/")).reduce((K,re)=>K??Mt(zr(Pn(fi(re.replaceAll('"',"")).replace(kw,"$1*"),U),U,j,ww),j),null)}var Gw="Recursive delete handed to powershell or pwsh in a form CC Safety Net does not read is blocked: pass the script as a single -Command with literal paths, after only -NoProfile, -NonInteractive, -NoLogo, or -ExecutionPolicy.",Fw=/^-(?:noprofile|nop|noninteractive|noni|nologo)$/i,zw=/^-(?:executionpolicy|ep)$/i,$w=/^-(?:command|c)$/i,Bw=/^(?:--?|[/\u2013\u2014\u2015])(\w+)$/,Uw="encodedcommand",Hw=/(?<![\w-])(?:remove-item|ri|rm|rmdir|rd|del|erase)(?![\w-])/i,jw=/(?<![\w-])(?:[-\u2013\u2014\u2015]{1,2}r(?:e(?:c(?:u(?:r(?:s(?:e|ive?)?)?)?)?)?)?(?!\w)|-[dfipvwx]*r[dfipvwx]*(?!\w))|\/s(?!\w)/i,Vw=/[$`]/,Kw="--%";function eg(G,U){let j=G.map(t),K=j.every((oe,de)=>de===0||oe!==Kw&&qw(G[de],oe))?Pc(j):void 0;if(K!==void 0)return U(K);if(j.some(Yw))return Co();let re=j.join(" ");return Hw.test(re)&&jw.test(re)?At("powershell.nested-recursive-delete-unread",Gw):null}function Pc(G){let U=Ac(G,1),j=U===void 0?[]:G.slice(U+1);return j.length>0?j.join(" "):void 0}function Ac(G,U){let j=G[U]??"";if($w.test(j))return U;if(Fw.test(j))return Ac(G,U+1);return zw.test(j)?Ac(G,U+2):void 0}function qw(G,U){return G?.provenance==="unknown"?!Vw.test(U):ao(G,U)}function Yw(G){let U=Bw.exec(G)?.[1]?.toLowerCase();return U!==void 0&&(U==="ec"||Uw.startsWith(U))}var ng=[{heads:new Set(["rm","rmdir"]),analyze:(G)=>Us(G.words,Tc(G))},{heads:new Set(["cmd"]),analyze:(G)=>Qp(G.words,{...Tc(G),powerShellRawWords:G.options.commandView?.dialect==="powershell"?G.options.commandView.words.map((U)=>U.raw):[],gitBashEscapesBodyQuotes:G.options.commandView?.dialect!=="powershell",analyzeNested:(U)=>Sr(G.options.analyzeNested(U,{effectiveCwd:G.effectiveCwd,envAssignments:G.envAssignments}))})},{heads:new Set(["powershell","pwsh"]),analyze:(G)=>eg(G.parsedWords,(U)=>Sr(G.options.analyzeNested(U,{effectiveCwd:G.effectiveCwd,envAssignments:G.envAssignments,shell:"powershell"})))},{heads:new Set(["git"]),analyze:(G)=>$s(G.words,Ic(G))},{heads:new Set(["find"]),analyze:(G)=>Nf(G.words,{...Tc(G),envAssignments:G.envAssignments,analyzeTokens:G.analyzeChildTokens})},{heads:new Set(["xargs"]),analyze:(G)=>Sp(G.words,{...tg(G),analyzeChild:G.analyzeChild,analyzeNested:(U,j)=>Sr(G.options.analyzeNested(U,j))})},{heads:new Set(["parallel"]),analyze:(G)=>Dp(G.words,{...tg(G),analyzeChild:G.analyzeChild,analyzeNested:(U,j)=>Sr(G.options.analyzeNested(U,j))})}];function tg(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 Sr(G){return G?{id:G.ruleId,reason:G.reason,intent:G.intent??"manual_only"}:null}function Tc(G){return{environment:G.options.environment,cwd:G.cwd,originalCwd:G.originalCwd,strict:G.options.strict,paranoid:G.options.paranoidRm,allowTmpdirVar:G.allowTmpdirVar,tmpdirWordSplittingUnsafe:Gr(G.envAssignments,G.options.environment),trustedTmpdirValue:go(G.envAssignments,G.options.environment),protectedGitMetadata:G.options.protectedGitMetadata,policy:G.options.policy,budget:G.options.budget}}function Ic(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 ig(G){return ng.find((U)=>U.heads.has(G))?.analyze}function wo(G,U,j){let K=j.trace;if(G.length===0)return null;let re=j.commandView?.dialect??"posix",oe=(Tt)=>Tt.map((Lt)=>re==="posix"?t(Lt):Lt.text),de=j.child,Ce=de!==void 0&&!de.embedded,Ee=de?.embedded===!0,we=j.effectiveCwd===null,Oe=de?de.cwd:we?void 0:j.effectiveCwd??j.cwd,Ze=de?de.originalCwd:we?void 0:j.cwd,Ke=Se(G);if(Ke.envAssignments.size>0)K?.recordSegment({type:"env-strip",input:oe(G),envVars:[...Ke.envAssignments.keys()],output:oe(Ke.words)});let Ye=Nr(Ke.words,j.environment,Oe,new Map([...j.envAssignments??[],...Ke.envAssignments])),Xe=Ye.envSplitValues??[];if(Xe.length>0){let Tt=[...Xe,...oe(Ye.words)].join(" "),Lt=Dn(Tt);if(Lt)return K?.recordSegment({type:"dangerous-text",token:Tt,matched:!0,reason:Lt.reason}),pn(Lt);if(j.strict)return vn(K);let Ht=bs(Xe,oe(Ye.words));if(Ht){j.budget.charge("derivedTokens",Ht.length);let sn=j.analyzeNested(Ht.join(" "),{effectiveCwd:Ye.cwd===void 0?j.effectiveCwd:Ye.cwd,envAssignments:new Map([...j.envAssignments??[],...Ke.envAssignments,...Ye.envAssignments])});if(sn)return sn}}let Je=Ye.rewritten?Zt(oe(Ye.words)):ne(re,Ye.words),Qe=oe(Je),mt={...j,wrapperNormalizationBudget:j.wrapperNormalizationBudget??{iterations:0}};if(K&&Ke.words.length>Je.length){let Tt=oe(Ke.words);K.recordSegment({type:"leading-tokens-stripped",input:Tt,removed:Tt.slice(0,Tt.length-Je.length),output:Qe})}let Rt=new Map([...j.envAssignments??[],...Ke.envAssignments,...Ye.envAssignments]),pt=Qe[0];if(!pt)return null;if($r(pt))throw new s("wrapperPeelIterations");let _t=Wt(pt),It=Ye.cwd===null?void 0:Ye.cwd??Oe,Ot=Ye.cwd===null?void 0:Ze,Dt=Ye.cwd===void 0?j.effectiveCwd:Ye.cwd,ft=de?de.allowTmpdirVar:!ui(Rt,j.environment),kt=Yp(re,Ye.words,j.environment,U===0,j.strict,j.policy);if(kt)return K?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:kt.reason}),pn(kt);let Ft=Ns(Qe,j.policy);if(Ft){for(let Tt of[Ft.childIndex,...Ft.alternativeChildIndices]){rg(mt.wrapperNormalizationBudget);let Lt=Je.slice(Tt);K?.recordSegment({type:"transparent-wrapper",wrapper:Ft.wrapper,output:oe(Lt)});let Ht=wo(Lt,U,{...mt,effectiveCwd:Dt,envAssignments:Rt});if(Ht)return Ht}return null}let rn=Ee?void 0:_t==="eval"?Hs(Je):_t==="trap"&&!Ce?fp(Je):void 0;if(Ce&&de&&_t==="eval"){if(rn?.kind==="dynamic")return xo(de,j.policy);if(rn?.kind==="literal"){let Tt=j.analyzeNested(rn.source,{effectiveCwd:Dt,envAssignments:Rt});if(Tt)return Tt}return Ao(de,j.policy)}if(rn?.kind==="dynamic"&&(j.strict||!j.commandView||!yc(j.commandView)))return vn(K);if(rn?.kind==="literal"){K?.recordSegment({type:"recurse",reason:_t==="eval"?"shell-eval":"shell-trap",innerCommand:rn.source,depth:U+1});let Tt=j.analyzeNested(rn.source,{effectiveCwd:Dt,envAssignments:Rt,functionDefinitions:j.functionDefinitions});if(Tt)return Tt}if(Ce?Xt.has(_t):ag(pt,_t)){if(sr(Qe))return null;if(Ce&&de){let Tt=Hn(Qe);if(Tt){if(de.dynamicSourceInput??de.dynamicInput){let Ht=xo(de,j.policy);if(Ht)return Ht}if(vi(Tt)){let Ht=xo(de,j.policy);if(Ht)return Ht}return j.analyzeNested(Tt,{effectiveCwd:Dt,envAssignments:Rt})}let Lt=lr(Je);if(Lt.kind==="dynamic")return xo(de,j.policy);if(Lt.kind==="literal")return de.dynamicSourceInput?xo(de,j.policy):null;return de.dynamicSourceInput??de.dynamicInput?xo(de,j.policy):null}if(Ee){let Tt=Hn(Qe),Lt=Tt?j.analyzeNested(Tt,{effectiveCwd:Dt,envAssignments:Rt}):lr(Je).kind==="dynamic"?vn(K):null;if(Lt)return Lt}if(de===void 0){let Tt=Qw(Qe,Rt,Dt,j,K,U);if(Tt)return Tt;let Lt=Hn(Qe);if(Lt){let Xr=js(Je,Lt);if(Xr.kind==="dynamic")return vn(K);let fa=Xr.kind==="literal"?Xr.source:pp(Je,Lt),td=eA(fa);K?.recordSegment({type:"shell-wrapper",wrapper:_t,innerCommand:td}),K?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:td,depth:U+1});let nd=j.analyzeNested(fa,{effectiveCwd:Dt,envAssignments:Rt});if(nd)return nd;return vi(fa)?vn(K):null}let Ht=lr(Je,j.strict?void 0:j.shellAssignments);if(Ht.kind==="dynamic")return vn(K);if(Ht.kind==="literal")return Qs(Ht.source,Dt,Rt,j,K,U);let sn=gp(Je,j.commandView?.redirections??[],j.hasPipelineInput??!1,j.literalShellInput);if(sn.kind==="dynamic")return vn(K);if(sn.kind==="literal")return K?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:sn.source,depth:U+1}),j.analyzeNested(sn.source,{effectiveCwd:Dt,envAssignments:Rt})}}if(!de&&(_t==="source"||_t===".")){let Tt=Qe[1]==="-p"?2:null;if(Tt!==null){let Xr=j.commandView?Je[Tt]:void 0;if(!Xr)return null;if(Xr.provenance!=="literal")return vn(K)}let Lt=Tt===null?1:3,Ht=Qe[Lt]==="--"?Lt+1:Lt,sn=j.commandView?Je[Ht]:void 0;if(!sn)return null;if(sn.provenance==="literal")return Qs(sn.text,Dt,Rt,j,K,U);if(j.strict||!j.commandView||!yc(j.commandView))return vn(K)}if(Mn.has(_t)&&!Ee){if(!de&&j.strict&&wc(hi(Qe),Je))return vn(K);let Tt=Pf(Qe,(Ht)=>Sr(j.analyzeNested(Ht,{effectiveCwd:Dt,envAssignments:Rt}))),Lt=Mt(Tt,j.policy);if(Lt)return K?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:Lt.reason}),pn(Lt)}if(Fn(_t)&&!Ee){if(!de&&j.strict&&wc(fs(Qe),Je))return vn(K);let Tt=Rm(Qe);if(Ce&&de)return Xw(_t,Tt,Dt,Rt,j,de);if(Tt){let Lt=tn(j.policy,"interpreter.one-liner-paranoid",!!j.paranoidInterpreters);if(K?.recordSegment({type:"interpreter",interpreter:_t,codeArg:Tt,paranoidBlocked:Lt}),Lt){let sn=Mt(At("interpreter.one-liner-paranoid",oi),j.policy);if(sn)return pn(sn)}if(Ol(_t,Tt))return null;K?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:Tt,depth:U+1});let Ht=j.analyzeNested(Tt,{effectiveCwd:Dt,envAssignments:Rt});if(Ht&&!sg(Ht,Tt))return Ht;if(ii(Tt,void 0,!j.strict)){let sn=Mt(At("interpreter.dangerous-command",uo),j.policy);if(sn)return K?.recordSegment({type:"dangerous-text",token:Tt,matched:!0,reason:uo}),pn(sn)}K=void 0}}if(_t==="busybox"&&Qe.length>1)return rg(mt.wrapperNormalizationBudget),K?.recordSegment({type:"busybox",subcommand:Qe[1]??"unknown"}),K?.recordSegment({type:"recurse",reason:"busybox",innerCommand:Qe.slice(1).join(" "),depth:U+1}),wo(Je.slice(1),U,{...mt,effectiveCwd:Dt,envAssignments:Rt});let Vt=de?null:Mt(Cm(_t,Qe),j.policy);if(Vt)return K?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:Vt.reason}),pn(Vt);let Bt=K===mt.trace?mt:{...mt,trace:K},un={words:Je,parsedWords:Ye.words,head:_t,cwd:It,originalCwd:Ot,envAssignments:Rt,allowTmpdirVar:ft,dynamicArguments:Ye.words.some((Tt)=>Tt.provenance==="command-substitution"),depth:U,effectiveCwd:Dt,options:Bt,analyzeChildTokens:(Tt,Lt)=>Ce&&de?Oc(Tt,U,Bt,{...de,cwd:Lt??void 0,effectiveCwd:Lt??void 0}):Sr(wo(Zt(Tt),U+1,{...Bt,child:void 0,commandView:void 0,effectiveCwd:Lt,envAssignments:Rt}))??D(Tt,Bt.policy.rules),analyzeChild:(Tt,Lt)=>Oc(Tt,U,Bt,Lt)},Qt=de&&(_t==="xargs"||_t==="parallel")?void 0:ig(_t);if(_t==="rm"||_t==="xargs"||_t==="parallel")K?.recordSegment({type:"tmpdir-check",tmpdirValue:Rt.has("TMPDIR")||j.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:ft});let en=K&&_t==="git"?ip(un.words,Ic(un)):void 0,Rn=og(en?en.match:Qt?.(un)??null,j.policy);if(K)tA(un,Rn,en?.relaxation??null);if(Rn)return pn(Rn);if(Ce&&de&&(_t==="rm"||_t==="rmdir")){if(!(_t==="rm"&&(ir(Qe)||de.dynamicRmInput)))return null;return(de.dynamicRmInput?Ao(de,j.policy):null)??Jw(de,j.policy)}let Jn=Qt!==void 0&&!rA.has(_t),_r=!de&&!Jn&&!Bi.has(_t),Oo=K&&_r?[]:void 0;if(_r)for(let Tt=1;Tt<Qe.length;Tt++){let Lt=Qe[Tt];if(!Lt)continue;Oo?.push(Lt);let Ht=og(Zw(Qe,Tt,U,Bt,It,Ot,Dt,Rt),j.policy);if(Ht)return K?.recordSegment({type:"fallback-scan",tokensScanned:Oo??[],embeddedCommandFound:Wt(Lt)}),pn(Ht)}if(K?.recordSegment({type:"fallback-scan",tokensScanned:Oo??[]}),Ee&&de&&!de.wrappedByTransparent)return null;let In=D(Qe,j.policy.rules);if(K?.recordSegment({type:"custom-rules-check",rulesChecked:j.policy.rules.length>0,matched:!!In,reason:In?.reason}),In)return pn(In);return Ce&&de?Ao(de,j.policy):null}function Oc(G,U,j,K){return Sr(wo(Zt(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 Zw(G,U,j,K,re,oe,de,Ce){for(let Ee of Un(G.slice(U),{environment:K.environment,cwd:re,envAssignments:Ce,policy:K.policy})){let we=Ee.tokens[0];if(!we)continue;let Oe=Wt(we);if(ag(we,Oe)||ig(Oe)!==void 0&&Oe!=="xargs"&&Oe!=="parallel"||Ee.wrappedByTransparent&&K.policy.rules.length>0)K.budget.charge("derivedTokens",G.length-U);let Ke=Oc(Ee.tokens,j,K,{embedded:!0,cwd:Ee.cwd,originalCwd:Ee.wrapperCwd===null?void 0:oe,effectiveCwd:Ee.wrapperCwd===void 0?de:Ee.wrapperCwd,envAssignments:Ee.envAssignments,allowTmpdirVar:!ui(Ee.envAssignments,K.environment),worktreeMode:!1,wrappedByTransparent:Ee.wrappedByTransparent});if(Ke)return Ke}return null}function Xw(G,U,j,K,re,oe){if(!U)return Ao(oe,re.policy);if(tn(re.policy,"interpreter.one-liner-paranoid",!!re.paranoidInterpreters)){let Ce=Mt(At("interpreter.one-liner-paranoid",oi),re.policy);if(Ce)return pn(Ce)}if(Ol(G,U))return Ao(oe,re.policy);let de=re.analyzeNested(U,{effectiveCwd:j,envAssignments:K});if(de&&!sg(de,U))return de;if(ii(U,void 0,!re.strict)){let Ce=Mt(At("interpreter.dangerous-command",uo),re.policy);if(Ce)return pn(Ce)}return Ao(oe,re.policy)}function sg(G,U){let j=G.ruleId==="raw-text.dangerous-command",K=(G.reason.startsWith(Os)||G.reason===bo)&&!Ui(U);return j||K}function xo(G,U){let j=G.shellDynamicMatch?Mt(G.shellDynamicMatch,U):null;return j?pn(j):null}function Ao(G,U){let j=G.dynamicSourceInput&&G.dynamicSourceMatch?Mt(G.dynamicSourceMatch,U):null;return j?pn(j):null}function Jw(G,U){let j=G.dynamicInput&&G.rmDynamicMatch?Mt(G.rmDynamicMatch,U):null;return j?pn(j):null}function Qw(G,U,j,K,re,oe){let de=Df(G);if(de.argvSource?.kind==="absent")return vn(re);if(de.argvSourceApplies&&de.argvSource){let Ee=Qs(de.argvSource.value,j,U,K,re,oe,!0);if(Ee)return Ee}if(!de.envSourceApplies||!de.envName)return null;let Ce=U.get(de.envName);if(!Ce)return null;return Qs(Ce,j,U,K,re,oe,!0)}function Qs(G,U,j,K,re,oe,de=!1){if(de&&/[$`*?[\]]/.test(G))return vn(re);let Ce=ri(G,U,K.environment.paths,K.budget),Ee=Ce?K.literalHeredocFiles?.get(Ce):void 0;if(Ee===void 0)return de?vn(re):null;return K.budget.charge("derivedTokens",1),re?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:Ee,depth:oe+1}),K.analyzeNested(Ee,{effectiveCwd:U,envAssignments:j})}function eA(G){let U=G[0];return G.length>=2&&(U==='"'||U==="'")&&G.at(-1)===U?G.slice(1,-1):G}function tA(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 rg(G){if(G.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");G.iterations++}function pn(G){return{reason:G.reason,ruleId:G.id,intent:G.intent}}function vn(G){return G?.recordSegment({type:"error",message:pi}),pn(Co())}function ag(G,U){return Xt.has(U)||G==="$SHELL"||G==="${SHELL}"||Xt.has(Nt(U))}function og(G,U){return G?.id.startsWith("custom.")||G?.id==="raw-text.dangerous-command"?G:Mt(G,U)}var nA=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,rA=new Set(["powershell","pwsh"]),oA=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function iA(G,U){let j=dg(G,U);if(j.length===0)return!1;let K=j[cg(j)];if(K==="cd"||K==="pushd"||K==="popd")return!0;return nA.test(G.join(" "))}function lg(G,U,j,K,re){if(G.dialect==="powershell"){let pt=sA(G.words,re);if(pt.kind==="none")return;if(!U||pt.kind==="unknown")return null;return kc(dA(pt.target),U,j.paths)}let oe=G.words.map(t),de=oe.some((pt)=>/^CDPATH\+?=/.test(pt));if(!iA(oe,j))return de?null:void 0;if(!U)return null;let Ce=dg(oe,j,U),Ee=cg(Ce);if(Ee===-1||Ce[Ee]!=="cd")return null;let we=Ce.slice(Ee+1),Oe=we.findIndex((pt)=>pt.length<=1||!pt.startsWith("-")||pt==="--");if((Oe===-1?we:we.slice(0,Oe)).some((pt)=>!/^-[LP]+$/.test(pt)))return null;let Ke=Oe===-1?[]:we.slice(Oe),Ye=Ke[0]==="--"?Ke.slice(1):Ke;if(Ye.length>1)return null;let Xe=Ye[0],Je=K.get("HOME")||j.home;if(Xe===void 0)return kc(mn(Je),U,j.paths);let Qe=G.words.find((pt)=>pt.provenance==="variable"&&pt.text===Xe),mt=G.words.find((pt)=>pt.text===Xe&&/^~(?:\/|$)/.test(pt.raw)),Rt=Qe?Zn(Qe,new Map([...K,["HOME",Je]])):mt?`${Je}${Xe.slice(1)}`:Xe;if(Rt===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(Rt)&&(de||j.env.has("CDPATH")))return null;return kc(mn(Rt),U,j.paths)}function kc(G,U,j){if(!G||G==="-"||G.startsWith("~")||G.includes("$")||G.includes("`"))return null;try{let K=fr(U,G,j);return j.isDirectory(K)?K:null}catch{return null}}function sA(G,U){let j=aA(G[0])?1:0,K=G[j];if(!lA(K,j===1))return{kind:"none"};let re=K.text.toLowerCase(),oe=re.split(/[\\/]/).pop()??re;if(!oA.has(oe))return{kind:"none"};if(re!==oe||oe==="pop-location"||oe==="popd")return{kind:"unknown"};return cA(G.slice(j+1),U)}function aA(G){return G?.provenance==="literal"&&!G.quoted&&G.raw===G.text&&(G.text==="&"||G.text===".")}function lA(G,U){return G?.provenance==="literal"&&(U||!G.quoted&&G.raw===G.text)}function cA(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 dA(G){return G.includes("::")?void 0:G.replaceAll("\\","/")}function cg(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 dg(G,U,j){let K=uA(G);return pr([...K],U,j)}function uA(G){let U=0;while(U<G.length){let j=G[U];if(j!=="{"&&j!=="("&&j!=="$(")break;U++}return G.slice(U)}var bA="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Vr="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 Gc(G,U,j,K){if(U>=a.recursionDepth.cap)return j.trace?.recordSegment({type:"error",message:Vn}),{reason:Vn,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:Vn}),{reason:Vn,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};if(re.status==="invalid"){let we=re.issues.find((Oe)=>Oe.code.includes("heredoc"));if(we){if(!j.strict)return Wc(G,j);let Oe=`${Os}: ${we.message}`;return j.trace?.recordGlobal({type:"error",message:Oe}),{reason:Oe,segment:G,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"}}return yg(G,j),{reason:bo,segment:G,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"}}if(j.strict&&re.status==="partial")return yg(G,j),{reason:bo,segment:G,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"};if(re.issues.some((we)=>we.code.includes("quote")))return Wc(G,j);let de=j.cwd,Ce=j.effectiveCwd!==void 0?j.effectiveCwd:j.cwd,Ee=Kf(j.environment.env,j.envAssignments);return na(re,U,{...j,rootProgram:re},de,[{effectiveCwd:Ce,shellGitContextState:Ee,literalHeredocFiles:new Map(j.literalHeredocFiles),functionDefinitions:new Map(j.functionDefinitions),createdDirectories:new Set,compoundBodies:[]}]).result}function na(G,U,j,K,re){let oe=[...re],de,Ce,Ee;for(let[we,Oe]of G.nodes.entries()){if(Oe.kind==="connector"){Ce=Oe.operator;continue}let Ze=G.nodes[we+1],Ke=Ze?.kind==="connector"?Ze.operator:void 0,Ye=CA(G,we,Oe,Ce,Ke),Je=Ce==="&&"||Ce==="||"?de:void 0,Qe=Ce==="&&"?Je?.success??oe:Ce==="||"?Je?.failure??oe:oe,mt=Ce==="||"?Je?.success??[]:[],Rt=Ce==="&&"?Je?.failure??[]:[],pt={connector:Ce,skippedSuccessStates:mt,skippedFailureStates:Rt};if(vr(Ke)&&!vr(Ce))Ee=pt;let _t=vr(Ke)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:vr(Ce)?Ee??pt:pt,It=Kr(_t.connector)||Kr(Ke);if(Oe.kind==="function"){let Vt=Qe.flatMap((un)=>{let Qt=qr(un);return Qt.functionDefinitions.set(Oe.name,Oe.body),Mc(un,[Qt],Ye,Ke==="&",Kr(Ke))}),Bt=Dc(Vt,[],_t.skippedSuccessStates,_t.skippedFailureStates,_t.connector,Ke);oe=Bt.states,de=Bt.conditionalStates,Ce=void 0;continue}if(Oe.kind==="group"){let Vt=[],Bt=[];for(let Qt of Qe){let en=na(Oe.body,U,j,K,[qr(Qt)]);if(en.result)return en;if(Vt.push(...Mc(Qt,en.states,Ye,Ke==="&",Kr(Ke))),It)Bt.push(Qt,...Ye?en.states.map((Rn)=>ea(Qt,Rn)):en.states)}let un=Dc(Vt,Bt,_t.skippedSuccessStates,_t.skippedFailureStates,_t.connector,Ke);oe=un.states,de=un.conditionalStates,Ce=void 0;continue}if(Oe.kind!=="command")continue;let Ot=BA(G.nodes[we-1]),Dt=j.trace?.flattenNested?j.trace.currentSegmentIndex:j.trace?.allocateSegment(),ft=G.nodes[we-2],kt=vr(Ce)&&ft?.kind==="command"?mp(ft)??vA(ft):void 0,Ft=[],rn=[];for(let Vt of Qe){let Bt=EA(Oe,U,j,K,[qr(Vt)]);if(Bt.result)return{result:Bt.result,states:oe};let un=G.dialect==="powershell"?Bt.states:Bt.states.map((Qt)=>ea(Vt,Qt));for(let Qt of un){let en=qr(Qt),Rn=xA(Oe,U,j.trace?{...j,trace:bg(j.trace,Dt)}:j,K,en,vr(Ce),kt);if(Rn)return{result:Rn,states:oe};let Jn=YA(Oe,en.functionDefinitions);if(Jn)j.budget.charge("derivedTokens",ra(Jn));let _r=Jn?U+1>=a.recursionDepth.cap?Nc(Oe.displayText,j,[en]):na(Jn,U+1,j,K,[en]):{result:null,states:KA(Oe,en).flatMap((In)=>UA(Oe,Qt,In,Ot))};if(_r.result)return _r;Ft.push(...Mc(Vt,_r.states,Ye,Ke==="&",Kr(Ke)));let Oo=typeof en.effectiveCwd==="string"&&en.effectiveCwd!==Qt.effectiveCwd&&Oe.redirections.every((In)=>["<",">",">>",">|"].includes(In.operator)&&In.target?.text==="/dev/null");if(It&&(Ot||!Oo))rn.push(Vt),rn.push(..._r.states.map((In)=>Ye?ea(Vt,In):In))}}let Rr=Dc(Ft,rn,_t.skippedSuccessStates,_t.skippedFailureStates,_t.connector,Ke);oe=Rr.states,de=Rr.conditionalStates,Ce=void 0}return{result:null,states:oe}}function CA(G,U,j,K,re){if(j.kind==="group"&&j.style==="subshell")return!0;if(G.dialect==="posix"&&(vr(K)||vr(re)))return!0;if(re==="&")return!0;return G.dialect==="powershell"&&j.kind==="group"&&j.style==="brace"&&SA(G,U)}function Mc(G,U,j,K,re){let oe=j?U.map((Ce)=>ea(G,Ce)):[...U],de=re?oe.flatMap((Ce)=>Po(G.literalHeredocFiles,Ce.literalHeredocFiles)?[Ce]:[{...Ce,literalHeredocFiles:new Map(G.literalHeredocFiles)},Ce]):oe;return K?[G,...de]:de}function ea(G,U){return{...G,literalHeredocFiles:new Map(U.literalHeredocFiles),createdDirectories:new Set(U.createdDirectories)}}function SA(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(RA(j))return!0;return j.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function vr(G){return G==="|"||G==="|&"}function vA(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 Kr(G){return G==="&&"||G==="||"}function Dc(G,U,j,K,re,oe){let de={success:ta([...j,...G]),failure:ta([...K,...U])},Ce=Kr(oe)?de:void 0;return{states:Kr(re)||Ce?ta([...de.success,...de.failure]):de.success,conditionalStates:Ce}}function bg(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 EA(G,U,j,K,re){let oe=G.nested.map((de)=>({program:de,depth:U}));if(G.dialect==="powershell"){let de=_A(G);if(de){if(U+1>=a.recursionDepth.cap)return Nc(de,j,re);let Ce=y(de,"powershell");if(Ce.status==="limited")return Nc(de,j,re);if(Ce.status!=="complete")return ug(oe,j,K,re);j.budget.charge("derivedTokens",ra(Ce)),oe.push({program:Ce,depth:U+1})}}return ug(oe,j,K,re)}function RA(G){let U=G.words[0];return U?.provenance==="variable"&&G.words.at(-1)?.text==="="?U.text.toLowerCase():void 0}function ug(G,U,j,K){let re=[...K];for(let oe of G){let de=[];for(let Ce of re){let Ee=na(oe.program,oe.depth,U,j,[qr(Ce)]);if(Ee.result)return Ee;de.push(...Ee.states)}re=ta(de)}return{result:null,states:re}}function _A(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 ra(G){return G.nodes.reduce((U,j)=>U+(j.kind==="command"?j.words.length+j.nested.reduce((K,re)=>K+ra(re),0):j.kind==="group"||j.kind==="function"?ra(j.body):0),0)}function Nc(G,U,j){return U.trace?.recordSegment({type:"error",message:Vn}),{result:{reason:Vn,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"},states:[...j]}}function xA(G,U,j,K,re,oe,de){let Ce={...j,environment:{...j.environment,env:re.shellGitContextState.env,paths:IA(j.environment.paths,re.createdDirectories,j.budget)}},Ee=LA(G,!Ce.strict);if(Ee&&Ce.strict)return Ce.trace?.recordSegment({type:"error",message:Ee}),{reason:Ee,segment:G.source,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"};Cg(G,re,"before-consumer",Ce.environment.paths,Ce.budget);let we=ne(G.dialect,G.words),Oe=we.map(t),Ze=G.displayText,Ke=jf(we,re.shellGitContextState),Ye=Yf(Ke,re.shellGitContextState);if(G.dialect==="powershell"){let mt=Mt(Sf(G,oe,ZA(Ce,re.effectiveCwd)),Ce.policy);if(Ce.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!mt,reason:mt?.reason}),mt)return hg(Ze,mt)}let Xe=Mt(Sm(G.redirections),Ce.policy);if(Xe)return Ce.trace?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceRedirectionMatch",matched:!0,reason:Xe.reason}),hg(Ze,Xe);if(Oe.length===1&&Oe[0]?.includes(" ")&&!qo(G.dialect,G.words)){let mt=Mt(Dn(Oe[0]),Ce.policy),Rt=mt!==null&&!Ce.strict&&gm(G,Ce.rootProgram);if(mt&&!Rt)return Ce.trace?.recordSegment({type:"dangerous-text",token:Oe[0],matched:!0,reason:mt.reason}),{reason:mt.reason,segment:Ze,ruleId:mt.id,intent:mt.intent};Ce.trace?.recordSegment({type:"dangerous-text",token:Oe[0],matched:!1});let pt=mg(G,Ee,re,Ye,de,Ce);if(pt)return pt;return uc(Ke,re.shellGitContextState),null}let Je=wo(G.words,U,{...Ce,commandView:G,cwd:K,effectiveCwd:re.effectiveCwd,envAssignments:Ye,shellAssignments:re.shellGitContextState.shellAssignments,literalHeredocFiles:re.literalHeredocFiles,functionDefinitions:re.functionDefinitions,hasPipelineInput:oe,literalShellInput:de,analyzeNested:(mt,Rt)=>{let pt=Rt&&Object.hasOwn(Rt,"effectiveCwd")?Rt.effectiveCwd:re.effectiveCwd,_t=Gc(mt,U+1,{...Ce,effectiveCwd:pt,envAssignments:Rt?.envAssignments??Ye,literalHeredocFiles:re.literalHeredocFiles,functionDefinitions:Rt?.functionDefinitions,worktreeMode:Rt?.worktreeMode??Ce.worktreeMode,shell:Rt?.shell??Ce.shell,trace:Ce.trace?bg(Ce.trace,Ce.trace.currentSegmentIndex,!0):void 0});return _t?{reason:_t.reason,ruleId:_t.ruleId,intent:_t.intent}:null}});if(Je)return{...Je,segment:Ze};let Qe=mg(G,Ee,re,Ye,de,Ce);if(Qe)return Qe;return uc(Ke,re.shellGitContextState),null}function mg(G,U,j,K,re,oe){let de=WA(G,U,j,K??new Map,oe);if(de)return de;return Cg(G,j,"after-consumer",oe.environment.paths,oe.budget),j.literalHeredocFiles.clear(),PA(G,U,j,oe.environment.paths,oe.budget),kA(G,j,oe.environment.paths,oe.budget),zA(G,j,re,oe.environment,oe.trace),null}var wA=new Set([">>","<>"]);function Cg(G,U,j,K,re){for(let de of G.redirections){if(!(j==="before-consumer"?AA(de):wA.has(de.operator)))continue;fg(de.target,U,K,re)}if(j!=="before-consumer"||!dn(G.words[0],"tee"))return;let oe=vg(G.words.slice(1));if(!oe)return;for(let de of oe.operands)fg(de,U,K,re)}function AA(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 fg(G,U,j,K){let re=G?.provenance==="literal"?ri(G.text,U.effectiveCwd,j,K):void 0;if(!re)return;U.literalHeredocFiles.delete(re)}function PA(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 TA(G,j.shellGitContextState.shellAssignments)){let Ce=ri(de,j.effectiveCwd,K,re);if(!Ce||!Em(Ce))continue;if(!j.literalHeredocFiles.has(Ce)&&j.literalHeredocFiles.size>=a.trackedHeredocFiles.cap)throw new s("trackedHeredocFiles");j.literalHeredocFiles.set(Ce,oe.body)}}function TA(G,U){let j=Lc(DA(G.redirections)?.target,U),K=j===void 0?[]:[j];if(dn(G.words[0],"cat"))return MA(G.words)?K:[];if(!dn(G.words[0],"tee"))return[];let re=vg(G.words.slice(1),U);if(!re||re.append||re.hasUnsupportedOptions)return[];let oe=re.operands.map((de)=>Lc(de,U));if(!oe.every((de)=>de!==void 0))return[];return[...oe,...K]}function Lc(G,U){if(NA(G))return G.text;return(G&&Zn(G,U))??void 0}function IA(G,U,j){if(U.size===0)return G;let K=(re)=>{let oe=zt(re,G,j);return[...U].some((de)=>de===oe||de.startsWith(`${oe}${yA}`))};return{realpath:(re)=>G.realpath(re)??(K(re)?zt(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 kA(G,U,j,K){if(U.shellGitContextState.bodyDepth>0||!dn(G.words[0],"mkdir"))return;let re=G.words.slice(1).map((we)=>Lc(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 Ce=de.some((we)=>we==="--parents"||/^-v*p/.test(we)),Ee=U.effectiveCwd;for(let we of re.slice(re[oe]==="--"?oe+1:oe)){if(we.split(/[\\/]/).includes("..")||!fA(we)&&!Ee)continue;let Oe=zt(hA(Ee??"",we),j,K);if(Ce?OA(Oe,j):j.isDirectory(mA(Oe))&&Sg(Oe,j))U.createdDirectories.add(Oe)}}function OA(G,U){let j=gA(G).root,K=G.slice(j.length).split(/[\\/]+/).filter(Boolean),re=(de)=>pA(j,...K.slice(0,de+1)),oe=K.findIndex((de,Ce)=>!U.isDirectory(re(Ce)));return oe===-1||Sg(re(oe),U)}function Sg(G,U){try{return U.entryKind(G)==="missing"}catch{return!1}}function MA(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 DA(G){let U=G.findLast((j)=>(j.fd??([">",">|",">>",">&"].includes(j.operator)?1:0))===1);return U?.operator===">"||U?.operator===">|"?U:void 0}function vg(G,U=new Map){let j=[],K=!0,re=!1,oe=!1;for(let de of G){if(de.provenance!=="literal"&&Zn(de,U)===null)return;if(K&&dn(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((Ce)=>Ce!=="a"&&Ce!=="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 NA(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 dn(G,U){return G?.text===U&&G.raw===U&&G.provenance==="literal"&&!G.quoted}function Fc(G){return G.quotedDelimiter||!/[$`\\]/.test(G.body)}function LA(G,U){let j=G.redirections.filter((Ee)=>Ee.operator==="<<"||Ee.operator==="<<-");if(j.length===0)return;if(j.length!==1)return Vr;let K=j[0];if(!K?.heredoc)return Vr;let re=/\$\(|`/.test(K.heredoc.body);if(!Fc(K.heredoc)&&(!U||re))return bA;if(K.fd!==void 0&&K.fd!==0)return Vr;if(G.redirections.some((Ee)=>Ee!==K&&["<","<<","<<-","<<<","<&","<>"].includes(Ee.operator)))return Vr;let oe=G.redirections.some((Ee)=>Ee!==K&&pg(Ee.target));if(dn(G.words[0],"cat"))return oe?Vr:void 0;if(dn(G.words[0],"tee"))return oe||G.words.slice(1).some(pg)?Vr:void 0;let de=G.words[0],Ce=G.words[1];if(dn(de,"git")&&(dn(Ce,"apply")||dn(Ce,"commit")))return;if(dn(de,"gh")&&(dn(Ce,"pr")||dn(Ce,"issue"))&&dn(G.words[2],"create"))return;return Vr}function pg(G){return G?.parts.some((U)=>U.provenance==="command-substitution"&&U.raw.startsWith(">("))??!1}function WA(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(FA(G,oe,j,K,re))return null;let Ce=GA(G,oe,re);if(Ce!==void 0)return Ce?{reason:Ce.reason,segment:G.displayText,ruleId:Ce.id,intent:Ce.intent}:null;let Ee=Wc(de.length===oe.length?de.join(`
|
|
43
|
+
`):G.source,re);return Ee?{...Ee,segment:G.displayText}:null}function GA(G,U,j){let K=U.length===1?U[0]:void 0;if(!K?.heredoc||!Fc(K.heredoc)||K.fd!==void 0&&K.fd!==0)return;let re=dn(G.words[0],"uv")&&dn(G.words[1],"run")?G.words.slice(2):G.words,oe=re[0];if(oe?.provenance!=="literal"||!Fn(oe.text))return;let de=re.findIndex((Ze)=>dn(Ze,"-"));if(!re.slice(1,de===-1?void 0:de).every((Ze)=>Ze.provenance==="literal"&&Ze.text.startsWith("-")))return;let Ee=K.heredoc.body,we=tn(j.policy,"interpreter.one-liner-paranoid",!!j.paranoidInterpreters);if(j.trace?.recordSegment({type:"interpreter",interpreter:oe.text,codeArg:Ee,paranoidBlocked:we}),we){let Ze=Mt(At("interpreter.one-liner-paranoid",oi),j.policy);if(Ze)return Ze}if(!ii(Ee,void 0,!j.strict))return null;let Oe=Mt(At("interpreter.dangerous-command",uo),j.policy);if(!Oe)return null;return j.trace?.recordSegment({type:"dangerous-text",token:Ee,matched:!0,reason:Oe.reason}),Oe}function FA(G,U,j,K,re){let oe=U.length===1?U[0]:void 0;if(!oe?.heredoc||!Fc(oe.heredoc)||oe.fd!==void 0&&oe.fd!==0)return!1;let de=Nr(G.words,re.environment,j.effectiveCwd,K),Ce=de.words.map(t),Ee=Wt(Ce[0]??"");if((de.envSplitValues?.length??0)>0||!Xt.has(Ee)&&!Xt.has(Nt(Ee)))return!1;return sr(Ce)}function zA(G,U,j,K,re){let oe=lg(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 $A=new Set(["fi","done","esac"]);function BA(G){return G?.kind==="command"&&G.words.length===1&&G.words[0]?.raw==="!"}function UA(G,U,j,K){let re=G.words[0]?.text??"",oe=U.shellGitContextState.bodyDepth,de=j.shellGitContextState.bodyDepth,Ce=j.compoundBodies;if(de>oe)return j.compoundBodies=[...Ce.slice(0,oe),{entryCwd:U.effectiveCwd,branchCwds:Ce[oe]?.branchCwds??[],hasElse:!1}],[j];let Ee=oe>0?Ce[oe-1]:void 0;if(Ee&&(re==="else"||re==="elif"))return j.compoundBodies=[...Ce.slice(0,oe-1),{entryCwd:Ee.entryCwd,branchCwds:[...Ee.branchCwds,j.effectiveCwd],hasElse:re==="else"}],j.effectiveCwd=Ee.entryCwd,[j];let we=Ee!==void 0&&$A.has(re);if(we)j.compoundBodies=Ce.slice(0,de);return[...new Set([j.effectiveCwd,...we?Ee.branchCwds:[],...we&&!Ee.hasElse?[Ee.entryCwd]:[],...K?[U.effectiveCwd]:[]])].map((Ze)=>{if(Ze===j.effectiveCwd)return j;let Ke=qr(j);return Ke.effectiveCwd=Ze,Ke})}function HA(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 jA=/^[A-Za-z_][A-Za-z0-9_]*$/,VA=8;function KA(G,U){let j=G.words[1]?.text;if(G.dialect!=="posix"||G.words[0]?.text!=="for"||j===void 0||!jA.test(j))return[U];let K=G.words.slice(3);if(!(G.words[2]?.text==="in"&&K.length>=1&&K.length<=VA&&K.every((oe)=>oe.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(oe.text))))return U.shellGitContextState.shellAssignments.delete(j),[U];return K.map((oe)=>{let de=qr(U);return de.shellGitContextState.shellAssignments.set(j,oe.text),de})}function qr(G){return{effectiveCwd:G.effectiveCwd,shellGitContextState:qf(G.shellGitContextState),literalHeredocFiles:new Map(G.literalHeredocFiles),functionDefinitions:new Map(G.functionDefinitions),createdDirectories:new Set(G.createdDirectories),compoundBodies:G.compoundBodies}}function ta(G){let U=[];for(let j of G){if(!U.some((K)=>qA(K,j)))U.push(j);if(U.length>a.controlFlowStates.cap)throw new s("controlFlowStates")}return U}function qA(G,U){return G.effectiveCwd===U.effectiveCwd&&HA(G.compoundBodies,U.compoundBodies)&&Po(G.shellGitContextState.env,U.shellGitContextState.env)&&Po(G.literalHeredocFiles,U.literalHeredocFiles)&&Po(G.functionDefinitions,U.functionDefinitions)&&Po(G.shellGitContextState.effectiveEnvAssignments,U.shellGitContextState.effectiveEnvAssignments)&&Po(G.shellGitContextState.shellAssignments,U.shellGitContextState.shellAssignments)&&G.shellGitContextState.bodyDepth===U.shellGitContextState.bodyDepth&&gg(G.shellGitContextState.bodyAssignments,U.shellGitContextState.bodyAssignments)&&gg(G.createdDirectories,U.createdDirectories)}function gg(G,U){return G.size===U.size&&[...G].every((j)=>U.has(j))}function Po(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 YA(G,U){let j=Yo(G);return j===void 0?void 0:U.get(j)}function hg(G,U){if(!U)return null;return{reason:U.reason,segment:G,ruleId:U.id,intent:U.intent}}function ZA(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 Wc(G,U){let j=Mt(Dn(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 yg(G,U){let j={type:"strict-unparseable",rawCommand:G,reason:bo},K=U.trace?.currentSegmentIndex;if(K===void 0)U.trace?.recordGlobal(j);if(K!==void 0)U.trace?.recordSegment(j)}var XA=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function Eg(G,U,j,K){let re=Gc(G,0,{...U,...ze(U),budget:U.budget??kn(),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 Rg(G,U,j){try{return{decision:G()}}catch(K){let re=JA(K,U,j);if(!re)throw K;return re}}function JA(G,U,j){if(!(G instanceof s)||!XA.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 QA=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),$c=new Set(["cc-safety-net","ccsn"]),eP=new Set(["bunx","npx","pnpx"]),tP=new Set(["pnpm","yarn"]),nP=new Set(["npm","pnpm","yarn"]),rP=new Set(["bun","node"]);function ia(G,U,j={}){if($c.has(G))return 0;if(eP.has(G)){if(j.broad)return zc(U);let re=U[0]==="-y"||U[0]==="--yes"?1:0;return oa(U[re])?re+1:null}let K=j.broad?U.findIndex((re)=>!re.startsWith("-")):0;if(K!==-1&&nP.has(G)&&j.broad&&U[K]==="exec"){let re=zc(U.slice(K+1));return re===null?null:K+1+re}if(tP.has(G)){if(G==="yarn"&&!j.broad)return null;if(!j.broad)return U[0]==="dlx"&&oa(U[1])?2:null;if(K===-1||U[K]!=="dlx")return null;let re=zc(U.slice(K+1));return re===null?null:K+1+re}if(rP.has(G)){let re=j.broad&&K!==-1?K:0;if(_g(U[re]))return re+1;if(G==="bun"&&U[re]==="run"&&_g(U[re+1]))return re+2}return null}function zc(G){let U=G.findIndex((K)=>oa(K));if(U===-1)return null;let j=U;while(j<G.length){let K=G[j]??"";if(!K.startsWith("-")&&!oa(K))break;j++}return j}function oa(G){if(!G)return!1;let U=G.indexOf("@");if(U===-1)return $c.has(G);if(U===0)return!1;let j=G.slice(U+1);if(j===""||j.includes("/")||j.includes(":"))return!1;return $c.has(G.slice(0,U))}function _g(G){let U=G?.replaceAll("\\","/");return[...QA].some((j)=>U===j||U?.endsWith(`/${j}`))}var Ve="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 xg(G,U,j){let K=Cn(G,"input-candidate");if(!K)return null;let re=po(K.shell,G.invocation.context.executionCwd,U,j,{findSegmentTarget:(oe)=>oP(oe,U),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return re?{target:re}:null}function oP(G,U){let j=pr([...G],U),K=j.slice(1),re=ia(Nt(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 sa}from"node:path";var qe="This path contains the protected policy config and you must not modify or delete it.",iP=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Tg(G,U,j){let K=uP(G.invocation.context,U,j);if(G.invocation.route.kind==="patch")return wg(G.paths,!1,G.invocation.context.executionCwd,K,U,j);let re=Cn(G,"input-candidate");if(G.invocation.route.kind==="command")return re?Ag(re.shell,G.invocation.context.executionCwd,K,U,j):null;if(G.invocation.route.kind==="unknown"&&re){let oe=Ag(re.shell,G.invocation.context.executionCwd,K,U,j);if(oe)return oe}return wg(G.paths,G.invocation.route.kind==="grep"||G.invocation.route.kind==="glob"||Mi(G.invocation.toolName),G.invocation.context.executionCwd,K,U,j)}function wg(G,U,j,K,re,oe){if(U)return null;let de=G.find((Ce)=>_i(Ce,j,K,re,oe));return de?{target:de}:null}function Ag(G,U,j,K,re){let oe=po(G,U,K,re,{findSegmentTarget:(de,Ce)=>sP(de,Ce,j,K,re)?.target??null,isRedirectionTarget:(de,Ce)=>_i(de,Ce.cwd,j,K,re),findMalformedTarget:(de)=>dP(de,U,j,K,re)?.target??null});return oe?{target:oe}:null}function sP(G,U,j,K,re){if(di(G))return null;let oe=gr([...G],K),de=Nt(oe[0]??"").toLowerCase(),Ce=oe.slice(1);if(de==="rm"&&aP(Ce)){let Ee=lP(Ce).find((we)=>Pg(bn(we,U.variables),U.cwd,j,K,re));if(Ee)return{target:Ee}}if(de==="find"){if(Gs(oe,1)||nc(oe,K)){let we=(yi(Zt(oe))??Zt(["."])).find((Oe)=>{let Ze=bn(Oe.text,U.variables);return _i(Ze,U.cwd,j,K,re)||Pg(Ze,U.cwd,j,K,re)})?.text;if(we)return{target:we}}}if(de==="mv"){let Ee=xs(Ce).sources.find((we)=>mP(bn(we,U.variables),U.cwd,j,K,re));if(Ee)return{target:Ee}}if(cP(oe,de))return null;for(let Ee of[...G,...oe])for(let we of Ig(Ee))if(_i(bn(we,U.variables),U.cwd,j,K,re))return{target:we};return null}function aP(G){return G.some((U)=>U==="--recursive"||U.startsWith("-")&&!U.startsWith("--")&&/[rR]/.test(U.slice(1)))}function lP(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 cP(G,U){if(!iP.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 dP(G,U,j,K,re){for(let oe of G.split(/\s+/))for(let de of Ig(oe))if(_i(de,U,j,K,re))return{target:de};return null}function Ig(G){let U=G.trim().replace(/^['"]|['"]$/g,""),j=U.indexOf("=");return j===-1||j===U.length-1?[U]:[U,U.slice(j+1)]}function uP(G,U,j){let K=(Ce)=>xi(fn(Ce,G.executionCwd,U,j)),re=K(u(U)),oe=[K(h(G.executionCwd)),K(h(G.configCwd))],de=new Set(oe.map((Ce)=>sa(Ce)));for(let Ce=sa(re);;Ce=sa(Ce))if(de.add(Ce),sa(Ce)===Ce)break;return{files:new Set([re,...oe]),directoriesAndAncestors:de}}function _i(G,U,j,K,re){let oe=ld(G,U,K,re,(de)=>xi(de)===zi);return oe!==null&&j.files.has(xi(oe))}function Pg(G,U,j,K,re){return j.directoriesAndAncestors.has(xi(fn(G,U,K,re)))}function mP(G,U,j,K,re){let oe=xi(fn(G,U,K,re));return j.files.has(oe)||j.directoriesAndAncestors.has(oe)}function xi(G){return process.platform==="win32"?G.toLowerCase():G}import{isAbsolute as aa,posix as Ug,resolve as ua,win32 as fP}from"node:path";import{fileURLToPath as pP}from"node:url";var Hg="Access to a sensitive path is not allowed.",jg=new Set(["echo","printf"]),gP=new Set(["find"]),hP=new Set(["!","do","elif","else","if","then","until","while"]),yP=new Set(["-exec","-execdir"]),bP=new Set([";","+"]),CP=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),SP=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Vg=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),vP=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),EP=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"]),Vc=new Set(["-c","-e","-r","-E","--eval","--exec"]),RP=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"])]]),Kc=new Set(["grep","rg"]),Kg=new Set(["files-with-matches","files-without-match","count","quiet"]),_P=new Set([...Kg,"ignore-case","fixed-strings","hidden"]),xP=new Set(["wc",...Kc]),wP=new Set(["cd","grep","head","openssl","tail","tailscale"]),AP=/^(?:-[lwcm]+|--(?:lines|words|bytes|chars))$/,PP=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),TP=new Set(["commit","merge","notes","stash","tag"]),IP=new Set(["-m","--message"]),kP=new Set(["--grep"]),OP=new Set(["powershell","pwsh"]),kg=new Set(["jq","gojq","jaq"]),Og="f",Mg="file",MP="files",DP=new Set(["e","f"]),NP=new Set(["regexp","file"]),LP=new Set(["e","f","A","B","C","m"]),WP=new Set(["regexp","file","after-context","before-context","context","max-count"]),Bc="__CC_SAFETY_NET_PIPE_INPUT__",Hc=/[\w./~@+-]*[./~][\w./~@+-]*/g,GP=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,FP=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,zP=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,Dg=/\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,Ng=/\b(?:system|exec|spawn|popen)\s*$/,$P=/\b(?:eval|exec)\s*\(/g,BP=/\b(?:eval|exec)\s*$/,UP=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 Lg(G,U,j,K,re,oe){for(let de of G){let Ce=de.target;if(cI(Ce,de.cwd,U?.denyPaths??[],j,K,re))return{target:Ce,ruleId:"secret.deny-path"};if(oe&&!oe.has(Ce))continue;let Ee=aI(Ce,de.cwd,U,K,re);if(Ee){let we=oe!==void 0&&!Ee.startsWith("secret.home.")&&!Ee.startsWith("secret.cli.");if(we&&K.paths.isDirectory(ah(Ce,de.cwd,K,re)))continue;if(we&&oe?.get(Ce)==="data")continue;if(we&&(de.isRedirectionWriteTarget===!0||oe?.get(Ce)==="write")&&!Ce.includes("$")&&!da(Ce,de.cwd,K,re))continue;if(we&&(de.isCreatedPath===!0||de.isCertificateInput===!0))continue;if(we&&/\s/.test(Ce)&&!Ce.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(Ce)&&!da(Ce,de.cwd,K,re))continue;if(!Ee.startsWith("secret.cli.")&&dI(Ce,de.cwd,U?.allowPaths??[],j,K,re))continue;return{target:Ce,ruleId:Ee}}}return null}function qg(G,U,j,K,re={}){let oe=Wg(G,j,K),de=Lg(oe,U,G.invocation.context.configCwd,j,K);if(de===null||de.ruleId==="secret.deny-path"||re.strict!==!1)return de;let Ce=Wg(G,j,K,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}),Ee=new Map;Ce.forEach((Xe)=>Yg(Xe.target).forEach((Je)=>Ee.set(Je,(Ee.get(Je)??new Set).add(Xe.loopVariable))));let we=(Xe,Je)=>(Ee.get(Xe)?.size??0)>(Ee.get(Xe)?.has(Je)?1:0),Oe=Ce.filter(({loopVariable:Xe})=>Xe===void 0||we(Xe,Xe)||we("!",Xe)),Ze=new Set(Oe.filter((Xe)=>Xe.literalRole===void 0).map((Xe)=>Xe.target)),Ke=new Set(Oe.filter((Xe)=>Xe.literalRole==="write").map((Xe)=>Xe.target)),Ye=Lg(oe,U,G.invocation.context.configCwd,j,K,new Map(Oe.map((Xe)=>[Xe.target,Ze.has(Xe.target)?"path":Ke.has(Xe.target)?"write":"data"])));return Ye?.ruleId!=="secret.deny-path"&&HP(G,j)?null:Ye}function HP(G,U){let j=Cn(G,"input-candidate")??Cn(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 _s(j.shell)){if(de.kind==="operator"&&de.boundary)return!1;if(de.kind==="redirection")return!1;if(de.kind==="operator")continue;K.push(or(de.text,U))}let re=Xn(K);if(re.length===0)return!1;let oe=gn(re[0]??"").toLowerCase();if(G.invocation.route.kind==="unknown")return j.program.dialect==="powershell"&&(oe==="ls"||oe==="stat");return qc(oe,re.slice(1))}function qc(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("-")||AP.test(j));if(Kc.has(G))return jP(G,U);if(G!=="find")return!1;return!U.some((j)=>CP.has(j))}function jP(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 Oe=j[we-1]??"";return/^--[^=]+$/.test(Oe)&&!_P.has(Oe.slice(2))||oe(Oe)&&Oe.slice(1).search(K)===Oe.length-2},Ce=j.findIndex((we,Oe)=>!we.startsWith("-")&&!de(Oe));return(G==="grep"&&Ce>=0?j.slice(0,Ce):j).some((we,Oe)=>{if(de(Oe))return!1;if(we.startsWith("--"))return Kg.has(we.slice(2));return oe(we)&&re.test(we.slice(1).split(K)[0]??"")})}function Wg(G,U,j,K={}){let re=G.invocation.context.executionCwd,oe=G.invocation.route.kind;if(oe!=="command"&&oe!=="unknown")return G.paths.map((Ce)=>({target:Ce,cwd:re}));let de=Cn(G,"input-candidate");return[...de?ko(de.shell,G.store,K,U,re,j,VP(de)):[],...oe==="unknown"?G.paths.map((Ce)=>({target:Ce,cwd:re})):[]]}function VP(G){return G.program.dialect==="powershell"}function ko(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 Ce=[...G.assignmentFallbacks.map((Qe)=>({target:Qe,cwd:re})),...UT(or(G.source,K),U,j,K,re,oe)],Ee=(Qe)=>or(oT(Qe,de),K),we=/[<>=]\(/.test(G.source),Oe=/\bcoproc\b|\|&/.test(G.source),Ze=[],Ke=[],Ye=(Qe)=>({...j,commandHoldsPipe:j.commandHoldsPipe===!0||Qe||Oe});Rs(G,re,K,oe,{word:Ee,segment:(Qe,mt,Rt,pt,_t,It)=>{if(Qe.length===0)return null;let Ot=Ye(It);if(Ot.commandHoldsPipe)Ze.push(...Qe);if(Ke.push(gn(Zg(Xn(Qe))[0]??"").toLowerCase()),Ce.push(...Ai(Qe,U,we||pt==="|"||pt==="|&"?{...Ot,segmentMayFeedReader:!0}:Ot,K,mt.cwd,oe,_t)),Rt!==null)Ce.push(...YP(Rt,Qe,U,Ot,K,mt.cwd,oe));return null},redirection:(Qe,mt,Rt)=>{if(Qe.body!==void 0&&Qe.consumer!==void 0){let pt=Ye(Rt);Ce.push(...Xg(Qe.consumer,[Qe.body],U,pt,K,mt.cwd,oe,(_t)=>ZP(Qe.consumer??[],_t,U,pt,K,mt.cwd,oe)))}if(Qe.targetOrder==="legacy-segment")return Fl;return Ce.push({target:Ee(Qe.target),cwd:mt.cwd,...Qe.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}});let Xe=new Set(Ze.flatMap(Yg)),Je=we||/\$\(|`/.test(G.source)||!Ke.every((Qe)=>wP.has(Qe));return Ce.map(({loopVariable:Qe,...mt})=>{if(mt.certificateOutputMayFeedReader===!0&&Je)return{target:mt.target,cwd:mt.cwd};return Qe===void 0||we||Xe.has(Qe)||Xe.has("!")?mt:{...mt,loopVariable:Qe}})}function Yg(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 la(G,U,j,K,re,oe,de=!1){let Ce=U.getShellSyntax(G,de?U.getCommandProgram(G,"powershell"):void 0);if(Ce.status==="structural-limit")throw new b;return Ce.status==="complete"?ko(Ce,U,j,K,re,oe,de):null}function Ai(G,U,j,K,re,oe,de){let Ce=(ft)=>({target:ft,cwd:re}),Ee=G.findIndex((ft)=>!hP.has(ft));if(j.skipMetadataOnlySegments===!0&&Ee>0)return Ai(G.slice(Ee),U,j,K,re,oe,new Set([...de??[]].map((ft)=>ft-Ee)));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((ft)=>Wn("for",ft)).map((ft)=>({...Ce(ft),loopVariable:we}));if(de?.size){let ft=G.filter((kt,Ft)=>!de.has(Ft));if(kg.has(gn(Xn(ft)[0]??"").toLowerCase()))return[...G.filter((kt,Ft)=>de.has(Ft)).map(Ce),...Ai(ft,U,j,K,re,oe)]}let Oe=rT(G).map(Ce),Ze=Xn(G);if(Ze.length===0)return Oe;let Ke=Ze[0]??"",Ye=gn(Ke).toLowerCase(),Xe=Ze.slice(1),Je=j.segmentMayFeedReader===!0||j.commandHoldsPipe===!0||j.displayOperandsAreCapturedOutput===!0,Qe=Je&&xP.has(Ye);if(j.skipMetadataOnlySegments===!0&&!Qe&&qc(Ye,Xe))return Oe;let mt=qP(Ke,Ye,Xe);if(mt)return[...Oe,...mt.map(Ce)];if(jg.has(Ye))return j.displayOperandsAreCapturedOutput===!0?[...Oe,...Jg(G).map(Ce)]:Oe;if(Ye==="eval")return[...Oe,...la(Xe.join(" "),U,j,K,re,oe)??Xe.map(Ce)];let Rt=OP.has(Wt(Ke))?Pc(Ze):void 0;if(Rt!==void 0)oe.charge("derivedTokens",Ze.length);let pt=Rt===void 0?null:la(Rt,U,j,K,re,oe,!0);if(pt?.length)return[...Oe,...pt];if(Ye==="export")return[...Oe,...Xe.flatMap((ft)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(ft)?[ft.slice(ft.indexOf("=")+1)]:Wn(Ye,ft)).map(Ce)];if(Ye==="git")return[...Oe,...sT(Xe).map(Ce)];if(Ye==="gh")return[...Oe,...jc(Ye,Xe,PP).map(Ce)];if(kg.has(Ye))return[...Oe,...iT(Xe).map(Ce)];if(Kc.has(Ye))return[...Oe,...XT(Xe).map(Ce)];if(gP.has(Ye))return[...Oe,...lT(Xe,U,j,K,re,oe).map(Ce)];if(Ye==="mkdir"||Ye==="touch"){let ft=new Set(G.filter((Ft,rn)=>de?.has(rn))),kt=j.segmentMayFeedReader!==!0&&!(Ye==="touch"&&Xe.some((Ft)=>/^(?:--r|-[^-]*r)/.test(Ft)));return[...Oe,...Xe.flatMap((Ft)=>Wn(Ye,Ft).map((rn)=>kt&&!Ft.startsWith("-")&&!ft.has(Ft)?{...Ce(rn),isCreatedPath:!0}:Ce(rn)))]}if(Mn.has(Ye))return[...Oe,...Xe.flatMap((ft)=>Wn("awk",ft)).map(Ce),...Xe.flatMap((ft)=>dT(ft,U,j,K,re,oe)),...Xe.flatMap(uT).map(Ce)];if(Ye==="curl")return[...Oe,...Xe.filter((ft,kt)=>eh(ft)===null&&Qg(Xe[kt-1])===null).flatMap((ft)=>Wn(Ye,ft)).map(Ce),...aT(Xe).map(Ce)];if(fo(Ye)){let ft=ci.has(Ye)?xn([Ye,...Xe]):null;if(ft!==null&&ft.command!==null&&ft.commandIndex!==null){let kt=U.getShellSyntax(ft.command);if(kt.status==="structural-limit")throw new b;if(kt.status==="complete")return[...Oe,...ko(kt,U,j,K,re,oe),...Xe.slice(ft.commandIndex).filter((Ft)=>!Ft.startsWith("-")).map(Ce)]}return[...Oe,...cT(Ye,Xe,U,j,K,re,oe)]}let _t=(ft,kt)=>new RegExp(`^--?${ft}=`).test(Xe[kt]??"")||new RegExp(`^--?${ft}$`).test(Xe[kt-1]??""),It=KP(Ze),Ot=Ye==="openssl"&&Xe[0]==="x509",Dt=Je?{certificateOutputMayFeedReader:!0}:{};return[...Oe,...Xe.flatMap((ft,kt)=>Wn(Ye,ft).map((Ft)=>It&&_t("(?:cert|key)-file",kt)?{...Ce(Ft),isCreatedPath:!0,...Dt}:Ot&&_t("in",kt)?{...Ce(Ft),isCertificateInput:!0,...Dt}:Ce(Ft)))]}function Zg(G){return gn(G[0]??"").toLowerCase()==="timeout"?G.slice(2):G}function KP(G){let U=Zg(G);return gn(U[0]??"").toLowerCase()==="tailscale"&&U[1]==="cert"}function qP(G,U,j){let K=ia(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 Ce=oe[de];if(Ce==="--json"||Ce==="--help"||Ce==="-h")continue;if(Ce==="--cwd"){let Ee=oe[de+1];if(Ee&&!Ee.startsWith("--"))re.push(Ee);de++;continue}return re}return re}function YP(G,U,j,K,re,oe,de){if(eT(U,j,K,re,oe,de)){let Ce=Xn(G),Ee=qc(gn(Ce[0]??"").toLowerCase(),Ce.slice(1))?Ce.slice(1).filter((we)=>!we.startsWith("-")):[];return[...Jg(G),...Ee].map((we)=>({target:we,cwd:oe}))}return Xg(U,XP(G),j,K,re,oe,de,()=>[])}function ZP(G,U,j,K,re,oe,de){let Ce=Xn(G);if(!fo(gn(Ce[0]??"").toLowerCase()))return[];return la(U,j,K,re,oe,de)??[{target:U,cwd:oe}]}function Xg(G,U,j,K,re,oe,de,Ce){let Ee=tT(G);if(Ee===null)return U.flatMap(Ce);return U.flatMap((we)=>ci.has(Ee)?ko(j.getShellSyntax(we),j,K,re,oe,de):ca(Ee,we,j,K,re,oe,de))}function Jg(G){let U=Xn(G);if(U.length===0)return[];let j=gn(U[0]??"").toLowerCase();if(!jg.has(j))return[];let K=U[U[1]==="--"?2:1];if(j==="printf"&&K!==void 0&&!K.startsWith("-")&&!K.replaceAll("%%","").includes("%"))return[Yc(K.replaceAll("%%","%"))];return U.slice(1)}function XP(G){let U=Xn(G);if(U.length===0)return[];let j=gn(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 JP(K);return[]}function JP(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[Yc(U)];let K=G.slice(1);return Array.from({length:Math.ceil(K.length/j)},(re,oe)=>QP(U,K.slice(oe*j,(oe+1)*j)))}function QP(G,U){let j=0;return Yc(G.replace(/%%|%[bqs]/g,(K)=>{if(K==="%%")return"%";let re=U[j]??"";return j++,re}))}function Yc(G){return G.replace(/\\n/g,`
|
|
44
|
+
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function eT(G,U,j,K,re,oe){let de=Xn(G);if(de.length===0||gn(de[0]??"").toLowerCase()!=="xargs")return!1;let Ce=jr(de),Ee=de.slice(Ce.childStart);if(Ee.length===0)return!1;if(Ce.replacementToken==="")return!1;let we=Ce.replacementToken,Oe=we===null?[...Ee,Bc]:Ee.map((Ze)=>Ze.split(we).join(Bc));return Ai(Oe,U,j,K,re,oe).some((Ze)=>Ze.target.includes(Bc))}function tT(G){let U=Xn(G);if(U.length===0)return null;let j=gn(U[0]??"").toLowerCase();if(!fo(j))return null;return nT(j,U.slice(1))?j:null}function nT(G,U){let j=Zc(G);for(let K=0;K<U.length;K++){let re=U[K];if(re===void 0)break;if(Vc.has(re)||th(G,re)||/^--(?:eval|exec)=/.test(re))return!1;if(re==="-")return!0;if(re.startsWith("-")){if(j==="python"&&re==="-m")return!1;if(UP.get(j)?.has(re))K++;continue}return!1}return!0}function Zc(G){return/^python\d/.test(G)?"python":G}function rT(G){let U=[];for(let j of G){if(sh(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 Gg=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function oT(G,U){if(!U||!Gg.test(G))return G;return`~${G.replace(Gg,"").replace(/\\/g,"/")}`}function Wn(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 iT(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)=>Wn("jq",oe))}return G.flatMap((K,re)=>re===U?[]:Wn("jq",K))}function sT(G){let U=[];for(let j=0;j<G.length;j++){let K=G[j]??"";if(K==="--"||!K.startsWith("-"))return[...U,...TP.has(K)?jc("git",G.slice(j).map((oe)=>/^-[aeinopqsv]+m$/.test(oe)?"-m":oe),IP):jc("git",G.slice(j),kP)];if(U.push(...Wn("git",K)),!_n.has(K))continue;let re=G[j+1];if(re===void 0)break;U.push(...K==="-c"&&re.includes("=")?[re.slice(re.indexOf("=")+1)]:Wn("git",re)),j++}return U}function jc(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)=>Wn(G,de))];if(j.has(oe)){re++;continue}if(oe.includes("=")&&j.has(oe.slice(0,oe.indexOf("="))))continue;K.push(...Wn(G,oe))}return K}function aT(G){return G.flatMap((U,j)=>{let K=eh(U);if(K!==null)return Fg(K.flag,K.value);let re=Qg(G[j-1]);return re===null?[]:Fg(re,U)})}function Fg(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 Uc(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 Uc(U.slice(j+1))}return U.startsWith("@")?Uc(U.slice(1)):[]}function Qg(G){if(G===void 0)return null;if(Vg.has(G))return G;return/^-[A-Za-z]+[dF]$/.test(G)?`-${G.slice(-1)}`:null}function eh(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 Vg.has(K)?{flag:K,value:G.slice(j+1)}:null}function Uc(G){return G===""||G==="-"?[]:[G]}function lT(G,U,j,K,re,oe){let de=G.findIndex((Ee)=>Ee.startsWith("-")||Ee==="("||Ee==="!"||Ee===";"),Ce=[...G.slice(0,de===-1?G.length:de),...G.flatMap((Ee,we)=>Ee==="-files0-from"&&G[we+1]!==void 0?[G[we+1]??""]:[])];for(let Ee=0;Ee<G.length;Ee++){if(!yP.has(G[Ee]??""))continue;let we=G.slice(Ee+1),Oe=we.findIndex((Ye)=>bP.has(Ye)),Ze=Oe===-1?we:we.slice(0,Oe),Ke=Ai(Ze,U,j,K,re,oe).map((Ye)=>Ye.target);if(Ce.push(...Ke.filter((Ye)=>Ye!=="{}")),!Ke.includes("{}"))continue;Ce.push(...G.slice(0,Ee).flatMap((Ye,Xe,Je)=>{if(!SP.has(Ye))return[];let Qe=Je[Xe+1];return Qe===void 0?[]:[Qe,Qe.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return Ce}function cT(G,U,j,K,re,oe,de){let Ce=[];for(let Ee=0;Ee<U.length;Ee++){let we=U[Ee];if(we===void 0)break;if(Vc.has(we)||th(G,we)){let Ze=U[Ee+1];if(Ze!==void 0)Ce.push(...ca(G,Ze,j,K,re,oe,de)),Ee++;continue}let Oe=/^--(?:eval|exec)=(.*)$/.exec(we);if(Oe!==null&&Oe[1]!==void 0){Ce.push(...ca(G,Oe[1],j,K,re,oe,de));continue}if(!we.startsWith("-"))Ce.push({target:we,cwd:oe})}return Ce}function th(G,U){if(!U.startsWith("-")||U.startsWith("--")||U.length<=2)return!1;return RP.get(U[U.length-1]??"")?.has(Zc(G))??!1}function dT(G,U,j,K,re,oe){if(!G.includes("system"))return[];return Jl(G)?.commands.flatMap((de)=>ko(U.getShellSyntax(de),U,j,K,re,oe))??[]}function uT(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 mT(G){let U=Array.from(G.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((j)=>j[2]).filter((j)=>j!==void 0&&j!=="");return[...U,...U.flatMap(Jc),...G.match(Hc)??[]]}function ca(G,U,j,K,re,oe,de){let Ce=(ft)=>({target:ft,cwd:oe}),Ee=NT(G),we=WT(U,Ee);if(we.kind==="unmaskable")return mT(U).map(Ce);let Oe=we.masked.match(Dg)!==null||we.literals.some((ft)=>Ng.test(we.masked.slice(0,ft.start))),Ze=we.masked.match($P)!==null||we.literals.some((ft)=>BP.test(we.masked.slice(0,ft.start))),Ke=K.inlineLiteralsPresumedData===!0&&!ci.has(G),Ye=Ke&&(Ee==="python"||Ee==="javascript"),Xe=Ke&&!(BT(we.masked)||Oe||Ze)?[]:we.literals,Je=Ke?Array.from(we.masked.matchAll(Dg),(ft)=>{let kt=ft.index+ft[0].length;return{start:kt,end:gs(we.masked,kt)}}):[],Qe=!Ke||Je.some((ft)=>Dl(we.masked,ft.start)&&!ST(we,ft.start))?we.literals:we.literals.filter((ft)=>Ng.test(we.masked.slice(0,ft.start))||Je.some((kt)=>ft.start>=kt.start&&ft.start<kt.end)),mt=new Set(Oe?Qe:[]),Rt=Ye&&Xe.length>0&&!hT(we.masked,Ee==="python"?"#":"//"),pt=Rt?vT(we.masked):[],_t=Rt?Array.from(we.masked.matchAll(/[A-Za-z_$][\w$]*/g),(ft)=>({name:ft[0],index:ft.index})):[],It=bT(_t),Ot=!yT(we.masked,_t),Dt=_t.filter((ft)=>!zg(we.masked,{start:ft.index,text:ft.name,tokenStart:ft.index,tokenEnd:ft.index+ft.name.length},pt,It,Ot)).reduce((ft,kt)=>{let Ft=ft.get(kt.name)??[];return Ft.push(kt.index),ft.set(kt.name,Ft)},new Map);return[...Xe.filter((ft)=>ft.text!=="").map((ft)=>{if(!Rt||mt.has(ft))return Ce(ft.text);if(zg(we.masked,ft,pt,It,Ot)||ET(we.masked,ft,pt,Dt))return{...Ce(ft.text),literalRole:"data"};return OT(we,ft,pt)?{...Ce(ft.text),literalRole:"write"}:Ce(ft.text)}),...Xe.flatMap((ft)=>Jc(ft.text)).map(Ce),...Ke?[]:we.literals.flatMap((ft)=>ft.text.match(Hc)??[]).map(Ce),...Oe?Qe.flatMap((ft)=>la(ft.text,j,{...K,commandHoldsPipe:!0},re,oe,de)??[Ce(ft.text)]):[],...Ze?we.literals.flatMap((ft)=>ca(G,ft.text.replace(/\\(.)/g,(kt,Ft)=>Ft==="n"?`
|
|
45
|
+
`:Ft),j,K,re,oe,de)):[],...Ye?[]:(we.masked.match(Hc)??[]).map(Ce),...Ke?(U.match(/\$\{[^}]*\}|\$[A-Za-z_]\w*/g)??[]).map(Ce):[]]}var Xc={"(":")","[":"]","{":"}"},nh="and|elif|else|if|in|is|not|of|or|return|while|yield",fT=new RegExp(`(?:^|[^\\w$])(?:${nh})$`),pT=new RegExp(`(?:\\*|\\.\\.\\.)\\s*[([{]|\\.\\s*(?:${nh})\\s*\\(|/\\*`),gT=/^(?:exec|spawn)|^(?:popen|system|subprocess)$/;function hT(G,U){return pT.test(G)||G.split(`
|
|
46
|
+
`).some((j)=>{let K=j.indexOf(U);return K>=0&&/[()[\]{}]/.test(j.slice(K))})}function yT(G,U){return xT.test(G)||U.some((j)=>{let K=_T.get(j.name),re=j.index+j.name.length;return K!==void 0&&!K.test(G.slice(re,re+40))})}function bT(G){return G.some((U)=>oh(U.name).some((j)=>gT.test(j)))}var CT=new Set(["cmd","powershell","pwsh"]);function ST(G,U){let j=Yr(G.masked,U),K=Xc[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(Yr(G.masked,re+1)))&&!G.literals.some((de)=>de.tokenStart>j&&de.tokenStart<re&&(Vc.has(de.text)||fo(gn(de.text).toLowerCase())||CT.has(gn(de.text).toLowerCase().replace(/\.exe$/,""))))}function vT(G){let U=[];return G.split("").map((j,K)=>{let re=U.at(-1)??-1;if(j in Xc)U.push(K);if(j===")"||j==="]"||j==="}")U.pop();return re})}function zg(G,U,j,K,re){let oe=j[U.tokenStart]??-1,de=G[oe]??"",Ce=Io(G,U.tokenStart),Ee=Yr(G,U.tokenEnd);if(/(?:^|[^\w$])in$|[=!]=$/.test(G.slice(Math.max(0,Ce-3),Ce+1)))return!0;if(/^(?:(?:not\s+)?in(?![\w$])|[=!]=)/.test(G.slice(Ee,Ee+8)))return!0;if(K&&(de==="["||de==="("))return!1;let we=G[Ce],Oe=G[Ee];if(de==="{"&&we===":")return MT(G,Ce);let Ze=(we===de||we===",")&&(Oe===","||Oe===Xc[de]||de==="{"&&Oe===":");if(de!=="(")return Ze&&de!=="";return Ze&&(re&&RT.test(G.slice(Math.max(0,oe-20),oe))||(we===","||Oe===",")&&DT(G,oe))}function ET(G,U,j,K){let re=Math.max(0,U.tokenStart-80),oe=`${re===0?`
|
|
47
|
+
`:""}${G.slice(re,U.tokenStart)}`,de=wT.exec(oe)?.[1],Ce=G[j[U.tokenStart]??-1];if(de===void 0||Ce==="("||Ce==="[")return!1;let Ee=Yr(G,U.tokenEnd)+1;if(!/^\s*(?:[;\n]|$)/.test(G.slice(U.tokenEnd,Ee)))return!1;let we=U.tokenStart-oe.length+oe.lastIndexOf(de);return(K.get(de)??[]).every((Oe)=>Oe===we)}var RT=/(?:^|[^\w$.])(?:print|console\s*\.\s*log)\s*$/,_T=new Map([["print",/^\s*\(/],["console",/^\s*\.\s*[\w$]+\s*\(/]]),xT=/(?:^|[^\w$])(?:as|class|const|def|function|import|let|var)\s+(?:print|console)(?![\w$])/,wT=/[;\n{]\s*(?:(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*=\s*$/,AT=/(?:^|[^\w$.])(?:pathlib\s*\.\s*)?Path\s*$/,PT=/^\s*\.\s*write_(?:text|bytes)\s*\(/,TT=/(?:^|[^\w$.])open\s*$/,IT=/^[bt]*[awx][abtwx]*$/,kT=/(?:^|[^\w$])(?:writeFile|writeFileSync|appendFile|appendFileSync|Bun\s*\.\s*write)\s*$/;function OT(G,U,j){let K=j[U.tokenStart]??-1;if(G.masked[K]!=="(")return!1;let re=Io(G.masked,U.tokenStart),oe=Yr(G.masked,U.tokenEnd),de=G.masked[oe],Ce=G.masked.slice(Math.max(0,K-40),K);if(AT.test(Ce))return(re===K||G.masked[re]===",")&&(de===","||de===")")&&!G.literals.some((we)=>we.tokenStart>K&&we.tokenStart<U.tokenStart)&&PT.test(G.masked.slice(gs(G.masked,K+1)+1));if(re!==K||de!==",")return!1;if(kT.test(Ce))return!0;if(!TT.test(Ce))return!1;let Ee=G.literals.find((we)=>/^,\s*(?:mode\s*=\s*)?$/.test(G.masked.slice(oe,we.tokenStart)));return Ee!==void 0&&IT.test(Ee.text)&&/^[,)]/.test(G.masked.slice(Yr(G.masked,Ee.tokenEnd)))}function MT(G,U){let j=Io(G,U),K=/[\w$]*$/.exec(G.slice(Math.max(0,j-63),j+1))?.[0]??"",re=G[Io(G,j+1-K.length)];return re==="{"||re===","}function DT(G,U){let j=Io(G,U),K=G.slice(Math.max(0,j-7),j+1);return!/[\w$)\]]$/.test(K)||fT.test(K)}function NT(G){let U=Zc(G);if(U==="python")return"python";if(U==="osascript")return"opaque";return U==="node"||U==="bun"||U==="deno"?"javascript":"simple"}var LT={python:"#",javascript:"/"};function WT(G,U){if(U==="opaque")return{kind:"unmaskable"};let j={masked:G.split(""),literals:[]};return rh(G,0,U,j,!1)===null?{kind:"unmaskable"}:{kind:"masked",masked:j.masked.join(""),literals:j.literals}}function rh(G,U,j,K,re){let oe=0;for(let de=U;de<G.length;de++){let Ce=G[de]??"";if(re&&Ce==="}"&&oe===0)return de;if(re&&Ce===LT[j])return null;if(Ce==="{")oe++;if(Ce==="}")oe--;if(j==="simple"&&(Ce==="`"||Ce==="%"||Ce==="<")){if(FP.test(G.slice(de)))return null}let Ee=Ce==="'"||Ce==='"'||j==="javascript"&&Ce==="`"?Ce:null;if(Ee===null)continue;if(Ee==="`"&&$T(G,de))return null;let we=j==="python"?FT(G,de):"",Oe=j==="python"&&G.startsWith(Ee.repeat(3),de)?Ee.repeat(3):Ee,Ze=de+Oe.length,Ke=Ee==="`"||/[fF]/.test(we),Ye=de-we.length,Xe=Ke?GT(G,Ye,Ze,Oe,j,K):zT(G,Ze,Oe);if(Xe===null)return null;if(!Ke){let Je=G.slice(Ze,Xe);if(j==="simple"&&Ee==='"'&&zP.test(Je))return null;K.literals.push({start:Ze,text:Je,tokenStart:Ye,tokenEnd:Xe+Oe.length}),K.masked.fill(" ",Ze,Xe)}K.masked.fill(" ",de,Ze),K.masked.fill(" ",Xe,Xe+Oe.length),de=Xe+Oe.length-1}return re?null:G.length}function GT(G,U,j,K,re,oe){let de=re==="python"?"{":"${",Ce=K==="`"||K.length===3,Ee="";for(let we=j;we<G.length;we++){let Oe=G[we]??"";if(G.startsWith(K,we))return oe.literals.push({start:j,text:Ee,tokenStart:U,tokenEnd:we+K.length}),we;if(!Ce&&(Oe===`
|
|
48
|
+
`||Oe==="\r"))return null;let Ze=re==="python"&&(Oe==="{"||Oe==="}")&&G[we+1]===Oe;if(!Ze&&G.startsWith(de,we)){let Xe=rh(G,we+de.length,re,oe,!0);if(Xe===null)return null;Ee+=`${de}}`,oe.masked.fill(" ",we,we+de.length),oe.masked[Xe]=" ",we=Xe;continue}let Ye=Oe==="\\"&&!(re==="python"&&G[we+1]==="{")||Ze?2:1;Ee+=G.slice(we,we+Ye),oe.masked.fill(" ",we,we+Ye),we+=Ye-1}return null}function FT(G,U){return GP.exec(G.slice(Math.max(0,U-3),U))?.[1]??""}function zT(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===`
|
|
49
|
+
`||oe==="\r"))return null;if(G.startsWith(j,re))return re}return null}function $T(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 BT(G){for(let U of G.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let j=U[0],K=U.index;if(vP.has(j.toLowerCase()))return!0;let re=oh(j);if(!re.some((oe)=>EP.has(oe)))continue;if(re.length>1)return!0;if(G[Io(G,K)]===".")return!0;if(G[Yr(G,K+j.length)]==="(")return!0}return!1}function oh(G){return G.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((U)=>U.toLowerCase())}function Io(G,U){for(let j=U-1;j>=0;j--)if(!/\s/.test(G[j]??""))return j;return-1}function Yr(G,U){for(let j=U;j<G.length;j++)if(!/\s/.test(G[j]??""))return j;return G.length}function UT(G,U,j,K,re,oe){return qT(G).flatMap((de)=>{let Ce=U.getShellSyntax(de);if(Ce.status==="invalid")return[];return[...ko(Ce,U,{...j,displayOperandsAreCapturedOutput:!0},K,re,oe),...HT(Ce,K)?jT(Ce,K).map((Ee)=>({target:Ee,cwd:re})):[]]})}function HT(G,U){let j=_s(G);for(let K=0;K<j.length;K++){let re=j[K];if(re?.kind!=="word"||gn(or(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 Ce=or(de.text,U);if(Ce==="--decode"||!Ce.startsWith("--")&&Ce.startsWith("-")&&/[dD]/.test(Ce))return!0}}return!1}function jT(G,U){return _s(G).flatMap((j)=>j.kind==="word"?[or(j.text,U)]:j.kind==="redirection"&&j.target?[or(j.target,U)]:[]).flatMap(Jc)}function Jc(G){let U=KT(G);if(U===null)return[];let j=Buffer.from(U,"base64").toString("utf8");if(j===""||VT(j))return[];return Buffer.from(j,"utf8").toString("base64").replace(/=+$/g,"")===U.replace(/=+$/g,"")?[j]:[]}function VT(G){return Array.from(G).some((U)=>{let j=U.charCodeAt(0);return j<32||j===127})}function KT(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 qT(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(Ho(re,j))continue;if(ih(G,K,j)){let oe=YT(G,K+1);if(oe!==null)U.push(oe.body),K=oe.endIndex;continue}if(!j.inSingle&&re==="`"){let oe=ZT(G,K);if(oe!==null)U.push(oe.body),K=oe.endIndex}}return U}function YT(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(Ho(oe,j))continue;if(ih(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 ZT(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 ih(G,U,j){return!j.inSingle&&G[U]==="$"&&G[U+1]==="("&&G[U+2]!=="("}function XT(G){let U=[],j=[],K=!1,re=!1,oe=!1;for(let Ee=0;Ee<G.length;Ee++){let we=G[Ee];if(we===void 0)break;if(!oe&&we==="--"){oe=!0;continue}if(oe){j.push(we);continue}let Oe=/^--([^=]+)(?:=(.*))?$/.exec(we);if(Oe!==null){let Ze=Oe[1]??"",Ke=Oe[2];if(Ze===MP)re=!0;if(NP.has(Ze))K=!0;if(Ke!==void 0){if(Ze===Mg)U.push(Ke);continue}if(WP.has(Ze)){let Ye=G[Ee+1];if(Ze===Mg&&Ye!==void 0)U.push(Ye);Ee++}continue}if(we.startsWith("-")&&we.length>1){let Ze=we.slice(1),Ke="",Ye="";for(let Je=0;Je<Ze.length;Je++){let Qe=Ze[Je]??"";if(DP.has(Qe))K=!0;if(LP.has(Qe)){Ke=Qe,Ye=Ze.slice(Je+1);break}}if(Ke==="")continue;if(Ye.length>0){if(Ke===Og)U.push(Ye);continue}let Xe=G[Ee+1];if(Ke===Og&&Xe!==void 0)U.push(Xe);Ee++;continue}j.push(we)}let Ce=!K&&!re?j.slice(1):j;return[...U,...Ce]}function Xn(G){let U=G.findIndex((j)=>!sh(j)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(j));return U===-1?[]:G.slice(U)}function sh(G){return G==="env"||G==="command"||G==="builtin"||G==="sudo"}var JT=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),QT=".env.",eI=new Set([".env.example",".env.sample",".env.template",".env.tpl",".env.defaults"]),tI=[".env.example.",".env.sample."];function nI(G){let U;try{U=new URL(G.trim())}catch{return!1}return U.protocol!=="file:"&&U.host!==""}function rI(G){return G.length>0&&!/\s/.test(G)}function da(G,U,j,K){let re=ah(G,U,j,K);return re!==""&&j.paths.entryKind(re)!=="missing"}function ah(G,U,j,K){try{return Pi(G,U,j,K)}catch(re){if(re instanceof s)throw re;return""}}var oI=/[?&][^?&=/]+=/,iI=new Set(["node_modules","__pycache__"]),sI=[["vendor","bundle"],["vendor","cache"]];function aI(G,U,j,K,re){if(nI(G))return null;let oe=En(G,U,K,re);if(!oe)return null;let de=jt(oe.split("/").pop()??""),Ce=jt(oe),Ee=()=>rI(de)||da(G,U,K,re),we=jt(fI(G,U,K,re));for(let Ke of Ka){let Ye=`~/${Ke.suffixParts.join("/")}`;if((Bg(Ce,Ye)||Bg(we,Ye))&&cr(Ke.id,j))return Ke.id}if(eI.has(de)||tI.some((Ke)=>de.startsWith(Ke)))return null;let Oe=lI(oe,U,j,K,re);if(Oe)return Oe;if(JT.has(de))return null;for(let Ke of Va)if(de===Ke.basename&&cr(Ke.id,j))return Ke.id;if(de.startsWith(QT)&&cr(ji.id,j)&&Ee())return ji.id;for(let Ke of qa)if(de.length>Ke.prefix.length&&de.startsWith(Ke.prefix)){let Ye=de.slice(Ke.prefix.length)[0];if((Ye==="-"||Ye==="_")&&cr(Ke.id,j)&&Ee())return Ke.id}for(let Ke of Ya)if(de.length>Ke.prefix.length&&de.startsWith(Ke.prefix)){if(de.slice(Ke.prefix.length)===Ke.suffix&&cr(Ke.id,j))return Ke.id}if(uI(Ce))return null;if(!de.includes(".")&&jo.pattern.test(de)&&cr(jo.id,j))return jo.id;if(oI.test(G)&&!da(G,U,K,re))return null;let Ze=mI(de,j);if(Ze)return Ze;return null}function lI(G,U,j,K,re){return Vi.find((oe)=>{if(!cr(oe.id,j))return!1;switch(oe.id){case"secret.cli.claude-code":return $t(G,Kt(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),[".credentials.json"]);case"secret.cli.claude-code.config":{let de=jt(G).split("/");return $t(G,Kt(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),["settings.json","settings.local.json"])||wi(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 $t(G,En("~/.gemini/config",U,K,re),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let de=Kt(K.env.get("CODEX_HOME"),"~/.codex",U,K,re);return $t(G,de,["auth.json",".credentials.json"])||To(G,de,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let de=Kt(K.env.get("CODEX_HOME"),"~/.codex",U,K,re),Ce=jt(G).split("/").at(-1)??"";return $t(G,de,["config.toml"])||Ce.endsWith(".config.toml")&&$t(G,de,[Ce])}case"secret.cli.gemini":return $t(G,nn(Kt(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=jt(G).split("/"),Ce=K.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),Ee=K.env.get("ProgramData")?[nn(Kt(K.env.get("ProgramData"),"",U,K,re),"gemini-cli")]:[];return $t(G,nn(Kt(K.env.get("GEMINI_CLI_HOME"),"~",U,K,re),".gemini"),["settings.json","google_accounts.json"])||de.at(-1)==="settings.json"&&de.at(-2)===".gemini"||(Ce?.trim()?wi(G,Ce,U,K,re):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...Ee].some((we)=>$t(G,En(we,U,K,re),["settings.json"]))}case"secret.cli.copilot-cli":{let de=Kt(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re);return $t(G,de,["config.json"])||To(G,de,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return $t(G,Kt(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re),["mcp-config.json"]);case"secret.cli.kimi-code":{let de=Kt(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),Ce=Kt(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re);return $t(G,de,["server.token"])||To(G,de,["credentials"])||To(G,Ce,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let de=["config.toml","mcp.json"],Ce=jt(G).split("/");return Ce.at(-1)==="mcp.json"&&Ce.at(-2)===".kimi-code"||$t(G,Kt(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),de)||$t(G,Kt(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re),[...de,"config.json","config.json.bak"])}case"secret.cli.opencode":{let de=nn(Kt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"opencode"),Ce=jt(G).split("/").at(-1)??"",Ee=K.env.get("OPENCODE_DB")?.trim(),we=Ee&&Ee!==":memory:"?[Ee,`${Ee}-wal`,`${Ee}-shm`]:[];return $t(G,de,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Ce)&&$t(G,de,[Ce])||we.some((Oe)=>wi(G,Oe,U,K,re))}case"secret.cli.opencode.config":{let de=nn(Kt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"opencode"),Ce=K.env.get("ProgramData")?[nn(Kt(K.env.get("ProgramData"),"",U,K,re),"opencode")]:[],Ee=["opencode.json","opencode.jsonc"],we=K.env.get("OPENCODE_CONFIG");return Ee.includes(jt(G).split("/").at(-1)??"")||$t(G,de,["config.json"])||(we?.trim()?wi(G,we,U,K,re):!1)||["/Library/Application Support/opencode","/etc/opencode",...Ce].some((Oe)=>$t(G,En(Oe,U,K,re),Ee))}case"secret.cli.pi":return $t(G,Kt(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["auth.json"]);case"secret.cli.pi.config":return $t(G,Kt(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["models.json"]);case"secret.cli.amp":{let de=En("~",U,K,re);return[nn(Kt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"amp"),nn(de,".local","share","amp")].some((Ee)=>$t(G,Ee,["secrets.json"]))||To(G,nn(de,".amp"),["oauth"])}case"secret.cli.amp.config":{let de=["settings.json","settings.jsonc"],Ce=[nn(Kt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"amp"),nn(En("~",U,K,re),".config","amp")],Ee=jt(G).split("/"),we=K.env.get("AMP_SETTINGS_FILE");return Ce.some((Oe)=>$t(G,Oe,de))||Ee.at(-2)===".amp"&&de.includes(Ee.at(-1)??"")||(we?.trim()?wi(G,we,U,K,re):!1)}case"secret.cli.cursor":{let de=nn(Kt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"cursor"),Ce=nn(Kt(K.env.get("CURSOR_DATA_DIR"),"~/.cursor",U,K,re),"projects");return $t(G,En("~/.cursor",U,K,re),["auth.json"])||$t(G,de,["auth.json"])||jt(G).split("/").at(-1)==="mcp-auth.json"&&Zr(jt(G),jt(Ce))}case"secret.cli.cursor.config":{let de=jt(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".cursor"}case"secret.cli.grok-build":return $t(G,Kt(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let de=jt(G).split("/");return de.at(-1)==="config.toml"&&de.at(-2)===".grok"||$t(G,Kt(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["config.toml","managed_config.toml","requirements.toml"])||$t(G,En("/etc/grok",U,K,re),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return $t(G,En("~/.factory",U,K,re),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let de=jt(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".factory"||$t(G,En("~/.factory",U,K,re),["settings.json","hooks.json"])}case"secret.cli.devin":return[Kt(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),En("~/.local/share",U,K,re)].some((de)=>$t(G,nn(de,"devin"),["credentials.toml"])||To(G,nn(de,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[Kt(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),En("~/.config",U,K,re)].some((de)=>$t(G,nn(de,"devin"),["config.json"]));default:return!1}})?.id??null}var $g=new WeakMap;function Kt(G,U,j,K,re){let oe=$g.get(re)??new Map;$g.set(re,oe);let de=`${j}\x00${G??""}\x00${U}`,Ce=oe.get(de);if(Ce!==void 0)return Ce;let Ee=En(G?.trim()?G:U,j,K,re);return oe.set(de,Ee),Ee}function $t(G,U,j){return j.some((K)=>lh(G,nn(U,K)))}function To(G,U,j){return j.some((K)=>Zr(jt(G),jt(nn(U,K))))}function wi(G,U,j,K,re){return lh(G,En(U,j,K,re))}function lh(G,U){return jt(G)===jt(U)}function nn(G,...U){return jn([G,...U].filter(Boolean).join("/"))}function cI(G,U,j,K,re,oe){if(j.length===0)return!1;let de=jt(Pi(G,U,re,oe));return j.some((Ce)=>Zr(de,jt(Pi(Ce,K,re,oe))))}function dI(G,U,j,K,re,oe){if(j.length===0)return!1;let de=jt(Pi(G,U,re,oe));if(!de)return!1;let Ce=re.env.get("HOME")??re.home,Ee=Ce?jn(zt(mn(Ce),re.paths,oe)):"",we=jt(Ee),Oe=re.env.get("CC_SAFETY_NET_HOME"),Ze=jt(Oe?jn(zt(ua(mn(Oe)),re.paths,oe)):Ee&&jn(zt(`${Ee}/.cc-safety-net`,re.paths,oe)));if(Ze&&Zr(de,Ze))return!1;return j.some((Ke)=>{let Ye=el(Ke);if(Ye&&Ug.basename(de)!==jt(Ye.name))return!1;let Xe=jt(Pi(Ye?.root??Ke,K,re,oe));if(!Xe)return!1;if(we&&(we===Xe||we.startsWith(Xe.endsWith("/")?Xe:`${Xe}/`)))return!1;return Zr(de,Xe)&&!(Ye&&de===Xe)})}function uI(G){let U=G.split("/");return U.some((j)=>iI.has(j))||sI.some(([j,K])=>U.some((re,oe)=>re===j&&U[oe+1]===K))}function mI(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 Za)if(K===re.extension&&cr(re.id,U))return re.id;for(let re of Xa)if(re.pattern.test(K)&&cr(re.id,U))return re.id;return null}function jt(G){return G.toLowerCase()}function cr(G,U){return!U?.disabledRules?.includes(G)}function En(G,U,j,K){let{home:re,normalized:oe}=Qc(G,j,K);if(!oe)return"";if(!re)return oe;let de=ed(oe,re),Ce=aa(de)?de:jn(ua(U,de)),Ee=jn(zt(Ce,j.paths,K));if(!Zr(Ee,re)){if(aa(de))return Ee;return Ee===Ce?oe:Ee}let we=Ee.slice(re.length);return we?`~${we}`:"~"}function Bg(G,U){return G===U||G.startsWith(`${U}/`)}function fI(G,U,j,K){let{home:re,normalized:oe}=Qc(G,j,K);if(!oe||!re)return"";let de=ed(oe,re),Ce=Ug.normalize(aa(de)?de:jn(ua(U,de))),Ee=jn(mn(j.env.get("HOME")??j.home)),we=(Ke)=>process.platform==="win32"?Ke.toLowerCase():Ke,Oe=[re,Ee].find((Ke)=>Ke!==""&&Zr(we(Ce),we(Ke)));if(Oe===void 0)return"";let Ze=Ce.slice(Oe.length);return Ze?`~${Ze}`:"~"}function Pi(G,U,j,K){let{home:re,normalized:oe}=Qc(G,j,K);if(!oe)return"";let de=re?ed(oe,re):oe;return jn(zt(aa(de)?de:ua(U,de),j.paths,K))}function Qc(G,U,j){let K=U.env.get("HOME")??U.home,re=K?jn(zt(mn(K),U.paths,j)):"",oe=jn(mn(pI(or(G,U))));return{home:re,normalized:oe}}function pI(G){if(!G.trim().toLowerCase().startsWith("file:"))return G;try{return pP(G)}catch{return G}}function ed(G,U){if(G==="~")return U;if(G.startsWith("~/"))return nn(U,G.slice(2));return G}function gI(G){if(process.platform==="win32")return!0;return fP.parse(G).root.length>1}function jn(G){let U=G.trim(),j=(U.includes("\\")&&gI(U)?U.replace(/\\/g,"/"):U).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(j==="/")return j;return j.replace(/\/+$/g,"")}function Zr(G,U){return G===U||G.startsWith(U.endsWith("/")?U:`${U}/`)}function gn(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}class f 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 hI={findPolicyMutation:Tg,findGitMetadataMutation:ef,resolveGitMetadata:SI,loadPolicySnapshot:R,findSensitiveTarget:qg,analyzeCommand:Eg,getModes:P},yI=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/,bI=["workdir","cwd","working_directory"];function q(G,U){let j={...hI,...U.dependencies},K=RI(G),re=()=>Er("config-load",K,()=>j.loadPolicySnapshot(U.environment,{...U.policyOptions,cwd:G.context.configCwd})),oe=G.route.kind==="unknown"&&K?re():void 0,de=oe?.policy.commandTools.find((kt)=>kt.name===G.toolName),Ce=de&&K?CI(G,K,de.cwd,U.environment.paths):G;if("decision"in Ce)return Ce;let Ee=Ce,we=Ee===G?{}:{promotedInvocation:Ee},Oe=Ti(Ee)?Ee.command:K,Ze=Er("policy-protection",Oe,()=>Zm(Ee)),Ke=Cn(Ze,"input-candidate"),Ye=Cn(Ze,"declared-command");if(Ti(Ee)&&Ee.command?.trim()&&Ye?.program.status==="limited")return{stage:"command-analysis",...we,decision:{kind:"deny",reason:Vn,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:Ee.command,segment:Ee.command}}};if(Ke?.program.status==="limited")return{stage:"command-validation",...we,decision:{kind:"deny",reason:vf,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let Xe=kn(),Je=Er("policy-protection",Oe,()=>j.resolveGitMetadata([Ee.context.executionCwd,Ee.context.configCwd],U.environment)),Qe=Er("policy-protection",Oe,()=>j.findPolicyMutation(Ze,U.environment,Xe));if(Qe){let kt=Oe??Qe.target;return{stage:"policy-protection",...we,decision:{kind:"deny",reason:qe,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:kt,segment:Qe.target}}}}let mt=Er("policy-protection",Oe,()=>xg(Ze,U.environment,Xe));if(mt){let kt=Oe??mt.target;return{stage:"policy-protection",...we,decision:{kind:"deny",reason:Ve,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:kt,segment:mt.target}}}}let Rt=Er("policy-protection",Oe,()=>j.findGitMetadataMutation(Ze,Je,U.environment,Xe));if(Rt){let kt=Oe??Rt.target;return{stage:"policy-protection",...we,decision:{kind:"deny",reason:v,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:kt,segment:Rt.target}}}}let pt=oe??re(),_t=pt.policy,It=j.getModes(_t,U.environment.env),Ot={level:It.effectiveLevel,...vI(pt),...we},Dt=_t.secretProtection.enabled===!1?null:Er("secret-protection",Oe,()=>j.findSensitiveTarget(Ze,_t.secretProtection,U.environment,Xe,{strict:Ti(Ee)||Ke?.program.dialect==="powershell"?It.strict:void 0}));if(Dt){let kt=Oe??Dt.target;return{stage:"secret-protection",...Ot,decision:{kind:"deny",reason:Hg,intent:"hard_stop",ruleId:Dt.ruleId,evidence:{command:kt,segment:Dt.target}}}}if(!Ti(Ee))return{stage:"non-command",...Ot,decision:{kind:"allow"}};if(!Ee.command||Ee.command.trim()==="")return{...ma("command-validation",Oe),...Ot};let ft=Er("command-analysis",Oe,()=>Rg(()=>j.analyzeCommand(Ee.command,{cwd:Ee.context.executionCwd,shell:Ee.route.shell,policySnapshot:pt,environment:U.environment,protectedGitMetadata:Je,effectiveCapabilities:It.capabilities,strict:It.strict,paranoidRm:It.paranoidRm,paranoidInterpreters:It.paranoidInterpreters,worktreeMode:It.worktreeMode,budget:Xe,...U.trace?{trace:U.trace}:{}},EI(Ze),Ze.store),Ee.command,U.trace));if(ft.decision){let kt=!It.strict&&(ft.decision.ruleId==="raw-text.dangerous-command"||ft.decision.reason===pi&&!yI.test(ft.decision.evidence?.segment??"")&&Dn(Ee.command)===null);return{stage:"command-analysis",...Ot,..."errorCode"in ft?{errorCode:ft.errorCode}:{},decision:kt?{...ft.decision,unverifiedByStandardMode:!0}:ft.decision}}return{stage:"command-analysis",...Ot,decision:{kind:"allow"}}}function CI(G,U,j,K){let re=[...new Set((j?[j]:bI).flatMap((Ee)=>{let we=Object.getOwnPropertyDescriptor(G.input,Ee);return we?[we.value]:[]}))],oe=re.filter((Ee)=>typeof Ee==="string"&&Ee.trim()!=="");if(re.length>1||oe.length!==re.length)return ma("command-validation",U);let de=oe[0],Ce=de===void 0?G.context.configCwd:Od(de,G.context.configCwd,K);if(!Ce){let Ee=_({directory:"requested",problem:"unusable",cwd:de??""});return{stage:"command-validation",decision:{kind:"deny",reason:Ee.reason,ruleId:Ee.ruleId,intent:Ee.intent,evidence:{command:U,segment:U}}}}return l(G.toolName,G.input,{kind:"command",shell:"auto"},{configCwd:G.context.configCwd,executionCwd:Ce},U)}function SI(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 vI(G){if(G.state==="ready")return{};return{configFallback:{reason:G.reason}}}function EI(G){return Cn(G,"declared-command")?.program}function RI(G){try{return ie(G.input)}catch(U){let j=Ti(G)?G.command:void 0;throw new f("policy-protection",ma("policy-protection",U instanceof m?void 0:j,U),U)}}function Er(G,U,j){try{return j()}catch(K){throw new f(G,ma(G,K instanceof m?void 0:U,K),K)}}function ma(G,U,j){let K=j instanceof s||j instanceof b;return{stage:G,decision:{kind:"deny",reason:K?ga:Do,ruleId:K?"analysis.limit":"analysis.failed-closed",intent:"stop_and_explain",...U?{evidence:{command:U,segment:U}}:{}}}}function Ti(G){return G.route.kind==="command"}
|
|
50
|
+
export{a,s,J,De,et,T,gt,tt,ke,N,_,Y,ht,c,n,nt,Re,P,S,pe,yt,m,Te,x,ie,fe,bt,rt,ot,l,Ne,o,w,i,se,r,g,me,H,xt,vt,p,ge,he,St,L,Z,ae,C,wt,I,h,_e,W,u,A,X,it,st,M,E,O,ye,be,Le,Ct,d,e,Me,Pe,Fe,xe,at,ct,ce,Ie,le,$e,Q,B,je,ve,z,lt,V,ee,te,ue,ut,dt,k,F,Ue,Ge,He,We,R,Be,Ae,ze,y,t,ne,Se,b,v,D,Et,Ve,qe,f,q};
|