cc-safety-net 2.4.6 → 2.4.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/amp/cc-safety-net/index.ts +37 -37
- package/dist/api.js +1 -1
- package/dist/bin/hook.js +35 -35
- package/dist/chunks/index-fvtsm6ez.js +45 -0
- package/dist/chunks/{index-q7q195qc.js → index-rr4ytenf.js} +1 -1
- package/dist/chunks/{index-4jcxaxr5.js → index-tfdjszbb.js} +2 -2
- package/dist/cli.js +4 -4
- package/dist/index.js +1 -1
- package/dist/openclaw/cc-safety-net/index.js +37 -37
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunks/index-c989ehp9.js +0 -45
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
var Ks="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Wn="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",te="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var Vs={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."},lo={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,...Vs},processedCandidateBytes:{cap:4194304,...Vs},pathEnvironmentExpansion:{cap:64,...Vs},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,...lo},trackedHeredocFiles:{cap:64,...lo},controlFlowStates:{cap:64,...lo},wrapperPeelIterations:{cap:20,...lo},derivedCommandShape:lo});class s extends Error{kind;name="AnalysisLimit";constructor(O){super(a[O].reason);this.kind=O}}function mn(){let O=new Map;return{counters:O,resolvedPaths:new Map,charge(D,B=1){let Q=(O.get(D)??0)+B;if(O.set(D,Q),Q>a[D].cap)throw new s(D)}}}import{lstatSync as Bg,realpathSync as $g,statSync as Ug}from"node:fs";import{homedir as Hg,tmpdir as jg}from"node:os";import{statSync as Gg}from"node:fs";import{join as Fg}from"node:path";import{basename as kc,dirname as sg,isAbsolute as ag,join as lg,normalize as cg,resolve as Tc}from"node:path";var ug=256,ai=new Set(["CC_SAFETY_NET_HOME","CLAUDE_CONFIG_DIR","CODEX_HOME","COPILOT_HOME","GEMINI_CLI_HOME","GROK_HOME","HOME","KIMI_CODE_HOME","KIMI_SHARE_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","ProgramData","TMPDIR","XDG_CONFIG_HOME","XDG_DATA_HOME"]);function pn(O,D=process.platform){if(D!=="win32")return O;return O.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function Qn(O,D=process.platform){if(D!=="win32")return!1;return(O[0]==="/"||O[0]==="\\")&&(O[1]==="/"||O[1]==="\\")}function Xs(O,D){return qs(O,0,D)}function qs(O,D,B){let Q="",ee=0;while(ee<O.length){if(O[ee]!=="$"){Q+=O[ee],ee++;continue}if(O[ee+1]==="{"){let je=Ys(O,ee+2),at=dg(O,ee,D);if(at===null){if(ai.has(je))throw new s("pathEnvironmentExpansion");Q+=O.slice(ee);break}let lt=O.slice(ee,at+1);Q+=fg(lt,D,B),ee=at+1;continue}let he=Ys(O,ee+1);if(!he){Q+="$",ee++;continue}Q+=Zs(he,B)??`$${he}`,ee+=he.length+1}return Q}function dg(O,D,B){let Q=1;for(let ee=D+2;ee<O.length;ee++){if(O[ee]==="\\"){ee++;continue}if(O[ee]==="$"&&O[ee+1]==="{"){if(Q++,B+Q>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");ee++;continue}if(O[ee]!=="}")continue;if(Q--,Q===0)return ee}return null}function fg(O,D,B){let Q=O.slice(2,-1),ee=Ys(Q,0);if(!ee)return O;let he=Q.slice(ee.length);if(!he)return Zs(ee,B)??O;let je=[":-",":+",":=",":?","-","+","=","?"].find((ct)=>he.startsWith(ct));if(!je){if(ai.has(ee))throw new s("pathEnvironmentExpansion");return O}if(!ai.has(ee))return O;if(je.endsWith("="))throw new s("pathEnvironmentExpansion");let at=Zs(ee,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??"":qs(he.slice(je.length),D+1,B);return lt?qs(he.slice(je.length),D+1,B):""}function Ys(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 Zs(O,D){if(!ai.has(O))return null;if(O==="HOME")return D.env.get("HOME")??D.home;return D.env.get(O)??null}function Wt(O,D,B){if(!O)return O;let Q=B.resolvedPaths.get(O);if(Q!==void 0)return Q;let ee=[],he=O;while(!0){Oc(B,he);let je=D.realpath(he);if(je!==null)return Ic(B,O,je,ee);let at=sg(he);if(at===he||ee.length>=ug)return Ic(B,O,he,ee);ee.push(kc(he)),he=at}}function Ic(O,D,B,Q){let ee=Q.length===0?B:lg(B,...Q.reverse());return O.resolvedPaths.set(D,ee),ee}function mg(O,D,B){let Q=B.resolvedPaths.get(O);if(Q!==void 0)return Q;Oc(B,O);let ee=D.realpath(O);if(ee!==null)B.resolvedPaths.set(O,ee);return ee}function Oc(O,D){O.charge("realpathAttempts"),O.charge("processedCandidateBytes",Buffer.byteLength(D))}function tn(O,D,B,Q){let ee=Dc(O,D,B);if(!ee)return"";return Wt(ee,B.paths,Q).replace(/\\/g,"/")}function Mc(O,D,B,Q,ee){let he=Dc(O,D,B);if(!he)return null;if(ee(kc(he)))return Wt(he,B.paths,Q).replace(/\\/g,"/");let je=mg(he,B.paths,Q);return je===null?null:je.replace(/\\/g,"/")}function Dc(O,D,B){let Q=B.home,ee=Xs(O.trim(),B).replace(/\\/g,"/");if(!ee)return"";let he=ee==="~"?Q:ee.startsWith("~/")?Tc(Q,ee.slice(2)):ee,je=pn(he);return cg(ag(je)?je:Tc(D,je))}import{spawnSync as pg}from"node:child_process";import{existsSync as uo,lstatSync as gg,readFileSync as fo,realpathSync as Nr,statSync as co}from"node:fs";import{dirname as Js,isAbsolute as Qs,join as Lr,resolve as li}from"node:path";var hg=["/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"],yg=5000;function Lc(O,D=Dg(),B=yg){let Q=bg(O),ee=Q===null?null:Sg(Q);if(Q===null||ee===null)return null;let he=Og(Q,ee,D,B);return he===null?null:{recursiveSubmodules:he}}function bg(O){try{let D=Nr(li(O));return co(D).isDirectory()?D:null}catch{return null}}function Sg(O){let D=kg(O);if(!D)return null;try{let B=gg(D);if(B.isSymbolicLink()||!B.isFile())return null;let Q=ea(D);if(!Q?.commonDir)return null;if(!Eg(Q.gitDir,D))return null;return xg(Q.gitDir,Js(D))?{gitDir:Q.gitDir,commonDir:Q.commonDir}:null}catch{return null}}function ea(O){try{let D=Cg(O);if(!D)return null;let B=Nr(Qs(D)?D:li(Js(O),D));if(!co(B).isDirectory())return null;return{gitDir:B,commonDir:vg(B)}}catch{return null}}function Cg(O){let D=fo(O,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!D.startsWith("gitdir:"))return null;return D.slice(7).trim()||null}function vg(O){try{let D=fo(Lr(O,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!D)return null;let B=Nr(Qs(D)?D:li(O,D));return co(B).isDirectory()?B:null}catch{return null}}function Eg(O,D){let B=Rg(O);return B===null?!1:Wc(O,B,D)}function xg(O,D){let B=_g(O);return B===null?!0:Wc(O,B,D)}function Rg(O){let D=Lr(O,"gitdir");if(!uo(D))return null;let B=fo(D,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return B===""?null:B}function _g(O){let D=Lr(O,"config.worktree");return uo(D)?Pg(D):null}function Wc(O,D,B){try{return wg(Qs(D)?D:li(O,D),B)}catch{return!1}}function wg(O,D){try{let B=co(O),Q=co(D);if(B.ino!==0&&Q.ino!==0&&B.dev===Q.dev&&B.ino===Q.ino)return!0}catch{}return Nc(Nr.native(O))===Nc(Nr.native(D))}function Nc(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 Pg(O){let D=fo(O,"utf-8"),B=!1,Q=null;for(let ee of D.split(/\r?\n/)){let he=ee.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)Q=Ag(je[1]??"")}return Q}function Ag(O){let D=O.trim();if(!D.startsWith('"')||!D.endsWith('"'))return D;return Ig(D.slice(1,-1))}var Tg={"\\":"\\",'"':'"',n:`
|
|
2
|
+
`,t:"\t",b:"\b"};function Ig(O){return O.replace(/\\(.?)/gs,(D,B)=>B===""?D:Tg[B]??D)}function kg(O){try{return ta(Nr(O))}catch{return null}}function ta(O){let D=O;while(!0){let B=Lr(D,".git");if(uo(B))return B;let Q=Js(D);if(Q===D)return null;D=Q}}function Og(O,D,B,Q){if(Mg(D))return!0;if(B===null)return!0;let ee=pg(B,["config","--get","submodule.recurse"],{cwd:O,encoding:"utf8",env:Ng(process.env),stdio:["ignore","pipe","ignore"],timeout:Q});if(ee.error!==void 0||ee.status!==0&&ee.status!==1)return null;return ee.status===0&&Gc(ee.stdout.trim())}function Mg(O){return[Lr(O.commonDir,"config"),Lr(O.gitDir,"config.worktree")].filter((D)=>uo(D)).some((D)=>Lg(D))}function Dg(){return hg.find((O)=>uo(O))??null}function mo(O){return O==="GIT_CONFIG_COUNT"||O==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(O)}function Ng(O){return Object.fromEntries(Object.entries(O).filter(([D])=>!mo(D)))}function Lg(O){let D;try{D=fo(O,"utf-8")}catch{return!0}let B="",Q=!1;for(let ee of D.split(/\r?\n/)){let he=ee.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(Wg(B)&<==="path")return!0;if(B==="submodule"&<==="recurse")Q=Gc(ct)}return Q}function Wg(O){return O==="include"||O.startsWith("includeif ")}function Gc(O){let D=O.toLowerCase();return D!=="false"&&D!=="no"&&D!=="off"&&D!=="0"}function Fc(O,D){if(O==="")return null;let B=mn(),Q=ta(tn(O,O,D,B)),ee=Q?zg(Q,O,D,B):null;if(!ee)return null;return Object.freeze({entries:Object.freeze([ee.entry]),markerFiles:Object.freeze(ee.markerFile?[ee.markerFile]:[]),directories:Object.freeze(ee.directories),hooksDirectories:Object.freeze(ee.hooksDirectories)})}function zg(O,D,B,Q){try{let ee=tn(O,D,B,Q),he=Gg(O),je=he.isFile()?ee:null,at=he.isFile()?ea(O):null,lt=(he.isDirectory()?[ee]:[at?.gitDir,at?.commonDir]).flatMap((ut)=>ut?[Wr(tn(ut,D,B,Q))]:[]),ct=[...new Set(he.isDirectory()?[Wr(O.replace(/\\/g,"/")),...lt]:lt)];return{entry:Wr(ee),markerFile:je?Wr(je):null,directories:ct,hooksDirectories:[...new Set(ct.flatMap((ut)=>{let ft=Wr(Fg(ut,"hooks").replace(/\\/g,"/"));return[ft,Wr(tn(ft,D,B,Q))]}))]}}catch{return null}}function Wr(O){return process.platform==="win32"?O.toLowerCase():O}var Vg={realpath:(O)=>{try{return $g(O)}catch{return null}},entryKind:(O)=>{let D=Bg(O,{throwIfNoEntry:!1});if(!D)return"missing";return D.isSymbolicLink()?"symlink":"present"},isDirectory:(O)=>{try{return Ug(O).isDirectory()}catch{return!1}}};function c(){return Kg({env:new Map(Object.entries(process.env).flatMap(([O,D])=>D===void 0?[]:[[O,D]])),home:pn(process.env.HOME||Hg()),tmpdir:jg(),paths:Vg})}function Kg(O,D={}){let B=new Map,Q=new Map,ee={...O,gitMetadata:(he)=>zc(B,he,()=>Fc(he,ee)),worktreeFacts:(he)=>zc(Q,he,()=>Lc(he)),...D};return ee}function zc(O,D,B){let Q=O.get(D);if(Q!==void 0)return Q;let ee=B();return O.set(D,ee),ee}import{accessSync as vh,constants as ru,statSync as Eh}from"node:fs";import{isAbsolute as iu,relative as xh,resolve as Rh,sep as _h}from"node:path";var qg=[/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bglpat-[A-Za-z0-9_-]{20,}\b/g,/\bxox[abeprs]-[A-Za-z0-9-]{20,}\b/g,/\bnpm_[A-Za-z0-9_]{20,}\b/g,/\bpypi-[A-Za-z0-9_-]{20,}\b/g,/\b[rs]k_(?:live|test)_[A-Za-z0-9_]{20,}\b/g,/\bsk-[A-Za-z0-9_-]{20,}\b/g,/\bsk_[A-Za-z0-9]{20,}\b/g,/\bgsk_[A-Za-z0-9]{52,}\b/g,/\bxai-[A-Za-z0-9_-]{80,}\b/g,/\bpplx-[A-Za-z0-9_-]{20,}\b/g,/\bbastn_[A-Za-z0-9]{16,}\b/g,/\btgp_v1_[A-Za-z0-9_-]{43,}\b/g,/\bflp_[A-Za-z0-9]{10,}\b/g,/\bwfr_[A-Za-z0-9]{20,}\b/g,/\bfwp?_[A-Za-z0-9_-]{20,}\b/g,/\btp-[A-Za-z0-9_-]{20,}\b/g,/\bpsk-[A-Za-z0-9_-]{8,}-[A-Za-z0-9_-]{8,}\b/g,/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/g];function 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 qg.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 Ue(O){return Bc(O).reduceRight((D,B)=>`${D.slice(0,B.valueStart)}<redacted>${D.slice(B.valueEnd)}`,O)}function k(O){return ke(Ue(O))}function Ze(O){return Bc(O).map((D)=>O.slice(D.valueStart,D.valueEnd))}function Ge(O){return/[A-Za-z_][A-Za-z0-9_]*=/.test(O)}function Bc(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 Q=D.index+D[0].length;if(Q>=O.length)return[];return[{valueStart:Q,valueEnd:Yg(O,Q)}]})}function Yg(O,D){if(O.startsWith("$(",D))return Zg(O,D);let B=O[D];if(B==='"'||B==="'"){for(let ee=D+1;ee<O.length;ee++){if(B==='"'&&O[ee]==="\\"){ee++;continue}if(O[ee]===B)return ee+1}return O.length}let Q=D;while(Q<O.length&&!/\s/.test(O[Q]??""))Q++;return Q}function Zg(O,D){let B=0,Q;for(let ee=D;ee<O.length;ee++){let he=O[ee];if(Q){if(Q==='"'&&he==="\\"){ee++;continue}if(he===Q)Q=void 0;continue}if(he==='"'||he==="'"){Q=he;continue}if(he==="$"&&O[ee+1]==="("){B++,ee++;continue}if(he!==")")continue;if(B--,B===0)return ee+1}return O.length}var Xg={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 Jg(O){let D=O.maxLen??200,B=O.redact??((ee)=>ee),Q=(ee)=>ee.length>D?`${ee.slice(0,D)}...`:ee;return[O.askUser?"CC Safety Net could not verify this command":"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: ${Q(B(O.command))}`:void 0,O.segment&&O.segment!==O.command?`Segment: ${Q(B(O.segment))}`:void 0,O.configWarning?`Config warning: ${B(O.configWarning)}`:void 0,O.askUser?"Approve only if you expected this command.":Xg[O.intent??"manual_only"]].filter((ee)=>ee!==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}:{},...O.decision.ask?{ask:!0}:{}}}function P(O={}){return{reason:te,intent:"stop_and_explain",command:O.command,segment:O.segment??O.command,toolName:O.toolName}}function be(O){return Jg({...O,redact:z})}function Xe(O){return z(O instanceof Error?O.message:String(O))}import{types as Qg}from"node:util";var eh=new Set(["applypatch","patch"]),th=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),nh=new Set(["grep","grepsearch","rg"]),rh=new Set(["find","findbyname","glob"]),oh=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),ih=new Set(["command","diff","input","patch","patchtext"]),$c=new TextEncoder,sh=new TextDecoder,ah=/\s/,lh=64;class f extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var po=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Kc(O){return O.replace(/[-_\s]/g,"").toLowerCase()}function ui(O){return oh.has(Kc(O))}function V(O){let D=Kc(O);if(eh.has(D))return"patch";if(nh.has(D))return"grep";if(rh.has(D))return"glob";if(th.has(D))return"path";return"unknown"}function ne(O){if(!O||typeof O!=="object")return;eu(O);let D=Object.getOwnPropertyDescriptor(O,"command");if(!D){if("command"in O)Gn();return}if(D.get||D.set)Gn();let B=D.value;return typeof B==="string"&&B!==""?B:void 0}function qc(O,D){return Yc(O,D,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Yc(O,D,B,Q){let ee=Qc(O,B,Q);if(!ee)return[];let he=ee.entries.flatMap(([je,at])=>{let lt=Yc(at,D,B,Q+1);return typeof at==="string"&&D.has(Zc(je))?[at]:lt});return B.ancestors.delete(ee.object),he}function Zc(O){return O.replace(/-/g,"_").toLowerCase()}function Xc(O){return Jc(O,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(uh)}function Jc(O,D,B,Q){let ee=Qc(O,B,Q);if(typeof O==="string")return D?[O]:[];if(!ee)return[];let he=ee.entries.flatMap(([je,at])=>Jc(at,ee.array?D:ih.has(Zc(je)),B,Q+1));return B.ancestors.delete(ee.object),he}function ch(O,D,B){if(D.nodes++,O!==null&&typeof O==="object"&&B>po.maxDepth||D.nodes>po.maxNodes)Gn();if(typeof O!=="string")return;let Q=Buffer.byteLength(O);if(D.stringBytes+=Q,Q>po.maxStringBytes||D.stringBytes>po.maxAggregateStringBytes)Gn()}function Qc(O,D,B){if(ch(O,D,B),!O||typeof O!=="object")return null;let Q=eu(O);if(D.ancestors.has(O))Gn();let ee=Reflect.ownKeys(O);if(D.keys+=ee.length,D.keys>po.maxKeys)Gn();let he=ee.flatMap((je)=>{let at=Object.getOwnPropertyDescriptor(O,je);if(!at||at.get||at.set)Gn();return typeof je==="string"&&at.enumerable?[[je,at.value]]:[]});return D.ancestors.add(O),{object:O,array:Q,entries:he}}function eu(O){if(Qg.isProxy(O))Gn();let D=Array.isArray(O),B=Object.getPrototypeOf(O);if(D&&B!==Array.prototype||!D&&B!==Object.prototype&&B!==null)Gn();return D}function Gn(){throw new f}function uh(O){let D=[],B=O.split(/\r?\n/),Q=!1,ee=!1,he=null,je=null,at=()=>{ee=!1,he=null,je=null};for(let lt=0;lt<B.length;lt++){let ct=B[lt]??"";if(ct==="*** Begin Patch"){Q=!0,at();continue}if(ct==="*** End Patch"){Q=!1,at();continue}if(ct.startsWith("@@")){let ut=dh(ct);if(ee=!0,he=ut?.oldLines??null,je=ut?.newLines??null,he===0&&je===0)at();continue}if(ee&&he!==null&&je!==null){let ut=ct.startsWith(" ")||ct.startsWith("-")?1:0,ft=ct.startsWith(" ")||ct.startsWith("+")?1:0;if(he=Math.max(0,he-ut),je=Math.max(0,je-ft),he===0&&je===0)at();continue}if(ct.startsWith("*** ")){at(),D.push(...na(ct));continue}if(ee)continue;if(ct.startsWith("diff --git ")){D.push(...na(ct));continue}if(ct.startsWith("--- ")){let ut=B[lt+1]??"";if(!ut.startsWith("+++ "))continue;D.push(...oa(ci(ct.slice(4),!0),ci(ut.slice(4),!0))),lt++;continue}if(!Q)D.push(...na(ct))}return D}function dh(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 na(O){let D=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(O);if(D?.[1])return Vc(D[1]);let B=/^\*\*\* Move to: (.+)$/.exec(O);if(B?.[1])return Vc(B[1]);if(O.startsWith("diff --git "))return fh(O.slice(11));let Q=/^--- (.+)$/.exec(O);if(Q?.[1])return jc(Q[1]);let ee=/^\+\+\+ (.+)$/.exec(O);if(ee?.[1])return jc(ee[1]);let he=/^(?:rename|copy) (?:from|to) (.+)$/.exec(O);if(he?.[1])return Sh(he[1]);return[]}function fh(O){let D=mh(O);if(D.length===2&&D[0]&&D[1])return oa(D[0],D[1]);let B=ph(O);return B?oa(O.slice(B.oldStart,B.oldEnd),O.slice(B.newStart,B.newEnd)):[]}function mh(O){let D=[],B=0;while(B<O.length&&D.length<2){while(dr(O[B]))B++;if(B>=O.length)break;let Q=O[B]==='"'||O[B]==="'"?O[B]:void 0;if(!Q){let he=B;while(B<O.length&&!dr(O[B]))B++;D.push(O.slice(he,B));continue}let ee=tu(O,B,Q);if(!ee)return[];D.push(ee.value),B=ee.end}while(dr(O[B]))B++;return B===O.length?D:[]}function ph(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 Q=0,ee=D;while(ee<B){if(!dr(O[ee])){ee++;continue}let he=ee;while(ee<B&&dr(O[ee]))ee++;if(he===D||ee===B)continue;if(Q++,Q>lh)Gn();if(gh(O,D,he,ee,B))return{oldStart:D,oldEnd:he,newStart:ee,newEnd:B}}return null}function gh(O,D,B,Q,ee){if(ra(O,D,B,Q,ee))return!0;let he=Uc(O,"/",D,B),je=Uc(O,"/",Q,ee);if(he<=D||je<=Q)return!1;if(ra(O,D,he,Q,je))return!1;return ra(O,he+1,B,je+1,ee)}function ra(O,D,B,Q,ee){if(B-D!==ee-Q)return!1;for(let he=0;he<B-D;he++)if(O[D+he]!==O[Q+he])return!1;return!0}function Uc(O,D,B,Q){for(let ee=B;ee<Q;ee++)if(O[ee]===D)return ee;return-1}function dr(O){return O!==void 0&&ah.test(O)}function tu(O,D,B){let Q=[],ee=D+1;while(ee<O.length){let he=String.fromCodePoint(O.codePointAt(ee)??0);if(he===B)return{value:sh.decode(Uint8Array.from(Q)),end:ee+1};if(he!=="\\"||B==="'"){Q.push(...$c.encode(he)),ee+=he.length;continue}let je=O.slice(ee+1),at=/^[0-7]{1,3}/.exec(je)?.[0];if(at){Q.push(Number.parseInt(at,8)),ee+=at.length+1;continue}Q.push(...$c.encode(hh(je[0]??""))),ee+=2}return null}function hh(O){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
5
|
+
`,r:"\r",t:"\t",v:"\v"}[O]??O}function yh(O){return go(Ch(O))}function oa(O,D){if(O==="/dev/null")return Hc(D);if(D==="/dev/null")return Hc(O);if(O.startsWith("a/")&&D.startsWith("b/"))return[O.slice(2),D.slice(2)].flatMap(go);let B=bh(O,D)??(O===D?nu(O):null);return[O,D,...B?[B]:[]].flatMap(go)}function Hc(O){let D=nu(O);return[O,...D?[D]:[]].flatMap(go)}function nu(O){let D=O.indexOf("/");return D>0&&D<O.length-1?O.slice(D+1):null}function bh(O,D){let B=O.indexOf("/"),Q=D.indexOf("/");if(B<1||Q<1)return null;if(O.slice(0,B)===D.slice(0,Q))return null;let ee=O.slice(B+1);return ee===D.slice(Q+1)?ee:null}function jc(O){return yh(ci(O,!0))}function Sh(O){return go(ci(O,!1))}function ci(O,D){let B=O.trim(),Q=B[0]==='"'||B[0]==="'"?B[0]:void 0;if(Q){let ee=tu(B,0,Q);if(ee&&(D||B.slice(ee.end).trim()===""))return ee.value}return D?B.split("\t",1)[0]?.trim()??"":B}function Ch(O){return O.startsWith("a/")||O.startsWith("b/")?O.slice(2):O}function go(O){return O===""||O==="/dev/null"?[]:[O]}function Vc(O){let D=O.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return D===""||D==="/dev/null"?[]:[D]}function ce(O){try{if(!Eh(O).isDirectory())return!1;return vh(O,ru.R_OK|ru.X_OK),!0}catch{return!1}}function et(O,D,B){if(Qn(O))return;let Q=D.flatMap((he)=>ou(he,B));if(!Q[0])return;let ee=ou(iu(O)?O:Rh(Q[0],O),B)[0];if(!ee)return;return Q.some((he)=>wh(ee,he))?ee:void 0}function ou(O,D){let B=D.realpath(O);if(B===null)return[];return D.isDirectory(B)?[B]:[]}function wh(O,D){let B=xh(D,O);return B===""||B!==".."&&!B.startsWith(`..${_h}`)&&!iu(B)}var Ph=8388608;async function We(O){let D=[],B=0;for await(let Q of O){let ee=typeof Q==="string"?Buffer.from(Q,"utf-8"):Buffer.from(Q.buffer,Q.byteOffset,Q.byteLength);if(B+=ee.byteLength,B>Ph)throw Ah(O),Error("hook input byte limit exceeded");D.push(ee)}return Buffer.concat(D,B).toString("utf-8")}function Ah(O){let D=O.destroy??O.cancel;if(!D)return;try{Promise.resolve(D.call(O)).catch(()=>{})}catch{}}function d(O,D,B,Q,ee){if(B.kind!=="command")return{toolName:O,input:D,route:B,context:Q};return{toolName:O,input:D,route:B,context:Q,command:ee}}var Gr=["fail_closed","paranoid_rm","paranoid_interpreters"],di={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"}},fi=["standard","strict","paranoid"];function Th(O,D){if(!D)return O;return fi.indexOf(D)>fi.indexOf(O)?D:O}function Ih(O){let D=ve(o.level,O);if(D===void 0||D==="")return;if(fi.includes(D))return D;console.error(`CC Safety Net: ignored invalid ${o.level.name}=${JSON.stringify(D.slice(0,40))}. Use ${fi.join(", ")}.`);return}function He(O){if(O===void 0||O==="all")return"all";if(O==="blocked")return"blocked";return"invalid"}function xe(O){return He(ve(o.auditScope,O))==="all"}function ia(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 R(O={},D){let B=O.safety?.level??"standard",Q=Ih(D),ee=Th(B,Q),he=di[ee],je={failClosed:he.fail_closed,paranoidRm:he.paranoid_rm,paranoidInterpreters:he.paranoid_interpreters},at={failClosed:ee===B?"preset":"environment",paranoidRm:ee===B?"preset":"environment",paranoidInterpreters:ee===B?"preset":"environment"},lt={failClosed:[`policy safety.level=${B}`],paranoidRm:[`policy safety.level=${B}`],paranoidInterpreters:[`policy safety.level=${B}`]};if(ee!==B)lt.failClosed.push(`env ${o.level.name}=${Q}`),lt.paranoidRm.push(`env ${o.level.name}=${Q}`),lt.paranoidInterpreters.push(`env ${o.level.name}=${Q}`);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(L(o.strict,D))je.failClosed=!0,at.failClosed="environment",lt.failClosed.push(`env ${o.strict.name}`);if(L(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(L(o.paranoidRm,D))je.paranoidRm=!0,at.paranoidRm="environment",lt.paranoidRm.push(`env ${o.paranoidRm.name}`);if(L(o.paranoidInterpreters,D))je.paranoidInterpreters=!0,at.paranoidInterpreters="environment",lt.paranoidInterpreters.push(`env ${o.paranoidInterpreters.name}`);let ct=!!O.worktreeMode||L(o.worktree,D);return{strict:je.failClosed,paranoidRm:je.paranoidRm,paranoidInterpreters:je.paranoidInterpreters,worktreeMode:ct,effectiveLevel:ia(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 L(O,D){let B=typeof O==="string"?ho(O,D):ve(O,D);return B==="1"||B?.toLowerCase()==="true"}function ho(O,D){return D.get(O)}function ve(O,D){let B=ho(O.name,D);if(B!==void 0)return B;if(O.legacyName)return ho(O.legacyName,D);return}function Qe(O,D){return ho(O.name,D)!==void 0||!!O.legacyName&&ho(O.legacyName,D)!==void 0}import{dirname as hr}from"node:path";import{closeSync as kh,constants as yo,fstatSync as sa,fsyncSync as Oh,lstatSync as vn,mkdirSync as su,openSync as au,readdirSync as la,readFileSync as Mh,realpathSync as Fr,renameSync as Dh,rmdirSync as lu,statSync as aa,unlinkSync as ca,writeFileSync as Nh}from"node:fs";import{isAbsolute as cu,join as fr,normalize as Lh,parse as mi,relative as ua,resolve as da,sep as pi}from"node:path";function Re(){let O=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${O()}${O()}`}var Wh=Symbol("PolicyFilesystemScope"),Gh=Symbol("PolicyFilesystemTarget"),uu=yo.O_NOFOLLOW??0;class r extends Error{name="PolicyFilesystemError";constructor(O){super(`Unable to access ${O} filesystem safely.`)}}function v(O,D){return{[Wh]:!0,root:da(O),label:D}}function bo(O,D){let B=Lh(D);if(D===""||cu(D)||B===".."||B.startsWith(`..${pi}`))throw new r(O.label);return{[Gh]:!0,scope:O,relativePath:B,path:fr(O.root,B)}}function i(O,D){return bo(O,ua(O.root,da(D)))}function re(O,D="rules policy"){let B=da(O),Q=mi(B).dir;return bo(v(Q,D),ua(Q,B))}function n(O){return $n(O.scope.label,()=>{if(!Zt(O))return null;let D=au(O.path,yo.O_RDONLY|uu);return fu(D,()=>{let B=sa(D);if(!B.isFile())throw new r(O.scope.label);let Q=Mh(D,"utf-8"),ee=vn(O.path);if(!ee.isFile()||ee.isSymbolicLink()||B.dev!==ee.dev||B.ino!==ee.ino)throw new r(O.scope.label);return Zt(O),Q})})}function g(O,D,B=384,Q){let ee=`${O.path}.${Re()}.tmp`;$n(O.scope.label,()=>{zh(O),Zt(O);let he=au(ee,yo.O_CREAT|yo.O_EXCL|yo.O_WRONLY|uu,B),je=fu(he,()=>{let at=sa(he);if(!at.isFile())throw new r(O.scope.label);Nh(he,D,"utf-8"),Oh(he);let lt=sa(he);if(!lt.isFile()||lt.dev!==at.dev||lt.ino!==at.ino)throw new r(O.scope.label);return lt});Zt(O),$h(O,ee,je.dev,je.ino),Dh(ee,O.path),Q?.(O.path),Zt(O)},()=>Uh(ee))}function du(O,D){if(O.path===D.path)return!0;return $n(O.scope.label,()=>{if(!Zt(O)||!Zt(D))return!1;let B=(Q)=>fr(Fr(mi(Q).dir),mi(Q).base);return B(O.path)===B(D.path)})}function le(O){let D=$n(O.scope.label,()=>{if(!Zt(O,"directory"))return null;let B=la(O.path);return Zt(O,"directory"),B});if(!D)return null;return $n(O.scope.label,()=>{let B=D.map((Q)=>{let ee=bo(O.scope,fr(O.relativePath,Q)),he=vn(ee.path);if(he.isSymbolicLink()||!he.isFile()&&!he.isDirectory())throw new r(O.scope.label);return gi(fa(O.scope),Fr(ee.path),O.scope.label),{name:Q,kind:he.isDirectory()?"directory":"file"}});return Zt(O,"directory"),B})}function N(O){$n(O.scope.label,()=>{if(!Zt(O))return;ca(O.path),Zt(O)})}function tt(O){$n(O.scope.label,()=>{if(!Fh(O))return;pu(O),Zt(O,"directory")})}function nt(O){$n(O.scope.label,()=>{if(!Zt(O,"directory"))return;lu(O.path),Zt(O,"directory")})}function Fh(O){return $n(O.scope.label,()=>{if(!Zt(O,"directory"))return!1;return mu(O),!0})}function $n(O,D,B){try{return D()}catch(Q){if(B?.(),Q instanceof r)throw Q;throw new r(O)}}function fu(O,D){try{return D()}finally{kh(O)}}function Zt(O,D="file"){let B=gu(O.scope);if(!B)return!1;let Q=O.relativePath.split(pi);for(let ee of Q.keys()){let he=fr(O.scope.root,...Q.slice(0,ee+1)),je=vn(he,{throwIfNoEntry:!1});if(!je)return!1;if(je.isSymbolicLink())throw new r(O.scope.label);if(ee<Q.length-1&&!je.isDirectory())throw new r(O.scope.label);if(ee===Q.length-1&&(D==="file"?!je.isFile():!je.isDirectory()))throw new r(O.scope.label);gi(B,Fr(he),O.scope.label)}return!0}function mu(O){for(let D of la(O.path)){let B=bo(O.scope,fr(O.relativePath,D)),Q=vn(B.path);if(Q.isSymbolicLink()||!Q.isDirectory()&&!Q.isFile())throw new r(O.scope.label);if(Q.isDirectory())mu(B)}Zt(O,"directory")}function pu(O){for(let D of la(O.path)){let B=bo(O.scope,fr(O.relativePath,D)),Q=vn(B.path);if(Q.isSymbolicLink())throw new r(O.scope.label);if(Q.isDirectory()){pu(B);continue}if(!Q.isFile())throw new r(O.scope.label);ca(B.path)}lu(O.path)}function zh(O){Bh(O.scope);let D=fa(O.scope),B=O.relativePath.split(pi).slice(0,-1);for(let Q of B.keys()){let ee=fr(O.scope.root,...B.slice(0,Q+1));if(!vn(ee,{throwIfNoEntry:!1}))su(ee,{mode:448});let he=vn(ee);if(!he.isDirectory()||he.isSymbolicLink())throw new r(O.scope.label);gi(D,Fr(ee),O.scope.label)}}function Bh(O){if(vn(O.root,{throwIfNoEntry:!1})){if(!aa(O.root).isDirectory())throw new r(O.label);return}let D=[],B=O.root;while(!vn(B,{throwIfNoEntry:!1})){D.unshift(B);let Q=mi(B).dir;if(Q===B)throw new r(O.label);B=Q}if(!aa(B).isDirectory())throw new r(O.label);for(let Q of D){su(Q,{mode:448});let ee=vn(Q);if(!ee.isDirectory()||ee.isSymbolicLink())throw new r(O.label)}}function gu(O){if(!vn(O.root,{throwIfNoEntry:!1}))return null;if(!aa(O.root).isDirectory())throw new r(O.label);return Fr(O.root)}function fa(O){let D=gu(O);if(!D)throw new r(O.label);return D}function $h(O,D,B,Q){let ee=vn(D);if(!ee.isFile()||ee.isSymbolicLink()||ee.dev!==B||ee.ino!==Q)throw new r(O.scope.label);gi(fa(O.scope),Fr(D),O.scope.label)}function gi(O,D,B){let Q=ua(O,D);if(Q===".."||Q.startsWith(`..${pi}`)||cu(Q))throw new r(B)}function Uh(O){try{ca(O)}catch{}}import{dirname as mr,isAbsolute as qh,join as gr,relative as Yh,resolve as pr,sep as Zh}from"node:path";var l=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ue="rulebook.json",de=".cc-safety-net/rules";var hu=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,Hh=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,yu=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,jh=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Vh="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),rt=new RegExp(`^${jh}/(${l.source.slice(1,-1)})/${Vh}$`);function Kh(O){return`.cc-safety-net/rules/${O}/rulebook.json`}function bu(O){if(S(O))try{return A(O),null}catch(D){return D instanceof Error?D.message:String(D)}return l.test(O)?null:`Local rulebook sources must be bare names matching ${l}: ${O}`}function A(O){if(O.startsWith("github:"))throw Error(`Invalid rulebook source: ${O}`);let D=O.match(hu);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 Q=D[3].slice(0,B),ee=D[3].slice(B+1);if(!Q||!yu.test(Q))throw Error(`GitHub rulebook refs must use valid path segments: ${O}`);if(!ee||!l.test(ee))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${O}`);return{owner:D[1],repo:D[2],ref:Q,path:Kh(ee),name:ee}}function q(O){return Hh.test(O)}function oe(O){return yu.test(O)}function S(O){return hu.test(O)}function ot(O){if(!l.test(O))throw Error(`Local rulebook sources must be bare names matching ${l}: ${O}`)}var Su="rule.json",hi="policy.json",Cu=".cc-safety-net",Xh="rules",Jh="CC_SAFETY_NET_HOME",vu="`cc-safety-net rule update`";function Qh(O){return pr(O,de)}function F(O){return gr(Qh(O),Su)}function b(O){return gr(pr(O),Cu,hi)}function Se(O,D={}){return D.userConfigDir??(D.userConfigPath?mr(D.userConfigPath):gr(ey(O),Xh))}function ey(O){let D=O.env.get(Jh);return D?pr(pn(D)):gr(O.home,Cu)}function M(O,D={}){return gr(Se(O,D),Su)}function u(O,D={}){return gr(mr(Se(O,D)),hi)}function K(O,D){let B=D.userConfigPath??M(O,D),Q=D.projectConfigPath??F(D.cwd),ee=Be(O,D),he=ze(Q,D.cwd);return{userConfigPath:B,projectConfigPath:Q,userScope:ee,projectScope:he,userConfigTarget:i(ee,B),projectConfigTarget:i(he,Q)}}function Be(O,D){let B=D.userConfigPath?mr(mr(pr(D.userConfigPath))):mr(pr(D.userConfigDir??Se(O,D)));return v(B,"user policy")}function ze(O,D){let B=pr(D),Q=pr(O),ee=Yh(B,Q);if(ee!==".."&&!ee.startsWith(`..${Zh}`)&&!qh(ee))return v(B,"project policy");return v(mr(mr(Q)),"project policy")}function I(O,D){return gr(O,D,ue)}var gn=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),w=/^[a-zA-Z][a-zA-Z0-9_-]*$/,T=256,Kt=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Eu=new Set(["python","python3","python2","node","ruby","perl"]),yi=/^python(?:[23](?:\.\d+)*)?$/,En=new Set(["awk","gawk","nawk","mawk"]),bi=new Set(["echo","printf","cat","head","tail","less","more","grep","rg","ag","ack","sed","awk","cut","tr","sort","uniq","wc","tee","man","help","info","type","which","whereis","whatis","apropos","file","stat","ls","ll","dir","tree","pwd","date","cal","uptime","whoami","id","groups","hostname","uname","env","printenv","set","export","alias","history","jobs","fg","bg","test","true","false","read","return","exit","break","continue","shift","wait","trap","basename","dirname","realpath","readlink","md5sum","sha256sum","base64","xxd","od","hexdump","strings","diff","cmp","comm","join","paste","column","fmt","fold","nl","pr","expand","unexpand","rev","tac","shuf","seq","yes","sleep","logger","write","wall","mesg","notify-send"]);var xu="Rulebook exceeds CC Safety Net's safe validation limits.",Ru="Additional rulebook validation errors were omitted.",Pn=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function _u(O){if(ma(O.allowed_commands,Pn.maxAllowedCommands)||ma(O.rules,Pn.maxRules)||ma(O.tests,Pn.maxTests))return!1;let{maxAggregateStringCodeUnits:D,maxTotalBlockArgs:B}=Pn,Q=(ee,he=!1)=>{if(typeof ee!=="string")return!0;if(ee.length>Pn.maxStringCodeUnits||he&&ee.length>Pn.maxFixtureCommandCodeUnits||ee.length>D)return!1;return D-=ee.length,!0};if(!Q(O.name)||!Q(O.version)||!Q(O.description)||!Q(O.author)||!Q(O.migrated_from))return!1;if(Array.isArray(O.allowed_commands)){for(let ee of O.allowed_commands)if(!Q(ee))return!1}if(Array.isArray(O.rules))for(let ee of O.rules){if(!ee||typeof ee!=="object")continue;let he=ee;if(!Q(he.name)||!Q(he.command)||!Q(he.subcommand)||!Q(he.reason)||!Q(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>Pn.maxBlockArgsPerRule||at.length>B)return!1;B-=at.length;for(let lt of at)if(!Q(lt))return!1}}if(Array.isArray(O.tests))for(let ee of O.tests){if(!ee||typeof ee!=="object")continue;let he=ee;if(!Q(he.command,!0)||!Q(he.expect)||!Q(he.rule))return!1}return!0}function ma(O,D){return Array.isArray(O)&&O.length>D}var pa=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 It(O){return Tt(O).toLowerCase()}function Tt(O){return O.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??O}function an(O,D){let B=new Set,Q=!1;for(let ee of O){if(ee==="--"){Q=!0;continue}if(Q)continue;if(ee.startsWith("-")&&!ee.startsWith("--")&&ee.length>1)for(let he=1;he<ee.length;he++){let je=ee[he];if(!je||!/[a-zA-Z]/.test(je))break;let at=`-${je}`;if(B.add(at),D?.shortOptsWithValue?.has(at))break}}return B}var ty={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},ga=new Set(["--init-file","--rcfile"]);function ha(O,D,B,Q){let ee=!1,he=0,je=!1,at=!1,lt=!1;for(let ct=1;ct<D.length;ct++){let ut=D[ct];if(ut===void 0)break;if(O==="ksh"&&ut==="o"&&ct+1<D.length){if(Q==="argv"){let ft=D.slice(ct+1);if(D[0]==="-"&&(ft==="c"||ft[0]==="-"&&ft.endsWith("c")))je=!0}break}if(O==="ksh"&&ut==="o"&&ct+1===D.length&&(B?.startsWith("-")||B?.startsWith("+")))break;if(O==="zsh"&&ut==="o"&&ct+1<D.length)break;if(Q==="startup"&&ut==="i")ee=D[0]==="-";if(Q==="argv"&&D[0]==="-"&&ut==="c")je=!0;if(Q==="argv"&&ut==="n")lt=D[0]==="-";if(Q==="argv"&&ut==="s")at=D[0]==="-";if(!ty[O]?.includes(ut))continue;if(ct+1===D.length)he++;break}return{interactive:ee,followingValues:he,commandSelected:je,stdinMode:at,syntaxCheck:lt}}function hn(O){let D=Tt(O[0]??"").toLowerCase(),B=!1,Q=!1,ee=!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&&!Q&&O[he+1]!==void 0?he+1:null,readsStdinAsCommands:!B&&(Q||O[he+1]===void 0),syntaxCheck:ee}}if(je==="-"||je[0]!=="-"&&je[0]!=="+")return{command:B?je:null,commandIndex:B?he:null,scriptIndex:!B&&!Q&&je!=="-"?he:null,readsStdinAsCommands:!B&&(Q||je==="-"),syntaxCheck:ee};if(je.startsWith("--")){let lt=je.split("=",1)[0]??je;if(D==="bash"&&ga.has(lt)&&!je.includes("="))he++;continue}let at=ha(D,je,O[he+1],"argv");if(at.commandSelected)B=!0;if(at.syntaxCheck)ee=!0;if(at.stdinMode)Q=!0;he+=at.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!B,syntaxCheck:ee}}function So(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 Si(O){let D={inSingle:!1,inDouble:!1,escaped:!1};for(let B of ny(O))So(B,D);return D.inSingle||D.inDouble}function ny(O){let D="",B={inSingle:!1,inDouble:!1,escaped:!1},Q=!1,ee=!0;for(let he=0;he<O.length;he++){let je=O[he];if(!je)break;if(Q){if(je===`
|
|
6
|
+
`||je==="\r")D+=je,Q=!1,B.escaped=!1;continue}if(je==="#"&&!B.inSingle&&!B.inDouble&&ee){Q=!0;continue}if(D+=je,!B.inSingle&&!B.inDouble&&!B.escaped)ee=/[\s;&|()<>]/.test(je);So(je,B)}return D}var ya=new Set(["rm","find","xargs","parallel"]),ry=new Set(["git","busybox",...ya,...Kt,...Eu,...En]),oy=new Set(["python","node","ruby","perl"]);function Le(O){let D=It(O);return ry.has(D)||An(D)}function An(O){return oy.has(iy(O))}function iy(O){let D=Tt(O).toLowerCase();return yi.test(D)?"python":D}var it={version:1,rules:[],overrides:{},transparent_wrappers:[]};function m(O){try{let D=n(sy(O));if(D===null)return{config:null,errors:[]};if(!D.trim())return{config:null,errors:["Config file is empty"]};let B=JSON.parse(D),Q=Ve(B);if(Q.errors.length>0)return{config:null,errors:Q.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 sy(O){return typeof O==="string"?re(O):O}var e=(O,D)=>({path:O,message:D,kind:"typed"}),Xt=(O,D)=>({path:O,message:D,kind:"custom"});function Te(O){let D=new Set;return O.flatMap((B,Q)=>{let ee=zr(B)?B.name:void 0;if(typeof ee!=="string")return[];if(D.has(ee.toLowerCase()))return[Xt(["rules",Q,"name"],`duplicate rule name "${ee}"`)];return D.add(ee.toLowerCase()),[]})}var we=`must be one of ${pa.join(", ")}`,ay=/^[^/]+\/[^/]+$/,ly=["version","rules","overrides","transparent_wrappers"];function Ve(O){let D=cy(O);return{errors:ie(qe(D,ly,(B)=>B.kind==="custom"),": "," "),sources:yy(O,D)}}function cy(O){if(!zr(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")],...uy(O.rules,D),...my(O.overrides),...gy(O.transparent_wrappers),...D?[]:fy(O.rules),...zr(O.overrides)?Object.keys(O.overrides).filter((B)=>!ay.test(B)).map((B)=>Xt(["overrides",B],"must use <rulebook-name>/<rule-name>")):[],...hy(O.transparent_wrappers)]}function uy(O,D){if(O===void 0)return[];if(!Array.isArray(O))return[e(["rules"],"must be an array of rulebook source strings"),...wu(O,pe)?[e(["rules"],fe)]:[]];if(D)return[{path:["rules"],message:fe,kind:"limit"}];return O.flatMap((B,Q)=>{if(typeof B!=="string")return[e(["rules",Q],"must be a rulebook source string"),...dy(B,1)?[e(["rules",Q],"must be a non-empty rulebook source string")]:[]];return B===""?[e(["rules",Q],"must be a non-empty rulebook source string")]:[]})}function wu(O,D){let B=Pu(O);return B!==void 0&&!(B<=D)}function dy(O,D){let B=Pu(O);return B!==void 0&&!(B>=D)}function Pu(O){if(O===null||O===void 0)return;let D=O.length;return D===void 0?void 0:Number(D)}function fy(O){if(!Array.isArray(O))return[];let D=new Set;return O.flatMap((B,Q)=>{if(typeof B!=="string"||B==="")return[];if(B.trim()==="")return[Xt(["rules",Q],"must be a non-empty rulebook source string")];let ee=bu(B);if(ee)return[Xt(["rules",Q],ee)];if(D.has(B))return[Xt(["rules",Q],`duplicate rulebook source "${B}"`)];return D.add(B),[]})}function my(O){if(O===void 0)return[];if(!zr(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(!zr(B))return[e(["overrides",D],'must be "off" or an object')];return[...py(B.reason,["overrides",D,"reason"]),...B.intent===void 0||Ce(B.intent)?[]:[e(["overrides",D,"intent"],we)]]})}function py(O,D){if(typeof O!=="string")return[e(D,"required non-empty string"),...wu(O,T)?[e(D,`must be at most ${T} characters`)]:[]];if(O==="")return[e(D,"required non-empty string")];return O.length>T?[e(D,`must be at most ${T} characters`)]:[]}function gy(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 w.test(D)?[]:[e(["transparent_wrappers",B],"must match command pattern")]})}function hy(O){if(!Array.isArray(O))return[];let D=new Set;return O.flatMap((B,Q)=>{if(typeof B!=="string"||!w.test(B))return[];if(D.has(B))return[Xt(["transparent_wrappers",Q],`duplicate command "${B}"`)];if(Le(B))return[Xt(["transparent_wrappers",Q],`reserved command "${B}" cannot be a wrapper`)];return D.add(B),[]})}function yy(O,D){let B=zr(O)?O.rules:void 0;if(!Array.isArray(B))return new Set;if(D.some((ee)=>ee.path.length===1&&ee.path[0]==="rules"))return new Set;let Q=new Set(D.filter((ee)=>ee.path[0]==="rules"&&typeof ee.path[1]==="number").map((ee)=>ee.path[1]));return new Set(B.filter((ee,he)=>typeof ee==="string"&&!Q.has(he)))}function qe(O,D,B){let Q=O.map((je)=>je.path[1]),ee=[...new Set(Q.filter((je)=>typeof je==="string"))],he=(je,at)=>[je.path.length===0?-1:D.indexOf(String(je.path[0])),typeof at==="number"?at:ee.indexOf(String(at)),B(je)?0:1];return O.map((je,at)=>({issue:je,rank:he(je,Q[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 ie(O,D,B){return[...new Set(O.map((Q)=>{let ee=ba(Q.path);if(Q.kind==="unknownKeys")return`${ee?`${ee}.`:""}unknown field "${Q.message}"`;if(Q.kind==="key"||Q.kind==="limit"||Q.path.length===0)return Q.message;return`${ee}${Q.path.length===1?B:D}${Q.message}`}))]}function ba(O){return O.map((D,B)=>{if(typeof D==="number")return`[${D}]`;return B===0?String(D):`.${String(D)}`}).join("")}function Ce(O){return pa.includes(O)}function zr(O){return!!O&&typeof O==="object"&&!Array.isArray(O)}function se(O){let D=Cy(O);if(D.errors.length>0)throw Error(D.errors.join("; "));return O}var by=`required non-empty string up to ${T} characters`,Au="must be a non-empty array of unique non-empty strings",Sy="required non-empty array of non-empty strings";function Cy(O){if(!er(O))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!_u(O))return{errors:[xu],ruleNames:new Set};let D=[...O.rulebook_version===1||O.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ie(vy(O,O.rulebook_version===2),": ",": ")];return{errors:D.length>Pn.maxValidationErrors?[...D.slice(0,Pn.maxValidationErrors),Ru]:D,ruleNames:new Set(_e(O).map((B)=>B.toLowerCase()))}}function _e(O){let D=er(O)?O.rules:void 0;return(Array.isArray(D)?D:[]).flatMap((B)=>{let Q=er(B)?B.name:void 0;return typeof Q==="string"?[Q]:[]})}function vy(O,D){return[...typeof O.name==="string"&&l.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),...xy(O.rules,D),...Py(O.tests),...Ay(O),...Ty(O)]}function Ey(O){if(!Array.isArray(O))return[e(["allowed_commands"],"required array")];let D=new Set;return[...O.flatMap((B,Q)=>typeof B==="string"&&w.test(B)?[]:[e(["allowed_commands",Q],"must match command pattern")]),...O.flatMap((B,Q)=>{if(typeof B!=="string"||!w.test(B))return[];if(D.has(B))return[Xt(["allowed_commands",Q],`duplicate command "${B}"`)];return D.add(B),[]})]}function xy(O,D){if(!Array.isArray(O))return[e(["rules"],"required array")];return[...O.flatMap((B,Q)=>{if(!er(B))return[e(["rules",Q],"must be an object")];return D?_y(B,["rules",Q]):Ry(B,["rules",Q])}),...Te(O)]}function Ry(O,D){return[...Tu(O.name,D),...Iu(O.command,D),...O.subcommand===void 0||typeof O.subcommand==="string"&&w.test(O.subcommand)?[]:[e([...D,"subcommand"],"must match command pattern")],...Ci(O.block_args,[...D,"block_args"],"required non-empty array",!1),...ku(O.reason,D),...Ou(O.intent,D)]}function _y(O,D){return[...Tu(O.name,D),...Iu(O.command,D),...ku(O.reason,D),...Ou(O.intent,D),...wy(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 Tu(O,D){if(typeof O!=="string")return[e([...D,"name"],"required string")];return l.test(O)?[]:[e([...D,"name"],"must match rule name pattern")]}function Iu(O,D){return typeof O==="string"&&w.test(O)?[]:[e([...D,"command"],"required string matching command pattern")]}function ku(O,D){return typeof O==="string"&&O!==""&&O.length<=T?[]:[e([...D,"reason"],by)]}function Ou(O,D){return O===void 0||Ce(O)?[]:[e([...D,"intent"],we)]}function wy(O,D){if(!er(O))return[e(D,"required object")];return[...Ci(O.command_path,[...D,"command_path"],Sy,!1),...O.any_args===void 0?[]:Ci(O.any_args,[...D,"any_args"],Au,!0),...O.exclude_args===void 0?[]:Ci(O.exclude_args,[...D,"exclude_args"],Au,!0)]}function Ci(O,D,B,Q){if(!Array.isArray(O))return[e(D,B)];let ee=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 ee;return[...ee,...O.length===0?[Xt(D,B)]:[],...Q&&new Set(O).size!==O.length?[Xt(D,"must not contain duplicate values")]:[]]}function Py(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(!er(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 Ay(O){if(!Array.isArray(O.tests))return[];let D=new Set(_e(O));return[...new Set(O.tests.flatMap((B)=>er(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 Ty(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,Q)=>{let ee=er(B)?B.command:void 0;if(typeof ee!=="string"||D.has(ee))return[];return[Xt(["rules",Q,"command"],`"${ee}" must be listed in allowed_commands`)]})}function er(O){return!!O&&typeof O==="object"&&!Array.isArray(O)}function J(O,D){let B=K(O,D),Q;try{Q=du(B.userConfigTarget,B.projectConfigTarget)}catch(mt){if(mt instanceof r)return Gy(B,mt.message);throw mt}let ee=m(B.userConfigTarget),he=Q?{config:null,errors:[]}:m(B.projectConfigTarget),je=Du(B.userConfigPath,ee.errors),at=Du(B.projectConfigPath,he.errors),lt=new Set,ct=ee.config?Sa(ee.config,hr(B.userConfigPath),"user",B.userScope,lt):Nu(),ut=he.config?Sa(he.config,hr(B.projectConfigPath),"project",B.projectScope,lt):Nu(),ft=ee.config?.overrides??{},dt=he.config?.overrides??{};return{rules:[...Mu(ct.rules,ft),...Mu(ut.rules,dt)],transparent_wrappers:Ly(ee.config,he.config),rulebooks:[...ct.rulebooks,...ut.rulebooks],errors:[...je,...at,...ct.errors,...ut.errors],warnings:[...ct.warnings,...ut.warnings,...ct.canValidateOverrides?Ca(ft,ct.knownRuleIds,B.userConfigPath):[],...ct.canValidateOverrides?Wy(dt,ct.knownRuleIds,B.projectConfigPath):[],...ut.canValidateOverrides?Ca(dt,ut.knownRuleIds,B.projectConfigPath):[]],userConfig:ee.config??void 0,projectConfig:he.config??void 0,...B}}function j(O,D){let B=Iy(O,D);if(!B)return[];return[...B.scope.errors,...B.scope.warnings,...ky(B.config,B.scope,O)]}function Iy(O,D){let B=D??v(hr(hr(O)),"rules policy"),Q=m(i(B,O)).config;if(!Q)return null;return{config:Q,scope:Sa(Q,hr(O),"project",B)}}function ky(O,D,B){return D.canValidateOverrides?Ca(O.overrides??{},D.knownRuleIds,B):[]}function Sa(O,D,B,Q=v(hr(hr(D)),B==="user"?"user policy":"project policy"),ee=new Set){let he=[],je=[],at=O.rules.flatMap((ct)=>{let ut=My(ct,D,Q);if(ut.errors.length>0||!ut.rulebook)return he.push(...ut.errors),[];let ft=ut.rulebook;if(ee.has(ft.name))return je.push(`duplicate active rulebook name "${ft.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 ee.add(ft.name),[{rules:Oy(ft),rulebook:{source:B,spec:ct,name:ft.name,version:ft.version,rules:ft.rules.map((dt)=>`${ft.name}/${dt.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 Oy(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 My(O,D,B){let Q=Pe(O),ee=I(D,Q),he=Ny(ee,B);if("error"in he)return{rulebook:null,errors:[he.error]};if(he.content===null)return{rulebook:null,errors:[`missing rulebook file ${ee} for ${O}; ${Dy(O)}`]};let je=me(he.content);if("problem"in je)return{rulebook:null,errors:[`invalid rulebook ${ee}: ${je.problem}; fix that file`]};if(je.rulebook.name!==Q)return{rulebook:null,errors:[`rulebook name "${je.rulebook.name}" in ${ee} must match source "${O}"; fix that file`]};return{rulebook:je.rulebook,errors:[]}}function Pe(O){return S(O)?A(O).name:O}function Dy(O){return S(O)?`run ${vu} to vendor ${O}`:"create that file or remove that source from the rules config"}function Ny(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:se(D)}}catch(B){return{problem:B instanceof Error?B.message:"invalid rulebook"}}}function Ly(O,D){return[...new Set([...O?.transparent_wrappers??[],...D?.transparent_wrappers??[]])]}function Mu(O,D){return O.flatMap((B)=>{let Q=D[B.name];if(Q==="off")return[];if(Q&&typeof Q==="object")return[{...B,intent:Q.intent??B.intent,reason:Q.reason}];return[B]})}function Ca(O,D,B){return Object.keys(O).filter((Q)=>!D.has(Q)).map((Q)=>`unknown override key "${Q}" in ${B}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function Wy(O,D,B){return Object.keys(O).filter((Q)=>D.has(Q)).map((Q)=>`project override cannot target user-scoped rule "${Q}" in ${B}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function Du(O,D){return D.map((B)=>B.startsWith("Unable to access ")?B:`${O}: ${B}`)}function Gy(O,D){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[D],warnings:[],userConfigPath:O.userConfigPath,projectConfigPath:O.projectConfigPath}}function Nu(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as Yy,readFileSync as Zy}from"node:fs";var Lu=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores, with or without --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"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"}],va=new Set(Lu.map((O)=>O.id)),U=Lu,Fy=new Map(U.map((O)=>[O.id,O.intent]));function St(O,D){return{id:O,reason:D,intent:Fy.get(O)??"manual_only"}}var Ea=[{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"}],vi={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},zy=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],By=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],xa=[{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"]},...By.flatMap((O)=>zy.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 Ei=[{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"]}],Wu=[{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"}],$y=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Ra=Wu.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})),_a=Wu.flatMap((O)=>$y.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}))),Co={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)$/},wa=["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})),Pa=[{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=[...Ea,vi,...xa,...Ra,..._a,Co,...wa,...Pa,...Ei].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}})),xi=new Set(Ei.flatMap((O)=>O.category==="Coding CLI config"?[O.id]:[])),Aa=new Set(Ke.map((O)=>O.id));import{isAbsolute as Ta,join as Uy,normalize as Hy,sep as Ri}from"node:path";var _i=process.platform==="win32",Gu=/[*?]/;function Ia(O){let D=O.trim(),B=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(_i?D.replaceAll("\\","/"):D);if(!B)return null;let Q=B[1]??"",ee=B[2]??"";if(Gu.test(Q)||ee==="."||ee==="..")return null;return{root:Q||"/",name:ee}}function vo(O,D){if(O==="~")return D;if(O.startsWith("~/"))return`${D}${O.slice(1)}`;return O}function ka(O,D){if(typeof O!=="string"||O.trim()==="")return"must be a non-empty path string";let B=vo(O.trim(),D);if(!Ta(B))return"must be an absolute path or start with ~/";return Eo(B,D)}function Oa(O,D){let B=Fu(O,D);if(B===null)return"must be a non-empty path string";if(!Ta(B))return null;if(Eo(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 jy="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Vy="cannot cover the guard's own configuration";function Fu(O,D){if(typeof O!=="string"||O.trim()==="")return null;let B=O.trim(),Q=_i?B.replaceAll("\\","/"):B;return vo(Q.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),D)}function Ma(O,D){let B=Fu(O,D);if(B===null)return"must be a non-empty path string";let Q=Ia(B)?.root??B;if(Gu.test(Q))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Ta(Q))return null;if(Eo(Q,D)!==null)return jy;return Ky(Q,D)?Vy:null}function Ky(O,D){let B=wi(O),Q=wi(Uy(D,".cc-safety-net"));return B===Q||B.startsWith(`${Q}${Ri}`)}function Eo(O,D){let B=wi(O),Q=wi(D);if(B===Q)return"cannot be the home directory";let ee=B.endsWith(Ri)?B:`${B}${Ri}`;if(Q.startsWith(ee))return"cannot contain the home directory";return null}function wi(O){let D=Hy(O);if(_i)D=D.replace(/\//g,"\\").toLowerCase();if(D.length>(_i?3:1)&&D.endsWith(Ri))D=D.slice(0,-1);return D}var zu=30,Pi=1,Ai=365;function Bu(O){if(typeof O!=="number"||!Number.isInteger(O))return 30;if(O<1)return 1;return O>365?365:O}var $u=new Set(U.filter((O)=>O.catastrophic).map((O)=>O.id));function wt(O,D){if(!O)return null;if($u.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($u.has(D))return!0;if(O?.destructiveCommandProtectionEnabled===!1)return!1;return O?.effectiveDestructiveCommandRules[D]?.enabled??B}function G(O,D){return Object.freeze(Object.fromEntries(U.map((B)=>{let Q=B.activationCapability?D[B.activationCapability]:void 0,ee=Q?.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:ee,changesInherited:he==="on"!==ee,source:"rule_override",...B.activationCapability?{activationCapability:B.activationCapability}:{},override:he}:{enabled:ee,inheritedEnabled:ee,changesInherited:!1,source:Q?.source??"built_in_default",...B.activationCapability?{activationCapability:B.activationCapability}:{}}:{enabled:!1,inheritedEnabled:ee,changesInherited:!1,source:"master_disabled",...B.activationCapability?{activationCapability:B.activationCapability}:{},...he?{override:he}:{}};return[B.id,Object.freeze(je)]})))}function Uu(O,D){return Object.freeze({...O,effectiveDestructiveCommandRules:G(O,D)})}var Hu={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:Da(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:Da(O.secret_protection.deny_paths,D.secret_protection?.deny_paths),allow_paths:Da(O.secret_protection.allow_paths,D.secret_protection?.allow_paths)},audit:O.audit},weakenings:qy(O,D)}}function Da(O,D){return[...new Set([...O,...D??[]])]}function qy(O,D){let B=D.safety?.level,Q=di[O.safety.level];return[...B&&Hu[B]<Hu[O.safety.level]?[`project policy lowers level: ${O.safety.level} -> ${B}`]:[],...Gr.flatMap((ee)=>D.safety?.overrides?.[ee]===!1&&(O.safety.overrides[ee]??Q[ee])?[`project policy disables ${ee}`]:[]),...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"]:[],...ju(D.destructive_command_protection?.overrides,(ee)=>O.destructive_command_protection.enabled&&O.destructive_command_protection.overrides[ee]!=="off"),...ju(D.secret_protection?.overrides,(ee)=>O.secret_protection.enabled&&(O.secret_protection.overrides[ee]==="on"?!0:O.secret_protection.overrides[ee]!=="off"&&!xi.has(ee))),...O.destructive_command_protection.enabled?Vu(O.destructive_command_protection.allow_paths,D.destructive_command_protection?.allow_paths).map((ee)=>`project policy adds destructive allow path: ${ee}`):[],...O.secret_protection.enabled?Vu(O.secret_protection.allow_paths,D.secret_protection?.allow_paths).map((ee)=>`project policy adds secret allow path: ${ee}`):[]]}function ju(O,D){return Object.entries(O??{}).flatMap(([B,Q])=>Q==="off"&&D(B)?[`project policy disables rule ${B}`]:[])}function Vu(O,D){return(D??[]).filter((B)=>!O.includes(B))}var Wa=new Set(["standard","strict","paranoid"]),Z={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:zu}};function Zu(O,D){let B=nb(u(O,D),O.home),Q=Ie(b(D.cwd),O.home),ee=ae(Q.parsed,O.home),he=Object.keys(ee.policy).length>0?Y(B.gui??Z,ee.policy):void 0,je=[...B.errors,...Q.errors,...ee.diagnostics],at=(B.fallback==="defaults"&&he?"salvaged":B.fallback)??(B.gui?void 0:Q.fallback)??(je.length>0?"salvaged":void 0),lt=ee.policy.safety?.level?"project":B.levelPresent?"user":"default";return{...he?La(he.policy):B.policy,errors:je,...at?{fallback:at}:{},...Q.exists?{policyScopes:{levelScope:lt,weakenings:he?.weakenings??[]}}:{}}}var Xy="project policy audit settings are ignored; audit is user scope only";function ae(O,D){if(!yn(O))return{policy:{},diagnostics:[]};let B=yn(O.safety)?O.safety:{},Q=yn(O.workflow)?O.workflow:{},ee=yn(O.destructive_command_protection)?O.destructive_command_protection:{},he=yn(O.secret_protection)?O.secret_protection:{},je={...Wa.has(B.level)?{level:B.level}:{},...yn(B.overrides)?Ku({overrides:Xu(B.overrides,Gr,["safety","overrides"],yr)}):{}},at={...typeof ee.enabled==="boolean"?{enabled:ee.enabled}:{},...ee.overrides!==void 0?{overrides:Ti(ee.overrides,va,Qu,yr)}:{},...ee.allow_paths!==void 0?{allow_paths:$r(ee.allow_paths,ka,D,["destructive_command_protection","allow_paths"],yr)}:{}},lt={...typeof he.enabled==="boolean"?{enabled:he.enabled}:{},...he.overrides!==void 0?{overrides:Ti(he.overrides,Aa,ed,yr)}:{},...he.deny_paths!==void 0?{deny_paths:$r(he.deny_paths,Oa,D,["secret_protection","deny_paths"],yr)}:{},...he.allow_paths!==void 0?{allow_paths:$r(he.allow_paths,Ma,D,["secret_protection","allow_paths"],yr)}:{}};return{policy:Ku({safety:je,workflow:typeof Q.worktree_mode==="boolean"?{worktree_mode:Q.worktree_mode}:{},destructive_command_protection:at,secret_protection:lt}),diagnostics:O.audit===void 0?[]:[Xy]}}function Xu(O,D,B,Q){return Object.fromEntries(D.flatMap((ee)=>{let he=O[ee];if(typeof he==="boolean")return[[ee,he]];if(he!==void 0)Q(e([...B,ee],Ga));return[]}))}function Ku(O){return Object.fromEntries(Object.entries(O).flatMap((D)=>Object.keys(D[1]).length>0?[D]:[]))}var yr=()=>{return},Ga="must be a boolean",Fa="must be an object if provided",Ju=`must be an integer between ${Pi} and ${Ai}`,Qu={path:["destructive_command_protection","overrides"],label:"destructive command"},ed={path:["secret_protection","overrides"],label:"secret protection"},Je=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Ye(O,D){let B=[];return{policy:td(O,D,(ee)=>{B.push(ee)}),issues:B}}function C(O,D){return td(O,D,yr)}function td(O,D,B){if(!yn(O))return B(e([],"Config must be an object")),H();if(O.version!==1)B(e(["version"],"must be 1"));let Q=Br(O.safety,["safety"],["level","overrides"],B),ee=Br(Q.overrides,["safety","overrides"],Gr,B),he=Br(O.workflow,["workflow"],["worktree_mode"],B),je=Br(O.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],B),at=Br(O.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],B),lt=Br(O.audit,["audit"],["retention_days"],B);return nd(O,Je,[],B),{version:1,safety:{level:Jy(Q.level,B),overrides:Xu(ee,Gr,["safety","overrides"],B)},workflow:{worktree_mode:Na(he.worktree_mode,["workflow","worktree_mode"],!1,B)},destructive_command_protection:{enabled:Na(je.enabled,["destructive_command_protection","enabled"],!0,B),overrides:Ti(je.overrides,va,Qu,B),allow_paths:$r(je.allow_paths,ka,D,["destructive_command_protection","allow_paths"],B)},secret_protection:{enabled:Na(at.enabled,["secret_protection","enabled"],!0,B),overrides:Ti(at.overrides,Aa,ed,B),deny_paths:$r(at.deny_paths,Oa,D,["secret_protection","deny_paths"],B),allow_paths:$r(at.allow_paths,Ma,D,["secret_protection","allow_paths"],B)},audit:{retention_days:Qy(lt.retention_days,B)}}}function Br(O,D,B,Q){if(O===void 0)return{};if(!yn(O))return Q(e(D,Fa)),{};return nd(O,B,D,Q),O}function nd(O,D,B,Q){for(let ee of Object.keys(O).filter((he)=>!D.includes(he)))Q({path:B,message:ee,kind:"unknownKeys"})}function Jy(O,D){if(O===void 0)return"standard";if(Wa.has(O))return O;return D(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Na(O,D,B,Q){if(typeof O==="boolean")return O;if(O!==void 0)Q(e(D,Ga));return B}function Qy(O,D){if(!(O===void 0||typeof O==="number"&&Number.isInteger(O)&&O>=Pi&&O<=Ai))D(e(["audit","retention_days"],Ju));return Bu(O)}function Ti(O,D,B,Q){if(O===void 0)return{};if(!yn(O))return Q(e(B.path,Fa)),{};return Object.fromEntries(Object.entries(O).flatMap(([ee,he])=>{if(!D.has(ee))return Q({path:[...B.path,ee],message:`unknown ${B.label} rule id "${ee}"`,kind:"key"}),[];if(he==="on"||he==="off")return[[ee,he]];return Q(e([...B.path,ee],'must be "on" or "off"')),[]}))}function $r(O,D,B,Q,ee){if(O===void 0)return[];if(!Array.isArray(O))return ee(e(Q,"must be an array of paths")),[];return O.flatMap((he,je)=>{let at=D(he,B);if(at===null)return[he];return ee(typeof he==="string"?Xt([...Q,je],at):e([...Q,je],at)),[]})}function yn(O){return!!O&&typeof O==="object"&&!Array.isArray(O)}function H(){return structuredClone(Z)}function Ae(O,D){let B=R({safety:De(O.safety)},D),Q=G({destructiveCommandProtectionEnabled:O.destructive_command_protection.enabled,destructiveCommandRuleOverrides:O.destructive_command_protection.overrides},B.capabilities),ee=Object.values(Q),he=ee.filter((je)=>je.source!=="catastrophic");return{selectedPreset:O.safety.level,effectiveLevel:B.effectiveLevel,capabilities:B.capabilities,rules:Q,counts:{enabled:he.filter((je)=>je.enabled).length,disabled:he.filter((je)=>!je.enabled).length,effectiveCustomizations:ee.filter((je)=>je.changesInherited).length}}}function Ie(O,D){if(!Yy(O))return{exists:!1,policy:H(),errors:[]};try{let B=Zy(O,"utf-8");if(!B.trim())return{exists:!0,policy:H(),errors:[`${O}: Config file is empty`],fallback:"defaults"};let Q=JSON.parse(B),ee=Ye(Q,D);if(ee.issues.length===0)return{exists:!0,parsed:Q,policy:ee.policy,errors:[]};return{exists:!0,parsed:Q,policy:ee.policy,errors:ee.issues.map((he)=>`${O}: ${tb(he)}`),fallback:yn(Q)?"salvaged":"defaults"}}catch(B){let Q=B instanceof Error?B.message:String(B);return{exists:!0,policy:H(),errors:[`${O}: ${B instanceof SyntaxError?"Invalid JSON":Q}`],fallback:"defaults"}}}var eb=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[Fa,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[Ga,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Ju,`not an integer between ${Pi} and ${Ai}`]]);function tb(O){let D=ba(O.path);if(O.kind==="unknownKeys")return`${D===""?"":`${D}.`}${O.message}: unknown field`;if(O.kind==="key")return`${D}: unknown rule id`;let B=eb.get(O.message)??O.message;return D===""?B:`${D}: ${B}`}function nb(O,D){let B=Ie(O,D);if(!B.exists){let Q=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!yn(Q))return{policy:Yu(),errors:[]};let ee=C(Q,D);return{policy:La(ee),gui:ee,errors:[],levelPresent:qu(Q)}}if(B.parsed===void 0)return{policy:Yu(),errors:B.errors,...B.fallback?{fallback:B.fallback}:{}};return{policy:La(B.policy),gui:B.policy,errors:B.errors,...B.fallback?{fallback:B.fallback}:{},levelPresent:qu(B.parsed)}}function qu(O){let D=yn(O)&&yn(O.safety)?O.safety:{};return Wa.has(D.level)}function Oe(O){let D=Object.entries(O),B=new Set(D.flatMap(([Q,ee])=>ee==="on"?[Q]:[]));return[...new Set([...[...xi].filter((Q)=>!B.has(Q)),...D.flatMap(([Q,ee])=>ee==="off"?[Q]:[])])]}function Yu(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Oe({}),denyPaths:[],allowPaths:[]}}}function La(O){return{safety:De(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:Oe(O.secret_protection.overrides),denyPaths:O.secret_protection.deny_paths,allowPaths:O.secret_protection.allow_paths}}}function De(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 E(O,D){let B=J(O,D),Q=Zu(O,D),ee={rules:B.rules,transparentWrappers:B.transparent_wrappers,safety:Q.safety,worktreeMode:Q.worktreeMode,destructiveCommandProtectionEnabled:Q.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:Q.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:Q.destructiveCommandAllowPaths,secretProtection:{enabled:Q.secretProtection.enabled??!0,disabledRules:Q.secretProtection.disabledRules??[],denyPaths:Q.secretProtection.denyPaths,allowPaths:Q.secretProtection.allowPaths??[]}},he={...B.userConfig?.overrides,...B.projectConfig?.overrides},je=Object.freeze(Object.fromEntries(ee.rules.map((at)=>{let lt=B.rulebooks.find((ut)=>ut.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}),...sb(lt.spec)?{source:lt.spec}:{}}:{},...ct&&typeof ct==="object"?{override:Object.freeze({type:"reason",reason:ct.reason})}:{}})]})));return Ee(ee,rb(B,Q),je,Q.policyScopes)}function Ne(O){if(O.state==="ready")return{state:O.state};return{state:O.state,reason:O.reason}}function rb(O,D){let B=ib(D);if(O.errors.length===0&&O.warnings.length===0&&!B)return;return{diagnostics:[...O.errors,...O.warnings,...D.errors],reason:ab(O.errors.length>0?ob(O.errors):void 0,O.warnings.length>0?Ba(O.warnings.join("; ")):void 0,B)}}function ob(O){return`${Ba(O.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function ib(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 sb(O){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(O)}function Ee(O,D,B=Object.freeze({}),Q){let ee=za(structuredClone(O)),he=Q?{policyScopes:za(structuredClone(Q))}:{};if(!D)return Object.freeze({state:"ready",policy:ee,diagnostics:Object.freeze([]),ruleMetadata:B,...he});return Object.freeze({state:"degraded",policy:ee,diagnostics:Object.freeze([...D.diagnostics]),reason:D.reason,ruleMetadata:B,...he})}function za(O){if(typeof O!=="object"||O===null)return O;for(let D of Object.values(O))za(D);return Object.freeze(O)}function ab(...O){return Ba(O.filter((D)=>!!D).join("; "))}function Ba(O){return/[.!?]$/.test(O)?O:`${O}.`}function Fe(O){let D=O.effectiveCapabilities,B=O.strict??D.fail_closed.enabled,Q=O.paranoidRm??D.paranoid_rm.enabled,ee=O.paranoidInterpreters??D.paranoid_interpreters.enabled,he={fail_closed:$a(D.fail_closed,O.strict,"strict"),paranoid_rm:$a(D.paranoid_rm,O.paranoidRm,"paranoidRm"),paranoid_interpreters:$a(D.paranoid_interpreters,O.paranoidInterpreters,"paranoidInterpreters")};return{policy:Uu(O.policySnapshot.policy,he),effectiveCapabilities:he,effectiveLevel:ia({failClosed:B,paranoidRm:Q,paranoidInterpreters:ee}),strict:B,paranoidRm:Q,paranoidInterpreters:ee,worktreeMode:O.worktreeMode??!1}}function $a(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 xo(O,D){if(O!=="powershell")return D[0]?.provenance==="command-substitution";let B=D[0]?.text==="&"||D[0]?.text==="."?1:0,Q=D[B]?.provenance;return Q!==void 0&&Q!=="literal"}var lb=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ii(O,D){return O?.provenance==="literal"&&!O.quoted&&O.raw===D&&O.text===D}function Ro(O){let D=Ii(O.words[0],"time")?1:0,B=D===1&&Ii(O.words[D],"-p")?D+1:D,Q=D===1&&Ii(O.words[B],"--")?B+1:B,ee=Ii(O.words[Q],"!")?Q+1:Q,he=O.words.slice(ee).find((je)=>!lb.test(je.text));return he?.provenance==="literal"?he.text:void 0}var tr=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function ki(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function cb(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)=>ln(D)))})}function Oi(O,D,B){O.push(B),D.reset()}function Mi(O){let D=[];return{parts:D,push:(B,Q,ee)=>{if(Q<=B)return;D.push({raw:O.slice(B,Q),span:{start:B,end:Q},provenance:ee})}}}function Ua(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 Ur(O,D,B,Q,ee,he,je){return Ua({text:Q,raw:O.slice(D,B),span:{start:D,end:B},provenance:ee,quoted:he,...je?{parts:je}:{}})}function ln(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 cb(D);if(D.kind==="group"||D.kind==="function")return Object.freeze({...D,span:Object.freeze(D.span),body:ln(D.body)});return Object.freeze({...D,span:Object.freeze(D.span)})}))})}function Ha(O,D,B){if(D>=B||od(O[D]??""))return null;let Q="",ee=!1,he=!1,je=D;while(je<B&&!od(O[je]??"")){let at=O[je]??"";if(at==="'"){ee=!0;let lt=rd(O,je+1,B,"'");Q+=lt.text,he||=!lt.closed,je=lt.next;continue}if(at==='"'){ee=!0;let lt=rd(O,je+1,B,'"');Q+=lt.text,he||=!lt.closed,je=lt.next;continue}if(at==="\\"){ee=!0;let lt=O[je+1];if(!lt||lt===`
|
|
7
|
+
`||lt==="\r"){he=!0;break}Q+=lt,je+=2;continue}if(at==="`"||O.startsWith("$(",je)||O.startsWith("${",je)||O.startsWith("<(",je)||O.startsWith(">(",je))he=!0;Q+=at,je++}return{delimiter:Q,quoted:ee,next:je,ambiguous:he}}function ja(O,D,B,Q){let ee=[],he=D;for(let je of Q){let at=he,lt=!1;while(he<B){let ct=ub(O,he,B);if((je.stripTabs?ct.text.replace(/^\t+/,""):ct.text)===je.delimiter){je.attach({body:je.stripTabs?db(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 ee.push({code:"unterminated-heredoc",message:`heredoc delimiter ${je.delimiter} was not found`}),{next:B,issues:ee,terminated:!1}}return{next:he,issues:ee,terminated:!0}}function rd(O,D,B,Q){let ee="",he=D;while(he<B&&O[he]!==`
|
|
8
|
+
`&&O[he]!=="\r"){let je=O[he]??"";if(je===Q)return{text:ee,next:he+1,closed:!0};if(Q==='"'&&je==="\\"&&O[he+1]){let at=O[he+1]??"";ee+=["$","`",'"',"\\"].includes(at)?at:`\\${at}`,he+=2;continue}ee+=je,he++}return{text:ee,next:he,closed:!1}}function od(O){return O!=="\r"&&(/[\s;&|<>)]/u.test(O)||O==="`")}function ub(O,D,B){let Q=D;while(Q<B&&O[Q]!==`
|
|
9
|
+
`)Q++;let ee=Q>=B?B:Q+1;return{text:O.slice(D,Q),contentEnd:Q,next:ee}}function db(O){return O.replace(/(^|\r\n?|\n)\t+/g,"$1")}var ld=new Set(["&&","||","|","|&"]);function cd(O,D){let B={start:0,end:O.length};if(O.length>D.maxInputLength)return ln({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 Q=Li(O,0,O.length,D,{used:0,max:D.maxWords},0);return ln({kind:"program",dialect:"posix",source:O,span:B,status:Fi(Q.issues,Q.limited),issues:Q.issues,nodes:Q.nodes})}function Li(O,D,B,Q,ee,he,je){let at=[],lt=[],ct=ki(),ut=[],ft=()=>{if(ct.words.length===0&&ct.redirections.length===0)return;let mt={start:ct.start,end:ct.end},pt=ct.words.map((gt)=>gt.text);Oi(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(" ")})},dt=D;while(dt<B){let mt=O[dt];if(!mt)break;if(je&&mt===je)return ft(),ad(at,lt),{nodes:at,issues:lt,next:dt+1,closed:!0,limited:!1,pendingHeredocs:ut};if(Gi(mt)){if(mt===`
|
|
10
|
+
`||mt==="\r"){ft();let vt=mt==="\r"&&O[dt+1]===`
|
|
11
|
+
`?dt+2:dt+1,Pt=at.at(-1);if(Pt?.kind!=="connector"||!ld.has(Pt.operator))at.push(Object.freeze({kind:"connector",operator:O.slice(dt,vt),span:Object.freeze({start:dt,end:vt})}));if(ut.length>0){let xt=ja(O,vt,B,ut.splice(0));lt.push(...xt.issues),dt=xt.next;continue}dt=vt;continue}dt++;continue}if(mt==="#"){while(dt<B&&O[dt]!==`
|
|
12
|
+
`&&O[dt]!=="\r")dt++;continue}let pt=ct.start===-1?Ob(O,dt,B):void 0;if(pt){if(Ka(at,lt),he>=Q.maxDepth)return Hr(at,lt,dt,"depth-limit",Q.maxDepth);if(!Va(ee))return Hr(at,lt,dt,"word-limit",Q.maxWords);let vt=Li(O,pt.braceIndex+1,B,Q,ee,he+1,"}"),Pt=vt.next,xt={start:pt.braceIndex+1,end:vt.closed?Pt-1:Pt},_t=id(O,xt,vt);if(at.push({kind:"function",name:pt.name,span:{start:dt,end:Pt},body:_t}),lt.push(...vt.issues),vt.pendingHeredocs.length>0||wo(vt.nodes))lt.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(ut.push(...vt.pendingHeredocs),vt.limited)return Ni(at,lt,vt.next);if(!vt.closed)lt.push({code:"unclosed-function-body",message:"function body is not closed"});dt=Pt;continue}let gt=Wi(O,dt);if(gt){if(ft(),!yd(at.at(-1)))lt.push({code:"unexpected-connector",message:`connector ${gt} has no preceding command`});at.push(Object.freeze({kind:"connector",operator:gt,span:Object.freeze({start:dt,end:dt+gt.length})})),dt+=gt.length;continue}if(mt===")"){ft(),lt.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),at.push({kind:"unknown",source:mt,span:{start:dt,end:dt+1}}),dt++;continue}if((mt==="("||mt==="{"&&Sb(O,dt,B))&&ct.start===-1){if(Ka(at,lt),he>=Q.maxDepth)return Hr(at,lt,dt,"depth-limit",Q.maxDepth);let vt=mt==="("?")":"}",Pt=Li(O,dt+1,B,Q,ee,he+1,vt),xt=Pt.next,_t={start:dt+1,end:Pt.closed?xt-1:xt},Ut=id(O,_t,Pt);if(at.push({kind:"group",style:mt==="("?"subshell":"brace",span:{start:dt,end:xt},body:Ut}),lt.push(...Pt.issues),Pt.pendingHeredocs.length>0||wo(Pt.nodes))lt.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(ut.push(...Pt.pendingHeredocs),Pt.limited)return Ni(at,lt,Pt.next);if(!Pt.closed)lt.push({code:mt==="("?"unclosed-subshell":"unclosed-brace-group",message:`${mt} group is not closed`});dt=xt;continue}let ht=(mt==="<"||mt===">")&&O[dt+1]!=="("?gb(O,dt):null;if(ht){let vt=ct.words.at(-1),Pt=vt&&vt.span.end===dt&&/^[0-9]+$/.test(vt.raw)?Number(vt.raw):void 0;if(Pt!==void 0)ct.words.pop();let xt=Pt===void 0?dt:vt?.span.start??dt;ct.start=ct.start===-1?dt:ct.start;let _t=dt+ht.length;while(_t<B&&/[ \t]/.test(O[_t]??""))_t++;let Ut=O[_t],jt=_t>dt+ht.length&&Ut==="#",qt=!Ut||Gi(Ut)||!!Wi(O,_t)||Ut===je||Ut===")"||jt||(Ut==="<"||Ut===">")&&O[_t+1]!=="(",Vt=ht==="<<"||ht==="<<-",Ft=Vt?Ha(O,_t,B):void 0,Ot=Ft?{word:Ur(O,_t,Ft.next,Ft.delimiter,"literal",Ft.quoted),nested:[],issues:[],next:Ft.next,limited:!1}:!qt?qa(O,_t,B,Q,ee,he):void 0;if(Ot){if(lt.push(...Ot.issues),Ot.limited)return Ni(at,lt,Ot.next);if(!Va(ee))return Hr(at,lt,Ot.next,"word-limit",Q.maxWords)}let on=Ot?.next??dt+ht.length,Cn={kind:"redirection",operator:ht,span:{start:xt,end:on},...Pt===void 0?{}:{fd:Pt},...Ot?{target:Ot.word}:{}};if(ct.redirections.push(Cn),Vt&&!Ft)lt.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if(Ft){if(Ft.ambiguous||Ft.delimiter.length===0)lt.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let Bn=ct.nested;ut.push({delimiter:Ft.delimiter,quotedDelimiter:Ft.quoted,stripTabs:ht==="<<-",attach:(wn)=>{if(Cn.heredoc=wn,wn.quotedDelimiter)return;Bn.push(...mb(O,wn.bodySpan.start,wn.bodySpan.end,Q,ee,he+1))}})}if(!Vt&&!Ot)lt.push({code:"missing-redirection-target",message:`redirection ${ht} requires a target word`});if(Ot)ct.nested.push(...Ot.nested);ct.end=on,dt=on;continue}if(ct.start===-1)Ka(at,lt);let yt=qa(O,dt,B,Q,ee,he);if(lt.push(...yt.issues),yt.limited)return Ni(at,lt,yt.next);let Ct=Eb(ct.words)?Pb(O,yt.word,ee.max-ee.used,Q.maxDepth,Q.maxInputLength):void 0;if(Ct?.limitCode)return Hr(at,lt,yt.next,Ct.limitCode,Ct.limitCode==="word-limit"?Q.maxWords:Ct.limitCode==="depth-limit"?Q.maxDepth:Q.maxInputLength);let Et=Ct?.words??[yt.word];for(let vt of Et){if(!Va(ee))return Hr(at,lt,yt.next,"word-limit",Q.maxWords);ct.words.push(vt)}ct.start=ct.start===-1?dt:ct.start,ct.end=yt.next,ct.nested.push(...yt.nested),dt=yt.next>dt?yt.next:dt+1}return ft(),ad(at,lt),lt.push(...Mb(ut)),{nodes:at,issues:lt,next:dt,closed:je===void 0,limited:!1,pendingHeredocs:[]}}function id(O,D,B){return{kind:"program",dialect:"posix",source:O.slice(D.start,D.end),span:D,status:Fi(B.issues,B.limited),issues:B.issues,nodes:B.nodes}}function qa(O,D,B,Q,ee,he){let je="",at=D,lt=!1,ct="literal",ut=[],ft=[],dt=!1;while(at<B){let mt=O[at],pt=(mt==="<"||mt===">")&&O[at+1]==="(";if(!mt||Gi(mt)||(mt===";"||mt==="|"||mt==="&")&&Wi(O,at)||(mt==="<"||mt===">")&&!pt)break;if(mt===")")break;if(mt==="'"){lt=!0;let ht=O.indexOf("'",at+1);if(ht===-1||ht>=B){je+=O.slice(at+1,B),ft.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),at=B;break}je+=O.slice(at+1,ht),at=ht+1;continue}if(mt==='"'){lt=!0;let ht=fb(O,at,B,Q,ee,he);if(je+=ht.text,ut.push(...ht.nested),ft.push(...ht.issues),dt||=ht.limited,ct=_o(ct,ht.provenance),at=ht.next,dt)break;continue}if(O.startsWith("$'",at)){lt=!0;let ht=hb(O,at+2,B);if(je+=ht.text,ft.push(...ht.issues),!ht.closed)ft.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});at=ht.next;continue}if(mt==="\\"){let ht=O[at+1];if(!ht){ft.push({code:"trailing-escape",message:"escape has no following character"}),at++;break}if(ht===`
|
|
13
|
+
`){at+=2;continue}je+=ht,at+=2;continue}let gt=mt==="$"||mt==="<"||mt===">"||mt==="`"?zi(O,at,B,Q,ee,he):null;if(gt){let ht=ud(gt,ut,ft);if(dt||=ht.limited,ct=_o(ct,ht.provenance),at=ht.next,dt)break;continue}if(mt==="$"){let ht=md(O,at,B,je,ct);je=ht.text,ct=ht.provenance,at=ht.next;continue}if(mt==="*"||mt==="?"||mt==="[")ct=_o(ct,"glob");je+=mt,at++}return{word:Ur(O,D,at,je,ct,lt,ct==="literal"?void 0:bb(O,D,at)),nested:ut,issues:ft,next:at,limited:dt}}function fb(O,D,B,Q,ee,he){let je="",at="literal",lt=[],ct=[],ut=!1,ft=D+1;while(ft<B){let dt=O[ft];if(dt==='"')return{text:je,provenance:at,nested:lt,issues:ct,next:ft+1,limited:ut};if(dt==="\\"&&O[ft+1]){let pt=O[ft+1]??"";if(pt===`
|
|
14
|
+
`){ft+=2;continue}if(pt==="\r"&&O[ft+2]===`
|
|
15
|
+
`){ft+=3;continue}je+=["$","`",'"',"\\"].includes(pt)?pt:`\\${pt}`,ft+=2;continue}if(O.startsWith("$((",ft)){let pt=Ya(O,ft+3,B,"))"),gt=pt===-1?B:pt+2;if(je+=O.slice(ft,gt),pt===-1)ct.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});ft=gt;continue}let mt=zi(O,ft,B,Q,ee,he);if(mt){let pt=ud(mt,lt,ct);if(ft=pt.next,ut||=pt.limited,at=_o(at,pt.provenance),ut)return{text:je,provenance:at,nested:lt,issues:ct,next:ft,limited:ut};continue}if(dt==="$"){let pt=md(O,ft,B,je,at);je=pt.text,at=pt.provenance,ft=pt.next;continue}je+=dt??"",ft++}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:ut}}function zi(O,D,B,Q,ee,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 ut=je?3:ct?1:2,ft=je?"))":ct?"`":")",dt=Ya(O,D+ut,B,ft),mt=dt===-1?B:dt,pt=dt===-1?B:dt+ft.length;if(he>=Q.maxDepth)return{program:kb(O,D+ut,mt,"depth-limit"),next:pt,provenance:je?"arithmetic":"command-substitution"};if(je){let Ct=[],Et=[],vt=!1,Pt=D+ut;while(Pt<mt){let xt=zi(O,Pt,mt,Q,ee,he+1);if(!xt){Pt++;continue}if(Ct.push(...xt.program.nodes),Et.push(...xt.program.issues),vt||=xt.program.status==="limited",Pt=xt.next,vt)break}if(dt===-1)Et.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:ln({kind:"program",dialect:"posix",source:O.slice(D+ut,mt),span:{start:D+ut,end:mt},status:Fi(Et,vt),issues:Et,nodes:Ct}),next:pt,provenance:"arithmetic"}}let gt=Li(O,D+ut,mt,Q,ee,he+1),ht=dt===-1?[{code:"unclosed-command-substitution",message:`${O.slice(D,D+ut)} substitution is not closed`}]:[],yt=(ct||lt)&&wo(gt.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[];return{program:ln({kind:"program",dialect:"posix",source:O.slice(D+ut,mt),span:{start:D+ut,end:mt},status:Fi([...gt.issues,...ht,...yt],gt.limited),issues:[...gt.issues,...ht,...yt],nodes:gt.nodes}),next:pt,provenance:"command-substitution"}}function mb(O,D,B,Q,ee,he){let je=[],at=D;while(at<B){let lt=O[at];if(lt==="\\"){at+=2;continue}let ct=lt==="$"||lt==="`"?zi(O,at,B,Q,ee,he):null;if(!ct){at++;continue}if(je.push(ct.program),at=ct.next,ct.program.status==="limited")break}return je}function ud(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 Ya(O,D,B,Q){if(Q==="`"){for(let at=D;at<B;at++){if(O[at]==="\\"){at++;continue}if(O[at]==="`")return at}return-1}let ee=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 ut=lt==="\r"&&O[at+1]===`
|
|
17
|
+
`?at+2:at+1,ft=ja(O,ut,B,je.splice(0));if(!ft.terminated)return-1;at=ft.next-1;continue}let ct=dd(O,at,D,B,he);if(ct!==null){at=ct;continue}if(!he.double&&O.startsWith("$((",at)){let ut=pb(O,at+3,B);if(ut===-1)return-1;at=ut+1;continue}if(Q===")"&&!he.double&<==="<"&&O[at+1]==="<"&&O[at+2]!=="<"){let ut=O[at+2]==="-",ft=at+(ut?3:2);while(ft<B&&/[ \t]/.test(O[ft]??""))ft++;let dt=Ha(O,ft,B);if(dt){je.push({delimiter:dt.delimiter,quotedDelimiter:dt.quoted,stripTabs:ut,attach:()=>{return}}),at=dt.next-1;continue}}if(O.startsWith("$(",at)&&!O.startsWith("$((",at)){ee++,at++;continue}if(lt==="("&&!he.double)ee++;if(lt===")"&&!he.double){if(ee--,ee===0)return Q==="))"&&O[at+1]!==")"?-1:at}}return-1}function pb(O,D,B){let Q=1,ee={single:!1,double:!1};for(let he=D;he<B;he++){let je=O[he],at=dd(O,he,D,B,ee);if(at!==null){he=at;continue}if(O.startsWith("$(",he)&&!O.startsWith("$((",he)){Q++,he++;continue}if(je==="("&&!ee.double)Q++;if(je!==")"||ee.double)continue;if(Q--,Q===0)return O[he+1]===")"?he:-1}return-1}function dd(O,D,B,Q,ee){let he=O[D];if(he==="\\"&&!ee.single)return D+1;if(!ee.double&&he==="'")ee.single=!ee.single;if(!ee.single&&he==='"')ee.double=!ee.double;if(ee.single)return D;if(ee.double||he!=="#"||!Db(O,D,B))return null;let je=D;while(je+1<Q&&O[je+1]!==`
|
|
18
|
+
`&&O[je+1]!=="\r")je++;return je}function Wi(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 gb(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 Gi(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 fd(O,D,B){if(O[D+1]==="{"){let ee=O.indexOf("}",D+2);return ee===-1||ee>=B?B:ee+1}let Q=D+1;while(Q<B&&/[A-Za-z0-9_?@#$!*-]/.test(O[Q]??""))Q++;return Q===D+1?D+1:Q}function hb(O,D,B){let Q="",ee=[],he=D;while(he<B){let je=O[he];if(je==="'")return{text:Q,next:he+1,closed:!0,issues:ee};if(je!=="\\"){Q+=je??"",he++;continue}let at=yb(O,he+1,B);if(Q+=at.text,at.invalidCodePoint!==void 0)ee.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:Q,next:B,closed:!1,issues:ee}}function yb(O,D,B){let Q=O[D];if(!Q||D>=B)return{text:"\\",next:D};let ee=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
|
|
19
|
+
`],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(ee.has(Q))return{text:ee.get(Q)??Q,next:D+1};if(Q==="x")return Di(O,D+1,B,16,2,D+1);if(Q==="u")return Di(O,D+1,B,16,4,D+1);if(Q==="U")return Di(O,D+1,B,16,8,D+1);if(/[0-7]/.test(Q))return Di(O,D,B,8,3,D+1);return{text:Q,next:D+1}}function Di(O,D,B,Q,ee,he){let je=Q===16?/[0-9a-fA-F]/:/[0-7]/,at="",lt=D;while(lt<B&&at.length<ee&&je.test(O[lt]??""))at+=O[lt],lt++;if(!at)return{text:O[he-1]??"",next:he};let ct=Number.parseInt(at,Q);return ct>1114111||ct>=55296&&ct<=57343?{text:"�",next:lt,invalidCodePoint:ct}:{text:String.fromCodePoint(ct),next:lt}}function Fi(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 md(O,D,B,Q,ee){let he=fd(O,D,B);return{text:Q+O.slice(D,he),provenance:_o(ee,"variable"),next:he}}function bb(O,D,B){let Q=Mi(O),ee=D,he=!1,je=!1,at=D;while(at<B){let lt=O[at];if(lt==="\\"&&!he){at+=2;continue}if(!je&<==="'"){he=!he,at++;continue}if(!he&<==='"'){je=!je,at++;continue}if(he){at++;continue}let ct=O.startsWith("$((",at),ut=O.startsWith("$(",at)&&!ct,ft=!je&&(O.startsWith("<(",at)||O.startsWith(">(",at)),dt=lt==="`";if(ct||ut||ft||dt){let mt=ct?3:dt?1:2,pt=ct?"))":dt?"`":")",gt=Ya(O,at+mt,B,pt),ht=gt===-1?B:gt+pt.length;Q.push(ee,at,"literal"),Q.push(at,ht,ct?"arithmetic":"command-substitution"),at=ht,ee=ht;continue}if(lt==="$"){let mt=fd(O,at,B);if(mt>at+1){Q.push(ee,at,"literal"),Q.push(at,mt,"variable"),at=mt,ee=mt;continue}}if(!je&&(lt==="*"||lt==="?"||lt==="[")){Q.push(ee,at,"literal"),Q.push(at,at+1,"glob"),at++,ee=at;continue}at++}return Q.push(ee,B,"literal"),Q.parts}function _o(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 Sb(O,D,B){return D+1>=B||Gi(O[D+1]??"")||Wi(O,D+1)!==null}var Cb=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),vb=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function Eb(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=xb(O,D);if(B===void 0||B===null)return!1;D=B}return!1}function xb(O,D){let B=O[D]?.text.toLowerCase();if(B==="command")return Rb(O,D);if(B==="env")return _b(O,D);if(B==="sudo")return wb(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 Q=O[B]?.text??"";if(Q==="--")return B+1;if(Q==="-p"||Q==="-v"||Q==="-V"||/^-[pvV]+$/.test(Q))continue;return B}return O.length}function _b(O,D){for(let B=D+1;B<O.length;B++){let Q=O[B]?.text??"";if(Q==="--")return B+1;if(Cb.has(Q)){if(O[B+1]===void 0)return null;B++;continue}if(Q.startsWith("-u=")||Q.startsWith("--unset=")||Q.startsWith("-C")&&Q.length>2||Q.startsWith("--chdir=")||Q.startsWith("-S")&&Q.length>2||Q.startsWith("--split-string=")||Q.startsWith("-P"))continue;if(Q.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(Q))continue;return B}return O.length}function wb(O,D){for(let B=D+1;B<O.length;B++){let Q=O[B]?.text??"";if(Q==="--")return B+1;if(vb.has(Q)){if(O[B+1]===void 0)return null;B++;continue}if(Q.startsWith("-"))continue;return B}return O.length}function pd(O,D,B,Q){if(O.provenance!=="literal"||!O.raw.includes("{"))return;let ee=gd(O.raw,D,B,Q,!0);if(!ee)return;if("limited"in ee)return{limited:!0};let he=ee.values.map((je)=>hd(je,B));if(he.some((je)=>je===null))return{limited:!0};return{words:[...new Set(he.filter((je)=>je!==null&&je!==""))]}}function Pb(O,D,B,Q,ee){if(D.provenance!=="literal"||!D.raw.includes("{"))return;let he=gd(D.raw,B,Q,ee,!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)=>hd(at,Q));if(je.some((at)=>at===null))return;return{words:je.filter((at)=>at!==null&&at!=="").map((at)=>Ur(O,D.span.start,D.span.end,at,"literal",!1))}}function gd(O,D,B,Q,ee){let he=[O],je=O.length,at=0;while(!0){let lt=he.findIndex((mt)=>sd(mt,ee));if(lt===-1)break;if(++at>B)return{limited:"expansions"};let ct=he[lt]??"",ut=sd(ct,ee);if(!ut||ut.kind==="range")return{limited:"expansions"};let ft=ut.start+ct.length-ut.end,dt=ut.alternatives.reduce((mt,pt)=>mt+ft+pt.length,0);if(je-ct.length+dt>Q)return{limited:"length"};if(he.length-1+ut.alternatives.length>D)return{limited:"words"};he.splice(lt,1,...Ab(ct,ut)),je+=dt-ct.length}return at===0?void 0:{values:he}}function sd(O,D){let B=[],Q,ee=null,he=!1;for(let je=0;je<O.length;je++){let at=O[je];if(he){he=!1;continue}if(at==="\\"&&ee!=="'"){he=!0;continue}if(at===ee){ee=null;continue}if(ee===null&&(at==="'"||at==='"')){ee=at;continue}if(ee!==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&&Ib(O.slice(lt.start+1,je))?{kind:"range",start:lt.start,end:je+1}:void 0;if(ct&&(!Q||ct.start<Q.start))Q=ct}if(!Q||Q.kind==="range")return Q;return{kind:Q.kind,start:Q.start,end:Q.end,alternatives:Tb(O,Q)}}function Ab(O,D){return D.alternatives.map((B)=>`${O.slice(0,D.start)}${B}${O.slice(D.end)}`)}function Tb(O,D){let B=[D.start,...D.commas,D.end-1];return B.slice(0,-1).map((Q,ee)=>O.slice(Q+1,B[ee+1]))}function Ib(O){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(O)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(O)}function hd(O,D){let B=`x${O}`,Q=qa(B,0,B.length,{maxInputLength:B.length,maxWords:1,maxDepth:D},{used:0,max:1},0);if(Q.limited||Q.issues.length>0||Q.next!==B.length||Q.word.provenance!=="literal")return null;return Q.word.text.slice(1)}function kb(O,D,B,Q){return ln({kind:"program",dialect:"posix",source:O.slice(D,B),span:{start:D,end:B},status:"limited",issues:[{code:Q,message:"command structure exceeds parser limit"}],nodes:[]})}function Hr(O,D,B,Q,ee){return{nodes:O,issues:[...D,{code:Q,message:`command structure exceeds parser limit ${ee}`}],next:B,closed:!1,limited:!0,pendingHeredocs:[]}}function Ni(O,D,B){return{nodes:O,issues:D,next:B,closed:!1,limited:!0,pendingHeredocs:[]}}function Va(O){return O.used++,O.used<=O.max}function Ob(O,D,B){let Q=O.slice(D,B),ee=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(Q)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(Q),he=ee?.[1];if(!ee||!he)return;return{name:he,braceIndex:D+ee[0].lastIndexOf("{")}}function wo(O){return O.some((D)=>{if(D.kind==="command")return D.redirections.some((B)=>B.heredoc)||D.nested.some((B)=>wo(B.nodes));return(D.kind==="group"||D.kind==="function")&&wo(D.body.nodes)})}function Mb(O){return O.map((D)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${D.delimiter} was not found`}))}function yd(O){return O?.kind==="command"||O?.kind==="group"||O?.kind==="function"}function ad(O,D){let B=O.at(-1);if(B?.kind!=="connector"||!ld.has(B.operator))return;D.push({code:"missing-command-after-connector",message:`connector ${B.operator} requires a following command`})}function Ka(O,D){if(!yd(O.at(-1)))return;D.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function Db(O,D,B){return D===B||/[\s;&|()]/u.test(O[D-1]??"")}var Sd=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),Nb=new Set(["gc","cat","type","cp","mv","rm"]),Cd=["-rec","-for","-path","-literalpath","-whatif"],Lb=/^\$env:\w/i,Wb=/^(?:\$\{?\w+\}?|~)\\./;function vd(O,D){let B=O.toLowerCase().replaceAll("`","");if(![...Sd].some((ee)=>B.includes(ee))&&!(B.includes("rm")&&Cd.some((ee)=>B.includes(ee)))&&!B.includes("<#")&&!Gb(B))return!1;let Q=Qa(O,D);if(Ed(Q))return!1;return Q.issues.some((ee)=>ee.code==="unclosed-block-comment"||ee.code==="comment-depth-limit")||Ja(Q).some(Fb)}function Ed(O){return O.nodes.some((D)=>{if(D.kind==="group")return Ed(D.body);if(D.kind!=="command")return!1;return D.redirections.some((B)=>B.operator==="<<")})}function Gb(O){if(O.includes("$env:"))return!0;return O.includes("\\")&&(O.includes("$")||O.includes("~"))}function Fb(O){let D=O[0]==="&"||O[0]==="."?1:0,B=O[D]?.toLowerCase();if(B&&Sd.has(B))return!0;let Q=O.slice(D+1);if(B&&Nb.has(B)&&Q.some(zb))return!0;if(B!=="rm")return!1;return Q.some((ee)=>{let he=ee.toLowerCase().split(":",1)[0]??"";return Cd.some((je)=>he.startsWith(je))})}function zb(O){return Lb.test(O)||Wb.test(O)}function Qa(O,D){let B={start:0,end:O.length};if(O.length>D.maxInputLength)return ln({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 Q=el(O,0,O.length,D,0);return ln({kind:"program",dialect:"powershell",source:O,span:B,status:jb(Q.issues,Q.limited),issues:Q.issues,nodes:Q.nodes})}function el(O,D,B,Q,ee,he=!1){let je=[],at=[],lt=ki(),ct=0,ut=!1,ft=()=>{if(lt.words.length===0&<.redirections.length===0)return;let mt={start:lt.start,end:lt.end};Oi(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(" ")})},dt=D;while(dt<B){let mt=O[dt];if(!mt)break;if(he&&mt==="}")return ft(),{nodes:je,issues:at,next:dt+1,closed:!0,words:ct,limited:ut};let pt=Hb(O,dt,B,Q.maxDepth);if(pt){if(pt.issue)at.push(pt.issue);if(pt.limited)return ft(),{nodes:je,issues:at,next:pt.next,closed:!1,words:ct,limited:!0};dt=pt.next;continue}if(/\s/.test(mt)){if(mt==="\r"||mt===`
|
|
20
|
+
`){ft();let yt=mt==="\r"&&O[dt+1]===`
|
|
21
|
+
`?dt+2:dt+1;je.push(Za(O,dt,yt)),dt=yt;continue}dt++;continue}let gt=_d(O,dt);if(gt){ft(),je.push(Za(O,dt,dt+gt.length)),dt+=gt.length;continue}if(mt==="{"){if(ft(),ee>=Q.maxDepth)return at.push(Rd(Q.maxDepth)),{nodes:je,issues:at,next:B,closed:!1,words:ct,limited:!0};let yt=el(O,dt+1,B,Q,ee+1,!0),Ct=yt.closed?yt.next-1:yt.next,Et=ln({kind:"program",dialect:"powershell",source:O.slice(dt+1,Ct),span:{start:dt+1,end:Ct},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:dt,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,ut||=yt.limited,dt=yt.next;continue}if(mt==="}"){ft(),je.push(Za(O,dt,dt+1)),dt++;continue}if(mt===">"||mt==="<"){lt.start=lt.start===-1?dt:lt.start;let yt=O[dt+1]===mt?dt+2:dt+1,Ct=yt;while(/[ \t]/.test(O[Ct]??""))Ct++;let Et=Ct<B?bd(O,Ct,B,Q,ee):void 0,vt=Et?.next??yt;if(lt.redirections.push(Object.freeze({kind:"redirection",operator:O.slice(dt,yt),span:Object.freeze({start:dt,end:vt}),...Et?{target:Et.word}:{}})),Et)at.push(...Et.issues),lt.nested.push(...Et.nested),ct+=Et.words,ut||=Et.limited;lt.end=vt,dt=vt;continue}if(mt===","){lt.start=lt.start===-1?dt:lt.start,lt.words.push(Ua({text:",",raw:",",span:{start:dt,end:dt+1},provenance:"literal",quoted:!1})),lt.end=++dt;continue}let ht=bd(O,dt,B,Q,ee);if(lt.start=lt.start===-1?dt:lt.start,lt.end=ht.next,lt.words.push(ht.word),at.push(...ht.issues),lt.nested.push(...ht.nested),ct+=1+ht.words,ut||=ht.limited,ct>Q.maxWords)return at.push({code:"word-limit",message:`command exceeds ${Q.maxWords} words`}),ft(),{nodes:je,issues:at,next:ht.next,closed:!1,words:ct,limited:!0};dt=ht.next>dt?ht.next:dt+1}return ft(),{nodes:je,issues:at,next:dt,closed:!he,words:ct,limited:ut}}function bd(O,D,B,Q,ee){let he="",je="literal",at=!1,lt=[],ct=[],ut=0,ft=!1,dt=(pt)=>{let gt=Bb(O,pt,B,Q,ee);return he+=O.slice(pt,gt.next),ct.push(gt.program),lt.push(...gt.program.issues),ut+=Xa(gt.program),ft||=gt.program.status==="limited",je="command-substitution",gt.next},mt=D;while(mt<B){let pt=O[mt];if(!pt||/\s/.test(pt)||_d(O,mt)||pt===">"||pt==="<"||pt==="#")break;if(pt===",")break;if(pt==="`"){let gt=O[mt+1];if(!gt){lt.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),mt++;break}he+=gt,mt+=2;continue}if(O.startsWith("$(",mt)){mt=dt(mt);continue}if(pt==="'"){at=!0,mt++;let gt=!1;while(mt<O.length){if(O[mt]==="'"&&O[mt+1]==="'"){he+="'",mt+=2;continue}if(O[mt]==="'"){gt=!0,mt++;break}he+=O[mt]??"",mt++}if(!gt)lt.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(pt==='"'){at=!0,mt++;let gt=!1;while(mt<B){let ht=O[mt];if(ht==="`"&&O[mt+1]){he+=O[mt+1],mt+=2;continue}if(ht==='"'){gt=!0,mt++;break}if(O.startsWith("$(",mt)){mt=dt(mt);continue}if(ht==="$")je=O[mt+1]==="("?"command-substitution":"variable";he+=ht??"",mt++}if(!gt)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:Ur(O,D,mt,he,je,at,je==="literal"?void 0:$b(O,D,mt)),next:mt,issues:lt,nested:ct,words:ut,limited:ft}}function Bb(O,D,B,Q,ee){let he=xd(O,D+2,B),je=he===-1?B:he,at=he===-1?B:he+1;if(ee>=Q.maxDepth)return{program:ln({kind:"program",dialect:"powershell",source:O.slice(D+2,je),span:{start:D+2,end:je},status:"limited",issues:[Rd(Q.maxDepth)],nodes:[]}),next:at};let lt=el(O,D+2,je,Q,ee+1),ct=he===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:ln({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 xd(O,D,B){let Q=1,ee=!1,he=!1;for(let je=D;je<B;je++){let at=O[je];if(at==="`"){je++;continue}if(!he&&at==="'"){if(ee&&O[je+1]==="'"){je++;continue}ee=!ee;continue}if(!ee&&at==='"'){he=!he;continue}if(ee)continue;if(O.startsWith("$(",je)){Q++,je++;continue}if(!he&&at==="(")Q++;if(at!==")")continue;if(Q--,Q===0)return je}return-1}function Xa(O){let D=0;for(let B of O.nodes){if(B.kind==="group")D+=Xa(B.body);if(B.kind==="command"){D+=B.words.length;for(let Q of B.nested)D+=Xa(Q)}}return D}function $b(O,D,B){let Q=Mi(O),ee=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=xd(O,je+2,B),ct=lt===-1?B:lt+1;Q.push(ee,je,"literal"),Q.push(je,ct,"command-substitution"),je=ct,ee=ct;continue}if(at==="$"||at==="@"&&je===D){let lt=Ub(O,je+1,B);Q.push(ee,je,"literal"),Q.push(je,lt,"variable"),je=lt,ee=lt;continue}je++}return Q.push(ee,B,"literal"),Q.parts}function Ub(O,D,B){if(O[D]==="{"){let ee=O.indexOf("}",D+1);return ee===-1||ee>=B?B:ee+1}let Q=D;while(Q<B&&/[A-Za-z0-9_:?]/.test(O[Q]??""))Q++;return Q}function Rd(O){return{code:"depth-limit",message:`command structure exceeds parser limit ${O}`}}function Ja(O){return O.nodes.flatMap((D)=>{if(D.kind==="group")return Ja(D.body);if(D.kind!=="command")return[];return[[...D.words,...D.redirections.flatMap((B)=>B.target?[B.target]:[])].sort((B,Q)=>B.span.start-Q.span.start).filter((B)=>B.text!==""&&B.raw!==",").map((B)=>B.text),...D.nested.flatMap(Ja)]})}function _d(O,D){for(let B of["&&","||",";","|"])if(O.startsWith(B,D))return B;return null}function Hb(O,D,B,Q){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 ee=1,he=D+2;while(he<B){if(O.startsWith("<#",he)){if(ee++,ee>Q)return{next:B,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${Q}`},limited:!0};he+=2;continue}if(O.startsWith("#>",he)){if(ee--,he+=2,ee===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 jb(O,D){if(D)return"limited";if(O.some((B)=>B.code==="unclosed-block-comment"))return"invalid";return O.length>0?"partial":"complete"}function Za(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=tr){if(D==="powershell"||D==="auto"&&vd(O.slice(0,B.maxInputLength),B))return Qa(O,B);return cd(O,B)}function t(O){return O.provenance==="command-substitution"?O.raw:O.text}function X(O,D){return O==="posix"?D:$t(D.map((B)=>B.text))}function Bi(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 tl(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 Po(O,D,B=1){if(O)O.units=Math.min(Number.MAX_SAFE_INTEGER,O.units+D.length*B)}function bn(O,D){Po(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 nl(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 Q=0;Q<B.length;Q++)if(bt(O,D+Q)!==B[Q])return!1;return!0}function Un(O,D,B){return!br(bt(O,D-1))&&Bt(O,D,B)&&!br(bt(O,D+B.length))}function Hn(O,D){return br(bt(O,D-1))!==br(bt(O,D))}function Qt(O){return O===`
|
|
24
|
+
`||O===";"||O==="&"||O==="|"}function jr(O){return O==="|"||O===";"}function $i(O,D,B){let Q=tl(O,B);if(D==="rm")return Vb(Q);if(D==="dd")return qb(Q);return kd(Q,!0)}function Ui(O,D,B){let Q=tl(O,B);if(D==="rm")return Yb(Q);if(D==="reset-hard")return Td(Q,"--ha","rd");if(D==="reset-merge")return Td(Q,"--me","rge");if(D==="clean")return Qb(Q);if(D==="checkout")return tS(Q);if(D==="push-force")return nS(Q);if(D==="push-refspec")return rS(Q);if(D==="push-delete")return oS(Q);if(D==="branch")return iS(Q);if(D==="tag")return lS(Q);if(D==="restore")return cS(Q);return kd(Q,!1)}function Vb(O){let D=!1,B=!1,Q=!1,ee=-1;for(let he=0;he<=Ht(O);he++){let je=bt(O,he);if(!D){let lt=bt(O,he+2);if(Un(O,he,"rm")&&zt(lt)&<!==`
|
|
25
|
+
`)D=!0,he++;continue}let at=Kb(O,he);if(je===`
|
|
26
|
+
`||at!==-1){if(D=!1,B=!1,Q=!1,ee=-1,at!==-1)he=at-1;continue}if(je===";"||je==="&"||je==="|"||he===Ht(O)){if(ee>=0){let lt=wd(O,ee,he);B||=lt.recursive,Q||=lt.force}if(B&&Q)return!0;D=!1,B=!1,Q=!1,ee=-1;continue}if(zt(je)){if(ee<0)continue;if(Bt(O,ee,"--")&&he-ee===2){D=!1,B=!1,Q=!1,ee=-1;continue}let lt=wd(O,ee,he);if(B||=lt.recursive,Q||=lt.force,B&&Q)return!0;ee=-1;continue}if(ee<0)ee=he}return!1}function Kb(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 wd(O,D,B){if(Pd(O,D,B,"recursive"))return{recursive:!0,force:!1};if(Pd(O,D,B,"force"))return{recursive:!1,force:!0};if(bt(O,D)!=="-"||bt(O,D+1)==="-")return{recursive:!1,force:!1};let Q=!1,ee=!1;for(let he=D+1;he<B;he++){let je=bt(O,he);Q||=je==="r"||je==="R",ee||=je==="f"||je==="F"}return{recursive:Q,force:ee}}function Pd(O,D,B,Q){let ee=B-D-2;if(ee<1||ee>Q.length||!Bt(O,D,"--"))return!1;for(let he=0;he<ee;he++)if(bt(O,D+he+2)!==Q[he])return!1;return!0}function qb(O){let D=!1;for(let B=0;B<Ht(O);B++){if(Qt(bt(O,B))){D=!1;continue}if(Un(O,B,"dd")){D=!0,B++;continue}if(!D||!Un(O,B,"of")||!Bt(O,B,"of=/dev/"))continue;let Q=B+8;if(Q<Ht(O)&&!zt(bt(O,Q))&&bt(O,Q)!=="'"&&bt(O,Q)!=='"')return!0}return!1}function Yb(O){let D=!1,B=!1,Q=!1;for(let ee=0;ee<=Ht(O);){let he=bt(O,ee);if(ee===Ht(O)||Qt(he)){D=!1,B=!1,Q=!1,ee++;continue}let je=Xb(O,ee);if(je>=0){if(Zb(O,je))return!0;let at=je,lt=!1;while(zt(bt(O,at)))lt||=bt(O,at)===`
|
|
27
|
+
`,at++;if(lt)B=!1,Q=!1;D=!0,ee=at;continue}if(!D){ee++;continue}if(Bt(O,ee,"--")&&(ee===0||zt(bt(O,ee-1)))&&(!bt(O,ee+2)||zt(bt(O,ee+2))||Qt(bt(O,ee+2)))){D=!1,B=!1,Q=!1,ee+=2;continue}if(B||=Bt(O,ee,"--recursive")&&Hn(O,ee+11)||rl(O,ee,"recursive"),Q||=Bt(O,ee,"--force")&&Hn(O,ee+7)||rl(O,ee,"force"),B&&Q)return!0;ee++}return!1}function rl(O,D,B){if(!Bt(O,D,"--"))return!1;let Q=0;while(Q<=B.length){let ee=bt(O,D+Q+2);if(!ee||zt(ee)||Qt(ee))break;if(ee!==B[Q])return!1;Q++}return Q>0&&Hn(O,D+Q+2)}function Zb(O,D){let B=D,Q=!1,ee=!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=Ad(O,he,"recursive"),at=Ad(O,he,"force");if(Q&&at||ee&&je)return!0;if(Q||=je,ee||=at,bt(O,he+1)==="-")continue;let lt=Jb(O,he,B);if(lt.combined||Q&<.forceAtBoundary||ee&<.recursiveAtBoundary)return!0;Q||=lt.recursive,ee||=lt.force}return!1}function Ad(O,D,B){return Bt(O,D,`--${B}`)&&Hn(O,D+B.length+2)||rl(O,D,B)}function Xb(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 Jb(O,D,B){let Q=!1,ee=!1,he=!1,je=!1,at=!1;if(bt(O,D)!=="-")return{recursive:Q,force:ee,recursiveAtBoundary:he,forceAtBoundary:je,combined:at};let lt="";for(let ct=D+1;ct<B;ct++){let ut=bt(O,ct)??"",ft=(ut==="r"||ut==="f")&&Hn(O,ct+1);Q||=ut==="r",ee||=ut==="f",he||=ut==="r"&&ft,je||=ut==="f"&&ft,at||=(lt==="r"&&ut==="f"||lt==="f"&&ut==="r")&&ft,lt=ut}return{recursive:Q,force:ee,recursiveAtBoundary:he,forceAtBoundary:je,combined:at}}function Td(O,D,B){return To(O,"reset",jr,!0,(Q)=>bt(O,Q)==="-"&&Vr(O,Q,D,B)?!0:Q)}function Qb(O){return To(O,"clean",jr,!0,(D)=>{if(bt(O,D)!=="-")return D;if(Vr(O,D,"--fo","rce"))return!0;let B=Ao(O,D,jr);for(let Q=D+1;Q<B;Q++)if(bt(O,Q)==="f")return!0;return B-1})}function Hi(O,D,B){if(!Un(O,D,"git"))return null;let Q=D+3;if(!zt(bt(O,Q)))return{commandEnd:-1,next:Q};while(zt(bt(O,Q)))Q++;while(Q<Ht(O)){if(Qt(bt(O,Q)))return{commandEnd:-1,next:Q};let ee=Ao(O,Q,Qt);if(Un(O,Q,B))return{commandEnd:Q+B.length,next:ee};if(bt(O,Q)!=="-")return{commandEnd:-1,next:ee};let he=ee-Q===2&&Bt(O,Q,"--"),je=eS(O,Q,ee);Q=ee;while(zt(bt(O,Q)))Q++;if(he)return{commandEnd:Un(O,Q,B)?Q+B.length:-1,next:Ao(O,Q,Qt)};if(!je)continue;if(Q>=Ht(O)||Qt(bt(O,Q)))return{commandEnd:-1,next:Q};Q=Ao(O,Q,Qt);while(zt(bt(O,Q)))Q++}return{commandEnd:-1,next:Q}}function eS(O,D,B){for(let Q of gn)if(B-D===Q.length&&Bt(O,D,Q))return!0;return!1}function tS(O){return Id(O,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function nS(O){return To(O,"push",jr,!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=Od(O,D,"--fo","rce");if(B>=0&&!Bt(O,B,"-with-lease"))return!0;return D})}function rS(O){return To(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 oS(O){return To(O,"push",Qt,!1,(D)=>{if(bt(O,D)==="-"&&Vr(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 iS(O){let D=!1,B=!1,Q=!1;for(let ee=0;ee<=Ht(O);ee++){if(ee===Ht(O)||Qt(bt(O,ee))){if(B&&Q)return!0;D=!1,B=!1,Q=!1;continue}if(!D){let at=Hi(O,ee,"branch");if(at){D=at.commandEnd>=0,ee=Math.max(ee,(D?at.commandEnd:at.next)-1);continue}}if(!D||bt(O,ee)!=="-")continue;let he=Ao(O,ee,Qt),je=sS(O,ee,he);if(B||=je.deletion,Q||=je.force,B&&Q)return!0;ee=he-1}return!1}function sS(O,D,B){let Q=!1,ee=!1;for(let he=D;he<B;he++){if(bt(O,he)!=="-")continue;if(Vr(O,he,"--de","lete"))Q=!0;if(Vr(O,he,"--fo","rce"))ee=!0;if(bt(O,he+1)==="-")continue;let je=he+1,at=!1,lt=!1,ct=!1;while(je<B&&aS(bt(O,je))){let ut=bt(O,je);at||=ut==="d"||ut==="D",lt||=ut==="f",ct||=ut==="D",je++}if(!Hn(O,je))continue;Q||=at,ee||=lt||ct}return{deletion:Q,force:ee}}function aS(O){if(!O)return!1;let D=O.charCodeAt(0);return D>=65&&D<=90||D>=97&&D<=122}function lS(O){return Id(O,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function Id(O,D){let B=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let Q=0;Q<Ht(O);Q++){let ee=bt(O,Q),he=B[B.length-1];if(!he)return!1;let je=he.escaped;if(he.escaped=!je&&he.quote!=="'"&&ee==="\\",!je&&ee==="'"&&he.quote!=='"')he.quote=he.quote==="'"?"":"'";if(!je&&ee==='"'&&he.quote!=="'")he.quote=he.quote==='"'?"":'"';if(ee==="$"&&bt(O,Q+1)==="("&&(B.length===1||!je&&he.quote!=="'")){B.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),Q++;continue}if(!je&&!he.quote&&B.length>1&&ee==="("){he.depth++;continue}if(!je&&!he.quote&&B.length>1&&ee===")"){if(he.depth--,he.depth===0)B.pop();continue}if(zt(ee))he.shortActive=!1,he.hasShortFlag=!1;if(!he.outerActive){let at=Hi(O,Q,D.command);if(at){he.outerActive=at.commandEnd>=0&&zt(bt(O,at.commandEnd)),he.shortActive=!1,he.hasShortFlag=!1,Q=Math.max(Q,(he.outerActive?at.commandEnd:at.next)-1);continue}}if(he.outerActive&&ee==="-"){if(Vr(O,Q,D.longPrefix,D.longOptional))return!0;he.shortActive||=!D.excludedShortStarts.includes(bt(O,Q+1)??"")}if(he.hasShortFlag||=he.shortActive&&ee===D.shortFlag,he.hasShortFlag&&Hn(O,Q+1))return!0;if(jr(ee))he.outerActive=!1}return!1}function To(O,D,B,Q,ee){let he=!1;for(let je=0;je<Ht(O);je++){let at=bt(O,je),lt=B(at);if(!he&&!lt){let ct=Hi(O,je,D);if(ct){he=ct.commandEnd>=0&&(!Q||zt(bt(O,ct.commandEnd))),je=Math.max(je,(he?ct.commandEnd:ct.next)-1);continue}}if(he){let ct=ee(je);if(ct===!0)return!0;for(let ut=je;ut<=ct;ut++)if(B(bt(O,ut)))he=!1;je=ct}if(lt)he=!1}return!1}function cS(O){let D=!1;for(let B=0;B<Ht(O);B++){if(nl(bt(O,B))){if(D)return!0;D=!1;continue}if(!D){let Q=Hi(O,B,"restore");if(Q){D=Q.commandEnd>=0,B=Math.max(B,(D?Q.commandEnd:Q.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 kd(O,D){let B=!1;for(let Q=0;Q<Ht(O);Q++){let ee=bt(O,Q),he=D?nl(ee):Qt(ee);if(B&&zt(ee)&&bt(O,Q+1)==="-"&&Un(O,Q+2,"delete"))return!0;if(he){B=!1;continue}if(Un(O,Q,"find"))B=!0,Q+=3}return!1}function Ao(O,D,B){let Q=D;while(Q<Ht(O)&&!zt(bt(O,Q))&&!B(bt(O,Q)))Q++;return Q}function Od(O,D,B,Q){if(!Bt(O,D,B))return-1;let ee=D+B.length;for(let he=0;he<Q.length&&bt(O,ee)===Q[he];he++)ee++;return Hn(O,ee)?ee:-1}function Vr(O,D,B,Q){return Od(O,D,B,Q)>=0}function xn(O,D){Po(D,O,2);let B=O.toLowerCase(),Q=B.trimStart(),ee=Q.startsWith("echo ")||Q.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&&ee)continue;let at=je.caseSensitive?O:B;if(je.regex)bn(D,at);if((je.regex?.test(at)??!1)||je.scan&&Ui(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 uS=/^[A-Za-z_][A-Za-z0-9_]*=/;function Dd(O,D,B){let Q=O.words[0];if(!D||!Q||O.words.length!==1||O.dialect!=="posix")return!1;if(!Q.quoted||Q.provenance!=="literal")return!1;let ee=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(Q.text)?.[1];if(!ee)return!1;Po(B,D.source,2);let he={anchored:new RegExp(`^\\$\\{?${ee}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${ee}(?![A-Za-z0-9_])`)};return Nd(D.nodes,Q,he)}function Nd(O,D,B){return O.every((Q)=>{if(Q.kind==="connector")return!0;if(Q.kind==="group"||Q.kind==="function")return Nd(Q.body.nodes,D,B);if(Q.kind==="unknown")return!B.loose.test(Q.source);return dS(Q,D,B)})}function dS(O,D,B){if(O.nested.some((ee)=>B.loose.test(ee.source)))return!1;let Q=O.words.findIndex((ee)=>!uS.test(ee.text));return O.words.every((ee,he)=>ee===D||Md(ee.raw,B.anchored,he!==Q))&&O.redirections.every((ee)=>(!ee.heredoc||ee.heredoc.quotedDelimiter||!B.loose.test(ee.heredoc.body))&&(!ee.target||Md(ee.target.raw,B.anchored,!0)))}function Md(O,D,B){let Q=!1,ee=!1;for(let he=0;he<O.length;he++){let je=O[he];if(je==="\\"&&!Q){he++;continue}if(!ee&&je==="'"){Q=!Q;continue}if(!Q&&je==='"'){ee=!ee;continue}if(Q||je!=="$")continue;if(!D.test(O.slice(he)))continue;if(!ee||!B)return!1}return!0}import{isAbsolute as fS,resolve as Ld}from"node:path";function Io(O,D,B,Q){let ee=fS(O)?Ld(O):D?Ld(D,O):void 0;if(!ee)return;try{return Wt(ee,B,Q)}catch{return ee}}function Wd(O){return!["/dev","/proc","/sys"].some((D)=>O===D||O.startsWith(`${D}/`))}var Kr="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",ko="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.",il=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),mS=new Set(["-p","--print"]),pS=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),gS=new Map([["python",new Set(["W","X"])],["node",new Set(["C","r"])],["ruby",new Set(["C","E","F","I","r"])],["perl",new Set(["F","I","M","m"])]]),hS=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),yS=new Map([["python",new Set(["m"])]]),bS=new Map([["node",new Set(["--allow-fs-read","--allow-fs-write","--conditions","--cpu-prof-dir","--cpu-prof-interval","--cpu-prof-name","--debug-port","--diagnostic-dir","--disable-proto","--disable-warning","--dns-result-order","--env-file","--env-file-if-exists","--experimental-package-map","--experimental-test-isolation","--experimental-test-tag-filter","--heap-prof-dir","--heap-prof-interval","--heap-prof-name","--heapsnapshot-near-heap-limit","--heapsnapshot-signal","--icu-data-dir","--input-type","--inspect-port","--inspect-publish-uid","--localstorage-file","--max-http-header-size","--max-old-space-size-percentage","--network-family-autoselection-attempt-timeout","--openssl-config","--redirect-warnings","--report-dir","--report-directory","--report-filename","--report-signal","--secure-heap","--secure-heap-min","--test-concurrency","--test-coverage-branches","--test-coverage-exclude","--test-coverage-functions","--test-coverage-include","--test-coverage-lines","--test-global-setup","--test-isolation","--test-name-pattern","--test-random-seed","--test-reporter","--test-reporter-destination","--test-rerun-failures","--test-shard","--test-skip-pattern","--test-timeout","--title","--tls-cipher-list","--tls-keylog","--trace-event-categories","--trace-event-file-pattern","--trace-require-module","--unhandled-rejections","--use-largepages","--v8-pool-size","--watch-kill-signal"])],["python",new Set(["--check-hash-based-pycs"])],["ruby",new Set(["--backtrace-limit","--crash-report","--disable","--enable","--encoding","--external-encoding","--internal-encoding","--parser"])]]),SS=new Set(["always","default","never"]),CS=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),vS=/\\\r?\n/g,ES=new Map([["python",[{selector:"-c",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-m",kind:"module-file",valueForm:"attached-or-separate"}]],["node",[{selector:"-e",kind:"inline-code",valueForm:"separate-only"},{selector:"--eval",kind:"inline-code",valueForm:"equals-or-separate"},{selector:"-p",kind:"inline-code",valueForm:"separate-only"},{selector:"--print",kind:"inline-code",valueForm:"separate-only"},{selector:"-r",kind:"module-file",valueForm:"separate-only"},{selector:"--require",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--import",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--loader",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--experimental-loader",kind:"module-file",valueForm:"equals-or-separate"}]],["ruby",[{selector:"-e",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-r",kind:"module-file",valueForm:"attached-or-separate"}]],["perl",[{selector:"-e",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-E",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-M",kind:"module-file",valueForm:"attached-only"},{selector:"-m",kind:"module-file",valueForm:"attached-only"}]]]);function Gd(O){return Vi(O).code}function ji(O){return Vi(O).sources}function Fd(O){return ES.get(al(O))??[]}function Vi(O){let D=al(O[0]??"");if(!il.has(D))return{code:null,sources:[],optionsOpen:!1};let B=[],Q=[],ee=!0;for(let he=1;he<O.length;he++){let je=O[he];if(je===void 0)break;if(je==="--")return Tn(D,B,Q,ee,O[he+1]===void 0?void 0:he+1,O[he+1]);if(je===""||je==="-"||!je.startsWith("-"))return Tn(D,B,Q,ee,he,je);if(D==="node"&&mS.has(je)){let ft=O[he+1];if(ft===void 0)return Tn(D,B,Q,ee);if(ft.startsWith("-"))continue;B.push({tokenIndex:he+1,value:ft}),Q.push({tokenIndex:he+1,kind:"inline-code",value:ft}),he++;continue}if(RS(D,je)){let ft=O[he+1];if(ft===void 0)return Tn(D,B,Q,ee);if(B.push({tokenIndex:he+1,value:ft}),Q.push({tokenIndex:he+1,kind:"inline-code",value:ft}),D==="python")return Tn(D,B,Q,ee);he++;continue}let at=/^--eval=(.*)$/s.exec(je);if(_S(D)&&at){let ft=at[1]??"";B.push({tokenIndex:he,value:ft}),Q.push({tokenIndex:he,kind:"inline-code",value:ft});continue}if(D==="node"){let ft=xS(je);if(ft){if(ft.attached){if(ee&&=ft.value!=="",ft.value!=="")Q.push({tokenIndex:he,kind:"module-file",value:ft.value});continue}let dt=O[he+1];if(dt===void 0||dt.startsWith("-"))return ee=!1,Tn(D,B,Q,ee);Q.push({tokenIndex:he+1,kind:"module-file",value:dt}),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 Tn(D,B,Q,ee);if(bS.get(D)?.has(je)){let ft=O[he+1];if(ft===void 0||ft.startsWith("-")&&!(D==="ruby"&&CS.has(je))||D==="python"&&!SS.has(ft))return Tn(D,B,Q,ee);he++;continue}if(je.startsWith("--"))continue;let lt,ct=!1;for(let ft=1;ft<je.length;ft++){let dt=je[ft];if(dt===void 0)break;if(yS.get(D)?.has(dt)){let mt=je.slice(ft+1),pt=mt||O[he+1];if(pt!==void 0)Q.push({tokenIndex:mt?he:he+1,kind:"module-file",value:pt});return Tn(D,B,Q,ee)}if(pS.get(D)?.has(dt)){lt=je.slice(ft+1)||O[he+1],ct=ft+1===je.length;break}if(D==="node"&&dt==="r"){if(ee&&=je==="-r",je==="-r"){let mt=O[he+1];if(ee&&=mt!==void 0&&!mt.startsWith("-"),ee&&mt!==void 0)Q.push({tokenIndex:he+1,kind:"module-file",value:mt});he++}break}if(D==="ruby"&&dt==="r"){let mt=je.slice(ft+1),pt=mt||O[he+1];if(ee&&=pt!==void 0,pt!==void 0)Q.push({tokenIndex:mt?he:he+1,kind:"module-file",value:pt});if(!mt)he++;break}if(D==="perl"&&(dt==="M"||dt==="m")){let mt=je.slice(ft+1);if(!mt){if(ee=!1,ft+1===je.length)he++;break}Q.push({tokenIndex:he,kind:"module-file",value:mt});break}if(gS.get(D)?.has(dt)){if(ft+1===je.length)he++;break}if(hS.get(D)?.has(dt)&&ft+1<je.length)break}if(lt===void 0)continue;let ut=ct?he+1:he;if(B.push({tokenIndex:ut,value:lt}),Q.push({tokenIndex:ut,kind:"inline-code",value:lt}),D==="python")return Tn(D,B,Q,ee);if(ct)he++}return Tn(D,B,Q,ee,void 0,void 0,!0)}function Tn(O,D,B,Q,ee,he,je=!1){let at=O==="node"?D.slice(-1):D,lt=new Set(at.map((ut)=>ut.tokenIndex)),ct=B.filter((ut)=>ut.kind!=="inline-code"||lt.has(ut.tokenIndex));if(Q&&D.length===0&&ee!==void 0&&he!==void 0)ct.push({tokenIndex:ee,kind:"main-script",value:he});return{code:(O==="node"?at[0]?.value:at.map((ut)=>ut.value).join(`
|
|
28
|
+
`))||null,sources:Q?ct:[],optionsOpen:Q&&je}}function xS(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 sl(O,D){return al(O)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(D)}function al(O){let D=Tt(O).toLowerCase();return yi.test(D)?"python":D}function RS(O,D){return il.get(O)?.has(D)??!1}function _S(O){return il.get(O)?.has("--eval")??!1}function Oo(O,D,B=!1){let Q=AS(O,D);if(!ol(Q,D))return!1;bn(D,Q);let ee=PS(Q);if(ol(ee,D))return!0;if(bn(D,ee),!zd.test(ee))return!1;return!B||wS(Q,D)}function wS(O,D){if(/`|%x|\bqx\b/.test(O))return!0;let B=O.split(""),Q=[];for(let je=0;je<O.length;je++){let at=O[je];if(at!=="'"&&at!=='"')continue;let lt=O.startsWith(at.repeat(3),je)?at.repeat(3):at,ct=je+lt.length,ut=ct;while(ut<O.length&&!O.startsWith(lt,ut))ut+=O[ut]==="\\"?2:1;if(ut>=O.length)return!0;Q.push({start:ct,text:O.slice(ct,ut)}),B.fill(" ",je,ut+lt.length),je=ut+lt.length-1}let ee=B.join(""),he=Array.from(ee.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((je)=>zd.test(je[1]??"")).map((je)=>{let at=je.index+je[0].length;return{start:at,end:ll(ee,at)}});if(he.some((je)=>cl(ee,je.start)))return!0;return Q.some((je)=>(/\b(?:system|exec|spawn|popen)\s*$/.test(ee.slice(0,je.start))||he.some((at)=>je.start>=at.start&&je.start<at.end))&&ol(je.text,D))}function ll(O,D){let B=1;for(let Q=D;Q<O.length;Q++){if(O[Q]==="(")B++;if(O[Q]===")")B--;if(B===0)return Q}return O.length}function cl(O,D){let B=0;for(let Q=D;Q<O.length;Q++){let ee=O[Q]??"";if("([{".includes(ee))B++;if(")]}".includes(ee)&&B--===0)return!1;if(ee===","&&B===0)return!1;if(/[A-Za-z_$]/.test(ee))return!0}return!1}var zd=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function PS(O){let D=[],B=0,Q=0;while(Q<O.length){let ee=O[Q];if(ee!=="'"&&ee!=='"'){Q++;continue}let he=O.startsWith(ee.repeat(3),Q)?ee.repeat(3):ee,je=Q+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,Q)," "),Q=je+he.length,B=Q}return D.push(O.slice(B)),D.join("")}function ol(O,D){if($i(O,"rm",D))return!0;for(let Q of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(bn(D,O),Q.test(O))return!0;if($i(O,"dd",D))return!0;for(let Q of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(bn(D,O),Q.test(O))return!0;if($i(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((Q)=>(bn(D,O),B.some((ee)=>Ui(ee,Q))))}function AS(O,D){return bn(D,O),O.replace(vS,"")}import{isAbsolute as mf,relative as pf}from"node:path";import{isAbsolute as Kd,parse as GS}from"node:path";import{dirname as TS,isAbsolute as IS,parse as kS,sep as OS}from"node:path";function nr(O,D,B){if(Qn(D))throw Error("Unsupported Windows namespace path");let Q=IS(D)?kS(D).root:"",ee=Q||O;for(let he of DS(Q?D.slice(Q.length):D)){if(he===""||he===".")continue;if(he===".."){ee=TS(ee);continue}let je=MS(ee,he),at=B.entryKind(je),lt=at==="symlink"?B.realpath(je):je;if(at==="missing"||lt===null)throw Error(`Cannot resolve path component: ${je}`);ee=lt}return ee}function MS(O,D){return O.endsWith("/")||O.endsWith("\\")?`${O}${D}`:`${O}${OS}${D}`}function DS(O){let D=process.platform==="win32"?/[\\/]+/:/\/+/;return O.split(D)}var ul=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],NS=new Set(ul),LS=1024,Bd=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),$d=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),WS=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function Ki(O){return NS.has(O)}function dl(O){return Ki(O)||Bd.has(O)||$d.has(O)||mo(O)}function jn(O,D,B){return B?.has(O)?B.get(O):D.get(O)}function Ud(O,D){let B=jn("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 Q=Number(B);return Number.isSafeInteger(Q)&&Q<=LS?{state:"valid",count:Q}:{state:"invalid"}}function qi(O,D,B){let ee=O.match(WS)?.[1];if(!ee||!dl(ee))return null;let he=O.indexOf("=");return{name:ee,value:`${jn(ee,D,B)??""}${O.slice(he+1)}`}}function Hd(O){return Vd(O,$d)}function jd(O){return Vd(O,Bd)}function Vd(O,D){if(!O)return!1;for(let B of O.keys())if(D.has(B))return!0;return!1}var Yd=/^[A-Za-z_][A-Za-z0-9_]*=/;function Rn(O){if(!Yd.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 Q=O[B];if(!Q)break;let ee=Rn(t(Q));if(!ee)break;D.set(ee.name,ee.value),B++}return{words:O.slice(B),envAssignments:D}}function Zd(O){let D=It(O);return O.includes("=")||D==="sudo"||D==="env"||D==="command"||D==="builtin"}function Sr(O,D,B,Q){if(!Zd(qr(O)))return{words:O,envAssignments:new Map,cwd:B,rewritten:!1};let ee=new Set(O),he=O,je=new Map,at=new Map(Q??[]),lt=[],ct=B;for(let ft=0;ft<a.wrapperPeelIterations.cap;ft++){let dt=qd(he),mt=ge(he);for(let[gt,ht]of mt.envAssignments)je.set(gt,ht),at.set(gt,ht);if(he=mt.words,he.length===0)break;while(he.length>0&&qr(he).includes("=")&&!zS(he)){let gt=BS(qr(he),at,D.env)??qi(qr(he),D.env,at);if(gt)je.set(gt.name,gt.value),at.set(gt.name,gt.value);he=he.slice(1)}if(he.length===0)break;let pt=It(qr(he));if(pt!=="sudo"&&pt!=="env"&&pt!=="command"&&pt!=="builtin")break;if(pt==="sudo"){let gt=US(he,D.paths,ct);if(he=gt.words,gt.cwd!==void 0)ct=gt.cwd}if(pt==="env"){let gt=VS(he,ct,at,D);if(lt.push(...gt.envSplitValues??[]),he=gt.words,gt.cwd!==void 0)ct=gt.cwd;for(let[ht,yt]of gt.envAssignments)je.set(ht,yt),at.set(ht,yt)}if(pt==="command")he=KS(he);if(pt==="builtin")he=he.slice(In(he,1)==="--"?2:1);if(qd(he)===dt)break}let ut=ge(he);for(let[ft,dt]of ut.envAssignments)je.set(ft,dt),at.set(ft,dt);return{words:ut.words,envAssignments:je,cwd:ct,envSplitValues:lt.length>0?lt:void 0,rewritten:FS(ut.words,ee)}}function FS(O,D){return O.some((B)=>!D.has(B))}function qd(O){return O.map(t).join(" ")}function qr(O){let D=O[0];return D?t(D):""}function In(O,D){let B=O[D];return B?t(B):void 0}function zS(O){return Yd.test(qr(O))}function BS(O,D,B){if(!O.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${D.get("TMPDIR")??B.get("TMPDIR")??""}${O.slice(8)}`}}var $S=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function US(O,D,B){let Q=1,ee=B;while(Q<O.length){let he=In(O,Q);if(!he)break;if(he==="--")return{words:O.slice(Q+1),cwd:ee};if(!he.startsWith("-"))break;if(he==="-D"||he==="--chdir"){let je=In(O,Q+1);ee=je?Mo(ee,je,D):null,Q+=2;continue}if(he.startsWith("--chdir=")){ee=Mo(ee,he.slice(8),D),Q++;continue}if(he.startsWith("-D")&&he.length>2){ee=Mo(ee,he.slice(2),D),Q++;continue}if(he==="-i"||he==="--login"){ee=null,Q++;continue}if($S.has(he)){Q+=2;continue}Q++}return{words:O.slice(Q),cwd:ee}}var HS=new Set(["-i","-0","--null"]),jS=new Set(["-u","--unset","-C","--chdir","-P"]);function VS(O,D,B,Q){let ee=new Map,he=[],je=D,at=1,lt=(ct)=>({words:O.slice(ct),envAssignments:ee,cwd:je,envSplitValues:he.length>0?he:void 0});while(at<O.length){let ct=In(O,at);if(!ct)break;if(ct==="--")return lt(at+1);if(ct==="-i"||ct==="--ignore-environment"||ct==="-"){ee.clear();for(let ft of B.keys())ee.set(ft,"");ee.set("TMPDIR",""),at++;continue}if(HS.has(ct)){at++;continue}if(ct==="-u"||ct==="--unset"){let ft=In(O,at+1);if(ft!==void 0)ee.set(ft,"");at+=2;continue}if(ct.startsWith("-u")&&ct.length>2&&!ct.startsWith("-u=")){ee.set(ct.slice(2),""),at++;continue}if(ct.startsWith("--unset=")){ee.set(ct.slice(8),""),at++;continue}let ut=ct==="-S"||ct==="--split-string"?{value:In(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(ut){if(ut.value!==void 0)he.push(ut.value);return je=null,lt(at+ut.consumed)}if(jS.has(ct)){if(ct==="-C"||ct==="--chdir"){let ft=In(O,at+1);je=ft?Mo(je,ft,Q.paths):null}at+=2;continue}if(ct.startsWith("-u=")){at++;continue}if(ct.startsWith("-C")&&ct.length>2||ct.startsWith("--chdir=")){let ft=ct.startsWith("--chdir=")?ct.slice(8):ct.startsWith("-C=")?ct.slice(3):ct.slice(2);je=Mo(je,ft,Q.paths),at++;continue}if(ct.startsWith("-P")){at++;continue}if(ct.startsWith("-")){at++;continue}if(!Rn(ct))break;while(at<O.length){let ft=Rn(In(O,at)??"");if(!ft)break;ee.set(ft.name,ft.value),at++}if(In(O,at)==="--")at++;return lt(at)}return lt(at)}function Mo(O,D,B){if(D==="")return null;if(!O&&!Kd(D))return null;let Q=Kd(D)?GS(D).root:B.realpath(O??"/");if(Q===null)return null;try{return nr(Q,D,B)}catch{return null}}function KS(O){if(In(O,1)==="-v")return[...$t(["type"]),...O.slice(2)];let D=1;while(D<O.length){let B=In(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 qS=/['"\\$`{}#]/;function Yi(O,D){if(O.some((Q)=>qS.test(Q)))return null;let B=[...O.flatMap((Q)=>Q.split(/\s+/).filter((ee)=>ee.length>0)),...D];return B.length<=64?B:null}function rr(O,D,B){return Zi(O,D,B).tokens}function YS(O){let D=[],B="",Q=0;while(Q<O.length){let ee=O.charAt(Q);if(ee==='"'||ee==="'"){let he=O.indexOf(ee,Q+1);if(he===-1)return O.split(/\s+/).map((je)=>je.replace(/["']/g,"")).filter((je)=>je.length>0);B+=O.slice(Q+1,he),Q=he+1;continue}if(/\s/.test(ee)){if(B.length>0)D.push(B);B="",Q++;continue}B+=ee,Q++}if(B.length>0)D.push(B);return D}function Cr(O,D,B,Q=0){let ee=Zi(O,D,B),he=(ee.envSplitValues??[]).flatMap(YS);if(he.length===0)return ee.tokens;let je=[...he,...ee.tokens];if(Q>=8)return je;return Cr(je,D,B,Q+1)}function Zi(O,D,B,Q){if(!Zd(O[0]??""))return{tokens:[...O],envAssignments:new Map,cwd:B};let ee=Sr($t(O),D,B,Q);return{tokens:ee.words.map(t),envAssignments:ee.envAssignments,cwd:ee.cwd,envSplitValues:ee.envSplitValues}}var gl=Symbol("adopt-as-operand"),ZS=new Set(["env","sudo","command","builtin"]),XS=new Set(["&&","||","|&","|","&",";"]),JS=new Set(["<<","<<<",">|"]),QS=new Set(["|","|&"]),eC=/[*@#?$!_-]/,tC=/^\w+(?::\w+)*/,nC=Object.freeze([]),Do=Object.freeze({kind:"scope",edge:"enter"}),No=Object.freeze({kind:"scope",edge:"exit"}),rC=Object.freeze([]),oC=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),Lo=new Set(["bash","sh","zsh","dash","ksh"]),iC=256,tf=new WeakMap;function nf(O,D){let B=D.status==="complete"?new Set(pl(D)):new Set,Q=lC(O,B);if(Si(Q))return Xi("unclosed-quote",Q,D);let ee={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},he=vr(D,{source:Q,suppressed:B,flags:ee,depth:0,functions:new Map,powershell:D.dialect==="powershell"});if(ee.limited)return Xi("structural-limit",Q,D);if(ee.invalid)return Xi("invalid",Q,D);let je=Xi("complete",Q,D,ee.assignmentFallbacks);return tf.set(je,Object.freeze(he)),je}function Qi(O,D,B,Q,ee){let he=ee.word??((ft)=>ft),je={cwd:D,variables:new Map,previous:null},at=[],lt=new Set,ct=null,ut=[];for(let ft of rf(O)){if(ft.kind==="scope"){if(ft.edge==="enter"){ut.push({state:je,segment:[...at],shellWords:new Set(lt),pipeProducer:ct});continue}let dt=ee.segment(at,je,ct,null,lt);if(dt)return dt;let mt=ut.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(ft.kind==="operator"){if(!ft.boundary)continue;let dt=ee.segment(at,je,ct,ft.operator,lt);if(dt)return dt;je=sC(at,je,B,Q),ct=at.length>0&&QS.has(ft.operator)?at:null,at=[],lt=new Set;continue}if(ft.kind==="redirection"){if(ft.fd!==void 0)lt.add(at.length-1);if(ft.target===void 0)continue;let dt=ee.redirection({operator:ft.operator,role:ft.role,targetOrder:ft.targetOrder,target:ft.target,...ft.body===void 0?{}:{body:ft.body,consumer:ft.consumer}},je);if(dt===gl){lt.add(at.length),at.push(he(ft.target));continue}if(dt)return dt;continue}at.push(he(ft.text))}return ee.segment(at,je,ct,null,lt)}function es(O){return rf(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 cn(O,D){return O.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(B,Q,ee,he)=>{let je=D.get(Q);if(je===void 0)return B;let at=ee.startsWith(":")?je!=="":!0;if(ee.endsWith("-"))return at?je:cn(he,D);return at?cn(he,D):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(B,Q)=>D.get(Q)??B).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(B,Q)=>D.get(Q)??B)}function Wo(O){return O.length>0&&O.every((D)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(D))}function sC(O,D,B,Q){let ee=Wo(O)?new Map([...D.variables,...aC(O,D.variables)]):D.variables,he=rr([...O],B),je=Tt(he[0]??"").toLowerCase()==="cd"?he[1]:void 0;if(!je)return{...D,variables:ee};if(je==="-"){if(D.previous===null)return{...D,variables:ee};return{cwd:D.previous,variables:ee,previous:D.cwd}}return{cwd:tn(cn(je,ee),D.cwd,B,Q),variables:ee,previous:D.cwd}}function aC(O,D){return O.flatMap((B)=>{let Q=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(B),ee=Q?.[2]?.startsWith("=")?Q[2].slice(1):void 0;return Q?.[1]!==void 0&&ee!==void 0?[[Q[1],cn(ee,D)]]:[]})}function rf(O){return tf.get(O)??nC}function lC(O,D){return[...D].reduce((B,Q)=>B.slice(0,Q.start)+" ".repeat(Q.end-Q.start)+B.slice(Q.end),O)}function Xi(O,D,B,Q=rC){return Object.freeze({status:O,source:D,program:B,assignmentFallbacks:Object.freeze(Q)})}function vr(O,D){return O.nodes.flatMap((B,Q)=>cC(B,O,Q,D)).sort((B,Q)=>B.start-Q.start).flatMap((B)=>[...B.events])}function cC(O,D,B,Q){if(O.kind==="connector")return[{start:O.span.start,events:[kn(pC(O.operator))]}];if(O.kind==="unknown")return[{start:O.span.start,events:[kn(O.source)]}];if(O.kind==="function")return Q.functions.set(O.name,O.body),[];if(O.kind==="group"){let he=O.style!=="subshell",je=Q.source[O.span.end-1]===(he?"}":")"),at=he?Q:{...Q,functions:new Map(Q.functions)};return[{start:O.span.start,events:he?[Ji("{"),...vr(O.body,at),...je?[Ji("}")]:[]]:[Do,kn("("),...vr(O.body,at),...je?[kn(")")]:[],No]}]}let ee=bC(O,Q.functions);if(ee){if(Q.depth>=tr.maxDepth||++Q.flags.expansions>iC)return Q.flags.limited=!0,[];return[{start:O.span.start,events:[...Xd(O,Q),Ji(";"),...vr(ee,{...Q,depth:Q.depth+1}),Ji(";")]},...Jd(O,D,B,Q)]}return[{start:O.span.start,events:Xd(O,Q)},...Jd(O,D,B,Q)]}function Xd(O,D){return[...O.words.map((B)=>({start:B.span.start,events:sf(B,O,D,!1)})),...O.redirections.map((B)=>({start:B.span.start,events:uC(B,O,D)}))].sort((B,Q)=>B.start-Q.start).flatMap((B)=>B.events)}function uC(O,D,B){let Q=O.operator==="<<-"?"<<":O.operator,ee=O.target?sf(O.target,D,B,!0):[],he=ee[0],je=he?.kind==="word"?he.text:void 0;return[...O.fd===void 0?[]:[hl(String(O.fd))],Object.freeze({kind:"redirection",operator:Q,...O.fd===void 0?{}:{fd:O.fd},role:gC(Q),targetOrder:JS.has(Q)?"legacy-segment":"immediate",...je===void 0?{}:{target:je},...O.heredoc&&B.suppressed.has(O.heredoc.bodySpan)?{body:O.heredoc.body,consumer:lf(D)}:{}}),...je===void 0?ee:ee.slice(1)]}function Jd(O,D,B,Q){let ee=O.redirections.filter((he)=>he.operator==="<<"||he.operator==="<<-");return[...ee.flatMap((he)=>{let je=he.heredoc;if(!je)return[];let at=[hl(je.delimiter),.../[\r\n]/.test(Q.source[je.terminatorSpan.end]??"")?[kn(";")]:[]];if(Q.suppressed.has(je.bodySpan))return[{start:je.bodySpan.start,events:at}];return[{start:je.bodySpan.start,events:[...of(Q.source.slice(je.bodySpan.start,je.bodySpan.end),Q),...at]}]}),...ee.some((he)=>!he.heredoc&&he.target)?dC(D,B,Q):[]]}function dC(O,D,B){let Q=O.nodes.slice(D+1).find((ee)=>ee.kind==="connector");if(!Q||Q.span.end>=O.span.end)return[];return[{start:Q.span.end,events:of(B.source.slice(Q.span.end,O.span.end),B)}]}function of(O,D){if(D.depth>=tr.maxDepth)return D.flags.limited=!0,[];let B=h(O,"posix");if(B.status==="limited")return D.flags.limited=!0,[];let Q={invalid:!1,limited:!1,expansions:D.flags.expansions,assignmentFallbacks:D.flags.assignmentFallbacks},ee=vr(B,{source:O,suppressed:new Set,flags:Q,depth:D.depth+1,functions:new Map,powershell:!1});return D.flags.limited||=Q.limited,D.flags.expansions=Q.expansions,ee}function sf(O,D,B,Q){let ee=[],he={single:!1,double:!1},je="",at=!1,lt=()=>{let ct=at&&!Q?kn("glob"):je!==""||O.quoted&&ee.length===0?hl(je):void 0;if(ct)ee.push(ct);je="",at=!1};for(let ct of O.parts){if(ct.provenance!=="command-substitution"&&ct.provenance!=="arithmetic"){for(let mt of fl(ct.raw,he,B.flags,B.powershell)){if(typeof mt==="string"){lt(),ee.push(kn(mt));continue}je+=mt.text,at||=mt.glob}continue}let ut=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+=fl(mt,{single:!1,double:!0},B.flags,B.powershell).map((gt)=>typeof gt==="string"?gt:gt.text).join("");let pt=ut?vr(ut,B).filter((gt)=>gt.kind==="redirection"&>.body!==void 0):[];if(pt.length>0)ee.push(Do,...pt,No);continue}let ft=ut?vr(ut,B):[];if(ct.raw.startsWith("`")){je+="${}",lt(),ee.push(Do,...ft,No);continue}if(ct.raw.startsWith("<(")||ct.raw.startsWith(">(")){lt(),ee.push(ct.raw.startsWith("<(")?kn("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),Do,...ft,...ct.raw.endsWith(")")?[kn(")")]:[],No);continue}let dt=ct.raw.startsWith("$((")?2:1;je+="${}",lt(),ee.push(...Array.from({length:dt},()=>kn("(")),...dt===1?[Do]:[],...ft,...ct.raw.endsWith(")".repeat(dt))?Array.from({length:dt},()=>kn(")")):[],...dt===1?[No]:[])}return lt(),ee}function fl(O,D,B,Q){let ee=[],he="",je=!1,at=0;while(at<O.length){let lt=O[at]??"";if(!D.single&&!D.double&&(lt==="("||lt===")")){ee.push({text:he,glob:je},lt),he="",je=!1,at++;continue}if(Q&<==="`"&&!D.single){he+=O[at+1]??"",at+=2;continue}if(D.single&<==="'"){D.single=!1,at++;continue}if(D.single){he+=lt,at++;continue}if(D.double){if(lt==='"'){D.double=!1,at++;continue}if(!Q&<==="\\"){let ct=O[at+1]??"";he+=['"',"\\","$"].includes(ct)?ct:`\\${ct}`,at+=2;continue}if(lt==="$"){let ct=Qd(O,at,D,B,Q);he+=ct.text,at=ct.next;continue}he+=lt,at++;continue}if(lt==="'"||lt==='"'){D.single=lt==="'",D.double=lt==='"',at++;continue}if(!Q&<==="\\"){let ct=O[at+1]??"";je||=ct==="*"||ct==="?",he+=ct,at+=2;continue}if(lt==="$"){let ct=Qd(O,at,D,B,Q);he+=ct.text,at=ct.next;continue}je||=lt==="*"||lt==="?",he+=lt,at++}return[...ee,{text:he,glob:je}]}function Qd(O,D,B,Q,ee){let he=O[D+1];if(he==="{"){let at=mC(O,D+2);if(at===-1)return Q.invalid=!0,{text:"",next:O.length};let lt=O.slice(D,at+1);return fC(lt,B,Q,ee),{text:lt,next:at+1}}if(he!==void 0&&eC.test(he))return{text:`\${${he}}`,next:D+2};let je=(ee?tC:/^\w*/).exec(O.slice(D+1))?.[0]??"";return{text:`\${${je}}`,next:D+1+je.length}}function fC(O,D,B,Q){let ee=O.slice(2,-1),he=/^[A-Za-z_][A-Za-z0-9_]*/.exec(ee)?.[0];if(!he)return;let je=ee.slice(he.length),at=[":=","="].find((ct)=>je.startsWith(ct));if(!at)return;let lt=fl(je.slice(at.length),{...D},B,Q);B.assignmentFallbacks.push(...lt.flatMap((ct)=>typeof ct==="string"||!ct.text?[]:[ct.text]))}function mC(O,D){let B=1,Q=D;while(B>0&&Q<O.length){if(O[Q]==="{"&&O[Q-1]==="$")B++;if(O[Q]==="}")B--;Q++}return B===0?Q-1:-1}function pC(O){return/^[\r\n]+$/.test(O)?";":O}function kn(O){return Object.freeze({kind:"operator",operator:O,boundary:XS.has(O)})}function Ji(O){return Object.freeze({kind:"operator",operator:O,boundary:!0})}function hl(O){return Object.freeze({kind:"word",text:O})}function gC(O){if(O==="<<"||O==="<<<")return"here-data";if(O==="<"||O==="<&")return"file-read";return"file-write"}function Go(O){return oC.has(O)||/^python\d/.test(O)}var hC=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 af(O,D){let B=D[0];if(B===void 0||!B.startsWith("-"))return D;let Q=hC.get(O)?.has(B)??!1;return af(O,D.slice(Q?2:1))}function ml(O){let D=O[0];if(D===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(D))return ml(O.slice(1));if(!ZS.has(D))return[...O];return ml(af(D,O.slice(1)))}function lf(O){let D=Ro(O),B=O.words.findIndex((Q)=>Q.provenance==="literal"&&Q.text===D);return ml(B<0?[]:O.words.slice(B).map((Q)=>Q.text))}function yC(O){let D=lf(O)[0];if(D===void 0)return!1;let B=Tt(D).toLowerCase();return Go(B)&&!Lo.has(B)}function pl(O){return O.nodes.flatMap((D,B)=>{if(D.kind==="group"||D.kind==="function")return pl(D.body);if(D.kind!=="command")return[];let Q=D.nested.flatMap((at)=>pl(at)),ee=D.redirections.flatMap((at)=>at.heredoc?.quotedDelimiter?[at.heredoc.bodySpan]:[]);if(yC(D))return[...Q,...ee];let he=O.nodes[B+1];if(he?.kind==="connector"&&(he.operator==="|"||he.operator==="|&")||!CC(D))return Q;return[...Q,...ee]})}function bC(O,D){let B=Ro(O);return B===void 0?void 0:D.get(B)}function or(O,D){return O!==void 0&&O.provenance==="literal"&&!O.quoted&&O.raw===O.text&&O.text===D}function SC(O){if(or(O.words[0],"git"))return or(O.words[1],"commit");if(!or(O.words[0],"gh")||!or(O.words[2],"create"))return!1;return or(O.words[1],"pr")||or(O.words[1],"issue")}function CC(O){return(or(O.words[0],"cat")||or(O.words[0],"tee")||SC(O))&&!O.words.some(ef)&&!O.redirections.some((B)=>ef(B.target))}function ef(O){return O?.parts.some((D)=>D.provenance==="command-substitution"&&D.raw.startsWith(">("))??!1}var cf=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),uf=new Set([...cf,"glob"]),vC=new Set([...uf,"pattern"]);class y extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Fo(O){let D=EC(),B=ne(O.input),Q=[];if((O.route.kind==="command"||O.route.kind==="unknown")&&B)Q.push({usage:"input-candidate",source:B});if(O.route.kind==="command"&&"command"in O&&O.command)Q.push({usage:"declared-command",source:O.command});let ee=Q.reduce((he,je)=>{let at=he.findIndex((ut)=>ut.source===je.source);if(at!==-1){let ut=he[at];if(!ut)return he;return he[at]={...ut,usages:[...ut.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:ee,paths:xC(O),store:D}}function un(O,D){return O.commands.find((B)=>B.usages.includes(D))}function Vn(O,D){if(!O.includes("$"))return O;return Xs(O,D)}function EC(){let O=new Map,D=new Map,B=new WeakMap,Q=(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??Q(he,"posix");if(at.status==="limited"){let ut=B.get(at);if(ut)return ut;let ft={status:"structural-limit",source:he,program:at,assignmentFallbacks:[]};return B.set(at,ft),ft}let lt=O.get(he);if(lt)return lt;let ct=nf(he,at);return O.set(he,ct),ct},getCommandProgram:Q}}function xC(O){let D=O.route.kind==="grep"?uf:O.route.kind==="glob"?vC:cf;return[...qc(O.input,D),...O.route.kind==="patch"?Xc(O.input):[]]}var RC=new Set(["-S","--suffix"]);function Yr(O,D,B,Q,ee){if(O.status==="structural-limit")throw new y;if(O.status!=="complete")return ee.findMalformedTarget(O.source);return Qi(O,D,B,Q,{segment:(he,je)=>ee.findSegmentTarget(he,je),redirection:(he,je)=>he.role==="file-write"&&ee.isRedirectionTarget(cn(he.target,je.variables),je)?he.target:null})}function ts(O){let D=[],B=null,Q=!1;for(let ee=0;ee<O.length;ee++){let he=O[ee];if(he===void 0)break;if(!Q&&he==="--"){Q=!0;continue}if(!Q&&(he==="-t"||he==="--target-directory")){B=O[++ee]??null;continue}if(!Q&&he.startsWith("--target-directory=")){B=he.slice(19);continue}if(!Q&&he.startsWith("-t")&&he.length>2){B=he.slice(2);continue}if(!Q&&RC.has(he)){ee++;continue}if(!Q&&(he.startsWith("--suffix=")||he.startsWith("--backup=")))continue;if(!Q&&he.startsWith("-"))continue;D.push(he)}return B?{sources:D,destination:B}:{sources:D.slice(0,-1),destination:D.at(-1)??null}}var x="Git metadata and hooks are protected. Ask the user before modifying them.";function gf(O,D,B,Q){let ee=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(ui(O.invocation.toolName))return null;let at=O.paths.find((lt)=>df(lt,ee,D,B,Q,D.entries));return at?{target:at}:null}if(O.invocation.route.kind!=="command")return null;let he=un(O,"input-candidate");if(!he)return null;let je=Yr(he.shell,ee,B,Q,{findSegmentTarget:(at,lt)=>AC(at,lt,D,B,Q),isRedirectionTarget:(at,lt)=>df(at,lt.cwd,D,B,Q,D.markerFiles),findMalformedTarget:()=>null});return je?{target:je}:null}function Er(O,D,B,Q,ee,he,je=!1){if(!B)return!1;let at=rs(tn(O,D,ee,he)),lt=at.replace(/(\/\.?\*+)+$/,"");if(lt!==at&<!==""){if(yl(lt,B))return!0;let ct=je||at.slice(lt.length).includes("/."),ut=(ft)=>ct?ns(ft,lt):_C(ft,lt);if(B.markerFiles.some(ut))return!0;return Q&&ff(B).some(ut)}if(yl(at,B))return!0;return Q&&ff(B).some((ct)=>ns(ct,at))}function _C(O,D){let B=pf(D,O);if(B===""||B.startsWith("..")||mf(B))return!1;return!B.split(/[\\/]/)[0]?.startsWith(".")}function wC(O,D,B,Q,ee){return Er(O,D,B,!0,Q,ee)}function PC(O,D,B,Q,ee){if(!B)return!1;return yl(rs(tn(O,D,Q,ee)),B)}function df(O,D,B,Q,ee,he){let je=rs(tn(O,D,Q,ee));return he.includes(je)||yf(je,B)}function hf(O,D,B,Q,ee){if(!B)return!1;return B.hooksDirectories.some((he)=>O.some((je)=>ns(he,rs(tn(je,D,Q,ee)))))}function yl(O,D){return D.entries.includes(O)||D.directories.includes(O)||yf(O,D)}function yf(O,D){return D.hooksDirectories.some((B)=>ns(O,B))}function ff(O){return[...O.entries,...O.directories,...O.hooksDirectories]}function ns(O,D){let B=pf(D,O);return B===""||!/^\.\.(?:[\\/]|$)/.test(B)&&!mf(B)}function rs(O){return process.platform==="win32"?O.toLowerCase():O}function AC(O,D,B,Q,ee){if(Wo(O))return null;let he=Cr([...O],Q);if(Tt(he[0]??"").toLowerCase()!=="mv")return null;let je=ts(he.slice(1)),at=je.sources.find((lt)=>wC(cn(lt,D.variables),D.cwd,B,Q,ee));if(at)return at;return je.destination&&PC(cn(je.destination,D.variables),D.cwd,B,Q,ee)?je.destination:null}import{isAbsolute as ls,normalize as LC,parse as WC,posix as _f,resolve as Rr,sep as vl}from"node:path";import{isAbsolute as TC,join as bf,normalize as vf,parse as IC,sep as Sf}from"node:path";var kC=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],OC=`
|
|
29
|
+
`;function zo(O,D){if(ir(O,D))return!0;if(!O.has("TMPDIR"))return!1;return!bl(O.get("TMPDIR")??"",D)}function xr(O,D){if(O.has("TMPDIR"))return bl(O.get("TMPDIR")??"",D);let B=Sl(O,D);if(B===void 0)return!0;return bl(B,D)}function Sl(O,D){return xf(O,D,"TMPDIR")}function bl(O,D){if(!O)return!1;if(DC(O))return!1;return Zr(O,D)}function ir(O,D){let B=xf(O,D,"IFS");return B!==void 0&&B!==""&&B!==OC}function Zr(O,D){let B=os(O,D.paths);if(B===null)return!1;return Ef(D).some((Q)=>as(B,Q))}function ss(O,D){let B=os(O,D.paths);if(B===null)return!1;return Ef(D).some((Q)=>is(Q)===is(B))}var Cf=new WeakMap;function Ef(O){let D=Cf.get(O);if(D)return D;let B=MC(O);return Cf.set(O,B),B}function MC(O){let D=kC.map((Q)=>os(Q,O.paths)??vf(Q)),B=os(O.tmpdir,O.paths);if(!B)return D;if(process.platform==="win32")return[...D,B];if(process.platform==="darwin"&&NC(B))return[...D,B];return D}function DC(O){return/[\s$`*?[]/.test(O)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(O)||/[+@!]\([^)]*\)/.test(O)}function xf(O,D,B){return O.has(B)?O.get(B):D.env.get(B)}function NC(O){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(O)}function os(O,D){try{let B=vf(O);if(!TC(B))return B;let Q=IC(B).root,ee=B.slice(Q.length).split(/[\\/]+/).filter(Boolean),he=Q;for(let je=0;je<ee.length;je++){let at=bf(he,ee[je]??"");if(D.entryKind(at)==="missing")return bf(at,...ee.slice(je+1));let lt=D.realpath(at);if(lt===null)return null;he=lt}return he}catch{return null}}function as(O,D){let B=is(O),Q=is(D);if(B===Q)return!0;let ee=Q.endsWith(Sf)?Q:`${Q}${Sf}`;return B.startsWith(ee)}function is(O){return process.platform==="win32"?O.toLowerCase():O}var GC=process.platform==="win32",Rf=64,FC=16384;function Bo(O,D,B,Q){if(O.kind==="temp_target")return null;let ee=Q[O.kind];if(O.kind==="dynamic_target"&&!Jt(B,ee.id,D.strict))return null;if(O.kind==="within_anchored_cwd"&&!Jt(B,ee.id,D.paranoid))return null;return St(ee.id,ee.reason)}function $o(O){let D=pd(O,Rf,Rf,FC);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:zC(O)}}function zC(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)=>BC(O.raw,B.span.start-O.span.start))}function BC(O,D){let B=null,Q=!1;for(let ee=0;ee<D;ee++){let he=O[ee];if(Q){Q=!1;continue}if(he==="\\"&&B!=="'"){Q=!0;continue}if(B===he){B=null;continue}if(B===null&&(he==="'"||he==='"'))B=he}return B==='"'}function _r(O){let D=O.environment.home,B=O.environment.paths,Q=O.budget??mn();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:KC(O.allowPaths,D,B,Q),protectedGitMetadata:O.protectedGitMetadata,budget:Q}}function On(O,D,B={}){let Q=B.targetIsLiteral??!1;if(!Q&&D.tmpdirWordSplittingUnsafe&&!B.tmpdirWordSplittingProtected&&YC(O))return{kind:"outside_anchored_cwd"};let ee=!Q&&Pf(O,D.posixShell);if(Qn(O))return{kind:"outside_anchored_cwd"};if(El(O,Q))return{kind:"root_or_home_target"};if(UC(O,D,Q))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(HC(O,D.trustTmpdirVar,D.posixShell,ee,Q,B.tmpdirWordSplittingProtected??!1,D.trustedTmpdirValue,D.environment))return{kind:"temp_target"};if(ee)return{kind:"dynamic_target"};if(qC(O,D,Q))return{kind:"temp_target"};let he=D.anchoredCwd;if(he){if(!B.skipHomeCwd&&QC(he,D.environment.home,D.environment.paths,D.budget))return{kind:"home_cwd_target"};if(!B.skipCwdSelf&&[D.resolvedCwd??he,he].some((je)=>ev(O,D.resolvedCwd??he,D.environment.paths,D.budget,je)))return{kind:"cwd_self_target"};if(tv(O,he,D.resolvedCwd??he,ee,Q,D.environment.paths,D.budget))return{kind:"within_anchored_cwd"}}if($C(O,D,ee))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function $C(O,D,B){let Q=O.trim();if(B||!D.resolvedCwd||!D.anchoredCwd||!Q)return!1;if(ls(Q)||Q.startsWith("~"))return!1;if(xl(Q))return!1;if(Af(D.resolvedCwd,D.anchoredCwd,D.environment.paths,D.budget))return!1;return Zr(Rr(D.resolvedCwd,Q),D.environment)}function wf(O,D,B={}){let{containmentTarget:Q,...ee}=B;if(On(O,D,ee).kind!=="temp_target")return!1;let he=O.trim();if(VC(he))return!1;if(ss(he,D.environment))return!1;return![D.anchoredCwd,D.resolvedCwd].some((je)=>Af(Q??he,je,D.environment.paths,D.budget))}function El(O,D=!1){let B=O.trim(),Q=_f.normalize(B),ee=B.replace(/\\/g,"/"),he=Q==="/"?Q:Q.replace(/\/+$/,"");if(he==="/"||he.startsWith("/")&&he.slice(1).split("/").every((je)=>/^\*+$/.test(je)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(ee)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(ee))return!0;if(!D&&(Q==="~"||Q==="~/"||Q==="~/*"))return!0;if(!D&&(Q==="$HOME"||Q==="$HOME/"||Q==="$HOME/*"))return!0;if(!D&&(Q==="${HOME}"||Q==="${HOME}/"||Q==="${HOME}/*"))return!0;return!1}function UC(O,D,B){let Q=O.trim(),ee=B?Q:Q==="*"?".":Q.endsWith("/*")?Q.slice(0,-2):Q;if(!ee)return!1;try{let he=ls(ee)?ee:D.resolvedCwd?Rr(D.resolvedCwd,ee):null;if(!he)return!1;let je=dn(Wt(he,D.environment.paths,D.budget));if(je===WC(je).root)return!0;return je===dn(Wt(D.environment.home,D.environment.paths,D.budget))}catch{return!1}}function dn(O){let D=LC(O);if(GC){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 HC(O,D,B,Q,ee,he,je,at){let lt=O.trim();if(xl(lt))return!1;if(!Q&&Zr(lt,at))return!0;return(D||he&&je)&&B&&!ee&&jC(lt,B)}function jC(O,D){return["$TMPDIR","${TMPDIR}"].some((B)=>{if(O===B)return!0;if(!O.startsWith(`${B}/`))return!1;return!Pf(O.slice(B.length+1),D)})}function VC(O){let D=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(O);if(!D)return!1;return _f.normalize(`/${D[1]??""}`)==="/"}function xl(O){return O.split(/[\\/]+/).includes("..")}function KC(O,D,B,Q){if(!O?.length)return[];return O.flatMap((ee)=>{let he=vo(ee.trim(),D);if(!ls(he))return[];try{let je=Wt(he,B,Q);if(Eo(je,Wt(D,B,Q)))return[];return[dn(je)]}catch{return[]}})}function qC(O,D,B){if(D.allowRoots.length===0)return!1;let Q=O.trim();if(xl(Q))return!1;let ee=B?Q:vo(Q,D.environment.home),he=D.resolvedCwd??D.anchoredCwd,je=ls(ee)?ee:he?Rr(he,ee):null;if(!je)return!1;try{let at=dn(Wt(je,D.environment.paths,D.budget));return D.allowRoots.some((lt)=>at===lt||at.startsWith(lt.endsWith(vl)?lt:`${lt}${vl}`))}catch{return!1}}function YC(O){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(O)}function Pf(O,D=!1){return O.includes("$")||O.includes("`")||ZC(O)||D&&XC(O)}function ZC(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 XC(O){let D=!1;for(let B=0;B<O.length;B++){let Q=O[B];if(D){D=!1;continue}if(Q==="\\"){D=!0;continue}if(Q==="{"&&JC(O,B)||(Q==="+"||Q==="@"||Q==="!")&&O[B+1]==="(")return!0}return!1}function JC(O,D){let B=O.indexOf("}",D+1);if(B===-1)return!1;let Q=O.slice(D+1,B);return Q.includes(",")||Q.includes("..")}function QC(O,D,B,Q){try{return dn(Wt(O,B,Q))===dn(Wt(D,B,Q))}catch{try{return dn(O)===dn(D)}catch{return!1}}}function ev(O,D,B,Q,ee=D){if(ee===D&&(O==="."||O==="./"||O===".\\"))return!0;try{return dn(Wt(Rr(D,O),B,Q))===dn(Wt(ee,B,Q))}catch{try{return dn(Rr(D,O))===dn(ee)}catch{return!1}}}function tv(O,D,B,Q,ee,he,je){let at=B??D;if(!ee&&(O.startsWith("~")||O.startsWith("$HOME")||O.startsWith("${HOME}")))return!1;if(Q)return!1;if(O.startsWith("/")||/^[A-Za-z]:[\\/]/.test(O))try{return Cl(O,D,he,je)}catch{return!1}if(O.startsWith("./")||O.startsWith(".\\")||!O.includes("/")&&!O.includes("\\"))try{return Cl(Rr(at,O),D,he,je)}catch{return!1}if(O.startsWith("../"))return!1;try{return Cl(Rr(at,O),D,he,je)}catch{return!1}}function Cl(O,D,B,Q){try{return Tf(Wt(O,B,Q),Wt(D,B,Q))}catch{return!1}}function Af(O,D,B,Q){if(!D)return!1;try{return Tf(Wt(D,B,Q),Wt(O,B,Q))}catch{return!0}}function Tf(O,D){let B=dn(O),Q=dn(D);return B.startsWith(`${Q}${vl}`)||B===Q}var nv=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),If="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",rv="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.",kf="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",Of="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",ov="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",iv="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",sv={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:Of},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:x},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:kf},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:ov},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:If},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:rv},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:If}};function Mf(O,D,B,Q=_r({...B,allowPaths:B.policy?.destructiveCommandAllowPaths})){return av(O.words.map((ee)=>({kind:"word",text:ee.text,dynamic:ee.provenance!=="literal"})),D,Q,B.policy)}function av(O,D,B,Q){let ee=O.filter((lt)=>lt.kind==="word"),he=cv(ee),je=ee[he];if(!je||!nv.has(bv(je.text)))return null;let at=lv(ee.slice(he+1));if(at.whatIfProtected)return null;if(Jt(Q,"powershell.remove-item-pipeline-dynamic-target",B.strict)&&D&&(at.targets.length===0||at.recursive))return St("powershell.remove-item-pipeline-dynamic-target",iv);for(let lt of at.targets)if(!Qn(lt.text)&&El(_l(lt.text)))return St(at.recursive&&at.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Of);for(let lt of at.targets)if(B.resolvedCwd&&Er(_l(lt.text),B.resolvedCwd,B.protectedGitMetadata,at.recursive,B.environment,B.budget,!0))return St("powershell.remove-item-git-metadata",x);if(!at.recursive||!at.force)return null;if(Jt(Q,"powershell.remove-item-recursive-force-dynamic-target",B.strict)&&(at.hasDynamicTarget||at.targets.length===0))return St("powershell.remove-item-recursive-force-dynamic-target",kf);for(let lt of at.targets){let ct=Bo(On(_l(lt.text),B),B,Q,sv);if(ct)return ct}return null}function lv(O){let D=[],B=!1,Q=!1,ee=!1,he=!1,je=!1;for(let at=0;at<O.length;at++){let lt=O[at];if(!lt||lt.kind!=="word")continue;if(uv(lt))continue;if(je){D.push(Rl(lt)),he=he||lt.dynamic;continue}if(lt.text==="--"){je=!0;continue}let ct=fv(lt.text);if(!ct){D.push(Rl(lt)),he=he||lt.dynamic;continue}if(mv(ct.name)){let ut=ct.value?dv(ct.value,lt):O[++at];if(ut?.kind==="word"){D.push(Rl(ut)),he=he||ut.dynamic;continue}he=!0;continue}if(pv(ct.name)){B=!0;continue}if(gv(ct.name)){Q=!0;continue}if(hv(ct.name))ee=yv(ct.value)}return{targets:D,recursive:B,force:Q,whatIfProtected:ee,hasDynamicTarget:he}}function cv(O){let D=O[0];if(D?.kind==="word"&&D.text==="&"||D?.text===".")return O.length>1?1:0;return 0}function Rl(O){return{text:O.kind==="word"?O.text:"",dynamic:O.kind==="word"&&O.dynamic}}function uv(O){return O.kind==="word"&&O.text===","}function _l(O){let D=O.replace(/\\/g,"/"),B=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(D);return B?`$HOME${D.slice(B[0].length)}`:D}function dv(O,D){return{kind:"word",text:O,dynamic:D.kind==="word"&&(D.dynamic||O.includes("$"))}}function fv(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 mv(O){return"path".startsWith(O)||"literalpath".startsWith(O)}function pv(O){return"recurse".startsWith(O)}function gv(O){return O.length>=2&&"force".startsWith(O)}function hv(O){return O==="wi"||"whatif".startsWith(O)}function yv(O){if(O===void 0||O==="")return!0;let D=O.toLowerCase();return D==="$true"||D==="true"}function bv(O){return O.toLowerCase()}var Xr="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",cs="Unsupported heredoc syntax",Uo="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.",Df="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var Sv=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),Cv=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),vv=new Set(["-o","--output","--query","--subscription"]),Ev=new Set;function Nf(O){if(O==="aws")return Sv;if(O==="gcloud")return Cv;if(O==="az")return vv;return Ev}var xv=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),Rv=new Set;function Lf(O){if(O==="git")return gn;if(O==="docker")return xv;return Rv}function _(O,D){if(O.length===0||D.length===0)return null;let B=It(O[0]??""),Q=an(O);for(let ee of D){if(!Pv(B,ee.command))continue;if(ee.match){if(_v(B,O,ee.match))return Wf(ee);continue}if(!Av(B,O,ee.subcommand))continue;if(Iv(O,new Set(ee.block_args),Q))return Wf(ee)}return null}function Wf(O){return{id:`custom.${O.name}`,reason:`[${O.name}] ${O.reason}`,intent:O.intent??"manual_only"}}function _v(O,D,B){let Q=D.slice(1);if(B.exclude_args?.some((ee)=>Q.includes(ee)))return!1;if(B.any_args&&!B.any_args.some((ee)=>Q.includes(ee)))return!1;return wv(Q,B.command_path,Nf(O))}function wv(O,D,B){let Q=0,ee=!1;for(let he of O){if(Q>=D.length)return!0;if(ee){ee=!1;continue}if(he.startsWith("-")){ee=!he.includes("=")&&B.has(he);continue}if(he!==D[Q])return!1;Q++}return Q>=D.length}function Pv(O,D){return O===It(D)}function Av(O,D,B){if(!B)return!0;return Gf(D,1,B,Lf(O))}function Gf(O,D,B,Q){let ee=!1;for(let he=D;he<O.length;he++){let je=O[he];if(!je)continue;if(ee){ee=!1;continue}if(je==="--"){let at=O[he+1];if(at&&!at.startsWith("-"))return at===B;return!1}if(Q.has(je)){ee=!0;continue}if(je.startsWith("-")){if(!je.includes("=")&&Tv(O,he,B,Q))return!0;continue}return je===B}return!1}function Tv(O,D,B,Q){let ee=O[D+1];if(!ee||ee.startsWith("-"))return!1;return Gf(O,D+2,B,Q)}function Iv(O,D,B){return O.some((Q)=>D.has(Q))||[...B].some((Q)=>D.has(Q))}var kv=new Set(["-e","--source"]),Ov=new Set(["-F","-v","--assign","--field-separator"]),Ff=new Set(["-f","--file"]),Mv=new Set(["print","printf","return"]),zf=[{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"}],Dv="Detected awk system(), pipe, or getline command with dynamic command that cannot be safely analyzed. Use a literal command or process the data without system(), pipes, or getline.";function Bf(O,D,B){let Q=!1;for(let ee of Nv(O)){let he=Lv(ee,B);if(!he)continue;for(let je of he.commands){let at=D(je);if(at)return at;if(je.includes("{}")||/[$`]/.test(je))Q=!0}Q||=he.dynamic}return Q?St("awk.system-dynamic",Dv):null}function Pl(O){let D=[],B=!1,Q=!1,ee=!0,he=!0;for(let je=1;je<O.length;je++){let at=O[je];if(at===void 0)break;if(ee&&at==="--"){ee=!1;continue}if(ee&&kv.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(ee&&at.startsWith("--source=")){B=!0,D.push({tokenIndex:je,kind:"inline-code",value:at.slice(9)});continue}if(ee&&at.startsWith("-e")&&at.length>2){B=!0,D.push({tokenIndex:je,kind:"inline-code",value:at.slice(2)});continue}if(ee&&(Ov.has(at)||Ff.has(at))){let lt=O[je+1];if(he&&=lt!==void 0,Ff.has(at)){if(Q=!0,lt!==void 0)D.push({tokenIndex:je+1,kind:"program-file",value:lt})}je++;continue}if(ee&&(at.startsWith("-F")||at.startsWith("-v")&&at.slice(2).includes("=")))continue;if(ee&&at.startsWith("-f")&&at.length>2){Q=!0,D.push({tokenIndex:je,kind:"program-file",value:at.slice(2)});continue}if(ee&&(at.startsWith("--assign=")||at.startsWith("--field-separator=")))continue;if(ee&&at.startsWith("--file=")){Q=!0,D.push({tokenIndex:je,kind:"program-file",value:at.slice(7)});continue}if(ee&&at.startsWith("-")&&at!=="-")continue;if(!B&&!Q)D.push({tokenIndex:je,kind:"main-program",value:at});return{sources:D,optionsOpen:!1}}return{sources:he?D:[],optionsOpen:ee&&he}}function jo(O){return Pl(O).sources}function Nv(O){return jo(O).filter((D)=>D.kind!=="program-file").map((D)=>D.value)}function Lv(O,D){bn(D,O);let B=O.includes("system")?Al(O,D):null,Q=Wv(O,D);if(!B&&!Q)return null;return{dynamic:!!B?.dynamic||!!Q?.dynamic,commands:[...B?.commands??[],...Q?.commands??[]]}}function Al(O,D){bn(D,O);let B=[],Q=!1,ee=!1,he=0;while(he<O.length){let je=O[he];if(je==='"'||je==="'"){he=ds(O,he,je)?.endIndex??he+1;continue}if(je==="#"){he=$f(O,he+1);continue}if(je==="/"&&Uf(O,he)){he=Hf(O,he+1)??he+1;continue}if(!O.startsWith("system",he)){he++;continue}let at=he;if(he+=6,Ho(O[at-1])||Ho(O[he]))continue;let lt=us(O,he);if(O[lt]!=="(")continue;lt=us(O,lt+1);let ct=O[lt];if(ct!=='"'&&ct!=="'"){Q=!0,ee=!0;continue}let ut=ds(O,lt,ct);if(!ut){Q=!0,ee=!0;continue}if(lt=us(O,ut.endIndex),Q=!0,O[lt]!==")"){ee=!0,he=ut.endIndex;continue}B.push(ut.value),he=lt+1}if(!Q)return null;return{dynamic:ee,commands:B}}function Wv(O,D){bn(D,O);let B=[],Q=!1,ee=!1,he=0,je=0,at=null,lt=null,ct=0;while(he<O.length){let ut=O[he];if(!ut)break;if(ut==='"'||ut==="'"){let mt=ds(O,he,ut);if(mt&&ct===je)lt={...mt,startIndex:he};ct=mt?.endIndex??he+1,he=mt?.endIndex??he+1;continue}if(ut==="#"){he=$f(O,he+1),je=he,at=null,lt=null,ct=he;continue}if(ut==="/"&&Uf(O,he)){let mt=Hf(O,he+1);ct=mt??he+1,he=mt??he+1;continue}if(`;
|
|
30
|
+
{}`.includes(ut)){he++,je=he,at=null,lt=null,ct=he;continue}if(at===null&&(wl(O,he,"print")||wl(O,he,"printf")))at=he;if(ut!=="|"||O[he-1]==="|"||O[he+1]==="|"){if(!/\s/.test(ut))ct=he+1;he++;continue}let ft=O[he+1]==="&"?he+2:he+1,dt=us(O,ft);if(wl(O,dt,"getline")){ee=!0;let mt=zv(je,lt,ct);if(Q||=mt===null,mt!==null)B.push(mt);ct=ft,he=ft;continue}if($v(je,at)){ee=!0;let mt=Fv(O,dt);if(!mt){Q=!0,ct=ft,he=ft;continue}if(!Gv(O,mt.endIndex)){Q=!0,ct=mt.endIndex,he=mt.endIndex;continue}B.push(mt.value),ct=mt.endIndex,he=mt.endIndex;continue}ct=ft,he++}if(!ee)return null;return{dynamic:Q,commands:B}}function Ho(O){return!!O&&/[A-Za-z0-9_]/.test(O)}function us(O,D){let B=D;while(/\s/.test(O[B]??""))B++;return B}function Gv(O,D){let B=D;while(/[\t\f\v\r ]/.test(O[B]??""))B++;let Q=O[B];return!Q||`;
|
|
31
|
+
}#`.includes(Q)}function ds(O,D,B){let Q="",ee=!1;for(let he=D+1;he<O.length;he++){let je=O[he];if(!je)break;if(ee){let at=Bv(O,he);if(!at)return null;Q+=at.value,he=at.endIndex,ee=!1;continue}if(je==="\\"){ee=!0;continue}if(je===B)return{value:Q,endIndex:he+1};Q+=je}return null}function Fv(O,D){let B=O[D];if(B!=='"'&&B!=="'")return null;return ds(O,D,B)}function zv(O,D,B){if(!D)return null;return D.startIndex>=O&&D.endIndex===B?D.value:null}function Bv(O,D){let B=O[D];if(!B)return null;if(B==="x"){let ee=O.slice(D+1,D+3);if(!/^[0-9A-Fa-f]{2}$/.test(ee))return null;return{value:String.fromCharCode(Number.parseInt(ee,16)),endIndex:D+2}}if(/[0-7]/.test(B)){let ee=/^[0-7]{1,3}/.exec(O.slice(D));if(!ee)return null;return{value:String.fromCharCode(Number.parseInt(ee[0],8)),endIndex:D+ee[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
|
|
32
|
+
`,r:"\r",t:"\t",v:"\v"}[B]??B,endIndex:D}}function wl(O,D,B){return O.startsWith(B,D)&&!Ho(O[D-1])&&!Ho(O[D+B.length])}function $v(O,D){return D!==null&&D>=O}function $f(O,D){let B=O.indexOf(`
|
|
33
|
+
`,D);return B===-1?O.length:B+1}function Uf(O,D){let B=Uv(O,D);if(B===-1)return!0;if("{([,;!~=".includes(O[B]??""))return!0;let Q=B;while(Ho(O[Q-1]))Q--;return Mv.has(O.slice(Q,B+1))}function Uv(O,D){for(let B=D-1;B>=0;B--)if(!/\s/.test(O[B]??""))return B;return-1}function Hf(O,D){let B=!1;for(let Q=D;Q<O.length;Q++){let ee=O[Q];if(!ee)break;if(B){B=!1;continue}if(ee==="\\"){B=!0;continue}if(ee==="/")return Q+1}return null}var Hv=new Set(["sudo","env","command","builtin"]);function fs(O,D){let B=O[0];if(!B||!D.transparentWrappers.includes(Tt(B)))return null;let Q=Tt(B),ee=O[1]==="--"?2:1,he=jv(O,ee,Q,D),je=he[0];if(je===void 0)return null;return{wrapper:Q,tokens:O.slice(je),childIndex:je,alternativeChildIndices:he.slice(1)}}function jv(O,D,B,Q){let ee=O[1]==="--",he=[];for(let je=D;je<O.length;je++){let at=O[je];if(!at)continue;let lt=Tt(at)!==B&&Vv(at,Q);if(lt)he.push(je);if(!lt&&bi.has(It(at)))break;if(ee)break}return he}function Vv(O,D){let B=Tt(O),Q=It(O);return Q==="git"||B==="busybox"||wr(O)||ya.has(B)||D.transparentWrappers.includes(B)||Kt.has(Q)||O==="$SHELL"||An(Q)||En.has(Q)||D.rules.some((ee)=>ee.command===B)}function wr(O){return Hv.has(O.toLowerCase())}function Pr(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 Mn(O,D){let B=D.policy??{rules:[],transparentWrappers:[]};return ms([...O],D.environment,D.cwd,D.cwd,new Map,new Map(D.envAssignments??[]),B,{iterations:0},!1)}function*ms(O,D,B,Q,ee,he,je,at,lt){let ct=Zi(O,D,B,he);for(let[mt,pt]of ct.envAssignments)he.set(mt,pt),ee.set(mt,pt);let{tokens:ut,cwd:ft}=ct;if(ct.envSplitValues){let mt=Yi(ct.envSplitValues,ut);if(!mt)throw new s("derivedCommandShape");Tl(at),yield*ms(mt,D,ft,Q,ee,he,je,at,lt);return}if(wr(ut[0]??""))throw new s("wrapperPeelIterations");let dt=fs(ut,je);if(dt){for(let mt of[dt.childIndex,...dt.alternativeChildIndices])Tl(at),yield*ms(mt===dt.childIndex?dt.tokens:ut.slice(mt),D,ft,Q,new Map(ee),new Map(he),je,at,!0);return}if(qv(ut)){Tl(at),yield*ms(ut.slice(1),D,ft,Q,ee,he,je,at,lt);return}yield Kv(ut,ft,Q,ee,he,lt)}function Kv(O,D,B,Q,ee,he){return{tokens:O,cwd:D===null?void 0:D??B,wrapperCwd:D,wrapperEnvAssignments:Q,envAssignments:ee,head:Tt(O[0]??"").toLowerCase(),wrappedByTransparent:he}}function Tl(O){if(O.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");O.iterations++}function qv(O){return Tt(O[0]??"").toLowerCase()==="busybox"&&O.length>1}function Il(O,D){let B=[],Q=D;while(Q<O.length){let ee=O[Q];if(ee===void 0||ee===":::")break;B.push(ee),Q++}return{markerIndex:Q<O.length&&O[Q]===":::"?Q:-1,templateTokens:B}}function Dn(O){let D=!1,B=!1;for(let Q of O){if(Q==="--")break;if(Q==="-r"||Q==="-R"||kl(Q,"recursive")){D=!0;continue}if(Q==="-f"||kl(Q,"force")){B=!0;continue}if(Q.startsWith("-")&&!Q.startsWith("--")){if(Q.includes("r")||Q.includes("R"))D=!0;if(Q.includes("f"))B=!0}}return D&&B}function jf(O){let D=O.indexOf("--");return O.slice(1,D===-1?void 0:D).some((B)=>kl(B,"recursive")||/^-[A-Za-z]+$/.test(B)&&/[rR]/.test(B.slice(1)))}function kl(O,D){return O.length>2&&O.startsWith("--")&&D.startsWith(O.slice(2))}var Yv="find -delete permanently removes files. Use -print first to preview.",Zv="find -exec rm -rf is dangerous. Use explicit file list instead.",Xv=new Set(["-exec","-execdir","-ok","-okdir"]),Jv=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 Vf(O,D){let B=O.map(t),Q=Qv(O,B,D);if(Q)return Q;if(gs(B,1)&&!tE(O,B,D)){let je=wt(St("find.delete",Yv),D.policy);if(je)return je}let ee=D.budget??mn(),he=0;while(he<B.length){let je=B[he],at=sr(je??"");if(at>0){he+=at+1;continue}if(!Kn(je)){he++;continue}ee.charge("derivedTokens",B.length-he-1);let lt=Vo(B,he);he=lt.nextIndex;let ct=rE(lt.tokens,D.environment);if(ct){let mt=wt(ct,D.policy);if(mt)return mt}let ut=je==="-execdir"||je==="-okdir",ft=D.analyzeTokens?D.analyzeTokens(lt.tokens,ut?null:D.cwd):D.analyzeNested?D.analyzeNested(lt.tokens.join(" "),{effectiveCwd:ut?void 0:D.cwd,envAssignments:D.envAssignments}):null,dt=ft?.id.startsWith("custom.")?ft:wt(ft,D.policy);if(dt)return dt}return null}function Qv(O,D,B){if(!gs(D,1)&&!Ol(D,B.environment))return null;let ee=ps(O)??$t(["."]),he=_r({...B,allowPaths:B.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let je of ee){let at=$o(je);for(let lt of at.expandedTargets??[t(je)]){let ct=On(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",x)}}if(eE(D)&&he.resolvedCwd&&hf(ee.map(t),he.resolvedCwd,he.protectedGitMetadata,he.environment,he.budget))return St("find.delete-git-metadata",x);return null}function Ol(O,D){let B=0;while(B<O.length){if(!Kn(O[B])){B++;continue}let Q=Vo(O,B),ee=Cr([...Q.tokens],D),he=Tt(ee[0]??"").toLowerCase();if((he==="rm"||he==="rmdir")&&ee.some((je)=>je.includes("{}")))return!0;B=Q.nextIndex}return!1}function eE(O){return O.some((D,B)=>{if(!["-name","-iname"].includes(D))return!1;return O[B+1]?.toLowerCase()==="hooks"})}function tE(O,D,B){if(D.includes("-L")||D.includes("-f")||D.includes("-follow"))return!1;let Q=ps(O);if(!Q)return!1;let ee=B.envAssignments??new Map,he=Sl(ee,B.environment),je=B.trustedTmpdirValue??xr(ee,B.environment),at=B.allowTmpdirVar??!zo(ee,B.environment),lt=_r({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??ir(ee,B.environment),trustedTmpdirValue:je,budget:B.budget});return Q.every((ct)=>{let ut=$o(ct);if(ut.unsafeBraceExpansion)return!1;return(ut.expandedTargets??[t(ct)]).every((ft)=>wf(ft,lt,{containmentTarget:nE(ft,he),targetIsLiteral:ut.expandedTargets!==void 0||ut.targetIsLiteral,tmpdirWordSplittingProtected:ut.tmpdirWordSplittingProtected}))})}function nE(O,D){if(!D)return O;return O.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>D)}function ps(O){let D=(ee)=>{let he=O[ee];return he?t(he):void 0},B=1;while(D(B)==="-H"||D(B)==="-P")B++;if(D(B)==="--")B++;let Q=[];while(B<O.length){let ee=D(B),he=O[B];if(!ee||!he||ee.startsWith("-")||["!","(",")"].includes(ee))break;Q.push(he),B++}return Q.length>0?Q:null}function rE(O,D){let B=rr([...O],D);if(B.length===0)return null;let Q=Tt(B[0]??"");if(Q==="busybox"&&B.length>1)B=B.slice(1),Q=Tt(B[0]??"");if(Q==="rm"&&Dn(B))return St("find.exec-rm-recursive-force",Zv);return null}function Vo(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 gs(O,D){let B=D;while(B<O.length){let Q=O[B];if(!Q){B++;continue}if(Kn(Q)){B=Vo(O,B).nextIndex;continue}let ee=sr(Q);if(ee>0){B+=ee+1;continue}if(Q==="-delete")return!0;B++}return!1}function sr(O){return Jv.get(O)??(/^-newer[A-Za-z]{2}$/.test(O)?1:0)}function Kn(O){return O!==void 0&&Xv.has(O)}import{resolve as kx}from"node:path";function*Ml(O){for(let D of O.nodes)yield*iE(D)}function oE(O){return Object.freeze([...Ml(O)])}function st(O){return Object.freeze(oE(O).map((D)=>Object.freeze(D.words.map((B)=>B.text))))}function Ko(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((Q)=>Q.provenance==="command-substitution"))return null;return B.words.map((Q)=>Q.text)}function*iE(O){if(O.kind==="command"){yield O;for(let D of O.nested)yield*Ml(D);return}if(O.kind==="group")yield*Ml(O.body)}var sE=5,Dl="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 en(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 qf(O,D,B){let Q=hs(O,D,B),ee=aE(Q.entries);if(ee.size===0)return{blockedReason:Q.blockedReason,expanded:!1,tokens:O};let he=O,je=!1;for(let at=0;at<sE;at++){let{subcommand:lt,rest:ct}=Sn(he),ut=lt?.toLowerCase();if(!ut||!ee.has(ut))return{blockedReason:Q.blockedReason,expanded:je,tokens:he};let ft=ee.get(ut),dt=fE(ft);if(dt===null||dt.length===0)return{blockedReason:Dl,expanded:!0,tokens:he};he=["git",...dt,...ct],je=!0}return{blockedReason:Dl,expanded:!0,tokens:he}}function Yf(O,D,B){return hs(O,D,B).entries.some((Q)=>Q.key.toLowerCase()==="core.sshcommand")}function Sn(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 Q=1;while(Q<O.length){let ee=O[Q];if(!ee)break;if(ee==="--"){let he=O[Q+1];if(he&&!he.startsWith("-"))return{subcommand:he,rest:O.slice(Q+2)};return{subcommand:null,rest:O.slice(Q+1)}}if(!ee.startsWith("-"))return{subcommand:ee,rest:O.slice(Q+1)};Q+=gn.has(ee)?2:1}return{subcommand:null,rest:[]}}function aE(O){let D=new Map;for(let B of O){let Q=B.key.toLowerCase();if(!Q.startsWith("alias."))continue;let ee=Q.slice(6);if(ee!=="")D.set(ee,B.value)}return D}function hs(O,D,B){if(O.length===0)return{blockedReason:null,entries:[]};let Q=O[0];if((Q?Tt(Q).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let he=cE(D,B);return{blockedReason:he.blockedReason,entries:[...he.entries,...lE(O,D,B)]}}function lE(O,D,B){let Q=[],ee=1;while(ee<O.length){let he=O[ee];if(!he||he==="--"||!he.startsWith("-"))return Q;if(he==="-c"){let je=Nl(O[ee+1]);if(je)Q.push(je);ee+=2;continue}if(he.startsWith("-c")&&he.length>2){let je=Nl(he.slice(2));if(je)Q.push(je);ee++;continue}if(he==="--config-env"){let je=Kf(O[ee+1],D,B);if(je)Q.push(je);ee+=2;continue}if(he.startsWith("--config-env=")){let je=Kf(he.slice(13),D,B);if(je)Q.push(je);ee++;continue}if(gn.has(he)){ee+=2;continue}ee++}return Q}function cE(O,D){let B=uE(O,D),Q=dE(O,D);return{blockedReason:B===null||Q===null?Dl:null,entries:[...B??[],...Q??[]]}}function uE(O,D){let B=jn("GIT_CONFIG_PARAMETERS",O,D);if(B===void 0)return[];let Q=[],ee=Ko(B);if(!ee)return null;for(let he of ee){let je=Nl(he);if(!je)return null;Q.push(je)}return Q}function dE(O,D){let B=Ud(O,D);if(B.state==="absent")return[];if(B.state==="invalid")return null;let Q=[];for(let ee=0;ee<B.count;ee++){let he=jn(`GIT_CONFIG_KEY_${ee}`,O,D)?.trim(),je=jn(`GIT_CONFIG_VALUE_${ee}`,O,D);if(!he||je===void 0)return null;Q.push({key:he,value:je})}return Q}function Nl(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 Kf(O,D,B){let Q=O?.indexOf("=")??-1;if(!O||Q===-1)return null;return{key:O.slice(0,Q).trim(),value:jn(O.slice(Q+1),D,B)}}function fE(O){let D=O?.trimStart();if(!D||D.startsWith("!"))return null;return Ko(D)}var mE="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",pE="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",gE="git checkout --force discards uncommitted changes. Use 'git stash' first.",hE="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",yE="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",bE="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",SE="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",CE="git switch --force discards uncommitted changes. Use 'git stash' first.",vE="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",EE="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",xE="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",RE="git reset --merge can lose uncommitted changes. Use 'git stash' first.",_E="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",wE="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.",PE="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.",TE="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",IE="git branch -D force-deletes without merge check. Use -d for safe delete.",kE="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",OE="git merge --abort discards merge conflict resolutions. Use 'git status' first.",ME="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",DE="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",NE="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",LE="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",WE="git worktree remove --force can delete uncommitted changes. Remove --force flag.",GE=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),FE=new Set(["--recurse-submodules","--track","-t"]),Ll=new Set(["-b","-B","-U"]),Wl=new Set(["-c","-C"]),zE=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function kt(O,D){let B=O.split("=",1)[0]??O;return B.length>=4&&D.startsWith(B)&&B.startsWith("--")&&B.slice(2).length>=2}var Jr=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function Xf(O,D){let{subcommand:B,rest:Q}=Sn(O);if(!B)return null;switch(B.toLowerCase()){case"checkout":return ar(BE(Q,D));case"switch":return ar(UE(Q));case"restore":return ar(jE(Q));case"reset":return KE(Q);case"clean":return ar(YE(Q));case"rm":return ar(ZE(Q));case"push":return Ar(XE(Q));case"branch":return Ar(ex(Q));case"stash":return Ar(ix(Q));case"worktree":return Ar(sx(Q));case"rebase":return ar(tx(Q));case"merge":return ar(nx(Q));case"tag":return Ar(rx(Q));case"reflog":return Ar(ox(Q));default:return null}}function ar(O){return O?{...O,localDiscard:!0}:null}function Ar(O){return O?{...O,localDiscard:!1}:null}function BE(O,D){let{index:B,before:Q}=en(O),ee=an(Q,{shortOptsWithValue:Ll});if(Q.some((at)=>kt(at,"--force"))||ee.has("-f"))return St("git.checkout-force",gE);for(let at of O){if(at==="-b"||at==="-B"||at==="--orphan")return null;if(kt(at,"--pathspec-from-file"))return St("git.checkout-pathspec-from-file",yE)}if(B!==-1){if(Q.some((lt)=>!lt.startsWith("-")))return St("git.checkout-ref-path",hE);return St("git.checkout-double-dash",mE)}let he=HE(O);if(he.length>=2)return St("git.checkout-ambiguous",bE);let je=he[0];if(je===void 0||ee.has("-d")||ee.has("-t")||O.some((at)=>kt(at,"--detach")||kt(at,"--track")))return null;if($E(je)||D(je))return St("git.checkout-double-dash",pE);return null}function $E(O){return O==="."||O===".."||/^\.\.?[/\\]/.test(O)||/^([/\\]|[A-Za-z]:[/\\])/.test(O)||O.endsWith("/")||O.startsWith(":")||/[*?[]/.test(O)}function UE(O){let{before:D}=en(O);if(D.some((Q)=>kt(Q,"--discard-changes")))return St("git.switch-discard-changes",SE);let B=an(D,{shortOptsWithValue:Wl});if(D.some((Q)=>kt(Q,"--force"))||B.has("-f"))return St("git.switch-force",CE);return null}function HE(O){let D=[],B=0;while(B<O.length){let Q=O[B];if(!Q)break;if(Q==="--")break;if(!Q.startsWith("-")){D.push(Q),B++;continue}if(GE.has(Q)){B+=2;continue}if(FE.has(Q)){let ee=O[B+1],he=Q==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"];B+=ee&&!ee.startsWith("-")&&he.includes(ee)?2:1;continue}B++}return D}function jE(O){let D=VE(O);if(D.isTerminal||!D.hasPathspec&&!D.hasPatch||!D.hasWorktree)return null;return D.hasExplicitLocation?St("git.restore-worktree",EE):St("git.restore-unstaged",vE)}function VE(O){let D=!1,B=!1,Q=!0,ee=!1,he=(je)=>{if(!ee)Q=!1,ee=!0;if(je!==void 0)Q=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:Q,hasExplicitLocation:ee,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(zE.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:Q,hasExplicitLocation:ee,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:Q,hasExplicitLocation:ee,isTerminal:!1}}function KE(O){let D=null;for(let B of O){if(kt(B,"--hard")){D=St("git.reset-hard",xE);break}if(kt(B,"--merge")){D=St("git.reset-merge",RE);break}}if(!D)return null;return qE(O)?Ar(D):ar(D)}function qE(O){for(let D of O){if(D==="--")return!1;if(!D.startsWith("-"))return!0}return!1}function YE(O){for(let B of O)if(B==="-n"||kt(B,"--dry-run"))return null;let D=an(O.filter((B)=>B!=="--"));if(O.some((B)=>kt(B,"--force"))||D.has("-f"))return St("git.clean-force",_E);return null}function ZE(O){let D=!1,B=!1,Q=!1;for(let ee of en(O).before){if(kt(ee,"--no-force")){D=!1;continue}if(kt(ee,"--force")){D=!0;continue}if(kt(ee,"--no-cached")){B=!1;continue}if(kt(ee,"--cached")){B=!0;continue}if(kt(ee,"--no-dry-run")){Q=!1;continue}if(kt(ee,"--dry-run")){Q=!0;continue}let he=an([ee]);D||=he.has("-f"),Q||=he.has("-n")}return D&&!B&&!Q?St("git.rm-force",wE):null}function XE(O){let{before:D,after:B}=en(O),Q=an(D);if(D.some((je)=>kt(je,"--mirror")))return St("git.push-mirror",TE);if(D.some((je)=>kt(je,"--force"))||Q.has("-f")||Zf(D,B).some(JE))return St("git.push-force",PE);if(D.some((je)=>kt(je,"--delete"))||Q.has("-d")||Zf(D,B).some(QE))return St("git.push-delete",AE);return null}function Zf(O,D){return[...O.filter((B)=>B!==""&&!B.startsWith("-")),...D]}function JE(O){return O.startsWith("+")||O.includes(":+")}function QE(O){return O.length>1&&O.startsWith(":")}function ex(O){let{before:D}=en(O),B=an(D),Q=B.has("-D")||B.has("-d")||D.some((he)=>kt(he,"--delete")),ee=B.has("-D")||B.has("-f")||D.some((he)=>kt(he,"--force"));if(Q&&ee)return St("git.branch-force-delete",IE);return null}function tx(O){let{before:D}=en(O);return D.some((B)=>kt(B,"--abort"))?St("git.rebase-abort",kE):null}function nx(O){let{before:D}=en(O);return D.some((B)=>kt(B,"--abort"))?St("git.merge-abort",OE):null}function rx(O){let{before:D}=en(O);return an(D).has("-d")||D.some((Q)=>kt(Q,"--delete"))?St("git.tag-delete",ME):null}function ox(O){return O[0]==="delete"?St("git.reflog-delete",DE):null}function ix(O){for(let D of O){if(D==="drop")return St("git.stash-drop",NE);if(D==="clear")return St("git.stash-clear",LE)}return null}function sx(O){let{before:D}=en(O);if(!D.includes("remove"))return null;let Q=an(D);if(D.some((ee)=>kt(ee,"--force"))||Q.has("-f"))return St("git.worktree-remove-force",WE);return null}import{dirname as wx,isAbsolute as Px,join as fm,resolve as Ax}from"node:path";var Fl="TMPDIR",zl="IFS",Qf=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,em=/^[A-Za-z_][A-Za-z0-9_]*$/,tm=new Set(["export","typeset","declare","readonly"]),ax=new Set(["builtin","command","time"]),nm=new Set(["do","then","else"]),lx=new Set(["do","then","case"]),Jf=new Set(["done","fi","esac"]),cx=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function rm(O,D){return O.map((B)=>B.provenance==="variable"&&cm(B.text)?qo(B.text,D.shellAssignments):t(B))}function qo(O,D){return O.replace(cx,(B,Q,ee)=>D.get(Q??ee??"")??B)}function om(O,D){return{env:O,effectiveEnvAssignments:mx(O,D),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function im(O){return{env:O.env,effectiveEnvAssignments:O.effectiveEnvAssignments?new Map(O.effectiveEnvAssignments):void 0,shellAssignments:new Map(O.shellAssignments),bodyDepth:O.bodyDepth,bodyAssignments:new Set(O.bodyAssignments)}}function Bl(O,D){let B=am(O,D),Q=O[0]??"";if(lx.has(Q))D.bodyDepth+=1;if(Q==="elif"||Jf.has(Q))D.bodyDepth=Math.max(0,D.bodyDepth-1);if(Jf.has(Q)&&D.bodyDepth===0)D.bodyAssignments.forEach((at)=>{D.shellAssignments.delete(at)}),D.bodyAssignments.clear();B.assignments.filter((at)=>at.persists).forEach((at)=>{if(D.shellAssignments.set(at.name,at.value),D.bodyDepth>0)D.bodyAssignments.add(at.name);$l(D,at)});let ee=B.commandIndex;if(ee!==-1&&tm.has(O[ee]??""))O.filter((at)=>em.test(at)&&Gl(at)).forEach((at)=>{px(D,at)});let he=ee===-1?-1:lm(O,ee);if(he===-1||O[he]!=="unset")return;let je=hx(O,he);if(je===null)return;O.slice(je).forEach((at)=>{if(nm.has(Q)){D.shellAssignments.set(at,"");return}gx(D,at)})}function sm(O,D){let B=am(O,D).assignments;if(B.length===0)return D.effectiveEnvAssignments;let Q=new Map(D.effectiveEnvAssignments??[]);return B.forEach((ee)=>{Q.set(ee.name,ee.value)}),Q}function am(O,D){let B=nm.has(O[0]??"")?1:0,Q=O.findIndex((at,lt)=>lt>=B&&!cm(at)),ee=Q!==-1&&tm.has(O[lm(O,Q)]??""),he=fx(D);return{assignments:O.flatMap((at,lt)=>{let ct=ux(at,he,D.env);if(!ct)return[];if(Q!==-1&<>Q&&!ee&&!Ki(ct.name))return[];return he.set(ct.name,ct.value),[{...ct,persists:Q===-1||ee}]}),commandIndex:Q}}function lm(O,D){let B=D;while(ax.has(O[B]??"")){B+=1;while(O[B]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(O[B]??""))return D;B+=1}}return B}function cm(O){return Rn(O)!==null||Qf.test(O)}function ux(O,D,B){return Rn(O)??dx(O,D,B)}function dx(O,D,B){let Q=qi(O,B,D);if(Q)return Q;let ee=O.match(Qf)?.[1];if(!ee)return null;let he=O.indexOf("=");return{name:ee,value:`${D.has(ee)?D.get(ee):B.get(ee)??""}${O.slice(he+1)}`}}function Gl(O){return O===Fl||O===zl||dl(O)}function fx(O){return new Map([...O.effectiveEnvAssignments??[],...O.shellAssignments])}function mx(O,D){let B=[Fl,zl].map((Q)=>{let ee=O.get(Q);return ee===void 0?null:[Q,ee]}).filter((Q)=>Q!==null);if(B.length===0)return D;return new Map([...B,...D??[]])}function $l(O,D){let B=new Map(O.effectiveEnvAssignments??[]);B.set(D.name,D.value),O.effectiveEnvAssignments=B}function px(O,D){$l(O,{name:D,value:O.shellAssignments.get(D)??O.effectiveEnvAssignments?.get(D)??O.env.get(D)??""})}function gx(O,D){if(!Gl(D)&&!em.test(D))return;if(O.shellAssignments.set(D,""),Ki(D)&&O.env.has(D)){let Q=new Map(O.env);Q.delete(D),O.env=Q}if(!Gl(D)||D===Fl||D===zl||mo(D)){$l(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 hx(O,D){let B=D+1;while(B<O.length){let Q=O[B];if(!Q)return null;if(Q==="--")return B+1;if(Q==="-v"){B++;continue}if(Q.startsWith("-"))return null;return B}return B}import{resolve as yx}from"node:path";function ys(O,D){return ul.some((B)=>D?.has(B)||O.has(B))}function Qr(O,D,B){if(!D)return{gitCwd:null,hasExplicitGitContext:!1};let Q=B.realpath(yx(D));if(Q===null||!B.isDirectory(Q))return{gitCwd:null,hasExplicitGitContext:!1};let ee=Q,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=um(ee,lt,B);if(!ct)return{gitCwd:null,hasExplicitGitContext:he};ee=ct,je+=2;continue}if(at.startsWith("-C")&&at.length>2){let lt=um(ee,at.slice(2),B);if(!lt)return{gitCwd:null,hasExplicitGitContext:he};ee=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+=gn.has(at)?2:1}return{gitCwd:ee,hasExplicitGitContext:he}}function um(O,D,B){try{let Q=nr(O,D,B);return B.isDirectory(Q)?Q:null}catch{return null}}function dm(O,D,B){if(!D.localDiscard||!B.worktreeMode||ys(B.environment.env,B.envAssignments))return null;let Q=Qr(O,B.cwd,B.environment.paths);if(!Q.gitCwd||Q.hasExplicitGitContext)return null;let ee=B.environment.worktreeFacts(Q.gitCwd);if(!ee)return null;if(Ul(O,B,ee))return null;return{kind:"worktree",originalReason:D.reason,gitCwd:Q.gitCwd}}function Ul(O,D,B){let{subcommand:Q,rest:ee}=Sn(O),he=Q?.toLowerCase();if(D.dynamicArguments||bx(ee)||xx(O,D.environment.env,D.envAssignments,B)||vx(ee)||Sx(he,ee))return!0;return he==="clean"&&Ex(ee)>1}function bx(O){return O.some((D)=>/[$*?[]/.test(D))}function Sx(O,D){if(O==="checkout"){let{before:B}=en(D),Q=an(B,{shortOptsWithValue:Ll}),ee=B.some((je)=>kt(je,"--force"))||Q.has("-f"),he=Q.has("-B")||B.some((je)=>je==="-B"||je.startsWith("-B"));return ee&&he}if(O==="switch"){let{before:B}=en(D),Q=an(B,{shortOptsWithValue:Wl}),ee=B.some((je)=>kt(je,"--force"))||B.some((je)=>kt(je,"--discard-changes"))||Q.has("-f"),he=B.some((je)=>je==="-C"||je.startsWith("-C")||Cx(je))||Q.has("-C");return ee&&he}return!1}function Cx(O){let D=O.split("=",1)[0]??O;return D==="--force-create"||D.length>=9&&"--force-create".startsWith(D)}function vx(O){return O.some((D)=>D.startsWith("--recurse-sub"))}function Ex(O){let D=0;for(let B of O){if(B==="--force"){D++;continue}if(B.startsWith("-")&&!B.startsWith("--")){for(let Q of B.slice(1))if(Q==="f")D++}}return D}function xx(O,D,B,Q){if(jn("GIT_CONFIG_PARAMETERS",D,B)!==void 0)return!0;let ee=hs(O,D,B);if(ee.blockedReason!==null)return!0;let he=ee.entries.map((at)=>({key:at.key.toLowerCase(),value:at.value}));if(he.some((at)=>_x(at.key)))return!0;let je=he.filter((at)=>at.key==="submodule.recurse").at(-1);if(je)return je.value===void 0||Rx(je.value);if(jd(B))return!0;return Q.recursiveSubmodules}function Rx(O){let D=O.toLowerCase();return D!=="false"&&D!=="no"&&D!=="off"&&D!=="0"}function _x(O){return O==="include.path"||O.startsWith("includeif.")&&O.endsWith(".path")}function mm(O,D,B){let Q=O.map(t),ee=B.environment.paths,he=Qr(Q,B.cwd,ee),je=B.originalCwd?ee.realpath(Ax(B.originalCwd)):null;if(D.id.startsWith("git.push-")||je===null||he.gitCwd===null||he.hasExplicitGitContext||ys(B.environment.env,B.envAssignments))return null;let at=D.id==="git.worktree-remove-force"?Ix(O,B.shellAssignments,ee):pm(he.gitCwd,ee);if(at===null||D.id!=="git.worktree-remove-force"&&!Tx(at,Q,D,B)||!Zr(at,B.environment)||ss(at,B.environment)||as(je,at)||as(at,je))return null;return{kind:"temp-root",originalReason:D.reason,gitCwd:he.gitCwd}}function Tx(O,D,B,Q){let ee=Q.environment.paths,he=fm(O,".git");if(ee.entryKind(he)!=="present")return!1;if(ee.isDirectory(he))return!0;let je=B.localDiscard?Q.environment.worktreeFacts(O):null;return je!==null&&!Ul(D,Q,je)}function Ix(O,D,B){let Q=Sn(O.map(t)).rest,{before:ee,after:he}=en(Q.slice(Q.indexOf("remove")+1)),je=[...ee.filter((ut)=>!ut.startsWith("-")),...he],at=je.length===1?je[0]??"":"",lt=O.find((ut)=>ut.text===at),ct=lt?.provenance==="variable"&<.parts.every((ut)=>ut.provenance!=="literal"||!/[$`]/.test(ut.raw))?qo(at,D??new Map):at;if(!Px(ct)||/[\s$`*?[]/.test(ct)||B.entryKind(ct)!=="present"||!B.isDirectory(ct))return null;return B.realpath(ct)}function pm(O,D){if(D.entryKind(fm(O,".git"))!=="missing")return O;let B=wx(O);return B===O?null:pm(B,D)}var Ox="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.",Mx=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function bs(O,D){return gm(O,D)}function gm(O,D,B){let Q=O.map(t),ee=qf(Q,D.environment.env,D.envAssignments),he=ee.blockedReason?wt(St("git.alias-config",ee.blockedReason),D.policy):null;if(he)return he;let je=ee.tokens;if((Hd(D.envAssignments)||Yf(Q,D.environment.env,D.envAssignments))&&Dx(je))return St("git.ssh-env",Ox);let at=Xf(je,(ct)=>{let ut=Qr(Q,D.cwd,D.environment.paths).gitCwd;return ut!==null&&D.environment.paths.entryKind(kx(ut,ct))!=="missing"});if(!at)return null;if(ee.expanded||ee.blockedReason)return at;let lt=dm(Q,at,D)??mm(O,at,D);if(!lt)return at;return B?.(lt),null}function hm(O,D){let B=null;return{match:gm(O,D,(ee)=>{B=ee}),relaxation:B}}function Dx(O){let{subcommand:D,rest:B}=Sn(O),Q=D?.toLowerCase();if(!Q)return!1;if(Mx.has(Q))return!0;if(Q==="archive")return en(B).before.some((ee)=>kt(ee,"--remote"));return Q==="remote"&&Nx(B)}function Nx(O){return O.find((D)=>!Lx(D))?.toLowerCase()==="update"}function Lx(O){return O==="-v"||kt(O,"--verbose")||kt(O,"--no-verbose")}import{isAbsolute as yR}from"node:path";function ym(O,D,B,Q){let ee=O.slice(0,D),he=O.slice(D+B);return Q.startsWith(ee)&&Q.endsWith(he)?Q.slice(ee.length,Q.length-he.length):null}function Ss(O,D,B){let Q=(he)=>`${he.tokenIndex}\x00${he.kind}\x00${he.value}`,ee=new Set(O.map(Q));return Array.from(D).some((he)=>B(he).some((je)=>!ee.has(Q(je))))}var bm="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Wx="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.",Gx="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",Cm="rm -rf targeting root or home directory is extremely dangerous and always blocked.",Fx="rm -rf in home directory is dangerous. Change to a project directory first.",Sm={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:Cm},git_metadata_target:{id:"rm.git-metadata",reason:x},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:Gx},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:Fx},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:bm},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:Wx},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:bm}};function Cs(O,D){let B=_r({...D,allowPaths:D.policy?.destructiveCommandAllowPaths,posixShell:!0}),Q=O.map(t),ee=Dn(Q),he=jf(Q),je=Bx(O);for(let at of je){let lt=$o(at.word);if(ee&<.unsafeBraceExpansion){let ct=wt(Bo({kind:"outside_anchored_cwd"},B,D.policy,Sm),D.policy);if(ct)return ct;continue}for(let ct of lt.expandedTargets??[at.text]){let ut=pn(ct),ft={targetIsLiteral:lt.expandedTargets!==void 0||lt.targetIsLiteral,tmpdirWordSplittingProtected:lt.tmpdirWordSplittingProtected};if(!he&&B.resolvedCwd&&Er(ut,B.resolvedCwd,B.protectedGitMetadata,he,B.environment,B.budget))return St("rm.git-metadata",x);if(he&&!ee){let dt=On(ut,B,ft);if(dt.kind==="root_or_home_target")return St("rm.recursive-force-root-or-home",Cm);if(dt.kind==="git_metadata_target")return St("rm.git-metadata",x);continue}if(!ee)continue;for(let dt of zx(ut,B,ft)){let mt=Bo(dt,B,D.policy,Sm),pt=wt(mt,D.policy);if(pt)return pt}}}return null}function zx(O,D,B){let Q=On(O,D,B);if(Q.kind==="cwd_self_target")return[Q,On(O,D,{...B,skipCwdSelf:!0})];if(Q.kind!=="home_cwd_target")return[Q];let ee=On(O,D,{...B,skipHomeCwd:!0});if(ee.kind!=="cwd_self_target")return[Q,ee];return[Q,ee,On(O,D,{...B,skipHomeCwd:!0,skipCwdSelf:!0})]}function Bx(O){let D=[],B=!1;for(let Q of O.slice(1)){let ee=t(Q);if(!ee)continue;if(ee==="--"){B=!0;continue}if(B){D.push({text:ee,word:Q});continue}if(!ee.startsWith("-"))D.push({text:ee,word:Q})}return D}var lr={kind:"none"},Tr={kind:"dynamic"},$x=new Set(["<","<<","<<-","<<<","<&","<>"]),Em=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,Ux=/^(?:[0-9]+|[@*])$/,Hx=tr.maxWords,jx=tr.maxInputLength;function xm(O){if(!O||Tt(It(O.words[0]?.text??""))!=="printf")return;if(O.words.some((ee)=>ee.provenance!=="literal"))return;let D=O.words.slice(O.words[1]?.text==="--"?2:1),B=D[0]?.text;if(B===void 0)return"";let Q=D.slice(1).map((ee)=>ee.text);if(B==="%s")return Q.join("");if(B==="%s\\n"||B===`%s
|
|
34
|
+
`)return`${Q.join(`
|
|
35
|
+
`)}
|
|
36
|
+
`;if(B.includes("%")||/\\(?![\\nrt])/.test(B))return;return B.replaceAll("\\n",`
|
|
37
|
+
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function vs(O){let D=Yo(O[1])==="--"?2:1;if(O.length<=D)return lr;let B=O.slice(D);if(!B.every(xs))return Tr;return{kind:"literal",source:B.map(t).join(" ")}}function Rm(O){let D=Yo(O[1])==="--"?2:1,B=O[D],Q=Yo(B);if(B===void 0||O.length<=D+1||Q==="-"||Q===""||Q==="-l"||Q==="-p")return lr;if(!xs(B))return Tr;return{kind:"literal",source:Q}}function Es(O,D){let B=Kx(O);if(B===-1)return lr;let Q=qx(D);if(!Q)return lr;let ee=[],he=Q.command?.length??0;for(let je of Q.references){let at=Zx(je,O,B,Q.ifs);if(!at)return Tr;if(he+=at.reduce((lt,ct)=>lt+ct.length+3,0),ee.length+at.length>Hx||he>jx)return Tr;ee.push(...at)}if(Q.command==="eval")return{kind:"literal",source:ee.join(" ")};if(ee.length===0||/\s/.test(ee[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[Q.command,Q.command&&Q.optionTerminator?"--":null,...ee.map(Jx)].filter((je)=>je!==null).join(" ")}}function _m(O,D,B,Q){if(!hn(O.map(t)).readsStdinAsCommands)return lr;let ee=D.filter((he)=>(he.fd===void 0||he.fd===0)&&$x.has(he.operator)).at(-1);if(ee){if(ee.operator==="<<"||ee.operator==="<<-")return lr;if(ee.operator!=="<<<"||ee.target?.provenance!=="literal")return Tr;return{kind:"literal",source:ee.target.text}}if(!B)return lr;return Q===void 0?Tr:{kind:"literal",source:Q}}function qn(O){let D=hn(O.map(t)).scriptIndex;if(D===null)return lr;let B=O[D],Q=Yo(B);return Bi(B,Q)?{kind:"literal",source:Q}:Tr}var Vx=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==="eval"&&!B.quoted&&B.parts.length===1&&B.parts[0]?.provenance==="command-substitution"&&B.parts[0].raw.startsWith("$(")||(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 ee=O.nested[0];if(ee?.status!=="complete"||ee.nodes.length!==1)return!1;let he=ee.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||Rn(je)!==null)return!1;let at=Tt(It(je));return!Vx.has(at)&&!Kt.has(at)&&!wr(at)}function Kx(O){return hn(O.map(t)).commandIndex??-1}function qx(O){let D=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(O.trim()),B=D?.[4]??O.trim(),Q=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(B),ee=(Q?.[3]??B).split(/\s+/).map(Yx);if(ee.length===0||ee.some((he)=>he===null))return null;return{command:Q?.[1]??null,optionTerminator:Q?.[2]!==void 0,references:ee.filter((he)=>!!he),ifs:D?D[1]??D[2]??D[3]??"":`
|
|
38
|
+
`}}function Yx(O){let D=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(O),B=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(O),Q=D??B;if(!Q)return null;let ee=Q[1]??Q[2];return{parameter:ee==="@"||ee==="*"?ee:Number(ee),quoted:D!==null}}function Zx(O,D,B,Q){let ee=D.slice(B+2);if(O.parameter==="@")return O.quoted?Hl(ee):Xx(ee,Q);if(O.parameter==="*"){let at=Hl(ee);if(!at)return;let lt=at.join(Q[0]??"");return O.quoted?[lt]:jl(lt,Q)}let he=D[B+1+O.parameter];if(he&&!xs(he))return;let je=Yo(he);return O.quoted?[je]:jl(je,Q)}function Hl(O){return O.every(xs)?O.map(t):void 0}function Xx(O,D){let B=Hl(O);if(!B)return;let Q=B.map((ee)=>jl(ee,D));return Q.some((ee)=>ee===void 0)?void 0:Q.flatMap((ee)=>ee??[])}function jl(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 xs(O){if(!O)return!0;return O.provenance==="unknown"?!/[$`]/.test(t(O)):O.provenance==="literal"}function Yo(O){return O?t(O):""}function Jx(O){return`'${O.replaceAll("'",`'"'"'`)}'`}function ql(O,D){return Vl(h(O,"posix"),D)}function Xo(O){return ql(O,new Set(Array.from(O.matchAll(Em)).flatMap((D)=>{let B=D[1]??D[2];return B===void 0?[]:[B]})))}function Vl(O,D){if(O.status==="invalid"||O.status==="limited")return!1;let B=new Set(D);for(let Q of O.nodes){if(Q.kind==="group"){if(Vl(Q.body,B))return!0;continue}if(Q.kind!=="command")continue;if(Q.nested.some((ee)=>Vl(ee,B))||wm(Q.words,B))return!0;rR(Q,B)}return!1}function wm(O,D){let B=O.findIndex((je)=>Rn(je.text)===null);if(B===-1)return!1;let Q=O[B];if(!Q)return!1;if(Zo(Q,D))return!0;let ee=It(Q.text);if(ee==="source"||ee==="."){let je=O[B+1]?.text==="--"?B+2:B+1;return vm(O[je],D)}if(Kt.has(ee)){let je=O.slice(B),at=hn(je.map((ct)=>ct.text)),lt=at.commandIndex??at.scriptIndex;return!at.syntaxCheck&<!==null&&vm(je[lt],D)}let he=Qx(O,B,D);if(he===null)return!1;if(he===-1)return!0;return wm(O.slice(he),D)}function Qx(O,D,B){let Q=It(O[D]?.text??"");if(Q==="command")return eR(O,D+1);if(Q==="exec")return tR(O,D+1);if(Q==="env")return nR(O,D+1,B);return null}function eR(O,D){for(let B=D;B<O.length;B++){let Q=O[B]?.text??"";if(Q==="--")return O[B+1]?B+1:null;if(/^-[p]*[vV][pvV]*$/.test(Q))return null;if(/^-p+$/.test(Q))continue;return B}return null}function tR(O,D){for(let B=D;B<O.length;B++){let Q=O[B]?.text??"";if(Q==="--")return O[B+1]?B+1:null;if(Q==="-a"){B++;continue}if(/^-a.+/.test(Q)||/^-[cl]+$/.test(Q))continue;return B}return null}function nR(O,D,B){for(let Q=D;Q<O.length;Q++){let ee=O[Q],he=ee?.text??"";if(he==="--")return O[Q+1]?Q+1:null;if(he==="-S"||he==="--split-string")return Zo(O[Q+1],B)?-1:Q+2;if(he.startsWith("-S")||he.startsWith("--split-string="))return Zo(ee,B)?-1:Q+1;if(he==="-u"||he==="--unset"||he==="-C"||he==="--chdir"||he==="-P"){Q++;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(Rn(he))continue;return Q}return null}function rR(O,D){if(!O.words.every((B)=>Rn(B.text)!==null))return;for(let B of O.words){let Q=Rn(B.text);if(!Q)continue;if(Zo(B,D))D.add(Q.name)}}function Zo(O,D){if(!O)return!1;return O.parts.filter((B)=>B.provenance==="variable").some((B)=>Array.from(B.raw.matchAll(Em)).some((Q)=>{let ee=Q[1]??Q[2];return ee!==void 0&&(Ux.test(ee)||D.has(ee))}))}function vm(O,D){return!!O&&(O.parts.some((B)=>B.provenance!=="literal"&&B.provenance!=="variable")||Zo(O,D))}var oR=["--init-file","--rcfile"],iR=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function Yn(O){for(let D=1;D<O.length;D++){let B=O[D];if(!B)continue;if(B==="-c")return Pm(O,D,!0);if(B.startsWith("-")&&B.includes("c")&&!B.startsWith("--")){let Q=Pm(O,D,!1);if(Q!==null)return Q}}return null}function Zn(O){let D=Tt(O[0]??"").toLowerCase();if(D==="zsh"||D==="ksh")return hn(O).syntaxCheck;let B=!1;for(let Q of O.slice(1)){if(Q==="--")return B;if(Q.startsWith("+")&&!Q.startsWith("++")){if(Q.slice(1).includes("n"))B=!1;continue}if(!Q.startsWith("-")||Q.startsWith("--"))return B;let ee=Q.slice(1);if(ee.includes("n"))B=!0;if(ee.includes("c"))return B}return B}function Pm(O,D,B){if(O[D+1]==="--")return O[D+2]||null;let Q=O[D+1];if(!Q||!B&&Q.startsWith("-"))return null;return Q}function Am(O){let D=Tt(O[0]??"").toLowerCase(),B=sR(O,D),Q=iR.get(D)??null,ee=B.argvSource?.kind!=="absent";return{argvSource:D==="bash"?B.argvSource:null,argvSourceApplies:D==="bash"&&B.interactive&&B.argvSource?.kind==="literal",envName:Q,envSourceApplies:ee&&(Q==="BASH_ENV"?!B.interactive:Q==="ENV"&&B.interactive)}}function sR(O,D){let B=hn(O),Q=B.commandIndex??B.scriptIndex??O.length,ee=[],he=!1,je=!0;for(let at=1;at<Q;at++){let lt=O[at];if(lt===void 0||lt==="--"||lt==="-"||lt[0]!=="-"&<[0]!=="+")break;if(lt.startsWith("--")){if(D==="bash"&&je?oR.find((dt)=>lt===dt):void 0){let dt=O[at+1];ee.push(dt===void 0?{kind:"absent"}:{kind:"literal",value:dt}),at++;continue}let ft=lt.split("=",1)[0]??lt;if(D==="bash"&&ga.has(ft)&&!lt.includes("="))at++;continue}if(D==="bash")je=!1;let ct=ha(D,lt,O[at+1],"startup");if(ct.interactive)he=lt[0]==="-";at+=ct.followingValues}return{argvSource:ee.at(-1)??null,interactive:he}}var Yl="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",Zl="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",aR="__CC_SAFETY_NET_XARGS_INPUT__",Rs="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",_s="rm",lR=/(?:^|[;&|]\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,cR=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,uR=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,dR=/^(?:[0-9]+|[@*])$/;function km(O,D){let B=O.map(t),{childStart:Q,replacementToken:ee}=Ir(B),he=B.slice(Q),je=St("xargs.shell-dynamic",Zl);if(mR(he,ee,D)&&wt(je,D.policy))return wt(je,D.policy);for(let at of Mn(he,D)){let lt=at.tokens,ct=ee!==null&<[0]!==he[0]&&(lt[0]?.includes(ee)??!1)?wt(je,D.policy):null;if(ct)return ct;let ut=Wm(lt,ee,at.wrapperEnvAssignments),ft=at.head==="rm"&&ee!==null&&Nm(lt,ee),dt=D.analyzeChild(lt,{...Pr(at,D),dynamicInput:ut,dynamicSourceInput:ft||Mm(lt,at.head,ee,at.wrapperEnvAssignments,ut,D.environment,D.strict?void 0:D.analyzeNested),dynamicRmInput:ft,shellDynamicMatch:je,dynamicSourceMatch:je,rmDynamicMatch:St("xargs.rm-recursive-force-dynamic",Yl)});if(dt)return dt;let mt=fR(lt,ee,D.policy?.rules??[],wt(je,D.policy));if(mt)return mt;if(at.head==="git"){let gt=ee===null?[...lt,aR]:lt,ht=ee!==null&&(lt.some((Ct)=>Ct.includes(ee))||Array.from(at.envAssignments.values()).some((Ct)=>Ct.includes(ee))),yt=D.analyzeChild(gt,{...Pr(at,D),worktreeMode:ee===null||ht?!1:D.worktreeMode});if(yt)return yt}let pt=_(lt,D.policy?.rules??[]);if(pt)return pt}return null}function fR(O,D,B,Q){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 ee=It(O[0]??"");if(!B.some((he)=>It(he.command)===ee))return null;return O.slice(1).some((he)=>he.includes(D))?Q:null}function Om(O,D,B){let Q=O.indexOf(D);if(Q===-1||O.indexOf(D,Q+D.length)!==-1)return[];let ee=ym(O,Q,D.length,B);return ee===null?[]:[ee]}function Mm(O,D,B,Q,ee,he,je){if(Kt.has(D)){if(Zn(O))return!1;if(B!==null&&pR(O,B,je))return!0;let at=Yn(O);if(!at){let lt=qn($t(O));if(lt.kind==="literal")return B!==null&<.source.includes(B);return lt.kind==="none"&&ee}if(B!==null&&at.includes(B)&&!Dm(at,B,je))return!0;if(xn(at))return!0;return gR(at,B,Q)}if(An(D))return Tm(O,B,Vi,Fd(D));if(En.has(D))return Tm(O,B,Pl,zf);if(D==="eval"){let at=vs($t(O));if(at.kind==="dynamic")return!0;if(B!==null)return at.kind==="literal"&&at.source.includes(B);return ee}if(D==="find")return hR(O,B,he);if(D==="git"){let at=Sn(O);return B===null?at.subcommand===null:(at.subcommand?.includes(B)??!1)||at.subcommand!==null&&Jr.has(at.subcommand.toLowerCase())&&Lm(at.rest,B).some((lt)=>lt.includes(B))}return!1}function Dm(O,D,B){if(B===void 0)return!1;let Q=D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`(?:^|[;&|({!\`\\n]|\\b(?:then|do|else|elif|if|while|until|time|command|builtin|nohup|eval|exec|source))\\s*(?:[A-Za-z_][A-Za-z0-9_]*=\\S*\\s+)*["']?${Q}`).test(O)||/\bcase\b/.test(O))return!1;let he=O.replaceAll(D,"/");return xn(he)===null&&B(he)===null}function Tm(O,D,B,Q){let ee=B(O);if(D===null)return ee.optionsOpen||B([...O,Rs]).sources.some((at)=>at.value===Rs);if(ee.sources.some((at)=>at.value.includes(D)))return!0;let he=Q.flatMap((at)=>[at.selector,...at.valueForm==="attached-only"||at.valueForm==="attached-or-separate"?[`${at.selector}${Rs}`]:[],...at.valueForm==="equals-or-separate"?[`${at.selector}=${Rs}`]:[]]),je=new Set(he.flatMap((at)=>O.flatMap((lt)=>Om(lt,D,at))));return Ss(ee.sources,je,(at)=>B(O.map((lt)=>lt.replaceAll(D,at))).sources)}function mR(O,D,B){if(O.length===0||(O[0]??"").toLowerCase()==="command")return!1;let Q=new Set(Array.from(Mn(O,B),(he)=>he.head)),ee=D===null?[...O,_s]:O.map((he,je)=>je===0?he:he.replaceAll(D,_s));return Array.from(Mn(ee,B)).some((he)=>he.head===_s&&!Q.has(_s))}function Nm(O,D){return Lm(O.slice(1),D).some((B)=>B.includes(D)&&(B.startsWith("-")||B.startsWith(D)))}function Lm(O,D){let B=O.findIndex((Q)=>Q==="--"&&!Q.includes(D));return B===-1?O:O.slice(0,B)}function Wm(O,D,B){if(D===null)return!0;return O.some((Q)=>Q.includes(D))||Array.from(B.values()).some((Q)=>Q.includes(D))}function pR(O,D,B){let Q=hn(O),ee=Q.commandIndex===null?"":O[Q.commandIndex]??"";if(ee.includes(D)&&!Dm(ee,D,B)||Q.scriptIndex!==null&&(O[Q.scriptIndex]??"").includes(D))return!0;return["-c","-nc","-cn",`--${D}`,D].some((je)=>O.some((at,lt)=>{if(lt===0||!at.includes(D))return!1;return Om(at,D,je).some((ut)=>{let ft=O.map((mt,pt)=>pt===lt?mt.replaceAll(D,ut):mt),dt=hn(ft);if(dt.commandIndex===null&&dt.scriptIndex===null)return!1;if(Q.commandIndex===null&&dt.commandIndex!==null)return!0;if(Q.scriptIndex===null&&dt.scriptIndex!==null)return!0;if(dt.commandIndex!==null&&(ft[dt.commandIndex]??"").includes(ut))return!0;return dt.scriptIndex!==null&&(ft[dt.scriptIndex]??"").includes(ut)})}))}function gR(O,D,B){let Q=new Set(D===null?[]:Array.from(B).filter(([,ee])=>ee.includes(D)).map(([ee])=>ee));for(let ee of O.matchAll(lR))if(Im(ee,Q))return!0;for(let ee of O.matchAll(cR))for(let he of(ee[1]??"").matchAll(uR))if(Im(he,Q))return!0;return ql(O,Q)}function Im(O,D){let B=O[1]??O[2];return B!==void 0&&(dR.test(B)||D.has(B))}function hR(O,D,B){if(D===null)return!0;let Q=!1,ee=0;for(let he=1;he<O.length;he++){let je=O[he]??"";if(!Q&&!je.startsWith("-")&&je!=="!"&&je!=="("){if(je.indexOf(D)===0)return!0;continue}if(Q=!0,ee>0){ee--;continue}if(Kn(je)){let lt=Vo(O,he);he=lt.nextIndex-1;for(let ct of Mn(lt.tokens,{environment:B,cwd:void 0})){let ut=Wm(ct.tokens,D,ct.wrapperEnvAssignments);if(ct.head==="rm"&&Nm(ct.tokens,D)||Mm(ct.tokens,ct.head,D,ct.wrapperEnvAssignments,ut,B))return!0}continue}let at=sr(je);if(at>0){if(ee=at,je.includes(D))return!0;continue}if(je.includes(D))return!0}return!1}function Ir(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,Q=1;while(Q<O.length){let ee=O[Q];if(!ee)break;if(ee==="--")return{childStart:Q+1,replacementToken:B};if(!ee.startsWith("-"))return{childStart:Q,replacementToken:B};if(ee==="-I"){B=O[Q+1]??"{}",Q+=2;continue}if(ee.startsWith("-I")&&ee.length>2){B=ee.slice(2),Q++;continue}if(ee==="--replace"){B="{}",Q++;continue}if(ee.startsWith("--replace=")){let he=ee.slice(10);B=he===""?"{}":he,Q++;continue}if(ee==="-J"){B=O[Q+1]??"{}",Q+=2;continue}Q+=D.has(ee)?2:1}return{childStart:O.length,replacementToken:B}}var Jo="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.",bR="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",SR="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Ps=/\{[^{}\s]*\}/g,Gm=/\{\}|\{-?\d+\}/g,CR=["e","f","source","file","-e","-f","--source","--file"],vR=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],ER=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),xR=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),Fm=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),RR=new Set(["--workdir","--wd"]),zm="__CC_SAFETY_NET_PARALLEL_SOURCE__";function _n(O,D){for(let B of O){let Q=D(B);if(Q)return Q}return null}function jm(O){return _n([...O],(D)=>xn(D))}function Vm(O,D){let B=O.map(t);if((D.envAssignments?.has("PARALLEL")?D.envAssignments.get("PARALLEL"):D.environment.env.get("PARALLEL"))?.trim()){let pt=eo(D);if(pt)return pt}if(B.length===2&&(B[1]==="--version"||B[1]==="--help"))return null;let ee=tp(B),{template:he,jobs:je,runsRemotely:at,readsCommandsFromInput:lt,unsupported:ct,workdir:ut,dryRun:ft}=ee;if(ct){let pt=eo(D);if(pt)return pt;let gt=jm(D.envAssignments?.values()??[]);if(gt)return gt}if(lt){let pt=IR(D);if(pt)return pt}if(ut!==void 0&&at){let pt=eo(D);if(pt)return pt}let dt=kR(ut,D.cwd,D.environment.paths);if(dt===null){let pt=eo(D);if(pt)return pt}let mt=at?{...D,cwd:void 0,originalCwd:void 0}:dt===null||dt===void 0||dt===D.cwd?D:{...D,cwd:dt};if(ft){if([...Mn(he,mt)].flatMap((gt)=>[...gt.envAssignments.values()]).some(Ql)){let gt=eo(D);if(gt)return gt}return null}if(he.length===0){let pt=je.map((ht)=>ht[0]??"");D.budget.charge("derivedTokens",pt.length);let gt=Zm(mt.envAssignments,mt.cwd,at);return _n(pt,(ht)=>D.analyzeNested(ht,gt))}return _n(Mn(he,mt),(pt)=>_R(pt,ee,D,mt))}function _R(O,D,B,Q){let{jobs:ee,templateHasPlaceholder:he,runsRemotely:je,usesStdin:at}=D,lt=O.tokens,ct=[...O.envAssignments.values()];if(ct.some(Qm)){let ht=eo(B);if(ht)return ht}let ut=jm(ct);if(ut)return ut;let ft=ct.some(Nt),dt=he||ft,mt=at&&dt,pt=Zm(O.envAssignments,O.wrapperCwd,je||mt);if(Kt.has(O.head)){let ht=()=>{if(!he||ee.length===0)return null;return _n(ee,(Et)=>B.analyzeChild(ws(lt,Et,B.budget),Pr(O,Q)))};if(Zn(lt))return ht();let yt=Yn(lt);if(yt){if(ep(yt)){let xt=cr(B);if(xt)return xt;if(ee.length===0)return null;return _n(ee,(_t)=>B.analyzeNested(Um(yt,_t,B.budget),pt))}if(Nt(yt)){if(ee.length>0)return _n(ee,(Ut)=>B.analyzeNested(Um(yt,Ut,B.budget),pt));let xt=Ko(yt);if(xt?.[0]&&It(xt[0])==="rm"&&Dn(xt)){let Ut=$m(B);if(Ut)return Ut}let _t=xt?B.analyzeChild(xt,{...Pr(O,Q),dynamicInput:at,shellDynamicMatch:St("parallel.shell-dynamic",Qo),rmDynamicMatch:St("parallel.rm-recursive-force-dynamic",Jo)}):null;if(_t)return _t;return B.analyzeNested(yt,pt)}let Et=!ft&&(!he||ee.length>0)?(ee.length>0?ee:[void 0]).map((xt)=>Es($t(xt===void 0?lt:he?lt.map((_t)=>Xm(_t,xt)):[...lt,...xt]),yt)):[];if(Et.some((xt)=>xt.kind==="dynamic")){let xt=cr(B);if(xt)return xt}let vt=Et.flatMap((xt)=>xt.kind==="literal"?[xt.source]:[]);if(vt.length>0)return B.budget.charge("derivedTokens",vt.length),_n(vt,(xt)=>B.analyzeNested(xt,pt));if(Xo(yt)){let xt=cr(B);if(xt)return xt}let Pt=B.analyzeNested(yt,pt);if(Pt)return Pt;if(dt)return cr(B);return null}let Ct=qn($t(lt));if(Ct.kind==="dynamic"||Ct.kind==="literal"&&Nt(Ct.source))return cr(B)??ht();if(Ct.kind==="literal")return ht();if(ee.length>0){let Et=cr(B);if(Et)return Et;let vt=ht();if(vt)return vt;if(he)return null;let Pt=ee.flatMap((xt)=>xt[0]===void 0?[]:[xt[0]]);return B.budget.charge("derivedTokens",Pt.length),_n(Pt,(xt)=>B.analyzeNested(xt,pt))}if(dt||at)return cr(B)??ht();return null}if(O.head==="rm"&&Dn(lt)){if(he&&ee.length>0)return _n(ee,(yt)=>Xl(ws(lt,yt,B.budget,Gm),O.cwd,Q));if(ee.length>0)return _n(ee,(yt)=>Xl(Hm(lt,yt,B.budget),O.cwd,Q));let ht=Xl(lt.flatMap((yt,Ct)=>{if(Ct===0||!Nt(yt))return[yt];return yt.startsWith("-")?[yt.replace(Gm,"")]:[]}),O.cwd,Q);if(ht)return ht;return $m(B)}let gt=ee.length>0?ee:[void 0];return _n(gt,(ht)=>{let yt=ht===void 0?lt:he?ws(lt,ht,B.budget):Hm(lt,ht,B.budget),Ct=St("parallel.shell-dynamic",Qo),Et=at&&O.head==="find"?TR(yt,Q):null,vt=qm(yt,at,B)??Et?.customResult??null,Pt=It(O.head),xt=at&&(Pt==="rm"&&Jl(yt)||Pt==="xargs"&&Ym(yt)||Et?.rmOptions===!0),_t=at&&(xt||Et?.executedSource===!0||Et===null&&Km(yt,Pt)),Ut=B.analyzeChild(yt,{...Pr(O,Q),worktreeMode:je||at||dt?!1:B.worktreeMode,dynamicInput:at||dt,dynamicRmInput:xt,dynamicSourceInput:vt!==null||_t,shellDynamicMatch:Ct,dynamicSourceMatch:Ct,rmDynamicMatch:St("parallel.rm-recursive-force-dynamic",Jo)});if(_t){let jt=wt(Ct,B.policy);if(jt)return jt}return Ut??vt??_(yt,B.policy?.rules??[])})}function Km(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 AR(O);if(D==="git")return wR(O);if(D==="find")return!0;if(En.has(D))return Bm(O,CR,jo);if(An(D))return Bm(O,vR,ji);return!1}function Jl(O){let D=O.indexOf("--"),B=O.slice(1,D===-1?void 0:D);if(!O.some(Nt))return D===-1;return B.some((ee)=>Nt(ee)&&(ee.startsWith("-")||ep(ee)))}function wR(O){if(PR(O))return!0;let D=Sn(O);if(D.subcommand===null||Nt(D.subcommand))return!0;if(!Jr.has(D.subcommand.toLowerCase()))return!1;let B=D.rest.indexOf("--"),Q=D.rest.slice(0,B===-1?void 0:B);if(!O.some(Nt))return B===-1;return Q.some(Nt)}function PR(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 AR(O){if(Zn(O))return!1;let D=Yn(O);if(D!==null)return Nt(D);let B=qn($t(O));if(B.kind==="literal")return Nt(B.source);if(B.kind==="dynamic")return!0;return!O.some(Nt)}function Bm(O,D,B){let Q=B(O);if(Q.some((ee)=>Nt(ee.value)))return!0;if(!O.some(Nt))return B([...O,zm]).some((ee)=>ee.value===zm);return Ss(Q,D,(ee)=>B(O.map((he)=>Xm(he,[ee]))))}function qm(O,D,B){let Q=B.policy?.rules??[];if(!D||Q.length===0)return null;let ee=Q.filter((he)=>It(he.command)===It(O[0]??""));if(ee.length===0)return null;if(O.slice(1).some(Nt))return cr(B);return _n(ee,(he)=>_([...O,...he.subcommand?[he.subcommand]:[],...he.block_args],[he]))}function TR(O,D){let B={customResult:null,executedSource:!O.some(Nt),rmOptions:!1},Q=!1,ee=0,he=null,je=()=>{if(!he?.some(Nt))return;for(let at of Mn(he,D))B.executedSource||=Km(at.tokens,at.head),B.rmOptions||=at.head==="rm"&&Jl(at.tokens)||at.head==="xargs"&&Ym(at.tokens),B.customResult??=qm(at.tokens,!0,D)};for(let at of O.slice(1)){if(!Q&&!at.startsWith("-")&&at!=="!"&&at!=="("){B.executedSource||=Nt(at);continue}if(Q=!0,he){if(at===";"||at==="+"){je(),he=null;continue}he.push(at);continue}if(ee>0){ee--;continue}if(Kn(at)){he=[],B.executedSource||=Nt(at);continue}let lt=sr(at);if(lt>0){ee=lt,B.executedSource||=Nt(at);continue}B.executedSource||=Nt(at)}return je(),B}function Ym(O){let D=O.slice(Ir(O).childStart);return It(D[0]??"")==="rm"&&Jl(D)}function As(O,D){return(B)=>wt(St(O,D),B.policy)}var cr=As("parallel.shell-dynamic",Qo),IR=As("parallel.command-stream-dynamic",bR),eo=As("parallel.command-stream-dynamic",SR),$m=As("parallel.rm-recursive-force-dynamic",Jo);function Xl(O,D,B){return wt(Cs($t(O),{environment:B.environment,cwd:D,budget:B.budget,originalCwd:B.originalCwd,strict:B.strict,paranoid:B.paranoidRm,allowTmpdirVar:B.allowTmpdirVar,tmpdirWordSplittingUnsafe:ir(B.envAssignments??new Map,B.environment),trustedTmpdirValue:xr(B.envAssignments??new Map,B.environment),protectedGitMetadata:B.protectedGitMetadata,policy:B.policy}),B.policy)}function Zm(O,D,B){let Q={};if(O)Q.envAssignments=O;if(B)return Q.effectiveCwd=null,Q.worktreeMode=!1,Q;if(D!==void 0)Q.effectiveCwd=D;return Object.keys(Q).length>0?Q:void 0}function Xm(O,D){return O.replace(Ps,(B)=>Jm(B,D))}function ws(O,D,B,Q=Ps){return B.charge("derivedTokens",O.reduce((ee,he)=>ee+1+Math.floor(he.length/64),0)),O.map((ee)=>ee.replace(Q,(he)=>{let je=Jm(he,D);return B.charge("derivedTokens",Math.max(1,Math.ceil(je.length/64))),je}))}function Um(O,D,B){return ws([O],D,B)[0]??""}function Hm(O,D,B){return B.charge("derivedTokens",O.length+D.length),[...O,...D]}function Jm(O,D){let B=/^\{(-?\d+)[^{}\s]*\}$/.exec(O)?.[1];if(B===void 0)return D[0]??"";let Q=Number(B);return D[Q>0?Q-1:D.length+Q]??""}function Nt(O){return O.search(Ps)!==-1}function Qm(O){if(Ql(O))return!0;for(let D of O.matchAll(Ps))if(!/^(?:\{\}|\{\d+\})$/.test(D[0]))return!0;return!1}function Ql(O){let D=O.indexOf("{=");return D!==-1&&O.indexOf("=}",D+2)!==-1}function ep(O){return/^\{[^{}\s]*\}$/.test(O)}function kR(O,D,B){if(O===void 0)return;if(O==="..."||/^~|[{}$`*?[]/.test(O))return null;if(!D&&!yR(O))return null;try{return nr(D??O,O,B)}catch{return null}}function tp(O){let D=1,B=[],Q=O.length,ee=-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===":::"){ee=D;break}if(pt==="--"){let Et=Il(O,D+1);B.push(...Et.templateTokens),Q=D+1,ee=Et.markerIndex;break}if(!pt.startsWith("-")){let Et=Il(O,D);B.push(...Et.templateTokens),Q=D,ee=Et.markerIndex;break}let gt=O[D+1],ht=pt.indexOf("="),yt=ht===-1?pt:pt.slice(0,ht),Ct=ht===-1?void 0:pt.slice(ht+1);if(pt==="--dry-run"){lt=!0,D++;continue}if(pt==="-I"||pt.startsWith("-I")&&pt.length>2){ct||=(pt==="-I"?gt: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"?Ct:pt.slice(2);ct||=Et!==""&&Et!=="{}",D++;continue}if(pt==="-a"||xR.has(yt)){ct=!0,D+=Ct===void 0?2:1;continue}if(pt==="--pipe"||pt==="--pipepart"){je=!0,D++;continue}if(yt==="--env"){ct=!0,D+=Ct===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(RR.has(yt)){ct=!0;let Et=Ct??gt;if(Et===void 0||Et===":::"||Et==="--"){D++;continue}at=Et,D+=Ct===void 0?2:1;continue}if(pt.startsWith("-j")&&pt.length>2&&/^\d+$/.test(pt.slice(2))){D++;continue}if(pt.startsWith("--")&&Ct!==void 0){D++;continue}if(ER.has(pt)){if(gt===void 0||gt===":::"||gt==="--"){ct=!0,D++;continue}D+=2;continue}D+=pt==="-j"||pt==="--jobs"?2:1}ct||=B.some(lt?Ql:Qm);let ut=[];if(ee!==-1){let pt=[];for(let gt=ee+1;gt<O.length;gt++){let ht=O[gt];if(ht===":::"){ut.push(pt),pt=[];continue}if(ht!==void 0)pt.push(ht)}ut.push(pt)}ct||=ut.length>1;let ft=OR(ut),dt=B.some(Nt),mt=B.length===0&&ee===-1;return{template:B,jobs:ft,childStart:Q,templateHasPlaceholder:dt,runsRemotely:he,usesStdin:je||ee===-1,readsCommandsFromInput:mt,unsupported:ct,workdir:at,dryRun:lt}}function OR(O){if(O.length===0||O.some((B)=>B.length===0))return[];let D=[[]];for(let[B,Q]of O.entries()){if(Q.length===1){let he=Q[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 ee=[];for(let he of D)for(let je of Q){if((ee.length+1)*(B+1)>a.derivedTokens.cap)throw new s("derivedTokens");ee.push([...he,je])}D=ee}return D}function np(O){return tp(O).childStart}var MR="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",Ts="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function tc(O){return O?.parts.some((D)=>D.provenance==="command-substitution")??!1}function ec(O){return O?.parts.some((D)=>D.provenance==="literal"&&D.raw.replace(/^["']/,"").startsWith("-"))??!1}function op(O,D,B,Q,ee=!1,he){let at=(xo(O,D)||Q&&O!=="powershell"&&D[0]?.provenance==="variable")&&Jt(he,"shell.dynamic-executable",ee)?St("shell.dynamic-executable",MR):null;return wt(at,he)??ip(O,D,B,ee,he)}function ip(O,D,B,Q,ee){if(D.length<2)return null;let he=D.flatMap((at,lt)=>tc(at)?[lt]:[]);if(he.length===0)return null;let je=It(D[0]?.text??"");if(je==="git"){let at=X(O,D),lt=NR(at);if(Jt(ee,"shell.dynamic-structure",Q)&&he.some((ft)=>ft<=lt))return wt(St("shell.dynamic-structure",Ts),ee);if(wt(bs(at,{environment:B}),ee))return null;let ct=D[lt]?.text.toLowerCase(),ut=at.findIndex((ft,dt)=>dt>lt&&t(ft)==="--");if(Jt(ee,"shell.dynamic-structure",Q)&&ct&&Jr.has(ct)&&he.some((ft)=>ft>lt&&(ut===-1||ft<ut)))return wt(St("shell.dynamic-structure",Ts),ee);return null}if(je==="find")return Jt(ee,"shell.dynamic-structure",Q)&&LR(D)?wt(St("shell.dynamic-structure",Ts),ee):null;if(je==="rm"){let at=D.findIndex((ct,ut)=>ut>0&&t(ct)==="--"),lt=Dn(D.map(t));return Jt(ee,"shell.dynamic-structure",Q)&&he.some((ct)=>(at===-1||ct<at)&&(ct<D.length-1||!lt))?wt(St("shell.dynamic-structure",Ts),ee):null}if(je==="xargs")return rp(O,D.slice(Ir(D.map(t)).childStart),"xargs",B,Q,ee);if(je==="parallel")return rp(O,D.slice(np(D.map(t))),"parallel",B,Q,ee);return null}function rp(O,D,B,Q,ee,he){if(D.length===0)return null;let je=DR(D,Q);if(xo(O,je)){let lt=wt(St(`${B}.shell-dynamic`,B==="xargs"?Zl:Qo),he);if(lt)return lt}let at=ip(O,je,Q,ee,he);if(at)return at;if(je[0]?.text==="rm"&&je.slice(1).some((lt)=>tc(lt)&&ec(lt)))return wt(St(`${B}.rm-recursive-force-dynamic`,B==="xargs"?Yl:Jo),he);return null}function DR(O,D){let B=Sr(O,D),Q=B.rewritten?$t(B.words.map(t)):B.words,ee=Q[0];return ee&&t(ee)==="busybox"?Q.slice(1):Q}function NR(O){let D=1;while(D<O.length){let B=O[D],Q=B?t(B):"";if(gn.has(Q)){D+=2;continue}if(Q.startsWith("-")){D++;continue}return D}return D}function LR(O){let D=!1,B=0,Q=!1,ee=!1;for(let he=1;he<O.length;he++){let je=O[he];if(!je)continue;let at=tc(je);if(B>0){B--;continue}if(ee){if(je.text===";"||je.text==="+"){ee=!1,D=!0,Q=!1;continue}if(at&&(Q||ec(je)))return!0;Q=!1;continue}if(!D&&!je.text.startsWith("-")){if(at&&(he>1||ec(je)))return!0;continue}if(D=!0,at)return!0;let lt=sr(je.text);if(lt>0){B=lt;continue}if(Kn(je.text))ee=!0,Q=!0}return!1}function nc(O,D){return O.some((B)=>{if(B.value==="-"&&(B.kind==="main-script"||B.kind==="program-file"))return!0;return!Bi(D[B.tokenIndex],B.value)})}var WR="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",GR="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",FR="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function sp(O,D){let B=D.slice(1);if(O==="dd"&&B.some((Q)=>/^of=\/dev\/.+/.test(Q)))return St("dd.device-write",WR);if((O==="mkfs"||O.startsWith("mkfs."))&&B.some((Q)=>Q.startsWith("/dev/")))return St("mkfs.device",GR);if(O==="shred"&&B.length>0)return St("shred.target",FR);return null}var lp=[{heads:new Set(["rm","rmdir"]),analyze:(O)=>Cs(O.words,{environment:O.options.environment,cwd:O.cwd,originalCwd:O.originalCwd,strict:O.options.strict,paranoid:O.options.paranoidRm,allowTmpdirVar:O.allowTmpdirVar,tmpdirWordSplittingUnsafe:ir(O.envAssignments,O.options.environment),trustedTmpdirValue:xr(O.envAssignments,O.options.environment),protectedGitMetadata:O.options.protectedGitMetadata,policy:O.options.policy,budget:O.options.budget})},{heads:new Set(["git"]),analyze:(O)=>bs(O.words,rc(O))},{heads:new Set(["find"]),analyze:(O)=>Vf(O.words,{environment:O.options.environment,cwd:O.cwd,originalCwd:O.originalCwd,strict:O.options.strict,allowTmpdirVar:O.allowTmpdirVar,tmpdirWordSplittingUnsafe:ir(O.envAssignments,O.options.environment),trustedTmpdirValue:xr(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)=>kr(O.options.analyzeNested(D,B))})},{heads:new Set(["xargs"]),analyze:(O)=>km(O.words,{...ap(O),analyzeChild:O.analyzeChild,analyzeNested:(D,B)=>kr(O.options.analyzeNested(D,B))})},{heads:new Set(["parallel"]),analyze:(O)=>Vm(O.words,{...ap(O),analyzeChild:O.analyzeChild,analyzeNested:(D,B)=>kr(O.options.analyzeNested(D,B))})}];function ap(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 kr(O){return O?{id:O.ruleId??"",reason:O.reason,intent:O.intent??"manual_only"}:null}function rc(O){return{environment:O.options.environment,cwd:O.cwd,originalCwd:O.originalCwd,dynamicArguments:O.dynamicArguments,envAssignments:O.envAssignments,shellAssignments:O.options.shellAssignments,policy:O.options.policy,worktreeMode:O.options.worktreeMode}}function fp(O){return lp.find((D)=>D.heads.has(O))?.analyze}function no(O,D,B){let Q=B.trace;if(O.length===0)return null;let ee=B.commandView?.dialect??"posix",he=(Rt)=>Rt.map((At)=>ee==="posix"?t(At):At.text),je=B.child,at=je!==void 0&&!je.embedded,lt=je?.embedded===!0,ct=B.effectiveCwd===null,ut=je?je.cwd:ct?void 0:B.effectiveCwd??B.cwd,ft=je?je.originalCwd:ct?void 0:B.cwd,dt=ge(O);if(dt.envAssignments.size>0)Q?.recordSegment({type:"env-strip",input:he(O),envVars:[...dt.envAssignments.keys()],output:he(dt.words)});let mt=Sr(dt.words,B.environment,ut,new Map([...B.envAssignments??[],...dt.envAssignments])),pt=mt.envSplitValues??[];if(pt.length>0){let Rt=[...pt,...he(mt.words)].join(" "),At=xn(Rt);if(At)return Q?.recordSegment({type:"dangerous-text",token:Rt,matched:!0,reason:At.reason}),sn(At);if(B.strict)return fn(Q);let Mt=Yi(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??[],...dt.envAssignments,...mt.envAssignments])});if(Yt)return Yt}}let gt=mt.rewritten?$t(he(mt.words)):X(ee,mt.words),ht=he(gt),yt={...B,wrapperNormalizationBudget:B.wrapperNormalizationBudget??{iterations:0}};if(Q&&dt.words.length>gt.length){let Rt=he(dt.words);Q.recordSegment({type:"leading-tokens-stripped",input:Rt,removed:Rt.slice(0,Rt.length-gt.length),output:ht})}let Ct=new Map([...B.envAssignments??[],...dt.envAssignments,...mt.envAssignments]),Et=ht[0];if(!Et)return null;if(wr(Et))throw new s("wrapperPeelIterations");let vt=It(Et),Pt=mt.cwd===null?void 0:mt.cwd??ut,xt=mt.cwd===null?void 0:ft,_t=mt.cwd===void 0?B.effectiveCwd:mt.cwd,Ut=je?je.allowTmpdirVar:!zo(Ct,B.environment),jt=op(ee,mt.words,B.environment,D===0,B.strict,B.policy);if(jt)return Q?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:jt.reason}),sn(jt);let qt=fs(ht,B.policy);if(qt){for(let Rt of[qt.childIndex,...qt.alternativeChildIndices]){cp(yt.wrapperNormalizationBudget);let At=gt.slice(Rt);Q?.recordSegment({type:"transparent-wrapper",wrapper:qt.wrapper,output:he(At)});let Mt=no(At,D,{...yt,effectiveCwd:_t,envAssignments:Ct});if(Mt)return Mt}return null}let Vt=lt?void 0:vt==="eval"?vs(gt):vt==="trap"&&!at?Rm(gt):void 0;if(at&&je&&vt==="eval"){if(Vt?.kind==="dynamic")return to(je,B.policy);if(Vt?.kind==="literal"){let Rt=B.analyzeNested(Vt.source,{effectiveCwd:_t,envAssignments:Ct});if(Rt)return Rt}return ro(je,B.policy)}if(Vt?.kind==="dynamic"&&(B.strict||!B.commandView||!Kl(B.commandView)))return fn(Q);if(Vt?.kind==="literal"){Q?.recordSegment({type:"recurse",reason:vt==="eval"?"shell-eval":"shell-trap",innerCommand:Vt.source,depth:D+1});let Rt=B.analyzeNested(Vt.source,{effectiveCwd:_t,envAssignments:Ct,functionDefinitions:B.functionDefinitions});if(Rt)return Rt}if(at?Kt.has(vt):pp(Et,vt)){if(Zn(ht))return null;if(at&&je){let Rt=Yn(ht);if(Rt){if(je.dynamicSourceInput??je.dynamicInput){let Mt=to(je,B.policy);if(Mt)return Mt}if(Xo(Rt)){let Mt=to(je,B.policy);if(Mt)return Mt}return B.analyzeNested(Rt,{effectiveCwd:_t,envAssignments:Ct})}let At=qn(gt);if(At.kind==="dynamic")return to(je,B.policy);if(At.kind==="literal")return je.dynamicSourceInput?to(je,B.policy):null;return je.dynamicSourceInput??je.dynamicInput?to(je,B.policy):null}if(lt){let Rt=Yn(ht),At=Rt?B.analyzeNested(Rt,{effectiveCwd:_t,envAssignments:Ct}):qn(gt).kind==="dynamic"?fn(Q):null;if(At)return At}if(je===void 0){let Rt=UR(ht,Ct,_t,B,Q,D);if(Rt)return Rt;let At=Yn(ht);if(At){let Dr=Es(gt,At);if(Dr.kind==="dynamic")return fn(Q);let js=Dr.kind==="literal"?Dr.source:At,Pc=HR(js);Q?.recordSegment({type:"shell-wrapper",wrapper:vt,innerCommand:Pc}),Q?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:Pc,depth:D+1});let Ac=B.analyzeNested(js,{effectiveCwd:_t,envAssignments:Ct});if(Ac)return Ac;return Xo(js)?fn(Q):null}let Mt=qn(gt);if(Mt.kind==="dynamic")return fn(Q);if(Mt.kind==="literal")return Is(Mt.source,_t,Ct,B,Q,D);let Yt=_m(gt,B.commandView?.redirections??[],B.hasPipelineInput??!1,B.literalShellInput);if(Yt.kind==="dynamic")return fn(Q);if(Yt.kind==="literal")return Q?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:Yt.source,depth:D+1}),B.analyzeNested(Yt.source,{effectiveCwd:_t,envAssignments:Ct})}}if(!je&&(vt==="source"||vt===".")){let Rt=ht[1]==="-p"?2:null;if(Rt!==null){let Dr=B.commandView?gt[Rt]:void 0;if(!Dr)return null;if(Dr.provenance!=="literal")return fn(Q)}let At=Rt===null?1:3,Mt=ht[At]==="--"?At+1:At,Yt=B.commandView?gt[Mt]:void 0;if(!Yt)return null;if(Yt.provenance==="literal")return Is(Yt.text,_t,Ct,B,Q,D);if(B.strict||!B.commandView||!Kl(B.commandView))return fn(Q)}if(En.has(vt)&&!lt){if(!je&&B.strict&&nc(jo(ht),gt))return fn(Q);let Rt=Bf(ht,(Mt)=>kr(B.analyzeNested(Mt,{effectiveCwd:_t,envAssignments:Ct}))),At=wt(Rt,B.policy);if(At)return Q?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:At.reason}),sn(At)}if(An(vt)&&!lt){if(!je&&B.strict&&nc(ji(ht),gt))return fn(Q);let Rt=Gd(ht);if(at&&je)return BR(vt,Rt,_t,Ct,B,je);if(Rt){let At=Jt(B.policy,"interpreter.one-liner-paranoid",!!B.paranoidInterpreters);if(Q?.recordSegment({type:"interpreter",interpreter:vt,codeArg:Rt,paranoidBlocked:At}),At){let Yt=wt(St("interpreter.one-liner-paranoid",ko),B.policy);if(Yt)return sn(Yt)}if(sl(vt,Rt))return null;Q?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:Rt,depth:D+1});let Mt=B.analyzeNested(Rt,{effectiveCwd:_t,envAssignments:Ct});if(Mt&&!mp(Mt,Rt))return Mt;if(Oo(Rt,void 0,!B.strict)){let Yt=wt(St("interpreter.dangerous-command",Kr),B.policy);if(Yt)return Q?.recordSegment({type:"dangerous-text",token:Rt,matched:!0,reason:Kr}),sn(Yt)}Q=void 0}}if(vt==="busybox"&&ht.length>1)return cp(yt.wrapperNormalizationBudget),Q?.recordSegment({type:"busybox",subcommand:ht[1]??"unknown"}),Q?.recordSegment({type:"recurse",reason:"busybox",innerCommand:ht.slice(1).join(" "),depth:D+1}),no(gt.slice(1),D,{...yt,effectiveCwd:_t,envAssignments:Ct});let Ot=je?null:wt(sp(vt,ht),B.policy);if(Ot)return Q?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:Ot.reason}),sn(Ot);let on=Q===yt.trace?yt:{...yt,trace:Q},Cn={words:gt,head:vt,cwd:Pt,originalCwd:xt,envAssignments:Ct,allowTmpdirVar:Ut,dynamicArguments:mt.words.some((Rt)=>Rt.provenance==="command-substitution"),depth:D,effectiveCwd:_t,options:on,analyzeChildTokens:(Rt,At)=>at&&je?oc(Rt,D,on,{...je,cwd:At??void 0,effectiveCwd:At??void 0}):kr(no($t(Rt),D+1,{...on,child:void 0,commandView:void 0,effectiveCwd:At,envAssignments:Ct}))??_(Rt,on.policy.rules),analyzeChild:(Rt,At)=>oc(Rt,D,on,At)},Bn=je&&(vt==="xargs"||vt==="parallel")?void 0:fp(vt);if(vt==="rm"||vt==="xargs"||vt==="parallel")Q?.recordSegment({type:"tmpdir-check",tmpdirValue:Ct.has("TMPDIR")||B.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:Ut});let wn=Q&&vt==="git"?hm(Cn.words,rc(Cn)):void 0,Us=up(wn?wn.match:Bn?.(Cn)??null,B.policy);if(Q)jR(Cn,Us,wn?.relaxation??null);if(Us)return sn(Us);if(at&&je&&(vt==="rm"||vt==="rmdir")){if(!(vt==="rm"&&(Dn(ht)||je.dynamicRmInput)))return null;return(je.dynamicRmInput?ro(je,B.policy):null)??$R(je,B.policy)}let wc=!je&&Bn===void 0&&!bi.has(vt),Hs=Q&&wc?[]:void 0;if(wc)for(let Rt=1;Rt<ht.length;Rt++){let At=ht[Rt];if(!At)continue;Hs?.push(At);let Mt=up(zR(ht,Rt,D,on,Pt,xt,_t,Ct),B.policy);if(Mt)return Q?.recordSegment({type:"fallback-scan",tokensScanned:Hs??[],embeddedCommandFound:It(At)}),sn(Mt)}if(Q?.recordSegment({type:"fallback-scan",tokensScanned:Hs??[]}),lt&&je&&!je.wrappedByTransparent)return null;let si=_(ht,B.policy.rules);if(Q?.recordSegment({type:"custom-rules-check",rulesChecked:B.policy.rules.length>0,matched:!!si,reason:si?.reason}),si)return sn(si);return at&&je?ro(je,B.policy):null}function oc(O,D,B,Q){return kr(no($t(O),D+1,{...B,trace:void 0,commandView:void 0,hasPipelineInput:void 0,literalShellInput:void 0,functionDefinitions:void 0,cwd:Q.originalCwd,effectiveCwd:Q.effectiveCwd,envAssignments:Q.envAssignments,worktreeMode:Q.dynamicInput?!1:Q.worktreeMode,wrapperNormalizationBudget:{iterations:0},child:Q}))}function zR(O,D,B,Q,ee,he,je,at){for(let lt of Mn(O.slice(D),{environment:Q.environment,cwd:ee,envAssignments:at,policy:Q.policy})){let ct=lt.tokens[0];if(!ct)continue;let ut=It(ct);if(pp(ct,ut)||fp(ut)!==void 0&&ut!=="xargs"&&ut!=="parallel"||lt.wrappedByTransparent&&Q.policy.rules.length>0)Q.budget.charge("derivedTokens",O.length-D);let dt=oc(lt.tokens,B,Q,{embedded:!0,cwd:lt.cwd,originalCwd:lt.wrapperCwd===null?void 0:he,effectiveCwd:lt.wrapperCwd===void 0?je:lt.wrapperCwd,envAssignments:lt.envAssignments,allowTmpdirVar:!zo(lt.envAssignments,Q.environment),worktreeMode:!1,wrappedByTransparent:lt.wrappedByTransparent});if(dt)return dt}return null}function BR(O,D,B,Q,ee,he){if(!D)return ro(he,ee.policy);if(Jt(ee.policy,"interpreter.one-liner-paranoid",!!ee.paranoidInterpreters)){let at=wt(St("interpreter.one-liner-paranoid",ko),ee.policy);if(at)return sn(at)}if(sl(O,D))return ro(he,ee.policy);let je=ee.analyzeNested(D,{effectiveCwd:B,envAssignments:Q});if(je&&!mp(je,D))return je;if(Oo(D,void 0,!ee.strict)){let at=wt(St("interpreter.dangerous-command",Kr),ee.policy);if(at)return sn(at)}return ro(he,ee.policy)}function mp(O,D){if(O.ruleId==="raw-text.dangerous-command")return!0;return(O.reason.startsWith(cs)||O.reason===Xr)&&!Si(D)}function to(O,D){let B=O.shellDynamicMatch?wt(O.shellDynamicMatch,D):null;return B?sn(B):null}function ro(O,D){let B=O.dynamicSourceInput&&O.dynamicSourceMatch?wt(O.dynamicSourceMatch,D):null;return B?sn(B):null}function $R(O,D){let B=O.dynamicInput&&O.rmDynamicMatch?wt(O.rmDynamicMatch,D):null;return B?sn(B):null}function UR(O,D,B,Q,ee,he){let je=Am(O);if(je.argvSource?.kind==="absent")return fn(ee);if(je.argvSourceApplies&&je.argvSource){let lt=Is(je.argvSource.value,B,D,Q,ee,he,!0);if(lt)return lt}if(!je.envSourceApplies||!je.envName)return null;let at=D.get(je.envName);if(!at)return null;return Is(at,B,D,Q,ee,he,!0)}function Is(O,D,B,Q,ee,he,je=!1){if(je&&/[$`*?[\]]/.test(O))return fn(ee);let at=Io(O,D,Q.environment.paths,Q.budget),lt=at?Q.literalHeredocFiles?.get(at):void 0;if(lt===void 0)return je?fn(ee):null;return Q.budget.charge("derivedTokens",1),ee?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:lt,depth:he+1}),Q.analyzeNested(lt,{effectiveCwd:D,envAssignments:B})}function HR(O){let D=O[0];return O.length>=2&&(D==='"'||D==="'")&&O.at(-1)===D?O.slice(1,-1):O}function jR(O,D,B){let Q={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(!Q)return;if(O.options.trace?.recordSegment({type:"rule-check",rule:Q,matched:!!D||!!B,reason:D?.reason??B?.originalReason}),B)O.options.trace?.recordSegment({type:B.kind==="worktree"?"worktree-relaxation":"temp-root-relaxation",originalReason:B.originalReason,gitCwd:B.gitCwd})}function cp(O){if(O.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");O.iterations++}function sn(O){return{reason:O.reason,ruleId:O.id||void 0,intent:O.intent}}function fn(O){return O?.recordSegment({type:"error",message:Uo}),sn(VR())}function VR(){return{id:"",reason:Uo,intent:"stop_and_explain"}}function pp(O,D){return Kt.has(D)||O==="$SHELL"||O==="${SHELL}"||Kt.has(Tt(D))}function up(O,D){return O?.id.startsWith("custom.")||O?.id==="raw-text.dangerous-command"?O:wt(O,D)}var KR=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,qR=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function YR(O,D){let B=yp(O,D);if(B.length===0)return!1;let Q=B[hp(B)];if(Q==="cd"||Q==="pushd"||Q==="popd")return!0;return KR.test(O.join(" "))}function gp(O,D,B,Q,ee){if(O.dialect==="powershell"){let ht=XR(O.words,ee);if(ht.kind==="none")return;if(!D||ht.kind==="unknown")return null;return dp(t_(ht.target),D,B.paths)}let he=O.words.map(t),je=he.some((ht)=>/^CDPATH\+?=/.test(ht));if(!YR(he,B))return je?null:void 0;if(!D)return null;let at=yp(he,B,D),lt=hp(at);if(lt===-1||at[lt]!=="cd")return null;let ct=at.slice(lt+1),ut=ct.findIndex((ht)=>ht.length<=1||!ht.startsWith("-")||ht==="--");if((ut===-1?ct:ct.slice(0,ut)).some((ht)=>!/^-[LP]+$/.test(ht)))return null;let dt=ut===-1?[]:ct.slice(ut),mt=dt[0]==="--"?dt.slice(1):dt;if(mt.length!==1)return null;let pt=mt[0]??"",gt=O.words.some((ht)=>ht.provenance==="variable"&&ht.text===pt)?ZR(pt,Q):pt;if(gt===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(gt)&&(je||B.env.has("CDPATH")))return null;return dp(gt,D,B.paths)}function ZR(O,D){let B=qo(O,D);return B.startsWith("~")||/[\s$`*?[]/.test(B)?null:B}function dp(O,D,B){if(!O||O==="-"||O.includes("$")||O.includes("`"))return null;try{return nr(D,O,B)}catch{return null}}function XR(O,D){let B=JR(O[0])?1:0,Q=O[B];if(!QR(Q,B===1))return{kind:"none"};let ee=Q.text.toLowerCase(),he=ee.split(/[\\/]/).pop()??ee;if(!qR.has(he))return{kind:"none"};if(ee!==he||he==="pop-location"||he==="popd")return{kind:"unknown"};return e_(O.slice(B+1),D)}function JR(O){return O?.provenance==="literal"&&!O.quoted&&O.raw===O.text&&(O.text==="&"||O.text===".")}function QR(O,D){return O?.provenance==="literal"&&(D||!O.quoted&&O.raw===O.text)}function e_(O,D){let B;for(let Q of O){if(Q.provenance!=="literal"||B!==void 0)return{kind:"unknown"};B=Q.text}if(B!==void 0)return{kind:"target",target:B};return D===void 0?{kind:"unknown"}:{kind:"target",target:D}}function t_(O){return O.includes("::")?void 0:O.replaceAll("\\","/")}function hp(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 yp(O,D,B){let Q=n_(O);return rr([...Q],D,B)}function n_(O){let D=0;while(D<O.length){let B=O[D];if(B!=="{"&&B!=="("&&B!=="$(")break;D++}return O.slice(D)}var r_="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Or="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 cc(O,D,B,Q){if(D>=a.recursionDepth.cap)return B.trace?.recordSegment({type:"error",message:Wn}),{reason:Wn,segment:O,intent:"stop_and_explain"};let ee=Q??B.factStore?.getCommandProgram(O,B.shell??"auto")??h(O,B.shell);if(ee.status==="limited")return B.trace?.recordSegment({type:"error",message:Wn}),{reason:Wn,segment:O,intent:"stop_and_explain"};if(ee.status==="invalid"){let ct=ee.issues.find((ut)=>ut.code.includes("heredoc"));if(ct){if(!B.strict)return lc(O,B);let ut=`${cs}: ${ct.message}`;return B.trace?.recordGlobal({type:"error",message:ut}),{reason:ut,segment:O,intent:"stop_and_explain"}}return xp(O,B),{reason:Xr,segment:O,intent:"stop_and_explain"}}if(B.strict&&ee.status==="partial")return xp(O,B),{reason:Xr,segment:O,intent:"stop_and_explain"};if(ee.issues.some((ct)=>ct.code.includes("quote")))return lc(O,B);let je=B.cwd,at=B.effectiveCwd!==void 0?B.effectiveCwd:B.cwd,lt=om(B.environment.env,B.envAssignments);return Ms(ee,D,{...B,rootProgram:ee},je,[{effectiveCwd:at,shellGitContextState:lt,literalHeredocFiles:new Map(B.literalHeredocFiles),functionDefinitions:new Map(B.functionDefinitions)}]).result}function Ms(O,D,B,Q,ee){let he=[...ee],je,at;for(let[lt,ct]of O.nodes.entries()){if(ct.kind==="connector"){at=ct.operator;continue}let ut=O.nodes[lt+1],ft=ut?.kind==="connector"?ut.operator:void 0,dt=o_(O,lt,ct,at,ft),mt=at==="&&"||at==="||",pt=mt?je:void 0,gt=at==="&&"?pt?.success??he:at==="||"?pt?.failure??he:he,ht=at==="||"?pt?.success??[]:[],yt=at==="&&"?pt?.failure??[]:[],Ct=mt||io(ft);if(ct.kind==="function"){let jt=gt.flatMap((Vt)=>{let Ft=so(Vt);return Ft.functionDefinitions.set(ct.name,ct.body),ic(Vt,[Ft],dt,ft==="&",io(ft))}),qt=sc(jt,[],ht,yt,at,ft);he=qt.states,je=qt.conditionalStates,at=void 0;continue}if(ct.kind==="group"){let jt=[],qt=[];for(let Ft of gt){let Ot=Ms(ct.body,D,B,Q,[so(Ft)]);if(Ot.result)return Ot;if(jt.push(...ic(Ft,Ot.states,dt,ft==="&",io(ft))),Ct)qt.push(Ft,...dt?Ot.states.map((on)=>ks(Ft,on)):Ot.states)}let Vt=sc(jt,qt,ht,yt,at,ft);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(),vt=O.nodes[lt-2],Pt=Ds(at)&&vt?.kind==="command"?xm(vt)??s_(vt):void 0,xt=[],_t=[];for(let jt of gt){let qt=a_(ct,D,B,Q,[so(jt)]);if(qt.result)return{result:qt.result,states:he};let Vt=O.dialect==="powershell"?qt.states:qt.states.map((Ft)=>ks(jt,Ft));for(let Ft of Vt){let Ot=so(Ft),on=u_(ct,D,B.trace?{...B,trace:Rp(B.trace,Et)}:B,Q,Ot,Ds(at),Pt);if(on)return{result:on,states:he};let Cn=w_(ct,Ot.functionDefinitions);if(Cn)B.budget.charge("derivedTokens",Ns(Cn));let Bn=Cn?D+1>=a.recursionDepth.cap?ac(ct.displayText,B,[Ot]):Ms(Cn,D+1,B,Q,[Ot]):{result:null,states:R_(ct,Ot)};if(Bn.result)return Bn;if(xt.push(...ic(jt,Bn.states,dt,ft==="&",io(ft))),Ct)_t.push(jt),_t.push(...Bn.states.map((wn)=>dt?ks(jt,wn):wn))}}let Ut=sc(xt,_t,ht,yt,at,ft);he=Ut.states,je=Ut.conditionalStates,at=void 0}return{result:null,states:he}}function o_(O,D,B,Q,ee){if(B.kind==="group"&&B.style==="subshell")return!0;if(O.dialect==="posix"&&(Ds(Q)||Ds(ee)))return!0;if(ee==="&")return!0;return O.dialect==="powershell"&&B.kind==="group"&&B.style==="brace"&&i_(O,D)}function ic(O,D,B,Q,ee){let he=B?D.map((at)=>ks(O,at)):[...D],je=ee?he.flatMap((at)=>oo(O.literalHeredocFiles,at.literalHeredocFiles)?[at]:[{...at,literalHeredocFiles:new Map(O.literalHeredocFiles)},at]):he;return Q?[O,...je]:je}function ks(O,D){return{...O,literalHeredocFiles:new Map(D.literalHeredocFiles)}}function i_(O,D){let B=O.nodes.slice(0,D).reverse().find((ee)=>ee.kind==="command"||ee.kind==="connector");if(!B||B.kind!=="command")return!0;let Q=B.words[0]?.text.toLowerCase();if(Q==="&"||Q===".")return!1;if(Q==="write-output"||Q==="function"||Q==="start-job")return!0;if(l_(B))return!0;return B.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function Ds(O){return O==="|"||O==="|&"}function s_(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 io(O){return O==="&&"||O==="||"}function sc(O,D,B,Q,ee,he){let je={success:Os([...B,...O]),failure:Os([...Q,...D])},at=io(he)?je:void 0;return{states:io(ee)||at?Os([...je.success,...je.failure]):je.success,conditionalStates:at}}function Rp(O,D,B=O.flattenNested){return{currentSegmentIndex:D,flattenNested:B,allocateSegment:O.allocateSegment,getNextSegmentIndex:O.getNextSegmentIndex,recordGlobal:O.recordGlobal,recordSegment:(Q,ee=D)=>O.recordSegment(Q,ee)}}function a_(O,D,B,Q,ee){let he=O.nested.map((je)=>({program:je,depth:D}));if(O.dialect==="powershell"){let je=c_(O);if(je){if(D+1>=a.recursionDepth.cap)return ac(je,B,ee);let at=h(je,"powershell");if(at.status==="limited")return ac(je,B,ee);if(at.status!=="complete")return bp(he,B,Q,ee);B.budget.charge("derivedTokens",Ns(at)),he.push({program:at,depth:D+1})}}return bp(he,B,Q,ee)}function l_(O){let D=O.words[0];return D?.provenance==="variable"&&O.words.at(-1)?.text==="="?D.text.toLowerCase():void 0}function bp(O,D,B,Q){let ee=[...Q];for(let he of O){let je=[];for(let at of ee){let lt=Ms(he.program,he.depth,D,B,[so(at)]);if(lt.result)return lt;je.push(...lt.states)}ee=Os(je)}return{result:null,states:ee}}function c_(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,Q=O.words[B];if(Q?.provenance!=="literal"||!D&&(Q.quoted||Q.raw!==Q.text)||!["iex","invoke-expression"].includes(Q.text.toLowerCase()))return;let ee=O.words.slice(B+1),he=ee[0]&&!ee[0].quoted&&ee[0].raw===ee[0].text&&["-c","-command"].includes(ee[0].text.toLowerCase())?1:0,je=ee[he];return ee.length===he+1&&je?.quoted&&je.provenance==="literal"?je.text:void 0}function Ns(O){return O.nodes.reduce((D,B)=>D+(B.kind==="command"?B.words.length+B.nested.reduce((Q,ee)=>Q+Ns(ee),0):B.kind==="group"||B.kind==="function"?Ns(B.body):0),0)}function ac(O,D,B){return D.trace?.recordSegment({type:"error",message:Wn}),{result:{reason:Wn,segment:O,intent:"stop_and_explain"},states:[...B]}}function u_(O,D,B,Q,ee,he,je){let at={...B,environment:{...B.environment,env:ee.shellGitContextState.env}},lt=y_(O,!at.strict);if(lt&&at.strict)return at.trace?.recordSegment({type:"error",message:lt}),{reason:lt,segment:O.source,intent:"stop_and_explain"};_p(O,ee,"before-consumer",at.environment.paths,at.budget);let ct=X(O.dialect,O.words),ut=ct.map(t),ft=O.displayText,dt=rm(ct,ee.shellGitContextState),mt=sm(dt,ee.shellGitContextState);if(O.dialect==="powershell"){let ht=wt(Mf(O,he,A_(at,ee.effectiveCwd)),at.policy);if(at.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!ht,reason:ht?.reason}),ht)return P_(ft,ht)}if(ut.length===1&&ut[0]?.includes(" ")&&!xo(O.dialect,O.words)){let ht=wt(xn(ut[0]),at.policy),yt=ht!==null&&!at.strict&&Dd(O,at.rootProgram);if(ht&&!yt)return at.trace?.recordSegment({type:"dangerous-text",token:ut[0],matched:!0,reason:ht.reason}),{reason:ht.reason,segment:ft,ruleId:ht.id,intent:ht.intent};at.trace?.recordSegment({type:"dangerous-text",token:ut[0],matched:!1});let Ct=Sp(O,lt,ee,mt,je,at);if(Ct)return Ct;return Bl(dt,ee.shellGitContextState),null}let pt=no(O.words,D,{...at,commandView:O,cwd:Q,effectiveCwd:ee.effectiveCwd,envAssignments:mt,shellAssignments:ee.shellGitContextState.shellAssignments,literalHeredocFiles:ee.literalHeredocFiles,functionDefinitions:ee.functionDefinitions,hasPipelineInput:he,literalShellInput:je,analyzeNested:(ht,yt)=>{let Ct=yt&&Object.hasOwn(yt,"effectiveCwd")?yt.effectiveCwd:ee.effectiveCwd,Et=cc(ht,D+1,{...at,effectiveCwd:Ct,envAssignments:yt?.envAssignments??mt,literalHeredocFiles:ee.literalHeredocFiles,functionDefinitions:yt?.functionDefinitions,worktreeMode:yt?.worktreeMode??at.worktreeMode,trace:at.trace?Rp(at.trace,at.trace.currentSegmentIndex,!0):void 0});return Et?{reason:Et.reason,ruleId:Et.ruleId,intent:Et.intent}:null}});if(pt)return{...pt,segment:ft};let gt=Sp(O,lt,ee,mt,je,at);if(gt)return gt;return Bl(dt,ee.shellGitContextState),null}function Sp(O,D,B,Q,ee,he){let je=b_(O,D,B,Q??new Map,he);if(je)return je;return _p(O,B,"after-consumer",he.environment.paths,he.budget),B.literalHeredocFiles.clear(),m_(O,D,B,he.environment.paths,he.budget),v_(O,B,ee,he.environment,he.trace),null}var d_=new Set([">>","<>"]);function _p(O,D,B,Q,ee){for(let je of O.redirections){if(!(B==="before-consumer"?f_(je):d_.has(je.operator)))continue;Cp(je.target,D,Q,ee)}if(B!=="before-consumer"||!nn(O.words[0],"tee"))return;let he=wp(O.words.slice(1));if(!he)return;for(let je of he.operands)Cp(je,D,Q,ee)}function f_(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 Cp(O,D,B,Q){let ee=O?.provenance==="literal"?Io(O.text,D.effectiveCwd,B,Q):void 0;if(!ee)return;D.literalHeredocFiles.delete(ee)}function m_(O,D,B,Q,ee){if(D)return;let he=O.redirections.find((je)=>je.operator==="<<"||je.operator==="<<-")?.heredoc;if(!he)return;for(let je of p_(O)){let at=Io(je.text,B.effectiveCwd,Q,ee);if(!at||!Wd(at))continue;if(!B.literalHeredocFiles.has(at)&&B.literalHeredocFiles.size>=a.trackedHeredocFiles.cap)throw new s("trackedHeredocFiles");B.literalHeredocFiles.set(at,he.body)}}function p_(O){let D=h_(O.redirections)?.target,B=vp(D)?[D]:[];if(nn(O.words[0],"cat"))return g_(O.words)?B:[];if(!nn(O.words[0],"tee"))return[];let Q=wp(O.words.slice(1));if(!Q||Q.append||Q.hasUnsupportedOptions||!Q.operands.every(vp))return[];return[...Q.operands,...B]}function g_(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 h_(O){let D=O.findLast((B)=>(B.fd??([">",">|",">>",">&"].includes(B.operator)?1:0))===1);return D?.operator===">"||D?.operator===">|"?D:void 0}function wp(O){let D=[],B=!0,Q=!1,ee=!1;for(let he of O){if(he.provenance!=="literal")return;if(B&&nn(he,"--")){B=!1;continue}if(B&&!he.quoted&&he.raw===he.text&&/^-[^-]/.test(he.text)){Q||=he.text.slice(1).includes("a"),ee||=Array.from(he.text.slice(1)).some((je)=>je!=="a"&&je!=="i");continue}if(B&&!he.quoted&&he.raw===he.text&&he.text.startsWith("--")){Q||=he.text==="--append",ee||=he.text!=="--append"&&he.text!=="--ignore-interrupts";continue}D.push(he)}return{operands:D,append:Q,hasUnsupportedOptions:ee}}function vp(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 nn(O,D){return O?.text===D&&O.raw===D&&O.provenance==="literal"&&!O.quoted}function uc(O){return O.quotedDelimiter||!/[$`\\]/.test(O.body)}function y_(O,D){let B=O.redirections.filter((at)=>at.operator==="<<"||at.operator==="<<-");if(B.length===0)return;if(B.length!==1)return Or;let Q=B[0];if(!Q?.heredoc)return Or;if(!uc(Q.heredoc)&&!(D&&!/\$\(|`/.test(Q.heredoc.body)))return r_;if(Q.fd!==void 0&&Q.fd!==0)return Or;if(O.redirections.some((at)=>at!==Q&&["<","<<","<<-","<<<","<&","<>"].includes(at.operator)))return Or;let ee=O.redirections.some((at)=>at!==Q&&Ep(at.target));if(nn(O.words[0],"cat"))return ee?Or:void 0;if(nn(O.words[0],"tee"))return ee||O.words.slice(1).some(Ep)?Or:void 0;let he=O.words[0],je=O.words[1];if(nn(he,"git")&&(nn(je,"apply")||nn(je,"commit")))return;if(nn(he,"gh")&&(nn(je,"pr")||nn(je,"issue"))&&nn(O.words[2],"create"))return;return Or}function Ep(O){return O?.parts.some((D)=>D.provenance==="command-substitution"&&D.raw.startsWith(">("))??!1}function b_(O,D,B,Q,ee){if(!D)return null;let he=O.redirections.filter((ct)=>ct.operator==="<<"||ct.operator==="<<-"),je=he.flatMap((ct)=>ct.heredoc?[ct.heredoc.body]:[]);if(C_(O,he,B,Q,ee))return null;let at=S_(O,he,ee);if(at!==void 0)return at?{reason:at.reason,segment:O.displayText,ruleId:at.id,intent:at.intent}:null;let lt=lc(je.length===he.length?je.join(`
|
|
41
|
+
`):O.source,ee);return lt?{...lt,segment:O.displayText}:null}function S_(O,D,B){let Q=D.length===1?D[0]:void 0;if(!Q?.heredoc||!uc(Q.heredoc)||Q.fd!==void 0&&Q.fd!==0)return;let ee=nn(O.words[0],"uv")&&nn(O.words[1],"run")?O.words.slice(2):O.words,he=ee[0];if(he?.provenance!=="literal"||!An(he.text))return;let je=ee.findIndex((ft)=>nn(ft,"-"));if(!ee.slice(1,je===-1?void 0:je).every((ft)=>ft.provenance==="literal"&&ft.text.startsWith("-")))return;let lt=Q.heredoc.body,ct=Jt(B.policy,"interpreter.one-liner-paranoid",!!B.paranoidInterpreters);if(B.trace?.recordSegment({type:"interpreter",interpreter:he.text,codeArg:lt,paranoidBlocked:ct}),ct){let ft=wt(St("interpreter.one-liner-paranoid",ko),B.policy);if(ft)return ft}if(!Oo(lt,void 0,!B.strict))return null;let ut=wt(St("interpreter.dangerous-command",Kr),B.policy);if(!ut)return null;return B.trace?.recordSegment({type:"dangerous-text",token:lt,matched:!0,reason:ut.reason}),ut}function C_(O,D,B,Q,ee){let he=D.length===1?D[0]:void 0;if(!he?.heredoc||!uc(he.heredoc)||he.fd!==void 0&&he.fd!==0)return!1;let je=Sr(O.words,ee.environment,B.effectiveCwd,Q),at=je.words.map(t),lt=It(at[0]??"");if((je.envSplitValues?.length??0)>0||!Kt.has(lt)&&!Kt.has(Tt(lt)))return!1;return Zn(at)}function v_(O,D,B,Q,ee){let he=gp(O,D.effectiveCwd,Q,D.shellGitContextState.shellAssignments,B);if(he===null)ee?.recordSegment({type:"cwd-change",segment:O.words.map(t).join(" "),effectiveCwdNowUnknown:!0});if(he!==void 0)D.effectiveCwd=he}var E_=/^[A-Za-z_][A-Za-z0-9_]*$/,x_=8;function R_(O,D){let B=O.words[1]?.text;if(O.dialect!=="posix"||O.words[0]?.text!=="for"||B===void 0||!E_.test(B))return[D];let Q=O.words.slice(3);if(!(O.words[2]?.text==="in"&&Q.length>=1&&Q.length<=x_&&Q.every((he)=>he.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(he.text))))return D.shellGitContextState.shellAssignments.delete(B),[D];return Q.map((he)=>{let je=so(D);return je.shellGitContextState.shellAssignments.set(B,he.text),je})}function so(O){return{effectiveCwd:O.effectiveCwd,shellGitContextState:im(O.shellGitContextState),literalHeredocFiles:new Map(O.literalHeredocFiles),functionDefinitions:new Map(O.functionDefinitions)}}function Os(O){let D=[];for(let B of O){if(!D.some((Q)=>__(Q,B)))D.push(B);if(D.length>a.controlFlowStates.cap)throw new s("controlFlowStates")}return D}function __(O,D){return O.effectiveCwd===D.effectiveCwd&&oo(O.shellGitContextState.env,D.shellGitContextState.env)&&oo(O.literalHeredocFiles,D.literalHeredocFiles)&&oo(O.functionDefinitions,D.functionDefinitions)&&oo(O.shellGitContextState.effectiveEnvAssignments,D.shellGitContextState.effectiveEnvAssignments)&&oo(O.shellGitContextState.shellAssignments,D.shellGitContextState.shellAssignments)&&O.shellGitContextState.bodyDepth===D.shellGitContextState.bodyDepth&&O.shellGitContextState.bodyAssignments.size===D.shellGitContextState.bodyAssignments.size&&[...O.shellGitContextState.bodyAssignments].every((B)=>D.shellGitContextState.bodyAssignments.has(B))}function oo(O,D){if(O===D)return!0;if(!O||!D||O.size!==D.size)return!1;return[...O].every(([B,Q])=>D.get(B)===Q&&D.has(B))}function w_(O,D){let B=Ro(O);return B===void 0?void 0:D.get(B)}function P_(O,D){if(!D)return null;return{reason:D.reason,segment:O,ruleId:D.id,intent:D.intent}}function A_(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 lc(O,D){let B=wt(xn(O),D.policy),Q=D.trace?.currentSegmentIndex??D.trace?.allocateSegment(),ee={type:"dangerous-text",token:O,matched:!!B,reason:B?.reason};if(D.trace?.recordSegment(ee,Q),!B&&/^(?:cd|pushd)\s/.test(O))D.trace?.recordSegment({type:"cwd-change",segment:O,effectiveCwdNowUnknown:!0},Q);return B?{reason:B.reason,segment:O,ruleId:B.id,intent:B.intent}:null}function xp(O,D){let B={type:"strict-unparseable",rawCommand:O,reason:Xr},Q=D.trace?.currentSegmentIndex;if(Q===void 0)D.trace?.recordGlobal(B);if(Q!==void 0)D.trace?.recordSegment(B)}var T_=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function Pp(O,D,B,Q){let ee=cc(O,0,{...D,...Fe(D),budget:D.budget??mn(),factStore:Q},B);if(!ee)return null;return{kind:"deny",reason:ee.reason,intent:ee.intent??"manual_only",...ee.ruleId?{ruleId:ee.ruleId}:{},evidence:{command:O,segment:ee.segment}}}function Ap(O,D,B){try{return{decision:O()}}catch(Q){let ee=I_(Q,D,B);if(!ee)throw Q;return ee}}function I_(O,D,B){if(!(O instanceof s)||!T_.has(O.kind))return null;let Q=a[O.kind];if(B?.currentSegmentIndex!==void 0)B.recordSegment({type:"error",message:Q.reason});if(B?.currentSegmentIndex===void 0)B?.recordGlobal({type:"error",message:Q.reason});return{decision:{kind:"deny",reason:Q.reason,intent:"stop_and_explain",evidence:{command:D,segment:D}},errorCode:Q.errorCode}}var k_=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),fc=new Set(["cc-safety-net","ccsn"]),O_=new Set(["bunx","npx","pnpx"]),M_=new Set(["pnpm","yarn"]),D_=new Set(["npm","pnpm","yarn"]),N_=new Set(["bun","node"]);function Ws(O,D,B={}){if(fc.has(O))return 0;if(O_.has(O)){if(B.broad)return dc(D);let ee=D[0]==="-y"||D[0]==="--yes"?1:0;return Ls(D[ee])?ee+1:null}let Q=B.broad?D.findIndex((ee)=>!ee.startsWith("-")):0;if(Q!==-1&&D_.has(O)&&B.broad&&D[Q]==="exec"){let ee=dc(D.slice(Q+1));return ee===null?null:Q+1+ee}if(M_.has(O)){if(O==="yarn"&&!B.broad)return null;if(!B.broad)return D[0]==="dlx"&&Ls(D[1])?2:null;if(Q===-1||D[Q]!=="dlx")return null;let ee=dc(D.slice(Q+1));return ee===null?null:Q+1+ee}if(N_.has(O)){let ee=B.broad&&Q!==-1?Q:0;if(Tp(D[ee]))return ee+1;if(O==="bun"&&D[ee]==="run"&&Tp(D[ee+1]))return ee+2}return null}function dc(O){let D=O.findIndex((Q)=>Ls(Q));if(D===-1)return null;let B=D;while(B<O.length){let Q=O[B]??"";if(!Q.startsWith("-")&&!Ls(Q))break;B++}return B}function Ls(O){if(!O)return!1;let D=O.indexOf("@");if(D===-1)return fc.has(O);if(D===0)return!1;let B=O.slice(D+1);if(B===""||B.includes("/")||B.includes(":"))return!1;return fc.has(O.slice(0,D))}function Tp(O){let D=O?.replaceAll("\\","/");return[...k_].some((B)=>D===B||D?.endsWith(`/${B}`))}var Me="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 Ip(O,D,B){let Q=un(O,"input-candidate");if(!Q)return null;let ee=Yr(Q.shell,O.invocation.context.executionCwd,D,B,{findSegmentTarget:(he)=>L_(he,D),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return ee?{target:ee}:null}function L_(O,D){let B=rr([...O],D),Q=B.slice(1),ee=Ws(Tt(B[0]??"").toLowerCase(),Q,{broad:!0});if(ee===null)return null;let he=Q.slice(ee).filter((je)=>je!=="-g"&&je!=="--global");return he[0]==="policy"&&he[1]==="apply"?B.join(" "):null}import{dirname as Gs}from"node:path";var $e="This path contains the protected policy config and you must not modify or delete it.",W_=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Dp(O,D,B){let Q=U_(O.invocation.context,D,B);if(O.invocation.route.kind==="patch")return kp(O.paths,!1,O.invocation.context.executionCwd,Q,D,B);let ee=un(O,"input-candidate");if(O.invocation.route.kind==="command")return ee?Op(ee.shell,O.invocation.context.executionCwd,Q,D,B):null;if(O.invocation.route.kind==="unknown"&&ee){let he=Op(ee.shell,O.invocation.context.executionCwd,Q,D,B);if(he)return he}return kp(O.paths,O.invocation.route.kind==="grep"||O.invocation.route.kind==="glob"||ui(O.invocation.toolName),O.invocation.context.executionCwd,Q,D,B)}function kp(O,D,B,Q,ee,he){if(D)return null;let je=O.find((at)=>ei(at,B,Q,ee,he));return je?{target:je}:null}function Op(O,D,B,Q,ee){let he=Yr(O,D,Q,ee,{findSegmentTarget:(je,at)=>G_(je,at,B,Q,ee)?.target??null,isRedirectionTarget:(je,at)=>ei(je,at.cwd,B,Q,ee),findMalformedTarget:(je)=>$_(je,D,B,Q,ee)?.target??null});return he?{target:he}:null}function G_(O,D,B,Q,ee){if(Wo(O))return null;let he=Cr([...O],Q),je=Tt(he[0]??"").toLowerCase(),at=he.slice(1);if(je==="rm"&&F_(at)){let lt=z_(at).find((ct)=>Mp(cn(ct,D.variables),D.cwd,B,Q,ee));if(lt)return{target:lt}}if(je==="find"){if(gs(he,1)||Ol(he,Q)){let ct=(ps($t(he))??$t(["."])).find((ut)=>{let ft=cn(ut.text,D.variables);return ei(ft,D.cwd,B,Q,ee)||Mp(ft,D.cwd,B,Q,ee)})?.text;if(ct)return{target:ct}}}if(je==="mv"){let lt=ts(at).sources.find((ct)=>H_(cn(ct,D.variables),D.cwd,B,Q,ee));if(lt)return{target:lt}}if(B_(he,je))return null;for(let lt of[...O,...he])for(let ct of Np(lt))if(ei(cn(ct,D.variables),D.cwd,B,Q,ee))return{target:ct};return null}function F_(O){return O.some((D)=>D==="--recursive"||D.startsWith("-")&&!D.startsWith("--")&&/[rR]/.test(D.slice(1)))}function z_(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 B_(O,D){if(!W_.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 $_(O,D,B,Q,ee){for(let he of O.split(/\s+/))for(let je of Np(he))if(ei(je,D,B,Q,ee))return{target:je};return null}function Np(O){let D=O.trim().replace(/^['"]|['"]$/g,""),B=D.indexOf("=");return B===-1||B===D.length-1?[D]:[D,D.slice(B+1)]}function U_(O,D,B){let Q=(at)=>ti(tn(at,O.executionCwd,D,B)),ee=Q(u(D)),he=[Q(b(O.executionCwd)),Q(b(O.configCwd))],je=new Set(he.map((at)=>Gs(at)));for(let at=Gs(ee);;at=Gs(at))if(je.add(at),Gs(at)===at)break;return{files:new Set([ee,...he]),directoriesAndAncestors:je}}function ei(O,D,B,Q,ee){let he=Mc(O,D,Q,ee,(je)=>ti(je)===hi);return he!==null&&B.files.has(ti(he))}function Mp(O,D,B,Q,ee){return B.directoriesAndAncestors.has(ti(tn(O,D,Q,ee)))}function H_(O,D,B,Q,ee){let he=ti(tn(O,D,Q,ee));return B.files.has(he)||B.directoriesAndAncestors.has(he)}function ti(O){return process.platform==="win32"?O.toLowerCase():O}import{isAbsolute as Fs,posix as Kp,resolve as Bs,win32 as j_}from"node:path";import{fileURLToPath as V_}from"node:url";var qp="Access to a sensitive path is not allowed.",Yp=new Set(["echo","printf"]),K_=new Set(["find"]),q_=new Set(["!","do","elif","else","if","then","until","while"]),Y_=new Set(["-exec","-execdir"]),Z_=new Set([";","+"]),X_=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),J_=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Zp=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),Q_=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),ew=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"]),Xp=new Set(["-c","-e","-r","-E","--eval","--exec"]),tw=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"])]]),nw=new Set(["grep","rg"]),rw=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),ow=new Set(["commit","merge","notes","stash","tag"]),iw=new Set(["-m","--message"]),sw=new Set(["--grep"]),Lp=new Set(["jq","gojq","jaq"]),Wp="f",Gp="file",aw="files",lw=new Set(["e","f"]),cw=new Set(["regexp","file"]),uw=new Set(["e","f","A","B","C","m"]),dw=new Set(["regexp","file","after-context","before-context","context","max-count"]),mc="__CC_SAFETY_NET_PIPE_INPUT__",gc=/[\w./~@+-]*[./~][\w./~@+-]*/g,fw=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,mw=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,pw=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,Fp=/\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,zp=/\b(?:system|exec|spawn|popen)\s*$/,gw=/\b(?:eval|exec)\s*\(/g,hw=/\b(?:eval|exec)\s*$/,yw=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 Bp(O,D,B,Q,ee,he){for(let je of O){let at=je.target;if(pP(at,je.cwd,D?.denyPaths??[],B,Q,ee))return{target:at,ruleId:"secret.deny-path"};if(he&&!he.has(at))continue;let lt=fP(at,je.cwd,D,Q,ee);if(lt){let ct=!lt.startsWith("secret.home.")&&!lt.startsWith("secret.cli.");if(he&&(ct&&Q.paths.isDirectory(og(at,je.cwd,Q,ee))||ct&&je.written===!0&&!at.includes("$")&&!yc(at,je.cwd,Q,ee)||ct&&/\s/.test(at)&&!at.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(at)&&!yc(at,je.cwd,Q,ee)))continue;if(!lt.startsWith("secret.cli.")&&gP(at,je.cwd,D?.allowPaths??[],B,Q,ee))continue;return{target:at,ruleId:lt}}}return null}function Jp(O,D,B,Q,ee={}){let he=$p(O,B,Q),je=Bp(he,D,O.invocation.context.configCwd,B,Q);if(je===null||je.ruleId==="secret.deny-path"||ee.strict!==!1)return je;let at=Bp(he,D,O.invocation.context.configCwd,B,Q,new Set($p(O,B,Q,{standard:!0}).map((lt)=>lt.target)));return at?.ruleId!=="secret.deny-path"&&bw(O,B)?null:at}function bw(O,D){let B=un(O,"input-candidate")??un(O,"declared-command");if(!B)return!1;if(B.program.nodes.some((je)=>je.kind==="command"&&je.nested.length>0))return!1;let Q=[];for(let je of es(B.shell)){if(je.kind==="operator"&&je.boundary)return!1;if(je.kind==="redirection")return!1;if(je.kind==="operator")continue;Q.push(Vn(je.text,D))}let ee=Jn(Q);if(ee.length===0)return!1;let he=Ln(ee[0]??"").toLowerCase();if(O.invocation.route.kind==="unknown")return B.program.dialect==="powershell"&&(he==="ls"||he==="stat");return bc(he,ee.slice(1))}function bc(O,D){if(O==="ls"||O==="stat")return!0;if(O==="test")return D.length===2&&(D[0]==="-e"||D[0]==="-f");if(O==="[")return D.length===3&&(D[0]==="-e"||D[0]==="-f")&&D[2]==="]";if(O==="git")return D[0]==="check-ignore";if(O!=="find")return!1;return!D.some((B)=>X_.has(B))}function $p(O,D,B,Q={}){let ee=O.invocation.context.executionCwd,he=O.invocation.route.kind;if(he!=="command"&&he!=="unknown")return O.paths.map((at)=>({target:at,cwd:ee}));let je=un(O,"input-candidate");return[...je?ao(je.shell,O.store,Q,D,ee,B,Sw(je)):[],...he==="unknown"?O.paths.map((at)=>({target:at,cwd:ee})):[]]}function Sw(O){return O.program.dialect==="powershell"}function ao(O,D,B,Q,ee,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:ee})),...Yw(Vn(O.source,Q),D,B,Q,ee,he)],lt=(ct)=>Vn(Iw(ct,je),Q);return Qi(O,ee,Q,he,{word:lt,segment:(ct,ut,ft,dt,mt)=>{if(ct.length===0)return null;if(at.push(...$s(ct,D,B,Q,ut.cwd,he,mt)),ft!==null)at.push(...vw(ft,ct,D,B,Q,ut.cwd,he));return null},redirection:(ct,ut)=>{if(ct.body!==void 0&&ct.consumer!==void 0)at.push(...Qp(ct.consumer,[ct.body],D,B,Q,ut.cwd,he,(ft)=>Ew(ct.consumer??[],ft,D,B,Q,ut.cwd,he)));if(ct.targetOrder==="legacy-segment")return gl;return at.push({target:lt(ct.target),cwd:ut.cwd,...ct.role==="file-write"?{written:!0}:{}}),null}}),at}function Sc(O,D,B,Q,ee,he){let je=D.getShellSyntax(O);if(je.status==="structural-limit")throw new y;return je.status==="complete"?ao(je,D,B,Q,ee,he):null}function $s(O,D,B,Q,ee,he,je){let at=(gt)=>({target:gt,cwd:ee});if(je?.size){let gt=O.filter((ht,yt)=>!je.has(yt));if(Lp.has(Ln(Jn(gt)[0]??"").toLowerCase()))return[...O.filter((ht,yt)=>je.has(yt)).map(at),...$s(gt,D,B,Q,ee,he)]}let lt=Tw(O).map(at),ct=Jn(O);if(ct.length===0)return lt;let ut=ct[0]??"",ft=Ln(ut).toLowerCase(),dt=ct.slice(1),mt=ct.findIndex((gt)=>!q_.has(gt));if(B.standard===!0&&mt!==-1&&bc(Ln(ct[mt]??"").toLowerCase(),ct.slice(mt+1)))return lt;let pt=Cw(ut,ft,dt);if(pt)return[...lt,...pt.map(at)];if(Yp.has(ft))return B.capturedOutput===!0?[...lt,...eg(O).map(at)]:lt;if(ft==="eval")return[...lt,...Sc(dt.join(" "),D,B,Q,ee,he)??dt.map(at)];if(ft==="export")return[...lt,...dt.flatMap((gt)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(gt)?[gt.slice(gt.indexOf("=")+1)]:zn(ft,gt)).map(at)];if(ft==="git")return[...lt,...Ow(dt).map(at)];if(ft==="gh")return[...lt,...hc(ft,dt,rw).map(at)];if(Lp.has(ft))return[...lt,...kw(dt).map(at)];if(nw.has(ft))return[...lt,...rP(dt).map(at)];if(K_.has(ft))return[...lt,...Lw(dt,D,B,Q,ee,he).map(at)];if(En.has(ft))return[...lt,...dt.flatMap((gt)=>zn("awk",gt)).map(at),...dt.flatMap((gt)=>Gw(gt,D,B,Q,ee,he)),...dt.flatMap(Fw).map(at)];if(ft==="curl")return[...lt,...dt.flatMap((gt)=>zn(ft,gt)).map(at),...Mw(dt).map(at)];if(Go(ft)){let gt=Lo.has(ft)?hn([ft,...dt]):null;if(gt!==null&>.command!==null&>.commandIndex!==null){let ht=D.getShellSyntax(gt.command);if(ht.status==="structural-limit")throw new y;if(ht.status==="complete")return[...lt,...ao(ht,D,B,Q,ee,he),...dt.slice(gt.commandIndex).filter((yt)=>!yt.startsWith("-")).map(at)]}return[...lt,...Ww(ft,dt,D,B,Q,ee,he)]}return[...lt,...dt.flatMap((gt)=>zn(ft,gt)).map(at)]}function Cw(O,D,B){let Q=Ws(D,B);if(Q===null||B[Q]!=="explain")return null;let ee=[O,...B.slice(0,Q)],he=B.slice(Q+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("--"))ee.push(lt);je++;continue}return ee}return ee}function vw(O,D,B,Q,ee,he,je){if(ww(D,B,Q,ee,he,je)){let at=Jn(O),lt=bc(Ln(at[0]??"").toLowerCase(),at.slice(1))?at.slice(1).filter((ct)=>!ct.startsWith("-")):[];return[...eg(O),...lt].map((ct)=>({target:ct,cwd:he}))}return Qp(D,xw(O),B,Q,ee,he,je,()=>[])}function Ew(O,D,B,Q,ee,he,je){let at=Jn(O);if(!Go(Ln(at[0]??"").toLowerCase()))return[];return Sc(D,B,Q,ee,he,je)??[{target:D,cwd:he}]}function Qp(O,D,B,Q,ee,he,je,at){let lt=Pw(O);if(lt===null)return D.flatMap(at);return D.flatMap((ct)=>Lo.has(lt)?ao(B.getShellSyntax(ct),B,Q,ee,he,je):zs(lt,ct,B,Q,ee,he,je))}function eg(O){let D=Jn(O);if(D.length===0)return[];let B=Ln(D[0]??"").toLowerCase();if(!Yp.has(B))return[];let Q=D[D[1]==="--"?2:1];if(B==="printf"&&Q!==void 0&&!Q.startsWith("-")&&!Q.replaceAll("%%","").includes("%"))return[Cc(Q.replaceAll("%%","%"))];return D.slice(1)}function xw(O){let D=Jn(O);if(D.length===0)return[];let B=Ln(D[0]??"").toLowerCase(),Q=D.slice(1);if(B==="echo"){let ee=Q.findIndex((he)=>!/^-[neE]+$/.test(he));return[(ee===-1?[]:Q.slice(ee)).join(" ")]}if(B==="printf")return Rw(Q);return[]}function Rw(O){let D=O[0];if(D===void 0)return[];let B=(D.match(/%%|%[bqs]/g)??[]).filter((ee)=>ee!=="%%").length;if(B===0||O.length===1)return[Cc(D)];let Q=O.slice(1);return Array.from({length:Math.ceil(Q.length/B)},(ee,he)=>_w(D,Q.slice(he*B,(he+1)*B)))}function _w(O,D){let B=0;return Cc(O.replace(/%%|%[bqs]/g,(Q)=>{if(Q==="%%")return"%";let ee=D[B]??"";return B++,ee}))}function Cc(O){return O.replace(/\\n/g,`
|
|
42
|
+
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function ww(O,D,B,Q,ee,he){let je=Jn(O);if(je.length===0||Ln(je[0]??"").toLowerCase()!=="xargs")return!1;let at=Ir(je),lt=je.slice(at.childStart);if(lt.length===0)return!1;if(at.replacementToken==="")return!1;let ct=at.replacementToken,ut=ct===null?[...lt,mc]:lt.map((ft)=>ft.split(ct).join(mc));return $s(ut,D,B,Q,ee,he).some((ft)=>ft.target.includes(mc))}function Pw(O){let D=Jn(O);if(D.length===0)return null;let B=Ln(D[0]??"").toLowerCase();if(!Go(B))return null;return Aw(B,D.slice(1))?B:null}function Aw(O,D){let B=vc(O);for(let Q=0;Q<D.length;Q++){let ee=D[Q];if(ee===void 0)break;if(Xp.has(ee)||tg(O,ee)||/^--(?:eval|exec)=/.test(ee))return!1;if(ee==="-")return!0;if(ee.startsWith("-")){if(B==="python"&&ee==="-m")return!1;if(yw.get(B)?.has(ee))Q++;continue}return!1}return!0}function vc(O){return/^python\d/.test(O)?"python":O}function Tw(O){let D=[];for(let B of O){if(rg(B))continue;let Q=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(B);if(Q===null)break;if(Q[1]!==void 0&&Q[1]!=="")D.push(Q[1])}return D}var Up=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function Iw(O,D){if(!D||!Up.test(O))return O;return`~${O.replace(Up,"").replace(/\\/g,"/")}`}function zn(O,D){if(D==="--")return[];let B=[],Q=D.indexOf("=");if(Q>0&&Q<D.length-1)B.push(D.slice(Q+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 kw(O){let D=-1,B=!1;for(let Q=0;Q<O.length;Q++){let ee=O[Q]??"";if(!B&&ee==="--"){B=!0;continue}if(B||!/^-(?:[A-Za-z]|-)/.test(ee)){if(D===-1)D=Q;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(ee)){Q+=2;continue}if(ee==="--indent"||ee==="-L"){Q++;continue}if(ee.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(ee)||/^--(?: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(ee))continue;return O.flatMap((he)=>zn("jq",he))}return O.flatMap((Q,ee)=>ee===D?[]:zn("jq",Q))}function Ow(O){let D=[];for(let B=0;B<O.length;B++){let Q=O[B]??"";if(Q==="--"||!Q.startsWith("-"))return[...D,...ow.has(Q)?hc("git",O.slice(B).map((he)=>/^-[aeinopqsv]+m$/.test(he)?"-m":he),iw):hc("git",O.slice(B),sw)];if(D.push(...zn("git",Q)),!gn.has(Q))continue;let ee=O[B+1];if(ee===void 0)break;D.push(...Q==="-c"&&ee.includes("=")?[ee.slice(ee.indexOf("=")+1)]:zn("git",ee)),B++}return D}function hc(O,D,B){let Q=[];for(let ee=0;ee<D.length;ee++){let he=D[ee]??"";if(he==="--")return[...Q,...D.slice(ee).flatMap((je)=>zn(O,je))];if(B.has(he)){ee++;continue}if(he.includes("=")&&B.has(he.slice(0,he.indexOf("="))))continue;Q.push(...zn(O,he))}return Q}function Mw(O){return O.flatMap((D,B)=>{let Q=Nw(D);if(Q!==null)return Hp(Q.flag,Q.value);let ee=Dw(O[B-1]);return ee===null?[]:Hp(ee,D)})}function Hp(O,D){if(O==="-F"||O==="--form"){let B=D.indexOf("="),Q=B===-1?D:D.slice(B+1);if(!Q.startsWith("@")&&!Q.startsWith("<"))return[];return pc(Q.slice(1).split(";")[0]??"")}if(O==="--data-urlencode"){let B=D.indexOf("@"),Q=D.indexOf("=");if(B===-1||Q!==-1&&Q<B)return[];return pc(D.slice(B+1))}return D.startsWith("@")?pc(D.slice(1)):[]}function Dw(O){if(O===void 0)return null;if(Zp.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 Q=O.slice(0,B);return Zp.has(Q)?{flag:Q,value:O.slice(B+1)}:null}function pc(O){return O===""||O==="-"?[]:[O]}function Lw(O,D,B,Q,ee,he){let je=O.findIndex((lt)=>lt.startsWith("-")||lt==="("||lt==="!"||lt===";"),at=[...O.slice(0,je===-1?O.length:je),...O.flatMap((lt,ct)=>lt==="-files0-from"&&O[ct+1]!==void 0?[O[ct+1]??""]:[])];for(let lt=0;lt<O.length;lt++){if(!Y_.has(O[lt]??""))continue;let ct=O.slice(lt+1),ut=ct.findIndex((mt)=>Z_.has(mt)),ft=ut===-1?ct:ct.slice(0,ut),dt=$s(ft,D,B,Q,ee,he).map((mt)=>mt.target);if(at.push(...dt.filter((mt)=>mt!=="{}")),!dt.includes("{}"))continue;at.push(...O.slice(0,lt).flatMap((mt,pt,gt)=>{if(!J_.has(mt))return[];let ht=gt[pt+1];return ht===void 0?[]:[ht,ht.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return at}function Ww(O,D,B,Q,ee,he,je){let at=[];for(let lt=0;lt<D.length;lt++){let ct=D[lt];if(ct===void 0)break;if(Xp.has(ct)||tg(O,ct)){let ft=D[lt+1];if(ft!==void 0)at.push(...zs(O,ft,B,Q,ee,he,je)),lt++;continue}let ut=/^--(?:eval|exec)=(.*)$/.exec(ct);if(ut!==null&&ut[1]!==void 0){at.push(...zs(O,ut[1],B,Q,ee,he,je));continue}if(!ct.startsWith("-"))at.push({target:ct,cwd:he})}return at}function tg(O,D){if(!D.startsWith("-")||D.startsWith("--")||D.length<=2)return!1;return tw.get(D[D.length-1]??"")?.has(vc(O))??!1}function Gw(O,D,B,Q,ee,he){if(!O.includes("system"))return[];return Al(O)?.commands.flatMap((je)=>ao(D.getShellSyntax(je),D,B,Q,ee,he))??[]}function Fw(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 zw(O){let D=Array.from(O.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((B)=>B[2]).filter((B)=>B!==void 0&&B!=="");return[...D,...D.flatMap(Ec),...O.match(gc)??[]]}function zs(O,D,B,Q,ee,he,je){let at=(gt)=>({target:gt,cwd:he}),lt=$w(D,Bw(O));if(lt===null)return zw(D).map(at);let ct=lt.masked.match(Fp)!==null||lt.literals.some((gt)=>zp.test(lt.masked.slice(0,gt.start))),ut=lt.masked.match(gw)!==null||lt.literals.some((gt)=>hw.test(lt.masked.slice(0,gt.start))),ft=Q.standard===!0&&!Lo.has(O),dt=ft&&!(Vw(lt.masked)||ct||ut)?[]:lt.literals,mt=ft?Array.from(lt.masked.matchAll(Fp),(gt)=>{let ht=gt.index+gt[0].length;return{start:ht,end:ll(lt.masked,ht)}}):[],pt=!ft||mt.some((gt)=>cl(lt.masked,gt.start))?lt.literals:lt.literals.filter((gt)=>zp.test(lt.masked.slice(0,gt.start))||mt.some((ht)=>gt.start>=ht.start&>.start<ht.end));return[...dt.map((gt)=>gt.text).filter((gt)=>gt!=="").map(at),...dt.flatMap((gt)=>Ec(gt.text)).map(at),...ft?[]:lt.literals.flatMap((gt)=>gt.text.match(gc)??[]).map(at),...ct?pt.flatMap((gt)=>Sc(gt.text,B,Q,ee,he,je)??[at(gt.text)]):[],...ut?lt.literals.flatMap((gt)=>zs(O,gt.text.replace(/\\(.)/g,(ht,yt)=>yt==="n"?`
|
|
43
|
+
`:yt),B,Q,ee,he,je)):[],...(lt.masked.match(gc)??[]).map(at)]}function Bw(O){let D=vc(O);if(D==="python")return"python";if(D==="osascript")return"opaque";return D==="node"||D==="bun"||D==="deno"?"javascript":"simple"}function $w(O,D){if(D==="opaque")return null;let B=O.split(""),Q=[];for(let ee=0;ee<O.length;ee++){let he=O[ee]??"";if(D==="simple"&&(he==="`"||he==="%"||he==="<")){if(mw.test(O.slice(ee)))return null}let je=he==="'"||he==='"'||D==="javascript"&&he==="`"?he:null;if(je===null)continue;if(je==="`"&&jw(O,ee))return null;let at=D==="python"?Uw(O,ee):"",lt=D==="python"&&O.startsWith(je.repeat(3),ee)?je.repeat(3):je,ct=ee+lt.length,ut=Hw(O,ct,lt);if(ut===null)return null;let ft=O.slice(ct,ut);if(/[fF]/.test(at)&&ft.includes("{"))return null;if(D==="simple"&&je==='"'&&pw.test(ft))return null;Q.push({start:ct,text:ft});for(let dt=ee;dt<ut+lt.length;dt++)B[dt]=" ";ee=ut+lt.length-1}return{masked:B.join(""),literals:Q}}function Uw(O,D){return fw.exec(O.slice(Math.max(0,D-3),D))?.[1]??""}function Hw(O,D,B){let Q=B==="`",ee=Q||B.length===3;for(let he=D;he<O.length;he++){let je=O[he];if(je==="\\"){he++;continue}if(Q&&je==="$"&&O[he+1]==="{")return null;if(!ee&&(je===`
|
|
44
|
+
`||je==="\r"))return null;if(O.startsWith(B,he))return he}return null}function jw(O,D){for(let B=D-1;B>=0;B--){let Q=O[B];if(!Q||/\s/.test(Q))continue;return/[\w$\])]/.test(Q)}return!1}function Vw(O){for(let D of O.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let B=D[0],Q=D.index;if(Q_.has(B.toLowerCase()))return!0;let ee=B.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((he)=>he.toLowerCase());if(!ee.some((he)=>ew.has(he)))continue;if(ee.length>1)return!0;if(Kw(O,Q)===".")return!0;if(qw(O,Q+B.length)==="(")return!0}return!1}function Kw(O,D){for(let B=D-1;B>=0;B--)if(!/\s/.test(O[B]??""))return O[B];return}function qw(O,D){for(let B=D;B<O.length;B++)if(!/\s/.test(O[B]??""))return O[B];return}function Yw(O,D,B,Q,ee,he){return eP(O).flatMap((je)=>{let at=D.getShellSyntax(je);if(at.status==="invalid")return[];return[...ao(at,D,{...B,capturedOutput:!0},Q,ee,he),...Zw(at,Q)?Xw(at,Q).map((lt)=>({target:lt,cwd:ee})):[]]})}function Zw(O,D){let B=es(O);for(let Q=0;Q<B.length;Q++){let ee=B[Q];if(ee?.kind!=="word"||Ln(Vn(ee.text,D)).toLowerCase()!=="base64")continue;for(let he=Q+1;he<B.length;he++){let je=B[he];if(je?.kind==="operator")break;if(je?.kind!=="word")continue;let at=Vn(je.text,D);if(at==="--decode"||!at.startsWith("--")&&at.startsWith("-")&&/[dD]/.test(at))return!0}}return!1}function Xw(O,D){return es(O).flatMap((B)=>B.kind==="word"?[Vn(B.text,D)]:B.kind==="redirection"&&B.target?[Vn(B.target,D)]:[]).flatMap(Ec)}function Ec(O){let D=Qw(O);if(D===null)return[];let B=Buffer.from(D,"base64").toString("utf8");if(B===""||Jw(B))return[];return Buffer.from(B,"utf8").toString("base64").replace(/=+$/g,"")===D.replace(/=+$/g,"")?[B]:[]}function Jw(O){return Array.from(O).some((D)=>{let B=D.charCodeAt(0);return B<32||B===127})}function Qw(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 eP(O){let D=[],B={inSingle:!1,inDouble:!1,escaped:!1};for(let Q=0;Q<O.length;Q++){let ee=O[Q];if(!ee)break;if(So(ee,B))continue;if(ng(O,Q,B)){let he=tP(O,Q+1);if(he!==null)D.push(he.body),Q=he.endIndex;continue}if(!B.inSingle&&ee==="`"){let he=nP(O,Q);if(he!==null)D.push(he.body),Q=he.endIndex}}return D}function tP(O,D){let B={inSingle:!1,inDouble:!1,escaped:!1},Q=1;for(let ee=D+1;ee<O.length;ee++){let he=O[ee];if(!he)break;if(So(he,B))continue;if(ng(O,ee,B)){Q++,ee++;continue}if(!B.inSingle&&!B.inDouble&&he===")"){if(Q--,Q===0)return{body:O.slice(D+1,ee),endIndex:ee}}}return null}function nP(O,D){let B=!1;for(let Q=D+1;Q<O.length;Q++){let ee=O[Q];if(!ee)break;if(B){B=!1;continue}if(ee==="\\"){B=!0;continue}if(ee==="`")return{body:O.slice(D+1,Q),endIndex:Q}}return null}function ng(O,D,B){return!B.inSingle&&O[D]==="$"&&O[D+1]==="("&&O[D+2]!=="("}function rP(O){let D=[],B=[],Q=!1,ee=!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 ut=/^--([^=]+)(?:=(.*))?$/.exec(ct);if(ut!==null){let ft=ut[1]??"",dt=ut[2];if(ft===aw)ee=!0;if(cw.has(ft))Q=!0;if(dt!==void 0){if(ft===Gp)D.push(dt);continue}if(dw.has(ft)){let mt=O[lt+1];if(ft===Gp&&mt!==void 0)D.push(mt);lt++}continue}if(ct.startsWith("-")&&ct.length>1){let ft=ct.slice(1),dt="",mt="";for(let gt=0;gt<ft.length;gt++){let ht=ft[gt]??"";if(lw.has(ht))Q=!0;if(uw.has(ht)){dt=ht,mt=ft.slice(gt+1);break}}if(dt==="")continue;if(mt.length>0){if(dt===Wp)D.push(mt);continue}let pt=O[lt+1];if(dt===Wp&&pt!==void 0)D.push(pt);lt++;continue}B.push(ct)}let at=!Q&&!ee?B.slice(1):B;return[...D,...at]}function Jn(O){let D=O.findIndex((B)=>!rg(B)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(B));return D===-1?[]:O.slice(D)}function rg(O){return O==="env"||O==="command"||O==="builtin"||O==="sudo"}var oP=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),iP=".env.",sP=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),aP=[".env.example.",".env.sample."];function lP(O){let D;try{D=new URL(O.trim())}catch{return!1}return D.protocol!=="file:"&&D.host!==""}function cP(O){return O.length>0&&!/\s/.test(O)}function yc(O,D,B,Q){let ee=og(O,D,B,Q);return ee!==""&&B.paths.entryKind(ee)!=="missing"}function og(O,D,B,Q){try{return oi(O,D,B,Q)}catch(ee){if(ee instanceof s)throw ee;return""}}var uP=new Set(["node_modules","__pycache__"]),dP=[["vendor","bundle"],["vendor","cache"]];function fP(O,D,B,Q,ee){if(lP(O))return null;let he=Fn(O,D,Q,ee);if(!he)return null;let je=Lt(he.split("/").pop()??""),at=Lt(he),lt=()=>cP(je)||yc(O,D,Q,ee);if(sP.has(je)||aP.some((dt)=>je.startsWith(dt)))return null;let ct=Lt(bP(O,D,Q,ee));for(let dt of xa){let mt=`~/${dt.suffixParts.join("/")}`;if((Vp(at,mt)||Vp(ct,mt))&&Xn(dt.id,B))return dt.id}let ut=mP(he,D,B,Q,ee);if(ut)return ut;if(oP.has(je))return null;for(let dt of Ea)if(je===dt.basename&&Xn(dt.id,B))return dt.id;if(je.startsWith(iP)&&Xn(vi.id,B)&<())return vi.id;for(let dt of Ra)if(je.length>dt.prefix.length&&je.startsWith(dt.prefix)){let mt=je.slice(dt.prefix.length)[0];if((mt==="-"||mt==="_")&&Xn(dt.id,B)&<())return dt.id}for(let dt of _a)if(je.length>dt.prefix.length&&je.startsWith(dt.prefix)){if(je.slice(dt.prefix.length)===dt.suffix&&Xn(dt.id,B))return dt.id}if(hP(at))return null;if(!je.includes(".")&&Co.pattern.test(je)&&Xn(Co.id,B))return Co.id;let ft=yP(je,B);if(ft)return ft;return null}function mP(O,D,B,Q,ee){return Ei.find((he)=>{if(!Xn(he.id,B))return!1;switch(he.id){case"secret.cli.claude-code":return Dt(O,Gt(Q.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",D,Q,ee),[".credentials.json"]);case"secret.cli.claude-code.config":{let je=Lt(O).split("/");return Dt(O,Gt(Q.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",D,Q,ee),["settings.json","settings.local.json"])||ri(O,"~/.claude.json",D,Q,ee)||je.at(-1)==="settings.local.json"&&je.at(-2)===".claude"||je.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Dt(O,Fn("~/.gemini/config",D,Q,ee),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let je=Gt(Q.env.get("CODEX_HOME"),"~/.codex",D,Q,ee);return Dt(O,je,["auth.json",".credentials.json"])||ni(O,je,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let je=Gt(Q.env.get("CODEX_HOME"),"~/.codex",D,Q,ee),at=Lt(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,rn(Gt(Q.env.get("GEMINI_CLI_HOME"),"~",D,Q,ee),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let je=Lt(O).split("/"),at=Q.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),lt=Q.env.get("ProgramData")?[rn(Gt(Q.env.get("ProgramData"),"",D,Q,ee),"gemini-cli")]:[];return Dt(O,rn(Gt(Q.env.get("GEMINI_CLI_HOME"),"~",D,Q,ee),".gemini"),["settings.json","google_accounts.json"])||je.at(-1)==="settings.json"&&je.at(-2)===".gemini"||(at?.trim()?ri(O,at,D,Q,ee):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...lt].some((ct)=>Dt(O,Fn(ct,D,Q,ee),["settings.json"]))}case"secret.cli.copilot-cli":{let je=Gt(Q.env.get("COPILOT_HOME"),"~/.copilot",D,Q,ee);return Dt(O,je,["config.json"])||ni(O,je,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Dt(O,Gt(Q.env.get("COPILOT_HOME"),"~/.copilot",D,Q,ee),["mcp-config.json"]);case"secret.cli.kimi-code":{let je=Gt(Q.env.get("KIMI_CODE_HOME"),"~/.kimi-code",D,Q,ee),at=Gt(Q.env.get("KIMI_SHARE_DIR"),"~/.kimi",D,Q,ee);return Dt(O,je,["server.token"])||ni(O,je,["credentials"])||ni(O,at,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let je=["config.toml","mcp.json"],at=Lt(O).split("/");return at.at(-1)==="mcp.json"&&at.at(-2)===".kimi-code"||Dt(O,Gt(Q.env.get("KIMI_CODE_HOME"),"~/.kimi-code",D,Q,ee),je)||Dt(O,Gt(Q.env.get("KIMI_SHARE_DIR"),"~/.kimi",D,Q,ee),[...je,"config.json","config.json.bak"])}case"secret.cli.opencode":{let je=rn(Gt(Q.env.get("XDG_DATA_HOME"),"~/.local/share",D,Q,ee),"opencode"),at=Lt(O).split("/").at(-1)??"",lt=Q.env.get("OPENCODE_DB")?.trim(),ct=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((ut)=>ri(O,ut,D,Q,ee))}case"secret.cli.opencode.config":{let je=Q.env.get("OPENCODE_CONFIG_DIR")?Gt(Q.env.get("OPENCODE_CONFIG_DIR"),"~/.config/opencode",D,Q,ee):rn(Gt(Q.env.get("XDG_CONFIG_HOME"),"~/.config",D,Q,ee),"opencode"),at=Q.env.get("ProgramData")?[rn(Gt(Q.env.get("ProgramData"),"",D,Q,ee),"opencode")]:[],lt=["opencode.json","opencode.jsonc"],ct=Q.env.get("OPENCODE_CONFIG");return lt.includes(Lt(O).split("/").at(-1)??"")||Dt(O,je,lt)||(ct?.trim()?ri(O,ct,D,Q,ee):!1)||["/Library/Application Support/opencode","/etc/opencode",...at].some((ut)=>Dt(O,Fn(ut,D,Q,ee),lt))}case"secret.cli.pi":return Dt(O,Gt(Q.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",D,Q,ee),["auth.json"]);case"secret.cli.pi.config":return Dt(O,Gt(Q.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",D,Q,ee),["models.json"]);case"secret.cli.amp":{let je=Fn("~",D,Q,ee);return[rn(Gt(Q.env.get("XDG_DATA_HOME"),"~/.local/share",D,Q,ee),"amp"),rn(je,".local","share","amp")].some((lt)=>Dt(O,lt,["secrets.json"]))||ni(O,rn(je,".amp"),["oauth"])}case"secret.cli.amp.config":{let je=["settings.json","settings.jsonc"],at=[rn(Gt(Q.env.get("XDG_CONFIG_HOME"),"~/.config",D,Q,ee),"amp"),rn(Fn("~",D,Q,ee),".config","amp")],lt=Lt(O).split("/"),ct=Q.env.get("AMP_SETTINGS_FILE");return at.some((ut)=>Dt(O,ut,je))||lt.at(-2)===".amp"&&je.includes(lt.at(-1)??"")||(ct?.trim()?ri(O,ct,D,Q,ee):!1)}case"secret.cli.cursor":{let je=rn(Gt(Q.env.get("XDG_CONFIG_HOME"),"~/.config",D,Q,ee),"cursor"),at=rn(Gt(Q.env.get("CURSOR_DATA_DIR"),"~/.cursor",D,Q,ee),"projects");return Dt(O,Fn("~/.cursor",D,Q,ee),["auth.json"])||Dt(O,je,["auth.json"])||Lt(O).split("/").at(-1)==="mcp-auth.json"&&Mr(Lt(O),Lt(at))}case"secret.cli.cursor.config":{let je=Lt(O).split("/");return je.at(-1)==="mcp.json"&&je.at(-2)===".cursor"}case"secret.cli.grok-build":return Dt(O,Gt(Q.env.get("GROK_HOME"),"~/.grok",D,Q,ee),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let je=Lt(O).split("/");return je.at(-1)==="config.toml"&&je.at(-2)===".grok"||Dt(O,Gt(Q.env.get("GROK_HOME"),"~/.grok",D,Q,ee),["config.toml","managed_config.toml","requirements.toml"])||Dt(O,Fn("/etc/grok",D,Q,ee),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var jp=new WeakMap;function Gt(O,D,B,Q,ee){let he=jp.get(ee)??new Map;jp.set(ee,he);let je=`${B}\x00${O??""}\x00${D}`,at=he.get(je);if(at!==void 0)return at;let lt=Fn(O?.trim()?O:D,B,Q,ee);return he.set(je,lt),lt}function Dt(O,D,B){return B.some((Q)=>ig(O,rn(D,Q)))}function ni(O,D,B){return B.some((Q)=>Mr(Lt(O),Lt(rn(D,Q))))}function ri(O,D,B,Q,ee){return ig(O,Fn(D,B,Q,ee))}function ig(O,D){return Lt(O)===Lt(D)}function rn(O,...D){return Nn([O,...D].filter(Boolean).join("/"))}function pP(O,D,B,Q,ee,he){if(B.length===0)return!1;let je=Lt(oi(O,D,ee,he));return B.some((at)=>Mr(je,Lt(oi(at,Q,ee,he))))}function gP(O,D,B,Q,ee,he){if(B.length===0)return!1;let je=Lt(oi(O,D,ee,he));if(!je)return!1;let at=ee.env.get("HOME")??ee.home,lt=at?Nn(Wt(pn(at),ee.paths,he)):"",ct=Lt(lt),ut=ee.env.get("CC_SAFETY_NET_HOME"),ft=Lt(ut?Nn(Wt(Bs(pn(ut)),ee.paths,he)):lt&&Nn(Wt(`${lt}/.cc-safety-net`,ee.paths,he)));if(ft&&Mr(je,ft))return!1;return B.some((dt)=>{let mt=Ia(dt);if(mt&&Kp.basename(je)!==Lt(mt.name))return!1;let pt=Lt(oi(mt?.root??dt,Q,ee,he));if(!pt)return!1;if(ct&&(ct===pt||ct.startsWith(pt.endsWith("/")?pt:`${pt}/`)))return!1;return Mr(je,pt)&&!(mt&&je===pt)})}function hP(O){let D=O.split("/");return D.some((B)=>uP.has(B))||dP.some(([B,Q])=>D.some((ee,he)=>ee===B&&D[he+1]===Q))}function yP(O,D){let B=O.lastIndexOf("."),Q=B>0&&B<O.length-1?O.slice(B+1):"";if(Q==="")return null;for(let ee of wa)if(Q===ee.extension&&Xn(ee.id,D))return ee.id;for(let ee of Pa)if(ee.pattern.test(Q)&&Xn(ee.id,D))return ee.id;return null}function Lt(O){return O.toLowerCase()}function Xn(O,D){return!D?.disabledRules?.includes(O)}function Fn(O,D,B,Q){let{home:ee,normalized:he}=xc(O,B,Q);if(!he)return"";if(!ee)return he;let je=Rc(he,ee),at=Fs(je)?je:Nn(Bs(D,je)),lt=Nn(Wt(at,B.paths,Q));if(!Mr(lt,ee)){if(Fs(je))return lt;return lt===at?he:lt}let ct=lt.slice(ee.length);return ct?`~${ct}`:"~"}function Vp(O,D){return O===D||O.startsWith(`${D}/`)}function bP(O,D,B,Q){let{home:ee,normalized:he}=xc(O,B,Q);if(!he||!ee)return"";let je=Rc(he,ee),at=Kp.normalize(Fs(je)?je:Nn(Bs(D,je))),lt=Nn(pn(B.env.get("HOME")??B.home)),ct=(dt)=>process.platform==="win32"?dt.toLowerCase():dt,ut=[ee,lt].find((dt)=>dt!==""&&Mr(ct(at),ct(dt)));if(ut===void 0)return"";let ft=at.slice(ut.length);return ft?`~${ft}`:"~"}function oi(O,D,B,Q){let{home:ee,normalized:he}=xc(O,B,Q);if(!he)return"";let je=ee?Rc(he,ee):he;return Nn(Wt(Fs(je)?je:Bs(D,je),B.paths,Q))}function xc(O,D,B){let Q=D.env.get("HOME")??D.home,ee=Q?Nn(Wt(pn(Q),D.paths,B)):"",he=Nn(pn(SP(Vn(O,D))));return{home:ee,normalized:he}}function SP(O){if(!O.trim().toLowerCase().startsWith("file:"))return O;try{return V_(O)}catch{return O}}function Rc(O,D){if(O==="~")return D;if(O.startsWith("~/"))return rn(D,O.slice(2));return O}function CP(O){if(process.platform==="win32")return!0;return j_.parse(O).root.length>1}function Nn(O){let D=O.trim(),B=(D.includes("\\")&&CP(D)?D.replace(/\\/g,"/"):D).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(B==="/")return B;return B.replace(/\/+$/g,"")}function Mr(O,D){return O===D||O.startsWith(D.endsWith("/")?D:`${D}/`)}function Ln(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 vP={findPolicyMutation:Dp,findGitMetadataMutation:gf,resolveGitMetadata:EP,loadPolicySnapshot:E,findSensitiveTarget:Jp,analyzeCommand:Pp,getModes:R};function W(O,D){let B={...vP,...D.dependencies},Q=_P(O),ee=ii(O)?O.command:Q,he=ur("policy-protection",ee,()=>Fo(O)),je=un(he,"input-candidate"),at=un(he,"declared-command");if(ii(O)&&O.command?.trim()&&at?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Wn,intent:"stop_and_explain",evidence:{command:O.command,segment:O.command}}};if(je?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:Df,intent:"stop_and_explain"}};let lt=mn(),ct=ur("policy-protection",ee,()=>B.resolveGitMetadata([O.context.executionCwd,O.context.configCwd],D.environment)),ut=ur("policy-protection",ee,()=>B.findPolicyMutation(he,D.environment,lt));if(ut){let Et=ee??ut.target;return{stage:"policy-protection",decision:{kind:"deny",reason:$e,intent:"hard_stop",evidence:{command:Et,segment:ut.target}}}}let ft=ur("policy-protection",ee,()=>Ip(he,D.environment,lt));if(ft){let Et=ee??ft.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Me,intent:"hard_stop",evidence:{command:Et,segment:ft.target}}}}let dt=ur("policy-protection",ee,()=>B.findGitMetadataMutation(he,ct,D.environment,lt));if(dt){let Et=ee??dt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:x,intent:"hard_stop",evidence:{command:Et,segment:dt.target}}}}let mt=ur("config-load",ee,()=>B.loadPolicySnapshot(D.environment,{...D.policyOptions,cwd:O.context.configCwd})),pt=mt.policy,gt=B.getModes(pt,D.environment.env),ht={level:gt.effectiveLevel,...xP(mt)},yt=pt.secretProtection.enabled===!1?null:ur("secret-protection",ee,()=>B.findSensitiveTarget(he,pt.secretProtection,D.environment,lt,{strict:ii(O)||je?.program.dialect==="powershell"?gt.strict:void 0}));if(yt){let Et=ee??yt.target;return{stage:"secret-protection",...ht,decision:{kind:"deny",reason:qp,intent:"hard_stop",ruleId:yt.ruleId,evidence:{command:Et,segment:yt.target}}}}if(!ii(O))return{stage:"non-command",...ht,decision:{kind:"allow"}};if(!O.command||O.command.trim()==="")return{..._c("command-validation",ee),...ht};let Ct=ur("command-analysis",ee,()=>Ap(()=>B.analyzeCommand(O.command,{cwd:O.context.executionCwd,shell:O.route.shell,policySnapshot:mt,environment:D.environment,protectedGitMetadata:ct,effectiveCapabilities:gt.capabilities,strict:gt.strict,paranoidRm:gt.paranoidRm,paranoidInterpreters:gt.paranoidInterpreters,worktreeMode:gt.worktreeMode,budget:lt,...D.trace?{trace:D.trace}:{}},RP(he),he.store),O.command,D.trace));if(Ct.decision){let Et=!gt.strict&&Ct.decision.kind==="deny"&&(Ct.decision.ruleId==="raw-text.dangerous-command"||Ct.decision.reason===Uo&&!/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/.test(Ct.decision.evidence?.segment??"")&&xn(O.command)===null);return{stage:"command-analysis",...ht,..."errorCode"in Ct?{errorCode:Ct.errorCode}:{},decision:Et?{...Ct.decision,ask:!0}:Ct.decision}}return{stage:"command-analysis",...ht,decision:{kind:"allow"}}}function EP(O,D){let B=[...new Set(O.filter((Q)=>typeof Q==="string"&&Q!==""))].flatMap((Q)=>D.gitMetadata(Q)??[]);if(B.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(B.flatMap((Q)=>Q.entries))]),markerFiles:Object.freeze([...new Set(B.flatMap((Q)=>Q.markerFiles))]),directories:Object.freeze([...new Set(B.flatMap((Q)=>Q.directories))]),hooksDirectories:Object.freeze([...new Set(B.flatMap((Q)=>Q.hooksDirectories))])})}function xP(O){if(O.state==="ready")return{};return{configFallback:{reason:O.reason}}}function RP(O){return un(O,"declared-command")?.program}function _P(O){try{return ne(O.input)}catch(D){let B=ii(O)?O.command:void 0;throw new p("policy-protection",_c("policy-protection",D instanceof f?void 0:B,D),D)}}function ur(O,D,B){try{return B()}catch(Q){throw new p(O,_c(O,Q instanceof f?void 0:D,Q),Q)}}function _c(O,D,B){let Q=B instanceof s||B instanceof y;return{stage:O,decision:{kind:"deny",reason:Q?Ks:te,intent:"stop_and_explain",...D?{evidence:{command:D,segment:D}}:{}}}}function ii(O){return O.route.kind==="command"}
|
|
45
|
+
export{te,a,s,z,ke,Ue,k,Ze,Ge,ye,P,be,Xe,c,o,He,xe,R,L,ve,Qe,f,V,ne,ce,et,We,d,Re,r,v,i,re,n,g,le,N,tt,nt,l,ue,de,rt,A,q,oe,S,ot,F,b,Se,M,u,K,Be,ze,I,w,T,pe,fe,Le,it,m,e,Te,we,Ve,qe,ie,Ce,se,_e,J,j,Pe,me,U,Ke,G,Y,Z,ae,Je,Ye,C,H,Ae,Ie,Oe,De,E,Ne,Ee,Fe,h,t,X,ge,y,x,_,st,Me,$e,p,W};
|