cc-safety-net 2.6.11 → 2.6.13
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 +43 -44
- package/dist/api.js +1 -1
- package/dist/bin/hook.js +43 -44
- package/dist/chunks/{index-6hppa0dh.js → index-e25d8rb4.js} +2 -2
- package/dist/chunks/index-q29jqk43.js +2 -0
- package/dist/chunks/index-rdxjms22.js +49 -0
- package/dist/chunks/{index-21n2w3y1.js → index-ry0wwdk0.js} +2 -2
- package/dist/chunks/{index-5ht7pdm3.js → index-wkjncmhg.js} +2 -2
- package/dist/chunks/index-x95aj0ja.js +4 -0
- package/dist/chunks/index-z5fwe2yq.js +2 -0
- package/dist/cli.js +128 -167
- package/dist/deepseek-harness/index.js +1 -1
- package/dist/index.js +4 -4
- package/dist/openclaw/cc-safety-net/index.js +43 -44
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +2 -2
- package/package.json +2 -2
- package/dist/chunks/index-1wd9cpbg.js +0 -2
- package/dist/chunks/index-7h15fjs7.js +0 -4
- package/dist/chunks/index-babcfevy.js +0 -50
- package/dist/chunks/index-n6djve2j.js +0 -2
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
var va="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",qn="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",Go="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var ba={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."},Wo={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,...ba},processedCandidateBytes:{cap:4194304,...ba},pathEnvironmentExpansion:{cap:64,...ba},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,...Wo},trackedHeredocFiles:{cap:64,...Wo},controlFlowStates:{cap:64,...Wo},wrapperPeelIterations:{cap:20,...Wo},derivedCommandShape:Wo});class s extends Error{kind;name="AnalysisLimit";constructor(W){super(a[W].reason);this.kind=W}}function In(){let W=new Map;return{counters:W,resolvedPaths:new Map,charge(G,H=1){let J=(W.get(G)??0)+H;if(W.set(G,J),J>a[G].cap)throw new s(G)}}}var 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 Y(W){return Me(W.replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_DSN|CONNECTION_STRING)=("[^"]*"|'[^']*'|[^\s]+(?:\s+[A-Z_][A-Z0-9_]*=[^\s]+)*)/gi,"$1=<redacted>").replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_(?:URL|URI|CONNECTION_STRING))=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIALS)[A-Z0-9_]*)=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>"))}function Me(W){return Ch.reduce((G,H)=>G.replace(H,"<redacted>"),W.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi,"<redacted>").replace(/((?:(['"])(?:authorization|cookie|x-api-key|api-key)\2|(?:authorization|cookie|x-api-key|api-key))\s*:\s*)(['"])(?:\\[^\r\n]|(?!\3)[^\\\r\n])*\3/gi,"$1$3<redacted>$3").replace(/(['"]?\s*(?:authorization|cookie|x-api-key|api-key)\s*:(?!\s*(?:"<redacted>"|'<redacted>'))\s*)([^'"\r\n]+)(['"]?)/gi,"$1<redacted>$3").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s@/]+)@/gi,"$1<redacted>:<redacted>@").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+)@/gi,"$1<redacted>@").replace(/(^|[\s?&;|])((?:x-amz-signature|x-goog-signature|sig|signature)=)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^&#\s'"`;|<>()]*)/gi,"$1$2<redacted>").replace(/(^|\s)((?:-u|--user)(?:\s+|=))([^\s:]+):([^\s]+)/g,"$1$2<redacted>:<redacted>")).replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"<redacted>").replace(/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,"<redacted>")}function nt(W){return ld(W).reduceRight((G,H)=>`${G.slice(0,H.valueStart)}<redacted>${G.slice(H.valueEnd)}`,W)}function T(W){return Me(nt(W))}function bt(W){return ld(W).map((G)=>W.slice(G.valueStart,G.valueEnd))}function rt(W){return/[A-Za-z_][A-Za-z0-9_]*=/.test(W)}function ld(W){return[...W.matchAll(/[A-Za-z_][A-Za-z0-9_]*=/g)].flatMap((G)=>{let H=W[G.index-1];if(G.index>0&&H&&!/[\s"'([{]/.test(H))return[];let J=G.index+G[0].length;if(J>=W.length)return[];return[{valueStart:J,valueEnd:bh(W,J)}]})}function bh(W,G){if(W.startsWith("$(",G))return vh(W,G);let H=W[G];if(H==='"'||H==="'"){for(let oe=G+1;oe<W.length;oe++){if(H==='"'&&W[oe]==="\\"){oe++;continue}if(W[oe]===H)return oe+1}return W.length}let J=G;while(J<W.length&&!/\s/.test(W[J]??""))J++;return J}function vh(W,G){let H=0,J;for(let oe=G;oe<W.length;oe++){let ie=W[oe];if(J){if(J==='"'&&ie==="\\"){oe++;continue}if(ie===J)J=void 0;continue}if(ie==='"'||ie==="'"){J=ie;continue}if(ie==="$"&&W[oe+1]==="("){H++,oe++;continue}if(ie!==")")continue;if(H--,H===0)return oe+1}return W.length}var Eh={hard_stop:"Do not retry this operation or attempt any workaround (other tools, flags, or paths). Report the block to the user and continue with the rest of the task.",use_alternative:"Do not retry the blocked form. Continue the task using the safer alternative described above.",scope_down:"Retry with a narrower, explicit target as described above. Escalate to the user if the broad operation is truly required.",manual_only:"If this operation is truly needed, ask the user for explicit permission and have them run the command manually.",stop_and_explain:"Do not brute-force variants. Simplify or restructure the command so it can be analyzed, or report the block to the user."};function Rh(W){let G=W.maxLen??200,H=W.redact??((oe)=>oe),J=(oe)=>oe.length>G?`${oe.slice(0,G)}...`:oe;return[W.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${H(W.reason)}`,W.ruleId?`Rule: ${W.ruleId}`:void 0,W.toolName?`Tool: ${W.toolName}`:void 0,W.command?`Command: ${J(H(W.command))}`:void 0,W.segment&&W.segment!==W.command?`Segment: ${J(H(W.segment))}`:void 0,W.cwd?`Working directory: ${J(H(W.cwd))}`:void 0,W.configWarning?`Config warning: ${H(W.configWarning)}`:void 0,W.askUser?"Approve only if you expected this command.":Eh[W.intent??"manual_only"]].filter((oe)=>oe!==void 0).join(`
|
|
2
|
+
|
|
3
|
+
`)}function _e(W,G){if(W.decision.kind!=="deny")return;let H=G.includeEvidence?W.decision.evidence:void 0;return{reason:W.decision.reason,ruleId:W.decision.ruleId,intent:W.decision.intent,command:H?.command,segment:H?.segment,toolName:G.toolName,...W.configFallback?{configWarning:W.configFallback.reason}:{},...W.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function L(W={}){return{reason:Go,ruleId:"analysis.failed-closed",intent:"stop_and_explain",command:W.command,segment:W.segment??W.command,toolName:W.toolName}}var _h={session:{unusable:{reason:"CC Safety Net cannot check tool calls because the session's working directory or workspace root no longer exists, is inaccessible, is not a directory, or uses an unsupported path form. Ask the user to restart the session from an existing directory.",intent:"hard_stop",ruleId:"cwd.session-unusable"},"outside-workspace":{reason:"CC Safety Net cannot check tool calls because the session's working directory is outside its workspace roots. Ask the user to restart the session from a directory inside the workspace.",intent:"hard_stop",ruleId:"cwd.session-outside-workspace"}},requested:{unusable:{reason:"CC Safety Net could not use the requested working directory because it does not exist, is inaccessible, is not a directory, or uses an unsupported path form. Use an existing accessible working directory. If the requested directory is missing, create it from an accessible location before retrying the command.",intent:"use_alternative",ruleId:"cwd.requested-unusable"},"outside-workspace":{reason:"CC Safety Net could not use the requested working directory because it is outside the session's workspace. Use a working directory inside the workspace.",intent:"use_alternative",ruleId:"cwd.requested-outside-workspace"}}};function _(W,G={}){return{..._h[W.directory][W.problem],command:G.command,toolName:G.toolName,cwd:W.cwd}}function Z(W){return Rh({...W,redact:Y})}function xt(W){return Y(W instanceof Error?W.message:String(W))}import{lstatSync as iy,realpathSync as sy,statSync as ay}from"node:fs";import{homedir as ly,tmpdir as cy}from"node:os";import{statSync as ny}from"node:fs";import{join as ry}from"node:path";import{basename as ud,dirname as xh,isAbsolute as wh,join as Ah,normalize as Ph,resolve as cd}from"node:path";var Th=256,Ni=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 pn(W,G=process.platform){if(G!=="win32")return W;return W.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function nr(W,G=process.platform){if(G!=="win32")return!1;return(W[0]==="/"||W[0]==="\\")&&(W[1]==="/"||W[1]==="\\")}function xa(W,G){return Ea(W,0,G)}function Ea(W,G,H){let J="",oe=0,ie=0;while(oe<W.length){if(W[oe]!=="$"){J+=W[oe],oe++;continue}if(W[oe+1]==="{"){let Re=Ra(W,oe+2),Te=Ih(W,oe,G);if(Te===null){if(Ni.has(Re))throw new s("pathEnvironmentExpansion");if(ie++,ie>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");J+="${",oe+=2;continue}let ke=W.slice(oe,Te+1);J+=kh(ke,G,H),oe=Te+1;continue}let fe=Ra(W,oe+1);if(!fe){J+="$",oe++;continue}J+=_a(fe,H)??`$${fe}`,oe+=fe.length+1}return J}function Ih(W,G,H){let J=1;for(let oe=G+2;oe<W.length;oe++){if(W[oe]==="\\"){oe++;continue}if(W[oe]==="$"&&W[oe+1]==="{"){if(J++,H+J>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");oe++;continue}if(W[oe]!=="}")continue;if(J--,J===0)return oe}return null}function kh(W,G,H){let J=W.slice(2,-1),oe=Ra(J,0);if(!oe)return W;let ie=J.slice(oe.length);if(!ie)return _a(oe,H)??W;let fe=[":-",":+",":=",":?","-","+","=","?"].find((ke)=>ie.startsWith(ke));if(!fe){if(Ni.has(oe))throw new s("pathEnvironmentExpansion");return W}if(!Ni.has(oe))return W;if(fe.endsWith("="))throw new s("pathEnvironmentExpansion");let Re=_a(oe,H),Te=fe.startsWith(":")?Re!==null&&Re!=="":Re!==null;if(fe.endsWith("?")&&!Te)throw new s("pathEnvironmentExpansion");if(fe.endsWith("-")||fe.endsWith("?"))return Te?Re??"":Ea(ie.slice(fe.length),G+1,H);return Te?Ea(ie.slice(fe.length),G+1,H):""}function Ra(W,G){if(!/[A-Za-z_]/.test(W[G]??""))return"";let H=G+1;while(/[A-Za-z0-9_]/.test(W[H]??""))H++;return W.slice(G,H)}function _a(W,G){if(!Ni.has(W))return null;if(W==="HOME")return G.env.get("HOME")??G.home;return G.env.get(W)??null}function Bt(W,G,H){if(!W)return W;let J=H.resolvedPaths.get(W);if(J!==void 0)return J;let oe=[],ie=W;while(!0){md(H,ie);let fe=G.realpath(ie);if(fe!==null)return dd(H,W,fe,oe);let Re=xh(ie);if(Re===ie||oe.length>=Th)return dd(H,W,ie,oe);oe.push(ud(ie)),ie=Re}}function dd(W,G,H,J){let oe=J.length===0?H:Ah(H,...J.reverse());return W.resolvedPaths.set(G,oe),oe}function Oh(W,G,H){let J=H.resolvedPaths.get(W);if(J!==void 0)return J;md(H,W);let oe=G.realpath(W);if(oe!==null)H.resolvedPaths.set(W,oe);return oe}function md(W,G){W.charge("realpathAttempts"),W.charge("processedCandidateBytes",Buffer.byteLength(G))}function gn(W,G,H,J){let oe=pd(W,G,H);if(!oe)return"";return Bt(oe,H.paths,J).replace(/\\/g,"/")}function fd(W,G,H,J,oe){let ie=pd(W,G,H);if(!ie)return null;if(oe(ud(ie)))return Bt(ie,H.paths,J).replace(/\\/g,"/");let fe=Oh(ie,H.paths,J);return fe===null?null:fe.replace(/\\/g,"/")}function pd(W,G,H){let J=H.home,oe=xa(W.trim(),H).replace(/\\/g,"/");if(!oe)return"";let ie=oe==="~"?J:oe.startsWith("~/")?cd(J,oe.slice(2)):oe,fe=pn(ie);return Ph(wh(fe)?fe:cd(G,fe))}import{spawnSync as Mh}from"node:child_process";import{accessSync as gd,constants as hd,existsSync as Fo,lstatSync as Dh,opendirSync as Nh,readFileSync as zo,realpathSync as ro,statSync as oo}from"node:fs";import{dirname as Cd,isAbsolute as wa,join as kn,resolve as Li}from"node:path";var Lh=["/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 bd(W,G=Jh(),H=Wh){let J=Gh(W),oe=J===null?null:Fh(J);if(J===null||oe===null)return null;let ie=Zh(J,oe,G,H);return ie===null?null:{recursiveSubmodules:ie}}function Gh(W){try{let G=ro(Li(W));return oo(G).isDirectory()?G:null}catch{return null}}function Fh(W){let G=Yh(W);if(!G)return null;try{let H=Dh(G);if(H.isSymbolicLink()||!H.isFile())return null;let J=Aa(G);if(!J?.commonDir)return null;if(!Bh(J.gitDir,G))return null;return Rd(J.gitDir,J.commonDir)?null:{gitDir:J.gitDir,commonDir:J.commonDir}}catch{return null}}function Aa(W){try{let G=zh(W);if(!G)return null;let H=ro(wa(G)?G:Li(Cd(W),G));if(!oo(H).isDirectory())return null;return{gitDir:H,commonDir:$h(H)}}catch{return null}}function zh(W){let G=zo(W,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!G.startsWith("gitdir:"))return null;return G.slice(7).trim()||null}function $h(W){try{let G=zo(kn(W,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!G)return null;let H=ro(wa(G)?G:Li(W,G));return oo(H).isDirectory()?H:null}catch{return null}}function Bh(W,G){let H=Uh(W);return H===null?!1:Hh(W,H,G)}function Uh(W){let G=kn(W,"gitdir");if(!Fo(G))return null;let H=zo(G,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return H===""?null:H}function Hh(W,G,H){try{return jh(wa(G)?G:Li(W,G),H)}catch{return!1}}function jh(W,G){try{let H=oo(W),J=oo(G);if(H.ino!==0&&J.ino!==0&&H.dev===J.dev&&H.ino===J.ino)return!0}catch{}return yd(ro.native(W))===yd(ro.native(G))}function yd(W){let G=W.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),H=G.length>1&&G.endsWith("/")?G.slice(0,-1):G;return process.platform==="win32"?H.toLowerCase():H}function vd(W){try{return gd(kn(W,"objects"),hd.X_OK),gd(kn(W,"refs"),hd.X_OK),/^(?:ref:[\t\n\r ]*refs\/|[0-9a-fA-F]{40})/.test(_d(kn(W,"HEAD")))}catch{return!1}}function Ed(W){return Fo(kn(W,"commondir"))||Rd(W,W)}function Rd(W,G){return[kn(G,"config"),kn(W,"config.worktree")].some(Vh)||qh(W)}var Sd=1048576;function _d(W){let G=oo(W);if(!G.isFile()||G.size>Sd)throw Error(`${W} is not a regular file within ${Sd} bytes`);return zo(W,"utf-8")}function Vh(W){try{return/(?:^|[\s\]])worktree\s*=/i.test(_d(W))}catch(G){return G.code!=="ENOENT"}}var Kh=1e4;function qh(W){let G=[W],H=0;try{while(G.length>0){let J=G.pop(),oe=Nh(J);try{for(let ie=oe.readSync();ie!==null;ie=oe.readSync()){if(H++,ie.isSymbolicLink()||ie.isFIFO()||H>Kh)return!0;let fe=J===W&&ie.name==="objects";if(ie.isDirectory()&&!fe)G.push(kn(J,ie.name))}}finally{oe.closeSync()}}return!1}catch(J){return J.code!=="ENOENT"}}function Yh(W){try{return Pa(ro(W))}catch{return null}}function Pa(W){let G=W;while(!0){let H=kn(G,".git");if(Fo(H))return H;let J=Cd(G);if(J===G)return null;G=J}}function Zh(W,G,H,J){if(Xh(G))return!0;if(H===null)return!0;let oe=Mh(H,["config","--get","submodule.recurse"],{cwd:W,encoding:"utf8",env:Qh(process.env),stdio:["ignore","pipe","ignore"],timeout:J});if(oe.error!==void 0||oe.status!==0&&oe.status!==1)return null;return oe.status===0&&xd(oe.stdout.trim())}function Xh(W){return[kn(W.commonDir,"config"),kn(W.gitDir,"config.worktree")].filter((G)=>Fo(G)).some((G)=>ey(G))}function Jh(){return Lh.find((W)=>Fo(W))??null}function $o(W){return W==="GIT_CONFIG_COUNT"||W==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(W)}function Qh(W){return Object.fromEntries(Object.entries(W).filter(([G])=>!$o(G)))}function ey(W){let G;try{G=zo(W,"utf-8")}catch{return!0}let H="",J=!1;for(let oe of G.split(/\r?\n/)){let ie=oe.trim();if(ie===""||ie.startsWith("#")||ie.startsWith(";"))continue;let fe=ie.match(/^\[([^\]]+)\]$/);if(fe){H=fe[1]?.trim().toLowerCase()??"";continue}let Re=ie.indexOf("="),Te=(Re===-1?ie:ie.slice(0,Re)).trim().toLowerCase(),ke=Re===-1?"true":ie.slice(Re+1).trim();if(ty(H)&&Te==="path")return!0;if(H==="submodule"&&Te==="recurse")J=xd(ke)}return J}function ty(W){return W==="include"||W.startsWith("includeif ")}function xd(W){let G=W.toLowerCase();return G!=="false"&&G!=="no"&&G!=="off"&&G!=="0"}function wd(W,G){if(W==="")return null;let H=In(),J=Pa(gn(W,W,G,H)),oe=J?oy(J,W,G,H):null;if(!oe)return null;return Object.freeze({entries:Object.freeze([oe.entry]),markerFiles:Object.freeze(oe.markerFile?[oe.markerFile]:[]),directories:Object.freeze(oe.directories),hooksDirectories:Object.freeze(oe.hooksDirectories)})}function oy(W,G,H,J){try{let oe=gn(W,G,H,J),ie=ny(W),fe=ie.isFile()?oe:null,Re=ie.isFile()?Aa(W):null,Te=(ie.isDirectory()?[oe]:[Re?.gitDir,Re?.commonDir]).flatMap((Le)=>Le?[io(gn(Le,G,H,J))]:[]),ke=[...new Set(ie.isDirectory()?[io(W.replace(/\\/g,"/")),...Te]:Te)];return{entry:io(oe),markerFile:fe?io(fe):null,directories:ke,hooksDirectories:[...new Set(ke.flatMap((Le)=>{let Xe=io(ry(Le,"hooks").replace(/\\/g,"/"));return[Xe,io(gn(Xe,G,H,J))]}))]}}catch{return null}}function io(W){return process.platform==="win32"?W.toLowerCase():W}var dy={realpath:(W)=>{try{return sy(W)}catch{return null}},entryKind:(W)=>{try{let G=iy(W,{throwIfNoEntry:!1});if(!G)return"missing";return G.isSymbolicLink()?"symlink":"present"}catch(G){if(G.code==="ENAMETOOLONG")return"missing";throw G}},isDirectory:(W)=>{try{return ay(W).isDirectory()}catch{return!1}}};function c(){return uy({env:new Map(Object.entries(process.env).flatMap(([W,G])=>G===void 0?[]:[[W,G]])),home:pn(process.env.HOME||ly()),tmpdir:cy(),paths:dy})}function uy(W,G={}){let H=new Map,J=new Map,oe=new Map,ie={...W,gitMetadata:(fe)=>Ta(H,fe,()=>wd(fe,ie)),worktreeFacts:(fe)=>Ta(J,fe,()=>bd(fe)),isGitDirectory:vd,gitDirectoryRedirects:(fe)=>Ta(oe,fe,()=>Ed(fe)),...G};return ie}function Ta(W,G,H){let J=W.get(G);if(J!==void 0)return J;let oe=H();return W.set(G,oe),oe}import{accessSync as Dy,constants as $d,statSync as Ny}from"node:fs";import{isAbsolute as Ma,relative as Ly,resolve as Bd,sep as Wy}from"node:path";import{types as my}from"node:util";var fy=new Set(["applypatch","patch"]),py=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),gy=new Set(["grep","grepsearch","rg"]),hy=new Set(["find","findbyname","glob"]),yy=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),Sy=new Set(["command","diff","input","patch","patchtext"]),Ad=new TextEncoder,Cy=new TextDecoder,by=/\s/,vy=64;class m extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var Bo=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Ie(W){return W.replace(/[-_\s]/g,"").toLowerCase()}function Gi(W){return yy.has(Ie(W))}function x(W){let G=Ie(W);if(fy.has(G))return"patch";if(gy.has(G))return"grep";if(hy.has(G))return"glob";if(py.has(G))return"path";return"unknown"}function se(W){if(!W||typeof W!=="object")return;Gd(W);let G=Object.getOwnPropertyDescriptor(W,"command");if(!G){if("command"in W)Yn();return}if(G.get||G.set)Yn();let H=G.value;return typeof H==="string"&&H!==""?H:void 0}function Od(W,G){return Md(W,G,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Md(W,G,H,J,oe){let ie=Wd(W,J,oe);if(typeof W==="string")return H?[W]:[];if(!ie)return[];let fe=ie.entries.flatMap(([Re,Te])=>Md(Te,G,ie.array?H:G.has(Dd(Re)),J,oe+1));return J.ancestors.delete(ie.object),fe}function Dd(W){return W.replace(/-/g,"_").toLowerCase()}function Nd(W){return Ld(W,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Ry)}function Ld(W,G,H,J){let oe=Wd(W,H,J);if(typeof W==="string")return G?[W]:[];if(!oe)return[];let ie=oe.entries.flatMap(([fe,Re])=>Ld(Re,oe.array?G:Sy.has(Dd(fe)),H,J+1));return H.ancestors.delete(oe.object),ie}function Ey(W,G,H){if(G.nodes++,W!==null&&typeof W==="object"&&H>Bo.maxDepth||G.nodes>Bo.maxNodes)Yn();if(typeof W!=="string")return;let J=Buffer.byteLength(W);if(G.stringBytes+=J,J>Bo.maxStringBytes||G.stringBytes>Bo.maxAggregateStringBytes)Yn()}function Wd(W,G,H){if(Ey(W,G,H),!W||typeof W!=="object")return null;let J=Gd(W);if(G.ancestors.has(W))Yn();let oe=Reflect.ownKeys(W);if(G.keys+=oe.length,G.keys>Bo.maxKeys)Yn();let ie=oe.flatMap((fe)=>{let Re=Object.getOwnPropertyDescriptor(W,fe);if(!Re||Re.get||Re.set)Yn();return typeof fe==="string"&&Re.enumerable?[[fe,Re.value]]:[]});return G.ancestors.add(W),{object:W,array:J,entries:ie}}function Gd(W){if(my.isProxy(W))Yn();let G=Array.isArray(W),H=Object.getPrototypeOf(W);if(G&&H!==Array.prototype||!G&&H!==Object.prototype&&H!==null)Yn();return G}function Yn(){throw new m}function Ry(W){let G=[],H=W.split(/\r?\n/),J=!1,oe=!1,ie=null,fe=null,Re=()=>{oe=!1,ie=null,fe=null};for(let Te=0;Te<H.length;Te++){let ke=H[Te]??"";if(ke==="*** Begin Patch"){J=!0,Re();continue}if(ke==="*** End Patch"){J=!1,Re();continue}if(ke.startsWith("@@")){let Le=_y(ke);if(oe=!0,ie=Le?.oldLines??null,fe=Le?.newLines??null,ie===0&&fe===0)Re();continue}if(oe&&ie!==null&&fe!==null){let Le=ke.startsWith(" ")||ke.startsWith("-")?1:0,Xe=ke.startsWith(" ")||ke.startsWith("+")?1:0;if(ie=Math.max(0,ie-Le),fe=Math.max(0,fe-Xe),ie===0&&fe===0)Re();continue}if(ke.startsWith("*** ")){Re(),G.push(...Ia(ke));continue}if(oe)continue;if(ke.startsWith("diff --git ")){G.push(...Ia(ke));continue}if(ke.startsWith("--- ")){let Le=H[Te+1]??"";if(!Le.startsWith("+++ "))continue;G.push(...Oa(Wi(ke.slice(4),!0),Wi(Le.slice(4),!0))),Te++;continue}if(!J)G.push(...Ia(ke))}return G}function _y(W){let G=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(W);if(!G)return null;return{oldLines:Number(G[1]??1),newLines:Number(G[2]??1)}}function Ia(W){let G=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(W);if(G?.[1])return kd(G[1]);let H=/^\*\*\* Move to: (.+)$/.exec(W);if(H?.[1])return kd(H[1]);if(W.startsWith("diff --git "))return xy(W.slice(11));let J=/^--- (.+)$/.exec(W);if(J?.[1])return Id(J[1]);let oe=/^\+\+\+ (.+)$/.exec(W);if(oe?.[1])return Id(oe[1]);let ie=/^(?:rename|copy) (?:from|to) (.+)$/.exec(W);if(ie?.[1])return Oy(ie[1]);return[]}function xy(W){let G=wy(W);if(G.length===2&&G[0]&&G[1])return Oa(G[0],G[1]);let H=Ay(W);return H?Oa(W.slice(H.oldStart,H.oldEnd),W.slice(H.newStart,H.newEnd)):[]}function wy(W){let G=[],H=0;while(H<W.length&&G.length<2){while(Ir(W[H]))H++;if(H>=W.length)break;let J=W[H]==='"'||W[H]==="'"?W[H]:void 0;if(!J){let ie=H;while(H<W.length&&!Ir(W[H]))H++;G.push(W.slice(ie,H));continue}let oe=Fd(W,H,J);if(!oe)return[];G.push(oe.value),H=oe.end}while(Ir(W[H]))H++;return H===W.length?G:[]}function Ay(W){let G=0;while(G<W.length&&Ir(W[G]))G++;let H=W.length;while(H>G&&Ir(W[H-1]))H--;let J=0,oe=G;while(oe<H){if(!Ir(W[oe])){oe++;continue}let ie=oe;while(oe<H&&Ir(W[oe]))oe++;if(ie===G||oe===H)continue;if(J++,J>vy)Yn();if(Py(W,G,ie,oe,H))return{oldStart:G,oldEnd:ie,newStart:oe,newEnd:H}}return null}function Py(W,G,H,J,oe){if(ka(W,G,H,J,oe))return!0;let ie=Pd(W,"/",G,H),fe=Pd(W,"/",J,oe);if(ie<=G||fe<=J)return!1;if(ka(W,G,ie,J,fe))return!1;return ka(W,ie+1,H,fe+1,oe)}function ka(W,G,H,J,oe){if(H-G!==oe-J)return!1;for(let ie=0;ie<H-G;ie++)if(W[G+ie]!==W[J+ie])return!1;return!0}function Pd(W,G,H,J){for(let oe=H;oe<J;oe++)if(W[oe]===G)return oe;return-1}function Ir(W){return W!==void 0&&by.test(W)}function Fd(W,G,H){let J=[],oe=G+1;while(oe<W.length){let ie=String.fromCodePoint(W.codePointAt(oe)??0);if(ie===H)return{value:Cy.decode(Uint8Array.from(J)),end:oe+1};if(ie!=="\\"||H==="'"){J.push(...Ad.encode(ie)),oe+=ie.length;continue}let fe=W.slice(oe+1),Re=/^[0-7]{1,3}/.exec(fe)?.[0];if(Re){J.push(Number.parseInt(Re,8)),oe+=Re.length+1;continue}J.push(...Ad.encode(Ty(fe[0]??""))),oe+=2}return null}function Ty(W){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
4
|
+
`,r:"\r",t:"\t",v:"\v"}[W]??W}function Iy(W){return Uo(My(W))}function Oa(W,G){if(W==="/dev/null")return Td(G);if(G==="/dev/null")return Td(W);if(W.startsWith("a/")&&G.startsWith("b/"))return[W.slice(2),G.slice(2)].flatMap(Uo);let H=ky(W,G)??(W===G?zd(W):null);return[W,G,...H?[H]:[]].flatMap(Uo)}function Td(W){let G=zd(W);return[W,...G?[G]:[]].flatMap(Uo)}function zd(W){let G=W.indexOf("/");return G>0&&G<W.length-1?W.slice(G+1):null}function ky(W,G){let H=W.indexOf("/"),J=G.indexOf("/");if(H<1||J<1)return null;if(W.slice(0,H)===G.slice(0,J))return null;let oe=W.slice(H+1);return oe===G.slice(J+1)?oe:null}function Id(W){return Iy(Wi(W,!0))}function Oy(W){return Uo(Wi(W,!1))}function Wi(W,G){let H=W.trim(),J=H[0]==='"'||H[0]==="'"?H[0]:void 0;if(J){let oe=Fd(H,0,J);if(oe&&(G||H.slice(oe.end).trim()===""))return oe.value}return G?H.split("\t",1)[0]?.trim()??"":H}function My(W){return W.startsWith("a/")||W.startsWith("b/")?W.slice(2):W}function Uo(W){return W===""||W==="/dev/null"?[]:[W]}function kd(W){let G=W.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return G===""||G==="/dev/null"?[]:[G]}function ge(W){try{if(!Ny(W).isDirectory())return!1;return Dy(W,$d.R_OK|$d.X_OK),!0}catch{return!1}}function St(W,G,H){if(nr(W))return;let J=G.flatMap((ie)=>Fi(ie,H));if(!J[0])return;let oe=Fi(Ma(W)?W:Bd(J[0],W),H)[0];if(!oe)return;return J.some((ie)=>Gy(oe,ie))?oe:void 0}function Ud(W,G,H){if(nr(W))return;return Fi(Ma(W)?W:Bd(G,W),H)[0]}function it(W,G){return W.flatMap((H)=>Fi(H,G))[0]}function Fi(W,G){let H=G.realpath(W);if(H===null)return[];return G.isDirectory(H)?[H]:[]}function Gy(W,G){let H=Ly(G,W);return H===""||H!==".."&&!H.startsWith(`..${Wy}`)&&!Ma(H)}var Fy=8388608;async function st(W){let G=[],H=0;for await(let J of W){let oe=typeof J==="string"?Buffer.from(J,"utf-8"):Buffer.from(J.buffer,J.byteOffset,J.byteLength);if(H+=oe.byteLength,H>Fy)throw zy(W),Error("hook input byte limit exceeded");G.push(oe)}return Buffer.concat(G,H).toString("utf-8")}function zy(W){let G=W.destroy??W.cancel;if(!G)return;try{Promise.resolve(G.call(W)).catch(()=>{})}catch{}}function l(W,G,H,J,oe){if(H.kind!=="command")return{toolName:W,input:G,route:H,context:J};return{toolName:W,input:G,route:H,context:J,command:oe}}var so=["fail_closed","paranoid_rm","paranoid_interpreters"],zi={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"}},$i=["standard","strict","paranoid"];function Hd(W,G){if(!G)return W;return $i.indexOf(G)>$i.indexOf(W)?G:W}function jd(W){let G=me(n.level,W);return $i.find((H)=>H===G)}function Vd(W,G){return Hd(W,jd(G))}function $y(W){let G=me(n.level,W);if(!G)return;let H=jd(W);if(H)return H;console.error(`CC Safety Net: ignored invalid ${n.level.name}=${JSON.stringify(G.slice(0,40))}. Use ${$i.join(", ")}.`);return}function ot(W){if(W===void 0||W==="all")return"all";if(W==="blocked")return"blocked";return"invalid"}function Pe(W){return ot(me(n.auditScope,W))==="all"}function Da(W){if(W.failClosed&&W.paranoidRm&&W.paranoidInterpreters)return"paranoid";if(W.failClosed&&!W.paranoidRm&&!W.paranoidInterpreters)return"strict";if(!W.failClosed&&!W.paranoidRm&&!W.paranoidInterpreters)return"standard";return"custom"}function P(W={},G){let H=W.safety?.level??"standard",J=$y(G),oe=Hd(H,J),ie=zi[oe],fe={failClosed:ie.fail_closed,paranoidRm:ie.paranoid_rm,paranoidInterpreters:ie.paranoid_interpreters},Re={failClosed:oe===H?"preset":"environment",paranoidRm:oe===H?"preset":"environment",paranoidInterpreters:oe===H?"preset":"environment"},Te={failClosed:[`policy safety.level=${H}`],paranoidRm:[`policy safety.level=${H}`],paranoidInterpreters:[`policy safety.level=${H}`]};if(oe!==H)Te.failClosed.push(`env ${n.level.name}=${J}`),Te.paranoidRm.push(`env ${n.level.name}=${J}`),Te.paranoidInterpreters.push(`env ${n.level.name}=${J}`);if(W.safety?.overrides?.failClosed!==void 0)fe.failClosed=W.safety.overrides.failClosed,Re.failClosed="capability_override",Te.failClosed.push("policy safety.overrides.fail_closed");if(W.safety?.overrides?.paranoidRm!==void 0)fe.paranoidRm=W.safety.overrides.paranoidRm,Re.paranoidRm="capability_override",Te.paranoidRm.push("policy safety.overrides.paranoid_rm");if(W.safety?.overrides?.paranoidInterpreters!==void 0)fe.paranoidInterpreters=W.safety.overrides.paranoidInterpreters,Re.paranoidInterpreters="capability_override",Te.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(S(n.strict,G))fe.failClosed=!0,Re.failClosed="environment",Te.failClosed.push(`env ${n.strict.name}`);if(S(n.paranoid,G))fe.paranoidRm=!0,fe.paranoidInterpreters=!0,Re.paranoidRm="environment",Re.paranoidInterpreters="environment",Te.paranoidRm.push(`env ${n.paranoid.name}`),Te.paranoidInterpreters.push(`env ${n.paranoid.name}`);if(S(n.paranoidRm,G))fe.paranoidRm=!0,Re.paranoidRm="environment",Te.paranoidRm.push(`env ${n.paranoidRm.name}`);if(S(n.paranoidInterpreters,G))fe.paranoidInterpreters=!0,Re.paranoidInterpreters="environment",Te.paranoidInterpreters.push(`env ${n.paranoidInterpreters.name}`);let ke=!!W.worktreeMode||S(n.worktree,G);return{strict:fe.failClosed,paranoidRm:fe.paranoidRm,paranoidInterpreters:fe.paranoidInterpreters,worktreeMode:ke,effectiveLevel:Da(fe),capabilities:{fail_closed:{enabled:fe.failClosed,source:Re.failClosed,sources:Te.failClosed},paranoid_rm:{enabled:fe.paranoidRm,source:Re.paranoidRm,sources:Te.paranoidRm},paranoid_interpreters:{enabled:fe.paranoidInterpreters,source:Re.paranoidInterpreters,sources:Te.paranoidInterpreters}}}}function S(W,G){let H=typeof W==="string"?Ho(W,G):me(W,G);return H==="1"||H?.toLowerCase()==="true"}function Ho(W,G){return G.get(W)}function me(W,G){let H=Ho(W.name,G);if(H!==void 0)return H;if(W.legacyName)return Ho(W.legacyName,G);return}function vt(W,G){return Ho(W.name,G)!==void 0||!!W.legacyName&&Ho(W.legacyName,G)!==void 0}import{dirname as Nr}from"node:path";import{closeSync as By,constants as jo,fstatSync as Na,fsyncSync as Uy,lstatSync as On,mkdirSync as Kd,openSync as qd,readdirSync as Wa,readFileSync as Hy,realpathSync as ao,renameSync as jy,rmdirSync as Yd,statSync as La,unlinkSync as Ga,writeFileSync as Vy}from"node:fs";import{isAbsolute as Zd,join as kr,normalize as Ky,parse as Bi,relative as Fa,resolve as za,sep as Ui}from"node:path";function Fe(){let W=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${W()}${W()}`}var qy=Symbol("PolicyFilesystemScope"),Yy=Symbol("PolicyFilesystemTarget"),Xd=jo.O_NOFOLLOW??0;class o extends Error{name="PolicyFilesystemError";constructor(W){super(`Unable to access ${W} filesystem safely.`)}}function w(W,G){return{[qy]:!0,root:za(W),label:G}}function Vo(W,G){let H=Ky(G);if(G===""||Zd(G)||H===".."||H.startsWith(`..${Ui}`))throw new o(W.label);return{[Yy]:!0,scope:W,relativePath:H,path:kr(W.root,H)}}function i(W,G){return Vo(W,Fa(W.root,za(G)))}function ae(W,G="rules policy"){let H=za(W),J=Bi(H).dir;return Vo(w(J,G),Fa(J,H))}function r(W){return rr(W.scope.label,()=>{if(!cn(W))return null;let G=qd(W.path,jo.O_RDONLY|Xd);return Qd(G,()=>{let H=Na(G);if(!H.isFile())throw new o(W.scope.label);let J=Hy(G,"utf-8"),oe=On(W.path);if(!oe.isFile()||oe.isSymbolicLink()||H.dev!==oe.dev||H.ino!==oe.ino)throw new o(W.scope.label);return cn(W),J})})}function g(W,G,H=384,J){let oe=`${W.path}.${Fe()}.tmp`;rr(W.scope.label,()=>{Xy(W),cn(W);let ie=qd(oe,jo.O_CREAT|jo.O_EXCL|jo.O_WRONLY|Xd,H),fe=Qd(ie,()=>{let Re=Na(ie);if(!Re.isFile())throw new o(W.scope.label);Vy(ie,G,"utf-8"),Uy(ie);let Te=Na(ie);if(!Te.isFile()||Te.dev!==Re.dev||Te.ino!==Re.ino)throw new o(W.scope.label);return Te});cn(W),Qy(W,oe,fe.dev,fe.ino),jy(oe,W.path),J?.(W.path),cn(W)},()=>eS(oe))}function Jd(W,G){if(W.path===G.path)return!0;return rr(W.scope.label,()=>{if(!cn(W)||!cn(G))return!1;let H=(J)=>kr(ao(Bi(J).dir),Bi(J).base);return H(W.path)===H(G.path)})}function he(W){let G=rr(W.scope.label,()=>{if(!cn(W,"directory"))return null;let H=Wa(W.path);return cn(W,"directory"),H});if(!G)return null;return rr(W.scope.label,()=>{let H=G.map((J)=>{let oe=Vo(W.scope,kr(W.relativePath,J)),ie=On(oe.path);if(ie.isSymbolicLink()||!ie.isFile()&&!ie.isDirectory())throw new o(W.scope.label);return Hi($a(W.scope),ao(oe.path),W.scope.label),{name:J,kind:ie.isDirectory()?"directory":"file"}});return cn(W,"directory"),H})}function B(W){rr(W.scope.label,()=>{if(!cn(W))return;Ga(W.path),cn(W)})}function wt(W){rr(W.scope.label,()=>{if(!Zy(W))return;tu(W),cn(W,"directory")})}function Ct(W){rr(W.scope.label,()=>{if(!cn(W,"directory"))return;Yd(W.path),cn(W,"directory")})}function Zy(W){return rr(W.scope.label,()=>{if(!cn(W,"directory"))return!1;return eu(W),!0})}function rr(W,G,H){try{return G()}catch(J){if(H?.(),J instanceof o)throw J;throw new o(W)}}function Qd(W,G){try{return G()}finally{By(W)}}function cn(W,G="file"){let H=nu(W.scope);if(!H)return!1;let J=W.relativePath.split(Ui);for(let oe of J.keys()){let ie=kr(W.scope.root,...J.slice(0,oe+1)),fe=On(ie,{throwIfNoEntry:!1});if(!fe)return!1;if(fe.isSymbolicLink())throw new o(W.scope.label);if(oe<J.length-1&&!fe.isDirectory())throw new o(W.scope.label);if(oe===J.length-1&&(G==="file"?!fe.isFile():!fe.isDirectory()))throw new o(W.scope.label);Hi(H,ao(ie),W.scope.label)}return!0}function eu(W){for(let G of Wa(W.path)){let H=Vo(W.scope,kr(W.relativePath,G)),J=On(H.path);if(J.isSymbolicLink()||!J.isDirectory()&&!J.isFile())throw new o(W.scope.label);if(J.isDirectory())eu(H)}cn(W,"directory")}function tu(W){for(let G of Wa(W.path)){let H=Vo(W.scope,kr(W.relativePath,G)),J=On(H.path);if(J.isSymbolicLink())throw new o(W.scope.label);if(J.isDirectory()){tu(H);continue}if(!J.isFile())throw new o(W.scope.label);Ga(H.path)}Yd(W.path)}function Xy(W){Jy(W.scope);let G=$a(W.scope),H=W.relativePath.split(Ui).slice(0,-1);for(let J of H.keys()){let oe=kr(W.scope.root,...H.slice(0,J+1));if(!On(oe,{throwIfNoEntry:!1}))Kd(oe,{mode:448});let ie=On(oe);if(!ie.isDirectory()||ie.isSymbolicLink())throw new o(W.scope.label);Hi(G,ao(oe),W.scope.label)}}function Jy(W){if(On(W.root,{throwIfNoEntry:!1})){if(!La(W.root).isDirectory())throw new o(W.label);return}let G=[],H=W.root;while(!On(H,{throwIfNoEntry:!1})){G.unshift(H);let J=Bi(H).dir;if(J===H)throw new o(W.label);H=J}if(!La(H).isDirectory())throw new o(W.label);for(let J of G){Kd(J,{mode:448});let oe=On(J);if(!oe.isDirectory()||oe.isSymbolicLink())throw new o(W.label)}}function nu(W){if(!On(W.root,{throwIfNoEntry:!1}))return null;if(!La(W.root).isDirectory())throw new o(W.label);return ao(W.root)}function $a(W){let G=nu(W);if(!G)throw new o(W.label);return G}function Qy(W,G,H,J){let oe=On(G);if(!oe.isFile()||oe.isSymbolicLink()||oe.dev!==H||oe.ino!==J)throw new o(W.scope.label);Hi($a(W.scope),ao(G),W.scope.label)}function Hi(W,G,H){let J=Fa(W,G);if(J===".."||J.startsWith(`..${Ui}`)||Zd(J))throw new o(H)}function eS(W){try{Ga(W)}catch{}}import{dirname as Or,isAbsolute as iS,join as Mr,relative as sS,resolve as fr,sep as aS}from"node:path";var p=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ye="rulebook.json",be=".cc-safety-net/rules";var ru=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,tS=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,ou=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,nS=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),rS="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Et=new RegExp(`^${nS}/(${p.source.slice(1,-1)})/${rS}$`);function oS(W){return`.cc-safety-net/rules/${W}/rulebook.json`}function iu(W){if(C(W))try{return M(W),null}catch(G){return G instanceof Error?G.message:String(G)}return p.test(W)?null:`Local rulebook sources must be bare names matching ${p}: ${W}`}function M(W){if(W.startsWith("github:"))throw Error(`Invalid rulebook source: ${W}`);let G=W.match(ru);if(!G?.[1]||!G[2]||!G[3])throw Error(`Invalid GitHub rulebook source: ${W}`);let H=G[3].lastIndexOf("/");if(H<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${W}`);let J=G[3].slice(0,H),oe=G[3].slice(H+1);if(!J||!ou.test(J))throw Error(`GitHub rulebook refs must use valid path segments: ${W}`);if(!oe||!p.test(oe))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${W}`);return{owner:G[1],repo:G[2],ref:J,path:oS(oe),name:oe}}function X(W){return tS.test(W)}function ce(W){return ou.test(W)}function C(W){return ru.test(W)}function kt(W){if(!p.test(W))throw Error(`Local rulebook sources must be bare names matching ${p}: ${W}`)}var su="rule.json",ji="policy.json",au=".cc-safety-net",lS="rules",cS="CC_SAFETY_NET_HOME",lu="`cc-safety-net rule update`";function dS(W){return fr(W,be)}function I(W){return Mr(dS(W),su)}function h(W){return Mr(fr(W),au,ji)}function Ae(W,G={}){return G.userConfigDir??(G.userConfigPath?Or(G.userConfigPath):Mr(uS(W),lS))}function uS(W){let G=W.env.get(cS);return G?fr(pn(G)):Mr(W.home,au)}function z(W,G={}){return Mr(Ae(W,G),su)}function u(W,G={}){return Mr(Or(Ae(W,G)),ji)}function O(W,G){let H=In();return Bt(h(G.cwd),W.paths,H)===Bt(fr(u(W,G)),W.paths,H)}function Q(W,G){let H=G.userConfigPath??z(W,G),J=G.projectConfigPath??I(G.cwd),oe=at(W,G),ie=ct(J,G.cwd);return{userConfigPath:H,projectConfigPath:J,userScope:oe,projectScope:ie,userConfigTarget:i(oe,H),projectConfigTarget:i(ie,J)}}function at(W,G){let H=G.userConfigPath?Or(Or(fr(G.userConfigPath))):Or(fr(G.userConfigDir??Ae(W,G)));return w(H,"user policy")}function ct(W,G){let H=fr(G),J=fr(W),oe=sS(H,J);if(oe!==".."&&!oe.startsWith(`..${aS}`)&&!iS(oe))return w(H,"project policy");return w(Or(Or(J)),"project policy")}function F(W,G){return Mr(W,G,ye)}var _n=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),E=/^[a-zA-Z][a-zA-Z0-9_-]*$/,D=256,en=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),cu=new Set(["python","python3","python2","node","ruby","perl"]),Vi=/^python(?:[23](?:\.\d+)*)?$/,Mn=new Set(["awk","gawk","nawk","mawk"]),Ki=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 du="Rulebook exceeds CC Safety Net's safe validation limits.",uu="Additional rulebook validation errors were omitted.",zn=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function mu(W){if(Ba(W.allowed_commands,zn.maxAllowedCommands)||Ba(W.rules,zn.maxRules)||Ba(W.tests,zn.maxTests))return!1;let{maxAggregateStringCodeUnits:G,maxTotalBlockArgs:H}=zn,J=(oe,ie=!1)=>{if(typeof oe!=="string")return!0;if(oe.length>zn.maxStringCodeUnits||ie&&oe.length>zn.maxFixtureCommandCodeUnits||oe.length>G)return!1;return G-=oe.length,!0};if(!J(W.name)||!J(W.version)||!J(W.description)||!J(W.author)||!J(W.migrated_from))return!1;if(Array.isArray(W.allowed_commands)){for(let oe of W.allowed_commands)if(!J(oe))return!1}if(Array.isArray(W.rules))for(let oe of W.rules){if(!oe||typeof oe!=="object")continue;let ie=oe;if(!J(ie.name)||!J(ie.command)||!J(ie.subcommand)||!J(ie.reason)||!J(ie.intent))return!1;let fe=ie.match&&typeof ie.match==="object"?ie.match:{};for(let Re of[ie.block_args,fe.command_path,fe.any_args,fe.exclude_args]){if(!Array.isArray(Re))continue;if(Re.length>zn.maxBlockArgsPerRule||Re.length>H)return!1;H-=Re.length;for(let Te of Re)if(!J(Te))return!1}}if(Array.isArray(W.tests))for(let oe of W.tests){if(!oe||typeof oe!=="object")continue;let ie=oe;if(!J(ie.command,!0)||!J(ie.expect)||!J(ie.rule))return!1}return!0}function Ba(W,G){return Array.isArray(W)&&W.length>G}var Ua=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var xe=64,ve="Rule config exceeds CC Safety Net's safe source limit.";function zt(W){return Ft(W).toLowerCase()}function Ft(W){return W.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??W}function Cn(W,G){let H=new Set,J=!1;for(let oe of W){if(oe==="--"){J=!0;continue}if(J)continue;if(oe.startsWith("-")&&!oe.startsWith("--")&&oe.length>1)for(let ie=1;ie<oe.length;ie++){let fe=oe[ie];if(!fe||!/[a-zA-Z]/.test(fe))break;let Re=`-${fe}`;if(H.add(Re),G?.shortOptsWithValue?.has(Re))break}}return H}var mS={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Ha=new Set(["--init-file","--rcfile"]);function ja(W,G,H,J){let oe=!1,ie=0,fe=!1,Re=!1;for(let Te=1;Te<G.length;Te++){let ke=G[Te];if(ke===void 0)break;if(W==="ksh"&&ke==="o"&&Te+1<G.length){if(J==="argv"){let Le=G.slice(Te+1);if(G[0]==="-"&&(Le==="c"||Le[0]==="-"&&Le.endsWith("c")))fe=!0}break}if(W==="ksh"&&ke==="o"&&Te+1===G.length&&(H?.startsWith("-")||H?.startsWith("+")))break;if(W==="zsh"&&ke==="o"&&Te+1<G.length)break;if(J==="startup"&&ke==="i")oe=G[0]==="-";if(J==="argv"&&G[0]==="-"&&ke==="c")fe=!0;if(J==="argv"&&ke==="s")Re=G[0]==="-";if(!mS[W]?.includes(ke))continue;if(Te+1===G.length)ie++;break}return{interactive:oe,followingValues:ie,commandSelected:fe,stdinMode:Re}}function Dn(W){let G=Ft(W[0]??"").toLowerCase(),H=!1,J=!1;for(let oe=1;oe<W.length;oe++){let ie=W[oe];if(ie===void 0)break;if(ie==="--"){let Re=H&&W[oe+1]!==void 0?oe+1:null;return{command:Re===null?null:W[Re]??null,commandIndex:Re,scriptIndex:!H&&!J&&W[oe+1]!==void 0?oe+1:null,readsStdinAsCommands:!H&&(J||W[oe+1]===void 0)}}if(ie==="-"||ie[0]!=="-"&&ie[0]!=="+")return{command:H?ie:null,commandIndex:H?oe:null,scriptIndex:!H&&!J&&ie!=="-"?oe:null,readsStdinAsCommands:!H&&(J||ie==="-")};if(ie.startsWith("--")){let Re=ie.split("=",1)[0]??ie;if(G==="bash"&&Ha.has(Re)&&!ie.includes("="))oe++;continue}let fe=ja(G,ie,W[oe+1],"argv");if(fe.commandSelected)H=!0;if(fe.stdinMode)J=!0;oe+=fe.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!H}}function Ko(W,G){if(G.escaped)return G.escaped=!1,!0;if(W==="\\"&&!G.inSingle)return G.escaped=!0,!0;if(W==="'"&&!G.inDouble)return G.inSingle=!G.inSingle,!0;if(W==='"'&&!G.inSingle)return G.inDouble=!G.inDouble,!0;return!1}function qi(W){let G={inSingle:!1,inDouble:!1,escaped:!1};for(let H of fS(W))Ko(H,G);return G.inSingle||G.inDouble}function fS(W){let G="",H={inSingle:!1,inDouble:!1,escaped:!1},J=!1,oe=!0;for(let ie=0;ie<W.length;ie++){let fe=W[ie];if(!fe)break;if(J){if(fe===`
|
|
5
|
+
`||fe==="\r")G+=fe,J=!1,H.escaped=!1;continue}if(fe==="#"&&!H.inSingle&&!H.inDouble&&oe){J=!0;continue}if(G+=fe,!H.inSingle&&!H.inDouble&&!H.escaped)oe=/[\s;&|()<>]/.test(fe);Ko(fe,H)}return G}var Va=new Set(["rm","find","xargs","parallel"]),pS=new Set(["git","busybox",...Va,...en,...cu,...Mn]),gS=new Set(["python","node","ruby","perl"]);function $e(W){let G=zt(W);return pS.has(G)||$n(G)}function $n(W){return gS.has(hS(W))}function hS(W){let G=Ft(W).toLowerCase();return Vi.test(G)?"python":G}var le={version:1,rules:[],overrides:{},transparent_wrappers:[]};function d(W){try{let G=r(yS(W));if(G===null)return{config:null,errors:[]};if(!G.trim())return{config:null,errors:["Config file is empty"]};let H=JSON.parse(G),J=lt(H);if(J.errors.length>0)return{config:null,errors:J.errors};return{config:{version:1,rules:H.rules??[],overrides:H.overrides??{},transparent_wrappers:H.transparent_wrappers??[],...H.command_tools?{command_tools:H.command_tools}:{}},errors:[]}}catch(G){if(G instanceof o)return{config:null,errors:[G.message]};let H=G instanceof Error?G.message:String(G);return{config:null,errors:[G instanceof SyntaxError?"Invalid JSON":H]}}}function yS(W){return typeof W==="string"?ae(W):W}var e=(W,G)=>({path:W,message:G,kind:"typed"}),an=(W,G)=>({path:W,message:G,kind:"custom"});function Ue(W){let G=new Set;return W.flatMap((H,J)=>{let oe=Dr(H)?H.name:void 0;if(typeof oe!=="string")return[];if(G.has(oe.toLowerCase()))return[an(["rules",J,"name"],`duplicate rule name "${oe}"`)];return G.add(oe.toLowerCase()),[]})}var Oe=`must be one of ${Ua.join(", ")}`,SS=/^[^/]+\/[^/]+$/,CS=["version","rules","overrides","transparent_wrappers","command_tools"],je=/^[^\s\p{Cc}]{1,256}$/u,Se="non-empty, at most 256 characters, no whitespace or control characters";function lt(W){let G=bS(W);return{errors:ue(ut(G,CS,(H)=>H.kind==="custom"),": "," "),sources:TS(W,G)}}function bS(W){if(!Dr(W))return[e([],"Config must be an object")];let G=Array.isArray(W.rules)&&W.rules.length>xe;return[...W.version===1?[]:[e(["version"],"must be 1")],...vS(W.rules,G),..._S(W.overrides),...wS(W.transparent_wrappers),...G?[]:RS(W.rules),...Dr(W.overrides)?Object.keys(W.overrides).filter((H)=>!SS.test(H)).map((H)=>an(["overrides",H],"must use <rulebook-name>/<rule-name>")):[],...AS(W.transparent_wrappers),...PS(W.command_tools)]}function vS(W,G){if(W===void 0)return[];if(!Array.isArray(W))return[e(["rules"],"must be an array of rulebook source strings"),...fu(W,xe)?[e(["rules"],ve)]:[]];if(G)return[{path:["rules"],message:ve,kind:"limit"}];return W.flatMap((H,J)=>{if(typeof H!=="string")return[e(["rules",J],"must be a rulebook source string"),...ES(H,1)?[e(["rules",J],"must be a non-empty rulebook source string")]:[]];return H===""?[e(["rules",J],"must be a non-empty rulebook source string")]:[]})}function fu(W,G){let H=pu(W);return H!==void 0&&!(H<=G)}function ES(W,G){let H=pu(W);return H!==void 0&&!(H>=G)}function pu(W){if(W===null||W===void 0)return;let G=W.length;return G===void 0?void 0:Number(G)}function RS(W){if(!Array.isArray(W))return[];let G=new Set;return W.flatMap((H,J)=>{if(typeof H!=="string"||H==="")return[];if(H.trim()==="")return[an(["rules",J],"must be a non-empty rulebook source string")];let oe=iu(H);if(oe)return[an(["rules",J],oe)];if(G.has(H))return[an(["rules",J],`duplicate rulebook source "${H}"`)];return G.add(H),[]})}function _S(W){if(W===void 0)return[];if(!Dr(W))return[e(["overrides"],"must be an object if provided")];return Object.keys(W).flatMap((G)=>{let H=W[G];if(H==="off")return[];if(!Dr(H))return[e(["overrides",G],'must be "off" or an object')];return[...xS(H.reason,["overrides",G,"reason"]),...H.intent===void 0||De(H.intent)?[]:[e(["overrides",G,"intent"],Oe)]]})}function xS(W,G){if(typeof W!=="string")return[e(G,"required non-empty string"),...fu(W,D)?[e(G,`must be at most ${D} characters`)]:[]];if(W==="")return[e(G,"required non-empty string")];return W.length>D?[e(G,`must be at most ${D} characters`)]:[]}function wS(W){if(W===void 0)return[];if(!Array.isArray(W))return[e(["transparent_wrappers"],"must be an array of command strings")];return W.flatMap((G,H)=>{if(typeof G!=="string")return[e(["transparent_wrappers",H],"must be a command string")];return E.test(G)?[]:[e(["transparent_wrappers",H],"must match command pattern")]})}function AS(W){if(!Array.isArray(W))return[];let G=new Set;return W.flatMap((H,J)=>{if(typeof H!=="string"||!E.test(H))return[];if(G.has(H))return[an(["transparent_wrappers",J],`duplicate command "${H}"`)];if($e(H))return[an(["transparent_wrappers",J],`reserved command "${H}" cannot be a wrapper`)];return G.add(H),[]})}function PS(W){if(W===void 0)return[];if(!Array.isArray(W))return[e(["command_tools"],"must be an array of tool names or {name, cwd} objects")];let G=new Set,H=(J,oe)=>{if(G.has(J))return[an(["command_tools",oe],`duplicate tool "${J}"`)];return G.add(J),[]};return W.flatMap((J,oe)=>{if(typeof J==="string")return Ka(J)?H(J,oe):[e(["command_tools",oe],`must be a tool name: ${Se}`)];if(!Dr(J))return[e(["command_tools",oe],"must be a tool name or a {name, cwd} object")];let ie=[...Ka(J.name)?[]:[e(["command_tools",oe,"name"],`must be a tool name: ${Se}`)],...J.cwd===void 0||Ka(J.cwd)?[]:[e(["command_tools",oe,"cwd"],`must be an argument name: ${Se}`)]];return ie.length>0?ie:H(J.name,oe)})}function Ka(W){return typeof W==="string"&&je.test(W)}function TS(W,G){let H=Dr(W)?W.rules:void 0;if(!Array.isArray(H))return new Set;if(G.some((oe)=>oe.path.length===1&&oe.path[0]==="rules"))return new Set;let J=new Set(G.filter((oe)=>oe.path[0]==="rules"&&typeof oe.path[1]==="number").map((oe)=>oe.path[1]));return new Set(H.filter((oe,ie)=>typeof oe==="string"&&!J.has(ie)))}function ut(W,G,H){let J=W.map((fe)=>fe.path[1]),oe=[...new Set(J.filter((fe)=>typeof fe==="string"))],ie=(fe,Re)=>[fe.path.length===0?-1:G.indexOf(String(fe.path[0])),typeof Re==="number"?Re:oe.indexOf(String(Re)),H(fe)?0:1];return W.map((fe,Re)=>({issue:fe,rank:ie(fe,J[Re])})).sort((fe,Re)=>fe.rank[0]-Re.rank[0]||fe.rank[1]-Re.rank[1]||fe.rank[2]-Re.rank[2]).map((fe)=>fe.issue)}function ue(W,G,H){return[...new Set(W.map((J)=>{let oe=qa(J.path);if(J.kind==="unknownKeys")return`${oe?`${oe}.`:""}unknown field "${J.message}"`;if(J.kind==="key"||J.kind==="limit"||J.path.length===0)return J.message;return`${oe}${J.path.length===1?H:G}${J.message}`}))]}function qa(W){return W.map((G,H)=>{if(typeof G==="number")return`[${G}]`;return H===0?String(G):`.${String(G)}`}).join("")}function De(W){return Ua.includes(W)}function Dr(W){return!!W&&typeof W==="object"&&!Array.isArray(W)}function de(W){let G=OS(W);if(G.errors.length>0)throw Error(G.errors.join("; "));return W}var IS=`required non-empty string up to ${D} characters`,gu="must be a non-empty array of unique non-empty strings",kS="required non-empty array of non-empty strings";function OS(W){if(!pr(W))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!mu(W))return{errors:[du],ruleNames:new Set};let G=[...W.rulebook_version===1||W.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ue(MS(W,W.rulebook_version===2),": ",": ")];return{errors:G.length>zn.maxValidationErrors?[...G.slice(0,zn.maxValidationErrors),uu]:G,ruleNames:new Set(Ge(W).map((H)=>H.toLowerCase()))}}function Ge(W){let G=pr(W)?W.rules:void 0;return(Array.isArray(G)?G:[]).flatMap((H)=>{let J=pr(H)?H.name:void 0;return typeof J==="string"?[J]:[]})}function MS(W,G){return[...typeof W.name==="string"&&p.test(W.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof W.version==="string"&&W.version!==""?[]:[e(["version"],"required non-empty string")],...DS(W.allowed_commands),...NS(W.rules,G),...FS(W.tests),...zS(W),...$S(W)]}function DS(W){if(!Array.isArray(W))return[e(["allowed_commands"],"required array")];let G=new Set;return[...W.flatMap((H,J)=>typeof H==="string"&&E.test(H)?[]:[e(["allowed_commands",J],"must match command pattern")]),...W.flatMap((H,J)=>{if(typeof H!=="string"||!E.test(H))return[];if(G.has(H))return[an(["allowed_commands",J],`duplicate command "${H}"`)];return G.add(H),[]})]}function NS(W,G){if(!Array.isArray(W))return[e(["rules"],"required array")];return[...W.flatMap((H,J)=>{if(!pr(H))return[e(["rules",J],"must be an object")];return G?WS(H,["rules",J]):LS(H,["rules",J])}),...Ue(W)]}function LS(W,G){return[...hu(W.name,G),...yu(W.command,G),...W.subcommand===void 0||typeof W.subcommand==="string"&&E.test(W.subcommand)?[]:[e([...G,"subcommand"],"must match command pattern")],...Yi(W.block_args,[...G,"block_args"],"required non-empty array",!1),...Su(W.reason,G),...Cu(W.intent,G)]}function WS(W,G){return[...hu(W.name,G),...yu(W.command,G),...Su(W.reason,G),...Cu(W.intent,G),...GS(W.match,[...G,"match"]),...W.subcommand===void 0?[]:[e([...G,"subcommand"],"not supported in rulebook_version 2")],...W.block_args===void 0?[]:[e([...G,"block_args"],"not supported in rulebook_version 2")]]}function hu(W,G){if(typeof W!=="string")return[e([...G,"name"],"required string")];return p.test(W)?[]:[e([...G,"name"],"must match rule name pattern")]}function yu(W,G){return typeof W==="string"&&E.test(W)?[]:[e([...G,"command"],"required string matching command pattern")]}function Su(W,G){return typeof W==="string"&&W!==""&&W.length<=D?[]:[e([...G,"reason"],IS)]}function Cu(W,G){return W===void 0||De(W)?[]:[e([...G,"intent"],Oe)]}function GS(W,G){if(!pr(W))return[e(G,"required object")];return[...Yi(W.command_path,[...G,"command_path"],kS,!1),...W.any_args===void 0?[]:Yi(W.any_args,[...G,"any_args"],gu,!0),...W.exclude_args===void 0?[]:Yi(W.exclude_args,[...G,"exclude_args"],gu,!0)]}function Yi(W,G,H,J){if(!Array.isArray(W))return[e(G,H)];let oe=W.flatMap((ie,fe)=>{if(typeof ie!=="string")return[e([...G,fe],"must be a non-empty string")];return ie===""?[an([...G,fe],"must be a non-empty string")]:[]});if(W.some((ie)=>typeof ie!=="string"))return oe;return[...oe,...W.length===0?[an(G,H)]:[],...J&&new Set(W).size!==W.length?[an(G,"must not contain duplicate values")]:[]]}function FS(W){if(W===void 0)return[];if(!Array.isArray(W))return[e(["tests"],"must be an array if provided")];return W.flatMap((G,H)=>{if(!pr(G))return[e(["tests",H],"must be an object")];return[...typeof G.command==="string"&&G.command.trim()!==""?[]:[e(["tests",H,"command"],"required non-empty string")],...G.expect==="blocked"||G.expect==="allowed"?[]:[e(["tests",H,"expect"],'must be "blocked" or "allowed"')],...G.rule===void 0||typeof G.rule==="string"?[]:[e(["tests",H,"rule"],"must be a string if provided")],...G.expect==="blocked"&&typeof G.rule!=="string"?[an(["tests",H,"rule"],"required string for blocked fixtures")]:[]]})}function zS(W){if(!Array.isArray(W.tests))return[];let G=new Set(Ge(W));return[...new Set(W.tests.flatMap((H)=>pr(H)&&H.expect==="blocked"&&typeof H.rule==="string"?[H.rule]:[]))].filter((H)=>!G.has(H)).map((H)=>an(["tests"],`blocked fixture references unknown rule "${H}"`))}function $S(W){if(!Array.isArray(W.allowed_commands)||!Array.isArray(W.rules))return[];let G=new Set(W.allowed_commands.filter((H)=>typeof H==="string"));return W.rules.flatMap((H,J)=>{let oe=pr(H)?H.command:void 0;if(typeof oe!=="string"||G.has(oe))return[];return[an(["rules",J,"command"],`"${oe}" must be listed in allowed_commands`)]})}function pr(W){return!!W&&typeof W==="object"&&!Array.isArray(W)}function ee(W,G){let H=Q(W,G),J;try{J=Jd(H.userConfigTarget,H.projectConfigTarget)}catch(Ze){if(Ze instanceof o)return XS(H,Ze.message);throw Ze}let oe=d(H.userConfigTarget),ie=J?{config:null,errors:[]}:d(H.projectConfigTarget),fe=Eu(H.userConfigPath,oe.errors),Re=Eu(H.projectConfigPath,ie.errors),Te=new Set,ke=oe.config?Ya(oe.config,Nr(H.userConfigPath),"user",H.userScope,Te):Ru(),Le=ie.config?Ya(ie.config,Nr(H.projectConfigPath),"project",H.projectScope,Te):Ru(),Xe=oe.config?.overrides??{},Ye=ie.config?.overrides??{};return{rules:[...vu(ke.rules,Xe),...vu(Le.rules,Ye)],transparent_wrappers:qS(oe.config,ie.config),command_tools:YS(oe.config,ie.config),rulebooks:[...ke.rulebooks,...Le.rulebooks],errors:[...fe,...Re,...ke.errors,...Le.errors],warnings:[...ke.warnings,...Le.warnings,...ke.canValidateOverrides?Za(Xe,ke.knownRuleIds,H.userConfigPath):[],...ke.canValidateOverrides?ZS(Ye,ke.knownRuleIds,H.projectConfigPath):[],...Le.canValidateOverrides?Za(Ye,Le.knownRuleIds,H.projectConfigPath):[]],userConfig:oe.config??void 0,projectConfig:ie.config??void 0,...H}}function V(W,G){let H=BS(W,G);if(!H)return[];return[...H.scope.errors,...H.scope.warnings,...US(H.config,H.scope,W)]}function BS(W,G){let H=G??w(Nr(Nr(W)),"rules policy"),J=d(i(H,W)).config;if(!J)return null;return{config:J,scope:Ya(J,Nr(W),"project",H)}}function US(W,G,H){return G.canValidateOverrides?Za(W.overrides??{},G.knownRuleIds,H):[]}function Ya(W,G,H,J=w(Nr(Nr(G)),H==="user"?"user policy":"project policy"),oe=new Set){let ie=[],fe=[],Re=W.rules.flatMap((ke)=>{let Le=jS(ke,G,J);if(Le.errors.length>0||!Le.rulebook)return ie.push(...Le.errors),[];let Xe=Le.rulebook;if(oe.has(Xe.name))return fe.push(`duplicate active rulebook name "${Xe.name}" for ${ke}; keeping the first and ignoring this one, so its rules are not active; rename one of them in its rulebook file and in the rules config that lists it`),[];return oe.add(Xe.name),[{rules:HS(Xe),rulebook:{source:H,spec:ke,name:Xe.name,version:Xe.version,rules:Xe.rules.map((Ye)=>`${Xe.name}/${Ye.name}`)}}]}),Te=Re.flatMap((ke)=>ke.rules);return{rules:Te,rulebooks:Re.map((ke)=>ke.rulebook),knownRuleIds:new Set(Te.map((ke)=>ke.name)),errors:ie,warnings:fe,canValidateOverrides:ie.length===0}}function HS(W){if(W.rulebook_version===2)return W.rules.map((G)=>({name:`${W.name}/${G.name}`,command:G.command,block_args:[],match:G.match,reason:G.reason,intent:G.intent}));return W.rules.map((G)=>({...G,name:`${W.name}/${G.name}`,match:void 0}))}function jS(W,G,H){let J=He(W),oe=F(G,J),ie=KS(oe,H);if("error"in ie)return{rulebook:null,errors:[ie.error]};if(ie.content===null)return{rulebook:null,errors:[`missing rulebook file ${oe} for ${W}; ${VS(W)}`]};let fe=we(ie.content);if("problem"in fe)return{rulebook:null,errors:[`invalid rulebook ${oe}: ${fe.problem}; fix that file`]};if(fe.rulebook.name!==J)return{rulebook:null,errors:[`rulebook name "${fe.rulebook.name}" in ${oe} must match source "${W}"; fix that file`]};return{rulebook:fe.rulebook,errors:[]}}function He(W){return C(W)?M(W).name:W}function VS(W){return C(W)?`run ${lu} to vendor ${W}`:"create that file or remove that source from the rules config"}function KS(W,G){try{return{content:r(i(G,W))}}catch(H){if(H instanceof o)return{error:H.message};throw H}}function we(W){let G;try{G=JSON.parse(W)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:de(G)}}catch(H){return{problem:H instanceof Error?H.message:"invalid rulebook"}}}function qS(W,G){return[...new Set([...W?.transparent_wrappers??[],...G?.transparent_wrappers??[]])]}function YS(W,G){let H=(W?.command_tools??[]).map(bu),J=(G?.command_tools??[]).map(bu);return[...H,...J.filter((oe)=>!H.some((ie)=>ie.name===oe.name))]}function bu(W){if(typeof W==="string")return{name:W};return W.cwd===void 0?{name:W.name}:{name:W.name,cwd:W.cwd}}function vu(W,G){return W.flatMap((H)=>{let J=G[H.name];if(J==="off")return[];if(J&&typeof J==="object")return[{...H,intent:J.intent??H.intent,reason:J.reason}];return[H]})}function Za(W,G,H){return Object.keys(W).filter((J)=>!G.has(J)).map((J)=>`unknown override key "${J}" in ${H}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function ZS(W,G,H){return Object.keys(W).filter((J)=>G.has(J)).map((J)=>`project override cannot target user-scoped rule "${J}" in ${H}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function Eu(W,G){return G.map((H)=>H.startsWith("Unable to access ")?H:`${W}: ${H}`)}function XS(W,G){return{rules:[],transparent_wrappers:[],command_tools:[],rulebooks:[],errors:[G],warnings:[],userConfigPath:W.userConfigPath,projectConfigPath:W.projectConfigPath}}function Ru(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as lC,readFileSync as cC}from"node:fs";var _u=[{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"}],Xa=new Set(_u.map((W)=>W.id)),q=_u,JS=new Map(q.map((W)=>[W.id,W.intent]));function Pt(W,G){return{id:W,reason:G,intent:JS.get(W)??"manual_only"}}var Ja=[{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"}],Zi={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},QS=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],eC=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Qa=[{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"]},...eC.flatMap((W)=>QS.map((G)=>({id:["secret.home",W.idSlug,G.slice(1)].join("."),category:"Home path",label:[W.label,G].join(""),description:["Blocks home ",W.label,G," credential backup files."].join(""),suffixParts:[...W.directoryParts,[W.basename,G].join("")]}))),{id:"secret.home.gh-hosts",category:"Home path",label:"~/.config/gh/hosts.yml",description:"Blocks GitHub CLI host credential files.",suffixParts:[".config","gh","hosts.yml"]}];var Xi=[{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"]}],xu=[{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"}],tC=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],el=xu.map((W)=>({id:`secret.variant.${W.slug}.separator`,category:"Variant",label:`${W.label}-* / ${W.label}_*`,description:`Blocks ${W.label} variants with dash or underscore suffixes.`,prefix:W.prefix})),tl=xu.flatMap((W)=>tC.map((G)=>({id:`secret.variant.${W.slug}.${G.slice(1)}`,category:"Variant",label:`${W.label}${G}`,description:`Blocks ${W.label}${G} private credential variants.`,prefix:W.prefix,suffix:G}))),qo={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)$/},nl=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((W)=>({id:`secret.ext.${W}`,category:"Extension",label:`.${W}`,description:`Blocks files with the .${W} extension.`,extension:W})),rl=[{id:"secret.ext-pattern.key",category:"Extension pattern",label:".key / .keypair",description:"Blocks key and keypair extension patterns.",pattern:/^key(pair)?$/},{id:"secret.ext-pattern.keystore",category:"Extension pattern",label:".keystore / .keyring",description:"Blocks keystore and keyring extension patterns.",pattern:/^key(store|ring)$/},{id:"secret.ext-pattern.kdbx",category:"Extension pattern",label:".kdb / .kdbx",description:"Blocks KeePass database extension patterns.",pattern:/^kdbx?$/}],dt=[...Ja,Zi,...Qa,...el,...tl,qo,...nl,...rl,...Xi].map((W)=>({id:W.id,category:W.category,label:W.label,...W.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in W?{paths:W.paths}:{description:W.description}})),Ji=new Set(Xi.flatMap((W)=>W.category==="Coding CLI config"?[W.id]:[])),ol=new Set(dt.map((W)=>W.id));import{isAbsolute as il,join as nC,normalize as rC,sep as Qi}from"node:path";var es=process.platform==="win32",wu=/[*?]/;function sl(W){let G=W.trim(),H=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(es?G.replaceAll("\\","/"):G);if(!H)return null;let J=H[1]??"",oe=H[2]??"";if(wu.test(J)||oe==="."||oe==="..")return null;return{root:J||"/",name:oe}}function Yo(W,G){if(W==="~")return G;if(W.startsWith("~/"))return`${G}${W.slice(1)}`;return W}function al(W,G){if(typeof W!=="string"||W.trim()==="")return"must be a non-empty path string";let H=Yo(W.trim(),G);if(!il(H))return"must be an absolute path or start with ~/";return Zo(H,G)}function ll(W,G){let H=Au(W,G);if(H===null)return"must be a non-empty path string";if(!il(H))return null;if(Zo(H,G)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var oC="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",iC="cannot cover the guard's own configuration";function Au(W,G){if(typeof W!=="string"||W.trim()==="")return null;let H=W.trim(),J=es?H.replaceAll("\\","/"):H;return Yo(J.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),G)}function cl(W,G){let H=Au(W,G);if(H===null)return"must be a non-empty path string";let J=sl(H)?.root??H;if(wu.test(J))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!il(J))return null;if(Zo(J,G)!==null)return oC;return sC(J,G)?iC:null}function sC(W,G){let H=ts(W),J=ts(nC(G,".cc-safety-net"));return H===J||H.startsWith(`${J}${Qi}`)}function Zo(W,G){let H=ts(W),J=ts(G);if(H===J)return"cannot be the home directory";let oe=H.endsWith(Qi)?H:`${H}${Qi}`;if(J.startsWith(oe))return"cannot contain the home directory";return null}function ts(W){let G=rC(W);if(es)G=G.replace(/\//g,"\\").toLowerCase();if(G.length>(es?3:1)&&G.endsWith(Qi))G=G.slice(0,-1);return G}var Pu=30,ns=1,rs=365;function Tu(W){if(typeof W!=="number"||!Number.isInteger(W))return 30;if(W<1)return 1;return W>365?365:W}var Iu=new Set(q.filter((W)=>W.catastrophic).map((W)=>W.id));function Nt(W,G){if(!W)return null;if(Iu.has(W.id))return W;if(G?.destructiveCommandProtectionEnabled===!1)return null;let H=G?.effectiveDestructiveCommandRules[W.id];return H&&!H.enabled?null:W}function on(W,G,H){if(Iu.has(G))return!0;if(W?.destructiveCommandProtectionEnabled===!1)return!1;return W?.effectiveDestructiveCommandRules[G]?.enabled??H}function K(W,G){return Object.freeze(Object.fromEntries(q.map((H)=>{let J=H.activationCapability?G[H.activationCapability]:void 0,oe=J?.enabled??!0,ie=W.destructiveCommandRuleOverrides[H.id],fe=H.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...ie?{override:ie}:{}}:W.destructiveCommandProtectionEnabled?ie?{enabled:ie==="on",inheritedEnabled:oe,changesInherited:ie==="on"!==oe,source:"rule_override",...H.activationCapability?{activationCapability:H.activationCapability}:{},override:ie}:{enabled:oe,inheritedEnabled:oe,changesInherited:!1,source:J?.source??"built_in_default",...H.activationCapability?{activationCapability:H.activationCapability}:{}}:{enabled:!1,inheritedEnabled:oe,changesInherited:!1,source:"master_disabled",...H.activationCapability?{activationCapability:H.activationCapability}:{},...ie?{override:ie}:{}};return[H.id,Object.freeze(fe)]})))}function ku(W,G){return Object.freeze({...W,effectiveDestructiveCommandRules:K(W,G)})}var Ou={standard:0,strict:1,paranoid:2};function te(W,G,H=!1,J=W.safety.level){let oe=aC(W,G,J),ie=new Set(H?oe.map((Le)=>Le.field):[]),fe=(Le,Xe)=>ie.has(Le)?void 0:Xe,Re=(Le,Xe)=>Object.fromEntries(Object.entries(Xe??{}).filter(([Ye])=>!ie.has(`${Le}.${Ye}`))),Te=(Le,Xe)=>Xe?.filter((Ye)=>!ie.has(`${Le}.${Ye}`));return{policy:{version:1,safety:{level:fe("safety.level",G.safety?.level)??W.safety.level,overrides:{...W.safety.overrides,...Re("safety.overrides",G.safety?.overrides)}},workflow:{worktree_mode:fe("workflow.worktree_mode",G.workflow?.worktree_mode)??W.workflow.worktree_mode},destructive_command_protection:{enabled:fe("destructive_command_protection.enabled",G.destructive_command_protection?.enabled)??W.destructive_command_protection.enabled,overrides:{...W.destructive_command_protection.overrides,...Re("destructive_command_protection.overrides",G.destructive_command_protection?.overrides)},allow_paths:dl(W.destructive_command_protection.allow_paths,Te("destructive_command_protection.allow_paths",G.destructive_command_protection?.allow_paths))},secret_protection:{enabled:fe("secret_protection.enabled",G.secret_protection?.enabled)??W.secret_protection.enabled,overrides:{...W.secret_protection.overrides,...Re("secret_protection.overrides",G.secret_protection?.overrides)},deny_paths:dl(W.secret_protection.deny_paths,G.secret_protection?.deny_paths),allow_paths:dl(W.secret_protection.allow_paths,Te("secret_protection.allow_paths",G.secret_protection?.allow_paths))},audit:W.audit},weakenings:oe.map((Le)=>Le.message)}}function dl(W,G){return[...new Set([...W,...G??[]])]}function aC(W,G,H){let J=G.safety?.level,oe=zi[H];return[...J&&Ou[J]<Ou[W.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${W.safety.level} -> ${J}`}]:[],...so.flatMap((ie)=>G.safety?.overrides?.[ie]===!1&&(W.safety.overrides[ie]??oe[ie])?[{field:`safety.overrides.${ie}`,message:`project policy disables ${ie}`}]:[]),...G.workflow?.worktree_mode===!0&&!W.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...G.destructive_command_protection?.enabled===!1&&W.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...G.secret_protection?.enabled===!1&&W.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...Mu("destructive_command_protection.overrides",G.destructive_command_protection?.overrides,(ie)=>W.destructive_command_protection.enabled&&W.destructive_command_protection.overrides[ie]!=="off"),...Mu("secret_protection.overrides",G.secret_protection?.overrides,(ie)=>W.secret_protection.enabled&&(W.secret_protection.overrides[ie]==="on"?!0:W.secret_protection.overrides[ie]!=="off"&&!Ji.has(ie))),...W.destructive_command_protection.enabled?Du(W.destructive_command_protection.allow_paths,G.destructive_command_protection?.allow_paths).map((ie)=>({field:`destructive_command_protection.allow_paths.${ie}`,message:`project policy adds destructive allow path: ${ie}`})):[],...W.secret_protection.enabled?Du(W.secret_protection.allow_paths,G.secret_protection?.allow_paths).map((ie)=>({field:`secret_protection.allow_paths.${ie}`,message:`project policy adds secret allow path: ${ie}`})):[]]}function Mu(W,G,H){return Object.entries(G??{}).flatMap(([J,oe])=>oe==="off"&&H(J)?[{field:`${W}.${J}`,message:`project policy disables rule ${J}`}]:[])}function Du(W,G){return(G??[]).filter((H)=>!W.includes(H))}var ml=new Set(["standard","strict","paranoid"]),ne={version:1,safety:{level:"standard",overrides:{}},workflow:{worktree_mode:!1},destructive_command_protection:{enabled:!0,overrides:{},allow_paths:[]},secret_protection:{enabled:!0,overrides:{},deny_paths:[],allow_paths:[]},audit:{retention_days:Pu}};function Wu(W,G){let H=gC(u(W,G),W.home),J=O(W,G)?{exists:!1,policy:A(),errors:[]}:Be(h(G.cwd),W.home),oe=pe(J.parsed,W.home),ie=S(n.projectTightenOnly,W.env),fe=H.gui??ne,Re=Object.keys(oe.policy).length>0?te(fe,oe.policy,ie,Vd(fe.safety.level,W.env)):void 0,Te=[...H.errors,...J.errors,...oe.diagnostics],ke=(H.fallback==="defaults"&&Re?"salvaged":H.fallback)??(H.gui?void 0:J.fallback)??(Te.length>0?"salvaged":void 0),Le=oe.policy.safety?.level&&Re?.policy.safety.level===oe.policy.safety.level?"project":H.levelPresent?"user":"default";return{...Re?Xo(Re.policy):H.policy,errors:Te,...ke?{fallback:ke}:{},...J.exists?{policyScopes:{levelScope:Le,weakenings:Re?.weakenings??[],weakeningsIgnored:ie}}:{}}}var dC="project policy audit settings are ignored; audit is user scope only";function pe(W,G){if(!xn(W))return{policy:{},diagnostics:[]};let H=xn(W.safety)?W.safety:{},J=xn(W.workflow)?W.workflow:{},oe=xn(W.destructive_command_protection)?W.destructive_command_protection:{},ie=xn(W.secret_protection)?W.secret_protection:{},fe={...ml.has(H.level)?{level:H.level}:{},...xn(H.overrides)?Nu({overrides:Gu(H.overrides,so,["safety","overrides"],Lr)}):{}},Re={...typeof oe.enabled==="boolean"?{enabled:oe.enabled}:{},...oe.overrides!==void 0?{overrides:os(oe.overrides,Xa,zu,Lr)}:{},...oe.allow_paths!==void 0?{allow_paths:co(oe.allow_paths,al,G,["destructive_command_protection","allow_paths"],Lr)}:{}},Te={...typeof ie.enabled==="boolean"?{enabled:ie.enabled}:{},...ie.overrides!==void 0?{overrides:os(ie.overrides,ol,$u,Lr)}:{},...ie.deny_paths!==void 0?{deny_paths:co(ie.deny_paths,ll,G,["secret_protection","deny_paths"],Lr)}:{},...ie.allow_paths!==void 0?{allow_paths:co(ie.allow_paths,cl,G,["secret_protection","allow_paths"],Lr)}:{}};return{policy:Nu({safety:fe,workflow:typeof J.worktree_mode==="boolean"?{worktree_mode:J.worktree_mode}:{},destructive_command_protection:Re,secret_protection:Te}),diagnostics:W.audit===void 0?[]:[dC]}}function Gu(W,G,H,J){return Object.fromEntries(G.flatMap((oe)=>{let ie=W[oe];if(typeof ie==="boolean")return[[oe,ie]];if(ie!==void 0)J(e([...H,oe],fl));return[]}))}function Nu(W){return Object.fromEntries(Object.entries(W).flatMap((G)=>Object.keys(G[1]).length>0?[G]:[]))}var Lr=()=>{return},fl="must be a boolean",pl="must be an object if provided",Fu=`must be an integer between ${ns} and ${rs}`,zu={path:["destructive_command_protection","overrides"],label:"destructive command"},$u={path:["secret_protection","overrides"],label:"secret protection"},pt=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function ft(W,G){let H=[];return{policy:Bu(W,G,(oe)=>{H.push(oe)}),issues:H}}function k(W,G){return Bu(W,G,Lr)}function Bu(W,G,H){if(!xn(W))return H(e([],"Config must be an object")),A();if(W.version!==1)H(e(["version"],"must be 1"));let J=lo(W.safety,["safety"],["level","overrides"],H),oe=lo(J.overrides,["safety","overrides"],so,H),ie=lo(W.workflow,["workflow"],["worktree_mode"],H),fe=lo(W.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],H),Re=lo(W.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],H),Te=lo(W.audit,["audit"],["retention_days"],H);return Uu(W,pt,[],H),{version:1,safety:{level:uC(J.level,H),overrides:Gu(oe,so,["safety","overrides"],H)},workflow:{worktree_mode:ul(ie.worktree_mode,["workflow","worktree_mode"],!1,H)},destructive_command_protection:{enabled:ul(fe.enabled,["destructive_command_protection","enabled"],!0,H),overrides:os(fe.overrides,Xa,zu,H),allow_paths:co(fe.allow_paths,al,G,["destructive_command_protection","allow_paths"],H)},secret_protection:{enabled:ul(Re.enabled,["secret_protection","enabled"],!0,H),overrides:os(Re.overrides,ol,$u,H),deny_paths:co(Re.deny_paths,ll,G,["secret_protection","deny_paths"],H),allow_paths:co(Re.allow_paths,cl,G,["secret_protection","allow_paths"],H)},audit:{retention_days:mC(Te.retention_days,H)}}}function lo(W,G,H,J){if(W===void 0)return{};if(!xn(W))return J(e(G,pl)),{};return Uu(W,H,G,J),W}function Uu(W,G,H,J){for(let oe of Object.keys(W).filter((ie)=>!G.includes(ie)))J({path:H,message:oe,kind:"unknownKeys"})}function uC(W,G){if(W===void 0)return"standard";if(ml.has(W))return W;return G(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function ul(W,G,H,J){if(typeof W==="boolean")return W;if(W!==void 0)J(e(G,fl));return H}function mC(W,G){if(!(W===void 0||typeof W==="number"&&Number.isInteger(W)&&W>=ns&&W<=rs))G(e(["audit","retention_days"],Fu));return Tu(W)}function os(W,G,H,J){if(W===void 0)return{};if(!xn(W))return J(e(H.path,pl)),{};return Object.fromEntries(Object.entries(W).flatMap(([oe,ie])=>{if(!G.has(oe))return J({path:[...H.path,oe],message:`unknown ${H.label} rule id "${oe}"`,kind:"key"}),[];if(ie==="on"||ie==="off")return[[oe,ie]];return J(e([...H.path,oe],'must be "on" or "off"')),[]}))}function co(W,G,H,J,oe){if(W===void 0)return[];if(!Array.isArray(W))return oe(e(J,"must be an array of paths")),[];return W.flatMap((ie,fe)=>{let Re=G(ie,H);if(Re===null)return[ie];return oe(typeof ie==="string"?an([...J,fe],Re):e([...J,fe],Re)),[]})}function xn(W){return!!W&&typeof W==="object"&&!Array.isArray(W)}function A(){return structuredClone(ne)}function We(W,G){let H=P({safety:ze(W.safety)},G),J=K({destructiveCommandProtectionEnabled:W.destructive_command_protection.enabled,destructiveCommandRuleOverrides:W.destructive_command_protection.overrides},H.capabilities),oe=Object.values(J),ie=oe.filter((fe)=>fe.source!=="catastrophic");return{selectedPreset:W.safety.level,effectiveLevel:H.effectiveLevel,capabilities:H.capabilities,rules:J,counts:{enabled:ie.filter((fe)=>fe.enabled).length,disabled:ie.filter((fe)=>!fe.enabled).length,effectiveCustomizations:oe.filter((fe)=>fe.changesInherited).length}}}function Be(W,G){if(!lC(W))return{exists:!1,policy:A(),errors:[]};try{let H=cC(W,"utf-8");if(!H.trim())return{exists:!0,policy:A(),errors:[`${W}: Config file is empty`],fallback:"defaults"};let J=JSON.parse(H),oe=ft(J,G);if(oe.issues.length===0)return{exists:!0,parsed:J,policy:oe.policy,errors:[]};return{exists:!0,parsed:J,policy:oe.policy,errors:oe.issues.map((ie)=>`${W}: ${pC(ie)}`),fallback:xn(J)?"salvaged":"defaults"}}catch(H){let J=H instanceof Error?H.message:String(H);return{exists:!0,policy:A(),errors:[`${W}: ${H instanceof SyntaxError?"Invalid JSON":J}`],fallback:"defaults"}}}var fC=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[pl,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[fl,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Fu,`not an integer between ${ns} and ${rs}`]]);function pC(W){let G=qa(W.path);if(W.kind==="unknownKeys")return`${G===""?"":`${G}.`}${W.message}: unknown field`;if(W.kind==="key")return`${G}: unknown rule id`;let H=fC.get(W.message)??W.message;return G===""?H:`${G}: ${H}`}function gC(W,G){let H=Be(W,G);if(!H.exists){let J=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!xn(J))return{policy:Xo(A()),errors:[]};let oe=k(J,G);return{policy:Xo(oe),gui:oe,errors:[],levelPresent:Lu(J)}}if(H.parsed===void 0)return{policy:Xo(A()),errors:H.errors,...H.fallback?{fallback:H.fallback}:{}};return{policy:Xo(H.policy),gui:H.policy,errors:H.errors,...H.fallback?{fallback:H.fallback}:{},levelPresent:Lu(H.parsed)}}function Lu(W){let G=xn(W)&&xn(W.safety)?W.safety:{};return ml.has(G.level)}function mt(W){let G=Object.entries(W),H=new Set(G.flatMap(([J,oe])=>oe==="on"?[J]:[]));return[...new Set([...[...Ji].filter((J)=>!H.has(J)),...G.flatMap(([J,oe])=>oe==="off"?[J]:[])])]}function Xo(W){return{safety:ze(W.safety),worktreeMode:W.workflow.worktree_mode,destructiveCommandProtectionEnabled:W.destructive_command_protection.enabled,destructiveCommandRuleOverrides:W.destructive_command_protection.overrides,destructiveCommandAllowPaths:W.destructive_command_protection.allow_paths,secretProtection:{enabled:W.secret_protection.enabled,disabledRules:mt(W.secret_protection.overrides),denyPaths:W.secret_protection.deny_paths,allowPaths:W.secret_protection.allow_paths}}}function ze(W){let G={...W.overrides.fail_closed!==void 0?{failClosed:W.overrides.fail_closed}:{},...W.overrides.paranoid_rm!==void 0?{paranoidRm:W.overrides.paranoid_rm}:{},...W.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:W.overrides.paranoid_interpreters}:{}};return{level:W.level,...Object.keys(G).length>0?{overrides:G}:{}}}function R(W,G){let H=ee(W,G),J=Wu(W,G),oe={rules:H.rules,transparentWrappers:H.transparent_wrappers,commandTools:H.command_tools,safety:J.safety,worktreeMode:J.worktreeMode,destructiveCommandProtectionEnabled:J.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:J.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:J.destructiveCommandAllowPaths,secretProtection:{enabled:J.secretProtection.enabled??!0,disabledRules:J.secretProtection.disabledRules??[],denyPaths:J.secretProtection.denyPaths,allowPaths:J.secretProtection.allowPaths??[]}},ie={...H.userConfig?.overrides,...H.projectConfig?.overrides},fe=Object.freeze(Object.fromEntries(oe.rules.map((Re)=>{let Te=H.rulebooks.find((Le)=>Le.rules.includes(Re.name)),ke=ie[Re.name];return[Re.name,Object.freeze({id:Re.name,...Te?{rulebook:Object.freeze({name:Te.name,version:Te.version}),...CC(Te.spec)?{source:Te.spec}:{}}:{},...ke&&typeof ke==="object"?{override:Object.freeze({type:"reason",reason:ke.reason})}:{}})]})));return Ne(oe,hC(H,J),fe,J.policyScopes)}function Ve(W){if(W.state==="ready")return{state:W.state};return{state:W.state,reason:W.reason}}function hC(W,G){let H=SC(G);if(W.errors.length===0&&W.warnings.length===0&&!H)return;return{diagnostics:[...W.errors,...W.warnings,...G.errors],reason:bC(W.errors.length>0?yC(W.errors):void 0,W.warnings.length>0?hl(W.warnings.join("; ")):void 0,H)}}function yC(W){return`${hl(W.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function SC(W){if(W.errors.length===0)return;let G=W.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${W.errors.join("; ")}. Enforcing ${G}; the invalid values are not active. Fix the policy file manually`}function CC(W){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(W)}function Ne(W,G,H=Object.freeze({}),J){let oe=gl(structuredClone(W)),ie=J?{policyScopes:gl(structuredClone(J))}:{};if(!G)return Object.freeze({state:"ready",policy:oe,diagnostics:Object.freeze([]),ruleMetadata:H,...ie});return Object.freeze({state:"degraded",policy:oe,diagnostics:Object.freeze([...G.diagnostics]),reason:G.reason,ruleMetadata:H,...ie})}function gl(W){if(typeof W!=="object"||W===null)return W;for(let G of Object.values(W))gl(G);return Object.freeze(W)}function bC(...W){return hl(W.filter((G)=>!!G).join("; "))}function hl(W){return/[.!?]$/.test(W)?W:`${W}.`}function qe(W){let G=W.effectiveCapabilities,H=G.fail_closed.enabled,J=G.paranoid_rm.enabled,oe=G.paranoid_interpreters.enabled;return{policy:ku(W.policySnapshot.policy,G),effectiveCapabilities:G,effectiveLevel:Da({failClosed:H,paranoidRm:J,paranoidInterpreters:oe}),strict:H,paranoidRm:J,paranoidInterpreters:oe,worktreeMode:W.worktreeMode??!1}}import{dirname as RA,isAbsolute as _A,join as xA,parse as wA,resolve as AA,sep as PA}from"node:path";function Jo(W,G){if(W!=="powershell")return G[0]?.provenance==="command-substitution";let H=G[0]?.text==="&"||G[0]?.text==="."?1:0,J=G[H]?.provenance;return J!==void 0&&J!=="literal"}var vC=/^[A-Za-z_][A-Za-z0-9_]*=/;function is(W,G){return W?.provenance==="literal"&&!W.quoted&&W.raw===G&&W.text===G}function Qo(W){let G=is(W.words[0],"time")?1:0,H=G===1&&is(W.words[G],"-p")?G+1:G,J=G===1&&is(W.words[H],"--")?H+1:H,oe=is(W.words[J],"!")?J+1:J,ie=W.words.slice(oe).find((fe)=>!vC.test(fe.text));return ie?.provenance==="literal"?ie.text:void 0}var gr=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function ss(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function as(W,G,H){W.push(H),G.reset()}function ls(W){let G=[];return{parts:G,push:(H,J,oe)=>{if(J<=H)return;G.push({raw:W.slice(H,J),span:{start:H,end:J},provenance:oe})}}}function yl(W){let G=W.parts??[{raw:W.raw,span:W.span,provenance:W.provenance}];return{kind:"word",...W,parts:G}}function uo(W,G,H,J,oe,ie,fe){return yl({text:J,raw:W.slice(G,H),span:{start:G,end:H},provenance:oe,quoted:ie,...fe?{parts:fe}:{}})}function Sl(W,G,H){if(G>=H||ju(W[G]??""))return null;let J="",oe=!1,ie=!1,fe=G;while(fe<H&&!ju(W[fe]??"")){let Re=W[fe]??"";if(Re==="'"){oe=!0;let Te=Hu(W,fe+1,H,"'");J+=Te.text,ie||=!Te.closed,fe=Te.next;continue}if(Re==='"'){oe=!0;let Te=Hu(W,fe+1,H,'"');J+=Te.text,ie||=!Te.closed,fe=Te.next;continue}if(Re==="\\"){oe=!0;let Te=W[fe+1];if(!Te||Te===`
|
|
6
|
+
`||Te==="\r"){ie=!0;break}J+=Te,fe+=2;continue}if(Re==="`"||W.startsWith("$(",fe)||W.startsWith("${",fe)||W.startsWith("<(",fe)||W.startsWith(">(",fe))ie=!0;J+=Re,fe++}return{delimiter:J,quoted:oe,next:fe,ambiguous:ie}}function Cl(W,G,H,J){let oe=[],ie=G;for(let fe of J){let Re=ie,Te=!1;while(ie<H){let ke=EC(W,ie,H);if((fe.stripTabs?ke.text.replace(/^\t+/,""):ke.text)===fe.delimiter){fe.attach({body:fe.stripTabs?RC(W.slice(Re,ie)):W.slice(Re,ie),delimiter:fe.delimiter,quotedDelimiter:fe.quotedDelimiter,bodySpan:{start:Re,end:ie},terminatorSpan:{start:ie,end:ke.contentEnd}}),ie=ke.next,Te=!0;break}if(ke.next<=ie)break;ie=ke.next}if(Te)continue;return oe.push({code:"unterminated-heredoc",message:`heredoc delimiter ${fe.delimiter} was not found`}),{next:H,issues:oe,terminated:!1}}return{next:ie,issues:oe,terminated:!0}}function Hu(W,G,H,J){let oe="",ie=G;while(ie<H&&W[ie]!==`
|
|
7
|
+
`&&W[ie]!=="\r"){let fe=W[ie]??"";if(fe===J)return{text:oe,next:ie+1,closed:!0};if(J==='"'&&fe==="\\"&&W[ie+1]){let Re=W[ie+1]??"";oe+=["$","`",'"',"\\"].includes(Re)?Re:`\\${Re}`,ie+=2;continue}oe+=fe,ie++}return{text:oe,next:ie,closed:!1}}function ju(W){return W!=="\r"&&(/[\s;&|<>)]/u.test(W)||W==="`")}function EC(W,G,H){let J=G;while(J<H&&W[J]!==`
|
|
8
|
+
`)J++;let oe=J>=H?H:J+1;return{text:W.slice(G,J),contentEnd:J,next:oe}}function RC(W){return W.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Zu=new Set(["&&","||","|","|&"]),_C=new Set(["!","do","elif","else","if","then","until","while"]);function Xu(W,G){let H={start:0,end:W.length};if(W.length>G.maxInputLength)return{kind:"program",dialect:"posix",source:W,span:H,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${G.maxInputLength} UTF-16 code units`}],nodes:[]};let J={wordsUsed:0,maxWords:G.maxWords,quotedExpansionEnd:1/0},oe=us(W,0,W.length,G,J,0),ie=[...oe.issues,...DC(W,J.quotedExpansionEnd,oe.nodes)?[tm]:[],...OC.test(W)?[em]:[]];return{kind:"program",dialect:"posix",source:W,span:H,status:fs(ie,oe.limited),issues:ie,nodes:oe.nodes}}function us(W,G,H,J,oe,ie,fe){let Re=[],Te=[],ke=ss(),Le=[],Xe=()=>{if(ke.words.length===0&&ke.redirections.length===0)return;let Ze={start:ke.start,end:ke.end},Qe=ke.words.map((et)=>et.text);as(Re,ke,{kind:"command",dialect:"posix",source:W.slice(Ze.start,Ze.end),span:Ze,words:ke.words,redirections:ke.redirections,nested:ke.nested,displayText:Te.length>0&&Re.length===0?W.slice(G,H):Qe.join(" ")})},Ye=G;while(Ye<H){let Ze=W[Ye];if(!Ze)break;if(fe&&Ze===fe)return Xe(),Yu(Re,Te),{nodes:Re,issues:Te,next:Ye+1,closed:!0,limited:!1,pendingHeredocs:Le};if(ti(Ze)){if(Ze.charCodeAt(0)>127)Te.push(em);if(Ze===`
|
|
9
|
+
`||Ze==="\r"){Xe();let Ot=Ze==="\r"&&W[Ye+1]===`
|
|
10
|
+
`?Ye+2:Ye+1,Mt=Re.at(-1);if(Mt?.kind!=="connector"||!Zu.has(Mt.operator))Re.push({kind:"connector",operator:W.slice(Ye,Ot),span:{start:Ye,end:Ot}});if(Le.length>0){let Lt=Cl(W,Ot,H,Le.splice(0));Te.push(...Lt.issues),Ye=Lt.next;continue}Ye=Ot;continue}Ye++;continue}if(Ze==="#"){while(Ye<H&&W[Ye]!==`
|
|
11
|
+
`&&W[Ye]!=="\r")Ye++;continue}let Qe=ke.start===-1?JC(W,Ye,H):void 0;if(Qe){if(vl(Re,Te),ie>=J.maxDepth)return mo(Re,Te,Ye,"depth-limit",J.maxDepth);if(!bl(oe))return mo(Re,Te,Ye,"word-limit",J.maxWords);let Ot=us(W,Qe.braceIndex+1,H,J,oe,ie+1,"}"),Mt=Ot.next,Lt={start:Qe.braceIndex+1,end:Ot.closed?Mt-1:Mt},ht=Vu(W,Lt,Ot);if(Re.push({kind:"function",name:Qe.name,span:{start:Ye,end:Mt},body:ht}),Te.push(...Ot.issues),Ot.pendingHeredocs.length>0||ni(Ot.nodes))Te.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(Le.push(...Ot.pendingHeredocs),Ot.limited)return ds(Re,Te,Ot.next);if(!Ot.closed)Te.push({code:"unclosed-function-body",message:"function body is not closed"});Ye=Mt;continue}let et=ms(W,Ye);if(et){if(Xe(),!lm(Re.at(-1)))Te.push({code:"unexpected-connector",message:`connector ${et} has no preceding command`});Re.push({kind:"connector",operator:et,span:{start:Ye,end:Ye+et.length}}),Ye+=et.length;continue}if(Ze===")"){Xe(),Te.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),Re.push({kind:"unknown",source:Ze,span:{start:Ye,end:Ye+1}}),Ye++;continue}if((Ze==="("||Ze==="{"&&FC(W,Ye,H))&&ke.start===-1){if(vl(Re,Te),ie>=J.maxDepth)return mo(Re,Te,Ye,"depth-limit",J.maxDepth);let Ot=Ze==="("?")":"}",Mt=us(W,Ye+1,H,J,oe,ie+1,Ot),Lt=Mt.next,ht={start:Ye+1,end:Mt.closed?Lt-1:Lt},Wt=Vu(W,ht,Mt);if(Re.push({kind:"group",style:Ze==="("?"subshell":"brace",span:{start:Ye,end:Lt},body:Wt}),Te.push(...Mt.issues),Mt.pendingHeredocs.length>0||ni(Mt.nodes))Te.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(Le.push(...Mt.pendingHeredocs),Mt.limited)return ds(Re,Te,Mt.next);if(!Mt.closed)Te.push({code:Ze==="("?"unclosed-subshell":"unclosed-brace-group",message:`${Ze} group is not closed`});Ye=Lt;continue}let tt=(Ze==="<"||Ze===">")&&W[Ye+1]!=="("?PC(W,Ye):null;if(tt){let Ot=ke.words.at(-1),Mt=Ot&&Ot.span.end===Ye&&/^[0-9]+$/.test(Ot.raw)?Number(Ot.raw):void 0;if(Mt!==void 0)ke.words.pop();let Lt=Mt===void 0?Ye:Ot?.span.start??Ye;ke.start=ke.start===-1?Ye:ke.start;let ht=Ye+tt.length;while(ht<H&&/[ \t]/.test(W[ht]??""))ht++;let Wt=W[ht],Dt=ht>Ye+tt.length&&Wt==="#",Zt=!Wt||ti(Wt)||!!ms(W,ht)||Wt===fe||Wt===")"||Dt||(Wt==="<"||Wt===">")&&W[ht+1]!=="(",Pr=tt==="<<"||tt==="<<-",qt=Pr?Sl(W,ht,H):void 0,Ht=qt?{word:uo(W,ht,qt.next,qt.delimiter,"literal",qt.quoted),nested:[],issues:[],next:qt.next,limited:!1}:!Zt?El(W,ht,H,J,oe,ie):void 0;if(Ht){if(Te.push(...Ht.issues),Ht.limited)return ds(Re,Te,Ht.next);if(!bl(oe))return mo(Re,Te,Ht.next,"word-limit",J.maxWords)}let fn=Ht?.next??Ye+tt.length,nn={kind:"redirection",operator:tt,span:{start:Lt,end:fn},...Mt===void 0?{}:{fd:Mt},...Ht?{target:Ht.word}:{}};if(ke.redirections.push(nn),Pr&&!qt)Te.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if(qt){if(qt.ambiguous||qt.delimiter.length===0)Te.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let rn=ke.nested;Le.push({delimiter:qt.delimiter,quotedDelimiter:qt.quoted,stripTabs:tt==="<<-",attach:(Rn)=>{if(nn.heredoc=Rn,Rn.quotedDelimiter)return;let tr=wC(W,Rn.bodySpan.start,Rn.bodySpan.end,J,oe,ie+1);rn.push(...tr.programs),Te.push(...tr.issues)}})}if(!Pr&&!Ht)Te.push({code:"missing-redirection-target",message:`redirection ${tt} requires a target word`});if(Ht)ke.nested.push(...Ht.nested);ke.end=fn,Ye=fn;continue}let gt=ke.start===-1;if(gt)vl(Re,Te);let _t=El(W,Ye,H,J,oe,ie);if(Te.push(..._t.issues),_t.limited)return ds(Re,Te,_t.next);let yt=BC(ke.words)?KC(W,_t.word,oe.maxWords-oe.wordsUsed,J.maxDepth,J.maxInputLength):void 0;if(yt?.limitCode)return mo(Re,Te,_t.next,yt.limitCode,yt.limitCode==="word-limit"?J.maxWords:yt.limitCode==="depth-limit"?J.maxDepth:J.maxInputLength);let At=yt?.words??[_t.word];for(let Ot of At){if(!bl(oe))return mo(Re,Te,_t.next,"word-limit",J.maxWords);ke.words.push(Ot)}if(ke.start=ke.start===-1?Ye:ke.start,ke.end=_t.next,ke.nested.push(..._t.nested),gt&&cm(_t.word))Xe();Ye=_t.next>Ye?_t.next:Ye+1}return Xe(),Yu(Re,Te),Te.push(...QC(Le)),{nodes:Re,issues:Te,next:Ye,closed:fe===void 0,limited:!1,pendingHeredocs:[]}}function Vu(W,G,H){return{kind:"program",dialect:"posix",source:W.slice(G.start,G.end),span:G,status:fs(H.issues,H.limited),issues:H.issues,nodes:H.nodes}}function El(W,G,H,J,oe,ie){let fe="",Re=G,Te=!1,ke="literal",Le=[],Xe=[],Ye=!1;while(Re<H){let Ze=W[Re],Qe=(Ze==="<"||Ze===">")&&W[Re+1]==="(";if(!Ze||ti(Ze)||(Ze===";"||Ze==="|"||Ze==="&")&&ms(W,Re)||(Ze==="<"||Ze===">")&&!Qe)break;if(Ze===")")break;if(Ze==="'"){Te=!0;let gt=W.indexOf("'",Re+1);if(gt===-1||gt>=H){fe+=W.slice(Re+1,H),Xe.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),Re=H;break}fe+=W.slice(Re+1,gt),Re=gt+1;continue}if(Ze==='"'){Te=!0;let gt=xC(W,Re,H,J,oe,ie);if(fe+=gt.text,Le.push(...gt.nested),Xe.push(...gt.issues),Ye||=gt.limited,ke=ei(ke,gt.provenance),Re=gt.next,Ye)break;continue}if(W.startsWith("$'",Re)){Te=!0;let gt=LC(W,Re+2,H);if(fe+=gt.text,Xe.push(...gt.issues),!gt.closed)Xe.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});Re=gt.next;continue}if(Ze==="\\"){let gt=W[Re+1];if(!gt){Xe.push({code:"trailing-escape",message:"escape has no following character"}),Re++;break}if(gt===`
|
|
12
|
+
`){Re+=2;continue}fe+=gt,Re+=2;continue}if(Gr(W,Re))Xe.push(Wr);let et=Ze==="$"||Ze==="<"||Ze===">"||Ze==="`"?ri(W,Re,H,J,oe,ie):null,tt=et?_l(et,Le,Xe):nm(W,Re,H,J,oe,ie,Le,Xe);if(tt){if(tt.provenance==="variable")fe+=W.slice(Re,tt.next);if(Ye||=tt.limited,ke=ei(ke,tt.provenance),Re=tt.next,Ye)break;continue}if(Ze==="$"){let gt=om(W,Re,H,fe,ke);fe=gt.text,ke=gt.provenance,Re=gt.next;continue}if(Ze==="*"||Ze==="?"||Ze==="[")ke=ei(ke,"glob");fe+=Ze,Re++}return{word:uo(W,G,Re,fe,ke,Te,ke==="literal"?void 0:GC(W,G,Re)),nested:Le,issues:Xe,next:Re,limited:Ye}}function xC(W,G,H,J,oe,ie){let fe="",Re="literal",Te=[],ke=[],Le=!1,Xe=G+1;while(Xe<H){let Ye=W[Xe];if(Ye==='"')return{text:fe,provenance:Re,nested:Te,issues:ke,next:Xe+1,limited:Le};if(Ye==="\\"&&W[Xe+1]){let et=W[Xe+1]??"";if(et===`
|
|
13
|
+
`){Xe+=2;continue}if(et==="\r"&&W[Xe+2]===`
|
|
14
|
+
`){Xe+=3;continue}fe+=["$","`",'"',"\\"].includes(et)?et:`\\${et}`,Xe+=2;continue}if(Gr(W,Xe))ke.push(Wr);let Ze=ri(W,Xe,H,J,oe,ie),Qe=Ze?_l(Ze,Te,ke):nm(W,Xe,H,J,oe,ie,Te,ke);if(Qe){if(Qe.provenance!=="command-substitution")fe+=W.slice(Xe,Qe.next);if(Xe=Qe.next,Le||=Qe.limited,Re=ei(Re,Qe.provenance),Le)return{text:fe,provenance:Re,nested:Te,issues:ke,next:Xe,limited:Le};continue}if(Ye==="$"){let et=om(W,Xe,H,fe,Re);fe=et.text,Re=et.provenance,Xe=et.next;continue}fe+=Ye??"",Xe++}return ke.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:fe,provenance:Re,nested:Te,issues:ke,next:H,limited:Le}}function ri(W,G,H,J,oe,ie){let fe=Qu(W,G);if(!fe)return null;let{length:Re,closing:Te}=fe,ke=Te==="))",Le=Te==="`",Xe=W[G]==="<"||W[G]===">",Ye=xl(W,G+Re,H,Te),Ze=Ye===-1?H:Ye,Qe=Ye===-1?H:Ye+Te.length;if(ie>=J.maxDepth)return{program:XC(W,G+Re,Ze,"depth-limit"),next:Qe,provenance:ke?"arithmetic":"command-substitution"};if(ke){let At=[],Ot=[],Mt=!1,Lt=G+Re;while(Lt<Ze){let ht=ri(W,Lt,Ze,J,oe,ie+1);if(!ht){if(Gr(W,Lt))Ot.push(Wr);Lt++;continue}if(At.push(...ht.program.nodes),Ot.push(...ht.program.issues),Mt||=ht.program.status==="limited",Lt=ht.next,Mt)break}if(Ye===-1)Ot.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:{kind:"program",dialect:"posix",source:W.slice(G+Re,Ze),span:{start:G+Re,end:Ze},status:fs(Ot,Mt),issues:Ot,nodes:At},next:Qe,provenance:"arithmetic"}}let et=us(W,G+Re,Ze,J,oe,ie+1),tt=Ye===-1?[{code:"unclosed-command-substitution",message:`${W.slice(G,G+Re)} substitution is not closed`}]:[],gt=(Le||Xe)&&ni(et.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[],_t=Le&&/\\[\\$`\n]/.test(W.slice(G+Re,Ze))?[NC]:[],yt=[...et.issues,...tt,...gt,..._t];return{program:{kind:"program",dialect:"posix",source:W.slice(G+Re,Ze),span:{start:G+Re,end:Ze},status:fs(yt,et.limited),issues:yt,nodes:et.nodes},next:Qe,provenance:"command-substitution"}}function wC(W,G,H,J,oe,ie){let fe=[],Re=[],Te=G;while(Te<H){let ke=W[Te];if(ke==="\\"){Te+=2;continue}let Le=ke==="$"||ke==="`"?ri(W,Te,H,J,oe,ie):null;if(!Le){if(Gr(W,Te))Re.push(Wr);Te++;continue}if(fe.push(Le.program),TC(W,Te,Le.next)&&IC(Le.program))Re.push(Wr);Te=Le.next}return{programs:fe,issues:Re}}function _l(W,G,H){return G.push(W.program),H.push(...W.program.issues),{provenance:W.provenance,next:W.next,limited:W.program.status==="limited"}}function xl(W,G,H,J){if(J==="`"){for(let Re=G;Re<H;Re++){if(W[Re]==="\\"){Re++;continue}if(W[Re]==="`")return Re}return-1}let oe={single:!1,double:!1},ie=[],fe=[];for(let Re=G;Re<H;Re++){let Te=W[Re];if((Te===`
|
|
15
|
+
`||Te==="\r")&&fe.length>0){let Xe=Te==="\r"&&W[Re+1]===`
|
|
16
|
+
`?Re+2:Re+1,Ye=Cl(W,Xe,H,fe.splice(0));if(!Ye.terminated)return-1;Re=Ye.next-1;continue}let ke=Ju(W,Re,G,H,oe);if(ke!==null){Re=ke;continue}if(!oe.double&&W.startsWith("$((",Re)){let Xe=AC(W,Re+3,H);if(Xe===-1)return-1;Re=Xe+1;continue}if(J===")"&&!oe.double&&Te==="<"&&W[Re+1]==="<"&&W[Re+2]!=="<"){let Xe=W[Re+2]==="-",Ye=Re+(Xe?3:2);while(Ye<H&&/[ \t]/.test(W[Ye]??""))Ye++;let Ze=Sl(W,Ye,H);if(Ze){fe.push({delimiter:Ze.delimiter,quotedDelimiter:Ze.quoted,stripTabs:Xe,attach:()=>{return}}),Re=Ze.next-1;continue}}if(W.startsWith("$(",Re)&&!W.startsWith("$((",Re)){ie.push(oe),oe={single:!1,double:!1},Re++;continue}if(Te==="("&&!oe.double){ie.push(oe),oe={single:!1,double:!1};continue}if(Te!==")"||oe.double)continue;let Le=ie.pop();if(Le){oe=Le;continue}return J==="))"&&W[Re+1]!==")"?-1:Re}return-1}function AC(W,G,H){let J=1,oe={single:!1,double:!1};for(let ie=G;ie<H;ie++){let fe=W[ie],Re=Ju(W,ie,G,H,oe);if(Re!==null){ie=Re;continue}if(W.startsWith("$(",ie)&&!W.startsWith("$((",ie)){J++,ie++;continue}if(fe==="("&&!oe.double)J++;if(fe!==")"||oe.double)continue;if(J--,J===0)return W[ie+1]===")"?ie:-1}return-1}function Ju(W,G,H,J,oe){let ie=W[G];if(ie==="\\"&&!oe.single)return G+1;if(!oe.double&&ie==="'")oe.single=!oe.single;if(!oe.single&&ie==='"')oe.double=!oe.double;if(oe.single)return G;if(oe.double||ie!=="#"||!eb(W,G,H))return null;let fe=G;while(fe+1<J&&W[fe+1]!==`
|
|
17
|
+
`&&W[fe+1]!=="\r")fe++;return fe}function ms(W,G){let H=W[G];if(H===";")return";";if(H==="&")return W[G+1]==="&"?"&&":"&";if(H==="|")return W[G+1]==="|"?"||":W[G+1]==="&"?"|&":"|";return null}function PC(W,G){let H=W[G];if(H===">"){if(W[G+1]===">")return">>";if(W[G+1]==="&")return">&";return W[G+1]==="|"?">|":">"}if(H!=="<")return null;if(W.startsWith("<<<",G))return"<<<";if(W.startsWith("<<-",G))return"<<-";if(W[G+1]==="<")return"<<";if(W[G+1]==="&")return"<&";if(W[G+1]===">")return"<>";return"<"}function ti(W){let G=W.charCodeAt(0);if(G===32||G>=9&&G<=13)return!0;if(G<128)return!1;return/\s/u.test(W)}var Wr=Object.freeze({code:"unsupported-function-substitution",message:"${ list; } function substitutions run in the current shell and cannot be analyzed"});function Gr(W,G){if(W[G]!=="$")return!1;let H=Ku(W,G+1);if(W[H]!=="{")return!1;let J=W[Ku(W,H+1)]??"";return J==="|"||ti(J)}function TC(W,G,H){for(let J=W.indexOf("$",G);J!==-1&&J<H;J=W.indexOf("$",J+1))if(Gr(W,J))return!0;return!1}function IC(W){return W?.status==="limited"||(W?.issues??[]).some((G)=>G.code===Wr.code)}function Ku(W,G){let H=G;while(W.startsWith("\\\n",H)||W.startsWith(`\\\r
|
|
18
|
+
`,H))H+=W[H+1]==="\r"?3:2;return H}function Qu(W,G){if(W.startsWith("$((",G))return{length:3,closing:"))"};if(W.startsWith("$(",G)||W.startsWith("<(",G)||W.startsWith(">(",G))return{length:2,closing:")"};return W[G]==="`"?{length:1,closing:"`"}:null}var kC=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"}),OC=/[\v\f\r]/,em=Object.freeze({code:"unsupported-blank",message:"a vertical tab, form feed, carriage return or Unicode space is part of a word in bash and zsh, not a separator"}),tm=Object.freeze({code:"unsupported-parameter-expansion",message:"a line continuation inside ${ }, or a quote or backslash inside ${ } with a substitution in or after it, cannot be analyzed"}),MC=/\$\(|`|[<>]\(/g;function DC(W,G,H){let J=Rl(H);return[...W.slice(G).matchAll(MC)].some((oe)=>{let ie=G+oe.index;return!J.some((fe)=>ie>=fe.start&&ie<fe.end)})}function Rl(W){return W.flatMap((G)=>{if(G.kind==="command")return[...G.redirections.flatMap((H)=>H.heredoc?[H.heredoc.bodySpan]:[]),...G.nested.flatMap((H)=>Rl(H.nodes))];return G.kind==="group"||G.kind==="function"?Rl(G.body.nodes):[]})}var NC=Object.freeze({code:"unsupported-backtick-escape",message:"a backslash escape inside backticks changes the command the shell runs and cannot be analyzed"});function nm(W,G,H,J,oe,ie,fe,Re){if(W[G]!=="$"||W[G+1]!=="{")return null;let Te=ps(W,G+2,H),ke=Te.close===-1?H:Te.close+1;if(Te.close===-1)Re.push(kC);if(Te.quoted&&Te.substitutions.length>0||Te.continued)Re.push(tm);if(Te.quoted)oe.quotedExpansionEnd=Math.min(oe.quotedExpansionEnd,ke);let Le=Te.substitutions.some((Xe)=>{if(Gr(W,Xe))return Re.push(Wr),!1;let Ye=ri(W,Xe,ke,J,oe,ie);return Ye!==null&&_l(Ye,fe,Re).limited});return{provenance:"variable",next:ke,limited:Le}}function ps(W,G,H){let J=[],oe=!1,ie=!1,fe=1,Re=G;while(Re<H){let Te=W[Re];if(Te==="$"&&Gr(W,Re))J.push(Re);if(Te==="\\"||Te==="'"||Te==='"'){oe=!0,ie||=Te==="\\"&&W[Re+1]===`
|
|
19
|
+
`,Re+=Te==="\\"?2:1;continue}let ke=Qu(W,Re);if(ke){J.push(Re);let Le=xl(W,Re+ke.length,H,ke.closing);if(Le===-1)break;Re=Le+ke.closing.length;continue}if(Te==="$"&&W[Re+1]==="{"){fe++,Re+=2;continue}if(Te==="}"&&--fe===0)return{close:Re,substitutions:J,quoted:oe,continued:ie};Re++}return{close:-1,substitutions:J,quoted:oe,continued:ie}}function rm(W,G,H){if(W[G+1]==="{"){let oe=ps(W,G+2,H).close;return oe===-1?H:oe+1}if(W[G+1]==="$")return G+2;let J=G+1;while(J<H&&/[A-Za-z0-9_?@#!*-]/.test(W[J]??""))J++;return J===G+1?G+1:J}function LC(W,G,H){let J="",oe=[],ie=G;while(ie<H){let fe=W[ie];if(fe==="'")return{text:J,next:ie+1,closed:!0,issues:oe};if(fe!=="\\"){J+=fe??"",ie++;continue}let Re=WC(W,ie+1,H);if(J+=Re.text,Re.invalidCodePoint!==void 0)oe.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${Re.invalidCodePoint}`});ie=Re.next}return{text:J,next:H,closed:!1,issues:oe}}function WC(W,G,H){let J=W[G];if(!J||G>=H)return{text:"\\",next:G};let oe=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
|
|
20
|
+
`],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(oe.has(J))return{text:oe.get(J)??J,next:G+1};if(J==="x")return cs(W,G+1,H,16,2,G+1);if(J==="u")return cs(W,G+1,H,16,4,G+1);if(J==="U")return cs(W,G+1,H,16,8,G+1);if(/[0-7]/.test(J))return cs(W,G,H,8,3,G+1);return{text:J,next:G+1}}function cs(W,G,H,J,oe,ie){let fe=J===16?/[0-9a-fA-F]/:/[0-7]/,Re="",Te=G;while(Te<H&&Re.length<oe&&fe.test(W[Te]??""))Re+=W[Te],Te++;if(!Re)return{text:W[ie-1]??"",next:ie};let ke=Number.parseInt(Re,J);return ke>1114111||ke>=55296&&ke<=57343?{text:"�",next:Te,invalidCodePoint:ke}:{text:String.fromCodePoint(ke),next:Te}}function fs(W,G=!1){if(G)return"limited";if(W.some((H)=>H.code==="invalid-ansi-c-code-point"||H.code==="missing-heredoc-delimiter"||H.code==="ambiguous-heredoc-delimiter"||H.code==="unterminated-heredoc"||H.code==="unsupported-heredoc-context"||H.code==="unsupported-function-substitution"||H.code==="unsupported-backtick-escape"||H.code==="unclosed-parameter-expansion"||H.code==="unsupported-parameter-expansion"||H.code==="unsupported-blank"))return"invalid";return W.length>0?"partial":"complete"}function om(W,G,H,J,oe){let ie=rm(W,G,H);return{text:J+W.slice(G,ie),provenance:ei(oe,"variable"),next:ie}}function GC(W,G,H){let J=ls(W),oe=G,ie=!1,fe=!1,Re=G;while(Re<H){let Te=W[Re];if(Te==="\\"&&!ie){Re+=2;continue}if(!fe&&Te==="'"){ie=!ie,Re++;continue}if(!ie&&Te==='"'){fe=!fe,Re++;continue}if(ie){Re++;continue}let ke=W.startsWith("$((",Re),Le=W.startsWith("$(",Re)&&!ke,Xe=!fe&&(W.startsWith("<(",Re)||W.startsWith(">(",Re)),Ye=Te==="`";if(ke||Le||Xe||Ye){let Ze=ke?3:Ye?1:2,Qe=ke?"))":Ye?"`":")",et=xl(W,Re+Ze,H,Qe),tt=et===-1?H:et+Qe.length;J.push(oe,Re,"literal"),J.push(Re,tt,ke?"arithmetic":"command-substitution"),Re=tt,oe=tt;continue}if(Te==="$"){let Ze=rm(W,Re,H);if(Ze>Re+1){J.push(oe,Re,"literal"),J.push(Re,Ze,"variable"),Re=Ze,oe=Ze;continue}}if(!fe&&(Te==="*"||Te==="?"||Te==="[")){J.push(oe,Re,"literal"),J.push(Re,Re+1,"glob"),Re++,oe=Re;continue}Re++}return J.push(oe,H,"literal"),J.parts}function ei(W,G){if(G==="command-substitution"||W==="command-substitution")return"command-substitution";if(G==="arithmetic"||W==="arithmetic")return"arithmetic";if(G==="variable"||W==="variable")return"variable";if(G==="glob"||W==="glob")return"glob";return W}function FC(W,G,H){return G+1>=H||ti(W[G+1]??"")||ms(W,G+1)!==null}var zC=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),$C=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function BC(W){let G=0;while(G<=W.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(W[G]?.text??""))G++;if(G===W.length)return!0;let H=UC(W,G);if(H===void 0||H===null)return!1;G=H}return!1}function UC(W,G){let H=W[G]?.text.toLowerCase();if(H==="command")return HC(W,G);if(H==="env")return jC(W,G);if(H==="sudo")return VC(W,G);return}function HC(W,G){if(W[G+1]?.text==="-v")return null;for(let H=G+1;H<W.length;H++){let J=W[H]?.text??"";if(J==="--")return H+1;if(J==="-p"||J==="-v"||J==="-V"||/^-[pvV]+$/.test(J))continue;return H}return W.length}function jC(W,G){for(let H=G+1;H<W.length;H++){let J=W[H]?.text??"";if(J==="--")return H+1;if(zC.has(J)){if(W[H+1]===void 0)return null;H++;continue}if(J.startsWith("-u=")||J.startsWith("--unset=")||J.startsWith("-C")&&J.length>2||J.startsWith("--chdir=")||J.startsWith("-S")&&J.length>2||J.startsWith("--split-string=")||J.startsWith("-P"))continue;if(J.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(J))continue;return H}return W.length}function VC(W,G){for(let H=G+1;H<W.length;H++){let J=W[H]?.text??"";if(J==="--")return H+1;if($C.has(J)){if(W[H+1]===void 0)return null;H++;continue}if(J.startsWith("-"))continue;return H}return W.length}function im(W,G,H,J){if(W.provenance!=="literal"||!W.raw.includes("{"))return;let oe=sm(W.raw,G,H,J,!0);if(!oe)return;if("limited"in oe)return{limited:!0};let ie=oe.values.map((fe)=>am(fe,H));if(ie.some((fe)=>fe===null))return{limited:!0};return{words:[...new Set(ie.filter((fe)=>fe!==null&&fe!==""))]}}function KC(W,G,H,J,oe){if(G.provenance!=="literal"||!G.raw.includes("{"))return;let ie=sm(G.raw,H,J,oe,!1);if(!ie)return;if("limited"in ie){if(ie.limited==="expansions")return{limitCode:"depth-limit"};return{limitCode:ie.limited==="length"?"brace-expansion-limit":"word-limit"}}let fe=ie.values.map((Re)=>am(Re,J));if(fe.some((Re)=>Re===null))return;return{words:fe.filter((Re)=>Re!==null&&Re!=="").map((Re)=>uo(W,G.span.start,G.span.end,Re,"literal",!1))}}function sm(W,G,H,J,oe){let ie=[W],fe=W.length,Re=0;while(!0){let Te=ie.findIndex((Ze)=>qu(Ze,oe));if(Te===-1)break;if(++Re>H)return{limited:"expansions"};let ke=ie[Te]??"",Le=qu(ke,oe);if(!Le||Le.kind==="range")return{limited:"expansions"};let Xe=Le.start+ke.length-Le.end,Ye=Le.alternatives.reduce((Ze,Qe)=>Ze+Xe+Qe.length,0);if(fe-ke.length+Ye>J)return{limited:"length"};if(ie.length-1+Le.alternatives.length>G)return{limited:"words"};ie.splice(Te,1,...qC(ke,Le)),fe+=Ye-ke.length}return Re===0?void 0:{values:ie}}function qu(W,G){let H=[],J,oe=null,ie=!1;for(let fe=0;fe<W.length;fe++){let Re=W[fe];if(ie){ie=!1;continue}if(Re==="\\"&&oe!=="'"){ie=!0;continue}if(Re===oe){oe=null;continue}if(oe===null&&(Re==="'"||Re==='"')){oe=Re;continue}if(oe!==null)continue;if(Re==="{"){H.push({start:fe,commas:[]});continue}if(Re===","&&H.length>0){H.at(-1)?.commas.push(fe);continue}if(Re!=="}"||H.length===0)continue;let Te=H.pop();if(!Te)continue;let ke=Te.commas.length>0?{kind:"alternatives",start:Te.start,end:fe+1,commas:Te.commas}:G&&ZC(W.slice(Te.start+1,fe))?{kind:"range",start:Te.start,end:fe+1}:void 0;if(ke&&(!J||ke.start<J.start))J=ke}if(!J||J.kind==="range")return J;return{kind:J.kind,start:J.start,end:J.end,alternatives:YC(W,J)}}function qC(W,G){return G.alternatives.map((H)=>`${W.slice(0,G.start)}${H}${W.slice(G.end)}`)}function YC(W,G){let H=[G.start,...G.commas,G.end-1];return H.slice(0,-1).map((J,oe)=>W.slice(J+1,H[oe+1]))}function ZC(W){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(W)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(W)}function am(W,G){let H=`x${W}`,J=El(H,0,H.length,{maxInputLength:H.length,maxWords:1,maxDepth:G},{wordsUsed:0,maxWords:1,quotedExpansionEnd:1/0},0);if(J.limited||J.issues.length>0||J.next!==H.length||J.word.provenance!=="literal")return null;return J.word.text.slice(1)}function XC(W,G,H,J){return{kind:"program",dialect:"posix",source:W.slice(G,H),span:{start:G,end:H},status:"limited",issues:[{code:J,message:"command structure exceeds parser limit"}],nodes:[]}}function mo(W,G,H,J,oe){return{nodes:W,issues:[...G,{code:J,message:`command structure exceeds parser limit ${oe}`}],next:H,closed:!1,limited:!0,pendingHeredocs:[]}}function ds(W,G,H){return{nodes:W,issues:G,next:H,closed:!1,limited:!0,pendingHeredocs:[]}}function bl(W){return W.wordsUsed++,W.wordsUsed<=W.maxWords}function JC(W,G,H){let J=W.slice(G,H),oe=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(J)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(J),ie=oe?.[1];if(!oe||!ie)return;return{name:ie,braceIndex:G+oe[0].lastIndexOf("{")}}function ni(W){return W.some((G)=>{if(G.kind==="command")return G.redirections.some((H)=>H.heredoc)||G.nested.some((H)=>ni(H.nodes));return(G.kind==="group"||G.kind==="function")&&ni(G.body.nodes)})}function QC(W){return W.map((G)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${G.delimiter} was not found`}))}function lm(W){return W?.kind==="command"||W?.kind==="group"||W?.kind==="function"}function Yu(W,G){let H=W.at(-1);if(H?.kind!=="connector"||!Zu.has(H.operator))return;G.push({code:"missing-command-after-connector",message:`connector ${H.operator} requires a following command`})}function cm(W){return W?.provenance==="literal"&&!W.quoted&&W.raw===W.text&&_C.has(W.text)}function vl(W,G){let H=W.at(-1);if(!lm(H))return;if(H?.kind==="command"&&cm(H.words[0]))return;G.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function eb(W,G,H){return G===H||/[\s;&|()]/u.test(W[G-1]??"")}var um=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item","foreach-object","where-object"]),tb=new Set(["gc","cat","type","cp","mv","rm"]),mm=["-rec","-for","-path","-literalpath","-whatif"],nb=/^\$env:\w/i,rb=/^(?:\$\{?\w+\}?|~)\\./;function fm(W,G){let H=W.toLowerCase().replaceAll("`","");if(![...um].some((oe)=>H.includes(oe))&&!(H.includes("rm")&&mm.some((oe)=>H.includes(oe)))&&!H.includes("<#")&&!ob(H))return!1;let J=Tl(W,G);if(pm(J))return!1;return J.issues.some((oe)=>oe.code==="unclosed-block-comment"||oe.code==="comment-depth-limit")||Pl(J).some(ib)}function pm(W){return W.nodes.some((G)=>{if(G.kind==="group")return pm(G.body);if(G.kind!=="command")return!1;return G.redirections.some((H)=>H.operator==="<<")})}function ob(W){if(W.includes("$env:"))return!0;return W.includes("\\")&&(W.includes("$")||W.includes("~"))}function ib(W){let G=W[0]==="&"||W[0]==="."?1:0,H=W[G]?.toLowerCase();if(H&&um.has(H))return!0;let J=W.slice(G+1);if(H&&tb.has(H)&&J.some(sb))return!0;if(H!=="rm")return!1;return J.some((oe)=>{let ie=oe.toLowerCase().split(":",1)[0]??"";return mm.some((fe)=>ie.startsWith(fe))})}function sb(W){return nb.test(W)||rb.test(W)}function Tl(W,G){let H={start:0,end:W.length};if(W.length>G.maxInputLength)return{kind:"program",dialect:"powershell",source:W,span:H,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${G.maxInputLength} UTF-16 code units`}],nodes:[]};let J=Il(W,0,W.length,G,0);return{kind:"program",dialect:"powershell",source:W,span:H,status:ub(J.issues,J.limited),issues:J.issues,nodes:J.nodes}}function Il(W,G,H,J,oe,ie=!1){let fe=[],Re=[],Te=ss(),ke=0,Le=!1,Xe=()=>{if(Te.words.length===0&&Te.redirections.length===0)return;let Ze={start:Te.start,end:Te.end};as(fe,Te,{kind:"command",dialect:"powershell",source:W.slice(Ze.start,Ze.end),span:Ze,words:Te.words,redirections:Te.redirections,nested:Te.nested,displayText:Te.words.map((Qe)=>Qe.text).join(" ")})},Ye=G;while(Ye<H){let Ze=W[Ye];if(!Ze)break;if(ie&&Ze==="}")return Xe(),{nodes:fe,issues:Re,next:Ye+1,closed:!0,words:ke,limited:Le};let Qe=db(W,Ye,H,J.maxDepth);if(Qe){if(Qe.issue)Re.push(Qe.issue);if(Qe.limited)return Xe(),{nodes:fe,issues:Re,next:Qe.next,closed:!1,words:ke,limited:!0};Ye=Qe.next;continue}if(/\s/.test(Ze)){if(Ze==="\r"||Ze===`
|
|
21
|
+
`){Xe();let gt=Ze==="\r"&&W[Ye+1]===`
|
|
22
|
+
`?Ye+2:Ye+1;fe.push(wl(W,Ye,gt)),Ye=gt;continue}Ye++;continue}let et=ym(W,Ye);if(et){Xe(),fe.push(wl(W,Ye,Ye+et.length)),Ye+=et.length;continue}if(Ze==="{"){if(Xe(),oe>=J.maxDepth)return Re.push(hm(J.maxDepth)),{nodes:fe,issues:Re,next:H,closed:!1,words:ke,limited:!0};let gt=Il(W,Ye+1,H,J,oe+1,!0),_t=gt.closed?gt.next-1:gt.next,yt={kind:"program",dialect:"powershell",source:W.slice(Ye+1,_t),span:{start:Ye+1,end:_t},status:gt.limited?"limited":gt.issues.length>0?"partial":"complete",issues:gt.issues,nodes:gt.nodes};if(fe.push({kind:"group",style:"brace",span:{start:Ye,end:gt.next},body:yt}),Re.push(...gt.issues),!gt.closed)Re.push({code:"unclosed-script-block",message:"PowerShell script block is not closed"});ke+=gt.words,Le||=gt.limited,Ye=gt.next;continue}if(Ze==="}"){Xe(),fe.push(wl(W,Ye,Ye+1)),Ye++;continue}if(Ze===">"||Ze==="<"){Te.start=Te.start===-1?Ye:Te.start;let gt=W[Ye+1]===Ze?Ye+2:Ye+1,_t=gt;while(/[ \t]/.test(W[_t]??""))_t++;let yt=_t<H?dm(W,_t,H,J,oe):void 0,At=yt?.next??gt;if(Te.redirections.push({kind:"redirection",operator:W.slice(Ye,gt),span:{start:Ye,end:At},...yt?{target:yt.word}:{}}),yt)Re.push(...yt.issues),Te.nested.push(...yt.nested),ke+=yt.words,Le||=yt.limited;Te.end=At,Ye=At;continue}if(Ze===","){Te.start=Te.start===-1?Ye:Te.start,Te.words.push(yl({text:",",raw:",",span:{start:Ye,end:Ye+1},provenance:"literal",quoted:!1})),Te.end=++Ye;continue}let tt=dm(W,Ye,H,J,oe);if(Te.start=Te.start===-1?Ye:Te.start,Te.end=tt.next,Te.words.push(tt.word),Re.push(...tt.issues),Te.nested.push(...tt.nested),ke+=1+tt.words,Le||=tt.limited,ke>J.maxWords)return Re.push({code:"word-limit",message:`command exceeds ${J.maxWords} words`}),Xe(),{nodes:fe,issues:Re,next:tt.next,closed:!1,words:ke,limited:!0};Ye=tt.next>Ye?tt.next:Ye+1}return Xe(),{nodes:fe,issues:Re,next:Ye,closed:!ie,words:ke,limited:Le}}function dm(W,G,H,J,oe){let ie="",fe="literal",Re=!1,Te=[],ke=[],Le=0,Xe=!1,Ye=(Qe)=>{let et=ab(W,Qe,H,J,oe);return ie+=W.slice(Qe,et.next),ke.push(et.program),Te.push(...et.program.issues),Le+=Al(et.program),Xe||=et.program.status==="limited",fe="command-substitution",et.next},Ze=G;while(Ze<H){let Qe=W[Ze];if(!Qe||/\s/.test(Qe)||ym(W,Ze)||Qe===">"||Qe==="<"||Qe==="#")break;if(Qe===",")break;if(Qe==="`"){let et=W[Ze+1];if(!et){Te.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),Ze++;break}ie+=et,Ze+=2;continue}if(W.startsWith("$(",Ze)){Ze=Ye(Ze);continue}if(Qe==="'"){Re=!0,Ze++;let et=!1;while(Ze<W.length){if(W[Ze]==="'"&&W[Ze+1]==="'"){ie+="'",Ze+=2;continue}if(W[Ze]==="'"){et=!0,Ze++;break}ie+=W[Ze]??"",Ze++}if(!et)Te.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(Qe==='"'){Re=!0,Ze++;let et=!1;while(Ze<H){let tt=W[Ze];if(tt==="`"&&W[Ze+1]){ie+=W[Ze+1],Ze+=2;continue}if(tt==='"'){et=!0,Ze++;break}if(W.startsWith("$(",Ze)){Ze=Ye(Ze);continue}if(tt==="$")fe=W[Ze+1]==="("?"command-substitution":"variable";ie+=tt??"",Ze++}if(!et)Te.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(Qe==="$")fe=W[Ze+1]==="("?"command-substitution":"variable";if(Qe==="@"&&Ze===G)fe="variable";ie+=Qe,Ze++}return{word:uo(W,G,Ze,ie,fe,Re,fe==="literal"?void 0:lb(W,G,Ze)),next:Ze,issues:Te,nested:ke,words:Le,limited:Xe}}function ab(W,G,H,J,oe){let ie=gm(W,G+2,H),fe=ie===-1?H:ie,Re=ie===-1?H:ie+1;if(oe>=J.maxDepth)return{program:{kind:"program",dialect:"powershell",source:W.slice(G+2,fe),span:{start:G+2,end:fe},status:"limited",issues:[hm(J.maxDepth)],nodes:[]},next:Re};let Te=Il(W,G+2,fe,J,oe+1),ke=ie===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:{kind:"program",dialect:"powershell",source:W.slice(G+2,fe),span:{start:G+2,end:fe},status:Te.limited?"limited":Te.issues.length+ke.length>0?"partial":"complete",issues:[...Te.issues,...ke],nodes:Te.nodes},next:Re}}function gm(W,G,H){let J=1,oe=!1,ie=!1;for(let fe=G;fe<H;fe++){let Re=W[fe];if(Re==="`"){fe++;continue}if(!ie&&Re==="'"){if(oe&&W[fe+1]==="'"){fe++;continue}oe=!oe;continue}if(!oe&&Re==='"'){ie=!ie;continue}if(oe)continue;if(W.startsWith("$(",fe)){J++,fe++;continue}if(!ie&&Re==="(")J++;if(Re!==")")continue;if(J--,J===0)return fe}return-1}function Al(W){let G=0;for(let H of W.nodes){if(H.kind==="group")G+=Al(H.body);if(H.kind==="command"){G+=H.words.length;for(let J of H.nested)G+=Al(J)}}return G}function lb(W,G,H){let J=ls(W),oe=G,ie=!1,fe=G;while(fe<H){let Re=W[fe];if(Re==="`"){fe+=2;continue}if(Re==="'"){if(ie&&W[fe+1]==="'"){fe+=2;continue}ie=!ie,fe++;continue}if(ie){fe++;continue}if(W.startsWith("$(",fe)){let Te=gm(W,fe+2,H),ke=Te===-1?H:Te+1;J.push(oe,fe,"literal"),J.push(fe,ke,"command-substitution"),fe=ke,oe=ke;continue}if(Re==="$"||Re==="@"&&fe===G){let Te=cb(W,fe+1,H);J.push(oe,fe,"literal"),J.push(fe,Te,"variable"),fe=Te,oe=Te;continue}fe++}return J.push(oe,H,"literal"),J.parts}function cb(W,G,H){if(W[G]==="{"){let oe=W.indexOf("}",G+1);return oe===-1||oe>=H?H:oe+1}let J=G;while(J<H&&/[A-Za-z0-9_:?]/.test(W[J]??""))J++;return J}function hm(W){return{code:"depth-limit",message:`command structure exceeds parser limit ${W}`}}function Pl(W){return W.nodes.flatMap((G)=>{if(G.kind==="group")return Pl(G.body);if(G.kind!=="command")return[];return[[...G.words,...G.redirections.flatMap((H)=>H.target?[H.target]:[])].sort((H,J)=>H.span.start-J.span.start).filter((H)=>H.text!==""&&H.raw!==",").map((H)=>H.text),...G.nested.flatMap(Pl)]})}function ym(W,G){for(let H of["&&","||",";","|"])if(W.startsWith(H,G))return H;return null}function db(W,G,H,J){if(W[G]==="#"&&W[G+1]!==">"){let fe=G+1;while(fe<H&&W[fe]!=="\r"&&W[fe]!==`
|
|
23
|
+
`)fe++;return{next:fe,limited:!1}}if(!W.startsWith("<#",G))return null;let oe=1,ie=G+2;while(ie<H){if(W.startsWith("<#",ie)){if(oe++,oe>J)return{next:H,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${J}`},limited:!0};ie+=2;continue}if(W.startsWith("#>",ie)){if(oe--,ie+=2,oe===0)return{next:ie,limited:!1};continue}ie++}return{next:H,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function ub(W,G){if(G)return"limited";if(W.some((H)=>H.code==="unclosed-block-comment"))return"invalid";return W.length>0?"partial":"complete"}function wl(W,G,H){return{kind:"connector",operator:W.slice(G,H),span:{start:G,end:H}}}function y(W,G="auto",H=gr){if(G==="powershell"||G==="auto"&&fm(W.slice(0,H.maxInputLength),H))return Tl(W,H);return Xu(W,H)}function t(W){return W.provenance==="command-substitution"?W.raw:W.text}function re(W,G){return W==="posix"?G:Qt(G.map((H)=>H.text))}function fo(W,G){return W&&W.provenance!=="unknown"?W.provenance==="literal":!/[$`*?[\]]/.test(G)}function Qt(W){return W.map((G)=>({kind:"word",text:G,raw:G,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function kl(W,G){return{value:W,work:G}}function Tt(W,G){if(W.work)W.work.units=Math.min(Number.MAX_SAFE_INTEGER,W.work.units+1);return W.value[G]}function tn(W){return W.value.length}function oi(W,G,H=1){if(W)W.units=Math.min(Number.MAX_SAFE_INTEGER,W.units+G.length*H)}function wn(W,G){oi(W,G)}function Fr(W){if(!W)return!1;let G=W.charCodeAt(0);return G>=48&&G<=57||G>=65&&G<=90||G===95||G>=97&&G<=122}function Xt(W){if(!W)return!1;let G=W.charCodeAt(0);return G===9||G===10||G===11||G===12||G===13||G===32||G===160||G===65279||G===5760||G>=8192&&G<=8202||G===8232||G===8233||G===8239||G===8287||G===12288}function Ol(W){return W===`
|
|
24
|
+
`||W==="\r"||W==="\u2028"||W==="\u2029"}function Jt(W,G,H){if(G+H.length>tn(W))return!1;for(let J=0;J<H.length;J++)if(Tt(W,G+J)!==H[J])return!1;return!0}function or(W,G,H){return!Fr(Tt(W,G-1))&&Jt(W,G,H)&&!Fr(Tt(W,G+H.length))}function ir(W,G){return Fr(Tt(W,G-1))!==Fr(Tt(W,G))}function dn(W){return W===`
|
|
25
|
+
`||W===";"||W==="&"||W==="|"}function po(W){return W==="|"||W===";"}function gs(W,G,H){let J=kl(W,H);if(G==="rm")return mb(J);if(G==="dd")return pb(J);return Rm(J,!0)}function hs(W,G,H){let J=kl(W,H);if(G==="rm")return gb(J);if(G==="reset-hard")return vm(J,"--ha","rd");if(G==="reset-merge")return vm(J,"--me","rge");if(G==="clean")return Cb(J);if(G==="checkout")return vb(J);if(G==="push-force")return Eb(J);if(G==="push-refspec")return Rb(J);if(G==="push-delete")return _b(J);if(G==="branch")return xb(J);if(G==="tag")return Pb(J);if(G==="restore")return Tb(J);return Rm(J,!1)}function mb(W){let G=!1,H=!1,J=!1,oe=-1;for(let ie=0;ie<=tn(W);ie++){let fe=Tt(W,ie);if(!G){let Te=Tt(W,ie+2);if(or(W,ie,"rm")&&Xt(Te)&&Te!==`
|
|
26
|
+
`)G=!0,ie++;continue}let Re=fb(W,ie);if(fe===`
|
|
27
|
+
`||Re!==-1){if(G=!1,H=!1,J=!1,oe=-1,Re!==-1)ie=Re-1;continue}if(fe===";"||fe==="&"||fe==="|"||ie===tn(W)){if(oe>=0){let Te=Sm(W,oe,ie);H||=Te.recursive,J||=Te.force}if(H&&J)return!0;G=!1,H=!1,J=!1,oe=-1;continue}if(Xt(fe)){if(oe<0)continue;if(Jt(W,oe,"--")&&ie-oe===2){G=!1,H=!1,J=!1,oe=-1;continue}let Te=Sm(W,oe,ie);if(H||=Te.recursive,J||=Te.force,H&&J)return!0;oe=-1;continue}if(oe<0)oe=ie}return!1}function fb(W,G){if(Tt(W,G)!=="\\"||Tt(W,G-1)==="\\")return-1;if(Jt(W,G,String.raw`\n`))return G+2;if(Jt(W,G,String.raw`\x0a`)||Jt(W,G,String.raw`\x0A`))return G+5;if(Jt(W,G,String.raw`\u000a`)||Jt(W,G,String.raw`\u000A`))return G+7;return Jt(W,G,String.raw`\012`)?G+4:-1}function Sm(W,G,H){if(Cm(W,G,H,"recursive"))return{recursive:!0,force:!1};if(Cm(W,G,H,"force"))return{recursive:!1,force:!0};if(Tt(W,G)!=="-"||Tt(W,G+1)==="-")return{recursive:!1,force:!1};let J=!1,oe=!1;for(let ie=G+1;ie<H;ie++){let fe=Tt(W,ie);J||=fe==="r"||fe==="R",oe||=fe==="f"||fe==="F"}return{recursive:J,force:oe}}function Cm(W,G,H,J){let oe=H-G-2;if(oe<1||oe>J.length||!Jt(W,G,"--"))return!1;for(let ie=0;ie<oe;ie++)if(Tt(W,G+ie+2)!==J[ie])return!1;return!0}function pb(W){let G=!1;for(let H=0;H<tn(W);H++){if(dn(Tt(W,H))){G=!1;continue}if(or(W,H,"dd")){G=!0,H++;continue}if(!G||!or(W,H,"of")||!Jt(W,H,"of=/dev/"))continue;let J=H+8;if(J<tn(W)&&!Xt(Tt(W,J))&&Tt(W,J)!=="'"&&Tt(W,J)!=='"')return!0}return!1}function gb(W){let G=!1,H=!1,J=!1;for(let oe=0;oe<=tn(W);){let ie=Tt(W,oe);if(oe===tn(W)||dn(ie)){G=!1,H=!1,J=!1,oe++;continue}let fe=yb(W,oe);if(fe>=0){if(hb(W,fe))return!0;let Re=fe,Te=!1;while(Xt(Tt(W,Re)))Te||=Tt(W,Re)===`
|
|
28
|
+
`,Re++;if(Te)H=!1,J=!1;G=!0,oe=Re;continue}if(!G){oe++;continue}if(Jt(W,oe,"--")&&(oe===0||Xt(Tt(W,oe-1)))&&(!Tt(W,oe+2)||Xt(Tt(W,oe+2))||dn(Tt(W,oe+2)))){G=!1,H=!1,J=!1,oe+=2;continue}if(H||=Jt(W,oe,"--recursive")&&ir(W,oe+11)||Ml(W,oe,"recursive"),J||=Jt(W,oe,"--force")&&ir(W,oe+7)||Ml(W,oe,"force"),H&&J)return!0;oe++}return!1}function Ml(W,G,H){if(!Jt(W,G,"--"))return!1;let J=0;while(J<=H.length){let oe=Tt(W,G+J+2);if(!oe||Xt(oe)||dn(oe))break;if(oe!==H[J])return!1;J++}return J>0&&ir(W,G+J+2)}function hb(W,G){let H=G,J=!1,oe=!1;while(H<tn(W)){while(Xt(Tt(W,H)))H++;let ie=H;while(H<tn(W)&&!Xt(Tt(W,H)))H++;if(Tt(W,ie)!=="-"||H-ie===2&&Jt(W,ie,"--"))return!1;let fe=bm(W,ie,"recursive"),Re=bm(W,ie,"force");if(J&&Re||oe&&fe)return!0;if(J||=fe,oe||=Re,Tt(W,ie+1)==="-")continue;let Te=Sb(W,ie,H);if(Te.combined||J&&Te.forceAtBoundary||oe&&Te.recursiveAtBoundary)return!0;J||=Te.recursive,oe||=Te.force}return!1}function bm(W,G,H){return Jt(W,G,`--${H}`)&&ir(W,G+H.length+2)||Ml(W,G,H)}function yb(W,G){if(G>0&&Fr(Tt(W,G-1)))return-1;let H=G;if(Tt(W,H)==="\\")H++;if(Tt(W,H)!=="r")return-1;if(H++,Tt(W,H)==="\\")H++;if(Tt(W,H)!=="m"||!Xt(Tt(W,H+1)))return-1;return H+1}function Sb(W,G,H){let J=!1,oe=!1,ie=!1,fe=!1,Re=!1;if(Tt(W,G)!=="-")return{recursive:J,force:oe,recursiveAtBoundary:ie,forceAtBoundary:fe,combined:Re};let Te="";for(let ke=G+1;ke<H;ke++){let Le=Tt(W,ke)??"",Xe=(Le==="r"||Le==="f")&&ir(W,ke+1);J||=Le==="r",oe||=Le==="f",ie||=Le==="r"&&Xe,fe||=Le==="f"&&Xe,Re||=(Te==="r"&&Le==="f"||Te==="f"&&Le==="r")&&Xe,Te=Le}return{recursive:J,force:oe,recursiveAtBoundary:ie,forceAtBoundary:fe,combined:Re}}function vm(W,G,H){return si(W,"reset",po,!0,(J)=>Tt(W,J)==="-"&&go(W,J,G,H)?!0:J)}function Cb(W){return si(W,"clean",po,!0,(G)=>{if(Tt(W,G)!=="-")return G;if(go(W,G,"--fo","rce"))return!0;let H=ii(W,G,po);for(let J=G+1;J<H;J++)if(Tt(W,J)==="f")return!0;return H-1})}function ys(W,G,H){if(!or(W,G,"git"))return null;let J=G+3;if(!Xt(Tt(W,J)))return{commandEnd:-1,next:J};while(Xt(Tt(W,J)))J++;while(J<tn(W)){if(dn(Tt(W,J)))return{commandEnd:-1,next:J};let oe=ii(W,J,dn);if(or(W,J,H))return{commandEnd:J+H.length,next:oe};if(Tt(W,J)!=="-")return{commandEnd:-1,next:oe};let ie=oe-J===2&&Jt(W,J,"--"),fe=bb(W,J,oe);J=oe;while(Xt(Tt(W,J)))J++;if(ie)return{commandEnd:or(W,J,H)?J+H.length:-1,next:ii(W,J,dn)};if(!fe)continue;if(J>=tn(W)||dn(Tt(W,J)))return{commandEnd:-1,next:J};J=ii(W,J,dn);while(Xt(Tt(W,J)))J++}return{commandEnd:-1,next:J}}function bb(W,G,H){for(let J of _n)if(H-G===J.length&&Jt(W,G,J))return!0;return!1}function vb(W){return Em(W,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function Eb(W){return si(W,"push",po,!0,(G)=>{if(Tt(W,G)!=="-")return G;if(Tt(W,G+1)==="f"&&!Fr(Tt(W,G+2))&&!Jt(W,G+2,"-with-lease"))return!0;let H=_m(W,G,"--fo","rce");if(H>=0&&!Jt(W,H,"-with-lease"))return!0;return G})}function Rb(W){return si(W,"push",dn,!1,(G)=>{if(Xt(Tt(W,G))&&Tt(W,G+1)==="+"&&G+2<tn(W)&&!dn(Tt(W,G+2))&&!Xt(Tt(W,G+2)))return!0;if(Tt(W,G)===":"&&Tt(W,G+1)==="+")return!0;return G})}function _b(W){return si(W,"push",dn,!1,(G)=>{if(Tt(W,G)==="-"&&go(W,G,"--de","lete"))return!0;if(Xt(Tt(W,G))&&Tt(W,G+1)===":"&&G+2<tn(W)&&!Xt(Tt(W,G+2))&&!dn(Tt(W,G+2)))return!0;return G})}function xb(W){let G=!1,H=!1,J=!1;for(let oe=0;oe<=tn(W);oe++){if(oe===tn(W)||dn(Tt(W,oe))){if(H&&J)return!0;G=!1,H=!1,J=!1;continue}if(!G){let Re=ys(W,oe,"branch");if(Re){G=Re.commandEnd>=0,oe=Math.max(oe,(G?Re.commandEnd:Re.next)-1);continue}}if(!G||Tt(W,oe)!=="-")continue;let ie=ii(W,oe,dn),fe=wb(W,oe,ie);if(H||=fe.deletion,J||=fe.force,H&&J)return!0;oe=ie-1}return!1}function wb(W,G,H){let J=!1,oe=!1;for(let ie=G;ie<H;ie++){if(Tt(W,ie)!=="-")continue;if(go(W,ie,"--de","lete"))J=!0;if(go(W,ie,"--fo","rce"))oe=!0;if(Tt(W,ie+1)==="-")continue;let fe=ie+1,Re=!1,Te=!1,ke=!1;while(fe<H&&Ab(Tt(W,fe))){let Le=Tt(W,fe);Re||=Le==="d"||Le==="D",Te||=Le==="f",ke||=Le==="D",fe++}if(!ir(W,fe))continue;J||=Re,oe||=Te||ke}return{deletion:J,force:oe}}function Ab(W){if(!W)return!1;let G=W.charCodeAt(0);return G>=65&&G<=90||G>=97&&G<=122}function Pb(W){return Em(W,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function Em(W,G){let H=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let J=0;J<tn(W);J++){let oe=Tt(W,J),ie=H[H.length-1];if(!ie)return!1;let fe=ie.escaped;if(ie.escaped=!fe&&ie.quote!=="'"&&oe==="\\",!fe&&oe==="'"&&ie.quote!=='"')ie.quote=ie.quote==="'"?"":"'";if(!fe&&oe==='"'&&ie.quote!=="'")ie.quote=ie.quote==='"'?"":'"';if(oe==="$"&&Tt(W,J+1)==="("&&(H.length===1||!fe&&ie.quote!=="'")){H.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),J++;continue}if(!fe&&!ie.quote&&H.length>1&&oe==="("){ie.depth++;continue}if(!fe&&!ie.quote&&H.length>1&&oe===")"){if(ie.depth--,ie.depth===0)H.pop();continue}if(Xt(oe))ie.shortActive=!1,ie.hasShortFlag=!1;if(!ie.outerActive){let Re=ys(W,J,G.command);if(Re){ie.outerActive=Re.commandEnd>=0&&Xt(Tt(W,Re.commandEnd)),ie.shortActive=!1,ie.hasShortFlag=!1,J=Math.max(J,(ie.outerActive?Re.commandEnd:Re.next)-1);continue}}if(ie.outerActive&&oe==="-"){if(go(W,J,G.longPrefix,G.longOptional))return!0;ie.shortActive||=!G.excludedShortStarts.includes(Tt(W,J+1)??"")}if(ie.hasShortFlag||=ie.shortActive&&oe===G.shortFlag,ie.hasShortFlag&&ir(W,J+1))return!0;if(po(oe))ie.outerActive=!1}return!1}function si(W,G,H,J,oe){let ie=!1;for(let fe=0;fe<tn(W);fe++){let Re=Tt(W,fe),Te=H(Re);if(!ie&&!Te){let ke=ys(W,fe,G);if(ke){ie=ke.commandEnd>=0&&(!J||Xt(Tt(W,ke.commandEnd))),fe=Math.max(fe,(ie?ke.commandEnd:ke.next)-1);continue}}if(ie){let ke=oe(fe);if(ke===!0)return!0;for(let Le=fe;Le<=ke;Le++)if(H(Tt(W,Le)))ie=!1;fe=ke}if(Te)ie=!1}return!1}function Tb(W){let G=!1;for(let H=0;H<tn(W);H++){if(Ol(Tt(W,H))){if(G)return!0;G=!1;continue}if(!G){let J=ys(W,H,"restore");if(J){G=J.commandEnd>=0,H=Math.max(H,(G?J.commandEnd:J.next)-1);continue}}if(G&&Tt(W,H)==="-"&&Tt(W,H+1)==="-"&&(Jt(W,H+2,"staged")||Jt(W,H+2,"help")))G=!1}return G}function Rm(W,G){let H=!1;for(let J=0;J<tn(W);J++){let oe=Tt(W,J),ie=G?Ol(oe):dn(oe);if(H&&Xt(oe)&&Tt(W,J+1)==="-"&&or(W,J+2,"delete"))return!0;if(ie){H=!1;continue}if(or(W,J,"find"))H=!0,J+=3}return!1}function ii(W,G,H){let J=G;while(J<tn(W)&&!Xt(Tt(W,J))&&!H(Tt(W,J)))J++;return J}function _m(W,G,H,J){if(!Jt(W,G,H))return-1;let oe=G+H.length;for(let ie=0;ie<J.length&&Tt(W,oe)===J[ie];ie++)oe++;return ir(W,oe)?oe:-1}function go(W,G,H,J){return _m(W,G,H,J)>=0}function Nn(W,G){oi(G,W,2);let H=W.toLowerCase(),J=H.trimStart(),oe=J.startsWith("echo ")||J.startsWith("rg "),ie=[{scan:"rm",label:"rm -rf"},{scan:"reset-hard",label:"git reset --hard"},{scan:"reset-merge",label:"git reset --merge"},{scan:"clean",label:"git clean -f"},{scan:"checkout",label:"git checkout --force"},{scan:"push-force",label:"git push --force"},{scan:"push-refspec",label:"git push --force"},{scan:"push-delete",label:"git push delete"},{scan:"branch",label:"git branch -D",caseSensitive:!0},{scan:"tag",label:"git tag -d"},{regex:/\bgit\s+stash\s+(drop|clear)\b/,label:"git stash drop/clear"},{regex:/\bgit\s+checkout\s+--\s/,label:"git checkout --"},{scan:"restore",label:"git restore without --staged"},{scan:"find",label:"find -delete",skipForEchoRg:!0},{regex:/\bdd\b[^\n|;&]*\bof=\/dev\/\S/,label:"dd of=/dev/",skipForEchoRg:!0},{regex:/\bmkfs(?:\.[a-z0-9_-]+)?\s+\/dev\/\S/,label:"mkfs /dev/",skipForEchoRg:!0},{regex:/\bshred\b\s+\S/,label:"shred",skipForEchoRg:!0},{regex:/\b(?:curl|wget|fetch|aria2c|https?|xhs?|ncat|netcat|nc)\b(?:[^\n|;&]|\\\n)*\|(?:\s|\\\n)*(?:(?:sudo|env|command|builtin)(?:\s+(?:-\S+|\w+=\S*))*\s+)?(?:[^\s|;&]*\/)?(?:ba|da|z|k)?sh(?![^\s;&|])/,label:"download piped to shell",skipForEchoRg:!0}];for(let fe of ie){if(fe.skipForEchoRg&&oe)continue;let Re=fe.caseSensitive?W:H;if(fe.regex)wn(G,Re);if((fe.regex?.test(Re)??!1)||fe.scan&&hs(Re,fe.scan,G))return Pt("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${fe.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var Ib=/^[A-Za-z_][A-Za-z0-9_]*=/;function wm(W,G,H){let J=W.words[0];if(!G||!J||W.words.length!==1||W.dialect!=="posix")return!1;if(!J.quoted||J.provenance!=="literal")return!1;let oe=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(J.text)?.[1];if(!oe)return!1;oi(H,G.source,2);let ie={anchored:new RegExp(`^\\$\\{?${oe}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${oe}(?![A-Za-z0-9_])`)};return Am(G.nodes,J,ie)}function Am(W,G,H){return W.every((J)=>{if(J.kind==="connector")return!0;if(J.kind==="group"||J.kind==="function")return Am(J.body.nodes,G,H);if(J.kind==="unknown")return!H.loose.test(J.source);return kb(J,G,H)})}function kb(W,G,H){if(W.nested.some((oe)=>H.loose.test(oe.source)))return!1;let J=W.words.findIndex((oe)=>!Ib.test(oe.text));return W.words.every((oe,ie)=>oe===G||xm(oe.raw,H.anchored,ie!==J))&&W.redirections.every((oe)=>(!oe.heredoc||oe.heredoc.quotedDelimiter||!H.loose.test(oe.heredoc.body))&&(!oe.target||xm(oe.target.raw,H.anchored,!0)))}function xm(W,G,H){let J=!1,oe=!1;for(let ie=0;ie<W.length;ie++){let fe=W[ie];if(fe==="\\"&&!J){ie++;continue}if(!oe&&fe==="'"){J=!J;continue}if(!J&&fe==='"'){oe=!oe;continue}if(J||fe!=="$")continue;if(!G.test(W.slice(ie)))continue;if(!oe||!H)return!1}return!0}var Ob="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",Mb="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",Db="This erases or repartitions a disk. Run disk erase and partition commands manually after confirming the target.",Nb="This output redirect overwrites a disk device. Run device writes manually after confirming the target.",Lb="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.",Wb=new Set(["of=/dev/null","of=/dev/zero","of=/dev/full"]),Pm=/^(?:mkfs(?:\..+)?|mke2fs|newfs(?:_.+)?)$/,Gb=new Set(["diskutil","wipefs","sgdisk","parted"]),Fb=new Set(["erasedisk","erasevolume","reformat","partitiondisk","zerodisk","randomdisk","secureerase"]),zb=/^(?:-[^-]*[ao]|--all$|--offset(?:=|$))/,$b=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"]),Bb=new Set(["p","v","O","E","F","f","D","L","P","V","?"]),Ub=new Set(["i","b"]),Hb=/^\/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\/)/,jb=new Set([">",">|",">>","<>",">&"]),Vb=new Set(["mklabel","mktable","mkpart","rm","resizepart"]);function Tm(W){return W==="dd"||W==="shred"||Pm.test(W)||Gb.has(W)}function Kb(W,G){let H=G.some((J)=>J.startsWith("/dev/"));if(W==="diskutil"){let J=G.find((oe)=>!oe.startsWith("-"));return J!==void 0&&Fb.has(J.toLowerCase())}if(W==="wipefs")return H&&G.some((J)=>zb.test(J));if(W==="sgdisk")return H&&G.some((J)=>J.startsWith("-")&&!qb(J));return W==="parted"&&H&&G.some((J)=>Vb.has(J.toLowerCase()))}function qb(W){if($b.has(W.split("=",1)[0]??W))return!0;if(W.startsWith("--"))return!1;let G=W.slice(1).split("");return Ub.has(G[0]??"")||G.every((H)=>Bb.has(H))}function Im(W,G){let H=G.slice(1);if(W==="dd"&&H.some((J)=>/^of=\/dev\/.+/.test(J)&&!Wb.has(J)))return Pt("dd.device-write",Ob);if(Pm.test(W)&&H.some((J)=>J.startsWith("/dev/")))return Pt("mkfs.device",Mb);if(Kb(W,H))return Pt("disk.erase",Db);if(W==="shred"&&H.length>0)return Pt("shred.target",Lb);return null}function km(W){return W.some((G)=>jb.has(G.operator)&&G.target?.provenance==="literal"&&Hb.test(G.target.text))?Pt("redirect.block-device",Nb):null}import{isAbsolute as Yb,resolve as Om}from"node:path";function ai(W,G,H,J){let oe=Yb(W)?Om(W):G?Om(G,W):void 0;if(!oe)return;try{return Bt(oe,H,J)}catch{return oe}}function Mm(W){return!["/dev","/proc","/sys"].some((G)=>W===G||W.startsWith(`${G}/`))}var ho="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",li="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.",Nl=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),Zb=new Set(["-p","--print"]),Xb=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),Jb=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"])]]),Qb=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),ev=new Map([["python",new Set(["m"])]]),tv=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"])]]),nv=new Set(["always","default","never"]),rv=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),ov=/\\\r?\n/g,iv=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 Dm(W){return Cs(W).code}function Ss(W){return Cs(W).sources}function Nm(W){return iv.get(Wl(W))??[]}function Cs(W){let G=Wl(W[0]??"");if(!Nl.has(G))return{code:null,sources:[],optionsOpen:!1};let H=[],J=[],oe=!0;for(let ie=1;ie<W.length;ie++){let fe=W[ie];if(fe===void 0)break;if(fe==="--")return Bn(G,H,J,oe,W[ie+1]===void 0?void 0:ie+1,W[ie+1]);if(fe===""||fe==="-"||!fe.startsWith("-"))return Bn(G,H,J,oe,ie,fe);if(G==="node"&&Zb.has(fe)){let Xe=W[ie+1];if(Xe===void 0)return Bn(G,H,J,oe);if(Xe.startsWith("-"))continue;H.push({tokenIndex:ie+1,value:Xe}),J.push({tokenIndex:ie+1,kind:"inline-code",value:Xe}),ie++;continue}if(av(G,fe)){let Xe=W[ie+1];if(Xe===void 0)return Bn(G,H,J,oe);if(H.push({tokenIndex:ie+1,value:Xe}),J.push({tokenIndex:ie+1,kind:"inline-code",value:Xe}),G==="python")return Bn(G,H,J,oe);ie++;continue}let Re=/^--eval=(.*)$/s.exec(fe);if(lv(G)&&Re){let Xe=Re[1]??"";H.push({tokenIndex:ie,value:Xe}),J.push({tokenIndex:ie,kind:"inline-code",value:Xe});continue}if(G==="node"){let Xe=sv(fe);if(Xe){if(Xe.attached){if(oe&&=Xe.value!=="",Xe.value!=="")J.push({tokenIndex:ie,kind:"module-file",value:Xe.value});continue}let Ye=W[ie+1];if(Ye===void 0||Ye.startsWith("-"))return oe=!1,Bn(G,H,J,oe);J.push({tokenIndex:ie+1,kind:"module-file",value:Ye}),ie++;continue}}if(G==="python"&&fe.startsWith("--check-hash-based-pycs=")||G==="node"&&(fe==="--conditions="||fe==="--diagnostic-dir="||fe==="--title=")||G==="ruby"&&(fe==="--disable="||fe==="--enable="))return Bn(G,H,J,oe);if(tv.get(G)?.has(fe)){let Xe=W[ie+1];if(Xe===void 0||Xe.startsWith("-")&&!(G==="ruby"&&rv.has(fe))||G==="python"&&!nv.has(Xe))return Bn(G,H,J,oe);ie++;continue}if(fe.startsWith("--"))continue;let Te,ke=!1;for(let Xe=1;Xe<fe.length;Xe++){let Ye=fe[Xe];if(Ye===void 0)break;if(ev.get(G)?.has(Ye)){let Ze=fe.slice(Xe+1),Qe=Ze||W[ie+1];if(Qe!==void 0)J.push({tokenIndex:Ze?ie:ie+1,kind:"module-file",value:Qe});return Bn(G,H,J,oe)}if(Xb.get(G)?.has(Ye)){Te=fe.slice(Xe+1)||W[ie+1],ke=Xe+1===fe.length;break}if(G==="node"&&Ye==="r"){if(oe&&=fe==="-r",fe==="-r"){let Ze=W[ie+1];if(oe&&=Ze!==void 0&&!Ze.startsWith("-"),oe&&Ze!==void 0)J.push({tokenIndex:ie+1,kind:"module-file",value:Ze});ie++}break}if(G==="ruby"&&Ye==="r"){let Ze=fe.slice(Xe+1),Qe=Ze||W[ie+1];if(oe&&=Qe!==void 0,Qe!==void 0)J.push({tokenIndex:Ze?ie:ie+1,kind:"module-file",value:Qe});if(!Ze)ie++;break}if(G==="perl"&&(Ye==="M"||Ye==="m")){let Ze=fe.slice(Xe+1);if(!Ze){if(oe=!1,Xe+1===fe.length)ie++;break}J.push({tokenIndex:ie,kind:"module-file",value:Ze});break}if(Jb.get(G)?.has(Ye)){if(Xe+1===fe.length)ie++;break}if(Qb.get(G)?.has(Ye)&&Xe+1<fe.length)break}if(Te===void 0)continue;let Le=ke?ie+1:ie;if(H.push({tokenIndex:Le,value:Te}),J.push({tokenIndex:Le,kind:"inline-code",value:Te}),G==="python")return Bn(G,H,J,oe);if(ke)ie++}return Bn(G,H,J,oe,void 0,void 0,!0)}function Bn(W,G,H,J,oe,ie,fe=!1){let Re=W==="node"?G.slice(-1):G,Te=new Set(Re.map((Le)=>Le.tokenIndex)),ke=H.filter((Le)=>Le.kind!=="inline-code"||Te.has(Le.tokenIndex));if(J&&G.length===0&&oe!==void 0&&ie!==void 0)ke.push({tokenIndex:oe,kind:"main-script",value:ie});return{code:(W==="node"?Re[0]?.value:Re.map((Le)=>Le.value).join(`
|
|
29
|
+
`))||null,sources:J?ke:[],optionsOpen:J&&fe}}function sv(W){for(let G of["--import","--loader","--experimental-loader","--require"]){if(W===G)return{attached:!1,value:""};if(W.startsWith(`${G}=`))return{attached:!0,value:W.slice(G.length+1)}}return}function Ll(W,G){return Wl(W)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(G)}function Wl(W){let G=Ft(W).toLowerCase();return Vi.test(G)?"python":G}function av(W,G){return Nl.get(W)?.has(G)??!1}function lv(W){return Nl.get(W)?.has("--eval")??!1}function ci(W,G,H=!1){let J=uv(W,G);if(!Dl(J,G))return!1;wn(G,J);let oe=dv(J);if(Dl(oe,G))return!0;if(wn(G,oe),!Lm.test(oe))return!1;return!H||cv(J,G)}function cv(W,G){if(/`|%x|\bqx\b/.test(W))return!0;let J=W.split(""),oe=[];for(let Te=0;Te<W.length;Te++){let ke=W[Te];if(ke!=="'"&&ke!=='"')continue;let Le=W.startsWith(ke.repeat(3),Te)?ke.repeat(3):ke,Xe=Te+Le.length,Ye=Xe;while(Ye<W.length&&!W.startsWith(Le,Ye))Ye+=W[Ye]==="\\"?2:1;if(Ye>=W.length)return!0;oe.push({start:Xe,text:W.slice(Xe,Ye)}),J.fill(" ",Te,Ye+Le.length),Te=Ye+Le.length-1}let ie=J.join(""),fe=Array.from(ie.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((Te)=>Lm.test(Te[1]??"")).map((Te)=>{let ke=Te.index+Te[0].length;return{start:ke,end:bs(ie,ke)}});if(fe.some((Te)=>Gl(ie,Te.start)))return!0;return oe.some((Te)=>{let ke=/\b(?:system|exec|spawn|popen)\s*$/.test(ie.slice(0,Te.start)),Le=fe.some((Xe)=>Te.start>=Xe.start&&Te.start<Xe.end);return(ke||Le)&&Dl(Te.text,G)})}function bs(W,G){let H=1;for(let J=G;J<W.length;J++){if(W[J]==="(")H++;if(W[J]===")")H--;if(H===0)return J}return W.length}function Gl(W,G){let H=0;for(let J=G;J<W.length;J++){let oe=W[J]??"";if("([{".includes(oe))H++;if(")]}".includes(oe)&&H--===0)return!1;if(oe===","&&H===0)return!1;if(/[A-Za-z_$]/.test(oe))return!0}return!1}var Lm=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function dv(W){let G=[],H=0,J=0;while(J<W.length){let oe=W[J];if(oe!=="'"&&oe!=='"'){J++;continue}let ie=W.startsWith(oe.repeat(3),J)?oe.repeat(3):oe,fe=J+ie.length;while(fe<W.length&&!W.startsWith(ie,fe))fe+=W[fe]==="\\"?2:1;if(fe>=W.length)break;G.push(W.slice(H,J)," "),J=fe+ie.length,H=J}return G.push(W.slice(H)),G.join("")}function Dl(W,G){if(gs(W,"rm",G))return!0;for(let J of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(wn(G,W),J.test(W))return!0;if(gs(W,"dd",G))return!0;for(let J of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(wn(G,W),J.test(W))return!0;if(gs(W,"find",G))return!0;let H=W.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((J)=>(wn(G,W),H.some((oe)=>hs(oe,J))))}function uv(W,G){return wn(G,W),W.replace(ov,"")}import{lstatSync as lE,readdirSync as cE}from"node:fs";import{basename as dE,isAbsolute as cf,join as uE,relative as df}from"node:path";import{isAbsolute as Um,parse as vv}from"node:path";import{dirname as mv,isAbsolute as fv,parse as pv,sep as gv}from"node:path";function hr(W,G,H){if(nr(G))throw Error("Unsupported Windows namespace path");let J=fv(G)?pv(G).root:"",oe=J||W;for(let ie of yv(J?G.slice(J.length):G)){if(ie===""||ie===".")continue;if(ie===".."){oe=mv(oe);continue}let fe=hv(oe,ie),Re=H.entryKind(fe),Te=Re==="symlink"?H.realpath(fe):fe;if(Re==="missing"||Te===null)throw Error(`Cannot resolve path component: ${fe}`);oe=Te}return oe}function hv(W,G){return W.endsWith("/")||W.endsWith("\\")?`${W}${G}`:`${W}${gv}${G}`}function yv(W){let G=process.platform==="win32"?/[\\/]+/:/\/+/;return W.split(G)}var Fl=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],Sv=new Set(Fl),Cv=1024,Wm=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),Gm=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),bv=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function vs(W){return Sv.has(W)}function zl(W){return vs(W)||Wm.has(W)||Gm.has(W)||$o(W)}function sr(W,G,H){return H?.has(W)?H.get(W):G.get(W)}function Fm(W,G){let H=sr("GIT_CONFIG_COUNT",W,G);if(H===void 0)return{state:"absent"};if(H==="")return{state:"valid",count:0};if(!/^\d+$/.test(H))return{state:"invalid"};let J=Number(H);return Number.isSafeInteger(J)&&J<=Cv?{state:"valid",count:J}:{state:"invalid"}}function Es(W,G,H){let oe=W.match(bv)?.[1];if(!oe||!zl(oe))return null;let ie=W.indexOf("=");return{name:oe,value:`${sr(oe,G,H)??""}${W.slice(ie+1)}`}}function zm(W){return Bm(W,Gm)}function $m(W){return Bm(W,Wm)}function Bm(W,G){if(!W)return!1;for(let H of W.keys())if(G.has(H))return!0;return!1}var jm=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ln(W){if(!jm.test(W))return null;let G=W.indexOf("=");return{name:W.slice(0,G),value:W.slice(G+1)}}function Ce(W){let G=new Map,H=0;while(H<W.length){let J=W[H];if(!J)break;let oe=Ln(t(J));if(!oe)break;G.set(oe.name,oe.value),H++}return{words:W.slice(H),envAssignments:G}}function Vm(W){let G=zt(W);return W.includes("=")||G==="sudo"||G==="env"||G==="command"||G==="builtin"}function zr(W,G,H,J){if(!Vm(yo(W)))return{words:W,envAssignments:new Map,cwd:H,rewritten:!1};let oe=new Set(W),ie=W,fe=new Map,Re=new Map(J??[]),Te=[],ke=H;for(let Xe=0;Xe<a.wrapperPeelIterations.cap;Xe++){let Ye=Hm(ie),Ze=Ce(ie);for(let[et,tt]of Ze.envAssignments)fe.set(et,tt),Re.set(et,tt);if(ie=Ze.words,ie.length===0)break;while(ie.length>0&&yo(ie).includes("=")&&!Rv(ie)){let et=_v(yo(ie),Re,G.env)??Es(yo(ie),G.env,Re);if(et)fe.set(et.name,et.value),Re.set(et.name,et.value);ie=ie.slice(1)}if(ie.length===0)break;let Qe=zt(yo(ie));if(Qe!=="sudo"&&Qe!=="env"&&Qe!=="command"&&Qe!=="builtin")break;if(Qe==="sudo"){let et=wv(ie,G.paths,ke);if(ie=et.words,et.cwd!==void 0)ke=et.cwd}if(Qe==="env"){let et=Tv(ie,ke,Re,G);if(Te.push(...et.envSplitValues??[]),ie=et.words,et.cwd!==void 0)ke=et.cwd;for(let[tt,gt]of et.envAssignments)fe.set(tt,gt),Re.set(tt,gt)}if(Qe==="command")ie=Iv(ie);if(Qe==="builtin")ie=ie.slice(Un(ie,1)==="--"?2:1);if(Hm(ie)===Ye)break}let Le=Ce(ie);for(let[Xe,Ye]of Le.envAssignments)fe.set(Xe,Ye),Re.set(Xe,Ye);return{words:Le.words,envAssignments:fe,cwd:ke,envSplitValues:Te.length>0?Te:void 0,rewritten:Ev(Le.words,oe)}}function Ev(W,G){return W.some((H)=>!G.has(H))}function Hm(W){return W.map(t).join(" ")}function yo(W){let G=W[0];return G?t(G):""}function Un(W,G){let H=W[G];return H?t(H):void 0}function Rv(W){return jm.test(yo(W))}function _v(W,G,H){if(!W.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${G.get("TMPDIR")??H.get("TMPDIR")??""}${W.slice(8)}`}}var xv=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function wv(W,G,H){let J=1,oe=H;while(J<W.length){let ie=Un(W,J);if(!ie)break;if(ie==="--")return{words:W.slice(J+1),cwd:oe};if(!ie.startsWith("-"))break;if(ie==="-D"||ie==="--chdir"){let fe=Un(W,J+1);oe=fe?di(oe,fe,G):null,J+=2;continue}if(ie.startsWith("--chdir=")){oe=di(oe,ie.slice(8),G),J++;continue}if(ie.startsWith("-D")&&ie.length>2){oe=di(oe,ie.slice(2),G),J++;continue}if(ie==="-i"||ie==="--login"){oe=null,J++;continue}if(xv.has(ie)){J+=2;continue}J++}return{words:W.slice(J),cwd:oe}}var Av=new Set(["-i","-0","--null"]),Pv=new Set(["-u","--unset","-C","--chdir","-P"]);function Tv(W,G,H,J){let oe=new Map,ie=[],fe=G,Re=1,Te=(ke)=>({words:W.slice(ke),envAssignments:oe,cwd:fe,envSplitValues:ie.length>0?ie:void 0});while(Re<W.length){let ke=Un(W,Re);if(!ke)break;if(ke==="--")return Te(Re+1);if(ke==="-i"||ke==="--ignore-environment"||ke==="-"){oe.clear();for(let Xe of H.keys())oe.set(Xe,"");oe.set("TMPDIR",""),Re++;continue}if(Av.has(ke)){Re++;continue}if(ke==="-u"||ke==="--unset"){let Xe=Un(W,Re+1);if(Xe!==void 0)oe.set(Xe,"");Re+=2;continue}if(ke.startsWith("-u")&&ke.length>2&&!ke.startsWith("-u=")){oe.set(ke.slice(2),""),Re++;continue}if(ke.startsWith("--unset=")){oe.set(ke.slice(8),""),Re++;continue}let Le=ke==="-S"||ke==="--split-string"?{value:Un(W,Re+1),consumed:2}:ke.startsWith("-S")&&ke.length>2?{value:ke.slice(2),consumed:1}:ke.startsWith("--split-string=")?{value:ke.slice(15),consumed:1}:null;if(Le){if(Le.value!==void 0)ie.push(Le.value);return fe=null,Te(Re+Le.consumed)}if(Pv.has(ke)){if(ke==="-C"||ke==="--chdir"){let Xe=Un(W,Re+1);fe=Xe?di(fe,Xe,J.paths):null}Re+=2;continue}if(ke.startsWith("-u=")){Re++;continue}if(ke.startsWith("-C")&&ke.length>2||ke.startsWith("--chdir=")){let Xe=ke.startsWith("--chdir=")?ke.slice(8):ke.startsWith("-C=")?ke.slice(3):ke.slice(2);fe=di(fe,Xe,J.paths),Re++;continue}if(ke.startsWith("-P")){Re++;continue}if(ke.startsWith("-")){Re++;continue}if(!Ln(ke))break;while(Re<W.length){let Xe=Ln(Un(W,Re)??"");if(!Xe)break;oe.set(Xe.name,Xe.value),Re++}if(Un(W,Re)==="--")Re++;return Te(Re)}return Te(Re)}function di(W,G,H){if(G==="")return null;if(!W&&!Um(G))return null;let J=Um(G)?vv(G).root:H.realpath(W??"/");if(J===null)return null;try{return hr(J,G,H)}catch{return null}}function Iv(W){if(Un(W,1)==="-v")return[...Qt(["type"]),...W.slice(2)];let G=1;while(G<W.length){let H=Un(W,G);if(!H)break;if(H==="-p"||H==="-v"||H==="-V"){G++;continue}if(H==="--")return W.slice(G+1);if(H.startsWith("-")&&!H.startsWith("--")&&H.length>1){if(!/^[pvV]+$/.test(H.slice(1)))break;G++;continue}break}return W.slice(G)}var kv=/['"\\$`{}#]/;function Rs(W,G){if(W.some((J)=>kv.test(J)))return null;let H=[...W.flatMap((J)=>J.split(/\s+/).filter((oe)=>oe.length>0)),...G];return H.length<=64?H:null}function yr(W,G,H){return _s(W,G,H).tokens}function Ov(W){let G=[],H="",J=0;while(J<W.length){let oe=W.charAt(J);if(oe==='"'||oe==="'"){let ie=W.indexOf(oe,J+1);if(ie===-1)return W.split(/\s+/).map((fe)=>fe.replace(/["']/g,"")).filter((fe)=>fe.length>0);H+=W.slice(J+1,ie),J=ie+1;continue}if(/\s/.test(oe)){if(H.length>0)G.push(H);H="",J++;continue}H+=oe,J++}if(H.length>0)G.push(H);return G}function Sr(W,G,H,J=0){let oe=_s(W,G,H),ie=(oe.envSplitValues??[]).flatMap(Ov);if(ie.length===0)return oe.tokens;let fe=[...ie,...oe.tokens];if(J>=8)return fe;return Sr(fe,G,H,J+1)}function _s(W,G,H,J){if(!Vm(W[0]??""))return{tokens:[...W],envAssignments:new Map,cwd:H};let oe=zr(Qt(W),G,H,J);return{tokens:oe.words.map(t),envAssignments:oe.envAssignments,cwd:oe.cwd,envSplitValues:oe.envSplitValues}}var Ul=Symbol("adopt-as-operand"),Mv=new Set(["env","sudo","command","builtin"]),Dv=new Set(["&&","||","|&","|","&",";"]),Nv=new Set(["<<","<<<",">|"]),Km=new Set(["|","|&"]),Lv=/[*@#?$!_-]/,Wv=/^\w+(?::\w+)*/,Gv=Object.freeze([]),ui=Object.freeze({kind:"scope",edge:"enter"}),mi=Object.freeze({kind:"scope",edge:"exit"}),Fv=Object.freeze([]),zv=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),fi=new Set(["bash","sh","zsh","dash","ksh"]),$v=256,Jm=new WeakMap;function Qm(W,G){let H=G.status==="complete"?new Set(Bl(G)):new Set,J=Hv(W,H);if(qi(J))return xs("unclosed-quote",J,G);let oe={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},ie=$r(G,{source:J,suppressed:H,flags:oe,depth:0,functions:new Map,powershell:G.dialect==="powershell"});if(oe.limited)return xs("structural-limit",J,G);if(oe.invalid)return xs("invalid",J,G);let fe=xs("complete",J,G,oe.assignmentFallbacks);return Jm.set(fe,Object.freeze(ie)),fe}function Ps(W,G,H,J,oe){let ie=oe.word??((Qe)=>Qe),fe={cwd:G,variables:new Map,previous:null},Re=[],Te=new Set,ke=null,Le=[],Xe=ef(W),Ye=Xe.findLastIndex((Qe)=>Qe.kind==="operator"&&Km.has(Qe.operator)),Ze=Ye!==-1&&Xe.some((Qe)=>Qe.kind==="redirection"&&Qe.operator==="<<"&&Qe.body===void 0);for(let[Qe,et]of Xe.entries()){let tt=Ze||Qe<=Ye;if(et.kind==="scope"){if(et.edge==="enter"){Le.push({state:fe,segment:[...Re],shellWords:new Set(Te),pipeProducer:ke});continue}let gt=oe.segment(Re,fe,ke,null,Te,tt);if(gt)return gt;let _t=Le.pop();if(_t===void 0)throw Error("scope exit without a matching enter");fe=_t.state,Re=_t.segment,Te=_t.shellWords,ke=_t.pipeProducer;continue}if(et.kind==="operator"){if(!et.boundary)continue;let gt=oe.segment(Re,fe,ke,et.operator,Te,tt);if(gt)return gt;fe=Bv(Re,fe,H,J),ke=Re.length>0&&Km.has(et.operator)?Re:null,Re=[],Te=new Set;continue}if(et.kind==="redirection"){if(et.fd!==void 0)Te.add(Re.length-1);if(et.target===void 0)continue;let gt=oe.redirection({operator:et.operator,role:et.role,targetOrder:et.targetOrder,target:et.target,...et.body===void 0?{}:{body:et.body,consumer:et.consumer}},fe,tt);if(gt===Ul){Te.add(Re.length),Re.push(ie(et.target));continue}if(gt)return gt;continue}Re.push(ie(et.text))}return oe.segment(Re,fe,ke,null,Te,Ze)}function Ts(W){return ef(W).flatMap((G)=>{if(G.kind==="word")return[{kind:"word",text:G.text}];if(G.kind==="operator")return[{kind:"operator",boundary:G.boundary}];if(G.kind==="redirection")return[{kind:"redirection",target:G.target}];return[]})}function bn(W,G){return W.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(H,J,oe,ie)=>{let fe=G.get(J);if(fe===void 0)return H;let Re=oe.startsWith(":")?fe!=="":!0;if(oe.endsWith("-"))return Re?fe:bn(ie,G);return Re?bn(ie,G):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(H,J)=>G.get(J)??H).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(H,J)=>G.get(J)??H)}function pi(W){return W.length>0&&W.every((G)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(G))}function Bv(W,G,H,J){let oe=pi(W)?new Map([...G.variables,...Uv(W,G.variables)]):G.variables,ie=yr([...W],H),fe=Ft(ie[0]??"").toLowerCase()==="cd"?ie[1]:void 0;if(!fe)return{...G,variables:oe};if(fe==="-"){if(G.previous===null)return{...G,variables:oe};return{cwd:G.previous,variables:oe,previous:G.cwd}}return{cwd:gn(bn(fe,oe),G.cwd,H,J),variables:oe,previous:G.cwd}}function Uv(W,G){return W.flatMap((H)=>{let J=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(H),oe=J?.[2]?.startsWith("=")?J[2].slice(1):void 0;return J?.[1]!==void 0&&oe!==void 0?[[J[1],bn(oe,G)]]:[]})}function ef(W){return Jm.get(W)??Gv}function Hv(W,G){return[...G].reduce((H,J)=>H.slice(0,J.start)+" ".repeat(J.end-J.start)+H.slice(J.end),W)}function xs(W,G,H,J=Fv){return Object.freeze({status:W,source:G,program:H,assignmentFallbacks:Object.freeze(J)})}function $r(W,G){return W.nodes.flatMap((H,J)=>jv(H,W,J,G)).sort((H,J)=>H.start-J.start).flatMap((H)=>[...H.events])}function jv(W,G,H,J){if(W.kind==="connector")return[{start:W.span.start,events:[Hn(Zv(W.operator))]}];if(W.kind==="unknown")return[{start:W.span.start,events:[Hn(W.source)]}];if(W.kind==="function")return J.functions.set(W.name,W.body),[];if(W.kind==="group"){let ie=W.style!=="subshell",fe=J.source[W.span.end-1]===(ie?"}":")"),Re=ie?J:{...J,functions:new Map(J.functions)};return[{start:W.span.start,events:ie?[ws("{"),...$r(W.body,Re),...fe?[ws("}")]:[]]:[ui,Hn("("),...$r(W.body,Re),...fe?[Hn(")")]:[],mi]}]}let oe=eE(W,J.functions);if(oe){if(J.depth>=gr.maxDepth||++J.flags.expansions>$v)return J.flags.limited=!0,[];return[{start:W.span.start,events:[...qm(W,J),ws(";"),...$r(oe,{...J,depth:J.depth+1}),ws(";")]},...Ym(W,G,H,J)]}return[{start:W.span.start,events:qm(W,J)},...Ym(W,G,H,J)]}function qm(W,G){return[...W.words.map((H)=>({start:H.span.start,events:nf(H,W,G,!1)})),...W.redirections.map((H)=>({start:H.span.start,events:Vv(H,W,G)}))].sort((H,J)=>H.start-J.start).flatMap((H)=>H.events)}function Vv(W,G,H){let J=W.operator==="<<-"?"<<":W.operator,oe=W.target?nf(W.target,G,H,!0):[],ie=oe[0],fe=ie?.kind==="word"?ie.text:void 0;return[...W.fd===void 0?[]:[Hl(String(W.fd))],Object.freeze({kind:"redirection",operator:J,...W.fd===void 0?{}:{fd:W.fd},role:Xv(J),targetOrder:Nv.has(J)?"legacy-segment":"immediate",...fe===void 0?{}:{target:fe},...W.heredoc&&H.suppressed.has(W.heredoc.bodySpan)?{body:W.heredoc.body,consumer:of(G)}:{}}),...fe===void 0?oe:oe.slice(1)]}function Ym(W,G,H,J){let oe=W.redirections.filter((ie)=>ie.operator==="<<"||ie.operator==="<<-");return[...oe.flatMap((ie)=>{let fe=ie.heredoc;if(!fe)return[];let Re=[Hl(fe.delimiter),.../[\r\n]/.test(J.source[fe.terminatorSpan.end]??"")?[Hn(";")]:[]];if(J.suppressed.has(fe.bodySpan))return[{start:fe.bodySpan.start,events:Re}];return[{start:fe.bodySpan.start,events:[...tf(J.source.slice(fe.bodySpan.start,fe.bodySpan.end),J),...Re]}]}),...oe.some((ie)=>!ie.heredoc&&ie.target)?Kv(G,H,J):[]]}function Kv(W,G,H){let J=W.nodes.slice(G+1).find((oe)=>oe.kind==="connector");if(!J||J.span.end>=W.span.end)return[];return[{start:J.span.end,events:tf(H.source.slice(J.span.end,W.span.end),H)}]}function tf(W,G){if(G.depth>=gr.maxDepth)return G.flags.limited=!0,[];let H=y(W,"posix");if(H.status==="limited")return G.flags.limited=!0,[];let J={invalid:!1,limited:!1,expansions:G.flags.expansions,assignmentFallbacks:G.flags.assignmentFallbacks},oe=$r(H,{source:W,suppressed:new Set,flags:J,depth:G.depth+1,functions:new Map,powershell:!1});return G.flags.limited||=J.limited,G.flags.expansions=J.expansions,oe}function nf(W,G,H,J){let oe=[],ie={single:!1,double:!1},fe="",Re=!1,Te=()=>{let ke=Re&&!J?Hn("glob"):fe!==""||W.quoted&&oe.length===0?Hl(fe):void 0;if(ke)oe.push(ke);fe="",Re=!1};for(let ke of W.parts){if(ke.provenance!=="command-substitution"&&ke.provenance!=="arithmetic"){for(let Ze of $l(ke.raw,ie,H.flags,H.powershell)){if(typeof Ze==="string"){Te(),oe.push(Hn(Ze));continue}fe+=Ze.text,Re||=Ze.glob}continue}let Le=G.nested.find((Ze)=>Ze.span.start>=ke.span.start&&Ze.span.end<=ke.span.end);if(ie.double){let Ze=H.source.slice(ke.span.start,ke.span.end);fe+=$l(Ze,{single:!1,double:!0},H.flags,H.powershell).map((et)=>typeof et==="string"?et:et.text).join("");let Qe=Le?$r(Le,H).filter((et)=>et.kind==="redirection"&&et.body!==void 0):[];if(Qe.length>0)oe.push(ui,...Qe,mi);continue}let Xe=Le?$r(Le,H):[];if(ke.raw.startsWith("`")){fe+="${}",Te(),oe.push(ui,...Xe,mi);continue}if(ke.raw.startsWith("<(")||ke.raw.startsWith(">(")){Te(),oe.push(ke.raw.startsWith("<(")?Hn("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),ui,...Xe,...ke.raw.endsWith(")")?[Hn(")")]:[],mi);continue}let Ye=ke.raw.startsWith("$((")?2:1;fe+="${}",Te(),oe.push(...Array.from({length:Ye},()=>Hn("(")),...Ye===1?[ui]:[],...Xe,...ke.raw.endsWith(")".repeat(Ye))?Array.from({length:Ye},()=>Hn(")")):[],...Ye===1?[mi]:[])}return Te(),oe}function $l(W,G,H,J){let oe=[],ie="",fe=!1,Re=0;while(Re<W.length){let Te=W[Re]??"";if(!G.single&&!G.double&&(Te==="("||Te===")")){oe.push({text:ie,glob:fe},Te),ie="",fe=!1,Re++;continue}if(J&&Te==="`"&&!G.single){ie+=W[Re+1]??"",Re+=2;continue}if(G.single&&Te==="'"){G.single=!1,Re++;continue}if(G.single){ie+=Te,Re++;continue}if(G.double){if(Te==='"'){G.double=!1,Re++;continue}if(!J&&Te==="\\"){let ke=W[Re+1]??"";ie+=['"',"\\","$"].includes(ke)?ke:`\\${ke}`,Re+=2;continue}if(Te==="$"){let ke=Zm(W,Re,G,H,J);ie+=ke.text,Re=ke.next;continue}ie+=Te,Re++;continue}if(Te==="'"||Te==='"'){G.single=Te==="'",G.double=Te==='"',Re++;continue}if(!J&&Te==="\\"){let ke=W[Re+1]??"";fe||=ke==="*"||ke==="?",ie+=ke,Re+=2;continue}if(Te==="$"){let ke=Zm(W,Re,G,H,J);ie+=ke.text,Re=ke.next;continue}fe||=Te==="*"||Te==="?",ie+=Te,Re++}return[...oe,{text:ie,glob:fe}]}function Zm(W,G,H,J,oe){let ie=W[G+1];if(ie==="{"){let Re=oe?Yv(W,G+2):ps(W,G+2,W.length).close;if(Re===-1)return J.invalid=!0,{text:"",next:W.length};let Te=W.slice(G,Re+1);return qv(Te,H,J,oe),{text:Te,next:Re+1}}if(ie!==void 0&&Lv.test(ie))return{text:`\${${ie}}`,next:G+2};let fe=(oe?Wv:/^\w*/).exec(W.slice(G+1))?.[0]??"";return{text:`\${${fe}}`,next:G+1+fe.length}}function qv(W,G,H,J){let oe=W.slice(2,-1),ie=/^[A-Za-z_][A-Za-z0-9_]*/.exec(oe)?.[0];if(!ie)return;let fe=oe.slice(ie.length),Re=[":=","="].find((ke)=>fe.startsWith(ke));if(!Re)return;let Te=$l(fe.slice(Re.length),{...G},H,J);H.assignmentFallbacks.push(...Te.flatMap((ke)=>typeof ke==="string"||!ke.text?[]:[ke.text]))}function Yv(W,G){let H=1,J=G;while(H>0&&J<W.length){if(W[J]==="{"&&W[J-1]==="$")H++;if(W[J]==="}")H--;J++}return H===0?J-1:-1}function Zv(W){return/^[\r\n]+$/.test(W)?";":W}function Hn(W){return Object.freeze({kind:"operator",operator:W,boundary:Dv.has(W)})}function ws(W){return Object.freeze({kind:"operator",operator:W,boundary:!0})}function Hl(W){return Object.freeze({kind:"word",text:W})}function Xv(W){if(W==="<<"||W==="<<<")return"here-data";if(W==="<"||W==="<&")return"file-read";return"file-write"}function So(W){return zv.has(W)||/^python\d/.test(W)}var Jv=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 rf(W,G){let H=G[0];if(H===void 0||!H.startsWith("-"))return G;let J=Jv.get(W)?.has(H)??!1;return rf(W,G.slice(J?2:1))}function As(W){let G=W[0];if(G===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(G))return As(W.slice(1));if(G==="uv"&&W[1]==="run")return As(W.slice(2));if(!Mv.has(G))return[...W];return As(rf(G,W.slice(1)))}function of(W){let G=Qo(W),H=W.words.findIndex((J)=>J.provenance==="literal"&&J.text===G);return As(H<0?[]:W.words.slice(H).map((J)=>J.text))}function Qv(W){let G=of(W)[0];if(G===void 0)return!1;let H=Ft(G).toLowerCase();return So(H)&&!fi.has(H)}function Bl(W){return W.nodes.flatMap((G,H)=>{if(G.kind==="group"||G.kind==="function")return Bl(G.body);if(G.kind!=="command")return[];let J=G.nested.flatMap((Re)=>Bl(Re)),oe=G.redirections.flatMap((Re)=>Re.heredoc?.quotedDelimiter?[Re.heredoc.bodySpan]:[]);if(Qv(G))return[...J,...oe];let ie=W.nodes[H+1];if(ie?.kind==="connector"&&(ie.operator==="|"||ie.operator==="|&")||!nE(G))return J;return[...J,...oe]})}function eE(W,G){let H=Qo(W);return H===void 0?void 0:G.get(H)}function Cr(W,G){return W!==void 0&&W.provenance==="literal"&&!W.quoted&&W.raw===W.text&&W.text===G}function tE(W){if(Cr(W.words[0],"git"))return Cr(W.words[1],"commit");if(!Cr(W.words[0],"gh")||!Cr(W.words[2],"create"))return!1;return Cr(W.words[1],"pr")||Cr(W.words[1],"issue")}function nE(W){return(Cr(W.words[0],"cat")||Cr(W.words[0],"tee")||tE(W))&&!W.words.some(Xm)&&!W.redirections.some((H)=>Xm(H.target))}function Xm(W){return W?.parts.some((G)=>G.provenance==="command-substitution"&&G.raw.startsWith(">("))??!1}var Zn="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",Is="Unsupported heredoc syntax",gi="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function br(){return{id:"analysis.dynamic-shell-source",reason:gi,intent:"stop_and_explain"}}var sf="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var jl=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),rE=new Set([...jl,"dir_path","glob","glob_pattern","include_pattern"]),oE=new Set([...jl,"folder","glob","pattern","patterns"]);class b extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}class U extends Error{name="UnparseableCommandError";constructor(){super(Zn)}}function af(W){let G=iE(),H=se(W.input),J=[];if((W.route.kind==="command"||W.route.kind==="unknown")&&H)J.push({usage:"input-candidate",source:H});if(W.route.kind==="command"&&"command"in W&&W.command)J.push({usage:"declared-command",source:W.command});let oe=J.reduce((ie,fe)=>{let Re=ie.findIndex((Le)=>Le.source===fe.source);if(Re!==-1){let Le=ie[Re];if(!Le)return ie;return ie[Re]={...Le,usages:[...Le.usages,fe.usage]},ie}let Te=W.route.kind==="command"?W.route.shell:process.platform==="win32"?"powershell":"posix",ke=G.getCommandProgram(fe.source,Te);return ie.push({usages:[fe.usage],source:fe.source,program:ke,shell:G.getShellSyntax(fe.source,ke)}),ie},[]);return{invocation:{toolName:W.toolName,route:W.route,context:W.context},commands:oe,paths:sE(W),store:G}}function Co(W,G){return W.commands.find((H)=>H.usages.includes(G))}function ar(W){return Co(W,"declared-command")??Co(W,"input-candidate")}function lr(W,G){if(!W.includes("$"))return W;return xa(W,G)}function iE(){let W=new Map,G=new WeakMap,H=(oe,ie)=>{let fe=`${ie}\x00${oe}`,Re=W.get(fe);if(Re)return Re;let Te=y(oe,ie);return W.set(fe,Te),Te};return{getShellSyntax:(oe,ie)=>{if(ie&&ie.source!==oe)throw TypeError("Shell syntax source does not match command program source.");let fe=ie??H(oe,"posix"),Re=G.get(fe);if(Re)return Re;let Te=fe.status==="limited"?{status:"structural-limit",source:oe,program:fe,assignmentFallbacks:[]}:Qm(oe,fe);return G.set(fe,Te),Te},getCommandProgram:H,readsAutoAsPowerShell:()=>[...W].some(([oe,ie])=>oe.startsWith("auto\x00")&&ie.dialect==="powershell")}}function sE(W){let G=W.route.kind==="grep"?rE:W.route.kind==="glob"?oE:jl;return[...Od(W.input,G),...W.route.kind==="patch"||typeof W.input==="string"?Nd(W.input):[]]}var aE=new Set(["-S","--suffix"]);function bo(W,G,H,J,oe){if(W.status==="structural-limit")throw new b;if(W.status!=="complete")return oe.findMalformedTarget(W.source);return Ps(W,G,H,J,{segment:(ie,fe)=>oe.findSegmentTarget(ie,fe),redirection:(ie,fe)=>ie.role==="file-write"&&oe.isRedirectionTarget(bn(ie.target,fe.variables),fe)?ie.target:null})}function ks(W){let G=[],H=null,J=!1;for(let oe=0;oe<W.length;oe++){let ie=W[oe];if(ie===void 0)break;if(!J&&ie==="--"){J=!0;continue}if(!J&&(ie==="-t"||ie==="--target-directory")){H=W[++oe]??null;continue}if(!J&&ie.startsWith("--target-directory=")){H=ie.slice(19);continue}if(!J&&ie.startsWith("-t")&&ie.length>2){H=ie.slice(2);continue}if(!J&&aE.has(ie)){oe++;continue}if(!J&&(ie.startsWith("--suffix=")||ie.startsWith("--backup=")))continue;if(!J&&ie.startsWith("-"))continue;G.push(ie)}return H?{sources:G,destination:H}:{sources:G.slice(0,-1),destination:G.at(-1)??null}}var v="Git metadata and hooks are protected. Ask the user before modifying them.";function uf(W,G,H,J){let oe=W.invocation.context.executionCwd;if(!G)return null;if(W.invocation.route.kind==="patch"||W.invocation.route.kind==="path"||W.invocation.route.kind==="unknown"){if(Gi(W.invocation.toolName))return null;let Re=W.paths.find((Te)=>lf(Te,oe,G,H,J,G.entries));return Re?{target:Re}:null}if(W.invocation.route.kind!=="command")return null;let ie=ar(W);if(!ie)return null;let fe=bo(ie.shell,oe,H,J,{findSegmentTarget:(Re,Te)=>yE(Re,Te,G,H,J),isRedirectionTarget:(Re,Te)=>lf(Re,Te.cwd,G,H,J,G.markerFiles),findMalformedTarget:()=>null});return fe?{target:fe}:null}function Br(W,G,H,J,oe,ie,fe=!1){if(!H)return!1;let Re=Ms(gn(W,G,oe,ie)),Te=Re.replace(/(\/\.?\*+)+$/,"");if(Te!==Re&&Te!==""){if(Vl(Te,H))return!0;let ke=fe||Re.slice(Te.length).includes("/."),Le=(Xe)=>ke?Os(Xe,Te):mE(Xe,Te);if(H.markerFiles.some(Le))return!0;return J&&Kl(H).some(Le)}if(Vl(Re,H))return!0;return J&&Kl(H).some((ke)=>Os(ke,Re))}function mE(W,G){let H=df(G,W);if(H===""||H.startsWith("..")||cf(H))return!1;return!H.split(/[\\/]/)[0]?.startsWith(".")}function fE(W,G,H,J,oe){return Br(W,G,H,!0,J,oe)}function pE(W,G,H,J,oe){if(!H)return!1;return Vl(Ms(gn(W,G,J,oe)),H)}function lf(W,G,H,J,oe,ie){let fe=Ms(gn(W,G,J,oe));return ie.includes(fe)||ff(fe,H)}function mf(W,G,H,J,oe){if(!H)return!1;return H.hooksDirectories.some((ie)=>W.some((fe)=>Os(ie,Ms(gn(fe,G,J,oe)))))}function Vl(W,G){return G.entries.includes(W)||G.directories.includes(W)||ff(W,G)}function ff(W,G){return G.hooksDirectories.some((H)=>Os(W,H))}var gE=50000;function pf(W,G){let H=[...new Set(Kl(W))];if(H.some((oe)=>G(dE(oe))))return!0;let J=0;while(H.length>0){let oe=H.pop()??"",ie=hE(oe);if(!ie)return!0;if(J+=ie.length,J>gE)return!0;if(ie.some((fe)=>G(fe.name)))return!0;H.push(...ie.filter((fe)=>fe.isDirectory()).map((fe)=>uE(oe,fe.name)))}return!1}function hE(W){try{let G=lE(W,{throwIfNoEntry:!1});if(!G)return[];if(!G.isDirectory())return G.isSymbolicLink()?null:[];return cE(W,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function Kl(W){return[...W.entries,...W.directories,...W.hooksDirectories]}function Os(W,G){let H=df(G,W);return H===""||!/^\.\.(?:[\\/]|$)/.test(H)&&!cf(H)}function Ms(W){return process.platform==="win32"?W.toLowerCase():W}function yE(W,G,H,J,oe){if(pi(W))return null;let ie=Sr([...W],J);if(Ft(ie[0]??"").toLowerCase()!=="mv")return null;let fe=ks(ie.slice(1)),Re=fe.sources.find((Te)=>fE(bn(Te,G.variables),G.cwd,H,J,oe));if(Re)return Re;return fe.destination&&pE(bn(fe.destination,G.variables),G.cwd,H,J,oe)?fe.destination:null}import{isAbsolute as Ws,normalize as xE,parse as wE,posix as Ef,resolve as Hr,sep as Xl}from"node:path";import{isAbsolute as SE,join as gf,normalize as Sf,parse as CE,sep as hf}from"node:path";var bE=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],vE=`
|
|
30
|
+
`;function hi(W,G){if(Ur(W,G))return!0;if(!W.has("TMPDIR"))return!1;return!ql(W.get("TMPDIR")??"",G)}function vo(W,G){if(W.has("TMPDIR"))return ql(W.get("TMPDIR")??"",G);let H=Yl(W,G);if(H===void 0)return!0;return ql(H,G)}function Yl(W,G){return bf(W,G,"TMPDIR")}function ql(W,G){if(!W)return!1;if(RE(W))return!1;return Eo(W,G)}function Ur(W,G){let H=bf(W,G,"IFS");return H!==void 0&&H!==""&&H!==vE}function Eo(W,G){let H=Ds(W,G.paths);if(H===null)return!1;return Cf(G).some((J)=>vr(H,J))}function Ls(W,G){let H=Ds(W,G.paths);if(H===null)return!1;return Cf(G).some((J)=>Ns(J)===Ns(H))}var yf=new WeakMap;function Cf(W){let G=yf.get(W);if(G)return G;let H=EE(W);return yf.set(W,H),H}function EE(W){let G=bE.map((J)=>Ds(J,W.paths)??Sf(J)),H=Ds(W.tmpdir,W.paths);if(!H)return G;if(process.platform==="win32")return[...G,H];if(process.platform==="darwin"&&_E(H))return[...G,H];return G}function RE(W){return/[\s$`*?[]/.test(W)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(W)||/[+@!]\([^)]*\)/.test(W)}function bf(W,G,H){return W.has(H)?W.get(H):G.env.get(H)}function _E(W){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(W)}function Ds(W,G){try{let H=Sf(W);if(!SE(H))return H;let J=CE(H).root,oe=H.slice(J.length).split(/[\\/]+/).filter(Boolean),ie=J;for(let fe=0;fe<oe.length;fe++){let Re=gf(ie,oe[fe]??"");if(G.entryKind(Re)==="missing")return gf(Re,...oe.slice(fe+1));let Te=G.realpath(Re);if(Te===null)return null;ie=Te}return ie}catch{return null}}function vr(W,G){let H=Ns(W),J=Ns(G);if(H===J)return!0;let oe=J.endsWith(hf)?J:`${J}${hf}`;return H.startsWith(oe)}function Ns(W){return process.platform==="win32"?W.toLowerCase():W}var AE=process.platform==="win32",vf=64,PE=16384;function jr(W,G,H,J){if(W.kind==="temp_target")return null;let oe=J[W.kind];if(W.kind==="dynamic_target"&&!on(H,oe.id,G.strict))return null;if(W.kind==="within_anchored_cwd"&&!on(H,oe.id,G.paranoid))return null;return Pt(oe.id,oe.reason)}function yi(W){let G=im(W,vf,vf,PE);return{expandedTargets:G&&"words"in G?G.words:void 0,unsafeBraceExpansion:G!==void 0&&"limited"in G,targetIsLiteral:G===void 0&&W.provenance==="literal"&&(W.quoted||W.raw!==W.text),tmpdirWordSplittingProtected:TE(W)}}function TE(W){let G=W.parts.filter((H)=>H.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(H.raw));return G.length>0&&G.every((H)=>IE(W.raw,H.span.start-W.span.start))}function IE(W,G){let H=null,J=!1;for(let oe=0;oe<G;oe++){let ie=W[oe];if(J){J=!1;continue}if(ie==="\\"&&H!=="'"){J=!0;continue}if(H===ie){H=null;continue}if(H===null&&(ie==="'"||ie==='"'))H=ie}return H==='"'}function Xn(W){let G=W.environment.home,H=W.environment.paths,J=W.budget??In();return{anchoredCwd:W.originalCwd??W.cwd??null,resolvedCwd:W.cwd??null,strict:W.strict??!1,paranoid:W.paranoid??!1,trustTmpdirVar:W.allowTmpdirVar??!0,posixShell:W.posixShell??!1,tmpdirWordSplittingUnsafe:W.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:W.trustedTmpdirValue??W.allowTmpdirVar??!0,environment:W.environment,allowRoots:LE(W.allowPaths,G,H,J),protectedGitMetadata:W.protectedGitMetadata,budget:J}}function An(W,G,H={}){let J=H.targetIsLiteral??!1;if(!J&&G.tmpdirWordSplittingUnsafe&&!H.tmpdirWordSplittingProtected&&GE(W))return{kind:"outside_anchored_cwd"};let oe=!J&&_f(W,G.posixShell);if(nr(W))return{kind:"outside_anchored_cwd"};if(Jl(W,J))return{kind:"root_or_home_target"};if(OE(W,G,J))return{kind:"root_or_home_target"};if(G.resolvedCwd&&Br(W,G.resolvedCwd,G.protectedGitMetadata,!0,G.environment,G.budget,!G.posixShell))return{kind:"git_metadata_target"};if(ME(W,G.trustTmpdirVar,G.posixShell,oe,J,H.tmpdirWordSplittingProtected??!1,G.trustedTmpdirValue,G.environment))return{kind:"temp_target"};if(oe)return{kind:"dynamic_target"};if(WE(W,G,J))return{kind:"temp_target"};let ie=G.anchoredCwd;if(ie){if(!H.skipHomeCwd&&BE(ie,G.environment.home,G.environment.paths,G.budget))return{kind:"home_cwd_target"};if(!H.skipCwdSelf&&[G.resolvedCwd??ie,ie].some((fe)=>UE(W,G.resolvedCwd??ie,G.environment.paths,G.budget,fe)))return{kind:"cwd_self_target"};if(HE(W,ie,G.resolvedCwd??ie,oe,J,G.environment.paths,G.budget))return{kind:"within_anchored_cwd"}}if(kE(W,G,oe))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function kE(W,G,H){let J=W.trim();if(H||!G.resolvedCwd||!G.anchoredCwd||!J)return!1;if(Ws(J)||J.startsWith("~"))return!1;if(Ql(J))return!1;if(xf(G.resolvedCwd,G.anchoredCwd,G.environment.paths,G.budget))return!1;return Eo(Hr(G.resolvedCwd,J),G.environment)}function Rf(W,G,H={}){let{containmentTarget:J,...oe}=H;if(An(W,G,oe).kind!=="temp_target")return!1;let ie=W.trim();if(NE(ie))return!1;if(Ls(ie,G.environment))return!1;return![G.anchoredCwd,G.resolvedCwd].some((fe)=>xf(J??ie,fe,G.environment.paths,G.budget))}function Jl(W,G=!1){let H=W.trim(),J=Ef.normalize(H),oe=H.replace(/\\/g,"/"),ie=J==="/"?J:J.replace(/\/+$/,"");if(ie==="/"||ie.startsWith("/")&&ie.slice(1).split("/").every((fe)=>/^\*+$/.test(fe)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(oe)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(oe))return!0;if(!G&&(J==="~"||J==="~/"||J==="~/*"))return!0;if(!G&&(J==="$HOME"||J==="$HOME/"||J==="$HOME/*"))return!0;if(!G&&(J==="${HOME}"||J==="${HOME}/"||J==="${HOME}/*"))return!0;return!1}function OE(W,G,H){let J=W.trim(),oe=H?J:J==="*"?".":J.endsWith("/*")?J.slice(0,-2):J;if(!oe)return!1;try{let ie=Ws(oe)?oe:G.resolvedCwd?Hr(G.resolvedCwd,oe):null;if(!ie)return!1;let fe=vn(Bt(ie,G.environment.paths,G.budget));if(fe===wE(fe).root)return!0;return fe===vn(Bt(G.environment.home,G.environment.paths,G.budget))}catch{return!1}}function vn(W){let G=xE(W);if(AE){if(G=G.replace(/\//g,"\\").toLowerCase(),G.length>3&&G.endsWith("\\"))G=G.slice(0,-1);return G}if(G.length>1&&G.endsWith("/"))G=G.slice(0,-1);return G}function ME(W,G,H,J,oe,ie,fe,Re){let Te=W.trim();if(Ql(Te))return!1;if(!J&&Eo(Te,Re))return!0;return(G||ie&&fe)&&H&&!oe&&DE(Te,H)}function DE(W,G){return["$TMPDIR","${TMPDIR}"].some((H)=>{if(W===H)return!0;if(!W.startsWith(`${H}/`))return!1;return!_f(W.slice(H.length+1),G)})}function NE(W){let G=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(W);if(!G)return!1;return Ef.normalize(`/${G[1]??""}`)==="/"}function Ql(W){return W.split(/[\\/]+/).includes("..")}function LE(W,G,H,J){if(!W?.length)return[];return W.flatMap((oe)=>{let ie=Yo(oe.trim(),G);if(!Ws(ie))return[];try{let fe=Bt(ie,H,J);if(Zo(fe,Bt(G,H,J)))return[];return[vn(fe)]}catch{return[]}})}function WE(W,G,H){if(G.allowRoots.length===0)return!1;let J=W.trim();if(Ql(J))return!1;let oe=H?J:Yo(J,G.environment.home),ie=G.resolvedCwd??G.anchoredCwd,fe=Ws(oe)?oe:ie?Hr(ie,oe):null;if(!fe)return!1;try{let Re=vn(Bt(fe,G.environment.paths,G.budget));return G.allowRoots.some((Te)=>Re===Te||Re.startsWith(Te.endsWith(Xl)?Te:`${Te}${Xl}`))}catch{return!1}}function GE(W){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(W)}function _f(W,G=!1){return W.includes("$")||W.includes("`")||FE(W)||G&&zE(W)}function FE(W){let G=!1;for(let H of W){if(G){G=!1;continue}if(H==="\\"){G=!0;continue}if(H==="*"||H==="?"||H==="[")return!0}return!1}function zE(W){let G=!1;for(let H=0;H<W.length;H++){let J=W[H];if(G){G=!1;continue}if(J==="\\"){G=!0;continue}if(J==="{"&&$E(W,H)||(J==="+"||J==="@"||J==="!")&&W[H+1]==="(")return!0}return!1}function $E(W,G){let H=W.indexOf("}",G+1);if(H===-1)return!1;let J=W.slice(G+1,H);return J.includes(",")||J.includes("..")}function BE(W,G,H,J){try{return vn(Bt(W,H,J))===vn(Bt(G,H,J))}catch{try{return vn(W)===vn(G)}catch{return!1}}}function UE(W,G,H,J,oe=G){if(oe===G&&(W==="."||W==="./"||W===".\\"))return!0;try{return vn(Bt(Hr(G,W),H,J))===vn(Bt(oe,H,J))}catch{try{return vn(Hr(G,W))===vn(oe)}catch{return!1}}}function HE(W,G,H,J,oe,ie,fe){let Re=H??G;if(!oe&&(W.startsWith("~")||W.startsWith("$HOME")||W.startsWith("${HOME}")))return!1;if(J)return!1;if(W.startsWith("/")||/^[A-Za-z]:[\\/]/.test(W))try{return Zl(W,G,ie,fe)}catch{return!1}if(W.startsWith("./")||W.startsWith(".\\")||!W.includes("/")&&!W.includes("\\"))try{return Zl(Hr(Re,W),G,ie,fe)}catch{return!1}if(W.startsWith("../"))return!1;try{return Zl(Hr(Re,W),G,ie,fe)}catch{return!1}}function Zl(W,G,H,J){try{return wf(Bt(W,H,J),Bt(G,H,J))}catch{return!1}}function xf(W,G,H,J){if(!G)return!1;try{return wf(Bt(G,H,J),Bt(W,H,J))}catch{return!0}}function wf(W,G){let H=vn(W),J=vn(G);return H.startsWith(`${J}${Xl}`)||H===J}var jE=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),Af="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",VE="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.",Pf="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",Tf="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",KE="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",qE="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",YE={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:Tf},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:v},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:Pf},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:KE},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:Af},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:VE},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:Af}};function If(W,G,H){return ZE(W.words.map((J)=>({kind:"word",text:J.text,dynamic:J.provenance!=="literal"})),G,Xn({...H,allowPaths:H.policy?.destructiveCommandAllowPaths}),H.policy)}function ZE(W,G,H,J){let oe=W.filter((Te)=>Te.kind==="word"),ie=JE(oe),fe=oe[ie];if(!fe||!jE.has(aR(fe.text)))return null;let Re=XE(oe.slice(ie+1));if(Re.whatIfProtected)return null;if(on(J,"powershell.remove-item-pipeline-dynamic-target",H.strict)&&G&&(Re.targets.length===0||Re.recursive))return Pt("powershell.remove-item-pipeline-dynamic-target",qE);for(let Te of Re.targets)if(!nr(Te.text)&&Jl(Si(Te.text)))return Pt(Re.recursive&&Re.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Tf);for(let Te of Re.targets)if(H.resolvedCwd&&Br(Si(Te.text),H.resolvedCwd,H.protectedGitMetadata,Re.recursive,H.environment,H.budget,!0))return Pt("powershell.remove-item-git-metadata",v);if(!Re.recursive||!Re.force)return null;if(on(J,"powershell.remove-item-recursive-force-dynamic-target",H.strict)&&(Re.hasDynamicTarget||Re.targets.length===0))return Pt("powershell.remove-item-recursive-force-dynamic-target",Pf);for(let Te of Re.targets){let ke=jr(An(Si(Te.text),H),H,J,YE);if(ke)return ke}return null}function XE(W){let G=[],H=!1,J=!1,oe=!1,ie=!1,fe=!1;for(let Re=0;Re<W.length;Re++){let Te=W[Re];if(!Te||Te.kind!=="word")continue;if(QE(Te))continue;if(fe){G.push(ec(Te)),ie=ie||Te.dynamic;continue}if(Te.text==="--"){fe=!0;continue}let ke=tR(Te.text);if(!ke){G.push(ec(Te)),ie=ie||Te.dynamic;continue}if(nR(ke.name)){let Le=ke.value?eR(ke.value,Te):W[++Re];if(Le?.kind==="word"){G.push(ec(Le)),ie=ie||Le.dynamic;continue}ie=!0;continue}if(rR(ke.name)){H=!0;continue}if(oR(ke.name)){J=!0;continue}if(iR(ke.name))oe=sR(ke.value)}return{targets:G,recursive:H,force:J,whatIfProtected:oe,hasDynamicTarget:ie}}function JE(W){let G=W[0];if(G?.kind==="word"&&G.text==="&"||G?.text===".")return W.length>1?1:0;return 0}function ec(W){return{text:W.kind==="word"?W.text:"",dynamic:W.kind==="word"&&W.dynamic}}function QE(W){return W.kind==="word"&&W.text===","}function Si(W){let G=W.replace(/\\/g,"/"),H=/^(?:\$env:(?:userprofile|home)|\$home|\$\{home\})(?=$|\/)/i.exec(G);return H?`$HOME${G.slice(H[0].length)}`:G}function eR(W,G){return{kind:"word",text:W,dynamic:G.kind==="word"&&(G.dynamic||W.includes("$"))}}function tR(W){if(!W.startsWith("-")||W==="-")return null;let G=W.slice(1),H=G.indexOf(":");if(H===-1)return{name:G.toLowerCase()};return{name:G.slice(0,H).toLowerCase(),value:G.slice(H+1)}}function nR(W){return"path".startsWith(W)||"literalpath".startsWith(W)}function rR(W){return"recurse".startsWith(W)}function oR(W){return W.length>=2&&"force".startsWith(W)}function iR(W){return W==="wi"||"whatif".startsWith(W)}function sR(W){if(W===void 0||W==="")return!0;let G=W.toLowerCase();return G==="$true"||G==="true"}function aR(W){return W.toLowerCase()}var lR=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),cR=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),dR=new Set(["-o","--output","--query","--subscription"]),uR=new Set;function kf(W){if(W==="aws")return lR;if(W==="gcloud")return cR;if(W==="az")return dR;return uR}var mR=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),fR=new Set;function Of(W){if(W==="git")return _n;if(W==="docker")return mR;return fR}function N(W,G){if(W.length===0||G.length===0)return null;let H=zt(W[0]??""),J=Cn(W);for(let oe of G){if(!hR(H,oe.command))continue;if(oe.match){if(pR(H,W,oe.match))return Mf(oe);continue}if(!yR(H,W,oe.subcommand))continue;if(CR(W,new Set(oe.block_args),J))return Mf(oe)}return null}function Mf(W){return{id:`custom.${W.name}`,reason:`[${W.name}] ${W.reason}`,intent:W.intent??"manual_only"}}function pR(W,G,H){let J=G.slice(1);if(H.exclude_args?.some((oe)=>J.includes(oe)))return!1;if(H.any_args&&!H.any_args.some((oe)=>J.includes(oe)))return!1;return gR(J,H.command_path,kf(W))}function gR(W,G,H){let J=0,oe=!1;for(let ie of W){if(J>=G.length)return!0;if(oe){oe=!1;continue}if(ie.startsWith("-")){oe=!ie.includes("=")&&H.has(ie);continue}if(ie!==G[J])return!1;J++}return J>=G.length}function hR(W,G){return W===zt(G)}function yR(W,G,H){if(!H)return!0;return Df(G,1,H,Of(W))}function Df(W,G,H,J){let oe=!1;for(let ie=G;ie<W.length;ie++){let fe=W[ie];if(!fe)continue;if(oe){oe=!1;continue}if(fe==="--"){let Re=W[ie+1];if(Re&&!Re.startsWith("-"))return Re===H;return!1}if(J.has(fe)){oe=!0;continue}if(fe.startsWith("-")){if(!fe.includes("=")&&SR(W,ie,H,J))return!0;continue}return fe===H}return!1}function SR(W,G,H,J){let oe=W[G+1];if(!oe||oe.startsWith("-"))return!1;return Df(W,G+2,H,J)}function CR(W,G,H){return W.some((J)=>G.has(J))||[...H].some((J)=>G.has(J))}var bR=new Set(["-e","--source"]),vR=new Set(["-F","-v","--assign","--field-separator"]),Nf=new Set(["-f","--file"]),ER=new Set(["print","printf","return"]),Lf=[{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"}],RR="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 Wf(W,G,H){let J=!1;for(let oe of _R(W)){let ie=xR(oe,H);if(!ie)continue;for(let fe of ie.commands){let Re=G(fe);if(Re)return Re;if(fe.includes("{}")||/[$`]/.test(fe))J=!0}J||=ie.dynamic}return J?Pt("awk.system-dynamic",RR):null}function nc(W){let G=[],H=!1,J=!1,oe=!0,ie=!0;for(let fe=1;fe<W.length;fe++){let Re=W[fe];if(Re===void 0)break;if(oe&&Re==="--"){oe=!1;continue}if(oe&&bR.has(Re)){H=!0;let Te=W[fe+1];if(ie&&=Te!==void 0,Te!==void 0)G.push({tokenIndex:fe+1,kind:"inline-code",value:Te});fe++;continue}if(oe&&Re.startsWith("--source=")){H=!0,G.push({tokenIndex:fe,kind:"inline-code",value:Re.slice(9)});continue}if(oe&&Re.startsWith("-e")&&Re.length>2){H=!0,G.push({tokenIndex:fe,kind:"inline-code",value:Re.slice(2)});continue}if(oe&&(vR.has(Re)||Nf.has(Re))){let Te=W[fe+1];if(ie&&=Te!==void 0,Nf.has(Re)){if(J=!0,Te!==void 0)G.push({tokenIndex:fe+1,kind:"program-file",value:Te})}fe++;continue}if(oe&&(Re.startsWith("-F")||Re.startsWith("-v")&&Re.slice(2).includes("=")))continue;if(oe&&Re.startsWith("-f")&&Re.length>2){J=!0,G.push({tokenIndex:fe,kind:"program-file",value:Re.slice(2)});continue}if(oe&&(Re.startsWith("--assign=")||Re.startsWith("--field-separator=")))continue;if(oe&&Re.startsWith("--file=")){J=!0,G.push({tokenIndex:fe,kind:"program-file",value:Re.slice(7)});continue}if(oe&&Re.startsWith("-")&&Re!=="-")continue;if(!H&&!J)G.push({tokenIndex:fe,kind:"main-program",value:Re});return{sources:G,optionsOpen:!1}}return{sources:ie?G:[],optionsOpen:oe&&ie}}function bi(W){return nc(W).sources}function _R(W){return bi(W).filter((G)=>G.kind!=="program-file").map((G)=>G.value)}function xR(W,G){wn(G,W);let H=W.includes("system")?rc(W,G):null,J=wR(W,G);if(!H&&!J)return null;return{dynamic:!!H?.dynamic||!!J?.dynamic,commands:[...H?.commands??[],...J?.commands??[]]}}function rc(W,G){wn(G,W);let H=[],J=!1,oe=!1,ie=0;while(ie<W.length){let fe=W[ie];if(fe==='"'||fe==="'"){ie=Fs(W,ie,fe)?.endIndex??ie+1;continue}if(fe==="#"){ie=Gf(W,ie+1);continue}if(fe==="/"&&Ff(W,ie)){ie=zf(W,ie+1)??ie+1;continue}if(!W.startsWith("system",ie)){ie++;continue}let Re=ie;if(ie+=6,Ci(W[Re-1])||Ci(W[ie]))continue;let Te=Gs(W,ie);if(W[Te]!=="(")continue;Te=Gs(W,Te+1);let ke=W[Te];if(ke!=='"'&&ke!=="'"){J=!0,oe=!0;continue}let Le=Fs(W,Te,ke);if(!Le){J=!0,oe=!0;continue}if(Te=Gs(W,Le.endIndex),J=!0,W[Te]!==")"){oe=!0,ie=Le.endIndex;continue}H.push(Le.value),ie=Te+1}if(!J)return null;return{dynamic:oe,commands:H}}function wR(W,G){wn(G,W);let H=[],J=!1,oe=!1,ie=0,fe=0,Re=null,Te=null,ke=0;while(ie<W.length){let Le=W[ie];if(!Le)break;if(Le==='"'||Le==="'"){let Ze=Fs(W,ie,Le);if(Ze&&ke===fe)Te={...Ze,startIndex:ie};ke=Ze?.endIndex??ie+1,ie=Ze?.endIndex??ie+1;continue}if(Le==="#"){ie=Gf(W,ie+1),fe=ie,Re=null,Te=null,ke=ie;continue}if(Le==="/"&&Ff(W,ie)){let Ze=zf(W,ie+1);ke=Ze??ie+1,ie=Ze??ie+1;continue}if(`;
|
|
31
|
+
{}`.includes(Le)){ie++,fe=ie,Re=null,Te=null,ke=ie;continue}if(Re===null&&(tc(W,ie,"print")||tc(W,ie,"printf")))Re=ie;if(Le!=="|"||W[ie-1]==="|"||W[ie+1]==="|"){if(!/\s/.test(Le))ke=ie+1;ie++;continue}let Xe=W[ie+1]==="&"?ie+2:ie+1,Ye=Gs(W,Xe);if(tc(W,Ye,"getline")){oe=!0;let Ze=TR(fe,Te,ke);if(J||=Ze===null,Ze!==null)H.push(Ze);ke=Xe,ie=Xe;continue}if(kR(fe,Re)){oe=!0;let Ze=PR(W,Ye);if(!Ze){J=!0,ke=Xe,ie=Xe;continue}if(!AR(W,Ze.endIndex)){J=!0,ke=Ze.endIndex,ie=Ze.endIndex;continue}H.push(Ze.value),ke=Ze.endIndex,ie=Ze.endIndex;continue}ke=Xe,ie++}if(!oe)return null;return{dynamic:J,commands:H}}function Ci(W){return!!W&&/[A-Za-z0-9_]/.test(W)}function Gs(W,G){let H=G;while(/\s/.test(W[H]??""))H++;return H}function AR(W,G){let H=G;while(/[\t\f\v\r ]/.test(W[H]??""))H++;let J=W[H];return!J||`;
|
|
32
|
+
}#`.includes(J)}function Fs(W,G,H){let J="",oe=!1;for(let ie=G+1;ie<W.length;ie++){let fe=W[ie];if(!fe)break;if(oe){let Re=IR(W,ie);if(!Re)return null;J+=Re.value,ie=Re.endIndex,oe=!1;continue}if(fe==="\\"){oe=!0;continue}if(fe===H)return{value:J,endIndex:ie+1};J+=fe}return null}function PR(W,G){let H=W[G];if(H!=='"'&&H!=="'")return null;return Fs(W,G,H)}function TR(W,G,H){if(!G)return null;return G.startIndex>=W&&G.endIndex===H?G.value:null}function IR(W,G){let H=W[G];if(!H)return null;if(H==="x"){let oe=W.slice(G+1,G+3);if(!/^[0-9A-Fa-f]{2}$/.test(oe))return null;return{value:String.fromCharCode(Number.parseInt(oe,16)),endIndex:G+2}}if(/[0-7]/.test(H)){let oe=/^[0-7]{1,3}/.exec(W.slice(G));if(!oe)return null;return{value:String.fromCharCode(Number.parseInt(oe[0],8)),endIndex:G+oe[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
|
|
33
|
+
`,r:"\r",t:"\t",v:"\v"}[H]??H,endIndex:G}}function tc(W,G,H){return W.startsWith(H,G)&&!Ci(W[G-1])&&!Ci(W[G+H.length])}function kR(W,G){return G!==null&&G>=W}function Gf(W,G){let H=W.indexOf(`
|
|
34
|
+
`,G);return H===-1?W.length:H+1}function Ff(W,G){let H=OR(W,G);if(H===-1)return!0;if("{([,;!~=".includes(W[H]??""))return!0;let J=H;while(Ci(W[J-1]))J--;return ER.has(W.slice(J,H+1))}function OR(W,G){for(let H=G-1;H>=0;H--)if(!/\s/.test(W[H]??""))return H;return-1}function zf(W,G){let H=!1;for(let J=G;J<W.length;J++){let oe=W[J];if(!oe)break;if(H){H=!1;continue}if(oe==="\\"){H=!0;continue}if(oe==="/")return J+1}return null}var MR=new Set(["sudo","env","command","builtin"]),DR=new Set(["caffeinate","exec","nice","nohup","setsid","stdbuf","time","timeout"]);function zs(W,G){let H=W[0];if(!H||!$f(Ft(H),G))return null;let J=Ft(H),oe=W[1]==="--"?2:1,ie=NR(W,oe,J,G),fe=ie[0];if(fe===void 0)return null;return{wrapper:J,tokens:W.slice(fe),childIndex:fe,alternativeChildIndices:ie.slice(1)}}function NR(W,G,H,J){let oe=W[1]==="--",ie=[];for(let fe=G;fe<W.length;fe++){let Re=W[fe];if(!Re)continue;let Te=Ft(Re)!==H&&LR(Re,J);if(Te)ie.push(fe);if(!Te&&Ki.has(zt(Re)))break;if(oe)break}return ie}function LR(W,G){let H=Ft(W),J=zt(W);return J==="git"||H==="busybox"||Vr(W)||Va.has(H)||Tm(J)||$f(H,G)||en.has(J)||W==="$SHELL"||$n(J)||Mn.has(J)||G.rules.some((oe)=>oe.command===H)}function $f(W,G){return DR.has(W)||G.transparentWrappers.includes(W)}function Vr(W){return MR.has(W.toLowerCase())}function Kr(W,G){return{embedded:!1,cwd:W.cwd,originalCwd:G.originalCwd,effectiveCwd:W.cwd,envAssignments:W.envAssignments,allowTmpdirVar:G.allowTmpdirVar,worktreeMode:G.worktreeMode,wrappedByTransparent:!1}}function jn(W,G){let H=G.policy??{rules:[],transparentWrappers:[]};return $s([...W],G.environment,G.cwd,G.cwd,new Map,new Map(G.envAssignments??[]),H,{iterations:0},!1)}function*$s(W,G,H,J,oe,ie,fe,Re,Te){let ke=_s(W,G,H,ie);for(let[Ze,Qe]of ke.envAssignments)ie.set(Ze,Qe),oe.set(Ze,Qe);let{tokens:Le,cwd:Xe}=ke;if(ke.envSplitValues){let Ze=Rs(ke.envSplitValues,Le);if(!Ze)throw new s("derivedCommandShape");oc(Re),yield*$s(Ze,G,Xe,J,oe,ie,fe,Re,Te);return}if(Vr(Le[0]??""))throw new s("wrapperPeelIterations");let Ye=zs(Le,fe);if(Ye){for(let Ze of[Ye.childIndex,...Ye.alternativeChildIndices])oc(Re),yield*$s(Ze===Ye.childIndex?Ye.tokens:Le.slice(Ze),G,Xe,J,new Map(oe),new Map(ie),fe,Re,!0);return}if(GR(Le)){oc(Re),yield*$s(Le.slice(1),G,Xe,J,oe,ie,fe,Re,Te);return}yield WR(Le,Xe,J,oe,ie,Te)}function WR(W,G,H,J,oe,ie){return{tokens:W,cwd:G===null?void 0:G??H,wrapperCwd:G,wrapperEnvAssignments:J,envAssignments:oe,head:Ft(W[0]??"").toLowerCase(),wrappedByTransparent:ie}}function oc(W){if(W.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");W.iterations++}function GR(W){return Ft(W[0]??"").toLowerCase()==="busybox"&&W.length>1}function ic(W,G){let H=[],J=G;while(J<W.length){let oe=W[J];if(oe===void 0||oe===":::")break;H.push(oe),J++}return{markerIndex:J<W.length&&W[J]===":::"?J:-1,templateTokens:H}}function cr(W){let G=!1,H=!1;for(let J of W){if(J==="--")break;if(J==="-r"||J==="-R"||sc(J,"recursive")){G=!0;continue}if(J==="-f"||sc(J,"force")){H=!0;continue}if(J.startsWith("-")&&!J.startsWith("--")){if(J.includes("r")||J.includes("R"))G=!0;if(J.includes("f"))H=!0}}return G&&H}function Bs(W){let G=W.indexOf("--");return W.slice(1,G===-1?void 0:G).some((H)=>sc(H,"recursive")||/^-[A-Za-z]+$/.test(H)&&/[rR]/.test(H.slice(1)))}function sc(W,G){return W.length>2&&W.startsWith("--")&&G.startsWith(W.slice(2))}var FR=["--init-file","--rcfile"],zR=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function Wn(W){for(let G=1;G<W.length;G++){let H=W[G];if(!H)continue;if(H==="-c")return Uf(W,G,!0);if(H.startsWith("-")&&H.includes("c")&&!H.startsWith("--")){let J=Uf(W,G,!1);if(J!==null)return J}}return null}var Bf=/^-[cn]+$/;function Vn(W){let G=W.slice(1);if(G.some((J)=>/^[-+]./.test(J)&&J!=="--"&&!Bf.test(J)))return!1;let H=G.findIndex((J)=>!Bf.test(J));return G.slice(0,H===-1?void 0:H).some((J)=>J.includes("n"))}var $R=/^-[abcefhiklmnprstuvx]+$/;function Us(W){let G=W.findIndex((ie,fe)=>fe>0&&!$R.test(ie)),H=G===-1||/^[-+]/.test(W[G]??"")?W.slice(1):W.slice(1,G+1);if(H.some((ie)=>ie.startsWith("+")))return!0;let J=H.filter((ie)=>ie.startsWith("-")&&!ie.startsWith("--")&&ie.includes("c"));if(J.length===0)return!1;let oe=Wn(W);if(oe===null)return H.some((ie)=>ie.startsWith("-")&&!J.includes(ie));return/^[-+]/.test(oe)||J.some((ie)=>/[oO]/.test(ie))}function Uf(W,G,H){if(W[G+1]==="--")return W[G+2]||null;let J=W[G+1];if(!J||!H&&J.startsWith("-"))return null;return J}function Hf(W){let G=Ft(W[0]??"").toLowerCase(),H=BR(W,G),J=zR.get(G)??null,oe=H.argvSource?.kind!=="absent";return{argvSource:G==="bash"?H.argvSource:null,argvSourceApplies:G==="bash"&&H.interactive&&H.argvSource?.kind==="literal",envName:J,envSourceApplies:oe&&(J==="BASH_ENV"?!H.interactive:J==="ENV"&&H.interactive)}}function BR(W,G){let H=Dn(W),J=H.commandIndex??H.scriptIndex??W.length,oe=[],ie=!1,fe=!0;for(let Re=1;Re<J;Re++){let Te=W[Re];if(Te===void 0||Te==="--"||Te==="-"||Te[0]!=="-"&&Te[0]!=="+")break;if(Te.startsWith("--")){if(G==="bash"&&fe?FR.find((Ye)=>Te===Ye):void 0){let Ye=W[Re+1];oe.push(Ye===void 0?{kind:"absent"}:{kind:"literal",value:Ye}),Re++;continue}let Xe=Te.split("=",1)[0]??Te;if(G==="bash"&&Ha.has(Xe)&&!Te.includes("="))Re++;continue}if(G==="bash")fe=!1;let ke=ja(G,Te,W[Re+1],"startup");if(ke.interactive)ie=Te[0]==="-";Re+=ke.followingValues}return{argvSource:oe.at(-1)??null,interactive:ie}}var UR="find -delete permanently removes files. Use -print first to preview.",HR="find -exec rm -rf is dangerous. Use explicit file list instead.",jR=new Set(["-exec","-execdir","-ok","-okdir"]),VR=new Map([...["-Bmin","-Bnewer","-Btime","-amin","-anewer","-atime","-cmin","-cnewer","-context","-ctime","-f","-flags","-fprint","-fprint0","-fls","-fstype","-gid","-group","-ilname","-iname","-inum","-ipath","-iwholename","-iregex","-links","-lname","-maxdepth","-mindepth","-mmin","-mnewer","-mtime","-name","-newer","-newerXY","-newermt","-path","-perm","-printf","-regex","-samefile","-size","-type","-uid","-used","-user","-wholename","-xattrname","-xtype"].map((W)=>[W,1]),["-fprintf",2]]);function jf(W,G){let H=W.map(t),J=KR(W,H,G);if(J)return J;if(Hs(H,1)&&!QR(W,H,G)){let fe=Nt(Pt("find.delete",UR),G.policy);if(fe)return fe}let oe=G.budget??In(),ie=0;while(ie<H.length){let fe=H[ie],Re=dr(fe??"");if(Re>0){ie+=Re+1;continue}if(!Jn(fe)){ie++;continue}oe.charge("derivedTokens",H.length-ie-1);let Te=Ro(H,ie);ie=Te.nextIndex;let ke=t_(Te.tokens,G.environment);if(ke){let Ze=Nt(ke,G.policy);if(Ze)return Ze}let Le=fe==="-execdir"||fe==="-okdir",Xe=G.analyzeTokens?.(Te.tokens,Le?null:G.cwd)??null,Ye=Xe?.id.startsWith("custom.")?Xe:Nt(Xe,G.policy);if(Ye)return Ye}return null}function KR(W,G,H){if(!Hs(G,1)&&!ac(G,H.environment))return null;let oe=vi(W)??Qt(["."]),ie=Xn({...H,allowPaths:H.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let fe of oe){let Re=yi(fe);for(let Te of Re.expandedTargets??[t(fe)]){let ke=An(Te,ie,{targetIsLiteral:Re.expandedTargets!==void 0||Re.targetIsLiteral,tmpdirWordSplittingProtected:Re.tmpdirWordSplittingProtected});if(ke.kind==="root_or_home_target")return Pt("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(ke.kind==="git_metadata_target"&&!qR(W,ie.protectedGitMetadata,H.environment))return Pt("find.delete-git-metadata",v)}}if(JR(G)&&ie.resolvedCwd&&mf(oe.map(t),ie.resolvedCwd,ie.protectedGitMetadata,ie.environment,ie.budget))return Pt("find.delete-git-metadata",v);return null}function qR(W,G,H){if(!G)return!1;let J=W.map(t),oe=[],ie=!1,fe=vi(W)?.at(-1),Re=fe?W.indexOf(fe)+1:1;while(Re<J.length){let Te=J[Re]??"";if(Jn(Te)){let ke=Ro(J,Re),Le=Sr([...ke.tokens],H),Xe=Bs(Le),Ye=en.has(Ft(Le[0]??"").toLowerCase()),Ze=ke.tokens.some((et)=>et!=="{}"&&et.includes("{}")),Qe=(Te==="-execdir"||Te==="-okdir")&&Le.slice(1).some((et)=>et!=="{}"&&!et.startsWith("-"));if(Xe||Ye||Ze||Qe)return!1;ie=!0,Re=ke.nextIndex;continue}if(Te==="-delete"){ie=!0,Re++;continue}if(Te==="-name"||Te==="-iname"){let ke=W[Re+1];if(!(ke?.provenance==="literal"&&!/[[\\]/.test(ke.text)))return!1;if(!ie)oe.push(ZR(ke.text,Te==="-iname"));Re+=2;continue}if(!YR.has(Te))return!1;Re+=1+dr(Te)}return oe.length>0&&!pf(G,(Te)=>oe.every((ke)=>ke.test(Te)))}var YR=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function ZR(W,G){let H=W.replace(/[*?]|[.+^${}()|\]/]/g,(J)=>J==="*"?".*":J==="?"?".":`\\${J}`);return new RegExp(`^${H}$`,G?"isu":"su")}var XR=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function ac(W,G){let H=0;while(H<W.length){if(!Jn(W[H])){H++;continue}let J=Ro(W,H),oe=Sr([...J.tokens],G),ie=Ft(oe[0]??"").toLowerCase(),fe=en.has(ie)&&XR.test((Wn(oe)??"").replace(/["'\\]/g,""));if((ie==="rm"||ie==="rmdir"||fe)&&oe.some((Te)=>Te.includes("{}")))return!0;H=J.nextIndex}return!1}function JR(W){return W.some((G,H)=>{if(!["-name","-iname"].includes(G))return!1;return W[H+1]?.toLowerCase()==="hooks"})}function QR(W,G,H){if(G.includes("-L")||G.includes("-f")||G.includes("-follow"))return!1;let J=vi(W);if(!J)return!1;let oe=H.envAssignments??new Map,ie=Yl(oe,H.environment),fe=H.trustedTmpdirValue??vo(oe,H.environment),Re=H.allowTmpdirVar??!hi(oe,H.environment),Te={environment:H.environment,protectedGitMetadata:H.protectedGitMetadata,cwd:H.cwd,originalCwd:H.originalCwd,strict:H.strict,allowTmpdirVar:Re&&fe&&Boolean(ie),allowPaths:H.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:H.tmpdirWordSplittingUnsafe??Ur(oe,H.environment),trustedTmpdirValue:fe,budget:H.budget},ke=Xn(Te),Le=Xn({...Te,cwd:H.originalCwd??H.cwd}),Xe=H.originalCwd&&H.environment.paths.realpath(H.originalCwd),Ye=H.cwd&&H.environment.paths.realpath(H.cwd),Ze=Xe&&Ye&&!vr(Ye,Xe)?H.cwd:void 0;return J.every((Qe)=>{let et=yi(Qe);if(et.unsafeBraceExpansion)return!1;return(et.expandedTargets??[t(Qe)]).every((tt)=>{let gt=/^\.\/*$/.test(tt)?Ze:void 0,_t=gt??tt,yt={targetIsLiteral:et.expandedTargets!==void 0||et.targetIsLiteral,tmpdirWordSplittingProtected:et.tmpdirWordSplittingProtected};if(!on(H.policy,"rm.recursive-force-paranoid",H.paranoid??!1)&&!gt&&An(_t,ke,yt).kind==="within_anchored_cwd")return!0;return Rf(_t,gt?Le:ke,{...yt,containmentTarget:e_(_t,ie)})})})}function e_(W,G){if(!G)return W;return W.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>G)}function vi(W){let G=(oe)=>{let ie=W[oe];return ie?t(ie):void 0},H=1;while(G(H)==="-H"||G(H)==="-P")H++;if(G(H)==="--")H++;let J=[];while(H<W.length){let oe=G(H),ie=W[H];if(!oe||!ie||oe.startsWith("-")||["!","(",")"].includes(oe))break;J.push(ie),H++}return J.length>0?J:null}function t_(W,G){let H=yr([...W],G);if(H.length===0)return null;let J=Ft(H[0]??"");if(J==="busybox"&&H.length>1)H=H.slice(1),J=Ft(H[0]??"");if(J==="rm"&&cr(H))return Pt("find.exec-rm-recursive-force",HR);return null}function Ro(W,G){let H=G+1;while(H<W.length&&W[H]!==";"&&!(W[H]==="+"&&W[H-1]==="{}"))H++;return{tokens:W.slice(G+1,H),nextIndex:Math.min(H+1,W.length)}}function Hs(W,G){let H=G;while(H<W.length){let J=W[H];if(!J){H++;continue}if(Jn(J)){H=Ro(W,H).nextIndex;continue}let oe=dr(J);if(oe>0){H+=oe+1;continue}if(J==="-delete")return!0;H++}return!1}function dr(W){return VR.get(W)??(/^-newer[A-Za-z]{2}$/.test(W)?1:0)}function Jn(W){return W!==void 0&&jR.has(W)}import{resolve as Ix}from"node:path";function*lc(W){for(let G of W.nodes)yield*r_(G)}function n_(W){return[...lc(W)]}function Rt(W){return n_(W).map((G)=>G.words.map((H)=>H.text))}function Ei(W){let G=y(W,"posix");if(G.status!=="complete"||G.nodes.length!==1)return null;let H=G.nodes[0];if(H?.kind!=="command")return null;if(H.redirections.length>0||H.nested.length>0)return null;if(H.words.some((J)=>J.provenance==="command-substitution"))return null;return H.words.map((J)=>J.text)}function*r_(W){if(W.kind==="command"){yield W;for(let G of W.nested)yield*lc(G);return}if(W.kind==="group")yield*lc(W.body)}var o_=5,cc="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 un(W){let G=W.indexOf("--");if(G===-1)return{index:-1,before:W,after:[]};return{index:G,before:W.slice(0,G),after:W.slice(G+1)}}function Kf(W,G,H){let J=_o(W,G,H),oe=i_(J.entries);if(oe.size===0)return{blockedReason:J.blockedReason,expanded:!1,tokens:W};let ie=W,fe=!1;for(let Re=0;Re<o_;Re++){let{subcommand:Te,rest:ke}=Pn(ie),Le=Te?.toLowerCase();if(!Le||!oe.has(Le))return{blockedReason:J.blockedReason,expanded:fe,tokens:ie};let Xe=oe.get(Le),Ye=d_(Xe);if(Ye===null||Ye.length===0)return{blockedReason:cc,expanded:!0,tokens:ie};ie=["git",...Ye,...ke],fe=!0}return{blockedReason:cc,expanded:!0,tokens:ie}}function qf(W,G,H){return _o(W,G,H).entries.some((J)=>J.key.toLowerCase()==="core.sshcommand")}function Pn(W){if(W.length===0)return{subcommand:null,rest:[]};let G=W[0];if((G?Ft(G).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let J=1;while(J<W.length){let oe=W[J];if(!oe)break;if(oe==="--"){let ie=W[J+1];if(ie&&!ie.startsWith("-"))return{subcommand:ie,rest:W.slice(J+2)};return{subcommand:null,rest:W.slice(J+1)}}if(!oe.startsWith("-"))return{subcommand:oe,rest:W.slice(J+1)};J+=_n.has(oe)?2:1}return{subcommand:null,rest:[]}}function i_(W){let G=new Map;for(let H of W){let J=H.key.toLowerCase();if(!J.startsWith("alias."))continue;let oe=J.slice(6);if(oe!=="")G.set(oe,H.value)}return G}function _o(W,G,H){if(W.length===0)return{blockedReason:null,entries:[]};let J=W[0];if((J?Ft(J).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let ie=a_(G,H);return{blockedReason:ie.blockedReason,entries:[...ie.entries,...s_(W,G,H)]}}function s_(W,G,H){let J=[],oe=1;while(oe<W.length){let ie=W[oe];if(!ie||ie==="--"||!ie.startsWith("-"))return J;if(ie==="-c"){let fe=dc(W[oe+1]);if(fe)J.push(fe);oe+=2;continue}if(ie.startsWith("-c")&&ie.length>2){let fe=dc(ie.slice(2));if(fe)J.push(fe);oe++;continue}if(ie==="--config-env"){let fe=Vf(W[oe+1],G,H);if(fe)J.push(fe);oe+=2;continue}if(ie.startsWith("--config-env=")){let fe=Vf(ie.slice(13),G,H);if(fe)J.push(fe);oe++;continue}if(_n.has(ie)){oe+=2;continue}oe++}return J}function a_(W,G){let H=l_(W,G),J=c_(W,G);return{blockedReason:H===null||J===null?cc:null,entries:[...H??[],...J??[]]}}function l_(W,G){let H=sr("GIT_CONFIG_PARAMETERS",W,G);if(H===void 0)return[];let J=[],oe=Ei(H);if(!oe)return null;for(let ie of oe){let fe=dc(ie);if(!fe)return null;J.push(fe)}return J}function c_(W,G){let H=Fm(W,G);if(H.state==="absent")return[];if(H.state==="invalid")return null;let J=[];for(let oe=0;oe<H.count;oe++){let ie=sr(`GIT_CONFIG_KEY_${oe}`,W,G)?.trim(),fe=sr(`GIT_CONFIG_VALUE_${oe}`,W,G);if(!ie||fe===void 0)return null;J.push({key:ie,value:fe})}return J}function dc(W){if(!W)return null;let G=W.indexOf("=");return{key:(G===-1?W:W.slice(0,G)).trim(),value:G===-1?void 0:W.slice(G+1)}}function Vf(W,G,H){let J=W?.indexOf("=")??-1;if(!W||J===-1)return null;return{key:W.slice(0,J).trim(),value:sr(W.slice(J+1),G,H)}}function d_(W){let G=W?.trimStart();if(!G||G.startsWith("!"))return null;return Ei(G)}var u_="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",m_="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",f_="git checkout --force discards uncommitted changes. Use 'git stash' first.",p_="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",g_="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",h_="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",y_="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",S_="git switch --force discards uncommitted changes. Use 'git stash' first.",C_="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",b_="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",v_="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",E_="git reset --merge can lose uncommitted changes. Use 'git stash' first.",R_="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",__="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.",x_="git push --force destroys remote history. Use --force-with-lease for safer force push.",w_="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",A_="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",P_="git branch -D force-deletes without merge check. Use -d for safe delete.",T_="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",I_="git merge --abort discards merge conflict resolutions. Use 'git status' first.",k_="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",O_="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",M_="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",D_="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",N_="git worktree remove --force can delete uncommitted changes. Remove --force flag.",L_=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),W_=new Set(["--recurse-submodules","--track","-t"]),uc=new Set(["-b","-B","-U"]),mc=new Set(["-c","-C"]),G_=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function $t(W,G){let H=W.split("=",1)[0]??W;return H.length>=4&&G.startsWith(H)&&H.startsWith("--")&&H.slice(2).length>=2}var xo=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function Zf(W,G){let{subcommand:H,rest:J}=Pn(W);if(!H)return null;switch(H.toLowerCase()){case"checkout":return Er(F_(J,G));case"switch":return Er($_(J));case"restore":return Er(U_(J));case"reset":return j_(J);case"clean":return Er(K_(J));case"rm":return Er(q_(J));case"push":return qr(Y_(J));case"branch":return qr(J_(J));case"stash":return qr(rx(J));case"worktree":return qr(ox(J));case"rebase":return Er(Q_(J));case"merge":return Er(ex(J));case"tag":return qr(tx(J));case"reflog":return qr(nx(J));default:return null}}function Er(W){return W?{...W,localDiscard:!0}:null}function qr(W){return W?{...W,localDiscard:!1}:null}function F_(W,G){let{index:H,before:J}=un(W),oe=Cn(J,{shortOptsWithValue:uc});if(J.some((Re)=>$t(Re,"--force"))||oe.has("-f"))return Pt("git.checkout-force",f_);for(let Re of W){if(Re==="-b"||Re==="-B"||Re==="--orphan")return null;if($t(Re,"--pathspec-from-file"))return Pt("git.checkout-pathspec-from-file",g_)}if(H!==-1){if(J.some((Te)=>!Te.startsWith("-")))return Pt("git.checkout-ref-path",p_);return Pt("git.checkout-double-dash",u_)}let ie=B_(W);if(ie.length>=2)return Pt("git.checkout-ambiguous",h_);let fe=ie[0];if(fe===void 0||oe.has("-d")||oe.has("-t")||W.some((Re)=>$t(Re,"--detach")||$t(Re,"--track")))return null;if(z_(fe)||G(fe))return Pt("git.checkout-double-dash",m_);return null}function z_(W){return W==="."||W===".."||/^\.\.?[/\\]/.test(W)||/^([/\\]|[A-Za-z]:[/\\])/.test(W)||W.endsWith("/")||W.startsWith(":")||/[*?[]/.test(W)}function $_(W){let{before:G}=un(W);if(G.some((J)=>$t(J,"--discard-changes")))return Pt("git.switch-discard-changes",y_);let H=Cn(G,{shortOptsWithValue:mc});if(G.some((J)=>$t(J,"--force"))||H.has("-f"))return Pt("git.switch-force",S_);return null}function B_(W){let G=[],H=0;while(H<W.length){let J=W[H];if(!J)break;if(J==="--")break;if(!J.startsWith("-")){G.push(J),H++;continue}if(L_.has(J)){H+=2;continue}if(W_.has(J)){let oe=W[H+1],ie=J==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"];H+=oe&&!oe.startsWith("-")&&ie.includes(oe)?2:1;continue}H++}return G}function U_(W){let G=H_(W);if(G.isTerminal||!G.hasPathspec&&!G.hasPatch||!G.hasWorktree)return null;return G.hasExplicitLocation?Pt("git.restore-worktree",b_):Pt("git.restore-unstaged",C_)}function H_(W){let G=!1,H=!1,J=!0,oe=!1,ie=(fe)=>{if(!oe)J=!1,oe=!0;if(fe!==void 0)J=fe};for(let fe=0;fe<W.length;fe++){let Re=W[fe];if(Re===void 0)break;if(Re==="--"){G||=fe+1<W.length;break}if(Re==="--pathspec-from-file"){G=!0,fe++;continue}if(Re.startsWith("--pathspec-from-file=")){G=!0;continue}if(Re==="-h"||Re==="--help"||Re==="--version")return{hasPathspec:G,hasPatch:H,hasWorktree:J,hasExplicitLocation:oe,isTerminal:!0};if(Re==="--staged"){ie();continue}if(Re==="--no-staged"){ie();continue}if(Re==="--worktree"){ie(!0);continue}if(Re==="--no-worktree"){ie(!1);continue}if(Re==="--patch"){H=!0;continue}if(Re==="--no-patch"){H=!1;continue}if(G_.has(Re)){fe++;continue}if(Re.startsWith("--"))continue;if(Re==="-"){G=!0;continue}if(!Re.startsWith("-")){G=!0;continue}for(let Te=1;Te<Re.length;Te++){let ke=Re.charAt(Te);if(ke==="h")return{hasPathspec:G,hasPatch:H,hasWorktree:J,hasExplicitLocation:oe,isTerminal:!0};if(ke==="S"){ie();continue}if(ke==="W"){ie(!0);continue}if(ke==="p"){H=!0;continue}if(ke==="s"||ke==="U"){if(Te===Re.length-1)fe++;break}}}return{hasPathspec:G,hasPatch:H,hasWorktree:J,hasExplicitLocation:oe,isTerminal:!1}}function j_(W){let G=null;for(let H of W){if($t(H,"--hard")){G=Pt("git.reset-hard",v_);break}if($t(H,"--merge")){G=Pt("git.reset-merge",E_);break}}if(!G)return null;return V_(W)?qr(G):Er(G)}function V_(W){for(let G of W){if(G==="--")return!1;if(!G.startsWith("-"))return!0}return!1}function K_(W){for(let H of W)if(H==="-n"||$t(H,"--dry-run"))return null;let G=Cn(W.filter((H)=>H!=="--"));if(W.some((H)=>$t(H,"--force"))||G.has("-f"))return Pt("git.clean-force",R_);return null}function q_(W){let G=!1,H=!1,J=!1;for(let oe of un(W).before){if($t(oe,"--no-force")){G=!1;continue}if($t(oe,"--force")){G=!0;continue}if($t(oe,"--no-cached")){H=!1;continue}if($t(oe,"--cached")){H=!0;continue}if($t(oe,"--no-dry-run")){J=!1;continue}if($t(oe,"--dry-run")){J=!0;continue}let ie=Cn([oe]);G||=ie.has("-f"),J||=ie.has("-n")}return G&&!H&&!J?Pt("git.rm-force",__):null}function Y_(W){let{before:G,after:H}=un(W),J=Cn(G);if(G.some((fe)=>$t(fe,"--mirror")))return Pt("git.push-mirror",A_);if(G.some((fe)=>$t(fe,"--force"))||J.has("-f")||Yf(G,H).some(Z_))return Pt("git.push-force",x_);if(G.some((fe)=>$t(fe,"--delete"))||J.has("-d")||Yf(G,H).some(X_))return Pt("git.push-delete",w_);return null}function Yf(W,G){return[...W.filter((H)=>H!==""&&!H.startsWith("-")),...G]}function Z_(W){return W.startsWith("+")||W.includes(":+")}function X_(W){return W.length>1&&W.startsWith(":")}function J_(W){let{before:G}=un(W),H=Cn(G),J=H.has("-D")||H.has("-d")||G.some((ie)=>$t(ie,"--delete")),oe=H.has("-D")||H.has("-f")||G.some((ie)=>$t(ie,"--force"));if(J&&oe)return Pt("git.branch-force-delete",P_);return null}function Q_(W){let{before:G}=un(W);return G.some((H)=>$t(H,"--abort"))?Pt("git.rebase-abort",T_):null}function ex(W){let{before:G}=un(W);return G.some((H)=>$t(H,"--abort"))?Pt("git.merge-abort",I_):null}function tx(W){let{before:G}=un(W);return Cn(G).has("-d")||G.some((J)=>$t(J,"--delete"))?Pt("git.tag-delete",k_):null}function nx(W){return W[0]==="delete"?Pt("git.reflog-delete",O_):null}function rx(W){for(let G of W){if(G==="drop")return Pt("git.stash-drop",M_);if(G==="clear")return Pt("git.stash-clear",D_)}return null}function ox(W){let{before:G}=un(W);if(!G.includes("remove"))return null;let J=Cn(G);if(G.some((oe)=>$t(oe,"--force"))||J.has("-f"))return Pt("git.worktree-remove-force",N_);return null}import{isAbsolute as xx,join as wx,resolve as Ax}from"node:path";var pc="TMPDIR",gc="IFS",Jf=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Qf=/^[A-Za-z_][A-Za-z0-9_]*$/,ep=new Set(["export","typeset","declare","readonly"]),ix=new Set(["builtin","command","time"]),sx=new Set(["do","then","else"]),ax=new Set(["do","then","case"]),Xf=new Set(["done","fi","esac"]),lx=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function tp(W,G){return W.map((H)=>H.provenance==="variable"&&lp(H.text)?np(H.text,G.shellAssignments):t(H))}function np(W,G){return W.replace(lx,(H,J,oe)=>G.get(J??oe??"")??H)}function Qn(W,G){let H=W.parts.every((oe)=>oe.provenance!=="literal"||!/[$`]/.test(oe.raw));if(W.provenance!=="variable"||!H)return null;let J=np(W.text,G);return/^[~-]/.test(J)||/[\s$`*?[]/.test(J)?null:J}function rp(W,G){return{env:W,effectiveEnvAssignments:mx(W,G),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function op(W){return{env:W.env,effectiveEnvAssignments:W.effectiveEnvAssignments?new Map(W.effectiveEnvAssignments):void 0,shellAssignments:new Map(W.shellAssignments),bodyDepth:W.bodyDepth,bodyAssignments:new Set(W.bodyAssignments)}}function hc(W,G){let H=sp(W,G),J=W[0]??"";if(ax.has(J))G.bodyDepth+=1;if(J==="elif"||Xf.has(J))G.bodyDepth=Math.max(0,G.bodyDepth-1);if(Xf.has(J)&&G.bodyDepth===0)G.bodyAssignments.forEach((Re)=>{G.shellAssignments.delete(Re)}),G.bodyAssignments.clear();H.assignments.filter((Re)=>Re.persists).forEach((Re)=>{if(G.shellAssignments.set(Re.name,Re.value),G.bodyDepth>0)G.bodyAssignments.add(Re.name);yc(G,Re)});let oe=H.commandIndex;if(oe!==-1&&ep.has(W[oe]??""))W.filter((Re)=>Qf.test(Re)&&fc(Re)).forEach((Re)=>{fx(G,Re)});let ie=oe===-1?-1:ap(W,oe);if(ie===-1||W[ie]!=="unset")return;let fe=gx(W,ie);if(fe===null)return;W.slice(fe).forEach((Re)=>{if(G.bodyDepth>0){G.shellAssignments.set(Re,"");return}px(G,Re)})}function ip(W,G){let H=sp(W,G).assignments;if(H.length===0)return G.effectiveEnvAssignments;let J=new Map(G.effectiveEnvAssignments??[]);return H.forEach((oe)=>{J.set(oe.name,oe.value)}),J}function sp(W,G){let H=sx.has(W[0]??"")?1:0,J=W.findIndex((Re,Te)=>Te>=H&&!lp(Re)),oe=J!==-1&&ep.has(W[ap(W,J)]??""),ie=ux(G);return{assignments:W.flatMap((Re,Te)=>{let ke=cx(Re,ie,G.env);if(!ke)return[];if(J!==-1&&Te>J&&!oe&&!vs(ke.name))return[];return ie.set(ke.name,ke.value),[{...ke,persists:J===-1||oe}]}),commandIndex:J}}function ap(W,G){let H=G;while(ix.has(W[H]??"")){H+=1;while(W[H]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(W[H]??""))return G;H+=1}}return H}function lp(W){return Ln(W)!==null||Jf.test(W)}function cx(W,G,H){return Ln(W)??dx(W,G,H)}function dx(W,G,H){let J=Es(W,H,G);if(J)return J;let oe=W.match(Jf)?.[1];if(!oe)return null;let ie=W.indexOf("=");return{name:oe,value:`${G.has(oe)?G.get(oe):H.get(oe)??""}${W.slice(ie+1)}`}}function fc(W){return W===pc||W===gc||zl(W)}function ux(W){return new Map([...W.effectiveEnvAssignments??[],...W.shellAssignments])}function mx(W,G){let H=[pc,gc].map((J)=>{let oe=W.get(J);return oe===void 0?null:[J,oe]}).filter((J)=>J!==null);if(H.length===0)return G;return new Map([...H,...G??[]])}function yc(W,G){let H=new Map(W.effectiveEnvAssignments??[]);H.set(G.name,G.value),W.effectiveEnvAssignments=H}function fx(W,G){yc(W,{name:G,value:W.shellAssignments.get(G)??W.effectiveEnvAssignments?.get(G)??W.env.get(G)??""})}function px(W,G){if(!fc(G)&&!Qf.test(G))return;if(W.shellAssignments.set(G,""),vs(G)&&W.env.has(G)){let J=new Map(W.env);J.delete(G),W.env=J}if(!fc(G)||G===pc||G===gc||$o(G)){yc(W,{name:G,value:""});return}if(!W.effectiveEnvAssignments?.has(G))return;let H=new Map(W.effectiveEnvAssignments);H.delete(G),W.effectiveEnvAssignments=H.size===0?void 0:H}function gx(W,G){let H=G+1;while(H<W.length){let J=W[H];if(!J)return null;if(J==="--")return H+1;if(J==="-v"){H++;continue}if(J.startsWith("-"))return null;return H}return H}import{dirname as dp,join as js,resolve as hx}from"node:path";function Vs(W,G){return Fl.some((H)=>G?.has(H)||W.has(H))}function wo(W,G,H){if(!G)return{gitCwd:null,hasExplicitGitContext:!1};let J=H.realpath(hx(G));if(J===null||!H.isDirectory(J))return{gitCwd:null,hasExplicitGitContext:!1};let oe=J,ie=!1,fe=1;while(fe<W.length){let Re=W[fe];if(!Re)break;if(Re==="--")break;if(!Re.startsWith("-"))break;if(Re==="-C"){let Te=W[fe+1];if(!Te)return{gitCwd:null,hasExplicitGitContext:ie};let ke=cp(oe,Te,H);if(!ke)return{gitCwd:null,hasExplicitGitContext:ie};oe=ke,fe+=2;continue}if(Re.startsWith("-C")&&Re.length>2){let Te=cp(oe,Re.slice(2),H);if(!Te)return{gitCwd:null,hasExplicitGitContext:ie};oe=Te,fe++;continue}if(Re==="--git-dir"||Re==="--work-tree"){ie=!0,fe+=2;continue}if(Re.startsWith("--git-dir=")||Re.startsWith("--work-tree=")){ie=!0,fe++;continue}fe+=_n.has(Re)?2:1}return{gitCwd:oe,hasExplicitGitContext:ie}}function cp(W,G,H){try{let J=hr(W,G,H);return H.isDirectory(J)?J:null}catch{return null}}function Ri(W,G){if(G.entryKind(js(W,".git"))!=="missing")return W;let H=dp(W);return H===W?null:Ri(H,G)}function Ks(W,G,H,J,oe){let ie=J.paths,fe=js(H,".git"),Re=ie.isDirectory(fe),Te=Re&&!J.isGitDirectory(fe),ke=up(G).filter((Le)=>Te||Le!==H&&vr(Le,H));return _o(W,J.env,oe).entries.some((Le)=>Le.key.toLowerCase()==="core.worktree")||ke.some((Le)=>ie.entryKind(js(Le,"HEAD"))!=="missing"||Le!==H&&ie.entryKind(js(Le,".git"))!=="missing")||Re&&J.gitDirectoryRedirects(fe)}function up(W){let G=dp(W);return G===W?[W]:[W,...up(G)]}function mp(W,G,H){if(!G.localDiscard||!H.worktreeMode||Vs(H.environment.env,H.envAssignments))return null;let J=wo(W,H.cwd,H.environment.paths);if(!J.gitCwd||J.hasExplicitGitContext)return null;let oe=H.environment.worktreeFacts(J.gitCwd),ie=Ri(J.gitCwd,H.environment.paths);if(!oe||ie===null||Ks(W,J.gitCwd,ie,H.environment,H.envAssignments))return null;if(Sc(W,H,oe))return null;return{kind:"worktree",originalReason:G.reason,gitCwd:J.gitCwd}}function Sc(W,G,H){let{subcommand:J,rest:oe}=Pn(W),ie=J?.toLowerCase();if(G.dynamicArguments||yx(oe)||Ex(W,G.environment.env,G.envAssignments,H)||bx(oe)||Sx(ie,oe))return!0;return ie==="clean"&&vx(oe)>1}function yx(W){return W.some((G)=>/[$*?[]/.test(G))}function Sx(W,G){if(W==="checkout"){let{before:H}=un(G),J=Cn(H,{shortOptsWithValue:uc}),oe=H.some((fe)=>$t(fe,"--force"))||J.has("-f"),ie=J.has("-B")||H.some((fe)=>fe==="-B"||fe.startsWith("-B"));return oe&&ie}if(W==="switch"){let{before:H}=un(G),J=Cn(H,{shortOptsWithValue:mc}),oe=H.some((fe)=>$t(fe,"--force"))||H.some((fe)=>$t(fe,"--discard-changes"))||J.has("-f"),ie=H.some((fe)=>fe==="-C"||fe.startsWith("-C")||Cx(fe))||J.has("-C");return oe&&ie}return!1}function Cx(W){let G=W.split("=",1)[0]??W;return G==="--force-create"||G.length>=9&&"--force-create".startsWith(G)}function bx(W){return W.some((G)=>G.startsWith("--recurse-sub"))}function vx(W){let G=0;for(let H of W){if(H==="--force"){G++;continue}if(H.startsWith("-")&&!H.startsWith("--")){for(let J of H.slice(1))if(J==="f")G++}}return G}function Ex(W,G,H,J){if(sr("GIT_CONFIG_PARAMETERS",G,H)!==void 0)return!0;let oe=_o(W,G,H);if(oe.blockedReason!==null)return!0;let ie=oe.entries.map((Re)=>({key:Re.key.toLowerCase(),value:Re.value}));if(ie.some((Re)=>_x(Re.key)))return!0;let fe=ie.filter((Re)=>Re.key==="submodule.recurse").at(-1);if(fe)return fe.value===void 0||Rx(fe.value);if($m(H))return!0;return J.recursiveSubmodules}function Rx(W){let G=W.toLowerCase();return G!=="false"&&G!=="no"&&G!=="off"&&G!=="0"}function _x(W){return W==="include.path"||W.startsWith("includeif.")&&W.endsWith(".path")}function fp(W,G,H){let J=W.map((Te)=>Qn(Te,H.shellAssignments??new Map)??t(Te)),oe=H.environment.paths,ie=wo(J,H.cwd,oe),fe=H.originalCwd?oe.realpath(Ax(H.originalCwd)):null;if(G.id.startsWith("git.push-")||fe===null||ie.gitCwd===null||ie.hasExplicitGitContext||Vs(H.environment.env,H.envAssignments))return null;let Re=G.id==="git.worktree-remove-force"?Tx(W,H.shellAssignments,oe):Ri(ie.gitCwd,oe);if(Re===null||G.id!=="git.worktree-remove-force"&&!Px(Re,ie.gitCwd,J,G,H)||!Eo(Re,H.environment)||Ls(Re,H.environment)||vr(fe,Re)||vr(Re,fe))return null;return{kind:"temp-root",originalReason:G.reason,gitCwd:ie.gitCwd}}function Px(W,G,H,J,oe){let ie=oe.environment.paths,fe=wx(W,".git");if(ie.entryKind(fe)!=="present"||Ks(H,G,W,oe.environment,oe.envAssignments))return!1;if(ie.isDirectory(fe))return!0;if(!J.localDiscard)return!1;let Te=oe.environment.worktreeFacts(W);return Te!==null&&!Sc(H,oe,Te)}function Tx(W,G,H){let J=Pn(W.map(t)).rest,{before:oe,after:ie}=un(J.slice(J.indexOf("remove")+1)),fe=[...oe.filter((Le)=>!Le.startsWith("-")),...ie],Re=fe.length===1?fe[0]??"":"",Te=W.find((Le)=>Le.text===Re),ke=(Te&&Qn(Te,G??new Map))??Re;if(!xx(ke)||/[\s$`*?[]/.test(ke)||H.entryKind(ke)!=="present"||!H.isDirectory(ke))return null;return H.realpath(ke)}var kx="Git SSH environment overrides can execute arbitrary commands during network operations. Run git without GIT_SSH/GIT_SSH_COMMAND overrides, or ask the user to run it manually.",Ox=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function qs(W,G){return pp(W,G)}function pp(W,G,H){let J=W.map(t),oe=Kf(J,G.environment.env,G.envAssignments),ie=oe.blockedReason?Nt(Pt("git.alias-config",oe.blockedReason),G.policy):null;if(ie)return ie;let fe=oe.tokens;if((zm(G.envAssignments)||qf(J,G.environment.env,G.envAssignments))&&Mx(fe))return Pt("git.ssh-env",kx);let Re=Zf(fe,(ke)=>{let Le=wo(J,G.cwd,G.environment.paths).gitCwd;return Le!==null&&G.environment.paths.entryKind(Ix(Le,ke))!=="missing"});if(!Re)return null;if(oe.expanded||oe.blockedReason)return Re;let Te=mp(J,Re,G)??fp(W,Re,G);if(!Te)return Re;return H?.(Te),null}function gp(W,G){let H=null;return{match:pp(W,G,(oe)=>{H=oe}),relaxation:H}}function Mx(W){let{subcommand:G,rest:H}=Pn(W),J=G?.toLowerCase();if(!J)return!1;if(Ox.has(J))return!0;if(J==="archive")return un(H).before.some((oe)=>$t(oe,"--remote"));return J==="remote"&&Dx(H)}function Dx(W){return W.find((G)=>!Nx(G))?.toLowerCase()==="update"}function Nx(W){return W==="-v"||$t(W,"--verbose")||$t(W,"--no-verbose")}import{isAbsolute as uw}from"node:path";function hp(W,G,H,J){let oe=W.slice(0,G),ie=W.slice(G+H);return J.startsWith(oe)&&J.endsWith(ie)?J.slice(oe.length,J.length-ie.length):null}function Ys(W,G,H){let J=(ie)=>`${ie.tokenIndex}\x00${ie.kind}\x00${ie.value}`,oe=new Set(W.map(J));return Array.from(G).some((ie)=>H(ie).some((fe)=>!oe.has(J(fe))))}var yp="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Lx="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.",Gx="rm -rf targeting root or home directory is extremely dangerous and always blocked.",Fx="rm -rf in home directory is dangerous. Change to a project directory first.",Sp={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:Gx},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:Fx},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:yp},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:Lx},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:yp}};function Zs(W,G){let H=Xn({...G,allowPaths:G.policy?.destructiveCommandAllowPaths,posixShell:!0}),J=W.map(t),oe=Bs(J),ie=$x(W);for(let fe of ie){let Re=yi(fe.word);if(oe&&Re.unsafeBraceExpansion){let Te=Nt(jr({kind:"outside_anchored_cwd"},H,G.policy,Sp),G.policy);if(Te)return Te;continue}for(let Te of Re.expandedTargets??[fe.text]){let ke=pn(Te),Le={targetIsLiteral:Re.expandedTargets!==void 0||Re.targetIsLiteral,tmpdirWordSplittingProtected:Re.tmpdirWordSplittingProtected};if(!oe&&H.resolvedCwd&&Br(ke,H.resolvedCwd,H.protectedGitMetadata,oe,H.environment,H.budget))return Pt("rm.git-metadata",v);if(!oe)continue;for(let Xe of zx(ke,H,Le)){let Ye=jr(Xe,H,G.policy,Sp),Ze=Nt(Ye,G.policy);if(Ze)return Ze}}}return null}function zx(W,G,H){let J=An(W,G,H);if(J.kind==="cwd_self_target")return[J,An(W,G,{...H,skipCwdSelf:!0})];if(J.kind!=="home_cwd_target")return[J];let oe=An(W,G,{...H,skipHomeCwd:!0});if(oe.kind!=="cwd_self_target")return[J,oe];return[J,oe,An(W,G,{...H,skipHomeCwd:!0,skipCwdSelf:!0})]}function $x(W){let G=[],H=!1;for(let J of W.slice(1)){let oe=t(J);if(!oe)continue;if(oe==="--"){H=!0;continue}if(H){G.push({text:oe,word:J});continue}if(!oe.startsWith("-"))G.push({text:oe,word:J})}return G}var Rr={kind:"none"},Yr={kind:"dynamic"},Bx=new Set(["<","<<","<<-","<<<","<&","<>"]),bp=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,Ux=/^(?:[0-9]+|[@*])$/,Hx=gr.maxWords,vp=gr.maxInputLength;function Ep(W){if(!W||Ft(zt(W.words[0]?.text??""))!=="printf")return;if(W.words.some((oe)=>oe.provenance!=="literal"))return;let G=W.words.slice(W.words[1]?.text==="--"?2:1),H=G[0]?.text;if(H===void 0)return"";let J=G.slice(1).map((oe)=>oe.text);if(H==="%s")return J.join("");if(H==="%s\\n"||H===`%s
|
|
35
|
+
`)return`${J.join(`
|
|
36
|
+
`)}
|
|
37
|
+
`;if(H.includes("%")||/\\(?![\\nrt])/.test(H))return;return H.replaceAll("\\n",`
|
|
38
|
+
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function Xs(W){let G=Ao(W[1])==="--"?2:1;if(W.length<=G)return Rr;let H=W.slice(G);if(!H.every(xi))return Yr;return{kind:"literal",source:H.map(t).join(" ")}}function Rp(W){let G=Ao(W[1])==="--"?2:1,H=W[G],J=Ao(H);if(H===void 0||W.length<=G+1||J==="-"||J===""||J==="-l"||J==="-p")return Rr;if(!xi(H))return Yr;return{kind:"literal",source:J}}function Js(W,G){let H=wp(W);if(H===-1)return Rr;let J=Vx(G);if(!J)return Rr;let oe=[],ie=J.command?.length??0;for(let fe of J.references){let Re=qx(fe,W,H,J.ifs);if(!Re)return Yr;if(ie+=Re.reduce((Te,ke)=>Te+ke.length+3,0),oe.length+Re.length>Hx||ie>vp)return Yr;oe.push(...Re)}if(J.command==="eval")return{kind:"literal",source:oe.join(" ")};if(oe.length===0||/\s/.test(oe[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[J.command,J.command&&J.optionTerminator?"--":null,...oe.map(Ee)].filter((fe)=>fe!==null).join(" ")}}function _p(W,G){let H=wp(W),J=W.slice(H+1),oe=/\bIFS\b/.test(G);if(H===-1||!J.every(xi)||oe)return G;let ie=J.map(Ao),fe="",Re=null,Te=0;while(Te<G.length){let ke=G[Te]??"",Le=Re==="'"?null:/^\$(?:\{([0-9]+|[@*])\}|([0-9@*]))/.exec(G.slice(Te));if(Le){let Xe=Le[1]??Le[2],Ye=Xe==="@"||Xe==="*"?ie.slice(1):[ie[Number(Xe)]??""];if(Re!=='"'&&Ye.some((Qe)=>/[*?[]/.test(Qe)))return G;if(fe+=Re==='"'?Ye.map((Qe)=>Qe.replace(/["$`\\]/g,"\\$&")).join(Xe==="@"?'" "':" "):Ye.map((Qe)=>Qe.split(/[ \t\n]+/).map((et)=>et?Ee(et):"").join(" ")).join(" "),fe.length>vp)return G;Te+=Le[0].length;continue}if(ke==="\\"&&Re!=="'"){fe+=G.slice(Te,Te+2),Te+=2;continue}if(ke==="'"&&Re!=='"'||ke==='"'&&Re!=="'")Re=Re?null:ke;fe+=ke,Te++}return fe}function xp(W,G,H,J){if(!Dn(W.map(t)).readsStdinAsCommands)return Rr;let oe=G.filter((ie)=>(ie.fd===void 0||ie.fd===0)&&Bx.has(ie.operator)).at(-1);if(oe){if(oe.operator==="<<"||oe.operator==="<<-")return Rr;if(oe.operator!=="<<<"||oe.target?.provenance!=="literal")return Yr;return{kind:"literal",source:oe.target.text}}if(!H)return Rr;return J===void 0?Yr:{kind:"literal",source:J}}function ur(W,G=new Map){let H=Dn(W.map(t)).scriptIndex;if(H===null)return Rr;let J=W[H],oe=Ao(J);if(fo(J,oe))return{kind:"literal",source:oe};let ie=J?Qn(J,G):null;return ie===null?Yr:{kind:"literal",source:ie}}var jx=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function Ec(W){if(W.words.length!==2||W.redirections.length!==0||W.nested.length!==1)return!1;let G=W.words[0],H=W.words[1];if(!G||G.provenance!=="literal"||G.quoted||G.raw!==G.text||!H)return!1;if(!(G.text==="eval"&&H.quoted&&H.parts.length===3&&H.parts[0]?.raw==='"'&&H.parts[1]?.provenance==="command-substitution"&&H.parts[1].raw.startsWith("$(")&&H.parts[2]?.raw==='"'||G.text==="eval"&&!H.quoted&&H.parts.length===1&&H.parts[0]?.provenance==="command-substitution"&&H.parts[0].raw.startsWith("$(")||(G.text==="source"||G.text===".")&&!H.quoted&&H.parts.length===1&&H.parts[0]?.provenance==="command-substitution"&&H.parts[0].raw.startsWith("<(")))return!1;let oe=W.nested[0];if(oe?.status!=="complete"||oe.nodes.length!==1)return!1;let ie=oe.nodes[0];if(ie?.kind!=="command"||ie.redirections.length!==0||ie.nested.length!==0||ie.words.some((Te)=>Te.provenance!=="literal"||Te.parts.some((ke)=>ke.provenance!=="literal")))return!1;let fe=ie.words[0]?.text;if(fe===void 0||Ln(fe)!==null)return!1;let Re=Ft(zt(fe));return!jx.has(Re)&&!en.has(Re)&&!Vr(Re)}function wp(W){return Dn(W.map(t)).commandIndex??-1}function Vx(W){let G=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(W.trim()),H=G?.[4]??W.trim(),J=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(H),oe=(J?.[3]??H).split(/\s+/).map(Kx);if(oe.length===0||oe.some((ie)=>ie===null))return null;return{command:J?.[1]??null,optionTerminator:J?.[2]!==void 0,references:oe.filter((ie)=>!!ie),ifs:G?G[1]??G[2]??G[3]??"":`
|
|
39
|
+
`}}function Kx(W){let G=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(W),H=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(W),J=G??H;if(!J)return null;let oe=J[1]??J[2];return{parameter:oe==="@"||oe==="*"?oe:Number(oe),quoted:G!==null}}function qx(W,G,H,J){let oe=G.slice(H+2);if(W.parameter==="@")return W.quoted?Cc(oe):Yx(oe,J);if(W.parameter==="*"){let Re=Cc(oe);if(!Re)return;let Te=Re.join(J[0]??"");return W.quoted?[Te]:bc(Te,J)}let ie=G[H+1+W.parameter];if(ie&&!xi(ie))return;let fe=Ao(ie);return W.quoted?[fe]:bc(fe,J)}function Cc(W){return W.every(xi)?W.map(t):void 0}function Yx(W,G){let H=Cc(W);if(!H)return;let J=H.map((oe)=>bc(oe,G));return J.some((oe)=>oe===void 0)?void 0:J.flatMap((oe)=>oe??[])}function bc(W,G){if(["*","?","[","]"].some((H)=>W.includes(H)))return;if(G==="")return W===""?[]:[W];if(G===`
|
|
40
|
+
`)return W.trim().split(/\s+/).filter(Boolean);if(G.length!==1)return;return G===" "||G==="\t"||G===`
|
|
41
|
+
`?W.trim().split(/\s+/).filter(Boolean):W.split(G).filter(Boolean)}function xi(W){if(!W)return!0;return W.provenance==="unknown"?!/[$`]/.test(t(W)):W.provenance==="literal"}function Ao(W){return W?t(W):""}function Ee(W){return`'${W.replaceAll("'",`'"'"'`)}'`}function Rc(W,G){return vc(y(W,"posix"),G)}function wi(W){return Rc(W,new Set(Array.from(W.matchAll(bp)).flatMap((G)=>{let H=G[1]??G[2];return H===void 0?[]:[H]})))}function vc(W,G){if(W.status==="invalid"||W.status==="limited")return!1;let H=new Set(G);for(let J of W.nodes){if(J.kind==="group"){if(vc(J.body,H))return!0;continue}if(J.kind!=="command")continue;if(J.nested.some((oe)=>vc(oe,H))||Ap(J.words,H))return!0;ew(J,H)}return!1}function Ap(W,G){let H=W.findIndex((fe)=>Ln(fe.text)===null);if(H===-1)return!1;let J=W[H];if(!J)return!1;if(_i(J,G))return!0;let oe=zt(J.text);if(oe==="source"||oe==="."){let fe=W[H+1]?.text==="--"?H+2:H+1;return Cp(W[fe],G)}if(en.has(oe)){let fe=W.slice(H),Re=fe.map((Le)=>Le.text),Te=Dn(Re),ke=Te.commandIndex??Te.scriptIndex;return!Vn(Re)&&ke!==null&&Cp(fe[ke],G)}let ie=Zx(W,H,G);if(ie===null)return!1;if(ie===-1)return!0;return Ap(W.slice(ie),G)}function Zx(W,G,H){let J=zt(W[G]?.text??"");if(J==="command")return Xx(W,G+1);if(J==="exec")return Jx(W,G+1);if(J==="env")return Qx(W,G+1,H);return null}function Xx(W,G){for(let H=G;H<W.length;H++){let J=W[H]?.text??"";if(J==="--")return W[H+1]?H+1:null;if(/^-[p]*[vV][pvV]*$/.test(J))return null;if(/^-p+$/.test(J))continue;return H}return null}function Jx(W,G){for(let H=G;H<W.length;H++){let J=W[H]?.text??"";if(J==="--")return W[H+1]?H+1:null;if(J==="-a"){H++;continue}if(/^-a.+/.test(J)||/^-[cl]+$/.test(J))continue;return H}return null}function Qx(W,G,H){for(let J=G;J<W.length;J++){let oe=W[J],ie=oe?.text??"";if(ie==="--")return W[J+1]?J+1:null;if(ie==="-S"||ie==="--split-string")return _i(W[J+1],H)?-1:J+2;if(ie.startsWith("-S")||ie.startsWith("--split-string="))return _i(oe,H)?-1:J+1;if(ie==="-u"||ie==="--unset"||ie==="-C"||ie==="--chdir"||ie==="-P"){J++;continue}if(ie==="-i"||ie==="-0"||ie==="--null"||ie.startsWith("-u=")||ie.startsWith("--unset=")||ie.startsWith("-C")||ie.startsWith("--chdir=")||ie.startsWith("-P"))continue;if(ie.startsWith("-"))continue;if(Ln(ie))continue;return J}return null}function ew(W,G){if(!W.words.every((H)=>Ln(H.text)!==null))return;for(let H of W.words){let J=Ln(H.text);if(!J)continue;if(_i(H,G))G.add(J.name)}}function _i(W,G){if(!W)return!1;return W.parts.filter((H)=>H.provenance==="variable").some((H)=>Array.from(H.raw.matchAll(bp)).some((J)=>{let oe=J[1]??J[2];return oe!==void 0&&(Ux.test(oe)||G.has(oe))}))}function Cp(W,G){return!!W&&(W.parts.some((H)=>H.provenance!=="literal"&&H.provenance!=="variable")||_i(W,G))}var _c="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",xc="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",tw="__CC_SAFETY_NET_XARGS_INPUT__",Qs="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",ea="rm",nw=/(?:^|[;&|]\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,rw=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,ow=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,iw=/^(?:[0-9]+|[@*])$/;function Ip(W,G){let H=W.map(t),{childStart:J,replacementToken:oe}=Zr(H),ie=H.slice(J),fe=Pt("xargs.shell-dynamic",xc);if(aw(ie,oe,G)&&Nt(fe,G.policy))return Nt(fe,G.policy);for(let Re of jn(ie,G)){let Te=Re.tokens,ke=oe!==null&&Te[0]!==ie[0]&&(Te[0]?.includes(oe)??!1)?Nt(fe,G.policy):null;if(ke)return ke;let Le=Lp(Te,oe,Re.wrapperEnvAssignments),Xe=Re.head==="rm"&&oe!==null&&Dp(Te,oe),Ye=G.analyzeChild(Te,{...Kr(Re,G),dynamicInput:Le,dynamicSourceInput:Xe||Op(Te,Re.head,oe,Re.wrapperEnvAssignments,Le,G.environment,G.strict?void 0:G.analyzeNested),dynamicRmInput:Xe,shellDynamicMatch:fe,dynamicSourceMatch:fe,rmDynamicMatch:Pt("xargs.rm-recursive-force-dynamic",_c)});if(Ye)return Ye;let Ze=sw(Te,oe,G.policy?.rules??[],Nt(fe,G.policy));if(Ze)return Ze;if(Re.head==="git"){let et=oe===null?[...Te,tw]:Te,tt=oe!==null&&(Te.some((_t)=>_t.includes(oe))||Array.from(Re.envAssignments.values()).some((_t)=>_t.includes(oe))),gt=G.analyzeChild(et,{...Kr(Re,G),worktreeMode:oe===null||tt?!1:G.worktreeMode});if(gt)return gt}let Qe=N(Te,G.policy?.rules??[]);if(Qe)return Qe}return null}function sw(W,G,H,J){if(H.length===0)return null;if(G===null){for(let ie of H){let fe=N([...W,...ie.subcommand?[ie.subcommand]:[],...ie.block_args],H);if(fe)return fe}return null}let oe=zt(W[0]??"");if(!H.some((ie)=>zt(ie.command)===oe))return null;return W.slice(1).some((ie)=>ie.includes(G))?J:null}function kp(W,G,H){let J=W.indexOf(G);if(J===-1||W.indexOf(G,J+G.length)!==-1)return[];let oe=hp(W,J,G.length,H);return oe===null?[]:[oe]}function Op(W,G,H,J,oe,ie,fe){if(en.has(G)){if(Vn(W))return!1;if(H!==null&&lw(W,H,fe))return!0;let Re=Wn(W);if(!Re){let Te=ur(Qt(W));if(Te.kind==="literal")return H!==null&&Te.source.includes(H);return Te.kind==="none"&&oe}if(H!==null&&Re.includes(H)&&!Mp(Re,H,fe))return!0;if(Nn(Re))return!0;return cw(Re,H,J)}if($n(G))return Pp(W,H,Cs,Nm(G));if(Mn.has(G))return Pp(W,H,nc,Lf);if(G==="eval"){let Re=Xs(Qt(W));if(Re.kind==="dynamic")return!0;if(H!==null)return Re.kind==="literal"&&Re.source.includes(H);return oe}if(G==="find")return dw(W,H,ie);if(G==="git"){let Re=Pn(W);return H===null?Re.subcommand===null:(Re.subcommand?.includes(H)??!1)||Re.subcommand!==null&&xo.has(Re.subcommand.toLowerCase())&&Np(Re.rest,H).some((Te)=>Te.includes(H))}return!1}function Mp(W,G,H){if(H===void 0)return!1;let J=G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`(?:^|[;&|({!\`\\n]|\\b(?:then|do|else|elif|if|while|until|time|command|builtin|nohup|eval|exec|source))\\s*(?:[A-Za-z_][A-Za-z0-9_]*=\\S*\\s+)*["']?${J}`).test(W)||/\bcase\b/.test(W))return!1;let ie=W.replaceAll(G,"/");return Nn(ie)===null&&H(ie)===null}function Pp(W,G,H,J){let oe=H(W);if(G===null)return oe.optionsOpen||H([...W,Qs]).sources.some((Re)=>Re.value===Qs);if(oe.sources.some((Re)=>Re.value.includes(G)))return!0;let ie=J.flatMap((Re)=>[Re.selector,...Re.valueForm==="attached-only"||Re.valueForm==="attached-or-separate"?[`${Re.selector}${Qs}`]:[],...Re.valueForm==="equals-or-separate"?[`${Re.selector}=${Qs}`]:[]]),fe=new Set(ie.flatMap((Re)=>W.flatMap((Te)=>kp(Te,G,Re))));return Ys(oe.sources,fe,(Re)=>H(W.map((Te)=>Te.replaceAll(G,Re))).sources)}function aw(W,G,H){if(W.length===0||(W[0]??"").toLowerCase()==="command")return!1;let J=new Set(Array.from(jn(W,H),(ie)=>ie.head)),oe=G===null?[...W,ea]:W.map((ie,fe)=>fe===0?ie:ie.replaceAll(G,ea));return Array.from(jn(oe,H)).some((ie)=>ie.head===ea&&!J.has(ea))}function Dp(W,G){return Np(W.slice(1),G).some((H)=>H.includes(G)&&(H.startsWith("-")||H.startsWith(G)))}function Np(W,G){let H=W.findIndex((J)=>J==="--"&&!J.includes(G));return H===-1?W:W.slice(0,H)}function Lp(W,G,H){if(G===null)return!0;return W.some((J)=>J.includes(G))||Array.from(H.values()).some((J)=>J.includes(G))}function lw(W,G,H){let J=Dn(W),oe=J.commandIndex===null?"":W[J.commandIndex]??"";if(oe.includes(G)&&!Mp(oe,G,H)||J.scriptIndex!==null&&(W[J.scriptIndex]??"").includes(G))return!0;return["-c","-nc","-cn",`--${G}`,G].some((fe)=>W.some((Re,Te)=>{if(Te===0||!Re.includes(G))return!1;return kp(Re,G,fe).some((Le)=>{let Xe=W.map((Ze,Qe)=>Qe===Te?Ze.replaceAll(G,Le):Ze),Ye=Dn(Xe);if(Ye.commandIndex===null&&Ye.scriptIndex===null)return!1;if(J.commandIndex===null&&Ye.commandIndex!==null)return!0;if(J.scriptIndex===null&&Ye.scriptIndex!==null)return!0;if(Ye.commandIndex!==null&&(Xe[Ye.commandIndex]??"").includes(Le))return!0;return Ye.scriptIndex!==null&&(Xe[Ye.scriptIndex]??"").includes(Le)})}))}function cw(W,G,H){let J=new Set(G===null?[]:Array.from(H).filter(([,oe])=>oe.includes(G)).map(([oe])=>oe));for(let oe of W.matchAll(nw))if(Tp(oe,J))return!0;for(let oe of W.matchAll(rw))for(let ie of(oe[1]??"").matchAll(ow))if(Tp(ie,J))return!0;return Rc(W,J)}function Tp(W,G){let H=W[1]??W[2];return H!==void 0&&(iw.test(H)||G.has(H))}function dw(W,G,H){if(G===null)return!0;let J=!1,oe=0;for(let ie=1;ie<W.length;ie++){let fe=W[ie]??"";if(!J&&!fe.startsWith("-")&&fe!=="!"&&fe!=="("){if(fe.indexOf(G)===0)return!0;continue}if(J=!0,oe>0){oe--;continue}if(Jn(fe)){let Te=Ro(W,ie);ie=Te.nextIndex-1;for(let ke of jn(Te.tokens,{environment:H,cwd:void 0})){let Le=Lp(ke.tokens,G,ke.wrapperEnvAssignments);if(ke.head==="rm"&&Dp(ke.tokens,G)||Op(ke.tokens,ke.head,G,ke.wrapperEnvAssignments,Le,H))return!0}continue}let Re=dr(fe);if(Re>0){if(oe=Re,fe.includes(G))return!0;continue}if(fe.includes(G))return!0}return!1}function Zr(W){let G=new Set(["-L","-n","-P","-s","-a","-E","-R","-S","-e","-d","-J","--max-args","--max-procs","--max-chars","--arg-file","--eof","--delimiter","--max-lines","--process-slot-var"]),H=null,J=1;while(J<W.length){let oe=W[J];if(!oe)break;if(oe==="--")return{childStart:J+1,replacementToken:H};if(!oe.startsWith("-"))return{childStart:J,replacementToken:H};if(oe==="-I"){H=W[J+1]??"{}",J+=2;continue}if(oe.startsWith("-I")&&oe.length>2){H=oe.slice(2),J++;continue}if(oe==="--replace"){H="{}",J++;continue}if(oe.startsWith("--replace=")){let ie=oe.slice(10);H=ie===""?"{}":ie,J++;continue}if(oe==="-J"){H=W[J+1]??"{}",J+=2;continue}J+=G.has(oe)?2:1}return{childStart:W.length,replacementToken:H}}var Ai="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",Pi="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",mw="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",fw="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",na=/\{[^{}\s]*\}/g,Wp=/\{\}|\{-?\d+\}/g,Gp=/[\s;&|<>()$`\\"']/,pw=["e","f","source","file","-e","-f","--source","--file"],gw=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],hw=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),yw=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),Fp=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),Sw=new Set(["--workdir","--wd"]),zp="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Gn(W,G){for(let H of W){let J=G(H);if(J)return J}return null}function Up(W){return Gn([...W],(G)=>Nn(G))}function Hp(W,G){let H=W.map(t);if((G.envAssignments?.has("PARALLEL")?G.envAssignments.get("PARALLEL"):G.environment.env.get("PARALLEL"))?.trim()){let Qe=Po(G);if(Qe)return Qe}if(H.length===2&&(H[1]==="--version"||H[1]==="--help"))return null;let oe=ng(H),{template:ie,jobs:fe,runsRemotely:Re,readsCommandsFromInput:Te,unsupported:ke,workdir:Le,dryRun:Xe}=oe;if(ke){let Qe=Po(G);if(Qe)return Qe;let et=Up(G.envAssignments?.values()??[]);if(et)return et}if(Te){let Qe=xw(G);if(Qe)return Qe}if(Le!==void 0&&Re){let Qe=Po(G);if(Qe)return Qe}let Ye=ww(Le,G.cwd,G.environment.paths);if(Ye===null){let Qe=Po(G);if(Qe)return Qe}let Ze=Re?{...G,cwd:void 0,originalCwd:void 0}:Ye===null||Ye===void 0||Ye===G.cwd?G:{...G,cwd:Ye};if(Xe){if([...jn(ie,Ze)].flatMap((et)=>[...et.envAssignments.values()]).some(Pc)){let et=Po(G);if(et)return et}return null}if(ie.length===0){let Qe=fe.map((tt)=>tt[0]??"");G.budget.charge("derivedTokens",Qe.length);let et=Zp(Ze.envAssignments,Ze.cwd,Re);return Gn(Qe,(tt)=>G.analyzeNested(tt,et))}return Gn(jn(ie,Ze),(Qe)=>Cw(Qe,oe,G,Ze))}function Cw(W,G,H,J){let{templateHasPlaceholder:oe,runsRemotely:ie,usesStdin:fe}=G,Re=W.tokens,Te=[...W.envAssignments.values()];if(Te.some(eg)){let At=Po(H);if(At)return At}let ke=Up(Te);if(ke)return ke;let Le=Te.some(jt),Xe=oe||Le,Ye=fe&&Xe,Ze=Zp(W.envAssignments,W.wrapperCwd,ie||Ye),Qe=Xe?{...Ze,worktreeMode:!1}:Ze,et=Re.join(" "),tt=jt(et.split(/[ \t\n=]/,1)[0]??""),gt=!G.quotesCommand&&(tt||Re.some((At)=>Gp.test(At))),_t=tt||Gp.test(Re[0]??""),yt=gt&&_t&&G.jobs.length>0?null:bw(W,G,H,J,Qe,Le);if(yt||!gt)return yt;return jp(jt(et)?et:`${et} {}`,!tt,W,G,H,J,Qe)}function bw(W,G,H,J,oe,ie){let{jobs:fe,templateHasPlaceholder:Re,runsRemotely:Te,usesStdin:ke}=G,Le=W.tokens,Xe=Re||ie;if(en.has(W.head)){let Ze=()=>{if(!Re||fe.length===0)return null;return Gn(fe,(tt)=>H.analyzeChild(ta(Le,tt,H.budget),Kr(W,J)))};if(Vn(Le))return Ze();if(Us(Le))return br();let Qe=Wn(Le);if(Qe){if(tg(Qe)){let yt=_r(H);if(yt)return yt;if(fe.length===0)return null;return Gn(fe,(At)=>H.analyzeNested(Jp(Qe,At,H.budget),oe))}if(jt(Qe))return jp(Qe,!1,W,G,H,J,oe);let tt=!ie&&(!Re||fe.length>0)?(fe.length>0?fe:[void 0]).map((yt)=>Js(Qt(yt===void 0?Le:Re?Le.map((At)=>Xp(At,yt)):[...Le,...yt]),Qe)):[];if(tt.some((yt)=>yt.kind==="dynamic")){let yt=_r(H);if(yt)return yt}let gt=tt.flatMap((yt)=>yt.kind==="literal"?[yt.source]:[]);if(gt.length>0)return H.budget.charge("derivedTokens",gt.length),Gn(gt,(yt)=>H.analyzeNested(yt,oe));if(wi(Qe)){let yt=_r(H);if(yt)return yt}let _t=H.analyzeNested(Qe,oe);if(_t)return _t;if(Xe)return _r(H);return null}let et=ur(Qt(Le));if(et.kind==="dynamic"||et.kind==="literal"&&jt(et.source))return _r(H)??Ze();if(et.kind==="literal")return Ze();if(fe.length>0){let tt=_r(H);if(tt)return tt;let gt=Ze();if(gt)return gt;if(Re)return null;let _t=fe.flatMap((yt)=>yt[0]===void 0?[]:[yt[0]]);return H.budget.charge("derivedTokens",_t.length),Gn(_t,(yt)=>H.analyzeNested(yt,oe))}if(Xe||ke)return _r(H)??Ze();return null}if(W.head==="rm"&&cr(Le)){if(Re&&fe.length>0)return Gn(fe,(Qe)=>wc(ta(Le,Qe,H.budget,Wp),W.cwd,J));if(fe.length>0)return Gn(fe,(Qe)=>wc(Bp(Le,Qe,H.budget),W.cwd,J));let Ze=wc(Le.flatMap((Qe,et)=>{if(et===0||!jt(Qe))return[Qe];return Qe.startsWith("-")?[Qe.replace(Wp,"")]:[]}),W.cwd,J);if(Ze)return Ze;return Yp(H)}let Ye=fe.length>0?fe:[void 0];return Gn(Ye,(Ze)=>{let Qe=Ze===void 0?Le:Re?ta(Le,Ze,H.budget):Bp(Le,Ze,H.budget),et=Pt("parallel.shell-dynamic",Pi),tt=ke&&W.head==="find"?_w(Qe,J):null,gt=Kp(Qe,ke,H)??tt?.customResult??null,_t=zt(W.head),yt=ke&&(_t==="rm"&&Ac(Qe)||_t==="xargs"&&qp(Qe)||tt?.rmOptions===!0),At=ke&&(yt||tt?.executedSource===!0||tt===null&&Vp(Qe,_t)),Ot=H.analyzeChild(Qe,{...Kr(W,J),worktreeMode:Te||ke||Xe?!1:H.worktreeMode,dynamicInput:ke||Xe,dynamicRmInput:yt,dynamicSourceInput:gt!==null||At,shellDynamicMatch:et,dynamicSourceMatch:et,rmDynamicMatch:Pt("parallel.rm-recursive-force-dynamic",Ai)});if(At){let Mt=Nt(et,H.policy);if(Mt)return Mt}return Ot??gt??N(Qe,H.policy?.rules??[])})}function jp(W,G,H,J,oe,ie,fe){if(J.jobs.length>0)return Gn(J.jobs,(ke)=>oe.analyzeNested(Jp(W,G?ke.map(Ee):ke,oe.budget),fe));let Re=Ei(W);if(Re?.[0]&&zt(Re[0])==="rm"&&cr(Re)){let ke=Yp(oe);if(ke)return ke}return(Re?oe.analyzeChild(Re,{...Kr(H,ie),dynamicInput:J.usesStdin,shellDynamicMatch:Pt("parallel.shell-dynamic",Pi),rmDynamicMatch:Pt("parallel.rm-recursive-force-dynamic",Ai)}):null)??oe.analyzeNested(W,fe)}function Vp(W,G){if(jt(W[0]??""))return!0;if(G==="eval"||G==="source"||G===".")return!0;if(G==="parallel"||G==="xargs")return!0;if(en.has(G))return Rw(W);if(G==="git")return vw(W);if(G==="find")return!0;if(Mn.has(G))return $p(W,pw,bi);if($n(G))return $p(W,gw,Ss);return!1}function Ac(W){let G=W.indexOf("--"),H=W.slice(1,G===-1?void 0:G);if(!W.some(jt))return G===-1;return H.some((oe)=>jt(oe)&&(oe.startsWith("-")||tg(oe)))}function vw(W){if(Ew(W))return!0;let G=Pn(W);if(G.subcommand===null||jt(G.subcommand))return!0;if(!xo.has(G.subcommand.toLowerCase()))return!1;let H=G.rest.indexOf("--"),J=G.rest.slice(0,H===-1?void 0:H);if(!W.some(jt))return H===-1;return J.some(jt)}function Ew(W){for(let G=1;G<W.length;G++){let H=W[G];if(!H||H==="--"||!H.startsWith("-"))return!1;if(H==="-c"||H==="--config-env"){if(jt(W[G+1]??""))return!0;G++;continue}if(H.startsWith("-c")&&H.length>2||H.startsWith("--config-env=")){if(jt(H))return!0;continue}if(jt(H))return!0}return!1}function Rw(W){if(Vn(W))return!1;let G=Wn(W);if(G!==null)return jt(G);let H=ur(Qt(W));if(H.kind==="literal")return jt(H.source);if(H.kind==="dynamic")return!0;return!W.some(jt)}function $p(W,G,H){let J=H(W);if(J.some((oe)=>jt(oe.value)))return!0;if(!W.some(jt))return H([...W,zp]).some((oe)=>oe.value===zp);return Ys(J,G,(oe)=>H(W.map((ie)=>Xp(ie,[oe]))))}function Kp(W,G,H){let J=H.policy?.rules??[];if(!G||J.length===0)return null;let oe=J.filter((ie)=>zt(ie.command)===zt(W[0]??""));if(oe.length===0)return null;if(W.slice(1).some(jt))return _r(H);return Gn(oe,(ie)=>N([...W,...ie.subcommand?[ie.subcommand]:[],...ie.block_args],[ie]))}function _w(W,G){let H={customResult:null,executedSource:!W.some(jt),rmOptions:!1},J=!1,oe=0,ie=null,fe=()=>{if(!ie?.some(jt))return;for(let Re of jn(ie,G))H.executedSource||=Vp(Re.tokens,Re.head),H.rmOptions||=Re.head==="rm"&&Ac(Re.tokens)||Re.head==="xargs"&&qp(Re.tokens),H.customResult??=Kp(Re.tokens,!0,G)};for(let Re of W.slice(1)){if(!J&&!Re.startsWith("-")&&Re!=="!"&&Re!=="("){H.executedSource||=jt(Re);continue}if(J=!0,ie){if(Re===";"||Re==="+"){fe(),ie=null;continue}ie.push(Re);continue}if(oe>0){oe--;continue}if(Jn(Re)){ie=[],H.executedSource||=jt(Re);continue}let Te=dr(Re);if(Te>0){oe=Te,H.executedSource||=jt(Re);continue}H.executedSource||=jt(Re)}return fe(),H}function qp(W){let G=W.slice(Zr(W).childStart);return zt(G[0]??"")==="rm"&&Ac(G)}function ra(W,G){return(H)=>Nt(Pt(W,G),H.policy)}var _r=ra("parallel.shell-dynamic",Pi),xw=ra("parallel.command-stream-dynamic",mw),Po=ra("parallel.command-stream-dynamic",fw),Yp=ra("parallel.rm-recursive-force-dynamic",Ai);function wc(W,G,H){return Nt(Zs(Qt(W),{environment:H.environment,cwd:G,budget:H.budget,originalCwd:H.originalCwd,strict:H.strict,paranoid:H.paranoidRm,allowTmpdirVar:H.allowTmpdirVar,tmpdirWordSplittingUnsafe:Ur(H.envAssignments??new Map,H.environment),trustedTmpdirValue:vo(H.envAssignments??new Map,H.environment),protectedGitMetadata:H.protectedGitMetadata,policy:H.policy}),H.policy)}function Zp(W,G,H){let J={};if(W)J.envAssignments=W;if(H)return J.effectiveCwd=null,J.worktreeMode=!1,J;if(G!==void 0)J.effectiveCwd=G;return Object.keys(J).length>0?J:void 0}function Xp(W,G){return W.replace(na,(H)=>Qp(H,G))}function ta(W,G,H,J=na){return H.charge("derivedTokens",W.reduce((oe,ie)=>oe+1+Math.floor(ie.length/64),0)),W.map((oe)=>oe.replace(J,(ie)=>{let fe=Qp(ie,G);return H.charge("derivedTokens",Math.max(1,Math.ceil(fe.length/64))),fe}))}function Jp(W,G,H){return ta([W],G,H)[0]??""}function Bp(W,G,H){return H.charge("derivedTokens",W.length+G.length),[...W,...G]}function Qp(W,G){let H=/^\{(-?\d+)[^{}\s]*\}$/.exec(W)?.[1];if(H===void 0)return G[0]??"";let J=Number(H);return G[J>0?J-1:G.length+J]??""}function jt(W){return W.search(na)!==-1}function eg(W){if(Pc(W))return!0;for(let G of W.matchAll(na))if(!/^(?:\{\}|\{\d+\})$/.test(G[0]))return!0;return!1}function Pc(W){let G=W.indexOf("{=");return G!==-1&&W.indexOf("=}",G+2)!==-1}function tg(W){return/^\{[^{}\s]*\}$/.test(W)}function ww(W,G,H){if(W===void 0)return;if(W==="..."||/^~|[{}$`*?[]/.test(W))return null;if(!G&&!uw(W))return null;try{return hr(G??W,W,H)}catch{return null}}function ng(W){let G=1,H=[],J=W.length,oe=-1,ie=!1,fe=!1,Re=!1,Te,ke=!1,Le=W.some((et)=>et==="::::"||et==="::::+"||et===":::+");while(G<W.length){let et=W[G];if(et===void 0)break;if(et===":::"){oe=G;break}if(et==="--"){let At=ic(W,G+1);H.push(...At.templateTokens),J=G+1,oe=At.markerIndex;break}if(!et.startsWith("-")){let At=ic(W,G);H.push(...At.templateTokens),J=G,oe=At.markerIndex;break}let tt=W[G+1],gt=et.indexOf("="),_t=gt===-1?et:et.slice(0,gt),yt=gt===-1?void 0:et.slice(gt+1);if(et==="--dry-run"){ke=!0,G++;continue}if(et==="-I"||et.startsWith("-I")&&et.length>2){Le||=(et==="-I"?tt:et.slice(2))!=="{}",G+=et==="-I"?2:1;continue}if(et==="--replace"||et==="-i"){Le=!0,G+=2;continue}if(_t==="--replace"||et.startsWith("-i")&&et.length>2){let At=_t==="--replace"?yt:et.slice(2);Le||=At!==""&&At!=="{}",G++;continue}if(et==="-a"||yw.has(_t)){Le=!0,G+=yt===void 0?2:1;continue}if(et==="-q"||et==="--quote"){fe=!0,G++;continue}if(et==="--pipe"||et==="--pipepart"){Re=!0,G++;continue}if(_t==="--env"){Le=!0,G+=yt===void 0?2:1;continue}if(Fp.has(_t)||et.startsWith("-S")&&et.length>2){ie=!0,G+=Fp.has(et)?2:1;continue}if(Sw.has(_t)){Le=!0;let At=yt??tt;if(At===void 0||At===":::"||At==="--"){G++;continue}Te=At,G+=yt===void 0?2:1;continue}if(et.startsWith("-j")&&et.length>2&&/^\d+$/.test(et.slice(2))){G++;continue}if(et.startsWith("--")&&yt!==void 0){G++;continue}if(hw.has(et)){if(tt===void 0||tt===":::"||tt==="--"){Le=!0,G++;continue}G+=2;continue}G+=et==="-j"||et==="--jobs"?2:1}Le||=H.some(ke?Pc:eg);let Xe=[];if(oe!==-1){let et=[];for(let tt=oe+1;tt<W.length;tt++){let gt=W[tt];if(gt===":::"){Xe.push(et),et=[];continue}if(gt!==void 0)et.push(gt)}Xe.push(et)}Le||=Xe.length>1;let Ye=Aw(Xe),Ze=H.some(jt),Qe=H.length===0&&oe===-1;return{template:H,jobs:Ye,childStart:J,templateHasPlaceholder:Ze,runsRemotely:ie,quotesCommand:fe,usesStdin:Re||oe===-1,readsCommandsFromInput:Qe,unsupported:Le,workdir:Te,dryRun:ke}}function Aw(W){if(W.length===0||W.some((H)=>H.length===0))return[];let G=[[]];for(let[H,J]of W.entries()){if(J.length===1){let ie=J[0];if(ie===void 0)return[];for(let fe of G)fe.push(ie);if(G.length*(H+1)>a.derivedTokens.cap)throw new s("derivedTokens");continue}let oe=[];for(let ie of G)for(let fe of J){if((oe.length+1)*(H+1)>a.derivedTokens.cap)throw new s("derivedTokens");oe.push([...ie,fe])}G=oe}return G}function rg(W){return ng(W).childStart}var Pw="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",oa="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function Ic(W){return W?.parts.some((G)=>G.provenance==="command-substitution")??!1}function Tc(W){return W?.parts.some((G)=>G.provenance==="literal"&&G.raw.replace(/^["']/,"").startsWith("-"))??!1}function ig(W,G,H,J,oe=!1,ie){let Re=(Jo(W,G)||J&&W!=="powershell"&&G[0]?.provenance==="variable")&&on(ie,"shell.dynamic-executable",oe)?Pt("shell.dynamic-executable",Pw):null;return Nt(Re,ie)??sg(W,G,H,oe,ie)}function sg(W,G,H,J,oe){if(G.length<2)return null;let ie=G.flatMap((Re,Te)=>Ic(Re)?[Te]:[]);if(ie.length===0)return null;let fe=zt(G[0]?.text??"");if(fe==="git"){let Re=re(W,G),Te=Iw(Re);if(on(oe,"shell.dynamic-structure",J)&&ie.some((Xe)=>Xe<=Te))return Nt(Pt("shell.dynamic-structure",oa),oe);if(Nt(qs(Re,{environment:H}),oe))return null;let ke=G[Te]?.text.toLowerCase(),Le=Re.findIndex((Xe,Ye)=>Ye>Te&&t(Xe)==="--");if(on(oe,"shell.dynamic-structure",J)&&ke&&xo.has(ke)&&ie.some((Xe)=>Xe>Te&&(Le===-1||Xe<Le)))return Nt(Pt("shell.dynamic-structure",oa),oe);return null}if(fe==="find")return on(oe,"shell.dynamic-structure",J)&&kw(G)?Nt(Pt("shell.dynamic-structure",oa),oe):null;if(fe==="rm"){let Re=G.findIndex((ke,Le)=>Le>0&&t(ke)==="--"),Te=cr(G.map(t));return on(oe,"shell.dynamic-structure",J)&&ie.some((ke)=>(Re===-1||ke<Re)&&(ke<G.length-1||!Te))?Nt(Pt("shell.dynamic-structure",oa),oe):null}if(fe==="xargs")return og(W,G.slice(Zr(G.map(t)).childStart),"xargs",H,J,oe);if(fe==="parallel")return og(W,G.slice(rg(G.map(t))),"parallel",H,J,oe);return null}function og(W,G,H,J,oe,ie){if(G.length===0)return null;let fe=Tw(G,J);if(Jo(W,fe)){let Te=Nt(Pt(`${H}.shell-dynamic`,H==="xargs"?xc:Pi),ie);if(Te)return Te}let Re=sg(W,fe,J,oe,ie);if(Re)return Re;if(fe[0]?.text==="rm"&&fe.slice(1).some((Te)=>Ic(Te)&&Tc(Te)))return Nt(Pt(`${H}.rm-recursive-force-dynamic`,H==="xargs"?_c:Ai),ie);return null}function Tw(W,G){let H=zr(W,G),J=H.rewritten?Qt(H.words.map(t)):H.words,oe=J[0];return oe&&t(oe)==="busybox"?J.slice(1):J}function Iw(W){let G=1;while(G<W.length){let H=W[G],J=H?t(H):"";if(_n.has(J)){G+=2;continue}if(J.startsWith("-")){G++;continue}return G}return G}function kw(W){let G=!1,H=0,J=!1,oe=!1;for(let ie=1;ie<W.length;ie++){let fe=W[ie];if(!fe)continue;let Re=Ic(fe);if(H>0){H--;continue}if(oe){if(fe.text===";"||fe.text==="+"){oe=!1,G=!0,J=!1;continue}if(Re&&(J||Tc(fe)))return!0;J=!1;continue}if(!G&&!fe.text.startsWith("-")){if(Re&&(ie>1||Tc(fe)))return!0;continue}if(G=!0,Re)return!0;let Te=dr(fe.text);if(Te>0){H=Te;continue}if(Jn(fe.text))oe=!0,J=!0}return!1}function kc(W,G){return W.some((H)=>{if(H.value==="-"&&(H.kind==="main-script"||H.kind==="program-file"))return!0;return!fo(G[H.tokenIndex],H.value)})}var ag="cmd rmdir /s or del /s outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Ow="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.",Mw="cmd rmdir /s or del /s target contains wildcards or variables that cannot be verified safely. Use literal paths within cwd.",Dw="cmd rmdir /s or del /s targeting root or home directory is extremely dangerous and always blocked.",Nw="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.",Lw="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:Dw},git_metadata_target:{id:"cmd.recursive-delete-git-metadata",reason:v},dynamic_target:{id:"cmd.recursive-delete-dynamic-target",reason:Mw},home_cwd_target:{id:"cmd.recursive-delete-home-cwd",reason:Lw},cwd_self_target:{id:"cmd.recursive-delete-cwd-self",reason:ag},within_anchored_cwd:{id:"cmd.recursive-delete-paranoid",reason:Ow},outside_anchored_cwd:{id:"cmd.recursive-delete-outside-cwd",reason:ag}},Gw=/^\/\/?[ck]$/i,lg=/[&|]+/,Fw=/(?:"[^"]*"|[^\s"])+/g,zw=/[\^%!]/,$w=/\\"./s,Bw=/(^|\/)[*.]*\*[*.]*$/,Uw=/^"?[\\/]+[?.][\\/]/,Hw=new Set(["rmdir","rd","del","erase"]),jw=/(?<![\w-])(?:rmdir|rd|del|erase)(?!\w)/i,Vw=/\/s(?!\w)/i,Kw=/(?<![\w-])(?:cd|chdir|pushd|popd)(?!\w)/i;function cg(W,G){let H=W.map(t),J=H.findIndex((Ye)=>Gw.test(Ye));if(J===-1)return null;let oe=H.slice(J+1).join(" "),ie=/^".*"$/s.test(oe)?oe.slice(1,-1):oe,fe=ie.split(lg).map((Ye)=>{let Ze=Ye.match(Fw)??[],Qe=Ze.findIndex((tt)=>Hw.has(tt.replace(/^@/,"").toLowerCase())),et=Qe===-1?[]:Ze.slice(Qe);return{piece:Ye,tokens:Ze,deleteTokens:et,recursiveDelete:et.slice(1).some((tt)=>tt.startsWith("/")&&tt.toLowerCase().split("/").includes("s"))}}),Re=fe.filter((Ye)=>Ye.recursiveDelete),Te=Re.length>0||jw.test(ie)&&Vw.test(ie);if(Te&&(ie.includes("\\\"")||G.gitBashEscapesBodyQuotes&&ie.includes('"')||G.powerShellRawWords.some((Ye)=>$w.test(Ye))||Re.some((Ye)=>Ye.tokens.some((Ze)=>Uw.test(Ze)))))return Pt("cmd.recursive-delete-escaped-quote",Nw);let ke=Xn({...G,allowPaths:G.policy?.destructiveCommandAllowPaths}),Le=fe.reduce((Ye,Ze)=>Ye??(Ze.recursiveDelete?qw(Ze.deleteTokens,ke,G.policy):G.analyzeNested(Ze.piece)),null),Xe=Te&&(Re.length===0||zw.test(ie)||Kw.test(ie)||ie.includes('"')&&lg.test(ie));return Le??(Xe?br():null)}function qw(W,G,H){return W.slice(1).filter((J)=>!J.startsWith("/")).reduce((J,oe)=>J??Nt(jr(An(Si(oe.replaceAll('"',"")).replace(Bw,"$1*"),G),G,H,Ww),H),null)}var Yw="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.",Zw=/^-(?:noprofile|nop|noninteractive|noni|nologo)$/i,Xw=/^-(?:executionpolicy|ep)$/i,Jw=/^-(?:command|c)$/i,Qw=/^(?:--?|[/\u2013\u2014\u2015])(\w+)$/,eA="encodedcommand",tA=/(?<![\w-])(?:remove-item|ri|rm|rmdir|rd|del|erase)(?![\w-])/i,nA=/(?<![\w-])(?:[-\u2013\u2014\u2015]{1,2}r(?:e(?:c(?:u(?:r(?:s(?:e|ive?)?)?)?)?)?)?(?!\w)|-[dfipvwx]*r[dfipvwx]*(?!\w))|\/s(?!\w)/i,rA=/[$`]/,oA="--%";function dg(W,G){let H=W.map(t),J=H.every((ie,fe)=>fe===0||ie!==oA&&iA(W[fe],ie))?Mc(H):void 0;if(J!==void 0)return G(J);if(H.some(sA))return br();let oe=H.join(" ");return tA.test(oe)&&nA.test(oe)?Pt("powershell.nested-recursive-delete-unread",Yw):null}function Mc(W){let G=Oc(W,1),H=G===void 0?[]:W.slice(G+1);return H.length>0?H.join(" "):void 0}function Oc(W,G){let H=W[G]??"";if(Jw.test(H))return G;if(Zw.test(H))return Oc(W,G+1);return Xw.test(H)?Oc(W,G+2):void 0}function iA(W,G){return W?.provenance==="unknown"?!rA.test(G):fo(W,G)}function sA(W){let G=Qw.exec(W)?.[1]?.toLowerCase();return G!==void 0&&(G==="ec"||eA.startsWith(G))}var mg=[{heads:new Set(["rm","rmdir"]),analyze:(W)=>Zs(W.words,Dc(W))},{heads:new Set(["cmd"]),analyze:(W)=>cg(W.words,{...Dc(W),powerShellRawWords:W.options.commandView?.dialect==="powershell"?W.options.commandView.words.map((G)=>G.raw):[],gitBashEscapesBodyQuotes:W.options.commandView?.dialect!=="powershell",analyzeNested:(G)=>xr(W.options.analyzeNested(G,{effectiveCwd:W.effectiveCwd,envAssignments:W.envAssignments}))})},{heads:new Set(["powershell","pwsh"]),analyze:(W)=>dg(W.parsedWords,(G)=>xr(W.options.analyzeNested(G,{effectiveCwd:W.effectiveCwd,envAssignments:W.envAssignments,shell:"powershell"})))},{heads:new Set(["git"]),analyze:(W)=>qs(W.words,Nc(W))},{heads:new Set(["find"]),analyze:(W)=>jf(W.words,{...Dc(W),envAssignments:W.envAssignments,analyzeTokens:W.analyzeChildTokens})},{heads:new Set(["xargs"]),analyze:(W)=>Ip(W.words,{...ug(W),analyzeChild:W.analyzeChild,analyzeNested:(G,H)=>xr(W.options.analyzeNested(G,H))})},{heads:new Set(["parallel"]),analyze:(W)=>Hp(W.words,{...ug(W),analyzeChild:W.analyzeChild,analyzeNested:(G,H)=>xr(W.options.analyzeNested(G,H))})}];function ug(W){return{environment:W.options.environment,cwd:W.cwd,originalCwd:W.originalCwd,strict:W.options.strict,paranoidRm:W.options.paranoidRm,paranoidInterpreters:W.options.paranoidInterpreters,allowTmpdirVar:W.allowTmpdirVar,protectedGitMetadata:W.options.protectedGitMetadata,budget:W.options.budget,envAssignments:W.envAssignments,worktreeMode:W.options.worktreeMode,policy:W.options.policy}}function xr(W){return W?{id:W.ruleId,reason:W.reason,intent:W.intent??"manual_only"}:null}function Dc(W){return{environment:W.options.environment,cwd:W.cwd,originalCwd:W.originalCwd,strict:W.options.strict,paranoid:W.options.paranoidRm,allowTmpdirVar:W.allowTmpdirVar,tmpdirWordSplittingUnsafe:Ur(W.envAssignments,W.options.environment),trustedTmpdirValue:vo(W.envAssignments,W.options.environment),protectedGitMetadata:W.options.protectedGitMetadata,policy:W.options.policy,budget:W.options.budget}}function Nc(W){return{environment:W.options.environment,cwd:W.cwd,originalCwd:W.originalCwd,dynamicArguments:W.dynamicArguments,envAssignments:W.envAssignments,shellAssignments:W.options.shellAssignments,policy:W.options.policy,worktreeMode:W.options.worktreeMode}}function gg(W){return mg.find((G)=>G.heads.has(W))?.analyze}function Io(W,G,H){let J=H.trace;if(W.length===0)return null;let oe=H.commandView?.dialect??"posix",ie=(It)=>It.map((Gt)=>oe==="posix"?t(Gt):Gt.text),fe=H.child,Re=fe!==void 0&&!fe.embedded,Te=fe?.embedded===!0,ke=H.effectiveCwd===null,Le=fe?fe.cwd:ke?void 0:H.effectiveCwd??H.cwd,Xe=fe?fe.originalCwd:ke?void 0:H.cwd,Ye=Ce(W);if(Ye.envAssignments.size>0)J?.recordSegment({type:"env-strip",input:ie(W),envVars:[...Ye.envAssignments.keys()],output:ie(Ye.words)});let Ze=zr(Ye.words,H.environment,Le,new Map([...H.envAssignments??[],...Ye.envAssignments])),Qe=Ze.envSplitValues??[];if(Qe.length>0){let It=[...Qe,...ie(Ze.words)].join(" "),Gt=Nn(It);if(Gt)return J?.recordSegment({type:"dangerous-text",token:It,matched:!0,reason:Gt.reason}),yn(Gt);if(H.strict)return hn(J);let Vt=Rs(Qe,ie(Ze.words));if(Vt){H.budget.charge("derivedTokens",Vt.length);let ln=H.analyzeNested(Vt.join(" "),{effectiveCwd:Ze.cwd===void 0?H.effectiveCwd:Ze.cwd,envAssignments:new Map([...H.envAssignments??[],...Ye.envAssignments,...Ze.envAssignments])});if(ln)return ln}}let et=Ze.rewritten?Qt(ie(Ze.words)):re(oe,Ze.words),tt=ie(et),gt={...H,wrapperNormalizationBudget:H.wrapperNormalizationBudget??{iterations:0}};if(J&&Ye.words.length>et.length){let It=ie(Ye.words);J.recordSegment({type:"leading-tokens-stripped",input:It,removed:It.slice(0,It.length-et.length),output:tt})}let _t=new Map([...H.envAssignments??[],...Ye.envAssignments,...Ze.envAssignments]),yt=tt[0];if(!yt)return null;if(Vr(yt))throw new s("wrapperPeelIterations");let At=zt(yt),Ot=Ze.cwd===null?void 0:Ze.cwd??Le,Mt=Ze.cwd===null?void 0:Xe,Lt=Ze.cwd===void 0?H.effectiveCwd:Ze.cwd,ht=fe?fe.allowTmpdirVar:!hi(_t,H.environment),Wt=ig(oe,Ze.words,H.environment,G===0,H.strict,H.policy);if(Wt)return J?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:Wt.reason}),yn(Wt);let Dt=zs(tt,H.policy);if(Dt){for(let It of[Dt.childIndex,...Dt.alternativeChildIndices]){fg(gt.wrapperNormalizationBudget);let Gt=et.slice(It);J?.recordSegment({type:"transparent-wrapper",wrapper:Dt.wrapper,output:ie(Gt)});let Vt=Io(Gt,G,{...gt,effectiveCwd:Lt,envAssignments:_t});if(Vt)return Vt}return null}let Zt=Te?void 0:At==="eval"?Xs(et):At==="trap"&&!Re?Rp(et):void 0;if(Re&&fe&&At==="eval"){if(Zt?.kind==="dynamic")return To(fe,H.policy);if(Zt?.kind==="literal"){let It=H.analyzeNested(Zt.source,{effectiveCwd:Lt,envAssignments:_t});if(It)return It}return ko(fe,H.policy)}if(Zt?.kind==="dynamic"&&(H.strict||!H.commandView||!Ec(H.commandView)))return hn(J);if(Zt?.kind==="literal"){J?.recordSegment({type:"recurse",reason:At==="eval"?"shell-eval":"shell-trap",innerCommand:Zt.source,depth:G+1});let It=H.analyzeNested(Zt.source,{effectiveCwd:Lt,envAssignments:_t,functionDefinitions:H.functionDefinitions});if(It)return It}if(Re?en.has(At):yg(yt,At)){if(Vn(tt))return null;if(Us(tt))return hn(J);if(Re&&fe){let It=Wn(tt);if(It){if(fe.dynamicSourceInput??fe.dynamicInput){let Vt=To(fe,H.policy);if(Vt)return Vt}if(wi(It)){let Vt=To(fe,H.policy);if(Vt)return Vt}return H.analyzeNested(It,{effectiveCwd:Lt,envAssignments:_t})}let Gt=ur(et);if(Gt.kind==="dynamic")return To(fe,H.policy);if(Gt.kind==="literal")return fe.dynamicSourceInput?To(fe,H.policy):null;return fe.dynamicSourceInput??fe.dynamicInput?To(fe,H.policy):null}if(Te){let It=Wn(tt),Gt=It?H.analyzeNested(It,{effectiveCwd:Lt,envAssignments:_t}):ur(et).kind==="dynamic"?hn(J):null;if(Gt)return Gt}if(fe===void 0){let It=dA(tt,_t,Lt,H,J,G);if(It)return It;let Gt=Wn(tt);if(Gt){let no=Js(et,Gt);if(no.kind==="dynamic")return hn(J);let Ca=no.kind==="literal"?no.source:_p(et,Gt),sd=uA(Ca);J?.recordSegment({type:"shell-wrapper",wrapper:At,innerCommand:sd}),J?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:sd,depth:G+1});let ad=H.analyzeNested(Ca,{effectiveCwd:Lt,envAssignments:_t});if(ad)return ad;return wi(Ca)?hn(J):null}let Vt=ur(et,H.strict?void 0:H.shellAssignments);if(Vt.kind==="dynamic")return hn(J);if(Vt.kind==="literal")return ia(Vt.source,Lt,_t,H,J,G);let ln=xp(et,H.commandView?.redirections??[],H.hasPipelineInput??!1,H.literalShellInput);if(ln.kind==="dynamic")return hn(J);if(ln.kind==="literal")return J?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:ln.source,depth:G+1}),H.analyzeNested(ln.source,{effectiveCwd:Lt,envAssignments:_t})}}if(!fe&&(At==="source"||At===".")){let It=tt[1]==="-p"?2:null;if(It!==null){let no=H.commandView?et[It]:void 0;if(!no)return null;if(no.provenance!=="literal")return hn(J)}let Gt=It===null?1:3,Vt=tt[Gt]==="--"?Gt+1:Gt,ln=H.commandView?et[Vt]:void 0;if(!ln)return null;if(ln.provenance==="literal")return ia(ln.text,Lt,_t,H,J,G);if(H.strict||!H.commandView||!Ec(H.commandView))return hn(J)}if(Mn.has(At)&&!Te){if(!fe&&H.strict&&kc(bi(tt),et))return hn(J);let It=Wf(tt,(Vt)=>xr(H.analyzeNested(Vt,{effectiveCwd:Lt,envAssignments:_t}))),Gt=Nt(It,H.policy);if(Gt)return J?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:Gt.reason}),yn(Gt)}if($n(At)&&!Te){if(!fe&&H.strict&&kc(Ss(tt),et))return hn(J);let It=Dm(tt);if(Re&&fe)return lA(At,It,Lt,_t,H,fe);if(It){let Gt=on(H.policy,"interpreter.one-liner-paranoid",!!H.paranoidInterpreters);if(J?.recordSegment({type:"interpreter",interpreter:At,codeArg:It,paranoidBlocked:Gt}),Gt){let ln=Nt(Pt("interpreter.one-liner-paranoid",li),H.policy);if(ln)return yn(ln)}if(Ll(At,It))return null;J?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:It,depth:G+1});let Vt=H.analyzeNested(It,{effectiveCwd:Lt,envAssignments:_t});if(Vt&&!hg(Vt,It))return Vt;if(ci(It,void 0,!H.strict)){let ln=Nt(Pt("interpreter.dangerous-command",ho),H.policy);if(ln)return J?.recordSegment({type:"dangerous-text",token:It,matched:!0,reason:ho}),yn(ln)}J=void 0}}if(At==="busybox"&&tt.length>1)return fg(gt.wrapperNormalizationBudget),J?.recordSegment({type:"busybox",subcommand:tt[1]??"unknown"}),J?.recordSegment({type:"recurse",reason:"busybox",innerCommand:tt.slice(1).join(" "),depth:G+1}),Io(et.slice(1),G,{...gt,effectiveCwd:Lt,envAssignments:_t});let qt=fe?null:Nt(Im(At,tt),H.policy);if(qt)return J?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:qt.reason}),yn(qt);let Ht=J===gt.trace?gt:{...gt,trace:J},fn={words:et,parsedWords:Ze.words,head:At,cwd:Ot,originalCwd:Mt,envAssignments:_t,allowTmpdirVar:ht,dynamicArguments:Ze.words.some((It)=>It.provenance==="command-substitution"),depth:G,effectiveCwd:Lt,options:Ht,analyzeChildTokens:(It,Gt)=>Re&&fe?Wc(It,G,Ht,{...fe,cwd:Gt??void 0,effectiveCwd:Gt??void 0}):xr(Io(Qt(It),G+1,{...Ht,child:void 0,commandView:void 0,effectiveCwd:Gt,envAssignments:_t}))??N(It,Ht.policy.rules),analyzeChild:(It,Gt)=>Wc(It,G,Ht,Gt)},nn=fe&&(At==="xargs"||At==="parallel")?void 0:gg(At);if(At==="rm"||At==="xargs"||At==="parallel")J?.recordSegment({type:"tmpdir-check",tmpdirValue:_t.has("TMPDIR")||H.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:ht});let rn=J&&At==="git"?gp(fn.words,Nc(fn)):void 0,Rn=pg(rn?rn.match:nn?.(fn)??null,H.policy);if(J)mA(fn,Rn,rn?.relaxation??null);if(Rn)return yn(Rn);if(Re&&fe&&(At==="rm"||At==="rmdir")){if(!(At==="rm"&&(cr(tt)||fe.dynamicRmInput)))return null;return(fe.dynamicRmInput?ko(fe,H.policy):null)??cA(fe,H.policy)}let tr=nn!==void 0&&!pA.has(At),Tr=!fe&&!tr&&!Ki.has(At),Lo=J&&Tr?[]:void 0;if(Tr)for(let It=1;It<tt.length;It++){let Gt=tt[It];if(!Gt)continue;Lo?.push(Gt);let Vt=pg(aA(tt,It,G,Ht,Ot,Mt,Lt,_t),H.policy);if(Vt)return J?.recordSegment({type:"fallback-scan",tokensScanned:Lo??[],embeddedCommandFound:zt(Gt)}),yn(Vt)}if(J?.recordSegment({type:"fallback-scan",tokensScanned:Lo??[]}),Te&&fe&&!fe.wrappedByTransparent)return null;let Tn=N(tt,H.policy.rules);if(J?.recordSegment({type:"custom-rules-check",rulesChecked:H.policy.rules.length>0,matched:!!Tn,reason:Tn?.reason}),Tn)return yn(Tn);return Re&&fe?ko(fe,H.policy):null}function Wc(W,G,H,J){return xr(Io(Qt(W),G+1,{...H,trace:void 0,commandView:void 0,hasPipelineInput:void 0,literalShellInput:void 0,functionDefinitions:void 0,cwd:J.originalCwd,effectiveCwd:J.effectiveCwd,envAssignments:J.envAssignments,worktreeMode:J.dynamicInput?!1:J.worktreeMode,wrapperNormalizationBudget:{iterations:0},child:J}))}function aA(W,G,H,J,oe,ie,fe,Re){for(let Te of jn(W.slice(G),{environment:J.environment,cwd:oe,envAssignments:Re,policy:J.policy})){let ke=Te.tokens[0];if(!ke)continue;let Le=zt(ke);if(yg(ke,Le)||gg(Le)!==void 0&&Le!=="xargs"&&Le!=="parallel"||Te.wrappedByTransparent&&J.policy.rules.length>0)J.budget.charge("derivedTokens",W.length-G);let Ye=Wc(Te.tokens,H,J,{embedded:!0,cwd:Te.cwd,originalCwd:Te.wrapperCwd===null?void 0:ie,effectiveCwd:Te.wrapperCwd===void 0?fe:Te.wrapperCwd,envAssignments:Te.envAssignments,allowTmpdirVar:!hi(Te.envAssignments,J.environment),worktreeMode:!1,wrappedByTransparent:Te.wrappedByTransparent});if(Ye)return Ye}return null}function lA(W,G,H,J,oe,ie){if(!G)return ko(ie,oe.policy);if(on(oe.policy,"interpreter.one-liner-paranoid",!!oe.paranoidInterpreters)){let Re=Nt(Pt("interpreter.one-liner-paranoid",li),oe.policy);if(Re)return yn(Re)}if(Ll(W,G))return ko(ie,oe.policy);let fe=oe.analyzeNested(G,{effectiveCwd:H,envAssignments:J});if(fe&&!hg(fe,G))return fe;if(ci(G,void 0,!oe.strict)){let Re=Nt(Pt("interpreter.dangerous-command",ho),oe.policy);if(Re)return yn(Re)}return ko(ie,oe.policy)}function hg(W,G){let H=W.ruleId==="raw-text.dangerous-command",J=(W.reason.startsWith(Is)||W.reason===Zn)&&!qi(G);return H||J}function To(W,G){let H=W.shellDynamicMatch?Nt(W.shellDynamicMatch,G):null;return H?yn(H):null}function ko(W,G){let H=W.dynamicSourceInput&&W.dynamicSourceMatch?Nt(W.dynamicSourceMatch,G):null;return H?yn(H):null}function cA(W,G){let H=W.dynamicInput&&W.rmDynamicMatch?Nt(W.rmDynamicMatch,G):null;return H?yn(H):null}function dA(W,G,H,J,oe,ie){let fe=Hf(W);if(fe.argvSource?.kind==="absent")return hn(oe);if(fe.argvSourceApplies&&fe.argvSource){let Te=ia(fe.argvSource.value,H,G,J,oe,ie,!0);if(Te)return Te}if(!fe.envSourceApplies||!fe.envName)return null;let Re=G.get(fe.envName);if(!Re)return null;return ia(Re,H,G,J,oe,ie,!0)}function ia(W,G,H,J,oe,ie,fe=!1){if(fe&&/[$`*?[\]]/.test(W))return hn(oe);let Re=ai(W,G,J.environment.paths,J.budget),Te=Re?J.literalHeredocFiles?.get(Re):void 0;if(Te===void 0)return fe?hn(oe):null;return J.budget.charge("derivedTokens",1),oe?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:Te,depth:ie+1}),J.analyzeNested(Te,{effectiveCwd:G,envAssignments:H})}function uA(W){let G=W[0];return W.length>=2&&(G==='"'||G==="'")&&W.at(-1)===G?W.slice(1,-1):W}function mA(W,G,H){let J={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",cmd:"analyzer/cmd.ts:analyzeCmdMatch",powershell:"analyzer/powershell-wrapper.ts:analyzePowerShellWrapperMatch",pwsh:"analyzer/powershell-wrapper.ts:analyzePowerShellWrapperMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[W.head];if(!J)return;if(W.options.trace?.recordSegment({type:"rule-check",rule:J,matched:!!G||!!H,reason:G?.reason??H?.originalReason}),H)W.options.trace?.recordSegment({type:H.kind==="worktree"?"worktree-relaxation":"temp-root-relaxation",originalReason:H.originalReason,gitCwd:H.gitCwd})}function fg(W){if(W.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");W.iterations++}function yn(W){return{reason:W.reason,ruleId:W.id,intent:W.intent}}function hn(W){return W?.recordSegment({type:"error",message:gi}),yn(br())}function yg(W,G){return en.has(G)||W==="$SHELL"||W==="${SHELL}"||en.has(Ft(G))}function pg(W,G){return W?.id.startsWith("custom.")||W?.id==="raw-text.dangerous-command"?W:Nt(W,G)}var fA=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,pA=new Set(["powershell","pwsh"]),gA=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function hA(W,G){let H=bg(W,G);if(H.length===0)return!1;let J=H[Cg(H)];if(J==="cd"||J==="pushd"||J==="popd")return!0;return fA.test(W.join(" "))}function Sg(W,G,H,J,oe){if(W.dialect==="powershell"){let yt=yA(W.words,oe);if(yt.kind==="none")return;if(!G||yt.kind==="unknown")return null;return Lc(vA(yt.target),G,H.paths)}let ie=W.words.map(t),fe=ie.some((yt)=>/^CDPATH\+?=/.test(yt));if(!hA(ie,H))return fe?null:void 0;if(!G)return null;let Re=bg(ie,H,G),Te=Cg(Re);if(Te===-1||Re[Te]!=="cd")return null;let ke=Re.slice(Te+1),Le=ke.findIndex((yt)=>yt.length<=1||!yt.startsWith("-")||yt==="--");if((Le===-1?ke:ke.slice(0,Le)).some((yt)=>!/^-[LP]+$/.test(yt)))return null;let Ye=Le===-1?[]:ke.slice(Le),Ze=Ye[0]==="--"?Ye.slice(1):Ye;if(Ze.length>1)return null;let Qe=Ze[0],et=J.get("HOME")||H.home;if(Qe===void 0)return Lc(pn(et),G,H.paths);let tt=W.words.find((yt)=>yt.provenance==="variable"&&yt.text===Qe),gt=W.words.find((yt)=>yt.text===Qe&&/^~(?:\/|$)/.test(yt.raw)),_t=tt?Qn(tt,new Map([...J,["HOME",et]])):gt?`${et}${Qe.slice(1)}`:Qe;if(_t===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(_t)&&(fe||H.env.has("CDPATH")))return null;return Lc(pn(_t),G,H.paths)}function Lc(W,G,H){if(!W||W==="-"||W.startsWith("~")||W.includes("$")||W.includes("`"))return null;try{let J=hr(G,W,H);return H.isDirectory(J)?J:null}catch{return null}}function yA(W,G){let H=SA(W[0])?1:0,J=W[H];if(!CA(J,H===1))return{kind:"none"};let oe=J.text.toLowerCase(),ie=oe.split(/[\\/]/).pop()??oe;if(!gA.has(ie))return{kind:"none"};if(oe!==ie||ie==="pop-location"||ie==="popd")return{kind:"unknown"};return bA(W.slice(H+1),G)}function SA(W){return W?.provenance==="literal"&&!W.quoted&&W.raw===W.text&&(W.text==="&"||W.text===".")}function CA(W,G){return W?.provenance==="literal"&&(G||!W.quoted&&W.raw===W.text)}function bA(W,G){let H;for(let J of W){if(J.provenance!=="literal"||H!==void 0)return{kind:"unknown"};H=J.text}if(H!==void 0)return{kind:"target",target:H};return G===void 0?{kind:"unknown"}:{kind:"target",target:G}}function vA(W){return W.includes("::")?void 0:W.replaceAll("\\","/")}function Cg(W){let G=0;if(W[0]==="builtin"&&W.length>1)G=1;if(W[G]!=="time")return G;let H=G+1;while(W[H]?.startsWith("-"))H++;return H}function bg(W,G,H){let J=EA(W);return yr([...J],G,H)}function EA(W){let G=0;while(G<W.length){let H=W[G];if(H!=="{"&&H!=="("&&H!=="$(")break;G++}return W.slice(G)}var TA="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Xr="This heredoc form or stdin consumer is not supported safely. Use a quoted heredoc with a supported consumer (cat, tee, git apply, git commit, gh pr create, gh issue create), or ask the user to verify.";function Uc(W,G,H,J){if(G>=a.recursionDepth.cap)return H.trace?.recordSegment({type:"error",message:qn}),{reason:qn,segment:W,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};let oe=J??H.factStore?.getCommandProgram(W,H.shell??"auto")??y(W,H.shell);if(oe.status==="limited")return H.trace?.recordSegment({type:"error",message:qn}),{reason:qn,segment:W,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};if(oe.status==="invalid"){let ke=oe.issues.find((Le)=>Le.code.includes("heredoc"));if(ke){if(!H.strict)return Bc(W,H);let Le=`${Is}: ${ke.message}`;return H.trace?.recordGlobal({type:"error",message:Le}),{reason:Le,segment:W,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"}}return Ag(W,H),{reason:Zn,segment:W,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"}}if(H.strict&&oe.status==="partial")return Ag(W,H),{reason:Zn,segment:W,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"};if(oe.issues.some((ke)=>ke.code.includes("quote")))return Bc(W,H);let fe=H.cwd,Re=H.effectiveCwd!==void 0?H.effectiveCwd:H.cwd,Te=rp(H.environment.env,H.envAssignments);return la(oe,G,{...H,rootProgram:oe},fe,[{effectiveCwd:Re,shellGitContextState:Te,literalHeredocFiles:new Map(H.literalHeredocFiles),functionDefinitions:new Map(H.functionDefinitions),createdDirectories:new Set,compoundBodies:[]}]).result}function la(W,G,H,J,oe){let ie=[...oe],fe,Re,Te;for(let[ke,Le]of W.nodes.entries()){if(Le.kind==="connector"){Re=Le.operator;continue}let Xe=W.nodes[ke+1],Ye=Xe?.kind==="connector"?Xe.operator:void 0,Ze=IA(W,ke,Le,Re,Ye),et=Re==="&&"||Re==="||"?fe:void 0,tt=Re==="&&"?et?.success??ie:Re==="||"?et?.failure??ie:ie,gt=Re==="||"?et?.success??[]:[],_t=Re==="&&"?et?.failure??[]:[],yt={connector:Re,skippedSuccessStates:gt,skippedFailureStates:_t};if(wr(Ye)&&!wr(Re))Te=yt;let At=wr(Ye)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:wr(Re)?Te??yt:yt,Ot=Jr(At.connector)||Jr(Ye);if(Le.kind==="function"){let qt=tt.flatMap((fn)=>{let nn=Qr(fn);return nn.functionDefinitions.set(Le.name,Le.body),Gc(fn,[nn],Ze,Ye==="&",Jr(Ye))}),Ht=Fc(qt,[],At.skippedSuccessStates,At.skippedFailureStates,At.connector,Ye);ie=Ht.states,fe=Ht.conditionalStates,Re=void 0;continue}if(Le.kind==="group"){let qt=[],Ht=[];for(let nn of tt){let rn=la(Le.body,G,H,J,[Qr(nn)]);if(rn.result)return rn;if(qt.push(...Gc(nn,rn.states,Ze,Ye==="&",Jr(Ye))),Ot)Ht.push(nn,...Ze?rn.states.map((Rn)=>sa(nn,Rn)):rn.states)}let fn=Fc(qt,Ht,At.skippedSuccessStates,At.skippedFailureStates,At.connector,Ye);ie=fn.states,fe=fn.conditionalStates,Re=void 0;continue}if(Le.kind!=="command")continue;let Mt=QA(W.nodes[ke-1]),Lt=H.trace?.flattenNested?H.trace.currentSegmentIndex:H.trace?.allocateSegment(),ht=W.nodes[ke-2],Wt=wr(Re)&&ht?.kind==="command"?Ep(ht)??OA(ht):void 0,Dt=[],Zt=[];for(let qt of tt){let Ht=MA(Le,G,H,J,[Qr(qt)]);if(Ht.result)return{result:Ht.result,states:ie};let fn=W.dialect==="powershell"?Ht.states:Ht.states.map((nn)=>sa(qt,nn));for(let nn of fn){let rn=Qr(nn),Rn=LA(Le,G,H.trace?{...H,trace:Pg(H.trace,Lt)}:H,J,rn,wr(Re),Wt);if(Rn)return{result:Rn,states:ie};let tr=sP(Le,rn.functionDefinitions);if(tr)H.budget.charge("derivedTokens",ca(tr));let Tr=tr?G+1>=a.recursionDepth.cap?zc(Le.displayText,H,[rn]):la(tr,G+1,H,J,[rn]):{result:null,states:oP(Le,rn).flatMap((Tn)=>eP(Le,nn,Tn,Mt))};if(Tr.result)return Tr;Dt.push(...Gc(qt,Tr.states,Ze,Ye==="&",Jr(Ye)));let Lo=typeof rn.effectiveCwd==="string"&&rn.effectiveCwd!==nn.effectiveCwd&&Le.redirections.every((Tn)=>["<",">",">>",">|"].includes(Tn.operator)&&Tn.target?.text==="/dev/null");if(Ot&&(Mt||!Lo))Zt.push(qt),Zt.push(...Tr.states.map((Tn)=>Ze?sa(qt,Tn):Tn))}}let Pr=Fc(Dt,Zt,At.skippedSuccessStates,At.skippedFailureStates,At.connector,Ye);ie=Pr.states,fe=Pr.conditionalStates,Re=void 0}return{result:null,states:ie}}function IA(W,G,H,J,oe){if(H.kind==="group"&&H.style==="subshell")return!0;if(W.dialect==="posix"&&(wr(J)||wr(oe)))return!0;if(oe==="&")return!0;return W.dialect==="powershell"&&H.kind==="group"&&H.style==="brace"&&kA(W,G)}function Gc(W,G,H,J,oe){let ie=H?G.map((Re)=>sa(W,Re)):[...G],fe=oe?ie.flatMap((Re)=>Oo(W.literalHeredocFiles,Re.literalHeredocFiles)?[Re]:[{...Re,literalHeredocFiles:new Map(W.literalHeredocFiles)},Re]):ie;return J?[W,...fe]:fe}function sa(W,G){return{...W,literalHeredocFiles:new Map(G.literalHeredocFiles),createdDirectories:new Set(G.createdDirectories)}}function kA(W,G){let H=W.nodes.slice(0,G).reverse().find((oe)=>oe.kind==="command"||oe.kind==="connector");if(!H||H.kind!=="command")return!0;let J=H.words[0]?.text.toLowerCase();if(J==="&"||J===".")return!1;if(J==="write-output"||J==="function"||J==="start-job")return!0;if(DA(H))return!0;return H.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function wr(W){return W==="|"||W==="|&"}function OA(W){if(W?.dialect!=="powershell")return;if(W.words.length===1&&W.words[0]?.quoted&&W.words[0].provenance==="literal")return W.words[0].text;if(W.words[0]?.text.toLowerCase()==="write-output"&&W.words.length===2&&W.words[1]?.provenance==="literal")return W.words[1].text;return}function Jr(W){return W==="&&"||W==="||"}function Fc(W,G,H,J,oe,ie){let fe={success:aa([...H,...W]),failure:aa([...J,...G])},Re=Jr(ie)?fe:void 0;return{states:Jr(oe)||Re?aa([...fe.success,...fe.failure]):fe.success,conditionalStates:Re}}function Pg(W,G,H=W.flattenNested){return{currentSegmentIndex:G,flattenNested:H,allocateSegment:W.allocateSegment,getNextSegmentIndex:W.getNextSegmentIndex,branch:W.branch,recordGlobal:W.recordGlobal,recordSegment:(J,oe=G)=>W.recordSegment(J,oe)}}function MA(W,G,H,J,oe){let ie=W.nested.map((fe)=>({program:fe,depth:G}));if(W.dialect==="powershell"){let fe=NA(W);if(fe){if(G+1>=a.recursionDepth.cap)return zc(fe,H,oe);let Re=y(fe,"powershell");if(Re.status==="limited")return zc(fe,H,oe);if(Re.status!=="complete")return vg(ie,H,J,oe);H.budget.charge("derivedTokens",ca(Re)),ie.push({program:Re,depth:G+1})}}return vg(ie,H,J,oe)}function DA(W){let G=W.words[0];return G?.provenance==="variable"&&W.words.at(-1)?.text==="="?G.text.toLowerCase():void 0}function vg(W,G,H,J){let oe=[...J];for(let ie of W){let fe=[];for(let Re of oe){let Te=la(ie.program,ie.depth,G,H,[Qr(Re)]);if(Te.result)return Te;fe.push(...Te.states)}oe=aa(fe)}return{result:null,states:oe}}function NA(W){let G=W.words[0]?.provenance==="literal"&&!W.words[0].quoted&&W.words[0].raw===W.words[0].text&&(W.words[0].text==="&"||W.words[0].text==="."),H=G?1:0,J=W.words[H];if(J?.provenance!=="literal"||!G&&(J.quoted||J.raw!==J.text)||!["iex","invoke-expression"].includes(J.text.toLowerCase()))return;let oe=W.words.slice(H+1),ie=oe[0]&&!oe[0].quoted&&oe[0].raw===oe[0].text&&["-c","-command"].includes(oe[0].text.toLowerCase())?1:0,fe=oe[ie];return oe.length===ie+1&&fe?.quoted&&fe.provenance==="literal"?fe.text:void 0}function ca(W){return W.nodes.reduce((G,H)=>G+(H.kind==="command"?H.words.length+H.nested.reduce((J,oe)=>J+ca(oe),0):H.kind==="group"||H.kind==="function"?ca(H.body):0),0)}function zc(W,G,H){return G.trace?.recordSegment({type:"error",message:qn}),{result:{reason:qn,segment:W,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"},states:[...H]}}function LA(W,G,H,J,oe,ie,fe){let Re={...H,environment:{...H.environment,env:oe.shellGitContextState.env,paths:$A(H.environment.paths,oe.createdDirectories,H.budget)}},Te=KA(W,!Re.strict);if(Te&&Re.strict)return Re.trace?.recordSegment({type:"error",message:Te}),{reason:Te,segment:W.source,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"};Tg(W,oe,"before-consumer",Re.environment.paths,Re.budget);let ke=re(W.dialect,W.words),Le=ke.map(t),Xe=W.displayText,Ye=tp(ke,oe.shellGitContextState),Ze=ip(Ye,oe.shellGitContextState);if(W.dialect==="powershell"){let gt=Nt(If(W,ie,aP(Re,oe.effectiveCwd)),Re.policy);if(Re.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!gt,reason:gt?.reason}),gt)return wg(Xe,gt)}let Qe=Nt(km(W.redirections),Re.policy);if(Qe)return Re.trace?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceRedirectionMatch",matched:!0,reason:Qe.reason}),wg(Xe,Qe);if(Le.length===1&&Le[0]?.includes(" ")&&!Jo(W.dialect,W.words)){let gt=Nt(Nn(Le[0]),Re.policy),_t=gt!==null&&!Re.strict&&wm(W,Re.rootProgram);if(gt&&!_t)return Re.trace?.recordSegment({type:"dangerous-text",token:Le[0],matched:!0,reason:gt.reason}),{reason:gt.reason,segment:Xe,ruleId:gt.id,intent:gt.intent};Re.trace?.recordSegment({type:"dangerous-text",token:Le[0],matched:!1});let yt=Eg(W,Te,oe,Ze,fe,Re);if(yt)return yt;return hc(Ye,oe.shellGitContextState),null}let et=Io(W.words,G,{...Re,commandView:W,cwd:J,effectiveCwd:oe.effectiveCwd,envAssignments:Ze,shellAssignments:oe.shellGitContextState.shellAssignments,literalHeredocFiles:oe.literalHeredocFiles,functionDefinitions:oe.functionDefinitions,hasPipelineInput:ie,literalShellInput:fe,analyzeNested:(gt,_t)=>{let yt=_t&&Object.hasOwn(_t,"effectiveCwd")?_t.effectiveCwd:oe.effectiveCwd,At=Uc(gt,G+1,{...Re,effectiveCwd:yt,envAssignments:_t?.envAssignments??Ze,literalHeredocFiles:oe.literalHeredocFiles,functionDefinitions:_t?.functionDefinitions,worktreeMode:_t?.worktreeMode??Re.worktreeMode,shell:_t?.shell??Re.shell,trace:Re.trace?Pg(Re.trace,Re.trace.currentSegmentIndex,!0):void 0});return At?{reason:At.reason,ruleId:At.ruleId,intent:At.intent}:null}});if(et)return{...et,segment:Xe};let tt=Eg(W,Te,oe,Ze,fe,Re);if(tt)return tt;return hc(Ye,oe.shellGitContextState),null}function Eg(W,G,H,J,oe,ie){let fe=qA(W,G,H,J??new Map,ie);if(fe)return fe;return Tg(W,H,"after-consumer",ie.environment.paths,ie.budget),H.literalHeredocFiles.clear(),FA(W,G,H,ie.environment.paths,ie.budget),BA(W,H,ie.environment.paths,ie.budget),XA(W,H,oe,ie.environment,ie.trace),null}var WA=new Set([">>","<>"]);function Tg(W,G,H,J,oe){for(let fe of W.redirections){if(!(H==="before-consumer"?GA(fe):WA.has(fe.operator)))continue;Rg(fe.target,G,J,oe)}if(H!=="before-consumer"||!mn(W.words[0],"tee"))return;let ie=kg(W.words.slice(1));if(!ie)return;for(let fe of ie.operands)Rg(fe,G,J,oe)}function GA(W){if(W.operator===">"||W.operator===">|")return!0;return W.operator===">&"&&W.fd===void 0&&W.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(W.target.text)}function Rg(W,G,H,J){let oe=W?.provenance==="literal"?ai(W.text,G.effectiveCwd,H,J):void 0;if(!oe)return;G.literalHeredocFiles.delete(oe)}function FA(W,G,H,J,oe){if(G)return;let ie=W.redirections.find((fe)=>fe.operator==="<<"||fe.operator==="<<-")?.heredoc;if(!ie)return;for(let fe of zA(W,H.shellGitContextState.shellAssignments)){let Re=ai(fe,H.effectiveCwd,J,oe);if(!Re||!Mm(Re))continue;if(!H.literalHeredocFiles.has(Re)&&H.literalHeredocFiles.size>=a.trackedHeredocFiles.cap)throw new s("trackedHeredocFiles");H.literalHeredocFiles.set(Re,ie.body)}}function zA(W,G){let H=$c(jA(W.redirections)?.target,G),J=H===void 0?[]:[H];if(mn(W.words[0],"cat"))return HA(W.words)?J:[];if(!mn(W.words[0],"tee"))return[];let oe=kg(W.words.slice(1),G);if(!oe||oe.append||oe.hasUnsupportedOptions)return[];let ie=oe.operands.map((fe)=>$c(fe,G));if(!ie.every((fe)=>fe!==void 0))return[];return[...ie,...J]}function $c(W,G){if(VA(W))return W.text;return(W&&Qn(W,G))??void 0}function $A(W,G,H){if(G.size===0)return W;let J=(oe)=>{let ie=Bt(oe,W,H);return[...G].some((fe)=>fe===ie||fe.startsWith(`${ie}${PA}`))};return{realpath:(oe)=>W.realpath(oe)??(J(oe)?Bt(oe,W,H):null),entryKind:(oe)=>{let ie=W.entryKind(oe);return ie==="missing"&&J(oe)?"present":ie},isDirectory:(oe)=>W.isDirectory(oe)||J(oe)}}function BA(W,G,H,J){if(G.shellGitContextState.bodyDepth>0||!mn(W.words[0],"mkdir"))return;let oe=W.words.slice(1).map((ke)=>$c(ke,G.shellGitContextState.shellAssignments));if(!oe.every((ke)=>ke!==void 0))return;let ie=oe.findIndex((ke)=>ke==="--"||ke==="-"||!ke.startsWith("-")),fe=oe.slice(0,ie);if(ie===-1||!fe.every((ke)=>/^(?:-[pv]+|--parents|--verbose)$/.test(ke)))return;let Re=fe.some((ke)=>ke==="--parents"||/^-v*p/.test(ke)),Te=G.effectiveCwd;for(let ke of oe.slice(oe[ie]==="--"?ie+1:ie)){if(ke.split(/[\\/]/).includes("..")||!_A(ke)&&!Te)continue;let Le=Bt(AA(Te??"",ke),H,J);if(Re?UA(Le,H):H.isDirectory(RA(Le))&&Ig(Le,H))G.createdDirectories.add(Le)}}function UA(W,G){let H=wA(W).root,J=W.slice(H.length).split(/[\\/]+/).filter(Boolean),oe=(fe)=>xA(H,...J.slice(0,fe+1)),ie=J.findIndex((fe,Re)=>!G.isDirectory(oe(Re)));return ie===-1||Ig(oe(ie),G)}function Ig(W,G){try{return G.entryKind(W)==="missing"}catch{return!1}}function HA(W){let G=!1;for(let H of W.slice(1)){if(G||H.provenance!=="literal")return!1;if(H.text==="--"){G=!0;continue}if(!/^-u+$/.test(H.text))return!1}return!0}function jA(W){let G=W.findLast((H)=>(H.fd??([">",">|",">>",">&"].includes(H.operator)?1:0))===1);return G?.operator===">"||G?.operator===">|"?G:void 0}function kg(W,G=new Map){let H=[],J=!0,oe=!1,ie=!1;for(let fe of W){if(fe.provenance!=="literal"&&Qn(fe,G)===null)return;if(J&&mn(fe,"--")){J=!1;continue}if(J&&!fe.quoted&&fe.raw===fe.text&&/^-[^-]/.test(fe.text)){oe||=fe.text.slice(1).includes("a"),ie||=Array.from(fe.text.slice(1)).some((Re)=>Re!=="a"&&Re!=="i");continue}if(J&&!fe.quoted&&fe.raw===fe.text&&fe.text.startsWith("--")){oe||=fe.text==="--append",ie||=fe.text!=="--append"&&fe.text!=="--ignore-interrupts";continue}H.push(fe)}return{operands:H,append:oe,hasUnsupportedOptions:ie}}function VA(W){if(!W||W.provenance!=="literal"||W.text.length===0)return!1;if(W.quoted||W.raw!==W.text)return!0;return!W.raw.startsWith("~")&&!/[{}]/.test(W.raw)}function mn(W,G){return W?.text===G&&W.raw===G&&W.provenance==="literal"&&!W.quoted}function Hc(W){return W.quotedDelimiter||!/[$`\\]/.test(W.body)}function KA(W,G){let H=W.redirections.filter((Te)=>Te.operator==="<<"||Te.operator==="<<-");if(H.length===0)return;if(H.length!==1)return Xr;let J=H[0];if(!J?.heredoc)return Xr;let oe=/\$\(|`/.test(J.heredoc.body);if(!Hc(J.heredoc)&&(!G||oe))return TA;if(J.fd!==void 0&&J.fd!==0)return Xr;if(W.redirections.some((Te)=>Te!==J&&["<","<<","<<-","<<<","<&","<>"].includes(Te.operator)))return Xr;let ie=W.redirections.some((Te)=>Te!==J&&_g(Te.target));if(mn(W.words[0],"cat"))return ie?Xr:void 0;if(mn(W.words[0],"tee"))return ie||W.words.slice(1).some(_g)?Xr:void 0;let fe=W.words[0],Re=W.words[1];if(mn(fe,"git")&&(mn(Re,"apply")||mn(Re,"commit")))return;if(mn(fe,"gh")&&(mn(Re,"pr")||mn(Re,"issue"))&&mn(W.words[2],"create"))return;return Xr}function _g(W){return W?.parts.some((G)=>G.provenance==="command-substitution"&&G.raw.startsWith(">("))??!1}function qA(W,G,H,J,oe){if(!G)return null;let ie=W.redirections.filter((ke)=>ke.operator==="<<"||ke.operator==="<<-"),fe=ie.flatMap((ke)=>ke.heredoc?[ke.heredoc.body]:[]);if(ZA(W,ie,H,J,oe))return null;let Re=YA(W,ie,oe);if(Re!==void 0)return Re?{reason:Re.reason,segment:W.displayText,ruleId:Re.id,intent:Re.intent}:null;let Te=Bc(fe.length===ie.length?fe.join(`
|
|
42
|
+
`):W.source,oe);return Te?{...Te,segment:W.displayText}:null}function YA(W,G,H){let J=G.length===1?G[0]:void 0;if(!J?.heredoc||!Hc(J.heredoc)||J.fd!==void 0&&J.fd!==0)return;let oe=mn(W.words[0],"uv")&&mn(W.words[1],"run")?W.words.slice(2):W.words,ie=oe[0];if(ie?.provenance!=="literal"||!$n(ie.text))return;let fe=oe.findIndex((Xe)=>mn(Xe,"-"));if(!oe.slice(1,fe===-1?void 0:fe).every((Xe)=>Xe.provenance==="literal"&&Xe.text.startsWith("-")))return;let Te=J.heredoc.body,ke=on(H.policy,"interpreter.one-liner-paranoid",!!H.paranoidInterpreters);if(H.trace?.recordSegment({type:"interpreter",interpreter:ie.text,codeArg:Te,paranoidBlocked:ke}),ke){let Xe=Nt(Pt("interpreter.one-liner-paranoid",li),H.policy);if(Xe)return Xe}if(!ci(Te,void 0,!H.strict))return null;let Le=Nt(Pt("interpreter.dangerous-command",ho),H.policy);if(!Le)return null;return H.trace?.recordSegment({type:"dangerous-text",token:Te,matched:!0,reason:Le.reason}),Le}function ZA(W,G,H,J,oe){let ie=G.length===1?G[0]:void 0;if(!ie?.heredoc||!Hc(ie.heredoc)||ie.fd!==void 0&&ie.fd!==0)return!1;let fe=zr(W.words,oe.environment,H.effectiveCwd,J),Re=fe.words.map(t),Te=zt(Re[0]??"");if((fe.envSplitValues?.length??0)>0||!en.has(Te)&&!en.has(Ft(Te)))return!1;return Vn(Re)}function XA(W,G,H,J,oe){let ie=Sg(W,G.effectiveCwd,J,G.shellGitContextState.shellAssignments,H);if(ie===null)oe?.recordSegment({type:"cwd-change",segment:W.words.map(t).join(" "),effectiveCwdNowUnknown:!0});if(ie!==void 0)G.effectiveCwd=ie}var JA=new Set(["fi","done","esac"]);function QA(W){return W?.kind==="command"&&W.words.length===1&&W.words[0]?.raw==="!"}function eP(W,G,H,J){let oe=W.words[0]?.text??"",ie=G.shellGitContextState.bodyDepth,fe=H.shellGitContextState.bodyDepth,Re=H.compoundBodies;if(fe>ie)return H.compoundBodies=[...Re.slice(0,ie),{entryCwd:G.effectiveCwd,branchCwds:Re[ie]?.branchCwds??[],hasElse:!1}],[H];let Te=ie>0?Re[ie-1]:void 0;if(Te&&(oe==="else"||oe==="elif"))return H.compoundBodies=[...Re.slice(0,ie-1),{entryCwd:Te.entryCwd,branchCwds:[...Te.branchCwds,H.effectiveCwd],hasElse:oe==="else"}],H.effectiveCwd=Te.entryCwd,[H];let ke=Te!==void 0&&JA.has(oe);if(ke)H.compoundBodies=Re.slice(0,fe);return[...new Set([H.effectiveCwd,...ke?Te.branchCwds:[],...ke&&!Te.hasElse?[Te.entryCwd]:[],...J?[G.effectiveCwd]:[]])].map((Xe)=>{if(Xe===H.effectiveCwd)return H;let Ye=Qr(H);return Ye.effectiveCwd=Xe,Ye})}function tP(W,G){return W.length===G.length&&W.every((H,J)=>{let oe=G[J];return oe!==void 0&&H.entryCwd===oe.entryCwd&&H.hasElse===oe.hasElse&&H.branchCwds.length===oe.branchCwds.length&&H.branchCwds.every((ie,fe)=>ie===oe.branchCwds[fe])})}var nP=/^[A-Za-z_][A-Za-z0-9_]*$/,rP=8;function oP(W,G){let H=W.words[1]?.text;if(W.dialect!=="posix"||W.words[0]?.text!=="for"||H===void 0||!nP.test(H))return[G];let J=W.words.slice(3);if(!(W.words[2]?.text==="in"&&J.length>=1&&J.length<=rP&&J.every((ie)=>ie.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(ie.text))))return G.shellGitContextState.shellAssignments.delete(H),[G];return J.map((ie)=>{let fe=Qr(G);return fe.shellGitContextState.shellAssignments.set(H,ie.text),fe})}function Qr(W){return{effectiveCwd:W.effectiveCwd,shellGitContextState:op(W.shellGitContextState),literalHeredocFiles:new Map(W.literalHeredocFiles),functionDefinitions:new Map(W.functionDefinitions),createdDirectories:new Set(W.createdDirectories),compoundBodies:W.compoundBodies}}function aa(W){let G=[];for(let H of W){if(!G.some((J)=>iP(J,H)))G.push(H);if(G.length>a.controlFlowStates.cap)throw new s("controlFlowStates")}return G}function iP(W,G){return W.effectiveCwd===G.effectiveCwd&&tP(W.compoundBodies,G.compoundBodies)&&Oo(W.shellGitContextState.env,G.shellGitContextState.env)&&Oo(W.literalHeredocFiles,G.literalHeredocFiles)&&Oo(W.functionDefinitions,G.functionDefinitions)&&Oo(W.shellGitContextState.effectiveEnvAssignments,G.shellGitContextState.effectiveEnvAssignments)&&Oo(W.shellGitContextState.shellAssignments,G.shellGitContextState.shellAssignments)&&W.shellGitContextState.bodyDepth===G.shellGitContextState.bodyDepth&&xg(W.shellGitContextState.bodyAssignments,G.shellGitContextState.bodyAssignments)&&xg(W.createdDirectories,G.createdDirectories)}function xg(W,G){return W.size===G.size&&[...W].every((H)=>G.has(H))}function Oo(W,G){if(W===G)return!0;if(!W||!G||W.size!==G.size)return!1;return[...W].every(([H,J])=>G.get(H)===J&&G.has(H))}function sP(W,G){let H=Qo(W);return H===void 0?void 0:G.get(H)}function wg(W,G){if(!G)return null;return{reason:G.reason,segment:W,ruleId:G.id,intent:G.intent}}function aP(W,G=W.effectiveCwd){let H=G===null;return{environment:W.environment,cwd:H?void 0:G??W.cwd,originalCwd:H?void 0:W.cwd,strict:W.strict,paranoid:W.paranoidRm,allowTmpdirVar:W.allowTmpdirVar,protectedGitMetadata:W.protectedGitMetadata,policy:W.policy,budget:W.budget}}function Bc(W,G){let H=Nt(Nn(W),G.policy),J=G.trace?.currentSegmentIndex??G.trace?.allocateSegment(),oe={type:"dangerous-text",token:W,matched:!!H,reason:H?.reason};if(G.trace?.recordSegment(oe,J),!H&&/^(?:cd|pushd)\s/.test(W))G.trace?.recordSegment({type:"cwd-change",segment:W,effectiveCwdNowUnknown:!0},J);return H?{reason:H.reason,segment:W,ruleId:H.id,intent:H.intent}:null}function Ag(W,G){let H={type:"strict-unparseable",rawCommand:W,reason:Zn},J=G.trace?.currentSegmentIndex;if(J===void 0)G.trace?.recordGlobal(H);if(J!==void 0)G.trace?.recordSegment(H)}var lP=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function Og(W,G,H,J){let oe=Uc(W,0,{...G,...qe(G),budget:G.budget??In(),factStore:J},H);if(!oe)return null;return{kind:"deny",reason:oe.reason,intent:oe.intent??"manual_only",ruleId:oe.ruleId,evidence:{command:W,segment:oe.segment}}}function Mg(W,G,H){try{return{decision:W()}}catch(J){let oe=cP(J,G,H);if(!oe)throw J;return oe}}function cP(W,G,H){if(!(W instanceof s)||!lP.has(W.kind))return null;let J=a[W.kind];if(H?.currentSegmentIndex!==void 0)H.recordSegment({type:"error",message:J.reason});if(H?.currentSegmentIndex===void 0)H?.recordGlobal({type:"error",message:J.reason});return{decision:{kind:"deny",reason:J.reason,ruleId:"analysis.derived-command-limit",intent:"stop_and_explain",evidence:{command:G,segment:G}},errorCode:J.errorCode}}var dP=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),Vc=new Set(["cc-safety-net","ccsn"]),uP=new Set(["bunx","npx","pnpx"]),mP=new Set(["pnpm","yarn"]),fP=new Set(["npm","pnpm","yarn"]),pP=new Set(["bun","node"]);function ua(W,G,H={}){if(Vc.has(W))return 0;if(uP.has(W)){if(H.broad)return jc(G);let oe=G[0]==="-y"||G[0]==="--yes"?1:0;return da(G[oe])?oe+1:null}let J=H.broad?G.findIndex((oe)=>!oe.startsWith("-")):0;if(J!==-1&&fP.has(W)&&H.broad&&G[J]==="exec"){let oe=jc(G.slice(J+1));return oe===null?null:J+1+oe}if(mP.has(W)){if(W==="yarn"&&!H.broad)return null;if(!H.broad)return G[0]==="dlx"&&da(G[1])?2:null;if(J===-1||G[J]!=="dlx")return null;let oe=jc(G.slice(J+1));return oe===null?null:J+1+oe}if(pP.has(W)){let oe=H.broad&&J!==-1?J:0;if(Dg(G[oe]))return oe+1;if(W==="bun"&&G[oe]==="run"&&Dg(G[oe+1]))return oe+2}return null}function jc(W){let G=W.findIndex((J)=>da(J));if(G===-1)return null;let H=G;while(H<W.length){let J=W[H]??"";if(!J.startsWith("-")&&!da(J))break;H++}return H}function da(W){if(!W)return!1;let G=W.indexOf("@");if(G===-1)return Vc.has(W);if(G===0)return!1;let H=W.slice(G+1);if(H===""||H.includes("/")||H.includes(":"))return!1;return Vc.has(W.slice(0,G))}function Dg(W){let G=W?.replaceAll("\\","/");return[...dP].some((H)=>G===H||G?.endsWith(`/${H}`))}var Ke="Only the user may apply a policy proposal, because it rewrites the configuration CC Safety Net enforces. Ask them to run `cc-safety-net policy apply <file>` themselves in a terminal; you can run `cc-safety-net policy check <file>` to show them what it would change.";function Ng(W,G,H){let J=ar(W);if(!J)return null;let oe=bo(J.shell,W.invocation.context.executionCwd,G,H,{findSegmentTarget:(ie)=>gP(ie,G),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return oe?{target:oe}:null}function gP(W,G){let H=yr([...W],G),J=H.slice(1),oe=ua(Ft(H[0]??"").toLowerCase(),J,{broad:!0});if(oe===null)return null;let ie=J.slice(oe).filter((fe)=>fe!=="-g"&&fe!=="--global");return ie[0]==="policy"&&ie[1]==="apply"?H.join(" "):null}import{dirname as ma}from"node:path";var Je="This path contains the protected policy config and you must not modify or delete it.",hP=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Fg(W,G,H){let J=EP(W.invocation.context,G,H);if(W.invocation.route.kind==="patch")return Lg(W.paths,!1,W.invocation.context.executionCwd,J,G,H);let oe=ar(W);if(W.invocation.route.kind==="command")return oe?Wg(oe.shell,W.invocation.context.executionCwd,J,G,H):null;if(W.invocation.route.kind==="unknown"&&oe){let ie=Wg(oe.shell,W.invocation.context.executionCwd,J,G,H);if(ie)return ie}return Lg(W.paths,W.invocation.route.kind==="grep"||W.invocation.route.kind==="glob"||Gi(W.invocation.toolName),W.invocation.context.executionCwd,J,G,H)}function Lg(W,G,H,J,oe,ie){if(G)return null;let fe=W.find((Re)=>Ti(Re,H,J,oe,ie));return fe?{target:fe}:null}function Wg(W,G,H,J,oe){let ie=bo(W,G,J,oe,{findSegmentTarget:(fe,Re)=>yP(fe,Re,H,J,oe)?.target??null,isRedirectionTarget:(fe,Re)=>Ti(fe,Re.cwd,H,J,oe),findMalformedTarget:(fe)=>vP(fe,G,H,J,oe)?.target??null});return ie?{target:ie}:null}function yP(W,G,H,J,oe){if(pi(W))return null;let ie=Sr([...W],J),fe=Ft(ie[0]??"").toLowerCase(),Re=ie.slice(1);if(fe==="rm"&&SP(Re)){let Te=CP(Re).find((ke)=>Gg(bn(ke,G.variables),G.cwd,H,J,oe));if(Te)return{target:Te}}if(fe==="find"){if(Hs(ie,1)||ac(ie,J)){let ke=(vi(Qt(ie))??Qt(["."])).find((Le)=>{let Xe=bn(Le.text,G.variables);return Ti(Xe,G.cwd,H,J,oe)||Gg(Xe,G.cwd,H,J,oe)})?.text;if(ke)return{target:ke}}}if(fe==="mv"){let Te=ks(Re).sources.find((ke)=>RP(bn(ke,G.variables),G.cwd,H,J,oe));if(Te)return{target:Te}}if(bP(ie,fe))return null;for(let Te of[...W,...ie])for(let ke of zg(Te))if(Ti(bn(ke,G.variables),G.cwd,H,J,oe))return{target:ke};return null}function SP(W){return W.some((G)=>G==="--recursive"||G.startsWith("-")&&!G.startsWith("--")&&/[rR]/.test(G.slice(1)))}function CP(W){let G=W.indexOf("--");if(G!==-1)return[...W.slice(0,G).filter((H)=>!H.startsWith("-")),...W.slice(G+1)];return W.filter((H)=>!H.startsWith("-"))}function bP(W,G){if(!hP.has(G))return!1;if(G!=="sed")return!0;return!W.slice(1).some((H)=>H.startsWith("-i")||H==="--in-place"||H.startsWith("--in-place="))}function vP(W,G,H,J,oe){for(let ie of W.split(/\s+/))for(let fe of zg(ie))if(Ti(fe,G,H,J,oe))return{target:fe};return null}function zg(W){let G=W.trim().replace(/^['"]|['"]$/g,""),H=G.indexOf("=");return H===-1||H===G.length-1?[G]:[G,G.slice(H+1)]}function EP(W,G,H){let J=(Re)=>Ii(gn(Re,W.executionCwd,G,H)),oe=J(u(G)),ie=[J(h(W.executionCwd)),J(h(W.configCwd))],fe=new Set(ie.map((Re)=>ma(Re)));for(let Re=ma(oe);;Re=ma(Re))if(fe.add(Re),ma(Re)===Re)break;return{files:new Set([oe,...ie]),directoriesAndAncestors:fe}}function Ti(W,G,H,J,oe){let ie=fd(W,G,J,oe,(fe)=>Ii(fe)===ji);return ie!==null&&H.files.has(Ii(ie))}function Gg(W,G,H,J,oe){return H.directoriesAndAncestors.has(Ii(gn(W,G,J,oe)))}function RP(W,G,H,J,oe){let ie=Ii(gn(W,G,J,oe));return H.files.has(ie)||H.directoriesAndAncestors.has(ie)}function Ii(W){return process.platform==="win32"?W.toLowerCase():W}import{isAbsolute as fa,posix as Qg,resolve as ya,win32 as _P}from"node:path";import{fileURLToPath as xP}from"node:url";var eh="Access to a sensitive path is not allowed.",th=new Set(["echo","printf"]),wP=new Set(["find"]),AP=new Set(["!","do","elif","else","if","then","until","while"]),PP=new Set(["-exec","-execdir"]),TP=new Set([";","+"]),IP=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),kP=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),nh=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),OP=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),MP=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"]),Xc=new Set(["-c","-e","-r","-E","--eval","--exec"]),DP=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"])]]),Jc=new Set(["grep","rg"]),rh=new Set(["files-with-matches","files-without-match","count","quiet"]),NP=new Set([...rh,"ignore-case","fixed-strings","hidden"]),LP=new Set(["wc",...Jc]),WP=new Set(["cd","grep","head","openssl","tail","tailscale"]),GP=/^(?:-[lwcm]+|--(?:lines|words|bytes|chars))$/,FP=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),zP=new Set(["commit","merge","notes","stash","tag"]),$P=new Set(["-m","--message"]),BP=new Set(["--grep"]),UP=new Set(["powershell","pwsh"]),$g=new Set(["jq","gojq","jaq"]),Bg="f",Ug="file",HP="files",jP=new Set(["e","f"]),VP=new Set(["regexp","file"]),KP=new Set(["e","f","A","B","C","m"]),qP=new Set(["regexp","file","after-context","before-context","context","max-count"]),Kc="__CC_SAFETY_NET_PIPE_INPUT__",Yc=/[\w./~@+-]*[./~][\w./~@+-]*/g,YP=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,ZP=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,XP=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,Hg=/\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,jg=/\b(?:system|exec|spawn|popen)\s*$/,JP=/\b(?:eval|exec)\s*\(/g,QP=/\b(?:eval|exec)\s*$/,eT=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 Vg(W,G,H,J,oe,ie){for(let fe of W){let Re=fe.target;if(bI(Re,fe.cwd,G?.denyPaths??[],H,J,oe))return{target:Re,ruleId:"secret.deny-path"};if(ie&&!ie.has(Re))continue;let Te=SI(Re,fe.cwd,G,J,oe);if(Te){let ke=ie!==void 0&&!Te.startsWith("secret.home.")&&!Te.startsWith("secret.cli.");if(ke&&J.paths.isDirectory(yh(Re,fe.cwd,J,oe)))continue;if(ke&&ie?.get(Re)==="data")continue;if(ke&&(fe.isRedirectionWriteTarget===!0||ie?.get(Re)==="write")&&!Re.includes("$")&&!ha(Re,fe.cwd,J,oe))continue;if(ke&&(fe.isCreatedPath===!0||fe.isCertificateInput===!0))continue;if(ke&&/\s/.test(Re)&&!Re.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(Re)&&!ha(Re,fe.cwd,J,oe))continue;if(!Te.startsWith("secret.cli.")&&vI(Re,fe.cwd,G?.allowPaths??[],H,J,oe))continue;return{target:Re,ruleId:Te}}}return null}function oh(W,G,H,J,oe={}){let ie=Kg(W,H,J),fe=Vg(ie,G,W.invocation.context.configCwd,H,J);if(fe===null||fe.ruleId==="secret.deny-path"||oe.strict!==!1)return fe;let Re=Kg(W,H,J,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}),Te=new Map;Re.forEach((Qe)=>ih(Qe.target).forEach((et)=>Te.set(et,(Te.get(et)??new Set).add(Qe.loopVariable))));let ke=(Qe,et)=>(Te.get(Qe)?.size??0)>(Te.get(Qe)?.has(et)?1:0),Le=Re.filter(({loopVariable:Qe})=>Qe===void 0||ke(Qe,Qe)||ke("!",Qe)),Xe=new Set(Le.filter((Qe)=>Qe.literalRole===void 0).map((Qe)=>Qe.target)),Ye=new Set(Le.filter((Qe)=>Qe.literalRole==="write").map((Qe)=>Qe.target)),Ze=Vg(ie,G,W.invocation.context.configCwd,H,J,new Map(Le.map((Qe)=>[Qe.target,Xe.has(Qe.target)?"path":Ye.has(Qe.target)?"write":"data"])));return Ze?.ruleId!=="secret.deny-path"&&tT(W,H)?null:Ze}function tT(W,G){let H=ar(W);if(!H)return!1;if(H.program.nodes.some((fe)=>fe.kind==="command"&&fe.nested.length>0))return!1;let J=[];for(let fe of Ts(H.shell)){if(fe.kind==="operator"&&fe.boundary)return!1;if(fe.kind==="redirection")return!1;if(fe.kind==="operator")continue;J.push(lr(fe.text,G))}let oe=er(J);if(oe.length===0)return!1;let ie=Sn(oe[0]??"").toLowerCase();if(W.invocation.route.kind==="unknown")return H.program.dialect==="powershell"&&(ie==="ls"||ie==="stat");return Qc(ie,oe.slice(1))}function Qc(W,G){if(W==="ls"||W==="stat")return!0;if(W==="test")return G.length===2&&(G[0]==="-e"||G[0]==="-f");if(W==="[")return G.length===3&&(G[0]==="-e"||G[0]==="-f")&&G[2]==="]";if(W==="git")return G[0]==="check-ignore";if(W==="wc")return G.every((H)=>!H.startsWith("-")||GP.test(H));if(Jc.has(W))return nT(W,G);if(W!=="find")return!1;return!G.some((H)=>IP.has(H))}function nT(W,G){let H=G.includes("--")?G.slice(0,G.indexOf("--")):G;if(H.some((ke)=>/^--(?:(?:file|pre)(?:=|$)|json|format)/.test(ke)||/^-[^-]*f/.test(ke)))return!1;let J=W==="rg"?/[ABCEMTdegjmrt]/:/[ABCDdefm]/,oe=W==="rg"?/[clq]/:/[Lclq]/,ie=(ke)=>/^-[^-]/.test(ke),fe=(ke)=>{let Le=H[ke-1]??"";return/^--[^=]+$/.test(Le)&&!NP.has(Le.slice(2))||ie(Le)&&Le.slice(1).search(J)===Le.length-2},Re=H.findIndex((ke,Le)=>!ke.startsWith("-")&&!fe(Le));return(W==="grep"&&Re>=0?H.slice(0,Re):H).some((ke,Le)=>{if(fe(Le))return!1;if(ke.startsWith("--"))return rh.has(ke.slice(2));return ie(ke)&&oe.test(ke.slice(1).split(J)[0]??"")})}function Kg(W,G,H,J={}){let oe=W.invocation.context.executionCwd,ie=W.invocation.route.kind;if(ie!=="command"&&ie!=="unknown")return W.paths.map((Re)=>({target:Re,cwd:oe}));let fe=ar(W);return[...fe?No(fe.shell,W.store,J,G,oe,H,rT(fe)):[],...ie==="unknown"?W.paths.map((Re)=>({target:Re,cwd:oe})):[]]}function rT(W){return W.program.dialect==="powershell"}function No(W,G,H,J,oe,ie,fe=!1){if(W.status==="structural-limit")throw new b;if(W.status==="unclosed-quote")return[];if(W.status==="invalid")throw new U;let Re=[...W.assignmentFallbacks.map((tt)=>({target:tt,cwd:oe})),...eI(lr(W.source,J),G,H,J,oe,ie)],Te=(tt)=>lr(gT(tt,fe),J),ke=/[<>=]\(/.test(W.source),Le=/\bcoproc\b|\|&/.test(W.source),Xe=[],Ye=[],Ze=(tt)=>({...H,commandHoldsPipe:H.commandHoldsPipe===!0||tt||Le});Ps(W,oe,J,ie,{word:Te,segment:(tt,gt,_t,yt,At,Ot)=>{if(tt.length===0)return null;let Mt=Ze(Ot);if(Mt.commandHoldsPipe)Xe.push(...tt);if(Ye.push(Sn(sh(er(tt))[0]??"").toLowerCase()),Re.push(...Oi(tt,G,ke||yt==="|"||yt==="|&"?{...Mt,segmentMayFeedReader:!0}:Mt,J,gt.cwd,ie,At)),_t!==null)Re.push(...sT(_t,tt,G,Mt,J,gt.cwd,ie));return null},redirection:(tt,gt,_t)=>{if(tt.body!==void 0&&tt.consumer!==void 0){let yt=Ze(_t);Re.push(...ah(tt.consumer,[tt.body],G,yt,J,gt.cwd,ie,(At)=>aT(tt.consumer??[],At,G,yt,J,gt.cwd,ie)))}if(tt.targetOrder==="legacy-segment")return Ul;return Re.push({target:Te(tt.target),cwd:gt.cwd,...tt.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}});let Qe=new Set(Xe.flatMap(ih)),et=ke||/\$\(|`/.test(W.source)||!Ye.every((tt)=>WP.has(tt));return Re.map(({loopVariable:tt,...gt})=>{if(gt.certificateOutputMayFeedReader===!0&&et)return{target:gt.target,cwd:gt.cwd};return tt===void 0||ke||Qe.has(tt)||Qe.has("!")?gt:{...gt,loopVariable:tt}})}function ih(W){return[.../^[A-Za-z_][A-Za-z0-9_]*$/.test(W)?[W]:[],...Array.from(W.matchAll(/\$(?:\{(!)|\{?([A-Za-z_][A-Za-z0-9_]*))/g),(G)=>G[1]??G[2]??"")]}function pa(W,G,H,J,oe,ie,fe=!1){let Re=G.getShellSyntax(W,fe?G.getCommandProgram(W,"powershell"):void 0);if(Re.status==="structural-limit")throw new b;return Re.status==="complete"?No(Re,G,H,J,oe,ie,fe):null}function Oi(W,G,H,J,oe,ie,fe){let Re=(ht)=>({target:ht,cwd:oe}),Te=W.findIndex((ht)=>!AP.has(ht));if(H.skipMetadataOnlySegments===!0&&Te>0)return Oi(W.slice(Te),G,H,J,oe,ie,new Set([...fe??[]].map((ht)=>ht-Te)));let ke=W[1]??"";if(H.skipMetadataOnlySegments===!0&&W[0]==="for"&&W[2]==="in"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(ke))return W.slice(3).flatMap((ht)=>Fn("for",ht)).map((ht)=>({...Re(ht),loopVariable:ke}));if(fe?.size){let ht=W.filter((Wt,Dt)=>!fe.has(Dt));if($g.has(Sn(er(ht)[0]??"").toLowerCase()))return[...W.filter((Wt,Dt)=>fe.has(Dt)).map(Re),...Oi(ht,G,H,J,oe,ie)]}let Le=pT(W).map(Re),Xe=er(W);if(Xe.length===0)return Le;let Ye=Xe[0]??"",Ze=Sn(Ye).toLowerCase(),Qe=Xe.slice(1),et=H.segmentMayFeedReader===!0||H.commandHoldsPipe===!0||H.displayOperandsAreCapturedOutput===!0,tt=et&&LP.has(Ze);if(H.skipMetadataOnlySegments===!0&&!tt&&Qc(Ze,Qe))return Le;let gt=iT(Ye,Ze,Qe);if(gt)return[...Le,...gt.map(Re)];if(th.has(Ze))return H.displayOperandsAreCapturedOutput===!0?[...Le,...lh(W).map(Re)]:Le;if(Ze==="eval")return[...Le,...pa(Qe.join(" "),G,H,J,oe,ie)??Qe.map(Re)];let _t=UP.has(zt(Ye))?Mc(Xe):void 0;if(_t!==void 0)ie.charge("derivedTokens",Xe.length);let yt=_t===void 0?null:pa(_t,G,H,J,oe,ie,!0);if(yt?.length)return[...Le,...yt];if(Ze==="export")return[...Le,...Qe.flatMap((ht)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(ht)?[ht.slice(ht.indexOf("=")+1)]:Fn(Ze,ht)).map(Re)];if(Ze==="git")return[...Le,...yT(Qe).map(Re)];if(Ze==="gh")return[...Le,...Zc(Ze,Qe,FP).map(Re)];if($g.has(Ze))return[...Le,...hT(Qe).map(Re)];if(Jc.has(Ze))return[...Le,...lI(Qe).map(Re)];if(wP.has(Ze))return[...Le,...CT(Qe,G,H,J,oe,ie).map(Re)];if(Ze==="mkdir"||Ze==="touch"){let ht=new Set(W.filter((Dt,Zt)=>fe?.has(Zt))),Wt=H.segmentMayFeedReader!==!0&&!(Ze==="touch"&&Qe.some((Dt)=>/^(?:--r|-[^-]*r)/.test(Dt)));return[...Le,...Qe.flatMap((Dt)=>Fn(Ze,Dt).map((Zt)=>Wt&&!Dt.startsWith("-")&&!ht.has(Dt)?{...Re(Zt),isCreatedPath:!0}:Re(Zt)))]}if(Mn.has(Ze))return[...Le,...Qe.flatMap((ht)=>Fn("awk",ht)).map(Re),...Qe.flatMap((ht)=>vT(ht,G,H,J,oe,ie)),...Qe.flatMap(ET).map(Re)];if(Ze==="curl")return[...Le,...Qe.filter((ht,Wt)=>dh(ht)===null&&ch(Qe[Wt-1])===null).flatMap((ht)=>Fn(Ze,ht)).map(Re),...ST(Qe).map(Re)];if(So(Ze)){let ht=fi.has(Ze)?Dn([Ze,...Qe]):null;if(ht!==null&&ht.command!==null&&ht.commandIndex!==null){let Wt=G.getShellSyntax(ht.command);if(Wt.status==="structural-limit")throw new b;if(Wt.status==="complete")return[...Le,...No(Wt,G,H,J,oe,ie),...Qe.slice(ht.commandIndex).filter((Dt)=>!Dt.startsWith("-")).map(Re)]}return[...Le,...bT(Ze,Qe,G,H,J,oe,ie)]}let At=(ht,Wt)=>new RegExp(`^--?${ht}=`).test(Qe[Wt]??"")||new RegExp(`^--?${ht}$`).test(Qe[Wt-1]??""),Ot=oT(Xe),Mt=Ze==="openssl"&&Qe[0]==="x509",Lt=et?{certificateOutputMayFeedReader:!0}:{};return[...Le,...Qe.flatMap((ht,Wt)=>Fn(Ze,ht).map((Dt)=>Ot&&At("(?:cert|key)-file",Wt)?{...Re(Dt),isCreatedPath:!0,...Lt}:Mt&&At("in",Wt)?{...Re(Dt),isCertificateInput:!0,...Lt}:Re(Dt)))]}function sh(W){return Sn(W[0]??"").toLowerCase()==="timeout"?W.slice(2):W}function oT(W){let G=sh(W);return Sn(G[0]??"").toLowerCase()==="tailscale"&&G[1]==="cert"}function iT(W,G,H){let J=ua(G,H);if(J===null||H[J]!=="explain")return null;let oe=[W,...H.slice(0,J)],ie=H.slice(J+1);for(let fe=0;fe<ie.length;fe++){let Re=ie[fe];if(Re==="--json"||Re==="--help"||Re==="-h")continue;if(Re==="--cwd"){let Te=ie[fe+1];if(Te&&!Te.startsWith("--"))oe.push(Te);fe++;continue}return oe}return oe}function sT(W,G,H,J,oe,ie,fe){if(uT(G,H,J,oe,ie,fe)){let Re=er(W),Te=Qc(Sn(Re[0]??"").toLowerCase(),Re.slice(1))?Re.slice(1).filter((ke)=>!ke.startsWith("-")):[];return[...lh(W),...Te].map((ke)=>({target:ke,cwd:ie}))}return ah(G,lT(W),H,J,oe,ie,fe,()=>[])}function aT(W,G,H,J,oe,ie,fe){let Re=er(W);if(!So(Sn(Re[0]??"").toLowerCase()))return[];return pa(G,H,J,oe,ie,fe)??[{target:G,cwd:ie}]}function ah(W,G,H,J,oe,ie,fe,Re){let Te=mT(W);if(Te===null)return G.flatMap(Re);return G.flatMap((ke)=>fi.has(Te)?No(H.getShellSyntax(ke),H,J,oe,ie,fe):ga(Te,ke,H,J,oe,ie,fe))}function lh(W){let G=er(W);if(G.length===0)return[];let H=Sn(G[0]??"").toLowerCase();if(!th.has(H))return[];let J=G[G[1]==="--"?2:1];if(H==="printf"&&J!==void 0&&!J.startsWith("-")&&!J.replaceAll("%%","").includes("%"))return[ed(J.replaceAll("%%","%"))];return G.slice(1)}function lT(W){let G=er(W);if(G.length===0)return[];let H=Sn(G[0]??"").toLowerCase(),J=G.slice(1);if(H==="echo"){let oe=J.findIndex((ie)=>!/^-[neE]+$/.test(ie));return[(oe===-1?[]:J.slice(oe)).join(" ")]}if(H==="printf")return cT(J);return[]}function cT(W){let G=W[0];if(G===void 0)return[];let H=(G.match(/%%|%[bqs]/g)??[]).filter((oe)=>oe!=="%%").length;if(H===0||W.length===1)return[ed(G)];let J=W.slice(1);return Array.from({length:Math.ceil(J.length/H)},(oe,ie)=>dT(G,J.slice(ie*H,(ie+1)*H)))}function dT(W,G){let H=0;return ed(W.replace(/%%|%[bqs]/g,(J)=>{if(J==="%%")return"%";let oe=G[H]??"";return H++,oe}))}function ed(W){return W.replace(/\\n/g,`
|
|
43
|
+
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function uT(W,G,H,J,oe,ie){let fe=er(W);if(fe.length===0||Sn(fe[0]??"").toLowerCase()!=="xargs")return!1;let Re=Zr(fe),Te=fe.slice(Re.childStart);if(Te.length===0)return!1;if(Re.replacementToken==="")return!1;let ke=Re.replacementToken,Le=ke===null?[...Te,Kc]:Te.map((Xe)=>Xe.split(ke).join(Kc));return Oi(Le,G,H,J,oe,ie).some((Xe)=>Xe.target.includes(Kc))}function mT(W){let G=er(W);if(G.length===0)return null;let H=Sn(G[0]??"").toLowerCase();if(!So(H))return null;return fT(H,G.slice(1))?H:null}function fT(W,G){let H=td(W);for(let J=0;J<G.length;J++){let oe=G[J];if(oe===void 0)break;if(Xc.has(oe)||uh(W,oe)||/^--(?:eval|exec)=/.test(oe))return!1;if(oe==="-")return!0;if(oe.startsWith("-")){if(H==="python"&&oe==="-m")return!1;if(eT.get(H)?.has(oe))J++;continue}return!1}return!0}function td(W){return/^python\d/.test(W)?"python":W}function pT(W){let G=[];for(let H of W){if(hh(H))continue;let J=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(H);if(J===null)break;if(J[1]!==void 0&&J[1]!=="")G.push(J[1])}return G}var qg=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function gT(W,G){if(!G||!qg.test(W))return W;return`~${W.replace(qg,"").replace(/\\/g,"/")}`}function Fn(W,G){if(G==="--")return[];let H=[],J=G.indexOf("=");if(J>0&&J<G.length-1&&!G.slice(0,J).includes("?"))H.push(G.slice(J+1));if(G.startsWith("-"))return H;if(W==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(G))return H;if(W==="zip"&&/\.zip$/i.test(G))return H;return H.push(G),H}function hT(W){let G=-1,H=!1;for(let J=0;J<W.length;J++){let oe=W[J]??"";if(!H&&oe==="--"){H=!0;continue}if(H||!/^-(?:[A-Za-z]|-)/.test(oe)){if(G===-1)G=J;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(oe)){J+=2;continue}if(oe==="--indent"||oe==="-L"){J++;continue}if(oe.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(oe)||/^--(?:slurp|raw-output0?|join-output|compact-output|color-output|monochrome-output|ascii-output|unbuffered|sort-keys|raw-input|null-input|binary|tab|seq|stream|stream-errors|exit-status|args|jsonargs|help|version|build-configuration)$/.test(oe))continue;return W.flatMap((ie)=>Fn("jq",ie))}return W.flatMap((J,oe)=>oe===G?[]:Fn("jq",J))}function yT(W){let G=[];for(let H=0;H<W.length;H++){let J=W[H]??"";if(J==="--"||!J.startsWith("-"))return[...G,...zP.has(J)?Zc("git",W.slice(H).map((ie)=>/^-[aeinopqsv]+m$/.test(ie)?"-m":ie),$P):Zc("git",W.slice(H),BP)];if(G.push(...Fn("git",J)),!_n.has(J))continue;let oe=W[H+1];if(oe===void 0)break;G.push(...J==="-c"&&oe.includes("=")?[oe.slice(oe.indexOf("=")+1)]:Fn("git",oe)),H++}return G}function Zc(W,G,H){let J=[];for(let oe=0;oe<G.length;oe++){let ie=G[oe]??"";if(ie==="--")return[...J,...G.slice(oe).flatMap((fe)=>Fn(W,fe))];if(H.has(ie)){oe++;continue}if(ie.includes("=")&&H.has(ie.slice(0,ie.indexOf("="))))continue;J.push(...Fn(W,ie))}return J}function ST(W){return W.flatMap((G,H)=>{let J=dh(G);if(J!==null)return Yg(J.flag,J.value);let oe=ch(W[H-1]);return oe===null?[]:Yg(oe,G)})}function Yg(W,G){if(W==="-F"||W==="--form"){let H=G.indexOf("="),J=H===-1?G:G.slice(H+1);if(!J.startsWith("@")&&!J.startsWith("<"))return[];return qc(J.slice(1).split(";")[0]??"")}if(W==="--data-urlencode"){let H=G.indexOf("@"),J=G.indexOf("=");if(H===-1||J!==-1&&J<H)return[];return qc(G.slice(H+1))}return G.startsWith("@")?qc(G.slice(1)):[]}function ch(W){if(W===void 0)return null;if(nh.has(W))return W;return/^-[A-Za-z]+[dF]$/.test(W)?`-${W.slice(-1)}`:null}function dh(W){let G=W.slice(0,2);if(W.length>2&&(G==="-d"||G==="-F"))return{flag:G,value:W.slice(2)};let H=W.indexOf("=");if(H===-1)return null;let J=W.slice(0,H);return nh.has(J)?{flag:J,value:W.slice(H+1)}:null}function qc(W){return W===""||W==="-"?[]:[W]}function CT(W,G,H,J,oe,ie){let fe=W.findIndex((Te)=>Te.startsWith("-")||Te==="("||Te==="!"||Te===";"),Re=[...W.slice(0,fe===-1?W.length:fe),...W.flatMap((Te,ke)=>Te==="-files0-from"&&W[ke+1]!==void 0?[W[ke+1]??""]:[])];for(let Te=0;Te<W.length;Te++){if(!PP.has(W[Te]??""))continue;let ke=W.slice(Te+1),Le=ke.findIndex((Ze)=>TP.has(Ze)),Xe=Le===-1?ke:ke.slice(0,Le),Ye=Oi(Xe,G,H,J,oe,ie).map((Ze)=>Ze.target);if(Re.push(...Ye.filter((Ze)=>Ze!=="{}")),!Ye.includes("{}"))continue;Re.push(...W.slice(0,Te).flatMap((Ze,Qe,et)=>{if(!kP.has(Ze))return[];let tt=et[Qe+1];return tt===void 0?[]:[tt,tt.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return Re}function bT(W,G,H,J,oe,ie,fe){let Re=[];for(let Te=0;Te<G.length;Te++){let ke=G[Te];if(ke===void 0)break;if(Xc.has(ke)||uh(W,ke)){let Xe=G[Te+1];if(Xe!==void 0)Re.push(...ga(W,Xe,H,J,oe,ie,fe)),Te++;continue}let Le=/^--(?:eval|exec)=(.*)$/.exec(ke);if(Le!==null&&Le[1]!==void 0){Re.push(...ga(W,Le[1],H,J,oe,ie,fe));continue}if(!ke.startsWith("-"))Re.push({target:ke,cwd:ie})}return Re}function uh(W,G){if(!G.startsWith("-")||G.startsWith("--")||G.length<=2)return!1;return DP.get(G[G.length-1]??"")?.has(td(W))??!1}function vT(W,G,H,J,oe,ie){if(!W.includes("system"))return[];return rc(W)?.commands.flatMap((fe)=>No(G.getShellSyntax(fe),G,H,J,oe,ie))??[]}function ET(W){return Array.from(W.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((G)=>G[1]).filter((G)=>G!==void 0&&G!=="")}function RT(W){let G=Array.from(W.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((H)=>H[2]).filter((H)=>H!==void 0&&H!=="");return[...G,...G.flatMap(rd),...W.match(Yc)??[]]}function ga(W,G,H,J,oe,ie,fe){let Re=(ht)=>({target:ht,cwd:ie}),Te=VT(W),ke=qT(G,Te);if(ke.kind==="unmaskable")return RT(G).map(Re);let Le=ke.masked.match(Hg)!==null||ke.literals.some((ht)=>jg.test(ke.masked.slice(0,ht.start))),Xe=ke.masked.match(JP)!==null||ke.literals.some((ht)=>QP.test(ke.masked.slice(0,ht.start))),Ye=J.inlineLiteralsPresumedData===!0&&!fi.has(W),Ze=Ye&&(Te==="python"||Te==="javascript"),Qe=Ye&&!(QT(ke.masked)||Le||Xe)?[]:ke.literals,et=Ye?Array.from(ke.masked.matchAll(Hg),(ht)=>{let Wt=ht.index+ht[0].length;return{start:Wt,end:bs(ke.masked,Wt)}}):[],tt=!Ye||et.some((ht)=>Gl(ke.masked,ht.start)&&!kT(ke,ht.start))?ke.literals:ke.literals.filter((ht)=>jg.test(ke.masked.slice(0,ht.start))||et.some((Wt)=>ht.start>=Wt.start&&ht.start<Wt.end)),gt=new Set(Le?tt:[]),_t=Ze&&Qe.length>0&&!AT(ke.masked,Te==="python"?"#":"//"),yt=_t?OT(ke.masked):[],At=_t?Array.from(ke.masked.matchAll(/[A-Za-z_$][\w$]*/g),(ht)=>({name:ht[0],index:ht.index})):[],Ot=TT(At),Mt=!PT(ke.masked,At),Lt=At.filter((ht)=>!Zg(ke.masked,{start:ht.index,text:ht.name,tokenStart:ht.index,tokenEnd:ht.index+ht.name.length},yt,Ot,Mt)).reduce((ht,Wt)=>{let Dt=ht.get(Wt.name)??[];return Dt.push(Wt.index),ht.set(Wt.name,Dt)},new Map);return[...Qe.filter((ht)=>ht.text!=="").map((ht)=>{if(!_t||gt.has(ht))return Re(ht.text);if(Zg(ke.masked,ht,yt,Ot,Mt)||MT(ke.masked,ht,yt,Lt))return{...Re(ht.text),literalRole:"data"};return UT(ke,ht,yt)?{...Re(ht.text),literalRole:"write"}:Re(ht.text)}),...Qe.flatMap((ht)=>rd(ht.text)).map(Re),...Ye?[]:ke.literals.flatMap((ht)=>ht.text.match(Yc)??[]).map(Re),...Le?tt.flatMap((ht)=>pa(ht.text,H,{...J,commandHoldsPipe:!0},oe,ie,fe)??[Re(ht.text)]):[],...Xe?ke.literals.flatMap((ht)=>ga(W,ht.text.replace(/\\(.)/g,(Wt,Dt)=>Dt==="n"?`
|
|
44
|
+
`:Dt),H,J,oe,ie,fe)):[],...Ze?[]:(ke.masked.match(Yc)??[]).map(Re),...Ye?(G.match(/\$\{[^}]*\}|\$[A-Za-z_]\w*/g)??[]).map(Re):[]]}var nd={"(":")","[":"]","{":"}"},mh="and|elif|else|if|in|is|not|of|or|return|while|yield",_T=new RegExp(`(?:^|[^\\w$])(?:${mh})$`),xT=new RegExp(`(?:\\*|\\.\\.\\.)\\s*[([{]|\\.\\s*(?:${mh})\\s*\\(|/\\*`),wT=/^(?:exec|spawn)|^(?:popen|system|subprocess)$/;function AT(W,G){return xT.test(W)||W.split(`
|
|
45
|
+
`).some((H)=>{let J=H.indexOf(G);return J>=0&&/[()[\]{}]/.test(H.slice(J))})}function PT(W,G){return LT.test(W)||G.some((H)=>{let J=NT.get(H.name),oe=H.index+H.name.length;return J!==void 0&&!J.test(W.slice(oe,oe+40))})}function TT(W){return W.some((G)=>ph(G.name).some((H)=>wT.test(H)))}var IT=new Set(["cmd","powershell","pwsh"]);function kT(W,G){let H=eo(W.masked,G),J=nd[W.masked[H]??""];if(J===void 0||J==="}")return!1;let oe=W.masked.indexOf(J,H+1),ie=W.masked.slice(H+1,oe);return oe!==-1&&/^\s*,[\w\s,]*$/.test(ie)&&/^[,)]/.test(W.masked.slice(eo(W.masked,oe+1)))&&!W.literals.some((fe)=>fe.tokenStart>H&&fe.tokenStart<oe&&(Xc.has(fe.text)||So(Sn(fe.text).toLowerCase())||IT.has(Sn(fe.text).toLowerCase().replace(/\.exe$/,""))))}function OT(W){let G=[];return W.split("").map((H,J)=>{let oe=G.at(-1)??-1;if(H in nd)G.push(J);if(H===")"||H==="]"||H==="}")G.pop();return oe})}function Zg(W,G,H,J,oe){let ie=H[G.tokenStart]??-1,fe=W[ie]??"",Re=Do(W,G.tokenStart),Te=eo(W,G.tokenEnd);if(/(?:^|[^\w$])in$|[=!]=$/.test(W.slice(Math.max(0,Re-3),Re+1)))return!0;if(/^(?:(?:not\s+)?in(?![\w$])|[=!]=)/.test(W.slice(Te,Te+8)))return!0;if(J&&(fe==="["||fe==="("))return!1;let ke=W[Re],Le=W[Te];if(fe==="{"&&ke===":")return HT(W,Re);let Xe=(ke===fe||ke===",")&&(Le===","||Le===nd[fe]||fe==="{"&&Le===":");if(fe!=="(")return Xe&&fe!=="";return Xe&&(oe&&DT.test(W.slice(Math.max(0,ie-20),ie))||(ke===","||Le===",")&&jT(W,ie))}function MT(W,G,H,J){let oe=Math.max(0,G.tokenStart-80),ie=`${oe===0?`
|
|
46
|
+
`:""}${W.slice(oe,G.tokenStart)}`,fe=WT.exec(ie)?.[1],Re=W[H[G.tokenStart]??-1];if(fe===void 0||Re==="("||Re==="[")return!1;let Te=eo(W,G.tokenEnd)+1;if(!/^\s*(?:[;\n]|$)/.test(W.slice(G.tokenEnd,Te)))return!1;let ke=G.tokenStart-ie.length+ie.lastIndexOf(fe);return(J.get(fe)??[]).every((Le)=>Le===ke)}var DT=/(?:^|[^\w$.])(?:print|console\s*\.\s*log)\s*$/,NT=new Map([["print",/^\s*\(/],["console",/^\s*\.\s*[\w$]+\s*\(/]]),LT=/(?:^|[^\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*$/,GT=/(?:^|[^\w$.])(?:pathlib\s*\.\s*)?Path\s*$/,FT=/^\s*\.\s*write_(?:text|bytes)\s*\(/,zT=/(?:^|[^\w$.])open\s*$/,$T=/^[bt]*[awx][abtwx]*$/,BT=/(?:^|[^\w$])(?:writeFile|writeFileSync|appendFile|appendFileSync|Bun\s*\.\s*write)\s*$/;function UT(W,G,H){let J=H[G.tokenStart]??-1;if(W.masked[J]!=="(")return!1;let oe=Do(W.masked,G.tokenStart),ie=eo(W.masked,G.tokenEnd),fe=W.masked[ie],Re=W.masked.slice(Math.max(0,J-40),J);if(GT.test(Re))return(oe===J||W.masked[oe]===",")&&(fe===","||fe===")")&&!W.literals.some((ke)=>ke.tokenStart>J&&ke.tokenStart<G.tokenStart)&&FT.test(W.masked.slice(bs(W.masked,J+1)+1));if(oe!==J||fe!==",")return!1;if(BT.test(Re))return!0;if(!zT.test(Re))return!1;let Te=W.literals.find((ke)=>/^,\s*(?:mode\s*=\s*)?$/.test(W.masked.slice(ie,ke.tokenStart)));return Te!==void 0&&$T.test(Te.text)&&/^[,)]/.test(W.masked.slice(eo(W.masked,Te.tokenEnd)))}function HT(W,G){let H=Do(W,G),J=/[\w$]*$/.exec(W.slice(Math.max(0,H-63),H+1))?.[0]??"",oe=W[Do(W,H+1-J.length)];return oe==="{"||oe===","}function jT(W,G){let H=Do(W,G),J=W.slice(Math.max(0,H-7),H+1);return!/[\w$)\]]$/.test(J)||_T.test(J)}function VT(W){let G=td(W);if(G==="python")return"python";if(G==="osascript")return"opaque";return G==="node"||G==="bun"||G==="deno"?"javascript":"simple"}var KT={python:"#",javascript:"/"};function qT(W,G){if(G==="opaque")return{kind:"unmaskable"};let H={masked:W.split(""),literals:[]};return fh(W,0,G,H,!1)===null?{kind:"unmaskable"}:{kind:"masked",masked:H.masked.join(""),literals:H.literals}}function fh(W,G,H,J,oe){let ie=0;for(let fe=G;fe<W.length;fe++){let Re=W[fe]??"";if(oe&&Re==="}"&&ie===0)return fe;if(oe&&Re===KT[H])return null;if(Re==="{")ie++;if(Re==="}")ie--;if(H==="simple"&&(Re==="`"||Re==="%"||Re==="<")){if(ZP.test(W.slice(fe)))return null}let Te=Re==="'"||Re==='"'||H==="javascript"&&Re==="`"?Re:null;if(Te===null)continue;if(Te==="`"&&JT(W,fe))return null;let ke=H==="python"?ZT(W,fe):"",Le=H==="python"&&W.startsWith(Te.repeat(3),fe)?Te.repeat(3):Te,Xe=fe+Le.length,Ye=Te==="`"||/[fF]/.test(ke),Ze=fe-ke.length,Qe=Ye?YT(W,Ze,Xe,Le,H,J):XT(W,Xe,Le);if(Qe===null)return null;if(!Ye){let et=W.slice(Xe,Qe);if(H==="simple"&&Te==='"'&&XP.test(et))return null;J.literals.push({start:Xe,text:et,tokenStart:Ze,tokenEnd:Qe+Le.length}),J.masked.fill(" ",Xe,Qe)}J.masked.fill(" ",fe,Xe),J.masked.fill(" ",Qe,Qe+Le.length),fe=Qe+Le.length-1}return oe?null:W.length}function YT(W,G,H,J,oe,ie){let fe=oe==="python"?"{":"${",Re=J==="`"||J.length===3,Te="";for(let ke=H;ke<W.length;ke++){let Le=W[ke]??"";if(W.startsWith(J,ke))return ie.literals.push({start:H,text:Te,tokenStart:G,tokenEnd:ke+J.length}),ke;if(!Re&&(Le===`
|
|
47
|
+
`||Le==="\r"))return null;let Xe=oe==="python"&&(Le==="{"||Le==="}")&&W[ke+1]===Le;if(!Xe&&W.startsWith(fe,ke)){let Qe=fh(W,ke+fe.length,oe,ie,!0);if(Qe===null)return null;Te+=`${fe}}`,ie.masked.fill(" ",ke,ke+fe.length),ie.masked[Qe]=" ",ke=Qe;continue}let Ze=Le==="\\"&&!(oe==="python"&&W[ke+1]==="{")||Xe?2:1;Te+=W.slice(ke,ke+Ze),ie.masked.fill(" ",ke,ke+Ze),ke+=Ze-1}return null}function ZT(W,G){return YP.exec(W.slice(Math.max(0,G-3),G))?.[1]??""}function XT(W,G,H){let J=H.length===3;for(let oe=G;oe<W.length;oe++){let ie=W[oe];if(ie==="\\"){oe++;continue}if(!J&&(ie===`
|
|
48
|
+
`||ie==="\r"))return null;if(W.startsWith(H,oe))return oe}return null}function JT(W,G){for(let H=G-1;H>=0;H--){let J=W[H];if(!J||/\s/.test(J))continue;return/[\w$\])]/.test(J)}return!1}function QT(W){for(let G of W.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let H=G[0],J=G.index;if(OP.has(H.toLowerCase()))return!0;let oe=ph(H);if(!oe.some((ie)=>MP.has(ie)))continue;if(oe.length>1)return!0;if(W[Do(W,J)]===".")return!0;if(W[eo(W,J+H.length)]==="(")return!0}return!1}function ph(W){return W.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((G)=>G.toLowerCase())}function Do(W,G){for(let H=G-1;H>=0;H--)if(!/\s/.test(W[H]??""))return H;return-1}function eo(W,G){for(let H=G;H<W.length;H++)if(!/\s/.test(W[H]??""))return H;return W.length}function eI(W,G,H,J,oe,ie){return iI(W).flatMap((fe)=>{let Re=G.getShellSyntax(fe);if(Re.status==="invalid")return[];return[...No(Re,G,{...H,displayOperandsAreCapturedOutput:!0},J,oe,ie),...tI(Re,J)?nI(Re,J).map((Te)=>({target:Te,cwd:oe})):[]]})}function tI(W,G){let H=Ts(W);for(let J=0;J<H.length;J++){let oe=H[J];if(oe?.kind!=="word"||Sn(lr(oe.text,G)).toLowerCase()!=="base64")continue;for(let ie=J+1;ie<H.length;ie++){let fe=H[ie];if(fe?.kind==="operator")break;if(fe?.kind!=="word")continue;let Re=lr(fe.text,G);if(Re==="--decode"||!Re.startsWith("--")&&Re.startsWith("-")&&/[dD]/.test(Re))return!0}}return!1}function nI(W,G){return Ts(W).flatMap((H)=>H.kind==="word"?[lr(H.text,G)]:H.kind==="redirection"&&H.target?[lr(H.target,G)]:[]).flatMap(rd)}function rd(W){let G=oI(W);if(G===null)return[];let H=Buffer.from(G,"base64").toString("utf8");if(H===""||rI(H))return[];return Buffer.from(H,"utf8").toString("base64").replace(/=+$/g,"")===G.replace(/=+$/g,"")?[H]:[]}function rI(W){return Array.from(W).some((G)=>{let H=G.charCodeAt(0);return H<32||H===127})}function oI(W){if(W.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(W))return null;if(/=/.test(W.replace(/=+$/g,"")))return null;let G=W.replace(/=+$/g,"");if(G.length%4===1)return null;return`${G.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-G.length%4)%4)}`}function iI(W){let G=[],H={inSingle:!1,inDouble:!1,escaped:!1};for(let J=0;J<W.length;J++){let oe=W[J];if(!oe)break;if(Ko(oe,H))continue;if(gh(W,J,H)){let ie=sI(W,J+1);if(ie!==null)G.push(ie.body),J=ie.endIndex;continue}if(!H.inSingle&&oe==="`"){let ie=aI(W,J);if(ie!==null)G.push(ie.body),J=ie.endIndex}}return G}function sI(W,G){let H={inSingle:!1,inDouble:!1,escaped:!1},J=1;for(let oe=G+1;oe<W.length;oe++){let ie=W[oe];if(!ie)break;if(Ko(ie,H))continue;if(gh(W,oe,H)){J++,oe++;continue}if(!H.inSingle&&!H.inDouble&&ie===")"){if(J--,J===0)return{body:W.slice(G+1,oe),endIndex:oe}}}return null}function aI(W,G){let H=!1;for(let J=G+1;J<W.length;J++){let oe=W[J];if(!oe)break;if(H){H=!1;continue}if(oe==="\\"){H=!0;continue}if(oe==="`")return{body:W.slice(G+1,J),endIndex:J}}return null}function gh(W,G,H){return!H.inSingle&&W[G]==="$"&&W[G+1]==="("&&W[G+2]!=="("}function lI(W){let G=[],H=[],J=!1,oe=!1,ie=!1;for(let Te=0;Te<W.length;Te++){let ke=W[Te];if(ke===void 0)break;if(!ie&&ke==="--"){ie=!0;continue}if(ie){H.push(ke);continue}let Le=/^--([^=]+)(?:=(.*))?$/.exec(ke);if(Le!==null){let Xe=Le[1]??"",Ye=Le[2];if(Xe===HP)oe=!0;if(VP.has(Xe))J=!0;if(Ye!==void 0){if(Xe===Ug)G.push(Ye);continue}if(qP.has(Xe)){let Ze=W[Te+1];if(Xe===Ug&&Ze!==void 0)G.push(Ze);Te++}continue}if(ke.startsWith("-")&&ke.length>1){let Xe=ke.slice(1),Ye="",Ze="";for(let et=0;et<Xe.length;et++){let tt=Xe[et]??"";if(jP.has(tt))J=!0;if(KP.has(tt)){Ye=tt,Ze=Xe.slice(et+1);break}}if(Ye==="")continue;if(Ze.length>0){if(Ye===Bg)G.push(Ze);continue}let Qe=W[Te+1];if(Ye===Bg&&Qe!==void 0)G.push(Qe);Te++;continue}H.push(ke)}let Re=!J&&!oe?H.slice(1):H;return[...G,...Re]}function er(W){let G=W.findIndex((H)=>!hh(H)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(H));return G===-1?[]:W.slice(G)}function hh(W){return W==="env"||W==="command"||W==="builtin"||W==="sudo"}var cI=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),dI=".env.",uI=new Set([".env.example",".env.sample",".env.template",".env.tpl",".env.defaults"]),mI=[".env.example.",".env.sample."];function fI(W){let G;try{G=new URL(W.trim())}catch{return!1}return G.protocol!=="file:"&&G.host!==""}function pI(W){return W.length>0&&!/\s/.test(W)}function ha(W,G,H,J){let oe=yh(W,G,H,J);return oe!==""&&H.paths.entryKind(oe)!=="missing"}function yh(W,G,H,J){try{return Mi(W,G,H,J)}catch(oe){if(oe instanceof s)throw oe;return""}}var gI=/[?&][^?&=/]+=/,hI=new Set(["node_modules","__pycache__"]),yI=[["vendor","bundle"],["vendor","cache"]];function SI(W,G,H,J,oe){if(fI(W))return null;let ie=En(W,G,J,oe);if(!ie)return null;let fe=Kt(ie.split("/").pop()??""),Re=Kt(ie),Te=()=>pI(fe)||ha(W,G,J,oe),ke=Kt(_I(W,G,J,oe));for(let Ye of Qa){let Ze=`~/${Ye.suffixParts.join("/")}`;if((Jg(Re,Ze)||Jg(ke,Ze))&&mr(Ye.id,H))return Ye.id}if(uI.has(fe)||mI.some((Ye)=>fe.startsWith(Ye)))return null;let Le=CI(ie,G,H,J,oe);if(Le)return Le;if(cI.has(fe))return null;for(let Ye of Ja)if(fe===Ye.basename&&mr(Ye.id,H))return Ye.id;if(fe.startsWith(dI)&&mr(Zi.id,H)&&Te())return Zi.id;for(let Ye of el)if(fe.length>Ye.prefix.length&&fe.startsWith(Ye.prefix)){let Ze=fe.slice(Ye.prefix.length)[0];if((Ze==="-"||Ze==="_")&&mr(Ye.id,H)&&Te())return Ye.id}for(let Ye of tl)if(fe.length>Ye.prefix.length&&fe.startsWith(Ye.prefix)){if(fe.slice(Ye.prefix.length)===Ye.suffix&&mr(Ye.id,H))return Ye.id}if(EI(Re))return null;if(!fe.includes(".")&&qo.pattern.test(fe)&&mr(qo.id,H))return qo.id;if(gI.test(W)&&!ha(W,G,J,oe))return null;let Xe=RI(fe,H);if(Xe)return Xe;return null}function CI(W,G,H,J,oe){return Xi.find((ie)=>{if(!mr(ie.id,H))return!1;switch(ie.id){case"secret.cli.claude-code":return Ut(W,Yt(J.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",G,J,oe),[".credentials.json"]);case"secret.cli.claude-code.config":{let fe=Kt(W).split("/");return Ut(W,Yt(J.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",G,J,oe),["settings.json","settings.local.json"])||ki(W,"~/.claude.json",G,J,oe)||fe.at(-1)==="settings.local.json"&&fe.at(-2)===".claude"||fe.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Ut(W,En("~/.gemini/config",G,J,oe),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let fe=Yt(J.env.get("CODEX_HOME"),"~/.codex",G,J,oe);return Ut(W,fe,["auth.json",".credentials.json"])||Mo(W,fe,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let fe=Yt(J.env.get("CODEX_HOME"),"~/.codex",G,J,oe),Re=Kt(W).split("/").at(-1)??"";return Ut(W,fe,["config.toml"])||Re.endsWith(".config.toml")&&Ut(W,fe,[Re])}case"secret.cli.gemini":return Ut(W,sn(Yt(J.env.get("GEMINI_CLI_HOME"),"~",G,J,oe),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let fe=Kt(W).split("/"),Re=J.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),Te=J.env.get("ProgramData")?[sn(Yt(J.env.get("ProgramData"),"",G,J,oe),"gemini-cli")]:[];return Ut(W,sn(Yt(J.env.get("GEMINI_CLI_HOME"),"~",G,J,oe),".gemini"),["settings.json","google_accounts.json"])||fe.at(-1)==="settings.json"&&fe.at(-2)===".gemini"||(Re?.trim()?ki(W,Re,G,J,oe):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...Te].some((ke)=>Ut(W,En(ke,G,J,oe),["settings.json"]))}case"secret.cli.copilot-cli":{let fe=Yt(J.env.get("COPILOT_HOME"),"~/.copilot",G,J,oe);return Ut(W,fe,["config.json"])||Mo(W,fe,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Ut(W,Yt(J.env.get("COPILOT_HOME"),"~/.copilot",G,J,oe),["mcp-config.json"]);case"secret.cli.kimi-code":{let fe=Yt(J.env.get("KIMI_CODE_HOME"),"~/.kimi-code",G,J,oe),Re=Yt(J.env.get("KIMI_SHARE_DIR"),"~/.kimi",G,J,oe);return Ut(W,fe,["server.token"])||Mo(W,fe,["credentials"])||Mo(W,Re,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let fe=["config.toml","mcp.json"],Re=Kt(W).split("/");return Re.at(-1)==="mcp.json"&&Re.at(-2)===".kimi-code"||Ut(W,Yt(J.env.get("KIMI_CODE_HOME"),"~/.kimi-code",G,J,oe),fe)||Ut(W,Yt(J.env.get("KIMI_SHARE_DIR"),"~/.kimi",G,J,oe),[...fe,"config.json","config.json.bak"])}case"secret.cli.opencode":{let fe=sn(Yt(J.env.get("XDG_DATA_HOME"),"~/.local/share",G,J,oe),"opencode"),Re=Kt(W).split("/").at(-1)??"",Te=J.env.get("OPENCODE_DB")?.trim(),ke=Te&&Te!==":memory:"?[Te,`${Te}-wal`,`${Te}-shm`]:[];return Ut(W,fe,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Re)&&Ut(W,fe,[Re])||ke.some((Le)=>ki(W,Le,G,J,oe))}case"secret.cli.opencode.config":{let fe=sn(Yt(J.env.get("XDG_CONFIG_HOME"),"~/.config",G,J,oe),"opencode"),Re=J.env.get("ProgramData")?[sn(Yt(J.env.get("ProgramData"),"",G,J,oe),"opencode")]:[],Te=["opencode.json","opencode.jsonc"],ke=J.env.get("OPENCODE_CONFIG");return Te.includes(Kt(W).split("/").at(-1)??"")||Ut(W,fe,["config.json"])||(ke?.trim()?ki(W,ke,G,J,oe):!1)||["/Library/Application Support/opencode","/etc/opencode",...Re].some((Le)=>Ut(W,En(Le,G,J,oe),Te))}case"secret.cli.pi":return Ut(W,Yt(J.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",G,J,oe),["auth.json"]);case"secret.cli.pi.config":return Ut(W,Yt(J.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",G,J,oe),["models.json"]);case"secret.cli.amp":{let fe=En("~",G,J,oe);return[sn(Yt(J.env.get("XDG_DATA_HOME"),"~/.local/share",G,J,oe),"amp"),sn(fe,".local","share","amp")].some((Te)=>Ut(W,Te,["secrets.json"]))||Mo(W,sn(fe,".amp"),["oauth"])}case"secret.cli.amp.config":{let fe=["settings.json","settings.jsonc"],Re=[sn(Yt(J.env.get("XDG_CONFIG_HOME"),"~/.config",G,J,oe),"amp"),sn(En("~",G,J,oe),".config","amp")],Te=Kt(W).split("/"),ke=J.env.get("AMP_SETTINGS_FILE");return Re.some((Le)=>Ut(W,Le,fe))||Te.at(-2)===".amp"&&fe.includes(Te.at(-1)??"")||(ke?.trim()?ki(W,ke,G,J,oe):!1)}case"secret.cli.cursor":{let fe=sn(Yt(J.env.get("XDG_CONFIG_HOME"),"~/.config",G,J,oe),"cursor"),Re=sn(Yt(J.env.get("CURSOR_DATA_DIR"),"~/.cursor",G,J,oe),"projects");return Ut(W,En("~/.cursor",G,J,oe),["auth.json"])||Ut(W,fe,["auth.json"])||Kt(W).split("/").at(-1)==="mcp-auth.json"&&to(Kt(W),Kt(Re))}case"secret.cli.cursor.config":{let fe=Kt(W).split("/");return fe.at(-1)==="mcp.json"&&fe.at(-2)===".cursor"}case"secret.cli.grok-build":return Ut(W,Yt(J.env.get("GROK_HOME"),"~/.grok",G,J,oe),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let fe=Kt(W).split("/");return fe.at(-1)==="config.toml"&&fe.at(-2)===".grok"||Ut(W,Yt(J.env.get("GROK_HOME"),"~/.grok",G,J,oe),["config.toml","managed_config.toml","requirements.toml"])||Ut(W,En("/etc/grok",G,J,oe),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return Ut(W,En("~/.factory",G,J,oe),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let fe=Kt(W).split("/");return fe.at(-1)==="mcp.json"&&fe.at(-2)===".factory"||Ut(W,En("~/.factory",G,J,oe),["settings.json","hooks.json"])}case"secret.cli.devin":return[Yt(J.env.get("XDG_DATA_HOME"),"~/.local/share",G,J,oe),En("~/.local/share",G,J,oe)].some((fe)=>Ut(W,sn(fe,"devin"),["credentials.toml"])||Mo(W,sn(fe,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[Yt(J.env.get("XDG_CONFIG_HOME"),"~/.config",G,J,oe),En("~/.config",G,J,oe)].some((fe)=>Ut(W,sn(fe,"devin"),["config.json"]));default:return!1}})?.id??null}var Xg=new WeakMap;function Yt(W,G,H,J,oe){let ie=Xg.get(oe)??new Map;Xg.set(oe,ie);let fe=`${H}\x00${W??""}\x00${G}`,Re=ie.get(fe);if(Re!==void 0)return Re;let Te=En(W?.trim()?W:G,H,J,oe);return ie.set(fe,Te),Te}function Ut(W,G,H){return H.some((J)=>Sh(W,sn(G,J)))}function Mo(W,G,H){return H.some((J)=>to(Kt(W),Kt(sn(G,J))))}function ki(W,G,H,J,oe){return Sh(W,En(G,H,J,oe))}function Sh(W,G){return Kt(W)===Kt(G)}function sn(W,...G){return Kn([W,...G].filter(Boolean).join("/"))}function bI(W,G,H,J,oe,ie){if(H.length===0)return!1;let fe=Kt(Mi(W,G,oe,ie));return H.some((Re)=>to(fe,Kt(Mi(Re,J,oe,ie))))}function vI(W,G,H,J,oe,ie){if(H.length===0)return!1;let fe=Kt(Mi(W,G,oe,ie));if(!fe)return!1;let Re=oe.env.get("HOME")??oe.home,Te=Re?Kn(Bt(pn(Re),oe.paths,ie)):"",ke=Kt(Te),Le=oe.env.get("CC_SAFETY_NET_HOME"),Xe=Kt(Le?Kn(Bt(ya(pn(Le)),oe.paths,ie)):Te&&Kn(Bt(`${Te}/.cc-safety-net`,oe.paths,ie)));if(Xe&&to(fe,Xe))return!1;return H.some((Ye)=>{let Ze=sl(Ye);if(Ze&&Qg.basename(fe)!==Kt(Ze.name))return!1;let Qe=Kt(Mi(Ze?.root??Ye,J,oe,ie));if(!Qe)return!1;if(ke&&(ke===Qe||ke.startsWith(Qe.endsWith("/")?Qe:`${Qe}/`)))return!1;return to(fe,Qe)&&!(Ze&&fe===Qe)})}function EI(W){let G=W.split("/");return G.some((H)=>hI.has(H))||yI.some(([H,J])=>G.some((oe,ie)=>oe===H&&G[ie+1]===J))}function RI(W,G){let H=W.lastIndexOf("."),J=H>0&&H<W.length-1?W.slice(H+1):"";if(J==="")return null;for(let oe of nl)if(J===oe.extension&&mr(oe.id,G))return oe.id;for(let oe of rl)if(oe.pattern.test(J)&&mr(oe.id,G))return oe.id;return null}function Kt(W){return W.toLowerCase()}function mr(W,G){return!G?.disabledRules?.includes(W)}function En(W,G,H,J){let{home:oe,normalized:ie}=od(W,H,J);if(!ie)return"";if(!oe)return ie;let fe=id(ie,oe),Re=fa(fe)?fe:Kn(ya(G,fe)),Te=Kn(Bt(Re,H.paths,J));if(!to(Te,oe)){if(fa(fe))return Te;return Te===Re?ie:Te}let ke=Te.slice(oe.length);return ke?`~${ke}`:"~"}function Jg(W,G){return W===G||W.startsWith(`${G}/`)}function _I(W,G,H,J){let{home:oe,normalized:ie}=od(W,H,J);if(!ie||!oe)return"";let fe=id(ie,oe),Re=Qg.normalize(fa(fe)?fe:Kn(ya(G,fe))),Te=Kn(pn(H.env.get("HOME")??H.home)),ke=(Ye)=>process.platform==="win32"?Ye.toLowerCase():Ye,Le=[oe,Te].find((Ye)=>Ye!==""&&to(ke(Re),ke(Ye)));if(Le===void 0)return"";let Xe=Re.slice(Le.length);return Xe?`~${Xe}`:"~"}function Mi(W,G,H,J){let{home:oe,normalized:ie}=od(W,H,J);if(!ie)return"";let fe=oe?id(ie,oe):ie;return Kn(Bt(fa(fe)?fe:ya(G,fe),H.paths,J))}function od(W,G,H){let J=G.env.get("HOME")??G.home,oe=J?Kn(Bt(pn(J),G.paths,H)):"",ie=Kn(pn(xI(lr(W,G))));return{home:oe,normalized:ie}}function xI(W){if(!W.trim().toLowerCase().startsWith("file:"))return W;try{return xP(W)}catch{return W}}function id(W,G){if(W==="~")return G;if(W.startsWith("~/"))return sn(G,W.slice(2));return W}function wI(W){if(process.platform==="win32")return!0;return _P.parse(W).root.length>1}function Kn(W){let G=W.trim(),H=(G.includes("\\")&&wI(G)?G.replace(/\\/g,"/"):G).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(H==="/")return H;return H.replace(/\/+$/g,"")}function to(W,G){return W===G||W.startsWith(G.endsWith("/")?G:`${G}/`)}function Sn(W){return W.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??W}class f extends Error{stage;evaluation;name="GuardEvaluationError";constructor(W,G,H){super(`CC Safety Net ${W} dependency failed`,{cause:H});this.stage=W;this.evaluation=G}}var AI={findPolicyMutation:Fg,findGitMetadataMutation:uf,resolveGitMetadata:kI,loadPolicySnapshot:R,findSensitiveTarget:oh,analyzeCommand:Og,getModes:P},PI=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/,TI=["workdir","cwd","working_directory"];function j(W,G){let H={...AI,...G.dependencies},J=DI(W),oe=()=>Ar("config-load",J,()=>H.loadPolicySnapshot(G.environment,{...G.policyOptions,cwd:W.context.configCwd})),ie=W.route.kind==="unknown"&&J?oe():void 0,fe=ie?.policy.commandTools.find((Dt)=>Dt.name===W.toolName),Re=fe&&J?II(W,J,fe.cwd,G.environment.paths):W;if("decision"in Re)return Re;let Te=Re,ke=Te===W?{}:{promotedInvocation:Te},Le=Di(Te)?Te.command:J,Xe=Ar("policy-protection",Le,()=>af(Te)),Ye=Co(Xe,"input-candidate"),Ze=Co(Xe,"declared-command");if(Di(Te)&&Te.command?.trim()&&Ze?.program.status==="limited")return{stage:"command-analysis",...ke,decision:{kind:"deny",reason:qn,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:Te.command,segment:Te.command}}};if(Ye?.program.status==="limited")return{stage:"command-validation",...ke,decision:{kind:"deny",reason:sf,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let Qe=In(),et=Ar("policy-protection",Le,()=>H.resolveGitMetadata([Te.context.executionCwd,Te.context.configCwd],G.environment)),tt=Ar("policy-protection",Le,()=>H.findPolicyMutation(Xe,G.environment,Qe));if(tt){let Dt=Le??tt.target;return{stage:"policy-protection",...ke,decision:{kind:"deny",reason:Je,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:Dt,segment:tt.target}}}}let gt=Ar("policy-protection",Le,()=>Ng(Xe,G.environment,Qe));if(gt){let Dt=Le??gt.target;return{stage:"policy-protection",...ke,decision:{kind:"deny",reason:Ke,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:Dt,segment:gt.target}}}}let _t=Ar("policy-protection",Le,()=>H.findGitMetadataMutation(Xe,et,G.environment,Qe));if(_t){let Dt=Le??_t.target;return{stage:"policy-protection",...ke,decision:{kind:"deny",reason:v,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:Dt,segment:_t.target}}}}let yt=ie??oe(),At=yt.policy,Ot=H.getModes(At,G.environment.env),Mt={level:Ot.effectiveLevel,...OI(yt),...ke},Lt=At.secretProtection.enabled===!1?null:Ar("secret-protection",Le,()=>H.findSensitiveTarget(Xe,At.secretProtection,G.environment,Qe,{strict:Di(Te)||Ye?.program.dialect==="powershell"?Ot.strict:void 0}));if(Lt){let Dt=Le??Lt.target;return{stage:"secret-protection",...Mt,decision:{kind:"deny",reason:eh,intent:"hard_stop",ruleId:Lt.ruleId,evidence:{command:Dt,segment:Lt.target}}}}if(!Di(Te))return{stage:"non-command",...Mt,decision:{kind:"allow"}};if(!Te.command||Te.command.trim()==="")return{...Sa("command-validation",Le),...Mt};let ht=Ar("command-analysis",Le,()=>Mg(()=>H.analyzeCommand(Te.command,{cwd:Te.context.executionCwd,shell:Te.route.shell,policySnapshot:yt,environment:G.environment,protectedGitMetadata:et,effectiveCapabilities:Ot.capabilities,worktreeMode:Ot.worktreeMode,budget:Qe,...G.trace?{trace:G.trace}:{}},MI(Xe),Xe.store),Te.command,G.trace)),Wt=Te.route.shell==="auto"&&Xe.store.readsAutoAsPowerShell()?()=>{let Dt=G.trace?.branch(),Zt={...j({...Te,route:{kind:"command",shell:"posix"}},{...G,...Dt?{trace:Dt.trace}:{},dependencies:{...G.dependencies,loadPolicySnapshot:()=>yt,resolveGitMetadata:()=>et}}),...ke};return{decision:Zt.decision,withItsTrace:()=>(Dt?.adopt(),Zt)}}:void 0;if(ht.decision){let Dt=!Ot.strict&&(ht.decision.ruleId==="raw-text.dangerous-command"||ht.decision.reason===gi&&!PI.test(ht.decision.evidence?.segment??"")&&Nn(Te.command)===null),Zt=Dt?Wt?.():void 0;if(Zt?.decision.kind==="deny"&&!Zt.decision.unverifiedByStandardMode)return Zt.withItsTrace();return{stage:"command-analysis",...Mt,..."errorCode"in ht?{errorCode:ht.errorCode}:{},decision:Dt?{...ht.decision,unverifiedByStandardMode:!0}:ht.decision}}return Wt?.().withItsTrace()??{stage:"command-analysis",...Mt,decision:{kind:"allow"}}}function II(W,G,H,J){let oe=[...new Set((H?[H]:TI).flatMap((Te)=>{let ke=Object.getOwnPropertyDescriptor(W.input,Te);return ke?[ke.value]:[]}))],ie=oe.filter((Te)=>typeof Te==="string"&&Te.trim()!=="");if(oe.length>1||ie.length!==oe.length)return Sa("command-validation",G);let fe=ie[0],Re=fe===void 0?W.context.configCwd:Ud(fe,W.context.configCwd,J);if(!Re){let Te=_({directory:"requested",problem:"unusable",cwd:fe??""});return{stage:"command-validation",decision:{kind:"deny",reason:Te.reason,ruleId:Te.ruleId,intent:Te.intent,evidence:{command:G,segment:G}}}}return l(W.toolName,W.input,{kind:"command",shell:"auto"},{configCwd:W.context.configCwd,executionCwd:Re},G)}function kI(W,G){let H=[...new Set(W.filter((J)=>typeof J==="string"&&J!==""))].flatMap((J)=>G.gitMetadata(J)??[]);if(H.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(H.flatMap((J)=>J.entries))]),markerFiles:Object.freeze([...new Set(H.flatMap((J)=>J.markerFiles))]),directories:Object.freeze([...new Set(H.flatMap((J)=>J.directories))]),hooksDirectories:Object.freeze([...new Set(H.flatMap((J)=>J.hooksDirectories))])})}function OI(W){if(W.state==="ready")return{};return{configFallback:{reason:W.reason}}}function MI(W){return Co(W,"declared-command")?.program}function DI(W){try{return se(W.input)}catch(G){let H=Di(W)?W.command:void 0;throw new f("policy-protection",Sa("policy-protection",G instanceof m?void 0:H,G),G)}}function Ar(W,G,H){try{return H()}catch(J){throw new f(W,Sa(W,J instanceof m?void 0:G,J),J)}}function Sa(W,G,H){let J=H instanceof U?{reason:Zn,ruleId:"analysis.strict-unparseable"}:H instanceof s||H instanceof b?{reason:va,ruleId:"analysis.limit"}:{reason:Go,ruleId:"analysis.failed-closed"};return{stage:W,decision:{kind:"deny",...J,intent:"stop_and_explain",...G?{evidence:{command:G,segment:G}}:{}}}}function Di(W){return W.route.kind==="command"}
|
|
49
|
+
export{a,s,Y,Me,nt,T,bt,rt,_e,L,_,Z,xt,c,n,ot,Pe,P,S,me,vt,m,Ie,x,se,ge,St,it,st,l,Fe,o,w,i,ae,r,g,he,B,wt,Ct,p,ye,be,Et,M,X,ce,C,kt,I,h,Ae,z,u,O,Q,at,ct,F,E,D,xe,ve,$e,le,d,e,Ue,Oe,je,Se,lt,ut,ue,De,de,Ge,ee,V,He,we,q,dt,K,te,ne,pe,pt,ft,k,A,We,Be,mt,ze,R,Ve,Ne,qe,y,t,re,Ce,b,U,v,N,Rt,Ee,Ke,Je,f,j};
|