cc-safety-net 2.4.12 → 2.4.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/amp/cc-safety-net/index.ts +11 -11
- package/dist/api.js +1 -1
- package/dist/bin/hook.js +40 -40
- package/dist/chunks/{index-kwg376ge.js → index-av9c301x.js} +9 -9
- package/dist/chunks/{index-q47ejf84.js → index-fjkkpma1.js} +2 -2
- package/dist/cli.js +126 -117
- package/dist/index.js +7 -7
- package/dist/openclaw/cc-safety-net/index.js +36 -36
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +2 -2
- package/package.json +2 -2
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
var Xs="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Fn="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",bo="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var Zs={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."},yo={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,...Zs},processedCandidateBytes:{cap:4194304,...Zs},pathEnvironmentExpansion:{cap:64,...Zs},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,...yo},trackedHeredocFiles:{cap:64,...yo},controlFlowStates:{cap:64,...yo},wrapperPeelIterations:{cap:20,...yo},derivedCommandShape:yo});class s extends Error{kind;name="AnalysisLimit";constructor(D){super(a[D].reason);this.kind=D}}function pn(){let D=new Map;return{counters:D,resolvedPaths:new Map,charge(N,z=1){let ee=(D.get(N)??0)+z;if(D.set(N,ee),ee>a[N].cap)throw new s(N)}}}var hg=[/\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 V(D){return ke(D.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(D){return hg.reduce((N,z)=>N.replace(z,"<redacted>"),D.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(D){return Dc(D).reduceRight((N,z)=>`${N.slice(0,z.valueStart)}<redacted>${N.slice(z.valueEnd)}`,D)}function k(D){return ke(Ue(D))}function Ze(D){return Dc(D).map((N)=>D.slice(N.valueStart,N.valueEnd))}function Ge(D){return/[A-Za-z_][A-Za-z0-9_]*=/.test(D)}function Dc(D){return[...D.matchAll(/[A-Za-z_][A-Za-z0-9_]*=/g)].flatMap((N)=>{let z=D[N.index-1];if(N.index>0&&z&&!/[\s"'([{]/.test(z))return[];let ee=N.index+N[0].length;if(ee>=D.length)return[];return[{valueStart:ee,valueEnd:yg(D,ee)}]})}function yg(D,N){if(D.startsWith("$(",N))return bg(D,N);let z=D[N];if(z==='"'||z==="'"){for(let te=N+1;te<D.length;te++){if(z==='"'&&D[te]==="\\"){te++;continue}if(D[te]===z)return te+1}return D.length}let ee=N;while(ee<D.length&&!/\s/.test(D[ee]??""))ee++;return ee}function bg(D,N){let z=0,ee;for(let te=N;te<D.length;te++){let he=D[te];if(ee){if(ee==='"'&&he==="\\"){te++;continue}if(he===ee)ee=void 0;continue}if(he==='"'||he==="'"){ee=he;continue}if(he==="$"&&D[te+1]==="("){z++,te++;continue}if(he!==")")continue;if(z--,z===0)return te+1}return D.length}var Sg={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 Cg(D){let N=D.maxLen??200,z=D.redact??((te)=>te),ee=(te)=>te.length>N?`${te.slice(0,N)}...`:te;return[D.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${z(D.reason)}`,D.ruleId?`Rule: ${D.ruleId}`:void 0,D.toolName?`Tool: ${D.toolName}`:void 0,D.command?`Command: ${ee(z(D.command))}`:void 0,D.segment&&D.segment!==D.command?`Segment: ${ee(z(D.segment))}`:void 0,D.cwd?`Working directory: ${ee(z(D.cwd))}`:void 0,D.configWarning?`Config warning: ${z(D.configWarning)}`:void 0,D.askUser?"Approve only if you expected this command.":Sg[D.intent??"manual_only"]].filter((te)=>te!==void 0).join(`
|
|
2
2
|
|
|
3
3
|
`)}function ye(D,N){if(D.decision.kind!=="deny")return;let z=N.includeEvidence?D.decision.evidence:void 0;return{reason:D.decision.reason,ruleId:D.decision.ruleId,intent:D.decision.intent,command:z?.command,segment:z?.segment,toolName:N.toolName,...D.configFallback?{configWarning:D.configFallback.reason}:{},...D.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function P(D={}){return{reason:bo,intent:"stop_and_explain",command:D.command,segment:D.segment??D.command,toolName:D.toolName}}var vg={session:{unusable:{reason:"CC Safety Net cannot check tool calls because the session's working directory or workspace root no longer exists, is inaccessible, is not a directory, or uses an unsupported path form. Ask the user to restart the session from an existing directory.",intent:"hard_stop"},"outside-workspace":{reason:"CC Safety Net cannot check tool calls because the session's working directory is outside its workspace roots. Ask the user to restart the session from a directory inside the workspace.",intent:"hard_stop"}},requested:{unusable:{reason:"CC Safety Net could not use the requested working directory because it does not exist, is inaccessible, is not a directory, or uses an unsupported path form. Use an existing accessible working directory. If the requested directory is missing, create it from an accessible location before retrying the command.",intent:"use_alternative"},"outside-workspace":{reason:"CC Safety Net could not use the requested working directory because it is outside the session's workspace. Use a working directory inside the workspace.",intent:"use_alternative"}}};function A(D,N={}){return{...vg[D.directory][D.problem],command:N.command,toolName:N.toolName,cwd:D.cwd}}function be(D){return Cg({...D,redact:V})}function Xe(D){return V(D instanceof Error?D.message:String(D))}import{lstatSync as rh,realpathSync as oh,statSync as ih}from"node:fs";import{homedir as sh,tmpdir as ah}from"node:os";import{statSync as eh}from"node:fs";import{join as th}from"node:path";import{basename as Wc,dirname as Eg,isAbsolute as xg,join as Rg,normalize as _g,resolve as Nc}from"node:path";var wg=256,hi=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 gn(D,N=process.platform){if(N!=="win32")return D;return D.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function rr(D,N=process.platform){if(N!=="win32")return!1;return(D[0]==="/"||D[0]==="\\")&&(D[1]==="/"||D[1]==="\\")}function ta(D,N){return Js(D,0,N)}function Js(D,N,z){let ee="",te=0;while(te<D.length){if(D[te]!=="$"){ee+=D[te],te++;continue}if(D[te+1]==="{"){let je=Qs(D,te+2),at=Pg(D,te,N);if(at===null){if(hi.has(je))throw new s("pathEnvironmentExpansion");ee+=D.slice(te);break}let lt=D.slice(te,at+1);ee+=Ag(lt,N,z),te=at+1;continue}let he=Qs(D,te+1);if(!he){ee+="$",te++;continue}ee+=ea(he,z)??`$${he}`,te+=he.length+1}return ee}function Pg(D,N,z){let ee=1;for(let te=N+2;te<D.length;te++){if(D[te]==="\\"){te++;continue}if(D[te]==="$"&&D[te+1]==="{"){if(ee++,z+ee>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");te++;continue}if(D[te]!=="}")continue;if(ee--,ee===0)return te}return null}function Ag(D,N,z){let ee=D.slice(2,-1),te=Qs(ee,0);if(!te)return D;let he=ee.slice(te.length);if(!he)return ea(te,z)??D;let je=[":-",":+",":=",":?","-","+","=","?"].find((ct)=>he.startsWith(ct));if(!je){if(hi.has(te))throw new s("pathEnvironmentExpansion");return D}if(!hi.has(te))return D;if(je.endsWith("="))throw new s("pathEnvironmentExpansion");let at=ea(te,z),lt=je.startsWith(":")?at!==null&&at!=="":at!==null;if(je.endsWith("?")&&!lt)throw new s("pathEnvironmentExpansion");if(je.endsWith("-")||je.endsWith("?"))return lt?at??"":Js(he.slice(je.length),N+1,z);return lt?Js(he.slice(je.length),N+1,z):""}function Qs(D,N){if(!/[A-Za-z_]/.test(D[N]??""))return"";let z=N+1;while(/[A-Za-z0-9_]/.test(D[z]??""))z++;return D.slice(N,z)}function ea(D,N){if(!hi.has(D))return null;if(D==="HOME")return N.env.get("HOME")??N.home;return N.env.get(D)??null}function Ot(D,N,z){if(!D)return D;let ee=z.resolvedPaths.get(D);if(ee!==void 0)return ee;let te=[],he=D;while(!0){Gc(z,he);let je=N.realpath(he);if(je!==null)return Lc(z,D,je,te);let at=Eg(he);if(at===he||te.length>=wg)return Lc(z,D,he,te);te.push(Wc(he)),he=at}}function Lc(D,N,z,ee){let te=ee.length===0?z:Rg(z,...ee.reverse());return D.resolvedPaths.set(N,te),te}function Tg(D,N,z){let ee=z.resolvedPaths.get(D);if(ee!==void 0)return ee;Gc(z,D);let te=N.realpath(D);if(te!==null)z.resolvedPaths.set(D,te);return te}function Gc(D,N){D.charge("realpathAttempts"),D.charge("processedCandidateBytes",Buffer.byteLength(N))}function nn(D,N,z,ee){let te=zc(D,N,z);if(!te)return"";return Ot(te,z.paths,ee).replace(/\\/g,"/")}function Fc(D,N,z,ee,te){let he=zc(D,N,z);if(!he)return null;if(te(Wc(he)))return Ot(he,z.paths,ee).replace(/\\/g,"/");let je=Tg(he,z.paths,ee);return je===null?null:je.replace(/\\/g,"/")}function zc(D,N,z){let ee=z.home,te=ta(D.trim(),z).replace(/\\/g,"/");if(!te)return"";let he=te==="~"?ee:te.startsWith("~/")?Nc(ee,te.slice(2)):te,je=gn(he);return _g(xg(je)?je:Nc(N,je))}import{spawnSync as Ig}from"node:child_process";import{existsSync as Co,lstatSync as kg,readFileSync as vo,realpathSync as zr,statSync as So}from"node:fs";import{dirname as na,isAbsolute as ra,join as Br,resolve as yi}from"node:path";var Og=["/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"],Mg=5000;function $c(D,N=Zg(),z=Mg){let ee=Dg(D),te=ee===null?null:Ng(ee);if(ee===null||te===null)return null;let he=qg(ee,te,N,z);return he===null?null:{recursiveSubmodules:he}}function Dg(D){try{let N=zr(yi(D));return So(N).isDirectory()?N:null}catch{return null}}function Ng(D){let N=Kg(D);if(!N)return null;try{let z=kg(N);if(z.isSymbolicLink()||!z.isFile())return null;let ee=oa(N);if(!ee?.commonDir)return null;if(!Gg(ee.gitDir,N))return null;return Fg(ee.gitDir,na(N))?{gitDir:ee.gitDir,commonDir:ee.commonDir}:null}catch{return null}}function oa(D){try{let N=Lg(D);if(!N)return null;let z=zr(ra(N)?N:yi(na(D),N));if(!So(z).isDirectory())return null;return{gitDir:z,commonDir:Wg(z)}}catch{return null}}function Lg(D){let N=vo(D,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!N.startsWith("gitdir:"))return null;return N.slice(7).trim()||null}function Wg(D){try{let N=vo(Br(D,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!N)return null;let z=zr(ra(N)?N:yi(D,N));return So(z).isDirectory()?z:null}catch{return null}}function Gg(D,N){let z=zg(D);return z===null?!1:Uc(D,z,N)}function Fg(D,N){let z=Bg(D);return z===null?!0:Uc(D,z,N)}function zg(D){let N=Br(D,"gitdir");if(!Co(N))return null;let z=vo(N,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return z===""?null:z}function Bg(D){let N=Br(D,"config.worktree");return Co(N)?Ug(N):null}function Uc(D,N,z){try{return $g(ra(N)?N:yi(D,N),z)}catch{return!1}}function $g(D,N){try{let z=So(D),ee=So(N);if(z.ino!==0&&ee.ino!==0&&z.dev===ee.dev&&z.ino===ee.ino)return!0}catch{}return Bc(zr.native(D))===Bc(zr.native(N))}function Bc(D){let N=D.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),z=N.length>1&&N.endsWith("/")?N.slice(0,-1):N;return process.platform==="win32"?z.toLowerCase():z}function Ug(D){let N=vo(D,"utf-8"),z=!1,ee=null;for(let te of N.split(/\r?\n/)){let he=te.trim();if(he===""||he.startsWith("#")||he.startsWith(";"))continue;if(he.startsWith("[")){z=/^\[core\]$/i.test(he);continue}if(!z)continue;let je=he.match(/^worktree\s*=\s*(.*)$/i);if(je)ee=Hg(je[1]??"")}return ee}function Hg(D){let N=D.trim();if(!N.startsWith('"')||!N.endsWith('"'))return N;return Vg(N.slice(1,-1))}var jg={"\\":"\\",'"':'"',n:`
|
|
4
|
-
`,t:"\t",b:"\b"};function Vg(D){return D.replace(/\\(.?)/gs,(N,z)=>z===""?N:jg[z]??N)}function Kg(D){try{return ia(zr(D))}catch{return null}}function ia(D){let N=D;while(!0){let z=Br(N,".git");if(Co(z))return z;let ee=na(N);if(ee===N)return null;N=ee}}function qg(D,N,z,ee){if(Yg(N))return!0;if(z===null)return!0;let te=Ig(z,["config","--get","submodule.recurse"],{cwd:D,encoding:"utf8",env:Xg(process.env),stdio:["ignore","pipe","ignore"],timeout:ee});if(te.error!==void 0||te.status!==0&&te.status!==1)return null;return te.status===0&&Hc(te.stdout.trim())}function Yg(D){return[Br(D.commonDir,"config"),Br(D.gitDir,"config.worktree")].filter((N)=>Co(N)).some((N)=>Jg(N))}function Zg(){return Og.find((D)=>Co(D))??null}function Eo(D){return D==="GIT_CONFIG_COUNT"||D==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(D)}function Xg(D){return Object.fromEntries(Object.entries(D).filter(([N])=>!Eo(N)))}function Jg(D){let N;try{N=vo(D,"utf-8")}catch{return!0}let z="",ee=!1;for(let te of N.split(/\r?\n/)){let he=te.trim();if(he===""||he.startsWith("#")||he.startsWith(";"))continue;let je=he.match(/^\[([^\]]+)\]$/);if(je){z=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(Qg(z)&<==="path")return!0;if(z==="submodule"&<==="recurse")ee=Hc(ct)}return ee}function Qg(D){return D==="include"||D.startsWith("includeif ")}function Hc(D){let N=D.toLowerCase();return N!=="false"&&N!=="no"&&N!=="off"&&N!=="0"}function jc(D,N){if(D==="")return null;let z=pn(),ee=ia(nn(D,D,N,z)),te=ee?nh(ee,D,N,z):null;if(!te)return null;return Object.freeze({entries:Object.freeze([te.entry]),markerFiles:Object.freeze(te.markerFile?[te.markerFile]:[]),directories:Object.freeze(te.directories),hooksDirectories:Object.freeze(te.hooksDirectories)})}function nh(D,N,z,ee){try{let te=nn(D,N,z,ee),he=eh(D),je=he.isFile()?te:null,at=he.isFile()?oa(D):null,lt=(he.isDirectory()?[te]:[at?.gitDir,at?.commonDir]).flatMap((dt)=>dt?[$r(nn(dt,N,z,ee))]:[]),ct=[...new Set(he.isDirectory()?[$r(D.replace(/\\/g,"/")),...lt]:lt)];return{entry:$r(te),markerFile:je?$r(je):null,directories:ct,hooksDirectories:[...new Set(ct.flatMap((dt)=>{let ft=$r(th(dt,"hooks").replace(/\\/g,"/"));return[ft,$r(nn(ft,N,z,ee))]}))]}}catch{return null}}function $r(D){return process.platform==="win32"?D.toLowerCase():D}var lh={realpath:(D)=>{try{return oh(D)}catch{return null}},entryKind:(D)=>{let N=rh(D,{throwIfNoEntry:!1});if(!N)return"missing";return N.isSymbolicLink()?"symlink":"present"},isDirectory:(D)=>{try{return ih(D).isDirectory()}catch{return!1}}};function c(){return ch({env:new Map(Object.entries(process.env).flatMap(([D,N])=>N===void 0?[]:[[D,N]])),home:gn(process.env.HOME||sh()),tmpdir:ah(),paths:lh})}function ch(D,N={}){let z=new Map,ee=new Map,te={...D,gitMetadata:(he)=>Vc(z,he,()=>jc(he,te)),worktreeFacts:(he)=>Vc(ee,he,()=>$c(he)),...N};return te}function Vc(D,N,z){let ee=D.get(N);if(ee!==void 0)return ee;let te=z();return D.set(N,te),te}import{accessSync as Oh,constants as lu,statSync as Mh}from"node:fs";import{isAbsolute as uu,relative as Dh,resolve as Nh,sep as Lh}from"node:path";import{types as uh}from"node:util";var dh=new Set(["applypatch","patch"]),fh=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),mh=new Set(["grep","grepsearch","rg"]),ph=new Set(["find","findbyname","glob"]),gh=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),hh=new Set(["command","diff","input","patch","patchtext"]),Kc=new TextEncoder,yh=new TextDecoder,bh=/\s/,Sh=64;class f extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var xo=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Jc(D){return D.replace(/[-_\s]/g,"").toLowerCase()}function Si(D){return gh.has(Jc(D))}function q(D){let N=Jc(D);if(dh.has(N))return"patch";if(mh.has(N))return"grep";if(ph.has(N))return"glob";if(fh.has(N))return"path";return"unknown"}function ne(D){if(!D||typeof D!=="object")return;iu(D);let N=Object.getOwnPropertyDescriptor(D,"command");if(!N){if("command"in D)zn();return}if(N.get||N.set)zn();let z=N.value;return typeof z==="string"&&z!==""?z:void 0}function Qc(D,N){return eu(D,N,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function eu(D,N,z,ee){let
|
|
4
|
+
`,t:"\t",b:"\b"};function Vg(D){return D.replace(/\\(.?)/gs,(N,z)=>z===""?N:jg[z]??N)}function Kg(D){try{return ia(zr(D))}catch{return null}}function ia(D){let N=D;while(!0){let z=Br(N,".git");if(Co(z))return z;let ee=na(N);if(ee===N)return null;N=ee}}function qg(D,N,z,ee){if(Yg(N))return!0;if(z===null)return!0;let te=Ig(z,["config","--get","submodule.recurse"],{cwd:D,encoding:"utf8",env:Xg(process.env),stdio:["ignore","pipe","ignore"],timeout:ee});if(te.error!==void 0||te.status!==0&&te.status!==1)return null;return te.status===0&&Hc(te.stdout.trim())}function Yg(D){return[Br(D.commonDir,"config"),Br(D.gitDir,"config.worktree")].filter((N)=>Co(N)).some((N)=>Jg(N))}function Zg(){return Og.find((D)=>Co(D))??null}function Eo(D){return D==="GIT_CONFIG_COUNT"||D==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(D)}function Xg(D){return Object.fromEntries(Object.entries(D).filter(([N])=>!Eo(N)))}function Jg(D){let N;try{N=vo(D,"utf-8")}catch{return!0}let z="",ee=!1;for(let te of N.split(/\r?\n/)){let he=te.trim();if(he===""||he.startsWith("#")||he.startsWith(";"))continue;let je=he.match(/^\[([^\]]+)\]$/);if(je){z=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(Qg(z)&<==="path")return!0;if(z==="submodule"&<==="recurse")ee=Hc(ct)}return ee}function Qg(D){return D==="include"||D.startsWith("includeif ")}function Hc(D){let N=D.toLowerCase();return N!=="false"&&N!=="no"&&N!=="off"&&N!=="0"}function jc(D,N){if(D==="")return null;let z=pn(),ee=ia(nn(D,D,N,z)),te=ee?nh(ee,D,N,z):null;if(!te)return null;return Object.freeze({entries:Object.freeze([te.entry]),markerFiles:Object.freeze(te.markerFile?[te.markerFile]:[]),directories:Object.freeze(te.directories),hooksDirectories:Object.freeze(te.hooksDirectories)})}function nh(D,N,z,ee){try{let te=nn(D,N,z,ee),he=eh(D),je=he.isFile()?te:null,at=he.isFile()?oa(D):null,lt=(he.isDirectory()?[te]:[at?.gitDir,at?.commonDir]).flatMap((dt)=>dt?[$r(nn(dt,N,z,ee))]:[]),ct=[...new Set(he.isDirectory()?[$r(D.replace(/\\/g,"/")),...lt]:lt)];return{entry:$r(te),markerFile:je?$r(je):null,directories:ct,hooksDirectories:[...new Set(ct.flatMap((dt)=>{let ft=$r(th(dt,"hooks").replace(/\\/g,"/"));return[ft,$r(nn(ft,N,z,ee))]}))]}}catch{return null}}function $r(D){return process.platform==="win32"?D.toLowerCase():D}var lh={realpath:(D)=>{try{return oh(D)}catch{return null}},entryKind:(D)=>{let N=rh(D,{throwIfNoEntry:!1});if(!N)return"missing";return N.isSymbolicLink()?"symlink":"present"},isDirectory:(D)=>{try{return ih(D).isDirectory()}catch{return!1}}};function c(){return ch({env:new Map(Object.entries(process.env).flatMap(([D,N])=>N===void 0?[]:[[D,N]])),home:gn(process.env.HOME||sh()),tmpdir:ah(),paths:lh})}function ch(D,N={}){let z=new Map,ee=new Map,te={...D,gitMetadata:(he)=>Vc(z,he,()=>jc(he,te)),worktreeFacts:(he)=>Vc(ee,he,()=>$c(he)),...N};return te}function Vc(D,N,z){let ee=D.get(N);if(ee!==void 0)return ee;let te=z();return D.set(N,te),te}import{accessSync as Oh,constants as lu,statSync as Mh}from"node:fs";import{isAbsolute as uu,relative as Dh,resolve as Nh,sep as Lh}from"node:path";import{types as uh}from"node:util";var dh=new Set(["applypatch","patch"]),fh=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),mh=new Set(["grep","grepsearch","rg"]),ph=new Set(["find","findbyname","glob"]),gh=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),hh=new Set(["command","diff","input","patch","patchtext"]),Kc=new TextEncoder,yh=new TextDecoder,bh=/\s/,Sh=64;class f extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var xo=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Jc(D){return D.replace(/[-_\s]/g,"").toLowerCase()}function Si(D){return gh.has(Jc(D))}function q(D){let N=Jc(D);if(dh.has(N))return"patch";if(mh.has(N))return"grep";if(ph.has(N))return"glob";if(fh.has(N))return"path";return"unknown"}function ne(D){if(!D||typeof D!=="object")return;iu(D);let N=Object.getOwnPropertyDescriptor(D,"command");if(!N){if("command"in D)zn();return}if(N.get||N.set)zn();let z=N.value;return typeof z==="string"&&z!==""?z:void 0}function Qc(D,N){return eu(D,N,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function eu(D,N,z,ee,te){let he=ou(D,ee,te);if(typeof D==="string")return z?[D]:[];if(!he)return[];let je=he.entries.flatMap(([at,lt])=>eu(lt,N,he.array?z:N.has(tu(at)),ee,te+1));return ee.ancestors.delete(he.object),je}function tu(D){return D.replace(/-/g,"_").toLowerCase()}function nu(D){return ru(D,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(vh)}function ru(D,N,z,ee){let te=ou(D,z,ee);if(typeof D==="string")return N?[D]:[];if(!te)return[];let he=te.entries.flatMap(([je,at])=>ru(at,te.array?N:hh.has(tu(je)),z,ee+1));return z.ancestors.delete(te.object),he}function Ch(D,N,z){if(N.nodes++,D!==null&&typeof D==="object"&&z>xo.maxDepth||N.nodes>xo.maxNodes)zn();if(typeof D!=="string")return;let ee=Buffer.byteLength(D);if(N.stringBytes+=ee,ee>xo.maxStringBytes||N.stringBytes>xo.maxAggregateStringBytes)zn()}function ou(D,N,z){if(Ch(D,N,z),!D||typeof D!=="object")return null;let ee=iu(D);if(N.ancestors.has(D))zn();let te=Reflect.ownKeys(D);if(N.keys+=te.length,N.keys>xo.maxKeys)zn();let he=te.flatMap((je)=>{let at=Object.getOwnPropertyDescriptor(D,je);if(!at||at.get||at.set)zn();return typeof je==="string"&&at.enumerable?[[je,at.value]]:[]});return N.ancestors.add(D),{object:D,array:ee,entries:he}}function iu(D){if(uh.isProxy(D))zn();let N=Array.isArray(D),z=Object.getPrototypeOf(D);if(N&&z!==Array.prototype||!N&&z!==Object.prototype&&z!==null)zn();return N}function zn(){throw new f}function vh(D){let N=[],z=D.split(/\r?\n/),ee=!1,te=!1,he=null,je=null,at=()=>{te=!1,he=null,je=null};for(let lt=0;lt<z.length;lt++){let ct=z[lt]??"";if(ct==="*** Begin Patch"){ee=!0,at();continue}if(ct==="*** End Patch"){ee=!1,at();continue}if(ct.startsWith("@@")){let dt=Eh(ct);if(te=!0,he=dt?.oldLines??null,je=dt?.newLines??null,he===0&&je===0)at();continue}if(te&&he!==null&&je!==null){let dt=ct.startsWith(" ")||ct.startsWith("-")?1:0,ft=ct.startsWith(" ")||ct.startsWith("+")?1:0;if(he=Math.max(0,he-dt),je=Math.max(0,je-ft),he===0&&je===0)at();continue}if(ct.startsWith("*** ")){at(),N.push(...sa(ct));continue}if(te)continue;if(ct.startsWith("diff --git ")){N.push(...sa(ct));continue}if(ct.startsWith("--- ")){let dt=z[lt+1]??"";if(!dt.startsWith("+++ "))continue;N.push(...la(bi(ct.slice(4),!0),bi(dt.slice(4),!0))),lt++;continue}if(!ee)N.push(...sa(ct))}return N}function Eh(D){let N=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(D);if(!N)return null;return{oldLines:Number(N[1]??1),newLines:Number(N[2]??1)}}function sa(D){let N=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(D);if(N?.[1])return Xc(N[1]);let z=/^\*\*\* Move to: (.+)$/.exec(D);if(z?.[1])return Xc(z[1]);if(D.startsWith("diff --git "))return xh(D.slice(11));let ee=/^--- (.+)$/.exec(D);if(ee?.[1])return Zc(ee[1]);let te=/^\+\+\+ (.+)$/.exec(D);if(te?.[1])return Zc(te[1]);let he=/^(?:rename|copy) (?:from|to) (.+)$/.exec(D);if(he?.[1])return Ih(he[1]);return[]}function xh(D){let N=Rh(D);if(N.length===2&&N[0]&&N[1])return la(N[0],N[1]);let z=_h(D);return z?la(D.slice(z.oldStart,z.oldEnd),D.slice(z.newStart,z.newEnd)):[]}function Rh(D){let N=[],z=0;while(z<D.length&&N.length<2){while(yr(D[z]))z++;if(z>=D.length)break;let ee=D[z]==='"'||D[z]==="'"?D[z]:void 0;if(!ee){let he=z;while(z<D.length&&!yr(D[z]))z++;N.push(D.slice(he,z));continue}let te=su(D,z,ee);if(!te)return[];N.push(te.value),z=te.end}while(yr(D[z]))z++;return z===D.length?N:[]}function _h(D){let N=0;while(N<D.length&&yr(D[N]))N++;let z=D.length;while(z>N&&yr(D[z-1]))z--;let ee=0,te=N;while(te<z){if(!yr(D[te])){te++;continue}let he=te;while(te<z&&yr(D[te]))te++;if(he===N||te===z)continue;if(ee++,ee>Sh)zn();if(wh(D,N,he,te,z))return{oldStart:N,oldEnd:he,newStart:te,newEnd:z}}return null}function wh(D,N,z,ee,te){if(aa(D,N,z,ee,te))return!0;let he=qc(D,"/",N,z),je=qc(D,"/",ee,te);if(he<=N||je<=ee)return!1;if(aa(D,N,he,ee,je))return!1;return aa(D,he+1,z,je+1,te)}function aa(D,N,z,ee,te){if(z-N!==te-ee)return!1;for(let he=0;he<z-N;he++)if(D[N+he]!==D[ee+he])return!1;return!0}function qc(D,N,z,ee){for(let te=z;te<ee;te++)if(D[te]===N)return te;return-1}function yr(D){return D!==void 0&&bh.test(D)}function su(D,N,z){let ee=[],te=N+1;while(te<D.length){let he=String.fromCodePoint(D.codePointAt(te)??0);if(he===z)return{value:yh.decode(Uint8Array.from(ee)),end:te+1};if(he!=="\\"||z==="'"){ee.push(...Kc.encode(he)),te+=he.length;continue}let je=D.slice(te+1),at=/^[0-7]{1,3}/.exec(je)?.[0];if(at){ee.push(Number.parseInt(at,8)),te+=at.length+1;continue}ee.push(...Kc.encode(Ph(je[0]??""))),te+=2}return null}function Ph(D){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
5
5
|
`,r:"\r",t:"\t",v:"\v"}[D]??D}function Ah(D){return Ro(kh(D))}function la(D,N){if(D==="/dev/null")return Yc(N);if(N==="/dev/null")return Yc(D);if(D.startsWith("a/")&&N.startsWith("b/"))return[D.slice(2),N.slice(2)].flatMap(Ro);let z=Th(D,N)??(D===N?au(D):null);return[D,N,...z?[z]:[]].flatMap(Ro)}function Yc(D){let N=au(D);return[D,...N?[N]:[]].flatMap(Ro)}function au(D){let N=D.indexOf("/");return N>0&&N<D.length-1?D.slice(N+1):null}function Th(D,N){let z=D.indexOf("/"),ee=N.indexOf("/");if(z<1||ee<1)return null;if(D.slice(0,z)===N.slice(0,ee))return null;let te=D.slice(z+1);return te===N.slice(ee+1)?te:null}function Zc(D){return Ah(bi(D,!0))}function Ih(D){return Ro(bi(D,!1))}function bi(D,N){let z=D.trim(),ee=z[0]==='"'||z[0]==="'"?z[0]:void 0;if(ee){let te=su(z,0,ee);if(te&&(N||z.slice(te.end).trim()===""))return te.value}return N?z.split("\t",1)[0]?.trim()??"":z}function kh(D){return D.startsWith("a/")||D.startsWith("b/")?D.slice(2):D}function Ro(D){return D===""||D==="/dev/null"?[]:[D]}function Xc(D){let N=D.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return N===""||N==="/dev/null"?[]:[N]}function ce(D){try{if(!Mh(D).isDirectory())return!1;return Oh(D,lu.R_OK|lu.X_OK),!0}catch{return!1}}function et(D,N,z){if(rr(D))return;let ee=N.flatMap((he)=>cu(he,z));if(!ee[0])return;let te=cu(uu(D)?D:Nh(ee[0],D),z)[0];if(!te)return;return ee.some((he)=>Wh(te,he))?te:void 0}function cu(D,N){let z=N.realpath(D);if(z===null)return[];return N.isDirectory(z)?[z]:[]}function Wh(D,N){let z=Dh(N,D);return z===""||z!==".."&&!z.startsWith(`..${Lh}`)&&!uu(z)}var Gh=8388608;async function We(D){let N=[],z=0;for await(let ee of D){let te=typeof ee==="string"?Buffer.from(ee,"utf-8"):Buffer.from(ee.buffer,ee.byteOffset,ee.byteLength);if(z+=te.byteLength,z>Gh)throw Fh(D),Error("hook input byte limit exceeded");N.push(te)}return Buffer.concat(N,z).toString("utf-8")}function Fh(D){let N=D.destroy??D.cancel;if(!N)return;try{Promise.resolve(N.call(D)).catch(()=>{})}catch{}}function d(D,N,z,ee,te){if(z.kind!=="command")return{toolName:D,input:N,route:z,context:ee};return{toolName:D,input:N,route:z,context:ee,command:te}}var Ur=["fail_closed","paranoid_rm","paranoid_interpreters"],Ci={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"}},vi=["standard","strict","paranoid"];function zh(D,N){if(!N)return D;return vi.indexOf(N)>vi.indexOf(D)?N:D}function Bh(D){let N=ve(o.level,D);if(N===void 0||N==="")return;if(vi.includes(N))return N;console.error(`CC Safety Net: ignored invalid ${o.level.name}=${JSON.stringify(N.slice(0,40))}. Use ${vi.join(", ")}.`);return}function He(D){if(D===void 0||D==="all")return"all";if(D==="blocked")return"blocked";return"invalid"}function xe(D){return He(ve(o.auditScope,D))==="all"}function ca(D){if(D.failClosed&&D.paranoidRm&&D.paranoidInterpreters)return"paranoid";if(D.failClosed&&!D.paranoidRm&&!D.paranoidInterpreters)return"strict";if(!D.failClosed&&!D.paranoidRm&&!D.paranoidInterpreters)return"standard";return"custom"}function R(D={},N){let z=D.safety?.level??"standard",ee=Bh(N),te=zh(z,ee),he=Ci[te],je={failClosed:he.fail_closed,paranoidRm:he.paranoid_rm,paranoidInterpreters:he.paranoid_interpreters},at={failClosed:te===z?"preset":"environment",paranoidRm:te===z?"preset":"environment",paranoidInterpreters:te===z?"preset":"environment"},lt={failClosed:[`policy safety.level=${z}`],paranoidRm:[`policy safety.level=${z}`],paranoidInterpreters:[`policy safety.level=${z}`]};if(te!==z)lt.failClosed.push(`env ${o.level.name}=${ee}`),lt.paranoidRm.push(`env ${o.level.name}=${ee}`),lt.paranoidInterpreters.push(`env ${o.level.name}=${ee}`);if(D.safety?.overrides?.failClosed!==void 0)je.failClosed=D.safety.overrides.failClosed,at.failClosed="capability_override",lt.failClosed.push("policy safety.overrides.fail_closed");if(D.safety?.overrides?.paranoidRm!==void 0)je.paranoidRm=D.safety.overrides.paranoidRm,at.paranoidRm="capability_override",lt.paranoidRm.push("policy safety.overrides.paranoid_rm");if(D.safety?.overrides?.paranoidInterpreters!==void 0)je.paranoidInterpreters=D.safety.overrides.paranoidInterpreters,at.paranoidInterpreters="capability_override",lt.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(L(o.strict,N))je.failClosed=!0,at.failClosed="environment",lt.failClosed.push(`env ${o.strict.name}`);if(L(o.paranoid,N))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,N))je.paranoidRm=!0,at.paranoidRm="environment",lt.paranoidRm.push(`env ${o.paranoidRm.name}`);if(L(o.paranoidInterpreters,N))je.paranoidInterpreters=!0,at.paranoidInterpreters="environment",lt.paranoidInterpreters.push(`env ${o.paranoidInterpreters.name}`);let ct=!!D.worktreeMode||L(o.worktree,N);return{strict:je.failClosed,paranoidRm:je.paranoidRm,paranoidInterpreters:je.paranoidInterpreters,worktreeMode:ct,effectiveLevel:ca(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(D,N){let z=typeof D==="string"?_o(D,N):ve(D,N);return z==="1"||z?.toLowerCase()==="true"}function _o(D,N){return N.get(D)}function ve(D,N){let z=_o(D.name,N);if(z!==void 0)return z;if(D.legacyName)return _o(D.legacyName,N);return}function Qe(D,N){return _o(D.name,N)!==void 0||!!D.legacyName&&_o(D.legacyName,N)!==void 0}import{dirname as Er}from"node:path";import{closeSync as $h,constants as wo,fstatSync as ua,fsyncSync as Uh,lstatSync as vn,mkdirSync as du,openSync as fu,readdirSync as fa,readFileSync as Hh,realpathSync as Hr,renameSync as jh,rmdirSync as mu,statSync as da,unlinkSync as ma,writeFileSync as Vh}from"node:fs";import{isAbsolute as pu,join as br,normalize as Kh,parse as Ei,relative as pa,resolve as ga,sep as xi}from"node:path";function Re(){let D=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${D()}${D()}`}var qh=Symbol("PolicyFilesystemScope"),Yh=Symbol("PolicyFilesystemTarget"),gu=wo.O_NOFOLLOW??0;class r extends Error{name="PolicyFilesystemError";constructor(D){super(`Unable to access ${D} filesystem safely.`)}}function v(D,N){return{[qh]:!0,root:ga(D),label:N}}function Po(D,N){let z=Kh(N);if(N===""||pu(N)||z===".."||z.startsWith(`..${xi}`))throw new r(D.label);return{[Yh]:!0,scope:D,relativePath:z,path:br(D.root,z)}}function i(D,N){return Po(D,pa(D.root,ga(N)))}function re(D,N="rules policy"){let z=ga(D),ee=Ei(z).dir;return Po(v(ee,N),pa(ee,z))}function n(D){return Vn(D.scope.label,()=>{if(!Zt(D))return null;let N=fu(D.path,wo.O_RDONLY|gu);return yu(N,()=>{let z=ua(N);if(!z.isFile())throw new r(D.scope.label);let ee=Hh(N,"utf-8"),te=vn(D.path);if(!te.isFile()||te.isSymbolicLink()||z.dev!==te.dev||z.ino!==te.ino)throw new r(D.scope.label);return Zt(D),ee})})}function g(D,N,z=384,ee){let te=`${D.path}.${Re()}.tmp`;Vn(D.scope.label,()=>{Xh(D),Zt(D);let he=fu(te,wo.O_CREAT|wo.O_EXCL|wo.O_WRONLY|gu,z),je=yu(he,()=>{let at=ua(he);if(!at.isFile())throw new r(D.scope.label);Vh(he,N,"utf-8"),Uh(he);let lt=ua(he);if(!lt.isFile()||lt.dev!==at.dev||lt.ino!==at.ino)throw new r(D.scope.label);return lt});Zt(D),Qh(D,te,je.dev,je.ino),jh(te,D.path),ee?.(D.path),Zt(D)},()=>ey(te))}function hu(D,N){if(D.path===N.path)return!0;return Vn(D.scope.label,()=>{if(!Zt(D)||!Zt(N))return!1;let z=(ee)=>br(Hr(Ei(ee).dir),Ei(ee).base);return z(D.path)===z(N.path)})}function le(D){let N=Vn(D.scope.label,()=>{if(!Zt(D,"directory"))return null;let z=fa(D.path);return Zt(D,"directory"),z});if(!N)return null;return Vn(D.scope.label,()=>{let z=N.map((ee)=>{let te=Po(D.scope,br(D.relativePath,ee)),he=vn(te.path);if(he.isSymbolicLink()||!he.isFile()&&!he.isDirectory())throw new r(D.scope.label);return Ri(ha(D.scope),Hr(te.path),D.scope.label),{name:ee,kind:he.isDirectory()?"directory":"file"}});return Zt(D,"directory"),z})}function F(D){Vn(D.scope.label,()=>{if(!Zt(D))return;ma(D.path),Zt(D)})}function tt(D){Vn(D.scope.label,()=>{if(!Zh(D))return;Su(D),Zt(D,"directory")})}function nt(D){Vn(D.scope.label,()=>{if(!Zt(D,"directory"))return;mu(D.path),Zt(D,"directory")})}function Zh(D){return Vn(D.scope.label,()=>{if(!Zt(D,"directory"))return!1;return bu(D),!0})}function Vn(D,N,z){try{return N()}catch(ee){if(z?.(),ee instanceof r)throw ee;throw new r(D)}}function yu(D,N){try{return N()}finally{$h(D)}}function Zt(D,N="file"){let z=Cu(D.scope);if(!z)return!1;let ee=D.relativePath.split(xi);for(let te of ee.keys()){let he=br(D.scope.root,...ee.slice(0,te+1)),je=vn(he,{throwIfNoEntry:!1});if(!je)return!1;if(je.isSymbolicLink())throw new r(D.scope.label);if(te<ee.length-1&&!je.isDirectory())throw new r(D.scope.label);if(te===ee.length-1&&(N==="file"?!je.isFile():!je.isDirectory()))throw new r(D.scope.label);Ri(z,Hr(he),D.scope.label)}return!0}function bu(D){for(let N of fa(D.path)){let z=Po(D.scope,br(D.relativePath,N)),ee=vn(z.path);if(ee.isSymbolicLink()||!ee.isDirectory()&&!ee.isFile())throw new r(D.scope.label);if(ee.isDirectory())bu(z)}Zt(D,"directory")}function Su(D){for(let N of fa(D.path)){let z=Po(D.scope,br(D.relativePath,N)),ee=vn(z.path);if(ee.isSymbolicLink())throw new r(D.scope.label);if(ee.isDirectory()){Su(z);continue}if(!ee.isFile())throw new r(D.scope.label);ma(z.path)}mu(D.path)}function Xh(D){Jh(D.scope);let N=ha(D.scope),z=D.relativePath.split(xi).slice(0,-1);for(let ee of z.keys()){let te=br(D.scope.root,...z.slice(0,ee+1));if(!vn(te,{throwIfNoEntry:!1}))du(te,{mode:448});let he=vn(te);if(!he.isDirectory()||he.isSymbolicLink())throw new r(D.scope.label);Ri(N,Hr(te),D.scope.label)}}function Jh(D){if(vn(D.root,{throwIfNoEntry:!1})){if(!da(D.root).isDirectory())throw new r(D.label);return}let N=[],z=D.root;while(!vn(z,{throwIfNoEntry:!1})){N.unshift(z);let ee=Ei(z).dir;if(ee===z)throw new r(D.label);z=ee}if(!da(z).isDirectory())throw new r(D.label);for(let ee of N){du(ee,{mode:448});let te=vn(ee);if(!te.isDirectory()||te.isSymbolicLink())throw new r(D.label)}}function Cu(D){if(!vn(D.root,{throwIfNoEntry:!1}))return null;if(!da(D.root).isDirectory())throw new r(D.label);return Hr(D.root)}function ha(D){let N=Cu(D);if(!N)throw new r(D.label);return N}function Qh(D,N,z,ee){let te=vn(N);if(!te.isFile()||te.isSymbolicLink()||te.dev!==z||te.ino!==ee)throw new r(D.scope.label);Ri(ha(D.scope),Hr(N),D.scope.label)}function Ri(D,N,z){let ee=pa(D,N);if(ee===".."||ee.startsWith(`..${xi}`)||pu(ee))throw new r(z)}function ey(D){try{ma(D)}catch{}}import{dirname as Sr,isAbsolute as iy,join as vr,relative as sy,resolve as Cr,sep as ay}from"node:path";var l=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ue="rulebook.json",de=".cc-safety-net/rules";var vu=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,ty=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,Eu=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,ny=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ry="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),rt=new RegExp(`^${ny}/(${l.source.slice(1,-1)})/${ry}$`);function oy(D){return`.cc-safety-net/rules/${D}/rulebook.json`}function xu(D){if(S(D))try{return I(D),null}catch(N){return N instanceof Error?N.message:String(N)}return l.test(D)?null:`Local rulebook sources must be bare names matching ${l}: ${D}`}function I(D){if(D.startsWith("github:"))throw Error(`Invalid rulebook source: ${D}`);let N=D.match(vu);if(!N?.[1]||!N[2]||!N[3])throw Error(`Invalid GitHub rulebook source: ${D}`);let z=N[3].lastIndexOf("/");if(z<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${D}`);let ee=N[3].slice(0,z),te=N[3].slice(z+1);if(!ee||!Eu.test(ee))throw Error(`GitHub rulebook refs must use valid path segments: ${D}`);if(!te||!l.test(te))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${D}`);return{owner:N[1],repo:N[2],ref:ee,path:oy(te),name:te}}function K(D){return ty.test(D)}function oe(D){return Eu.test(D)}function S(D){return vu.test(D)}function ot(D){if(!l.test(D))throw Error(`Local rulebook sources must be bare names matching ${l}: ${D}`)}var Ru="rule.json",_i="policy.json",_u=".cc-safety-net",ly="rules",cy="CC_SAFETY_NET_HOME",wu="`cc-safety-net rule update`";function uy(D){return Cr(D,de)}function M(D){return vr(uy(D),Ru)}function b(D){return vr(Cr(D),_u,_i)}function Se(D,N={}){return N.userConfigDir??(N.userConfigPath?Sr(N.userConfigPath):vr(dy(D),ly))}function dy(D){let N=D.env.get(cy);return N?Cr(gn(N)):vr(D.home,_u)}function j(D,N={}){return vr(Se(D,N),Ru)}function u(D,N={}){return vr(Sr(Se(D,N)),_i)}function J(D,N){let z=N.userConfigPath??j(D,N),ee=N.projectConfigPath??M(N.cwd),te=Be(D,N),he=ze(ee,N.cwd);return{userConfigPath:z,projectConfigPath:ee,userScope:te,projectScope:he,userConfigTarget:i(te,z),projectConfigTarget:i(he,ee)}}function Be(D,N){let z=N.userConfigPath?Sr(Sr(Cr(N.userConfigPath))):Sr(Cr(N.userConfigDir??Se(D,N)));return v(z,"user policy")}function ze(D,N){let z=Cr(N),ee=Cr(D),te=sy(z,ee);if(te!==".."&&!te.startsWith(`..${ay}`)&&!iy(te))return v(z,"project policy");return v(Sr(Sr(ee)),"project policy")}function O(D,N){return vr(D,N,ue)}var hn=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),w=/^[a-zA-Z][a-zA-Z0-9_-]*$/,T=256,Ut=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Pu=new Set(["python","python3","python2","node","ruby","perl"]),wi=/^python(?:[23](?:\.\d+)*)?$/,En=new Set(["awk","gawk","nawk","mawk"]),Pi=new Set(["echo","printf","cat","head","tail","less","more","grep","rg","ag","ack","sed","awk","cut","tr","sort","uniq","wc","tee","man","help","info","type","which","whereis","whatis","apropos","file","stat","ls","ll","dir","tree","pwd","date","cal","uptime","whoami","id","groups","hostname","uname","env","printenv","set","export","alias","history","jobs","fg","bg","test","true","false","read","return","exit","break","continue","shift","wait","trap","basename","dirname","realpath","readlink","md5sum","sha256sum","base64","xxd","od","hexdump","strings","diff","cmp","comm","join","paste","column","fmt","fold","nl","pr","expand","unexpand","rev","tac","shuf","seq","yes","sleep","logger","write","wall","mesg","notify-send"]);var Au="Rulebook exceeds CC Safety Net's safe validation limits.",Tu="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 Iu(D){if(ya(D.allowed_commands,Pn.maxAllowedCommands)||ya(D.rules,Pn.maxRules)||ya(D.tests,Pn.maxTests))return!1;let{maxAggregateStringCodeUnits:N,maxTotalBlockArgs:z}=Pn,ee=(te,he=!1)=>{if(typeof te!=="string")return!0;if(te.length>Pn.maxStringCodeUnits||he&&te.length>Pn.maxFixtureCommandCodeUnits||te.length>N)return!1;return N-=te.length,!0};if(!ee(D.name)||!ee(D.version)||!ee(D.description)||!ee(D.author)||!ee(D.migrated_from))return!1;if(Array.isArray(D.allowed_commands)){for(let te of D.allowed_commands)if(!ee(te))return!1}if(Array.isArray(D.rules))for(let te of D.rules){if(!te||typeof te!=="object")continue;let he=te;if(!ee(he.name)||!ee(he.command)||!ee(he.subcommand)||!ee(he.reason)||!ee(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>z)return!1;z-=at.length;for(let lt of at)if(!ee(lt))return!1}}if(Array.isArray(D.tests))for(let te of D.tests){if(!te||typeof te!=="object")continue;let he=te;if(!ee(he.command,!0)||!ee(he.expect)||!ee(he.rule))return!1}return!0}function ya(D,N){return Array.isArray(D)&&D.length>N}var ba=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(D){return At(D).toLowerCase()}function At(D){return D.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??D}function an(D,N){let z=new Set,ee=!1;for(let te of D){if(te==="--"){ee=!0;continue}if(ee)continue;if(te.startsWith("-")&&!te.startsWith("--")&&te.length>1)for(let he=1;he<te.length;he++){let je=te[he];if(!je||!/[a-zA-Z]/.test(je))break;let at=`-${je}`;if(z.add(at),N?.shortOptsWithValue?.has(at))break}}return z}var fy={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Sa=new Set(["--init-file","--rcfile"]);function Ca(D,N,z,ee){let te=!1,he=0,je=!1,at=!1,lt=!1;for(let ct=1;ct<N.length;ct++){let dt=N[ct];if(dt===void 0)break;if(D==="ksh"&&dt==="o"&&ct+1<N.length){if(ee==="argv"){let ft=N.slice(ct+1);if(N[0]==="-"&&(ft==="c"||ft[0]==="-"&&ft.endsWith("c")))je=!0}break}if(D==="ksh"&&dt==="o"&&ct+1===N.length&&(z?.startsWith("-")||z?.startsWith("+")))break;if(D==="zsh"&&dt==="o"&&ct+1<N.length)break;if(ee==="startup"&&dt==="i")te=N[0]==="-";if(ee==="argv"&&N[0]==="-"&&dt==="c")je=!0;if(ee==="argv"&&dt==="n")lt=N[0]==="-";if(ee==="argv"&&dt==="s")at=N[0]==="-";if(!fy[D]?.includes(dt))continue;if(ct+1===N.length)he++;break}return{interactive:te,followingValues:he,commandSelected:je,stdinMode:at,syntaxCheck:lt}}function yn(D){let N=At(D[0]??"").toLowerCase(),z=!1,ee=!1,te=!1;for(let he=1;he<D.length;he++){let je=D[he];if(je===void 0)break;if(je==="--"){let lt=z&&D[he+1]!==void 0?he+1:null;return{command:lt===null?null:D[lt]??null,commandIndex:lt,scriptIndex:!z&&!ee&&D[he+1]!==void 0?he+1:null,readsStdinAsCommands:!z&&(ee||D[he+1]===void 0),syntaxCheck:te}}if(je==="-"||je[0]!=="-"&&je[0]!=="+")return{command:z?je:null,commandIndex:z?he:null,scriptIndex:!z&&!ee&&je!=="-"?he:null,readsStdinAsCommands:!z&&(ee||je==="-"),syntaxCheck:te};if(je.startsWith("--")){let lt=je.split("=",1)[0]??je;if(N==="bash"&&Sa.has(lt)&&!je.includes("="))he++;continue}let at=Ca(N,je,D[he+1],"argv");if(at.commandSelected)z=!0;if(at.syntaxCheck)te=!0;if(at.stdinMode)ee=!0;he+=at.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!z,syntaxCheck:te}}function Ao(D,N){if(N.escaped)return N.escaped=!1,!0;if(D==="\\"&&!N.inSingle)return N.escaped=!0,!0;if(D==="'"&&!N.inDouble)return N.inSingle=!N.inSingle,!0;if(D==='"'&&!N.inSingle)return N.inDouble=!N.inDouble,!0;return!1}function Ai(D){let N={inSingle:!1,inDouble:!1,escaped:!1};for(let z of my(D))Ao(z,N);return N.inSingle||N.inDouble}function my(D){let N="",z={inSingle:!1,inDouble:!1,escaped:!1},ee=!1,te=!0;for(let he=0;he<D.length;he++){let je=D[he];if(!je)break;if(ee){if(je===`
|
|
6
|
-
`||je==="\r")N+=je,ee=!1,z.escaped=!1;continue}if(je==="#"&&!z.inSingle&&!z.inDouble&&te){ee=!0;continue}if(N+=je,!z.inSingle&&!z.inDouble&&!z.escaped)te=/[\s;&|()<>]/.test(je);Ao(je,z)}return N}var va=new Set(["rm","find","xargs","parallel"]),py=new Set(["git","busybox",...va,...Ut,...Pu,...En]),gy=new Set(["python","node","ruby","perl"]);function Le(D){let N=It(D);return py.has(N)||An(N)}function An(D){return gy.has(hy(D))}function hy(D){let N=At(D).toLowerCase();return wi.test(N)?"python":N}var it={version:1,rules:[],overrides:{},transparent_wrappers:[]};function m(D){try{let N=n(yy(D));if(N===null)return{config:null,errors:[]};if(!N.trim())return{config:null,errors:["Config file is empty"]};let z=JSON.parse(N),ee=Ve(z);if(ee.errors.length>0)return{config:null,errors:ee.errors};return{config:{version:1,rules:z.rules??[],overrides:z.overrides??{},transparent_wrappers:z.transparent_wrappers??[]},errors:[]}}catch(N){if(N instanceof r)return{config:null,errors:[N.message]};let z=N instanceof Error?N.message:String(N);return{config:null,errors:[N instanceof SyntaxError?"Invalid JSON":z]}}}function yy(D){return typeof D==="string"?re(D):D}var e=(D,N)=>({path:D,message:N,kind:"typed"}),Xt=(D,N)=>({path:D,message:N,kind:"custom"});function Te(D){let N=new Set;return D.flatMap((z,ee)=>{let te=jr(z)?z.name:void 0;if(typeof te!=="string")return[];if(N.has(te.toLowerCase()))return[Xt(["rules",ee,"name"],`duplicate rule name "${te}"`)];return N.add(te.toLowerCase()),[]})}var we=`must be one of ${ba.join(", ")}`,by=/^[^/]+\/[^/]+$/,Sy=["version","rules","overrides","transparent_wrappers"];function Ve(D){let N=Cy(D);return{errors:ie(qe(N,Sy,(z)=>z.kind==="custom"),": "," "),sources:Ay(D,N)}}function Cy(D){if(!jr(D))return[e([],"Config must be an object")];let N=Array.isArray(D.rules)&&D.rules.length>pe;return[...D.version===1?[]:[e(["version"],"must be 1")],...vy(D.rules,N),...Ry(D.overrides),...wy(D.transparent_wrappers),...N?[]:xy(D.rules),...jr(D.overrides)?Object.keys(D.overrides).filter((z)=>!by.test(z)).map((z)=>Xt(["overrides",z],"must use <rulebook-name>/<rule-name>")):[],...Py(D.transparent_wrappers)]}function vy(D,N){if(D===void 0)return[];if(!Array.isArray(D))return[e(["rules"],"must be an array of rulebook source strings"),...ku(D,pe)?[e(["rules"],fe)]:[]];if(N)return[{path:["rules"],message:fe,kind:"limit"}];return D.flatMap((z,ee)=>{if(typeof z!=="string")return[e(["rules",ee],"must be a rulebook source string"),...Ey(z,1)?[e(["rules",ee],"must be a non-empty rulebook source string")]:[]];return z===""?[e(["rules",ee],"must be a non-empty rulebook source string")]:[]})}function ku(D,N){let z=Ou(D);return z!==void 0&&!(z<=N)}function Ey(D,N){let z=Ou(D);return z!==void 0&&!(z>=N)}function Ou(D){if(D===null||D===void 0)return;let N=D.length;return N===void 0?void 0:Number(N)}function xy(D){if(!Array.isArray(D))return[];let N=new Set;return D.flatMap((z,ee)=>{if(typeof z!=="string"||z==="")return[];if(z.trim()==="")return[Xt(["rules",ee],"must be a non-empty rulebook source string")];let te=xu(z);if(te)return[Xt(["rules",ee],te)];if(N.has(z))return[Xt(["rules",ee],`duplicate rulebook source "${z}"`)];return N.add(z),[]})}function Ry(D){if(D===void 0)return[];if(!jr(D))return[e(["overrides"],"must be an object if provided")];return Object.keys(D).flatMap((N)=>{let z=D[N];if(z==="off")return[];if(!jr(z))return[e(["overrides",N],'must be "off" or an object')];return[..._y(z.reason,["overrides",N,"reason"]),...z.intent===void 0||Ce(z.intent)?[]:[e(["overrides",N,"intent"],we)]]})}function _y(D,N){if(typeof D!=="string")return[e(N,"required non-empty string"),...ku(D,T)?[e(N,`must be at most ${T} characters`)]:[]];if(D==="")return[e(N,"required non-empty string")];return D.length>T?[e(N,`must be at most ${T} characters`)]:[]}function wy(D){if(D===void 0)return[];if(!Array.isArray(D))return[e(["transparent_wrappers"],"must be an array of command strings")];return D.flatMap((N,z)=>{if(typeof N!=="string")return[e(["transparent_wrappers",z],"must be a command string")];return w.test(N)?[]:[e(["transparent_wrappers",z],"must match command pattern")]})}function Py(D){if(!Array.isArray(D))return[];let N=new Set;return D.flatMap((z,ee)=>{if(typeof z!=="string"||!w.test(z))return[];if(N.has(z))return[Xt(["transparent_wrappers",ee],`duplicate command "${z}"`)];if(Le(z))return[Xt(["transparent_wrappers",ee],`reserved command "${z}" cannot be a wrapper`)];return N.add(z),[]})}function Ay(D,N){let z=jr(D)?D.rules:void 0;if(!Array.isArray(z))return new Set;if(N.some((te)=>te.path.length===1&&te.path[0]==="rules"))return new Set;let ee=new Set(N.filter((te)=>te.path[0]==="rules"&&typeof te.path[1]==="number").map((te)=>te.path[1]));return new Set(z.filter((te,he)=>typeof te==="string"&&!ee.has(he)))}function qe(D,N,z){let ee=D.map((je)=>je.path[1]),te=[...new Set(ee.filter((je)=>typeof je==="string"))],he=(je,at)=>[je.path.length===0?-1:N.indexOf(String(je.path[0])),typeof at==="number"?at:te.indexOf(String(at)),z(je)?0:1];return D.map((je,at)=>({issue:je,rank:he(je,ee[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(D,N,z){return[...new Set(D.map((ee)=>{let te=Ea(ee.path);if(ee.kind==="unknownKeys")return`${te?`${te}.`:""}unknown field "${ee.message}"`;if(ee.kind==="key"||ee.kind==="limit"||ee.path.length===0)return ee.message;return`${te}${ee.path.length===1?z:N}${ee.message}`}))]}function Ea(D){return D.map((N,z)=>{if(typeof N==="number")return`[${N}]`;return z===0?String(N):`.${String(N)}`}).join("")}function Ce(D){return ba.includes(D)}function jr(D){return!!D&&typeof D==="object"&&!Array.isArray(D)}function se(D){let N=ky(D);if(N.errors.length>0)throw Error(N.errors.join("; "));return D}var Ty=`required non-empty string up to ${T} characters`,Mu="must be a non-empty array of unique non-empty strings",Iy="required non-empty array of non-empty strings";function ky(D){if(!or(D))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Iu(D))return{errors:[Au],ruleNames:new Set};let N=[...D.rulebook_version===1||D.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ie(Oy(D,D.rulebook_version===2),": ",": ")];return{errors:N.length>Pn.maxValidationErrors?[...N.slice(0,Pn.maxValidationErrors),Tu]:N,ruleNames:new Set(_e(D).map((z)=>z.toLowerCase()))}}function _e(D){let N=or(D)?D.rules:void 0;return(Array.isArray(N)?N:[]).flatMap((z)=>{let ee=or(z)?z.name:void 0;return typeof ee==="string"?[ee]:[]})}function Oy(D,N){return[...typeof D.name==="string"&&l.test(D.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof D.version==="string"&&D.version!==""?[]:[e(["version"],"required non-empty string")],...My(D.allowed_commands),...Dy(D.rules,N),...Gy(D.tests),...Fy(D),...zy(D)]}function My(D){if(!Array.isArray(D))return[e(["allowed_commands"],"required array")];let N=new Set;return[...D.flatMap((z,ee)=>typeof z==="string"&&w.test(z)?[]:[e(["allowed_commands",ee],"must match command pattern")]),...D.flatMap((z,ee)=>{if(typeof z!=="string"||!w.test(z))return[];if(N.has(z))return[Xt(["allowed_commands",ee],`duplicate command "${z}"`)];return N.add(z),[]})]}function Dy(D,N){if(!Array.isArray(D))return[e(["rules"],"required array")];return[...D.flatMap((z,ee)=>{if(!or(z))return[e(["rules",ee],"must be an object")];return N?Ly(z,["rules",ee]):Ny(z,["rules",ee])}),...Te(D)]}function Ny(D,N){return[...Du(D.name,N),...Nu(D.command,N),...D.subcommand===void 0||typeof D.subcommand==="string"&&w.test(D.subcommand)?[]:[e([...N,"subcommand"],"must match command pattern")],...Ti(D.block_args,[...N,"block_args"],"required non-empty array",!1),...Lu(D.reason,N),...Wu(D.intent,N)]}function Ly(D,N){return[...Du(D.name,N),...Nu(D.command,N),...Lu(D.reason,N),...Wu(D.intent,N),...Wy(D.match,[...N,"match"]),...D.subcommand===void 0?[]:[e([...N,"subcommand"],"not supported in rulebook_version 2")],...D.block_args===void 0?[]:[e([...N,"block_args"],"not supported in rulebook_version 2")]]}function Du(D,N){if(typeof D!=="string")return[e([...N,"name"],"required string")];return l.test(D)?[]:[e([...N,"name"],"must match rule name pattern")]}function Nu(D,N){return typeof D==="string"&&w.test(D)?[]:[e([...N,"command"],"required string matching command pattern")]}function Lu(D,N){return typeof D==="string"&&D!==""&&D.length<=T?[]:[e([...N,"reason"],Ty)]}function Wu(D,N){return D===void 0||Ce(D)?[]:[e([...N,"intent"],we)]}function Wy(D,N){if(!or(D))return[e(N,"required object")];return[...Ti(D.command_path,[...N,"command_path"],Iy,!1),...D.any_args===void 0?[]:Ti(D.any_args,[...N,"any_args"],Mu,!0),...D.exclude_args===void 0?[]:Ti(D.exclude_args,[...N,"exclude_args"],Mu,!0)]}function Ti(D,N,z,ee){if(!Array.isArray(D))return[e(N,z)];let te=D.flatMap((he,je)=>{if(typeof he!=="string")return[e([...N,je],"must be a non-empty string")];return he===""?[Xt([...N,je],"must be a non-empty string")]:[]});if(D.some((he)=>typeof he!=="string"))return te;return[...te,...D.length===0?[Xt(N,z)]:[],...ee&&new Set(D).size!==D.length?[Xt(N,"must not contain duplicate values")]:[]]}function Gy(D){if(D===void 0)return[];if(!Array.isArray(D))return[e(["tests"],"must be an array if provided")];return D.flatMap((N,z)=>{if(!or(N))return[e(["tests",z],"must be an object")];return[...typeof N.command==="string"&&N.command.trim()!==""?[]:[e(["tests",z,"command"],"required non-empty string")],...N.expect==="blocked"||N.expect==="allowed"?[]:[e(["tests",z,"expect"],'must be "blocked" or "allowed"')],...N.rule===void 0||typeof N.rule==="string"?[]:[e(["tests",z,"rule"],"must be a string if provided")],...N.expect==="blocked"&&typeof N.rule!=="string"?[Xt(["tests",z,"rule"],"required string for blocked fixtures")]:[]]})}function Fy(D){if(!Array.isArray(D.tests))return[];let N=new Set(_e(D));return[...new Set(D.tests.flatMap((z)=>or(z)&&z.expect==="blocked"&&typeof z.rule==="string"?[z.rule]:[]))].filter((z)=>!N.has(z)).map((z)=>Xt(["tests"],`blocked fixture references unknown rule "${z}"`))}function zy(D){if(!Array.isArray(D.allowed_commands)||!Array.isArray(D.rules))return[];let N=new Set(D.allowed_commands.filter((z)=>typeof z==="string"));return D.rules.flatMap((z,ee)=>{let te=or(z)?z.command:void 0;if(typeof te!=="string"||N.has(te))return[];return[Xt(["rules",ee,"command"],`"${te}" must be listed in allowed_commands`)]})}function or(D){return!!D&&typeof D==="object"&&!Array.isArray(D)}function Y(D,N){let z=J(D,N),ee;try{ee=hu(z.userConfigTarget,z.projectConfigTarget)}catch(mt){if(mt instanceof r)return Yy(z,mt.message);throw mt}let te=m(z.userConfigTarget),he=ee?{config:null,errors:[]}:m(z.projectConfigTarget),je=Fu(z.userConfigPath,te.errors),at=Fu(z.projectConfigPath,he.errors),lt=new Set,ct=te.config?xa(te.config,Er(z.userConfigPath),"user",z.userScope,lt):zu(),dt=he.config?xa(he.config,Er(z.projectConfigPath),"project",z.projectScope,lt):zu(),ft=te.config?.overrides??{},ut=he.config?.overrides??{};return{rules:[...Gu(ct.rules,ft),...Gu(dt.rules,ut)],transparent_wrappers:Ky(te.config,he.config),rulebooks:[...ct.rulebooks,...dt.rulebooks],errors:[...je,...at,...ct.errors,...dt.errors],warnings:[...ct.warnings,...dt.warnings,...ct.canValidateOverrides?Ra(ft,ct.knownRuleIds,z.userConfigPath):[],...ct.canValidateOverrides?qy(ut,ct.knownRuleIds,z.projectConfigPath):[],...dt.canValidateOverrides?Ra(ut,dt.knownRuleIds,z.projectConfigPath):[]],userConfig:te.config??void 0,projectConfig:he.config??void 0,...z}}function U(D,N){let z=By(D,N);if(!z)return[];return[...z.scope.errors,...z.scope.warnings,...$y(z.config,z.scope,D)]}function By(D,N){let z=N??v(Er(Er(D)),"rules policy"),ee=m(i(z,D)).config;if(!ee)return null;return{config:ee,scope:xa(ee,Er(D),"project",z)}}function $y(D,N,z){return N.canValidateOverrides?Ra(D.overrides??{},N.knownRuleIds,z):[]}function xa(D,N,z,ee=v(Er(Er(N)),z==="user"?"user policy":"project policy"),te=new Set){let he=[],je=[],at=D.rules.flatMap((ct)=>{let dt=Hy(ct,N,ee);if(dt.errors.length>0||!dt.rulebook)return he.push(...dt.errors),[];let ft=dt.rulebook;if(te.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 te.add(ft.name),[{rules:Uy(ft),rulebook:{source:z,spec:ct,name:ft.name,version:ft.version,rules:ft.rules.map((ut)=>`${ft.name}/${ut.name}`)}}]}),lt=at.flatMap((ct)=>ct.rules);return{rules:lt,rulebooks:at.map((ct)=>ct.rulebook),knownRuleIds:new Set(lt.map((ct)=>ct.name)),errors:he,warnings:je,canValidateOverrides:he.length===0}}function Uy(D){if(D.rulebook_version===2)return D.rules.map((N)=>({name:`${D.name}/${N.name}`,command:N.command,block_args:[],match:N.match,reason:N.reason,intent:N.intent}));return D.rules.map((N)=>({...N,name:`${D.name}/${N.name}`,match:void 0}))}function Hy(D,N,z){let ee=Pe(D),te=O(N,ee),he=Vy(te,z);if("error"in he)return{rulebook:null,errors:[he.error]};if(he.content===null)return{rulebook:null,errors:[`missing rulebook file ${te} for ${D}; ${jy(D)}`]};let je=me(he.content);if("problem"in je)return{rulebook:null,errors:[`invalid rulebook ${te}: ${je.problem}; fix that file`]};if(je.rulebook.name!==ee)return{rulebook:null,errors:[`rulebook name "${je.rulebook.name}" in ${te} must match source "${D}"; fix that file`]};return{rulebook:je.rulebook,errors:[]}}function Pe(D){return S(D)?I(D).name:D}function jy(D){return S(D)?`run ${wu} to vendor ${D}`:"create that file or remove that source from the rules config"}function Vy(D,N){try{return{content:n(i(N,D))}}catch(z){if(z instanceof r)return{error:z.message};throw z}}function me(D){let N;try{N=JSON.parse(D)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:se(N)}}catch(z){return{problem:z instanceof Error?z.message:"invalid rulebook"}}}function Ky(D,N){return[...new Set([...D?.transparent_wrappers??[],...N?.transparent_wrappers??[]])]}function Gu(D,N){return D.flatMap((z)=>{let ee=N[z.name];if(ee==="off")return[];if(ee&&typeof ee==="object")return[{...z,intent:ee.intent??z.intent,reason:ee.reason}];return[z]})}function Ra(D,N,z){return Object.keys(D).filter((ee)=>!N.has(ee)).map((ee)=>`unknown override key "${ee}" in ${z}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function qy(D,N,z){return Object.keys(D).filter((ee)=>N.has(ee)).map((ee)=>`project override cannot target user-scoped rule "${ee}" in ${z}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function Fu(D,N){return N.map((z)=>z.startsWith("Unable to access ")?z:`${D}: ${z}`)}function Yy(D,N){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[N],warnings:[],userConfigPath:D.userConfigPath,projectConfigPath:D.projectConfigPath}}function zu(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as sb,readFileSync as ab}from"node:fs";var Bu=[{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"}],_a=new Set(Bu.map((D)=>D.id)),G=Bu,Zy=new Map(G.map((D)=>[D.id,D.intent]));function Ct(D,N){return{id:D,reason:N,intent:Zy.get(D)??"manual_only"}}var wa=[{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"}],Ii={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Xy=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Jy=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Pa=[{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"]},...Jy.flatMap((D)=>Xy.map((N)=>({id:["secret.home",D.idSlug,N.slice(1)].join("."),category:"Home path",label:[D.label,N].join(""),description:["Blocks home ",D.label,N," credential backup files."].join(""),suffixParts:[...D.directoryParts,[D.basename,N].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 ki=[{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"]}],$u=[{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"}],Qy=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Aa=$u.map((D)=>({id:`secret.variant.${D.slug}.separator`,category:"Variant",label:`${D.label}-* / ${D.label}_*`,description:`Blocks ${D.label} variants with dash or underscore suffixes.`,prefix:D.prefix})),Ta=$u.flatMap((D)=>Qy.map((N)=>({id:`secret.variant.${D.slug}.${N.slice(1)}`,category:"Variant",label:`${D.label}${N}`,description:`Blocks ${D.label}${N} private credential variants.`,prefix:D.prefix,suffix:N}))),To={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)$/},Ia=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((D)=>({id:`secret.ext.${D}`,category:"Extension",label:`.${D}`,description:`Blocks files with the .${D} extension.`,extension:D})),ka=[{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=[...wa,Ii,...Pa,...Aa,...Ta,To,...Ia,...ka,...ki].map((D)=>({id:D.id,category:D.category,label:D.label,...D.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in D?{paths:D.paths}:{description:D.description}})),Oi=new Set(ki.flatMap((D)=>D.category==="Coding CLI config"?[D.id]:[])),Oa=new Set(Ke.map((D)=>D.id));import{isAbsolute as Ma,join as eb,normalize as tb,sep as Mi}from"node:path";var Di=process.platform==="win32",Uu=/[*?]/;function Da(D){let N=D.trim(),z=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(Di?N.replaceAll("\\","/"):N);if(!z)return null;let ee=z[1]??"",te=z[2]??"";if(Uu.test(ee)||te==="."||te==="..")return null;return{root:ee||"/",name:te}}function Io(D,N){if(D==="~")return N;if(D.startsWith("~/"))return`${N}${D.slice(1)}`;return D}function Na(D,N){if(typeof D!=="string"||D.trim()==="")return"must be a non-empty path string";let z=Io(D.trim(),N);if(!Ma(z))return"must be an absolute path or start with ~/";return ko(z,N)}function La(D,N){let z=Hu(D,N);if(z===null)return"must be a non-empty path string";if(!Ma(z))return null;if(ko(z,N)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var nb="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",rb="cannot cover the guard's own configuration";function Hu(D,N){if(typeof D!=="string"||D.trim()==="")return null;let z=D.trim(),ee=Di?z.replaceAll("\\","/"):z;return Io(ee.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),N)}function Wa(D,N){let z=Hu(D,N);if(z===null)return"must be a non-empty path string";let ee=Da(z)?.root??z;if(Uu.test(ee))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Ma(ee))return null;if(ko(ee,N)!==null)return nb;return ob(ee,N)?rb:null}function ob(D,N){let z=Ni(D),ee=Ni(eb(N,".cc-safety-net"));return z===ee||z.startsWith(`${ee}${Mi}`)}function ko(D,N){let z=Ni(D),ee=Ni(N);if(z===ee)return"cannot be the home directory";let te=z.endsWith(Mi)?z:`${z}${Mi}`;if(ee.startsWith(te))return"cannot contain the home directory";return null}function Ni(D){let N=tb(D);if(Di)N=N.replace(/\//g,"\\").toLowerCase();if(N.length>(Di?3:1)&&N.endsWith(Mi))N=N.slice(0,-1);return N}var ju=30,Li=1,Wi=365;function Vu(D){if(typeof D!=="number"||!Number.isInteger(D))return 30;if(D<1)return 1;return D>365?365:D}var Ku=new Set(G.filter((D)=>D.catastrophic).map((D)=>D.id));function Pt(D,N){if(!D)return null;if(Ku.has(D.id))return D;if(N?.destructiveCommandProtectionEnabled===!1)return null;let z=N?.effectiveDestructiveCommandRules[D.id];return z&&!z.enabled?null:D}function Jt(D,N,z){if(Ku.has(N))return!0;if(D?.destructiveCommandProtectionEnabled===!1)return!1;return D?.effectiveDestructiveCommandRules[N]?.enabled??z}function H(D,N){return Object.freeze(Object.fromEntries(G.map((z)=>{let ee=z.activationCapability?N[z.activationCapability]:void 0,te=ee?.enabled??!0,he=D.destructiveCommandRuleOverrides[z.id],je=z.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...he?{override:he}:{}}:D.destructiveCommandProtectionEnabled?he?{enabled:he==="on",inheritedEnabled:te,changesInherited:he==="on"!==te,source:"rule_override",...z.activationCapability?{activationCapability:z.activationCapability}:{},override:he}:{enabled:te,inheritedEnabled:te,changesInherited:!1,source:ee?.source??"built_in_default",...z.activationCapability?{activationCapability:z.activationCapability}:{}}:{enabled:!1,inheritedEnabled:te,changesInherited:!1,source:"master_disabled",...z.activationCapability?{activationCapability:z.activationCapability}:{},...he?{override:he}:{}};return[z.id,Object.freeze(je)]})))}function qu(D,N){return Object.freeze({...D,effectiveDestructiveCommandRules:H(D,N)})}var Yu={standard:0,strict:1,paranoid:2};function Z(D,N){return{policy:{version:1,safety:{level:N.safety?.level??D.safety.level,overrides:{...D.safety.overrides,...N.safety?.overrides}},workflow:{worktree_mode:N.workflow?.worktree_mode??D.workflow.worktree_mode},destructive_command_protection:{enabled:N.destructive_command_protection?.enabled??D.destructive_command_protection.enabled,overrides:{...D.destructive_command_protection.overrides,...N.destructive_command_protection?.overrides},allow_paths:Ga(D.destructive_command_protection.allow_paths,N.destructive_command_protection?.allow_paths)},secret_protection:{enabled:N.secret_protection?.enabled??D.secret_protection.enabled,overrides:{...D.secret_protection.overrides,...N.secret_protection?.overrides},deny_paths:Ga(D.secret_protection.deny_paths,N.secret_protection?.deny_paths),allow_paths:Ga(D.secret_protection.allow_paths,N.secret_protection?.allow_paths)},audit:D.audit},weakenings:ib(D,N)}}function Ga(D,N){return[...new Set([...D,...N??[]])]}function ib(D,N){let z=N.safety?.level,ee=Ci[D.safety.level];return[...z&&Yu[z]<Yu[D.safety.level]?[`project policy lowers level: ${D.safety.level} -> ${z}`]:[],...Ur.flatMap((te)=>N.safety?.overrides?.[te]===!1&&(D.safety.overrides[te]??ee[te])?[`project policy disables ${te}`]:[]),...N.workflow?.worktree_mode===!0&&!D.workflow.worktree_mode?["project policy enables worktree mode relaxations"]:[],...N.destructive_command_protection?.enabled===!1&&D.destructive_command_protection.enabled?["project policy disables destructive command protection"]:[],...N.secret_protection?.enabled===!1&&D.secret_protection.enabled?["project policy disables secret protection"]:[],...Zu(N.destructive_command_protection?.overrides,(te)=>D.destructive_command_protection.enabled&&D.destructive_command_protection.overrides[te]!=="off"),...Zu(N.secret_protection?.overrides,(te)=>D.secret_protection.enabled&&(D.secret_protection.overrides[te]==="on"?!0:D.secret_protection.overrides[te]!=="off"&&!Oi.has(te))),...D.destructive_command_protection.enabled?Xu(D.destructive_command_protection.allow_paths,N.destructive_command_protection?.allow_paths).map((te)=>`project policy adds destructive allow path: ${te}`):[],...D.secret_protection.enabled?Xu(D.secret_protection.allow_paths,N.secret_protection?.allow_paths).map((te)=>`project policy adds secret allow path: ${te}`):[]]}function Zu(D,N){return Object.entries(D??{}).flatMap(([z,ee])=>ee==="off"&&N(z)?[`project policy disables rule ${z}`]:[])}function Xu(D,N){return(N??[]).filter((z)=>!D.includes(z))}var Ba=new Set(["standard","strict","paranoid"]),X={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:ju}};function td(D,N){let z=mb(u(D,N),D.home),ee=Ie(b(N.cwd),D.home),te=ae(ee.parsed,D.home),he=Object.keys(te.policy).length>0?Z(z.gui??X,te.policy):void 0,je=[...z.errors,...ee.errors,...te.diagnostics],at=(z.fallback==="defaults"&&he?"salvaged":z.fallback)??(z.gui?void 0:ee.fallback)??(je.length>0?"salvaged":void 0),lt=te.policy.safety?.level?"project":z.levelPresent?"user":"default";return{...he?za(he.policy):z.policy,errors:je,...at?{fallback:at}:{},...ee.exists?{policyScopes:{levelScope:lt,weakenings:he?.weakenings??[]}}:{}}}var lb="project policy audit settings are ignored; audit is user scope only";function ae(D,N){if(!bn(D))return{policy:{},diagnostics:[]};let z=bn(D.safety)?D.safety:{},ee=bn(D.workflow)?D.workflow:{},te=bn(D.destructive_command_protection)?D.destructive_command_protection:{},he=bn(D.secret_protection)?D.secret_protection:{},je={...Ba.has(z.level)?{level:z.level}:{},...bn(z.overrides)?Ju({overrides:nd(z.overrides,Ur,["safety","overrides"],xr)}):{}},at={...typeof te.enabled==="boolean"?{enabled:te.enabled}:{},...te.overrides!==void 0?{overrides:Gi(te.overrides,_a,od,xr)}:{},...te.allow_paths!==void 0?{allow_paths:Kr(te.allow_paths,Na,N,["destructive_command_protection","allow_paths"],xr)}:{}},lt={...typeof he.enabled==="boolean"?{enabled:he.enabled}:{},...he.overrides!==void 0?{overrides:Gi(he.overrides,Oa,id,xr)}:{},...he.deny_paths!==void 0?{deny_paths:Kr(he.deny_paths,La,N,["secret_protection","deny_paths"],xr)}:{},...he.allow_paths!==void 0?{allow_paths:Kr(he.allow_paths,Wa,N,["secret_protection","allow_paths"],xr)}:{}};return{policy:Ju({safety:je,workflow:typeof ee.worktree_mode==="boolean"?{worktree_mode:ee.worktree_mode}:{},destructive_command_protection:at,secret_protection:lt}),diagnostics:D.audit===void 0?[]:[lb]}}function nd(D,N,z,ee){return Object.fromEntries(N.flatMap((te)=>{let he=D[te];if(typeof he==="boolean")return[[te,he]];if(he!==void 0)ee(e([...z,te],$a));return[]}))}function Ju(D){return Object.fromEntries(Object.entries(D).flatMap((N)=>Object.keys(N[1]).length>0?[N]:[]))}var xr=()=>{return},$a="must be a boolean",Ua="must be an object if provided",rd=`must be an integer between ${Li} and ${Wi}`,od={path:["destructive_command_protection","overrides"],label:"destructive command"},id={path:["secret_protection","overrides"],label:"secret protection"},Je=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Ye(D,N){let z=[];return{policy:sd(D,N,(te)=>{z.push(te)}),issues:z}}function C(D,N){return sd(D,N,xr)}function sd(D,N,z){if(!bn(D))return z(e([],"Config must be an object")),W();if(D.version!==1)z(e(["version"],"must be 1"));let ee=Vr(D.safety,["safety"],["level","overrides"],z),te=Vr(ee.overrides,["safety","overrides"],Ur,z),he=Vr(D.workflow,["workflow"],["worktree_mode"],z),je=Vr(D.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],z),at=Vr(D.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],z),lt=Vr(D.audit,["audit"],["retention_days"],z);return ad(D,Je,[],z),{version:1,safety:{level:cb(ee.level,z),overrides:nd(te,Ur,["safety","overrides"],z)},workflow:{worktree_mode:Fa(he.worktree_mode,["workflow","worktree_mode"],!1,z)},destructive_command_protection:{enabled:Fa(je.enabled,["destructive_command_protection","enabled"],!0,z),overrides:Gi(je.overrides,_a,od,z),allow_paths:Kr(je.allow_paths,Na,N,["destructive_command_protection","allow_paths"],z)},secret_protection:{enabled:Fa(at.enabled,["secret_protection","enabled"],!0,z),overrides:Gi(at.overrides,Oa,id,z),deny_paths:Kr(at.deny_paths,La,N,["secret_protection","deny_paths"],z),allow_paths:Kr(at.allow_paths,Wa,N,["secret_protection","allow_paths"],z)},audit:{retention_days:ub(lt.retention_days,z)}}}function Vr(D,N,z,ee){if(D===void 0)return{};if(!bn(D))return ee(e(N,Ua)),{};return ad(D,z,N,ee),D}function ad(D,N,z,ee){for(let te of Object.keys(D).filter((he)=>!N.includes(he)))ee({path:z,message:te,kind:"unknownKeys"})}function cb(D,N){if(D===void 0)return"standard";if(Ba.has(D))return D;return N(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Fa(D,N,z,ee){if(typeof D==="boolean")return D;if(D!==void 0)ee(e(N,$a));return z}function ub(D,N){if(!(D===void 0||typeof D==="number"&&Number.isInteger(D)&&D>=Li&&D<=Wi))N(e(["audit","retention_days"],rd));return Vu(D)}function Gi(D,N,z,ee){if(D===void 0)return{};if(!bn(D))return ee(e(z.path,Ua)),{};return Object.fromEntries(Object.entries(D).flatMap(([te,he])=>{if(!N.has(te))return ee({path:[...z.path,te],message:`unknown ${z.label} rule id "${te}"`,kind:"key"}),[];if(he==="on"||he==="off")return[[te,he]];return ee(e([...z.path,te],'must be "on" or "off"')),[]}))}function Kr(D,N,z,ee,te){if(D===void 0)return[];if(!Array.isArray(D))return te(e(ee,"must be an array of paths")),[];return D.flatMap((he,je)=>{let at=N(he,z);if(at===null)return[he];return te(typeof he==="string"?Xt([...ee,je],at):e([...ee,je],at)),[]})}function bn(D){return!!D&&typeof D==="object"&&!Array.isArray(D)}function W(){return structuredClone(X)}function Ae(D,N){let z=R({safety:De(D.safety)},N),ee=H({destructiveCommandProtectionEnabled:D.destructive_command_protection.enabled,destructiveCommandRuleOverrides:D.destructive_command_protection.overrides},z.capabilities),te=Object.values(ee),he=te.filter((je)=>je.source!=="catastrophic");return{selectedPreset:D.safety.level,effectiveLevel:z.effectiveLevel,capabilities:z.capabilities,rules:ee,counts:{enabled:he.filter((je)=>je.enabled).length,disabled:he.filter((je)=>!je.enabled).length,effectiveCustomizations:te.filter((je)=>je.changesInherited).length}}}function Ie(D,N){if(!sb(D))return{exists:!1,policy:W(),errors:[]};try{let z=ab(D,"utf-8");if(!z.trim())return{exists:!0,policy:W(),errors:[`${D}: Config file is empty`],fallback:"defaults"};let ee=JSON.parse(z),te=Ye(ee,N);if(te.issues.length===0)return{exists:!0,parsed:ee,policy:te.policy,errors:[]};return{exists:!0,parsed:ee,policy:te.policy,errors:te.issues.map((he)=>`${D}: ${fb(he)}`),fallback:bn(ee)?"salvaged":"defaults"}}catch(z){let ee=z instanceof Error?z.message:String(z);return{exists:!0,policy:W(),errors:[`${D}: ${z instanceof SyntaxError?"Invalid JSON":ee}`],fallback:"defaults"}}}var db=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[Ua,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[$a,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[rd,`not an integer between ${Li} and ${Wi}`]]);function fb(D){let N=Ea(D.path);if(D.kind==="unknownKeys")return`${N===""?"":`${N}.`}${D.message}: unknown field`;if(D.kind==="key")return`${N}: unknown rule id`;let z=db.get(D.message)??D.message;return N===""?z:`${N}: ${z}`}function mb(D,N){let z=Ie(D,N);if(!z.exists){let ee=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!bn(ee))return{policy:ed(),errors:[]};let te=C(ee,N);return{policy:za(te),gui:te,errors:[],levelPresent:Qu(ee)}}if(z.parsed===void 0)return{policy:ed(),errors:z.errors,...z.fallback?{fallback:z.fallback}:{}};return{policy:za(z.policy),gui:z.policy,errors:z.errors,...z.fallback?{fallback:z.fallback}:{},levelPresent:Qu(z.parsed)}}function Qu(D){let N=bn(D)&&bn(D.safety)?D.safety:{};return Ba.has(N.level)}function Oe(D){let N=Object.entries(D),z=new Set(N.flatMap(([ee,te])=>te==="on"?[ee]:[]));return[...new Set([...[...Oi].filter((ee)=>!z.has(ee)),...N.flatMap(([ee,te])=>te==="off"?[ee]:[])])]}function ed(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Oe({}),denyPaths:[],allowPaths:[]}}}function za(D){return{safety:De(D.safety),worktreeMode:D.workflow.worktree_mode,destructiveCommandProtectionEnabled:D.destructive_command_protection.enabled,destructiveCommandRuleOverrides:D.destructive_command_protection.overrides,destructiveCommandAllowPaths:D.destructive_command_protection.allow_paths,secretProtection:{enabled:D.secret_protection.enabled,disabledRules:Oe(D.secret_protection.overrides),denyPaths:D.secret_protection.deny_paths,allowPaths:D.secret_protection.allow_paths}}}function De(D){let N={...D.overrides.fail_closed!==void 0?{failClosed:D.overrides.fail_closed}:{},...D.overrides.paranoid_rm!==void 0?{paranoidRm:D.overrides.paranoid_rm}:{},...D.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:D.overrides.paranoid_interpreters}:{}};return{level:D.level,...Object.keys(N).length>0?{overrides:N}:{}}}function E(D,N){let z=Y(D,N),ee=td(D,N),te={rules:z.rules,transparentWrappers:z.transparent_wrappers,safety:ee.safety,worktreeMode:ee.worktreeMode,destructiveCommandProtectionEnabled:ee.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:ee.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:ee.destructiveCommandAllowPaths,secretProtection:{enabled:ee.secretProtection.enabled??!0,disabledRules:ee.secretProtection.disabledRules??[],denyPaths:ee.secretProtection.denyPaths,allowPaths:ee.secretProtection.allowPaths??[]}},he={...z.userConfig?.overrides,...z.projectConfig?.overrides},je=Object.freeze(Object.fromEntries(te.rules.map((at)=>{let lt=z.rulebooks.find((dt)=>dt.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}),...yb(lt.spec)?{source:lt.spec}:{}}:{},...ct&&typeof ct==="object"?{override:Object.freeze({type:"reason",reason:ct.reason})}:{}})]})));return Ee(te,pb(z,ee),je,ee.policyScopes)}function Ne(D){if(D.state==="ready")return{state:D.state};return{state:D.state,reason:D.reason}}function pb(D,N){let z=hb(N);if(D.errors.length===0&&D.warnings.length===0&&!z)return;return{diagnostics:[...D.errors,...D.warnings,...N.errors],reason:bb(D.errors.length>0?gb(D.errors):void 0,D.warnings.length>0?ja(D.warnings.join("; ")):void 0,z)}}function gb(D){return`${ja(D.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function hb(D){if(D.errors.length===0)return;let N=D.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${D.errors.join("; ")}. Enforcing ${N}; the invalid values are not active. Fix the policy file manually`}function yb(D){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(D)}function Ee(D,N,z=Object.freeze({}),ee){let te=Ha(structuredClone(D)),he=ee?{policyScopes:Ha(structuredClone(ee))}:{};if(!N)return Object.freeze({state:"ready",policy:te,diagnostics:Object.freeze([]),ruleMetadata:z,...he});return Object.freeze({state:"degraded",policy:te,diagnostics:Object.freeze([...N.diagnostics]),reason:N.reason,ruleMetadata:z,...he})}function Ha(D){if(typeof D!=="object"||D===null)return D;for(let N of Object.values(D))Ha(N);return Object.freeze(D)}function bb(...D){return ja(D.filter((N)=>!!N).join("; "))}function ja(D){return/[.!?]$/.test(D)?D:`${D}.`}function Fe(D){let N=D.effectiveCapabilities,z=D.strict??N.fail_closed.enabled,ee=D.paranoidRm??N.paranoid_rm.enabled,te=D.paranoidInterpreters??N.paranoid_interpreters.enabled,he={fail_closed:Va(N.fail_closed,D.strict,"strict"),paranoid_rm:Va(N.paranoid_rm,D.paranoidRm,"paranoidRm"),paranoid_interpreters:Va(N.paranoid_interpreters,D.paranoidInterpreters,"paranoidInterpreters")};return{policy:qu(D.policySnapshot.policy,he),effectiveCapabilities:he,effectiveLevel:ca({failClosed:z,paranoidRm:ee,paranoidInterpreters:te}),strict:z,paranoidRm:ee,paranoidInterpreters:te,worktreeMode:D.worktreeMode??!1}}function Va(D,N,z){if(N===void 0||N===D.enabled)return D;return{enabled:N,source:"capability_override",sources:[...D.sources,`analysis options.${z}`]}}import{dirname as C_,isAbsolute as v_,join as E_,parse as x_,resolve as R_,sep as __}from"node:path";function Oo(D,N){if(D!=="powershell")return N[0]?.provenance==="command-substitution";let z=N[0]?.text==="&"||N[0]?.text==="."?1:0,ee=N[z]?.provenance;return ee!==void 0&&ee!=="literal"}var Sb=/^[A-Za-z_][A-Za-z0-9_]*=/;function Fi(D,N){return D?.provenance==="literal"&&!D.quoted&&D.raw===N&&D.text===N}function Mo(D){let N=Fi(D.words[0],"time")?1:0,z=N===1&&Fi(D.words[N],"-p")?N+1:N,ee=N===1&&Fi(D.words[z],"--")?z+1:z,te=Fi(D.words[ee],"!")?ee+1:ee,he=D.words.slice(te).find((je)=>!Sb.test(je.text));return he?.provenance==="literal"?he.text:void 0}var ir=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function zi(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Cb(D){return Object.freeze({...D,span:Object.freeze(D.span),words:Object.freeze(D.words),redirections:Object.freeze(D.redirections.map((N)=>Object.freeze({...N,span:Object.freeze(N.span),...N.heredoc?{heredoc:Object.freeze({...N.heredoc,bodySpan:Object.freeze(N.heredoc.bodySpan),terminatorSpan:Object.freeze(N.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(D.nested.map((N)=>ln(N)))})}function Bi(D,N,z){D.push(z),N.reset()}function $i(D){let N=[];return{parts:N,push:(z,ee,te)=>{if(ee<=z)return;N.push({raw:D.slice(z,ee),span:{start:z,end:ee},provenance:te})}}}function Ka(D){let N=D.parts??[{raw:D.raw,span:D.span,provenance:D.provenance}];return Object.freeze({kind:"word",...D,span:Object.freeze(D.span),parts:Object.freeze(N.map((z)=>Object.freeze({...z,span:Object.freeze(z.span)})))})}function qr(D,N,z,ee,te,he,je){return Ka({text:ee,raw:D.slice(N,z),span:{start:N,end:z},provenance:te,quoted:he,...je?{parts:je}:{}})}function ln(D){return Object.freeze({...D,span:Object.freeze(D.span),issues:Object.freeze(D.issues.map((N)=>Object.freeze({...N}))),nodes:Object.freeze(D.nodes.map((N)=>{if(N.kind==="command")return Cb(N);if(N.kind==="group"||N.kind==="function")return Object.freeze({...N,span:Object.freeze(N.span),body:ln(N.body)});return Object.freeze({...N,span:Object.freeze(N.span)})}))})}function qa(D,N,z){if(N>=z||cd(D[N]??""))return null;let ee="",te=!1,he=!1,je=N;while(je<z&&!cd(D[je]??"")){let at=D[je]??"";if(at==="'"){te=!0;let lt=ld(D,je+1,z,"'");ee+=lt.text,he||=!lt.closed,je=lt.next;continue}if(at==='"'){te=!0;let lt=ld(D,je+1,z,'"');ee+=lt.text,he||=!lt.closed,je=lt.next;continue}if(at==="\\"){te=!0;let lt=D[je+1];if(!lt||lt===`
|
|
6
|
+
`||je==="\r")N+=je,ee=!1,z.escaped=!1;continue}if(je==="#"&&!z.inSingle&&!z.inDouble&&te){ee=!0;continue}if(N+=je,!z.inSingle&&!z.inDouble&&!z.escaped)te=/[\s;&|()<>]/.test(je);Ao(je,z)}return N}var va=new Set(["rm","find","xargs","parallel"]),py=new Set(["git","busybox",...va,...Ut,...Pu,...En]),gy=new Set(["python","node","ruby","perl"]);function Le(D){let N=It(D);return py.has(N)||An(N)}function An(D){return gy.has(hy(D))}function hy(D){let N=At(D).toLowerCase();return wi.test(N)?"python":N}var it={version:1,rules:[],overrides:{},transparent_wrappers:[]};function m(D){try{let N=n(yy(D));if(N===null)return{config:null,errors:[]};if(!N.trim())return{config:null,errors:["Config file is empty"]};let z=JSON.parse(N),ee=Ve(z);if(ee.errors.length>0)return{config:null,errors:ee.errors};return{config:{version:1,rules:z.rules??[],overrides:z.overrides??{},transparent_wrappers:z.transparent_wrappers??[]},errors:[]}}catch(N){if(N instanceof r)return{config:null,errors:[N.message]};let z=N instanceof Error?N.message:String(N);return{config:null,errors:[N instanceof SyntaxError?"Invalid JSON":z]}}}function yy(D){return typeof D==="string"?re(D):D}var e=(D,N)=>({path:D,message:N,kind:"typed"}),Xt=(D,N)=>({path:D,message:N,kind:"custom"});function Te(D){let N=new Set;return D.flatMap((z,ee)=>{let te=jr(z)?z.name:void 0;if(typeof te!=="string")return[];if(N.has(te.toLowerCase()))return[Xt(["rules",ee,"name"],`duplicate rule name "${te}"`)];return N.add(te.toLowerCase()),[]})}var we=`must be one of ${ba.join(", ")}`,by=/^[^/]+\/[^/]+$/,Sy=["version","rules","overrides","transparent_wrappers"];function Ve(D){let N=Cy(D);return{errors:ie(qe(N,Sy,(z)=>z.kind==="custom"),": "," "),sources:Ay(D,N)}}function Cy(D){if(!jr(D))return[e([],"Config must be an object")];let N=Array.isArray(D.rules)&&D.rules.length>pe;return[...D.version===1?[]:[e(["version"],"must be 1")],...vy(D.rules,N),...Ry(D.overrides),...wy(D.transparent_wrappers),...N?[]:xy(D.rules),...jr(D.overrides)?Object.keys(D.overrides).filter((z)=>!by.test(z)).map((z)=>Xt(["overrides",z],"must use <rulebook-name>/<rule-name>")):[],...Py(D.transparent_wrappers)]}function vy(D,N){if(D===void 0)return[];if(!Array.isArray(D))return[e(["rules"],"must be an array of rulebook source strings"),...ku(D,pe)?[e(["rules"],fe)]:[]];if(N)return[{path:["rules"],message:fe,kind:"limit"}];return D.flatMap((z,ee)=>{if(typeof z!=="string")return[e(["rules",ee],"must be a rulebook source string"),...Ey(z,1)?[e(["rules",ee],"must be a non-empty rulebook source string")]:[]];return z===""?[e(["rules",ee],"must be a non-empty rulebook source string")]:[]})}function ku(D,N){let z=Ou(D);return z!==void 0&&!(z<=N)}function Ey(D,N){let z=Ou(D);return z!==void 0&&!(z>=N)}function Ou(D){if(D===null||D===void 0)return;let N=D.length;return N===void 0?void 0:Number(N)}function xy(D){if(!Array.isArray(D))return[];let N=new Set;return D.flatMap((z,ee)=>{if(typeof z!=="string"||z==="")return[];if(z.trim()==="")return[Xt(["rules",ee],"must be a non-empty rulebook source string")];let te=xu(z);if(te)return[Xt(["rules",ee],te)];if(N.has(z))return[Xt(["rules",ee],`duplicate rulebook source "${z}"`)];return N.add(z),[]})}function Ry(D){if(D===void 0)return[];if(!jr(D))return[e(["overrides"],"must be an object if provided")];return Object.keys(D).flatMap((N)=>{let z=D[N];if(z==="off")return[];if(!jr(z))return[e(["overrides",N],'must be "off" or an object')];return[..._y(z.reason,["overrides",N,"reason"]),...z.intent===void 0||Ce(z.intent)?[]:[e(["overrides",N,"intent"],we)]]})}function _y(D,N){if(typeof D!=="string")return[e(N,"required non-empty string"),...ku(D,T)?[e(N,`must be at most ${T} characters`)]:[]];if(D==="")return[e(N,"required non-empty string")];return D.length>T?[e(N,`must be at most ${T} characters`)]:[]}function wy(D){if(D===void 0)return[];if(!Array.isArray(D))return[e(["transparent_wrappers"],"must be an array of command strings")];return D.flatMap((N,z)=>{if(typeof N!=="string")return[e(["transparent_wrappers",z],"must be a command string")];return w.test(N)?[]:[e(["transparent_wrappers",z],"must match command pattern")]})}function Py(D){if(!Array.isArray(D))return[];let N=new Set;return D.flatMap((z,ee)=>{if(typeof z!=="string"||!w.test(z))return[];if(N.has(z))return[Xt(["transparent_wrappers",ee],`duplicate command "${z}"`)];if(Le(z))return[Xt(["transparent_wrappers",ee],`reserved command "${z}" cannot be a wrapper`)];return N.add(z),[]})}function Ay(D,N){let z=jr(D)?D.rules:void 0;if(!Array.isArray(z))return new Set;if(N.some((te)=>te.path.length===1&&te.path[0]==="rules"))return new Set;let ee=new Set(N.filter((te)=>te.path[0]==="rules"&&typeof te.path[1]==="number").map((te)=>te.path[1]));return new Set(z.filter((te,he)=>typeof te==="string"&&!ee.has(he)))}function qe(D,N,z){let ee=D.map((je)=>je.path[1]),te=[...new Set(ee.filter((je)=>typeof je==="string"))],he=(je,at)=>[je.path.length===0?-1:N.indexOf(String(je.path[0])),typeof at==="number"?at:te.indexOf(String(at)),z(je)?0:1];return D.map((je,at)=>({issue:je,rank:he(je,ee[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(D,N,z){return[...new Set(D.map((ee)=>{let te=Ea(ee.path);if(ee.kind==="unknownKeys")return`${te?`${te}.`:""}unknown field "${ee.message}"`;if(ee.kind==="key"||ee.kind==="limit"||ee.path.length===0)return ee.message;return`${te}${ee.path.length===1?z:N}${ee.message}`}))]}function Ea(D){return D.map((N,z)=>{if(typeof N==="number")return`[${N}]`;return z===0?String(N):`.${String(N)}`}).join("")}function Ce(D){return ba.includes(D)}function jr(D){return!!D&&typeof D==="object"&&!Array.isArray(D)}function se(D){let N=ky(D);if(N.errors.length>0)throw Error(N.errors.join("; "));return D}var Ty=`required non-empty string up to ${T} characters`,Mu="must be a non-empty array of unique non-empty strings",Iy="required non-empty array of non-empty strings";function ky(D){if(!or(D))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Iu(D))return{errors:[Au],ruleNames:new Set};let N=[...D.rulebook_version===1||D.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ie(Oy(D,D.rulebook_version===2),": ",": ")];return{errors:N.length>Pn.maxValidationErrors?[...N.slice(0,Pn.maxValidationErrors),Tu]:N,ruleNames:new Set(_e(D).map((z)=>z.toLowerCase()))}}function _e(D){let N=or(D)?D.rules:void 0;return(Array.isArray(N)?N:[]).flatMap((z)=>{let ee=or(z)?z.name:void 0;return typeof ee==="string"?[ee]:[]})}function Oy(D,N){return[...typeof D.name==="string"&&l.test(D.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof D.version==="string"&&D.version!==""?[]:[e(["version"],"required non-empty string")],...My(D.allowed_commands),...Dy(D.rules,N),...Gy(D.tests),...Fy(D),...zy(D)]}function My(D){if(!Array.isArray(D))return[e(["allowed_commands"],"required array")];let N=new Set;return[...D.flatMap((z,ee)=>typeof z==="string"&&w.test(z)?[]:[e(["allowed_commands",ee],"must match command pattern")]),...D.flatMap((z,ee)=>{if(typeof z!=="string"||!w.test(z))return[];if(N.has(z))return[Xt(["allowed_commands",ee],`duplicate command "${z}"`)];return N.add(z),[]})]}function Dy(D,N){if(!Array.isArray(D))return[e(["rules"],"required array")];return[...D.flatMap((z,ee)=>{if(!or(z))return[e(["rules",ee],"must be an object")];return N?Ly(z,["rules",ee]):Ny(z,["rules",ee])}),...Te(D)]}function Ny(D,N){return[...Du(D.name,N),...Nu(D.command,N),...D.subcommand===void 0||typeof D.subcommand==="string"&&w.test(D.subcommand)?[]:[e([...N,"subcommand"],"must match command pattern")],...Ti(D.block_args,[...N,"block_args"],"required non-empty array",!1),...Lu(D.reason,N),...Wu(D.intent,N)]}function Ly(D,N){return[...Du(D.name,N),...Nu(D.command,N),...Lu(D.reason,N),...Wu(D.intent,N),...Wy(D.match,[...N,"match"]),...D.subcommand===void 0?[]:[e([...N,"subcommand"],"not supported in rulebook_version 2")],...D.block_args===void 0?[]:[e([...N,"block_args"],"not supported in rulebook_version 2")]]}function Du(D,N){if(typeof D!=="string")return[e([...N,"name"],"required string")];return l.test(D)?[]:[e([...N,"name"],"must match rule name pattern")]}function Nu(D,N){return typeof D==="string"&&w.test(D)?[]:[e([...N,"command"],"required string matching command pattern")]}function Lu(D,N){return typeof D==="string"&&D!==""&&D.length<=T?[]:[e([...N,"reason"],Ty)]}function Wu(D,N){return D===void 0||Ce(D)?[]:[e([...N,"intent"],we)]}function Wy(D,N){if(!or(D))return[e(N,"required object")];return[...Ti(D.command_path,[...N,"command_path"],Iy,!1),...D.any_args===void 0?[]:Ti(D.any_args,[...N,"any_args"],Mu,!0),...D.exclude_args===void 0?[]:Ti(D.exclude_args,[...N,"exclude_args"],Mu,!0)]}function Ti(D,N,z,ee){if(!Array.isArray(D))return[e(N,z)];let te=D.flatMap((he,je)=>{if(typeof he!=="string")return[e([...N,je],"must be a non-empty string")];return he===""?[Xt([...N,je],"must be a non-empty string")]:[]});if(D.some((he)=>typeof he!=="string"))return te;return[...te,...D.length===0?[Xt(N,z)]:[],...ee&&new Set(D).size!==D.length?[Xt(N,"must not contain duplicate values")]:[]]}function Gy(D){if(D===void 0)return[];if(!Array.isArray(D))return[e(["tests"],"must be an array if provided")];return D.flatMap((N,z)=>{if(!or(N))return[e(["tests",z],"must be an object")];return[...typeof N.command==="string"&&N.command.trim()!==""?[]:[e(["tests",z,"command"],"required non-empty string")],...N.expect==="blocked"||N.expect==="allowed"?[]:[e(["tests",z,"expect"],'must be "blocked" or "allowed"')],...N.rule===void 0||typeof N.rule==="string"?[]:[e(["tests",z,"rule"],"must be a string if provided")],...N.expect==="blocked"&&typeof N.rule!=="string"?[Xt(["tests",z,"rule"],"required string for blocked fixtures")]:[]]})}function Fy(D){if(!Array.isArray(D.tests))return[];let N=new Set(_e(D));return[...new Set(D.tests.flatMap((z)=>or(z)&&z.expect==="blocked"&&typeof z.rule==="string"?[z.rule]:[]))].filter((z)=>!N.has(z)).map((z)=>Xt(["tests"],`blocked fixture references unknown rule "${z}"`))}function zy(D){if(!Array.isArray(D.allowed_commands)||!Array.isArray(D.rules))return[];let N=new Set(D.allowed_commands.filter((z)=>typeof z==="string"));return D.rules.flatMap((z,ee)=>{let te=or(z)?z.command:void 0;if(typeof te!=="string"||N.has(te))return[];return[Xt(["rules",ee,"command"],`"${te}" must be listed in allowed_commands`)]})}function or(D){return!!D&&typeof D==="object"&&!Array.isArray(D)}function Y(D,N){let z=J(D,N),ee;try{ee=hu(z.userConfigTarget,z.projectConfigTarget)}catch(mt){if(mt instanceof r)return Yy(z,mt.message);throw mt}let te=m(z.userConfigTarget),he=ee?{config:null,errors:[]}:m(z.projectConfigTarget),je=Fu(z.userConfigPath,te.errors),at=Fu(z.projectConfigPath,he.errors),lt=new Set,ct=te.config?xa(te.config,Er(z.userConfigPath),"user",z.userScope,lt):zu(),dt=he.config?xa(he.config,Er(z.projectConfigPath),"project",z.projectScope,lt):zu(),ft=te.config?.overrides??{},ut=he.config?.overrides??{};return{rules:[...Gu(ct.rules,ft),...Gu(dt.rules,ut)],transparent_wrappers:Ky(te.config,he.config),rulebooks:[...ct.rulebooks,...dt.rulebooks],errors:[...je,...at,...ct.errors,...dt.errors],warnings:[...ct.warnings,...dt.warnings,...ct.canValidateOverrides?Ra(ft,ct.knownRuleIds,z.userConfigPath):[],...ct.canValidateOverrides?qy(ut,ct.knownRuleIds,z.projectConfigPath):[],...dt.canValidateOverrides?Ra(ut,dt.knownRuleIds,z.projectConfigPath):[]],userConfig:te.config??void 0,projectConfig:he.config??void 0,...z}}function U(D,N){let z=By(D,N);if(!z)return[];return[...z.scope.errors,...z.scope.warnings,...$y(z.config,z.scope,D)]}function By(D,N){let z=N??v(Er(Er(D)),"rules policy"),ee=m(i(z,D)).config;if(!ee)return null;return{config:ee,scope:xa(ee,Er(D),"project",z)}}function $y(D,N,z){return N.canValidateOverrides?Ra(D.overrides??{},N.knownRuleIds,z):[]}function xa(D,N,z,ee=v(Er(Er(N)),z==="user"?"user policy":"project policy"),te=new Set){let he=[],je=[],at=D.rules.flatMap((ct)=>{let dt=Hy(ct,N,ee);if(dt.errors.length>0||!dt.rulebook)return he.push(...dt.errors),[];let ft=dt.rulebook;if(te.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 te.add(ft.name),[{rules:Uy(ft),rulebook:{source:z,spec:ct,name:ft.name,version:ft.version,rules:ft.rules.map((ut)=>`${ft.name}/${ut.name}`)}}]}),lt=at.flatMap((ct)=>ct.rules);return{rules:lt,rulebooks:at.map((ct)=>ct.rulebook),knownRuleIds:new Set(lt.map((ct)=>ct.name)),errors:he,warnings:je,canValidateOverrides:he.length===0}}function Uy(D){if(D.rulebook_version===2)return D.rules.map((N)=>({name:`${D.name}/${N.name}`,command:N.command,block_args:[],match:N.match,reason:N.reason,intent:N.intent}));return D.rules.map((N)=>({...N,name:`${D.name}/${N.name}`,match:void 0}))}function Hy(D,N,z){let ee=Pe(D),te=O(N,ee),he=Vy(te,z);if("error"in he)return{rulebook:null,errors:[he.error]};if(he.content===null)return{rulebook:null,errors:[`missing rulebook file ${te} for ${D}; ${jy(D)}`]};let je=me(he.content);if("problem"in je)return{rulebook:null,errors:[`invalid rulebook ${te}: ${je.problem}; fix that file`]};if(je.rulebook.name!==ee)return{rulebook:null,errors:[`rulebook name "${je.rulebook.name}" in ${te} must match source "${D}"; fix that file`]};return{rulebook:je.rulebook,errors:[]}}function Pe(D){return S(D)?I(D).name:D}function jy(D){return S(D)?`run ${wu} to vendor ${D}`:"create that file or remove that source from the rules config"}function Vy(D,N){try{return{content:n(i(N,D))}}catch(z){if(z instanceof r)return{error:z.message};throw z}}function me(D){let N;try{N=JSON.parse(D)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:se(N)}}catch(z){return{problem:z instanceof Error?z.message:"invalid rulebook"}}}function Ky(D,N){return[...new Set([...D?.transparent_wrappers??[],...N?.transparent_wrappers??[]])]}function Gu(D,N){return D.flatMap((z)=>{let ee=N[z.name];if(ee==="off")return[];if(ee&&typeof ee==="object")return[{...z,intent:ee.intent??z.intent,reason:ee.reason}];return[z]})}function Ra(D,N,z){return Object.keys(D).filter((ee)=>!N.has(ee)).map((ee)=>`unknown override key "${ee}" in ${z}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function qy(D,N,z){return Object.keys(D).filter((ee)=>N.has(ee)).map((ee)=>`project override cannot target user-scoped rule "${ee}" in ${z}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function Fu(D,N){return N.map((z)=>z.startsWith("Unable to access ")?z:`${D}: ${z}`)}function Yy(D,N){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[N],warnings:[],userConfigPath:D.userConfigPath,projectConfigPath:D.projectConfigPath}}function zu(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as sb,readFileSync as ab}from"node:fs";var Bu=[{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"}],_a=new Set(Bu.map((D)=>D.id)),G=Bu,Zy=new Map(G.map((D)=>[D.id,D.intent]));function Ct(D,N){return{id:D,reason:N,intent:Zy.get(D)??"manual_only"}}var wa=[{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"}],Ii={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Xy=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Jy=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Pa=[{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"]},...Jy.flatMap((D)=>Xy.map((N)=>({id:["secret.home",D.idSlug,N.slice(1)].join("."),category:"Home path",label:[D.label,N].join(""),description:["Blocks home ",D.label,N," credential backup files."].join(""),suffixParts:[...D.directoryParts,[D.basename,N].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 ki=[{id:"secret.cli.claude-code",category:"Coding CLI credential",label:"Claude Code credentials",paths:["~/.claude/.credentials.json"]},{id:"secret.cli.claude-code.config",category:"Coding CLI config",label:"Claude Code config",paths:["~/.claude/settings.json","~/.claude/settings.local.json","~/.claude.json","<project>/.claude/settings.local.json","<project>/.mcp.json"]},{id:"secret.cli.antigravity",category:"Coding CLI config",label:"Antigravity CLI hook config",paths:["~/.gemini/config/hooks.json","~/.gemini/config/mcp_config.json"]},{id:"secret.cli.codex",category:"Coding CLI credential",label:"Codex credentials",paths:["~/.codex/auth.json","~/.codex/.credentials.json","~/.codex/secrets","~/.codex/.sandbox-secrets"]},{id:"secret.cli.codex.config",category:"Coding CLI config",label:"Codex config",paths:["~/.codex/config.toml","~/.codex/<name>.config.toml"]},{id:"secret.cli.gemini",category:"Coding CLI credential",label:"Gemini CLI credentials",paths:["~/.gemini/oauth_creds.json","~/.gemini/mcp-oauth-tokens.json","~/.gemini/a2a-oauth-tokens.json","~/.gemini/gemini-credentials.json"]},{id:"secret.cli.gemini.config",category:"Coding CLI config",label:"Gemini CLI config",paths:["~/.gemini/settings.json","~/.gemini/google_accounts.json","<project>/.gemini/settings.json","/Library/Application Support/GeminiCli/settings.json","/etc/gemini-cli/settings.json"]},{id:"secret.cli.copilot-cli",category:"Coding CLI credential",label:"GitHub Copilot CLI credentials",paths:["~/.copilot/config.json","~/.copilot/mcp-oauth-config","~/.copilot/mcp-secrets"]},{id:"secret.cli.copilot-cli.config",category:"Coding CLI config",label:"GitHub Copilot CLI config",paths:["~/.copilot/mcp-config.json"]},{id:"secret.cli.kimi-code",category:"Coding CLI credential",label:"Kimi Code credentials",paths:["~/.kimi-code/server.token","~/.kimi-code/credentials","~/.kimi/credentials","~/.kimi/mcp-oauth"]},{id:"secret.cli.kimi-code.config",category:"Coding CLI config",label:"Kimi Code config",paths:["~/.kimi-code/config.toml","~/.kimi-code/mcp.json","~/.kimi/config.toml","~/.kimi/config.json","~/.kimi/config.json.bak","~/.kimi/mcp.json","<project>/.kimi-code/mcp.json"]},{id:"secret.cli.opencode",category:"Coding CLI credential",label:"OpenCode credentials",paths:["~/.local/share/opencode/auth.json","~/.local/share/opencode/mcp-auth.json","~/.local/share/opencode/opencode.db"]},{id:"secret.cli.opencode.config",category:"Coding CLI config",label:"OpenCode config",paths:["~/.config/opencode/opencode.json","~/.config/opencode/opencode.jsonc","~/.config/opencode/config.json","/Library/Application Support/opencode/opencode.json","/etc/opencode/opencode.json","<project>/opencode.json","<project>/opencode.jsonc"]},{id:"secret.cli.pi",category:"Coding CLI credential",label:"Pi credentials",paths:["~/.pi/agent/auth.json"]},{id:"secret.cli.pi.config",category:"Coding CLI config",label:"Pi config",paths:["~/.pi/agent/models.json"]},{id:"secret.cli.amp",category:"Coding CLI credential",label:"Amp Code credentials",paths:["~/.local/share/amp/secrets.json","~/.amp/oauth"]},{id:"secret.cli.amp.config",category:"Coding CLI config",label:"Amp Code config",paths:["~/.config/amp/settings.json","~/.config/amp/settings.jsonc","<project>/.amp/settings.json","<project>/.amp/settings.jsonc"]},{id:"secret.cli.cursor",category:"Coding CLI credential",label:"Cursor CLI credentials",paths:["~/.cursor/auth.json","~/.config/cursor/auth.json","~/.cursor/projects/<name>/mcp-auth.json"]},{id:"secret.cli.cursor.config",category:"Coding CLI config",label:"Cursor CLI config",paths:["~/.cursor/mcp.json","<project>/.cursor/mcp.json"]},{id:"secret.cli.grok-build",category:"Coding CLI credential",label:"Grok Build credentials",paths:["~/.grok/auth.json","~/.grok/mcp_credentials.json"]},{id:"secret.cli.grok-build.config",category:"Coding CLI config",label:"Grok Build config",paths:["~/.grok/config.toml","~/.grok/managed_config.toml","~/.grok/requirements.toml","<project>/.grok/config.toml","/etc/grok/managed_config.toml","/etc/grok/requirements.toml"]}],$u=[{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"}],Qy=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Aa=$u.map((D)=>({id:`secret.variant.${D.slug}.separator`,category:"Variant",label:`${D.label}-* / ${D.label}_*`,description:`Blocks ${D.label} variants with dash or underscore suffixes.`,prefix:D.prefix})),Ta=$u.flatMap((D)=>Qy.map((N)=>({id:`secret.variant.${D.slug}.${N.slice(1)}`,category:"Variant",label:`${D.label}${N}`,description:`Blocks ${D.label}${N} private credential variants.`,prefix:D.prefix,suffix:N}))),To={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)$/},Ia=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((D)=>({id:`secret.ext.${D}`,category:"Extension",label:`.${D}`,description:`Blocks files with the .${D} extension.`,extension:D})),ka=[{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=[...wa,Ii,...Pa,...Aa,...Ta,To,...Ia,...ka,...ki].map((D)=>({id:D.id,category:D.category,label:D.label,...D.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in D?{paths:D.paths}:{description:D.description}})),Oi=new Set(ki.flatMap((D)=>D.category==="Coding CLI config"?[D.id]:[])),Oa=new Set(Ke.map((D)=>D.id));import{isAbsolute as Ma,join as eb,normalize as tb,sep as Mi}from"node:path";var Di=process.platform==="win32",Uu=/[*?]/;function Da(D){let N=D.trim(),z=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(Di?N.replaceAll("\\","/"):N);if(!z)return null;let ee=z[1]??"",te=z[2]??"";if(Uu.test(ee)||te==="."||te==="..")return null;return{root:ee||"/",name:te}}function Io(D,N){if(D==="~")return N;if(D.startsWith("~/"))return`${N}${D.slice(1)}`;return D}function Na(D,N){if(typeof D!=="string"||D.trim()==="")return"must be a non-empty path string";let z=Io(D.trim(),N);if(!Ma(z))return"must be an absolute path or start with ~/";return ko(z,N)}function La(D,N){let z=Hu(D,N);if(z===null)return"must be a non-empty path string";if(!Ma(z))return null;if(ko(z,N)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var nb="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",rb="cannot cover the guard's own configuration";function Hu(D,N){if(typeof D!=="string"||D.trim()==="")return null;let z=D.trim(),ee=Di?z.replaceAll("\\","/"):z;return Io(ee.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),N)}function Wa(D,N){let z=Hu(D,N);if(z===null)return"must be a non-empty path string";let ee=Da(z)?.root??z;if(Uu.test(ee))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Ma(ee))return null;if(ko(ee,N)!==null)return nb;return ob(ee,N)?rb:null}function ob(D,N){let z=Ni(D),ee=Ni(eb(N,".cc-safety-net"));return z===ee||z.startsWith(`${ee}${Mi}`)}function ko(D,N){let z=Ni(D),ee=Ni(N);if(z===ee)return"cannot be the home directory";let te=z.endsWith(Mi)?z:`${z}${Mi}`;if(ee.startsWith(te))return"cannot contain the home directory";return null}function Ni(D){let N=tb(D);if(Di)N=N.replace(/\//g,"\\").toLowerCase();if(N.length>(Di?3:1)&&N.endsWith(Mi))N=N.slice(0,-1);return N}var ju=30,Li=1,Wi=365;function Vu(D){if(typeof D!=="number"||!Number.isInteger(D))return 30;if(D<1)return 1;return D>365?365:D}var Ku=new Set(G.filter((D)=>D.catastrophic).map((D)=>D.id));function Pt(D,N){if(!D)return null;if(Ku.has(D.id))return D;if(N?.destructiveCommandProtectionEnabled===!1)return null;let z=N?.effectiveDestructiveCommandRules[D.id];return z&&!z.enabled?null:D}function Jt(D,N,z){if(Ku.has(N))return!0;if(D?.destructiveCommandProtectionEnabled===!1)return!1;return D?.effectiveDestructiveCommandRules[N]?.enabled??z}function H(D,N){return Object.freeze(Object.fromEntries(G.map((z)=>{let ee=z.activationCapability?N[z.activationCapability]:void 0,te=ee?.enabled??!0,he=D.destructiveCommandRuleOverrides[z.id],je=z.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...he?{override:he}:{}}:D.destructiveCommandProtectionEnabled?he?{enabled:he==="on",inheritedEnabled:te,changesInherited:he==="on"!==te,source:"rule_override",...z.activationCapability?{activationCapability:z.activationCapability}:{},override:he}:{enabled:te,inheritedEnabled:te,changesInherited:!1,source:ee?.source??"built_in_default",...z.activationCapability?{activationCapability:z.activationCapability}:{}}:{enabled:!1,inheritedEnabled:te,changesInherited:!1,source:"master_disabled",...z.activationCapability?{activationCapability:z.activationCapability}:{},...he?{override:he}:{}};return[z.id,Object.freeze(je)]})))}function qu(D,N){return Object.freeze({...D,effectiveDestructiveCommandRules:H(D,N)})}var Yu={standard:0,strict:1,paranoid:2};function Z(D,N){return{policy:{version:1,safety:{level:N.safety?.level??D.safety.level,overrides:{...D.safety.overrides,...N.safety?.overrides}},workflow:{worktree_mode:N.workflow?.worktree_mode??D.workflow.worktree_mode},destructive_command_protection:{enabled:N.destructive_command_protection?.enabled??D.destructive_command_protection.enabled,overrides:{...D.destructive_command_protection.overrides,...N.destructive_command_protection?.overrides},allow_paths:Ga(D.destructive_command_protection.allow_paths,N.destructive_command_protection?.allow_paths)},secret_protection:{enabled:N.secret_protection?.enabled??D.secret_protection.enabled,overrides:{...D.secret_protection.overrides,...N.secret_protection?.overrides},deny_paths:Ga(D.secret_protection.deny_paths,N.secret_protection?.deny_paths),allow_paths:Ga(D.secret_protection.allow_paths,N.secret_protection?.allow_paths)},audit:D.audit},weakenings:ib(D,N)}}function Ga(D,N){return[...new Set([...D,...N??[]])]}function ib(D,N){let z=N.safety?.level,ee=Ci[D.safety.level];return[...z&&Yu[z]<Yu[D.safety.level]?[`project policy lowers level: ${D.safety.level} -> ${z}`]:[],...Ur.flatMap((te)=>N.safety?.overrides?.[te]===!1&&(D.safety.overrides[te]??ee[te])?[`project policy disables ${te}`]:[]),...N.workflow?.worktree_mode===!0&&!D.workflow.worktree_mode?["project policy enables worktree mode relaxations"]:[],...N.destructive_command_protection?.enabled===!1&&D.destructive_command_protection.enabled?["project policy disables destructive command protection"]:[],...N.secret_protection?.enabled===!1&&D.secret_protection.enabled?["project policy disables secret protection"]:[],...Zu(N.destructive_command_protection?.overrides,(te)=>D.destructive_command_protection.enabled&&D.destructive_command_protection.overrides[te]!=="off"),...Zu(N.secret_protection?.overrides,(te)=>D.secret_protection.enabled&&(D.secret_protection.overrides[te]==="on"?!0:D.secret_protection.overrides[te]!=="off"&&!Oi.has(te))),...D.destructive_command_protection.enabled?Xu(D.destructive_command_protection.allow_paths,N.destructive_command_protection?.allow_paths).map((te)=>`project policy adds destructive allow path: ${te}`):[],...D.secret_protection.enabled?Xu(D.secret_protection.allow_paths,N.secret_protection?.allow_paths).map((te)=>`project policy adds secret allow path: ${te}`):[]]}function Zu(D,N){return Object.entries(D??{}).flatMap(([z,ee])=>ee==="off"&&N(z)?[`project policy disables rule ${z}`]:[])}function Xu(D,N){return(N??[]).filter((z)=>!D.includes(z))}var Ba=new Set(["standard","strict","paranoid"]),X={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:ju}};function td(D,N){let z=mb(u(D,N),D.home),ee=Ie(b(N.cwd),D.home),te=ae(ee.parsed,D.home),he=Object.keys(te.policy).length>0?Z(z.gui??X,te.policy):void 0,je=[...z.errors,...ee.errors,...te.diagnostics],at=(z.fallback==="defaults"&&he?"salvaged":z.fallback)??(z.gui?void 0:ee.fallback)??(je.length>0?"salvaged":void 0),lt=te.policy.safety?.level?"project":z.levelPresent?"user":"default";return{...he?za(he.policy):z.policy,errors:je,...at?{fallback:at}:{},...ee.exists?{policyScopes:{levelScope:lt,weakenings:he?.weakenings??[]}}:{}}}var lb="project policy audit settings are ignored; audit is user scope only";function ae(D,N){if(!bn(D))return{policy:{},diagnostics:[]};let z=bn(D.safety)?D.safety:{},ee=bn(D.workflow)?D.workflow:{},te=bn(D.destructive_command_protection)?D.destructive_command_protection:{},he=bn(D.secret_protection)?D.secret_protection:{},je={...Ba.has(z.level)?{level:z.level}:{},...bn(z.overrides)?Ju({overrides:nd(z.overrides,Ur,["safety","overrides"],xr)}):{}},at={...typeof te.enabled==="boolean"?{enabled:te.enabled}:{},...te.overrides!==void 0?{overrides:Gi(te.overrides,_a,od,xr)}:{},...te.allow_paths!==void 0?{allow_paths:Kr(te.allow_paths,Na,N,["destructive_command_protection","allow_paths"],xr)}:{}},lt={...typeof he.enabled==="boolean"?{enabled:he.enabled}:{},...he.overrides!==void 0?{overrides:Gi(he.overrides,Oa,id,xr)}:{},...he.deny_paths!==void 0?{deny_paths:Kr(he.deny_paths,La,N,["secret_protection","deny_paths"],xr)}:{},...he.allow_paths!==void 0?{allow_paths:Kr(he.allow_paths,Wa,N,["secret_protection","allow_paths"],xr)}:{}};return{policy:Ju({safety:je,workflow:typeof ee.worktree_mode==="boolean"?{worktree_mode:ee.worktree_mode}:{},destructive_command_protection:at,secret_protection:lt}),diagnostics:D.audit===void 0?[]:[lb]}}function nd(D,N,z,ee){return Object.fromEntries(N.flatMap((te)=>{let he=D[te];if(typeof he==="boolean")return[[te,he]];if(he!==void 0)ee(e([...z,te],$a));return[]}))}function Ju(D){return Object.fromEntries(Object.entries(D).flatMap((N)=>Object.keys(N[1]).length>0?[N]:[]))}var xr=()=>{return},$a="must be a boolean",Ua="must be an object if provided",rd=`must be an integer between ${Li} and ${Wi}`,od={path:["destructive_command_protection","overrides"],label:"destructive command"},id={path:["secret_protection","overrides"],label:"secret protection"},Je=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Ye(D,N){let z=[];return{policy:sd(D,N,(te)=>{z.push(te)}),issues:z}}function C(D,N){return sd(D,N,xr)}function sd(D,N,z){if(!bn(D))return z(e([],"Config must be an object")),W();if(D.version!==1)z(e(["version"],"must be 1"));let ee=Vr(D.safety,["safety"],["level","overrides"],z),te=Vr(ee.overrides,["safety","overrides"],Ur,z),he=Vr(D.workflow,["workflow"],["worktree_mode"],z),je=Vr(D.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],z),at=Vr(D.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],z),lt=Vr(D.audit,["audit"],["retention_days"],z);return ad(D,Je,[],z),{version:1,safety:{level:cb(ee.level,z),overrides:nd(te,Ur,["safety","overrides"],z)},workflow:{worktree_mode:Fa(he.worktree_mode,["workflow","worktree_mode"],!1,z)},destructive_command_protection:{enabled:Fa(je.enabled,["destructive_command_protection","enabled"],!0,z),overrides:Gi(je.overrides,_a,od,z),allow_paths:Kr(je.allow_paths,Na,N,["destructive_command_protection","allow_paths"],z)},secret_protection:{enabled:Fa(at.enabled,["secret_protection","enabled"],!0,z),overrides:Gi(at.overrides,Oa,id,z),deny_paths:Kr(at.deny_paths,La,N,["secret_protection","deny_paths"],z),allow_paths:Kr(at.allow_paths,Wa,N,["secret_protection","allow_paths"],z)},audit:{retention_days:ub(lt.retention_days,z)}}}function Vr(D,N,z,ee){if(D===void 0)return{};if(!bn(D))return ee(e(N,Ua)),{};return ad(D,z,N,ee),D}function ad(D,N,z,ee){for(let te of Object.keys(D).filter((he)=>!N.includes(he)))ee({path:z,message:te,kind:"unknownKeys"})}function cb(D,N){if(D===void 0)return"standard";if(Ba.has(D))return D;return N(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Fa(D,N,z,ee){if(typeof D==="boolean")return D;if(D!==void 0)ee(e(N,$a));return z}function ub(D,N){if(!(D===void 0||typeof D==="number"&&Number.isInteger(D)&&D>=Li&&D<=Wi))N(e(["audit","retention_days"],rd));return Vu(D)}function Gi(D,N,z,ee){if(D===void 0)return{};if(!bn(D))return ee(e(z.path,Ua)),{};return Object.fromEntries(Object.entries(D).flatMap(([te,he])=>{if(!N.has(te))return ee({path:[...z.path,te],message:`unknown ${z.label} rule id "${te}"`,kind:"key"}),[];if(he==="on"||he==="off")return[[te,he]];return ee(e([...z.path,te],'must be "on" or "off"')),[]}))}function Kr(D,N,z,ee,te){if(D===void 0)return[];if(!Array.isArray(D))return te(e(ee,"must be an array of paths")),[];return D.flatMap((he,je)=>{let at=N(he,z);if(at===null)return[he];return te(typeof he==="string"?Xt([...ee,je],at):e([...ee,je],at)),[]})}function bn(D){return!!D&&typeof D==="object"&&!Array.isArray(D)}function W(){return structuredClone(X)}function Ae(D,N){let z=R({safety:De(D.safety)},N),ee=H({destructiveCommandProtectionEnabled:D.destructive_command_protection.enabled,destructiveCommandRuleOverrides:D.destructive_command_protection.overrides},z.capabilities),te=Object.values(ee),he=te.filter((je)=>je.source!=="catastrophic");return{selectedPreset:D.safety.level,effectiveLevel:z.effectiveLevel,capabilities:z.capabilities,rules:ee,counts:{enabled:he.filter((je)=>je.enabled).length,disabled:he.filter((je)=>!je.enabled).length,effectiveCustomizations:te.filter((je)=>je.changesInherited).length}}}function Ie(D,N){if(!sb(D))return{exists:!1,policy:W(),errors:[]};try{let z=ab(D,"utf-8");if(!z.trim())return{exists:!0,policy:W(),errors:[`${D}: Config file is empty`],fallback:"defaults"};let ee=JSON.parse(z),te=Ye(ee,N);if(te.issues.length===0)return{exists:!0,parsed:ee,policy:te.policy,errors:[]};return{exists:!0,parsed:ee,policy:te.policy,errors:te.issues.map((he)=>`${D}: ${fb(he)}`),fallback:bn(ee)?"salvaged":"defaults"}}catch(z){let ee=z instanceof Error?z.message:String(z);return{exists:!0,policy:W(),errors:[`${D}: ${z instanceof SyntaxError?"Invalid JSON":ee}`],fallback:"defaults"}}}var db=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[Ua,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[$a,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[rd,`not an integer between ${Li} and ${Wi}`]]);function fb(D){let N=Ea(D.path);if(D.kind==="unknownKeys")return`${N===""?"":`${N}.`}${D.message}: unknown field`;if(D.kind==="key")return`${N}: unknown rule id`;let z=db.get(D.message)??D.message;return N===""?z:`${N}: ${z}`}function mb(D,N){let z=Ie(D,N);if(!z.exists){let ee=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!bn(ee))return{policy:ed(),errors:[]};let te=C(ee,N);return{policy:za(te),gui:te,errors:[],levelPresent:Qu(ee)}}if(z.parsed===void 0)return{policy:ed(),errors:z.errors,...z.fallback?{fallback:z.fallback}:{}};return{policy:za(z.policy),gui:z.policy,errors:z.errors,...z.fallback?{fallback:z.fallback}:{},levelPresent:Qu(z.parsed)}}function Qu(D){let N=bn(D)&&bn(D.safety)?D.safety:{};return Ba.has(N.level)}function Oe(D){let N=Object.entries(D),z=new Set(N.flatMap(([ee,te])=>te==="on"?[ee]:[]));return[...new Set([...[...Oi].filter((ee)=>!z.has(ee)),...N.flatMap(([ee,te])=>te==="off"?[ee]:[])])]}function ed(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Oe({}),denyPaths:[],allowPaths:[]}}}function za(D){return{safety:De(D.safety),worktreeMode:D.workflow.worktree_mode,destructiveCommandProtectionEnabled:D.destructive_command_protection.enabled,destructiveCommandRuleOverrides:D.destructive_command_protection.overrides,destructiveCommandAllowPaths:D.destructive_command_protection.allow_paths,secretProtection:{enabled:D.secret_protection.enabled,disabledRules:Oe(D.secret_protection.overrides),denyPaths:D.secret_protection.deny_paths,allowPaths:D.secret_protection.allow_paths}}}function De(D){let N={...D.overrides.fail_closed!==void 0?{failClosed:D.overrides.fail_closed}:{},...D.overrides.paranoid_rm!==void 0?{paranoidRm:D.overrides.paranoid_rm}:{},...D.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:D.overrides.paranoid_interpreters}:{}};return{level:D.level,...Object.keys(N).length>0?{overrides:N}:{}}}function E(D,N){let z=Y(D,N),ee=td(D,N),te={rules:z.rules,transparentWrappers:z.transparent_wrappers,safety:ee.safety,worktreeMode:ee.worktreeMode,destructiveCommandProtectionEnabled:ee.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:ee.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:ee.destructiveCommandAllowPaths,secretProtection:{enabled:ee.secretProtection.enabled??!0,disabledRules:ee.secretProtection.disabledRules??[],denyPaths:ee.secretProtection.denyPaths,allowPaths:ee.secretProtection.allowPaths??[]}},he={...z.userConfig?.overrides,...z.projectConfig?.overrides},je=Object.freeze(Object.fromEntries(te.rules.map((at)=>{let lt=z.rulebooks.find((dt)=>dt.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}),...yb(lt.spec)?{source:lt.spec}:{}}:{},...ct&&typeof ct==="object"?{override:Object.freeze({type:"reason",reason:ct.reason})}:{}})]})));return Ee(te,pb(z,ee),je,ee.policyScopes)}function Ne(D){if(D.state==="ready")return{state:D.state};return{state:D.state,reason:D.reason}}function pb(D,N){let z=hb(N);if(D.errors.length===0&&D.warnings.length===0&&!z)return;return{diagnostics:[...D.errors,...D.warnings,...N.errors],reason:bb(D.errors.length>0?gb(D.errors):void 0,D.warnings.length>0?ja(D.warnings.join("; ")):void 0,z)}}function gb(D){return`${ja(D.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function hb(D){if(D.errors.length===0)return;let N=D.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${D.errors.join("; ")}. Enforcing ${N}; the invalid values are not active. Fix the policy file manually`}function yb(D){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(D)}function Ee(D,N,z=Object.freeze({}),ee){let te=Ha(structuredClone(D)),he=ee?{policyScopes:Ha(structuredClone(ee))}:{};if(!N)return Object.freeze({state:"ready",policy:te,diagnostics:Object.freeze([]),ruleMetadata:z,...he});return Object.freeze({state:"degraded",policy:te,diagnostics:Object.freeze([...N.diagnostics]),reason:N.reason,ruleMetadata:z,...he})}function Ha(D){if(typeof D!=="object"||D===null)return D;for(let N of Object.values(D))Ha(N);return Object.freeze(D)}function bb(...D){return ja(D.filter((N)=>!!N).join("; "))}function ja(D){return/[.!?]$/.test(D)?D:`${D}.`}function Fe(D){let N=D.effectiveCapabilities,z=D.strict??N.fail_closed.enabled,ee=D.paranoidRm??N.paranoid_rm.enabled,te=D.paranoidInterpreters??N.paranoid_interpreters.enabled,he={fail_closed:Va(N.fail_closed,D.strict,"strict"),paranoid_rm:Va(N.paranoid_rm,D.paranoidRm,"paranoidRm"),paranoid_interpreters:Va(N.paranoid_interpreters,D.paranoidInterpreters,"paranoidInterpreters")};return{policy:qu(D.policySnapshot.policy,he),effectiveCapabilities:he,effectiveLevel:ca({failClosed:z,paranoidRm:ee,paranoidInterpreters:te}),strict:z,paranoidRm:ee,paranoidInterpreters:te,worktreeMode:D.worktreeMode??!1}}function Va(D,N,z){if(N===void 0||N===D.enabled)return D;return{enabled:N,source:"capability_override",sources:[...D.sources,`analysis options.${z}`]}}import{dirname as C_,isAbsolute as v_,join as E_,parse as x_,resolve as R_,sep as __}from"node:path";function Oo(D,N){if(D!=="powershell")return N[0]?.provenance==="command-substitution";let z=N[0]?.text==="&"||N[0]?.text==="."?1:0,ee=N[z]?.provenance;return ee!==void 0&&ee!=="literal"}var Sb=/^[A-Za-z_][A-Za-z0-9_]*=/;function Fi(D,N){return D?.provenance==="literal"&&!D.quoted&&D.raw===N&&D.text===N}function Mo(D){let N=Fi(D.words[0],"time")?1:0,z=N===1&&Fi(D.words[N],"-p")?N+1:N,ee=N===1&&Fi(D.words[z],"--")?z+1:z,te=Fi(D.words[ee],"!")?ee+1:ee,he=D.words.slice(te).find((je)=>!Sb.test(je.text));return he?.provenance==="literal"?he.text:void 0}var ir=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function zi(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Cb(D){return Object.freeze({...D,span:Object.freeze(D.span),words:Object.freeze(D.words),redirections:Object.freeze(D.redirections.map((N)=>Object.freeze({...N,span:Object.freeze(N.span),...N.heredoc?{heredoc:Object.freeze({...N.heredoc,bodySpan:Object.freeze(N.heredoc.bodySpan),terminatorSpan:Object.freeze(N.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(D.nested.map((N)=>ln(N)))})}function Bi(D,N,z){D.push(z),N.reset()}function $i(D){let N=[];return{parts:N,push:(z,ee,te)=>{if(ee<=z)return;N.push({raw:D.slice(z,ee),span:{start:z,end:ee},provenance:te})}}}function Ka(D){let N=D.parts??[{raw:D.raw,span:D.span,provenance:D.provenance}];return Object.freeze({kind:"word",...D,span:Object.freeze(D.span),parts:Object.freeze(N.map((z)=>Object.freeze({...z,span:Object.freeze(z.span)})))})}function qr(D,N,z,ee,te,he,je){return Ka({text:ee,raw:D.slice(N,z),span:{start:N,end:z},provenance:te,quoted:he,...je?{parts:je}:{}})}function ln(D){return Object.freeze({...D,span:Object.freeze(D.span),issues:Object.freeze(D.issues.map((N)=>Object.freeze({...N}))),nodes:Object.freeze(D.nodes.map((N)=>{if(N.kind==="command")return Cb(N);if(N.kind==="group"||N.kind==="function")return Object.freeze({...N,span:Object.freeze(N.span),body:ln(N.body)});return Object.freeze({...N,span:Object.freeze(N.span)})}))})}function qa(D,N,z){if(N>=z||cd(D[N]??""))return null;let ee="",te=!1,he=!1,je=N;while(je<z&&!cd(D[je]??"")){let at=D[je]??"";if(at==="'"){te=!0;let lt=ld(D,je+1,z,"'");ee+=lt.text,he||=!lt.closed,je=lt.next;continue}if(at==='"'){te=!0;let lt=ld(D,je+1,z,'"');ee+=lt.text,he||=!lt.closed,je=lt.next;continue}if(at==="\\"){te=!0;let lt=D[je+1];if(!lt||lt===`
|
|
7
7
|
`||lt==="\r"){he=!0;break}ee+=lt,je+=2;continue}if(at==="`"||D.startsWith("$(",je)||D.startsWith("${",je)||D.startsWith("<(",je)||D.startsWith(">(",je))he=!0;ee+=at,je++}return{delimiter:ee,quoted:te,next:je,ambiguous:he}}function Ya(D,N,z,ee){let te=[],he=N;for(let je of ee){let at=he,lt=!1;while(he<z){let ct=vb(D,he,z);if((je.stripTabs?ct.text.replace(/^\t+/,""):ct.text)===je.delimiter){je.attach({body:je.stripTabs?Eb(D.slice(at,he)):D.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 te.push({code:"unterminated-heredoc",message:`heredoc delimiter ${je.delimiter} was not found`}),{next:z,issues:te,terminated:!1}}return{next:he,issues:te,terminated:!0}}function ld(D,N,z,ee){let te="",he=N;while(he<z&&D[he]!==`
|
|
8
8
|
`&&D[he]!=="\r"){let je=D[he]??"";if(je===ee)return{text:te,next:he+1,closed:!0};if(ee==='"'&&je==="\\"&&D[he+1]){let at=D[he+1]??"";te+=["$","`",'"',"\\"].includes(at)?at:`\\${at}`,he+=2;continue}te+=je,he++}return{text:te,next:he,closed:!1}}function cd(D){return D!=="\r"&&(/[\s;&|<>)]/u.test(D)||D==="`")}function vb(D,N,z){let ee=N;while(ee<z&&D[ee]!==`
|
|
9
9
|
`)ee++;let te=ee>=z?z:ee+1;return{text:D.slice(N,ee),contentEnd:ee,next:te}}function Eb(D){return D.replace(/(^|\r\n?|\n)\t+/g,"$1")}var md=new Set(["&&","||","|","|&"]);function pd(D,N){let z={start:0,end:D.length};if(D.length>N.maxInputLength)return ln({kind:"program",dialect:"posix",source:D,span:z,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${N.maxInputLength} UTF-16 code units`}],nodes:[]});let ee=ji(D,0,D.length,N,{used:0,max:N.maxWords},0);return ln({kind:"program",dialect:"posix",source:D,span:z,status:qi(ee.issues,ee.limited),issues:ee.issues,nodes:ee.nodes})}function ji(D,N,z,ee,te,he,je){let at=[],lt=[],ct=zi(),dt=[],ft=()=>{if(ct.words.length===0&&ct.redirections.length===0)return;let mt={start:ct.start,end:ct.end},gt=ct.words.map((pt)=>pt.text);Bi(at,ct,{kind:"command",dialect:"posix",source:D.slice(mt.start,mt.end),span:mt,words:ct.words,redirections:ct.redirections,nested:ct.nested,displayText:lt.length>0&&at.length===0?D.slice(N,z):gt.join(" ")})},ut=N;while(ut<z){let mt=D[ut];if(!mt)break;if(je&&mt===je)return ft(),fd(at,lt),{nodes:at,issues:lt,next:ut+1,closed:!0,limited:!1,pendingHeredocs:dt};if(Ki(mt)){if(mt===`
|
|
@@ -19,13 +19,13 @@ var Xs="CC Safety Net could not analyze the command because it exceeds safe anal
|
|
|
19
19
|
`],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(te.has(ee))return{text:te.get(ee)??ee,next:N+1};if(ee==="x")return Ui(D,N+1,z,16,2,N+1);if(ee==="u")return Ui(D,N+1,z,16,4,N+1);if(ee==="U")return Ui(D,N+1,z,16,8,N+1);if(/[0-7]/.test(ee))return Ui(D,N,z,8,3,N+1);return{text:ee,next:N+1}}function Ui(D,N,z,ee,te,he){let je=ee===16?/[0-9a-fA-F]/:/[0-7]/,at="",lt=N;while(lt<z&&at.length<te&&je.test(D[lt]??""))at+=D[lt],lt++;if(!at)return{text:D[he-1]??"",next:he};let ct=Number.parseInt(at,ee);return ct>1114111||ct>=55296&&ct<=57343?{text:"�",next:lt,invalidCodePoint:ct}:{text:String.fromCodePoint(ct),next:lt}}function qi(D,N=!1){if(N)return"limited";if(D.some((z)=>z.code==="invalid-ansi-c-code-point"||z.code==="missing-heredoc-delimiter"||z.code==="ambiguous-heredoc-delimiter"||z.code==="unterminated-heredoc"||z.code==="unsupported-heredoc-context"))return"invalid";return D.length>0?"partial":"complete"}function bd(D,N,z,ee,te){let he=yd(D,N,z);return{text:ee+D.slice(N,he),provenance:Do(te,"variable"),next:he}}function Tb(D,N,z){let ee=$i(D),te=N,he=!1,je=!1,at=N;while(at<z){let lt=D[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=D.startsWith("$((",at),dt=D.startsWith("$(",at)&&!ct,ft=!je&&(D.startsWith("<(",at)||D.startsWith(">(",at)),ut=lt==="`";if(ct||dt||ft||ut){let mt=ct?3:ut?1:2,gt=ct?"))":ut?"`":")",pt=Qa(D,at+mt,z,gt),ht=pt===-1?z:pt+gt.length;ee.push(te,at,"literal"),ee.push(at,ht,ct?"arithmetic":"command-substitution"),at=ht,te=ht;continue}if(lt==="$"){let mt=yd(D,at,z);if(mt>at+1){ee.push(te,at,"literal"),ee.push(at,mt,"variable"),at=mt,te=mt;continue}}if(!je&&(lt==="*"||lt==="?"||lt==="[")){ee.push(te,at,"literal"),ee.push(at,at+1,"glob"),at++,te=at;continue}at++}return ee.push(te,z,"literal"),ee.parts}function Do(D,N){if(N==="command-substitution"||D==="command-substitution")return"command-substitution";if(N==="arithmetic"||D==="arithmetic")return"arithmetic";if(N==="variable"||D==="variable")return"variable";if(N==="glob"||D==="glob")return"glob";return D}function Ib(D,N,z){return N+1>=z||Ki(D[N+1]??"")||Vi(D,N+1)!==null}var kb=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),Ob=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function Mb(D){let N=0;while(N<=D.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(D[N]?.text??""))N++;if(N===D.length)return!0;let z=Db(D,N);if(z===void 0||z===null)return!1;N=z}return!1}function Db(D,N){let z=D[N]?.text.toLowerCase();if(z==="command")return Nb(D,N);if(z==="env")return Lb(D,N);if(z==="sudo")return Wb(D,N);return}function Nb(D,N){if(D[N+1]?.text==="-v")return null;for(let z=N+1;z<D.length;z++){let ee=D[z]?.text??"";if(ee==="--")return z+1;if(ee==="-p"||ee==="-v"||ee==="-V"||/^-[pvV]+$/.test(ee))continue;return z}return D.length}function Lb(D,N){for(let z=N+1;z<D.length;z++){let ee=D[z]?.text??"";if(ee==="--")return z+1;if(kb.has(ee)){if(D[z+1]===void 0)return null;z++;continue}if(ee.startsWith("-u=")||ee.startsWith("--unset=")||ee.startsWith("-C")&&ee.length>2||ee.startsWith("--chdir=")||ee.startsWith("-S")&&ee.length>2||ee.startsWith("--split-string=")||ee.startsWith("-P"))continue;if(ee.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(ee))continue;return z}return D.length}function Wb(D,N){for(let z=N+1;z<D.length;z++){let ee=D[z]?.text??"";if(ee==="--")return z+1;if(Ob.has(ee)){if(D[z+1]===void 0)return null;z++;continue}if(ee.startsWith("-"))continue;return z}return D.length}function Sd(D,N,z,ee){if(D.provenance!=="literal"||!D.raw.includes("{"))return;let te=Cd(D.raw,N,z,ee,!0);if(!te)return;if("limited"in te)return{limited:!0};let he=te.values.map((je)=>vd(je,z));if(he.some((je)=>je===null))return{limited:!0};return{words:[...new Set(he.filter((je)=>je!==null&&je!==""))]}}function Gb(D,N,z,ee,te){if(N.provenance!=="literal"||!N.raw.includes("{"))return;let he=Cd(N.raw,z,ee,te,!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)=>vd(at,ee));if(je.some((at)=>at===null))return;return{words:je.filter((at)=>at!==null&&at!=="").map((at)=>qr(D,N.span.start,N.span.end,at,"literal",!1))}}function Cd(D,N,z,ee,te){let he=[D],je=D.length,at=0;while(!0){let lt=he.findIndex((mt)=>dd(mt,te));if(lt===-1)break;if(++at>z)return{limited:"expansions"};let ct=he[lt]??"",dt=dd(ct,te);if(!dt||dt.kind==="range")return{limited:"expansions"};let ft=dt.start+ct.length-dt.end,ut=dt.alternatives.reduce((mt,gt)=>mt+ft+gt.length,0);if(je-ct.length+ut>ee)return{limited:"length"};if(he.length-1+dt.alternatives.length>N)return{limited:"words"};he.splice(lt,1,...Fb(ct,dt)),je+=ut-ct.length}return at===0?void 0:{values:he}}function dd(D,N){let z=[],ee,te=null,he=!1;for(let je=0;je<D.length;je++){let at=D[je];if(he){he=!1;continue}if(at==="\\"&&te!=="'"){he=!0;continue}if(at===te){te=null;continue}if(te===null&&(at==="'"||at==='"')){te=at;continue}if(te!==null)continue;if(at==="{"){z.push({start:je,commas:[]});continue}if(at===","&&z.length>0){z.at(-1)?.commas.push(je);continue}if(at!=="}"||z.length===0)continue;let lt=z.pop();if(!lt)continue;let ct=lt.commas.length>0?{kind:"alternatives",start:lt.start,end:je+1,commas:lt.commas}:N&&Bb(D.slice(lt.start+1,je))?{kind:"range",start:lt.start,end:je+1}:void 0;if(ct&&(!ee||ct.start<ee.start))ee=ct}if(!ee||ee.kind==="range")return ee;return{kind:ee.kind,start:ee.start,end:ee.end,alternatives:zb(D,ee)}}function Fb(D,N){return N.alternatives.map((z)=>`${D.slice(0,N.start)}${z}${D.slice(N.end)}`)}function zb(D,N){let z=[N.start,...N.commas,N.end-1];return z.slice(0,-1).map((ee,te)=>D.slice(ee+1,z[te+1]))}function Bb(D){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(D)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(D)}function vd(D,N){let z=`x${D}`,ee=Ja(z,0,z.length,{maxInputLength:z.length,maxWords:1,maxDepth:N},{used:0,max:1},0);if(ee.limited||ee.issues.length>0||ee.next!==z.length||ee.word.provenance!=="literal")return null;return ee.word.text.slice(1)}function $b(D,N,z,ee){return ln({kind:"program",dialect:"posix",source:D.slice(N,z),span:{start:N,end:z},status:"limited",issues:[{code:ee,message:"command structure exceeds parser limit"}],nodes:[]})}function Yr(D,N,z,ee,te){return{nodes:D,issues:[...N,{code:ee,message:`command structure exceeds parser limit ${te}`}],next:z,closed:!1,limited:!0,pendingHeredocs:[]}}function Hi(D,N,z){return{nodes:D,issues:N,next:z,closed:!1,limited:!0,pendingHeredocs:[]}}function Za(D){return D.used++,D.used<=D.max}function Ub(D,N,z){let ee=D.slice(N,z),te=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(ee)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(ee),he=te?.[1];if(!te||!he)return;return{name:he,braceIndex:N+te[0].lastIndexOf("{")}}function No(D){return D.some((N)=>{if(N.kind==="command")return N.redirections.some((z)=>z.heredoc)||N.nested.some((z)=>No(z.nodes));return(N.kind==="group"||N.kind==="function")&&No(N.body.nodes)})}function Hb(D){return D.map((N)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${N.delimiter} was not found`}))}function Ed(D){return D?.kind==="command"||D?.kind==="group"||D?.kind==="function"}function fd(D,N){let z=D.at(-1);if(z?.kind!=="connector"||!md.has(z.operator))return;N.push({code:"missing-command-after-connector",message:`connector ${z.operator} requires a following command`})}function Xa(D,N){if(!Ed(D.at(-1)))return;N.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function jb(D,N,z){return N===z||/[\s;&|()]/u.test(D[N-1]??"")}var Rd=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),Vb=new Set(["gc","cat","type","cp","mv","rm"]),_d=["-rec","-for","-path","-literalpath","-whatif"],Kb=/^\$env:\w/i,qb=/^(?:\$\{?\w+\}?|~)\\./;function wd(D,N){let z=D.toLowerCase().replaceAll("`","");if(![...Rd].some((te)=>z.includes(te))&&!(z.includes("rm")&&_d.some((te)=>z.includes(te)))&&!z.includes("<#")&&!Yb(z))return!1;let ee=rl(D,N);if(Pd(ee))return!1;return ee.issues.some((te)=>te.code==="unclosed-block-comment"||te.code==="comment-depth-limit")||nl(ee).some(Zb)}function Pd(D){return D.nodes.some((N)=>{if(N.kind==="group")return Pd(N.body);if(N.kind!=="command")return!1;return N.redirections.some((z)=>z.operator==="<<")})}function Yb(D){if(D.includes("$env:"))return!0;return D.includes("\\")&&(D.includes("$")||D.includes("~"))}function Zb(D){let N=D[0]==="&"||D[0]==="."?1:0,z=D[N]?.toLowerCase();if(z&&Rd.has(z))return!0;let ee=D.slice(N+1);if(z&&Vb.has(z)&&ee.some(Xb))return!0;if(z!=="rm")return!1;return ee.some((te)=>{let he=te.toLowerCase().split(":",1)[0]??"";return _d.some((je)=>he.startsWith(je))})}function Xb(D){return Kb.test(D)||qb.test(D)}function rl(D,N){let z={start:0,end:D.length};if(D.length>N.maxInputLength)return ln({kind:"program",dialect:"powershell",source:D,span:z,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${N.maxInputLength} UTF-16 code units`}],nodes:[]});let ee=ol(D,0,D.length,N,0);return ln({kind:"program",dialect:"powershell",source:D,span:z,status:nS(ee.issues,ee.limited),issues:ee.issues,nodes:ee.nodes})}function ol(D,N,z,ee,te,he=!1){let je=[],at=[],lt=zi(),ct=0,dt=!1,ft=()=>{if(lt.words.length===0&<.redirections.length===0)return;let mt={start:lt.start,end:lt.end};Bi(je,lt,{kind:"command",dialect:"powershell",source:D.slice(mt.start,mt.end),span:mt,words:lt.words,redirections:lt.redirections,nested:lt.nested,displayText:lt.words.map((gt)=>gt.text).join(" ")})},ut=N;while(ut<z){let mt=D[ut];if(!mt)break;if(he&&mt==="}")return ft(),{nodes:je,issues:at,next:ut+1,closed:!0,words:ct,limited:dt};let gt=tS(D,ut,z,ee.maxDepth);if(gt){if(gt.issue)at.push(gt.issue);if(gt.limited)return ft(),{nodes:je,issues:at,next:gt.next,closed:!1,words:ct,limited:!0};ut=gt.next;continue}if(/\s/.test(mt)){if(mt==="\r"||mt===`
|
|
20
20
|
`){ft();let yt=mt==="\r"&&D[ut+1]===`
|
|
21
21
|
`?ut+2:ut+1;je.push(el(D,ut,yt)),ut=yt;continue}ut++;continue}let pt=Id(D,ut);if(pt){ft(),je.push(el(D,ut,ut+pt.length)),ut+=pt.length;continue}if(mt==="{"){if(ft(),te>=ee.maxDepth)return at.push(Td(ee.maxDepth)),{nodes:je,issues:at,next:z,closed:!1,words:ct,limited:!0};let yt=ol(D,ut+1,z,ee,te+1,!0),vt=yt.closed?yt.next-1:yt.next,Et=ln({kind:"program",dialect:"powershell",source:D.slice(ut+1,vt),span:{start:ut+1,end:vt},status:yt.limited?"limited":yt.issues.length>0?"partial":"complete",issues:yt.issues,nodes:yt.nodes});if(je.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:ut,end:yt.next}),body:Et})),at.push(...yt.issues),!yt.closed)at.push({code:"unclosed-script-block",message:"PowerShell script block is not closed"});ct+=yt.words,dt||=yt.limited,ut=yt.next;continue}if(mt==="}"){ft(),je.push(el(D,ut,ut+1)),ut++;continue}if(mt===">"||mt==="<"){lt.start=lt.start===-1?ut:lt.start;let yt=D[ut+1]===mt?ut+2:ut+1,vt=yt;while(/[ \t]/.test(D[vt]??""))vt++;let Et=vt<z?xd(D,vt,z,ee,te):void 0,bt=Et?.next??yt;if(lt.redirections.push(Object.freeze({kind:"redirection",operator:D.slice(ut,yt),span:Object.freeze({start:ut,end:bt}),...Et?{target:Et.word}:{}})),Et)at.push(...Et.issues),lt.nested.push(...Et.nested),ct+=Et.words,dt||=Et.limited;lt.end=bt,ut=bt;continue}if(mt===","){lt.start=lt.start===-1?ut:lt.start,lt.words.push(Ka({text:",",raw:",",span:{start:ut,end:ut+1},provenance:"literal",quoted:!1})),lt.end=++ut;continue}let ht=xd(D,ut,z,ee,te);if(lt.start=lt.start===-1?ut:lt.start,lt.end=ht.next,lt.words.push(ht.word),at.push(...ht.issues),lt.nested.push(...ht.nested),ct+=1+ht.words,dt||=ht.limited,ct>ee.maxWords)return at.push({code:"word-limit",message:`command exceeds ${ee.maxWords} words`}),ft(),{nodes:je,issues:at,next:ht.next,closed:!1,words:ct,limited:!0};ut=ht.next>ut?ht.next:ut+1}return ft(),{nodes:je,issues:at,next:ut,closed:!he,words:ct,limited:dt}}function xd(D,N,z,ee,te){let he="",je="literal",at=!1,lt=[],ct=[],dt=0,ft=!1,ut=(gt)=>{let pt=Jb(D,gt,z,ee,te);return he+=D.slice(gt,pt.next),ct.push(pt.program),lt.push(...pt.program.issues),dt+=tl(pt.program),ft||=pt.program.status==="limited",je="command-substitution",pt.next},mt=N;while(mt<z){let gt=D[mt];if(!gt||/\s/.test(gt)||Id(D,mt)||gt===">"||gt==="<"||gt==="#")break;if(gt===",")break;if(gt==="`"){let pt=D[mt+1];if(!pt){lt.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),mt++;break}he+=pt,mt+=2;continue}if(D.startsWith("$(",mt)){mt=ut(mt);continue}if(gt==="'"){at=!0,mt++;let pt=!1;while(mt<D.length){if(D[mt]==="'"&&D[mt+1]==="'"){he+="'",mt+=2;continue}if(D[mt]==="'"){pt=!0,mt++;break}he+=D[mt]??"",mt++}if(!pt)lt.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(gt==='"'){at=!0,mt++;let pt=!1;while(mt<z){let ht=D[mt];if(ht==="`"&&D[mt+1]){he+=D[mt+1],mt+=2;continue}if(ht==='"'){pt=!0,mt++;break}if(D.startsWith("$(",mt)){mt=ut(mt);continue}if(ht==="$")je=D[mt+1]==="("?"command-substitution":"variable";he+=ht??"",mt++}if(!pt)lt.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(gt==="$")je=D[mt+1]==="("?"command-substitution":"variable";if(gt==="@"&&mt===N)je="variable";he+=gt,mt++}return{word:qr(D,N,mt,he,je,at,je==="literal"?void 0:Qb(D,N,mt)),next:mt,issues:lt,nested:ct,words:dt,limited:ft}}function Jb(D,N,z,ee,te){let he=Ad(D,N+2,z),je=he===-1?z:he,at=he===-1?z:he+1;if(te>=ee.maxDepth)return{program:ln({kind:"program",dialect:"powershell",source:D.slice(N+2,je),span:{start:N+2,end:je},status:"limited",issues:[Td(ee.maxDepth)],nodes:[]}),next:at};let lt=ol(D,N+2,je,ee,te+1),ct=he===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:ln({kind:"program",dialect:"powershell",source:D.slice(N+2,je),span:{start:N+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 Ad(D,N,z){let ee=1,te=!1,he=!1;for(let je=N;je<z;je++){let at=D[je];if(at==="`"){je++;continue}if(!he&&at==="'"){if(te&&D[je+1]==="'"){je++;continue}te=!te;continue}if(!te&&at==='"'){he=!he;continue}if(te)continue;if(D.startsWith("$(",je)){ee++,je++;continue}if(!he&&at==="(")ee++;if(at!==")")continue;if(ee--,ee===0)return je}return-1}function tl(D){let N=0;for(let z of D.nodes){if(z.kind==="group")N+=tl(z.body);if(z.kind==="command"){N+=z.words.length;for(let ee of z.nested)N+=tl(ee)}}return N}function Qb(D,N,z){let ee=$i(D),te=N,he=!1,je=N;while(je<z){let at=D[je];if(at==="`"){je+=2;continue}if(at==="'"){if(he&&D[je+1]==="'"){je+=2;continue}he=!he,je++;continue}if(he){je++;continue}if(D.startsWith("$(",je)){let lt=Ad(D,je+2,z),ct=lt===-1?z:lt+1;ee.push(te,je,"literal"),ee.push(je,ct,"command-substitution"),je=ct,te=ct;continue}if(at==="$"||at==="@"&&je===N){let lt=eS(D,je+1,z);ee.push(te,je,"literal"),ee.push(je,lt,"variable"),je=lt,te=lt;continue}je++}return ee.push(te,z,"literal"),ee.parts}function eS(D,N,z){if(D[N]==="{"){let te=D.indexOf("}",N+1);return te===-1||te>=z?z:te+1}let ee=N;while(ee<z&&/[A-Za-z0-9_:?]/.test(D[ee]??""))ee++;return ee}function Td(D){return{code:"depth-limit",message:`command structure exceeds parser limit ${D}`}}function nl(D){return D.nodes.flatMap((N)=>{if(N.kind==="group")return nl(N.body);if(N.kind!=="command")return[];return[[...N.words,...N.redirections.flatMap((z)=>z.target?[z.target]:[])].sort((z,ee)=>z.span.start-ee.span.start).filter((z)=>z.text!==""&&z.raw!==",").map((z)=>z.text),...N.nested.flatMap(nl)]})}function Id(D,N){for(let z of["&&","||",";","|"])if(D.startsWith(z,N))return z;return null}function tS(D,N,z,ee){if(D[N]==="#"&&D[N+1]!==">"){let je=N+1;while(je<z&&D[je]!=="\r"&&D[je]!==`
|
|
22
|
-
`)je++;return{next:je,limited:!1}}if(!D.startsWith("<#",N))return null;let te=1,he=N+2;while(he<z){if(D.startsWith("<#",he)){if(te++,te>ee)return{next:z,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${ee}`},limited:!0};he+=2;continue}if(D.startsWith("#>",he)){if(te--,he+=2,te===0)return{next:he,limited:!1};continue}he++}return{next:z,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function nS(D,N){if(N)return"limited";if(D.some((z)=>z.code==="unclosed-block-comment"))return"invalid";return D.length>0?"partial":"complete"}function el(D,N,z){return Object.freeze({kind:"connector",operator:D.slice(N,z),span:Object.freeze({start:N,end:z})})}function h(D,N="auto",z=ir){if(N==="powershell"||N==="auto"&&wd(D.slice(0,z.maxInputLength),z))return rl(D,z);return pd(D,z)}function t(D){return D.provenance==="command-substitution"?D.raw:D.text}function Q(D,N){return D==="posix"?N:$t(N.map((z)=>z.text))}function Zi(D,N){return D&&D.provenance!=="unknown"?D.provenance==="literal":!/[$`*?[\]]/.test(N)}function $t(D){return D.map((N)=>({kind:"word",text:N,raw:N,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function il(D,N){return{value:D,work:N}}function St(D,N){if(D.work)D.work.units=Math.min(Number.MAX_SAFE_INTEGER,D.work.units+1);return D.value[N]}function jt(D){return D.value.length}function Lo(D,N,z=1){if(D)D.units=Math.min(Number.MAX_SAFE_INTEGER,D.units+N.length*z)}function Sn(D,N){Lo(D,N)}function Rr(D){if(!D)return!1;let N=D.charCodeAt(0);return N>=48&&N<=57||N>=65&&N<=90||N===95||N>=97&&N<=122}function
|
|
23
|
-
`||D==="\r"||D==="\u2028"||D==="\u2029"}function
|
|
24
|
-
`||D===";"||D==="&"||D==="|"}function Zr(D){return D==="|"||D===";"}function Xi(D,N,z){let ee=il(D,z);if(N==="rm")return rS(ee);if(N==="dd")return iS(ee);return Ld(ee,!0)}function Ji(D,N,z){let ee=il(D,z);if(N==="rm")return sS(ee);if(N==="reset-hard")return Dd(ee,"--ha","rd");if(N==="reset-merge")return Dd(ee,"--me","rge");if(N==="clean")return uS(ee);if(N==="checkout")return fS(ee);if(N==="push-force")return mS(ee);if(N==="push-refspec")return pS(ee);if(N==="push-delete")return gS(ee);if(N==="branch")return hS(ee);if(N==="tag")return SS(ee);if(N==="restore")return CS(ee);return Ld(ee,!1)}function rS(D){let N=!1,z=!1,ee=!1,te=-1;for(let he=0;he<=jt(D);he++){let je=St(D,he);if(!N){let lt=St(D,he+2);if(Kn(D,he,"rm")&&
|
|
22
|
+
`)je++;return{next:je,limited:!1}}if(!D.startsWith("<#",N))return null;let te=1,he=N+2;while(he<z){if(D.startsWith("<#",he)){if(te++,te>ee)return{next:z,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${ee}`},limited:!0};he+=2;continue}if(D.startsWith("#>",he)){if(te--,he+=2,te===0)return{next:he,limited:!1};continue}he++}return{next:z,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function nS(D,N){if(N)return"limited";if(D.some((z)=>z.code==="unclosed-block-comment"))return"invalid";return D.length>0?"partial":"complete"}function el(D,N,z){return Object.freeze({kind:"connector",operator:D.slice(N,z),span:Object.freeze({start:N,end:z})})}function h(D,N="auto",z=ir){if(N==="powershell"||N==="auto"&&wd(D.slice(0,z.maxInputLength),z))return rl(D,z);return pd(D,z)}function t(D){return D.provenance==="command-substitution"?D.raw:D.text}function Q(D,N){return D==="posix"?N:$t(N.map((z)=>z.text))}function Zi(D,N){return D&&D.provenance!=="unknown"?D.provenance==="literal":!/[$`*?[\]]/.test(N)}function $t(D){return D.map((N)=>({kind:"word",text:N,raw:N,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function il(D,N){return{value:D,work:N}}function St(D,N){if(D.work)D.work.units=Math.min(Number.MAX_SAFE_INTEGER,D.work.units+1);return D.value[N]}function jt(D){return D.value.length}function Lo(D,N,z=1){if(D)D.units=Math.min(Number.MAX_SAFE_INTEGER,D.units+N.length*z)}function Sn(D,N){Lo(D,N)}function Rr(D){if(!D)return!1;let N=D.charCodeAt(0);return N>=48&&N<=57||N>=65&&N<=90||N===95||N>=97&&N<=122}function Gt(D){if(!D)return!1;let N=D.charCodeAt(0);return N===9||N===10||N===11||N===12||N===13||N===32||N===160||N===65279||N===5760||N>=8192&&N<=8202||N===8232||N===8233||N===8239||N===8287||N===12288}function sl(D){return D===`
|
|
23
|
+
`||D==="\r"||D==="\u2028"||D==="\u2029"}function Ft(D,N,z){if(N+z.length>jt(D))return!1;for(let ee=0;ee<z.length;ee++)if(St(D,N+ee)!==z[ee])return!1;return!0}function Kn(D,N,z){return!Rr(St(D,N-1))&&Ft(D,N,z)&&!Rr(St(D,N+z.length))}function qn(D,N){return Rr(St(D,N-1))!==Rr(St(D,N))}function Qt(D){return D===`
|
|
24
|
+
`||D===";"||D==="&"||D==="|"}function Zr(D){return D==="|"||D===";"}function Xi(D,N,z){let ee=il(D,z);if(N==="rm")return rS(ee);if(N==="dd")return iS(ee);return Ld(ee,!0)}function Ji(D,N,z){let ee=il(D,z);if(N==="rm")return sS(ee);if(N==="reset-hard")return Dd(ee,"--ha","rd");if(N==="reset-merge")return Dd(ee,"--me","rge");if(N==="clean")return uS(ee);if(N==="checkout")return fS(ee);if(N==="push-force")return mS(ee);if(N==="push-refspec")return pS(ee);if(N==="push-delete")return gS(ee);if(N==="branch")return hS(ee);if(N==="tag")return SS(ee);if(N==="restore")return CS(ee);return Ld(ee,!1)}function rS(D){let N=!1,z=!1,ee=!1,te=-1;for(let he=0;he<=jt(D);he++){let je=St(D,he);if(!N){let lt=St(D,he+2);if(Kn(D,he,"rm")&&Gt(lt)&<!==`
|
|
25
25
|
`)N=!0,he++;continue}let at=oS(D,he);if(je===`
|
|
26
|
-
`||at!==-1){if(N=!1,z=!1,ee=!1,te=-1,at!==-1)he=at-1;continue}if(je===";"||je==="&"||je==="|"||he===jt(D)){if(te>=0){let lt=kd(D,te,he);z||=lt.recursive,ee||=lt.force}if(z&&ee)return!0;N=!1,z=!1,ee=!1,te=-1;continue}if(
|
|
27
|
-
`,at++;if(lt)z=!1,ee=!1;N=!0,te=at;continue}if(!N){te++;continue}if(zt(D,te,"--")&&(te===0||Ft(St(D,te-1)))&&(!St(D,te+2)||Ft(St(D,te+2))||Qt(St(D,te+2)))){N=!1,z=!1,ee=!1,te+=2;continue}if(z||=zt(D,te,"--recursive")&&qn(D,te+11)||al(D,te,"recursive"),ee||=zt(D,te,"--force")&&qn(D,te+7)||al(D,te,"force"),z&&ee)return!0;te++}return!1}function al(D,N,z){if(!zt(D,N,"--"))return!1;let ee=0;while(ee<=z.length){let te=St(D,N+ee+2);if(!te||Ft(te)||Qt(te))break;if(te!==z[ee])return!1;ee++}return ee>0&&qn(D,N+ee+2)}function aS(D,N){let z=N,ee=!1,te=!1;while(z<jt(D)){while(Ft(St(D,z)))z++;let he=z;while(z<jt(D)&&!Ft(St(D,z)))z++;if(St(D,he)!=="-"||z-he===2&&zt(D,he,"--"))return!1;let je=Md(D,he,"recursive"),at=Md(D,he,"force");if(ee&&at||te&&je)return!0;if(ee||=je,te||=at,St(D,he+1)==="-")continue;let lt=cS(D,he,z);if(lt.combined||ee&<.forceAtBoundary||te&<.recursiveAtBoundary)return!0;ee||=lt.recursive,te||=lt.force}return!1}function Md(D,N,z){return zt(D,N,`--${z}`)&&qn(D,N+z.length+2)||al(D,N,z)}function lS(D,N){if(N>0&&Rr(St(D,N-1)))return-1;let z=N;if(St(D,z)==="\\")z++;if(St(D,z)!=="r")return-1;if(z++,St(D,z)==="\\")z++;if(St(D,z)!=="m"||!Ft(St(D,z+1)))return-1;return z+1}function cS(D,N,z){let ee=!1,te=!1,he=!1,je=!1,at=!1;if(St(D,N)!=="-")return{recursive:ee,force:te,recursiveAtBoundary:he,forceAtBoundary:je,combined:at};let lt="";for(let ct=N+1;ct<z;ct++){let dt=St(D,ct)??"",ft=(dt==="r"||dt==="f")&&qn(D,ct+1);ee||=dt==="r",te||=dt==="f",he||=dt==="r"&&ft,je||=dt==="f"&&ft,at||=(lt==="r"&&dt==="f"||lt==="f"&&dt==="r")&&ft,lt=dt}return{recursive:ee,force:te,recursiveAtBoundary:he,forceAtBoundary:je,combined:at}}function Dd(D,N,z){return Go(D,"reset",Zr,!0,(ee)=>St(D,ee)==="-"&&Xr(D,ee,N,z)?!0:ee)}function uS(D){return Go(D,"clean",Zr,!0,(N)=>{if(St(D,N)!=="-")return N;if(Xr(D,N,"--fo","rce"))return!0;let z=Wo(D,N,Zr);for(let ee=N+1;ee<z;ee++)if(St(D,ee)==="f")return!0;return z-1})}function Qi(D,N,z){if(!Kn(D,N,"git"))return null;let ee=N+3;if(!Ft(St(D,ee)))return{commandEnd:-1,next:ee};while(Ft(St(D,ee)))ee++;while(ee<jt(D)){if(Qt(St(D,ee)))return{commandEnd:-1,next:ee};let te=Wo(D,ee,Qt);if(Kn(D,ee,z))return{commandEnd:ee+z.length,next:te};if(St(D,ee)!=="-")return{commandEnd:-1,next:te};let he=te-ee===2&&zt(D,ee,"--"),je=dS(D,ee,te);ee=te;while(Ft(St(D,ee)))ee++;if(he)return{commandEnd:Kn(D,ee,z)?ee+z.length:-1,next:Wo(D,ee,Qt)};if(!je)continue;if(ee>=jt(D)||Qt(St(D,ee)))return{commandEnd:-1,next:ee};ee=Wo(D,ee,Qt);while(Ft(St(D,ee)))ee++}return{commandEnd:-1,next:ee}}function dS(D,N,z){for(let ee of hn)if(z-N===ee.length&&zt(D,N,ee))return!0;return!1}function fS(D){return Nd(D,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function mS(D){return Go(D,"push",Zr,!0,(N)=>{if(St(D,N)!=="-")return N;if(St(D,N+1)==="f"&&!Rr(St(D,N+2))&&!zt(D,N+2,"-with-lease"))return!0;let z=Wd(D,N,"--fo","rce");if(z>=0&&!zt(D,z,"-with-lease"))return!0;return N})}function pS(D){return Go(D,"push",Qt,!1,(N)=>{if(Ft(St(D,N))&&St(D,N+1)==="+"&&N+2<jt(D)&&!Qt(St(D,N+2))&&!Ft(St(D,N+2)))return!0;if(St(D,N)===":"&&St(D,N+1)==="+")return!0;return N})}function gS(D){return Go(D,"push",Qt,!1,(N)=>{if(St(D,N)==="-"&&Xr(D,N,"--de","lete"))return!0;if(Ft(St(D,N))&&St(D,N+1)===":"&&N+2<jt(D)&&!Ft(St(D,N+2))&&!Qt(St(D,N+2)))return!0;return N})}function hS(D){let N=!1,z=!1,ee=!1;for(let te=0;te<=jt(D);te++){if(te===jt(D)||Qt(St(D,te))){if(z&&ee)return!0;N=!1,z=!1,ee=!1;continue}if(!N){let at=Qi(D,te,"branch");if(at){N=at.commandEnd>=0,te=Math.max(te,(N?at.commandEnd:at.next)-1);continue}}if(!N||St(D,te)!=="-")continue;let he=Wo(D,te,Qt),je=yS(D,te,he);if(z||=je.deletion,ee||=je.force,z&&ee)return!0;te=he-1}return!1}function yS(D,N,z){let ee=!1,te=!1;for(let he=N;he<z;he++){if(St(D,he)!=="-")continue;if(Xr(D,he,"--de","lete"))ee=!0;if(Xr(D,he,"--fo","rce"))te=!0;if(St(D,he+1)==="-")continue;let je=he+1,at=!1,lt=!1,ct=!1;while(je<z&&bS(St(D,je))){let dt=St(D,je);at||=dt==="d"||dt==="D",lt||=dt==="f",ct||=dt==="D",je++}if(!qn(D,je))continue;ee||=at,te||=lt||ct}return{deletion:ee,force:te}}function bS(D){if(!D)return!1;let N=D.charCodeAt(0);return N>=65&&N<=90||N>=97&&N<=122}function SS(D){return Nd(D,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function Nd(D,N){let z=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let ee=0;ee<jt(D);ee++){let te=St(D,ee),he=z[z.length-1];if(!he)return!1;let je=he.escaped;if(he.escaped=!je&&he.quote!=="'"&&te==="\\",!je&&te==="'"&&he.quote!=='"')he.quote=he.quote==="'"?"":"'";if(!je&&te==='"'&&he.quote!=="'")he.quote=he.quote==='"'?"":'"';if(te==="$"&&St(D,ee+1)==="("&&(z.length===1||!je&&he.quote!=="'")){z.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),ee++;continue}if(!je&&!he.quote&&z.length>1&&te==="("){he.depth++;continue}if(!je&&!he.quote&&z.length>1&&te===")"){if(he.depth--,he.depth===0)z.pop();continue}if(Ft(te))he.shortActive=!1,he.hasShortFlag=!1;if(!he.outerActive){let at=Qi(D,ee,N.command);if(at){he.outerActive=at.commandEnd>=0&&Ft(St(D,at.commandEnd)),he.shortActive=!1,he.hasShortFlag=!1,ee=Math.max(ee,(he.outerActive?at.commandEnd:at.next)-1);continue}}if(he.outerActive&&te==="-"){if(Xr(D,ee,N.longPrefix,N.longOptional))return!0;he.shortActive||=!N.excludedShortStarts.includes(St(D,ee+1)??"")}if(he.hasShortFlag||=he.shortActive&&te===N.shortFlag,he.hasShortFlag&&qn(D,ee+1))return!0;if(Zr(te))he.outerActive=!1}return!1}function Go(D,N,z,ee,te){let he=!1;for(let je=0;je<jt(D);je++){let at=St(D,je),lt=z(at);if(!he&&!lt){let ct=Qi(D,je,N);if(ct){he=ct.commandEnd>=0&&(!ee||Ft(St(D,ct.commandEnd))),je=Math.max(je,(he?ct.commandEnd:ct.next)-1);continue}}if(he){let ct=te(je);if(ct===!0)return!0;for(let dt=je;dt<=ct;dt++)if(z(St(D,dt)))he=!1;je=ct}if(lt)he=!1}return!1}function CS(D){let N=!1;for(let z=0;z<jt(D);z++){if(sl(St(D,z))){if(N)return!0;N=!1;continue}if(!N){let ee=Qi(D,z,"restore");if(ee){N=ee.commandEnd>=0,z=Math.max(z,(N?ee.commandEnd:ee.next)-1);continue}}if(N&&St(D,z)==="-"&&St(D,z+1)==="-"&&(zt(D,z+2,"staged")||zt(D,z+2,"help")))N=!1}return N}function Ld(D,N){let z=!1;for(let ee=0;ee<jt(D);ee++){let te=St(D,ee),he=N?sl(te):Qt(te);if(z&&Ft(te)&&St(D,ee+1)==="-"&&Kn(D,ee+2,"delete"))return!0;if(he){z=!1;continue}if(Kn(D,ee,"find"))z=!0,ee+=3}return!1}function Wo(D,N,z){let ee=N;while(ee<jt(D)&&!Ft(St(D,ee))&&!z(St(D,ee)))ee++;return ee}function Wd(D,N,z,ee){if(!zt(D,N,z))return-1;let te=N+z.length;for(let he=0;he<ee.length&&St(D,te)===ee[he];he++)te++;return qn(D,te)?te:-1}function Xr(D,N,z,ee){return Wd(D,N,z,ee)>=0}function xn(D,N){Lo(N,D,2);let z=D.toLowerCase(),ee=z.trimStart(),te=ee.startsWith("echo ")||ee.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&&te)continue;let at=je.caseSensitive?D:z;if(je.regex)Sn(N,at);if((je.regex?.test(at)??!1)||je.scan&&Ji(at,je.scan,N))return Ct("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 vS=/^[A-Za-z_][A-Za-z0-9_]*=/;function Fd(D,N,z){let ee=D.words[0];if(!N||!ee||D.words.length!==1||D.dialect!=="posix")return!1;if(!ee.quoted||ee.provenance!=="literal")return!1;let te=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(ee.text)?.[1];if(!te)return!1;Lo(z,N.source,2);let he={anchored:new RegExp(`^\\$\\{?${te}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${te}(?![A-Za-z0-9_])`)};return zd(N.nodes,ee,he)}function zd(D,N,z){return D.every((ee)=>{if(ee.kind==="connector")return!0;if(ee.kind==="group"||ee.kind==="function")return zd(ee.body.nodes,N,z);if(ee.kind==="unknown")return!z.loose.test(ee.source);return ES(ee,N,z)})}function ES(D,N,z){if(D.nested.some((te)=>z.loose.test(te.source)))return!1;let ee=D.words.findIndex((te)=>!vS.test(te.text));return D.words.every((te,he)=>te===N||Gd(te.raw,z.anchored,he!==ee))&&D.redirections.every((te)=>(!te.heredoc||te.heredoc.quotedDelimiter||!z.loose.test(te.heredoc.body))&&(!te.target||Gd(te.target.raw,z.anchored,!0)))}function Gd(D,N,z){let ee=!1,te=!1;for(let he=0;he<D.length;he++){let je=D[he];if(je==="\\"&&!ee){he++;continue}if(!te&&je==="'"){ee=!ee;continue}if(!ee&&je==='"'){te=!te;continue}if(ee||je!=="$")continue;if(!N.test(D.slice(he)))continue;if(!te||!z)return!1}return!0}import{isAbsolute as xS,resolve as Bd}from"node:path";function Fo(D,N,z,ee){let te=xS(D)?Bd(D):N?Bd(N,D):void 0;if(!te)return;try{return Ot(te,z,ee)}catch{return te}}function $d(D){return!["/dev","/proc","/sys"].some((N)=>D===N||D.startsWith(`${N}/`))}var Jr="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",zo="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.",cl=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),RS=new Set(["-p","--print"]),_S=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),wS=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"])]]),PS=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),AS=new Map([["python",new Set(["m"])]]),TS=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"])]]),IS=new Set(["always","default","never"]),kS=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),OS=/\\\r?\n/g,MS=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 Ud(D){return ts(D).code}function es(D){return ts(D).sources}function Hd(D){return MS.get(dl(D))??[]}function ts(D){let N=dl(D[0]??"");if(!cl.has(N))return{code:null,sources:[],optionsOpen:!1};let z=[],ee=[],te=!0;for(let he=1;he<D.length;he++){let je=D[he];if(je===void 0)break;if(je==="--")return Tn(N,z,ee,te,D[he+1]===void 0?void 0:he+1,D[he+1]);if(je===""||je==="-"||!je.startsWith("-"))return Tn(N,z,ee,te,he,je);if(N==="node"&&RS.has(je)){let ft=D[he+1];if(ft===void 0)return Tn(N,z,ee,te);if(ft.startsWith("-"))continue;z.push({tokenIndex:he+1,value:ft}),ee.push({tokenIndex:he+1,kind:"inline-code",value:ft}),he++;continue}if(NS(N,je)){let ft=D[he+1];if(ft===void 0)return Tn(N,z,ee,te);if(z.push({tokenIndex:he+1,value:ft}),ee.push({tokenIndex:he+1,kind:"inline-code",value:ft}),N==="python")return Tn(N,z,ee,te);he++;continue}let at=/^--eval=(.*)$/s.exec(je);if(LS(N)&&at){let ft=at[1]??"";z.push({tokenIndex:he,value:ft}),ee.push({tokenIndex:he,kind:"inline-code",value:ft});continue}if(N==="node"){let ft=DS(je);if(ft){if(ft.attached){if(te&&=ft.value!=="",ft.value!=="")ee.push({tokenIndex:he,kind:"module-file",value:ft.value});continue}let ut=D[he+1];if(ut===void 0||ut.startsWith("-"))return te=!1,Tn(N,z,ee,te);ee.push({tokenIndex:he+1,kind:"module-file",value:ut}),he++;continue}}if(N==="python"&&je.startsWith("--check-hash-based-pycs=")||N==="node"&&(je==="--conditions="||je==="--diagnostic-dir="||je==="--title=")||N==="ruby"&&(je==="--disable="||je==="--enable="))return Tn(N,z,ee,te);if(TS.get(N)?.has(je)){let ft=D[he+1];if(ft===void 0||ft.startsWith("-")&&!(N==="ruby"&&kS.has(je))||N==="python"&&!IS.has(ft))return Tn(N,z,ee,te);he++;continue}if(je.startsWith("--"))continue;let lt,ct=!1;for(let ft=1;ft<je.length;ft++){let ut=je[ft];if(ut===void 0)break;if(AS.get(N)?.has(ut)){let mt=je.slice(ft+1),gt=mt||D[he+1];if(gt!==void 0)ee.push({tokenIndex:mt?he:he+1,kind:"module-file",value:gt});return Tn(N,z,ee,te)}if(_S.get(N)?.has(ut)){lt=je.slice(ft+1)||D[he+1],ct=ft+1===je.length;break}if(N==="node"&&ut==="r"){if(te&&=je==="-r",je==="-r"){let mt=D[he+1];if(te&&=mt!==void 0&&!mt.startsWith("-"),te&&mt!==void 0)ee.push({tokenIndex:he+1,kind:"module-file",value:mt});he++}break}if(N==="ruby"&&ut==="r"){let mt=je.slice(ft+1),gt=mt||D[he+1];if(te&&=gt!==void 0,gt!==void 0)ee.push({tokenIndex:mt?he:he+1,kind:"module-file",value:gt});if(!mt)he++;break}if(N==="perl"&&(ut==="M"||ut==="m")){let mt=je.slice(ft+1);if(!mt){if(te=!1,ft+1===je.length)he++;break}ee.push({tokenIndex:he,kind:"module-file",value:mt});break}if(wS.get(N)?.has(ut)){if(ft+1===je.length)he++;break}if(PS.get(N)?.has(ut)&&ft+1<je.length)break}if(lt===void 0)continue;let dt=ct?he+1:he;if(z.push({tokenIndex:dt,value:lt}),ee.push({tokenIndex:dt,kind:"inline-code",value:lt}),N==="python")return Tn(N,z,ee,te);if(ct)he++}return Tn(N,z,ee,te,void 0,void 0,!0)}function Tn(D,N,z,ee,te,he,je=!1){let at=D==="node"?N.slice(-1):N,lt=new Set(at.map((dt)=>dt.tokenIndex)),ct=z.filter((dt)=>dt.kind!=="inline-code"||lt.has(dt.tokenIndex));if(ee&&N.length===0&&te!==void 0&&he!==void 0)ct.push({tokenIndex:te,kind:"main-script",value:he});return{code:(D==="node"?at[0]?.value:at.map((dt)=>dt.value).join(`
|
|
28
|
-
`))||null,sources:ee?ct:[],optionsOpen:ee&&je}}function DS(D){for(let N of["--import","--loader","--experimental-loader","--require"]){if(D===N)return{attached:!1,value:""};if(D.startsWith(`${N}=`))return{attached:!0,value:D.slice(N.length+1)}}return}function ul(D,N){return dl(D)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(N)}function dl(D){let N=At(D).toLowerCase();return wi.test(N)?"python":N}function NS(D,N){return cl.get(D)?.has(N)??!1}function LS(D){return cl.get(D)?.has("--eval")??!1}function Bo(D,N,z=!1){let ee=FS(D,N);if(!ll(ee,N))return!1;Sn(N,ee);let te=GS(ee);if(ll(te,N))return!0;if(Sn(N,te),!jd.test(te))return!1;return!z||WS(ee,N)}function WS(D,N){if(/`|%x|\bqx\b/.test(D))return!0;let ee=D.split(""),te=[];for(let lt=0;lt<D.length;lt++){let ct=D[lt];if(ct!=="'"&&ct!=='"')continue;let dt=D.startsWith(ct.repeat(3),lt)?ct.repeat(3):ct,ft=lt+dt.length,ut=ft;while(ut<D.length&&!D.startsWith(dt,ut))ut+=D[ut]==="\\"?2:1;if(ut>=D.length)return!0;te.push({start:ft,text:D.slice(ft,ut)}),ee.fill(" ",lt,ut+dt.length),lt=ut+dt.length-1}let he=ee.join(""),je=Array.from(he.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((lt)=>jd.test(lt[1]??"")).map((lt)=>{let ct=lt.index+lt[0].length;return{start:ct,end:fl(he,ct)}});if(je.some((lt)=>ml(he,lt.start)))return!0;return te.some((lt)=>{let ct=/\b(?:system|exec|spawn|popen)\s*$/.test(he.slice(0,lt.start)),dt=je.some((ft)=>lt.start>=ft.start&<.start<ft.end);return(ct||dt)&&ll(lt.text,N)})}function fl(D,N){let z=1;for(let ee=N;ee<D.length;ee++){if(D[ee]==="(")z++;if(D[ee]===")")z--;if(z===0)return ee}return D.length}function ml(D,N){let z=0;for(let ee=N;ee<D.length;ee++){let te=D[ee]??"";if("([{".includes(te))z++;if(")]}".includes(te)&&z--===0)return!1;if(te===","&&z===0)return!1;if(/[A-Za-z_$]/.test(te))return!0}return!1}var jd=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function GS(D){let N=[],z=0,ee=0;while(ee<D.length){let te=D[ee];if(te!=="'"&&te!=='"'){ee++;continue}let he=D.startsWith(te.repeat(3),ee)?te.repeat(3):te,je=ee+he.length;while(je<D.length&&!D.startsWith(he,je))je+=D[je]==="\\"?2:1;if(je>=D.length)break;N.push(D.slice(z,ee)," "),ee=je+he.length,z=ee}return N.push(D.slice(z)),N.join("")}function ll(D,N){if(Xi(D,"rm",N))return!0;for(let ee of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(Sn(N,D),ee.test(D))return!0;if(Xi(D,"dd",N))return!0;for(let ee of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(Sn(N,D),ee.test(D))return!0;if(Xi(D,"find",N))return!0;let z=D.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((ee)=>(Sn(N,D),z.some((te)=>Ji(te,ee))))}function FS(D,N){return Sn(N,D),D.replace(OS,"")}import{lstatSync as LC,readdirSync as WC}from"node:fs";import{basename as GC,isAbsolute as yf,join as FC,relative as bf}from"node:path";import{isAbsolute as Jd,parse as YS}from"node:path";import{dirname as zS,isAbsolute as BS,parse as $S,sep as US}from"node:path";function sr(D,N,z){if(rr(N))throw Error("Unsupported Windows namespace path");let ee=BS(N)?$S(N).root:"",te=ee||D;for(let he of jS(ee?N.slice(ee.length):N)){if(he===""||he===".")continue;if(he===".."){te=zS(te);continue}let je=HS(te,he),at=z.entryKind(je),lt=at==="symlink"?z.realpath(je):je;if(at==="missing"||lt===null)throw Error(`Cannot resolve path component: ${je}`);te=lt}return te}function HS(D,N){return D.endsWith("/")||D.endsWith("\\")?`${D}${N}`:`${D}${US}${N}`}function jS(D){let N=process.platform==="win32"?/[\\/]+/:/\/+/;return D.split(N)}var pl=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],VS=new Set(pl),KS=1024,Vd=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),Kd=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),qS=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ns(D){return VS.has(D)}function gl(D){return ns(D)||Vd.has(D)||Kd.has(D)||Eo(D)}function Yn(D,N,z){return z?.has(D)?z.get(D):N.get(D)}function qd(D,N){let z=Yn("GIT_CONFIG_COUNT",D,N);if(z===void 0)return{state:"absent"};if(z==="")return{state:"valid",count:0};if(!/^\d+$/.test(z))return{state:"invalid"};let ee=Number(z);return Number.isSafeInteger(ee)&&ee<=KS?{state:"valid",count:ee}:{state:"invalid"}}function rs(D,N,z){let te=D.match(qS)?.[1];if(!te||!gl(te))return null;let he=D.indexOf("=");return{name:te,value:`${Yn(te,N,z)??""}${D.slice(he+1)}`}}function Yd(D){return Xd(D,Kd)}function Zd(D){return Xd(D,Vd)}function Xd(D,N){if(!D)return!1;for(let z of D.keys())if(N.has(z))return!0;return!1}var ef=/^[A-Za-z_][A-Za-z0-9_]*=/;function Rn(D){if(!ef.test(D))return null;let N=D.indexOf("=");return{name:D.slice(0,N),value:D.slice(N+1)}}function ge(D){let N=new Map,z=0;while(z<D.length){let ee=D[z];if(!ee)break;let te=Rn(t(ee));if(!te)break;N.set(te.name,te.value),z++}return{words:D.slice(z),envAssignments:N}}function tf(D){let N=It(D);return D.includes("=")||N==="sudo"||N==="env"||N==="command"||N==="builtin"}function _r(D,N,z,ee){if(!tf(Qr(D)))return{words:D,envAssignments:new Map,cwd:z,rewritten:!1};let te=new Set(D),he=D,je=new Map,at=new Map(ee??[]),lt=[],ct=z;for(let ft=0;ft<a.wrapperPeelIterations.cap;ft++){let ut=Qd(he),mt=ge(he);for(let[pt,ht]of mt.envAssignments)je.set(pt,ht),at.set(pt,ht);if(he=mt.words,he.length===0)break;while(he.length>0&&Qr(he).includes("=")&&!XS(he)){let pt=JS(Qr(he),at,N.env)??rs(Qr(he),N.env,at);if(pt)je.set(pt.name,pt.value),at.set(pt.name,pt.value);he=he.slice(1)}if(he.length===0)break;let gt=It(Qr(he));if(gt!=="sudo"&>!=="env"&>!=="command"&>!=="builtin")break;if(gt==="sudo"){let pt=eC(he,N.paths,ct);if(he=pt.words,pt.cwd!==void 0)ct=pt.cwd}if(gt==="env"){let pt=rC(he,ct,at,N);if(lt.push(...pt.envSplitValues??[]),he=pt.words,pt.cwd!==void 0)ct=pt.cwd;for(let[ht,yt]of pt.envAssignments)je.set(ht,yt),at.set(ht,yt)}if(gt==="command")he=oC(he);if(gt==="builtin")he=he.slice(In(he,1)==="--"?2:1);if(Qd(he)===ut)break}let dt=ge(he);for(let[ft,ut]of dt.envAssignments)je.set(ft,ut),at.set(ft,ut);return{words:dt.words,envAssignments:je,cwd:ct,envSplitValues:lt.length>0?lt:void 0,rewritten:ZS(dt.words,te)}}function ZS(D,N){return D.some((z)=>!N.has(z))}function Qd(D){return D.map(t).join(" ")}function Qr(D){let N=D[0];return N?t(N):""}function In(D,N){let z=D[N];return z?t(z):void 0}function XS(D){return ef.test(Qr(D))}function JS(D,N,z){if(!D.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${N.get("TMPDIR")??z.get("TMPDIR")??""}${D.slice(8)}`}}var QS=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function eC(D,N,z){let ee=1,te=z;while(ee<D.length){let he=In(D,ee);if(!he)break;if(he==="--")return{words:D.slice(ee+1),cwd:te};if(!he.startsWith("-"))break;if(he==="-D"||he==="--chdir"){let je=In(D,ee+1);te=je?$o(te,je,N):null,ee+=2;continue}if(he.startsWith("--chdir=")){te=$o(te,he.slice(8),N),ee++;continue}if(he.startsWith("-D")&&he.length>2){te=$o(te,he.slice(2),N),ee++;continue}if(he==="-i"||he==="--login"){te=null,ee++;continue}if(QS.has(he)){ee+=2;continue}ee++}return{words:D.slice(ee),cwd:te}}var tC=new Set(["-i","-0","--null"]),nC=new Set(["-u","--unset","-C","--chdir","-P"]);function rC(D,N,z,ee){let te=new Map,he=[],je=N,at=1,lt=(ct)=>({words:D.slice(ct),envAssignments:te,cwd:je,envSplitValues:he.length>0?he:void 0});while(at<D.length){let ct=In(D,at);if(!ct)break;if(ct==="--")return lt(at+1);if(ct==="-i"||ct==="--ignore-environment"||ct==="-"){te.clear();for(let ft of z.keys())te.set(ft,"");te.set("TMPDIR",""),at++;continue}if(tC.has(ct)){at++;continue}if(ct==="-u"||ct==="--unset"){let ft=In(D,at+1);if(ft!==void 0)te.set(ft,"");at+=2;continue}if(ct.startsWith("-u")&&ct.length>2&&!ct.startsWith("-u=")){te.set(ct.slice(2),""),at++;continue}if(ct.startsWith("--unset=")){te.set(ct.slice(8),""),at++;continue}let dt=ct==="-S"||ct==="--split-string"?{value:In(D,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(dt){if(dt.value!==void 0)he.push(dt.value);return je=null,lt(at+dt.consumed)}if(nC.has(ct)){if(ct==="-C"||ct==="--chdir"){let ft=In(D,at+1);je=ft?$o(je,ft,ee.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=$o(je,ft,ee.paths),at++;continue}if(ct.startsWith("-P")){at++;continue}if(ct.startsWith("-")){at++;continue}if(!Rn(ct))break;while(at<D.length){let ft=Rn(In(D,at)??"");if(!ft)break;te.set(ft.name,ft.value),at++}if(In(D,at)==="--")at++;return lt(at)}return lt(at)}function $o(D,N,z){if(N==="")return null;if(!D&&!Jd(N))return null;let ee=Jd(N)?YS(N).root:z.realpath(D??"/");if(ee===null)return null;try{return sr(ee,N,z)}catch{return null}}function oC(D){if(In(D,1)==="-v")return[...$t(["type"]),...D.slice(2)];let N=1;while(N<D.length){let z=In(D,N);if(!z)break;if(z==="-p"||z==="-v"||z==="-V"){N++;continue}if(z==="--")return D.slice(N+1);if(z.startsWith("-")&&!z.startsWith("--")&&z.length>1){if(!/^[pvV]+$/.test(z.slice(1)))break;N++;continue}break}return D.slice(N)}var iC=/['"\\$`{}#]/;function os(D,N){if(D.some((ee)=>iC.test(ee)))return null;let z=[...D.flatMap((ee)=>ee.split(/\s+/).filter((te)=>te.length>0)),...N];return z.length<=64?z:null}function ar(D,N,z){return is(D,N,z).tokens}function sC(D){let N=[],z="",ee=0;while(ee<D.length){let te=D.charAt(ee);if(te==='"'||te==="'"){let he=D.indexOf(te,ee+1);if(he===-1)return D.split(/\s+/).map((je)=>je.replace(/["']/g,"")).filter((je)=>je.length>0);z+=D.slice(ee+1,he),ee=he+1;continue}if(/\s/.test(te)){if(z.length>0)N.push(z);z="",ee++;continue}z+=te,ee++}if(z.length>0)N.push(z);return N}function lr(D,N,z,ee=0){let te=is(D,N,z),he=(te.envSplitValues??[]).flatMap(sC);if(he.length===0)return te.tokens;let je=[...he,...te.tokens];if(ee>=8)return je;return lr(je,N,z,ee+1)}function is(D,N,z,ee){if(!tf(D[0]??""))return{tokens:[...D],envAssignments:new Map,cwd:z};let te=_r($t(D),N,z,ee);return{tokens:te.words.map(t),envAssignments:te.envAssignments,cwd:te.cwd,envSplitValues:te.envSplitValues}}var Sl=Symbol("adopt-as-operand"),aC=new Set(["env","sudo","command","builtin"]),lC=new Set(["&&","||","|&","|","&",";"]),cC=new Set(["<<","<<<",">|"]),uC=new Set(["|","|&"]),dC=/[*@#?$!_-]/,fC=/^\w+(?::\w+)*/,mC=Object.freeze([]),Uo=Object.freeze({kind:"scope",edge:"enter"}),Ho=Object.freeze({kind:"scope",edge:"exit"}),pC=Object.freeze([]),gC=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),jo=new Set(["bash","sh","zsh","dash","ksh"]),hC=256,af=new WeakMap;function lf(D,N){let z=N.status==="complete"?new Set(bl(N)):new Set,ee=SC(D,z);if(Ai(ee))return ss("unclosed-quote",ee,N);let te={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},he=wr(N,{source:ee,suppressed:z,flags:te,depth:0,functions:new Map,powershell:N.dialect==="powershell"});if(te.limited)return ss("structural-limit",ee,N);if(te.invalid)return ss("invalid",ee,N);let je=ss("complete",ee,N,te.assignmentFallbacks);return af.set(je,Object.freeze(he)),je}function ls(D,N,z,ee,te){let he=te.word??((ft)=>ft),je={cwd:N,variables:new Map,previous:null},at=[],lt=new Set,ct=null,dt=[];for(let ft of cf(D)){if(ft.kind==="scope"){if(ft.edge==="enter"){dt.push({state:je,segment:[...at],shellWords:new Set(lt),pipeProducer:ct});continue}let ut=te.segment(at,je,ct,null,lt);if(ut)return ut;let mt=dt.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 ut=te.segment(at,je,ct,ft.operator,lt);if(ut)return ut;je=yC(at,je,z,ee),ct=at.length>0&&uC.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 ut=te.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(ut===Sl){lt.add(at.length),at.push(he(ft.target));continue}if(ut)return ut;continue}at.push(he(ft.text))}return te.segment(at,je,ct,null,lt)}function cs(D){return cf(D).flatMap((N)=>{if(N.kind==="word")return[{kind:"word",text:N.text}];if(N.kind==="operator")return[{kind:"operator",boundary:N.boundary}];if(N.kind==="redirection")return[{kind:"redirection",target:N.target}];return[]})}function cn(D,N){return D.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(z,ee,te,he)=>{let je=N.get(ee);if(je===void 0)return z;let at=te.startsWith(":")?je!=="":!0;if(te.endsWith("-"))return at?je:cn(he,N);return at?cn(he,N):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(z,ee)=>N.get(ee)??z).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(z,ee)=>N.get(ee)??z)}function Vo(D){return D.length>0&&D.every((N)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(N))}function yC(D,N,z,ee){let te=Vo(D)?new Map([...N.variables,...bC(D,N.variables)]):N.variables,he=ar([...D],z),je=At(he[0]??"").toLowerCase()==="cd"?he[1]:void 0;if(!je)return{...N,variables:te};if(je==="-"){if(N.previous===null)return{...N,variables:te};return{cwd:N.previous,variables:te,previous:N.cwd}}return{cwd:nn(cn(je,te),N.cwd,z,ee),variables:te,previous:N.cwd}}function bC(D,N){return D.flatMap((z)=>{let ee=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(z),te=ee?.[2]?.startsWith("=")?ee[2].slice(1):void 0;return ee?.[1]!==void 0&&te!==void 0?[[ee[1],cn(te,N)]]:[]})}function cf(D){return af.get(D)??mC}function SC(D,N){return[...N].reduce((z,ee)=>z.slice(0,ee.start)+" ".repeat(ee.end-ee.start)+z.slice(ee.end),D)}function ss(D,N,z,ee=pC){return Object.freeze({status:D,source:N,program:z,assignmentFallbacks:Object.freeze(ee)})}function wr(D,N){return D.nodes.flatMap((z,ee)=>CC(z,D,ee,N)).sort((z,ee)=>z.start-ee.start).flatMap((z)=>[...z.events])}function CC(D,N,z,ee){if(D.kind==="connector")return[{start:D.span.start,events:[kn(_C(D.operator))]}];if(D.kind==="unknown")return[{start:D.span.start,events:[kn(D.source)]}];if(D.kind==="function")return ee.functions.set(D.name,D.body),[];if(D.kind==="group"){let he=D.style!=="subshell",je=ee.source[D.span.end-1]===(he?"}":")"),at=he?ee:{...ee,functions:new Map(ee.functions)};return[{start:D.span.start,events:he?[as("{"),...wr(D.body,at),...je?[as("}")]:[]]:[Uo,kn("("),...wr(D.body,at),...je?[kn(")")]:[],Ho]}]}let te=TC(D,ee.functions);if(te){if(ee.depth>=ir.maxDepth||++ee.flags.expansions>hC)return ee.flags.limited=!0,[];return[{start:D.span.start,events:[...nf(D,ee),as(";"),...wr(te,{...ee,depth:ee.depth+1}),as(";")]},...rf(D,N,z,ee)]}return[{start:D.span.start,events:nf(D,ee)},...rf(D,N,z,ee)]}function nf(D,N){return[...D.words.map((z)=>({start:z.span.start,events:df(z,D,N,!1)})),...D.redirections.map((z)=>({start:z.span.start,events:vC(z,D,N)}))].sort((z,ee)=>z.start-ee.start).flatMap((z)=>z.events)}function vC(D,N,z){let ee=D.operator==="<<-"?"<<":D.operator,te=D.target?df(D.target,N,z,!0):[],he=te[0],je=he?.kind==="word"?he.text:void 0;return[...D.fd===void 0?[]:[Cl(String(D.fd))],Object.freeze({kind:"redirection",operator:ee,...D.fd===void 0?{}:{fd:D.fd},role:wC(ee),targetOrder:cC.has(ee)?"legacy-segment":"immediate",...je===void 0?{}:{target:je},...D.heredoc&&z.suppressed.has(D.heredoc.bodySpan)?{body:D.heredoc.body,consumer:mf(N)}:{}}),...je===void 0?te:te.slice(1)]}function rf(D,N,z,ee){let te=D.redirections.filter((he)=>he.operator==="<<"||he.operator==="<<-");return[...te.flatMap((he)=>{let je=he.heredoc;if(!je)return[];let at=[Cl(je.delimiter),.../[\r\n]/.test(ee.source[je.terminatorSpan.end]??"")?[kn(";")]:[]];if(ee.suppressed.has(je.bodySpan))return[{start:je.bodySpan.start,events:at}];return[{start:je.bodySpan.start,events:[...uf(ee.source.slice(je.bodySpan.start,je.bodySpan.end),ee),...at]}]}),...te.some((he)=>!he.heredoc&&he.target)?EC(N,z,ee):[]]}function EC(D,N,z){let ee=D.nodes.slice(N+1).find((te)=>te.kind==="connector");if(!ee||ee.span.end>=D.span.end)return[];return[{start:ee.span.end,events:uf(z.source.slice(ee.span.end,D.span.end),z)}]}function uf(D,N){if(N.depth>=ir.maxDepth)return N.flags.limited=!0,[];let z=h(D,"posix");if(z.status==="limited")return N.flags.limited=!0,[];let ee={invalid:!1,limited:!1,expansions:N.flags.expansions,assignmentFallbacks:N.flags.assignmentFallbacks},te=wr(z,{source:D,suppressed:new Set,flags:ee,depth:N.depth+1,functions:new Map,powershell:!1});return N.flags.limited||=ee.limited,N.flags.expansions=ee.expansions,te}function df(D,N,z,ee){let te=[],he={single:!1,double:!1},je="",at=!1,lt=()=>{let ct=at&&!ee?kn("glob"):je!==""||D.quoted&&te.length===0?Cl(je):void 0;if(ct)te.push(ct);je="",at=!1};for(let ct of D.parts){if(ct.provenance!=="command-substitution"&&ct.provenance!=="arithmetic"){for(let mt of hl(ct.raw,he,z.flags,z.powershell)){if(typeof mt==="string"){lt(),te.push(kn(mt));continue}je+=mt.text,at||=mt.glob}continue}let dt=N.nested.find((mt)=>mt.span.start>=ct.span.start&&mt.span.end<=ct.span.end);if(he.double){let mt=z.source.slice(ct.span.start,ct.span.end);je+=hl(mt,{single:!1,double:!0},z.flags,z.powershell).map((pt)=>typeof pt==="string"?pt:pt.text).join("");let gt=dt?wr(dt,z).filter((pt)=>pt.kind==="redirection"&&pt.body!==void 0):[];if(gt.length>0)te.push(Uo,...gt,Ho);continue}let ft=dt?wr(dt,z):[];if(ct.raw.startsWith("`")){je+="${}",lt(),te.push(Uo,...ft,Ho);continue}if(ct.raw.startsWith("<(")||ct.raw.startsWith(">(")){lt(),te.push(ct.raw.startsWith("<(")?kn("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),Uo,...ft,...ct.raw.endsWith(")")?[kn(")")]:[],Ho);continue}let ut=ct.raw.startsWith("$((")?2:1;je+="${}",lt(),te.push(...Array.from({length:ut},()=>kn("(")),...ut===1?[Uo]:[],...ft,...ct.raw.endsWith(")".repeat(ut))?Array.from({length:ut},()=>kn(")")):[],...ut===1?[Ho]:[])}return lt(),te}function hl(D,N,z,ee){let te=[],he="",je=!1,at=0;while(at<D.length){let lt=D[at]??"";if(!N.single&&!N.double&&(lt==="("||lt===")")){te.push({text:he,glob:je},lt),he="",je=!1,at++;continue}if(ee&<==="`"&&!N.single){he+=D[at+1]??"",at+=2;continue}if(N.single&<==="'"){N.single=!1,at++;continue}if(N.single){he+=lt,at++;continue}if(N.double){if(lt==='"'){N.double=!1,at++;continue}if(!ee&<==="\\"){let ct=D[at+1]??"";he+=['"',"\\","$"].includes(ct)?ct:`\\${ct}`,at+=2;continue}if(lt==="$"){let ct=of(D,at,N,z,ee);he+=ct.text,at=ct.next;continue}he+=lt,at++;continue}if(lt==="'"||lt==='"'){N.single=lt==="'",N.double=lt==='"',at++;continue}if(!ee&<==="\\"){let ct=D[at+1]??"";je||=ct==="*"||ct==="?",he+=ct,at+=2;continue}if(lt==="$"){let ct=of(D,at,N,z,ee);he+=ct.text,at=ct.next;continue}je||=lt==="*"||lt==="?",he+=lt,at++}return[...te,{text:he,glob:je}]}function of(D,N,z,ee,te){let he=D[N+1];if(he==="{"){let at=RC(D,N+2);if(at===-1)return ee.invalid=!0,{text:"",next:D.length};let lt=D.slice(N,at+1);return xC(lt,z,ee,te),{text:lt,next:at+1}}if(he!==void 0&&dC.test(he))return{text:`\${${he}}`,next:N+2};let je=(te?fC:/^\w*/).exec(D.slice(N+1))?.[0]??"";return{text:`\${${je}}`,next:N+1+je.length}}function xC(D,N,z,ee){let te=D.slice(2,-1),he=/^[A-Za-z_][A-Za-z0-9_]*/.exec(te)?.[0];if(!he)return;let je=te.slice(he.length),at=[":=","="].find((ct)=>je.startsWith(ct));if(!at)return;let lt=hl(je.slice(at.length),{...N},z,ee);z.assignmentFallbacks.push(...lt.flatMap((ct)=>typeof ct==="string"||!ct.text?[]:[ct.text]))}function RC(D,N){let z=1,ee=N;while(z>0&&ee<D.length){if(D[ee]==="{"&&D[ee-1]==="$")z++;if(D[ee]==="}")z--;ee++}return z===0?ee-1:-1}function _C(D){return/^[\r\n]+$/.test(D)?";":D}function kn(D){return Object.freeze({kind:"operator",operator:D,boundary:lC.has(D)})}function as(D){return Object.freeze({kind:"operator",operator:D,boundary:!0})}function Cl(D){return Object.freeze({kind:"word",text:D})}function wC(D){if(D==="<<"||D==="<<<")return"here-data";if(D==="<"||D==="<&")return"file-read";return"file-write"}function Ko(D){return gC.has(D)||/^python\d/.test(D)}var PC=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 ff(D,N){let z=N[0];if(z===void 0||!z.startsWith("-"))return N;let ee=PC.get(D)?.has(z)??!1;return ff(D,N.slice(ee?2:1))}function yl(D){let N=D[0];if(N===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(N))return yl(D.slice(1));if(!aC.has(N))return[...D];return yl(ff(N,D.slice(1)))}function mf(D){let N=Mo(D),z=D.words.findIndex((ee)=>ee.provenance==="literal"&&ee.text===N);return yl(z<0?[]:D.words.slice(z).map((ee)=>ee.text))}function AC(D){let N=mf(D)[0];if(N===void 0)return!1;let z=At(N).toLowerCase();return Ko(z)&&!jo.has(z)}function bl(D){return D.nodes.flatMap((N,z)=>{if(N.kind==="group"||N.kind==="function")return bl(N.body);if(N.kind!=="command")return[];let ee=N.nested.flatMap((at)=>bl(at)),te=N.redirections.flatMap((at)=>at.heredoc?.quotedDelimiter?[at.heredoc.bodySpan]:[]);if(AC(N))return[...ee,...te];let he=D.nodes[z+1];if(he?.kind==="connector"&&(he.operator==="|"||he.operator==="|&")||!kC(N))return ee;return[...ee,...te]})}function TC(D,N){let z=Mo(D);return z===void 0?void 0:N.get(z)}function cr(D,N){return D!==void 0&&D.provenance==="literal"&&!D.quoted&&D.raw===D.text&&D.text===N}function IC(D){if(cr(D.words[0],"git"))return cr(D.words[1],"commit");if(!cr(D.words[0],"gh")||!cr(D.words[2],"create"))return!1;return cr(D.words[1],"pr")||cr(D.words[1],"issue")}function kC(D){return(cr(D.words[0],"cat")||cr(D.words[0],"tee")||IC(D))&&!D.words.some(sf)&&!D.redirections.some((z)=>sf(z.target))}function sf(D){return D?.parts.some((N)=>N.provenance==="command-substitution"&&N.raw.startsWith(">("))??!1}var pf=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),gf=new Set([...pf,"glob"]),OC=new Set([...gf,"pattern"]);class y extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function qo(D){let N=MC(),z=ne(D.input),ee=[];if((D.route.kind==="command"||D.route.kind==="unknown")&&z)ee.push({usage:"input-candidate",source:z});if(D.route.kind==="command"&&"command"in D&&D.command)ee.push({usage:"declared-command",source:D.command});let te=ee.reduce((he,je)=>{let at=he.findIndex((dt)=>dt.source===je.source);if(at!==-1){let dt=he[at];if(!dt)return he;return he[at]={...dt,usages:[...dt.usages,je.usage]},he}let lt=D.route.kind==="command"?D.route.shell:process.platform==="win32"?"powershell":"posix",ct=N.getCommandProgram(je.source,lt);return he.push({usages:[je.usage],source:je.source,program:ct,shell:N.getShellSyntax(je.source,ct)}),he},[]);return{invocation:{toolName:D.toolName,route:D.route,context:D.context},commands:te,paths:DC(D),store:N}}function un(D,N){return D.commands.find((z)=>z.usages.includes(N))}function Zn(D,N){if(!D.includes("$"))return D;return ta(D,N)}function MC(){let D=new Map,N=new Map,z=new WeakMap,ee=(he,je)=>{let at=`${je}\x00${he}`,lt=N.get(at);if(lt)return lt;let ct=h(he,je);return N.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??ee(he,"posix");if(at.status==="limited"){let dt=z.get(at);if(dt)return dt;let ft={status:"structural-limit",source:he,program:at,assignmentFallbacks:[]};return z.set(at,ft),ft}let lt=D.get(he);if(lt)return lt;let ct=lf(he,at);return D.set(he,ct),ct},getCommandProgram:ee}}function DC(D){let N=D.route.kind==="grep"?gf:D.route.kind==="glob"?OC:pf;return[...Qc(D.input,N),...D.route.kind==="patch"?nu(D.input):[]]}var NC=new Set(["-S","--suffix"]);function eo(D,N,z,ee,te){if(D.status==="structural-limit")throw new y;if(D.status!=="complete")return te.findMalformedTarget(D.source);return ls(D,N,z,ee,{segment:(he,je)=>te.findSegmentTarget(he,je),redirection:(he,je)=>he.role==="file-write"&&te.isRedirectionTarget(cn(he.target,je.variables),je)?he.target:null})}function us(D){let N=[],z=null,ee=!1;for(let te=0;te<D.length;te++){let he=D[te];if(he===void 0)break;if(!ee&&he==="--"){ee=!0;continue}if(!ee&&(he==="-t"||he==="--target-directory")){z=D[++te]??null;continue}if(!ee&&he.startsWith("--target-directory=")){z=he.slice(19);continue}if(!ee&&he.startsWith("-t")&&he.length>2){z=he.slice(2);continue}if(!ee&&NC.has(he)){te++;continue}if(!ee&&(he.startsWith("--suffix=")||he.startsWith("--backup=")))continue;if(!ee&&he.startsWith("-"))continue;N.push(he)}return z?{sources:N,destination:z}:{sources:N.slice(0,-1),destination:N.at(-1)??null}}var x="Git metadata and hooks are protected. Ask the user before modifying them.";function Sf(D,N,z,ee){let te=D.invocation.context.executionCwd;if(!N)return null;if(D.invocation.route.kind==="patch"||D.invocation.route.kind==="path"||D.invocation.route.kind==="unknown"){if(Si(D.invocation.toolName))return null;let at=D.paths.find((lt)=>hf(lt,te,N,z,ee,N.entries));return at?{target:at}:null}if(D.invocation.route.kind!=="command")return null;let he=un(D,"input-candidate");if(!he)return null;let je=eo(he.shell,te,z,ee,{findSegmentTarget:(at,lt)=>jC(at,lt,N,z,ee),isRedirectionTarget:(at,lt)=>hf(at,lt.cwd,N,z,ee,N.markerFiles),findMalformedTarget:()=>null});return je?{target:je}:null}function Pr(D,N,z,ee,te,he,je=!1){if(!z)return!1;let at=fs(nn(D,N,te,he)),lt=at.replace(/(\/\.?\*+)+$/,"");if(lt!==at&<!==""){if(vl(lt,z))return!0;let ct=je||at.slice(lt.length).includes("/."),dt=(ft)=>ct?ds(ft,lt):zC(ft,lt);if(z.markerFiles.some(dt))return!0;return ee&&El(z).some(dt)}if(vl(at,z))return!0;return ee&&El(z).some((ct)=>ds(ct,at))}function zC(D,N){let z=bf(N,D);if(z===""||z.startsWith("..")||yf(z))return!1;return!z.split(/[\\/]/)[0]?.startsWith(".")}function BC(D,N,z,ee,te){return Pr(D,N,z,!0,ee,te)}function $C(D,N,z,ee,te){if(!z)return!1;return vl(fs(nn(D,N,ee,te)),z)}function hf(D,N,z,ee,te,he){let je=fs(nn(D,N,ee,te));return he.includes(je)||vf(je,z)}function Cf(D,N,z,ee,te){if(!z)return!1;return z.hooksDirectories.some((he)=>D.some((je)=>ds(he,fs(nn(je,N,ee,te)))))}function vl(D,N){return N.entries.includes(D)||N.directories.includes(D)||vf(D,N)}function vf(D,N){return N.hooksDirectories.some((z)=>ds(D,z))}var UC=50000;function Ef(D,N){let z=[...new Set(El(D))];if(z.some((te)=>N(GC(te))))return!0;let ee=0;while(z.length>0){let te=z.pop()??"",he=HC(te);if(!he)return!0;if(ee+=he.length,ee>UC)return!0;if(he.some((je)=>N(je.name)))return!0;z.push(...he.filter((je)=>je.isDirectory()).map((je)=>FC(te,je.name)))}return!1}function HC(D){try{let N=LC(D,{throwIfNoEntry:!1});if(!N)return[];if(!N.isDirectory())return N.isSymbolicLink()?null:[];return WC(D,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function El(D){return[...D.entries,...D.directories,...D.hooksDirectories]}function ds(D,N){let z=bf(N,D);return z===""||!/^\.\.(?:[\\/]|$)/.test(z)&&!yf(z)}function fs(D){return process.platform==="win32"?D.toLowerCase():D}function jC(D,N,z,ee,te){if(Vo(D))return null;let he=lr([...D],ee);if(At(he[0]??"").toLowerCase()!=="mv")return null;let je=us(he.slice(1)),at=je.sources.find((lt)=>BC(cn(lt,N.variables),N.cwd,z,ee,te));if(at)return at;return je.destination&&$C(cn(je.destination,N.variables),N.cwd,z,ee,te)?je.destination:null}import{isAbsolute as hs,normalize as QC,parse as ev,posix as If,resolve as Tr,sep as wl}from"node:path";import{isAbsolute as VC,join as xf,normalize as wf,parse as KC,sep as Rf}from"node:path";var qC=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],YC=`
|
|
26
|
+
`||at!==-1){if(N=!1,z=!1,ee=!1,te=-1,at!==-1)he=at-1;continue}if(je===";"||je==="&"||je==="|"||he===jt(D)){if(te>=0){let lt=kd(D,te,he);z||=lt.recursive,ee||=lt.force}if(z&&ee)return!0;N=!1,z=!1,ee=!1,te=-1;continue}if(Gt(je)){if(te<0)continue;if(Ft(D,te,"--")&&he-te===2){N=!1,z=!1,ee=!1,te=-1;continue}let lt=kd(D,te,he);if(z||=lt.recursive,ee||=lt.force,z&&ee)return!0;te=-1;continue}if(te<0)te=he}return!1}function oS(D,N){if(St(D,N)!=="\\"||St(D,N-1)==="\\")return-1;if(Ft(D,N,String.raw`\n`))return N+2;if(Ft(D,N,String.raw`\x0a`)||Ft(D,N,String.raw`\x0A`))return N+5;if(Ft(D,N,String.raw`\u000a`)||Ft(D,N,String.raw`\u000A`))return N+7;return Ft(D,N,String.raw`\012`)?N+4:-1}function kd(D,N,z){if(Od(D,N,z,"recursive"))return{recursive:!0,force:!1};if(Od(D,N,z,"force"))return{recursive:!1,force:!0};if(St(D,N)!=="-"||St(D,N+1)==="-")return{recursive:!1,force:!1};let ee=!1,te=!1;for(let he=N+1;he<z;he++){let je=St(D,he);ee||=je==="r"||je==="R",te||=je==="f"||je==="F"}return{recursive:ee,force:te}}function Od(D,N,z,ee){let te=z-N-2;if(te<1||te>ee.length||!Ft(D,N,"--"))return!1;for(let he=0;he<te;he++)if(St(D,N+he+2)!==ee[he])return!1;return!0}function iS(D){let N=!1;for(let z=0;z<jt(D);z++){if(Qt(St(D,z))){N=!1;continue}if(Kn(D,z,"dd")){N=!0,z++;continue}if(!N||!Kn(D,z,"of")||!Ft(D,z,"of=/dev/"))continue;let ee=z+8;if(ee<jt(D)&&!Gt(St(D,ee))&&St(D,ee)!=="'"&&St(D,ee)!=='"')return!0}return!1}function sS(D){let N=!1,z=!1,ee=!1;for(let te=0;te<=jt(D);){let he=St(D,te);if(te===jt(D)||Qt(he)){N=!1,z=!1,ee=!1,te++;continue}let je=lS(D,te);if(je>=0){if(aS(D,je))return!0;let at=je,lt=!1;while(Gt(St(D,at)))lt||=St(D,at)===`
|
|
27
|
+
`,at++;if(lt)z=!1,ee=!1;N=!0,te=at;continue}if(!N){te++;continue}if(Ft(D,te,"--")&&(te===0||Gt(St(D,te-1)))&&(!St(D,te+2)||Gt(St(D,te+2))||Qt(St(D,te+2)))){N=!1,z=!1,ee=!1,te+=2;continue}if(z||=Ft(D,te,"--recursive")&&qn(D,te+11)||al(D,te,"recursive"),ee||=Ft(D,te,"--force")&&qn(D,te+7)||al(D,te,"force"),z&&ee)return!0;te++}return!1}function al(D,N,z){if(!Ft(D,N,"--"))return!1;let ee=0;while(ee<=z.length){let te=St(D,N+ee+2);if(!te||Gt(te)||Qt(te))break;if(te!==z[ee])return!1;ee++}return ee>0&&qn(D,N+ee+2)}function aS(D,N){let z=N,ee=!1,te=!1;while(z<jt(D)){while(Gt(St(D,z)))z++;let he=z;while(z<jt(D)&&!Gt(St(D,z)))z++;if(St(D,he)!=="-"||z-he===2&&Ft(D,he,"--"))return!1;let je=Md(D,he,"recursive"),at=Md(D,he,"force");if(ee&&at||te&&je)return!0;if(ee||=je,te||=at,St(D,he+1)==="-")continue;let lt=cS(D,he,z);if(lt.combined||ee&<.forceAtBoundary||te&<.recursiveAtBoundary)return!0;ee||=lt.recursive,te||=lt.force}return!1}function Md(D,N,z){return Ft(D,N,`--${z}`)&&qn(D,N+z.length+2)||al(D,N,z)}function lS(D,N){if(N>0&&Rr(St(D,N-1)))return-1;let z=N;if(St(D,z)==="\\")z++;if(St(D,z)!=="r")return-1;if(z++,St(D,z)==="\\")z++;if(St(D,z)!=="m"||!Gt(St(D,z+1)))return-1;return z+1}function cS(D,N,z){let ee=!1,te=!1,he=!1,je=!1,at=!1;if(St(D,N)!=="-")return{recursive:ee,force:te,recursiveAtBoundary:he,forceAtBoundary:je,combined:at};let lt="";for(let ct=N+1;ct<z;ct++){let dt=St(D,ct)??"",ft=(dt==="r"||dt==="f")&&qn(D,ct+1);ee||=dt==="r",te||=dt==="f",he||=dt==="r"&&ft,je||=dt==="f"&&ft,at||=(lt==="r"&&dt==="f"||lt==="f"&&dt==="r")&&ft,lt=dt}return{recursive:ee,force:te,recursiveAtBoundary:he,forceAtBoundary:je,combined:at}}function Dd(D,N,z){return Go(D,"reset",Zr,!0,(ee)=>St(D,ee)==="-"&&Xr(D,ee,N,z)?!0:ee)}function uS(D){return Go(D,"clean",Zr,!0,(N)=>{if(St(D,N)!=="-")return N;if(Xr(D,N,"--fo","rce"))return!0;let z=Wo(D,N,Zr);for(let ee=N+1;ee<z;ee++)if(St(D,ee)==="f")return!0;return z-1})}function Qi(D,N,z){if(!Kn(D,N,"git"))return null;let ee=N+3;if(!Gt(St(D,ee)))return{commandEnd:-1,next:ee};while(Gt(St(D,ee)))ee++;while(ee<jt(D)){if(Qt(St(D,ee)))return{commandEnd:-1,next:ee};let te=Wo(D,ee,Qt);if(Kn(D,ee,z))return{commandEnd:ee+z.length,next:te};if(St(D,ee)!=="-")return{commandEnd:-1,next:te};let he=te-ee===2&&Ft(D,ee,"--"),je=dS(D,ee,te);ee=te;while(Gt(St(D,ee)))ee++;if(he)return{commandEnd:Kn(D,ee,z)?ee+z.length:-1,next:Wo(D,ee,Qt)};if(!je)continue;if(ee>=jt(D)||Qt(St(D,ee)))return{commandEnd:-1,next:ee};ee=Wo(D,ee,Qt);while(Gt(St(D,ee)))ee++}return{commandEnd:-1,next:ee}}function dS(D,N,z){for(let ee of hn)if(z-N===ee.length&&Ft(D,N,ee))return!0;return!1}function fS(D){return Nd(D,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function mS(D){return Go(D,"push",Zr,!0,(N)=>{if(St(D,N)!=="-")return N;if(St(D,N+1)==="f"&&!Rr(St(D,N+2))&&!Ft(D,N+2,"-with-lease"))return!0;let z=Wd(D,N,"--fo","rce");if(z>=0&&!Ft(D,z,"-with-lease"))return!0;return N})}function pS(D){return Go(D,"push",Qt,!1,(N)=>{if(Gt(St(D,N))&&St(D,N+1)==="+"&&N+2<jt(D)&&!Qt(St(D,N+2))&&!Gt(St(D,N+2)))return!0;if(St(D,N)===":"&&St(D,N+1)==="+")return!0;return N})}function gS(D){return Go(D,"push",Qt,!1,(N)=>{if(St(D,N)==="-"&&Xr(D,N,"--de","lete"))return!0;if(Gt(St(D,N))&&St(D,N+1)===":"&&N+2<jt(D)&&!Gt(St(D,N+2))&&!Qt(St(D,N+2)))return!0;return N})}function hS(D){let N=!1,z=!1,ee=!1;for(let te=0;te<=jt(D);te++){if(te===jt(D)||Qt(St(D,te))){if(z&&ee)return!0;N=!1,z=!1,ee=!1;continue}if(!N){let at=Qi(D,te,"branch");if(at){N=at.commandEnd>=0,te=Math.max(te,(N?at.commandEnd:at.next)-1);continue}}if(!N||St(D,te)!=="-")continue;let he=Wo(D,te,Qt),je=yS(D,te,he);if(z||=je.deletion,ee||=je.force,z&&ee)return!0;te=he-1}return!1}function yS(D,N,z){let ee=!1,te=!1;for(let he=N;he<z;he++){if(St(D,he)!=="-")continue;if(Xr(D,he,"--de","lete"))ee=!0;if(Xr(D,he,"--fo","rce"))te=!0;if(St(D,he+1)==="-")continue;let je=he+1,at=!1,lt=!1,ct=!1;while(je<z&&bS(St(D,je))){let dt=St(D,je);at||=dt==="d"||dt==="D",lt||=dt==="f",ct||=dt==="D",je++}if(!qn(D,je))continue;ee||=at,te||=lt||ct}return{deletion:ee,force:te}}function bS(D){if(!D)return!1;let N=D.charCodeAt(0);return N>=65&&N<=90||N>=97&&N<=122}function SS(D){return Nd(D,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function Nd(D,N){let z=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let ee=0;ee<jt(D);ee++){let te=St(D,ee),he=z[z.length-1];if(!he)return!1;let je=he.escaped;if(he.escaped=!je&&he.quote!=="'"&&te==="\\",!je&&te==="'"&&he.quote!=='"')he.quote=he.quote==="'"?"":"'";if(!je&&te==='"'&&he.quote!=="'")he.quote=he.quote==='"'?"":'"';if(te==="$"&&St(D,ee+1)==="("&&(z.length===1||!je&&he.quote!=="'")){z.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),ee++;continue}if(!je&&!he.quote&&z.length>1&&te==="("){he.depth++;continue}if(!je&&!he.quote&&z.length>1&&te===")"){if(he.depth--,he.depth===0)z.pop();continue}if(Gt(te))he.shortActive=!1,he.hasShortFlag=!1;if(!he.outerActive){let at=Qi(D,ee,N.command);if(at){he.outerActive=at.commandEnd>=0&&Gt(St(D,at.commandEnd)),he.shortActive=!1,he.hasShortFlag=!1,ee=Math.max(ee,(he.outerActive?at.commandEnd:at.next)-1);continue}}if(he.outerActive&&te==="-"){if(Xr(D,ee,N.longPrefix,N.longOptional))return!0;he.shortActive||=!N.excludedShortStarts.includes(St(D,ee+1)??"")}if(he.hasShortFlag||=he.shortActive&&te===N.shortFlag,he.hasShortFlag&&qn(D,ee+1))return!0;if(Zr(te))he.outerActive=!1}return!1}function Go(D,N,z,ee,te){let he=!1;for(let je=0;je<jt(D);je++){let at=St(D,je),lt=z(at);if(!he&&!lt){let ct=Qi(D,je,N);if(ct){he=ct.commandEnd>=0&&(!ee||Gt(St(D,ct.commandEnd))),je=Math.max(je,(he?ct.commandEnd:ct.next)-1);continue}}if(he){let ct=te(je);if(ct===!0)return!0;for(let dt=je;dt<=ct;dt++)if(z(St(D,dt)))he=!1;je=ct}if(lt)he=!1}return!1}function CS(D){let N=!1;for(let z=0;z<jt(D);z++){if(sl(St(D,z))){if(N)return!0;N=!1;continue}if(!N){let ee=Qi(D,z,"restore");if(ee){N=ee.commandEnd>=0,z=Math.max(z,(N?ee.commandEnd:ee.next)-1);continue}}if(N&&St(D,z)==="-"&&St(D,z+1)==="-"&&(Ft(D,z+2,"staged")||Ft(D,z+2,"help")))N=!1}return N}function Ld(D,N){let z=!1;for(let ee=0;ee<jt(D);ee++){let te=St(D,ee),he=N?sl(te):Qt(te);if(z&&Gt(te)&&St(D,ee+1)==="-"&&Kn(D,ee+2,"delete"))return!0;if(he){z=!1;continue}if(Kn(D,ee,"find"))z=!0,ee+=3}return!1}function Wo(D,N,z){let ee=N;while(ee<jt(D)&&!Gt(St(D,ee))&&!z(St(D,ee)))ee++;return ee}function Wd(D,N,z,ee){if(!Ft(D,N,z))return-1;let te=N+z.length;for(let he=0;he<ee.length&&St(D,te)===ee[he];he++)te++;return qn(D,te)?te:-1}function Xr(D,N,z,ee){return Wd(D,N,z,ee)>=0}function xn(D,N){Lo(N,D,2);let z=D.toLowerCase(),ee=z.trimStart(),te=ee.startsWith("echo ")||ee.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&&te)continue;let at=je.caseSensitive?D:z;if(je.regex)Sn(N,at);if((je.regex?.test(at)??!1)||je.scan&&Ji(at,je.scan,N))return Ct("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 vS=/^[A-Za-z_][A-Za-z0-9_]*=/;function Fd(D,N,z){let ee=D.words[0];if(!N||!ee||D.words.length!==1||D.dialect!=="posix")return!1;if(!ee.quoted||ee.provenance!=="literal")return!1;let te=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(ee.text)?.[1];if(!te)return!1;Lo(z,N.source,2);let he={anchored:new RegExp(`^\\$\\{?${te}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${te}(?![A-Za-z0-9_])`)};return zd(N.nodes,ee,he)}function zd(D,N,z){return D.every((ee)=>{if(ee.kind==="connector")return!0;if(ee.kind==="group"||ee.kind==="function")return zd(ee.body.nodes,N,z);if(ee.kind==="unknown")return!z.loose.test(ee.source);return ES(ee,N,z)})}function ES(D,N,z){if(D.nested.some((te)=>z.loose.test(te.source)))return!1;let ee=D.words.findIndex((te)=>!vS.test(te.text));return D.words.every((te,he)=>te===N||Gd(te.raw,z.anchored,he!==ee))&&D.redirections.every((te)=>(!te.heredoc||te.heredoc.quotedDelimiter||!z.loose.test(te.heredoc.body))&&(!te.target||Gd(te.target.raw,z.anchored,!0)))}function Gd(D,N,z){let ee=!1,te=!1;for(let he=0;he<D.length;he++){let je=D[he];if(je==="\\"&&!ee){he++;continue}if(!te&&je==="'"){ee=!ee;continue}if(!ee&&je==='"'){te=!te;continue}if(ee||je!=="$")continue;if(!N.test(D.slice(he)))continue;if(!te||!z)return!1}return!0}import{isAbsolute as xS,resolve as Bd}from"node:path";function Fo(D,N,z,ee){let te=xS(D)?Bd(D):N?Bd(N,D):void 0;if(!te)return;try{return Ot(te,z,ee)}catch{return te}}function $d(D){return!["/dev","/proc","/sys"].some((N)=>D===N||D.startsWith(`${N}/`))}var Jr="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",zo="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.",cl=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),RS=new Set(["-p","--print"]),_S=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),wS=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"])]]),PS=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),AS=new Map([["python",new Set(["m"])]]),TS=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"])]]),IS=new Set(["always","default","never"]),kS=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),OS=/\\\r?\n/g,MS=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 Ud(D){return ts(D).code}function es(D){return ts(D).sources}function Hd(D){return MS.get(dl(D))??[]}function ts(D){let N=dl(D[0]??"");if(!cl.has(N))return{code:null,sources:[],optionsOpen:!1};let z=[],ee=[],te=!0;for(let he=1;he<D.length;he++){let je=D[he];if(je===void 0)break;if(je==="--")return Tn(N,z,ee,te,D[he+1]===void 0?void 0:he+1,D[he+1]);if(je===""||je==="-"||!je.startsWith("-"))return Tn(N,z,ee,te,he,je);if(N==="node"&&RS.has(je)){let ft=D[he+1];if(ft===void 0)return Tn(N,z,ee,te);if(ft.startsWith("-"))continue;z.push({tokenIndex:he+1,value:ft}),ee.push({tokenIndex:he+1,kind:"inline-code",value:ft}),he++;continue}if(NS(N,je)){let ft=D[he+1];if(ft===void 0)return Tn(N,z,ee,te);if(z.push({tokenIndex:he+1,value:ft}),ee.push({tokenIndex:he+1,kind:"inline-code",value:ft}),N==="python")return Tn(N,z,ee,te);he++;continue}let at=/^--eval=(.*)$/s.exec(je);if(LS(N)&&at){let ft=at[1]??"";z.push({tokenIndex:he,value:ft}),ee.push({tokenIndex:he,kind:"inline-code",value:ft});continue}if(N==="node"){let ft=DS(je);if(ft){if(ft.attached){if(te&&=ft.value!=="",ft.value!=="")ee.push({tokenIndex:he,kind:"module-file",value:ft.value});continue}let ut=D[he+1];if(ut===void 0||ut.startsWith("-"))return te=!1,Tn(N,z,ee,te);ee.push({tokenIndex:he+1,kind:"module-file",value:ut}),he++;continue}}if(N==="python"&&je.startsWith("--check-hash-based-pycs=")||N==="node"&&(je==="--conditions="||je==="--diagnostic-dir="||je==="--title=")||N==="ruby"&&(je==="--disable="||je==="--enable="))return Tn(N,z,ee,te);if(TS.get(N)?.has(je)){let ft=D[he+1];if(ft===void 0||ft.startsWith("-")&&!(N==="ruby"&&kS.has(je))||N==="python"&&!IS.has(ft))return Tn(N,z,ee,te);he++;continue}if(je.startsWith("--"))continue;let lt,ct=!1;for(let ft=1;ft<je.length;ft++){let ut=je[ft];if(ut===void 0)break;if(AS.get(N)?.has(ut)){let mt=je.slice(ft+1),gt=mt||D[he+1];if(gt!==void 0)ee.push({tokenIndex:mt?he:he+1,kind:"module-file",value:gt});return Tn(N,z,ee,te)}if(_S.get(N)?.has(ut)){lt=je.slice(ft+1)||D[he+1],ct=ft+1===je.length;break}if(N==="node"&&ut==="r"){if(te&&=je==="-r",je==="-r"){let mt=D[he+1];if(te&&=mt!==void 0&&!mt.startsWith("-"),te&&mt!==void 0)ee.push({tokenIndex:he+1,kind:"module-file",value:mt});he++}break}if(N==="ruby"&&ut==="r"){let mt=je.slice(ft+1),gt=mt||D[he+1];if(te&&=gt!==void 0,gt!==void 0)ee.push({tokenIndex:mt?he:he+1,kind:"module-file",value:gt});if(!mt)he++;break}if(N==="perl"&&(ut==="M"||ut==="m")){let mt=je.slice(ft+1);if(!mt){if(te=!1,ft+1===je.length)he++;break}ee.push({tokenIndex:he,kind:"module-file",value:mt});break}if(wS.get(N)?.has(ut)){if(ft+1===je.length)he++;break}if(PS.get(N)?.has(ut)&&ft+1<je.length)break}if(lt===void 0)continue;let dt=ct?he+1:he;if(z.push({tokenIndex:dt,value:lt}),ee.push({tokenIndex:dt,kind:"inline-code",value:lt}),N==="python")return Tn(N,z,ee,te);if(ct)he++}return Tn(N,z,ee,te,void 0,void 0,!0)}function Tn(D,N,z,ee,te,he,je=!1){let at=D==="node"?N.slice(-1):N,lt=new Set(at.map((dt)=>dt.tokenIndex)),ct=z.filter((dt)=>dt.kind!=="inline-code"||lt.has(dt.tokenIndex));if(ee&&N.length===0&&te!==void 0&&he!==void 0)ct.push({tokenIndex:te,kind:"main-script",value:he});return{code:(D==="node"?at[0]?.value:at.map((dt)=>dt.value).join(`
|
|
28
|
+
`))||null,sources:ee?ct:[],optionsOpen:ee&&je}}function DS(D){for(let N of["--import","--loader","--experimental-loader","--require"]){if(D===N)return{attached:!1,value:""};if(D.startsWith(`${N}=`))return{attached:!0,value:D.slice(N.length+1)}}return}function ul(D,N){return dl(D)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(N)}function dl(D){let N=At(D).toLowerCase();return wi.test(N)?"python":N}function NS(D,N){return cl.get(D)?.has(N)??!1}function LS(D){return cl.get(D)?.has("--eval")??!1}function Bo(D,N,z=!1){let ee=FS(D,N);if(!ll(ee,N))return!1;Sn(N,ee);let te=GS(ee);if(ll(te,N))return!0;if(Sn(N,te),!jd.test(te))return!1;return!z||WS(ee,N)}function WS(D,N){if(/`|%x|\bqx\b/.test(D))return!0;let ee=D.split(""),te=[];for(let lt=0;lt<D.length;lt++){let ct=D[lt];if(ct!=="'"&&ct!=='"')continue;let dt=D.startsWith(ct.repeat(3),lt)?ct.repeat(3):ct,ft=lt+dt.length,ut=ft;while(ut<D.length&&!D.startsWith(dt,ut))ut+=D[ut]==="\\"?2:1;if(ut>=D.length)return!0;te.push({start:ft,text:D.slice(ft,ut)}),ee.fill(" ",lt,ut+dt.length),lt=ut+dt.length-1}let he=ee.join(""),je=Array.from(he.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((lt)=>jd.test(lt[1]??"")).map((lt)=>{let ct=lt.index+lt[0].length;return{start:ct,end:fl(he,ct)}});if(je.some((lt)=>ml(he,lt.start)))return!0;return te.some((lt)=>{let ct=/\b(?:system|exec|spawn|popen)\s*$/.test(he.slice(0,lt.start)),dt=je.some((ft)=>lt.start>=ft.start&<.start<ft.end);return(ct||dt)&&ll(lt.text,N)})}function fl(D,N){let z=1;for(let ee=N;ee<D.length;ee++){if(D[ee]==="(")z++;if(D[ee]===")")z--;if(z===0)return ee}return D.length}function ml(D,N){let z=0;for(let ee=N;ee<D.length;ee++){let te=D[ee]??"";if("([{".includes(te))z++;if(")]}".includes(te)&&z--===0)return!1;if(te===","&&z===0)return!1;if(/[A-Za-z_$]/.test(te))return!0}return!1}var jd=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function GS(D){let N=[],z=0,ee=0;while(ee<D.length){let te=D[ee];if(te!=="'"&&te!=='"'){ee++;continue}let he=D.startsWith(te.repeat(3),ee)?te.repeat(3):te,je=ee+he.length;while(je<D.length&&!D.startsWith(he,je))je+=D[je]==="\\"?2:1;if(je>=D.length)break;N.push(D.slice(z,ee)," "),ee=je+he.length,z=ee}return N.push(D.slice(z)),N.join("")}function ll(D,N){if(Xi(D,"rm",N))return!0;for(let ee of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(Sn(N,D),ee.test(D))return!0;if(Xi(D,"dd",N))return!0;for(let ee of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(Sn(N,D),ee.test(D))return!0;if(Xi(D,"find",N))return!0;let z=D.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((ee)=>(Sn(N,D),z.some((te)=>Ji(te,ee))))}function FS(D,N){return Sn(N,D),D.replace(OS,"")}import{lstatSync as LC,readdirSync as WC}from"node:fs";import{basename as GC,isAbsolute as yf,join as FC,relative as bf}from"node:path";import{isAbsolute as Jd,parse as YS}from"node:path";import{dirname as zS,isAbsolute as BS,parse as $S,sep as US}from"node:path";function sr(D,N,z){if(rr(N))throw Error("Unsupported Windows namespace path");let ee=BS(N)?$S(N).root:"",te=ee||D;for(let he of jS(ee?N.slice(ee.length):N)){if(he===""||he===".")continue;if(he===".."){te=zS(te);continue}let je=HS(te,he),at=z.entryKind(je),lt=at==="symlink"?z.realpath(je):je;if(at==="missing"||lt===null)throw Error(`Cannot resolve path component: ${je}`);te=lt}return te}function HS(D,N){return D.endsWith("/")||D.endsWith("\\")?`${D}${N}`:`${D}${US}${N}`}function jS(D){let N=process.platform==="win32"?/[\\/]+/:/\/+/;return D.split(N)}var pl=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],VS=new Set(pl),KS=1024,Vd=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),Kd=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),qS=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ns(D){return VS.has(D)}function gl(D){return ns(D)||Vd.has(D)||Kd.has(D)||Eo(D)}function Yn(D,N,z){return z?.has(D)?z.get(D):N.get(D)}function qd(D,N){let z=Yn("GIT_CONFIG_COUNT",D,N);if(z===void 0)return{state:"absent"};if(z==="")return{state:"valid",count:0};if(!/^\d+$/.test(z))return{state:"invalid"};let ee=Number(z);return Number.isSafeInteger(ee)&&ee<=KS?{state:"valid",count:ee}:{state:"invalid"}}function rs(D,N,z){let te=D.match(qS)?.[1];if(!te||!gl(te))return null;let he=D.indexOf("=");return{name:te,value:`${Yn(te,N,z)??""}${D.slice(he+1)}`}}function Yd(D){return Xd(D,Kd)}function Zd(D){return Xd(D,Vd)}function Xd(D,N){if(!D)return!1;for(let z of D.keys())if(N.has(z))return!0;return!1}var ef=/^[A-Za-z_][A-Za-z0-9_]*=/;function Rn(D){if(!ef.test(D))return null;let N=D.indexOf("=");return{name:D.slice(0,N),value:D.slice(N+1)}}function ge(D){let N=new Map,z=0;while(z<D.length){let ee=D[z];if(!ee)break;let te=Rn(t(ee));if(!te)break;N.set(te.name,te.value),z++}return{words:D.slice(z),envAssignments:N}}function tf(D){let N=It(D);return D.includes("=")||N==="sudo"||N==="env"||N==="command"||N==="builtin"}function _r(D,N,z,ee){if(!tf(Qr(D)))return{words:D,envAssignments:new Map,cwd:z,rewritten:!1};let te=new Set(D),he=D,je=new Map,at=new Map(ee??[]),lt=[],ct=z;for(let ft=0;ft<a.wrapperPeelIterations.cap;ft++){let ut=Qd(he),mt=ge(he);for(let[pt,ht]of mt.envAssignments)je.set(pt,ht),at.set(pt,ht);if(he=mt.words,he.length===0)break;while(he.length>0&&Qr(he).includes("=")&&!XS(he)){let pt=JS(Qr(he),at,N.env)??rs(Qr(he),N.env,at);if(pt)je.set(pt.name,pt.value),at.set(pt.name,pt.value);he=he.slice(1)}if(he.length===0)break;let gt=It(Qr(he));if(gt!=="sudo"&>!=="env"&>!=="command"&>!=="builtin")break;if(gt==="sudo"){let pt=eC(he,N.paths,ct);if(he=pt.words,pt.cwd!==void 0)ct=pt.cwd}if(gt==="env"){let pt=rC(he,ct,at,N);if(lt.push(...pt.envSplitValues??[]),he=pt.words,pt.cwd!==void 0)ct=pt.cwd;for(let[ht,yt]of pt.envAssignments)je.set(ht,yt),at.set(ht,yt)}if(gt==="command")he=oC(he);if(gt==="builtin")he=he.slice(In(he,1)==="--"?2:1);if(Qd(he)===ut)break}let dt=ge(he);for(let[ft,ut]of dt.envAssignments)je.set(ft,ut),at.set(ft,ut);return{words:dt.words,envAssignments:je,cwd:ct,envSplitValues:lt.length>0?lt:void 0,rewritten:ZS(dt.words,te)}}function ZS(D,N){return D.some((z)=>!N.has(z))}function Qd(D){return D.map(t).join(" ")}function Qr(D){let N=D[0];return N?t(N):""}function In(D,N){let z=D[N];return z?t(z):void 0}function XS(D){return ef.test(Qr(D))}function JS(D,N,z){if(!D.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${N.get("TMPDIR")??z.get("TMPDIR")??""}${D.slice(8)}`}}var QS=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function eC(D,N,z){let ee=1,te=z;while(ee<D.length){let he=In(D,ee);if(!he)break;if(he==="--")return{words:D.slice(ee+1),cwd:te};if(!he.startsWith("-"))break;if(he==="-D"||he==="--chdir"){let je=In(D,ee+1);te=je?$o(te,je,N):null,ee+=2;continue}if(he.startsWith("--chdir=")){te=$o(te,he.slice(8),N),ee++;continue}if(he.startsWith("-D")&&he.length>2){te=$o(te,he.slice(2),N),ee++;continue}if(he==="-i"||he==="--login"){te=null,ee++;continue}if(QS.has(he)){ee+=2;continue}ee++}return{words:D.slice(ee),cwd:te}}var tC=new Set(["-i","-0","--null"]),nC=new Set(["-u","--unset","-C","--chdir","-P"]);function rC(D,N,z,ee){let te=new Map,he=[],je=N,at=1,lt=(ct)=>({words:D.slice(ct),envAssignments:te,cwd:je,envSplitValues:he.length>0?he:void 0});while(at<D.length){let ct=In(D,at);if(!ct)break;if(ct==="--")return lt(at+1);if(ct==="-i"||ct==="--ignore-environment"||ct==="-"){te.clear();for(let ft of z.keys())te.set(ft,"");te.set("TMPDIR",""),at++;continue}if(tC.has(ct)){at++;continue}if(ct==="-u"||ct==="--unset"){let ft=In(D,at+1);if(ft!==void 0)te.set(ft,"");at+=2;continue}if(ct.startsWith("-u")&&ct.length>2&&!ct.startsWith("-u=")){te.set(ct.slice(2),""),at++;continue}if(ct.startsWith("--unset=")){te.set(ct.slice(8),""),at++;continue}let dt=ct==="-S"||ct==="--split-string"?{value:In(D,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(dt){if(dt.value!==void 0)he.push(dt.value);return je=null,lt(at+dt.consumed)}if(nC.has(ct)){if(ct==="-C"||ct==="--chdir"){let ft=In(D,at+1);je=ft?$o(je,ft,ee.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=$o(je,ft,ee.paths),at++;continue}if(ct.startsWith("-P")){at++;continue}if(ct.startsWith("-")){at++;continue}if(!Rn(ct))break;while(at<D.length){let ft=Rn(In(D,at)??"");if(!ft)break;te.set(ft.name,ft.value),at++}if(In(D,at)==="--")at++;return lt(at)}return lt(at)}function $o(D,N,z){if(N==="")return null;if(!D&&!Jd(N))return null;let ee=Jd(N)?YS(N).root:z.realpath(D??"/");if(ee===null)return null;try{return sr(ee,N,z)}catch{return null}}function oC(D){if(In(D,1)==="-v")return[...$t(["type"]),...D.slice(2)];let N=1;while(N<D.length){let z=In(D,N);if(!z)break;if(z==="-p"||z==="-v"||z==="-V"){N++;continue}if(z==="--")return D.slice(N+1);if(z.startsWith("-")&&!z.startsWith("--")&&z.length>1){if(!/^[pvV]+$/.test(z.slice(1)))break;N++;continue}break}return D.slice(N)}var iC=/['"\\$`{}#]/;function os(D,N){if(D.some((ee)=>iC.test(ee)))return null;let z=[...D.flatMap((ee)=>ee.split(/\s+/).filter((te)=>te.length>0)),...N];return z.length<=64?z:null}function ar(D,N,z){return is(D,N,z).tokens}function sC(D){let N=[],z="",ee=0;while(ee<D.length){let te=D.charAt(ee);if(te==='"'||te==="'"){let he=D.indexOf(te,ee+1);if(he===-1)return D.split(/\s+/).map((je)=>je.replace(/["']/g,"")).filter((je)=>je.length>0);z+=D.slice(ee+1,he),ee=he+1;continue}if(/\s/.test(te)){if(z.length>0)N.push(z);z="",ee++;continue}z+=te,ee++}if(z.length>0)N.push(z);return N}function lr(D,N,z,ee=0){let te=is(D,N,z),he=(te.envSplitValues??[]).flatMap(sC);if(he.length===0)return te.tokens;let je=[...he,...te.tokens];if(ee>=8)return je;return lr(je,N,z,ee+1)}function is(D,N,z,ee){if(!tf(D[0]??""))return{tokens:[...D],envAssignments:new Map,cwd:z};let te=_r($t(D),N,z,ee);return{tokens:te.words.map(t),envAssignments:te.envAssignments,cwd:te.cwd,envSplitValues:te.envSplitValues}}var Sl=Symbol("adopt-as-operand"),aC=new Set(["env","sudo","command","builtin"]),lC=new Set(["&&","||","|&","|","&",";"]),cC=new Set(["<<","<<<",">|"]),uC=new Set(["|","|&"]),dC=/[*@#?$!_-]/,fC=/^\w+(?::\w+)*/,mC=Object.freeze([]),Uo=Object.freeze({kind:"scope",edge:"enter"}),Ho=Object.freeze({kind:"scope",edge:"exit"}),pC=Object.freeze([]),gC=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),jo=new Set(["bash","sh","zsh","dash","ksh"]),hC=256,af=new WeakMap;function lf(D,N){let z=N.status==="complete"?new Set(bl(N)):new Set,ee=SC(D,z);if(Ai(ee))return ss("unclosed-quote",ee,N);let te={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},he=wr(N,{source:ee,suppressed:z,flags:te,depth:0,functions:new Map,powershell:N.dialect==="powershell"});if(te.limited)return ss("structural-limit",ee,N);if(te.invalid)return ss("invalid",ee,N);let je=ss("complete",ee,N,te.assignmentFallbacks);return af.set(je,Object.freeze(he)),je}function ls(D,N,z,ee,te){let he=te.word??((ft)=>ft),je={cwd:N,variables:new Map,previous:null},at=[],lt=new Set,ct=null,dt=[];for(let ft of cf(D)){if(ft.kind==="scope"){if(ft.edge==="enter"){dt.push({state:je,segment:[...at],shellWords:new Set(lt),pipeProducer:ct});continue}let ut=te.segment(at,je,ct,null,lt);if(ut)return ut;let mt=dt.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 ut=te.segment(at,je,ct,ft.operator,lt);if(ut)return ut;je=yC(at,je,z,ee),ct=at.length>0&&uC.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 ut=te.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(ut===Sl){lt.add(at.length),at.push(he(ft.target));continue}if(ut)return ut;continue}at.push(he(ft.text))}return te.segment(at,je,ct,null,lt)}function cs(D){return cf(D).flatMap((N)=>{if(N.kind==="word")return[{kind:"word",text:N.text}];if(N.kind==="operator")return[{kind:"operator",boundary:N.boundary}];if(N.kind==="redirection")return[{kind:"redirection",target:N.target}];return[]})}function cn(D,N){return D.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(z,ee,te,he)=>{let je=N.get(ee);if(je===void 0)return z;let at=te.startsWith(":")?je!=="":!0;if(te.endsWith("-"))return at?je:cn(he,N);return at?cn(he,N):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(z,ee)=>N.get(ee)??z).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(z,ee)=>N.get(ee)??z)}function Vo(D){return D.length>0&&D.every((N)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(N))}function yC(D,N,z,ee){let te=Vo(D)?new Map([...N.variables,...bC(D,N.variables)]):N.variables,he=ar([...D],z),je=At(he[0]??"").toLowerCase()==="cd"?he[1]:void 0;if(!je)return{...N,variables:te};if(je==="-"){if(N.previous===null)return{...N,variables:te};return{cwd:N.previous,variables:te,previous:N.cwd}}return{cwd:nn(cn(je,te),N.cwd,z,ee),variables:te,previous:N.cwd}}function bC(D,N){return D.flatMap((z)=>{let ee=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(z),te=ee?.[2]?.startsWith("=")?ee[2].slice(1):void 0;return ee?.[1]!==void 0&&te!==void 0?[[ee[1],cn(te,N)]]:[]})}function cf(D){return af.get(D)??mC}function SC(D,N){return[...N].reduce((z,ee)=>z.slice(0,ee.start)+" ".repeat(ee.end-ee.start)+z.slice(ee.end),D)}function ss(D,N,z,ee=pC){return Object.freeze({status:D,source:N,program:z,assignmentFallbacks:Object.freeze(ee)})}function wr(D,N){return D.nodes.flatMap((z,ee)=>CC(z,D,ee,N)).sort((z,ee)=>z.start-ee.start).flatMap((z)=>[...z.events])}function CC(D,N,z,ee){if(D.kind==="connector")return[{start:D.span.start,events:[kn(_C(D.operator))]}];if(D.kind==="unknown")return[{start:D.span.start,events:[kn(D.source)]}];if(D.kind==="function")return ee.functions.set(D.name,D.body),[];if(D.kind==="group"){let he=D.style!=="subshell",je=ee.source[D.span.end-1]===(he?"}":")"),at=he?ee:{...ee,functions:new Map(ee.functions)};return[{start:D.span.start,events:he?[as("{"),...wr(D.body,at),...je?[as("}")]:[]]:[Uo,kn("("),...wr(D.body,at),...je?[kn(")")]:[],Ho]}]}let te=TC(D,ee.functions);if(te){if(ee.depth>=ir.maxDepth||++ee.flags.expansions>hC)return ee.flags.limited=!0,[];return[{start:D.span.start,events:[...nf(D,ee),as(";"),...wr(te,{...ee,depth:ee.depth+1}),as(";")]},...rf(D,N,z,ee)]}return[{start:D.span.start,events:nf(D,ee)},...rf(D,N,z,ee)]}function nf(D,N){return[...D.words.map((z)=>({start:z.span.start,events:df(z,D,N,!1)})),...D.redirections.map((z)=>({start:z.span.start,events:vC(z,D,N)}))].sort((z,ee)=>z.start-ee.start).flatMap((z)=>z.events)}function vC(D,N,z){let ee=D.operator==="<<-"?"<<":D.operator,te=D.target?df(D.target,N,z,!0):[],he=te[0],je=he?.kind==="word"?he.text:void 0;return[...D.fd===void 0?[]:[Cl(String(D.fd))],Object.freeze({kind:"redirection",operator:ee,...D.fd===void 0?{}:{fd:D.fd},role:wC(ee),targetOrder:cC.has(ee)?"legacy-segment":"immediate",...je===void 0?{}:{target:je},...D.heredoc&&z.suppressed.has(D.heredoc.bodySpan)?{body:D.heredoc.body,consumer:mf(N)}:{}}),...je===void 0?te:te.slice(1)]}function rf(D,N,z,ee){let te=D.redirections.filter((he)=>he.operator==="<<"||he.operator==="<<-");return[...te.flatMap((he)=>{let je=he.heredoc;if(!je)return[];let at=[Cl(je.delimiter),.../[\r\n]/.test(ee.source[je.terminatorSpan.end]??"")?[kn(";")]:[]];if(ee.suppressed.has(je.bodySpan))return[{start:je.bodySpan.start,events:at}];return[{start:je.bodySpan.start,events:[...uf(ee.source.slice(je.bodySpan.start,je.bodySpan.end),ee),...at]}]}),...te.some((he)=>!he.heredoc&&he.target)?EC(N,z,ee):[]]}function EC(D,N,z){let ee=D.nodes.slice(N+1).find((te)=>te.kind==="connector");if(!ee||ee.span.end>=D.span.end)return[];return[{start:ee.span.end,events:uf(z.source.slice(ee.span.end,D.span.end),z)}]}function uf(D,N){if(N.depth>=ir.maxDepth)return N.flags.limited=!0,[];let z=h(D,"posix");if(z.status==="limited")return N.flags.limited=!0,[];let ee={invalid:!1,limited:!1,expansions:N.flags.expansions,assignmentFallbacks:N.flags.assignmentFallbacks},te=wr(z,{source:D,suppressed:new Set,flags:ee,depth:N.depth+1,functions:new Map,powershell:!1});return N.flags.limited||=ee.limited,N.flags.expansions=ee.expansions,te}function df(D,N,z,ee){let te=[],he={single:!1,double:!1},je="",at=!1,lt=()=>{let ct=at&&!ee?kn("glob"):je!==""||D.quoted&&te.length===0?Cl(je):void 0;if(ct)te.push(ct);je="",at=!1};for(let ct of D.parts){if(ct.provenance!=="command-substitution"&&ct.provenance!=="arithmetic"){for(let mt of hl(ct.raw,he,z.flags,z.powershell)){if(typeof mt==="string"){lt(),te.push(kn(mt));continue}je+=mt.text,at||=mt.glob}continue}let dt=N.nested.find((mt)=>mt.span.start>=ct.span.start&&mt.span.end<=ct.span.end);if(he.double){let mt=z.source.slice(ct.span.start,ct.span.end);je+=hl(mt,{single:!1,double:!0},z.flags,z.powershell).map((pt)=>typeof pt==="string"?pt:pt.text).join("");let gt=dt?wr(dt,z).filter((pt)=>pt.kind==="redirection"&&pt.body!==void 0):[];if(gt.length>0)te.push(Uo,...gt,Ho);continue}let ft=dt?wr(dt,z):[];if(ct.raw.startsWith("`")){je+="${}",lt(),te.push(Uo,...ft,Ho);continue}if(ct.raw.startsWith("<(")||ct.raw.startsWith(">(")){lt(),te.push(ct.raw.startsWith("<(")?kn("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),Uo,...ft,...ct.raw.endsWith(")")?[kn(")")]:[],Ho);continue}let ut=ct.raw.startsWith("$((")?2:1;je+="${}",lt(),te.push(...Array.from({length:ut},()=>kn("(")),...ut===1?[Uo]:[],...ft,...ct.raw.endsWith(")".repeat(ut))?Array.from({length:ut},()=>kn(")")):[],...ut===1?[Ho]:[])}return lt(),te}function hl(D,N,z,ee){let te=[],he="",je=!1,at=0;while(at<D.length){let lt=D[at]??"";if(!N.single&&!N.double&&(lt==="("||lt===")")){te.push({text:he,glob:je},lt),he="",je=!1,at++;continue}if(ee&<==="`"&&!N.single){he+=D[at+1]??"",at+=2;continue}if(N.single&<==="'"){N.single=!1,at++;continue}if(N.single){he+=lt,at++;continue}if(N.double){if(lt==='"'){N.double=!1,at++;continue}if(!ee&<==="\\"){let ct=D[at+1]??"";he+=['"',"\\","$"].includes(ct)?ct:`\\${ct}`,at+=2;continue}if(lt==="$"){let ct=of(D,at,N,z,ee);he+=ct.text,at=ct.next;continue}he+=lt,at++;continue}if(lt==="'"||lt==='"'){N.single=lt==="'",N.double=lt==='"',at++;continue}if(!ee&<==="\\"){let ct=D[at+1]??"";je||=ct==="*"||ct==="?",he+=ct,at+=2;continue}if(lt==="$"){let ct=of(D,at,N,z,ee);he+=ct.text,at=ct.next;continue}je||=lt==="*"||lt==="?",he+=lt,at++}return[...te,{text:he,glob:je}]}function of(D,N,z,ee,te){let he=D[N+1];if(he==="{"){let at=RC(D,N+2);if(at===-1)return ee.invalid=!0,{text:"",next:D.length};let lt=D.slice(N,at+1);return xC(lt,z,ee,te),{text:lt,next:at+1}}if(he!==void 0&&dC.test(he))return{text:`\${${he}}`,next:N+2};let je=(te?fC:/^\w*/).exec(D.slice(N+1))?.[0]??"";return{text:`\${${je}}`,next:N+1+je.length}}function xC(D,N,z,ee){let te=D.slice(2,-1),he=/^[A-Za-z_][A-Za-z0-9_]*/.exec(te)?.[0];if(!he)return;let je=te.slice(he.length),at=[":=","="].find((ct)=>je.startsWith(ct));if(!at)return;let lt=hl(je.slice(at.length),{...N},z,ee);z.assignmentFallbacks.push(...lt.flatMap((ct)=>typeof ct==="string"||!ct.text?[]:[ct.text]))}function RC(D,N){let z=1,ee=N;while(z>0&&ee<D.length){if(D[ee]==="{"&&D[ee-1]==="$")z++;if(D[ee]==="}")z--;ee++}return z===0?ee-1:-1}function _C(D){return/^[\r\n]+$/.test(D)?";":D}function kn(D){return Object.freeze({kind:"operator",operator:D,boundary:lC.has(D)})}function as(D){return Object.freeze({kind:"operator",operator:D,boundary:!0})}function Cl(D){return Object.freeze({kind:"word",text:D})}function wC(D){if(D==="<<"||D==="<<<")return"here-data";if(D==="<"||D==="<&")return"file-read";return"file-write"}function Ko(D){return gC.has(D)||/^python\d/.test(D)}var PC=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 ff(D,N){let z=N[0];if(z===void 0||!z.startsWith("-"))return N;let ee=PC.get(D)?.has(z)??!1;return ff(D,N.slice(ee?2:1))}function yl(D){let N=D[0];if(N===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(N))return yl(D.slice(1));if(!aC.has(N))return[...D];return yl(ff(N,D.slice(1)))}function mf(D){let N=Mo(D),z=D.words.findIndex((ee)=>ee.provenance==="literal"&&ee.text===N);return yl(z<0?[]:D.words.slice(z).map((ee)=>ee.text))}function AC(D){let N=mf(D)[0];if(N===void 0)return!1;let z=At(N).toLowerCase();return Ko(z)&&!jo.has(z)}function bl(D){return D.nodes.flatMap((N,z)=>{if(N.kind==="group"||N.kind==="function")return bl(N.body);if(N.kind!=="command")return[];let ee=N.nested.flatMap((at)=>bl(at)),te=N.redirections.flatMap((at)=>at.heredoc?.quotedDelimiter?[at.heredoc.bodySpan]:[]);if(AC(N))return[...ee,...te];let he=D.nodes[z+1];if(he?.kind==="connector"&&(he.operator==="|"||he.operator==="|&")||!kC(N))return ee;return[...ee,...te]})}function TC(D,N){let z=Mo(D);return z===void 0?void 0:N.get(z)}function cr(D,N){return D!==void 0&&D.provenance==="literal"&&!D.quoted&&D.raw===D.text&&D.text===N}function IC(D){if(cr(D.words[0],"git"))return cr(D.words[1],"commit");if(!cr(D.words[0],"gh")||!cr(D.words[2],"create"))return!1;return cr(D.words[1],"pr")||cr(D.words[1],"issue")}function kC(D){return(cr(D.words[0],"cat")||cr(D.words[0],"tee")||IC(D))&&!D.words.some(sf)&&!D.redirections.some((z)=>sf(z.target))}function sf(D){return D?.parts.some((N)=>N.provenance==="command-substitution"&&N.raw.startsWith(">("))??!1}var pf=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),gf=new Set([...pf,"glob"]),OC=new Set([...gf,"pattern"]);class y extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function qo(D){let N=MC(),z=ne(D.input),ee=[];if((D.route.kind==="command"||D.route.kind==="unknown")&&z)ee.push({usage:"input-candidate",source:z});if(D.route.kind==="command"&&"command"in D&&D.command)ee.push({usage:"declared-command",source:D.command});let te=ee.reduce((he,je)=>{let at=he.findIndex((dt)=>dt.source===je.source);if(at!==-1){let dt=he[at];if(!dt)return he;return he[at]={...dt,usages:[...dt.usages,je.usage]},he}let lt=D.route.kind==="command"?D.route.shell:process.platform==="win32"?"powershell":"posix",ct=N.getCommandProgram(je.source,lt);return he.push({usages:[je.usage],source:je.source,program:ct,shell:N.getShellSyntax(je.source,ct)}),he},[]);return{invocation:{toolName:D.toolName,route:D.route,context:D.context},commands:te,paths:DC(D),store:N}}function un(D,N){return D.commands.find((z)=>z.usages.includes(N))}function Zn(D,N){if(!D.includes("$"))return D;return ta(D,N)}function MC(){let D=new Map,N=new Map,z=new WeakMap,ee=(he,je)=>{let at=`${je}\x00${he}`,lt=N.get(at);if(lt)return lt;let ct=h(he,je);return N.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??ee(he,"posix");if(at.status==="limited"){let dt=z.get(at);if(dt)return dt;let ft={status:"structural-limit",source:he,program:at,assignmentFallbacks:[]};return z.set(at,ft),ft}let lt=D.get(he);if(lt)return lt;let ct=lf(he,at);return D.set(he,ct),ct},getCommandProgram:ee}}function DC(D){let N=D.route.kind==="grep"?gf:D.route.kind==="glob"?OC:pf;return[...Qc(D.input,N),...D.route.kind==="patch"||typeof D.input==="string"?nu(D.input):[]]}var NC=new Set(["-S","--suffix"]);function eo(D,N,z,ee,te){if(D.status==="structural-limit")throw new y;if(D.status!=="complete")return te.findMalformedTarget(D.source);return ls(D,N,z,ee,{segment:(he,je)=>te.findSegmentTarget(he,je),redirection:(he,je)=>he.role==="file-write"&&te.isRedirectionTarget(cn(he.target,je.variables),je)?he.target:null})}function us(D){let N=[],z=null,ee=!1;for(let te=0;te<D.length;te++){let he=D[te];if(he===void 0)break;if(!ee&&he==="--"){ee=!0;continue}if(!ee&&(he==="-t"||he==="--target-directory")){z=D[++te]??null;continue}if(!ee&&he.startsWith("--target-directory=")){z=he.slice(19);continue}if(!ee&&he.startsWith("-t")&&he.length>2){z=he.slice(2);continue}if(!ee&&NC.has(he)){te++;continue}if(!ee&&(he.startsWith("--suffix=")||he.startsWith("--backup=")))continue;if(!ee&&he.startsWith("-"))continue;N.push(he)}return z?{sources:N,destination:z}:{sources:N.slice(0,-1),destination:N.at(-1)??null}}var x="Git metadata and hooks are protected. Ask the user before modifying them.";function Sf(D,N,z,ee){let te=D.invocation.context.executionCwd;if(!N)return null;if(D.invocation.route.kind==="patch"||D.invocation.route.kind==="path"||D.invocation.route.kind==="unknown"){if(Si(D.invocation.toolName))return null;let at=D.paths.find((lt)=>hf(lt,te,N,z,ee,N.entries));return at?{target:at}:null}if(D.invocation.route.kind!=="command")return null;let he=un(D,"input-candidate");if(!he)return null;let je=eo(he.shell,te,z,ee,{findSegmentTarget:(at,lt)=>jC(at,lt,N,z,ee),isRedirectionTarget:(at,lt)=>hf(at,lt.cwd,N,z,ee,N.markerFiles),findMalformedTarget:()=>null});return je?{target:je}:null}function Pr(D,N,z,ee,te,he,je=!1){if(!z)return!1;let at=fs(nn(D,N,te,he)),lt=at.replace(/(\/\.?\*+)+$/,"");if(lt!==at&<!==""){if(vl(lt,z))return!0;let ct=je||at.slice(lt.length).includes("/."),dt=(ft)=>ct?ds(ft,lt):zC(ft,lt);if(z.markerFiles.some(dt))return!0;return ee&&El(z).some(dt)}if(vl(at,z))return!0;return ee&&El(z).some((ct)=>ds(ct,at))}function zC(D,N){let z=bf(N,D);if(z===""||z.startsWith("..")||yf(z))return!1;return!z.split(/[\\/]/)[0]?.startsWith(".")}function BC(D,N,z,ee,te){return Pr(D,N,z,!0,ee,te)}function $C(D,N,z,ee,te){if(!z)return!1;return vl(fs(nn(D,N,ee,te)),z)}function hf(D,N,z,ee,te,he){let je=fs(nn(D,N,ee,te));return he.includes(je)||vf(je,z)}function Cf(D,N,z,ee,te){if(!z)return!1;return z.hooksDirectories.some((he)=>D.some((je)=>ds(he,fs(nn(je,N,ee,te)))))}function vl(D,N){return N.entries.includes(D)||N.directories.includes(D)||vf(D,N)}function vf(D,N){return N.hooksDirectories.some((z)=>ds(D,z))}var UC=50000;function Ef(D,N){let z=[...new Set(El(D))];if(z.some((te)=>N(GC(te))))return!0;let ee=0;while(z.length>0){let te=z.pop()??"",he=HC(te);if(!he)return!0;if(ee+=he.length,ee>UC)return!0;if(he.some((je)=>N(je.name)))return!0;z.push(...he.filter((je)=>je.isDirectory()).map((je)=>FC(te,je.name)))}return!1}function HC(D){try{let N=LC(D,{throwIfNoEntry:!1});if(!N)return[];if(!N.isDirectory())return N.isSymbolicLink()?null:[];return WC(D,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function El(D){return[...D.entries,...D.directories,...D.hooksDirectories]}function ds(D,N){let z=bf(N,D);return z===""||!/^\.\.(?:[\\/]|$)/.test(z)&&!yf(z)}function fs(D){return process.platform==="win32"?D.toLowerCase():D}function jC(D,N,z,ee,te){if(Vo(D))return null;let he=lr([...D],ee);if(At(he[0]??"").toLowerCase()!=="mv")return null;let je=us(he.slice(1)),at=je.sources.find((lt)=>BC(cn(lt,N.variables),N.cwd,z,ee,te));if(at)return at;return je.destination&&$C(cn(je.destination,N.variables),N.cwd,z,ee,te)?je.destination:null}import{isAbsolute as hs,normalize as QC,parse as ev,posix as If,resolve as Tr,sep as wl}from"node:path";import{isAbsolute as VC,join as xf,normalize as wf,parse as KC,sep as Rf}from"node:path";var qC=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],YC=`
|
|
29
29
|
`;function Yo(D,N){if(ur(D,N))return!0;if(!D.has("TMPDIR"))return!1;return!xl(D.get("TMPDIR")??"",N)}function Ar(D,N){if(D.has("TMPDIR"))return xl(D.get("TMPDIR")??"",N);let z=Rl(D,N);if(z===void 0)return!0;return xl(z,N)}function Rl(D,N){return Af(D,N,"TMPDIR")}function xl(D,N){if(!D)return!1;if(XC(D))return!1;return to(D,N)}function ur(D,N){let z=Af(D,N,"IFS");return z!==void 0&&z!==""&&z!==YC}function to(D,N){let z=ms(D,N.paths);if(z===null)return!1;return Pf(N).some((ee)=>no(z,ee))}function gs(D,N){let z=ms(D,N.paths);if(z===null)return!1;return Pf(N).some((ee)=>ps(ee)===ps(z))}var _f=new WeakMap;function Pf(D){let N=_f.get(D);if(N)return N;let z=ZC(D);return _f.set(D,z),z}function ZC(D){let N=qC.map((ee)=>ms(ee,D.paths)??wf(ee)),z=ms(D.tmpdir,D.paths);if(!z)return N;if(process.platform==="win32")return[...N,z];if(process.platform==="darwin"&&JC(z))return[...N,z];return N}function XC(D){return/[\s$`*?[]/.test(D)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(D)||/[+@!]\([^)]*\)/.test(D)}function Af(D,N,z){return D.has(z)?D.get(z):N.env.get(z)}function JC(D){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(D)}function ms(D,N){try{let z=wf(D);if(!VC(z))return z;let ee=KC(z).root,te=z.slice(ee.length).split(/[\\/]+/).filter(Boolean),he=ee;for(let je=0;je<te.length;je++){let at=xf(he,te[je]??"");if(N.entryKind(at)==="missing")return xf(at,...te.slice(je+1));let lt=N.realpath(at);if(lt===null)return null;he=lt}return he}catch{return null}}function no(D,N){let z=ps(D),ee=ps(N);if(z===ee)return!0;let te=ee.endsWith(Rf)?ee:`${ee}${Rf}`;return z.startsWith(te)}function ps(D){return process.platform==="win32"?D.toLowerCase():D}var tv=process.platform==="win32",Tf=64,nv=16384;function Zo(D,N,z,ee){if(D.kind==="temp_target")return null;let te=ee[D.kind];if(D.kind==="dynamic_target"&&!Jt(z,te.id,N.strict))return null;if(D.kind==="within_anchored_cwd"&&!Jt(z,te.id,N.paranoid))return null;return Ct(te.id,te.reason)}function Xo(D){let N=Sd(D,Tf,Tf,nv);return{expandedTargets:N&&"words"in N?N.words:void 0,unsafeBraceExpansion:N!==void 0&&"limited"in N,targetIsLiteral:N===void 0&&D.provenance==="literal"&&(D.quoted||D.raw!==D.text),tmpdirWordSplittingProtected:rv(D)}}function rv(D){let N=D.parts.filter((z)=>z.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(z.raw));return N.length>0&&N.every((z)=>ov(D.raw,z.span.start-D.span.start))}function ov(D,N){let z=null,ee=!1;for(let te=0;te<N;te++){let he=D[te];if(ee){ee=!1;continue}if(he==="\\"&&z!=="'"){ee=!0;continue}if(z===he){z=null;continue}if(z===null&&(he==="'"||he==='"'))z=he}return z==='"'}function dr(D){let N=D.environment.home,z=D.environment.paths,ee=D.budget??pn();return{anchoredCwd:D.originalCwd??D.cwd??null,resolvedCwd:D.cwd??null,strict:D.strict??!1,paranoid:D.paranoid??!1,trustTmpdirVar:D.allowTmpdirVar??!0,posixShell:D.posixShell??!1,tmpdirWordSplittingUnsafe:D.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:D.trustedTmpdirValue??D.allowTmpdirVar??!0,environment:D.environment,allowRoots:uv(D.allowPaths,N,z,ee),protectedGitMetadata:D.protectedGitMetadata,budget:ee}}function On(D,N,z={}){let ee=z.targetIsLiteral??!1;if(!ee&&N.tmpdirWordSplittingUnsafe&&!z.tmpdirWordSplittingProtected&&fv(D))return{kind:"outside_anchored_cwd"};let te=!ee&&Of(D,N.posixShell);if(rr(D))return{kind:"outside_anchored_cwd"};if(Pl(D,ee))return{kind:"root_or_home_target"};if(sv(D,N,ee))return{kind:"root_or_home_target"};if(N.resolvedCwd&&Pr(D,N.resolvedCwd,N.protectedGitMetadata,!0,N.environment,N.budget,!N.posixShell))return{kind:"git_metadata_target"};if(av(D,N.trustTmpdirVar,N.posixShell,te,ee,z.tmpdirWordSplittingProtected??!1,N.trustedTmpdirValue,N.environment))return{kind:"temp_target"};if(te)return{kind:"dynamic_target"};if(dv(D,N,ee))return{kind:"temp_target"};let he=N.anchoredCwd;if(he){if(!z.skipHomeCwd&&hv(he,N.environment.home,N.environment.paths,N.budget))return{kind:"home_cwd_target"};if(!z.skipCwdSelf&&[N.resolvedCwd??he,he].some((je)=>yv(D,N.resolvedCwd??he,N.environment.paths,N.budget,je)))return{kind:"cwd_self_target"};if(bv(D,he,N.resolvedCwd??he,te,ee,N.environment.paths,N.budget))return{kind:"within_anchored_cwd"}}if(iv(D,N,te))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function iv(D,N,z){let ee=D.trim();if(z||!N.resolvedCwd||!N.anchoredCwd||!ee)return!1;if(hs(ee)||ee.startsWith("~"))return!1;if(Al(ee))return!1;if(Mf(N.resolvedCwd,N.anchoredCwd,N.environment.paths,N.budget))return!1;return to(Tr(N.resolvedCwd,ee),N.environment)}function kf(D,N,z={}){let{containmentTarget:ee,...te}=z;if(On(D,N,te).kind!=="temp_target")return!1;let he=D.trim();if(cv(he))return!1;if(gs(he,N.environment))return!1;return![N.anchoredCwd,N.resolvedCwd].some((je)=>Mf(ee??he,je,N.environment.paths,N.budget))}function Pl(D,N=!1){let z=D.trim(),ee=If.normalize(z),te=z.replace(/\\/g,"/"),he=ee==="/"?ee:ee.replace(/\/+$/,"");if(he==="/"||he.startsWith("/")&&he.slice(1).split("/").every((je)=>/^\*+$/.test(je)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(te)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(te))return!0;if(!N&&(ee==="~"||ee==="~/"||ee==="~/*"))return!0;if(!N&&(ee==="$HOME"||ee==="$HOME/"||ee==="$HOME/*"))return!0;if(!N&&(ee==="${HOME}"||ee==="${HOME}/"||ee==="${HOME}/*"))return!0;return!1}function sv(D,N,z){let ee=D.trim(),te=z?ee:ee==="*"?".":ee.endsWith("/*")?ee.slice(0,-2):ee;if(!te)return!1;try{let he=hs(te)?te:N.resolvedCwd?Tr(N.resolvedCwd,te):null;if(!he)return!1;let je=dn(Ot(he,N.environment.paths,N.budget));if(je===ev(je).root)return!0;return je===dn(Ot(N.environment.home,N.environment.paths,N.budget))}catch{return!1}}function dn(D){let N=QC(D);if(tv){if(N=N.replace(/\//g,"\\").toLowerCase(),N.length>3&&N.endsWith("\\"))N=N.slice(0,-1);return N}if(N.length>1&&N.endsWith("/"))N=N.slice(0,-1);return N}function av(D,N,z,ee,te,he,je,at){let lt=D.trim();if(Al(lt))return!1;if(!ee&&to(lt,at))return!0;return(N||he&&je)&&z&&!te&&lv(lt,z)}function lv(D,N){return["$TMPDIR","${TMPDIR}"].some((z)=>{if(D===z)return!0;if(!D.startsWith(`${z}/`))return!1;return!Of(D.slice(z.length+1),N)})}function cv(D){let N=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(D);if(!N)return!1;return If.normalize(`/${N[1]??""}`)==="/"}function Al(D){return D.split(/[\\/]+/).includes("..")}function uv(D,N,z,ee){if(!D?.length)return[];return D.flatMap((te)=>{let he=Io(te.trim(),N);if(!hs(he))return[];try{let je=Ot(he,z,ee);if(ko(je,Ot(N,z,ee)))return[];return[dn(je)]}catch{return[]}})}function dv(D,N,z){if(N.allowRoots.length===0)return!1;let ee=D.trim();if(Al(ee))return!1;let te=z?ee:Io(ee,N.environment.home),he=N.resolvedCwd??N.anchoredCwd,je=hs(te)?te:he?Tr(he,te):null;if(!je)return!1;try{let at=dn(Ot(je,N.environment.paths,N.budget));return N.allowRoots.some((lt)=>at===lt||at.startsWith(lt.endsWith(wl)?lt:`${lt}${wl}`))}catch{return!1}}function fv(D){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(D)}function Of(D,N=!1){return D.includes("$")||D.includes("`")||mv(D)||N&&pv(D)}function mv(D){let N=!1;for(let z of D){if(N){N=!1;continue}if(z==="\\"){N=!0;continue}if(z==="*"||z==="?"||z==="[")return!0}return!1}function pv(D){let N=!1;for(let z=0;z<D.length;z++){let ee=D[z];if(N){N=!1;continue}if(ee==="\\"){N=!0;continue}if(ee==="{"&&gv(D,z)||(ee==="+"||ee==="@"||ee==="!")&&D[z+1]==="(")return!0}return!1}function gv(D,N){let z=D.indexOf("}",N+1);if(z===-1)return!1;let ee=D.slice(N+1,z);return ee.includes(",")||ee.includes("..")}function hv(D,N,z,ee){try{return dn(Ot(D,z,ee))===dn(Ot(N,z,ee))}catch{try{return dn(D)===dn(N)}catch{return!1}}}function yv(D,N,z,ee,te=N){if(te===N&&(D==="."||D==="./"||D===".\\"))return!0;try{return dn(Ot(Tr(N,D),z,ee))===dn(Ot(te,z,ee))}catch{try{return dn(Tr(N,D))===dn(te)}catch{return!1}}}function bv(D,N,z,ee,te,he,je){let at=z??N;if(!te&&(D.startsWith("~")||D.startsWith("$HOME")||D.startsWith("${HOME}")))return!1;if(ee)return!1;if(D.startsWith("/")||/^[A-Za-z]:[\\/]/.test(D))try{return _l(D,N,he,je)}catch{return!1}if(D.startsWith("./")||D.startsWith(".\\")||!D.includes("/")&&!D.includes("\\"))try{return _l(Tr(at,D),N,he,je)}catch{return!1}if(D.startsWith("../"))return!1;try{return _l(Tr(at,D),N,he,je)}catch{return!1}}function _l(D,N,z,ee){try{return Df(Ot(D,z,ee),Ot(N,z,ee))}catch{return!1}}function Mf(D,N,z,ee){if(!N)return!1;try{return Df(Ot(N,z,ee),Ot(D,z,ee))}catch{return!0}}function Df(D,N){let z=dn(D),ee=dn(N);return z.startsWith(`${ee}${wl}`)||z===ee}var Sv=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),Nf="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Cv="PowerShell Remove-Item -Recurse -Force for non-temporary paths is blocked by the active safety policy. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Lf="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",Wf="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",vv="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",Ev="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",xv={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:Wf},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:x},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:Lf},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:vv},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:Nf},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:Cv},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:Nf}};function Gf(D,N,z,ee=dr({...z,allowPaths:z.policy?.destructiveCommandAllowPaths})){return Rv(D.words.map((te)=>({kind:"word",text:te.text,dynamic:te.provenance!=="literal"})),N,ee,z.policy)}function Rv(D,N,z,ee){let te=D.filter((lt)=>lt.kind==="word"),he=wv(te),je=te[he];if(!je||!Sv.has(Nv(je.text)))return null;let at=_v(te.slice(he+1));if(at.whatIfProtected)return null;if(Jt(ee,"powershell.remove-item-pipeline-dynamic-target",z.strict)&&N&&(at.targets.length===0||at.recursive))return Ct("powershell.remove-item-pipeline-dynamic-target",Ev);for(let lt of at.targets)if(!rr(lt.text)&&Pl(Il(lt.text)))return Ct(at.recursive&&at.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Wf);for(let lt of at.targets)if(z.resolvedCwd&&Pr(Il(lt.text),z.resolvedCwd,z.protectedGitMetadata,at.recursive,z.environment,z.budget,!0))return Ct("powershell.remove-item-git-metadata",x);if(!at.recursive||!at.force)return null;if(Jt(ee,"powershell.remove-item-recursive-force-dynamic-target",z.strict)&&(at.hasDynamicTarget||at.targets.length===0))return Ct("powershell.remove-item-recursive-force-dynamic-target",Lf);for(let lt of at.targets){let ct=Zo(On(Il(lt.text),z),z,ee,xv);if(ct)return ct}return null}function _v(D){let N=[],z=!1,ee=!1,te=!1,he=!1,je=!1;for(let at=0;at<D.length;at++){let lt=D[at];if(!lt||lt.kind!=="word")continue;if(Pv(lt))continue;if(je){N.push(Tl(lt)),he=he||lt.dynamic;continue}if(lt.text==="--"){je=!0;continue}let ct=Tv(lt.text);if(!ct){N.push(Tl(lt)),he=he||lt.dynamic;continue}if(Iv(ct.name)){let dt=ct.value?Av(ct.value,lt):D[++at];if(dt?.kind==="word"){N.push(Tl(dt)),he=he||dt.dynamic;continue}he=!0;continue}if(kv(ct.name)){z=!0;continue}if(Ov(ct.name)){ee=!0;continue}if(Mv(ct.name))te=Dv(ct.value)}return{targets:N,recursive:z,force:ee,whatIfProtected:te,hasDynamicTarget:he}}function wv(D){let N=D[0];if(N?.kind==="word"&&N.text==="&"||N?.text===".")return D.length>1?1:0;return 0}function Tl(D){return{text:D.kind==="word"?D.text:"",dynamic:D.kind==="word"&&D.dynamic}}function Pv(D){return D.kind==="word"&&D.text===","}function Il(D){let N=D.replace(/\\/g,"/"),z=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(N);return z?`$HOME${N.slice(z[0].length)}`:N}function Av(D,N){return{kind:"word",text:D,dynamic:N.kind==="word"&&(N.dynamic||D.includes("$"))}}function Tv(D){if(!D.startsWith("-")||D==="-")return null;let N=D.slice(1),z=N.indexOf(":");if(z===-1)return{name:N.toLowerCase()};return{name:N.slice(0,z).toLowerCase(),value:N.slice(z+1)}}function Iv(D){return"path".startsWith(D)||"literalpath".startsWith(D)}function kv(D){return"recurse".startsWith(D)}function Ov(D){return D.length>=2&&"force".startsWith(D)}function Mv(D){return D==="wi"||"whatif".startsWith(D)}function Dv(D){if(D===void 0||D==="")return!0;let N=D.toLowerCase();return N==="$true"||N==="true"}function Nv(D){return D.toLowerCase()}var ro="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",ys="Unsupported heredoc syntax",Jo="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.",Ff="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var Lv=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),Wv=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),Gv=new Set(["-o","--output","--query","--subscription"]),Fv=new Set;function zf(D){if(D==="aws")return Lv;if(D==="gcloud")return Wv;if(D==="az")return Gv;return Fv}var zv=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),Bv=new Set;function Bf(D){if(D==="git")return hn;if(D==="docker")return zv;return Bv}function _(D,N){if(D.length===0||N.length===0)return null;let z=It(D[0]??""),ee=an(D);for(let te of N){if(!Hv(z,te.command))continue;if(te.match){if($v(z,D,te.match))return $f(te);continue}if(!jv(z,D,te.subcommand))continue;if(Kv(D,new Set(te.block_args),ee))return $f(te)}return null}function $f(D){return{id:`custom.${D.name}`,reason:`[${D.name}] ${D.reason}`,intent:D.intent??"manual_only"}}function $v(D,N,z){let ee=N.slice(1);if(z.exclude_args?.some((te)=>ee.includes(te)))return!1;if(z.any_args&&!z.any_args.some((te)=>ee.includes(te)))return!1;return Uv(ee,z.command_path,zf(D))}function Uv(D,N,z){let ee=0,te=!1;for(let he of D){if(ee>=N.length)return!0;if(te){te=!1;continue}if(he.startsWith("-")){te=!he.includes("=")&&z.has(he);continue}if(he!==N[ee])return!1;ee++}return ee>=N.length}function Hv(D,N){return D===It(N)}function jv(D,N,z){if(!z)return!0;return Uf(N,1,z,Bf(D))}function Uf(D,N,z,ee){let te=!1;for(let he=N;he<D.length;he++){let je=D[he];if(!je)continue;if(te){te=!1;continue}if(je==="--"){let at=D[he+1];if(at&&!at.startsWith("-"))return at===z;return!1}if(ee.has(je)){te=!0;continue}if(je.startsWith("-")){if(!je.includes("=")&&Vv(D,he,z,ee))return!0;continue}return je===z}return!1}function Vv(D,N,z,ee){let te=D[N+1];if(!te||te.startsWith("-"))return!1;return Uf(D,N+2,z,ee)}function Kv(D,N,z){return D.some((ee)=>N.has(ee))||[...z].some((ee)=>N.has(ee))}var qv=new Set(["-e","--source"]),Yv=new Set(["-F","-v","--assign","--field-separator"]),Hf=new Set(["-f","--file"]),Zv=new Set(["print","printf","return"]),jf=[{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"}],Xv="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 Vf(D,N,z){let ee=!1;for(let te of Jv(D)){let he=Qv(te,z);if(!he)continue;for(let je of he.commands){let at=N(je);if(at)return at;if(je.includes("{}")||/[$`]/.test(je))ee=!0}ee||=he.dynamic}return ee?Ct("awk.system-dynamic",Xv):null}function Ol(D){let N=[],z=!1,ee=!1,te=!0,he=!0;for(let je=1;je<D.length;je++){let at=D[je];if(at===void 0)break;if(te&&at==="--"){te=!1;continue}if(te&&qv.has(at)){z=!0;let lt=D[je+1];if(he&&=lt!==void 0,lt!==void 0)N.push({tokenIndex:je+1,kind:"inline-code",value:lt});je++;continue}if(te&&at.startsWith("--source=")){z=!0,N.push({tokenIndex:je,kind:"inline-code",value:at.slice(9)});continue}if(te&&at.startsWith("-e")&&at.length>2){z=!0,N.push({tokenIndex:je,kind:"inline-code",value:at.slice(2)});continue}if(te&&(Yv.has(at)||Hf.has(at))){let lt=D[je+1];if(he&&=lt!==void 0,Hf.has(at)){if(ee=!0,lt!==void 0)N.push({tokenIndex:je+1,kind:"program-file",value:lt})}je++;continue}if(te&&(at.startsWith("-F")||at.startsWith("-v")&&at.slice(2).includes("=")))continue;if(te&&at.startsWith("-f")&&at.length>2){ee=!0,N.push({tokenIndex:je,kind:"program-file",value:at.slice(2)});continue}if(te&&(at.startsWith("--assign=")||at.startsWith("--field-separator=")))continue;if(te&&at.startsWith("--file=")){ee=!0,N.push({tokenIndex:je,kind:"program-file",value:at.slice(7)});continue}if(te&&at.startsWith("-")&&at!=="-")continue;if(!z&&!ee)N.push({tokenIndex:je,kind:"main-program",value:at});return{sources:N,optionsOpen:!1}}return{sources:he?N:[],optionsOpen:te&&he}}function ei(D){return Ol(D).sources}function Jv(D){return ei(D).filter((N)=>N.kind!=="program-file").map((N)=>N.value)}function Qv(D,N){Sn(N,D);let z=D.includes("system")?Ml(D,N):null,ee=eE(D,N);if(!z&&!ee)return null;return{dynamic:!!z?.dynamic||!!ee?.dynamic,commands:[...z?.commands??[],...ee?.commands??[]]}}function Ml(D,N){Sn(N,D);let z=[],ee=!1,te=!1,he=0;while(he<D.length){let je=D[he];if(je==='"'||je==="'"){he=Ss(D,he,je)?.endIndex??he+1;continue}if(je==="#"){he=Kf(D,he+1);continue}if(je==="/"&&qf(D,he)){he=Yf(D,he+1)??he+1;continue}if(!D.startsWith("system",he)){he++;continue}let at=he;if(he+=6,Qo(D[at-1])||Qo(D[he]))continue;let lt=bs(D,he);if(D[lt]!=="(")continue;lt=bs(D,lt+1);let ct=D[lt];if(ct!=='"'&&ct!=="'"){ee=!0,te=!0;continue}let dt=Ss(D,lt,ct);if(!dt){ee=!0,te=!0;continue}if(lt=bs(D,dt.endIndex),ee=!0,D[lt]!==")"){te=!0,he=dt.endIndex;continue}z.push(dt.value),he=lt+1}if(!ee)return null;return{dynamic:te,commands:z}}function eE(D,N){Sn(N,D);let z=[],ee=!1,te=!1,he=0,je=0,at=null,lt=null,ct=0;while(he<D.length){let dt=D[he];if(!dt)break;if(dt==='"'||dt==="'"){let mt=Ss(D,he,dt);if(mt&&ct===je)lt={...mt,startIndex:he};ct=mt?.endIndex??he+1,he=mt?.endIndex??he+1;continue}if(dt==="#"){he=Kf(D,he+1),je=he,at=null,lt=null,ct=he;continue}if(dt==="/"&&qf(D,he)){let mt=Yf(D,he+1);ct=mt??he+1,he=mt??he+1;continue}if(`;
|
|
30
30
|
{}`.includes(dt)){he++,je=he,at=null,lt=null,ct=he;continue}if(at===null&&(kl(D,he,"print")||kl(D,he,"printf")))at=he;if(dt!=="|"||D[he-1]==="|"||D[he+1]==="|"){if(!/\s/.test(dt))ct=he+1;he++;continue}let ft=D[he+1]==="&"?he+2:he+1,ut=bs(D,ft);if(kl(D,ut,"getline")){te=!0;let mt=rE(je,lt,ct);if(ee||=mt===null,mt!==null)z.push(mt);ct=ft,he=ft;continue}if(iE(je,at)){te=!0;let mt=nE(D,ut);if(!mt){ee=!0,ct=ft,he=ft;continue}if(!tE(D,mt.endIndex)){ee=!0,ct=mt.endIndex,he=mt.endIndex;continue}z.push(mt.value),ct=mt.endIndex,he=mt.endIndex;continue}ct=ft,he++}if(!te)return null;return{dynamic:ee,commands:z}}function Qo(D){return!!D&&/[A-Za-z0-9_]/.test(D)}function bs(D,N){let z=N;while(/\s/.test(D[z]??""))z++;return z}function tE(D,N){let z=N;while(/[\t\f\v\r ]/.test(D[z]??""))z++;let ee=D[z];return!ee||`;
|
|
31
31
|
}#`.includes(ee)}function Ss(D,N,z){let ee="",te=!1;for(let he=N+1;he<D.length;he++){let je=D[he];if(!je)break;if(te){let at=oE(D,he);if(!at)return null;ee+=at.value,he=at.endIndex,te=!1;continue}if(je==="\\"){te=!0;continue}if(je===z)return{value:ee,endIndex:he+1};ee+=je}return null}function nE(D,N){let z=D[N];if(z!=='"'&&z!=="'")return null;return Ss(D,N,z)}function rE(D,N,z){if(!N)return null;return N.startIndex>=D&&N.endIndex===z?N.value:null}function oE(D,N){let z=D[N];if(!z)return null;if(z==="x"){let te=D.slice(N+1,N+3);if(!/^[0-9A-Fa-f]{2}$/.test(te))return null;return{value:String.fromCharCode(Number.parseInt(te,16)),endIndex:N+2}}if(/[0-7]/.test(z)){let te=/^[0-7]{1,3}/.exec(D.slice(N));if(!te)return null;return{value:String.fromCharCode(Number.parseInt(te[0],8)),endIndex:N+te[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
|
|
@@ -41,5 +41,5 @@ var Xs="CC Safety Net could not analyze the command because it exceeds safe anal
|
|
|
41
41
|
`):D.source,te);return lt?{...lt,segment:D.displayText}:null}function V_(D,N,z){let ee=N.length===1?N[0]:void 0;if(!ee?.heredoc||!hc(ee.heredoc)||ee.fd!==void 0&&ee.fd!==0)return;let te=tn(D.words[0],"uv")&&tn(D.words[1],"run")?D.words.slice(2):D.words,he=te[0];if(he?.provenance!=="literal"||!An(he.text))return;let je=te.findIndex((ft)=>tn(ft,"-"));if(!te.slice(1,je===-1?void 0:je).every((ft)=>ft.provenance==="literal"&&ft.text.startsWith("-")))return;let lt=ee.heredoc.body,ct=Jt(z.policy,"interpreter.one-liner-paranoid",!!z.paranoidInterpreters);if(z.trace?.recordSegment({type:"interpreter",interpreter:he.text,codeArg:lt,paranoidBlocked:ct}),ct){let ft=Pt(Ct("interpreter.one-liner-paranoid",zo),z.policy);if(ft)return ft}if(!Bo(lt,void 0,!z.strict))return null;let dt=Pt(Ct("interpreter.dangerous-command",Jr),z.policy);if(!dt)return null;return z.trace?.recordSegment({type:"dangerous-text",token:lt,matched:!0,reason:dt.reason}),dt}function K_(D,N,z,ee,te){let he=N.length===1?N[0]:void 0;if(!he?.heredoc||!hc(he.heredoc)||he.fd!==void 0&&he.fd!==0)return!1;let je=_r(D.words,te.environment,z.effectiveCwd,ee),at=je.words.map(t),lt=It(at[0]??"");if((je.envSplitValues?.length??0)>0||!Ut.has(lt)&&!Ut.has(At(lt)))return!1;return Xn(at)}function q_(D,N,z,ee,te){let he=Rp(D,N.effectiveCwd,ee,N.shellGitContextState.shellAssignments,z);if(he===null)te?.recordSegment({type:"cwd-change",segment:D.words.map(t).join(" "),effectiveCwdNowUnknown:!0});if(he!==void 0)N.effectiveCwd=he}var Y_=/^[A-Za-z_][A-Za-z0-9_]*$/,Z_=8;function X_(D,N){let z=D.words[1]?.text;if(D.dialect!=="posix"||D.words[0]?.text!=="for"||z===void 0||!Y_.test(z))return[N];let ee=D.words.slice(3);if(!(D.words[2]?.text==="in"&&ee.length>=1&&ee.length<=Z_&&ee.every((he)=>he.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(he.text))))return N.shellGitContextState.shellAssignments.delete(z),[N];return ee.map((he)=>{let je=po(N);return je.shellGitContextState.shellAssignments.set(z,he.text),je})}function po(D){return{effectiveCwd:D.effectiveCwd,shellGitContextState:fm(D.shellGitContextState),literalHeredocFiles:new Map(D.literalHeredocFiles),functionDefinitions:new Map(D.functionDefinitions),createdDirectories:new Set(D.createdDirectories)}}function Fs(D){let N=[];for(let z of D){if(!N.some((ee)=>J_(ee,z)))N.push(z);if(N.length>a.controlFlowStates.cap)throw new s("controlFlowStates")}return N}function J_(D,N){return D.effectiveCwd===N.effectiveCwd&&mo(D.shellGitContextState.env,N.shellGitContextState.env)&&mo(D.literalHeredocFiles,N.literalHeredocFiles)&&mo(D.functionDefinitions,N.functionDefinitions)&&mo(D.shellGitContextState.effectiveEnvAssignments,N.shellGitContextState.effectiveEnvAssignments)&&mo(D.shellGitContextState.shellAssignments,N.shellGitContextState.shellAssignments)&&D.shellGitContextState.bodyDepth===N.shellGitContextState.bodyDepth&&kp(D.shellGitContextState.bodyAssignments,N.shellGitContextState.bodyAssignments)&&kp(D.createdDirectories,N.createdDirectories)}function kp(D,N){return D.size===N.size&&[...D].every((z)=>N.has(z))}function mo(D,N){if(D===N)return!0;if(!D||!N||D.size!==N.size)return!1;return[...D].every(([z,ee])=>N.get(z)===ee&&N.has(z))}function Q_(D,N){let z=Mo(D);return z===void 0?void 0:N.get(z)}function ew(D,N){if(!N)return null;return{reason:N.reason,segment:D,ruleId:N.id,intent:N.intent}}function tw(D,N=D.effectiveCwd){let z=N===null;return{environment:D.environment,cwd:z?void 0:N??D.cwd,originalCwd:z?void 0:D.cwd,strict:D.strict,paranoid:D.paranoidRm,allowTmpdirVar:D.allowTmpdirVar,protectedGitMetadata:D.protectedGitMetadata,policy:D.policy,budget:D.budget}}function pc(D,N){let z=Pt(xn(D),N.policy),ee=N.trace?.currentSegmentIndex??N.trace?.allocateSegment(),te={type:"dangerous-text",token:D,matched:!!z,reason:z?.reason};if(N.trace?.recordSegment(te,ee),!z&&/^(?:cd|pushd)\s/.test(D))N.trace?.recordSegment({type:"cwd-change",segment:D,effectiveCwdNowUnknown:!0},ee);return z?{reason:z.reason,segment:D,ruleId:z.id,intent:z.intent}:null}function Op(D,N){let z={type:"strict-unparseable",rawCommand:D,reason:ro},ee=N.trace?.currentSegmentIndex;if(ee===void 0)N.trace?.recordGlobal(z);if(ee!==void 0)N.trace?.recordSegment(z)}var nw=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function Wp(D,N,z,ee){let te=gc(D,0,{...N,...Fe(N),budget:N.budget??pn(),factStore:ee},z);if(!te)return null;return{kind:"deny",reason:te.reason,intent:te.intent??"manual_only",...te.ruleId?{ruleId:te.ruleId}:{},evidence:{command:D,segment:te.segment}}}function Gp(D,N,z){try{return{decision:D()}}catch(ee){let te=rw(ee,N,z);if(!te)throw ee;return te}}function rw(D,N,z){if(!(D instanceof s)||!nw.has(D.kind))return null;let ee=a[D.kind];if(z?.currentSegmentIndex!==void 0)z.recordSegment({type:"error",message:ee.reason});if(z?.currentSegmentIndex===void 0)z?.recordGlobal({type:"error",message:ee.reason});return{decision:{kind:"deny",reason:ee.reason,intent:"stop_and_explain",evidence:{command:N,segment:N}},errorCode:ee.errorCode}}var ow=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),bc=new Set(["cc-safety-net","ccsn"]),iw=new Set(["bunx","npx","pnpx"]),sw=new Set(["pnpm","yarn"]),aw=new Set(["npm","pnpm","yarn"]),lw=new Set(["bun","node"]);function Us(D,N,z={}){if(bc.has(D))return 0;if(iw.has(D)){if(z.broad)return yc(N);let te=N[0]==="-y"||N[0]==="--yes"?1:0;return $s(N[te])?te+1:null}let ee=z.broad?N.findIndex((te)=>!te.startsWith("-")):0;if(ee!==-1&&aw.has(D)&&z.broad&&N[ee]==="exec"){let te=yc(N.slice(ee+1));return te===null?null:ee+1+te}if(sw.has(D)){if(D==="yarn"&&!z.broad)return null;if(!z.broad)return N[0]==="dlx"&&$s(N[1])?2:null;if(ee===-1||N[ee]!=="dlx")return null;let te=yc(N.slice(ee+1));return te===null?null:ee+1+te}if(lw.has(D)){let te=z.broad&&ee!==-1?ee:0;if(Fp(N[te]))return te+1;if(D==="bun"&&N[te]==="run"&&Fp(N[te+1]))return te+2}return null}function yc(D){let N=D.findIndex((ee)=>$s(ee));if(N===-1)return null;let z=N;while(z<D.length){let ee=D[z]??"";if(!ee.startsWith("-")&&!$s(ee))break;z++}return z}function $s(D){if(!D)return!1;let N=D.indexOf("@");if(N===-1)return bc.has(D);if(N===0)return!1;let z=D.slice(N+1);if(z===""||z.includes("/")||z.includes(":"))return!1;return bc.has(D.slice(0,N))}function Fp(D){let N=D?.replaceAll("\\","/");return[...ow].some((z)=>N===z||N?.endsWith(`/${z}`))}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 zp(D,N,z){let ee=un(D,"input-candidate");if(!ee)return null;let te=eo(ee.shell,D.invocation.context.executionCwd,N,z,{findSegmentTarget:(he)=>cw(he,N),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return te?{target:te}:null}function cw(D,N){let z=ar([...D],N),ee=z.slice(1),te=Us(At(z[0]??"").toLowerCase(),ee,{broad:!0});if(te===null)return null;let he=ee.slice(te).filter((je)=>je!=="-g"&&je!=="--global");return he[0]==="policy"&&he[1]==="apply"?z.join(" "):null}import{dirname as Hs}from"node:path";var $e="This path contains the protected policy config and you must not modify or delete it.",uw=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Hp(D,N,z){let ee=hw(D.invocation.context,N,z);if(D.invocation.route.kind==="patch")return Bp(D.paths,!1,D.invocation.context.executionCwd,ee,N,z);let te=un(D,"input-candidate");if(D.invocation.route.kind==="command")return te?$p(te.shell,D.invocation.context.executionCwd,ee,N,z):null;if(D.invocation.route.kind==="unknown"&&te){let he=$p(te.shell,D.invocation.context.executionCwd,ee,N,z);if(he)return he}return Bp(D.paths,D.invocation.route.kind==="grep"||D.invocation.route.kind==="glob"||Si(D.invocation.toolName),D.invocation.context.executionCwd,ee,N,z)}function Bp(D,N,z,ee,te,he){if(N)return null;let je=D.find((at)=>li(at,z,ee,te,he));return je?{target:je}:null}function $p(D,N,z,ee,te){let he=eo(D,N,ee,te,{findSegmentTarget:(je,at)=>dw(je,at,z,ee,te)?.target??null,isRedirectionTarget:(je,at)=>li(je,at.cwd,z,ee,te),findMalformedTarget:(je)=>gw(je,N,z,ee,te)?.target??null});return he?{target:he}:null}function dw(D,N,z,ee,te){if(Vo(D))return null;let he=lr([...D],ee),je=At(he[0]??"").toLowerCase(),at=he.slice(1);if(je==="rm"&&fw(at)){let lt=mw(at).find((ct)=>Up(cn(ct,N.variables),N.cwd,z,ee,te));if(lt)return{target:lt}}if(je==="find"){if(xs(he,1)||Wl(he,ee)){let ct=(ti($t(he))??$t(["."])).find((dt)=>{let ft=cn(dt.text,N.variables);return li(ft,N.cwd,z,ee,te)||Up(ft,N.cwd,z,ee,te)})?.text;if(ct)return{target:ct}}}if(je==="mv"){let lt=us(at).sources.find((ct)=>yw(cn(ct,N.variables),N.cwd,z,ee,te));if(lt)return{target:lt}}if(pw(he,je))return null;for(let lt of[...D,...he])for(let ct of jp(lt))if(li(cn(ct,N.variables),N.cwd,z,ee,te))return{target:ct};return null}function fw(D){return D.some((N)=>N==="--recursive"||N.startsWith("-")&&!N.startsWith("--")&&/[rR]/.test(N.slice(1)))}function mw(D){let N=D.indexOf("--");if(N!==-1)return[...D.slice(0,N).filter((z)=>!z.startsWith("-")),...D.slice(N+1)];return D.filter((z)=>!z.startsWith("-"))}function pw(D,N){if(!uw.has(N))return!1;if(N!=="sed")return!0;return!D.slice(1).some((z)=>z.startsWith("-i")||z==="--in-place"||z.startsWith("--in-place="))}function gw(D,N,z,ee,te){for(let he of D.split(/\s+/))for(let je of jp(he))if(li(je,N,z,ee,te))return{target:je};return null}function jp(D){let N=D.trim().replace(/^['"]|['"]$/g,""),z=N.indexOf("=");return z===-1||z===N.length-1?[N]:[N,N.slice(z+1)]}function hw(D,N,z){let ee=(at)=>ci(nn(at,D.executionCwd,N,z)),te=ee(u(N)),he=[ee(b(D.executionCwd)),ee(b(D.configCwd))],je=new Set(he.map((at)=>Hs(at)));for(let at=Hs(te);;at=Hs(at))if(je.add(at),Hs(at)===at)break;return{files:new Set([te,...he]),directoriesAndAncestors:je}}function li(D,N,z,ee,te){let he=Fc(D,N,ee,te,(je)=>ci(je)===_i);return he!==null&&z.files.has(ci(he))}function Up(D,N,z,ee,te){return z.directoriesAndAncestors.has(ci(nn(D,N,ee,te)))}function yw(D,N,z,ee,te){let he=ci(nn(D,N,ee,te));return z.files.has(he)||z.directoriesAndAncestors.has(he)}function ci(D){return process.platform==="win32"?D.toLowerCase():D}import{isAbsolute as js,posix as rg,resolve as Ks,win32 as bw}from"node:path";import{fileURLToPath as Sw}from"node:url";var og="Access to a sensitive path is not allowed.",ig=new Set(["echo","printf"]),Cw=new Set(["find"]),vw=new Set(["!","do","elif","else","if","then","until","while"]),Ew=new Set(["-exec","-execdir"]),xw=new Set([";","+"]),Rw=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),_w=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),sg=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),ww=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),Pw=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"]),ag=new Set(["-c","-e","-r","-E","--eval","--exec"]),Aw=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"])]]),Tw=new Set(["grep","rg"]),Iw=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),kw=new Set(["commit","merge","notes","stash","tag"]),Ow=new Set(["-m","--message"]),Mw=new Set(["--grep"]),Vp=new Set(["jq","gojq","jaq"]),Kp="f",qp="file",Dw="files",Nw=new Set(["e","f"]),Lw=new Set(["regexp","file"]),Ww=new Set(["e","f","A","B","C","m"]),Gw=new Set(["regexp","file","after-context","before-context","context","max-count"]),Sc="__CC_SAFETY_NET_PIPE_INPUT__",vc=/[\w./~@+-]*[./~][\w./~@+-]*/g,Fw=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,zw=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,Bw=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,Yp=/\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*$/,$w=/\b(?:eval|exec)\s*\(/g,Uw=/\b(?:eval|exec)\s*$/,Hw=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 Xp(D,N,z,ee,te,he){for(let je of D){let at=je.target;if(BP(at,je.cwd,N?.denyPaths??[],z,ee,te))return{target:at,ruleId:"secret.deny-path"};if(he&&!he.has(at))continue;let lt=FP(at,je.cwd,N,ee,te);if(lt){let ct=he!==void 0&&!lt.startsWith("secret.home.")&&!lt.startsWith("secret.cli.");if(ct&&ee.paths.isDirectory(pg(at,je.cwd,ee,te)))continue;if(ct&&je.isRedirectionWriteTarget===!0&&!at.includes("$")&&!xc(at,je.cwd,ee,te))continue;if(ct&&/\s/.test(at)&&!at.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(at)&&!xc(at,je.cwd,ee,te))continue;if(!lt.startsWith("secret.cli.")&&$P(at,je.cwd,N?.allowPaths??[],z,ee,te))continue;return{target:at,ruleId:lt}}}return null}function lg(D,N,z,ee,te={}){let he=Jp(D,z,ee),je=Xp(he,N,D.invocation.context.configCwd,z,ee);if(je===null||je.ruleId==="secret.deny-path"||te.strict!==!1)return je;let at=Xp(he,N,D.invocation.context.configCwd,z,ee,new Set(Jp(D,z,ee,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}).map((lt)=>lt.target)));return at?.ruleId!=="secret.deny-path"&&jw(D,z)?null:at}function jw(D,N){let z=un(D,"input-candidate")??un(D,"declared-command");if(!z)return!1;if(z.program.nodes.some((je)=>je.kind==="command"&&je.nested.length>0))return!1;let ee=[];for(let je of cs(z.shell)){if(je.kind==="operator"&&je.boundary)return!1;if(je.kind==="redirection")return!1;if(je.kind==="operator")continue;ee.push(Zn(je.text,N))}let te=tr(ee);if(te.length===0)return!1;let he=Wn(te[0]??"").toLowerCase();if(D.invocation.route.kind==="unknown")return z.program.dialect==="powershell"&&(he==="ls"||he==="stat");return Rc(he,te.slice(1))}function Rc(D,N){if(D==="ls"||D==="stat")return!0;if(D==="test")return N.length===2&&(N[0]==="-e"||N[0]==="-f");if(D==="[")return N.length===3&&(N[0]==="-e"||N[0]==="-f")&&N[2]==="]";if(D==="git")return N[0]==="check-ignore";if(D!=="find")return!1;return!N.some((z)=>Rw.has(z))}function Jp(D,N,z,ee={}){let te=D.invocation.context.executionCwd,he=D.invocation.route.kind;if(he!=="command"&&he!=="unknown")return D.paths.map((at)=>({target:at,cwd:te}));let je=un(D,"input-candidate");return[...je?go(je.shell,D.store,ee,N,te,z,Vw(je)):[],...he==="unknown"?D.paths.map((at)=>({target:at,cwd:te})):[]]}function Vw(D){return D.program.dialect==="powershell"}function go(D,N,z,ee,te,he,je=!1){if(D.status==="structural-limit")throw new y;if(D.status==="unclosed-quote")return[];if(D.status==="invalid")throw Error("Unable to parse command for secret protection");let at=[...D.assignmentFallbacks.map((ct)=>({target:ct,cwd:te})),...EP(Zn(D.source,ee),N,z,ee,te,he)],lt=(ct)=>Zn(rP(ct,je),ee);return ls(D,te,ee,he,{word:lt,segment:(ct,dt,ft,ut,mt)=>{if(ct.length===0)return null;if(at.push(...qs(ct,N,z,ee,dt.cwd,he,mt)),ft!==null)at.push(...qw(ft,ct,N,z,ee,dt.cwd,he));return null},redirection:(ct,dt)=>{if(ct.body!==void 0&&ct.consumer!==void 0)at.push(...cg(ct.consumer,[ct.body],N,z,ee,dt.cwd,he,(ft)=>Yw(ct.consumer??[],ft,N,z,ee,dt.cwd,he)));if(ct.targetOrder==="legacy-segment")return Sl;return at.push({target:lt(ct.target),cwd:dt.cwd,...ct.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}}),at}function _c(D,N,z,ee,te,he){let je=N.getShellSyntax(D);if(je.status==="structural-limit")throw new y;return je.status==="complete"?go(je,N,z,ee,te,he):null}function qs(D,N,z,ee,te,he,je){let at=(pt)=>({target:pt,cwd:te});if(je?.size){let pt=D.filter((ht,yt)=>!je.has(yt));if(Vp.has(Wn(tr(pt)[0]??"").toLowerCase()))return[...D.filter((ht,yt)=>je.has(yt)).map(at),...qs(pt,N,z,ee,te,he)]}let lt=nP(D).map(at),ct=tr(D);if(ct.length===0)return lt;let dt=ct[0]??"",ft=Wn(dt).toLowerCase(),ut=ct.slice(1),mt=ct.findIndex((pt)=>!vw.has(pt));if(z.skipMetadataOnlySegments===!0&&mt!==-1&&Rc(Wn(ct[mt]??"").toLowerCase(),ct.slice(mt+1)))return lt;let gt=Kw(dt,ft,ut);if(gt)return[...lt,...gt.map(at)];if(ig.has(ft))return z.displayOperandsAreCapturedOutput===!0?[...lt,...ug(D).map(at)]:lt;if(ft==="eval")return[...lt,..._c(ut.join(" "),N,z,ee,te,he)??ut.map(at)];if(ft==="export")return[...lt,...ut.flatMap((pt)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(pt)?[pt.slice(pt.indexOf("=")+1)]:Hn(ft,pt)).map(at)];if(ft==="git")return[...lt,...iP(ut).map(at)];if(ft==="gh")return[...lt,...Ec(ft,ut,Iw).map(at)];if(Vp.has(ft))return[...lt,...oP(ut).map(at)];if(Tw.has(ft))return[...lt,...IP(ut).map(at)];if(Cw.has(ft))return[...lt,...cP(ut,N,z,ee,te,he).map(at)];if(En.has(ft))return[...lt,...ut.flatMap((pt)=>Hn("awk",pt)).map(at),...ut.flatMap((pt)=>dP(pt,N,z,ee,te,he)),...ut.flatMap(fP).map(at)];if(ft==="curl")return[...lt,...ut.flatMap((pt)=>Hn(ft,pt)).map(at),...sP(ut).map(at)];if(Ko(ft)){let pt=jo.has(ft)?yn([ft,...ut]):null;if(pt!==null&&pt.command!==null&&pt.commandIndex!==null){let ht=N.getShellSyntax(pt.command);if(ht.status==="structural-limit")throw new y;if(ht.status==="complete")return[...lt,...go(ht,N,z,ee,te,he),...ut.slice(pt.commandIndex).filter((yt)=>!yt.startsWith("-")).map(at)]}return[...lt,...uP(ft,ut,N,z,ee,te,he)]}return[...lt,...ut.flatMap((pt)=>Hn(ft,pt)).map(at)]}function Kw(D,N,z){let ee=Us(N,z);if(ee===null||z[ee]!=="explain")return null;let te=[D,...z.slice(0,ee)],he=z.slice(ee+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("--"))te.push(lt);je++;continue}return te}return te}function qw(D,N,z,ee,te,he,je){if(Qw(N,z,ee,te,he,je)){let at=tr(D),lt=Rc(Wn(at[0]??"").toLowerCase(),at.slice(1))?at.slice(1).filter((ct)=>!ct.startsWith("-")):[];return[...ug(D),...lt].map((ct)=>({target:ct,cwd:he}))}return cg(N,Zw(D),z,ee,te,he,je,()=>[])}function Yw(D,N,z,ee,te,he,je){let at=tr(D);if(!Ko(Wn(at[0]??"").toLowerCase()))return[];return _c(N,z,ee,te,he,je)??[{target:N,cwd:he}]}function cg(D,N,z,ee,te,he,je,at){let lt=eP(D);if(lt===null)return N.flatMap(at);return N.flatMap((ct)=>jo.has(lt)?go(z.getShellSyntax(ct),z,ee,te,he,je):Vs(lt,ct,z,ee,te,he,je))}function ug(D){let N=tr(D);if(N.length===0)return[];let z=Wn(N[0]??"").toLowerCase();if(!ig.has(z))return[];let ee=N[N[1]==="--"?2:1];if(z==="printf"&&ee!==void 0&&!ee.startsWith("-")&&!ee.replaceAll("%%","").includes("%"))return[wc(ee.replaceAll("%%","%"))];return N.slice(1)}function Zw(D){let N=tr(D);if(N.length===0)return[];let z=Wn(N[0]??"").toLowerCase(),ee=N.slice(1);if(z==="echo"){let te=ee.findIndex((he)=>!/^-[neE]+$/.test(he));return[(te===-1?[]:ee.slice(te)).join(" ")]}if(z==="printf")return Xw(ee);return[]}function Xw(D){let N=D[0];if(N===void 0)return[];let z=(N.match(/%%|%[bqs]/g)??[]).filter((te)=>te!=="%%").length;if(z===0||D.length===1)return[wc(N)];let ee=D.slice(1);return Array.from({length:Math.ceil(ee.length/z)},(te,he)=>Jw(N,ee.slice(he*z,(he+1)*z)))}function Jw(D,N){let z=0;return wc(D.replace(/%%|%[bqs]/g,(ee)=>{if(ee==="%%")return"%";let te=N[z]??"";return z++,te}))}function wc(D){return D.replace(/\\n/g,`
|
|
42
42
|
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function Qw(D,N,z,ee,te,he){let je=tr(D);if(je.length===0||Wn(je[0]??"").toLowerCase()!=="xargs")return!1;let at=Dr(je),lt=je.slice(at.childStart);if(lt.length===0)return!1;if(at.replacementToken==="")return!1;let ct=at.replacementToken,dt=ct===null?[...lt,Sc]:lt.map((ft)=>ft.split(ct).join(Sc));return qs(dt,N,z,ee,te,he).some((ft)=>ft.target.includes(Sc))}function eP(D){let N=tr(D);if(N.length===0)return null;let z=Wn(N[0]??"").toLowerCase();if(!Ko(z))return null;return tP(z,N.slice(1))?z:null}function tP(D,N){let z=Pc(D);for(let ee=0;ee<N.length;ee++){let te=N[ee];if(te===void 0)break;if(ag.has(te)||dg(D,te)||/^--(?:eval|exec)=/.test(te))return!1;if(te==="-")return!0;if(te.startsWith("-")){if(z==="python"&&te==="-m")return!1;if(Hw.get(z)?.has(te))ee++;continue}return!1}return!0}function Pc(D){return/^python\d/.test(D)?"python":D}function nP(D){let N=[];for(let z of D){if(mg(z))continue;let ee=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(z);if(ee===null)break;if(ee[1]!==void 0&&ee[1]!=="")N.push(ee[1])}return N}var Qp=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function rP(D,N){if(!N||!Qp.test(D))return D;return`~${D.replace(Qp,"").replace(/\\/g,"/")}`}function Hn(D,N){if(N==="--")return[];let z=[],ee=N.indexOf("=");if(ee>0&&ee<N.length-1)z.push(N.slice(ee+1));if(N.startsWith("-"))return z;if(D==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(N))return z;if(D==="zip"&&/\.zip$/i.test(N))return z;return z.push(N),z}function oP(D){let N=-1,z=!1;for(let ee=0;ee<D.length;ee++){let te=D[ee]??"";if(!z&&te==="--"){z=!0;continue}if(z||!/^-(?:[A-Za-z]|-)/.test(te)){if(N===-1)N=ee;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(te)){ee+=2;continue}if(te==="--indent"||te==="-L"){ee++;continue}if(te.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(te)||/^--(?: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(te))continue;return D.flatMap((he)=>Hn("jq",he))}return D.flatMap((ee,te)=>te===N?[]:Hn("jq",ee))}function iP(D){let N=[];for(let z=0;z<D.length;z++){let ee=D[z]??"";if(ee==="--"||!ee.startsWith("-"))return[...N,...kw.has(ee)?Ec("git",D.slice(z).map((he)=>/^-[aeinopqsv]+m$/.test(he)?"-m":he),Ow):Ec("git",D.slice(z),Mw)];if(N.push(...Hn("git",ee)),!hn.has(ee))continue;let te=D[z+1];if(te===void 0)break;N.push(...ee==="-c"&&te.includes("=")?[te.slice(te.indexOf("=")+1)]:Hn("git",te)),z++}return N}function Ec(D,N,z){let ee=[];for(let te=0;te<N.length;te++){let he=N[te]??"";if(he==="--")return[...ee,...N.slice(te).flatMap((je)=>Hn(D,je))];if(z.has(he)){te++;continue}if(he.includes("=")&&z.has(he.slice(0,he.indexOf("="))))continue;ee.push(...Hn(D,he))}return ee}function sP(D){return D.flatMap((N,z)=>{let ee=lP(N);if(ee!==null)return eg(ee.flag,ee.value);let te=aP(D[z-1]);return te===null?[]:eg(te,N)})}function eg(D,N){if(D==="-F"||D==="--form"){let z=N.indexOf("="),ee=z===-1?N:N.slice(z+1);if(!ee.startsWith("@")&&!ee.startsWith("<"))return[];return Cc(ee.slice(1).split(";")[0]??"")}if(D==="--data-urlencode"){let z=N.indexOf("@"),ee=N.indexOf("=");if(z===-1||ee!==-1&&ee<z)return[];return Cc(N.slice(z+1))}return N.startsWith("@")?Cc(N.slice(1)):[]}function aP(D){if(D===void 0)return null;if(sg.has(D))return D;return/^-[A-Za-z]+[dF]$/.test(D)?`-${D.slice(-1)}`:null}function lP(D){let N=D.slice(0,2);if(D.length>2&&(N==="-d"||N==="-F"))return{flag:N,value:D.slice(2)};let z=D.indexOf("=");if(z===-1)return null;let ee=D.slice(0,z);return sg.has(ee)?{flag:ee,value:D.slice(z+1)}:null}function Cc(D){return D===""||D==="-"?[]:[D]}function cP(D,N,z,ee,te,he){let je=D.findIndex((lt)=>lt.startsWith("-")||lt==="("||lt==="!"||lt===";"),at=[...D.slice(0,je===-1?D.length:je),...D.flatMap((lt,ct)=>lt==="-files0-from"&&D[ct+1]!==void 0?[D[ct+1]??""]:[])];for(let lt=0;lt<D.length;lt++){if(!Ew.has(D[lt]??""))continue;let ct=D.slice(lt+1),dt=ct.findIndex((mt)=>xw.has(mt)),ft=dt===-1?ct:ct.slice(0,dt),ut=qs(ft,N,z,ee,te,he).map((mt)=>mt.target);if(at.push(...ut.filter((mt)=>mt!=="{}")),!ut.includes("{}"))continue;at.push(...D.slice(0,lt).flatMap((mt,gt,pt)=>{if(!_w.has(mt))return[];let ht=pt[gt+1];return ht===void 0?[]:[ht,ht.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return at}function uP(D,N,z,ee,te,he,je){let at=[];for(let lt=0;lt<N.length;lt++){let ct=N[lt];if(ct===void 0)break;if(ag.has(ct)||dg(D,ct)){let ft=N[lt+1];if(ft!==void 0)at.push(...Vs(D,ft,z,ee,te,he,je)),lt++;continue}let dt=/^--(?:eval|exec)=(.*)$/.exec(ct);if(dt!==null&&dt[1]!==void 0){at.push(...Vs(D,dt[1],z,ee,te,he,je));continue}if(!ct.startsWith("-"))at.push({target:ct,cwd:he})}return at}function dg(D,N){if(!N.startsWith("-")||N.startsWith("--")||N.length<=2)return!1;return Aw.get(N[N.length-1]??"")?.has(Pc(D))??!1}function dP(D,N,z,ee,te,he){if(!D.includes("system"))return[];return Ml(D)?.commands.flatMap((je)=>go(N.getShellSyntax(je),N,z,ee,te,he))??[]}function fP(D){return Array.from(D.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((N)=>N[1]).filter((N)=>N!==void 0&&N!=="")}function mP(D){let N=Array.from(D.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((z)=>z[2]).filter((z)=>z!==void 0&&z!=="");return[...N,...N.flatMap(Ac),...D.match(vc)??[]]}function Vs(D,N,z,ee,te,he,je){let at=(pt)=>({target:pt,cwd:he}),lt=gP(N,pP(D));if(lt.kind==="unmaskable")return mP(N).map(at);let ct=lt.masked.match(Yp)!==null||lt.literals.some((pt)=>Zp.test(lt.masked.slice(0,pt.start))),dt=lt.masked.match($w)!==null||lt.literals.some((pt)=>Uw.test(lt.masked.slice(0,pt.start))),ft=ee.inlineLiteralsPresumedData===!0&&!jo.has(D),ut=ft&&!(SP(lt.masked)||ct||dt)?[]:lt.literals,mt=ft?Array.from(lt.masked.matchAll(Yp),(pt)=>{let ht=pt.index+pt[0].length;return{start:ht,end:fl(lt.masked,ht)}}):[],gt=!ft||mt.some((pt)=>ml(lt.masked,pt.start))?lt.literals:lt.literals.filter((pt)=>Zp.test(lt.masked.slice(0,pt.start))||mt.some((ht)=>pt.start>=ht.start&&pt.start<ht.end));return[...ut.map((pt)=>pt.text).filter((pt)=>pt!=="").map(at),...ut.flatMap((pt)=>Ac(pt.text)).map(at),...ft?[]:lt.literals.flatMap((pt)=>pt.text.match(vc)??[]).map(at),...ct?gt.flatMap((pt)=>_c(pt.text,z,ee,te,he,je)??[at(pt.text)]):[],...dt?lt.literals.flatMap((pt)=>Vs(D,pt.text.replace(/\\(.)/g,(ht,yt)=>yt==="n"?`
|
|
43
43
|
`:yt),z,ee,te,he,je)):[],...(lt.masked.match(vc)??[]).map(at)]}function pP(D){let N=Pc(D);if(N==="python")return"python";if(N==="osascript")return"opaque";return N==="node"||N==="bun"||N==="deno"?"javascript":"simple"}function gP(D,N){if(N==="opaque")return{kind:"unmaskable"};let z=D.split(""),ee=[];for(let te=0;te<D.length;te++){let he=D[te]??"";if(N==="simple"&&(he==="`"||he==="%"||he==="<")){if(zw.test(D.slice(te)))return{kind:"unmaskable"}}let je=he==="'"||he==='"'||N==="javascript"&&he==="`"?he:null;if(je===null)continue;if(je==="`"&&bP(D,te))return{kind:"unmaskable"};let at=N==="python"?hP(D,te):"",lt=N==="python"&&D.startsWith(je.repeat(3),te)?je.repeat(3):je,ct=te+lt.length,dt=yP(D,ct,lt);if(dt===null)return{kind:"unmaskable"};let ft=D.slice(ct,dt);if(/[fF]/.test(at)&&ft.includes("{"))return{kind:"unmaskable"};if(N==="simple"&&je==='"'&&Bw.test(ft))return{kind:"unmaskable"};ee.push({start:ct,text:ft});for(let ut=te;ut<dt+lt.length;ut++)z[ut]=" ";te=dt+lt.length-1}return{kind:"masked",masked:z.join(""),literals:ee}}function hP(D,N){return Fw.exec(D.slice(Math.max(0,N-3),N))?.[1]??""}function yP(D,N,z){let ee=z==="`",te=ee||z.length===3;for(let he=N;he<D.length;he++){let je=D[he];if(je==="\\"){he++;continue}if(ee&&je==="$"&&D[he+1]==="{")return null;if(!te&&(je===`
|
|
44
|
-
`||je==="\r"))return null;if(D.startsWith(z,he))return he}return null}function bP(D,N){for(let z=N-1;z>=0;z--){let ee=D[z];if(!ee||/\s/.test(ee))continue;return/[\w$\])]/.test(ee)}return!1}function SP(D){for(let N of D.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let z=N[0],ee=N.index;if(ww.has(z.toLowerCase()))return!0;let te=z.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((he)=>he.toLowerCase());if(!te.some((he)=>Pw.has(he)))continue;if(te.length>1)return!0;if(CP(D,ee)===".")return!0;if(vP(D,ee+z.length)==="(")return!0}return!1}function CP(D,N){for(let z=N-1;z>=0;z--)if(!/\s/.test(D[z]??""))return D[z];return}function vP(D,N){for(let z=N;z<D.length;z++)if(!/\s/.test(D[z]??""))return D[z];return}function EP(D,N,z,ee,te,he){return PP(D).flatMap((je)=>{let at=N.getShellSyntax(je);if(at.status==="invalid")return[];return[...go(at,N,{...z,displayOperandsAreCapturedOutput:!0},ee,te,he),...xP(at,ee)?RP(at,ee).map((lt)=>({target:lt,cwd:te})):[]]})}function xP(D,N){let z=cs(D);for(let ee=0;ee<z.length;ee++){let te=z[ee];if(te?.kind!=="word"||Wn(Zn(te.text,N)).toLowerCase()!=="base64")continue;for(let he=ee+1;he<z.length;he++){let je=z[he];if(je?.kind==="operator")break;if(je?.kind!=="word")continue;let at=Zn(je.text,N);if(at==="--decode"||!at.startsWith("--")&&at.startsWith("-")&&/[dD]/.test(at))return!0}}return!1}function RP(D,N){return cs(D).flatMap((z)=>z.kind==="word"?[Zn(z.text,N)]:z.kind==="redirection"&&z.target?[Zn(z.target,N)]:[]).flatMap(Ac)}function Ac(D){let N=wP(D);if(N===null)return[];let z=Buffer.from(N,"base64").toString("utf8");if(z===""||_P(z))return[];return Buffer.from(z,"utf8").toString("base64").replace(/=+$/g,"")===N.replace(/=+$/g,"")?[z]:[]}function _P(D){return Array.from(D).some((N)=>{let z=N.charCodeAt(0);return z<32||z===127})}function wP(D){if(D.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(D))return null;if(/=/.test(D.replace(/=+$/g,"")))return null;let N=D.replace(/=+$/g,"");if(N.length%4===1)return null;return`${N.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-N.length%4)%4)}`}function PP(D){let N=[],z={inSingle:!1,inDouble:!1,escaped:!1};for(let ee=0;ee<D.length;ee++){let te=D[ee];if(!te)break;if(Ao(te,z))continue;if(fg(D,ee,z)){let he=AP(D,ee+1);if(he!==null)N.push(he.body),ee=he.endIndex;continue}if(!z.inSingle&&te==="`"){let he=TP(D,ee);if(he!==null)N.push(he.body),ee=he.endIndex}}return N}function AP(D,N){let z={inSingle:!1,inDouble:!1,escaped:!1},ee=1;for(let te=N+1;te<D.length;te++){let he=D[te];if(!he)break;if(Ao(he,z))continue;if(fg(D,te,z)){ee++,te++;continue}if(!z.inSingle&&!z.inDouble&&he===")"){if(ee--,ee===0)return{body:D.slice(N+1,te),endIndex:te}}}return null}function TP(D,N){let z=!1;for(let ee=N+1;ee<D.length;ee++){let te=D[ee];if(!te)break;if(z){z=!1;continue}if(te==="\\"){z=!0;continue}if(te==="`")return{body:D.slice(N+1,ee),endIndex:ee}}return null}function fg(D,N,z){return!z.inSingle&&D[N]==="$"&&D[N+1]==="("&&D[N+2]!=="("}function IP(D){let N=[],z=[],ee=!1,te=!1,he=!1;for(let lt=0;lt<D.length;lt++){let ct=D[lt];if(ct===void 0)break;if(!he&&ct==="--"){he=!0;continue}if(he){z.push(ct);continue}let dt=/^--([^=]+)(?:=(.*))?$/.exec(ct);if(dt!==null){let ft=dt[1]??"",ut=dt[2];if(ft===Dw)te=!0;if(Lw.has(ft))ee=!0;if(ut!==void 0){if(ft===qp)N.push(ut);continue}if(Gw.has(ft)){let mt=D[lt+1];if(ft===qp&&mt!==void 0)N.push(mt);lt++}continue}if(ct.startsWith("-")&&ct.length>1){let ft=ct.slice(1),ut="",mt="";for(let pt=0;pt<ft.length;pt++){let ht=ft[pt]??"";if(Nw.has(ht))ee=!0;if(Ww.has(ht)){ut=ht,mt=ft.slice(pt+1);break}}if(ut==="")continue;if(mt.length>0){if(ut===Kp)N.push(mt);continue}let gt=D[lt+1];if(ut===Kp&>!==void 0)N.push(gt);lt++;continue}z.push(ct)}let at=!ee&&!te?z.slice(1):z;return[...N,...at]}function tr(D){let N=D.findIndex((z)=>!mg(z)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(z));return N===-1?[]:D.slice(N)}function mg(D){return D==="env"||D==="command"||D==="builtin"||D==="sudo"}var kP=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),OP=".env.",MP=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),DP=[".env.example.",".env.sample."];function NP(D){let N;try{N=new URL(D.trim())}catch{return!1}return N.protocol!=="file:"&&N.host!==""}function LP(D){return D.length>0&&!/\s/.test(D)}function xc(D,N,z,ee){let te=pg(D,N,z,ee);return te!==""&&z.paths.entryKind(te)!=="missing"}function pg(D,N,z,ee){try{return fi(D,N,z,ee)}catch(te){if(te instanceof s)throw te;return""}}var WP=new Set(["node_modules","__pycache__"]),GP=[["vendor","bundle"],["vendor","cache"]];function FP(D,N,z,ee,te){if(NP(D))return null;let he=Un(D,N,ee,te);if(!he)return null;let je=Wt(he.split("/").pop()??""),at=Wt(he),lt=()=>LP(je)||xc(D,N,ee,te);if(MP.has(je)||DP.some((ut)=>je.startsWith(ut)))return null;let ct=Wt(jP(D,N,ee,te));for(let ut of Pa){let mt=`~/${ut.suffixParts.join("/")}`;if((ng(at,mt)||ng(ct,mt))&&er(ut.id,z))return ut.id}let dt=zP(he,N,z,ee,te);if(dt)return dt;if(kP.has(je))return null;for(let ut of wa)if(je===ut.basename&&er(ut.id,z))return ut.id;if(je.startsWith(OP)&&er(Ii.id,z)&<())return Ii.id;for(let ut of Aa)if(je.length>ut.prefix.length&&je.startsWith(ut.prefix)){let mt=je.slice(ut.prefix.length)[0];if((mt==="-"||mt==="_")&&er(ut.id,z)&<())return ut.id}for(let ut of Ta)if(je.length>ut.prefix.length&&je.startsWith(ut.prefix)){if(je.slice(ut.prefix.length)===ut.suffix&&er(ut.id,z))return ut.id}if(UP(at))return null;if(!je.includes(".")&&To.pattern.test(je)&&er(To.id,z))return To.id;let ft=HP(je,z);if(ft)return ft;return null}function zP(D,N,z,ee,te){return ki.find((he)=>{if(!er(he.id,z))return!1;switch(he.id){case"secret.cli.claude-code":return Dt(D,Gt(ee.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",N,ee,te),[".credentials.json"]);case"secret.cli.claude-code.config":{let je=Wt(D).split("/");return Dt(D,Gt(ee.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",N,ee,te),["settings.json","settings.local.json"])||di(D,"~/.claude.json",N,ee,te)||je.at(-1)==="settings.local.json"&&je.at(-2)===".claude"||je.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Dt(D,Un("~/.gemini/config",N,ee,te),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let je=Gt(ee.env.get("CODEX_HOME"),"~/.codex",N,ee,te);return Dt(D,je,["auth.json",".credentials.json"])||ui(D,je,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let je=Gt(ee.env.get("CODEX_HOME"),"~/.codex",N,ee,te),at=Wt(D).split("/").at(-1)??"";return Dt(D,je,["config.toml"])||at.endsWith(".config.toml")&&Dt(D,je,[at])}case"secret.cli.gemini":return Dt(D,rn(Gt(ee.env.get("GEMINI_CLI_HOME"),"~",N,ee,te),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let je=Wt(D).split("/"),at=ee.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),lt=ee.env.get("ProgramData")?[rn(Gt(ee.env.get("ProgramData"),"",N,ee,te),"gemini-cli")]:[];return Dt(D,rn(Gt(ee.env.get("GEMINI_CLI_HOME"),"~",N,ee,te),".gemini"),["settings.json","google_accounts.json"])||je.at(-1)==="settings.json"&&je.at(-2)===".gemini"||(at?.trim()?di(D,at,N,ee,te):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...lt].some((ct)=>Dt(D,Un(ct,N,ee,te),["settings.json"]))}case"secret.cli.copilot-cli":{let je=Gt(ee.env.get("COPILOT_HOME"),"~/.copilot",N,ee,te);return Dt(D,je,["config.json"])||ui(D,je,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Dt(D,Gt(ee.env.get("COPILOT_HOME"),"~/.copilot",N,ee,te),["mcp-config.json"]);case"secret.cli.kimi-code":{let je=Gt(ee.env.get("KIMI_CODE_HOME"),"~/.kimi-code",N,ee,te),at=Gt(ee.env.get("KIMI_SHARE_DIR"),"~/.kimi",N,ee,te);return Dt(D,je,["server.token"])||ui(D,je,["credentials"])||ui(D,at,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let je=["config.toml","mcp.json"],at=Wt(D).split("/");return at.at(-1)==="mcp.json"&&at.at(-2)===".kimi-code"||Dt(D,Gt(ee.env.get("KIMI_CODE_HOME"),"~/.kimi-code",N,ee,te),je)||Dt(D,Gt(ee.env.get("KIMI_SHARE_DIR"),"~/.kimi",N,ee,te),[...je,"config.json","config.json.bak"])}case"secret.cli.opencode":{let je=rn(Gt(ee.env.get("XDG_DATA_HOME"),"~/.local/share",N,ee,te),"opencode"),at=Wt(D).split("/").at(-1)??"",lt=ee.env.get("OPENCODE_DB")?.trim(),ct=lt&<!==":memory:"?[lt,`${lt}-wal`,`${lt}-shm`]:[];return Dt(D,je,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(at)&&Dt(D,je,[at])||ct.some((dt)=>di(D,dt,N,ee,te))}case"secret.cli.opencode.config":{let je=ee.env.get("OPENCODE_CONFIG_DIR")?Gt(ee.env.get("OPENCODE_CONFIG_DIR"),"~/.config/opencode",N,ee,te):rn(Gt(ee.env.get("XDG_CONFIG_HOME"),"~/.config",N,ee,te),"opencode"),at=ee.env.get("ProgramData")?[rn(Gt(ee.env.get("ProgramData"),"",N,ee,te),"opencode")]:[],lt=["opencode.json","opencode.jsonc"],ct=ee.env.get("OPENCODE_CONFIG");return lt.includes(Wt(D).split("/").at(-1)??"")||Dt(D,je,lt)||(ct?.trim()?di(D,ct,N,ee,te):!1)||["/Library/Application Support/opencode","/etc/opencode",...at].some((dt)=>Dt(D,Un(dt,N,ee,te),lt))}case"secret.cli.pi":return Dt(D,Gt(ee.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",N,ee,te),["auth.json"]);case"secret.cli.pi.config":return Dt(D,Gt(ee.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",N,ee,te),["models.json"]);case"secret.cli.amp":{let je=Un("~",N,ee,te);return[rn(Gt(ee.env.get("XDG_DATA_HOME"),"~/.local/share",N,ee,te),"amp"),rn(je,".local","share","amp")].some((lt)=>Dt(D,lt,["secrets.json"]))||ui(D,rn(je,".amp"),["oauth"])}case"secret.cli.amp.config":{let je=["settings.json","settings.jsonc"],at=[rn(Gt(ee.env.get("XDG_CONFIG_HOME"),"~/.config",N,ee,te),"amp"),rn(Un("~",N,ee,te),".config","amp")],lt=Wt(D).split("/"),ct=ee.env.get("AMP_SETTINGS_FILE");return at.some((dt)=>Dt(D,dt,je))||lt.at(-2)===".amp"&&je.includes(lt.at(-1)??"")||(ct?.trim()?di(D,ct,N,ee,te):!1)}case"secret.cli.cursor":{let je=rn(Gt(ee.env.get("XDG_CONFIG_HOME"),"~/.config",N,ee,te),"cursor"),at=rn(Gt(ee.env.get("CURSOR_DATA_DIR"),"~/.cursor",N,ee,te),"projects");return Dt(D,Un("~/.cursor",N,ee,te),["auth.json"])||Dt(D,je,["auth.json"])||Wt(D).split("/").at(-1)==="mcp-auth.json"&&Gr(Wt(D),Wt(at))}case"secret.cli.cursor.config":{let je=Wt(D).split("/");return je.at(-1)==="mcp.json"&&je.at(-2)===".cursor"}case"secret.cli.grok-build":return Dt(D,Gt(ee.env.get("GROK_HOME"),"~/.grok",N,ee,te),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let je=Wt(D).split("/");return je.at(-1)==="config.toml"&&je.at(-2)===".grok"||Dt(D,Gt(ee.env.get("GROK_HOME"),"~/.grok",N,ee,te),["config.toml","managed_config.toml","requirements.toml"])||Dt(D,Un("/etc/grok",N,ee,te),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var tg=new WeakMap;function Gt(D,N,z,ee,te){let he=tg.get(te)??new Map;tg.set(te,he);let je=`${z}\x00${D??""}\x00${N}`,at=he.get(je);if(at!==void 0)return at;let lt=Un(D?.trim()?D:N,z,ee,te);return he.set(je,lt),lt}function Dt(D,N,z){return z.some((ee)=>gg(D,rn(N,ee)))}function ui(D,N,z){return z.some((ee)=>Gr(Wt(D),Wt(rn(N,ee))))}function di(D,N,z,ee,te){return gg(D,Un(N,z,ee,te))}function gg(D,N){return Wt(D)===Wt(N)}function rn(D,...N){return Ln([D,...N].filter(Boolean).join("/"))}function BP(D,N,z,ee,te,he){if(z.length===0)return!1;let je=Wt(fi(D,N,te,he));return z.some((at)=>Gr(je,Wt(fi(at,ee,te,he))))}function $P(D,N,z,ee,te,he){if(z.length===0)return!1;let je=Wt(fi(D,N,te,he));if(!je)return!1;let at=te.env.get("HOME")??te.home,lt=at?Ln(Ot(gn(at),te.paths,he)):"",ct=Wt(lt),dt=te.env.get("CC_SAFETY_NET_HOME"),ft=Wt(dt?Ln(Ot(Ks(gn(dt)),te.paths,he)):lt&&Ln(Ot(`${lt}/.cc-safety-net`,te.paths,he)));if(ft&&Gr(je,ft))return!1;return z.some((ut)=>{let mt=Da(ut);if(mt&&rg.basename(je)!==Wt(mt.name))return!1;let gt=Wt(fi(mt?.root??ut,ee,te,he));if(!gt)return!1;if(ct&&(ct===gt||ct.startsWith(gt.endsWith("/")?gt:`${gt}/`)))return!1;return Gr(je,gt)&&!(mt&&je===gt)})}function UP(D){let N=D.split("/");return N.some((z)=>WP.has(z))||GP.some(([z,ee])=>N.some((te,he)=>te===z&&N[he+1]===ee))}function HP(D,N){let z=D.lastIndexOf("."),ee=z>0&&z<D.length-1?D.slice(z+1):"";if(ee==="")return null;for(let te of Ia)if(ee===te.extension&&er(te.id,N))return te.id;for(let te of ka)if(te.pattern.test(ee)&&er(te.id,N))return te.id;return null}function Wt(D){return D.toLowerCase()}function er(D,N){return!N?.disabledRules?.includes(D)}function Un(D,N,z,ee){let{home:te,normalized:he}=Tc(D,z,ee);if(!he)return"";if(!te)return he;let je=Ic(he,te),at=js(je)?je:Ln(Ks(N,je)),lt=Ln(Ot(at,z.paths,ee));if(!Gr(lt,te)){if(js(je))return lt;return lt===at?he:lt}let ct=lt.slice(te.length);return ct?`~${ct}`:"~"}function ng(D,N){return D===N||D.startsWith(`${N}/`)}function jP(D,N,z,ee){let{home:te,normalized:he}=Tc(D,z,ee);if(!he||!te)return"";let je=Ic(he,te),at=rg.normalize(js(je)?je:Ln(Ks(N,je))),lt=Ln(gn(z.env.get("HOME")??z.home)),ct=(ut)=>process.platform==="win32"?ut.toLowerCase():ut,dt=[te,lt].find((ut)=>ut!==""&&Gr(ct(at),ct(ut)));if(dt===void 0)return"";let ft=at.slice(dt.length);return ft?`~${ft}`:"~"}function fi(D,N,z,ee){let{home:te,normalized:he}=Tc(D,z,ee);if(!he)return"";let je=te?Ic(he,te):he;return Ln(Ot(js(je)?je:Ks(N,je),z.paths,ee))}function Tc(D,N,z){let ee=N.env.get("HOME")??N.home,te=ee?Ln(Ot(gn(ee),N.paths,z)):"",he=Ln(gn(VP(Zn(D,N))));return{home:te,normalized:he}}function VP(D){if(!D.trim().toLowerCase().startsWith("file:"))return D;try{return Sw(D)}catch{return D}}function Ic(D,N){if(D==="~")return N;if(D.startsWith("~/"))return rn(N,D.slice(2));return D}function KP(D){if(process.platform==="win32")return!0;return bw.parse(D).root.length>1}function Ln(D){let N=D.trim(),z=(N.includes("\\")&&KP(N)?N.replace(/\\/g,"/"):N).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(z==="/")return z;return z.replace(/\/+$/g,"")}function Gr(D,N){return D===N||D.startsWith(N.endsWith("/")?N:`${N}/`)}function Wn(D){return D.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??D}class p extends Error{stage;evaluation;name="GuardEvaluationError";constructor(D,N,z){super(`CC Safety Net ${D} dependency failed`,{cause:z});this.stage=D;this.evaluation=N}}var qP={findPolicyMutation:Hp,findGitMetadataMutation:Sf,resolveGitMetadata:ZP,loadPolicySnapshot:E,findSensitiveTarget:lg,analyzeCommand:Wp,getModes:R},YP=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function B(D,N){let z={...qP,...N.dependencies},ee=QP(D),te=mi(D)?D.command:ee,he=hr("policy-protection",te,()=>qo(D)),je=un(he,"input-candidate"),at=un(he,"declared-command");if(mi(D)&&D.command?.trim()&&at?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Fn,intent:"stop_and_explain",evidence:{command:D.command,segment:D.command}}};if(je?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:Ff,intent:"stop_and_explain"}};let lt=pn(),ct=hr("policy-protection",te,()=>z.resolveGitMetadata([D.context.executionCwd,D.context.configCwd],N.environment)),dt=hr("policy-protection",te,()=>z.findPolicyMutation(he,N.environment,lt));if(dt){let Et=te??dt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:$e,intent:"hard_stop",evidence:{command:Et,segment:dt.target}}}}let ft=hr("policy-protection",te,()=>zp(he,N.environment,lt));if(ft){let Et=te??ft.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Me,intent:"hard_stop",evidence:{command:Et,segment:ft.target}}}}let ut=hr("policy-protection",te,()=>z.findGitMetadataMutation(he,ct,N.environment,lt));if(ut){let Et=te??ut.target;return{stage:"policy-protection",decision:{kind:"deny",reason:x,intent:"hard_stop",evidence:{command:Et,segment:ut.target}}}}let mt=hr("config-load",te,()=>z.loadPolicySnapshot(N.environment,{...N.policyOptions,cwd:D.context.configCwd})),gt=mt.policy,pt=z.getModes(gt,N.environment.env),ht={level:pt.effectiveLevel,...XP(mt)},yt=gt.secretProtection.enabled===!1?null:hr("secret-protection",te,()=>z.findSensitiveTarget(he,gt.secretProtection,N.environment,lt,{strict:mi(D)||je?.program.dialect==="powershell"?pt.strict:void 0}));if(yt){let Et=te??yt.target;return{stage:"secret-protection",...ht,decision:{kind:"deny",reason:og,intent:"hard_stop",ruleId:yt.ruleId,evidence:{command:Et,segment:yt.target}}}}if(!mi(D))return{stage:"non-command",...ht,decision:{kind:"allow"}};if(!D.command||D.command.trim()==="")return{...kc("command-validation",te),...ht};let vt=hr("command-analysis",te,()=>Gp(()=>z.analyzeCommand(D.command,{cwd:D.context.executionCwd,shell:D.route.shell,policySnapshot:mt,environment:N.environment,protectedGitMetadata:ct,effectiveCapabilities:pt.capabilities,strict:pt.strict,paranoidRm:pt.paranoidRm,paranoidInterpreters:pt.paranoidInterpreters,worktreeMode:pt.worktreeMode,budget:lt,...N.trace?{trace:N.trace}:{}},JP(he),he.store),D.command,N.trace));if(vt.decision){let Et=!pt.strict&&(vt.decision.ruleId==="raw-text.dangerous-command"||vt.decision.reason===Jo&&!YP.test(vt.decision.evidence?.segment??"")&&xn(D.command)===null);return{stage:"command-analysis",...ht,..."errorCode"in vt?{errorCode:vt.errorCode}:{},decision:Et?{...vt.decision,unverifiedByStandardMode:!0}:vt.decision}}return{stage:"command-analysis",...ht,decision:{kind:"allow"}}}function ZP(D,N){let z=[...new Set(D.filter((ee)=>typeof ee==="string"&&ee!==""))].flatMap((ee)=>N.gitMetadata(ee)??[]);if(z.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(z.flatMap((ee)=>ee.entries))]),markerFiles:Object.freeze([...new Set(z.flatMap((ee)=>ee.markerFiles))]),directories:Object.freeze([...new Set(z.flatMap((ee)=>ee.directories))]),hooksDirectories:Object.freeze([...new Set(z.flatMap((ee)=>ee.hooksDirectories))])})}function XP(D){if(D.state==="ready")return{};return{configFallback:{reason:D.reason}}}function JP(D){return un(D,"declared-command")?.program}function QP(D){try{return ne(D.input)}catch(N){let z=mi(D)?D.command:void 0;throw new p("policy-protection",kc("policy-protection",N instanceof f?void 0:z,N),N)}}function hr(D,N,z){try{return z()}catch(ee){throw new p(D,kc(D,ee instanceof f?void 0:N,ee),ee)}}function kc(D,N,z){let ee=z instanceof s||z instanceof y;return{stage:D,decision:{kind:"deny",reason:ee?Xs:bo,intent:"stop_and_explain",...N?{evidence:{command:N,segment:N}}:{}}}}function mi(D){return D.route.kind==="command"}
|
|
44
|
+
`||je==="\r"))return null;if(D.startsWith(z,he))return he}return null}function bP(D,N){for(let z=N-1;z>=0;z--){let ee=D[z];if(!ee||/\s/.test(ee))continue;return/[\w$\])]/.test(ee)}return!1}function SP(D){for(let N of D.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let z=N[0],ee=N.index;if(ww.has(z.toLowerCase()))return!0;let te=z.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((he)=>he.toLowerCase());if(!te.some((he)=>Pw.has(he)))continue;if(te.length>1)return!0;if(CP(D,ee)===".")return!0;if(vP(D,ee+z.length)==="(")return!0}return!1}function CP(D,N){for(let z=N-1;z>=0;z--)if(!/\s/.test(D[z]??""))return D[z];return}function vP(D,N){for(let z=N;z<D.length;z++)if(!/\s/.test(D[z]??""))return D[z];return}function EP(D,N,z,ee,te,he){return PP(D).flatMap((je)=>{let at=N.getShellSyntax(je);if(at.status==="invalid")return[];return[...go(at,N,{...z,displayOperandsAreCapturedOutput:!0},ee,te,he),...xP(at,ee)?RP(at,ee).map((lt)=>({target:lt,cwd:te})):[]]})}function xP(D,N){let z=cs(D);for(let ee=0;ee<z.length;ee++){let te=z[ee];if(te?.kind!=="word"||Wn(Zn(te.text,N)).toLowerCase()!=="base64")continue;for(let he=ee+1;he<z.length;he++){let je=z[he];if(je?.kind==="operator")break;if(je?.kind!=="word")continue;let at=Zn(je.text,N);if(at==="--decode"||!at.startsWith("--")&&at.startsWith("-")&&/[dD]/.test(at))return!0}}return!1}function RP(D,N){return cs(D).flatMap((z)=>z.kind==="word"?[Zn(z.text,N)]:z.kind==="redirection"&&z.target?[Zn(z.target,N)]:[]).flatMap(Ac)}function Ac(D){let N=wP(D);if(N===null)return[];let z=Buffer.from(N,"base64").toString("utf8");if(z===""||_P(z))return[];return Buffer.from(z,"utf8").toString("base64").replace(/=+$/g,"")===N.replace(/=+$/g,"")?[z]:[]}function _P(D){return Array.from(D).some((N)=>{let z=N.charCodeAt(0);return z<32||z===127})}function wP(D){if(D.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(D))return null;if(/=/.test(D.replace(/=+$/g,"")))return null;let N=D.replace(/=+$/g,"");if(N.length%4===1)return null;return`${N.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-N.length%4)%4)}`}function PP(D){let N=[],z={inSingle:!1,inDouble:!1,escaped:!1};for(let ee=0;ee<D.length;ee++){let te=D[ee];if(!te)break;if(Ao(te,z))continue;if(fg(D,ee,z)){let he=AP(D,ee+1);if(he!==null)N.push(he.body),ee=he.endIndex;continue}if(!z.inSingle&&te==="`"){let he=TP(D,ee);if(he!==null)N.push(he.body),ee=he.endIndex}}return N}function AP(D,N){let z={inSingle:!1,inDouble:!1,escaped:!1},ee=1;for(let te=N+1;te<D.length;te++){let he=D[te];if(!he)break;if(Ao(he,z))continue;if(fg(D,te,z)){ee++,te++;continue}if(!z.inSingle&&!z.inDouble&&he===")"){if(ee--,ee===0)return{body:D.slice(N+1,te),endIndex:te}}}return null}function TP(D,N){let z=!1;for(let ee=N+1;ee<D.length;ee++){let te=D[ee];if(!te)break;if(z){z=!1;continue}if(te==="\\"){z=!0;continue}if(te==="`")return{body:D.slice(N+1,ee),endIndex:ee}}return null}function fg(D,N,z){return!z.inSingle&&D[N]==="$"&&D[N+1]==="("&&D[N+2]!=="("}function IP(D){let N=[],z=[],ee=!1,te=!1,he=!1;for(let lt=0;lt<D.length;lt++){let ct=D[lt];if(ct===void 0)break;if(!he&&ct==="--"){he=!0;continue}if(he){z.push(ct);continue}let dt=/^--([^=]+)(?:=(.*))?$/.exec(ct);if(dt!==null){let ft=dt[1]??"",ut=dt[2];if(ft===Dw)te=!0;if(Lw.has(ft))ee=!0;if(ut!==void 0){if(ft===qp)N.push(ut);continue}if(Gw.has(ft)){let mt=D[lt+1];if(ft===qp&&mt!==void 0)N.push(mt);lt++}continue}if(ct.startsWith("-")&&ct.length>1){let ft=ct.slice(1),ut="",mt="";for(let pt=0;pt<ft.length;pt++){let ht=ft[pt]??"";if(Nw.has(ht))ee=!0;if(Ww.has(ht)){ut=ht,mt=ft.slice(pt+1);break}}if(ut==="")continue;if(mt.length>0){if(ut===Kp)N.push(mt);continue}let gt=D[lt+1];if(ut===Kp&>!==void 0)N.push(gt);lt++;continue}z.push(ct)}let at=!ee&&!te?z.slice(1):z;return[...N,...at]}function tr(D){let N=D.findIndex((z)=>!mg(z)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(z));return N===-1?[]:D.slice(N)}function mg(D){return D==="env"||D==="command"||D==="builtin"||D==="sudo"}var kP=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),OP=".env.",MP=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),DP=[".env.example.",".env.sample."];function NP(D){let N;try{N=new URL(D.trim())}catch{return!1}return N.protocol!=="file:"&&N.host!==""}function LP(D){return D.length>0&&!/\s/.test(D)}function xc(D,N,z,ee){let te=pg(D,N,z,ee);return te!==""&&z.paths.entryKind(te)!=="missing"}function pg(D,N,z,ee){try{return fi(D,N,z,ee)}catch(te){if(te instanceof s)throw te;return""}}var WP=new Set(["node_modules","__pycache__"]),GP=[["vendor","bundle"],["vendor","cache"]];function FP(D,N,z,ee,te){if(NP(D))return null;let he=Un(D,N,ee,te);if(!he)return null;let je=Wt(he.split("/").pop()??""),at=Wt(he),lt=()=>LP(je)||xc(D,N,ee,te);if(MP.has(je)||DP.some((ut)=>je.startsWith(ut)))return null;let ct=Wt(jP(D,N,ee,te));for(let ut of Pa){let mt=`~/${ut.suffixParts.join("/")}`;if((ng(at,mt)||ng(ct,mt))&&er(ut.id,z))return ut.id}let dt=zP(he,N,z,ee,te);if(dt)return dt;if(kP.has(je))return null;for(let ut of wa)if(je===ut.basename&&er(ut.id,z))return ut.id;if(je.startsWith(OP)&&er(Ii.id,z)&<())return Ii.id;for(let ut of Aa)if(je.length>ut.prefix.length&&je.startsWith(ut.prefix)){let mt=je.slice(ut.prefix.length)[0];if((mt==="-"||mt==="_")&&er(ut.id,z)&<())return ut.id}for(let ut of Ta)if(je.length>ut.prefix.length&&je.startsWith(ut.prefix)){if(je.slice(ut.prefix.length)===ut.suffix&&er(ut.id,z))return ut.id}if(UP(at))return null;if(!je.includes(".")&&To.pattern.test(je)&&er(To.id,z))return To.id;let ft=HP(je,z);if(ft)return ft;return null}function zP(D,N,z,ee,te){return ki.find((he)=>{if(!er(he.id,z))return!1;switch(he.id){case"secret.cli.claude-code":return Dt(D,zt(ee.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",N,ee,te),[".credentials.json"]);case"secret.cli.claude-code.config":{let je=Wt(D).split("/");return Dt(D,zt(ee.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",N,ee,te),["settings.json","settings.local.json"])||di(D,"~/.claude.json",N,ee,te)||je.at(-1)==="settings.local.json"&&je.at(-2)===".claude"||je.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Dt(D,Un("~/.gemini/config",N,ee,te),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let je=zt(ee.env.get("CODEX_HOME"),"~/.codex",N,ee,te);return Dt(D,je,["auth.json",".credentials.json"])||ui(D,je,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let je=zt(ee.env.get("CODEX_HOME"),"~/.codex",N,ee,te),at=Wt(D).split("/").at(-1)??"";return Dt(D,je,["config.toml"])||at.endsWith(".config.toml")&&Dt(D,je,[at])}case"secret.cli.gemini":return Dt(D,rn(zt(ee.env.get("GEMINI_CLI_HOME"),"~",N,ee,te),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let je=Wt(D).split("/"),at=ee.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),lt=ee.env.get("ProgramData")?[rn(zt(ee.env.get("ProgramData"),"",N,ee,te),"gemini-cli")]:[];return Dt(D,rn(zt(ee.env.get("GEMINI_CLI_HOME"),"~",N,ee,te),".gemini"),["settings.json","google_accounts.json"])||je.at(-1)==="settings.json"&&je.at(-2)===".gemini"||(at?.trim()?di(D,at,N,ee,te):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...lt].some((ct)=>Dt(D,Un(ct,N,ee,te),["settings.json"]))}case"secret.cli.copilot-cli":{let je=zt(ee.env.get("COPILOT_HOME"),"~/.copilot",N,ee,te);return Dt(D,je,["config.json"])||ui(D,je,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Dt(D,zt(ee.env.get("COPILOT_HOME"),"~/.copilot",N,ee,te),["mcp-config.json"]);case"secret.cli.kimi-code":{let je=zt(ee.env.get("KIMI_CODE_HOME"),"~/.kimi-code",N,ee,te),at=zt(ee.env.get("KIMI_SHARE_DIR"),"~/.kimi",N,ee,te);return Dt(D,je,["server.token"])||ui(D,je,["credentials"])||ui(D,at,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let je=["config.toml","mcp.json"],at=Wt(D).split("/");return at.at(-1)==="mcp.json"&&at.at(-2)===".kimi-code"||Dt(D,zt(ee.env.get("KIMI_CODE_HOME"),"~/.kimi-code",N,ee,te),je)||Dt(D,zt(ee.env.get("KIMI_SHARE_DIR"),"~/.kimi",N,ee,te),[...je,"config.json","config.json.bak"])}case"secret.cli.opencode":{let je=rn(zt(ee.env.get("XDG_DATA_HOME"),"~/.local/share",N,ee,te),"opencode"),at=Wt(D).split("/").at(-1)??"",lt=ee.env.get("OPENCODE_DB")?.trim(),ct=lt&<!==":memory:"?[lt,`${lt}-wal`,`${lt}-shm`]:[];return Dt(D,je,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(at)&&Dt(D,je,[at])||ct.some((dt)=>di(D,dt,N,ee,te))}case"secret.cli.opencode.config":{let je=rn(zt(ee.env.get("XDG_CONFIG_HOME"),"~/.config",N,ee,te),"opencode"),at=ee.env.get("ProgramData")?[rn(zt(ee.env.get("ProgramData"),"",N,ee,te),"opencode")]:[],lt=["opencode.json","opencode.jsonc"],ct=ee.env.get("OPENCODE_CONFIG");return lt.includes(Wt(D).split("/").at(-1)??"")||Dt(D,je,["config.json"])||(ct?.trim()?di(D,ct,N,ee,te):!1)||["/Library/Application Support/opencode","/etc/opencode",...at].some((dt)=>Dt(D,Un(dt,N,ee,te),lt))}case"secret.cli.pi":return Dt(D,zt(ee.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",N,ee,te),["auth.json"]);case"secret.cli.pi.config":return Dt(D,zt(ee.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",N,ee,te),["models.json"]);case"secret.cli.amp":{let je=Un("~",N,ee,te);return[rn(zt(ee.env.get("XDG_DATA_HOME"),"~/.local/share",N,ee,te),"amp"),rn(je,".local","share","amp")].some((lt)=>Dt(D,lt,["secrets.json"]))||ui(D,rn(je,".amp"),["oauth"])}case"secret.cli.amp.config":{let je=["settings.json","settings.jsonc"],at=[rn(zt(ee.env.get("XDG_CONFIG_HOME"),"~/.config",N,ee,te),"amp"),rn(Un("~",N,ee,te),".config","amp")],lt=Wt(D).split("/"),ct=ee.env.get("AMP_SETTINGS_FILE");return at.some((dt)=>Dt(D,dt,je))||lt.at(-2)===".amp"&&je.includes(lt.at(-1)??"")||(ct?.trim()?di(D,ct,N,ee,te):!1)}case"secret.cli.cursor":{let je=rn(zt(ee.env.get("XDG_CONFIG_HOME"),"~/.config",N,ee,te),"cursor"),at=rn(zt(ee.env.get("CURSOR_DATA_DIR"),"~/.cursor",N,ee,te),"projects");return Dt(D,Un("~/.cursor",N,ee,te),["auth.json"])||Dt(D,je,["auth.json"])||Wt(D).split("/").at(-1)==="mcp-auth.json"&&Gr(Wt(D),Wt(at))}case"secret.cli.cursor.config":{let je=Wt(D).split("/");return je.at(-1)==="mcp.json"&&je.at(-2)===".cursor"}case"secret.cli.grok-build":return Dt(D,zt(ee.env.get("GROK_HOME"),"~/.grok",N,ee,te),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let je=Wt(D).split("/");return je.at(-1)==="config.toml"&&je.at(-2)===".grok"||Dt(D,zt(ee.env.get("GROK_HOME"),"~/.grok",N,ee,te),["config.toml","managed_config.toml","requirements.toml"])||Dt(D,Un("/etc/grok",N,ee,te),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var tg=new WeakMap;function zt(D,N,z,ee,te){let he=tg.get(te)??new Map;tg.set(te,he);let je=`${z}\x00${D??""}\x00${N}`,at=he.get(je);if(at!==void 0)return at;let lt=Un(D?.trim()?D:N,z,ee,te);return he.set(je,lt),lt}function Dt(D,N,z){return z.some((ee)=>gg(D,rn(N,ee)))}function ui(D,N,z){return z.some((ee)=>Gr(Wt(D),Wt(rn(N,ee))))}function di(D,N,z,ee,te){return gg(D,Un(N,z,ee,te))}function gg(D,N){return Wt(D)===Wt(N)}function rn(D,...N){return Ln([D,...N].filter(Boolean).join("/"))}function BP(D,N,z,ee,te,he){if(z.length===0)return!1;let je=Wt(fi(D,N,te,he));return z.some((at)=>Gr(je,Wt(fi(at,ee,te,he))))}function $P(D,N,z,ee,te,he){if(z.length===0)return!1;let je=Wt(fi(D,N,te,he));if(!je)return!1;let at=te.env.get("HOME")??te.home,lt=at?Ln(Ot(gn(at),te.paths,he)):"",ct=Wt(lt),dt=te.env.get("CC_SAFETY_NET_HOME"),ft=Wt(dt?Ln(Ot(Ks(gn(dt)),te.paths,he)):lt&&Ln(Ot(`${lt}/.cc-safety-net`,te.paths,he)));if(ft&&Gr(je,ft))return!1;return z.some((ut)=>{let mt=Da(ut);if(mt&&rg.basename(je)!==Wt(mt.name))return!1;let gt=Wt(fi(mt?.root??ut,ee,te,he));if(!gt)return!1;if(ct&&(ct===gt||ct.startsWith(gt.endsWith("/")?gt:`${gt}/`)))return!1;return Gr(je,gt)&&!(mt&&je===gt)})}function UP(D){let N=D.split("/");return N.some((z)=>WP.has(z))||GP.some(([z,ee])=>N.some((te,he)=>te===z&&N[he+1]===ee))}function HP(D,N){let z=D.lastIndexOf("."),ee=z>0&&z<D.length-1?D.slice(z+1):"";if(ee==="")return null;for(let te of Ia)if(ee===te.extension&&er(te.id,N))return te.id;for(let te of ka)if(te.pattern.test(ee)&&er(te.id,N))return te.id;return null}function Wt(D){return D.toLowerCase()}function er(D,N){return!N?.disabledRules?.includes(D)}function Un(D,N,z,ee){let{home:te,normalized:he}=Tc(D,z,ee);if(!he)return"";if(!te)return he;let je=Ic(he,te),at=js(je)?je:Ln(Ks(N,je)),lt=Ln(Ot(at,z.paths,ee));if(!Gr(lt,te)){if(js(je))return lt;return lt===at?he:lt}let ct=lt.slice(te.length);return ct?`~${ct}`:"~"}function ng(D,N){return D===N||D.startsWith(`${N}/`)}function jP(D,N,z,ee){let{home:te,normalized:he}=Tc(D,z,ee);if(!he||!te)return"";let je=Ic(he,te),at=rg.normalize(js(je)?je:Ln(Ks(N,je))),lt=Ln(gn(z.env.get("HOME")??z.home)),ct=(ut)=>process.platform==="win32"?ut.toLowerCase():ut,dt=[te,lt].find((ut)=>ut!==""&&Gr(ct(at),ct(ut)));if(dt===void 0)return"";let ft=at.slice(dt.length);return ft?`~${ft}`:"~"}function fi(D,N,z,ee){let{home:te,normalized:he}=Tc(D,z,ee);if(!he)return"";let je=te?Ic(he,te):he;return Ln(Ot(js(je)?je:Ks(N,je),z.paths,ee))}function Tc(D,N,z){let ee=N.env.get("HOME")??N.home,te=ee?Ln(Ot(gn(ee),N.paths,z)):"",he=Ln(gn(VP(Zn(D,N))));return{home:te,normalized:he}}function VP(D){if(!D.trim().toLowerCase().startsWith("file:"))return D;try{return Sw(D)}catch{return D}}function Ic(D,N){if(D==="~")return N;if(D.startsWith("~/"))return rn(N,D.slice(2));return D}function KP(D){if(process.platform==="win32")return!0;return bw.parse(D).root.length>1}function Ln(D){let N=D.trim(),z=(N.includes("\\")&&KP(N)?N.replace(/\\/g,"/"):N).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(z==="/")return z;return z.replace(/\/+$/g,"")}function Gr(D,N){return D===N||D.startsWith(N.endsWith("/")?N:`${N}/`)}function Wn(D){return D.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??D}class p extends Error{stage;evaluation;name="GuardEvaluationError";constructor(D,N,z){super(`CC Safety Net ${D} dependency failed`,{cause:z});this.stage=D;this.evaluation=N}}var qP={findPolicyMutation:Hp,findGitMetadataMutation:Sf,resolveGitMetadata:ZP,loadPolicySnapshot:E,findSensitiveTarget:lg,analyzeCommand:Wp,getModes:R},YP=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function B(D,N){let z={...qP,...N.dependencies},ee=QP(D),te=mi(D)?D.command:ee,he=hr("policy-protection",te,()=>qo(D)),je=un(he,"input-candidate"),at=un(he,"declared-command");if(mi(D)&&D.command?.trim()&&at?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Fn,intent:"stop_and_explain",evidence:{command:D.command,segment:D.command}}};if(je?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:Ff,intent:"stop_and_explain"}};let lt=pn(),ct=hr("policy-protection",te,()=>z.resolveGitMetadata([D.context.executionCwd,D.context.configCwd],N.environment)),dt=hr("policy-protection",te,()=>z.findPolicyMutation(he,N.environment,lt));if(dt){let Et=te??dt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:$e,intent:"hard_stop",evidence:{command:Et,segment:dt.target}}}}let ft=hr("policy-protection",te,()=>zp(he,N.environment,lt));if(ft){let Et=te??ft.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Me,intent:"hard_stop",evidence:{command:Et,segment:ft.target}}}}let ut=hr("policy-protection",te,()=>z.findGitMetadataMutation(he,ct,N.environment,lt));if(ut){let Et=te??ut.target;return{stage:"policy-protection",decision:{kind:"deny",reason:x,intent:"hard_stop",evidence:{command:Et,segment:ut.target}}}}let mt=hr("config-load",te,()=>z.loadPolicySnapshot(N.environment,{...N.policyOptions,cwd:D.context.configCwd})),gt=mt.policy,pt=z.getModes(gt,N.environment.env),ht={level:pt.effectiveLevel,...XP(mt)},yt=gt.secretProtection.enabled===!1?null:hr("secret-protection",te,()=>z.findSensitiveTarget(he,gt.secretProtection,N.environment,lt,{strict:mi(D)||je?.program.dialect==="powershell"?pt.strict:void 0}));if(yt){let Et=te??yt.target;return{stage:"secret-protection",...ht,decision:{kind:"deny",reason:og,intent:"hard_stop",ruleId:yt.ruleId,evidence:{command:Et,segment:yt.target}}}}if(!mi(D))return{stage:"non-command",...ht,decision:{kind:"allow"}};if(!D.command||D.command.trim()==="")return{...kc("command-validation",te),...ht};let vt=hr("command-analysis",te,()=>Gp(()=>z.analyzeCommand(D.command,{cwd:D.context.executionCwd,shell:D.route.shell,policySnapshot:mt,environment:N.environment,protectedGitMetadata:ct,effectiveCapabilities:pt.capabilities,strict:pt.strict,paranoidRm:pt.paranoidRm,paranoidInterpreters:pt.paranoidInterpreters,worktreeMode:pt.worktreeMode,budget:lt,...N.trace?{trace:N.trace}:{}},JP(he),he.store),D.command,N.trace));if(vt.decision){let Et=!pt.strict&&(vt.decision.ruleId==="raw-text.dangerous-command"||vt.decision.reason===Jo&&!YP.test(vt.decision.evidence?.segment??"")&&xn(D.command)===null);return{stage:"command-analysis",...ht,..."errorCode"in vt?{errorCode:vt.errorCode}:{},decision:Et?{...vt.decision,unverifiedByStandardMode:!0}:vt.decision}}return{stage:"command-analysis",...ht,decision:{kind:"allow"}}}function ZP(D,N){let z=[...new Set(D.filter((ee)=>typeof ee==="string"&&ee!==""))].flatMap((ee)=>N.gitMetadata(ee)??[]);if(z.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(z.flatMap((ee)=>ee.entries))]),markerFiles:Object.freeze([...new Set(z.flatMap((ee)=>ee.markerFiles))]),directories:Object.freeze([...new Set(z.flatMap((ee)=>ee.directories))]),hooksDirectories:Object.freeze([...new Set(z.flatMap((ee)=>ee.hooksDirectories))])})}function XP(D){if(D.state==="ready")return{};return{configFallback:{reason:D.reason}}}function JP(D){return un(D,"declared-command")?.program}function QP(D){try{return ne(D.input)}catch(N){let z=mi(D)?D.command:void 0;throw new p("policy-protection",kc("policy-protection",N instanceof f?void 0:z,N),N)}}function hr(D,N,z){try{return z()}catch(ee){throw new p(D,kc(D,ee instanceof f?void 0:N,ee),ee)}}function kc(D,N,z){let ee=z instanceof s||z instanceof y;return{stage:D,decision:{kind:"deny",reason:ee?Xs:bo,intent:"stop_and_explain",...N?{evidence:{command:N,segment:N}}:{}}}}function mi(D){return D.route.kind==="command"}
|
|
45
45
|
export{a,s,V,ke,Ue,k,Ze,Ge,ye,P,A,be,Xe,c,o,He,xe,R,L,ve,Qe,f,q,ne,ce,et,We,d,Re,r,v,i,re,n,g,le,F,tt,nt,l,ue,de,rt,I,K,oe,S,ot,M,b,Se,j,u,J,Be,ze,O,w,T,pe,fe,Le,it,m,e,Te,we,Ve,qe,ie,Ce,se,_e,Y,U,Pe,me,G,Ke,H,Z,X,ae,Je,Ye,C,W,Ae,Ie,Oe,De,E,Ne,Ee,Fe,h,t,Q,ge,y,x,_,st,Me,$e,p,B};
|