cc-safety-net 2.4.2 → 2.4.4

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.
@@ -1,45 +0,0 @@
1
- var zs="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Nn="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",ee="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var Gs={errorCode:"path-canonicalization-limit",reason:"CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry."},io={errorCode:"structural-shell-syntax-limit",reason:"Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry."},a=Object.freeze({realpathAttempts:{cap:16384,...Gs},processedCandidateBytes:{cap:4194304,...Gs},pathEnvironmentExpansion:{cap:64,...Gs},recursionDepth:{cap:10,errorCode:"structural-shell-syntax-limit",reason:"Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry."},derivedTokens:{cap:16384,...io},trackedHeredocFiles:{cap:64,...io},controlFlowStates:{cap:64,...io},wrapperPeelIterations:{cap:20,...io},derivedCommandShape:io});class s extends Error{kind;name="AnalysisLimit";constructor(O){super(a[O].reason);this.kind=O}}function fn(){let O=new Map;return{counters:O,resolvedPaths:new Map,charge(D,B=1){let X=(O.get(D)??0)+B;if(O.set(D,X),X>a[D].cap)throw new s(D)}}}import{lstatSync as Sg,realpathSync as Cg,statSync as vg}from"node:fs";import{homedir as Eg,tmpdir as Rg}from"node:os";import{statSync as hg}from"node:fs";import{join as yg}from"node:path";import{basename as yc,dirname as Fp,isAbsolute as Gp,join as zp,normalize as Bp,resolve as gc}from"node:path";var $p=256,ri=new Set(["CC_SAFETY_NET_HOME","CLAUDE_CONFIG_DIR","CODEX_HOME","COPILOT_HOME","GEMINI_CLI_HOME","GROK_HOME","HOME","KIMI_CODE_HOME","KIMI_SHARE_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","ProgramData","TMPDIR","XDG_CONFIG_HOME","XDG_DATA_HOME"]);function mn(O,D=process.platform){if(D!=="win32")return O;return O.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function Jn(O,D=process.platform){if(D!=="win32")return!1;return(O[0]==="/"||O[0]==="\\")&&(O[1]==="/"||O[1]==="\\")}function Hs(O,D){return Bs(O,0,D)}function Bs(O,D,B){let X="",Q=0;while(Q<O.length){if(O[Q]!=="$"){X+=O[Q],Q++;continue}if(O[Q+1]==="{"){let je=$s(O,Q+2),at=Up(O,Q,D);if(at===null){if(ri.has(je))throw new s("pathEnvironmentExpansion");X+=O.slice(Q);break}let lt=O.slice(Q,at+1);X+=Hp(lt,D,B),Q=at+1;continue}let he=$s(O,Q+1);if(!he){X+="$",Q++;continue}X+=Us(he,B)??`$${he}`,Q+=he.length+1}return X}function Up(O,D,B){let X=1;for(let Q=D+2;Q<O.length;Q++){if(O[Q]==="\\"){Q++;continue}if(O[Q]==="$"&&O[Q+1]==="{"){if(X++,B+X>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");Q++;continue}if(O[Q]!=="}")continue;if(X--,X===0)return Q}return null}function Hp(O,D,B){let X=O.slice(2,-1),Q=$s(X,0);if(!Q)return O;let he=X.slice(Q.length);if(!he)return Us(Q,B)??O;let je=[":-",":+",":=",":?","-","+","=","?"].find((ct)=>he.startsWith(ct));if(!je){if(ri.has(Q))throw new s("pathEnvironmentExpansion");return O}if(!ri.has(Q))return O;if(je.endsWith("="))throw new s("pathEnvironmentExpansion");let at=Us(Q,B),lt=je.startsWith(":")?at!==null&&at!=="":at!==null;if(je.endsWith("?")&&!lt)throw new s("pathEnvironmentExpansion");if(je.endsWith("-")||je.endsWith("?"))return lt?at??"":Bs(he.slice(je.length),D+1,B);return lt?Bs(he.slice(je.length),D+1,B):""}function $s(O,D){if(!/[A-Za-z_]/.test(O[D]??""))return"";let B=D+1;while(/[A-Za-z0-9_]/.test(O[B]??""))B++;return O.slice(D,B)}function Us(O,D){if(!ri.has(O))return null;if(O==="HOME")return D.env.get("HOME")??D.home;return D.env.get(O)??null}function Lt(O,D,B){if(!O)return O;let X=B.resolvedPaths.get(O);if(X!==void 0)return X;let Q=[],he=O;while(!0){bc(B,he);let je=D.realpath(he);if(je!==null)return hc(B,O,je,Q);let at=Fp(he);if(at===he||Q.length>=$p)return hc(B,O,he,Q);Q.push(yc(he)),he=at}}function hc(O,D,B,X){let Q=X.length===0?B:zp(B,...X.reverse());return O.resolvedPaths.set(D,Q),Q}function jp(O,D,B){let X=B.resolvedPaths.get(O);if(X!==void 0)return X;bc(B,O);let Q=D.realpath(O);if(Q!==null)B.resolvedPaths.set(O,Q);return Q}function bc(O,D){O.charge("realpathAttempts"),O.charge("processedCandidateBytes",Buffer.byteLength(D))}function en(O,D,B,X){let Q=Cc(O,D,B);if(!Q)return"";return Lt(Q,B.paths,X).replace(/\\/g,"/")}function Sc(O,D,B,X,Q){let he=Cc(O,D,B);if(!he)return null;if(Q(yc(he)))return Lt(he,B.paths,X).replace(/\\/g,"/");let je=jp(he,B.paths,X);return je===null?null:je.replace(/\\/g,"/")}function Cc(O,D,B){let X=B.home,Q=Hs(O.trim(),B).replace(/\\/g,"/");if(!Q)return"";let he=Q==="~"?X:Q.startsWith("~/")?gc(X,Q.slice(2)):Q,je=mn(he);return Bp(Gp(je)?je:gc(D,je))}import{spawnSync as Vp}from"node:child_process";import{existsSync as ao,lstatSync as Kp,readFileSync as lo,realpathSync as Dr,statSync as so}from"node:fs";import{dirname as js,isAbsolute as Vs,join as Nr,resolve as oi}from"node:path";var qp=["/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"],Yp=5000;function Ec(O,D=fg(),B=Yp){let X=Zp(O),Q=X===null?null:Xp(X);if(X===null||Q===null)return null;let he=ug(X,Q,D,B);return he===null?null:{recursiveSubmodules:he}}function Zp(O){try{let D=Dr(oi(O));return so(D).isDirectory()?D:null}catch{return null}}function Xp(O){let D=cg(O);if(!D)return null;try{let B=Kp(D);if(B.isSymbolicLink()||!B.isFile())return null;let X=Ks(D);if(!X?.commonDir)return null;if(!eg(X.gitDir,D))return null;return tg(X.gitDir,js(D))?{gitDir:X.gitDir,commonDir:X.commonDir}:null}catch{return null}}function Ks(O){try{let D=Jp(O);if(!D)return null;let B=Dr(Vs(D)?D:oi(js(O),D));if(!so(B).isDirectory())return null;return{gitDir:B,commonDir:Qp(B)}}catch{return null}}function Jp(O){let D=lo(O,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!D.startsWith("gitdir:"))return null;return D.slice(7).trim()||null}function Qp(O){try{let D=lo(Nr(O,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!D)return null;let B=Dr(Vs(D)?D:oi(O,D));return so(B).isDirectory()?B:null}catch{return null}}function eg(O,D){let B=ng(O);return B===null?!1:Rc(O,B,D)}function tg(O,D){let B=rg(O);return B===null?!0:Rc(O,B,D)}function ng(O){let D=Nr(O,"gitdir");if(!ao(D))return null;let B=lo(D,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return B===""?null:B}function rg(O){let D=Nr(O,"config.worktree");return ao(D)?ig(D):null}function Rc(O,D,B){try{return og(Vs(D)?D:oi(O,D),B)}catch{return!1}}function og(O,D){try{let B=so(O),X=so(D);if(B.ino!==0&&X.ino!==0&&B.dev===X.dev&&B.ino===X.ino)return!0}catch{}return vc(Dr.native(O))===vc(Dr.native(D))}function vc(O){let D=O.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),B=D.length>1&&D.endsWith("/")?D.slice(0,-1):D;return process.platform==="win32"?B.toLowerCase():B}function ig(O){let D=lo(O,"utf-8"),B=!1,X=null;for(let Q of D.split(/\r?\n/)){let he=Q.trim();if(he===""||he.startsWith("#")||he.startsWith(";"))continue;if(he.startsWith("[")){B=/^\[core\]$/i.test(he);continue}if(!B)continue;let je=he.match(/^worktree\s*=\s*(.*)$/i);if(je)X=sg(je[1]??"")}return X}function sg(O){let D=O.trim();if(!D.startsWith('"')||!D.endsWith('"'))return D;return lg(D.slice(1,-1))}var ag={"\\":"\\",'"':'"',n:`
2
- `,t:"\t",b:"\b"};function lg(O){return O.replace(/\\(.?)/gs,(D,B)=>B===""?D:ag[B]??D)}function cg(O){try{return qs(Dr(O))}catch{return null}}function qs(O){let D=O;while(!0){let B=Nr(D,".git");if(ao(B))return B;let X=js(D);if(X===D)return null;D=X}}function ug(O,D,B,X){if(dg(D))return!0;if(B===null)return!0;let Q=Vp(B,["config","--get","submodule.recurse"],{cwd:O,encoding:"utf8",env:mg(process.env),stdio:["ignore","pipe","ignore"],timeout:X});if(Q.error!==void 0||Q.status!==0&&Q.status!==1)return null;return Q.status===0&&xc(Q.stdout.trim())}function dg(O){return[Nr(O.commonDir,"config"),Nr(O.gitDir,"config.worktree")].filter((D)=>ao(D)).some((D)=>pg(D))}function fg(){return qp.find((O)=>ao(O))??null}function co(O){return O==="GIT_CONFIG_COUNT"||O==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(O)}function mg(O){return Object.fromEntries(Object.entries(O).filter(([D])=>!co(D)))}function pg(O){let D;try{D=lo(O,"utf-8")}catch{return!0}let B="",X=!1;for(let Q of D.split(/\r?\n/)){let he=Q.trim();if(he===""||he.startsWith("#")||he.startsWith(";"))continue;let je=he.match(/^\[([^\]]+)\]$/);if(je){B=je[1]?.trim().toLowerCase()??"";continue}let at=he.indexOf("="),lt=(at===-1?he:he.slice(0,at)).trim().toLowerCase(),ct=at===-1?"true":he.slice(at+1).trim();if(gg(B)&&lt==="path")return!0;if(B==="submodule"&&lt==="recurse")X=xc(ct)}return X}function gg(O){return O==="include"||O.startsWith("includeif ")}function xc(O){let D=O.toLowerCase();return D!=="false"&&D!=="no"&&D!=="off"&&D!=="0"}function _c(O,D){if(O==="")return null;let B=fn(),X=qs(en(O,O,D,B)),Q=X?bg(X,O,D,B):null;if(!Q)return null;return Object.freeze({entries:Object.freeze([Q.entry]),markerFiles:Object.freeze(Q.markerFile?[Q.markerFile]:[]),directories:Object.freeze(Q.directories),hooksDirectories:Object.freeze(Q.hooksDirectories)})}function bg(O,D,B,X){try{let Q=en(O,D,B,X),he=hg(O),je=he.isFile()?Q:null,at=he.isFile()?Ks(O):null,lt=(he.isDirectory()?[Q]:[at?.gitDir,at?.commonDir]).flatMap((ft)=>ft?[Lr(en(ft,D,B,X))]:[]),ct=[...new Set(he.isDirectory()?[Lr(O.replace(/\\/g,"/")),...lt]:lt)];return{entry:Lr(Q),markerFile:je?Lr(je):null,directories:ct,hooksDirectories:[...new Set(ct.flatMap((ft)=>{let dt=Lr(yg(ft,"hooks").replace(/\\/g,"/"));return[dt,Lr(en(dt,D,B,X))]}))]}}catch{return null}}function Lr(O){return process.platform==="win32"?O.toLowerCase():O}var xg={realpath:(O)=>{try{return Cg(O)}catch{return null}},entryKind:(O)=>{let D=Sg(O,{throwIfNoEntry:!1});if(!D)return"missing";return D.isSymbolicLink()?"symlink":"present"},isDirectory:(O)=>{try{return vg(O).isDirectory()}catch{return!1}}};function l(){return _g({env:new Map(Object.entries(process.env).flatMap(([O,D])=>D===void 0?[]:[[O,D]])),home:mn(process.env.HOME||Eg()),tmpdir:Rg(),paths:xg})}function _g(O,D={}){let B=new Map,X=new Map,Q={...O,gitMetadata:(he)=>wc(B,he,()=>_c(he,Q)),worktreeFacts:(he)=>wc(X,he,()=>Ec(he)),...D};return Q}function wc(O,D,B){let X=O.get(D);if(X!==void 0)return X;let Q=B();return O.set(D,Q),Q}import{accessSync as Qg,constants as Uc,statSync as eh}from"node:fs";import{isAbsolute as jc,relative as th,resolve as nh,sep as rh}from"node:path";var wg=[/\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 z(O){return ke(O.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 ke(O){return wg.reduce((D,B)=>D.replace(B,"<redacted>"),O.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 Ge(O){return Pc(O).reduceRight((D,B)=>`${D.slice(0,B.valueStart)}<redacted>${D.slice(B.valueEnd)}`,O)}function k(O){return ke(Ge(O))}function Ze(O){return Pc(O).map((D)=>O.slice(D.valueStart,D.valueEnd))}function He(O){return/[A-Za-z_][A-Za-z0-9_]*=/.test(O)}function Pc(O){return[...O.matchAll(/[A-Za-z_][A-Za-z0-9_]*=/g)].flatMap((D)=>{let B=O[D.index-1];if(D.index>0&&B&&!/[\s"'([{]/.test(B))return[];let X=D.index+D[0].length;if(X>=O.length)return[];return[{valueStart:X,valueEnd:Pg(O,X)}]})}function Pg(O,D){if(O.startsWith("$(",D))return Ag(O,D);let B=O[D];if(B==='"'||B==="'"){for(let Q=D+1;Q<O.length;Q++){if(B==='"'&&O[Q]==="\\"){Q++;continue}if(O[Q]===B)return Q+1}return O.length}let X=D;while(X<O.length&&!/\s/.test(O[X]??""))X++;return X}function Ag(O,D){let B=0,X;for(let Q=D;Q<O.length;Q++){let he=O[Q];if(X){if(X==='"'&&he==="\\"){Q++;continue}if(he===X)X=void 0;continue}if(he==='"'||he==="'"){X=he;continue}if(he==="$"&&O[Q+1]==="("){B++,Q++;continue}if(he!==")")continue;if(B--,B===0)return Q+1}return O.length}var Tg={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 Ig(O){let D=O.maxLen??200,B=O.redact??((Q)=>Q),X=(Q)=>Q.length>D?`${Q.slice(0,D)}...`:Q;return["BLOCKED by CC Safety Net",`Reason: ${B(O.reason)}`,O.ruleId?`Rule: ${O.ruleId}`:void 0,O.toolName?`Tool: ${O.toolName}`:void 0,O.command?`Command: ${X(B(O.command))}`:void 0,O.segment&&O.segment!==O.command?`Segment: ${X(B(O.segment))}`:void 0,O.configWarning?`Config warning: ${B(O.configWarning)}`:void 0,Tg[O.intent??"manual_only"]].filter((Q)=>Q!==void 0).join(`
3
-
4
- `)}function ye(O,D){if(O.decision.kind!=="deny")return;let B=D.includeEvidence?O.decision.evidence:void 0;return{reason:O.decision.reason,ruleId:O.decision.ruleId,intent:O.decision.intent,command:B?.command,segment:B?.segment,toolName:D.toolName,...O.configFallback?{configWarning:O.configFallback.reason}:{}}}function A(O={}){return{reason:ee,intent:"stop_and_explain",command:O.command,segment:O.segment??O.command,toolName:O.toolName}}function ve(O){return Ig({...O,redact:z})}function Xe(O){return z(O instanceof Error?O.message:String(O))}import{types as kg}from"node:util";var Og=new Set(["applypatch","patch"]),Mg=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),Dg=new Set(["grep","grepsearch","rg"]),Ng=new Set(["find","findbyname","glob"]),Lg=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),Wg=new Set(["command","diff","input","patch","patchtext"]),Ac=new TextEncoder,Fg=new TextDecoder,Gg=/\s/,zg=64;class f extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var uo=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Mc(O){return O.replace(/[-_\s]/g,"").toLowerCase()}function si(O){return Lg.has(Mc(O))}function ae(O){let D=Mc(O);if(Og.has(D))return"patch";if(Dg.has(D))return"grep";if(Ng.has(D))return"glob";if(Mg.has(D))return"path";return"unknown"}function te(O){if(!O||typeof O!=="object")return;zc(O);let D=Object.getOwnPropertyDescriptor(O,"command");if(!D){if("command"in O)Ln();return}if(D.get||D.set)Ln();let B=D.value;return typeof B==="string"&&B!==""?B:void 0}function Dc(O,D){return Nc(O,D,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Nc(O,D,B,X){let Q=Gc(O,B,X);if(!Q)return[];let he=Q.entries.flatMap(([je,at])=>{let lt=Nc(at,D,B,X+1);return typeof at==="string"&&D.has(Lc(je))?[at]:lt});return B.ancestors.delete(Q.object),he}function Lc(O){return O.replace(/-/g,"_").toLowerCase()}function Wc(O){return Fc(O,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap($g)}function Fc(O,D,B,X){let Q=Gc(O,B,X);if(typeof O==="string")return D?[O]:[];if(!Q)return[];let he=Q.entries.flatMap(([je,at])=>Fc(at,Q.array?D:Wg.has(Lc(je)),B,X+1));return B.ancestors.delete(Q.object),he}function Bg(O,D,B){if(D.nodes++,O!==null&&typeof O==="object"&&B>uo.maxDepth||D.nodes>uo.maxNodes)Ln();if(typeof O!=="string")return;let X=Buffer.byteLength(O);if(D.stringBytes+=X,X>uo.maxStringBytes||D.stringBytes>uo.maxAggregateStringBytes)Ln()}function Gc(O,D,B){if(Bg(O,D,B),!O||typeof O!=="object")return null;let X=zc(O);if(D.ancestors.has(O))Ln();let Q=Reflect.ownKeys(O);if(D.keys+=Q.length,D.keys>uo.maxKeys)Ln();let he=Q.flatMap((je)=>{let at=Object.getOwnPropertyDescriptor(O,je);if(!at||at.get||at.set)Ln();return typeof je==="string"&&at.enumerable?[[je,at.value]]:[]});return D.ancestors.add(O),{object:O,array:X,entries:he}}function zc(O){if(kg.isProxy(O))Ln();let D=Array.isArray(O),B=Object.getPrototypeOf(O);if(D&&B!==Array.prototype||!D&&B!==Object.prototype&&B!==null)Ln();return D}function Ln(){throw new f}function $g(O){let D=[],B=O.split(/\r?\n/),X=!1,Q=!1,he=null,je=null,at=()=>{Q=!1,he=null,je=null};for(let lt=0;lt<B.length;lt++){let ct=B[lt]??"";if(ct==="*** Begin Patch"){X=!0,at();continue}if(ct==="*** End Patch"){X=!1,at();continue}if(ct.startsWith("@@")){let ft=Ug(ct);if(Q=!0,he=ft?.oldLines??null,je=ft?.newLines??null,he===0&&je===0)at();continue}if(Q&&he!==null&&je!==null){let ft=ct.startsWith(" ")||ct.startsWith("-")?1:0,dt=ct.startsWith(" ")||ct.startsWith("+")?1:0;if(he=Math.max(0,he-ft),je=Math.max(0,je-dt),he===0&&je===0)at();continue}if(ct.startsWith("*** ")){at(),D.push(...Ys(ct));continue}if(Q)continue;if(ct.startsWith("diff --git ")){D.push(...Ys(ct));continue}if(ct.startsWith("--- ")){let ft=B[lt+1]??"";if(!ft.startsWith("+++ "))continue;D.push(...Xs(ii(ct.slice(4),!0),ii(ft.slice(4),!0))),lt++;continue}if(!X)D.push(...Ys(ct))}return D}function Ug(O){let D=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(O);if(!D)return null;return{oldLines:Number(D[1]??1),newLines:Number(D[2]??1)}}function Ys(O){let D=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(O);if(D?.[1])return Oc(D[1]);let B=/^\*\*\* Move to: (.+)$/.exec(O);if(B?.[1])return Oc(B[1]);if(O.startsWith("diff --git "))return Hg(O.slice(11));let X=/^--- (.+)$/.exec(O);if(X?.[1])return kc(X[1]);let Q=/^\+\+\+ (.+)$/.exec(O);if(Q?.[1])return kc(Q[1]);let he=/^(?:rename|copy) (?:from|to) (.+)$/.exec(O);if(he?.[1])return Xg(he[1]);return[]}function Hg(O){let D=jg(O);if(D.length===2&&D[0]&&D[1])return Xs(D[0],D[1]);let B=Vg(O);return B?Xs(O.slice(B.oldStart,B.oldEnd),O.slice(B.newStart,B.newEnd)):[]}function jg(O){let D=[],B=0;while(B<O.length&&D.length<2){while(dr(O[B]))B++;if(B>=O.length)break;let X=O[B]==='"'||O[B]==="'"?O[B]:void 0;if(!X){let he=B;while(B<O.length&&!dr(O[B]))B++;D.push(O.slice(he,B));continue}let Q=Bc(O,B,X);if(!Q)return[];D.push(Q.value),B=Q.end}while(dr(O[B]))B++;return B===O.length?D:[]}function Vg(O){let D=0;while(D<O.length&&dr(O[D]))D++;let B=O.length;while(B>D&&dr(O[B-1]))B--;let X=0,Q=D;while(Q<B){if(!dr(O[Q])){Q++;continue}let he=Q;while(Q<B&&dr(O[Q]))Q++;if(he===D||Q===B)continue;if(X++,X>zg)Ln();if(Kg(O,D,he,Q,B))return{oldStart:D,oldEnd:he,newStart:Q,newEnd:B}}return null}function Kg(O,D,B,X,Q){if(Zs(O,D,B,X,Q))return!0;let he=Tc(O,"/",D,B),je=Tc(O,"/",X,Q);if(he<=D||je<=X)return!1;if(Zs(O,D,he,X,je))return!1;return Zs(O,he+1,B,je+1,Q)}function Zs(O,D,B,X,Q){if(B-D!==Q-X)return!1;for(let he=0;he<B-D;he++)if(O[D+he]!==O[X+he])return!1;return!0}function Tc(O,D,B,X){for(let Q=B;Q<X;Q++)if(O[Q]===D)return Q;return-1}function dr(O){return O!==void 0&&Gg.test(O)}function Bc(O,D,B){let X=[],Q=D+1;while(Q<O.length){let he=String.fromCodePoint(O.codePointAt(Q)??0);if(he===B)return{value:Fg.decode(Uint8Array.from(X)),end:Q+1};if(he!=="\\"||B==="'"){X.push(...Ac.encode(he)),Q+=he.length;continue}let je=O.slice(Q+1),at=/^[0-7]{1,3}/.exec(je)?.[0];if(at){X.push(Number.parseInt(at,8)),Q+=at.length+1;continue}X.push(...Ac.encode(qg(je[0]??""))),Q+=2}return null}function qg(O){return{a:"\x07",b:"\b",f:"\f",n:`
5
- `,r:"\r",t:"\t",v:"\v"}[O]??O}function Yg(O){return fo(Jg(O))}function Xs(O,D){if(O==="/dev/null")return Ic(D);if(D==="/dev/null")return Ic(O);if(O.startsWith("a/")&&D.startsWith("b/"))return[O.slice(2),D.slice(2)].flatMap(fo);let B=Zg(O,D)??(O===D?$c(O):null);return[O,D,...B?[B]:[]].flatMap(fo)}function Ic(O){let D=$c(O);return[O,...D?[D]:[]].flatMap(fo)}function $c(O){let D=O.indexOf("/");return D>0&&D<O.length-1?O.slice(D+1):null}function Zg(O,D){let B=O.indexOf("/"),X=D.indexOf("/");if(B<1||X<1)return null;if(O.slice(0,B)===D.slice(0,X))return null;let Q=O.slice(B+1);return Q===D.slice(X+1)?Q:null}function kc(O){return Yg(ii(O,!0))}function Xg(O){return fo(ii(O,!1))}function ii(O,D){let B=O.trim(),X=B[0]==='"'||B[0]==="'"?B[0]:void 0;if(X){let Q=Bc(B,0,X);if(Q&&(D||B.slice(Q.end).trim()===""))return Q.value}return D?B.split("\t",1)[0]?.trim()??"":B}function Jg(O){return O.startsWith("a/")||O.startsWith("b/")?O.slice(2):O}function fo(O){return O===""||O==="/dev/null"?[]:[O]}function Oc(O){let D=O.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return D===""||D==="/dev/null"?[]:[D]}function le(O){try{if(!eh(O).isDirectory())return!1;return Qg(O,Uc.R_OK|Uc.X_OK),!0}catch{return!1}}function et(O,D,B){if(Jn(O))return;let X=D.flatMap((he)=>Hc(he,B));if(!X[0])return;let Q=Hc(jc(O)?O:nh(X[0],O),B)[0];if(!Q)return;return X.some((he)=>oh(Q,he))?Q:void 0}function Hc(O,D){let B=D.realpath(O);if(B===null)return[];return D.isDirectory(B)?[B]:[]}function oh(O,D){let B=th(D,O);return B===""||B!==".."&&!B.startsWith(`..${rh}`)&&!jc(B)}var ih=8388608;async function Ue(O){let D=[],B=0;for await(let X of O){let Q=typeof X==="string"?Buffer.from(X,"utf-8"):Buffer.from(X.buffer,X.byteOffset,X.byteLength);if(B+=Q.byteLength,B>ih)throw sh(O),Error("hook input byte limit exceeded");D.push(Q)}return Buffer.concat(D,B).toString("utf-8")}function sh(O){let D=O.destroy??O.cancel;if(!D)return;try{Promise.resolve(D.call(O)).catch(()=>{})}catch{}}function u(O,D,B,X,Q){if(B.kind!=="command")return{toolName:O,input:D,route:B,context:X};return{toolName:O,input:D,route:B,context:X,command:Q}}var Wr=["fail_closed","paranoid_rm","paranoid_interpreters"],ai={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 o={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"}},li=["standard","strict","paranoid"];function ah(O,D){if(!D)return O;return li.indexOf(D)>li.indexOf(O)?D:O}function lh(O){let D=we(o.level,O);if(D===void 0||D==="")return;if(li.includes(D))return D;console.error(`CC Safety Net: ignored invalid ${o.level.name}=${JSON.stringify(D.slice(0,40))}. Use ${li.join(", ")}.`);return}function We(O){if(O===void 0||O==="all")return"all";if(O==="blocked")return"blocked";return"invalid"}function be(O){return We(we(o.auditScope,O))==="all"}function Js(O){if(O.failClosed&&O.paranoidRm&&O.paranoidInterpreters)return"paranoid";if(O.failClosed&&!O.paranoidRm&&!O.paranoidInterpreters)return"strict";if(!O.failClosed&&!O.paranoidRm&&!O.paranoidInterpreters)return"standard";return"custom"}function E(O={},D){let B=O.safety?.level??"standard",X=lh(D),Q=ah(B,X),he=ai[Q],je={failClosed:he.fail_closed,paranoidRm:he.paranoid_rm,paranoidInterpreters:he.paranoid_interpreters},at={failClosed:Q===B?"preset":"environment",paranoidRm:Q===B?"preset":"environment",paranoidInterpreters:Q===B?"preset":"environment"},lt={failClosed:[`policy safety.level=${B}`],paranoidRm:[`policy safety.level=${B}`],paranoidInterpreters:[`policy safety.level=${B}`]};if(Q!==B)lt.failClosed.push(`env ${o.level.name}=${X}`),lt.paranoidRm.push(`env ${o.level.name}=${X}`),lt.paranoidInterpreters.push(`env ${o.level.name}=${X}`);if(O.safety?.overrides?.failClosed!==void 0)je.failClosed=O.safety.overrides.failClosed,at.failClosed="capability_override",lt.failClosed.push("policy safety.overrides.fail_closed");if(O.safety?.overrides?.paranoidRm!==void 0)je.paranoidRm=O.safety.overrides.paranoidRm,at.paranoidRm="capability_override",lt.paranoidRm.push("policy safety.overrides.paranoid_rm");if(O.safety?.overrides?.paranoidInterpreters!==void 0)je.paranoidInterpreters=O.safety.overrides.paranoidInterpreters,at.paranoidInterpreters="capability_override",lt.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(R(o.strict,D))je.failClosed=!0,at.failClosed="environment",lt.failClosed.push(`env ${o.strict.name}`);if(R(o.paranoid,D))je.paranoidRm=!0,je.paranoidInterpreters=!0,at.paranoidRm="environment",at.paranoidInterpreters="environment",lt.paranoidRm.push(`env ${o.paranoid.name}`),lt.paranoidInterpreters.push(`env ${o.paranoid.name}`);if(R(o.paranoidRm,D))je.paranoidRm=!0,at.paranoidRm="environment",lt.paranoidRm.push(`env ${o.paranoidRm.name}`);if(R(o.paranoidInterpreters,D))je.paranoidInterpreters=!0,at.paranoidInterpreters="environment",lt.paranoidInterpreters.push(`env ${o.paranoidInterpreters.name}`);let ct=!!O.worktreeMode||R(o.worktree,D);return{strict:je.failClosed,paranoidRm:je.paranoidRm,paranoidInterpreters:je.paranoidInterpreters,worktreeMode:ct,effectiveLevel:Js(je),capabilities:{fail_closed:{enabled:je.failClosed,source:at.failClosed,sources:lt.failClosed},paranoid_rm:{enabled:je.paranoidRm,source:at.paranoidRm,sources:lt.paranoidRm},paranoid_interpreters:{enabled:je.paranoidInterpreters,source:at.paranoidInterpreters,sources:lt.paranoidInterpreters}}}}function R(O,D){let B=typeof O==="string"?mo(O,D):we(O,D);return B==="1"||B?.toLowerCase()==="true"}function mo(O,D){return D.get(O)}function we(O,D){let B=mo(O.name,D);if(B!==void 0)return B;if(O.legacyName)return mo(O.legacyName,D);return}function Qe(O,D){return mo(O.name,D)!==void 0||!!O.legacyName&&mo(O.legacyName,D)!==void 0}import{dirname as hr}from"node:path";import{closeSync as ch,constants as po,fstatSync as Qs,fsyncSync as uh,lstatSync as Cn,mkdirSync as Vc,openSync as Kc,readdirSync as ta,readFileSync as dh,realpathSync as Fr,renameSync as fh,rmdirSync as qc,statSync as ea,unlinkSync as na,writeFileSync as mh}from"node:fs";import{isAbsolute as Yc,join as fr,normalize as ph,parse as ci,relative as ra,resolve as oa,sep as ui}from"node:path";function Ee(){let O=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${O()}${O()}`}var gh=Symbol("PolicyFilesystemScope"),hh=Symbol("PolicyFilesystemTarget"),Zc=po.O_NOFOLLOW??0;class r extends Error{name="PolicyFilesystemError";constructor(O){super(`Unable to access ${O} filesystem safely.`)}}function w(O,D){return{[gh]:!0,root:oa(O),label:D}}function go(O,D){let B=ph(D);if(D===""||Yc(D)||B===".."||B.startsWith(`..${ui}`))throw new r(O.label);return{[hh]:!0,scope:O,relativePath:B,path:fr(O.root,B)}}function i(O,D){return go(O,ra(O.root,oa(D)))}function ne(O,D="rules policy"){let B=oa(O),X=ci(B).dir;return go(w(X,D),ra(X,B))}function n(O){return Gn(O.scope.label,()=>{if(!Zt(O))return null;let D=Kc(O.path,po.O_RDONLY|Zc);return Jc(D,()=>{let B=Qs(D);if(!B.isFile())throw new r(O.scope.label);let X=dh(D,"utf-8"),Q=Cn(O.path);if(!Q.isFile()||Q.isSymbolicLink()||B.dev!==Q.dev||B.ino!==Q.ino)throw new r(O.scope.label);return Zt(O),X})})}function g(O,D,B=384,X){let Q=`${O.path}.${Ee()}.tmp`;Gn(O.scope.label,()=>{bh(O),Zt(O);let he=Kc(Q,po.O_CREAT|po.O_EXCL|po.O_WRONLY|Zc,B),je=Jc(he,()=>{let at=Qs(he);if(!at.isFile())throw new r(O.scope.label);mh(he,D,"utf-8"),uh(he);let lt=Qs(he);if(!lt.isFile()||lt.dev!==at.dev||lt.ino!==at.ino)throw new r(O.scope.label);return lt});Zt(O),Ch(O,Q,je.dev,je.ino),fh(Q,O.path),X?.(O.path),Zt(O)},()=>vh(Q))}function Xc(O,D){if(O.path===D.path)return!0;return Gn(O.scope.label,()=>{if(!Zt(O)||!Zt(D))return!1;let B=(X)=>fr(Fr(ci(X).dir),ci(X).base);return B(O.path)===B(D.path)})}function ce(O){let D=Gn(O.scope.label,()=>{if(!Zt(O,"directory"))return null;let B=ta(O.path);return Zt(O,"directory"),B});if(!D)return null;return Gn(O.scope.label,()=>{let B=D.map((X)=>{let Q=go(O.scope,fr(O.relativePath,X)),he=Cn(Q.path);if(he.isSymbolicLink()||!he.isFile()&&!he.isDirectory())throw new r(O.scope.label);return di(ia(O.scope),Fr(Q.path),O.scope.label),{name:X,kind:he.isDirectory()?"directory":"file"}});return Zt(O,"directory"),B})}function N(O){Gn(O.scope.label,()=>{if(!Zt(O))return;na(O.path),Zt(O)})}function tt(O){Gn(O.scope.label,()=>{if(!yh(O))return;eu(O),Zt(O,"directory")})}function nt(O){Gn(O.scope.label,()=>{if(!Zt(O,"directory"))return;qc(O.path),Zt(O,"directory")})}function yh(O){return Gn(O.scope.label,()=>{if(!Zt(O,"directory"))return!1;return Qc(O),!0})}function Gn(O,D,B){try{return D()}catch(X){if(B?.(),X instanceof r)throw X;throw new r(O)}}function Jc(O,D){try{return D()}finally{ch(O)}}function Zt(O,D="file"){let B=tu(O.scope);if(!B)return!1;let X=O.relativePath.split(ui);for(let Q of X.keys()){let he=fr(O.scope.root,...X.slice(0,Q+1)),je=Cn(he,{throwIfNoEntry:!1});if(!je)return!1;if(je.isSymbolicLink())throw new r(O.scope.label);if(Q<X.length-1&&!je.isDirectory())throw new r(O.scope.label);if(Q===X.length-1&&(D==="file"?!je.isFile():!je.isDirectory()))throw new r(O.scope.label);di(B,Fr(he),O.scope.label)}return!0}function Qc(O){for(let D of ta(O.path)){let B=go(O.scope,fr(O.relativePath,D)),X=Cn(B.path);if(X.isSymbolicLink()||!X.isDirectory()&&!X.isFile())throw new r(O.scope.label);if(X.isDirectory())Qc(B)}Zt(O,"directory")}function eu(O){for(let D of ta(O.path)){let B=go(O.scope,fr(O.relativePath,D)),X=Cn(B.path);if(X.isSymbolicLink())throw new r(O.scope.label);if(X.isDirectory()){eu(B);continue}if(!X.isFile())throw new r(O.scope.label);na(B.path)}qc(O.path)}function bh(O){Sh(O.scope);let D=ia(O.scope),B=O.relativePath.split(ui).slice(0,-1);for(let X of B.keys()){let Q=fr(O.scope.root,...B.slice(0,X+1));if(!Cn(Q,{throwIfNoEntry:!1}))Vc(Q,{mode:448});let he=Cn(Q);if(!he.isDirectory()||he.isSymbolicLink())throw new r(O.scope.label);di(D,Fr(Q),O.scope.label)}}function Sh(O){if(Cn(O.root,{throwIfNoEntry:!1})){if(!ea(O.root).isDirectory())throw new r(O.label);return}let D=[],B=O.root;while(!Cn(B,{throwIfNoEntry:!1})){D.unshift(B);let X=ci(B).dir;if(X===B)throw new r(O.label);B=X}if(!ea(B).isDirectory())throw new r(O.label);for(let X of D){Vc(X,{mode:448});let Q=Cn(X);if(!Q.isDirectory()||Q.isSymbolicLink())throw new r(O.label)}}function tu(O){if(!Cn(O.root,{throwIfNoEntry:!1}))return null;if(!ea(O.root).isDirectory())throw new r(O.label);return Fr(O.root)}function ia(O){let D=tu(O);if(!D)throw new r(O.label);return D}function Ch(O,D,B,X){let Q=Cn(D);if(!Q.isFile()||Q.isSymbolicLink()||Q.dev!==B||Q.ino!==X)throw new r(O.scope.label);di(ia(O.scope),Fr(D),O.scope.label)}function di(O,D,B){let X=ra(O,D);if(X===".."||X.startsWith(`..${ui}`)||Yc(X))throw new r(B)}function vh(O){try{na(O)}catch{}}import{dirname as mr,isAbsolute as wh,join as gr,relative as Ph,resolve as pr,sep as Ah}from"node:path";var c=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,de="rulebook.json",ue=".cc-safety-net/rules";var nu=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,Eh=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,ru=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,Rh=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),xh="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),rt=new RegExp(`^${Rh}/(${c.source.slice(1,-1)})/${xh}$`);function _h(O){return`.cc-safety-net/rules/${O}/rulebook.json`}function ou(O){if(C(O))try{return T(O),null}catch(D){return D instanceof Error?D.message:String(D)}return c.test(O)?null:`Local rulebook sources must be bare names matching ${c}: ${O}`}function T(O){if(O.startsWith("github:"))throw Error(`Invalid rulebook source: ${O}`);let D=O.match(nu);if(!D?.[1]||!D[2]||!D[3])throw Error(`Invalid GitHub rulebook source: ${O}`);let B=D[3].lastIndexOf("/");if(B<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${O}`);let X=D[3].slice(0,B),Q=D[3].slice(B+1);if(!X||!ru.test(X))throw Error(`GitHub rulebook refs must use valid path segments: ${O}`);if(!Q||!c.test(Q))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${O}`);return{owner:D[1],repo:D[2],ref:X,path:_h(Q),name:Q}}function V(O){return Eh.test(O)}function re(O){return ru.test(O)}function C(O){return nu.test(O)}function ot(O){if(!c.test(O))throw Error(`Local rulebook sources must be bare names matching ${c}: ${O}`)}var iu="rule.json",fi="policy.json",su=".cc-safety-net",Th="rules",Ih="CC_SAFETY_NET_HOME",au="`cc-safety-net rule update`";function kh(O){return pr(O,ue)}function M(O){return gr(kh(O),iu)}function v(O){return gr(pr(O),su,fi)}function Ce(O,D={}){return D.userConfigDir??(D.userConfigPath?mr(D.userConfigPath):gr(Oh(O),Th))}function Oh(O){let D=O.env.get(Ih);return D?pr(mn(D)):gr(O.home,su)}function F(O,D={}){return gr(Ce(O,D),iu)}function d(O,D={}){return gr(mr(Ce(O,D)),fi)}function q(O,D){let B=D.userConfigPath??F(O,D),X=D.projectConfigPath??M(D.cwd),Q=Be(O,D),he=ze(X,D.cwd);return{userConfigPath:B,projectConfigPath:X,userScope:Q,projectScope:he,userConfigTarget:i(Q,B),projectConfigTarget:i(he,X)}}function Be(O,D){let B=D.userConfigPath?mr(mr(pr(D.userConfigPath))):mr(pr(D.userConfigDir??Ce(O,D)));return w(B,"user policy")}function ze(O,D){let B=pr(D),X=pr(O),Q=Ph(B,X);if(Q!==".."&&!Q.startsWith(`..${Ah}`)&&!wh(Q))return w(B,"project policy");return w(mr(mr(X)),"project policy")}function I(O,D){return gr(O,D,de)}var pn=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),S=/^[a-zA-Z][a-zA-Z0-9_-]*$/,P=256,Kt=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),lu=new Set(["python","python3","python2","node","ruby","perl"]),mi=/^python(?:[23](?:\.\d+)*)?$/,vn=new Set(["awk","gawk","nawk","mawk"]),pi=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 cu="Rulebook exceeds CC Safety Net's safe validation limits.",uu="Additional rulebook validation errors were omitted.",_n=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function du(O){if(sa(O.allowed_commands,_n.maxAllowedCommands)||sa(O.rules,_n.maxRules)||sa(O.tests,_n.maxTests))return!1;let{maxAggregateStringCodeUnits:D,maxTotalBlockArgs:B}=_n,X=(Q,he=!1)=>{if(typeof Q!=="string")return!0;if(Q.length>_n.maxStringCodeUnits||he&&Q.length>_n.maxFixtureCommandCodeUnits||Q.length>D)return!1;return D-=Q.length,!0};if(!X(O.name)||!X(O.version)||!X(O.description)||!X(O.author)||!X(O.migrated_from))return!1;if(Array.isArray(O.allowed_commands)){for(let Q of O.allowed_commands)if(!X(Q))return!1}if(Array.isArray(O.rules))for(let Q of O.rules){if(!Q||typeof Q!=="object")continue;let he=Q;if(!X(he.name)||!X(he.command)||!X(he.subcommand)||!X(he.reason)||!X(he.intent))return!1;let je=he.match&&typeof he.match==="object"?he.match:{};for(let at of[he.block_args,je.command_path,je.any_args,je.exclude_args]){if(!Array.isArray(at))continue;if(at.length>_n.maxBlockArgsPerRule||at.length>B)return!1;B-=at.length;for(let lt of at)if(!X(lt))return!1}}if(Array.isArray(O.tests))for(let Q of O.tests){if(!Q||typeof Q!=="object")continue;let he=Q;if(!X(he.command,!0)||!X(he.expect)||!X(he.rule))return!1}return!0}function sa(O,D){return Array.isArray(O)&&O.length>D}var aa=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var pe=64,fe="Rule config exceeds CC Safety Net's safe source limit.";function kt(O){return Tt(O).toLowerCase()}function Tt(O){return O.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??O}function sn(O,D){let B=new Set,X=!1;for(let Q of O){if(Q==="--"){X=!0;continue}if(X)continue;if(Q.startsWith("-")&&!Q.startsWith("--")&&Q.length>1)for(let he=1;he<Q.length;he++){let je=Q[he];if(!je||!/[a-zA-Z]/.test(je))break;let at=`-${je}`;if(B.add(at),D?.shortOptsWithValue?.has(at))break}}return B}var Mh={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},la=new Set(["--init-file","--rcfile"]);function ca(O,D,B,X){let Q=!1,he=0,je=!1,at=!1,lt=!1;for(let ct=1;ct<D.length;ct++){let ft=D[ct];if(ft===void 0)break;if(O==="ksh"&&ft==="o"&&ct+1<D.length){if(X==="argv"){let dt=D.slice(ct+1);if(D[0]==="-"&&(dt==="c"||dt[0]==="-"&&dt.endsWith("c")))je=!0}break}if(O==="ksh"&&ft==="o"&&ct+1===D.length&&(B?.startsWith("-")||B?.startsWith("+")))break;if(O==="zsh"&&ft==="o"&&ct+1<D.length)break;if(X==="startup"&&ft==="i")Q=D[0]==="-";if(X==="argv"&&D[0]==="-"&&ft==="c")je=!0;if(X==="argv"&&ft==="n")lt=D[0]==="-";if(X==="argv"&&ft==="s")at=D[0]==="-";if(!Mh[O]?.includes(ft))continue;if(ct+1===D.length)he++;break}return{interactive:Q,followingValues:he,commandSelected:je,stdinMode:at,syntaxCheck:lt}}function gn(O){let D=Tt(O[0]??"").toLowerCase(),B=!1,X=!1,Q=!1;for(let he=1;he<O.length;he++){let je=O[he];if(je===void 0)break;if(je==="--"){let lt=B&&O[he+1]!==void 0?he+1:null;return{command:lt===null?null:O[lt]??null,commandIndex:lt,scriptIndex:!B&&!X&&O[he+1]!==void 0?he+1:null,readsStdinAsCommands:!B&&(X||O[he+1]===void 0),syntaxCheck:Q}}if(je==="-"||je[0]!=="-"&&je[0]!=="+")return{command:B?je:null,commandIndex:B?he:null,scriptIndex:!B&&!X&&je!=="-"?he:null,readsStdinAsCommands:!B&&(X||je==="-"),syntaxCheck:Q};if(je.startsWith("--")){let lt=je.split("=",1)[0]??je;if(D==="bash"&&la.has(lt)&&!je.includes("="))he++;continue}let at=ca(D,je,O[he+1],"argv");if(at.commandSelected)B=!0;if(at.syntaxCheck)Q=!0;if(at.stdinMode)X=!0;he+=at.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!B,syntaxCheck:Q}}function ho(O,D){if(D.escaped)return D.escaped=!1,!0;if(O==="\\"&&!D.inSingle)return D.escaped=!0,!0;if(O==="'"&&!D.inDouble)return D.inSingle=!D.inSingle,!0;if(O==='"'&&!D.inSingle)return D.inDouble=!D.inDouble,!0;return!1}function gi(O){let D={inSingle:!1,inDouble:!1,escaped:!1};for(let B of Dh(O))ho(B,D);return D.inSingle||D.inDouble}function Dh(O){let D="",B={inSingle:!1,inDouble:!1,escaped:!1},X=!1,Q=!0;for(let he=0;he<O.length;he++){let je=O[he];if(!je)break;if(X){if(je===`
6
- `||je==="\r")D+=je,X=!1,B.escaped=!1;continue}if(je==="#"&&!B.inSingle&&!B.inDouble&&Q){X=!0;continue}if(D+=je,!B.inSingle&&!B.inDouble&&!B.escaped)Q=/[\s;&|()<>]/.test(je);ho(je,B)}return D}var ua=new Set(["rm","find","xargs","parallel"]),Nh=new Set(["git","busybox",...ua,...Kt,...lu,...vn]),Lh=new Set(["python","node","ruby","perl"]);function Re(O){let D=kt(O);return Nh.has(D)||wn(D)}function wn(O){return Lh.has(Wh(O))}function Wh(O){let D=Tt(O).toLowerCase();return mi.test(D)?"python":D}var it={version:1,rules:[],overrides:{},transparent_wrappers:[]};function m(O){try{let D=n(Fh(O));if(D===null)return{config:null,errors:[]};if(!D.trim())return{config:null,errors:["Config file is empty"]};let B=JSON.parse(D),X=Ve(B);if(X.errors.length>0)return{config:null,errors:X.errors};return{config:{version:1,rules:B.rules??[],overrides:B.overrides??{},transparent_wrappers:B.transparent_wrappers??[]},errors:[]}}catch(D){if(D instanceof r)return{config:null,errors:[D.message]};let B=D instanceof Error?D.message:String(D);return{config:null,errors:[D instanceof SyntaxError?"Invalid JSON":B]}}}function Fh(O){return typeof O==="string"?ne(O):O}var e=(O,D)=>({path:O,message:D,kind:"typed"}),Xt=(O,D)=>({path:O,message:D,kind:"custom"});function Pe(O){let D=new Set;return O.flatMap((B,X)=>{let Q=Gr(B)?B.name:void 0;if(typeof Q!=="string")return[];if(D.has(Q.toLowerCase()))return[Xt(["rules",X,"name"],`duplicate rule name "${Q}"`)];return D.add(Q.toLowerCase()),[]})}var Se=`must be one of ${aa.join(", ")}`,Gh=/^[^/]+\/[^/]+$/,zh=["version","rules","overrides","transparent_wrappers"];function Ve(O){let D=Bh(O);return{errors:oe(qe(D,zh,(B)=>B.kind==="custom"),": "," "),sources:Yh(O,D)}}function Bh(O){if(!Gr(O))return[e([],"Config must be an object")];let D=Array.isArray(O.rules)&&O.rules.length>pe;return[...O.version===1?[]:[e(["version"],"must be 1")],...$h(O.rules,D),...jh(O.overrides),...Kh(O.transparent_wrappers),...D?[]:Hh(O.rules),...Gr(O.overrides)?Object.keys(O.overrides).filter((B)=>!Gh.test(B)).map((B)=>Xt(["overrides",B],"must use <rulebook-name>/<rule-name>")):[],...qh(O.transparent_wrappers)]}function $h(O,D){if(O===void 0)return[];if(!Array.isArray(O))return[e(["rules"],"must be an array of rulebook source strings"),...fu(O,pe)?[e(["rules"],fe)]:[]];if(D)return[{path:["rules"],message:fe,kind:"limit"}];return O.flatMap((B,X)=>{if(typeof B!=="string")return[e(["rules",X],"must be a rulebook source string"),...Uh(B,1)?[e(["rules",X],"must be a non-empty rulebook source string")]:[]];return B===""?[e(["rules",X],"must be a non-empty rulebook source string")]:[]})}function fu(O,D){let B=mu(O);return B!==void 0&&!(B<=D)}function Uh(O,D){let B=mu(O);return B!==void 0&&!(B>=D)}function mu(O){if(O===null||O===void 0)return;let D=O.length;return D===void 0?void 0:Number(D)}function Hh(O){if(!Array.isArray(O))return[];let D=new Set;return O.flatMap((B,X)=>{if(typeof B!=="string"||B==="")return[];if(B.trim()==="")return[Xt(["rules",X],"must be a non-empty rulebook source string")];let Q=ou(B);if(Q)return[Xt(["rules",X],Q)];if(D.has(B))return[Xt(["rules",X],`duplicate rulebook source "${B}"`)];return D.add(B),[]})}function jh(O){if(O===void 0)return[];if(!Gr(O))return[e(["overrides"],"must be an object if provided")];return Object.keys(O).flatMap((D)=>{let B=O[D];if(B==="off")return[];if(!Gr(B))return[e(["overrides",D],'must be "off" or an object')];return[...Vh(B.reason,["overrides",D,"reason"]),...B.intent===void 0||xe(B.intent)?[]:[e(["overrides",D,"intent"],Se)]]})}function Vh(O,D){if(typeof O!=="string")return[e(D,"required non-empty string"),...fu(O,P)?[e(D,`must be at most ${P} characters`)]:[]];if(O==="")return[e(D,"required non-empty string")];return O.length>P?[e(D,`must be at most ${P} characters`)]:[]}function Kh(O){if(O===void 0)return[];if(!Array.isArray(O))return[e(["transparent_wrappers"],"must be an array of command strings")];return O.flatMap((D,B)=>{if(typeof D!=="string")return[e(["transparent_wrappers",B],"must be a command string")];return S.test(D)?[]:[e(["transparent_wrappers",B],"must match command pattern")]})}function qh(O){if(!Array.isArray(O))return[];let D=new Set;return O.flatMap((B,X)=>{if(typeof B!=="string"||!S.test(B))return[];if(D.has(B))return[Xt(["transparent_wrappers",X],`duplicate command "${B}"`)];if(Re(B))return[Xt(["transparent_wrappers",X],`reserved command "${B}" cannot be a wrapper`)];return D.add(B),[]})}function Yh(O,D){let B=Gr(O)?O.rules:void 0;if(!Array.isArray(B))return new Set;if(D.some((Q)=>Q.path.length===1&&Q.path[0]==="rules"))return new Set;let X=new Set(D.filter((Q)=>Q.path[0]==="rules"&&typeof Q.path[1]==="number").map((Q)=>Q.path[1]));return new Set(B.filter((Q,he)=>typeof Q==="string"&&!X.has(he)))}function qe(O,D,B){let X=O.map((je)=>je.path[1]),Q=[...new Set(X.filter((je)=>typeof je==="string"))],he=(je,at)=>[je.path.length===0?-1:D.indexOf(String(je.path[0])),typeof at==="number"?at:Q.indexOf(String(at)),B(je)?0:1];return O.map((je,at)=>({issue:je,rank:he(je,X[at])})).sort((je,at)=>je.rank[0]-at.rank[0]||je.rank[1]-at.rank[1]||je.rank[2]-at.rank[2]).map((je)=>je.issue)}function oe(O,D,B){return[...new Set(O.map((X)=>{let Q=da(X.path);if(X.kind==="unknownKeys")return`${Q?`${Q}.`:""}unknown field "${X.message}"`;if(X.kind==="key"||X.kind==="limit"||X.path.length===0)return X.message;return`${Q}${X.path.length===1?B:D}${X.message}`}))]}function da(O){return O.map((D,B)=>{if(typeof D==="number")return`[${D}]`;return B===0?String(D):`.${String(D)}`}).join("")}function xe(O){return aa.includes(O)}function Gr(O){return!!O&&typeof O==="object"&&!Array.isArray(O)}function ie(O){let D=Jh(O);if(D.errors.length>0)throw Error(D.errors.join("; "));return O}var Zh=`required non-empty string up to ${P} characters`,pu="must be a non-empty array of unique non-empty strings",Xh="required non-empty array of non-empty strings";function Jh(O){if(!Qn(O))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!du(O))return{errors:[cu],ruleNames:new Set};let D=[...O.rulebook_version===1||O.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...oe(Qh(O,O.rulebook_version===2),": ",": ")];return{errors:D.length>_n.maxValidationErrors?[...D.slice(0,_n.maxValidationErrors),uu]:D,ruleNames:new Set(_e(O).map((B)=>B.toLowerCase()))}}function _e(O){let D=Qn(O)?O.rules:void 0;return(Array.isArray(D)?D:[]).flatMap((B)=>{let X=Qn(B)?B.name:void 0;return typeof X==="string"?[X]:[]})}function Qh(O,D){return[...typeof O.name==="string"&&c.test(O.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof O.version==="string"&&O.version!==""?[]:[e(["version"],"required non-empty string")],...ey(O.allowed_commands),...ty(O.rules,D),...iy(O.tests),...sy(O),...ay(O)]}function ey(O){if(!Array.isArray(O))return[e(["allowed_commands"],"required array")];let D=new Set;return[...O.flatMap((B,X)=>typeof B==="string"&&S.test(B)?[]:[e(["allowed_commands",X],"must match command pattern")]),...O.flatMap((B,X)=>{if(typeof B!=="string"||!S.test(B))return[];if(D.has(B))return[Xt(["allowed_commands",X],`duplicate command "${B}"`)];return D.add(B),[]})]}function ty(O,D){if(!Array.isArray(O))return[e(["rules"],"required array")];return[...O.flatMap((B,X)=>{if(!Qn(B))return[e(["rules",X],"must be an object")];return D?ry(B,["rules",X]):ny(B,["rules",X])}),...Pe(O)]}function ny(O,D){return[...gu(O.name,D),...hu(O.command,D),...O.subcommand===void 0||typeof O.subcommand==="string"&&S.test(O.subcommand)?[]:[e([...D,"subcommand"],"must match command pattern")],...hi(O.block_args,[...D,"block_args"],"required non-empty array",!1),...yu(O.reason,D),...bu(O.intent,D)]}function ry(O,D){return[...gu(O.name,D),...hu(O.command,D),...yu(O.reason,D),...bu(O.intent,D),...oy(O.match,[...D,"match"]),...O.subcommand===void 0?[]:[e([...D,"subcommand"],"not supported in rulebook_version 2")],...O.block_args===void 0?[]:[e([...D,"block_args"],"not supported in rulebook_version 2")]]}function gu(O,D){if(typeof O!=="string")return[e([...D,"name"],"required string")];return c.test(O)?[]:[e([...D,"name"],"must match rule name pattern")]}function hu(O,D){return typeof O==="string"&&S.test(O)?[]:[e([...D,"command"],"required string matching command pattern")]}function yu(O,D){return typeof O==="string"&&O!==""&&O.length<=P?[]:[e([...D,"reason"],Zh)]}function bu(O,D){return O===void 0||xe(O)?[]:[e([...D,"intent"],Se)]}function oy(O,D){if(!Qn(O))return[e(D,"required object")];return[...hi(O.command_path,[...D,"command_path"],Xh,!1),...O.any_args===void 0?[]:hi(O.any_args,[...D,"any_args"],pu,!0),...O.exclude_args===void 0?[]:hi(O.exclude_args,[...D,"exclude_args"],pu,!0)]}function hi(O,D,B,X){if(!Array.isArray(O))return[e(D,B)];let Q=O.flatMap((he,je)=>{if(typeof he!=="string")return[e([...D,je],"must be a non-empty string")];return he===""?[Xt([...D,je],"must be a non-empty string")]:[]});if(O.some((he)=>typeof he!=="string"))return Q;return[...Q,...O.length===0?[Xt(D,B)]:[],...X&&new Set(O).size!==O.length?[Xt(D,"must not contain duplicate values")]:[]]}function iy(O){if(O===void 0)return[];if(!Array.isArray(O))return[e(["tests"],"must be an array if provided")];return O.flatMap((D,B)=>{if(!Qn(D))return[e(["tests",B],"must be an object")];return[...typeof D.command==="string"&&D.command.trim()!==""?[]:[e(["tests",B,"command"],"required non-empty string")],...D.expect==="blocked"||D.expect==="allowed"?[]:[e(["tests",B,"expect"],'must be "blocked" or "allowed"')],...D.rule===void 0||typeof D.rule==="string"?[]:[e(["tests",B,"rule"],"must be a string if provided")],...D.expect==="blocked"&&typeof D.rule!=="string"?[Xt(["tests",B,"rule"],"required string for blocked fixtures")]:[]]})}function sy(O){if(!Array.isArray(O.tests))return[];let D=new Set(_e(O));return[...new Set(O.tests.flatMap((B)=>Qn(B)&&B.expect==="blocked"&&typeof B.rule==="string"?[B.rule]:[]))].filter((B)=>!D.has(B)).map((B)=>Xt(["tests"],`blocked fixture references unknown rule "${B}"`))}function ay(O){if(!Array.isArray(O.allowed_commands)||!Array.isArray(O.rules))return[];let D=new Set(O.allowed_commands.filter((B)=>typeof B==="string"));return O.rules.flatMap((B,X)=>{let Q=Qn(B)?B.command:void 0;if(typeof Q!=="string"||D.has(Q))return[];return[Xt(["rules",X,"command"],`"${Q}" must be listed in allowed_commands`)]})}function Qn(O){return!!O&&typeof O==="object"&&!Array.isArray(O)}function K(O,D){let B=q(O,D),X=!1;try{X=Xc(B.userConfigTarget,B.projectConfigTarget)}catch(mt){if(mt instanceof r)return hy(B,mt.message);throw mt}let Q=m(B.userConfigTarget),he=X?{config:null,errors:[]}:m(B.projectConfigTarget),je=Cu(B.userConfigPath,Q.errors),at=Cu(B.projectConfigPath,he.errors),lt=new Set,ct=Q.config?fa(Q.config,hr(B.userConfigPath),"user",B.userScope,lt):vu(),ft=he.config?fa(he.config,hr(B.projectConfigPath),"project",B.projectScope,lt):vu(),dt=Q.config?.overrides??{},ut=he.config?.overrides??{};return{rules:[...Su(ct.rules,dt),...Su(ft.rules,ut)],transparent_wrappers:py(Q.config,he.config),rulebooks:[...ct.rulebooks,...ft.rulebooks],errors:[...je,...at,...ct.errors,...ft.errors],warnings:[...ct.warnings,...ft.warnings,...ct.canValidateOverrides?ma(dt,ct.knownRuleIds,B.userConfigPath):[],...ct.canValidateOverrides?gy(ut,ct.knownRuleIds,B.projectConfigPath):[],...ft.canValidateOverrides?ma(ut,ft.knownRuleIds,B.projectConfigPath):[]],userConfig:Q.config??void 0,projectConfig:he.config??void 0,...B}}function j(O,D){let B=ly(O,D);if(!B)return[];return[...B.scope.errors,...B.scope.warnings,...cy(B.config,B.scope,O)]}function ly(O,D){let B=D??w(hr(hr(O)),"rules policy"),X=m(i(B,O)).config;if(!X)return null;return{config:X,scope:fa(X,hr(O),"project",B)}}function cy(O,D,B){return D.canValidateOverrides?ma(O.overrides??{},D.knownRuleIds,B):[]}function fa(O,D,B,X=w(hr(hr(D)),B==="user"?"user policy":"project policy"),Q=new Set){let he=[],je=[],at=O.rules.flatMap((ct)=>{let ft=dy(ct,D,X);if(ft.errors.length>0||!ft.rulebook)return he.push(...ft.errors),[];let dt=ft.rulebook;if(Q.has(dt.name))return je.push(`duplicate active rulebook name "${dt.name}" for ${ct}; 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 Q.add(dt.name),[{rules:uy(dt),rulebook:{source:B,spec:ct,name:dt.name,version:dt.version,rules:dt.rules.map((ut)=>`${dt.name}/${ut.name}`)}}]}),lt=at.flatMap((ct)=>ct.rules);return{rules:lt,rulebooks:at.map((ct)=>ct.rulebook),knownRuleIds:new Set(lt.map((ct)=>ct.name)),errors:he,warnings:je,canValidateOverrides:he.length===0}}function uy(O){if(O.rulebook_version===2)return O.rules.map((D)=>({name:`${O.name}/${D.name}`,command:D.command,block_args:[],match:D.match,reason:D.reason,intent:D.intent}));return O.rules.map((D)=>({...D,name:`${O.name}/${D.name}`,match:void 0}))}function dy(O,D,B){let X=Ae(O),Q=I(D,X),he=my(Q,B);if("error"in he)return{rulebook:null,errors:[he.error]};if(he.content===null)return{rulebook:null,errors:[`missing rulebook file ${Q} for ${O}; ${fy(O)}`]};let je=me(he.content);if("problem"in je)return{rulebook:null,errors:[`invalid rulebook ${Q}: ${je.problem}; fix that file`]};if(je.rulebook.name!==X)return{rulebook:null,errors:[`rulebook name "${je.rulebook.name}" in ${Q} must match source "${O}"; fix that file`]};return{rulebook:je.rulebook,errors:[]}}function Ae(O){return C(O)?T(O).name:O}function fy(O){return C(O)?`run ${au} to vendor ${O}`:"create that file or remove that source from the rules config"}function my(O,D){try{return{content:n(i(D,O))}}catch(B){if(B instanceof r)return{error:B.message};throw B}}function me(O){let D;try{D=JSON.parse(O)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:ie(D)}}catch(B){return{problem:B instanceof Error?B.message:"invalid rulebook"}}}function py(O,D){return[...new Set([...O?.transparent_wrappers??[],...D?.transparent_wrappers??[]])]}function Su(O,D){return O.flatMap((B)=>{let X=D[B.name];if(X==="off")return[];if(X&&typeof X==="object")return[{...B,intent:X.intent??B.intent,reason:X.reason}];return[B]})}function ma(O,D,B){return Object.keys(O).filter((X)=>!D.has(X)).map((X)=>`unknown override key "${X}" in ${B}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function gy(O,D,B){return Object.keys(O).filter((X)=>D.has(X)).map((X)=>`project override cannot target user-scoped rule "${X}" in ${B}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function Cu(O,D){return D.map((B)=>B.startsWith("Unable to access ")?B:`${O}: ${B}`)}function hy(O,D){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[D],warnings:[],userConfigPath:O.userConfigPath,projectConfigPath:O.projectConfigPath}}function vu(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as Ay,readFileSync as Ty}from"node:fs";var Eu=[{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 after --.",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:"find.delete",category:"Filesystem",label:"find delete",description:"Blocks unsafe find -delete operations.",example:"find . -delete",intent:"scope_down"},{id:"find.delete-git-metadata",category:"Filesystem",label:"find delete Git metadata",description:"Blocks find -delete operations selecting protected Git metadata and hooks.",example:"find .git -delete",intent:"hard_stop",catastrophic:!0},{id:"find.exec-rm-recursive-force",category:"Filesystem",label:"find exec rm -rf",description:"Blocks find -exec rm -rf operations.",example:"find . -exec rm -rf {} +",intent:"scope_down"},{id:"dd.device-write",category:"Filesystem",label:"dd device write",description:"Blocks dd writing to a /dev device.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"mkfs device format",description:"Blocks mkfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],pa=new Set(Eu.map((O)=>O.id)),G=Eu,yy=new Map(G.map((O)=>[O.id,O.intent]));function St(O,D){return{id:O,reason:D,intent:yy.get(O)??"manual_only"}}var ga=[{id:"secret.basename.env",category:"Basename",label:".env",description:"Blocks exact .env files.",basename:".env"},{id:"secret.basename.npmrc",category:"Basename",label:".npmrc",description:"Blocks npm credential config files.",basename:".npmrc"},{id:"secret.basename.pypirc",category:"Basename",label:".pypirc",description:"Blocks Python package index credential files.",basename:".pypirc"},{id:"secret.basename.netrc",category:"Basename",label:".netrc",description:"Blocks machine login credential files.",basename:".netrc"},{id:"secret.basename.git-credentials",category:"Basename",label:".git-credentials",description:"Blocks Git credential storage files.",basename:".git-credentials"},{id:"secret.basename.id-rsa",category:"Basename",label:"id_rsa",description:"Blocks RSA private key basenames.",basename:"id_rsa"},{id:"secret.basename.id-ed25519",category:"Basename",label:"id_ed25519",description:"Blocks Ed25519 private key basenames.",basename:"id_ed25519"},{id:"secret.basename.id-ecdsa",category:"Basename",label:"id_ecdsa",description:"Blocks ECDSA private key basenames.",basename:"id_ecdsa"},{id:"secret.basename.credentials",category:"Basename",label:"credentials",description:"Blocks generic credentials file basenames.",basename:"credentials"}],yi={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},by=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Sy=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],ha=[{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"]},...Sy.flatMap((O)=>by.map((D)=>({id:["secret.home",O.idSlug,D.slice(1)].join("."),category:"Home path",label:[O.label,D].join(""),description:["Blocks home ",O.label,D," credential backup files."].join(""),suffixParts:[...O.directoryParts,[O.basename,D].join("")]}))),{id:"secret.home.gh-hosts",category:"Home path",label:"~/.config/gh/hosts.yml",description:"Blocks GitHub CLI host credential files.",suffixParts:[".config","gh","hosts.yml"]}];var bi=[{id:"secret.cli.claude-code",category:"Coding CLI credential",label:"Claude Code credentials",paths:["~/.claude/.credentials.json"]},{id:"secret.cli.claude-code.config",category:"Coding CLI config",label:"Claude Code config",paths:["~/.claude/settings.json","~/.claude/settings.local.json","~/.claude.json","<project>/.claude/settings.local.json","<project>/.mcp.json"]},{id:"secret.cli.antigravity",category:"Coding CLI config",label:"Antigravity CLI hook config",paths:["~/.gemini/config/hooks.json","~/.gemini/config/mcp_config.json"]},{id:"secret.cli.codex",category:"Coding CLI credential",label:"Codex credentials",paths:["~/.codex/auth.json","~/.codex/.credentials.json","~/.codex/secrets","~/.codex/.sandbox-secrets"]},{id:"secret.cli.codex.config",category:"Coding CLI config",label:"Codex config",paths:["~/.codex/config.toml","~/.codex/<name>.config.toml"]},{id:"secret.cli.gemini",category:"Coding CLI credential",label:"Gemini CLI credentials",paths:["~/.gemini/oauth_creds.json","~/.gemini/mcp-oauth-tokens.json","~/.gemini/a2a-oauth-tokens.json","~/.gemini/gemini-credentials.json"]},{id:"secret.cli.gemini.config",category:"Coding CLI config",label:"Gemini CLI config",paths:["~/.gemini/settings.json","~/.gemini/google_accounts.json","<project>/.gemini/settings.json","/Library/Application Support/GeminiCli/settings.json","/etc/gemini-cli/settings.json"]},{id:"secret.cli.copilot-cli",category:"Coding CLI credential",label:"GitHub Copilot CLI credentials",paths:["~/.copilot/config.json","~/.copilot/mcp-oauth-config","~/.copilot/mcp-secrets"]},{id:"secret.cli.copilot-cli.config",category:"Coding CLI config",label:"GitHub Copilot CLI config",paths:["~/.copilot/mcp-config.json"]},{id:"secret.cli.kimi-code",category:"Coding CLI credential",label:"Kimi Code credentials",paths:["~/.kimi-code/server.token","~/.kimi-code/credentials","~/.kimi/credentials","~/.kimi/mcp-oauth"]},{id:"secret.cli.kimi-code.config",category:"Coding CLI config",label:"Kimi Code config",paths:["~/.kimi-code/config.toml","~/.kimi-code/mcp.json","~/.kimi/config.toml","~/.kimi/config.json","~/.kimi/config.json.bak","~/.kimi/mcp.json","<project>/.kimi-code/mcp.json"]},{id:"secret.cli.opencode",category:"Coding CLI credential",label:"OpenCode credentials",paths:["~/.local/share/opencode/auth.json","~/.local/share/opencode/mcp-auth.json","~/.local/share/opencode/opencode.db"]},{id:"secret.cli.opencode.config",category:"Coding CLI config",label:"OpenCode config",paths:["~/.config/opencode/opencode.json","~/.config/opencode/opencode.jsonc","/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"]}],Ru=[{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"}],Cy=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],ya=Ru.map((O)=>({id:`secret.variant.${O.slug}.separator`,category:"Variant",label:`${O.label}-* / ${O.label}_*`,description:`Blocks ${O.label} variants with dash or underscore suffixes.`,prefix:O.prefix})),ba=Ru.flatMap((O)=>Cy.map((D)=>({id:`secret.variant.${O.slug}.${D.slice(1)}`,category:"Variant",label:`${O.label}${D}`,description:`Blocks ${O.label}${D} private credential variants.`,prefix:O.prefix,suffix:D}))),yo={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)$/},Sa=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((O)=>({id:`secret.ext.${O}`,category:"Extension",label:`.${O}`,description:`Blocks files with the .${O} extension.`,extension:O})),Ca=[{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?$/}],Ke=[...ga,yi,...ha,...ya,...ba,yo,...Sa,...Ca,...bi].map((O)=>({id:O.id,category:O.category,label:O.label,...O.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in O?{paths:O.paths}:{description:O.description}})),Si=new Set(bi.flatMap((O)=>O.category==="Coding CLI config"?[O.id]:[])),va=new Set(Ke.map((O)=>O.id));import{isAbsolute as Ea,join as vy,normalize as Ey,sep as Ci}from"node:path";var xu=process.platform==="win32",Ry=/[*?]/;function bo(O,D){if(O==="~")return D;if(O.startsWith("~/"))return`${D}${O.slice(1)}`;return O}function Ra(O,D){if(typeof O!=="string"||O.trim()==="")return"must be a non-empty path string";let B=bo(O.trim(),D);if(!Ea(B))return"must be an absolute path or start with ~/";return So(B,D)}function xa(O,D){let B=_u(O,D);if(B===null)return"must be a non-empty path string";if(!Ea(B))return null;if(So(B,D)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var xy="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",_y="cannot cover the guard's own configuration";function _u(O,D){if(typeof O!=="string"||O.trim()==="")return null;return bo(O.trim().replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),D)}function _a(O,D){let B=_u(O,D);if(B===null)return"must be a non-empty path string";if(Ry.test(B))return"cannot contain glob characters (* or ?); list the exact file or directory";if(!Ea(B))return null;if(So(B,D)!==null)return xy;return wy(B,D)?_y:null}function wy(O,D){let B=vi(O),X=vi(vy(D,".cc-safety-net"));return B===X||B.startsWith(`${X}${Ci}`)}function So(O,D){let B=vi(O),X=vi(D);if(B===X)return"cannot be the home directory";let Q=B.endsWith(Ci)?B:`${B}${Ci}`;if(X.startsWith(Q))return"cannot contain the home directory";return null}function vi(O){let D=Ey(O);if(xu)D=D.replace(/\//g,"\\").toLowerCase();if(D.length>(xu?3:1)&&D.endsWith(Ci))D=D.slice(0,-1);return D}var wu=30,Ei=1,Ri=365;function Pu(O){if(typeof O!=="number"||!Number.isInteger(O))return 30;if(O<1)return 1;return O>365?365:O}var Au=new Set(G.filter((O)=>O.catastrophic).map((O)=>O.id));function wt(O,D){if(!O)return null;if(Au.has(O.id))return O;if(D?.destructiveCommandProtectionEnabled===!1)return null;let B=D?.effectiveDestructiveCommandRules[O.id];return B&&!B.enabled?null:O}function Jt(O,D,B){if(Au.has(D))return!0;if(O?.destructiveCommandProtectionEnabled===!1)return!1;return O?.effectiveDestructiveCommandRules[D]?.enabled??B}function H(O,D){return Object.freeze(Object.fromEntries(G.map((B)=>{let X=B.activationCapability?D[B.activationCapability]:void 0,Q=X?.enabled??!0,he=O.destructiveCommandRuleOverrides[B.id],je=B.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...he?{override:he}:{}}:O.destructiveCommandProtectionEnabled?he?{enabled:he==="on",inheritedEnabled:Q,changesInherited:he==="on"!==Q,source:"rule_override",...B.activationCapability?{activationCapability:B.activationCapability}:{},override:he}:{enabled:Q,inheritedEnabled:Q,changesInherited:!1,source:X?.source??"built_in_default",...B.activationCapability?{activationCapability:B.activationCapability}:{}}:{enabled:!1,inheritedEnabled:Q,changesInherited:!1,source:"master_disabled",...B.activationCapability?{activationCapability:B.activationCapability}:{},...he?{override:he}:{}};return[B.id,Object.freeze(je)]})))}function Tu(O,D){return Object.freeze({...O,effectiveDestructiveCommandRules:H(O,D)})}var Iu={standard:0,strict:1,paranoid:2};function Y(O,D){return{policy:{version:1,safety:{level:D.safety?.level??O.safety.level,overrides:{...O.safety.overrides,...D.safety?.overrides}},workflow:{worktree_mode:D.workflow?.worktree_mode??O.workflow.worktree_mode},destructive_command_protection:{enabled:D.destructive_command_protection?.enabled??O.destructive_command_protection.enabled,overrides:{...O.destructive_command_protection.overrides,...D.destructive_command_protection?.overrides},allow_paths:wa(O.destructive_command_protection.allow_paths,D.destructive_command_protection?.allow_paths)},secret_protection:{enabled:D.secret_protection?.enabled??O.secret_protection.enabled,overrides:{...O.secret_protection.overrides,...D.secret_protection?.overrides},deny_paths:wa(O.secret_protection.deny_paths,D.secret_protection?.deny_paths),allow_paths:wa(O.secret_protection.allow_paths,D.secret_protection?.allow_paths)},audit:O.audit},weakenings:Py(O,D)}}function wa(O,D){return[...new Set([...O,...D??[]])]}function Py(O,D){let B=D.safety?.level,X=ai[O.safety.level];return[...B&&Iu[B]<Iu[O.safety.level]?[`project policy lowers level: ${O.safety.level} -> ${B}`]:[],...Wr.flatMap((Q)=>D.safety?.overrides?.[Q]===!1&&(O.safety.overrides[Q]??X[Q])?[`project policy disables ${Q}`]:[]),...D.workflow?.worktree_mode===!0&&!O.workflow.worktree_mode?["project policy enables worktree mode relaxations"]:[],...D.destructive_command_protection?.enabled===!1&&O.destructive_command_protection.enabled?["project policy disables destructive command protection"]:[],...D.secret_protection?.enabled===!1&&O.secret_protection.enabled?["project policy disables secret protection"]:[],...ku(D.destructive_command_protection?.overrides,(Q)=>O.destructive_command_protection.enabled&&O.destructive_command_protection.overrides[Q]!=="off"),...ku(D.secret_protection?.overrides,(Q)=>O.secret_protection.enabled&&(O.secret_protection.overrides[Q]==="on"?!0:O.secret_protection.overrides[Q]!=="off"&&!Si.has(Q))),...O.destructive_command_protection.enabled?Ou(O.destructive_command_protection.allow_paths,D.destructive_command_protection?.allow_paths).map((Q)=>`project policy adds destructive allow path: ${Q}`):[],...O.secret_protection.enabled?Ou(O.secret_protection.allow_paths,D.secret_protection?.allow_paths).map((Q)=>`project policy adds secret allow path: ${Q}`):[]]}function ku(O,D){return Object.entries(O??{}).flatMap(([B,X])=>X==="off"&&D(B)?[`project policy disables rule ${B}`]:[])}function Ou(O,D){return(D??[]).filter((B)=>!O.includes(B))}var Ta=new Set(["standard","strict","paranoid"]),J={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:wu}};function Lu(O,D){let B=Ny(d(O,D),O.home),X=Ie(v(D.cwd),O.home),Q=se(X.parsed,O.home),he=Object.keys(Q.policy).length>0?Y(B.gui??J,Q.policy):void 0,je=[...B.errors,...X.errors,...Q.diagnostics],at=(B.fallback==="defaults"&&he?"salvaged":B.fallback)??(B.gui?void 0:X.fallback)??(je.length>0?"salvaged":void 0),lt=Q.policy.safety?.level?"project":B.levelPresent?"user":"default";return{...he?Aa(he.policy):B.policy,errors:je,...at?{fallback:at}:{},...X.exists?{policyScopes:{levelScope:lt,weakenings:he?.weakenings??[]}}:{}}}var Iy="project policy audit settings are ignored; audit is user scope only";function se(O,D){if(!hn(O))return{policy:{},diagnostics:[]};let B=hn(O.safety)?O.safety:{},X=hn(O.workflow)?O.workflow:{},Q=hn(O.destructive_command_protection)?O.destructive_command_protection:{},he=hn(O.secret_protection)?O.secret_protection:{},je={...Ta.has(B.level)?{level:B.level}:{},...hn(B.overrides)?Mu({overrides:Wu(B.overrides,Wr,["safety","overrides"],yr)}):{}},at={...typeof Q.enabled==="boolean"?{enabled:Q.enabled}:{},...Q.overrides!==void 0?{overrides:xi(Q.overrides,pa,Gu,yr)}:{},...Q.allow_paths!==void 0?{allow_paths:Br(Q.allow_paths,Ra,D,["destructive_command_protection","allow_paths"],yr)}:{}},lt={...typeof he.enabled==="boolean"?{enabled:he.enabled}:{},...he.overrides!==void 0?{overrides:xi(he.overrides,va,zu,yr)}:{},...he.deny_paths!==void 0?{deny_paths:Br(he.deny_paths,xa,D,["secret_protection","deny_paths"],yr)}:{},...he.allow_paths!==void 0?{allow_paths:Br(he.allow_paths,_a,D,["secret_protection","allow_paths"],yr)}:{}};return{policy:Mu({safety:je,workflow:typeof X.worktree_mode==="boolean"?{worktree_mode:X.worktree_mode}:{},destructive_command_protection:at,secret_protection:lt}),diagnostics:O.audit===void 0?[]:[Iy]}}function Wu(O,D,B,X){return Object.fromEntries(D.flatMap((Q)=>{let he=O[Q];if(typeof he==="boolean")return[[Q,he]];if(he!==void 0)X(e([...B,Q],Ia));return[]}))}function Mu(O){return Object.fromEntries(Object.entries(O).flatMap((D)=>Object.keys(D[1]).length>0?[D]:[]))}var yr=()=>{return},Ia="must be a boolean",ka="must be an object if provided",Fu=`must be an integer between ${Ei} and ${Ri}`,Gu={path:["destructive_command_protection","overrides"],label:"destructive command"},zu={path:["secret_protection","overrides"],label:"secret protection"},Ye=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Je(O,D){let B=[];return{policy:Bu(O,D,(Q)=>{B.push(Q)}),issues:B}}function x(O,D){return Bu(O,D,yr)}function Bu(O,D,B){if(!hn(O))return B(e([],"Config must be an object")),W();if(O.version!==1)B(e(["version"],"must be 1"));let X=zr(O.safety,["safety"],["level","overrides"],B),Q=zr(X.overrides,["safety","overrides"],Wr,B),he=zr(O.workflow,["workflow"],["worktree_mode"],B),je=zr(O.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],B),at=zr(O.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],B),lt=zr(O.audit,["audit"],["retention_days"],B);return $u(O,Ye,[],B),{version:1,safety:{level:ky(X.level,B),overrides:Wu(Q,Wr,["safety","overrides"],B)},workflow:{worktree_mode:Pa(he.worktree_mode,["workflow","worktree_mode"],!1,B)},destructive_command_protection:{enabled:Pa(je.enabled,["destructive_command_protection","enabled"],!0,B),overrides:xi(je.overrides,pa,Gu,B),allow_paths:Br(je.allow_paths,Ra,D,["destructive_command_protection","allow_paths"],B)},secret_protection:{enabled:Pa(at.enabled,["secret_protection","enabled"],!0,B),overrides:xi(at.overrides,va,zu,B),deny_paths:Br(at.deny_paths,xa,D,["secret_protection","deny_paths"],B),allow_paths:Br(at.allow_paths,_a,D,["secret_protection","allow_paths"],B)},audit:{retention_days:Oy(lt.retention_days,B)}}}function zr(O,D,B,X){if(O===void 0)return{};if(!hn(O))return X(e(D,ka)),{};return $u(O,B,D,X),O}function $u(O,D,B,X){for(let Q of Object.keys(O).filter((he)=>!D.includes(he)))X({path:B,message:Q,kind:"unknownKeys"})}function ky(O,D){if(O===void 0)return"standard";if(Ta.has(O))return O;return D(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Pa(O,D,B,X){if(typeof O==="boolean")return O;if(O!==void 0)X(e(D,Ia));return B}function Oy(O,D){if(!(O===void 0||typeof O==="number"&&Number.isInteger(O)&&O>=Ei&&O<=Ri))D(e(["audit","retention_days"],Fu));return Pu(O)}function xi(O,D,B,X){if(O===void 0)return{};if(!hn(O))return X(e(B.path,ka)),{};return Object.fromEntries(Object.entries(O).flatMap(([Q,he])=>{if(!D.has(Q))return X({path:[...B.path,Q],message:`unknown ${B.label} rule id "${Q}"`,kind:"key"}),[];if(he==="on"||he==="off")return[[Q,he]];return X(e([...B.path,Q],'must be "on" or "off"')),[]}))}function Br(O,D,B,X,Q){if(O===void 0)return[];if(!Array.isArray(O))return Q(e(X,"must be an array of paths")),[];return O.flatMap((he,je)=>{let at=D(he,B);if(at===null)return[he];return Q(typeof he==="string"?Xt([...X,je],at):e([...X,je],at)),[]})}function hn(O){return!!O&&typeof O==="object"&&!Array.isArray(O)}function W(){return structuredClone(J)}function Te(O,D){let B=E({safety:Oe(O.safety)},D),X=H({destructiveCommandProtectionEnabled:O.destructive_command_protection.enabled,destructiveCommandRuleOverrides:O.destructive_command_protection.overrides},B.capabilities),Q=Object.values(X),he=Q.filter((je)=>je.source!=="catastrophic");return{selectedPreset:O.safety.level,effectiveLevel:B.effectiveLevel,capabilities:B.capabilities,rules:X,counts:{enabled:he.filter((je)=>je.enabled).length,disabled:he.filter((je)=>!je.enabled).length,effectiveCustomizations:Q.filter((je)=>je.changesInherited).length}}}function Ie(O,D){if(!Ay(O))return{exists:!1,policy:W(),errors:[]};try{let B=Ty(O,"utf-8");if(!B.trim())return{exists:!0,policy:W(),errors:[`${O}: Config file is empty`],fallback:"defaults"};let X=JSON.parse(B),Q=Je(X,D);if(Q.issues.length===0)return{exists:!0,parsed:X,policy:Q.policy,errors:[]};return{exists:!0,parsed:X,policy:Q.policy,errors:Q.issues.map((he)=>`${O}: ${Dy(he)}`),fallback:hn(X)?"salvaged":"defaults"}}catch(B){let X=B instanceof Error?B.message:String(B);return{exists:!0,policy:W(),errors:[`${O}: ${B instanceof SyntaxError?"Invalid JSON":X}`],fallback:"defaults"}}}var My=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[ka,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[Ia,"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 ${Ei} and ${Ri}`]]);function Dy(O){let D=da(O.path);if(O.kind==="unknownKeys")return`${D===""?"":`${D}.`}${O.message}: unknown field`;if(O.kind==="key")return`${D}: unknown rule id`;let B=My.get(O.message)??O.message;return D===""?B:`${D}: ${B}`}function Ny(O,D){let B=Ie(O,D);if(!B.exists){let X=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!hn(X))return{policy:Nu(),errors:[]};let Q=x(X,D);return{policy:Aa(Q),gui:Q,errors:[],levelPresent:Du(X)}}if(B.parsed===void 0)return{policy:Nu(),errors:B.errors,...B.fallback?{fallback:B.fallback}:{}};return{policy:Aa(B.policy),gui:B.policy,errors:B.errors,...B.fallback?{fallback:B.fallback}:{},levelPresent:Du(B.parsed)}}function Du(O){let D=hn(O)&&hn(O.safety)?O.safety:{};return Ta.has(D.level)}function De(O){let D=Object.entries(O),B=new Set(D.flatMap(([X,Q])=>Q==="on"?[X]:[]));return[...new Set([...[...Si].filter((X)=>!B.has(X)),...D.flatMap(([X,Q])=>Q==="off"?[X]:[])])]}function Nu(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:De({}),denyPaths:[],allowPaths:[]}}}function Aa(O){return{safety:Oe(O.safety),worktreeMode:O.workflow.worktree_mode,destructiveCommandProtectionEnabled:O.destructive_command_protection.enabled,destructiveCommandRuleOverrides:O.destructive_command_protection.overrides,destructiveCommandAllowPaths:O.destructive_command_protection.allow_paths,secretProtection:{enabled:O.secret_protection.enabled,disabledRules:De(O.secret_protection.overrides),denyPaths:O.secret_protection.deny_paths,allowPaths:O.secret_protection.allow_paths}}}function Oe(O){let D={...O.overrides.fail_closed!==void 0?{failClosed:O.overrides.fail_closed}:{},...O.overrides.paranoid_rm!==void 0?{paranoidRm:O.overrides.paranoid_rm}:{},...O.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:O.overrides.paranoid_interpreters}:{}};return{level:O.level,...Object.keys(D).length>0?{overrides:D}:{}}}function L(O,D){let B=K(O,D),X=Lu(O,D),Q={rules:B.rules,transparentWrappers:B.transparent_wrappers,safety:X.safety,worktreeMode:X.worktreeMode,destructiveCommandProtectionEnabled:X.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:X.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:X.destructiveCommandAllowPaths,secretProtection:{enabled:X.secretProtection.enabled??!0,disabledRules:X.secretProtection.disabledRules??[],denyPaths:X.secretProtection.denyPaths,allowPaths:X.secretProtection.allowPaths??[]}},he={...B.userConfig?.overrides??{},...B.projectConfig?.overrides??{}},je=Object.freeze(Object.fromEntries(Q.rules.map((at)=>{let lt=B.rulebooks.find((ft)=>ft.rules.includes(at.name)),ct=he[at.name];return[at.name,Object.freeze({id:at.name,...lt?{rulebook:Object.freeze({name:lt.name,version:lt.version}),...Gy(lt.spec)?{source:lt.spec}:{}}:{},...ct&&typeof ct==="object"?{override:Object.freeze({type:"reason",reason:ct.reason})}:{}})]})));return Le(Q,Ly(B,X),je,X.policyScopes)}function Ne(O){if(O.state==="ready")return{state:O.state};return{state:O.state,reason:O.reason}}function Ly(O,D){let B=Fy(D);if(O.errors.length===0&&O.warnings.length===0&&!B)return;return{diagnostics:[...O.errors,...O.warnings,...D.errors],reason:zy(O.errors.length>0?Wy(O.errors):void 0,O.warnings.length>0?Ma(O.warnings.join("; ")):void 0,B)}}function Wy(O){return`${Ma(O.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Fy(O){if(O.errors.length===0)return;let D=O.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${O.errors.join("; ")}. Enforcing ${D}; the invalid values are not active. Fix the policy file manually`}function Gy(O){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(O)}function Le(O,D,B=Object.freeze({}),X){let Q=Oa(structuredClone(O)),he=X?{policyScopes:Oa(structuredClone(X))}:{};if(!D)return Object.freeze({state:"ready",policy:Q,diagnostics:Object.freeze([]),ruleMetadata:B,...he});return Object.freeze({state:"degraded",policy:Q,diagnostics:Object.freeze([...D.diagnostics]),reason:D.reason,ruleMetadata:B,...he})}function Oa(O){if(typeof O!=="object"||O===null)return O;for(let D of Object.values(O))Oa(D);return Object.freeze(O)}function zy(...O){return Ma(O.filter((D)=>!!D).join("; "))}function Ma(O){return/[.!?]$/.test(O)?O:`${O}.`}function Me(O){let D=O.effectiveCapabilities,B=O.strict??D.fail_closed.enabled,X=O.paranoidRm??D.paranoid_rm.enabled,Q=O.paranoidInterpreters??D.paranoid_interpreters.enabled,he={fail_closed:Da(D.fail_closed,O.strict,"strict"),paranoid_rm:Da(D.paranoid_rm,O.paranoidRm,"paranoidRm"),paranoid_interpreters:Da(D.paranoid_interpreters,O.paranoidInterpreters,"paranoidInterpreters")};return{policy:Tu(O.policySnapshot.policy,he),effectiveCapabilities:he,effectiveLevel:Js({failClosed:B,paranoidRm:X,paranoidInterpreters:Q}),strict:B,paranoidRm:X,paranoidInterpreters:Q,worktreeMode:O.worktreeMode??!1}}function Da(O,D,B){if(D===void 0||D===O.enabled)return O;return{enabled:D,source:"capability_override",sources:[...O.sources,`analysis options.${B}`]}}function Co(O,D){if(O!=="powershell")return D[0]?.provenance==="command-substitution";let B=D[0]?.text==="&"||D[0]?.text==="."?1:0,X=D[B]?.provenance;return X!==void 0&&X!=="literal"}var By=/^[A-Za-z_][A-Za-z0-9_]*=/;function _i(O,D){return O?.provenance==="literal"&&!O.quoted&&O.raw===D&&O.text===D}function vo(O){let D=_i(O.words[0],"time")?1:0,B=D===1&&_i(O.words[D],"-p")?D+1:D,X=D===1&&_i(O.words[B],"--")?B+1:B,Q=_i(O.words[X],"!")?X+1:X,he=O.words.slice(Q).find((je)=>!By.test(je.text));return he?.provenance==="literal"?he.text:void 0}var er=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function wi(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function $y(O){return Object.freeze({...O,span:Object.freeze(O.span),words:Object.freeze(O.words),redirections:Object.freeze(O.redirections.map((D)=>Object.freeze({...D,span:Object.freeze(D.span),...D.heredoc?{heredoc:Object.freeze({...D.heredoc,bodySpan:Object.freeze(D.heredoc.bodySpan),terminatorSpan:Object.freeze(D.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(O.nested.map((D)=>an(D)))})}function Pi(O,D,B){O.push(B),D.reset()}function Ai(O){let D=[];return{parts:D,push:(B,X,Q)=>{if(X<=B)return;D.push({raw:O.slice(B,X),span:{start:B,end:X},provenance:Q})}}}function Na(O){let D=O.parts??[{raw:O.raw,span:O.span,provenance:O.provenance}];return Object.freeze({kind:"word",...O,span:Object.freeze(O.span),parts:Object.freeze(D.map((B)=>Object.freeze({...B,span:Object.freeze(B.span)})))})}function $r(O,D,B,X,Q,he,je){return Na({text:X,raw:O.slice(D,B),span:{start:D,end:B},provenance:Q,quoted:he,...je?{parts:je}:{}})}function an(O){return Object.freeze({...O,span:Object.freeze(O.span),issues:Object.freeze(O.issues.map((D)=>Object.freeze({...D}))),nodes:Object.freeze(O.nodes.map((D)=>{if(D.kind==="command")return $y(D);if(D.kind==="group"||D.kind==="function")return Object.freeze({...D,span:Object.freeze(D.span),body:an(D.body)});return Object.freeze({...D,span:Object.freeze(D.span)})}))})}function La(O,D,B){if(D>=B||Hu(O[D]??""))return null;let X="",Q=!1,he=!1,je=D;while(je<B&&!Hu(O[je]??"")){let at=O[je]??"";if(at==="'"){Q=!0;let lt=Uu(O,je+1,B,"'");X+=lt.text,he||=!lt.closed,je=lt.next;continue}if(at==='"'){Q=!0;let lt=Uu(O,je+1,B,'"');X+=lt.text,he||=!lt.closed,je=lt.next;continue}if(at==="\\"){Q=!0;let lt=O[je+1];if(!lt||lt===`
7
- `||lt==="\r"){he=!0;break}X+=lt,je+=2;continue}if(at==="`"||O.startsWith("$(",je)||O.startsWith("${",je)||O.startsWith("<(",je)||O.startsWith(">(",je))he=!0;X+=at,je++}return{delimiter:X,quoted:Q,next:je,ambiguous:he}}function Wa(O,D,B,X){let Q=[],he=D;for(let je of X){let at=he,lt=!1;while(he<B){let ct=Uy(O,he,B);if((je.stripTabs?ct.text.replace(/^\t+/,""):ct.text)===je.delimiter){je.attach({body:je.stripTabs?Hy(O.slice(at,he)):O.slice(at,he),delimiter:je.delimiter,quotedDelimiter:je.quotedDelimiter,bodySpan:{start:at,end:he},terminatorSpan:{start:he,end:ct.contentEnd}}),he=ct.next,lt=!0;break}if(ct.next<=he)break;he=ct.next}if(lt)continue;return Q.push({code:"unterminated-heredoc",message:`heredoc delimiter ${je.delimiter} was not found`}),{next:B,issues:Q,terminated:!1}}return{next:he,issues:Q,terminated:!0}}function Uu(O,D,B,X){let Q="",he=D;while(he<B&&O[he]!==`
8
- `&&O[he]!=="\r"){let je=O[he]??"";if(je===X)return{text:Q,next:he+1,closed:!0};if(X==='"'&&je==="\\"&&O[he+1]){let at=O[he+1]??"";Q+=["$","`",'"',"\\"].includes(at)?at:`\\${at}`,he+=2;continue}Q+=je,he++}return{text:Q,next:he,closed:!1}}function Hu(O){return O!=="\r"&&(/[\s;&|<>)]/u.test(O)||O==="`")}function Uy(O,D,B){let X=D;while(X<B&&O[X]!==`
9
- `)X++;let Q=X>=B?B:X+1;return{text:O.slice(D,X),contentEnd:X,next:Q}}function Hy(O){return O.replace(/(^|\r\n?|\n)\t+/g,"$1")}var qu=new Set(["&&","||","|","|&"]);function Yu(O,D){let B={start:0,end:O.length};if(O.length>D.maxInputLength)return an({kind:"program",dialect:"posix",source:O,span:B,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${D.maxInputLength} UTF-16 code units`}],nodes:[]});let X=ki(O,0,O.length,D,{used:0,max:D.maxWords},0);return an({kind:"program",dialect:"posix",source:O,span:B,status:Di(X.issues,X.limited),issues:X.issues,nodes:X.nodes})}function ki(O,D,B,X,Q,he,je){let at=[],lt=[],ct=wi(),ft=[],dt=()=>{if(ct.words.length===0&&ct.redirections.length===0)return;let mt={start:ct.start,end:ct.end},pt=ct.words.map((ht)=>ht.text);Pi(at,ct,{kind:"command",dialect:"posix",source:O.slice(mt.start,mt.end),span:mt,words:ct.words,redirections:ct.redirections,nested:ct.nested,displayText:lt.length>0&&at.length===0?O.slice(D,B):pt.join(" ")})},ut=D;while(ut<B){let mt=O[ut];if(!mt)break;if(je&&mt===je)return dt(),Ku(at,lt),{nodes:at,issues:lt,next:ut+1,closed:!0,limited:!1,pendingHeredocs:ft};if(Mi(mt)){if(mt===`
10
- `||mt==="\r"){dt();let Ct=mt==="\r"&&O[ut+1]===`
11
- `?ut+2:ut+1,Pt=at.at(-1);if(Pt?.kind!=="connector"||!qu.has(Pt.operator))at.push(Object.freeze({kind:"connector",operator:O.slice(ut,Ct),span:Object.freeze({start:ut,end:Ct})}));if(ft.length>0){let Rt=Wa(O,Ct,B,ft.splice(0));lt.push(...Rt.issues),ut=Rt.next;continue}ut=Ct;continue}ut++;continue}if(mt==="#"){while(ut<B&&O[ut]!==`
12
- `&&O[ut]!=="\r")ut++;continue}let pt=ct.start===-1?db(O,ut,B):void 0;if(pt){if(Ga(at,lt),he>=X.maxDepth)return Ur(at,lt,ut,"depth-limit",X.maxDepth);if(!Fa(Q))return Ur(at,lt,ut,"word-limit",X.maxWords);let Ct=ki(O,pt.braceIndex+1,B,X,Q,he+1,"}"),Pt=Ct.next,Rt={start:pt.braceIndex+1,end:Ct.closed?Pt-1:Pt},_t=ju(O,Rt,Ct);if(at.push({kind:"function",name:pt.name,span:{start:ut,end:Pt},body:_t}),lt.push(...Ct.issues),Ct.pendingHeredocs.length>0||Ro(Ct.nodes))lt.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(ft.push(...Ct.pendingHeredocs),Ct.limited)return Ii(at,lt,Ct.next);if(!Ct.closed)lt.push({code:"unclosed-function-body",message:"function body is not closed"});ut=Pt;continue}let ht=Oi(O,ut);if(ht){if(dt(),!rd(at.at(-1)))lt.push({code:"unexpected-connector",message:`connector ${ht} has no preceding command`});at.push(Object.freeze({kind:"connector",operator:ht,span:Object.freeze({start:ut,end:ut+ht.length})})),ut+=ht.length;continue}if(mt===")"){dt(),lt.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),at.push({kind:"unknown",source:mt,span:{start:ut,end:ut+1}}),ut++;continue}if((mt==="("||mt==="{"&&Jy(O,ut,B))&&ct.start===-1){if(Ga(at,lt),he>=X.maxDepth)return Ur(at,lt,ut,"depth-limit",X.maxDepth);let Ct=mt==="("?")":"}",Pt=ki(O,ut+1,B,X,Q,he+1,Ct),Rt=Pt.next,_t={start:ut+1,end:Pt.closed?Rt-1:Rt},Ut=ju(O,_t,Pt);if(at.push({kind:"group",style:mt==="("?"subshell":"brace",span:{start:ut,end:Rt},body:Ut}),lt.push(...Pt.issues),Pt.pendingHeredocs.length>0||Ro(Pt.nodes))lt.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(ft.push(...Pt.pendingHeredocs),Pt.limited)return Ii(at,lt,Pt.next);if(!Pt.closed)lt.push({code:mt==="("?"unclosed-subshell":"unclosed-brace-group",message:`${mt} group is not closed`});ut=Rt;continue}let gt=(mt==="<"||mt===">")&&O[ut+1]!=="("?qy(O,ut):null;if(gt){let Ct=ct.words.at(-1),Pt=Ct&&Ct.span.end===ut&&/^[0-9]+$/.test(Ct.raw)?Number(Ct.raw):void 0;if(Pt!==void 0)ct.words.pop();let Rt=Pt===void 0?ut:Ct?.span.start??ut;ct.start=ct.start===-1?ut:ct.start;let _t=ut+gt.length;while(_t<B&&/[ \t]/.test(O[_t]??""))_t++;let Ut=O[_t],jt=_t>ut+gt.length&&Ut==="#",qt=!Ut||Mi(Ut)||!!Oi(O,_t)||Ut===je||Ut===")"||jt||(Ut==="<"||Ut===">")&&O[_t+1]!=="(",Vt=gt==="<<"||gt==="<<-",Gt=Vt?La(O,_t,B):void 0,Ot=Gt?{word:$r(O,_t,Gt.next,Gt.delimiter,"literal",Gt.quoted),nested:[],issues:[],next:Gt.next,limited:!1}:!qt?za(O,_t,B,X,Q,he):void 0;if(Ot){if(lt.push(...Ot.issues),Ot.limited)return Ii(at,lt,Ot.next);if(!Fa(Q))return Ur(at,lt,Ot.next,"word-limit",X.maxWords)}let nn=Ot?.next??ut+gt.length,Sn={kind:"redirection",operator:gt,span:{start:Rt,end:nn},...Pt===void 0?{}:{fd:Pt},...Ot?{target:Ot.word}:{}};if(ct.redirections.push(Sn),Vt&&!Gt)lt.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if(Gt){if(Gt.ambiguous||Gt.delimiter.length===0)lt.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let Fn=ct.nested;ft.push({delimiter:Gt.delimiter,quotedDelimiter:Gt.quoted,stripTabs:gt==="<<-",attach:(xn)=>{if(Sn.heredoc=xn,xn.quotedDelimiter)return;Fn.push(...Vy(O,xn.bodySpan.start,xn.bodySpan.end,X,Q,he+1))}})}if(!Vt&&!Ot)lt.push({code:"missing-redirection-target",message:`redirection ${gt} requires a target word`});if(Ot)ct.nested.push(...Ot.nested);ct.end=nn,ut=nn;continue}if(ct.start===-1)Ga(at,lt);let yt=za(O,ut,B,X,Q,he);if(lt.push(...yt.issues),yt.limited)return Ii(at,lt,yt.next);let vt=tb(ct.words)?sb(O,yt.word,Q.max-Q.used,X.maxDepth,X.maxInputLength):void 0;if(vt?.limitCode)return Ur(at,lt,yt.next,vt.limitCode,vt.limitCode==="word-limit"?X.maxWords:vt.limitCode==="depth-limit"?X.maxDepth:X.maxInputLength);let Et=vt?.words??[yt.word];for(let Ct of Et){if(!Fa(Q))return Ur(at,lt,yt.next,"word-limit",X.maxWords);ct.words.push(Ct)}ct.start=ct.start===-1?ut:ct.start,ct.end=yt.next,ct.nested.push(...yt.nested),ut=yt.next>ut?yt.next:ut+1}return dt(),Ku(at,lt),lt.push(...fb(ft)),{nodes:at,issues:lt,next:ut,closed:je===void 0,limited:!1,pendingHeredocs:[]}}function ju(O,D,B){return{kind:"program",dialect:"posix",source:O.slice(D.start,D.end),span:D,status:Di(B.issues,B.limited),issues:B.issues,nodes:B.nodes}}function za(O,D,B,X,Q,he){let je="",at=D,lt=!1,ct="literal",ft=[],dt=[],ut=!1;while(at<B){let mt=O[at],pt=(mt==="<"||mt===">")&&O[at+1]==="(";if(!mt||Mi(mt)||(mt===";"||mt==="|"||mt==="&")&&Oi(O,at)||(mt==="<"||mt===">")&&!pt)break;if(mt===")")break;if(mt==="'"){lt=!0;let gt=O.indexOf("'",at+1);if(gt===-1||gt>=B){je+=O.slice(at+1,B),dt.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),at=B;break}je+=O.slice(at+1,gt),at=gt+1;continue}if(mt==='"'){lt=!0;let gt=jy(O,at,B,X,Q,he);if(je+=gt.text,ft.push(...gt.nested),dt.push(...gt.issues),ut||=gt.limited,ct=Eo(ct,gt.provenance),at=gt.next,ut)break;continue}if(O.startsWith("$'",at)){lt=!0;let gt=Yy(O,at+2,B);if(je+=gt.text,dt.push(...gt.issues),!gt.closed)dt.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});at=gt.next;continue}if(mt==="\\"){let gt=O[at+1];if(!gt){dt.push({code:"trailing-escape",message:"escape has no following character"}),at++;break}if(gt===`
13
- `){at+=2;continue}je+=gt,at+=2;continue}let ht=mt==="$"||mt==="<"||mt===">"||mt==="`"?Ni(O,at,B,X,Q,he):null;if(ht){let gt=Zu(ht,ft,dt);if(ut||=gt.limited,ct=Eo(ct,gt.provenance),at=gt.next,ut)break;continue}if(mt==="$"){let gt=Qu(O,at,B,je,ct);je=gt.text,ct=gt.provenance,at=gt.next;continue}if(mt==="*"||mt==="?"||mt==="[")ct=Eo(ct,"glob");je+=mt,at++}return{word:$r(O,D,at,je,ct,lt,ct==="literal"?void 0:Xy(O,D,at)),nested:ft,issues:dt,next:at,limited:ut}}function jy(O,D,B,X,Q,he){let je="",at="literal",lt=[],ct=[],ft=!1,dt=D+1;while(dt<B){let ut=O[dt];if(ut==='"')return{text:je,provenance:at,nested:lt,issues:ct,next:dt+1,limited:ft};if(ut==="\\"&&O[dt+1]){let pt=O[dt+1]??"";if(pt===`
14
- `){dt+=2;continue}if(pt==="\r"&&O[dt+2]===`
15
- `){dt+=3;continue}je+=["$","`",'"',"\\"].includes(pt)?pt:`\\${pt}`,dt+=2;continue}if(O.startsWith("$((",dt)){let pt=Ba(O,dt+3,B,"))"),ht=pt===-1?B:pt+2;if(je+=O.slice(dt,ht),pt===-1)ct.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});dt=ht;continue}let mt=Ni(O,dt,B,X,Q,he);if(mt){let pt=Zu(mt,lt,ct);if(dt=pt.next,ft||=pt.limited,at=Eo(at,pt.provenance),ft)return{text:je,provenance:at,nested:lt,issues:ct,next:dt,limited:ft};continue}if(ut==="$"){let pt=Qu(O,dt,B,je,at);je=pt.text,at=pt.provenance,dt=pt.next;continue}je+=ut??"",dt++}return ct.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:je,provenance:at,nested:lt,issues:ct,next:B,limited:ft}}function Ni(O,D,B,X,Q,he){let je=O.startsWith("$((",D),at=O.startsWith("$(",D)&&!je,lt=O.startsWith("<(",D)||O.startsWith(">(",D),ct=O[D]==="`";if(!je&&!at&&!lt&&!ct)return null;let ft=je?3:ct?1:2,dt=je?"))":ct?"`":")",ut=Ba(O,D+ft,B,dt),mt=ut===-1?B:ut,pt=ut===-1?B:ut+dt.length;if(he>=X.maxDepth)return{program:ub(O,D+ft,mt,"depth-limit"),next:pt,provenance:je?"arithmetic":"command-substitution"};if(je){let vt=[],Et=[],Ct=!1,Pt=D+ft;while(Pt<mt){let Rt=Ni(O,Pt,mt,X,Q,he+1);if(!Rt){Pt++;continue}if(vt.push(...Rt.program.nodes),Et.push(...Rt.program.issues),Ct||=Rt.program.status==="limited",Pt=Rt.next,Ct)break}if(ut===-1)Et.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:an({kind:"program",dialect:"posix",source:O.slice(D+ft,mt),span:{start:D+ft,end:mt},status:Di(Et,Ct),issues:Et,nodes:vt}),next:pt,provenance:"arithmetic"}}let ht=ki(O,D+ft,mt,X,Q,he+1),gt=ut===-1?[{code:"unclosed-command-substitution",message:`${O.slice(D,D+ft)} substitution is not closed`}]:[],yt=(ct||lt)&&Ro(ht.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[];return{program:an({kind:"program",dialect:"posix",source:O.slice(D+ft,mt),span:{start:D+ft,end:mt},status:Di([...ht.issues,...gt,...yt],ht.limited),issues:[...ht.issues,...gt,...yt],nodes:ht.nodes}),next:pt,provenance:"command-substitution"}}function Vy(O,D,B,X,Q,he){let je=[],at=D;while(at<B){let lt=O[at];if(lt==="\\"){at+=2;continue}let ct=lt==="$"||lt==="`"?Ni(O,at,B,X,Q,he):null;if(!ct){at++;continue}if(je.push(ct.program),at=ct.next,ct.program.status==="limited")break}return je}function Zu(O,D,B){return D.push(O.program),B.push(...O.program.issues),{provenance:O.provenance,next:O.next,limited:O.program.status==="limited"}}function Ba(O,D,B,X){if(X==="`"){for(let at=D;at<B;at++){if(O[at]==="\\"){at++;continue}if(O[at]==="`")return at}return-1}let Q=1,he={single:!1,double:!1},je=[];for(let at=D;at<B;at++){let lt=O[at];if((lt===`
16
- `||lt==="\r")&&je.length>0){let ft=lt==="\r"&&O[at+1]===`
17
- `?at+2:at+1,dt=Wa(O,ft,B,je.splice(0));if(!dt.terminated)return-1;at=dt.next-1;continue}let ct=Xu(O,at,D,B,he);if(ct!==null){at=ct;continue}if(!he.double&&O.startsWith("$((",at)){let ft=Ky(O,at+3,B);if(ft===-1)return-1;at=ft+1;continue}if(X===")"&&!he.double&&lt==="<"&&O[at+1]==="<"&&O[at+2]!=="<"){let ft=O[at+2]==="-",dt=at+(ft?3:2);while(dt<B&&/[ \t]/.test(O[dt]??""))dt++;let ut=La(O,dt,B);if(ut){je.push({delimiter:ut.delimiter,quotedDelimiter:ut.quoted,stripTabs:ft,attach:()=>{return}}),at=ut.next-1;continue}}if(O.startsWith("$(",at)&&!O.startsWith("$((",at)){Q++,at++;continue}if(lt==="("&&!he.double)Q++;if(lt===")"&&!he.double){if(Q--,Q===0)return X==="))"&&O[at+1]!==")"?-1:at}}return-1}function Ky(O,D,B){let X=1,Q={single:!1,double:!1};for(let he=D;he<B;he++){let je=O[he],at=Xu(O,he,D,B,Q);if(at!==null){he=at;continue}if(O.startsWith("$(",he)&&!O.startsWith("$((",he)){X++,he++;continue}if(je==="("&&!Q.double)X++;if(je!==")"||Q.double)continue;if(X--,X===0)return O[he+1]===")"?he:-1}return-1}function Xu(O,D,B,X,Q){let he=O[D];if(he==="\\"&&!Q.single)return D+1;if(!Q.double&&he==="'")Q.single=!Q.single;if(!Q.single&&he==='"')Q.double=!Q.double;if(Q.single)return D;if(Q.double||he!=="#"||!mb(O,D,B))return null;let je=D;while(je+1<X&&O[je+1]!==`
18
- `&&O[je+1]!=="\r")je++;return je}function Oi(O,D){let B=O[D];if(B===";")return";";if(B==="&")return O[D+1]==="&"?"&&":"&";if(B==="|")return O[D+1]==="|"?"||":O[D+1]==="&"?"|&":"|";return null}function qy(O,D){let B=O[D];if(B===">"){if(O[D+1]===">")return">>";if(O[D+1]==="&")return">&";return O[D+1]==="|"?">|":">"}if(B!=="<")return null;if(O.startsWith("<<<",D))return"<<<";if(O.startsWith("<<-",D))return"<<-";if(O[D+1]==="<")return"<<";if(O[D+1]==="&")return"<&";if(O[D+1]===">")return"<>";return"<"}function Mi(O){let D=O.charCodeAt(0);if(D===32||D>=9&&D<=13)return!0;if(D<128)return!1;return/\s/u.test(O)}function Ju(O,D,B){if(O[D+1]==="{"){let Q=O.indexOf("}",D+2);return Q===-1||Q>=B?B:Q+1}let X=D+1;while(X<B&&/[A-Za-z0-9_?@#$!*-]/.test(O[X]??""))X++;return X===D+1?D+1:X}function Yy(O,D,B){let X="",Q=[],he=D;while(he<B){let je=O[he];if(je==="'")return{text:X,next:he+1,closed:!0,issues:Q};if(je!=="\\"){X+=je??"",he++;continue}let at=Zy(O,he+1,B);if(X+=at.text,at.invalidCodePoint!==void 0)Q.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${at.invalidCodePoint}`});he=at.next}return{text:X,next:B,closed:!1,issues:Q}}function Zy(O,D,B){let X=O[D];if(!X||D>=B)return{text:"\\",next:D};let Q=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
19
- `],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(Q.has(X))return{text:Q.get(X)??X,next:D+1};if(X==="x")return Ti(O,D+1,B,16,2,D+1);if(X==="u")return Ti(O,D+1,B,16,4,D+1);if(X==="U")return Ti(O,D+1,B,16,8,D+1);if(/[0-7]/.test(X))return Ti(O,D,B,8,3,D+1);return{text:X,next:D+1}}function Ti(O,D,B,X,Q,he){let je=X===16?/[0-9a-fA-F]/:/[0-7]/,at="",lt=D;while(lt<B&&at.length<Q&&je.test(O[lt]??""))at+=O[lt],lt++;if(!at)return{text:O[he-1]??"",next:he};let ct=Number.parseInt(at,X);return ct>1114111||ct>=55296&&ct<=57343?{text:"�",next:lt,invalidCodePoint:ct}:{text:String.fromCodePoint(ct),next:lt}}function Di(O,D=!1){if(D)return"limited";if(O.some((B)=>B.code==="invalid-ansi-c-code-point"||B.code==="missing-heredoc-delimiter"||B.code==="ambiguous-heredoc-delimiter"||B.code==="unterminated-heredoc"||B.code==="unsupported-heredoc-context"))return"invalid";return O.length>0?"partial":"complete"}function Qu(O,D,B,X,Q){let he=Ju(O,D,B);return{text:X+O.slice(D,he),provenance:Eo(Q,"variable"),next:he}}function Xy(O,D,B){let X=Ai(O),Q=D,he=!1,je=!1,at=D;while(at<B){let lt=O[at];if(lt==="\\"&&!he){at+=2;continue}if(!je&&lt==="'"){he=!he,at++;continue}if(!he&&lt==='"'){je=!je,at++;continue}if(he){at++;continue}let ct=O.startsWith("$((",at),ft=O.startsWith("$(",at)&&!ct,dt=!je&&(O.startsWith("<(",at)||O.startsWith(">(",at)),ut=lt==="`";if(ct||ft||dt||ut){let mt=ct?3:ut?1:2,pt=ct?"))":ut?"`":")",ht=Ba(O,at+mt,B,pt),gt=ht===-1?B:ht+pt.length;X.push(Q,at,"literal"),X.push(at,gt,ct?"arithmetic":"command-substitution"),at=gt,Q=gt;continue}if(lt==="$"){let mt=Ju(O,at,B);if(mt>at+1){X.push(Q,at,"literal"),X.push(at,mt,"variable"),at=mt,Q=mt;continue}}if(!je&&(lt==="*"||lt==="?"||lt==="[")){X.push(Q,at,"literal"),X.push(at,at+1,"glob"),at++,Q=at;continue}at++}return X.push(Q,B,"literal"),X.parts}function Eo(O,D){if(D==="command-substitution"||O==="command-substitution")return"command-substitution";if(D==="arithmetic"||O==="arithmetic")return"arithmetic";if(D==="variable"||O==="variable")return"variable";if(D==="glob"||O==="glob")return"glob";return O}function Jy(O,D,B){return D+1>=B||Mi(O[D+1]??"")||Oi(O,D+1)!==null}var Qy=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),eb=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function tb(O){let D=0;while(D<=O.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(O[D]?.text??""))D++;if(D===O.length)return!0;let B=nb(O,D);if(B===void 0||B===null)return!1;D=B}return!1}function nb(O,D){let B=O[D]?.text.toLowerCase();if(B==="command")return rb(O,D);if(B==="env")return ob(O,D);if(B==="sudo")return ib(O,D);return}function rb(O,D){if(O[D+1]?.text==="-v")return null;for(let B=D+1;B<O.length;B++){let X=O[B]?.text??"";if(X==="--")return B+1;if(X==="-p"||X==="-v"||X==="-V"||/^-[pvV]+$/.test(X))continue;return B}return O.length}function ob(O,D){for(let B=D+1;B<O.length;B++){let X=O[B]?.text??"";if(X==="--")return B+1;if(Qy.has(X)){if(O[B+1]===void 0)return null;B++;continue}if(X.startsWith("-u=")||X.startsWith("--unset=")||X.startsWith("-C")&&X.length>2||X.startsWith("--chdir=")||X.startsWith("-S")&&X.length>2||X.startsWith("--split-string=")||X.startsWith("-P"))continue;if(X.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(X))continue;return B}return O.length}function ib(O,D){for(let B=D+1;B<O.length;B++){let X=O[B]?.text??"";if(X==="--")return B+1;if(eb.has(X)){if(O[B+1]===void 0)return null;B++;continue}if(X.startsWith("-"))continue;return B}return O.length}function ed(O,D,B,X){if(O.provenance!=="literal"||!O.raw.includes("{"))return;let Q=td(O.raw,D,B,X,!0);if(!Q)return;if("limited"in Q)return{limited:!0};let he=Q.values.map((je)=>nd(je,B));if(he.some((je)=>je===null))return{limited:!0};return{words:[...new Set(he.filter((je)=>je!==null&&je!==""))]}}function sb(O,D,B,X,Q){if(D.provenance!=="literal"||!D.raw.includes("{"))return;let he=td(D.raw,B,X,Q,!1);if(!he)return;if("limited"in he){if(he.limited==="expansions")return{limitCode:"depth-limit"};return{limitCode:he.limited==="length"?"brace-expansion-limit":"word-limit"}}let je=he.values.map((at)=>nd(at,X));if(je.some((at)=>at===null))return;return{words:je.filter((at)=>at!==null&&at!=="").map((at)=>$r(O,D.span.start,D.span.end,at,"literal",!1))}}function td(O,D,B,X,Q){let he=[O],je=O.length,at=0;while(!0){let lt=he.findIndex((mt)=>Vu(mt,Q));if(lt===-1)break;if(++at>B)return{limited:"expansions"};let ct=he[lt]??"",ft=Vu(ct,Q);if(!ft||ft.kind==="range")return{limited:"expansions"};let dt=ft.start+ct.length-ft.end,ut=ft.alternatives.reduce((mt,pt)=>mt+dt+pt.length,0);if(je-ct.length+ut>X)return{limited:"length"};if(he.length-1+ft.alternatives.length>D)return{limited:"words"};he.splice(lt,1,...ab(ct,ft)),je+=ut-ct.length}return at===0?void 0:{values:he}}function Vu(O,D){let B=[],X,Q=null,he=!1;for(let je=0;je<O.length;je++){let at=O[je];if(he){he=!1;continue}if(at==="\\"&&Q!=="'"){he=!0;continue}if(at===Q){Q=null;continue}if(Q===null&&(at==="'"||at==='"')){Q=at;continue}if(Q!==null)continue;if(at==="{"){B.push({start:je,commas:[]});continue}if(at===","&&B.length>0){B.at(-1)?.commas.push(je);continue}if(at!=="}"||B.length===0)continue;let lt=B.pop();if(!lt)continue;let ct=lt.commas.length>0?{kind:"alternatives",start:lt.start,end:je+1,commas:lt.commas}:D&&cb(O.slice(lt.start+1,je))?{kind:"range",start:lt.start,end:je+1}:void 0;if(ct&&(!X||ct.start<X.start))X=ct}if(!X||X.kind==="range")return X;return{kind:X.kind,start:X.start,end:X.end,alternatives:lb(O,X)}}function ab(O,D){return D.alternatives.map((B)=>`${O.slice(0,D.start)}${B}${O.slice(D.end)}`)}function lb(O,D){let B=[D.start,...D.commas,D.end-1];return B.slice(0,-1).map((X,Q)=>O.slice(X+1,B[Q+1]))}function cb(O){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(O)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(O)}function nd(O,D){let B=`x${O}`,X=za(B,0,B.length,{maxInputLength:B.length,maxWords:1,maxDepth:D},{used:0,max:1},0);if(X.limited||X.issues.length>0||X.next!==B.length||X.word.provenance!=="literal")return null;return X.word.text.slice(1)}function ub(O,D,B,X){return an({kind:"program",dialect:"posix",source:O.slice(D,B),span:{start:D,end:B},status:"limited",issues:[{code:X,message:"command structure exceeds parser limit"}],nodes:[]})}function Ur(O,D,B,X,Q){return{nodes:O,issues:[...D,{code:X,message:`command structure exceeds parser limit ${Q}`}],next:B,closed:!1,limited:!0,pendingHeredocs:[]}}function Ii(O,D,B){return{nodes:O,issues:D,next:B,closed:!1,limited:!0,pendingHeredocs:[]}}function Fa(O){return O.used++,O.used<=O.max}function db(O,D,B){let X=O.slice(D,B),Q=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(X)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(X),he=Q?.[1];if(!Q||!he)return;return{name:he,braceIndex:D+Q[0].lastIndexOf("{")}}function Ro(O){return O.some((D)=>{if(D.kind==="command")return D.redirections.some((B)=>B.heredoc)||D.nested.some((B)=>Ro(B.nodes));return(D.kind==="group"||D.kind==="function")&&Ro(D.body.nodes)})}function fb(O){return O.map((D)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${D.delimiter} was not found`}))}function rd(O){return O?.kind==="command"||O?.kind==="group"||O?.kind==="function"}function Ku(O,D){let B=O.at(-1);if(B?.kind!=="connector"||!qu.has(B.operator))return;D.push({code:"missing-command-after-connector",message:`connector ${B.operator} requires a following command`})}function Ga(O,D){if(!rd(O.at(-1)))return;D.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function mb(O,D,B){return D===B||/[\s;&|()]/u.test(O[D-1]??"")}var id=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),pb=new Set(["gc","cat","type","cp","mv","rm"]),sd=["-rec","-for","-path","-literalpath","-whatif"],gb=/^\$env:\w/i,hb=/^(?:\$\{?\w+\}?|~)\\./;function ad(O,D){let B=O.toLowerCase().replaceAll("`","");if(![...id].some((Q)=>B.includes(Q))&&!(B.includes("rm")&&sd.some((Q)=>B.includes(Q)))&&!B.includes("<#")&&!yb(B))return!1;let X=ja(O,D);if(ld(X))return!1;return X.issues.some((Q)=>Q.code==="unclosed-block-comment"||Q.code==="comment-depth-limit")||Ha(X).some(bb)}function ld(O){return O.nodes.some((D)=>{if(D.kind==="group")return ld(D.body);if(D.kind!=="command")return!1;return D.redirections.some((B)=>B.operator==="<<")})}function yb(O){if(O.includes("$env:"))return!0;return O.includes("\\")&&(O.includes("$")||O.includes("~"))}function bb(O){let D=O[0]==="&"||O[0]==="."?1:0,B=O[D]?.toLowerCase();if(B&&id.has(B))return!0;let X=O.slice(D+1);if(B&&pb.has(B)&&X.some(Sb))return!0;if(B!=="rm")return!1;return X.some((Q)=>{let he=Q.toLowerCase().split(":",1)[0]??"";return sd.some((je)=>he.startsWith(je))})}function Sb(O){return gb.test(O)||hb.test(O)}function ja(O,D){let B={start:0,end:O.length};if(O.length>D.maxInputLength)return an({kind:"program",dialect:"powershell",source:O,span:B,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${D.maxInputLength} UTF-16 code units`}],nodes:[]});let X=Va(O,0,O.length,D,0);return an({kind:"program",dialect:"powershell",source:O,span:B,status:xb(X.issues,X.limited),issues:X.issues,nodes:X.nodes})}function Va(O,D,B,X,Q,he=!1){let je=[],at=[],lt=wi(),ct=0,ft=!1,dt=()=>{if(lt.words.length===0&&lt.redirections.length===0)return;let mt={start:lt.start,end:lt.end};Pi(je,lt,{kind:"command",dialect:"powershell",source:O.slice(mt.start,mt.end),span:mt,words:lt.words,redirections:lt.redirections,nested:lt.nested,displayText:lt.words.map((pt)=>pt.text).join(" ")})},ut=D;while(ut<B){let mt=O[ut];if(!mt)break;if(he&&mt==="}")return dt(),{nodes:je,issues:at,next:ut+1,closed:!0,words:ct,limited:ft};let pt=Rb(O,ut,B,X.maxDepth);if(pt){if(pt.issue)at.push(pt.issue);if(pt.limited)return dt(),{nodes:je,issues:at,next:pt.next,closed:!1,words:ct,limited:!0};ut=pt.next;continue}if(/\s/.test(mt)){if(mt==="\r"||mt===`
20
- `){dt();let yt=mt==="\r"&&O[ut+1]===`
21
- `?ut+2:ut+1;je.push($a(O,ut,yt)),ut=yt;continue}ut++;continue}let ht=dd(O,ut);if(ht){dt(),je.push($a(O,ut,ut+ht.length)),ut+=ht.length;continue}if(mt==="{"){if(dt(),Q>=X.maxDepth)return at.push(ud(X.maxDepth)),{nodes:je,issues:at,next:B,closed:!1,words:ct,limited:!0};let yt=Va(O,ut+1,B,X,Q+1,!0),vt=yt.closed?yt.next-1:yt.next,Et=an({kind:"program",dialect:"powershell",source:O.slice(ut+1,vt),span:{start:ut+1,end:vt},status:yt.limited?"limited":yt.issues.length>0?"partial":"complete",issues:yt.issues,nodes:yt.nodes});if(je.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:ut,end:yt.next}),body:Et})),at.push(...yt.issues),!yt.closed)at.push({code:"unclosed-script-block",message:"PowerShell script block is not closed"});ct+=yt.words,ft||=yt.limited,ut=yt.next;continue}if(mt==="}"){dt(),je.push($a(O,ut,ut+1)),ut++;continue}if(mt===">"||mt==="<"){lt.start=lt.start===-1?ut:lt.start;let yt=O[ut+1]===mt?ut+2:ut+1,vt=yt;while(/[ \t]/.test(O[vt]??""))vt++;let Et=vt<B?od(O,vt,B,X,Q):void 0,Ct=Et?.next??yt;if(lt.redirections.push(Object.freeze({kind:"redirection",operator:O.slice(ut,yt),span:Object.freeze({start:ut,end:Ct}),...Et?{target:Et.word}:{}})),Et)at.push(...Et.issues),lt.nested.push(...Et.nested),ct+=Et.words,ft||=Et.limited;lt.end=Ct,ut=Ct;continue}if(mt===","){lt.start=lt.start===-1?ut:lt.start,lt.words.push(Na({text:",",raw:",",span:{start:ut,end:ut+1},provenance:"literal",quoted:!1})),lt.end=++ut;continue}let gt=od(O,ut,B,X,Q);if(lt.start=lt.start===-1?ut:lt.start,lt.end=gt.next,lt.words.push(gt.word),at.push(...gt.issues),lt.nested.push(...gt.nested),ct+=1+gt.words,ft||=gt.limited,ct>X.maxWords)return at.push({code:"word-limit",message:`command exceeds ${X.maxWords} words`}),dt(),{nodes:je,issues:at,next:gt.next,closed:!1,words:ct,limited:!0};ut=gt.next>ut?gt.next:ut+1}return dt(),{nodes:je,issues:at,next:ut,closed:!he,words:ct,limited:ft}}function od(O,D,B,X,Q){let he="",je="literal",at=!1,lt=[],ct=[],ft=0,dt=!1,ut=(pt)=>{let ht=Cb(O,pt,B,X,Q);return he+=O.slice(pt,ht.next),ct.push(ht.program),lt.push(...ht.program.issues),ft+=Ua(ht.program),dt||=ht.program.status==="limited",je="command-substitution",ht.next},mt=D;while(mt<B){let pt=O[mt];if(!pt||/\s/.test(pt)||dd(O,mt)||pt===">"||pt==="<"||pt==="#")break;if(pt===",")break;if(pt==="`"){let ht=O[mt+1];if(!ht){lt.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),mt++;break}he+=ht,mt+=2;continue}if(O.startsWith("$(",mt)){mt=ut(mt);continue}if(pt==="'"){at=!0,mt++;let ht=!1;while(mt<O.length){if(O[mt]==="'"&&O[mt+1]==="'"){he+="'",mt+=2;continue}if(O[mt]==="'"){ht=!0,mt++;break}he+=O[mt]??"",mt++}if(!ht)lt.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(pt==='"'){at=!0,mt++;let ht=!1;while(mt<B){let gt=O[mt];if(gt==="`"&&O[mt+1]){he+=O[mt+1],mt+=2;continue}if(gt==='"'){ht=!0,mt++;break}if(O.startsWith("$(",mt)){mt=ut(mt);continue}if(gt==="$")je=O[mt+1]==="("?"command-substitution":"variable";he+=gt??"",mt++}if(!ht)lt.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(pt==="$")je=O[mt+1]==="("?"command-substitution":"variable";if(pt==="@"&&mt===D)je="variable";he+=pt,mt++}return{word:$r(O,D,mt,he,je,at,je==="literal"?void 0:vb(O,D,mt)),next:mt,issues:lt,nested:ct,words:ft,limited:dt}}function Cb(O,D,B,X,Q){let he=cd(O,D+2,B),je=he===-1?B:he,at=he===-1?B:he+1;if(Q>=X.maxDepth)return{program:an({kind:"program",dialect:"powershell",source:O.slice(D+2,je),span:{start:D+2,end:je},status:"limited",issues:[ud(X.maxDepth)],nodes:[]}),next:at};let lt=Va(O,D+2,je,X,Q+1),ct=he===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:an({kind:"program",dialect:"powershell",source:O.slice(D+2,je),span:{start:D+2,end:je},status:lt.limited?"limited":lt.issues.length+ct.length>0?"partial":"complete",issues:[...lt.issues,...ct],nodes:lt.nodes}),next:at}}function cd(O,D,B){let X=1,Q=!1,he=!1;for(let je=D;je<B;je++){let at=O[je];if(at==="`"){je++;continue}if(!he&&at==="'"){if(Q&&O[je+1]==="'"){je++;continue}Q=!Q;continue}if(!Q&&at==='"'){he=!he;continue}if(Q)continue;if(O.startsWith("$(",je)){X++,je++;continue}if(!he&&at==="(")X++;if(at!==")")continue;if(X--,X===0)return je}return-1}function Ua(O){let D=0;for(let B of O.nodes){if(B.kind==="group")D+=Ua(B.body);if(B.kind==="command"){D+=B.words.length;for(let X of B.nested)D+=Ua(X)}}return D}function vb(O,D,B){let X=Ai(O),Q=D,he=!1,je=D;while(je<B){let at=O[je];if(at==="`"){je+=2;continue}if(at==="'"){if(he&&O[je+1]==="'"){je+=2;continue}he=!he,je++;continue}if(he){je++;continue}if(O.startsWith("$(",je)){let lt=cd(O,je+2,B),ct=lt===-1?B:lt+1;X.push(Q,je,"literal"),X.push(je,ct,"command-substitution"),je=ct,Q=ct;continue}if(at==="$"||at==="@"&&je===D){let lt=Eb(O,je+1,B);X.push(Q,je,"literal"),X.push(je,lt,"variable"),je=lt,Q=lt;continue}je++}return X.push(Q,B,"literal"),X.parts}function Eb(O,D,B){if(O[D]==="{"){let Q=O.indexOf("}",D+1);return Q===-1||Q>=B?B:Q+1}let X=D;while(X<B&&/[A-Za-z0-9_:?]/.test(O[X]??""))X++;return X}function ud(O){return{code:"depth-limit",message:`command structure exceeds parser limit ${O}`}}function Ha(O){return O.nodes.flatMap((D)=>{if(D.kind==="group")return Ha(D.body);if(D.kind!=="command")return[];return[[...D.words,...D.redirections.flatMap((B)=>B.target?[B.target]:[])].sort((B,X)=>B.span.start-X.span.start).filter((B)=>B.text!==""&&B.raw!==",").map((B)=>B.text),...D.nested.flatMap(Ha)]})}function dd(O,D){for(let B of["&&","||",";","|"])if(O.startsWith(B,D))return B;return null}function Rb(O,D,B,X){if(O[D]==="#"&&O[D+1]!==">"){let je=D+1;while(je<B&&O[je]!=="\r"&&O[je]!==`
22
- `)je++;return{next:je,limited:!1}}if(!O.startsWith("<#",D))return null;let Q=1,he=D+2;while(he<B){if(O.startsWith("<#",he)){if(Q++,Q>X)return{next:B,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${X}`},limited:!0};he+=2;continue}if(O.startsWith("#>",he)){if(Q--,he+=2,Q===0)return{next:he,limited:!1};continue}he++}return{next:B,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function xb(O,D){if(D)return"limited";if(O.some((B)=>B.code==="unclosed-block-comment"))return"invalid";return O.length>0?"partial":"complete"}function $a(O,D,B){return Object.freeze({kind:"connector",operator:O.slice(D,B),span:Object.freeze({start:D,end:B})})}function h(O,D="auto",B=er){if(D==="powershell"||D==="auto"&&ad(O.slice(0,B.maxInputLength),B))return ja(O,B);return Yu(O,B)}function t(O){return O.provenance==="command-substitution"?O.raw:O.text}function Z(O,D){return O==="posix"?D:$t(D.map((B)=>B.text))}function Li(O,D){return O&&O.provenance!=="unknown"?O.provenance==="literal":!/[$`*?[\]]/.test(D)}function $t(O){return O.map((D)=>({kind:"word",text:D,raw:D,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function Ka(O,D){return{value:O,work:D}}function bt(O,D){if(O.work)O.work.units=Math.min(Number.MAX_SAFE_INTEGER,O.work.units+1);return O.value[D]}function Ht(O){return O.value.length}function xo(O,D,B=1){if(O)O.units=Math.min(Number.MAX_SAFE_INTEGER,O.units+D.length*B)}function yn(O,D){xo(O,D)}function br(O){if(!O)return!1;let D=O.charCodeAt(0);return D>=48&&D<=57||D>=65&&D<=90||D===95||D>=97&&D<=122}function zt(O){if(!O)return!1;let D=O.charCodeAt(0);return D===9||D===10||D===11||D===12||D===13||D===32||D===160||D===65279||D===5760||D>=8192&&D<=8202||D===8232||D===8233||D===8239||D===8287||D===12288}function qa(O){return O===`
23
- `||O==="\r"||O==="\u2028"||O==="\u2029"}function Bt(O,D,B){if(D+B.length>Ht(O))return!1;for(let X=0;X<B.length;X++)if(bt(O,D+X)!==B[X])return!1;return!0}function zn(O,D,B){return!br(bt(O,D-1))&&Bt(O,D,B)&&!br(bt(O,D+B.length))}function Bn(O,D){return br(bt(O,D-1))!==br(bt(O,D))}function Qt(O){return O===`
24
- `||O===";"||O==="&"||O==="|"}function Hr(O){return O==="|"||O===";"}function Wi(O,D,B){let X=Ka(O,B);if(D==="rm")return _b(X);if(D==="dd")return Pb(X);return yd(X,!0)}function Fi(O,D,B){let X=Ka(O,B);if(D==="rm")return Ab(X);if(D==="reset-hard")return gd(X,"--ha","rd");if(D==="reset-merge")return gd(X,"--me","rge");if(D==="clean")return Ob(X);if(D==="checkout")return Db(X);if(D==="push-force")return Nb(X);if(D==="push-refspec")return Lb(X);if(D==="push-delete")return Wb(X);if(D==="branch")return Fb(X);if(D==="tag")return Bb(X);if(D==="restore")return $b(X);return yd(X,!1)}function _b(O){let D=!1,B=!1,X=!1,Q=-1;for(let he=0;he<=Ht(O);he++){let je=bt(O,he);if(!D){let lt=bt(O,he+2);if(zn(O,he,"rm")&&zt(lt)&&lt!==`
25
- `)D=!0,he++;continue}let at=wb(O,he);if(je===`
26
- `||at!==-1){if(D=!1,B=!1,X=!1,Q=-1,at!==-1)he=at-1;continue}if(je===";"||je==="&"||je==="|"||he===Ht(O)){if(Q>=0){let lt=fd(O,Q,he);B||=lt.recursive,X||=lt.force}if(B&&X)return!0;D=!1,B=!1,X=!1,Q=-1;continue}if(zt(je)){if(Q<0)continue;if(Bt(O,Q,"--")&&he-Q===2){D=!1,B=!1,X=!1,Q=-1;continue}let lt=fd(O,Q,he);if(B||=lt.recursive,X||=lt.force,B&&X)return!0;Q=-1;continue}if(Q<0)Q=he}return!1}function wb(O,D){if(bt(O,D)!=="\\"||bt(O,D-1)==="\\")return-1;if(Bt(O,D,String.raw`\n`))return D+2;if(Bt(O,D,String.raw`\x0a`)||Bt(O,D,String.raw`\x0A`))return D+5;if(Bt(O,D,String.raw`\u000a`)||Bt(O,D,String.raw`\u000A`))return D+7;return Bt(O,D,String.raw`\012`)?D+4:-1}function fd(O,D,B){if(md(O,D,B,"recursive"))return{recursive:!0,force:!1};if(md(O,D,B,"force"))return{recursive:!1,force:!0};if(bt(O,D)!=="-"||bt(O,D+1)==="-")return{recursive:!1,force:!1};let X=!1,Q=!1;for(let he=D+1;he<B;he++){let je=bt(O,he);X||=je==="r"||je==="R",Q||=je==="f"||je==="F"}return{recursive:X,force:Q}}function md(O,D,B,X){let Q=B-D-2;if(Q<1||Q>X.length||!Bt(O,D,"--"))return!1;for(let he=0;he<Q;he++)if(bt(O,D+he+2)!==X[he])return!1;return!0}function Pb(O){let D=!1;for(let B=0;B<Ht(O);B++){if(Qt(bt(O,B))){D=!1;continue}if(zn(O,B,"dd")){D=!0,B++;continue}if(!D||!zn(O,B,"of")||!Bt(O,B,"of=/dev/"))continue;let X=B+8;if(X<Ht(O)&&!zt(bt(O,X))&&bt(O,X)!=="'"&&bt(O,X)!=='"')return!0}return!1}function Ab(O){let D=!1,B=!1,X=!1;for(let Q=0;Q<=Ht(O);){let he=bt(O,Q);if(Q===Ht(O)||Qt(he)){D=!1,B=!1,X=!1,Q++;continue}let je=Ib(O,Q);if(je>=0){if(Tb(O,je))return!0;let at=je,lt=!1;while(zt(bt(O,at)))lt||=bt(O,at)===`
27
- `,at++;if(lt)B=!1,X=!1;D=!0,Q=at;continue}if(!D){Q++;continue}if(Bt(O,Q,"--")&&(Q===0||zt(bt(O,Q-1)))&&(!bt(O,Q+2)||zt(bt(O,Q+2))||Qt(bt(O,Q+2)))){D=!1,B=!1,X=!1,Q+=2;continue}if(B||=Bt(O,Q,"--recursive")&&Bn(O,Q+11)||Ya(O,Q,"recursive"),X||=Bt(O,Q,"--force")&&Bn(O,Q+7)||Ya(O,Q,"force"),B&&X)return!0;Q++}return!1}function Ya(O,D,B){if(!Bt(O,D,"--"))return!1;let X=0;while(X<=B.length){let Q=bt(O,D+X+2);if(!Q||zt(Q)||Qt(Q))break;if(Q!==B[X])return!1;X++}return X>0&&Bn(O,D+X+2)}function Tb(O,D){let B=D,X=!1,Q=!1;while(B<Ht(O)){while(zt(bt(O,B)))B++;let he=B;while(B<Ht(O)&&!zt(bt(O,B)))B++;if(bt(O,he)!=="-"||B-he===2&&Bt(O,he,"--"))return!1;let je=pd(O,he,"recursive"),at=pd(O,he,"force");if(X&&at||Q&&je)return!0;if(X||=je,Q||=at,bt(O,he+1)==="-")continue;let lt=kb(O,he,B);if(lt.combined||X&&lt.forceAtBoundary||Q&&lt.recursiveAtBoundary)return!0;X||=lt.recursive,Q||=lt.force}return!1}function pd(O,D,B){return Bt(O,D,`--${B}`)&&Bn(O,D+B.length+2)||Ya(O,D,B)}function Ib(O,D){if(D>0&&br(bt(O,D-1)))return-1;let B=D;if(bt(O,B)==="\\")B++;if(bt(O,B)!=="r")return-1;if(B++,bt(O,B)==="\\")B++;if(bt(O,B)!=="m"||!zt(bt(O,B+1)))return-1;return B+1}function kb(O,D,B){let X=!1,Q=!1,he=!1,je=!1,at=!1;if(bt(O,D)!=="-")return{recursive:X,force:Q,recursiveAtBoundary:he,forceAtBoundary:je,combined:at};let lt="";for(let ct=D+1;ct<B;ct++){let ft=bt(O,ct)??"",dt=(ft==="r"||ft==="f")&&Bn(O,ct+1);X||=ft==="r",Q||=ft==="f",he||=ft==="r"&&dt,je||=ft==="f"&&dt,at||=(lt==="r"&&ft==="f"||lt==="f"&&ft==="r")&&dt,lt=ft}return{recursive:X,force:Q,recursiveAtBoundary:he,forceAtBoundary:je,combined:at}}function gd(O,D,B){return wo(O,"reset",Hr,!0,(X)=>bt(O,X)==="-"&&jr(O,X,D,B)?!0:X)}function Ob(O){return wo(O,"clean",Hr,!0,(D)=>{if(bt(O,D)!=="-")return D;if(jr(O,D,"--fo","rce"))return!0;let B=_o(O,D,Hr);for(let X=D+1;X<B;X++)if(bt(O,X)==="f")return!0;return B-1})}function Gi(O,D,B){if(!zn(O,D,"git"))return null;let X=D+3;if(!zt(bt(O,X)))return{commandEnd:-1,next:X};while(zt(bt(O,X)))X++;while(X<Ht(O)){if(Qt(bt(O,X)))return{commandEnd:-1,next:X};let Q=_o(O,X,Qt);if(zn(O,X,B))return{commandEnd:X+B.length,next:Q};if(bt(O,X)!=="-")return{commandEnd:-1,next:Q};let he=Q-X===2&&Bt(O,X,"--"),je=Mb(O,X,Q);X=Q;while(zt(bt(O,X)))X++;if(he)return{commandEnd:zn(O,X,B)?X+B.length:-1,next:_o(O,X,Qt)};if(!je)continue;if(X>=Ht(O)||Qt(bt(O,X)))return{commandEnd:-1,next:X};X=_o(O,X,Qt);while(zt(bt(O,X)))X++}return{commandEnd:-1,next:X}}function Mb(O,D,B){for(let X of pn)if(B-D===X.length&&Bt(O,D,X))return!0;return!1}function Db(O){return hd(O,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function Nb(O){return wo(O,"push",Hr,!0,(D)=>{if(bt(O,D)!=="-")return D;if(bt(O,D+1)==="f"&&!br(bt(O,D+2))&&!Bt(O,D+2,"-with-lease"))return!0;let B=bd(O,D,"--fo","rce");if(B>=0&&!Bt(O,B,"-with-lease"))return!0;return D})}function Lb(O){return wo(O,"push",Qt,!1,(D)=>{if(zt(bt(O,D))&&bt(O,D+1)==="+"&&D+2<Ht(O)&&!Qt(bt(O,D+2))&&!zt(bt(O,D+2)))return!0;if(bt(O,D)===":"&&bt(O,D+1)==="+")return!0;return D})}function Wb(O){return wo(O,"push",Qt,!1,(D)=>{if(bt(O,D)==="-"&&jr(O,D,"--de","lete"))return!0;if(zt(bt(O,D))&&bt(O,D+1)===":"&&D+2<Ht(O)&&!zt(bt(O,D+2))&&!Qt(bt(O,D+2)))return!0;return D})}function Fb(O){let D=!1,B=!1,X=!1;for(let Q=0;Q<=Ht(O);Q++){if(Q===Ht(O)||Qt(bt(O,Q))){if(B&&X)return!0;D=!1,B=!1,X=!1;continue}if(!D){let at=Gi(O,Q,"branch");if(at){D=at.commandEnd>=0,Q=Math.max(Q,(D?at.commandEnd:at.next)-1);continue}}if(!D||bt(O,Q)!=="-")continue;let he=_o(O,Q,Qt),je=Gb(O,Q,he);if(B||=je.deletion,X||=je.force,B&&X)return!0;Q=he-1}return!1}function Gb(O,D,B){let X=!1,Q=!1;for(let he=D;he<B;he++){if(bt(O,he)!=="-")continue;if(jr(O,he,"--de","lete"))X=!0;if(jr(O,he,"--fo","rce"))Q=!0;if(bt(O,he+1)==="-")continue;let je=he+1,at=!1,lt=!1,ct=!1;while(je<B&&zb(bt(O,je))){let ft=bt(O,je);at||=ft==="d"||ft==="D",lt||=ft==="f",ct||=ft==="D",je++}if(!Bn(O,je))continue;X||=at,Q||=lt||ct}return{deletion:X,force:Q}}function zb(O){if(!O)return!1;let D=O.charCodeAt(0);return D>=65&&D<=90||D>=97&&D<=122}function Bb(O){return hd(O,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function hd(O,D){let B=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let X=0;X<Ht(O);X++){let Q=bt(O,X),he=B[B.length-1];if(!he)return!1;let je=he.escaped;if(he.escaped=!je&&he.quote!=="'"&&Q==="\\",!je&&Q==="'"&&he.quote!=='"')he.quote=he.quote==="'"?"":"'";if(!je&&Q==='"'&&he.quote!=="'")he.quote=he.quote==='"'?"":'"';if(Q==="$"&&bt(O,X+1)==="("&&(B.length===1||!je&&he.quote!=="'")){B.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),X++;continue}if(!je&&!he.quote&&B.length>1&&Q==="("){he.depth++;continue}if(!je&&!he.quote&&B.length>1&&Q===")"){if(he.depth--,he.depth===0)B.pop();continue}if(zt(Q))he.shortActive=!1,he.hasShortFlag=!1;if(!he.outerActive){let at=Gi(O,X,D.command);if(at){he.outerActive=at.commandEnd>=0&&zt(bt(O,at.commandEnd)),he.shortActive=!1,he.hasShortFlag=!1,X=Math.max(X,(he.outerActive?at.commandEnd:at.next)-1);continue}}if(he.outerActive&&Q==="-"){if(jr(O,X,D.longPrefix,D.longOptional))return!0;he.shortActive||=!D.excludedShortStarts.includes(bt(O,X+1)??"")}if(he.hasShortFlag||=he.shortActive&&Q===D.shortFlag,he.hasShortFlag&&Bn(O,X+1))return!0;if(Hr(Q))he.outerActive=!1}return!1}function wo(O,D,B,X,Q){let he=!1;for(let je=0;je<Ht(O);je++){let at=bt(O,je),lt=B(at);if(!he&&!lt){let ct=Gi(O,je,D);if(ct){he=ct.commandEnd>=0&&(!X||zt(bt(O,ct.commandEnd))),je=Math.max(je,(he?ct.commandEnd:ct.next)-1);continue}}if(he){let ct=Q(je);if(ct===!0)return!0;for(let ft=je;ft<=ct;ft++)if(B(bt(O,ft)))he=!1;je=ct}if(lt)he=!1}return!1}function $b(O){let D=!1;for(let B=0;B<Ht(O);B++){if(qa(bt(O,B))){if(D)return!0;D=!1;continue}if(!D){let X=Gi(O,B,"restore");if(X){D=X.commandEnd>=0,B=Math.max(B,(D?X.commandEnd:X.next)-1);continue}}if(D&&bt(O,B)==="-"&&bt(O,B+1)==="-"&&(Bt(O,B+2,"staged")||Bt(O,B+2,"help")))D=!1}return D}function yd(O,D){let B=!1;for(let X=0;X<Ht(O);X++){let Q=bt(O,X),he=D?qa(Q):Qt(Q);if(B&&zt(Q)&&bt(O,X+1)==="-"&&zn(O,X+2,"delete"))return!0;if(he){B=!1;continue}if(zn(O,X,"find"))B=!0,X+=3}return!1}function _o(O,D,B){let X=D;while(X<Ht(O)&&!zt(bt(O,X))&&!B(bt(O,X)))X++;return X}function bd(O,D,B,X){if(!Bt(O,D,B))return-1;let Q=D+B.length;for(let he=0;he<X.length&&bt(O,Q)===X[he];he++)Q++;return Bn(O,Q)?Q:-1}function jr(O,D,B,X){return bd(O,D,B,X)>=0}function $n(O,D){xo(D,O,2);let B=O.toLowerCase(),X=B.trimStart(),Q=X.startsWith("echo ")||X.startsWith("rg "),he=[{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 je of he){if(je.skipForEchoRg&&Q)continue;let at=je.caseSensitive?O:B;if(je.regex)yn(D,at);if((je.regex?.test(at)??!1)||je.scan&&Fi(at,je.scan,D))return St("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${je.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var Ub=/^[A-Za-z_][A-Za-z0-9_]*=/;function Cd(O,D,B){let X=O.words[0];if(!D||!X||O.words.length!==1||O.dialect!=="posix")return!1;if(!X.quoted||X.provenance!=="literal")return!1;let Q=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(X.text)?.[1];if(!Q)return!1;xo(B,D.source,2);let he={anchored:new RegExp(`^\\$\\{?${Q}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${Q}(?![A-Za-z0-9_])`)};return vd(D.nodes,X,he)}function vd(O,D,B){return O.every((X)=>{if(X.kind==="connector")return!0;if(X.kind==="group"||X.kind==="function")return vd(X.body.nodes,D,B);if(X.kind==="unknown")return!B.loose.test(X.source);return Hb(X,D,B)})}function Hb(O,D,B){if(O.nested.some((Q)=>B.loose.test(Q.source)))return!1;let X=O.words.findIndex((Q)=>!Ub.test(Q.text));return O.words.every((Q,he)=>Q===D||Sd(Q.raw,B.anchored,he!==X))&&O.redirections.every((Q)=>(!Q.heredoc||Q.heredoc.quotedDelimiter||!B.loose.test(Q.heredoc.body))&&(!Q.target||Sd(Q.target.raw,B.anchored,!0)))}function Sd(O,D,B){let X=!1,Q=!1;for(let he=0;he<O.length;he++){let je=O[he];if(je==="\\"&&!X){he++;continue}if(!Q&&je==="'"){X=!X;continue}if(!X&&je==='"'){Q=!Q;continue}if(X||je!=="$")continue;if(!D.test(O.slice(he)))continue;if(!Q||!B)return!1}return!0}import{isAbsolute as jb,resolve as Ed}from"node:path";function Po(O,D,B,X){let Q=jb(O)?Ed(O):D?Ed(D,O):void 0;if(!Q)return;try{return Lt(Q,B,X)}catch{return Q}}function Rd(O){return!["/dev","/proc","/sys"].some((D)=>O===D||O.startsWith(`${D}/`))}var Vr="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",Ao="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.",Za=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),Vb=new Set(["-p","--print"]),Kb=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),qb=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"])]]),Yb=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),Zb=new Map([["python",new Set(["m"])]]),Xb=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"])]]),Jb=new Set(["always","default","never"]),Qb=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),eS=/\\\r?\n/g,tS=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 _d(O){return Bi(O).code}function zi(O){return Bi(O).sources}function wd(O){return tS.get(Ja(O))??[]}function Bi(O){let D=Ja(O[0]??"");if(!Za.has(D))return{code:null,sources:[],optionsOpen:!1};let B=[],X=[],Q=!0;for(let he=1;he<O.length;he++){let je=O[he];if(je===void 0)break;if(je==="--")return Pn(D,B,X,Q,O[he+1]===void 0?void 0:he+1,O[he+1]);if(je===""||je==="-"||!je.startsWith("-"))return Pn(D,B,X,Q,he,je);if(D==="node"&&Vb.has(je)){let dt=O[he+1];if(dt===void 0)return Pn(D,B,X,Q);if(dt.startsWith("-"))continue;B.push({tokenIndex:he+1,value:dt}),X.push({tokenIndex:he+1,kind:"inline-code",value:dt}),he++;continue}if(rS(D,je)){let dt=O[he+1];if(dt===void 0)return Pn(D,B,X,Q);if(B.push({tokenIndex:he+1,value:dt}),X.push({tokenIndex:he+1,kind:"inline-code",value:dt}),D==="python")return Pn(D,B,X,Q);he++;continue}let at=/^--eval=(.*)$/s.exec(je);if(oS(D)&&at){let dt=at[1]??"";B.push({tokenIndex:he,value:dt}),X.push({tokenIndex:he,kind:"inline-code",value:dt});continue}if(D==="node"){let dt=nS(je);if(dt){if(dt.attached){if(Q&&=dt.value!=="",dt.value!=="")X.push({tokenIndex:he,kind:"module-file",value:dt.value});continue}let ut=O[he+1];if(ut===void 0||ut.startsWith("-"))return Q=!1,Pn(D,B,X,Q);X.push({tokenIndex:he+1,kind:"module-file",value:ut}),he++;continue}}if(D==="python"&&je.startsWith("--check-hash-based-pycs=")||D==="node"&&(je==="--conditions="||je==="--diagnostic-dir="||je==="--title=")||D==="ruby"&&(je==="--disable="||je==="--enable="))return Pn(D,B,X,Q);if(Xb.get(D)?.has(je)){let dt=O[he+1];if(dt===void 0||dt.startsWith("-")&&!(D==="ruby"&&Qb.has(je))||D==="python"&&!Jb.has(dt))return Pn(D,B,X,Q);he++;continue}if(je.startsWith("--"))continue;let lt,ct=!1;for(let dt=1;dt<je.length;dt++){let ut=je[dt];if(ut===void 0)break;if(Zb.get(D)?.has(ut)){let mt=je.slice(dt+1),pt=mt||O[he+1];if(pt!==void 0)X.push({tokenIndex:mt?he:he+1,kind:"module-file",value:pt});return Pn(D,B,X,Q)}if(Kb.get(D)?.has(ut)){lt=je.slice(dt+1)||O[he+1],ct=dt+1===je.length;break}if(D==="node"&&ut==="r"){if(Q&&=je==="-r",je==="-r"){let mt=O[he+1];if(Q&&=mt!==void 0&&!mt.startsWith("-"),Q&&mt!==void 0)X.push({tokenIndex:he+1,kind:"module-file",value:mt});he++}break}if(D==="ruby"&&ut==="r"){let mt=je.slice(dt+1),pt=mt||O[he+1];if(Q&&=pt!==void 0,pt!==void 0)X.push({tokenIndex:mt?he:he+1,kind:"module-file",value:pt});if(!mt)he++;break}if(D==="perl"&&(ut==="M"||ut==="m")){let mt=je.slice(dt+1);if(!mt){if(Q=!1,dt+1===je.length)he++;break}X.push({tokenIndex:he,kind:"module-file",value:mt});break}if(qb.get(D)?.has(ut)){if(dt+1===je.length)he++;break}if(Yb.get(D)?.has(ut)&&dt+1<je.length)break}if(lt===void 0)continue;let ft=ct?he+1:he;if(B.push({tokenIndex:ft,value:lt}),X.push({tokenIndex:ft,kind:"inline-code",value:lt}),D==="python")return Pn(D,B,X,Q);if(ct)he++}return Pn(D,B,X,Q,void 0,void 0,!0)}function Pn(O,D,B,X,Q,he,je=!1){let at=O==="node"?D.slice(-1):D,lt=new Set(at.map((ft)=>ft.tokenIndex)),ct=B.filter((ft)=>ft.kind!=="inline-code"||lt.has(ft.tokenIndex));if(X&&D.length===0&&Q!==void 0&&he!==void 0)ct.push({tokenIndex:Q,kind:"main-script",value:he});return{code:(O==="node"?at[0]?.value:at.map((ft)=>ft.value).join(`
28
- `))||null,sources:X?ct:[],optionsOpen:X&&je}}function nS(O){for(let D of["--import","--loader","--experimental-loader","--require"]){if(O===D)return{attached:!1,value:""};if(O.startsWith(`${D}=`))return{attached:!0,value:O.slice(D.length+1)}}return}function Xa(O,D){return Ja(O)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(D)}function Ja(O){let D=Tt(O).toLowerCase();return mi.test(D)?"python":D}function rS(O,D){return Za.get(O)?.has(D)??!1}function oS(O){return Za.get(O)?.has("--eval")??!1}function To(O,D){let B=aS(O,D);if(!xd(B,D))return!1;yn(D,B);let X=sS(B);if(xd(X,D))return!0;return yn(D,X),iS.test(X)}var iS=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function sS(O){let D=[],B=0,X=0;while(X<O.length){let Q=O[X];if(Q!=="'"&&Q!=='"'){X++;continue}let he=O.startsWith(Q.repeat(3),X)?Q.repeat(3):Q,je=X+he.length;while(je<O.length&&!O.startsWith(he,je))je+=O[je]==="\\"?2:1;if(je>=O.length)break;D.push(O.slice(B,X)," "),X=je+he.length,B=X}return D.push(O.slice(B)),D.join("")}function xd(O,D){if(Wi(O,"rm",D))return!0;for(let X of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(yn(D,O),X.test(O))return!0;if(Wi(O,"dd",D))return!0;for(let X of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(yn(D,O),X.test(O))return!0;if(Wi(O,"find",D))return!0;let B=O.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((X)=>(yn(D,O),B.some((Q)=>Fi(Q,X))))}function aS(O,D){return yn(D,O),O.replace(eS,"")}import{isAbsolute as Jd,relative as Qd}from"node:path";import{isAbsolute as Md,parse as yS}from"node:path";import{dirname as lS,isAbsolute as cS,parse as uS,sep as dS}from"node:path";function tr(O,D,B){if(Jn(D))throw Error("Unsupported Windows namespace path");let X=cS(D)?uS(D).root:"",Q=X||O;for(let he of mS(X?D.slice(X.length):D)){if(he===""||he===".")continue;if(he===".."){Q=lS(Q);continue}let je=fS(Q,he),at=B.entryKind(je),lt=at==="symlink"?B.realpath(je):je;if(at==="missing"||lt===null)throw Error(`Cannot resolve path component: ${je}`);Q=lt}return Q}function fS(O,D){return O.endsWith("/")||O.endsWith("\\")?`${O}${D}`:`${O}${dS}${D}`}function mS(O){let D=process.platform==="win32"?/[\\/]+/:/\/+/;return O.split(D)}var Qa=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],pS=new Set(Qa),gS=1024,Pd=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),Ad=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),hS=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function $i(O){return pS.has(O)}function el(O){return $i(O)||Pd.has(O)||Ad.has(O)||co(O)}function Un(O,D,B){return B?.has(O)?B.get(O):D.get(O)}function Td(O,D){let B=Un("GIT_CONFIG_COUNT",O,D);if(B===void 0)return{state:"absent"};if(B==="")return{state:"valid",count:0};if(!/^\d+$/.test(B))return{state:"invalid"};let X=Number(B);return Number.isSafeInteger(X)&&X<=gS?{state:"valid",count:X}:{state:"invalid"}}function Ui(O,D,B){let Q=O.match(hS)?.[1];if(!Q||!el(Q))return null;let he=O.indexOf("=");return{name:Q,value:`${Un(Q,D,B)??""}${O.slice(he+1)}`}}function Id(O){return Od(O,Ad)}function kd(O){return Od(O,Pd)}function Od(O,D){if(!O)return!1;for(let B of O.keys())if(D.has(B))return!0;return!1}var Nd=/^[A-Za-z_][A-Za-z0-9_]*=/;function En(O){if(!Nd.test(O))return null;let D=O.indexOf("=");return{name:O.slice(0,D),value:O.slice(D+1)}}function ge(O){let D=new Map,B=0;while(B<O.length){let X=O[B];if(!X)break;let Q=En(t(X));if(!Q)break;D.set(Q.name,Q.value),B++}return{words:O.slice(B),envAssignments:D}}function Ld(O){let D=O.toLowerCase();return O.includes("=")||D==="sudo"||D==="env"||D==="command"||D==="builtin"}function Sr(O,D,B,X){if(!Ld(Kr(O)))return{words:O,envAssignments:new Map,cwd:B,rewritten:!1};let Q=new Set(O),he=O,je=new Map,at=new Map(X??[]),lt=[],ct=B;for(let dt=0;dt<a.wrapperPeelIterations.cap;dt++){let ut=Dd(he),mt=ge(he);for(let[ht,gt]of mt.envAssignments)je.set(ht,gt),at.set(ht,gt);if(he=mt.words,he.length===0)break;while(he.length>0&&Kr(he).includes("=")&&!SS(he)){let ht=CS(Kr(he),at,D.env)??Ui(Kr(he),D.env,at);if(ht)je.set(ht.name,ht.value),at.set(ht.name,ht.value);he=he.slice(1)}if(he.length===0)break;let pt=Kr(he).toLowerCase();if(pt!=="sudo"&&pt!=="env"&&pt!=="command"&&pt!=="builtin")break;if(pt==="sudo"){let ht=ES(he,D.paths,ct);if(he=ht.words,ht.cwd!==void 0)ct=ht.cwd}if(pt==="env"){let ht=_S(he,ct,at,D);if(lt.push(...ht.envSplitValues??[]),he=ht.words,ht.cwd!==void 0)ct=ht.cwd;for(let[gt,yt]of ht.envAssignments)je.set(gt,yt),at.set(gt,yt)}if(pt==="command")he=wS(he);if(pt==="builtin")he=he.slice(An(he,1)==="--"?2:1);if(Dd(he)===ut)break}let ft=ge(he);for(let[dt,ut]of ft.envAssignments)je.set(dt,ut),at.set(dt,ut);return{words:ft.words,envAssignments:je,cwd:ct,envSplitValues:lt.length>0?lt:void 0,rewritten:bS(ft.words,Q)}}function bS(O,D){return O.some((B)=>!D.has(B))}function Dd(O){return O.map(t).join(" ")}function Kr(O){let D=O[0];return D?t(D):""}function An(O,D){let B=O[D];return B?t(B):void 0}function SS(O){return Nd.test(Kr(O))}function CS(O,D,B){if(!O.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${D.get("TMPDIR")??B.get("TMPDIR")??""}${O.slice(8)}`}}var vS=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function ES(O,D,B){let X=1,Q=B;while(X<O.length){let he=An(O,X);if(!he)break;if(he==="--")return{words:O.slice(X+1),cwd:Q};if(!he.startsWith("-"))break;if(he==="-D"||he==="--chdir"){let je=An(O,X+1);Q=je?Io(Q,je,D):null,X+=2;continue}if(he.startsWith("--chdir=")){Q=Io(Q,he.slice(8),D),X++;continue}if(he.startsWith("-D")&&he.length>2){Q=Io(Q,he.slice(2),D),X++;continue}if(he==="-i"||he==="--login"){Q=null,X++;continue}if(vS.has(he)){X+=2;continue}X++}return{words:O.slice(X),cwd:Q}}var RS=new Set(["-i","-0","--null"]),xS=new Set(["-u","--unset","-C","--chdir","-P"]);function _S(O,D,B,X){let Q=new Map,he=[],je=D,at=1,lt=(ct)=>({words:O.slice(ct),envAssignments:Q,cwd:je,envSplitValues:he.length>0?he:void 0});while(at<O.length){let ct=An(O,at);if(!ct)break;if(ct==="--")return lt(at+1);if(ct==="-i"||ct==="--ignore-environment"||ct==="-"){Q.clear();for(let dt of B.keys())Q.set(dt,"");Q.set("TMPDIR",""),at++;continue}if(RS.has(ct)){at++;continue}if(ct==="-u"||ct==="--unset"){let dt=An(O,at+1);if(dt!==void 0)Q.set(dt,"");at+=2;continue}if(ct.startsWith("-u")&&ct.length>2&&!ct.startsWith("-u=")){Q.set(ct.slice(2),""),at++;continue}if(ct.startsWith("--unset=")){Q.set(ct.slice(8),""),at++;continue}let ft=ct==="-S"||ct==="--split-string"?{value:An(O,at+1),consumed:2}:ct.startsWith("-S")&&ct.length>2?{value:ct.slice(2),consumed:1}:ct.startsWith("--split-string=")?{value:ct.slice(15),consumed:1}:null;if(ft){if(ft.value!==void 0)he.push(ft.value);return je=null,lt(at+ft.consumed)}if(xS.has(ct)){if(ct==="-C"||ct==="--chdir"){let dt=An(O,at+1);je=dt?Io(je,dt,X.paths):null}at+=2;continue}if(ct.startsWith("-u=")){at++;continue}if(ct.startsWith("-C")&&ct.length>2||ct.startsWith("--chdir=")){let dt=ct.startsWith("--chdir=")?ct.slice(8):ct.startsWith("-C=")?ct.slice(3):ct.slice(2);je=Io(je,dt,X.paths),at++;continue}if(ct.startsWith("-P")){at++;continue}if(ct.startsWith("-")){at++;continue}if(!En(ct))break;while(at<O.length){let dt=En(An(O,at)??"");if(!dt)break;Q.set(dt.name,dt.value),at++}if(An(O,at)==="--")at++;return lt(at)}return lt(at)}function Io(O,D,B){if(D==="")return null;if(!O&&!Md(D))return null;let X=Md(D)?yS(D).root:B.realpath(O??"/");if(X===null)return null;try{return tr(X,D,B)}catch{return null}}function wS(O){if(An(O,1)==="-v")return[...$t(["type"]),...O.slice(2)];let D=1;while(D<O.length){let B=An(O,D);if(!B)break;if(B==="-p"||B==="-v"||B==="-V"){D++;continue}if(B==="--")return O.slice(D+1);if(B.startsWith("-")&&!B.startsWith("--")&&B.length>1){if(!/^[pvV]+$/.test(B.slice(1)))break;D++;continue}break}return O.slice(D)}var PS=/['"\\$`{}#]/;function Hi(O,D){if(O.some((X)=>PS.test(X)))return null;let B=[...O.flatMap((X)=>X.split(/\s+/).filter((Q)=>Q.length>0)),...D];return B.length<=64?B:null}function nr(O,D,B){return ji(O,D,B).tokens}function AS(O){let D=[],B="",X=0;while(X<O.length){let Q=O.charAt(X);if(Q==='"'||Q==="'"){let he=O.indexOf(Q,X+1);if(he===-1)return O.split(/\s+/).map((je)=>je.replace(/["']/g,"")).filter((je)=>je.length>0);B+=O.slice(X+1,he),X=he+1;continue}if(/\s/.test(Q)){if(B.length>0)D.push(B);B="",X++;continue}B+=Q,X++}if(B.length>0)D.push(B);return D}function Cr(O,D,B,X=0){let Q=ji(O,D,B),he=(Q.envSplitValues??[]).flatMap(AS);if(he.length===0)return Q.tokens;let je=[...he,...Q.tokens];if(X>=8)return je;return Cr(je,D,B,X+1)}function ji(O,D,B,X){if(!Ld(O[0]??""))return{tokens:[...O],envAssignments:new Map,cwd:B};let Q=Sr($t(O),D,B,X);return{tokens:Q.words.map(t),envAssignments:Q.envAssignments,cwd:Q.cwd,envSplitValues:Q.envSplitValues}}var ol=Symbol("adopt-as-operand"),TS=new Set(["env","sudo","command","builtin"]),IS=new Set(["&&","||","|&","|","&",";"]),kS=new Set(["<<","<<<",">|"]),OS=new Set(["|","|&"]),MS=/[*@#?$!_-]/,DS=/^\w+(?::\w+)*/,NS=Object.freeze([]),ko=Object.freeze({kind:"scope",edge:"enter"}),Oo=Object.freeze({kind:"scope",edge:"exit"}),LS=Object.freeze([]),WS=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),Mo=new Set(["bash","sh","zsh","dash","ksh"]),FS=256,Bd=new WeakMap;function $d(O,D){let B=D.status==="complete"?new Set(rl(D)):new Set,X=BS(O,B);if(gi(X))return Vi("unclosed-quote",X,D);let Q={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},he=vr(D,{source:X,suppressed:B,flags:Q,depth:0,functions:new Map,powershell:D.dialect==="powershell"});if(Q.limited)return Vi("structural-limit",X,D);if(Q.invalid)return Vi("invalid",X,D);let je=Vi("complete",X,D,Q.assignmentFallbacks);return Bd.set(je,Object.freeze(he)),je}function qi(O,D,B,X,Q){let he=Q.word??((dt)=>dt),je={cwd:D,variables:new Map,previous:null},at=[],lt=new Set,ct=null,ft=[];for(let dt of Ud(O)){if(dt.kind==="scope"){if(dt.edge==="enter"){ft.push({state:je,segment:[...at],shellWords:new Set(lt),pipeProducer:ct});continue}let ut=Q.segment(at,je,ct,null,lt);if(ut)return ut;let mt=ft.pop();if(mt===void 0)throw Error("scope exit without a matching enter");je=mt.state,at=mt.segment,lt=mt.shellWords,ct=mt.pipeProducer;continue}if(dt.kind==="operator"){if(!dt.boundary)continue;let ut=Q.segment(at,je,ct,dt.operator,lt);if(ut)return ut;je=GS(at,je,B,X),ct=at.length>0&&OS.has(dt.operator)?at:null,at=[],lt=new Set;continue}if(dt.kind==="redirection"){if(dt.fd!==void 0)lt.add(at.length-1);if(dt.target===void 0)continue;let ut=Q.redirection({operator:dt.operator,role:dt.role,targetOrder:dt.targetOrder,target:dt.target,...dt.body===void 0?{}:{body:dt.body,consumer:dt.consumer}},je);if(ut===ol){lt.add(at.length),at.push(he(dt.target));continue}if(ut)return ut;continue}at.push(he(dt.text))}return Q.segment(at,je,ct,null,lt)}function Yi(O){return Ud(O).flatMap((D)=>{if(D.kind==="word")return[{kind:"word",text:D.text}];if(D.kind==="operator")return[{kind:"operator",boundary:D.boundary}];if(D.kind==="redirection")return[{kind:"redirection",target:D.target}];return[]})}function ln(O,D){return O.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(B,X,Q,he)=>{let je=D.get(X);if(je===void 0)return B;let at=Q.startsWith(":")?je!=="":!0;if(Q.endsWith("-"))return at?je:ln(he,D);return at?ln(he,D):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(B,X)=>D.get(X)??B).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(B,X)=>D.get(X)??B)}function Do(O){return O.length>0&&O.every((D)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(D))}function GS(O,D,B,X){let Q=Do(O)?new Map([...D.variables,...zS(O,D.variables)]):D.variables,he=nr([...O],B),je=Tt(he[0]??"").toLowerCase()==="cd"?he[1]:void 0;if(!je)return{...D,variables:Q};if(je==="-"){if(D.previous===null)return{...D,variables:Q};return{cwd:D.previous,variables:Q,previous:D.cwd}}return{cwd:en(ln(je,Q),D.cwd,B,X),variables:Q,previous:D.cwd}}function zS(O,D){return O.flatMap((B)=>{let X=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(B),Q=X?.[2]?.startsWith("=")?X[2].slice(1):void 0;return X?.[1]!==void 0&&Q!==void 0?[[X[1],ln(Q,D)]]:[]})}function Ud(O){return Bd.get(O)??NS}function BS(O,D){return[...D].reduce((B,X)=>B.slice(0,X.start)+" ".repeat(X.end-X.start)+B.slice(X.end),O)}function Vi(O,D,B,X=LS){return Object.freeze({status:O,source:D,program:B,assignmentFallbacks:Object.freeze(X)})}function vr(O,D){return O.nodes.flatMap((B,X)=>$S(B,O,X,D)).sort((B,X)=>B.start-X.start).flatMap((B)=>[...B.events])}function $S(O,D,B,X){if(O.kind==="connector")return[{start:O.span.start,events:[Tn(KS(O.operator))]}];if(O.kind==="unknown")return[{start:O.span.start,events:[Tn(O.source)]}];if(O.kind==="function")return X.functions.set(O.name,O.body),[];if(O.kind==="group"){let he=O.style!=="subshell",je=X.source[O.span.end-1]===(he?"}":")"),at=he?X:{...X,functions:new Map(X.functions)};return[{start:O.span.start,events:he?[Ki("{"),...vr(O.body,at),...je?[Ki("}")]:[]]:[ko,Tn("("),...vr(O.body,at),...je?[Tn(")")]:[],Oo]}]}let Q=XS(O,X.functions);if(Q){if(X.depth>=er.maxDepth||++X.flags.expansions>FS)return X.flags.limited=!0,[];return[{start:O.span.start,events:[...Wd(O,X),Ki(";"),...vr(Q,{...X,depth:X.depth+1}),Ki(";")]},...Fd(O,D,B,X)]}return[{start:O.span.start,events:Wd(O,X)},...Fd(O,D,B,X)]}function Wd(O,D){return[...O.words.map((B)=>({start:B.span.start,events:jd(B,O,D,!1)})),...O.redirections.map((B)=>({start:B.span.start,events:US(B,O,D)}))].sort((B,X)=>B.start-X.start).flatMap((B)=>B.events)}function US(O,D,B){let X=O.operator==="<<-"?"<<":O.operator,Q=O.target?jd(O.target,D,B,!0):[],he=Q[0],je=he?.kind==="word"?he.text:void 0;return[...O.fd===void 0?[]:[il(String(O.fd))],Object.freeze({kind:"redirection",operator:X,...O.fd===void 0?{}:{fd:O.fd},role:qS(X),targetOrder:kS.has(X)?"legacy-segment":"immediate",...je===void 0?{}:{target:je},...O.heredoc&&B.suppressed.has(O.heredoc.bodySpan)?{body:O.heredoc.body,consumer:Kd(D)}:{}}),...je===void 0?Q:Q.slice(1)]}function Fd(O,D,B,X){let Q=O.redirections.filter((he)=>he.operator==="<<"||he.operator==="<<-");return[...Q.flatMap((he)=>{let je=he.heredoc;if(!je)return[];let at=[il(je.delimiter),.../[\r\n]/.test(X.source[je.terminatorSpan.end]??"")?[Tn(";")]:[]];if(X.suppressed.has(je.bodySpan))return[{start:je.bodySpan.start,events:at}];return[{start:je.bodySpan.start,events:[...Hd(X.source.slice(je.bodySpan.start,je.bodySpan.end),X),...at]}]}),...Q.some((he)=>!he.heredoc&&he.target)?HS(D,B,X):[]]}function HS(O,D,B){let X=O.nodes.slice(D+1).find((Q)=>Q.kind==="connector");if(!X||X.span.end>=O.span.end)return[];return[{start:X.span.end,events:Hd(B.source.slice(X.span.end,O.span.end),B)}]}function Hd(O,D){if(D.depth>=er.maxDepth)return D.flags.limited=!0,[];let B=h(O,"posix");if(B.status==="limited")return D.flags.limited=!0,[];let X={invalid:!1,limited:!1,expansions:D.flags.expansions,assignmentFallbacks:D.flags.assignmentFallbacks},Q=vr(B,{source:O,suppressed:new Set,flags:X,depth:D.depth+1,functions:new Map,powershell:!1});return D.flags.limited||=X.limited,D.flags.expansions=X.expansions,Q}function jd(O,D,B,X){let Q=[],he={single:!1,double:!1},je="",at=!1,lt=()=>{let ct=at&&!X?Tn("glob"):je!==""||O.quoted&&Q.length===0?il(je):void 0;if(ct)Q.push(ct);je="",at=!1};for(let ct of O.parts){if(ct.provenance!=="command-substitution"&&ct.provenance!=="arithmetic"){for(let mt of tl(ct.raw,he,B.flags,B.powershell)){if(typeof mt==="string"){lt(),Q.push(Tn(mt));continue}je+=mt.text,at||=mt.glob}continue}let ft=D.nested.find((mt)=>mt.span.start>=ct.span.start&&mt.span.end<=ct.span.end);if(he.double){let mt=B.source.slice(ct.span.start,ct.span.end);je+=tl(mt,{single:!1,double:!0},B.flags,B.powershell).map((ht)=>typeof ht==="string"?ht:ht.text).join("");let pt=ft?vr(ft,B).filter((ht)=>ht.kind==="redirection"&&ht.body!==void 0):[];if(pt.length>0)Q.push(ko,...pt,Oo);continue}let dt=ft?vr(ft,B):[];if(ct.raw.startsWith("`")){je+="${}",lt(),Q.push(ko,...dt,Oo);continue}if(ct.raw.startsWith("<(")||ct.raw.startsWith(">(")){lt(),Q.push(ct.raw.startsWith("<(")?Tn("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),ko,...dt,...ct.raw.endsWith(")")?[Tn(")")]:[],Oo);continue}let ut=ct.raw.startsWith("$((")?2:1;je+="${}",lt(),Q.push(...Array.from({length:ut},()=>Tn("(")),...ut===1?[ko]:[],...dt,...ct.raw.endsWith(")".repeat(ut))?Array.from({length:ut},()=>Tn(")")):[],...ut===1?[Oo]:[])}return lt(),Q}function tl(O,D,B,X){let Q=[],he="",je=!1,at=0;while(at<O.length){let lt=O[at]??"";if(!D.single&&!D.double&&(lt==="("||lt===")")){Q.push({text:he,glob:je},lt),he="",je=!1,at++;continue}if(X&&lt==="`"&&!D.single){he+=O[at+1]??"",at+=2;continue}if(D.single&&lt==="'"){D.single=!1,at++;continue}if(D.single){he+=lt,at++;continue}if(D.double){if(lt==='"'){D.double=!1,at++;continue}if(!X&&lt==="\\"){let ct=O[at+1]??"";he+=['"',"\\","$"].includes(ct)?ct:`\\${ct}`,at+=2;continue}if(lt==="$"){let ct=Gd(O,at,D,B,X);he+=ct.text,at=ct.next;continue}he+=lt,at++;continue}if(lt==="'"||lt==='"'){D.single=lt==="'",D.double=lt==='"',at++;continue}if(!X&&lt==="\\"){let ct=O[at+1]??"";je||=ct==="*"||ct==="?",he+=ct,at+=2;continue}if(lt==="$"){let ct=Gd(O,at,D,B,X);he+=ct.text,at=ct.next;continue}je||=lt==="*"||lt==="?",he+=lt,at++}return[...Q,{text:he,glob:je}]}function Gd(O,D,B,X,Q){let he=O[D+1];if(he==="{"){let at=VS(O,D+2);if(at===-1)return X.invalid=!0,{text:"",next:O.length};let lt=O.slice(D,at+1);return jS(lt,B,X,Q),{text:lt,next:at+1}}if(he!==void 0&&MS.test(he))return{text:`\${${he}}`,next:D+2};let je=(Q?DS:/^\w*/).exec(O.slice(D+1))?.[0]??"";return{text:`\${${je}}`,next:D+1+je.length}}function jS(O,D,B,X){let Q=O.slice(2,-1),he=/^[A-Za-z_][A-Za-z0-9_]*/.exec(Q)?.[0];if(!he)return;let je=Q.slice(he.length),at=[":=","="].find((ct)=>je.startsWith(ct));if(!at)return;let lt=tl(je.slice(at.length),{...D},B,X);B.assignmentFallbacks.push(...lt.flatMap((ct)=>typeof ct==="string"||!ct.text?[]:[ct.text]))}function VS(O,D){let B=1,X=D;while(B>0&&X<O.length){if(O[X]==="{"&&O[X-1]==="$")B++;if(O[X]==="}")B--;X++}return B===0?X-1:-1}function KS(O){return/^[\r\n]+$/.test(O)?";":O}function Tn(O){return Object.freeze({kind:"operator",operator:O,boundary:IS.has(O)})}function Ki(O){return Object.freeze({kind:"operator",operator:O,boundary:!0})}function il(O){return Object.freeze({kind:"word",text:O})}function qS(O){if(O==="<<"||O==="<<<")return"here-data";if(O==="<"||O==="<&")return"file-read";return"file-write"}function No(O){return WS.has(O)||/^python\d/.test(O)}var YS=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 Vd(O,D){let B=D[0];if(B===void 0||!B.startsWith("-"))return D;let X=YS.get(O)?.has(B)??!1;return Vd(O,D.slice(X?2:1))}function nl(O){let D=O[0];if(D===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(D))return nl(O.slice(1));if(!TS.has(D))return[...O];return nl(Vd(D,O.slice(1)))}function Kd(O){let D=vo(O),B=O.words.findIndex((X)=>X.provenance==="literal"&&X.text===D);return nl(B<0?[]:O.words.slice(B).map((X)=>X.text))}function ZS(O){let D=Kd(O)[0];if(D===void 0)return!1;let B=Tt(D).toLowerCase();return No(B)&&!Mo.has(B)}function rl(O){return O.nodes.flatMap((D,B)=>{if(D.kind==="group"||D.kind==="function")return rl(D.body);if(D.kind!=="command")return[];let X=D.nested.flatMap((at)=>rl(at)),Q=D.redirections.flatMap((at)=>at.heredoc?.quotedDelimiter?[at.heredoc.bodySpan]:[]);if(ZS(D))return[...X,...Q];let he=O.nodes[B+1];if(he?.kind==="connector"&&(he.operator==="|"||he.operator==="|&")||!QS(D))return X;return[...X,...Q]})}function XS(O,D){let B=vo(O);return B===void 0?void 0:D.get(B)}function rr(O,D){return O!==void 0&&O.provenance==="literal"&&!O.quoted&&O.raw===O.text&&O.text===D}function JS(O){if(rr(O.words[0],"git"))return rr(O.words[1],"commit");if(!rr(O.words[0],"gh")||!rr(O.words[2],"create"))return!1;return rr(O.words[1],"pr")||rr(O.words[1],"issue")}function QS(O){return(rr(O.words[0],"cat")||rr(O.words[0],"tee")||JS(O))&&!O.words.some(zd)&&!O.redirections.some((B)=>zd(B.target))}function zd(O){return O?.parts.some((D)=>D.provenance==="command-substitution"&&D.raw.startsWith(">("))??!1}var qd=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Yd=new Set([...qd,"glob"]),eC=new Set([...Yd,"pattern"]);class y extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Lo(O){let D=tC(),B=te(O.input),X=[];if((O.route.kind==="command"||O.route.kind==="unknown")&&B)X.push({usage:"input-candidate",source:B});if(O.route.kind==="command"&&"command"in O&&O.command)X.push({usage:"declared-command",source:O.command});let Q=X.reduce((he,je)=>{let at=he.findIndex((ft)=>ft.source===je.source);if(at!==-1){let ft=he[at];if(!ft)return he;return he[at]={...ft,usages:[...ft.usages,je.usage]},he}let lt=O.route.kind==="command"?O.route.shell:process.platform==="win32"?"powershell":"posix",ct=D.getCommandProgram(je.source,lt);return he.push({usages:[je.usage],source:je.source,program:ct,shell:D.getShellSyntax(je.source,ct)}),he},[]);return{invocation:{toolName:O.toolName,route:O.route,context:O.context},commands:Q,paths:nC(O),store:D}}function cn(O,D){return O.commands.find((B)=>B.usages.includes(D))}function Hn(O,D){if(!O.includes("$"))return O;return Hs(O,D)}function tC(){let O=new Map,D=new Map,B=new WeakMap,X=(he,je)=>{let at=`${je}\x00${he}`,lt=D.get(at);if(lt)return lt;let ct=h(he,je);return D.set(at,ct),ct};return{getShellSyntax:(he,je)=>{if(je&&je.source!==he)throw TypeError("Shell syntax source does not match command program source.");let at=je??X(he,"posix");if(at.status==="limited"){let ft=B.get(at);if(ft)return ft;let dt={status:"structural-limit",source:he,program:at,assignmentFallbacks:[]};return B.set(at,dt),dt}let lt=O.get(he);if(lt)return lt;let ct=$d(he,at);return O.set(he,ct),ct},getCommandProgram:X}}function nC(O){let D=O.route.kind==="grep"?Yd:O.route.kind==="glob"?eC:qd;return[...Dc(O.input,D),...O.route.kind==="patch"?Wc(O.input):[]]}var rC=new Set(["-S","--suffix"]);function qr(O,D,B,X,Q){if(O.status==="structural-limit")throw new y;if(O.status!=="complete")return Q.findMalformedTarget(O.source);return qi(O,D,B,X,{segment:(he,je)=>Q.findSegmentTarget(he,je),redirection:(he,je)=>he.role==="file-write"&&Q.isRedirectionTarget(ln(he.target,je.variables),je)?he.target:null})}function Zi(O){let D=[],B=null,X=!1;for(let Q=0;Q<O.length;Q++){let he=O[Q];if(he===void 0)break;if(!X&&he==="--"){X=!0;continue}if(!X&&(he==="-t"||he==="--target-directory")){B=O[++Q]??null;continue}if(!X&&he.startsWith("--target-directory=")){B=he.slice(19);continue}if(!X&&he.startsWith("-t")&&he.length>2){B=he.slice(2);continue}if(!X&&rC.has(he)){Q++;continue}if(!X&&(he.startsWith("--suffix=")||he.startsWith("--backup=")))continue;if(!X&&he.startsWith("-"))continue;D.push(he)}return B?{sources:D,destination:B}:{sources:D.slice(0,-1),destination:D.at(-1)??null}}var b="Git metadata and hooks are protected. Ask the user before modifying them.";function ef(O,D,B,X){let Q=O.invocation.context.executionCwd;if(!D)return null;if(O.invocation.route.kind==="patch"||O.invocation.route.kind==="path"||O.invocation.route.kind==="unknown"){if(si(O.invocation.toolName))return null;let at=O.paths.find((lt)=>Zd(lt,Q,D,B,X,D.entries));return at?{target:at}:null}if(O.invocation.route.kind!=="command")return null;let he=cn(O,"input-candidate");if(!he)return null;let je=qr(he.shell,Q,B,X,{findSegmentTarget:(at,lt)=>aC(at,lt,D,B,X),isRedirectionTarget:(at,lt)=>Zd(at,lt.cwd,D,B,X,D.markerFiles),findMalformedTarget:()=>null});return je?{target:je}:null}function Er(O,D,B,X,Q,he,je=!1){if(!B)return!1;let at=Ji(en(O,D,Q,he)),lt=at.replace(/(\/\.?\*+)+$/,"");if(lt!==at&&lt!==""){if(sl(lt,B))return!0;let ct=je||at.slice(lt.length).includes("/."),ft=(dt)=>ct?Xi(dt,lt):oC(dt,lt);if(B.markerFiles.some(ft))return!0;return X&&Xd(B).some(ft)}if(sl(at,B))return!0;return X&&Xd(B).some((ct)=>Xi(ct,at))}function oC(O,D){let B=Qd(D,O);if(B===""||B.startsWith("..")||Jd(B))return!1;return!B.split(/[\\/]/)[0]?.startsWith(".")}function iC(O,D,B,X,Q){return Er(O,D,B,!0,X,Q)}function sC(O,D,B,X,Q){if(!B)return!1;return sl(Ji(en(O,D,X,Q)),B)}function Zd(O,D,B,X,Q,he){let je=Ji(en(O,D,X,Q));return he.includes(je)||nf(je,B)}function tf(O,D,B,X,Q){if(!B)return!1;return B.hooksDirectories.some((he)=>O.some((je)=>Xi(he,Ji(en(je,D,X,Q)))))}function sl(O,D){return D.entries.includes(O)||D.directories.includes(O)||nf(O,D)}function nf(O,D){return D.hooksDirectories.some((B)=>Xi(O,B))}function Xd(O){return[...O.entries,...O.directories,...O.hooksDirectories]}function Xi(O,D){let B=Qd(D,O);return B===""||!/^\.\.(?:[\\/]|$)/.test(B)&&!Jd(B)}function Ji(O){return process.platform==="win32"?O.toLowerCase():O}function aC(O,D,B,X,Q){if(Do(O))return null;let he=Cr([...O],X);if(Tt(he[0]??"").toLowerCase()!=="mv")return null;let je=Zi(he.slice(1)),at=je.sources.find((lt)=>iC(ln(lt,D.variables),D.cwd,B,X,Q));if(at)return at;return je.destination&&sC(ln(je.destination,D.variables),D.cwd,B,X,Q)?je.destination:null}import{isAbsolute as fl,normalize as hC,parse as yC,posix as ff,resolve as Yr,sep as dl}from"node:path";import{isAbsolute as lC,join as rf,normalize as af,parse as cC,sep as of}from"node:path";var uC=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],dC=`
29
- `;function Wo(O,D){if(or(O,D))return!0;if(!O.has("TMPDIR"))return!1;return!al(O.get("TMPDIR")??"",D)}function Rr(O,D){if(O.has("TMPDIR"))return al(O.get("TMPDIR")??"",D);let B=ll(O,D);if(B===void 0)return!0;return al(B,D)}function ll(O,D){return uf(O,D,"TMPDIR")}function al(O,D){if(!O)return!1;if(mC(O))return!1;return cl(O,D)}function or(O,D){let B=uf(O,D,"IFS");return B!==void 0&&B!==""&&B!==dC}function cl(O,D){let B=Qi(O,D.paths);if(B===null)return!1;return cf(D).some((X)=>gC(B,X))}function lf(O,D){let B=Qi(O,D.paths);if(B===null)return!1;return cf(D).some((X)=>es(X)===es(B))}var sf=new WeakMap;function cf(O){let D=sf.get(O);if(D)return D;let B=fC(O);return sf.set(O,B),B}function fC(O){let D=uC.map((X)=>Qi(X,O.paths)??af(X)),B=Qi(O.tmpdir,O.paths);if(!B)return D;if(process.platform==="win32")return[...D,B];if(process.platform==="darwin"&&pC(B))return[...D,B];return D}function mC(O){return/[\s$`*?[]/.test(O)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(O)||/[+@!]\([^)]*\)/.test(O)}function uf(O,D,B){return O.has(B)?O.get(B):D.env.get(B)}function pC(O){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(O)}function Qi(O,D){try{let B=af(O);if(!lC(B))return B;let X=cC(B).root,Q=B.slice(X.length).split(/[\\/]+/).filter(Boolean),he=X;for(let je=0;je<Q.length;je++){let at=rf(he,Q[je]??"");if(D.entryKind(at)==="missing")return rf(at,...Q.slice(je+1));let lt=D.realpath(at);if(lt===null)return null;he=lt}return he}catch{return null}}function gC(O,D){let B=es(O),X=es(D);if(B===X)return!0;let Q=X.endsWith(of)?X:`${X}${of}`;return B.startsWith(Q)}function es(O){return process.platform==="win32"?O.toLowerCase():O}var bC=process.platform==="win32",df=64,SC=16384;function Fo(O,D,B,X){if(O.kind==="temp_target")return null;let Q=X[O.kind];if(O.kind==="dynamic_target"&&!Jt(B,Q.id,D.strict))return null;if(O.kind==="within_anchored_cwd"&&!Jt(B,Q.id,D.paranoid))return null;return St(Q.id,Q.reason)}function Go(O){let D=ed(O,df,df,SC);return{expandedTargets:D&&"words"in D?D.words:void 0,unsafeBraceExpansion:D!==void 0&&"limited"in D,targetIsLiteral:D===void 0&&O.provenance==="literal"&&(O.quoted||O.raw!==O.text),tmpdirWordSplittingProtected:CC(O)}}function CC(O){let D=O.parts.filter((B)=>B.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(B.raw));return D.length>0&&D.every((B)=>vC(O.raw,B.span.start-O.span.start))}function vC(O,D){let B=null,X=!1;for(let Q=0;Q<D;Q++){let he=O[Q];if(X){X=!1;continue}if(he==="\\"&&B!=="'"){X=!0;continue}if(B===he){B=null;continue}if(B===null&&(he==="'"||he==='"'))B=he}return B==='"'}function xr(O){let D=O.environment.home,B=O.environment.paths,X=O.budget??fn();return{anchoredCwd:O.originalCwd??O.cwd??null,resolvedCwd:O.cwd??null,strict:O.strict??!1,paranoid:O.paranoid??!1,trustTmpdirVar:O.allowTmpdirVar??!0,posixShell:O.posixShell??!1,tmpdirWordSplittingUnsafe:O.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:O.trustedTmpdirValue??O.allowTmpdirVar??!0,environment:O.environment,allowRoots:wC(O.allowPaths,D,B,X),protectedGitMetadata:O.protectedGitMetadata,budget:X}}function In(O,D,B={}){let X=B.targetIsLiteral??!1;if(!X&&D.tmpdirWordSplittingUnsafe&&!B.tmpdirWordSplittingProtected&&AC(O))return{kind:"outside_anchored_cwd"};let Q=!X&&gf(O,D.posixShell);if(Jn(O))return{kind:"outside_anchored_cwd"};if(ml(O,X))return{kind:"root_or_home_target"};if(EC(O,D,X))return{kind:"root_or_home_target"};if(D.resolvedCwd&&Er(O,D.resolvedCwd,D.protectedGitMetadata,!0,D.environment,D.budget,!D.posixShell))return{kind:"git_metadata_target"};if(RC(O,D.trustTmpdirVar,D.posixShell,Q,X,B.tmpdirWordSplittingProtected??!1,D.trustedTmpdirValue,D.environment))return{kind:"temp_target"};if(Q)return{kind:"dynamic_target"};if(PC(O,D,X))return{kind:"temp_target"};let he=D.anchoredCwd;if(he){if(!B.skipHomeCwd&&OC(he,D.environment.home,D.environment.paths,D.budget))return{kind:"home_cwd_target"};if(!B.skipCwdSelf&&MC(O,D.resolvedCwd??he,D.environment.paths,D.budget))return{kind:"cwd_self_target"};if(DC(O,he,D.resolvedCwd??he,Q,X,D.environment.paths,D.budget))return{kind:"within_anchored_cwd"}}return{kind:"outside_anchored_cwd"}}function mf(O,D,B={}){let{containmentTarget:X,...Q}=B;if(In(O,D,Q).kind!=="temp_target")return!1;let he=O.trim();if(_C(he))return!1;if(lf(he,D.environment))return!1;return![D.anchoredCwd,D.resolvedCwd].some((je)=>NC(X??he,je,D.environment.paths,D.budget))}function ml(O,D=!1){let B=O.trim(),X=ff.normalize(B),Q=B.replace(/\\/g,"/"),he=X==="/"?X:X.replace(/\/+$/,"");if(he==="/"||he.startsWith("/")&&he.slice(1).split("/").every((je)=>/^\*+$/.test(je)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(Q)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(Q))return!0;if(!D&&(X==="~"||X==="~/"||X==="~/*"))return!0;if(!D&&(X==="$HOME"||X==="$HOME/"||X==="$HOME/*"))return!0;if(!D&&(X==="${HOME}"||X==="${HOME}/"||X==="${HOME}/*"))return!0;return!1}function EC(O,D,B){let X=O.trim(),Q=B?X:X==="*"?".":X.endsWith("/*")?X.slice(0,-2):X;if(!Q)return!1;try{let he=fl(Q)?Q:D.resolvedCwd?Yr(D.resolvedCwd,Q):null;if(!he)return!1;let je=un(Lt(he,D.environment.paths,D.budget));if(je===yC(je).root)return!0;return je===un(Lt(D.environment.home,D.environment.paths,D.budget))}catch{return!1}}function un(O){let D=hC(O);if(bC){if(D=D.replace(/\//g,"\\").toLowerCase(),D.length>3&&D.endsWith("\\"))D=D.slice(0,-1);return D}if(D.length>1&&D.endsWith("/"))D=D.slice(0,-1);return D}function RC(O,D,B,X,Q,he,je,at){let lt=O.trim();if(pf(lt))return!1;if(!X&&cl(lt,at))return!0;return(D||he&&je)&&B&&!Q&&xC(lt,B)}function xC(O,D){return["$TMPDIR","${TMPDIR}"].some((B)=>{if(O===B)return!0;if(!O.startsWith(`${B}/`))return!1;return!gf(O.slice(B.length+1),D)})}function _C(O){let D=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(O);if(!D)return!1;return ff.normalize(`/${D[1]??""}`)==="/"}function pf(O){return O.split(/[\\/]+/).includes("..")}function wC(O,D,B,X){if(!O?.length)return[];return O.flatMap((Q)=>{let he=bo(Q.trim(),D);if(!fl(he))return[];try{let je=Lt(he,B,X);if(So(je,Lt(D,B,X)))return[];return[un(je)]}catch{return[]}})}function PC(O,D,B){if(D.allowRoots.length===0)return!1;let X=O.trim();if(pf(X))return!1;let Q=B?X:bo(X,D.environment.home),he=D.resolvedCwd??D.anchoredCwd,je=fl(Q)?Q:he?Yr(he,Q):null;if(!je)return!1;try{let at=un(Lt(je,D.environment.paths,D.budget));return D.allowRoots.some((lt)=>at===lt||at.startsWith(lt.endsWith(dl)?lt:`${lt}${dl}`))}catch{return!1}}function AC(O){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(O)}function gf(O,D=!1){return O.includes("$")||O.includes("`")||TC(O)||D&&IC(O)}function TC(O){let D=!1;for(let B of O){if(D){D=!1;continue}if(B==="\\"){D=!0;continue}if(B==="*"||B==="?"||B==="[")return!0}return!1}function IC(O){let D=!1;for(let B=0;B<O.length;B++){let X=O[B];if(D){D=!1;continue}if(X==="\\"){D=!0;continue}if(X==="{"&&kC(O,B)||(X==="+"||X==="@"||X==="!")&&O[B+1]==="(")return!0}return!1}function kC(O,D){let B=O.indexOf("}",D+1);if(B===-1)return!1;let X=O.slice(D+1,B);return X.includes(",")||X.includes("..")}function OC(O,D,B,X){try{return un(Lt(O,B,X))===un(Lt(D,B,X))}catch{try{return un(O)===un(D)}catch{return!1}}}function MC(O,D,B,X){if(O==="."||O==="./"||O===".\\")return!0;try{return un(Lt(Yr(D,O),B,X))===un(Lt(D,B,X))}catch{try{return un(Yr(D,O))===un(D)}catch{return!1}}}function DC(O,D,B,X,Q,he,je){let at=B??D;if(!Q&&(O.startsWith("~")||O.startsWith("$HOME")||O.startsWith("${HOME}")))return!1;if(X)return!1;if(O.startsWith("/")||/^[A-Za-z]:[\\/]/.test(O))try{return ul(O,D,he,je)}catch{return!1}if(O.startsWith("./")||O.startsWith(".\\")||!O.includes("/")&&!O.includes("\\"))try{return ul(Yr(at,O),D,he,je)}catch{return!1}if(O.startsWith("../"))return!1;try{return ul(Yr(at,O),D,he,je)}catch{return!1}}function ul(O,D,B,X){try{return hf(Lt(O,B,X),Lt(D,B,X))}catch{return!1}}function NC(O,D,B,X){if(!D)return!1;try{return hf(Lt(D,B,X),Lt(O,B,X))}catch{return!0}}function hf(O,D){let B=un(O),X=un(D);return B.startsWith(`${X}${dl}`)||B===X}var LC=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),yf="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",WC="PowerShell Remove-Item -Recurse -Force for non-temporary paths is blocked by the active safety policy. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",bf="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",Sf="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",FC="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",GC="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",zC={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:Sf},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:b},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:bf},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:FC},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:yf},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:WC},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:yf}};function Cf(O,D,B,X=xr({...B,allowPaths:B.policy?.destructiveCommandAllowPaths})){return BC(O.words.map((Q)=>({kind:"word",text:Q.text,dynamic:Q.provenance!=="literal"})),D,X,B.policy)}function BC(O,D,B,X){let Q=O.filter((lt)=>lt.kind==="word"),he=UC(Q),je=Q[he];if(!je||!LC.has(JC(je.text)))return null;let at=$C(Q.slice(he+1));if(at.whatIfProtected)return null;if(Jt(X,"powershell.remove-item-pipeline-dynamic-target",B.strict)&&D&&(at.targets.length===0||at.recursive))return St("powershell.remove-item-pipeline-dynamic-target",GC);for(let lt of at.targets)if(!Jn(lt.text)&&ml(gl(lt.text)))return St(at.recursive&&at.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Sf);for(let lt of at.targets)if(B.resolvedCwd&&Er(gl(lt.text),B.resolvedCwd,B.protectedGitMetadata,at.recursive,B.environment,B.budget,!0))return St("powershell.remove-item-git-metadata",b);if(!at.recursive||!at.force)return null;if(Jt(X,"powershell.remove-item-recursive-force-dynamic-target",B.strict)&&(at.hasDynamicTarget||at.targets.length===0))return St("powershell.remove-item-recursive-force-dynamic-target",bf);for(let lt of at.targets){let ct=Fo(In(gl(lt.text),B),B,X,zC);if(ct)return ct}return null}function $C(O){let D=[],B=!1,X=!1,Q=!1,he=!1,je=!1;for(let at=0;at<O.length;at++){let lt=O[at];if(!lt||lt.kind!=="word")continue;if(HC(lt))continue;if(je){D.push(pl(lt)),he=he||lt.dynamic;continue}if(lt.text==="--"){je=!0;continue}let ct=VC(lt.text);if(!ct){D.push(pl(lt)),he=he||lt.dynamic;continue}if(KC(ct.name)){let ft=ct.value?jC(ct.value,lt):O[++at];if(ft?.kind==="word"){D.push(pl(ft)),he=he||ft.dynamic;continue}he=!0;continue}if(qC(ct.name)){B=!0;continue}if(YC(ct.name)){X=!0;continue}if(ZC(ct.name))Q=XC(ct.value)}return{targets:D,recursive:B,force:X,whatIfProtected:Q,hasDynamicTarget:he}}function UC(O){let D=O[0];if(D?.kind==="word"&&D.text==="&"||D?.text===".")return O.length>1?1:0;return 0}function pl(O){return{text:O.kind==="word"?O.text:"",dynamic:O.kind==="word"&&O.dynamic}}function HC(O){return O.kind==="word"&&O.text===","}function gl(O){let D=O.replace(/\\/g,"/"),B=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(D);return B?`$HOME${D.slice(B[0].length)}`:D}function jC(O,D){return{kind:"word",text:O,dynamic:D.kind==="word"&&(D.dynamic||O.includes("$"))}}function VC(O){if(!O.startsWith("-")||O==="-")return null;let D=O.slice(1),B=D.indexOf(":");if(B===-1)return{name:D.toLowerCase()};return{name:D.slice(0,B).toLowerCase(),value:D.slice(B+1)}}function KC(O){return"path".startsWith(O)||"literalpath".startsWith(O)}function qC(O){return"recurse".startsWith(O)}function YC(O){return O.length>=2&&"force".startsWith(O)}function ZC(O){return O==="wi"||"whatif".startsWith(O)}function XC(O){if(O===void 0||O==="")return!0;let D=O.toLowerCase();return D==="$true"||D==="true"}function JC(O){return O.toLowerCase()}var Zr="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",ts="Unsupported heredoc syntax",vf="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";import{normalize as vs}from"node:path";var QC=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),ev=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),tv=new Set(["-o","--output","--query","--subscription"]),nv=new Set;function Ef(O){if(O==="aws")return QC;if(O==="gcloud")return ev;if(O==="az")return tv;return nv}var rv=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),ov=new Set;function Rf(O){if(O==="git")return pn;if(O==="docker")return rv;return ov}function _(O,D){if(O.length===0||D.length===0)return null;let B=kt(O[0]??""),X=sn(O);for(let Q of D){if(!av(B,Q.command))continue;if(Q.match){if(iv(B,O,Q.match))return xf(Q);continue}if(!lv(B,O,Q.subcommand))continue;if(uv(O,new Set(Q.block_args),X))return xf(Q)}return null}function xf(O){return{id:`custom.${O.name}`,reason:`[${O.name}] ${O.reason}`,intent:O.intent??"manual_only"}}function iv(O,D,B){let X=D.slice(1);if(B.exclude_args?.some((Q)=>X.includes(Q)))return!1;if(B.any_args&&!B.any_args.some((Q)=>X.includes(Q)))return!1;return sv(X,B.command_path,Ef(O))}function sv(O,D,B){let X=0,Q=!1;for(let he of O){if(X>=D.length)return!0;if(Q){Q=!1;continue}if(he.startsWith("-")){Q=!he.includes("=")&&B.has(he);continue}if(he!==D[X])return!1;X++}return X>=D.length}function av(O,D){return O===kt(D)}function lv(O,D,B){if(!B)return!0;return _f(D,1,B,Rf(O))}function _f(O,D,B,X){let Q=!1;for(let he=D;he<O.length;he++){let je=O[he];if(!je)continue;if(Q){Q=!1;continue}if(je==="--"){let at=O[he+1];if(at&&!at.startsWith("-"))return at===B;return!1}if(X.has(je)){Q=!0;continue}if(je.startsWith("-")){if(!je.includes("=")&&cv(O,he,B,X))return!0;continue}return je===B}return!1}function cv(O,D,B,X){let Q=O[D+1];if(!Q||Q.startsWith("-"))return!1;return _f(O,D+2,B,X)}function uv(O,D,B){return O.some((X)=>D.has(X))||[...B].some((X)=>D.has(X))}var dv=new Set(["-e","--source"]),fv=new Set(["-F","-v","--assign","--field-separator"]),wf=new Set(["-f","--file"]),mv=new Set(["print","printf","return"]),Pf=[{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"}],pv="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 Af(O,D,B){let X=!1;for(let Q of gv(O)){let he=hv(Q,B);if(!he)continue;for(let je of he.commands){let at=D(je);if(at)return at;if(je.includes("{}")||/[$`]/.test(je))X=!0}X||=he.dynamic}return X?St("awk.system-dynamic",pv):null}function yl(O){let D=[],B=!1,X=!1,Q=!0,he=!0;for(let je=1;je<O.length;je++){let at=O[je];if(at===void 0)break;if(Q&&at==="--"){Q=!1;continue}if(Q&&dv.has(at)){B=!0;let lt=O[je+1];if(he&&=lt!==void 0,lt!==void 0)D.push({tokenIndex:je+1,kind:"inline-code",value:lt});je++;continue}if(Q&&at.startsWith("--source=")){B=!0,D.push({tokenIndex:je,kind:"inline-code",value:at.slice(9)});continue}if(Q&&at.startsWith("-e")&&at.length>2){B=!0,D.push({tokenIndex:je,kind:"inline-code",value:at.slice(2)});continue}if(Q&&(fv.has(at)||wf.has(at))){let lt=O[je+1];if(he&&=lt!==void 0,wf.has(at)){if(X=!0,lt!==void 0)D.push({tokenIndex:je+1,kind:"program-file",value:lt})}je++;continue}if(Q&&(at.startsWith("-F")||at.startsWith("-v")&&at.slice(2).includes("=")))continue;if(Q&&at.startsWith("-f")&&at.length>2){X=!0,D.push({tokenIndex:je,kind:"program-file",value:at.slice(2)});continue}if(Q&&(at.startsWith("--assign=")||at.startsWith("--field-separator=")))continue;if(Q&&at.startsWith("--file=")){X=!0,D.push({tokenIndex:je,kind:"program-file",value:at.slice(7)});continue}if(Q&&at.startsWith("-")&&at!=="-")continue;if(Q=!1,!B&&!X)D.push({tokenIndex:je,kind:"main-program",value:at});return{sources:D,optionsOpen:!1}}return{sources:he?D:[],optionsOpen:Q&&he}}function Bo(O){return yl(O).sources}function gv(O){return Bo(O).filter((D)=>D.kind!=="program-file").map((D)=>D.value)}function hv(O,D){yn(D,O);let B=O.includes("system")?bl(O,D):null,X=yv(O,D);if(!B&&!X)return null;return{dynamic:!!B?.dynamic||!!X?.dynamic,commands:[...B?.commands??[],...X?.commands??[]]}}function bl(O,D){yn(D,O);let B=[],X=!1,Q=!1,he=0;while(he<O.length){let je=O[he];if(je==='"'||je==="'"){he=rs(O,he,je)?.endIndex??he+1;continue}if(je==="#"){he=Tf(O,he+1);continue}if(je==="/"&&If(O,he)){he=kf(O,he+1)??he+1;continue}if(!O.startsWith("system",he)){he++;continue}let at=he;if(he+=6,zo(O[at-1])||zo(O[he]))continue;let lt=ns(O,he);if(O[lt]!=="(")continue;lt=ns(O,lt+1);let ct=O[lt];if(ct!=='"'&&ct!=="'"){X=!0,Q=!0;continue}let ft=rs(O,lt,ct);if(!ft){X=!0,Q=!0;continue}if(lt=ns(O,ft.endIndex),X=!0,O[lt]!==")"){Q=!0,he=ft.endIndex;continue}B.push(ft.value),he=lt+1}if(!X)return null;return{dynamic:Q,commands:B}}function yv(O,D){yn(D,O);let B=[],X=!1,Q=!1,he=0,je=0,at=null,lt=null,ct=0;while(he<O.length){let ft=O[he];if(!ft)break;if(ft==='"'||ft==="'"){let mt=rs(O,he,ft);if(mt&&ct===je)lt={...mt,startIndex:he};ct=mt?.endIndex??he+1,he=mt?.endIndex??he+1;continue}if(ft==="#"){he=Tf(O,he+1),je=he,at=null,lt=null,ct=he;continue}if(ft==="/"&&If(O,he)){let mt=kf(O,he+1);ct=mt??he+1,he=mt??he+1;continue}if(`;
30
- {}`.includes(ft)){he++,je=he,at=null,lt=null,ct=he;continue}if(at===null&&(hl(O,he,"print")||hl(O,he,"printf")))at=he;if(ft!=="|"||O[he-1]==="|"||O[he+1]==="|"){if(!/\s/.test(ft))ct=he+1;he++;continue}let dt=O[he+1]==="&"?he+2:he+1,ut=ns(O,dt);if(hl(O,ut,"getline")){Q=!0;let mt=Cv(je,lt,ct);if(X||=mt===null,mt!==null)B.push(mt);ct=dt,he=dt;continue}if(Ev(je,at)){Q=!0;let mt=Sv(O,ut);if(!mt){X=!0,ct=dt,he=dt;continue}if(!bv(O,mt.endIndex)){X=!0,ct=mt.endIndex,he=mt.endIndex;continue}B.push(mt.value),ct=mt.endIndex,he=mt.endIndex;continue}ct=dt,he++}if(!Q)return null;return{dynamic:X,commands:B}}function zo(O){return!!O&&/[A-Za-z0-9_]/.test(O)}function ns(O,D){let B=D;while(/\s/.test(O[B]??""))B++;return B}function bv(O,D){let B=D;while(/[\t\f\v\r ]/.test(O[B]??""))B++;let X=O[B];return!X||`;
31
- }#`.includes(X)}function rs(O,D,B){let X="",Q=!1;for(let he=D+1;he<O.length;he++){let je=O[he];if(!je)break;if(Q){let at=vv(O,he);if(!at)return null;X+=at.value,he=at.endIndex,Q=!1;continue}if(je==="\\"){Q=!0;continue}if(je===B)return{value:X,endIndex:he+1};X+=je}return null}function Sv(O,D){let B=O[D];if(B!=='"'&&B!=="'")return null;return rs(O,D,B)}function Cv(O,D,B){if(!D)return null;return D.startIndex>=O&&D.endIndex===B?D.value:null}function vv(O,D){let B=O[D];if(!B)return null;if(B==="x"){let Q=O.slice(D+1,D+3);if(!/^[0-9A-Fa-f]{2}$/.test(Q))return null;return{value:String.fromCharCode(Number.parseInt(Q,16)),endIndex:D+2}}if(/[0-7]/.test(B)){let Q=/^[0-7]{1,3}/.exec(O.slice(D));if(!Q)return null;return{value:String.fromCharCode(Number.parseInt(Q[0],8)),endIndex:D+Q[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
32
- `,r:"\r",t:"\t",v:"\v"}[B]??B,endIndex:D}}function hl(O,D,B){return O.startsWith(B,D)&&!zo(O[D-1])&&!zo(O[D+B.length])}function Ev(O,D){return D!==null&&D>=O}function Tf(O,D){let B=O.indexOf(`
33
- `,D);return B===-1?O.length:B+1}function If(O,D){let B=Rv(O,D);if(B===-1)return!0;if("{([,;!~=".includes(O[B]??""))return!0;let X=B;while(zo(O[X-1]))X--;return mv.has(O.slice(X,B+1))}function Rv(O,D){for(let B=D-1;B>=0;B--)if(!/\s/.test(O[B]??""))return B;return-1}function kf(O,D){let B=!1;for(let X=D;X<O.length;X++){let Q=O[X];if(!Q)break;if(B){B=!1;continue}if(Q==="\\"){B=!0;continue}if(Q==="/")return X+1}return null}var xv=new Set(["sudo","env","command","builtin"]);function os(O,D){let B=O[0];if(!B||!D.transparentWrappers.includes(Tt(B)))return null;let X=Tt(B),Q=O[1]==="--"?2:1,he=_v(O,Q,X,D),je=he[0];if(je===void 0)return null;return{wrapper:X,tokens:[...O.slice(je)],childIndex:je,alternativeChildIndices:he.slice(1)}}function _v(O,D,B,X){let Q=O[1]==="--",he=[];for(let je=D;je<O.length;je++){let at=O[je];if(!at)continue;let lt=Tt(at)!==B&&wv(at,X);if(lt)he.push(je);if(!lt&&pi.has(kt(at)))break;if(Q)break}return he}function wv(O,D){let B=Tt(O),X=kt(O);return X==="git"||B==="busybox"||_r(O)||ua.has(B)||D.transparentWrappers.includes(B)||Kt.has(X)||O==="$SHELL"||wn(X)||vn.has(X)||D.rules.some((Q)=>Q.command===B)}function _r(O){return xv.has(O.toLowerCase())}function wr(O,D){return{embedded:!1,cwd:O.cwd,originalCwd:D.originalCwd,effectiveCwd:O.cwd,envAssignments:O.envAssignments,allowTmpdirVar:D.allowTmpdirVar,worktreeMode:D.worktreeMode,wrappedByTransparent:!1}}function kn(O,D){let B=D.policy??{rules:[],transparentWrappers:[]};return is([...O],D.environment,D.cwd,D.cwd,new Map,new Map(D.envAssignments??[]),B,{iterations:0},!1)}function*is(O,D,B,X,Q,he,je,at,lt){let ct=ji(O,D,B,he);for(let[mt,pt]of ct.envAssignments)he.set(mt,pt),Q.set(mt,pt);let{tokens:ft,cwd:dt}=ct;if(ct.envSplitValues){let mt=Hi(ct.envSplitValues,ft);if(!mt)throw new s("derivedCommandShape");Sl(at),yield*is(mt,D,dt,X,Q,he,je,at,lt);return}if(_r(ft[0]??""))throw new s("wrapperPeelIterations");let ut=os(ft,je);if(ut){for(let mt of[ut.childIndex,...ut.alternativeChildIndices])Sl(at),yield*is(mt===ut.childIndex?ut.tokens:[...ft.slice(mt)],D,dt,X,new Map(Q),new Map(he),je,at,!0);return}if(Av(ft)){Sl(at),yield*is([...ft.slice(1)],D,dt,X,Q,he,je,at,lt);return}yield Pv(ft,dt,X,Q,he,lt)}function Pv(O,D,B,X,Q,he){return{tokens:O,cwd:D===null?void 0:D??B,wrapperCwd:D,wrapperEnvAssignments:X,envAssignments:Q,head:Tt(O[0]??"").toLowerCase(),wrappedByTransparent:he}}function Sl(O){if(O.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");O.iterations++}function Av(O){return Tt(O[0]??"").toLowerCase()==="busybox"&&O.length>1}function Cl(O,D){let B=[],X=D;while(X<O.length){let Q=O[X];if(Q===void 0||Q===":::")break;B.push(Q),X++}return{markerIndex:X<O.length&&O[X]===":::"?X:-1,templateTokens:B}}function On(O){let D=!1,B=!1;for(let X of O){if(X==="--")break;if(X==="-r"||X==="-R"||vl(X,"recursive")){D=!0;continue}if(X==="-f"||vl(X,"force")){B=!0;continue}if(X.startsWith("-")&&!X.startsWith("--")){if(X.includes("r")||X.includes("R"))D=!0;if(X.includes("f"))B=!0}}return D&&B}function Of(O){let D=O.indexOf("--");return O.slice(1,D===-1?void 0:D).some((B)=>vl(B,"recursive")||/^-[A-Za-z]+$/.test(B)&&/[rR]/.test(B.slice(1)))}function vl(O,D){return O.length>2&&O.startsWith("--")&&D.startsWith(O.slice(2))}var Tv="find -delete permanently removes files. Use -print first to preview.",Iv="find -exec rm -rf is dangerous. Use explicit file list instead.",kv=new Set(["-exec","-execdir","-ok","-okdir"]),Ov=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((O)=>[O,1]),["-fprintf",2]]);function Mf(O,D){let B=O.map(t),X=Mv(O,B,D);if(X)return X;if(as(B,1)&&!Nv(O,B,D)){let je=wt(St("find.delete",Tv),D.policy);if(je)return je}let Q=D.budget??fn(),he=0;while(he<B.length){let je=B[he],at=ir(je??"");if(at>0){he+=at+1;continue}if(!jn(je)){he++;continue}Q.charge("derivedTokens",B.length-he-1);let lt=$o(B,he);he=lt.nextIndex;let ct=Wv(lt.tokens,D.environment);if(ct){let mt=wt(ct,D.policy);if(mt)return mt}let ft=je==="-execdir"||je==="-okdir",dt=D.analyzeTokens?D.analyzeTokens(lt.tokens,ft?null:D.cwd):D.analyzeNested?D.analyzeNested(lt.tokens.join(" "),{effectiveCwd:ft?void 0:D.cwd,envAssignments:D.envAssignments}):null,ut=dt?.id.startsWith("custom.")?dt:wt(dt,D.policy);if(ut)return ut}return null}function Mv(O,D,B){if(!as(D,1)&&!El(D,B.environment))return null;let Q=ss(O)??$t(["."]),he=xr({...B,allowPaths:B.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let je of Q){let at=Go(je);for(let lt of at.expandedTargets??[t(je)]){let ct=In(lt,he,{targetIsLiteral:at.expandedTargets!==void 0||at.targetIsLiteral,tmpdirWordSplittingProtected:at.tmpdirWordSplittingProtected});if(ct.kind==="root_or_home_target")return St("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(ct.kind==="git_metadata_target")return St("find.delete-git-metadata",b)}}if(Dv(D)&&he.resolvedCwd&&tf(Q.map(t),he.resolvedCwd,he.protectedGitMetadata,he.environment,he.budget))return St("find.delete-git-metadata",b);return null}function El(O,D){let B=0;while(B<O.length){if(!jn(O[B])){B++;continue}let X=$o(O,B),Q=Cr([...X.tokens],D),he=Tt(Q[0]??"").toLowerCase();if((he==="rm"||he==="rmdir")&&Q.some((je)=>je.includes("{}")))return!0;B=X.nextIndex}return!1}function Dv(O){return O.some((D,B)=>{if(!["-name","-iname"].includes(D))return!1;return O[B+1]?.toLowerCase()==="hooks"})}function Nv(O,D,B){if(D.includes("-L")||D.includes("-f")||D.includes("-follow"))return!1;let X=ss(O);if(!X)return!1;let Q=B.envAssignments??new Map,he=ll(Q,B.environment),je=B.trustedTmpdirValue??Rr(Q,B.environment),at=B.allowTmpdirVar??!Wo(Q,B.environment),lt=xr({environment:B.environment,protectedGitMetadata:B.protectedGitMetadata,cwd:B.cwd,originalCwd:B.originalCwd,strict:B.strict,allowTmpdirVar:at&&je&&Boolean(he),allowPaths:B.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:B.tmpdirWordSplittingUnsafe??or(Q,B.environment),trustedTmpdirValue:je,budget:B.budget});return X.every((ct)=>{let ft=Go(ct);if(ft.unsafeBraceExpansion)return!1;return(ft.expandedTargets??[t(ct)]).every((dt)=>mf(dt,lt,{containmentTarget:Lv(dt,he),targetIsLiteral:ft.expandedTargets!==void 0||ft.targetIsLiteral,tmpdirWordSplittingProtected:ft.tmpdirWordSplittingProtected}))})}function Lv(O,D){if(!D)return O;return O.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>D)}function ss(O){let D=(Q)=>{let he=O[Q];return he?t(he):void 0},B=1;while(D(B)==="-H"||D(B)==="-P")B++;if(D(B)==="--")B++;let X=[];while(B<O.length){let Q=D(B),he=O[B];if(!Q||!he||Q.startsWith("-")||["!","(",")"].includes(Q))break;X.push(he),B++}return X.length>0?X:null}function Wv(O,D){let B=nr([...O],D);if(B.length===0)return null;let X=Tt(B[0]??"");if(X==="busybox"&&B.length>1)B=B.slice(1),X=Tt(B[0]??"");if(X==="rm"&&On(B))return St("find.exec-rm-recursive-force",Iv);return null}function $o(O,D){let B=D+1;while(B<O.length&&O[B]!==";"&&!(O[B]==="+"&&O[B-1]==="{}"))B++;return{tokens:O.slice(D+1,B),nextIndex:Math.min(B+1,O.length)}}function as(O,D){let B=D;while(B<O.length){let X=O[B];if(!X){B++;continue}if(jn(X)){B=$o(O,B).nextIndex;continue}let Q=ir(X);if(Q>0){B+=Q+1;continue}if(X==="-delete")return!0;B++}return!1}function ir(O){return Ov.get(O)??(/^-newer[A-Za-z]{2}$/.test(O)?1:0)}function jn(O){return O!==void 0&&kv.has(O)}function*Rl(O){for(let D of O.nodes)yield*Gv(D)}function Fv(O){return Object.freeze([...Rl(O)])}function st(O){return Object.freeze(Fv(O).map((D)=>Object.freeze(D.words.map((B)=>B.text))))}function Uo(O){let D=h(O,"posix");if(D.status!=="complete"||D.nodes.length!==1)return null;let B=D.nodes[0];if(B?.kind!=="command")return null;if(B.redirections.length>0||B.nested.length>0)return null;if(B.words.some((X)=>X.provenance==="command-substitution"))return null;return B.words.map((X)=>X.text)}function*Gv(O){if(O.kind==="command"){yield O;for(let D of O.nested)yield*Rl(D);return}if(O.kind==="group")yield*Rl(O.body)}var zv=5,xl="Git aliases supplied through command-line or environment config can hide or execute commands. Run git without Git alias overrides, or ask the user to run it manually.";function rn(O){let D=O.indexOf("--");if(D===-1)return{index:-1,before:O,after:[]};return{index:D,before:O.slice(0,D),after:O.slice(D+1)}}function Nf(O,D,B){let X=ls(O,D,B),Q=Bv(X.entries);if(Q.size===0)return{blockedReason:X.blockedReason,expanded:!1,tokens:O};let he=O,je=!1;for(let at=0;at<zv;at++){let{subcommand:lt,rest:ct}=Mn(he),ft=lt?.toLowerCase();if(!ft||!Q.has(ft))return{blockedReason:X.blockedReason,expanded:je,tokens:he};let dt=Q.get(ft),ut=Vv(dt);if(ut===null||ut.length===0)return{blockedReason:xl,expanded:!0,tokens:he};he=["git",...ut,...ct],je=!0}return{blockedReason:xl,expanded:!0,tokens:he}}function Lf(O,D,B){return ls(O,D,B).entries.some((X)=>X.key.toLowerCase()==="core.sshcommand")}function Mn(O){if(O.length===0)return{subcommand:null,rest:[]};let D=O[0];if((D?Tt(D).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let X=1;while(X<O.length){let Q=O[X];if(!Q)break;if(Q==="--"){let he=O[X+1];if(he&&!he.startsWith("-"))return{subcommand:he,rest:O.slice(X+2)};return{subcommand:null,rest:O.slice(X+1)}}if(!Q.startsWith("-"))return{subcommand:Q,rest:O.slice(X+1)};X+=pn.has(Q)?2:1}return{subcommand:null,rest:[]}}function Bv(O){let D=new Map;for(let B of O){let X=B.key.toLowerCase();if(!X.startsWith("alias."))continue;let Q=X.slice(6);if(Q!=="")D.set(Q,B.value)}return D}function ls(O,D,B){if(O.length===0)return{blockedReason:null,entries:[]};let X=O[0];if((X?Tt(X).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let he=Uv(D,B);return{blockedReason:he.blockedReason,entries:[...he.entries,...$v(O,D,B)]}}function $v(O,D,B){let X=[],Q=1;while(Q<O.length){let he=O[Q];if(!he||he==="--"||!he.startsWith("-"))return X;if(he==="-c"){let je=_l(O[Q+1]);if(je)X.push(je);Q+=2;continue}if(he.startsWith("-c")&&he.length>2){let je=_l(he.slice(2));if(je)X.push(je);Q++;continue}if(he==="--config-env"){let je=Df(O[Q+1],D,B);if(je)X.push(je);Q+=2;continue}if(he.startsWith("--config-env=")){let je=Df(he.slice(13),D,B);if(je)X.push(je);Q++;continue}if(pn.has(he)){Q+=2;continue}Q++}return X}function Uv(O,D){let B=Hv(O,D),X=jv(O,D);return{blockedReason:B===null||X===null?xl:null,entries:[...B??[],...X??[]]}}function Hv(O,D){let B=Un("GIT_CONFIG_PARAMETERS",O,D);if(B===void 0)return[];let X=[],Q=Uo(B);if(!Q)return null;for(let he of Q){let je=_l(he);if(!je)return null;X.push(je)}return X}function jv(O,D){let B=Td(O,D);if(B.state==="absent")return[];if(B.state==="invalid")return null;let X=[];for(let Q=0;Q<B.count;Q++){let he=Un(`GIT_CONFIG_KEY_${Q}`,O,D)?.trim(),je=Un(`GIT_CONFIG_VALUE_${Q}`,O,D);if(!he||je===void 0)return null;X.push({key:he,value:je})}return X}function _l(O){if(!O)return null;let D=O.indexOf("=");return{key:(D===-1?O:O.slice(0,D)).trim(),value:D===-1?void 0:O.slice(D+1)}}function Df(O,D,B){let X=O?.indexOf("=")??-1;if(!O||X===-1)return null;return{key:O.slice(0,X).trim(),value:Un(O.slice(X+1),D,B)}}function Vv(O){let D=O?.trimStart();if(!D||D.startsWith("!"))return null;return Uo(D)}var Kv="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",qv="git checkout --force discards uncommitted changes. Use 'git stash' first.",Yv="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",Zv="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",Xv="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",Jv="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",Qv="git switch --force discards uncommitted changes. Use 'git stash' first.",eE="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",tE="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",nE="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",rE="git reset --merge can lose uncommitted changes. Use 'git stash' first.",oE="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",iE="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.",sE="git push --force destroys remote history. Use --force-with-lease for safer force push.",aE="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",lE="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",cE="git branch -D force-deletes without merge check. Use -d for safe delete.",uE="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",dE="git merge --abort discards merge conflict resolutions. Use 'git status' first.",fE="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",mE="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",pE="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",gE="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",hE="git worktree remove --force can delete uncommitted changes. Remove --force flag.",yE=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),bE=new Set(["--recurse-submodules","--track","-t"]),wl=new Set(["-b","-B","-U"]),Pl=new Set(["-c","-C"]),SE=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function It(O,D){let B=O.split("=",1)[0]??O;return B.length>=4&&D.startsWith(B)&&B.startsWith("--")&&B.slice(2).length>=2}var Xr=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function Ff(O){let{subcommand:D,rest:B}=Mn(O);if(!D)return null;switch(D.toLowerCase()){case"checkout":return sr(CE(B));case"switch":return sr(vE(B));case"restore":return sr(RE(B));case"reset":return _E(B);case"clean":return sr(PE(B));case"rm":return sr(AE(B));case"push":return Pr(TE(B));case"branch":return Pr(OE(B));case"stash":return Pr(WE(B));case"worktree":return Pr(FE(B));case"rebase":return sr(ME(B));case"merge":return sr(DE(B));case"tag":return Pr(NE(B));case"reflog":return Pr(LE(B));default:return null}}function sr(O){return O?{...O,localDiscard:!0}:null}function Pr(O){return O?{...O,localDiscard:!1}:null}function CE(O){let{index:D,before:B}=rn(O),X=sn(B,{shortOptsWithValue:wl});if(B.some((he)=>It(he,"--force"))||X.has("-f"))return St("git.checkout-force",qv);for(let he of O){if(he==="-b"||he==="-B"||he==="--orphan")return null;if(It(he,"--pathspec-from-file"))return St("git.checkout-pathspec-from-file",Zv)}if(D!==-1){if(B.some((je)=>!je.startsWith("-")))return St("git.checkout-ref-path",Yv);return St("git.checkout-double-dash",Kv)}if(EE(O).length>=2)return St("git.checkout-ambiguous",Xv);return null}function vE(O){let{before:D}=rn(O);if(D.some((X)=>It(X,"--discard-changes")))return St("git.switch-discard-changes",Jv);let B=sn(D,{shortOptsWithValue:Pl});if(D.some((X)=>It(X,"--force"))||B.has("-f"))return St("git.switch-force",Qv);return null}function EE(O){let D=[],B=0;while(B<O.length){let X=O[B];if(!X)break;if(X==="--")break;if(!X.startsWith("-")){D.push(X),B++;continue}if(yE.has(X)){B+=2;continue}if(bE.has(X)){let Q=O[B+1],he=X==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"];B+=Q&&!Q.startsWith("-")&&he.includes(Q)?2:1;continue}B++}return D}function RE(O){let D=xE(O);if(D.isTerminal||!D.hasPathspec&&!D.hasPatch||!D.hasWorktree)return null;return D.hasExplicitLocation?St("git.restore-worktree",tE):St("git.restore-unstaged",eE)}function xE(O){let D=!1,B=!1,X=!0,Q=!1,he=(je)=>{if(!Q)X=!1,Q=!0;if(je!==void 0)X=je};for(let je=0;je<O.length;je++){let at=O[je];if(at===void 0)break;if(at==="--"){D||=je+1<O.length;break}if(at==="--pathspec-from-file"){D=!0,je++;continue}if(at.startsWith("--pathspec-from-file=")){D=!0;continue}if(at==="-h"||at==="--help"||at==="--version")return{hasPathspec:D,hasPatch:B,hasWorktree:X,hasExplicitLocation:Q,isTerminal:!0};if(at==="--staged"){he();continue}if(at==="--no-staged"){he();continue}if(at==="--worktree"){he(!0);continue}if(at==="--no-worktree"){he(!1);continue}if(at==="--patch"){B=!0;continue}if(at==="--no-patch"){B=!1;continue}if(SE.has(at)){je++;continue}if(at.startsWith("--"))continue;if(at==="-"){D=!0;continue}if(!at.startsWith("-")){D=!0;continue}for(let lt=1;lt<at.length;lt++){let ct=at.charAt(lt);if(ct==="h")return{hasPathspec:D,hasPatch:B,hasWorktree:X,hasExplicitLocation:Q,isTerminal:!0};if(ct==="S"){he();continue}if(ct==="W"){he(!0);continue}if(ct==="p"){B=!0;continue}if(ct==="s"||ct==="U"){if(lt===at.length-1)je++;break}}}return{hasPathspec:D,hasPatch:B,hasWorktree:X,hasExplicitLocation:Q,isTerminal:!1}}function _E(O){let D=null;for(let B of O){if(It(B,"--hard")){D=St("git.reset-hard",nE);break}if(It(B,"--merge")){D=St("git.reset-merge",rE);break}}if(!D)return null;return wE(O)?Pr(D):sr(D)}function wE(O){for(let D of O){if(D==="--")return!1;if(!D.startsWith("-"))return!0}return!1}function PE(O){for(let B of O)if(B==="-n"||It(B,"--dry-run"))return null;let D=sn(O.filter((B)=>B!=="--"));if(O.some((B)=>It(B,"--force"))||D.has("-f"))return St("git.clean-force",oE);return null}function AE(O){let D=!1,B=!1,X=!1;for(let Q of rn(O).before){if(It(Q,"--no-force")){D=!1;continue}if(It(Q,"--force")){D=!0;continue}if(It(Q,"--no-cached")){B=!1;continue}if(It(Q,"--cached")){B=!0;continue}if(It(Q,"--no-dry-run")){X=!1;continue}if(It(Q,"--dry-run")){X=!0;continue}let he=sn([Q]);D||=he.has("-f"),X||=he.has("-n")}return D&&!B&&!X?St("git.rm-force",iE):null}function TE(O){let{before:D,after:B}=rn(O),X=sn(D);if(D.some((je)=>It(je,"--mirror")))return St("git.push-mirror",lE);if(D.some((je)=>It(je,"--force"))||X.has("-f")||Wf(D,B).some(IE))return St("git.push-force",sE);if(D.some((je)=>It(je,"--delete"))||X.has("-d")||Wf(D,B).some(kE))return St("git.push-delete",aE);return null}function Wf(O,D){return[...O.filter((B)=>B!==""&&!B.startsWith("-")),...D]}function IE(O){return O.startsWith("+")||O.includes(":+")}function kE(O){return O.length>1&&O.startsWith(":")}function OE(O){let{before:D}=rn(O),B=sn(D),X=B.has("-D")||B.has("-d")||D.some((he)=>It(he,"--delete")),Q=B.has("-D")||B.has("-f")||D.some((he)=>It(he,"--force"));if(X&&Q)return St("git.branch-force-delete",cE);return null}function ME(O){let{before:D}=rn(O);return D.some((B)=>It(B,"--abort"))?St("git.rebase-abort",uE):null}function DE(O){let{before:D}=rn(O);return D.some((B)=>It(B,"--abort"))?St("git.merge-abort",dE):null}function NE(O){let{before:D}=rn(O);return sn(D).has("-d")||D.some((X)=>It(X,"--delete"))?St("git.tag-delete",fE):null}function LE(O){return O[0]==="delete"?St("git.reflog-delete",mE):null}function WE(O){for(let D of O){if(D==="drop")return St("git.stash-drop",pE);if(D==="clear")return St("git.stash-clear",gE)}return null}function FE(O){let{before:D}=rn(O);if(!D.includes("remove"))return null;let X=sn(D);if(D.some((Q)=>It(Q,"--force"))||X.has("-f"))return St("git.worktree-remove-force",hE);return null}import{resolve as GE}from"node:path";function zf(O,D){return Qa.some((B)=>D?.has(B)||O.has(B))}function Bf(O,D,B){if(!D)return{gitCwd:null,hasExplicitGitContext:!1};let X=B.realpath(GE(D));if(X===null||!B.isDirectory(X))return{gitCwd:null,hasExplicitGitContext:!1};let Q=X,he=!1,je=1;while(je<O.length){let at=O[je];if(!at)break;if(at==="--")break;if(!at.startsWith("-"))break;if(at==="-C"){let lt=O[je+1];if(!lt)return{gitCwd:null,hasExplicitGitContext:he};let ct=Gf(Q,lt,B);if(!ct)return{gitCwd:null,hasExplicitGitContext:he};Q=ct,je+=2;continue}if(at.startsWith("-C")&&at.length>2){let lt=Gf(Q,at.slice(2),B);if(!lt)return{gitCwd:null,hasExplicitGitContext:he};Q=lt,je++;continue}if(at==="--git-dir"||at==="--work-tree"){he=!0,je+=2;continue}if(at.startsWith("--git-dir=")||at.startsWith("--work-tree=")){he=!0,je++;continue}je+=pn.has(at)?2:1}return{gitCwd:Q,hasExplicitGitContext:he}}function Gf(O,D,B){try{let X=tr(O,D,B);return B.isDirectory(X)?X:null}catch{return null}}function $f(O,D,B){if(!D.localDiscard||!B.worktreeMode||zf(B.environment.env,B.envAssignments))return null;let X=Bf(O,B.cwd,B.environment.paths);if(!X.gitCwd||X.hasExplicitGitContext)return null;let Q=B.environment.worktreeFacts(X.gitCwd);if(!Q)return null;if(zE(O,B,Q))return null;return{originalReason:D.reason,gitCwd:X.gitCwd}}function zE(O,D,B){let{subcommand:X,rest:Q}=Mn(O),he=X?.toLowerCase();if(D.dynamicArguments||BE(Q)||VE(O,D.environment.env,D.envAssignments,B)||HE(Q)||$E(he,Q))return!0;return he==="clean"&&jE(Q)>1}function BE(O){return O.some((D)=>/[$*?[]/.test(D))}function $E(O,D){if(O==="checkout"){let{before:B}=rn(D),X=sn(B,{shortOptsWithValue:wl}),Q=B.some((je)=>It(je,"--force"))||X.has("-f"),he=X.has("-B")||B.some((je)=>je==="-B"||je.startsWith("-B"));return Q&&he}if(O==="switch"){let{before:B}=rn(D),X=sn(B,{shortOptsWithValue:Pl}),Q=B.some((je)=>It(je,"--force"))||B.some((je)=>It(je,"--discard-changes"))||X.has("-f"),he=B.some((je)=>je==="-C"||je.startsWith("-C")||UE(je))||X.has("-C");return Q&&he}return!1}function UE(O){let D=O.split("=",1)[0]??O;return D==="--force-create"||D.length>=9&&"--force-create".startsWith(D)}function HE(O){return O.some((D)=>D.startsWith("--recurse-sub"))}function jE(O){let D=0;for(let B of O){if(B==="--force"){D++;continue}if(B.startsWith("-")&&!B.startsWith("--")){for(let X of B.slice(1))if(X==="f")D++}}return D}function VE(O,D,B,X){if(Un("GIT_CONFIG_PARAMETERS",D,B)!==void 0)return!0;let Q=ls(O,D,B);if(Q.blockedReason!==null)return!0;let he=Q.entries.map((at)=>({key:at.key.toLowerCase(),value:at.value}));if(he.some((at)=>qE(at.key)))return!0;let je=he.filter((at)=>at.key==="submodule.recurse").at(-1);if(je)return je.value===void 0||KE(je.value);if(kd(B))return!0;return X.recursiveSubmodules}function KE(O){let D=O.toLowerCase();return D!=="false"&&D!=="no"&&D!=="off"&&D!=="0"}function qE(O){return O==="include.path"||O.startsWith("includeif.")&&O.endsWith(".path")}var YE="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.",ZE=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function cs(O,D){return Uf(O.map(t),D)}function Uf(O,D,B){let X=Nf(O,D.environment.env,D.envAssignments),Q=X.blockedReason?wt(St("git.alias-config",X.blockedReason),D.policy):null;if(Q)return Q;let he=X.tokens;if((Id(D.envAssignments)||Lf(O,D.environment.env,D.envAssignments))&&XE(he))return St("git.ssh-env",YE);let je=Ff(he);if(!je)return null;if(X.expanded||X.blockedReason)return je;let at=$f(O,je,D);if(!at)return je;return B?.(at),null}function Hf(O,D){let B=null;return{match:Uf(O.map(t),D,(Q)=>{B=Q}),relaxation:B}}function XE(O){let{subcommand:D,rest:B}=Mn(O),X=D?.toLowerCase();if(!X)return!1;if(ZE.has(X))return!0;if(X==="archive")return rn(B).before.some((Q)=>It(Q,"--remote"));return X==="remote"&&JE(B)}function JE(O){return O.find((D)=>!QE(D))?.toLowerCase()==="update"}function QE(O){return O==="-v"||It(O,"--verbose")||It(O,"--no-verbose")}import{isAbsolute as DR}from"node:path";function jf(O,D,B,X){let Q=O.slice(0,D),he=O.slice(D+B);return X.startsWith(Q)&&X.endsWith(he)?X.slice(Q.length,X.length-he.length):null}function us(O,D,B){let X=(he)=>`${he.tokenIndex}\x00${he.kind}\x00${he.value}`,Q=new Set(O.map(X));return Array.from(D).some((he)=>B(he).some((je)=>!Q.has(X(je))))}var Vf="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",eR="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.",tR="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",qf="rm -rf targeting root or home directory is extremely dangerous and always blocked.",nR="rm -rf in home directory is dangerous. Change to a project directory first.",Kf={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:qf},git_metadata_target:{id:"rm.git-metadata",reason:b},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:tR},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:nR},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:Vf},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:eR},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:Vf}};function ds(O,D){let B=xr({...D,allowPaths:D.policy?.destructiveCommandAllowPaths,posixShell:!0}),X=O.map(t),Q=On(X),he=Of(X),je=oR(O);for(let at of je){let lt=Go(at.word);if(Q&&lt.unsafeBraceExpansion){let ct=wt(Fo({kind:"outside_anchored_cwd"},B,D.policy,Kf),D.policy);if(ct)return ct;continue}for(let ct of lt.expandedTargets??[at.text]){let ft=mn(ct),dt={targetIsLiteral:lt.expandedTargets!==void 0||lt.targetIsLiteral,tmpdirWordSplittingProtected:lt.tmpdirWordSplittingProtected};if(!he&&B.resolvedCwd&&Er(ft,B.resolvedCwd,B.protectedGitMetadata,he,B.environment,B.budget))return St("rm.git-metadata",b);if(he&&!Q){let ut=In(ft,B,dt);if(ut.kind==="root_or_home_target")return St("rm.recursive-force-root-or-home",qf);if(ut.kind==="git_metadata_target")return St("rm.git-metadata",b);continue}if(!Q)continue;for(let ut of rR(ft,B,dt)){let mt=Fo(ut,B,D.policy,Kf),pt=wt(mt,D.policy);if(pt)return pt}}}return null}function rR(O,D,B){let X=In(O,D,B);if(X.kind==="cwd_self_target")return[X,In(O,D,{...B,skipCwdSelf:!0})];if(X.kind!=="home_cwd_target")return[X];let Q=In(O,D,{...B,skipHomeCwd:!0});if(Q.kind!=="cwd_self_target")return[X,Q];return[X,Q,In(O,D,{...B,skipHomeCwd:!0,skipCwdSelf:!0})]}function oR(O){let D=[],B=!1;for(let X of O.slice(1)){let Q=t(X);if(!Q)continue;if(Q==="--"){B=!0;continue}if(B){D.push({text:Q,word:X});continue}if(!Q.startsWith("-"))D.push({text:Q,word:X})}return D}var ar={kind:"none"},Ar={kind:"dynamic"},iR=new Set(["<","<<","<<-","<<<","<&","<>"]),Zf=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,sR=/^(?:[0-9]+|[@*])$/,aR=er.maxWords,lR=er.maxInputLength;function Xf(O){if(!O||Tt(kt(O.words[0]?.text??""))!=="printf")return;if(O.words.some((Q)=>Q.provenance!=="literal"))return;let D=O.words.slice(O.words[1]?.text==="--"?2:1),B=D[0]?.text;if(B===void 0)return"";let X=D.slice(1).map((Q)=>Q.text);if(B==="%s")return X.join("");if(B==="%s\\n"||B===`%s
34
- `)return`${X.join(`
35
- `)}
36
- `;if(B.includes("%")||/\\(?![\\nrt])/.test(B))return;return B.replaceAll("\\n",`
37
- `).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function fs(O){let D=Ho(O[1])==="--"?2:1;if(O.length<=D)return ar;let B=O.slice(D);if(!B.every(ps))return Ar;return{kind:"literal",source:B.map(t).join(" ")}}function Jf(O){let D=Ho(O[1])==="--"?2:1,B=O[D],X=Ho(B);if(B===void 0||O.length<=D+1||X==="-"||X===""||X==="-l"||X==="-p")return ar;if(!ps(B))return Ar;return{kind:"literal",source:X}}function ms(O,D){let B=uR(O);if(B===-1)return ar;let X=dR(D);if(!X)return ar;let Q=[],he=X.command?.length??0;for(let je of X.references){let at=mR(je,O,B,X.ifs);if(!at)return Ar;if(he+=at.reduce((lt,ct)=>lt+ct.length+3,0),Q.length+at.length>aR||he>lR)return Ar;Q.push(...at)}if(X.command==="eval")return{kind:"literal",source:Q.join(" ")};if(Q.length===0||/\s/.test(Q[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[X.command,X.command&&X.optionTerminator?"--":null,...Q.map(gR)].filter((je)=>je!==null).join(" ")}}function Qf(O,D,B,X){if(!gn(O.map(t)).readsStdinAsCommands)return ar;let Q=D.filter((he)=>(he.fd===void 0||he.fd===0)&&iR.has(he.operator)).at(-1);if(Q){if(Q.operator==="<<"||Q.operator==="<<-")return ar;if(Q.operator!=="<<<"||Q.target?.provenance!=="literal")return Ar;return{kind:"literal",source:Q.target.text}}if(!B)return ar;return X===void 0?Ar:{kind:"literal",source:X}}function Vn(O){let D=gn(O.map(t)).scriptIndex;if(D===null)return ar;let B=O[D],X=Ho(B);return Li(B,X)?{kind:"literal",source:X}:Ar}var cR=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function kl(O){if(O.words.length!==2||O.redirections.length!==0||O.nested.length!==1)return!1;let D=O.words[0],B=O.words[1];if(!D||D.provenance!=="literal"||D.quoted||D.raw!==D.text||!B)return!1;if(!(D.text==="eval"&&B.quoted&&B.parts.length===3&&B.parts[0]?.raw==='"'&&B.parts[1]?.provenance==="command-substitution"&&B.parts[1].raw.startsWith("$(")&&B.parts[2]?.raw==='"'||(D.text==="source"||D.text===".")&&!B.quoted&&B.parts.length===1&&B.parts[0]?.provenance==="command-substitution"&&B.parts[0].raw.startsWith("<(")))return!1;let Q=O.nested[0];if(Q?.status!=="complete"||Q.nodes.length!==1)return!1;let he=Q.nodes[0];if(he?.kind!=="command"||he.redirections.length!==0||he.nested.length!==0||he.words.some((lt)=>lt.provenance!=="literal"||lt.parts.some((ct)=>ct.provenance!=="literal")))return!1;let je=he.words[0]?.text;if(je===void 0||En(je)!==null)return!1;let at=Tt(kt(je));return!cR.has(at)&&!Kt.has(at)&&!_r(at)}function uR(O){return gn(O.map(t)).commandIndex??-1}function dR(O){let D=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(O.trim()),B=D?.[4]??O.trim(),X=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(B),Q=(X?.[3]??B).split(/\s+/).map(fR);if(Q.length===0||Q.some((he)=>he===null))return null;return{command:X?.[1]??null,optionTerminator:X?.[2]!==void 0,references:Q.filter((he)=>!!he),ifs:D?D[1]??D[2]??D[3]??"":`
38
- `}}function fR(O){let D=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(O),B=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(O),X=D??B;if(!X)return null;let Q=X[1]??X[2];return{parameter:Q==="@"||Q==="*"?Q:Number(Q),quoted:D!==null}}function mR(O,D,B,X){let Q=D.slice(B+2);if(O.parameter==="@")return O.quoted?Al(Q):pR(Q,X);if(O.parameter==="*"){let at=Al(Q);if(!at)return;let lt=at.join(X[0]??"");return O.quoted?[lt]:Tl(lt,X)}let he=D[B+1+O.parameter];if(he&&!ps(he))return;let je=Ho(he);return O.quoted?[je]:Tl(je,X)}function Al(O){return O.every(ps)?O.map(t):void 0}function pR(O,D){let B=Al(O);if(!B)return;let X=B.map((Q)=>Tl(Q,D));return X.some((Q)=>Q===void 0)?void 0:X.flatMap((Q)=>Q??[])}function Tl(O,D){if(["*","?","[","]"].some((B)=>O.includes(B)))return;if(D==="")return O===""?[]:[O];if(D===`
39
- `)return O.trim().split(/\s+/).filter(Boolean);if(D.length!==1)return;return D===" "||D==="\t"||D===`
40
- `?O.trim().split(/\s+/).filter(Boolean):O.split(D).filter(Boolean)}function ps(O){if(!O)return!0;return O.provenance==="unknown"?!/[$`]/.test(t(O)):O.provenance==="literal"}function Ho(O){return O?t(O):""}function gR(O){return`'${O.replaceAll("'",`'"'"'`)}'`}function Ol(O,D){return Il(h(O,"posix"),D)}function Vo(O){return Ol(O,new Set(Array.from(O.matchAll(Zf)).flatMap((D)=>{let B=D[1]??D[2];return B===void 0?[]:[B]})))}function Il(O,D){if(O.status==="invalid"||O.status==="limited")return!1;let B=new Set(D);for(let X of O.nodes){if(X.kind==="group"){if(Il(X.body,B))return!0;continue}if(X.kind!=="command")continue;if(X.nested.some((Q)=>Il(Q,B))||em(X.words,B))return!0;CR(X,B)}return!1}function em(O,D){let B=O.findIndex((je)=>En(je.text)===null);if(B===-1)return!1;let X=O[B];if(!X)return!1;if(jo(X,D))return!0;let Q=kt(X.text);if(Q==="source"||Q==="."){let je=O[B+1]?.text==="--"?B+2:B+1;return Yf(O[je],D)}if(Kt.has(Q)){let je=O.slice(B),at=gn(je.map((ct)=>ct.text)),lt=at.commandIndex??at.scriptIndex;return!at.syntaxCheck&&lt!==null&&Yf(je[lt],D)}let he=hR(O,B,D);if(he===null)return!1;if(he===-1)return!0;return em(O.slice(he),D)}function hR(O,D,B){let X=kt(O[D]?.text??"");if(X==="command")return yR(O,D+1);if(X==="exec")return bR(O,D+1);if(X==="env")return SR(O,D+1,B);return null}function yR(O,D){for(let B=D;B<O.length;B++){let X=O[B]?.text??"";if(X==="--")return O[B+1]?B+1:null;if(/^-[p]*[vV][pvV]*$/.test(X))return null;if(/^-p+$/.test(X))continue;return B}return null}function bR(O,D){for(let B=D;B<O.length;B++){let X=O[B]?.text??"";if(X==="--")return O[B+1]?B+1:null;if(X==="-a"){B++;continue}if(/^-a.+/.test(X)||/^-[cl]+$/.test(X))continue;return B}return null}function SR(O,D,B){for(let X=D;X<O.length;X++){let Q=O[X],he=Q?.text??"";if(he==="--")return O[X+1]?X+1:null;if(he==="-S"||he==="--split-string")return jo(O[X+1],B)?-1:X+2;if(he.startsWith("-S")||he.startsWith("--split-string="))return jo(Q,B)?-1:X+1;if(he==="-u"||he==="--unset"||he==="-C"||he==="--chdir"||he==="-P"){X++;continue}if(he==="-i"||he==="-0"||he==="--null"||he.startsWith("-u=")||he.startsWith("--unset=")||he.startsWith("-C")||he.startsWith("--chdir=")||he.startsWith("-P"))continue;if(he.startsWith("-"))continue;if(En(he))continue;return X}return null}function CR(O,D){if(!O.words.every((B)=>En(B.text)!==null))return;for(let B of O.words){let X=En(B.text);if(!X)continue;if(jo(B,D))D.add(X.name)}}function jo(O,D){if(!O)return!1;return O.parts.filter((B)=>B.provenance==="variable").some((B)=>Array.from(B.raw.matchAll(Zf)).some((X)=>{let Q=X[1]??X[2];return Q!==void 0&&(sR.test(Q)||D.has(Q))}))}function Yf(O,D){return!!O&&(O.parts.some((B)=>B.provenance!=="literal"&&B.provenance!=="variable")||jo(O,D))}var vR=["--init-file","--rcfile"],ER=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function Kn(O){for(let D=1;D<O.length;D++){let B=O[D];if(!B)continue;if(B==="-c")return tm(O,D,!0);if(B.startsWith("-")&&B.includes("c")&&!B.startsWith("--")){let X=tm(O,D,!1);if(X!==null)return X}}return null}function qn(O){let D=Tt(O[0]??"").toLowerCase();if(D==="zsh"||D==="ksh")return gn(O).syntaxCheck;let B=!1;for(let X of O.slice(1)){if(X==="--")return B;if(X.startsWith("+")&&!X.startsWith("++")){if(X.slice(1).includes("n"))B=!1;continue}if(!X.startsWith("-")||X.startsWith("--"))return B;let Q=X.slice(1);if(Q.includes("n"))B=!0;if(Q.includes("c"))return B}return B}function tm(O,D,B){if(O[D+1]==="--")return O[D+2]||null;let X=O[D+1];if(!X||!B&&X.startsWith("-"))return null;return X}function nm(O){let D=Tt(O[0]??"").toLowerCase(),B=RR(O,D),X=ER.get(D)??null,Q=B.argvSource?.kind!=="absent";return{argvSource:D==="bash"?B.argvSource:null,argvSourceApplies:D==="bash"&&B.interactive&&B.argvSource?.kind==="literal",envName:X,envSourceApplies:Q&&(X==="BASH_ENV"?!B.interactive:X==="ENV"&&B.interactive)}}function RR(O,D){let B=gn(O),X=B.commandIndex??B.scriptIndex??O.length,Q=[],he=!1,je=!0;for(let at=1;at<X;at++){let lt=O[at];if(lt===void 0||lt==="--"||lt==="-"||lt[0]!=="-"&&lt[0]!=="+")break;if(lt.startsWith("--")){if(D==="bash"&&je?vR.find((ut)=>lt===ut):void 0){let ut=O[at+1];Q.push(ut===void 0?{kind:"absent"}:{kind:"literal",value:ut}),at++;continue}let dt=lt.split("=",1)[0]??lt;if(D==="bash"&&la.has(dt)&&!lt.includes("="))at++;continue}if(D==="bash")je=!1;let ct=ca(D,lt,O[at+1],"startup");if(ct.interactive)he=lt[0]==="-";at+=ct.followingValues}return{argvSource:Q.at(-1)??null,interactive:he}}var Ml="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",Dl="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",xR="__CC_SAFETY_NET_XARGS_INPUT__",gs="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",hs="rm",_R=/(?:^|[;&|]\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,wR=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,PR=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,AR=/^(?:[0-9]+|[@*])$/;function im(O,D){let B=O.map(t),{childStart:X,replacementToken:Q}=Tr(B),he=B.slice(X),je=St("xargs.shell-dynamic",Dl);if(IR(he,Q,D)&&wt(je,D.policy))return wt(je,D.policy);for(let at of kn(he,D)){let lt=at.tokens,ct=Q!==null&&lt[0]!==he[0]&&(lt[0]?.includes(Q)??!1)?wt(je,D.policy):null;if(ct)return ct;let ft=um(lt,Q,at.wrapperEnvAssignments),dt=at.head==="rm"&&Q!==null&&lm(lt,Q),ut=D.analyzeChild(lt,{...wr(at,D),dynamicInput:ft,dynamicSourceInput:dt||am(lt,at.head,Q,at.wrapperEnvAssignments,ft,D.environment),dynamicRmInput:dt,shellDynamicMatch:je,dynamicSourceMatch:je,rmDynamicMatch:St("xargs.rm-recursive-force-dynamic",Ml)});if(ut)return ut;let mt=TR(lt,Q,D.policy?.rules??[],wt(je,D.policy));if(mt)return mt;if(at.head==="git"){let ht=Q===null?[...lt,xR]:lt,gt=Q!==null&&(lt.some((vt)=>vt.includes(Q))||Array.from(at.envAssignments.values()).some((vt)=>vt.includes(Q))),yt=D.analyzeChild(ht,{...wr(at,D),worktreeMode:Q===null||gt?!1:D.worktreeMode});if(yt)return yt}let pt=_(lt,D.policy?.rules??[]);if(pt)return pt}return null}function TR(O,D,B,X){if(B.length===0)return null;if(D===null){for(let he of B){let je=_([...O,...he.subcommand?[he.subcommand]:[],...he.block_args],B);if(je)return je}return null}let Q=kt(O[0]??"");if(!B.some((he)=>kt(he.command)===Q))return null;return O.slice(1).some((he)=>he.includes(D))?X:null}function sm(O,D,B){let X=O.indexOf(D);if(X===-1||O.indexOf(D,X+D.length)!==-1)return[];let Q=jf(O,X,D.length,B);return Q===null?[]:[Q]}function am(O,D,B,X,Q,he){if(Kt.has(D)){if(qn(O))return!1;if(B!==null&&kR(O,B))return!0;let je=Kn(O);if(!je){let at=Vn($t(O));if(at.kind==="literal")return B!==null&&at.source.includes(B);return at.kind==="none"&&Q}if(B!==null&&je.includes(B))return!0;if($n(je))return!0;return OR(je,B,X)}if(wn(D))return rm(O,B,Bi,wd(D));if(vn.has(D))return rm(O,B,yl,Pf);if(D==="eval"){let je=fs($t(O));if(je.kind==="dynamic")return!0;if(B!==null)return je.kind==="literal"&&je.source.includes(B);return Q}if(D==="find")return MR(O,B,he);if(D==="git"){let je=Mn(O);return B===null?je.subcommand===null:(je.subcommand?.includes(B)??!1)||je.subcommand!==null&&Xr.has(je.subcommand.toLowerCase())&&cm(je.rest,B).some((at)=>at.includes(B))}return!1}function rm(O,D,B,X){let Q=B(O);if(D===null)return Q.optionsOpen||B([...O,gs]).sources.some((at)=>at.value===gs);if(Q.sources.some((at)=>at.value.includes(D)))return!0;let he=X.flatMap((at)=>[at.selector,...at.valueForm==="attached-only"||at.valueForm==="attached-or-separate"?[`${at.selector}${gs}`]:[],...at.valueForm==="equals-or-separate"?[`${at.selector}=${gs}`]:[]]),je=new Set(he.flatMap((at)=>O.flatMap((lt)=>sm(lt,D,at))));return us(Q.sources,je,(at)=>B(O.map((lt)=>lt.replaceAll(D,at))).sources)}function IR(O,D,B){if(O.length===0||(O[0]??"").toLowerCase()==="command")return!1;let X=new Set(Array.from(kn(O,B),(he)=>he.head)),Q=D===null?[...O,hs]:O.map((he,je)=>je===0?he:he.replaceAll(D,hs));return Array.from(kn(Q,B)).some((he)=>he.head===hs&&!X.has(hs))}function lm(O,D){return cm(O.slice(1),D).some((B)=>B.includes(D)&&(B.startsWith("-")||B.startsWith(D)))}function cm(O,D){let B=O.findIndex((X)=>X==="--"&&!X.includes(D));return B===-1?O:O.slice(0,B)}function um(O,D,B){if(D===null)return!0;return O.some((X)=>X.includes(D))||Array.from(B.values()).some((X)=>X.includes(D))}function kR(O,D){let B=gn(O);if(B.commandIndex!==null&&(O[B.commandIndex]??"").includes(D)||B.scriptIndex!==null&&(O[B.scriptIndex]??"").includes(D))return!0;return["-c","-nc","-cn",`--${D}`,D].some((Q)=>O.some((he,je)=>{if(je===0||!he.includes(D))return!1;return sm(he,D,Q).some((lt)=>{let ct=O.map((dt,ut)=>ut===je?dt.replaceAll(D,lt):dt),ft=gn(ct);if(ft.commandIndex===null&&ft.scriptIndex===null)return!1;if(B.commandIndex===null&&ft.commandIndex!==null)return!0;if(B.scriptIndex===null&&ft.scriptIndex!==null)return!0;if(ft.commandIndex!==null&&(ct[ft.commandIndex]??"").includes(lt))return!0;return ft.scriptIndex!==null&&(ct[ft.scriptIndex]??"").includes(lt)})}))}function OR(O,D,B){let X=new Set(D===null?[]:Array.from(B).filter(([,Q])=>Q.includes(D)).map(([Q])=>Q));for(let Q of O.matchAll(_R))if(om(Q,X))return!0;for(let Q of O.matchAll(wR))for(let he of(Q[1]??"").matchAll(PR))if(om(he,X))return!0;return Ol(O,X)}function om(O,D){let B=O[1]??O[2];return B!==void 0&&(AR.test(B)||D.has(B))}function MR(O,D,B){if(D===null)return!0;let X=!1,Q=0;for(let he=1;he<O.length;he++){let je=O[he]??"";if(!X&&!je.startsWith("-")&&je!=="!"&&je!=="("){if(je.indexOf(D)===0)return!0;continue}if(X=!0,Q>0){Q--;continue}if(jn(je)){let lt=$o(O,he);he=lt.nextIndex-1;for(let ct of kn(lt.tokens,{environment:B,cwd:void 0})){let ft=um(ct.tokens,D,ct.wrapperEnvAssignments);if(ct.head==="rm"&&lm(ct.tokens,D)||am(ct.tokens,ct.head,D,ct.wrapperEnvAssignments,ft,B))return!0}continue}let at=ir(je);if(at>0){if(Q=at,je.includes(D))return!0;continue}if(je.includes(D))return!0}return!1}function Tr(O){let D=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"]),B=null,X=1;while(X<O.length){let Q=O[X];if(!Q)break;if(Q==="--")return{childStart:X+1,replacementToken:B};if(!Q.startsWith("-"))return{childStart:X,replacementToken:B};if(Q==="-I"){B=O[X+1]??"{}",X+=2;continue}if(Q.startsWith("-I")&&Q.length>2){B=Q.slice(2),X++;continue}if(Q==="--replace"){B="{}",X++;continue}if(Q.startsWith("--replace=")){let he=Q.slice(10);B=he===""?"{}":he,X++;continue}if(Q==="-J"){B=O[X+1]??"{}",X+=2;continue}X+=D.has(Q)?2:1}return{childStart:O.length,replacementToken:B}}var Ko="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",qo="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",NR="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",LR="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",bs=/\{[^{}\s]*\}/g,dm=/\{\}|\{-?\d+\}/g,WR=["e","f","source","file","-e","-f","--source","--file"],FR=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],GR=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),zR=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),fm=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),BR=new Set(["--workdir","--wd"]),mm="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Rn(O,D){for(let B of O){let X=D(B);if(X)return X}return null}function bm(O){return Rn([...O],(D)=>$n(D))}function Sm(O,D){let B=O.map(t);if((D.envAssignments?.has("PARALLEL")?D.envAssignments.get("PARALLEL"):D.environment.env.get("PARALLEL"))?.trim()){let pt=Jr(D);if(pt)return pt}if(B.length===2&&(B[1]==="--version"||B[1]==="--help"))return null;let Q=Am(B),{template:he,jobs:je,runsRemotely:at,readsCommandsFromInput:lt,unsupported:ct,workdir:ft,dryRun:dt}=Q;if(ct){let pt=Jr(D);if(pt)return pt;let ht=bm(D.envAssignments?.values()??[]);if(ht)return ht}if(lt){let pt=KR(D);if(pt)return pt}if(ft!==void 0&&at){let pt=Jr(D);if(pt)return pt}let ut=qR(ft,D.cwd,D.environment.paths);if(ut===null){let pt=Jr(D);if(pt)return pt}let mt=at?{...D,cwd:void 0,originalCwd:void 0}:ut===null||ut===void 0||ut===D.cwd?D:{...D,cwd:ut};if(dt){if([...kn(he,mt)].flatMap((ht)=>[...ht.envAssignments.values()]).some(Wl)){let ht=Jr(D);if(ht)return ht}return null}if(he.length===0){let pt=je.map((gt)=>gt[0]??"");D.budget.charge("derivedTokens",pt.length);let ht=Rm(mt.envAssignments,mt.cwd,at);return Rn(pt,(gt)=>D.analyzeNested(gt,ht))}return Rn(kn(he,mt),(pt)=>$R(pt,Q,D,mt))}function $R(O,D,B,X){let{jobs:Q,templateHasPlaceholder:he,runsRemotely:je,usesStdin:at}=D,lt=O.tokens,ct=[...O.envAssignments.values()];if(ct.some(wm)){let gt=Jr(B);if(gt)return gt}let ft=bm(ct);if(ft)return ft;let dt=ct.some(Nt),ut=he||dt,mt=at&&ut,pt=Rm(O.envAssignments,O.wrapperCwd,je||mt);if(Kt.has(O.head)){let gt=()=>{if(!he||Q.length===0)return null;return Rn(Q,(Et)=>B.analyzeChild(ys(lt,Et,B.budget),wr(O,X)))};if(qn(lt))return gt();let yt=Kn(lt);if(yt){if(Pm(yt)){let Rt=lr(B);if(Rt)return Rt;if(Q.length===0)return null;return Rn(Q,(_t)=>B.analyzeNested(hm(yt,_t,B.budget),pt))}if(Nt(yt)){if(Q.length>0)return Rn(Q,(Ut)=>B.analyzeNested(hm(yt,Ut,B.budget),pt));let Rt=Uo(yt);if(Rt?.[0]&&kt(Rt[0])==="rm"&&On(Rt)){let Ut=gm(B);if(Ut)return Ut}let _t=Rt?B.analyzeChild(Rt,{...wr(O,X),dynamicInput:at,shellDynamicMatch:St("parallel.shell-dynamic",qo),rmDynamicMatch:St("parallel.rm-recursive-force-dynamic",Ko)}):null;if(_t)return _t;return B.analyzeNested(yt,pt)}let Et=!dt&&(!he||Q.length>0)?(Q.length>0?Q:[void 0]).map((Rt)=>ms($t(Rt===void 0?lt:he?lt.map((_t)=>xm(_t,Rt)):[...lt,...Rt]),yt)):[];if(Et.some((Rt)=>Rt.kind==="dynamic")){let Rt=lr(B);if(Rt)return Rt}let Ct=Et.flatMap((Rt)=>Rt.kind==="literal"?[Rt.source]:[]);if(Ct.length>0)return B.budget.charge("derivedTokens",Ct.length),Rn(Ct,(Rt)=>B.analyzeNested(Rt,pt));if(Vo(yt)){let Rt=lr(B);if(Rt)return Rt}let Pt=B.analyzeNested(yt,pt);if(Pt)return Pt;if(ut)return lr(B);return null}let vt=Vn($t(lt));if(vt.kind==="dynamic"||vt.kind==="literal"&&Nt(vt.source))return lr(B)??gt();if(vt.kind==="literal")return gt();if(Q.length>0){let Et=lr(B);if(Et)return Et;let Ct=gt();if(Ct)return Ct;if(he)return null;let Pt=Q.flatMap((Rt)=>Rt[0]===void 0?[]:[Rt[0]]);return B.budget.charge("derivedTokens",Pt.length),Rn(Pt,(Rt)=>B.analyzeNested(Rt,pt))}if(ut||at)return lr(B)??gt();return null}if(O.head==="rm"&&On(lt)){if(he&&Q.length>0)return Rn(Q,(yt)=>Nl(ys(lt,yt,B.budget,dm),O.cwd,X));if(Q.length>0)return Rn(Q,(yt)=>Nl(ym(lt,yt,B.budget),O.cwd,X));let gt=Nl(lt.flatMap((yt,vt)=>{if(vt===0||!Nt(yt))return[yt];return yt.startsWith("-")?[yt.replace(dm,"")]:[]}),O.cwd,X);if(gt)return gt;return gm(B)}let ht=Q.length>0?Q:[void 0];return Rn(ht,(gt)=>{let yt=gt===void 0?lt:he?ys(lt,gt,B.budget):ym(lt,gt,B.budget),vt=St("parallel.shell-dynamic",qo),Et=at&&O.head==="find"?VR(yt,X):null,Ct=vm(yt,at,B)??Et?.customResult??null,Pt=kt(O.head),Rt=at&&(Pt==="rm"&&Ll(yt)||Pt==="xargs"&&Em(yt)||Et?.rmOptions===!0),_t=at&&(Rt||Et?.executedSource===!0||Et===null&&Cm(yt,Pt)),Ut=B.analyzeChild(yt,{...wr(O,X),worktreeMode:je||at||ut?!1:B.worktreeMode,dynamicInput:at||ut,dynamicRmInput:Rt,dynamicSourceInput:Ct!==null||_t,shellDynamicMatch:vt,dynamicSourceMatch:vt,rmDynamicMatch:St("parallel.rm-recursive-force-dynamic",Ko)});if(_t){let jt=wt(vt,B.policy);if(jt)return jt}return Ut??Ct??_(yt,B.policy?.rules??[])})}function Cm(O,D){if(Nt(O[0]??""))return!0;if(D==="eval"||D==="source"||D===".")return!0;if(D==="parallel"||D==="xargs")return!0;if(Kt.has(D))return jR(O);if(D==="git")return UR(O);if(D==="find")return!0;if(vn.has(D))return pm(O,WR,Bo);if(wn(D))return pm(O,FR,zi);return!1}function Ll(O){let D=O.indexOf("--"),B=O.slice(1,D===-1?void 0:D);if(!O.some(Nt))return D===-1;return B.some((Q)=>Nt(Q)&&(Q.startsWith("-")||Pm(Q)))}function UR(O){if(HR(O))return!0;let D=Mn(O);if(D.subcommand===null||Nt(D.subcommand))return!0;if(!Xr.has(D.subcommand.toLowerCase()))return!1;let B=D.rest.indexOf("--"),X=D.rest.slice(0,B===-1?void 0:B);if(!O.some(Nt))return B===-1;return X.some(Nt)}function HR(O){for(let D=1;D<O.length;D++){let B=O[D];if(!B||B==="--"||!B.startsWith("-"))return!1;if(B==="-c"||B==="--config-env"){if(Nt(O[D+1]??""))return!0;D++;continue}if(B.startsWith("-c")&&B.length>2||B.startsWith("--config-env=")){if(Nt(B))return!0;continue}if(Nt(B))return!0}return!1}function jR(O){if(qn(O))return!1;let D=Kn(O);if(D!==null)return Nt(D);let B=Vn($t(O));if(B.kind==="literal")return Nt(B.source);if(B.kind==="dynamic")return!0;return!O.some(Nt)}function pm(O,D,B){let X=B(O);if(X.some((Q)=>Nt(Q.value)))return!0;if(!O.some(Nt))return B([...O,mm]).some((Q)=>Q.value===mm);return us(X,D,(Q)=>B(O.map((he)=>xm(he,[Q]))))}function vm(O,D,B){let X=B.policy?.rules??[];if(!D||X.length===0)return null;let Q=X.filter((he)=>kt(he.command)===kt(O[0]??""));if(Q.length===0)return null;if(O.slice(1).some(Nt))return lr(B);return Rn(Q,(he)=>_([...O,...he.subcommand?[he.subcommand]:[],...he.block_args],[he]))}function VR(O,D){let B={customResult:null,executedSource:!O.some(Nt),rmOptions:!1},X=!1,Q=0,he=null,je=()=>{if(!he?.some(Nt))return;for(let at of kn(he,D))B.executedSource||=Cm(at.tokens,at.head),B.rmOptions||=at.head==="rm"&&Ll(at.tokens)||at.head==="xargs"&&Em(at.tokens),B.customResult??=vm(at.tokens,!0,D)};for(let at of O.slice(1)){if(!X&&!at.startsWith("-")&&at!=="!"&&at!=="("){B.executedSource||=Nt(at);continue}if(X=!0,he){if(at===";"||at==="+"){je(),he=null;continue}he.push(at);continue}if(Q>0){Q--;continue}if(jn(at)){he=[],B.executedSource||=Nt(at);continue}let lt=ir(at);if(lt>0){Q=lt,B.executedSource||=Nt(at);continue}B.executedSource||=Nt(at)}return je(),B}function Em(O){let D=O.slice(Tr(O).childStart);return kt(D[0]??"")==="rm"&&Ll(D)}function Ss(O,D){return(B)=>wt(St(O,D),B.policy)}var lr=Ss("parallel.shell-dynamic",qo),KR=Ss("parallel.command-stream-dynamic",NR),Jr=Ss("parallel.command-stream-dynamic",LR),gm=Ss("parallel.rm-recursive-force-dynamic",Ko);function Nl(O,D,B){return wt(ds($t(O),{environment:B.environment,cwd:D,budget:B.budget,originalCwd:B.originalCwd,strict:B.strict,paranoid:B.paranoidRm,allowTmpdirVar:B.allowTmpdirVar,tmpdirWordSplittingUnsafe:or(B.envAssignments??new Map,B.environment),trustedTmpdirValue:Rr(B.envAssignments??new Map,B.environment),protectedGitMetadata:B.protectedGitMetadata,policy:B.policy}),B.policy)}function Rm(O,D,B){let X={};if(O)X.envAssignments=O;if(B)return X.effectiveCwd=null,X.worktreeMode=!1,X;if(D!==void 0)X.effectiveCwd=D;return Object.keys(X).length>0?X:void 0}function xm(O,D){return O.replace(bs,(B)=>_m(B,D))}function ys(O,D,B,X=bs){return B.charge("derivedTokens",O.reduce((Q,he)=>Q+1+Math.floor(he.length/64),0)),O.map((Q)=>Q.replace(X,(he)=>{let je=_m(he,D);return B.charge("derivedTokens",Math.max(1,Math.ceil(je.length/64))),je}))}function hm(O,D,B){return ys([O],D,B)[0]??""}function ym(O,D,B){return B.charge("derivedTokens",O.length+D.length),[...O,...D]}function _m(O,D){let B=/^\{(-?\d+)[^{}\s]*\}$/.exec(O)?.[1];if(B===void 0)return D[0]??"";let X=Number(B);return D[X>0?X-1:D.length+X]??""}function Nt(O){return O.search(bs)!==-1}function wm(O){if(Wl(O))return!0;for(let D of O.matchAll(bs))if(!/^(?:\{\}|\{\d+\})$/.test(D[0]))return!0;return!1}function Wl(O){let D=O.indexOf("{=");return D!==-1&&O.indexOf("=}",D+2)!==-1}function Pm(O){return/^\{[^{}\s]*\}$/.test(O)}function qR(O,D,B){if(O===void 0)return;if(O==="..."||/^~|[{}$`*?[]/.test(O))return null;if(!D&&!DR(O))return null;try{return tr(D??O,O,B)}catch{return null}}function Am(O){let D=1,B=[],X=O.length,Q=-1,he=!1,je=!1,at,lt=!1,ct=O.some((pt)=>pt==="::::"||pt==="::::+"||pt===":::+");while(D<O.length){let pt=O[D];if(pt===void 0)break;if(pt===":::"){Q=D;break}if(pt==="--"){let Et=Cl(O,D+1);B.push(...Et.templateTokens),X=D+1,Q=Et.markerIndex;break}if(!pt.startsWith("-")){let Et=Cl(O,D);B.push(...Et.templateTokens),X=D,Q=Et.markerIndex;break}let ht=O[D+1],gt=pt.indexOf("="),yt=gt===-1?pt:pt.slice(0,gt),vt=gt===-1?void 0:pt.slice(gt+1);if(pt==="--dry-run"){lt=!0,D++;continue}if(pt==="-I"||pt.startsWith("-I")&&pt.length>2){ct||=(pt==="-I"?ht:pt.slice(2))!=="{}",D+=pt==="-I"?2:1;continue}if(pt==="--replace"||pt==="-i"){ct=!0,D+=2;continue}if(yt==="--replace"||pt.startsWith("-i")&&pt.length>2){let Et=yt==="--replace"?vt:pt.slice(2);ct||=Et!==""&&Et!=="{}",D++;continue}if(pt==="-a"||zR.has(yt)){ct=!0,D+=vt===void 0?2:1;continue}if(pt==="--pipe"||pt==="--pipepart"){je=!0,D++;continue}if(yt==="--env"){ct=!0,D+=vt===void 0?2:1;continue}if(fm.has(yt)||pt.startsWith("-S")&&pt.length>2){he=!0,D+=fm.has(pt)?2:1;continue}if(BR.has(yt)){ct=!0;let Et=vt??ht;if(Et===void 0||Et===":::"||Et==="--"){D++;continue}at=Et,D+=vt===void 0?2:1;continue}if(pt.startsWith("-j")&&pt.length>2&&/^\d+$/.test(pt.slice(2))){D++;continue}if(pt.startsWith("--")&&vt!==void 0){D++;continue}if(GR.has(pt)){if(ht===void 0||ht===":::"||ht==="--"){ct=!0,D++;continue}D+=2;continue}D+=pt==="-j"||pt==="--jobs"?2:1}ct||=B.some(lt?Wl:wm);let ft=[];if(Q!==-1){let pt=[];for(let ht=Q+1;ht<O.length;ht++){let gt=O[ht];if(gt===":::"){ft.push(pt),pt=[];continue}if(gt!==void 0)pt.push(gt)}ft.push(pt)}ct||=ft.length>1;let dt=YR(ft),ut=B.some(Nt),mt=B.length===0&&Q===-1;return{template:B,jobs:dt,childStart:X,templateHasPlaceholder:ut,runsRemotely:he,usesStdin:je||Q===-1,readsCommandsFromInput:mt,unsupported:ct,workdir:at,dryRun:lt}}function YR(O){if(O.length===0||O.some((B)=>B.length===0))return[];let D=[[]];for(let[B,X]of O.entries()){if(X.length===1){let he=X[0];if(he===void 0)return[];for(let je of D)je.push(he);if(D.length*(B+1)>a.derivedTokens.cap)throw new s("derivedTokens");continue}let Q=[];for(let he of D)for(let je of X){if((Q.length+1)*(B+1)>a.derivedTokens.cap)throw new s("derivedTokens");Q.push([...he,je])}D=Q}return D}function Tm(O){return Am(O).childStart}var ZR="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",Cs="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function Gl(O){return O?.parts.some((D)=>D.provenance==="command-substitution")??!1}function Fl(O){return O?.parts.some((D)=>D.provenance==="literal"&&D.raw.replace(/^["']/,"").startsWith("-"))??!1}function km(O,D,B,X,Q=!1,he){let at=(Co(O,D)||X&&O!=="powershell"&&D[0]?.provenance==="variable")&&Jt(he,"shell.dynamic-executable",Q)?St("shell.dynamic-executable",ZR):null;return wt(at,he)??Om(O,D,B,Q,he)}function Om(O,D,B,X,Q){if(D.length<2)return null;let he=D.flatMap((at,lt)=>Gl(at)?[lt]:[]);if(he.length===0)return null;let je=kt(D[0]?.text??"");if(je==="git"){let at=Z(O,D),lt=JR(at);if(Jt(Q,"shell.dynamic-structure",X)&&he.some((dt)=>dt<=lt))return wt(St("shell.dynamic-structure",Cs),Q);if(wt(cs(at,{environment:B}),Q))return null;let ct=D[lt]?.text.toLowerCase(),ft=at.findIndex((dt,ut)=>ut>lt&&t(dt)==="--");if(Jt(Q,"shell.dynamic-structure",X)&&ct&&Xr.has(ct)&&he.some((dt)=>dt>lt&&(ft===-1||dt<ft)))return wt(St("shell.dynamic-structure",Cs),Q);return null}if(je==="find")return Jt(Q,"shell.dynamic-structure",X)&&QR(D)?wt(St("shell.dynamic-structure",Cs),Q):null;if(je==="rm"){let at=D.findIndex((ct,ft)=>ft>0&&t(ct)==="--"),lt=On(D.map(t));return Jt(Q,"shell.dynamic-structure",X)&&he.some((ct)=>(at===-1||ct<at)&&(ct<D.length-1||!lt))?wt(St("shell.dynamic-structure",Cs),Q):null}if(je==="xargs")return Im(O,D.slice(Tr(D.map(t)).childStart),"xargs",B,X,Q);if(je==="parallel")return Im(O,D.slice(Tm(D.map(t))),"parallel",B,X,Q);return null}function Im(O,D,B,X,Q,he){if(D.length===0)return null;let je=XR(D,X);if(Co(O,je)){let lt=wt(St(`${B}.shell-dynamic`,B==="xargs"?Dl:qo),he);if(lt)return lt}let at=Om(O,je,X,Q,he);if(at)return at;if(je[0]?.text==="rm"&&je.slice(1).some((lt)=>Gl(lt)&&Fl(lt)))return wt(St(`${B}.rm-recursive-force-dynamic`,B==="xargs"?Ml:Ko),he);return null}function XR(O,D){let B=Sr(O,D),X=B.rewritten?$t(B.words.map(t)):B.words,Q=X[0];return Q&&t(Q)==="busybox"?X.slice(1):X}function JR(O){let D=1;while(D<O.length){let B=O[D],X=B?t(B):"";if(pn.has(X)){D+=2;continue}if(X.startsWith("-")){D++;continue}return D}return D}function QR(O){let D=!1,B=0,X=!1,Q=!1;for(let he=1;he<O.length;he++){let je=O[he];if(!je)continue;let at=Gl(je);if(B>0){B--;continue}if(Q){if(je.text===";"||je.text==="+"){Q=!1,D=!0,X=!1;continue}if(at&&(X||Fl(je)))return!0;X=!1;continue}if(!D&&!je.text.startsWith("-")){if(at&&(he>1||Fl(je)))return!0;continue}if(D=!0,at)return!0;let lt=ir(je.text);if(lt>0){B=lt;continue}if(jn(je.text))Q=!0,X=!0}return!1}function zl(O,D){return O.some((B)=>{if(B.value==="-"&&(B.kind==="main-script"||B.kind==="program-file"))return!0;return!Li(D[B.tokenIndex],B.value)})}var ex="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",tx="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",nx="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function Mm(O,D){let B=D.slice(1);if(O==="dd"&&B.some((X)=>/^of=\/dev\/.+/.test(X)))return St("dd.device-write",ex);if((O==="mkfs"||O.startsWith("mkfs."))&&B.some((X)=>X.startsWith("/dev/")))return St("mkfs.device",tx);if(O==="shred"&&B.length>0)return St("shred.target",nx);return null}var Nm=[{heads:new Set(["rm","rmdir"]),analyze:(O)=>ds(O.words,{environment:O.options.environment,cwd:O.cwd,originalCwd:O.originalCwd,strict:O.options.strict,paranoid:O.options.paranoidRm,allowTmpdirVar:O.allowTmpdirVar,tmpdirWordSplittingUnsafe:or(O.envAssignments,O.options.environment),trustedTmpdirValue:Rr(O.envAssignments,O.options.environment),protectedGitMetadata:O.options.protectedGitMetadata,policy:O.options.policy,budget:O.options.budget})},{heads:new Set(["git"]),analyze:(O)=>cs(O.words,Bl(O))},{heads:new Set(["find"]),analyze:(O)=>Mf(O.words,{environment:O.options.environment,cwd:O.cwd,originalCwd:O.originalCwd,strict:O.options.strict,allowTmpdirVar:O.allowTmpdirVar,tmpdirWordSplittingUnsafe:or(O.envAssignments,O.options.environment),trustedTmpdirValue:Rr(O.envAssignments,O.options.environment),protectedGitMetadata:O.options.protectedGitMetadata,budget:O.options.budget,envAssignments:O.envAssignments,policy:O.options.policy,analyzeTokens:O.analyzeChildTokens,analyzeNested:(D,B)=>Ir(O.options.analyzeNested(D,B))})},{heads:new Set(["xargs"]),analyze:(O)=>im(O.words,{...Dm(O),analyzeChild:O.analyzeChild,analyzeNested:(D,B)=>Ir(O.options.analyzeNested(D,B))})},{heads:new Set(["parallel"]),analyze:(O)=>Sm(O.words,{...Dm(O),analyzeChild:O.analyzeChild,analyzeNested:(D,B)=>Ir(O.options.analyzeNested(D,B))})}];function Dm(O){return{environment:O.options.environment,cwd:O.cwd,originalCwd:O.originalCwd,strict:O.options.strict,paranoidRm:O.options.paranoidRm,paranoidInterpreters:O.options.paranoidInterpreters,allowTmpdirVar:O.allowTmpdirVar,protectedGitMetadata:O.options.protectedGitMetadata,budget:O.options.budget,envAssignments:O.envAssignments,worktreeMode:O.options.worktreeMode,policy:O.options.policy}}function Ir(O){return O?{id:O.ruleId??"",reason:O.reason,intent:O.intent??"manual_only"}:null}function Bl(O){return{environment:O.options.environment,cwd:O.cwd,dynamicArguments:O.dynamicArguments,envAssignments:O.envAssignments,policy:O.options.policy,worktreeMode:O.options.worktreeMode}}var Gm="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function zm(O){return Nm.find((D)=>D.heads.has(O))?.analyze}function eo(O,D,B){let X=B.trace;if(O.length===0)return null;let Q=B.commandView?.dialect??"posix",he=(xt)=>xt.map((At)=>Q==="posix"?t(At):At.text),je=B.child,at=je!==void 0&&!je.embedded,lt=je?.embedded===!0,ct=B.effectiveCwd===null,ft=je?je.cwd:ct?void 0:B.effectiveCwd??B.cwd,dt=je?je.originalCwd:ct?void 0:B.cwd,ut=ge(O);if(ut.envAssignments.size>0)X?.recordSegment({type:"env-strip",input:he(O),envVars:[...ut.envAssignments.keys()],output:he(ut.words)});let mt=Sr(ut.words,B.environment,ft,new Map([...B.envAssignments??[],...ut.envAssignments])),pt=mt.envSplitValues??[];if(pt.length>0){let xt=[...pt,...he(mt.words)].join(" "),At=$n(xt);if(At)return X?.recordSegment({type:"dangerous-text",token:xt,matched:!0,reason:At.reason}),on(At);if(B.strict)return dn(X);let Mt=Hi(pt,he(mt.words));if(Mt){B.budget.charge("derivedTokens",Mt.length);let Yt=B.analyzeNested(Mt.join(" "),{effectiveCwd:mt.cwd===void 0?B.effectiveCwd:mt.cwd,envAssignments:new Map([...B.envAssignments??[],...ut.envAssignments,...mt.envAssignments])});if(Yt)return Yt}}let ht=mt.rewritten?$t(he(mt.words)):Z(Q,mt.words),gt=he(ht),yt={...B,wrapperNormalizationBudget:B.wrapperNormalizationBudget??{iterations:0}};if(X&&ut.words.length>ht.length){let xt=he(ut.words);X.recordSegment({type:"leading-tokens-stripped",input:xt,removed:xt.slice(0,xt.length-ht.length),output:gt})}let vt=new Map([...B.envAssignments??[],...ut.envAssignments,...mt.envAssignments]),Et=gt[0];if(!Et)return null;if(_r(Et))throw new s("wrapperPeelIterations");let Ct=kt(Et),Pt=mt.cwd===null?void 0:mt.cwd??ft,Rt=mt.cwd===null?void 0:dt,_t=mt.cwd===void 0?B.effectiveCwd:mt.cwd,Ut=je?je.allowTmpdirVar:!Wo(vt,B.environment),jt=km(Q,mt.words,B.environment,D===0,B.strict,B.policy);if(jt)return X?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:jt.reason}),on(jt);let qt=os(gt,B.policy);if(qt){for(let xt of[qt.childIndex,...qt.alternativeChildIndices]){Lm(yt.wrapperNormalizationBudget);let At=ht.slice(xt);X?.recordSegment({type:"transparent-wrapper",wrapper:qt.wrapper,output:he(At)});let Mt=eo(At,D,{...yt,effectiveCwd:_t,envAssignments:vt});if(Mt)return Mt}return null}let Vt=lt?void 0:Ct==="eval"?fs(ht):Ct==="trap"&&!at?Jf(ht):void 0;if(at&&je&&Ct==="eval"){if(Vt?.kind==="dynamic")return Qr(je,B.policy);if(Vt?.kind==="literal"){let xt=B.analyzeNested(Vt.source,{effectiveCwd:_t,envAssignments:vt});if(xt)return xt}return to(je,B.policy)}if(Vt?.kind==="dynamic"&&(B.strict||!B.commandView||!kl(B.commandView)))return dn(X);if(Vt?.kind==="literal"){X?.recordSegment({type:"recurse",reason:Ct==="eval"?"shell-eval":"shell-trap",innerCommand:Vt.source,depth:D+1});let xt=B.analyzeNested(Vt.source,{effectiveCwd:_t,envAssignments:vt,functionDefinitions:B.functionDefinitions});if(xt)return xt}if(at?Kt.has(Ct):$m(Et,Ct)){if(qn(gt))return null;if(at&&je){let xt=Kn(gt);if(xt){if(je.dynamicSourceInput??je.dynamicInput){let Mt=Qr(je,B.policy);if(Mt)return Mt}if(Vo(xt)){let Mt=Qr(je,B.policy);if(Mt)return Mt}return B.analyzeNested(xt,{effectiveCwd:_t,envAssignments:vt})}let At=Vn(ht);if(At.kind==="dynamic")return Qr(je,B.policy);if(At.kind==="literal")return je.dynamicSourceInput?Qr(je,B.policy):null;return je.dynamicSourceInput??je.dynamicInput?Qr(je,B.policy):null}if(lt){let xt=Kn(gt),At=xt?B.analyzeNested(xt,{effectiveCwd:_t,envAssignments:vt}):Vn(ht).kind==="dynamic"?dn(X):null;if(At)return At}if(je===void 0){let xt=sx(gt,vt,_t,B,X,D);if(xt)return xt;let At=Kn(gt);if(At){let Mr=ms(ht,At);if(Mr.kind==="dynamic")return dn(X);let Fs=Mr.kind==="literal"?Mr.source:At,mc=ax(Fs);X?.recordSegment({type:"shell-wrapper",wrapper:Ct,innerCommand:mc}),X?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:mc,depth:D+1});let pc=B.analyzeNested(Fs,{effectiveCwd:_t,envAssignments:vt});if(pc)return pc;return Vo(Fs)?dn(X):null}let Mt=Vn(ht);if(Mt.kind==="dynamic")return dn(X);if(Mt.kind==="literal")return Es(Mt.source,_t,vt,B,X,D);let Yt=Qf(ht,B.commandView?.redirections??[],B.hasPipelineInput??!1,B.literalShellInput);if(Yt.kind==="dynamic")return dn(X);if(Yt.kind==="literal")return X?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:Yt.source,depth:D+1}),B.analyzeNested(Yt.source,{effectiveCwd:_t,envAssignments:vt})}}if(!je&&(Ct==="source"||Ct===".")){let xt=gt[1]==="-p"?2:null;if(xt!==null){let Mr=B.commandView?ht[xt]:void 0;if(!Mr)return null;if(Mr.provenance!=="literal")return dn(X)}let At=xt===null?1:3,Mt=gt[At]==="--"?At+1:At,Yt=B.commandView?ht[Mt]:void 0;if(!Yt)return null;if(Yt.provenance==="literal")return Es(Yt.text,_t,vt,B,X,D);if(B.strict||!B.commandView||!kl(B.commandView))return dn(X)}if(vn.has(Ct)&&!lt){if(!je&&B.strict&&zl(Bo(gt),ht))return dn(X);let xt=Af(gt,(Mt)=>Ir(B.analyzeNested(Mt,{effectiveCwd:_t,envAssignments:vt}))),At=wt(xt,B.policy);if(At)return X?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:At.reason}),on(At)}if(wn(Ct)&&!lt){if(!je&&B.strict&&zl(zi(gt),ht))return dn(X);let xt=_d(gt);if(at&&je)return ox(Ct,xt,_t,vt,B,je);if(xt){let At=Jt(B.policy,"interpreter.one-liner-paranoid",!!B.paranoidInterpreters);if(X?.recordSegment({type:"interpreter",interpreter:Ct,codeArg:xt,paranoidBlocked:At}),At){let Yt=wt(St("interpreter.one-liner-paranoid",Ao),B.policy);if(Yt)return on(Yt)}if(Xa(Ct,xt))return null;X?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:xt,depth:D+1});let Mt=B.analyzeNested(xt,{effectiveCwd:_t,envAssignments:vt});if(Mt&&!Bm(Mt,xt))return Mt;if(To(xt)){let Yt=wt(St("interpreter.dangerous-command",Vr),B.policy);if(Yt)return X?.recordSegment({type:"dangerous-text",token:xt,matched:!0,reason:Vr}),on(Yt)}X=void 0}}if(Ct==="busybox"&&gt.length>1)return Lm(yt.wrapperNormalizationBudget),X?.recordSegment({type:"busybox",subcommand:gt[1]??"unknown"}),X?.recordSegment({type:"recurse",reason:"busybox",innerCommand:gt.slice(1).join(" "),depth:D+1}),eo(ht.slice(1),D,{...yt,effectiveCwd:_t,envAssignments:vt});let Ot=je?null:wt(Mm(Ct,gt),B.policy);if(Ot)return X?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:Ot.reason}),on(Ot);let nn=X===yt.trace?yt:{...yt,trace:X},Sn={words:ht,head:Ct,cwd:Pt,originalCwd:Rt,envAssignments:vt,allowTmpdirVar:Ut,dynamicArguments:mt.words.some((xt)=>xt.provenance==="command-substitution"),depth:D,effectiveCwd:_t,options:nn,analyzeChildTokens:(xt,At)=>at&&je?$l(xt,D,nn,{...je,cwd:At??void 0,effectiveCwd:At??void 0}):Ir(eo($t(xt),D+1,{...nn,child:void 0,commandView:void 0,effectiveCwd:At,envAssignments:vt}))??_(xt,nn.policy.rules),analyzeChild:(xt,At)=>$l(xt,D,nn,At)},Fn=je&&(Ct==="xargs"||Ct==="parallel")?void 0:zm(Ct);if(Ct==="rm"||Ct==="xargs"||Ct==="parallel")X?.recordSegment({type:"tmpdir-check",tmpdirValue:vt.has("TMPDIR")||B.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:Ut});let xn=X&&Ct==="git"?Hf(Sn.words,Bl(Sn)):void 0,Ls=Wm(xn?xn.match:Fn?.(Sn)??null,B.policy);if(X)lx(Sn,Ls,xn?.relaxation??null);if(Ls)return on(Ls);if(at&&je&&(Ct==="rm"||Ct==="rmdir")){if(!(Ct==="rm"&&(On(gt)||je.dynamicRmInput)))return null;return(je.dynamicRmInput?to(je,B.policy):null)??ix(je,B.policy)}let dc=Fn!==void 0,fc=!je&&!dc&&!pi.has(Ct),Ws=X&&fc?[]:void 0;if(fc)for(let xt=1;xt<gt.length;xt++){let At=gt[xt];if(!At)continue;Ws?.push(At);let Mt=Wm(rx(gt,xt,D,nn,Pt,Rt,_t,vt),B.policy);if(Mt)return X?.recordSegment({type:"fallback-scan",tokensScanned:Ws??[],embeddedCommandFound:kt(At)}),on(Mt)}if(X?.recordSegment({type:"fallback-scan",tokensScanned:Ws??[]}),lt&&je&&!je.wrappedByTransparent)return null;if(!je&&D!==0&&dc)return X?.recordSegment({type:"custom-rules-check",rulesChecked:!1,matched:!1}),null;let ni=_(gt,B.policy.rules);if(X?.recordSegment({type:"custom-rules-check",rulesChecked:B.policy.rules.length>0,matched:!!ni,reason:ni?.reason}),ni)return on(ni);return at&&je?to(je,B.policy):null}function $l(O,D,B,X){return Ir(eo($t(O),D+1,{...B,trace:void 0,commandView:void 0,hasPipelineInput:void 0,literalShellInput:void 0,functionDefinitions:void 0,cwd:X.originalCwd,effectiveCwd:X.effectiveCwd,envAssignments:X.envAssignments,worktreeMode:X.dynamicInput?!1:X.worktreeMode,wrapperNormalizationBudget:{iterations:0},child:X}))}function rx(O,D,B,X,Q,he,je,at){for(let lt of kn(O.slice(D),{environment:X.environment,cwd:Q,envAssignments:at,policy:X.policy})){let ct=lt.tokens[0];if(!ct)continue;let ft=kt(ct);if($m(ct,ft)||zm(ft)!==void 0&&ft!=="xargs"&&ft!=="parallel"||lt.wrappedByTransparent&&X.policy.rules.length>0)X.budget.charge("derivedTokens",O.length-D);let ut=$l(lt.tokens,B,X,{embedded:!0,cwd:lt.cwd,originalCwd:lt.wrapperCwd===null?void 0:he,effectiveCwd:lt.wrapperCwd===void 0?je:lt.wrapperCwd,envAssignments:lt.envAssignments,allowTmpdirVar:!Wo(lt.envAssignments,X.environment),worktreeMode:!1,wrappedByTransparent:lt.wrappedByTransparent});if(ut)return ut}return null}function ox(O,D,B,X,Q,he){if(!D)return to(he,Q.policy);if(Jt(Q.policy,"interpreter.one-liner-paranoid",!!Q.paranoidInterpreters)){let at=wt(St("interpreter.one-liner-paranoid",Ao),Q.policy);if(at)return on(at)}if(Xa(O,D))return to(he,Q.policy);let je=Q.analyzeNested(D,{effectiveCwd:B,envAssignments:X});if(je&&!Bm(je,D))return je;if(To(D)){let at=wt(St("interpreter.dangerous-command",Vr),Q.policy);if(at)return on(at)}return to(he,Q.policy)}function Bm(O,D){if(O.ruleId==="raw-text.dangerous-command")return!0;return(O.reason.startsWith(ts)||O.reason===Zr)&&!gi(D)}function Qr(O,D){let B=O.shellDynamicMatch?wt(O.shellDynamicMatch,D):null;return B?on(B):null}function to(O,D){let B=O.dynamicSourceInput&&O.dynamicSourceMatch?wt(O.dynamicSourceMatch,D):null;return B?on(B):null}function ix(O,D){let B=O.dynamicInput&&O.rmDynamicMatch?wt(O.rmDynamicMatch,D):null;return B?on(B):null}function sx(O,D,B,X,Q,he){let je=nm(O);if(je.argvSource?.kind==="absent")return dn(Q);if(je.argvSourceApplies&&je.argvSource){let lt=Es(je.argvSource.value,B,D,X,Q,he,!0);if(lt)return lt}if(!je.envSourceApplies||!je.envName)return null;let at=D.get(je.envName);if(!at)return null;return Es(at,B,D,X,Q,he,!0)}function Es(O,D,B,X,Q,he,je=!1){if(je&&/[$`*?[\]]/.test(O))return dn(Q);let at=Po(O,D,X.environment.paths,X.budget),lt=at?X.literalHeredocFiles?.get(at):void 0;if(lt===void 0)return je?dn(Q):null;return X.budget.charge("derivedTokens",1),Q?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:lt,depth:he+1}),X.analyzeNested(lt,{effectiveCwd:D,envAssignments:B})}function ax(O){let D=O[0];return O.length>=2&&(D==='"'||D==="'")&&O.at(-1)===D?O.slice(1,-1):O}function lx(O,D,B){let X={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[O.head];if(!X)return;if(O.options.trace?.recordSegment({type:"rule-check",rule:X,matched:!!D||!!B,reason:D?.reason??B?.originalReason}),B)O.options.trace?.recordSegment({type:"worktree-relaxation",originalReason:B.originalReason,gitCwd:B.gitCwd})}function Lm(O){if(O.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");O.iterations++}function on(O){return{reason:O.reason,ruleId:O.id||void 0,intent:O.intent}}function dn(O){return O?.recordSegment({type:"error",message:Gm}),on(cx())}function cx(){return{id:"",reason:Gm,intent:"stop_and_explain"}}function $m(O,D){return Kt.has(D)||O==="$SHELL"||O==="${SHELL}"||Kt.has(Tt(D))}function Wm(O,D){return O?.id.startsWith("custom.")||O?.id==="raw-text.dangerous-command"?O:wt(O,D)}var ux=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,dx=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function fx(O,D){let B=jm(O,D);if(B.length===0)return!1;let X=B[Hm(B)];if(X==="cd"||X==="pushd"||X==="popd")return!0;return ux.test(O.join(" "))}function Um(O,D,B,X){if(O.dialect==="powershell"){let at=mx(O.words,X);if(at.kind==="none")return;if(!D||at.kind==="unknown")return null;return Fm(yx(at.target),D,B.paths)}let Q=O.words.map(t);if(!fx(Q,B))return;if(!D)return null;let he=jm(Q,B,D),je=Hm(he);if(je===-1||he[je]!=="cd")return null;return Fm(he[je+1],D,B.paths)}function Fm(O,D,B){if(!O||O==="-"||O.includes("$")||O.includes("`"))return null;try{return bx(tr(D,O,B),D,B)?D:null}catch{return null}}function mx(O,D){let B=px(O[0])?1:0,X=O[B];if(!gx(X,B===1))return{kind:"none"};let Q=X.text.toLowerCase(),he=Q.split(/[\\/]/).pop()??Q;if(!dx.has(he))return{kind:"none"};if(Q!==he||he==="pop-location"||he==="popd")return{kind:"unknown"};return hx(O.slice(B+1),D)}function px(O){return O?.provenance==="literal"&&!O.quoted&&O.raw===O.text&&(O.text==="&"||O.text===".")}function gx(O,D){return O?.provenance==="literal"&&(D||!O.quoted&&O.raw===O.text)}function hx(O,D){let B;for(let X of O){if(X.provenance!=="literal"||B!==void 0)return{kind:"unknown"};B=X.text}if(B!==void 0)return{kind:"target",target:B};return D===void 0?{kind:"unknown"}:{kind:"target",target:D}}function yx(O){return O.includes("::")?void 0:O.replaceAll("\\","/")}function Hm(O){let D=0;if(O[0]==="builtin"&&O.length>1)D=1;if(O[D]!=="time")return D;let B=D+1;while(O[B]?.startsWith("-"))B++;return B}function jm(O,D,B){let X=Sx(O);return nr([...X],D,B)}function bx(O,D,B){let X=B.realpath(O),Q=B.realpath(D);if(X===null||Q===null)return vs(O)===vs(D);return vs(X)===vs(Q)}function Sx(O){let D=0;while(D<O.length){let B=O[D];if(B!=="{"&&B!=="("&&B!=="$(")break;D++}return O.slice(D)}var Hl="TMPDIR",jl="IFS",Vm=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Km=/^[A-Za-z_][A-Za-z0-9_]*$/,qm=new Set(["export","typeset","declare","readonly"]),Cx=new Set(["builtin","command","time"]);function Ym(O,D){return{env:O,effectiveEnvAssignments:_x(O,D),shellAssignments:new Map}}function Zm(O){return{env:O.env,effectiveEnvAssignments:O.effectiveEnvAssignments?new Map(O.effectiveEnvAssignments):void 0,shellAssignments:new Map(O.shellAssignments)}}function Vl(O,D){let B=Jm(O,D);B.assignments.filter((je)=>je.persists).forEach((je)=>{D.shellAssignments.set(je.name,je.value),Kl(D,je)});let X=B.commandIndex;if(X!==-1&&qm.has(O[X]??""))O.filter((je)=>Km.test(je)&&Ul(je)).forEach((je)=>{wx(D,je)});let Q=X===-1?-1:Qm(O,X);if(Q===-1||O[Q]!=="unset")return;let he=Ax(O,Q);if(he===null)return;O.slice(he).forEach((je)=>{Px(D,je)})}function Xm(O,D){let B=Jm(O,D).assignments;if(B.length===0)return D.effectiveEnvAssignments;let X=new Map(D.effectiveEnvAssignments??[]);return B.forEach((Q)=>{X.set(Q.name,Q.value)}),X}function Jm(O,D){let B=O.findIndex((je)=>!vx(je)),X=B!==-1&&qm.has(O[Qm(O,B)]??""),Q=xx(D);return{assignments:O.flatMap((je,at)=>{let lt=Ex(je,Q,D.env);if(!lt)return[];if(B!==-1&&at>B&&!X&&!$i(lt.name))return[];return Q.set(lt.name,lt.value),[{...lt,persists:B===-1||X}]}),commandIndex:B}}function Qm(O,D){let B=D;while(Cx.has(O[B]??"")){B+=1;while(O[B]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(O[B]??""))return D;B+=1}}return B}function vx(O){return En(O)!==null||Vm.test(O)}function Ex(O,D,B){return En(O)??Rx(O,D,B)}function Rx(O,D,B){let X=Ui(O,B,D);if(X)return X;let Q=O.match(Vm)?.[1];if(!Q)return null;let he=O.indexOf("=");return{name:Q,value:`${D.has(Q)?D.get(Q):B.get(Q)??""}${O.slice(he+1)}`}}function Ul(O){return O===Hl||O===jl||el(O)}function xx(O){return new Map([...O.effectiveEnvAssignments??[],...O.shellAssignments])}function _x(O,D){let B=[Hl,jl].map((X)=>{let Q=O.get(X);return Q===void 0?null:[X,Q]}).filter((X)=>X!==null);if(B.length===0)return D;return new Map([...B,...D??[]])}function Kl(O,D){let B=new Map(O.effectiveEnvAssignments??[]);B.set(D.name,D.value),O.effectiveEnvAssignments=B}function wx(O,D){Kl(O,{name:D,value:O.shellAssignments.get(D)??O.effectiveEnvAssignments?.get(D)??O.env.get(D)??""})}function Px(O,D){if(!Ul(D)&&!Km.test(D))return;if(O.shellAssignments.set(D,""),$i(D)&&O.env.has(D)){let X=new Map(O.env);X.delete(D),O.env=X}if(!Ul(D)||D===Hl||D===jl||co(D)){Kl(O,{name:D,value:""});return}if(!O.effectiveEnvAssignments?.has(D))return;let B=new Map(O.effectiveEnvAssignments);B.delete(D),O.effectiveEnvAssignments=B.size===0?void 0:B}function Ax(O,D){let B=D+1;while(B<O.length){let X=O[B];if(!X)return null;if(X==="--")return B+1;if(X==="-v"){B++;continue}if(X.startsWith("-"))return null;return B}return B}var Tx="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",kr="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 Jl(O,D,B,X){if(D>=a.recursionDepth.cap)return B.trace?.recordSegment({type:"error",message:Nn}),{reason:Nn,segment:O,intent:"stop_and_explain"};let Q=X??B.factStore?.getCommandProgram(O,B.shell??"auto")??h(O,B.shell);if(Q.status==="limited")return B.trace?.recordSegment({type:"error",message:Nn}),{reason:Nn,segment:O,intent:"stop_and_explain"};if(Q.status==="invalid"){let ct=Q.issues.find((ft)=>ft.code.includes("heredoc"));if(ct){if(!B.strict)return Xl(O,B);let ft=`${ts}: ${ct.message}`;return B.trace?.recordGlobal({type:"error",message:ft}),{reason:ft,segment:O,intent:"stop_and_explain"}}return ip(O,B),{reason:Zr,segment:O,intent:"stop_and_explain"}}if(B.strict&&Q.status==="partial")return ip(O,B),{reason:Zr,segment:O,intent:"stop_and_explain"};if(Q.issues.some((ct)=>ct.code.includes("quote")))return Xl(O,B);let je=B.cwd,at=B.effectiveCwd!==void 0?B.effectiveCwd:B.cwd,lt=Ym(B.environment.env,B.envAssignments);return _s(Q,D,{...B,rootProgram:Q},je,[{effectiveCwd:at,shellGitContextState:lt,literalHeredocFiles:new Map(B.literalHeredocFiles),functionDefinitions:new Map(B.functionDefinitions)}]).result}function _s(O,D,B,X,Q){let he=[...Q],je,at;for(let[lt,ct]of O.nodes.entries()){if(ct.kind==="connector"){at=ct.operator;continue}let ft=O.nodes[lt+1],dt=ft?.kind==="connector"?ft.operator:void 0,ut=Ix(O,lt,ct,at,dt),mt=at==="&&"||at==="||",pt=mt?je:void 0,ht=at==="&&"?pt?.success??he:at==="||"?pt?.failure??he:he,gt=at==="||"?pt?.success??[]:[],yt=at==="&&"?pt?.failure??[]:[],vt=mt||ro(dt);if(ct.kind==="function"){let jt=ht.flatMap((Vt)=>{let Gt=Yo(Vt);return Gt.functionDefinitions.set(ct.name,ct.body),ql(Vt,[Gt],ut,dt==="&",ro(dt))}),qt=Yl(jt,[],gt,yt,at,dt);he=qt.states,je=qt.conditionalStates,at=void 0;continue}if(ct.kind==="group"){let jt=[],qt=[];for(let Gt of ht){let Ot=_s(ct.body,D,B,X,[Yo(Gt)]);if(Ot.result)return Ot;if(jt.push(...ql(Gt,Ot.states,ut,dt==="&",ro(dt))),vt)qt.push(Gt,...ut?Ot.states.map((nn)=>Rs(Gt,nn)):Ot.states)}let Vt=Yl(jt,qt,gt,yt,at,dt);he=Vt.states,je=Vt.conditionalStates,at=void 0;continue}if(ct.kind!=="command")continue;let Et=B.trace?.flattenNested?B.trace.currentSegmentIndex:B.trace?.allocateSegment(),Ct=O.nodes[lt-2],Pt=ws(at)&&Ct?.kind==="command"?Xf(Ct)??Ox(Ct):void 0,Rt=[],_t=[];for(let jt of ht){let qt=Mx(ct,D,B,X,[Yo(jt)]);if(qt.result)return{result:qt.result,states:he};let Vt=O.dialect==="powershell"?qt.states:qt.states.map((Gt)=>Rs(jt,Gt));for(let Gt of Vt){let Ot=Yo(Gt),nn=Lx(ct,D,B.trace?{...B,trace:sp(B.trace,Et)}:B,X,Ot,ws(at),Pt);if(nn)return{result:nn,states:he};let Sn=Yx(ct,Ot.functionDefinitions);if(Sn)B.budget.charge("derivedTokens",Ps(Sn));let Fn=Sn?D+1>=a.recursionDepth.cap?Zl(ct.displayText,B,[Ot]):_s(Sn,D+1,B,X,[Ot]):{result:null,states:[Ot]};if(Fn.result)return Fn;if(Rt.push(...ql(jt,Fn.states,ut,dt==="&",ro(dt))),vt)_t.push(jt),_t.push(...Fn.states.map((xn)=>ut?Rs(jt,xn):xn))}}let Ut=Yl(Rt,_t,gt,yt,at,dt);he=Ut.states,je=Ut.conditionalStates,at=void 0}return{result:null,states:he}}function Ix(O,D,B,X,Q){if(B.kind==="group"&&B.style==="subshell")return!0;if(O.dialect==="posix"&&(ws(X)||ws(Q)))return!0;if(Q==="&")return!0;return O.dialect==="powershell"&&B.kind==="group"&&B.style==="brace"&&kx(O,D)}function ql(O,D,B,X,Q){let he=B?D.map((at)=>Rs(O,at)):[...D],je=Q?he.flatMap((at)=>no(O.literalHeredocFiles,at.literalHeredocFiles)?[at]:[{...at,literalHeredocFiles:new Map(O.literalHeredocFiles)},at]):he;return X?[O,...je]:je}function Rs(O,D){return{...O,literalHeredocFiles:new Map(D.literalHeredocFiles)}}function kx(O,D){let B=[...O.nodes.slice(0,D)].reverse().find((Q)=>Q.kind==="command"||Q.kind==="connector");if(!B||B.kind!=="command")return!0;let X=B.words[0]?.text.toLowerCase();if(X==="&"||X===".")return!1;if(X==="write-output"||X==="function"||X==="start-job")return!0;if(Dx(B))return!0;return B.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function ws(O){return O==="|"||O==="|&"}function Ox(O){if(O?.dialect!=="powershell")return;if(O.words.length===1&&O.words[0]?.quoted&&O.words[0].provenance==="literal")return O.words[0].text;if(O.words[0]?.text.toLowerCase()==="write-output"&&O.words.length===2&&O.words[1]?.provenance==="literal")return O.words[1].text;return}function ro(O){return O==="&&"||O==="||"}function Yl(O,D,B,X,Q,he){let je={success:xs([...B,...O]),failure:xs([...X,...D])},at=ro(he)?je:void 0;return{states:ro(Q)||at?xs([...je.success,...je.failure]):je.success,conditionalStates:at}}function sp(O,D,B=O.flattenNested){return{currentSegmentIndex:D,flattenNested:B,allocateSegment:O.allocateSegment,getNextSegmentIndex:O.getNextSegmentIndex,recordGlobal:O.recordGlobal,recordSegment:(X,Q=D)=>O.recordSegment(X,Q)}}function Mx(O,D,B,X,Q){let he=O.nested.map((je)=>({program:je,depth:D}));if(O.dialect==="powershell"){let je=Nx(O);if(je){if(D+1>=a.recursionDepth.cap)return Zl(je,B,Q);let at=h(je,"powershell");if(at.status==="limited")return Zl(je,B,Q);if(at.status!=="complete")return ep(he,B,X,Q);B.budget.charge("derivedTokens",Ps(at)),he.push({program:at,depth:D+1})}}return ep(he,B,X,Q)}function Dx(O){let D=O.words[0];return D?.provenance==="variable"&&O.words.at(-1)?.text==="="?D.text.toLowerCase():void 0}function ep(O,D,B,X){let Q=[...X];for(let he of O){let je=[];for(let at of Q){let lt=_s(he.program,he.depth,D,B,[Yo(at)]);if(lt.result)return lt;je.push(...lt.states)}Q=xs(je)}return{result:null,states:Q}}function Nx(O){let D=O.words[0]?.provenance==="literal"&&!O.words[0].quoted&&O.words[0].raw===O.words[0].text&&(O.words[0].text==="&"||O.words[0].text==="."),B=D?1:0,X=O.words[B];if(X?.provenance!=="literal"||!D&&(X.quoted||X.raw!==X.text)||!["iex","invoke-expression"].includes(X.text.toLowerCase()))return;let Q=O.words.slice(B+1),he=Q[0]&&!Q[0].quoted&&Q[0].raw===Q[0].text&&["-c","-command"].includes(Q[0].text.toLowerCase())?1:0,je=Q[he];return Q.length===he+1&&je?.quoted&&je.provenance==="literal"?je.text:void 0}function Ps(O){return O.nodes.reduce((D,B)=>D+(B.kind==="command"?B.words.length+B.nested.reduce((X,Q)=>X+Ps(Q),0):B.kind==="group"||B.kind==="function"?Ps(B.body):0),0)}function Zl(O,D,B){return D.trace?.recordSegment({type:"error",message:Nn}),{result:{reason:Nn,segment:O,intent:"stop_and_explain"},states:[...B]}}function Lx(O,D,B,X,Q,he,je){let at={...B,environment:{...B.environment,env:Q.shellGitContextState.env}},lt=Ux(O);if(lt&&at.strict)return at.trace?.recordSegment({type:"error",message:lt}),{reason:lt,segment:O.source,intent:"stop_and_explain"};ap(O,Q,"before-consumer",at.environment.paths,at.budget);let ct=Z(O.dialect,O.words).map(t),ft=O.displayText,dt=Xm(ct,Q.shellGitContextState);if(O.dialect==="powershell"){let pt=wt(Cf(O,he,Xx(at,Q.effectiveCwd)),at.policy);if(at.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!pt,reason:pt?.reason}),pt)return Zx(ft,pt)}if(ct.length===1&&ct[0]?.includes(" ")&&!Co(O.dialect,O.words)){let pt=wt($n(ct[0]),at.policy),ht=pt!==null&&!at.strict&&Cd(O,at.rootProgram);if(pt&&!ht)return at.trace?.recordSegment({type:"dangerous-text",token:ct[0],matched:!0,reason:pt.reason}),{reason:pt.reason,segment:ft,ruleId:pt.id,intent:pt.intent};at.trace?.recordSegment({type:"dangerous-text",token:ct[0],matched:!1});let gt=tp(O,lt,Q,dt,je,at);if(gt)return gt;return Vl(ct,Q.shellGitContextState),null}let ut=eo(O.words,D,{...at,commandView:O,cwd:X,effectiveCwd:Q.effectiveCwd,envAssignments:dt,literalHeredocFiles:Q.literalHeredocFiles,functionDefinitions:Q.functionDefinitions,hasPipelineInput:he,literalShellInput:je,analyzeNested:(pt,ht)=>{let gt=ht&&Object.hasOwn(ht,"effectiveCwd")?ht.effectiveCwd:Q.effectiveCwd,yt=Jl(pt,D+1,{...at,effectiveCwd:gt,envAssignments:ht?.envAssignments??dt,literalHeredocFiles:Q.literalHeredocFiles,functionDefinitions:ht?.functionDefinitions,worktreeMode:ht?.worktreeMode??at.worktreeMode,trace:at.trace?sp(at.trace,at.trace.currentSegmentIndex,!0):void 0});return yt?{reason:yt.reason,ruleId:yt.ruleId,intent:yt.intent}:null}});if(ut)return{...ut,segment:ft};let mt=tp(O,lt,Q,dt,je,at);if(mt)return mt;return Vl(ct,Q.shellGitContextState),null}function tp(O,D,B,X,Q,he){let je=Hx(O,D,B,X??new Map,he);if(je)return je;return ap(O,B,"after-consumer",he.environment.paths,he.budget),B.literalHeredocFiles.clear(),Gx(O,D,B,he.environment.paths,he.budget),Kx(O,B,Q,he.environment,he.trace),null}var Wx=new Set([">>","<>"]);function ap(O,D,B,X,Q){for(let je of O.redirections){if(!(B==="before-consumer"?Fx(je):Wx.has(je.operator)))continue;np(je.target,D,X,Q)}if(B!=="before-consumer"||!bn(O.words[0],"tee"))return;let he=lp(O.words.slice(1));if(!he)return;for(let je of he.operands)np(je,D,X,Q)}function Fx(O){if(O.operator===">"||O.operator===">|")return!0;return O.operator===">&"&&O.fd===void 0&&O.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(O.target.text)}function np(O,D,B,X){let Q=O?.provenance==="literal"?Po(O.text,D.effectiveCwd,B,X):void 0;if(!Q)return;D.literalHeredocFiles.delete(Q)}function Gx(O,D,B,X,Q){if(D)return;let he=O.redirections.find((je)=>je.operator==="<<"||je.operator==="<<-")?.heredoc;if(!he||!As(he))return;for(let je of zx(O)){let at=Po(je.text,B.effectiveCwd,X,Q);if(!at||!Rd(at))continue;if(!B.literalHeredocFiles.has(at)&&B.literalHeredocFiles.size>=a.trackedHeredocFiles.cap)throw new s("trackedHeredocFiles");B.literalHeredocFiles.set(at,he.body)}}function zx(O){let D=$x(O.redirections)?.target,B=rp(D)?[D]:[];if(bn(O.words[0],"cat"))return Bx(O.words)?B:[];if(!bn(O.words[0],"tee"))return[];let X=lp(O.words.slice(1));if(!X||X.append||X.hasUnsupportedOptions||!X.operands.every(rp))return[];return[...X.operands,...B]}function Bx(O){let D=!1;for(let B of O.slice(1)){if(D||B.provenance!=="literal")return!1;if(B.text==="--"){D=!0;continue}if(!/^-u+$/.test(B.text))return!1}return!0}function $x(O){let D=O.findLast((B)=>(B.fd??([">",">|",">>",">&"].includes(B.operator)?1:0))===1);return D?.operator===">"||D?.operator===">|"?D:void 0}function lp(O){let D=[],B=!0,X=!1,Q=!1;for(let he of O){if(he.provenance!=="literal")return;if(B&&bn(he,"--")){B=!1;continue}if(B&&!he.quoted&&he.raw===he.text&&/^-[^-]/.test(he.text)){X||=he.text.slice(1).includes("a"),Q||=[...he.text.slice(1)].some((je)=>je!=="a"&&je!=="i");continue}if(B&&!he.quoted&&he.raw===he.text&&he.text.startsWith("--")){X||=he.text==="--append",Q||=he.text!=="--append"&&he.text!=="--ignore-interrupts";continue}D.push(he)}return{operands:D,append:X,hasUnsupportedOptions:Q}}function rp(O){if(!O||O.provenance!=="literal"||O.text.length===0)return!1;if(O.quoted||O.raw!==O.text)return!0;return!O.raw.startsWith("~")&&!/[{}]/.test(O.raw)}function bn(O,D){return O?.text===D&&O.raw===D&&O.provenance==="literal"&&!O.quoted}function As(O){return O.quotedDelimiter||!/[$`\\]/.test(O.body)}function Ux(O){let D=O.redirections.filter((je)=>je.operator==="<<"||je.operator==="<<-");if(D.length===0)return;if(D.length!==1)return kr;let B=D[0];if(!B?.heredoc)return kr;if(!As(B.heredoc))return Tx;if(B.fd!==void 0&&B.fd!==0)return kr;if(O.redirections.some((je)=>je!==B&&["<","<<","<<-","<<<","<&","<>"].includes(je.operator)))return kr;let X=O.redirections.some((je)=>je!==B&&op(je.target));if(bn(O.words[0],"cat"))return X?kr:void 0;if(bn(O.words[0],"tee"))return X||O.words.slice(1).some(op)?kr:void 0;let Q=O.words[0],he=O.words[1];if(bn(Q,"git")&&(bn(he,"apply")||bn(he,"commit")))return;if(bn(Q,"gh")&&(bn(he,"pr")||bn(he,"issue"))&&bn(O.words[2],"create"))return;return kr}function op(O){return O?.parts.some((D)=>D.provenance==="command-substitution"&&D.raw.startsWith(">("))??!1}function Hx(O,D,B,X,Q){if(!D)return null;let he=O.redirections.filter((ct)=>ct.operator==="<<"||ct.operator==="<<-"),je=he.flatMap((ct)=>ct.heredoc?[ct.heredoc.body]:[]);if(Vx(O,he,B,X,Q))return null;let at=jx(O,he,Q);if(at!==void 0)return at?{reason:at.reason,segment:O.displayText,ruleId:at.id,intent:at.intent}:null;let lt=Xl(je.length===he.length?je.join(`
41
- `):O.source,Q);return lt?{...lt,segment:O.displayText}:null}function jx(O,D,B){let X=D.length===1?D[0]:void 0;if(!X?.heredoc||!As(X.heredoc)||X.fd!==void 0&&X.fd!==0)return;let Q=O.words[0];if(Q?.provenance!=="literal"||!wn(Q.text))return;if(!O.words.slice(1).every((ct)=>ct.provenance==="literal"&&ct.text.startsWith("-")))return;let je=X.heredoc.body,at=Jt(B.policy,"interpreter.one-liner-paranoid",!!B.paranoidInterpreters);if(B.trace?.recordSegment({type:"interpreter",interpreter:Q.text,codeArg:je,paranoidBlocked:at}),at){let ct=wt(St("interpreter.one-liner-paranoid",Ao),B.policy);if(ct)return ct}if(!To(je))return null;let lt=wt(St("interpreter.dangerous-command",Vr),B.policy);if(!lt)return null;return B.trace?.recordSegment({type:"dangerous-text",token:je,matched:!0,reason:lt.reason}),lt}function Vx(O,D,B,X,Q){let he=D.length===1?D[0]:void 0;if(!he?.heredoc||!As(he.heredoc)||he.fd!==void 0&&he.fd!==0)return!1;let je=Sr(O.words,Q.environment,B.effectiveCwd,X),at=je.words.map(t),lt=kt(at[0]??"");if((je.envSplitValues?.length??0)>0||!Kt.has(lt)&&!Kt.has(Tt(lt)))return!1;return qn(at)}function Kx(O,D,B,X,Q){let he=Um(O,D.effectiveCwd,X,B);if(he===null)Q?.recordSegment({type:"cwd-change",segment:O.words.map(t).join(" "),effectiveCwdNowUnknown:!0});if(he!==void 0)D.effectiveCwd=he}function Yo(O){return{effectiveCwd:O.effectiveCwd,shellGitContextState:Zm(O.shellGitContextState),literalHeredocFiles:new Map(O.literalHeredocFiles),functionDefinitions:new Map(O.functionDefinitions)}}function xs(O){let D=[];for(let B of O){if(!D.some((X)=>qx(X,B)))D.push(B);if(D.length>a.controlFlowStates.cap)throw new s("controlFlowStates")}return D}function qx(O,D){return O.effectiveCwd===D.effectiveCwd&&no(O.shellGitContextState.env,D.shellGitContextState.env)&&no(O.literalHeredocFiles,D.literalHeredocFiles)&&no(O.functionDefinitions,D.functionDefinitions)&&no(O.shellGitContextState.effectiveEnvAssignments,D.shellGitContextState.effectiveEnvAssignments)&&no(O.shellGitContextState.shellAssignments,D.shellGitContextState.shellAssignments)}function no(O,D){if(O===D)return!0;if(!O||!D||O.size!==D.size)return!1;return[...O].every(([B,X])=>D.get(B)===X&&D.has(B))}function Yx(O,D){let B=vo(O);return B===void 0?void 0:D.get(B)}function Zx(O,D){if(!D)return null;return{reason:D.reason,segment:O,ruleId:D.id,intent:D.intent}}function Xx(O,D=O.effectiveCwd){let B=D===null;return{environment:O.environment,cwd:B?void 0:D??O.cwd,originalCwd:B?void 0:O.cwd,strict:O.strict,paranoid:O.paranoidRm,allowTmpdirVar:O.allowTmpdirVar,protectedGitMetadata:O.protectedGitMetadata,policy:O.policy,budget:O.budget}}function Xl(O,D){let B=wt($n(O),D.policy),X=D.trace?.currentSegmentIndex??D.trace?.allocateSegment(),Q={type:"dangerous-text",token:O,matched:!!B,reason:B?.reason};if(D.trace?.recordSegment(Q,X),!B&&/^(?:cd|pushd)\s/.test(O))D.trace?.recordSegment({type:"cwd-change",segment:O,effectiveCwdNowUnknown:!0},X);return B?{reason:B.reason,segment:O,ruleId:B.id,intent:B.intent}:null}function ip(O,D){let B={type:"strict-unparseable",rawCommand:O,reason:Zr},X=D.trace?.currentSegmentIndex;if(X===void 0)D.trace?.recordGlobal(B);if(X!==void 0)D.trace?.recordSegment(B)}var Jx=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function cp(O,D,B,X){let Q=Jl(O,0,{...D,...Me(D),budget:D.budget??fn(),factStore:X},B);if(!Q)return null;return{kind:"deny",reason:Q.reason,intent:Q.intent??"manual_only",...Q.ruleId?{ruleId:Q.ruleId}:{},evidence:{command:O,segment:Q.segment}}}function up(O,D,B){try{return{decision:O()}}catch(X){let Q=Qx(X,D,B);if(!Q)throw X;return Q}}function Qx(O,D,B){if(!(O instanceof s)||!Jx.has(O.kind))return null;let X=a[O.kind];if(B?.currentSegmentIndex!==void 0)B.recordSegment({type:"error",message:X.reason});if(B?.currentSegmentIndex===void 0)B?.recordGlobal({type:"error",message:X.reason});return{decision:{kind:"deny",reason:X.reason,intent:"stop_and_explain",evidence:{command:D,segment:D}},errorCode:X.errorCode}}var e_=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),ec=new Set(["cc-safety-net","ccsn"]),t_=new Set(["bunx","npx","pnpx"]),n_=new Set(["pnpm","yarn"]),r_=new Set(["npm","pnpm","yarn"]),o_=new Set(["bun","node"]);function Is(O,D,B={}){if(ec.has(O))return 0;if(t_.has(O)){if(B.broad)return Ql(D);let Q=D[0]==="-y"||D[0]==="--yes"?1:0;return Ts(D[Q])?Q+1:null}let X=B.broad?D.findIndex((Q)=>!Q.startsWith("-")):0;if(X!==-1&&r_.has(O)&&B.broad&&D[X]==="exec"){let Q=Ql(D.slice(X+1));return Q===null?null:X+1+Q}if(n_.has(O)){if(O==="yarn"&&!B.broad)return null;if(!B.broad)return D[0]==="dlx"&&Ts(D[1])?2:null;if(X===-1||D[X]!=="dlx")return null;let Q=Ql(D.slice(X+1));return Q===null?null:X+1+Q}if(o_.has(O)){let Q=B.broad&&X!==-1?X:0;if(dp(D[Q]))return Q+1;if(O==="bun"&&D[Q]==="run"&&dp(D[Q+1]))return Q+2}return null}function Ql(O){let D=O.findIndex((X)=>Ts(X));if(D===-1)return null;let B=D;while(B<O.length){let X=O[B]??"";if(!X.startsWith("-")&&!Ts(X))break;B++}return B}function Ts(O){if(!O)return!1;let D=O.indexOf("@");if(D===-1)return ec.has(O);if(D===0)return!1;let B=O.slice(D+1);if(B===""||B.includes("/")||B.includes(":"))return!1;return ec.has(O.slice(0,D))}function dp(O){let D=O?.replaceAll("\\","/");return[...e_].some((B)=>D===B||D?.endsWith(`/${B}`))}var $e="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 fp(O,D,B){let X=cn(O,"input-candidate");if(!X)return null;let Q=qr(X.shell,O.invocation.context.executionCwd,D,B,{findSegmentTarget:(he)=>i_(he,D),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return Q?{target:Q}:null}function i_(O,D){let B=nr([...O],D),X=B.slice(1),Q=Is(Tt(B[0]??"").toLowerCase(),X,{broad:!0});if(Q===null)return null;let he=X.slice(Q).filter((je)=>je!=="-g"&&je!=="--global");return he[0]==="policy"&&he[1]==="apply"?B.join(" "):null}import{dirname as ks}from"node:path";var Fe="This path contains the protected policy config and you must not modify or delete it.",s_=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function hp(O,D,B){let X=f_(O.invocation.context,D,B);if(O.invocation.route.kind==="patch")return mp(O.paths,!1,O.invocation.context.executionCwd,X,D,B);let Q=cn(O,"input-candidate");if(O.invocation.route.kind==="command")return Q?pp(Q.shell,O.invocation.context.executionCwd,X,D,B):null;if(O.invocation.route.kind==="unknown"&&Q){let he=pp(Q.shell,O.invocation.context.executionCwd,X,D,B);if(he)return he}return mp(O.paths,O.invocation.route.kind==="grep"||O.invocation.route.kind==="glob"||si(O.invocation.toolName),O.invocation.context.executionCwd,X,D,B)}function mp(O,D,B,X,Q,he){if(D)return null;let je=O.find((at)=>Zo(at,B,X,Q,he));return je?{target:je}:null}function pp(O,D,B,X,Q){let he=qr(O,D,X,Q,{findSegmentTarget:(je,at)=>a_(je,at,B,X,Q)?.target??null,isRedirectionTarget:(je,at)=>Zo(je,at.cwd,B,X,Q),findMalformedTarget:(je)=>d_(je,D,B,X,Q)?.target??null});return he?{target:he}:null}function a_(O,D,B,X,Q){if(Do(O))return null;let he=Cr([...O],X),je=Tt(he[0]??"").toLowerCase(),at=he.slice(1);if(je==="rm"&&l_(at)){let lt=c_(at).find((ct)=>gp(ln(ct,D.variables),D.cwd,B,X,Q));if(lt)return{target:lt}}if(je==="find"){if(as(he,1)||El(he,X)){let ct=(ss($t(he))??$t(["."])).find((ft)=>{let dt=ln(ft.text,D.variables);return Zo(dt,D.cwd,B,X,Q)||gp(dt,D.cwd,B,X,Q)})?.text;if(ct)return{target:ct}}}if(je==="mv"){let lt=Zi(at).sources.find((ct)=>m_(ln(ct,D.variables),D.cwd,B,X,Q));if(lt)return{target:lt}}if(u_(he,je))return null;for(let lt of[...O,...he])for(let ct of yp(lt))if(Zo(ln(ct,D.variables),D.cwd,B,X,Q))return{target:ct};return null}function l_(O){return O.some((D)=>D==="--recursive"||D.startsWith("-")&&!D.startsWith("--")&&/[rR]/.test(D.slice(1)))}function c_(O){let D=O.indexOf("--");if(D!==-1)return[...O.slice(0,D).filter((B)=>!B.startsWith("-")),...O.slice(D+1)];return O.filter((B)=>!B.startsWith("-"))}function u_(O,D){if(!s_.has(D))return!1;if(D!=="sed")return!0;return!O.slice(1).some((B)=>B.startsWith("-i")||B==="--in-place"||B.startsWith("--in-place="))}function d_(O,D,B,X,Q){for(let he of O.split(/\s+/))for(let je of yp(he))if(Zo(je,D,B,X,Q))return{target:je};return null}function yp(O){let D=O.trim().replace(/^['"]|['"]$/g,""),B=D.indexOf("=");return B===-1||B===D.length-1?[D]:[D,D.slice(B+1)]}function f_(O,D,B){let X=(at)=>Xo(en(at,O.executionCwd,D,B)),Q=X(d(D)),he=[X(v(O.executionCwd)),X(v(O.configCwd))],je=new Set(he.map((at)=>ks(at)));for(let at=ks(Q);;at=ks(at))if(je.add(at),ks(at)===at)break;return{files:new Set([Q,...he]),directoriesAndAncestors:je}}function Zo(O,D,B,X,Q){let he=Sc(O,D,X,Q,(je)=>Xo(je)===fi);return he!==null&&B.files.has(Xo(he))}function gp(O,D,B,X,Q){return B.directoriesAndAncestors.has(Xo(en(O,D,X,Q)))}function m_(O,D,B,X,Q){let he=Xo(en(O,D,X,Q));return B.files.has(he)||B.directoriesAndAncestors.has(he)}function Xo(O){return process.platform==="win32"?O.toLowerCase():O}import{isAbsolute as Os,posix as p_,resolve as Ds,win32 as g_}from"node:path";import{fileURLToPath as h_}from"node:url";var Pp="Access to a sensitive path is not allowed.",Ap=new Set(["echo","printf"]),y_=new Set(["find"]),b_=new Set(["-exec","-execdir"]),S_=new Set([";","+"]),C_=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),v_=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Tp=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),E_=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),R_=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"]),Ip=new Set(["-c","-e","-r","-E","--eval","--exec"]),x_=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"])]]),__=new Set(["grep","rg"]),bp=new Set(["jq","gojq","jaq"]),Sp="f",Cp="file",w_="files",P_=new Set(["e","f"]),A_=new Set(["regexp","file"]),T_=new Set(["e","f","A","B","C","m"]),I_=new Set(["regexp","file","after-context","before-context","context","max-count"]),tc="__CC_SAFETY_NET_PIPE_INPUT__",rc=/[\w./~@+-]*[./~][\w./~@+-]*/g,k_=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,O_=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,M_=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,D_=/\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,N_=/\b(?:system|exec)\s*$/,L_=/\b(?:eval|exec)\s*\(/g,W_=/\b(?:eval|exec)\s*$/,F_=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 vp(O,D,B,X,Q,he){for(let je of O){let at=je.target;if(Lw(at,je.cwd,D?.denyPaths??[],B,X,Q))return{target:at,ruleId:"secret.deny-path"};if(he&&!he.has(at))continue;let lt=Dw(at,je.cwd,D,X,Q);if(lt){if(!lt.startsWith("secret.cli.")&&Ww(at,je.cwd,D?.allowPaths??[],B,X,Q))continue;return{target:at,ruleId:lt}}}return null}function kp(O,D,B,X,Q={}){let he=Ep(O,B,X),je=vp(he,D,O.invocation.context.configCwd,B,X);if(je===null)return null;let at=je.ruleId!=="secret.deny-path"&&Q.strict===!1?Ep(O,B,X,{refineInlineData:!0}):he,lt=at.length===he.length?je:vp(he,D,O.invocation.context.configCwd,B,X,new Set(at.map((ct)=>ct.target)));if(lt?.ruleId!=="secret.deny-path"&&Q.strict===!1&&G_(O,B))return null;return lt}function G_(O,D){let B=cn(O,"input-candidate")??cn(O,"declared-command");if(!B)return!1;if(B.program.nodes.some((at)=>at.kind==="command"&&at.nested.length>0))return!1;let X=[];for(let at of Yi(B.shell)){if(at.kind==="operator"&&at.boundary)return!1;if(at.kind==="redirection")return!1;if(at.kind==="operator")continue;X.push(Hn(at.text,D))}let Q=cr(X);if(Q.length===0)return!1;let he=Xn(Q[0]??"").toLowerCase(),je=Q.slice(1);if(O.invocation.route.kind==="unknown")return B.program.dialect==="powershell"&&(he==="ls"||he==="stat");if(he==="ls"||he==="stat")return!0;if(he==="test")return je.length===2&&(je[0]==="-e"||je[0]==="-f");if(he!=="find")return!1;return!je.some((at)=>C_.has(at))}function Ep(O,D,B,X={}){let Q=O.invocation.context.executionCwd,he=O.invocation.route.kind;if(he!=="command"&&he!=="unknown")return O.paths.map((at)=>({target:at,cwd:Q}));let je=cn(O,"input-candidate");return[...je?oo(je.shell,O.store,X,D,Q,B,z_(je)):[],...he==="unknown"?O.paths.map((at)=>({target:at,cwd:Q})):[]]}function z_(O){return O.program.dialect==="powershell"}function oo(O,D,B,X,Q,he,je=!1){if(O.status==="structural-limit")throw new y;if(O.status==="unclosed-quote")return[];if(O.status==="invalid")throw Error("Unable to parse command for secret protection");let at=[...O.assignmentFallbacks.map((ct)=>({target:ct,cwd:Q})),...hw(Hn(O.source,X),D,B,X,Q,he)],lt=(ct)=>Hn(X_(ct,je),X);return qi(O,Q,X,he,{word:lt,segment:(ct,ft,dt,ut,mt)=>{if(ct.length===0)return null;if(at.push(...Ns(ct,D,B,X,ft.cwd,he,mt)),dt!==null)at.push(...$_(dt,ct,D,B,X,ft.cwd,he));return null},redirection:(ct,ft)=>{if(ct.body!==void 0&&ct.consumer!==void 0)at.push(...Op(ct.consumer,[ct.body],D,B,X,ft.cwd,he,(dt)=>U_(ct.consumer??[],dt,D,B,X,ft.cwd,he)));if(ct.targetOrder==="legacy-segment")return ol;return at.push({target:lt(ct.target),cwd:ft.cwd}),null}}),at}function oc(O,D,B,X,Q,he){let je=D.getShellSyntax(O);if(je.status==="structural-limit")throw new y;return je.status==="complete"?oo(je,D,B,X,Q,he):null}function Ns(O,D,B,X,Q,he,je){let at=(pt)=>({target:pt,cwd:Q});if(je?.size){let pt=O.filter((ht,gt)=>!je.has(gt));if(bp.has(Xn(cr(pt)[0]??"").toLowerCase()))return[...O.filter((ht,gt)=>je.has(gt)).map(at),...Ns(pt,D,B,X,Q,he)]}let lt=Z_(O).map(at),ct=cr(O);if(ct.length===0)return lt;let ft=ct[0]??"",dt=Xn(ft).toLowerCase(),ut=ct.slice(1),mt=B_(ft,dt,ut);if(mt)return[...lt,...mt.map(at)];if(Ap.has(dt))return B.capturedOutput===!0?[...lt,...Mp(O).map(at)]:lt;if(dt==="eval")return[...lt,...oc(ut.join(" "),D,B,X,Q,he)??ut.map(at)];if(dt==="export")return[...lt,...ut.flatMap((pt)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(pt)?[pt.slice(pt.indexOf("=")+1)]:Zn(dt,pt)).map(at)];if(dt==="git")return[...lt,...Q_(ut).map(at)];if(bp.has(dt))return[...lt,...J_(ut).map(at)];if(__.has(dt))return[...lt,...xw(ut).map(at)];if(y_.has(dt))return[...lt,...rw(ut,D,B,X,Q,he).map(at)];if(vn.has(dt))return[...lt,...ut.flatMap((pt)=>Zn("awk",pt)).map(at),...ut.flatMap((pt)=>iw(pt,D,B,X,Q,he)),...ut.flatMap(sw).map(at)];if(dt==="curl")return[...lt,...ut.flatMap((pt)=>Zn(dt,pt)).map(at),...ew(ut).map(at)];if(No(dt)){let pt=Mo.has(dt)?gn([dt,...ut]):null;if(pt!==null&&pt.command!==null&&pt.commandIndex!==null){let ht=D.getShellSyntax(pt.command);if(ht.status==="structural-limit")throw new y;if(ht.status==="complete")return[...lt,...oo(ht,D,B,X,Q,he),...ut.slice(pt.commandIndex).filter((gt)=>!gt.startsWith("-")).map(at)]}return[...lt,...ow(dt,ut,D,B,X,Q,he)]}return[...lt,...ut.flatMap((pt)=>Zn(dt,pt)).map(at)]}function B_(O,D,B){let X=Is(D,B);if(X===null||B[X]!=="explain")return null;let Q=[O,...B.slice(0,X)],he=B.slice(X+1);for(let je=0;je<he.length;je++){let at=he[je];if(at==="--json"||at==="--help"||at==="-h")continue;if(at==="--cwd"){let lt=he[je+1];if(lt&&!lt.startsWith("--"))Q.push(lt);je++;continue}return Q}return Q}function $_(O,D,B,X,Q,he,je){if(K_(D,B,X,Q,he,je))return Mp(O).map((at)=>({target:at,cwd:he}));return Op(D,H_(O),B,X,Q,he,je,()=>[])}function U_(O,D,B,X,Q,he,je){let at=cr(O);if(!No(Xn(at[0]??"").toLowerCase()))return[];return oc(D,B,X,Q,he,je)??[{target:D,cwd:he}]}function Op(O,D,B,X,Q,he,je,at){let lt=q_(O);if(lt===null)return D.flatMap(at);return D.flatMap((ct)=>Mo.has(lt)?oo(B.getShellSyntax(ct),B,X,Q,he,je):Ms(lt,ct,B,X,Q,he,je))}function Mp(O){let D=cr(O);if(D.length===0)return[];let B=Xn(D[0]??"").toLowerCase();if(!Ap.has(B))return[];let X=D[D[1]==="--"?2:1];if(B==="printf"&&X!==void 0&&!X.startsWith("-")&&!X.replaceAll("%%","").includes("%"))return[ic(X.replaceAll("%%","%"))];return D.slice(1)}function H_(O){let D=cr(O);if(D.length===0)return[];let B=Xn(D[0]??"").toLowerCase(),X=D.slice(1);if(B==="echo"){let Q=X.findIndex((he)=>!/^-[neE]+$/.test(he));return[(Q===-1?[]:X.slice(Q)).join(" ")]}if(B==="printf")return j_(X);return[]}function j_(O){let D=O[0];if(D===void 0)return[];let B=(D.match(/%%|%[bqs]/g)??[]).filter((Q)=>Q!=="%%").length;if(B===0||O.length===1)return[ic(D)];let X=O.slice(1);return Array.from({length:Math.ceil(X.length/B)},(Q,he)=>V_(D,X.slice(he*B,(he+1)*B)))}function V_(O,D){let B=0;return ic(O.replace(/%%|%[bqs]/g,(X)=>{if(X==="%%")return"%";let Q=D[B]??"";return B++,Q}))}function ic(O){return O.replace(/\\n/g,`
42
- `).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function K_(O,D,B,X,Q,he){let je=cr(O);if(je.length===0||Xn(je[0]??"").toLowerCase()!=="xargs")return!1;let at=Tr(je),lt=je.slice(at.childStart);if(lt.length===0)return!1;if(at.replacementToken==="")return!1;let ct=at.replacementToken,ft=ct===null?[...lt,tc]:lt.map((dt)=>dt.split(ct).join(tc));return Ns(ft,D,B,X,Q,he).some((dt)=>dt.target.includes(tc))}function q_(O){let D=cr(O);if(D.length===0)return null;let B=Xn(D[0]??"").toLowerCase();if(!No(B))return null;return Y_(B,D.slice(1))?B:null}function Y_(O,D){let B=sc(O);for(let X=0;X<D.length;X++){let Q=D[X];if(Q===void 0)break;if(Ip.has(Q)||Dp(O,Q)||/^--(?:eval|exec)=/.test(Q))return!1;if(Q==="-")return!0;if(Q.startsWith("-")){if(B==="python"&&Q==="-m")return!1;if(F_.get(B)?.has(Q))X++;continue}return!1}return!0}function sc(O){return/^python\d/.test(O)?"python":O}function Z_(O){let D=[];for(let B of O){if(Lp(B))continue;let X=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(B);if(X===null)break;if(X[1]!==void 0&&X[1]!=="")D.push(X[1])}return D}var Rp=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function X_(O,D){if(!D||!Rp.test(O))return O;return`~${O.replace(Rp,"").replace(/\\/g,"/")}`}function Zn(O,D){if(D==="--")return[];let B=[],X=D.indexOf("=");if(X>0&&X<D.length-1)B.push(D.slice(X+1));if(D.startsWith("-"))return B;if(O==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(D))return B;if(O==="zip"&&/\.zip$/i.test(D))return B;return B.push(D),B}function J_(O){let D=-1,B=!1;for(let X=0;X<O.length;X++){let Q=O[X]??"";if(!B&&Q==="--"){B=!0;continue}if(B||!/^-(?:[A-Za-z]|-)/.test(Q)){if(D===-1)D=X;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(Q)){X+=2;continue}if(Q==="--indent"||Q==="-L"){X++;continue}if(Q.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(Q)||/^--(?: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(Q))continue;return O.flatMap((he)=>Zn("jq",he))}return O.flatMap((X,Q)=>Q===D?[]:Zn("jq",X))}function Q_(O){let D=[];for(let B=0;B<O.length;B++){let X=O[B]??"";if(X==="--"||!X.startsWith("-"))return[...D,...O.slice(B).flatMap((he)=>Zn("git",he))];if(D.push(...Zn("git",X)),!pn.has(X))continue;let Q=O[B+1];if(Q===void 0)break;D.push(...X==="-c"&&Q.includes("=")?[Q.slice(Q.indexOf("=")+1)]:Zn("git",Q)),B++}return D}function ew(O){return O.flatMap((D,B)=>{let X=nw(D);if(X!==null)return xp(X.flag,X.value);let Q=tw(O[B-1]);return Q===null?[]:xp(Q,D)})}function xp(O,D){if(O==="-F"||O==="--form"){let B=D.indexOf("="),X=B===-1?D:D.slice(B+1);if(!X.startsWith("@")&&!X.startsWith("<"))return[];return nc(X.slice(1).split(";")[0]??"")}if(O==="--data-urlencode"){let B=D.indexOf("@"),X=D.indexOf("=");if(B===-1||X!==-1&&X<B)return[];return nc(D.slice(B+1))}return D.startsWith("@")?nc(D.slice(1)):[]}function tw(O){if(O===void 0)return null;if(Tp.has(O))return O;return/^-[A-Za-z]+[dF]$/.test(O)?`-${O.slice(-1)}`:null}function nw(O){let D=O.slice(0,2);if(O.length>2&&(D==="-d"||D==="-F"))return{flag:D,value:O.slice(2)};let B=O.indexOf("=");if(B===-1)return null;let X=O.slice(0,B);return Tp.has(X)?{flag:X,value:O.slice(B+1)}:null}function nc(O){return O===""||O==="-"?[]:[O]}function rw(O,D,B,X,Q,he){let je=O.findIndex((lt)=>lt.startsWith("-")||lt==="("||lt==="!"||lt===";"),at=[...O.slice(0,je===-1?O.length:je)];for(let lt=0;lt<O.length;lt++){if(!b_.has(O[lt]??""))continue;let ct=O.slice(lt+1),ft=ct.findIndex((mt)=>S_.has(mt)),dt=ft===-1?ct:ct.slice(0,ft),ut=Ns(dt,D,B,X,Q,he).map((mt)=>mt.target);if(at.push(...ut.filter((mt)=>mt!=="{}")),!ut.includes("{}"))continue;at.push(...O.slice(0,lt).flatMap((mt,pt,ht)=>{if(!v_.has(mt))return[];let gt=ht[pt+1];return gt===void 0?[]:[gt,gt.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return at}function ow(O,D,B,X,Q,he,je){let at=[];for(let lt=0;lt<D.length;lt++){let ct=D[lt];if(ct===void 0)break;if(Ip.has(ct)||Dp(O,ct)){let dt=D[lt+1];if(dt!==void 0)at.push(...Ms(O,dt,B,X,Q,he,je)),lt++;continue}let ft=/^--(?:eval|exec)=(.*)$/.exec(ct);if(ft!==null&&ft[1]!==void 0){at.push(...Ms(O,ft[1],B,X,Q,he,je));continue}if(!ct.startsWith("-"))at.push({target:ct,cwd:he})}return at}function Dp(O,D){if(!D.startsWith("-")||D.startsWith("--")||D.length<=2)return!1;return x_.get(D[D.length-1]??"")?.has(sc(O))??!1}function iw(O,D,B,X,Q,he){if(!O.includes("system"))return[];return bl(O)?.commands.flatMap((je)=>oo(D.getShellSyntax(je),D,B,X,Q,he))??[]}function sw(O){return Array.from(O.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((D)=>D[1]).filter((D)=>D!==void 0&&D!=="")}function aw(O){let D=Array.from(O.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((B)=>B[2]).filter((B)=>B!==void 0&&B!=="");return[...D,...D.flatMap(ac),...O.match(rc)??[]]}function Ms(O,D,B,X,Q,he,je){let at=(mt)=>({target:mt,cwd:he}),lt=cw(D,lw(O));if(lt===null)return aw(D).map(at);let ct=lt.masked.match(D_)!==null||lt.literals.some((mt)=>N_.test(lt.masked.slice(0,mt.start))),ft=lt.masked.match(L_)!==null||lt.literals.some((mt)=>W_.test(lt.masked.slice(0,mt.start))),dt=X.refineInlineData===!0&&!Mo.has(O),ut=dt&&!(mw(lt.masked)||ct||ft)?[]:lt.literals;return[...ut.map((mt)=>mt.text).filter((mt)=>mt!=="").map(at),...ut.flatMap((mt)=>ac(mt.text)).map(at),...dt?[]:lt.literals.flatMap((mt)=>mt.text.match(rc)??[]).map(at),...ct?lt.literals.flatMap((mt)=>oc(mt.text,B,X,Q,he,je)??[at(mt.text)]):[],...ft?lt.literals.flatMap((mt)=>Ms(O,mt.text.replace(/\\(.)/g,(pt,ht)=>ht==="n"?`
43
- `:ht),B,X,Q,he,je)):[],...(lt.masked.match(rc)??[]).map(at)]}function lw(O){let D=sc(O);if(D==="python")return"python";if(D==="osascript")return"opaque";return D==="node"||D==="bun"||D==="deno"?"javascript":"simple"}function cw(O,D){if(D==="opaque")return null;let B=O.split(""),X=[];for(let Q=0;Q<O.length;Q++){let he=O[Q]??"";if(D==="simple"&&(he==="`"||he==="%"||he==="<")){if(O_.test(O.slice(Q)))return null}let je=he==="'"||he==='"'||D==="javascript"&&he==="`"?he:null;if(je===null)continue;if(je==="`"&&fw(O,Q))return null;let at=D==="python"?uw(O,Q):"",lt=D==="python"&&O.startsWith(je.repeat(3),Q)?je.repeat(3):je,ct=Q+lt.length,ft=dw(O,ct,lt);if(ft===null)return null;let dt=O.slice(ct,ft);if(/[fF]/.test(at)&&dt.includes("{"))return null;if(D==="simple"&&je==='"'&&M_.test(dt))return null;X.push({start:ct,text:dt});for(let ut=Q;ut<ft+lt.length;ut++)B[ut]=" ";Q=ft+lt.length-1}return{masked:B.join(""),literals:X}}function uw(O,D){return k_.exec(O.slice(Math.max(0,D-3),D))?.[1]??""}function dw(O,D,B){let X=B==="`",Q=X||B.length===3;for(let he=D;he<O.length;he++){let je=O[he];if(je==="\\"){he++;continue}if(X&&je==="$"&&O[he+1]==="{")return null;if(!Q&&(je===`
44
- `||je==="\r"))return null;if(O.startsWith(B,he))return he}return null}function fw(O,D){for(let B=D-1;B>=0;B--){let X=O[B];if(!X||/\s/.test(X))continue;return/[\w$\])]/.test(X)}return!1}function mw(O){for(let D of O.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let B=D[0],X=D.index;if(E_.has(B.toLowerCase()))return!0;let Q=B.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((he)=>he.toLowerCase());if(!Q.some((he)=>R_.has(he)))continue;if(Q.length>1)return!0;if(pw(O,X)===".")return!0;if(gw(O,X+B.length)==="(")return!0}return!1}function pw(O,D){for(let B=D-1;B>=0;B--)if(!/\s/.test(O[B]??""))return O[B];return}function gw(O,D){for(let B=D;B<O.length;B++)if(!/\s/.test(O[B]??""))return O[B];return}function hw(O,D,B,X,Q,he){return vw(O).flatMap((je)=>{let at=D.getShellSyntax(je);if(at.status==="invalid")return[];return[...oo(at,D,{...B,capturedOutput:!0},X,Q,he),...yw(at,X)?bw(at,X).map((lt)=>({target:lt,cwd:Q})):[]]})}function yw(O,D){let B=Yi(O);for(let X=0;X<B.length;X++){let Q=B[X];if(Q?.kind!=="word"||Xn(Hn(Q.text,D)).toLowerCase()!=="base64")continue;for(let he=X+1;he<B.length;he++){let je=B[he];if(je?.kind==="operator")break;if(je?.kind!=="word")continue;let at=Hn(je.text,D);if(at==="--decode"||!at.startsWith("--")&&at.startsWith("-")&&/[dD]/.test(at))return!0}}return!1}function bw(O,D){return Yi(O).flatMap((B)=>B.kind==="word"?[Hn(B.text,D)]:B.kind==="redirection"&&B.target?[Hn(B.target,D)]:[]).flatMap(ac)}function ac(O){let D=Cw(O);if(D===null)return[];let B=Buffer.from(D,"base64").toString("utf8");if(B===""||Sw(B))return[];return Buffer.from(B,"utf8").toString("base64").replace(/=+$/g,"")===D.replace(/=+$/g,"")?[B]:[]}function Sw(O){return Array.from(O).some((D)=>{let B=D.charCodeAt(0);return B<32||B===127})}function Cw(O){if(O.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(O))return null;if(/=/.test(O.replace(/=+$/g,"")))return null;let D=O.replace(/=+$/g,"");if(D.length%4===1)return null;return`${D.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-D.length%4)%4)}`}function vw(O){let D=[],B={inSingle:!1,inDouble:!1,escaped:!1};for(let X=0;X<O.length;X++){let Q=O[X];if(!Q)break;if(ho(Q,B))continue;if(Np(O,X,B)){let he=Ew(O,X+1);if(he!==null)D.push(he.body),X=he.endIndex;continue}if(!B.inSingle&&Q==="`"){let he=Rw(O,X);if(he!==null)D.push(he.body),X=he.endIndex}}return D}function Ew(O,D){let B={inSingle:!1,inDouble:!1,escaped:!1},X=1;for(let Q=D+1;Q<O.length;Q++){let he=O[Q];if(!he)break;if(ho(he,B))continue;if(Np(O,Q,B)){X++,Q++;continue}if(!B.inSingle&&!B.inDouble&&he===")"){if(X--,X===0)return{body:O.slice(D+1,Q),endIndex:Q}}}return null}function Rw(O,D){let B=!1;for(let X=D+1;X<O.length;X++){let Q=O[X];if(!Q)break;if(B){B=!1;continue}if(Q==="\\"){B=!0;continue}if(Q==="`")return{body:O.slice(D+1,X),endIndex:X}}return null}function Np(O,D,B){return!B.inSingle&&O[D]==="$"&&O[D+1]==="("&&O[D+2]!=="("}function xw(O){let D=[],B=[],X=!1,Q=!1,he=!1;for(let lt=0;lt<O.length;lt++){let ct=O[lt];if(ct===void 0)break;if(!he&&ct==="--"){he=!0;continue}if(he){B.push(ct);continue}let ft=/^--([^=]+)(?:=(.*))?$/.exec(ct);if(ft!==null){let dt=ft[1]??"",ut=ft[2];if(dt===w_)Q=!0;if(A_.has(dt))X=!0;if(ut!==void 0){if(dt===Cp)D.push(ut);continue}if(I_.has(dt)){let mt=O[lt+1];if(dt===Cp&&mt!==void 0)D.push(mt);lt++}continue}if(ct.startsWith("-")&&ct.length>1){let dt=ct.slice(1),ut="",mt="";for(let ht=0;ht<dt.length;ht++){let gt=dt[ht]??"";if(P_.has(gt))X=!0;if(T_.has(gt)){ut=gt,mt=dt.slice(ht+1);break}}if(ut==="")continue;if(mt.length>0){if(ut===Sp)D.push(mt);continue}let pt=O[lt+1];if(ut===Sp&&pt!==void 0)D.push(pt);lt++;continue}B.push(ct)}let at=!X&&!Q?B.slice(1):B;return[...D,...at]}function cr(O){let D=O.findIndex((B)=>!Lp(B)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(B));return D===-1?[]:[...O.slice(D)]}function Lp(O){return O==="env"||O==="command"||O==="builtin"||O==="sudo"}var _w=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),ww=".env.",Pw=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),Aw=[".env.example.",".env.sample."];function Tw(O){let D;try{D=new URL(O.trim())}catch{return!1}return D.protocol!=="file:"&&D.host!==""}function Iw(O){return O.length>0&&!/\s/.test(O)}function kw(O,D,B,X){try{let Q=ei(O,D,B,X);return Q!==""&&B.paths.entryKind(Q)!=="missing"}catch(Q){if(Q instanceof s)throw Q;return!1}}var Ow=new Set(["node_modules","__pycache__"]),Mw=[["vendor","bundle"],["vendor","cache"]];function Dw(O,D,B,X,Q){if(Tw(O))return null;let he=Wn(O,D,X,Q);if(!he)return null;let je=Ft(he.split("/").pop()??""),at=Ft(he),lt=()=>Iw(je)||kw(O,D,X,Q);if(Pw.has(je)||Aw.some((ut)=>je.startsWith(ut)))return null;let ct=Ft(zw(O,D,X,Q));for(let ut of ha){let mt=`~/${ut.suffixParts.join("/")}`;if((wp(at,mt)||wp(ct,mt))&&Yn(ut.id,B))return ut.id}let ft=Nw(he,D,B,X,Q);if(ft)return ft;if(_w.has(je))return null;for(let ut of ga)if(je===ut.basename&&Yn(ut.id,B))return ut.id;if(je.startsWith(ww)&&Yn(yi.id,B)&&lt())return yi.id;for(let ut of ya)if(je.length>ut.prefix.length&&je.startsWith(ut.prefix)){let mt=je.slice(ut.prefix.length)[0];if((mt==="-"||mt==="_")&&Yn(ut.id,B)&&lt())return ut.id}for(let ut of ba)if(je.length>ut.prefix.length&&je.startsWith(ut.prefix)){if(je.slice(ut.prefix.length)===ut.suffix&&Yn(ut.id,B))return ut.id}if(Fw(at))return null;if(!je.includes(".")&&yo.pattern.test(je)&&Yn(yo.id,B))return yo.id;let dt=Gw(je,B);if(dt)return dt;return null}function Nw(O,D,B,X,Q){return bi.find((he)=>{if(!Yn(he.id,B))return!1;switch(he.id){case"secret.cli.claude-code":return Dt(O,Wt(X.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",D,X,Q),[".credentials.json"]);case"secret.cli.claude-code.config":{let je=Ft(O).split("/");return Dt(O,Wt(X.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",D,X,Q),["settings.json","settings.local.json"])||Qo(O,"~/.claude.json",D,X,Q)||je.at(-1)==="settings.local.json"&&je.at(-2)===".claude"||je.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Dt(O,Wn("~/.gemini/config",D,X,Q),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let je=Wt(X.env.get("CODEX_HOME"),"~/.codex",D,X,Q);return Dt(O,je,["auth.json",".credentials.json"])||Jo(O,je,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let je=Wt(X.env.get("CODEX_HOME"),"~/.codex",D,X,Q),at=Ft(O).split("/").at(-1)??"";return Dt(O,je,["config.toml"])||at.endsWith(".config.toml")&&Dt(O,je,[at])}case"secret.cli.gemini":return Dt(O,tn(Wt(X.env.get("GEMINI_CLI_HOME"),"~",D,X,Q),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let je=Ft(O).split("/"),at=X.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),lt=X.env.get("ProgramData")?[tn(Wt(X.env.get("ProgramData"),"",D,X,Q),"gemini-cli")]:[];return Dt(O,tn(Wt(X.env.get("GEMINI_CLI_HOME"),"~",D,X,Q),".gemini"),["settings.json","google_accounts.json"])||je.at(-1)==="settings.json"&&je.at(-2)===".gemini"||(at?.trim()?Qo(O,at,D,X,Q):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...lt].some((ct)=>Dt(O,Wn(ct,D,X,Q),["settings.json"]))}case"secret.cli.copilot-cli":{let je=Wt(X.env.get("COPILOT_HOME"),"~/.copilot",D,X,Q);return Dt(O,je,["config.json"])||Jo(O,je,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Dt(O,Wt(X.env.get("COPILOT_HOME"),"~/.copilot",D,X,Q),["mcp-config.json"]);case"secret.cli.kimi-code":{let je=Wt(X.env.get("KIMI_CODE_HOME"),"~/.kimi-code",D,X,Q),at=Wt(X.env.get("KIMI_SHARE_DIR"),"~/.kimi",D,X,Q);return Dt(O,je,["server.token"])||Jo(O,je,["credentials"])||Jo(O,at,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let je=["config.toml","mcp.json"],at=Ft(O).split("/");return at.at(-1)==="mcp.json"&&at.at(-2)===".kimi-code"||Dt(O,Wt(X.env.get("KIMI_CODE_HOME"),"~/.kimi-code",D,X,Q),je)||Dt(O,Wt(X.env.get("KIMI_SHARE_DIR"),"~/.kimi",D,X,Q),[...je,"config.json","config.json.bak"])}case"secret.cli.opencode":{let je=tn(Wt(X.env.get("XDG_DATA_HOME"),"~/.local/share",D,X,Q),"opencode"),at=Ft(O).split("/").at(-1)??"",lt=X.env.get("OPENCODE_DB")?.trim(),ct=lt&&lt!==":memory:"?[lt,`${lt}-wal`,`${lt}-shm`]:[];return Dt(O,je,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(at)&&Dt(O,je,[at])||ct.some((ft)=>Qo(O,ft,D,X,Q))}case"secret.cli.opencode.config":{let je=X.env.get("OPENCODE_CONFIG_DIR")?Wt(X.env.get("OPENCODE_CONFIG_DIR"),"~/.config/opencode",D,X,Q):tn(Wt(X.env.get("XDG_CONFIG_HOME"),"~/.config",D,X,Q),"opencode"),at=X.env.get("ProgramData")?[tn(Wt(X.env.get("ProgramData"),"",D,X,Q),"opencode")]:[],lt=["opencode.json","opencode.jsonc"],ct=X.env.get("OPENCODE_CONFIG");return lt.includes(Ft(O).split("/").at(-1)??"")||Dt(O,je,lt)||(ct?.trim()?Qo(O,ct,D,X,Q):!1)||["/Library/Application Support/opencode","/etc/opencode",...at].some((ft)=>Dt(O,Wn(ft,D,X,Q),lt))}case"secret.cli.pi":return Dt(O,Wt(X.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",D,X,Q),["auth.json"]);case"secret.cli.pi.config":return Dt(O,Wt(X.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",D,X,Q),["models.json"]);case"secret.cli.amp":{let je=Wn("~",D,X,Q);return[tn(Wt(X.env.get("XDG_DATA_HOME"),"~/.local/share",D,X,Q),"amp"),tn(je,".local","share","amp")].some((lt)=>Dt(O,lt,["secrets.json"]))||Jo(O,tn(je,".amp"),["oauth"])}case"secret.cli.amp.config":{let je=["settings.json","settings.jsonc"],at=[tn(Wt(X.env.get("XDG_CONFIG_HOME"),"~/.config",D,X,Q),"amp"),tn(Wn("~",D,X,Q),".config","amp")],lt=Ft(O).split("/"),ct=X.env.get("AMP_SETTINGS_FILE");return at.some((ft)=>Dt(O,ft,je))||lt.at(-2)===".amp"&&je.includes(lt.at(-1)??"")||(ct?.trim()?Qo(O,ct,D,X,Q):!1)}case"secret.cli.cursor":{let je=tn(Wt(X.env.get("XDG_CONFIG_HOME"),"~/.config",D,X,Q),"cursor"),at=tn(Wt(X.env.get("CURSOR_DATA_DIR"),"~/.cursor",D,X,Q),"projects");return Dt(O,Wn("~/.cursor",D,X,Q),["auth.json"])||Dt(O,je,["auth.json"])||Ft(O).split("/").at(-1)==="mcp-auth.json"&&Or(Ft(O),Ft(at))}case"secret.cli.cursor.config":{let je=Ft(O).split("/");return je.at(-1)==="mcp.json"&&je.at(-2)===".cursor"}case"secret.cli.grok-build":return Dt(O,Wt(X.env.get("GROK_HOME"),"~/.grok",D,X,Q),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let je=Ft(O).split("/");return je.at(-1)==="config.toml"&&je.at(-2)===".grok"||Dt(O,Wt(X.env.get("GROK_HOME"),"~/.grok",D,X,Q),["config.toml","managed_config.toml","requirements.toml"])||Dt(O,Wn("/etc/grok",D,X,Q),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var _p=new WeakMap;function Wt(O,D,B,X,Q){let he=_p.get(Q)??new Map;_p.set(Q,he);let je=`${B}\x00${O??""}\x00${D}`,at=he.get(je);if(at!==void 0)return at;let lt=Wn(O?.trim()?O:D,B,X,Q);return he.set(je,lt),lt}function Dt(O,D,B){return B.some((X)=>Wp(O,tn(D,X)))}function Jo(O,D,B){return B.some((X)=>Or(Ft(O),Ft(tn(D,X))))}function Qo(O,D,B,X,Q){return Wp(O,Wn(D,B,X,Q))}function Wp(O,D){return Ft(O)===Ft(D)}function tn(O,...D){return Dn([O,...D].filter(Boolean).join("/"))}function Lw(O,D,B,X,Q,he){if(B.length===0)return!1;let je=Ft(ei(O,D,Q,he));return B.some((at)=>Or(je,Ft(ei(at,X,Q,he))))}function Ww(O,D,B,X,Q,he){if(B.length===0)return!1;let je=Ft(ei(O,D,Q,he));if(!je)return!1;let at=Q.env.get("HOME")??Q.home,lt=at?Dn(Lt(mn(at),Q.paths,he)):"",ct=Ft(lt),ft=Q.env.get("CC_SAFETY_NET_HOME"),dt=Ft(ft?Dn(Lt(Ds(mn(ft)),Q.paths,he)):lt&&Dn(Lt(`${lt}/.cc-safety-net`,Q.paths,he)));if(dt&&Or(je,dt))return!1;return B.some((ut)=>{let mt=Ft(ei(ut,X,Q,he));if(!mt)return!1;if(ct&&(ct===mt||ct.startsWith(mt.endsWith("/")?mt:`${mt}/`)))return!1;return Or(je,mt)})}function Fw(O){let D=O.split("/");return D.some((B)=>Ow.has(B))||Mw.some(([B,X])=>D.some((Q,he)=>Q===B&&D[he+1]===X))}function Gw(O,D){let B=O.lastIndexOf("."),X=B>0&&B<O.length-1?O.slice(B+1):"";if(X==="")return null;for(let Q of Sa)if(X===Q.extension&&Yn(Q.id,D))return Q.id;for(let Q of Ca)if(Q.pattern.test(X)&&Yn(Q.id,D))return Q.id;return null}function Ft(O){return O.toLowerCase()}function Yn(O,D){return!D?.disabledRules?.includes(O)}function Wn(O,D,B,X){let{home:Q,normalized:he}=lc(O,B,X);if(!he)return"";if(!Q)return he;let je=cc(he,Q),at=Os(je)?je:Dn(Ds(D,je)),lt=Dn(Lt(at,B.paths,X));if(!Or(lt,Q)){if(Os(je))return lt;return lt===at?he:lt}let ct=lt.slice(Q.length);return ct?`~${ct}`:"~"}function wp(O,D){return O===D||O.startsWith(`${D}/`)}function zw(O,D,B,X){let{home:Q,normalized:he}=lc(O,B,X);if(!he||!Q)return"";let je=cc(he,Q),at=p_.normalize(Os(je)?je:Dn(Ds(D,je))),lt=Dn(mn(B.env.get("HOME")??B.home)),ct=(ut)=>process.platform==="win32"?ut.toLowerCase():ut,ft=[Q,lt].find((ut)=>ut!==""&&Or(ct(at),ct(ut)));if(ft===void 0)return"";let dt=at.slice(ft.length);return dt?`~${dt}`:"~"}function ei(O,D,B,X){let{home:Q,normalized:he}=lc(O,B,X);if(!he)return"";let je=Q?cc(he,Q):he;return Dn(Lt(Os(je)?je:Ds(D,je),B.paths,X))}function lc(O,D,B){let X=D.env.get("HOME")??D.home,Q=X?Dn(Lt(mn(X),D.paths,B)):"",he=Dn(mn(Bw(Hn(O,D))));return{home:Q,normalized:he}}function Bw(O){if(!O.trim().toLowerCase().startsWith("file:"))return O;try{return h_(O)}catch{return O}}function cc(O,D){if(O==="~")return D;if(O.startsWith("~/"))return tn(D,O.slice(2));return O}function $w(O){if(process.platform==="win32")return!0;return g_.parse(O).root.length>1}function Dn(O){let D=O.trim(),B=(D.includes("\\")&&$w(D)?D.replace(/\\/g,"/"):D).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(B==="/")return B;return B.replace(/\/+$/g,"")}function Or(O,D){return O===D||O.startsWith(D.endsWith("/")?D:`${D}/`)}function Xn(O){return O.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??O}class p extends Error{stage;evaluation;name="GuardEvaluationError";constructor(O,D,B){super(`CC Safety Net ${O} dependency failed`,{cause:B});this.stage=O;this.evaluation=D}}var Uw={findPolicyMutation:hp,findGitMetadataMutation:ef,resolveGitMetadata:Hw,loadPolicySnapshot:L,findSensitiveTarget:kp,analyzeCommand:cp,getModes:E};function U(O,D){let B={...Uw,...D.dependencies},X=Kw(O),Q=ti(O)?O.command:X,he=ur("policy-protection",Q,()=>Lo(O)),je=cn(he,"input-candidate"),at=cn(he,"declared-command");if(ti(O)&&O.command?.trim()&&at?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Nn,intent:"stop_and_explain",evidence:{command:O.command,segment:O.command}}};if(je?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:vf,intent:"stop_and_explain"}};let lt=fn(),ct=ur("policy-protection",Q,()=>B.resolveGitMetadata([O.context.executionCwd,O.context.configCwd],D.environment)),ft=ur("policy-protection",Q,()=>B.findPolicyMutation(he,D.environment,lt));if(ft){let Et=Q??ft.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Fe,intent:"hard_stop",evidence:{command:Et,segment:ft.target}}}}let dt=ur("policy-protection",Q,()=>fp(he,D.environment,lt));if(dt){let Et=Q??dt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:$e,intent:"hard_stop",evidence:{command:Et,segment:dt.target}}}}let ut=ur("policy-protection",Q,()=>B.findGitMetadataMutation(he,ct,D.environment,lt));if(ut){let Et=Q??ut.target;return{stage:"policy-protection",decision:{kind:"deny",reason:b,intent:"hard_stop",evidence:{command:Et,segment:ut.target}}}}let mt=ur("config-load",Q,()=>B.loadPolicySnapshot(D.environment,{...D.policyOptions,cwd:O.context.configCwd})),pt=mt.policy,ht=B.getModes(pt,D.environment.env),gt={level:ht.effectiveLevel,...jw(mt)},yt=pt.secretProtection.enabled===!1?null:ur("secret-protection",Q,()=>B.findSensitiveTarget(he,pt.secretProtection,D.environment,lt,{strict:ti(O)||je?.program.dialect==="powershell"?ht.strict:void 0}));if(yt){let Et=Q??yt.target;return{stage:"secret-protection",...gt,decision:{kind:"deny",reason:Pp,intent:"hard_stop",ruleId:yt.ruleId,evidence:{command:Et,segment:yt.target}}}}if(!ti(O))return{stage:"non-command",...gt,decision:{kind:"allow"}};if(!O.command||O.command.trim()==="")return{...uc("command-validation",Q),...gt};let vt=ur("command-analysis",Q,()=>up(()=>B.analyzeCommand(O.command,{cwd:O.context.executionCwd,shell:O.route.shell,policySnapshot:mt,environment:D.environment,protectedGitMetadata:ct,effectiveCapabilities:ht.capabilities,strict:ht.strict,paranoidRm:ht.paranoidRm,paranoidInterpreters:ht.paranoidInterpreters,worktreeMode:ht.worktreeMode,budget:lt,...D.trace?{trace:D.trace}:{}},Vw(he),he.store),O.command,D.trace));if(vt.decision)return{stage:"command-analysis",...gt,..."errorCode"in vt?{errorCode:vt.errorCode}:{},decision:vt.decision};return{stage:"command-analysis",...gt,decision:{kind:"allow"}}}function Hw(O,D){let B=[...new Set(O.filter((X)=>typeof X==="string"&&X!==""))].flatMap((X)=>D.gitMetadata(X)??[]);if(B.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(B.flatMap((X)=>X.entries))]),markerFiles:Object.freeze([...new Set(B.flatMap((X)=>X.markerFiles))]),directories:Object.freeze([...new Set(B.flatMap((X)=>X.directories))]),hooksDirectories:Object.freeze([...new Set(B.flatMap((X)=>X.hooksDirectories))])})}function jw(O){if(O.state==="ready")return{};return{configFallback:{reason:O.reason}}}function Vw(O){return cn(O,"declared-command")?.program}function Kw(O){try{return te(O.input)}catch(D){let B=ti(O)?O.command:void 0;throw new p("policy-protection",uc("policy-protection",D instanceof f?void 0:B,D),D)}}function ur(O,D,B){try{return B()}catch(X){throw new p(O,uc(O,X instanceof f?void 0:D,X),X)}}function uc(O,D,B){let X=B instanceof s||B instanceof y;return{stage:O,decision:{kind:"deny",reason:X?zs:ee,intent:"stop_and_explain",...D?{evidence:{command:D,segment:D}}:{}}}}function ti(O){return O.route.kind==="command"}
45
- export{ee,a,s,z,ke,Ge,k,Ze,He,ye,A,ve,Xe,l,o,We,be,E,R,we,Qe,f,ae,te,le,et,Ue,u,Ee,r,w,i,ne,n,g,ce,N,tt,nt,c,de,ue,rt,T,V,re,C,ot,M,v,Ce,F,d,q,Be,ze,I,S,P,pe,fe,Re,it,m,e,Pe,Se,Ve,qe,oe,xe,ie,_e,K,j,Ae,me,G,Ke,H,Y,J,se,Ye,Je,x,W,Te,Ie,De,Oe,L,Ne,Le,Me,h,t,Z,ge,y,b,_,st,$e,Fe,p,U};