cc-safety-net 2.0.7 → 2.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,64 +0,0 @@
1
- import{randomBytes as EX}from"node:crypto";import{closeSync as p3,constants as k$,fstatSync as l3,fsyncSync as TX,lstatSync as V0,mkdirSync as OZ,openSync as LZ,readdirSync as c3,readFileSync as SX,realpathSync as T0,renameSync as yX,rmdirSync as wX,statSync as m3,unlinkSync as d3,writeFileSync as vX}from"node:fs";import{isAbsolute as MZ,join as Q$,normalize as uX,parse as FZ,relative as i3,resolve as s3,sep as l$}from"node:path";var hX=Symbol("PolicyFilesystemScope"),gX=Symbol("PolicyFilesystemTarget"),NZ=k$.O_NOFOLLOW??0;class h extends Error{constructor($){super(`Unable to access ${$} filesystem safely.`);this.name="PolicyFilesystemError"}}function z1($,Z){return{[hX]:!0,root:s3($),label:Z}}function m$($,Z){let J=uX(Z);if(Z===""||MZ(Z)||J===".."||J.startsWith(`..${l$}`))throw new h($.label);return{[gX]:!0,scope:$,relativePath:J,path:Q$($.root,J)}}function X1($,Z){let J=i3($.root,s3(Z));return m$($,J)}function k2($,Z="rules policy"){let J=s3($),Q=FZ(J).dir;return m$(z1(Q,Z),i3(Q,J))}function K0($){try{if(!B1($,!1).exists)return null;let J=LZ($.path,k$.O_RDONLY|NZ);try{let Q=l3(J);if(!Q.isFile())throw new h($.scope.label);let X=SX(J,"utf-8"),W=V0($.path);if(!W.isFile()||W.isSymbolicLink()||Q.dev!==W.dev||Q.ino!==W.ino)throw new h($.scope.label);return B1($,!1),X}finally{p3(J)}}catch(Z){R0($.scope.label,Z)}}function VZ($,Z,J=384,Q){let X=`${$.path}.${EX(8).toString("hex")}.tmp`,W=null;try{lX($),B1($,!0),W=LZ(X,k$.O_CREAT|k$.O_EXCL|k$.O_WRONLY|NZ,J);let K=l3(W);if(!K.isFile())throw new h($.scope.label);vX(W,Z,"utf-8"),TX(W);let Y=l3(W);if(!Y.isFile()||Y.dev!==K.dev||Y.ino!==K.ino)throw new h($.scope.label);p3(W),W=null,B1($,!0),pX($,X,Y.dev,Y.ino),yX(X,$.path),Q?.($.path),B1($,!1)}catch(K){if(W!==null)dX(W);iX(X),R0($.scope.label,K)}}function RZ($,Z){if($.path===Z.path)return!0;try{if(!B1($,!1).exists||!B1(Z,!1).exists)return!1;return T0($.path)===T0(Z.path)}catch(J){if(J instanceof h)throw J;throw new h($.scope.label)}}function kX($){try{if(!B1($,!1,"directory").exists)return null;let J=c3($.path);return B1($,!1,"directory"),J}catch(Z){R0($.scope.label,Z)}}function OM($){let Z=kX($);if(!Z)return null;try{let J=Z.map((Q)=>{let X=m$($.scope,Q$($.relativePath,Q)),W=V0(X.path);if(W.isSymbolicLink()||!W.isFile()&&!W.isDirectory())throw new h($.scope.label);return x2(bZ($.scope),T0(X.path),$.scope.label),{name:Q,kind:W.isDirectory()?"directory":"file"}});return B1($,!1,"directory"),J}catch(J){R0($.scope.label,J)}}function LM($){try{if(!B1($,!0).exists)return;d3($.path),B1($,!0)}catch(Z){R0($.scope.label,Z)}}function MM($){try{IZ($,$.relativePath.split(l$))}catch(Z){R0($.scope.label,Z)}}function FM($){try{if(!xX($))return;zZ($),B1($,!0,"directory")}catch(Z){R0($.scope.label,Z)}}function xX($){try{if(!B1($,!0,"directory").exists)return!1;return DZ($),!0}catch(Z){R0($.scope.label,Z)}}function B1($,Z,J="file"){let Q=r3($.scope);if(!Q)return{exists:!1};let X=$.relativePath.split(l$);for(let W of X.keys()){let K=Q$($.scope.root,...X.slice(0,W+1)),Y=x$(K);if(!Y){if(W===X.length-1&&Z)return{exists:!1};return{exists:!1}}if(Y.isSymbolicLink())throw new h($.scope.label);if(W<X.length-1&&!Y.isDirectory())throw new h($.scope.label);if(W===X.length-1&&(J==="file"?!Y.isFile():!Y.isDirectory()))throw new h($.scope.label);x2(Q,T0(K),$.scope.label)}return{exists:!0}}function DZ($){for(let Z of c3($.path)){let J=m$($.scope,Q$($.relativePath,Z)),Q=V0(J.path);if(Q.isSymbolicLink()||!Q.isDirectory()&&!Q.isFile())throw new h($.scope.label);if(Q.isDirectory())DZ(J)}B1($,!1,"directory")}function zZ($){for(let Z of c3($.path)){let J=m$($.scope,Q$($.relativePath,Z)),Q=V0(J.path);if(Q.isSymbolicLink())throw new h($.scope.label);if(Q.isDirectory()){zZ(J);continue}if(!Q.isFile())throw new h($.scope.label);d3(J.path)}wX($.path)}function lX($){IZ($,$.relativePath.split(l$).slice(0,-1))}function IZ($,Z){mX($.scope);let J=bZ($.scope);for(let Q of Z.keys()){let X=Q$($.scope.root,...Z.slice(0,Q+1));if(!x$(X))OZ(X,{mode:448});let K=V0(X);if(!K.isDirectory()||K.isSymbolicLink())throw new h($.scope.label);x2(J,T0(X),$.scope.label)}}function mX($){if(x$($.root)){if(!m3($.root).isDirectory())throw new h($.label);return}let Z=[],J=$.root;while(!x$(J)){Z.unshift(J);let Q=FZ(J).dir;if(Q===J)throw new h($.label);J=Q}if(!m3(J).isDirectory())throw new h($.label);for(let Q of Z){OZ(Q,{mode:448});let X=V0(Q);if(!X.isDirectory()||X.isSymbolicLink())throw new h($.label)}}function r3($){if(!x$($.root))return null;if(!m3($.root).isDirectory())throw new h($.label);return T0($.root)}function bZ($){let Z=r3($);if(!Z)throw new h($.label);return Z}function pX($,Z,J,Q){let X=V0(Z);if(!X.isFile()||X.isSymbolicLink()||X.dev!==J||X.ino!==Q)throw new h($.scope.label);let W=r3($.scope);if(!W)throw new h($.scope.label);x2(W,T0(Z),$.scope.label)}function x2($,Z,J){let Q=i3($,Z);if(Q===".."||Q.startsWith(`..${l$}`)||MZ(Q))throw new h(J)}function x$($){try{return V0($)}catch(Z){if(cX(Z)&&Z.code==="ENOENT")return null;throw Z}}function R0($,Z){if(Z instanceof h)throw Z;throw new h($)}function cX($){return $ instanceof Error&&"code"in $}function dX($){try{p3($)}catch{}}function iX($){try{d3($)}catch{}}import{homedir as oX}from"node:os";import{dirname as i1,isAbsolute as tX,join as y1,relative as eX,resolve as s1,sep as $W}from"node:path";var I1=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,l2="rulebook.json",m2=".cc-safety-net/rules";var fZ=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,sX=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,rX=/^[A-Za-z0-9._-]+$/,nX=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),aX="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n3=new RegExp(`^${nX}/(${I1.source.slice(1,-1)})/${aX}$`);function PZ($){return`.cc-safety-net/rules/${$}/rulebook.json`}function p$($){if(W$($))try{return X$($),null}catch(Z){return Z instanceof Error?Z.message:String(Z)}return I1.test($)?null:`Local rulebook sources must be bare names matching ${I1}: ${$}`}function X$($){if($.startsWith("github:"))throw Error(`Invalid rulebook source: ${$}`);let Z=$.match(fZ);if(!Z?.[1]||!Z[2]||!Z[3])throw Error(`Invalid GitHub rulebook source: ${$}`);let[J,Q,...X]=Z[3].split("/");if(!J||!rX.test(J))throw Error(`GitHub rulebook refs must be a single path segment: ${$}`);if(!Q||X.length>0||!I1.test(Q))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${$}`);return{owner:Z[1],repo:Z[2],ref:J,path:PZ(Q),name:Q}}function CZ($){return sX.test($)}function W$($){return fZ.test($)}function a3($){if(!I1.test($))throw Error(`Local rulebook sources must be bare names matching ${I1}: ${$}`)}var EZ="rule.json",p2="policy.json",TZ="rule.lock",ZW="config.json",SZ=".cc-safety-net",JW="rules",AZ="cache",QW="CC_SAFETY_NET_HOME",w1="`cc-safety-net rule sync`";function XW($){return s1($??process.cwd(),m2)}function yZ($){return y1(XW($),EZ)}function Y0($){return $?.userConfigDir??($?.userConfigPath?i1($.userConfigPath):y1(WW(),JW))}function WW(){let $=process.env[QW];return $?s1($):y1(oX(),SZ)}function wZ($){return y1(Y0($),EZ)}function fM($){return y1(Y0($),TZ)}function S0($){return y1(i1($),TZ)}function PM($={}){return y1(i1(Y0($)),ZW)}function CM($={}){return s1($.cwd??process.cwd(),".safety-net.json")}function vZ($){let Z=$.userConfigPath??wZ($),J=$.projectConfigPath??yZ($.cwd),Q=uZ(Z,$),X=hZ(J,$);return{userConfigPath:Z,projectConfigPath:J,userLockPath:S0(Z),projectLockPath:S0(J),userScope:Q,projectScope:X,userConfigTarget:X1(Q,Z),projectConfigTarget:X1(X,J),userLockTarget:X1(Q,S0(Z)),projectLockTarget:X1(X,S0(J))}}function AM($){let Z=$.global?$.userConfigPath??wZ($):$.projectConfigPath??yZ($.cwd),J=$.global?uZ(Z,$):hZ(Z,$),Q=S0(Z);return{configDir:i1(Z),configPath:Z,lockPath:Q,filesystemScope:J,configTarget:X1(J,Z),lockTarget:X1(J,Q)}}function uZ($,Z){let J=Z.userConfigPath?i1(i1(s1(Z.userConfigPath))):i1(s1(Z.userConfigDir??Y0(Z)));return z1(J,"user policy")}function hZ($,Z){let J=s1(Z.cwd??process.cwd()),Q=s1($),X=eX(J,Q);if(X!==".."&&!X.startsWith(`..${$W}`)&&!tX(X))return z1(J,"project policy");return z1(i1(i1(Q)),"project policy")}function gZ($){if($.kind==="github"&&$.display_ref)return`${$.owner}/${$.repo}#${$.display_ref}/${$.name}`;return $.spec}function c2($,Z){let J=$.digest.startsWith("sha256:")?$.digest.slice(7):$.digest;return y1(kZ(Z),"rulebooks",`${KW($)}--${J.slice(0,12)}`,l2)}function EM($){return y1(kZ($),"rulebooks")}function d2($,Z){let J=Z;return{cacheConfigDir:$,cwd:Z.cwd,global:J.global}}function KW($){return($.kind==="github"&&$.display_ref?`${$.owner}/${$.repo}#${$.display_ref}/${$.name}`:$.spec).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"rulebook"}function kZ($){let Z=$?.cacheConfigDir??Y0($),J=$;if(J&&!J.global&&J.cwd&&s1(Z)===s1(J.cwd))return y1(s1(J.cwd),SZ,AZ);return y1(i1(Z),AZ)}import{lstatSync as xZ,readdirSync as YW,readFileSync as cZ,rmdirSync as BW,statSync as lZ,unlinkSync as qW,utimesSync as UW,writeFileSync as GW}from"node:fs";import{dirname as HW,join as K$}from"node:path";var i2=30,o3=1,t3=365;function s2($){if(typeof $!=="number"||!Number.isInteger($))return 30;if($<1)return 1;return $>365?365:$}var $6=86400000,jW=".last-prune",_W=/^\d{4}-\d{2}$/,OW=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,mZ=($)=>Math.floor($/$6);function LW($){try{let Z=K$(HW(Y0($)),p2),J=JSON.parse(cZ(Z,"utf-8"));return s2(J?.audit?.retention_days)}catch{return i2}}function dZ($,Z=()=>new Date){try{let J=Z().getTime();if(!lZ($,{throwIfNoEntry:!1})?.isDirectory())return;let Q=K$($,jW),X=lZ(Q,{throwIfNoEntry:!1})?.mtimeMs;if(X!==void 0&&mZ(X)===mZ(J))return;let W=J-LW()*$6,K=new Date(J).toISOString().slice(0,7);for(let Y of e3($)){if(Y.isDirectory()){MW(K$($,Y.name),W,K);continue}if(Y.isFile()&&Y.name.endsWith(".jsonl"))FW(K$($,Y.name),W)}GW(Q,"",{mode:384}),UW(Q,J/1000,J/1000)}catch{}}function MW($,Z,J){for(let Q of e3($)){if(!Q.isDirectory()||!_W.test(Q.name))continue;let X=K$($,Q.name);for(let W of e3(X)){if(!W.isFile())continue;let K=OW.exec(W.name);if(!K||K[2]!==Q.name)continue;let Y=Date.parse(`${K[1]}T00:00:00.000Z`)+$6;if(!Number.isFinite(Y)||Y>=Z)continue;iZ(K$(X,W.name))}if(Q.name!==J)pZ(X)}pZ($)}function FW($,Z){try{let J=xZ($);if(J.mtimeMs>=Z)return;let Q=cZ($,"utf-8").split(`
2
- `).filter((X)=>X.trim()).map(NW);if(Q.length===0)return;if(Q.some((X)=>X===void 0||X>=Z))return;if(xZ($).mtimeMs!==J.mtimeMs)return;iZ($)}catch{}}function NW($){try{let Z=JSON.parse($).ts,J=typeof Z==="string"?Date.parse(Z):Number.NaN;return Number.isFinite(J)?J:void 0}catch{return}}function e3($){try{return YW($,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function iZ($){try{qW($)}catch{}}function pZ($){try{BW($)}catch{}}import{randomBytes as IW}from"node:crypto";import{appendFileSync as bW,mkdirSync as fW}from"node:fs";import{homedir as PW,userInfo as CW}from"node:os";import{isAbsolute as AW,join as Z6}from"node:path";var VW=[/\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 B0($){let Z=$.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>");return sZ(Z)}function sZ($){let Z=$.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>");for(let J of VW)Z=Z.replace(J,"<redacted>");return Z.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 RW($){return rZ($).reduceRight((J,Q)=>`${J.slice(0,Q.valueStart)}<redacted>${J.slice(Q.valueEnd)}`,$)}function kM($){return sZ(RW($))}function xM($){return rZ($).map((Z)=>$.slice(Z.valueStart,Z.valueEnd))}function lM($){return/[A-Za-z_][A-Za-z0-9_]*=/.test($)}function rZ($){let Z=[],J=/[A-Za-z_][A-Za-z0-9_]*=/g;for(let Q of $.matchAll(J)){let X=Q.index,W=$[X-1];if(X>0&&W&&!/[\s"'([{]/.test(W))continue;let K=X+Q[0].length;if(K>=$.length)continue;Z.push({valueStart:K,valueEnd:DW($,K)})}return Z}function DW($,Z){if($.startsWith("$(",Z))return zW($,Z);let J=$[Z];if(J==='"'||J==="'"){for(let X=Z+1;X<$.length;X++)if(J==='"'&&$[X]==="\\")X++;else if($[X]===J)return X+1}let Q=Z;while(Q<$.length&&!/\s/.test($[Q]??""))Q++;return Q}function zW($,Z){let J=0,Q;for(let X=Z;X<$.length;X++){let W=$[X];if(Q){if(Q==='"'&&W==="\\")X++;else if(W===Q)Q=void 0;continue}if(W==='"'||W==="'"){Q=W;continue}if(W==="$"&&$[X+1]==="("){J++,X++;continue}if(W!==")")continue;if(J--,J===0)return X+1}return $.length}var EW="2.0.7",TW=1e4,SW=2000,yW=256,wW=32768;function vW($){let Z=$.trim();if(!Z)return null;let J=Z.replace(/[^A-Za-z0-9_.-]+/g,"_");if(J=J.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!J||J==="."||J==="..")return null;return J}function uW($){return($??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function J6($,Z,J,Q,X,W={}){let K=vW($);if(!K)return;let Y=W.homeDir??nZ();if(!Y)return;let B=hW(Y);if(!B)return;try{let q=(W.now??(()=>new Date))().toISOString(),U=r2(B0(Z),TW),G=r2(B0(J),SW),j=W.toolName?r2(B0(W.toolName),yW):void 0,H=X===null?void 0:r2(B0(X),wW),_=Z6(B,uW(H?.value??null),q.slice(0,7));fW(_,{recursive:!0,mode:448});let O=Z6(_,`${q.slice(0,10)}-${K}.jsonl`),M={ts:q,id:(W.createId??(()=>IW(8).toString("hex")))(),v:EW,sessionId:K,decision:W.decision??"deny",agent:W.agent,shape:W.shape,level:W.level,configFallback:W.configFallback,toolName:j?.value,command:U.value,segment:G.value,...U.truncated||G.truncated||j?.truncated||H?.truncated?{truncated:!0}:{},reason:Q,ruleId:W.ruleId,intent:W.intent,failureStage:W.failureStage,errorCode:W.errorCode,cwd:H?.value??null};bW(O,`${JSON.stringify(M)}
3
- `,{encoding:"utf-8",mode:384}),dZ(B,W.now)}catch{}}function r2($,Z){return{value:$.slice(0,Z),truncated:$.length>Z}}function nZ($=process.env.CC_SAFETY_NET_AUDIT_HOME||process.env.HOME){let Z=$||PW()||CW().homedir;return Z&&AW(Z)?Z:null}function hW($=nZ()){return $?Z6($,".cc-safety-net","logs"):null}function oZ($,Z,J,Q=!0,X){if(Z.decision.kind==="allow"){if(!J||$.route.kind!=="command")return;let Y=aZ($);return{decision:"allow",command:Y,segment:Y,reason:"allowed",cwd:$.context.executionCwd,toolName:$.toolName,level:Z.level,...Z.configFallback?{configFallback:!0}:{}}}let W=Z.decision.evidence.find((Y)=>Y.kind==="command"),K=W?.command??(Q?aZ($):"");return{decision:"deny",command:K,segment:W?.segment??K,reason:Z.decision.reason,cwd:$.context.executionCwd,toolName:$.toolName,level:Z.level,...Z.configFallback?{configFallback:!0}:{},ruleId:Z.decision.ruleId,intent:Z.decision.intent,failureStage:X?.stage,errorCode:X?.errorCode}}function aZ($){return"command"in $?$.command??"":""}function tZ($,Z,J){if(!$)return;let Q;try{Q=Z()}catch{return}if(typeof Q!=="string"||!Q.trim())return;J6(Q,$.command,$.segment,$.reason,$.cwd,{homeDir:J.homeDir,decision:$.decision,agent:J.agent,shape:J.shape,level:$.level,configFallback:$.configFallback,toolName:$.toolName,ruleId:$.ruleId,intent:$.intent,failureStage:$.failureStage,errorCode:$.errorCode})}function tM($,Z,J){let Q;try{Q=Z()}catch{return}if(typeof Q!=="string"||!Q.trim())return;J6(Q,$.command??"",$.segment??$.command??"",$.reason,J.cwd??null,{homeDir:J.homeDir,decision:"deny",agent:J.agent,shape:J.shape,toolName:J.toolName??$.toolName,ruleId:$.ruleId,intent:$.intent})}var D0="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",q0="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",eZ="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.",n2="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";function Z8($){let{reason:Z,command:J,segment:Q,toolName:X}=$,W=$.maxLen??200,K=$.redact??((B)=>B),Y=`BLOCKED by CC Safety Net
4
-
5
- Reason: ${K(Z)}`;if($.ruleId)Y+=`
6
-
7
- Rule: ${$.ruleId}`;if(X)Y+=`
8
-
9
- Tool: ${X}`;if(J){let B=K(J);Y+=`
10
-
11
- Command: ${$8(B,W)}`}if(Q&&Q!==J){let B=K(Q);Y+=`
12
-
13
- Segment: ${$8(B,W)}`}if($.configWarning)Y+=`
14
-
15
- Config warning: ${K($.configWarning)}`;return Y+=`
16
-
17
- ${gW($.intent??"manual_only")}`,Y}function gW($){switch($){case"hard_stop":return"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.";case"use_alternative":return"Do not retry the blocked form. Continue the task using the safer alternative described above.";case"scope_down":return"Retry with a narrower, explicit target as described above. Escalate to the user if the broad operation is truly required.";case"manual_only":return"If this operation is truly needed, ask the user for explicit permission and have them run the command manually.";case"stop_and_explain":return"Do not brute-force variants. Simplify or restructure the command so it can be analyzed, or report the block to the user."}}function $8($,Z){return $.length>Z?`${$.slice(0,Z)}...`:$}function WF($,Z){if($.decision.kind!=="deny")return;let J=Z.includeEvidence?$.decision.evidence.find((Q)=>Q.kind==="command"):void 0;return{reason:$.decision.reason,ruleId:$.decision.ruleId,intent:$.decision.intent,command:J?.command,segment:J?.segment,toolName:Z.toolName,...$.configFallback?{configWarning:$.configFallback.reason}:{}}}function KF($={}){return{reason:n2,intent:"stop_and_explain",command:$.command,segment:$.segment??$.command,toolName:$.toolName}}function YF($){return Z8({...$,redact:B0})}function BF($){return B0($ instanceof Error?$.message:String($))}import{basename as kW,dirname as xW,join as J8}from"node:path";var a2=Object.freeze({maxEnvironmentExpansionDepth:64,maxMissingSuffixComponents:256,maxRealpathAttempts:1024,maxProcessedCandidateBytes:4194304});class O1 extends Error{name="PathCanonicalizationLimitError";constructor(){super("Path canonicalization work limit exceeded.")}}function c$(){return{realpathAttempts:0,processedCandidateBytes:0,resolvedPaths:new Map}}function y0($){return{...c$(),environment:$}}var o2=new Set(["CC_SAFETY_NET_HOME","CLAUDE_CONFIG_DIR","CODEX_HOME","COPILOT_HOME","GEMINI_CLI_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 t2($,Z){return Q6($,0,Z)}function Q6($,Z,J){let Q="",X=0;while(X<$.length){if($[X]!=="$"){Q+=$[X],X++;continue}if($[X+1]==="{"){let K=X6($,X+2),Y=lW($,X,Z);if(Y===null){if(o2.has(K))throw new O1;Q+=$.slice(X);break}let B=$.slice(X,Y+1);Q+=mW(B,Z,J),X=Y+1;continue}let W=X6($,X+1);if(!W){Q+="$",X++;continue}Q+=W6(W,J)??`$${W}`,X+=W.length+1}return Q}function lW($,Z,J){let Q=1;for(let X=Z+2;X<$.length;X++){if($[X]==="\\"){X++;continue}if($[X]==="$"&&$[X+1]==="{"){if(Q++,J+Q>a2.maxEnvironmentExpansionDepth)throw new O1;X++;continue}if($[X]!=="}")continue;if(Q--,Q===0)return X}return null}function mW($,Z,J){let Q=$.slice(2,-1),X=X6(Q,0);if(!X)return $;let W=Q.slice(X.length);if(!W)return W6(X,J)??$;let K=[":-",":+",":=",":?","-","+","=","?"].find((q)=>W.startsWith(q));if(!K){if(o2.has(X))throw new O1;return $}if(!o2.has(X))return $;if(K.endsWith("="))throw new O1;let Y=W6(X,J),B=K.startsWith(":")?Y!==null&&Y!=="":Y!==null;if(K.endsWith("?")&&!B)throw new O1;if(K.endsWith("-")||K.endsWith("?"))return B?Y??"":Q6(W.slice(K.length),Z+1,J);return B?Q6(W.slice(K.length),Z+1,J):""}function X6($,Z){if(!/[A-Za-z_]/.test($[Z]??""))return"";let J=Z+1;while(/[A-Za-z0-9_]/.test($[J]??""))J++;return $.slice(Z,J)}function m($,Z,J=c$()){if(!$)return $;let Q=J.resolvedPaths.get($);if(Q!==void 0)return Q;let X=[],W=$;while(!0){if(J.realpathAttempts++,J.processedCandidateBytes+=Buffer.byteLength(W),J.realpathAttempts>a2.maxRealpathAttempts||J.processedCandidateBytes>a2.maxProcessedCandidateBytes)throw new O1;let K=Z.realpath(W);if(K!==null){let B=X.length===0?K:J8(K,...X.reverse());return J.resolvedPaths.set($,B),B}let Y=xW(W);if(Y===W){let B=X.length===0?W:J8(W,...X.reverse());return J.resolvedPaths.set($,B),B}if(X.length>=a2.maxMissingSuffixComponents)throw new O1;X.push(kW(W)),W=Y}}function W6($,Z){if(!o2.has($))return null;if($==="HOME")return Z.env.get("HOME")??Z.home;return Z.env.get($)??null}var pW=["git.ssh-env","git.alias-config","git.checkout-force","git.checkout-double-dash","git.checkout-ref-path","git.checkout-pathspec-from-file","git.checkout-ambiguous","git.switch-discard-changes","git.switch-force","git.restore-worktree","git.restore-unstaged","git.reset-hard","git.reset-merge","git.clean-force","git.rm-force","git.push-force","git.push-delete","git.push-mirror","git.branch-force-delete","git.rebase-abort","git.merge-abort","git.tag-delete","git.reflog-delete","git.stash-drop","git.stash-clear","git.worktree-remove-force","rm.recursive-force-root-or-home","rm.git-metadata","rm.recursive-force-dynamic-target","rm.recursive-force-home-cwd","rm.recursive-force-cwd-self","rm.recursive-force-outside-cwd","rm.recursive-force-paranoid","powershell.remove-item-root-or-home","powershell.remove-item-recursive-force-root-or-home","powershell.remove-item-git-metadata","powershell.remove-item-recursive-force-dynamic-target","powershell.remove-item-recursive-force-home-cwd","powershell.remove-item-recursive-force-cwd-self","powershell.remove-item-recursive-force-outside-cwd","powershell.remove-item-recursive-force-paranoid","powershell.remove-item-pipeline-dynamic-target","find.delete","find.delete-git-metadata","find.exec-rm-recursive-force","dd.device-write","mkfs.device","shred.target","interpreter.dangerous-command","interpreter.one-liner-paranoid","awk.system-dynamic","xargs.rm-recursive-force-dynamic","xargs.shell-dynamic","parallel.rm-recursive-force-dynamic","parallel.shell-dynamic","parallel.command-stream-dynamic","shell.dynamic-structure","shell.dynamic-executable","raw-text.dangerous-command"],e2=new Set(pW),$4=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores after --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"find.delete",category:"Filesystem",label:"find delete",description:"Blocks unsafe find -delete operations.",example:"find . -delete",intent:"scope_down"},{id:"find.delete-git-metadata",category:"Filesystem",label:"find delete Git metadata",description:"Blocks find -delete operations selecting protected Git metadata and hooks.",example:"find .git -delete",intent:"hard_stop",catastrophic:!0},{id:"find.exec-rm-recursive-force",category:"Filesystem",label:"find exec rm -rf",description:"Blocks find -exec rm -rf operations.",example:"find . -exec rm -rf {} +",intent:"scope_down"},{id:"dd.device-write",category:"Filesystem",label:"dd device write",description:"Blocks dd writing to a /dev device.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"mkfs device format",description:"Blocks mkfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],cW=new Map($4.map(($)=>[$.id,$.intent])),Q8=new Set($4.filter(($)=>$.catastrophic).map(($)=>$.id));function N($,Z){return{id:$,reason:Z,intent:cW.get($)??"manual_only"}}function T($,Z){if(!$)return null;if(Q8.has($.id))return $;if(Z?.destructiveCommandProtectionEnabled===!1)return null;let J=Z?.effectiveDestructiveCommandRules?.[$.id];if(J)return J.enabled?$:null;return Z?.destructiveCommandRuleOverrides[$.id]==="off"?null:$}function o($,Z,J){if(Q8.has(Z))return!0;if($?.destructiveCommandProtectionEnabled===!1)return!1;let Q=$?.effectiveDestructiveCommandRules?.[Z];if(Q)return Q.enabled;let X=$?.destructiveCommandRuleOverrides[Z];return X?X==="on":J}function K6($,Z){return Object.freeze(Object.fromEntries($4.map((J)=>{let Q=J.activationCapability?Z[J.activationCapability]:void 0,X=Q?.enabled??!0,W=$.destructiveCommandRuleOverrides[J.id],K=J.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...W?{override:W}:{}}:$.destructiveCommandProtectionEnabled?W?{enabled:W==="on",inheritedEnabled:X,changesInherited:W==="on"!==X,source:"rule_override",...J.activationCapability?{activationCapability:J.activationCapability}:{},override:W}:{enabled:X,inheritedEnabled:X,changesInherited:!1,source:Q?.source??"built_in_default",...J.activationCapability?{activationCapability:J.activationCapability}:{}}:{enabled:!1,inheritedEnabled:X,changesInherited:!1,source:"master_disabled",...J.activationCapability?{activationCapability:J.activationCapability}:{},...W?{override:W}:{}};return[J.id,Object.freeze(K)]})))}function X8($,Z){return Object.freeze({...$,effectiveDestructiveCommandRules:K6($,Z)})}var Z4=10,Y$=20,w0=/^[a-zA-Z][a-zA-Z0-9_-]*$/,B$=256,t=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),W8=new Set(["python","python3","python2","node","ruby","perl"]),K8=/^python(?:[23](?:\.\d+)*)?$/,J4=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"]);import{types as dW}from"node:util";var iW=new Set(["applypatch","patch"]),sW=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),rW=new Set(["grep","grepsearch","rg"]),nW=new Set(["find","findbyname","glob"]),aW=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),oW=new Set(["command","diff","input","patch","patchtext"]),Y8=new TextEncoder,tW=new TextDecoder,eW=/\s/,$K=64;class U0 extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var d$=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function H8($){return $.replace(/[-_\s]/g,"").toLowerCase()}function X4($){return aW.has(H8($))}function ZK($){let Z=H8($);if(iW.has(Z))return"patch";if(rW.has(Z))return"grep";if(nW.has(Z))return"glob";if(sW.has(Z))return"path";return"unknown"}function q$($){if(!$||typeof $!=="object")return;M8($);let Z=Object.getOwnPropertyDescriptor($,"command");if(!Z){if("command"in $)r1();return}if(Z.get||Z.set)r1();let J=Z.value;return typeof J==="string"&&J!==""?J:void 0}function U6($,Z){return j8($,Z,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function j8($,Z,J,Q){let X=L8($,J,Q);if(!X)return[];let W=X.entries.flatMap(([K,Y])=>{let B=j8(Y,Z,J,Q+1);return typeof Y==="string"&&Z.has(_8(K))?[Y]:B});return J.ancestors.delete(X.object),W}function _8($){return $.replace(/-/g,"_").toLowerCase()}function G6($){return O8($,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(QK)}function O8($,Z,J,Q){let X=L8($,J,Q);if(typeof $==="string")return Z?[$]:[];if(!X)return[];let W=X.entries.flatMap(([K,Y])=>O8(Y,X.array?Z:oW.has(_8(K)),J,Q+1));return J.ancestors.delete(X.object),W}function JK($,Z,J){if(Z.nodes++,$!==null&&typeof $==="object"&&J>d$.maxDepth||Z.nodes>d$.maxNodes)r1();if(typeof $!=="string")return;let Q=Buffer.byteLength($);if(Z.stringBytes+=Q,Q>d$.maxStringBytes||Z.stringBytes>d$.maxAggregateStringBytes)r1()}function L8($,Z,J){if(JK($,Z,J),!$||typeof $!=="object")return null;let Q=M8($);if(Z.ancestors.has($))r1();let X=Reflect.ownKeys($);if(Z.keys+=X.length,Z.keys>d$.maxKeys)r1();let W=X.flatMap((K)=>{let Y=Object.getOwnPropertyDescriptor($,K);if(!Y||Y.get||Y.set)r1();return typeof K==="string"&&Y.enumerable?[[K,Y.value]]:[]});return Z.ancestors.add($),{object:$,array:Q,entries:W}}function M8($){if(dW.isProxy($))r1();let Z=Array.isArray($),J=Object.getPrototypeOf($);if(Z&&J!==Array.prototype||!Z&&J!==Object.prototype&&J!==null)r1();return Z}function r1(){throw new U0}function QK($){let Z=[],J=$.split(/\r?\n/),Q=!1,X=!1,W=null,K=null,Y=()=>{X=!1,W=null,K=null};for(let B=0;B<J.length;B++){let q=J[B]??"";if(q==="*** Begin Patch"){Q=!0,Y();continue}if(q==="*** End Patch"){Q=!1,Y();continue}if(q.startsWith("@@")){let U=XK(q);if(X=!0,W=U?.oldLines??null,K=U?.newLines??null,W===0&&K===0)Y();continue}if(X&&W!==null&&K!==null){let U=q.startsWith(" ")||q.startsWith("-")?1:0,G=q.startsWith(" ")||q.startsWith("+")?1:0;if(W=Math.max(0,W-U),K=Math.max(0,K-G),W===0&&K===0)Y();continue}if(q.startsWith("*** ")){Y(),Z.push(...Y6(q));continue}if(X)continue;if(q.startsWith("diff --git ")){Z.push(...Y6(q));continue}if(q.startsWith("--- ")){let U=J[B+1]??"";if(!U.startsWith("+++ "))continue;Z.push(...q6(Q4(q.slice(4),!0),Q4(U.slice(4),!0))),B++;continue}if(!Q)Z.push(...Y6(q))}return Z}function XK($){let Z=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec($);if(!Z)return null;return{oldLines:Number(Z[1]??1),newLines:Number(Z[2]??1)}}function Y6($){let Z=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec($);if(Z?.[1])return G8(Z[1]);let J=/^\*\*\* Move to: (.+)$/.exec($);if(J?.[1])return G8(J[1]);if($.startsWith("diff --git "))return WK($.slice(11));let Q=/^--- (.+)$/.exec($);if(Q?.[1])return U8(Q[1]);let X=/^\+\+\+ (.+)$/.exec($);if(X?.[1])return U8(X[1]);let W=/^(?:rename|copy) (?:from|to) (.+)$/.exec($);if(W?.[1])return HK(W[1]);return[]}function WK($){let Z=KK($);if(Z.length===2&&Z[0]&&Z[1])return q6(Z[0],Z[1]);let J=YK($);return J?q6($.slice(J.oldStart,J.oldEnd),$.slice(J.newStart,J.newEnd)):[]}function KK($){let Z=[],J=0;while(J<$.length&&Z.length<2){while(v0($[J]))J++;if(J>=$.length)break;let Q=$[J]==='"'||$[J]==="'"?$[J]:void 0;if(!Q){let W=J;while(J<$.length&&!v0($[J]))J++;Z.push($.slice(W,J));continue}let X=F8($,J,Q);if(!X)return[];Z.push(X.value),J=X.end}while(v0($[J]))J++;return J===$.length?Z:[]}function YK($){let Z=0;while(Z<$.length&&v0($[Z]))Z++;let J=$.length;while(J>Z&&v0($[J-1]))J--;let Q=0,X=Z;while(X<J){if(!v0($[X])){X++;continue}let W=X;while(X<J&&v0($[X]))X++;if(W===Z||X===J)continue;if(Q++,Q>$K)r1();if(BK($,Z,W,X,J))return{oldStart:Z,oldEnd:W,newStart:X,newEnd:J}}return null}function BK($,Z,J,Q,X){if(B6($,Z,J,Q,X))return!0;let W=B8($,"/",Z,J),K=B8($,"/",Q,X);if(W<=Z||K<=Q)return!1;if(B6($,Z,W,Q,K))return!1;return B6($,W+1,J,K+1,X)}function B6($,Z,J,Q,X){if(J-Z!==X-Q)return!1;for(let W=0;W<J-Z;W++)if($[Z+W]!==$[Q+W])return!1;return!0}function B8($,Z,J,Q){for(let X=J;X<Q;X++)if($[X]===Z)return X;return-1}function v0($){return $!==void 0&&eW.test($)}function F8($,Z,J){let Q=[],X=Z+1;while(X<$.length){let W=$[X]??"";if(W===J)return{value:tW.decode(Uint8Array.from(Q)),end:X+1};if(W!=="\\"||J==="'"){Q.push(...Y8.encode(W)),X++;continue}let K=$.slice(X+1),Y=/^[0-7]{1,3}/.exec(K)?.[0];if(Y){Q.push(Number.parseInt(Y,8)),X+=Y.length+1;continue}Q.push(...Y8.encode(qK(K[0]??""))),X+=2}return null}function qK($){return{a:"\x07",b:"\b",f:"\f",n:`
18
- `,r:"\r",t:"\t",v:"\v"}[$]??$}function UK($){return i$(jK($))}function q6($,Z){if($==="/dev/null")return q8(Z);if(Z==="/dev/null")return q8($);if($.startsWith("a/")&&Z.startsWith("b/"))return[$.slice(2),Z.slice(2)].flatMap(i$);let J=GK($,Z)??($===Z?N8($):null);return[$,Z,...J?[J]:[]].flatMap(i$)}function q8($){let Z=N8($);return[$,...Z?[Z]:[]].flatMap(i$)}function N8($){let Z=$.indexOf("/");return Z>0&&Z<$.length-1?$.slice(Z+1):null}function GK($,Z){let J=$.indexOf("/"),Q=Z.indexOf("/");if(J<1||Q<1)return null;if($.slice(0,J)===Z.slice(0,Q))return null;let X=$.slice(J+1);return X===Z.slice(Q+1)?X:null}function U8($){return UK(Q4($,!0))}function HK($){return i$(Q4($,!1))}function Q4($,Z){let J=$.trim(),Q=J[0]==='"'||J[0]==="'"?J[0]:void 0;if(Q){let X=F8(J,0,Q);if(X&&(Z||J.slice(X.end).trim()===""))return X.value}return Z?J.split("\t",1)[0]?.trim()??"":J}function jK($){return $.startsWith("a/")||$.startsWith("b/")?$.slice(2):$}function i$($){return $===""||$==="/dev/null"?[]:[$]}function G8($){let Z=$.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return Z===""||Z==="/dev/null"?[]:[Z]}import{lstatSync as _K,realpathSync as OK}from"node:fs";import{homedir as LK,tmpdir as MK}from"node:os";var b1={realpath:($)=>{try{return OK($)}catch{return null}},entryKind:($)=>{let Z=_K($,{throwIfNoEntry:!1});if(!Z)return"missing";return Z.isSymbolicLink()?"symlink":"present"}};function u0(){return process.env.HOME||LK()}function G0(){return{env:new Map(Object.entries(process.env).flatMap(([$,Z])=>Z===void 0?[]:[[$,Z]])),home:u0(),tmpdir:MK(),paths:b1}}function W4(){return[]}function K4(){return[]}function Y4(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function FK($){return Object.freeze({...$,span:Object.freeze($.span),words:Object.freeze($.words),redirections:Object.freeze($.redirections.map((Z)=>Object.freeze({...Z,span:Object.freeze(Z.span),...Z.heredoc?{heredoc:Object.freeze({...Z.heredoc,bodySpan:Object.freeze(Z.heredoc.bodySpan),terminatorSpan:Object.freeze(Z.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze($.nested.map((Z)=>G1(Z)))})}function B4($,Z,J){$.push(J),Z.reset()}function NK($,Z,J,Q,X){if(Q<=J)return;$.push({raw:Z.slice(J,Q),span:{start:J,end:Q},provenance:X})}function q4($){let Z=[];return{parts:Z,push:(J,Q,X)=>NK(Z,$,J,Q,X)}}function H6($){let Z=$.parts??[{raw:$.raw,span:$.span,provenance:$.provenance}];return Object.freeze({kind:"word",...$,span:Object.freeze($.span),parts:Object.freeze(Z.map((J)=>Object.freeze({...J,span:Object.freeze(J.span)})))})}function U$($,Z,J,Q,X,W,K){return H6({text:Q,raw:$.slice(Z,J),span:{start:Z,end:J},provenance:X,quoted:W,...K?{parts:K}:{}})}function G1($){return Object.freeze({...$,span:Object.freeze($.span),issues:Object.freeze($.issues.map((Z)=>Object.freeze({...Z,span:Object.freeze(Z.span)}))),nodes:Object.freeze($.nodes.map((Z)=>{if(Z.kind==="command")return FK(Z);if(Z.kind==="group"||Z.kind==="function")return Object.freeze({...Z,span:Object.freeze(Z.span),body:G1(Z.body)});return Object.freeze({...Z,span:Object.freeze(Z.span)})}))})}function j6($,Z,J){if(Z>=J||R8($[Z]??""))return null;let Q="",X=!1,W=!1,K=Z;while(K<J&&!R8($[K]??"")){let Y=$[K]??"";if(Y==="'"){X=!0;let B=V8($,K+1,J,"'");Q+=B.text,W||=!B.closed,K=B.next;continue}if(Y==='"'){X=!0;let B=V8($,K+1,J,'"');Q+=B.text,W||=!B.closed,K=B.next;continue}if(Y==="\\"){X=!0;let B=$[K+1];if(!B||B===`
19
- `||B==="\r"){W=!0;break}Q+=B,K+=2;continue}if(Y==="`"||$.startsWith("$(",K)||$.startsWith("${",K)||$.startsWith("<(",K)||$.startsWith(">(",K))W=!0;Q+=Y,K++}return{delimiter:Q,quoted:X,next:K,span:{start:Z,end:K},ambiguous:W}}function _6($,Z,J,Q){let X=[],W=Z;for(let K of Q){let Y=W,B=!1;while(W<J){let q=VK($,W,J);if((K.stripTabs?q.text.replace(/^\t+/,""):q.text)===K.delimiter){K.attach({body:K.stripTabs?RK($.slice(Y,W)):$.slice(Y,W),delimiter:K.delimiter,quotedDelimiter:K.quotedDelimiter,stripTabs:K.stripTabs,bodySpan:{start:Y,end:W},terminatorSpan:{start:W,end:q.contentEnd}}),W=q.next,B=!0;break}if(q.next<=W)break;W=q.next}if(B)continue;return X.push({code:"unterminated-heredoc",message:`heredoc delimiter ${K.delimiter} was not found`,span:K.declarationSpan}),{next:J,issues:X,terminated:!1}}return{next:W,issues:X,terminated:!0}}function V8($,Z,J,Q){let X="",W=Z;while(W<J&&$[W]!==`
20
- `&&$[W]!=="\r"){let K=$[W]??"";if(K===Q)return{text:X,next:W+1,closed:!0};if(Q==='"'&&K==="\\"&&$[W+1]){let Y=$[W+1]??"";X+=["$","`",'"',"\\"].includes(Y)?Y:`\\${Y}`,W+=2;continue}X+=K,W++}return{text:X,next:W,closed:!1}}function R8($){return/[\s;&|<>)]/u.test($)||$==="`"}function VK($,Z,J){let Q=Z;while(Q<J&&$[Q]!==`
21
- `&&$[Q]!=="\r")Q++;let X=Q>=J?J:$[Q]==="\r"&&$[Q+1]===`
22
- `?Q+2:Q+1;return{text:$.slice(Z,Q),contentEnd:Q,next:X}}function RK($){return $.replace(/(^|\r\n?|\n)\t+/g,"$1")}var f8=new Set(["&&","||","|","|&"]);function P8($,Z,J){let Q={start:0,end:$.length};if($.length>J.maxInputLength)return G1({kind:"program",dialect:Z,source:$,span:Q,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${J.maxInputLength} UTF-16 code units`,span:Q}],nodes:[]});let X=H4($,0,$.length,Z,J,{used:0,max:J.maxWords},0);return G1({kind:"program",dialect:Z,source:$,span:Q,status:O4(X.issues,X.limited),issues:X.issues,nodes:X.nodes})}function H4($,Z,J,Q,X,W,K,Y){let B=W4(),q=K4(),U=Y4(),G=[],j=()=>{if(U.words.length===0&&U.redirections.length===0)return;let _={start:U.start,end:U.end},O=U.words.map((M)=>M.text);B4(B,U,{kind:"command",dialect:Q,source:$.slice(_.start,_.end),span:_,words:U.words,redirections:U.redirections,nested:U.nested,dynamicExecutable:U.words[0]?.provenance==="command-substitution",displayText:q.length>0&&B.length===0?$.slice(Z,J):O.join(" ")})},H=Z;while(H<J){let _=$[H];if(!_)break;if(Y&&_===Y)return j(),b8(B,q),{nodes:B,issues:q,next:H+1,closed:!0,limited:!1,pendingHeredocs:G};if(_4(_)){if(_===`
23
- `||_==="\r"){j();let A=_==="\r"&&$[H+1]===`
24
- `?H+2:H+1,F=B.at(-1);if(F?.kind!=="connector"||!f8.has(F.operator))B.push(Object.freeze({kind:"connector",operator:$.slice(H,A),span:Object.freeze({start:H,end:A})}));if(G.length>0){let R=_6($,A,J,G.splice(0));q.push(...R.issues),H=R.next;continue}H=A;continue}H++;continue}if(_==="#"){while(H<J&&$[H]!==`
25
- `&&$[H]!=="\r")H++;continue}let O=U.start===-1?xK($,H,J):void 0;if(O){if(L6(B,q,H),K>=X.maxDepth)return G$(B,q,H,"depth-limit",X.maxDepth);if(!O6(W))return G$(B,q,H,"word-limit",X.maxWords);let A=H4($,O.braceIndex+1,J,Q,X,W,K+1,"}"),F=A.next,R={start:O.braceIndex+1,end:A.closed?F-1:F},I=D8($,Q,R,A);if(B.push({kind:"function",name:O.name,span:{start:H,end:F},body:I}),q.push(...A.issues),A.pendingHeredocs.length>0||r$(A.nodes))q.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely",span:{start:H,end:F}});if(G.push(...A.pendingHeredocs),A.limited)return G4(B,q,A.next);if(!A.closed)q.push({code:"unclosed-function-body",message:"function body is not closed",span:{start:O.braceIndex,end:F}});H=F;continue}let M=j4($,H);if(M){if(j(),!v8(B.at(-1)))q.push({code:"unexpected-connector",message:`connector ${M} has no preceding command`,span:{start:H,end:H+M.length}});B.push(Object.freeze({kind:"connector",operator:M,span:Object.freeze({start:H,end:H+M.length})})),H+=M.length;continue}if(_===")"){j(),q.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis",span:{start:H,end:H+1}}),B.push({kind:"unknown",source:_,span:{start:H,end:H+1}}),H++;continue}if((_==="("||_==="{"&&CK($,H,J))&&U.start===-1){if(L6(B,q,H),K>=X.maxDepth)return G$(B,q,H,"depth-limit",X.maxDepth);let A=_==="("?")":"}",F=H4($,H+1,J,Q,X,W,K+1,A),R=F.next,I={start:H+1,end:F.closed?R-1:R},b=D8($,Q,I,F);if(B.push({kind:"group",style:_==="("?"subshell":"brace",span:{start:H,end:R},body:b}),q.push(...F.issues),F.pendingHeredocs.length>0||r$(F.nodes))q.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely",span:{start:H,end:R}});if(G.push(...F.pendingHeredocs),F.limited)return G4(B,q,F.next);if(!F.closed)q.push({code:_==="("?"unclosed-subshell":"unclosed-brace-group",message:`${_} group is not closed`,span:{start:H,end:R}});H=R;continue}let L=(_==="<"||_===">")&&$[H+1]!=="("?IK($,H):null;if(L){let A=U.words.at(-1),F=A&&A.span.end===H&&/^[0-9]+$/.test(A.raw)?Number(A.raw):void 0;if(F!==void 0)U.words.pop();let R=F===void 0?H:A?.span.start??H;U.start=U.start===-1?H:U.start;let I=H+L.length;while(I<J&&/[ \t]/.test($[I]??""))I++;let b=$[I],P=I>H+L.length&&b==="#",y=!b||_4(b)||!!j4($,I)||b===Y||b===")"||P||(b==="<"||b===">")&&$[I+1]!=="(",w=L==="<<"||L==="<<-"?j6($,I,J):void 0,x=w?{word:U$($,I,w.next,w.delimiter,"literal",w.quoted),nested:[],issues:[],next:w.next,limited:!1}:!y?M6($,I,J,Q,X,W,K):void 0;if(x){if(q.push(...x.issues),x.limited)return G4(B,q,x.next);if(!O6(W))return G$(B,q,x.next,"word-limit",X.maxWords)}let Y1=x?.next??H+L.length,C={kind:"redirection",operator:L,span:{start:R,end:Y1},...F===void 0?{}:{fd:F},...x?{target:x.word}:{}};if(U.redirections.push(C),L==="<<"||L==="<<-")if(!w)q.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word",span:{start:H,end:H+L.length}});else{if(w.ambiguous||w.delimiter.length===0)q.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely",span:w.span});G.push({delimiter:w.delimiter,quotedDelimiter:w.quoted,stripTabs:L==="<<-",declarationSpan:{start:R,end:Y1},attach:(v)=>{C.heredoc=v}})}else if(!x)q.push({code:"missing-redirection-target",message:`redirection ${L} requires a target word`,span:{start:H,end:H+L.length}});if(x)U.nested.push(...x.nested);U.end=Y1,H=Y1;continue}if(U.start===-1)L6(B,q,H);let D=M6($,H,J,Q,X,W,K);if(q.push(...D.issues),D.limited)return G4(B,q,D.next);let z=TK(U.words)?uK($,D.word,W.max-W.used,X.maxDepth,X.maxInputLength):void 0;if(z?.limitCode)return G$(B,q,D.next,z.limitCode,z.limitCode==="word-limit"?X.maxWords:z.limitCode==="depth-limit"?X.maxDepth:X.maxInputLength);let f=z?.words??[D.word];for(let A of f){if(!O6(W))return G$(B,q,D.next,"word-limit",X.maxWords);U.words.push(A)}U.start=U.start===-1?H:U.start,U.end=D.next,U.nested.push(...D.nested),H=D.next>H?D.next:H+1}return j(),b8(B,q),q.push(...lK(G)),{nodes:B,issues:q,next:H,closed:Y===void 0,limited:!1,pendingHeredocs:[]}}function D8($,Z,J,Q){return{kind:"program",dialect:Z,source:$.slice(J.start,J.end),span:J,status:O4(Q.issues,Q.limited),issues:Q.issues,nodes:Q.nodes}}function M6($,Z,J,Q,X,W,K){let Y="",B=Z,q=!1,U="literal",G=[],j=[],H=!1;while(B<J){let _=$[B],O=(_==="<"||_===">")&&$[B+1]==="(";if(!_||_4(_)||(_===";"||_==="|"||_==="&")&&j4($,B)||(_==="<"||_===">")&&!O)break;if(_===")")break;if(_==="'"){q=!0;let L=$.indexOf("'",B+1);if(L===-1||L>=J){Y+=$.slice(B+1,J),j.push({code:"unclosed-single-quote",message:"single-quoted word is not closed",span:{start:B,end:J}}),B=J;break}Y+=$.slice(B+1,L),B=L+1;continue}if(_==='"'){q=!0;let L=DK($,B,J,Q,X,W,K);if(Y+=L.text,G.push(...L.nested),j.push(...L.issues),H||=L.limited,U=s$(U,L.provenance),B=L.next,H)break;continue}if($.startsWith("$'",B)){q=!0;let L=bK($,B+2,J);if(Y+=L.text,j.push(...L.issues),!L.closed)j.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed",span:{start:B,end:J}});B=L.next;continue}if(_==="\\"){let L=$[B+1];if(!L){j.push({code:"trailing-escape",message:"escape has no following character",span:{start:B,end:B+1}}),B++;break}if(L===`
26
- `){B+=2;continue}Y+=L,B+=2;continue}let M=_==="$"||_==="<"||_===">"||_==="`"?F6($,B,J,Q,X,W,K):null;if(M){let L=C8(M,G,j);if(H||=L.limited,U=s$(U,L.provenance),B=L.next,H)break;continue}if(_==="$"){let L=T8($,B,J,Y,U);Y=L.text,U=L.provenance,B=L.next;continue}if(_==="*"||_==="?"||_==="[")U=s$(U,"glob");Y+=_,B++}return{word:U$($,Z,B,Y,U,q,U==="literal"?void 0:PK($,Z,B)),nested:G,issues:j,next:B,limited:H}}function DK($,Z,J,Q,X,W,K){let Y="",B="literal",q=[],U=[],G=!1,j=Z+1;while(j<J){let H=$[j];if(H==='"')return{text:Y,provenance:B,nested:q,issues:U,next:j+1,limited:G};if(H==="\\"&&$[j+1]){let O=$[j+1]??"";if(O===`
27
- `){j+=2;continue}if(O==="\r"&&$[j+2]===`
28
- `){j+=3;continue}Y+=["$","`",'"',"\\"].includes(O)?O:`\\${O}`,j+=2;continue}if($.startsWith("$((",j)){let O=N6($,j+3,J,"))"),M=O===-1?J:O+2;if(Y+=$.slice(j,M),O===-1)U.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:j,end:M}});j=M;continue}let _=F6($,j,J,Q,X,W,K);if(_){let O=C8(_,q,U);if(j=O.next,G||=O.limited,B=s$(B,O.provenance),G)return{text:Y,provenance:B,nested:q,issues:U,next:j,limited:G};continue}if(H==="$"){let O=T8($,j,J,Y,B);Y=O.text,B=O.provenance,j=O.next;continue}Y+=H??"",j++}return U.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:Z,end:J}}),{text:Y,provenance:B,nested:q,issues:U,next:J,limited:G}}function F6($,Z,J,Q,X,W,K){let Y=$.startsWith("$((",Z),B=$.startsWith("$(",Z)&&!Y,q=($.startsWith("<(",Z)||$.startsWith(">(",Z))&&!0,U=$[Z]==="`";if(!Y&&!B&&!q&&!U)return null;let G=Y?3:U?1:2,j=Y?"))":U?"`":")",H=N6($,Z+G,J,j),_=H===-1?J:H,O=H===-1?J:H+j.length;if(K>=X.maxDepth)return{program:kK($,Z+G,_,Q,"depth-limit"),next:O,provenance:Y?"arithmetic":"command-substitution"};if(Y){let z=[],f=[],A=!1,F=Z+G;while(F<_){let R=F6($,F,_,Q,X,W,K+1);if(!R){F++;continue}if(z.push(...R.program.nodes),f.push(...R.program.issues),A||=R.program.status==="limited",F=R.next,A)break}if(H===-1)f.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:Z,end:O}});return{program:G1({kind:"program",dialect:Q,source:$.slice(Z+G,_),span:{start:Z+G,end:_},status:O4(f,A),issues:f,nodes:z}),next:O,provenance:"arithmetic"}}let M=H4($,Z+G,_,Q,X,W,K+1),L=H===-1?[{code:Y?"unclosed-arithmetic":"unclosed-command-substitution",message:`${$.slice(Z,Z+G)} substitution is not closed`,span:{start:Z,end:O}}]:[],D=(U||q)&&r$(M.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions",span:{start:Z,end:O}}]:[];return{program:G1({kind:"program",dialect:Q,source:$.slice(Z+G,_),span:{start:Z+G,end:_},status:O4([...M.issues,...L,...D],M.limited),issues:[...M.issues,...L,...D],nodes:M.nodes}),next:O,provenance:Y?"arithmetic":"command-substitution"}}function C8($,Z,J){return Z.push($.program),J.push(...$.program.issues),{provenance:$.provenance,next:$.next,limited:$.program.status==="limited"}}function N6($,Z,J,Q){if(Q==="`"){for(let Y=Z;Y<J;Y++)if($[Y]==="\\")Y++;else if($[Y]==="`")return Y;return-1}let X=1,W={single:!1,double:!1},K=[];for(let Y=Z;Y<J;Y++){let B=$[Y];if((B===`
29
- `||B==="\r")&&K.length>0){let U=B==="\r"&&$[Y+1]===`
30
- `?Y+2:Y+1,G=_6($,U,J,K.splice(0));if(!G.terminated)return-1;Y=G.next-1;continue}let q=A8($,Y,Z,J,W);if(q!==null){Y=q;continue}if(!W.double&&$.startsWith("$((",Y)){let U=zK($,Y+3,J);if(U===-1)return-1;Y=U+1;continue}if(Q===")"&&!W.double&&B==="<"&&$[Y+1]==="<"&&$[Y+2]!=="<"){let U=$[Y+2]==="-",G=Y+(U?3:2);while(G<J&&/[ \t]/.test($[G]??""))G++;let j=j6($,G,J);if(j){K.push({delimiter:j.delimiter,quotedDelimiter:j.quoted,stripTabs:U,declarationSpan:{start:Y,end:j.next},attach:()=>{return}}),Y=j.next-1;continue}}if($.startsWith("$(",Y)&&!$.startsWith("$((",Y)){X++,Y++;continue}if(B==="("&&!W.double)X++;if(B===")"&&!W.double){if(X--,X===0)return Q==="))"&&$[Y+1]!==")"?-1:Y}}return-1}function zK($,Z,J){let Q=1,X={single:!1,double:!1};for(let W=Z;W<J;W++){let K=$[W],Y=A8($,W,Z,J,X);if(Y!==null){W=Y;continue}if($.startsWith("$(",W)&&!$.startsWith("$((",W)){Q++,W++;continue}if(K==="("&&!X.double)Q++;if(K!==")"||X.double)continue;if(Q--,Q===0)return $[W+1]===")"?W:-1}return-1}function A8($,Z,J,Q,X){let W=$[Z];if(W==="\\"&&!X.single)return Z+1;if(!X.double&&W==="'")X.single=!X.single;if(!X.single&&W==='"')X.double=!X.double;if(X.single)return Z;if(X.double||W!=="#"||!mK($,Z,J))return null;let K=Z;while(K+1<Q&&$[K+1]!==`
31
- `&&$[K+1]!=="\r")K++;return K}function j4($,Z){let J=$[Z];if(J===";")return";";if(J==="&")return $[Z+1]==="&"?"&&":"&";if(J==="|")return $[Z+1]==="|"?"||":$[Z+1]==="&"?"|&":"|";return null}function IK($,Z){let J=$[Z];if(J===">"){if($[Z+1]===">")return">>";if($[Z+1]==="&")return">&";return $[Z+1]==="|"?">|":">"}if(J!=="<")return null;if($.startsWith("<<<",Z))return"<<<";if($.startsWith("<<-",Z))return"<<-";if($[Z+1]==="<")return"<<";if($[Z+1]==="&")return"<&";if($[Z+1]===">")return"<>";return"<"}function _4($){let Z=$.charCodeAt(0);if(Z===32||Z>=9&&Z<=13)return!0;if(Z<128)return!1;return/\s/u.test($)}function E8($,Z,J){if($[Z+1]==="{"){let X=$.indexOf("}",Z+2);return X===-1||X>=J?J:X+1}let Q=Z+1;while(Q<J&&/[A-Za-z0-9_?@#$!*-]/.test($[Q]??""))Q++;return Q===Z+1?Z+1:Q}function bK($,Z,J){let Q="",X=[],W=Z;while(W<J){let K=$[W];if(K==="'")return{text:Q,next:W+1,closed:!0,issues:X};if(K!=="\\"){Q+=K??"",W++;continue}let Y=fK($,W+1,J);if(Q+=Y.text,Y.invalidCodePoint!==void 0)X.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${Y.invalidCodePoint}`,span:{start:W,end:Y.next}});W=Y.next}return{text:Q,next:J,closed:!1,issues:X}}function fK($,Z,J){let Q=$[Z];if(!Q||Z>=J)return{text:"\\",next:Z};let X=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
32
- `],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(X.has(Q))return{text:X.get(Q)??Q,next:Z+1};if(Q==="x")return U4($,Z+1,J,16,2,Z+1);if(Q==="u")return U4($,Z+1,J,16,4,Z+1);if(Q==="U")return U4($,Z+1,J,16,8,Z+1);if(/[0-7]/.test(Q))return U4($,Z,J,8,3,Z+1);return{text:Q,next:Z+1}}function U4($,Z,J,Q,X,W){let K=Q===16?/[0-9a-fA-F]/:/[0-7]/,Y="",B=Z;while(B<J&&Y.length<X&&K.test($[B]??""))Y+=$[B],B++;if(!Y)return{text:$[W-1]??"",next:W};let q=Number.parseInt(Y,Q);return q>1114111||q>=55296&&q<=57343?{text:"�",next:B,invalidCodePoint:q}:{text:String.fromCodePoint(q),next:B}}function O4($,Z=!1){if(Z)return"limited";if($.some((J)=>J.code==="invalid-ansi-c-code-point"||J.code==="missing-heredoc-delimiter"||J.code==="ambiguous-heredoc-delimiter"||J.code==="unterminated-heredoc"||J.code==="unsupported-heredoc-context"))return"invalid";return $.length>0?"partial":"complete"}function T8($,Z,J,Q,X){let W=E8($,Z,J);return{text:Q+$.slice(Z,W),provenance:s$(X,"variable"),next:W}}function PK($,Z,J){let Q=q4($),X=Z,W=!1,K=!1,Y=Z;while(Y<J){let B=$[Y];if(B==="\\"&&!W){Y+=2;continue}if(!K&&B==="'"){W=!W,Y++;continue}if(!W&&B==='"'){K=!K,Y++;continue}if(W){Y++;continue}let q=$.startsWith("$((",Y),U=$.startsWith("$(",Y)&&!q,G=!K&&($.startsWith("<(",Y)||$.startsWith(">(",Y)),j=B==="`";if(q||U||G||j){let H=q?3:j?1:2,_=q?"))":j?"`":")",O=N6($,Y+H,J,_),M=O===-1?J:O+_.length;Q.push(X,Y,"literal"),Q.push(Y,M,q?"arithmetic":"command-substitution"),Y=M,X=M;continue}if(B==="$"){let H=E8($,Y,J);if(H>Y+1){Q.push(X,Y,"literal"),Q.push(Y,H,"variable"),Y=H,X=H;continue}}if(!K&&(B==="*"||B==="?"||B==="[")){Q.push(X,Y,"literal"),Q.push(Y,Y+1,"glob"),Y++,X=Y;continue}Y++}return Q.push(X,J,"literal"),Q.parts}function s$($,Z){if(Z==="command-substitution"||$==="command-substitution")return"command-substitution";if(Z==="arithmetic"||$==="arithmetic")return"arithmetic";if(Z==="variable"||$==="variable")return"variable";if(Z==="glob"||$==="glob")return"glob";return $}function CK($,Z,J){return Z+1>=J||_4($[Z+1]??"")||j4($,Z+1)!==null}var AK=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),EK=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function TK($){let Z=0;while(Z<=$.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test($[Z]?.text??""))Z++;if(Z===$.length)return!0;let J=SK($,Z);if(J===void 0||J===null)return!1;Z=J}return!1}function SK($,Z){let J=$[Z]?.text.toLowerCase();if(J==="command")return yK($,Z);if(J==="env")return wK($,Z);if(J==="sudo")return vK($,Z);return}function yK($,Z){if($[Z+1]?.text==="-v")return null;for(let J=Z+1;J<$.length;J++){let Q=$[J]?.text??"";if(Q==="--")return J+1;if(Q==="-p"||Q==="-v"||Q==="-V"||/^-[pvV]+$/.test(Q))continue;return J}return $.length}function wK($,Z){for(let J=Z+1;J<$.length;J++){let Q=$[J]?.text??"";if(Q==="--")return J+1;if(AK.has(Q)){if($[J+1]===void 0)return null;J++;continue}if(Q.startsWith("-u=")||Q.startsWith("--unset=")||Q.startsWith("-C")&&Q.length>2||Q.startsWith("--chdir=")||Q.startsWith("-S")&&Q.length>2||Q.startsWith("--split-string=")||Q.startsWith("-P"))continue;if(Q.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(Q))continue;return J}return $.length}function vK($,Z){for(let J=Z+1;J<$.length;J++){let Q=$[J]?.text??"";if(Q==="--")return J+1;if(EK.has(Q)){if($[J+1]===void 0)return null;J++;continue}if(Q.startsWith("-"))continue;return J}return $.length}function S8($,Z,J,Q){if($.provenance!=="literal"||!$.raw.includes("{"))return;let X=[$.raw],W=$.raw.length,K=0;while(!0){let B=X.findIndex((_)=>I8(_));if(B===-1)break;if(++K>J)return{limited:!0};let q=X[B]??"",U=I8(q);if(!U||U.kind==="range")return{limited:!0};let G=U.start+q.length-U.end,j=U.alternatives.reduce((_,O)=>_+G+O.length,0);if(W-q.length+j>Q||X.length-1+U.alternatives.length>Z)return{limited:!0};let H=y8(q,U);X.splice(B,1,...H),W+=j-q.length}if(K===0)return;let Y=X.map((B)=>gK(B,J));if(Y.some((B)=>B===null))return{limited:!0};return{words:[...new Set(Y.filter((B)=>B!==null&&B!==""))]}}function uK($,Z,J,Q,X){if(Z.provenance!=="literal"||Z.quoted||Z.raw!==Z.text||!Z.raw.includes("{"))return;let W=[Z.text],K=Z.text.length,Y=0;while(!0){let q=W.findIndex((M)=>z8(M));if(q===-1)break;if(++Y>Q)return{limitCode:"depth-limit"};let U=W[q]??"",G=z8(U);if(!G)break;let j=G.start+U.length-G.end,H=G.alternatives.filter((M)=>j+M.length>0),_=H.reduce((M,L)=>M+j+L.length,0);if(K-U.length+_>X)return{limitCode:"brace-expansion-limit"};if(W.length-1+H.length>J)return{limitCode:"word-limit"};let O=y8(U,{...G,alternatives:H});W.splice(q,1,...O),K+=_-U.length}let B=W.filter((q)=>q.length>0);if(Y===0)return;return{words:B.map((q)=>U$($,Z.span.start,Z.span.end,q,"literal",!1))}}function z8($){let Z=[],J;for(let Q=0;Q<$.length;Q++){let X=$[Q];if(X==="{"){Z.push({start:Q,commas:[]});continue}if(X===","&&Z.length>0){Z.at(-1)?.commas.push(Q);continue}if(X!=="}"||Z.length===0)continue;let W=Z.pop();if(!W||W.commas.length===0)continue;if(!J||W.start<J.start)J={start:W.start,end:Q+1,commas:W.commas}}if(!J)return;return{start:J.start,end:J.end,alternatives:w8($,J)}}function I8($){let Z=[],J,Q=null,X=!1;for(let W=0;W<$.length;W++){let K=$[W];if(X){X=!1;continue}if(K==="\\"&&Q!=="'"){X=!0;continue}if(K===Q){Q=null;continue}if(Q===null&&(K==="'"||K==='"')){Q=K;continue}if(Q!==null)continue;if(K==="{"){Z.push({start:W,commas:[]});continue}if(K===","&&Z.length>0){Z.at(-1)?.commas.push(W);continue}if(K!=="}"||Z.length===0)continue;let Y=Z.pop();if(!Y)continue;let B=Y.commas.length>0?{kind:"alternatives",start:Y.start,end:W+1,commas:Y.commas}:hK($.slice(Y.start+1,W))?{kind:"range",start:Y.start,end:W+1}:void 0;if(B&&(!J||B.start<J.start))J=B}if(!J||J.kind==="range")return J;return{kind:J.kind,start:J.start,end:J.end,alternatives:w8($,J)}}function y8($,Z){return Z.alternatives.map((J)=>`${$.slice(0,Z.start)}${J}${$.slice(Z.end)}`)}function w8($,Z){let J=[Z.start,...Z.commas,Z.end-1];return J.slice(0,-1).map((Q,X)=>$.slice(Q+1,J[X+1]))}function hK($){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test($)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test($)}function gK($,Z){let J=`x${$}`,Q=M6(J,0,J.length,"posix",{maxInputLength:J.length,maxWords:1,maxDepth:Z},{used:0,max:1},0);if(Q.limited||Q.issues.length>0||Q.next!==J.length||Q.word.provenance!=="literal")return null;return Q.word.text.slice(1)}function kK($,Z,J,Q,X){return G1({kind:"program",dialect:Q,source:$.slice(Z,J),span:{start:Z,end:J},status:"limited",issues:[{code:X,message:"command structure exceeds parser limit",span:{start:Z,end:J}}],nodes:[]})}function G$($,Z,J,Q,X){return{nodes:$,issues:[...Z,{code:Q,message:`command structure exceeds parser limit ${X}`,span:{start:J,end:J}}],next:J,closed:!1,limited:!0,pendingHeredocs:[]}}function G4($,Z,J){return{nodes:$,issues:Z,next:J,closed:!1,limited:!0,pendingHeredocs:[]}}function O6($){return $.used++,$.used<=$.max}function xK($,Z,J){let Q=/^([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec($.slice(Z,J)),X=Q?.[1];if(!Q||!X)return;return{name:X,braceIndex:Z+Q[0].lastIndexOf("{")}}function r$($){return $.some((Z)=>{if(Z.kind==="command")return Z.redirections.some((J)=>J.heredoc)||Z.nested.some((J)=>r$(J.nodes));return(Z.kind==="group"||Z.kind==="function")&&r$(Z.body.nodes)})}function lK($){return $.map((Z)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${Z.delimiter} was not found`,span:Z.declarationSpan}))}function v8($){return $?.kind==="command"||$?.kind==="group"||$?.kind==="function"}function b8($,Z){let J=$.at(-1);if(J?.kind!=="connector"||!f8.has(J.operator))return;Z.push({code:"missing-command-after-connector",message:`connector ${J.operator} requires a following command`,span:J.span})}function L6($,Z,J){if(!v8($.at(-1)))return;Z.push({code:"missing-command-connector",message:"adjacent commands require a connector",span:{start:J,end:J+1}})}function mK($,Z,J){return Z===J||/[\s;&|()]/u.test($[Z-1]??"")}var u8=new Set(["remove-item","ri","del","erase","rd","rmdir"]),h8=["-rec","-for","-path","-literalpath","-whatif"],L4={maxInputLength:131072,maxWords:16384,maxDepth:64};function g8($){let Z=$.toLowerCase().replaceAll("`","");if(![...u8].some((Q)=>Z.includes(Q))&&!(Z.includes("rm")&&h8.some((Q)=>Z.includes(Q)))&&!Z.includes("<#"))return!1;let J=iK($);return J.invalidComment||J.commands.some(pK)}function pK($){let Z=$[0]==="&"||$[0]==="."?1:0,J=$[Z]?.toLowerCase();if(J&&u8.has(J))return!0;if(J!=="rm")return!1;return $.slice(Z+1).some((Q)=>{let X=Q.toLowerCase().split(":",1)[0]??"";return h8.some((W)=>X.startsWith(W))})}function k8($,Z){let J={start:0,end:$.length};if($.length>Z.maxInputLength)return G1({kind:"program",dialect:"powershell",source:$,span:J,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${Z.maxInputLength} UTF-16 code units`,span:J}],nodes:[]});let Q=I6($,0,$.length,Z,0);return G1({kind:"program",dialect:"powershell",source:$,span:J,status:sK(Q.issues,Q.limited),issues:Q.issues,nodes:Q.nodes})}function I6($,Z,J,Q,X,W=!1){let K=W4(),Y=K4(),B=Y4(),q=0,U=!1,G=()=>{if(B.words.length===0&&B.redirections.length===0)return;let H={start:B.start,end:B.end};B4(K,B,{kind:"command",dialect:"powershell",source:$.slice(H.start,H.end),span:H,words:B.words,redirections:B.redirections,nested:B.nested,dynamicExecutable:B.words[0]?.provenance!=="literal",displayText:B.words.map((_)=>_.text).join(" ")})},j=Z;while(j<J){let H=$[j];if(!H)break;if(W&&H==="}")return G(),{nodes:K,issues:Y,next:j+1,closed:!0,words:q,limited:U};let _=m8($,j,J,Q.maxDepth);if(_){if(_.issue)Y.push(_.issue);if(_.limited)return G(),{nodes:K,issues:Y,next:_.next,closed:!1,words:q,limited:!0};j=_.next;continue}if(/\s/.test(H)){if(H==="\r"||H===`
33
- `){G();let L=H==="\r"&&$[j+1]===`
34
- `?j+2:j+1;K.push(V6($,j,L)),j=L;continue}j++;continue}let O=b6($,j);if(O){G(),K.push(V6($,j,j+O.length)),j+=O.length;continue}if(H==="{"){if(G(),X>=Q.maxDepth)return Y.push(l8(j,Q.maxDepth)),{nodes:K,issues:Y,next:J,closed:!1,words:q,limited:!0};let L=I6($,j+1,J,Q,X+1,!0),D=L.closed?L.next-1:L.next,z=G1({kind:"program",dialect:"powershell",source:$.slice(j+1,D),span:{start:j+1,end:D},status:L.limited?"limited":L.issues.length>0?"partial":"complete",issues:L.issues,nodes:L.nodes});if(K.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:j,end:L.next}),body:z})),Y.push(...L.issues),!L.closed)Y.push({code:"unclosed-script-block",message:"PowerShell script block is not closed",span:{start:j,end:L.next}});q+=L.words,U||=L.limited,j=L.next;continue}if(H==="}"){G(),K.push(V6($,j,j+1)),j++;continue}if(H===">"||H==="<"){B.start=B.start===-1?j:B.start;let L=$[j+1]===H?j+2:j+1,D=L;while(/[ \t]/.test($[D]??""))D++;let z=D<J?R6($,D,J,Q,X):void 0,f=z?.next??L;if(B.redirections.push(Object.freeze({kind:"redirection",operator:$.slice(j,L),span:Object.freeze({start:j,end:f}),...z?{target:z.word}:{}})),z)Y.push(...z.issues),B.nested.push(...z.nested),q+=z.words,U||=z.limited;B.end=f,j=f;continue}if(H===","){B.start=B.start===-1?j:B.start,B.words.push(H6({text:",",raw:",",span:{start:j,end:j+1},provenance:"literal",quoted:!1})),B.end=++j;continue}let M=R6($,j,J,Q,X);if(B.start=B.start===-1?j:B.start,B.end=M.next,B.words.push(M.word),Y.push(...M.issues),B.nested.push(...M.nested),q+=1+M.words,U||=M.limited,q>Q.maxWords)return Y.push({code:"word-limit",message:`command exceeds ${Q.maxWords} words`,span:{start:j,end:M.next}}),G(),{nodes:K,issues:Y,next:M.next,closed:!1,words:q,limited:!0};j=M.next>j?M.next:j+1}return G(),{nodes:K,issues:Y,next:j,closed:!W,words:q,limited:U}}function R6($,Z,J,Q,X){let W="",K="literal",Y=!1,B=[],q=[],U=0,G=!1,j=(_)=>{let O=cK($,_,J,Q,X);return W+=$.slice(_,O.next),q.push(O.program),B.push(...O.program.issues),U+=D6(O.program),G||=O.program.status==="limited",K="command-substitution",O.next},H=Z;while(H<J){let _=$[H];if(!_||/\s/.test(_)||b6($,H)||_===">"||_==="<"||_==="#")break;if(_===",")break;if(_==="`"){let O=$[H+1];if(!O){B.push({code:"trailing-escape",message:"PowerShell escape has no following character",span:{start:H,end:H+1}}),H++;break}W+=O,H+=2;continue}if($.startsWith("$(",H)){H=j(H);continue}if(_==="'"){Y=!0,H++;let O=!1;while(H<$.length){if($[H]==="'"&&$[H+1]==="'"){W+="'",H+=2;continue}if($[H]==="'"){O=!0,H++;break}W+=$[H]??"",H++}if(!O)B.push({code:"unclosed-single-quote",message:"single-quoted word is not closed",span:{start:Z,end:$.length}});continue}if(_==='"'){Y=!0;let O=H++,M=!1;while(H<J){let L=$[H];if(L==="`"&&$[H+1]){W+=$[H+1],H+=2;continue}if(L==='"'){M=!0,H++;break}if($.startsWith("$(",H)){H=j(H);continue}if(L==="$")K=$[H+1]==="("?"command-substitution":"variable";W+=L??"",H++}if(!M)B.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:O,end:$.length}});continue}if(_==="$")K=$[H+1]==="("?"command-substitution":"variable";if(_==="@"&&H===Z)K="variable";W+=_,H++}return{word:U$($,Z,H,W,K,Y,K==="literal"?void 0:dK($,Z,H)),next:H,issues:B,nested:q,words:U,limited:G}}function cK($,Z,J,Q,X){let W=x8($,Z+2,J),K=W===-1?J:W,Y=W===-1?J:W+1;if(X>=Q.maxDepth)return{program:G1({kind:"program",dialect:"powershell",source:$.slice(Z+2,K),span:{start:Z+2,end:K},status:"limited",issues:[l8(Z,Q.maxDepth)],nodes:[]}),next:Y};let B=I6($,Z+2,K,Q,X+1),q=W===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed",span:{start:Z,end:Y}}]:[];return{program:G1({kind:"program",dialect:"powershell",source:$.slice(Z+2,K),span:{start:Z+2,end:K},status:B.limited?"limited":B.issues.length+q.length>0?"partial":"complete",issues:[...B.issues,...q],nodes:B.nodes}),next:Y}}function x8($,Z,J){let Q=1,X=!1,W=!1;for(let K=Z;K<J;K++){let Y=$[K];if(Y==="`"){K++;continue}if(!W&&Y==="'"){if(X&&$[K+1]==="'"){K++;continue}X=!X;continue}if(!X&&Y==='"'){W=!W;continue}if(X)continue;if($.startsWith("$(",K)){Q++,K++;continue}if(!W&&Y==="(")Q++;if(Y!==")")continue;if(Q--,Q===0)return K}return-1}function D6($){let Z=0;for(let J of $.nodes){if(J.kind==="group")Z+=D6(J.body);if(J.kind==="command"){Z+=J.words.length;for(let Q of J.nested)Z+=D6(Q)}}return Z}function dK($,Z,J){let Q=q4($),X=Z,W=!1,K=Z;while(K<J){let Y=$[K];if(Y==="`"){K+=2;continue}if(Y==="'"){if(W&&$[K+1]==="'"){K+=2;continue}W=!W,K++;continue}if(W){K++;continue}if($.startsWith("$(",K)){let B=x8($,K+2,J),q=B===-1?J:B+1;Q.push(X,K,"literal"),Q.push(K,q,"command-substitution"),K=q,X=q;continue}if(Y==="$"||Y==="@"&&K===Z){let B=K+1;if($[B]==="{"){let q=$.indexOf("}",B+1);B=q===-1||q>=J?J:q+1}else while(B<J&&/[A-Za-z0-9_:?]/.test($[B]??""))B++;Q.push(X,K,"literal"),Q.push(K,B,"variable"),K=B,X=B;continue}K++}return Q.push(X,J,"literal"),Q.parts}function l8($,Z){return{code:"depth-limit",message:`command structure exceeds parser limit ${Z}`,span:{start:$,end:$}}}function iK($){let Z=[],J=[],Q=0,X=0,W=!1,K=()=>{if(J.length>0)Z.push(J);J=[]};while(Q<$.length&&Q<131072&&X<16384){let Y=$[Q];if(Y==="\r"||Y===`
35
- `){K(),Q+=Y==="\r"&&$[Q+1]===`
36
- `?2:1;continue}if(/\s/.test(Y??"")){Q++;continue}let B=m8($,Q,Math.min($.length,L4.maxInputLength),L4.maxDepth);if(B){W||=!!B.issue||B.limited,Q=B.next;continue}let q=b6($,Q);if(q){K(),Q+=q.length;continue}if(Y==="{"||Y==="}"){K(),Q++;continue}let U=R6($,Q,Math.min($.length,L4.maxInputLength),L4,0);if(U.word.text)J.push(U.word.text);for(let G of U.nested)Z.push(...z6(G));X++,Q=U.next>Q?U.next:Q+1}return K(),{commands:Z,invalidComment:W}}function z6($){return $.nodes.flatMap((Z)=>{if(Z.kind==="group")return z6(Z.body);if(Z.kind!=="command")return[];return[Z.words.map((J)=>J.text),...Z.nested.flatMap(z6)]})}function b6($,Z){for(let J of["&&","||",";","|"])if($.startsWith(J,Z))return J;return null}function m8($,Z,J,Q){if($[Z]==="#"&&$[Z+1]!==">"){let K=Z+1;while(K<J&&$[K]!=="\r"&&$[K]!==`
37
- `)K++;return{next:K,limited:!1}}if(!$.startsWith("<#",Z))return null;let X=1,W=Z+2;while(W<J){if($.startsWith("<#",W)){if(X++,X>Q)return{next:J,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${Q}`,span:{start:Z,end:W+2}},limited:!0};W+=2;continue}if($.startsWith("#>",W)){if(X--,W+=2,X===0)return{next:W,limited:!1};continue}W++}return{next:J,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed",span:{start:Z,end:J}},limited:!1}}function sK($,Z){if(Z)return"limited";if($.some((J)=>J.code==="unclosed-block-comment"))return"invalid";return $.length>0?"partial":"complete"}function V6($,Z,J){return Object.freeze({kind:"connector",operator:$.slice(Z,J),span:Object.freeze({start:Z,end:J})})}var h0=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function v1($,Z="auto",J=h0){if(Z==="powershell"||Z==="auto"&&g8($.slice(0,J.maxInputLength)))return k8($,J);return P8($,"posix",J)}function f6($,Z){if($!=="powershell")return Z[0]?.provenance==="command-substitution";let J=Z[0]?.text==="&"||Z[0]?.text==="."?1:0,Q=Z[J]?.provenance;return Q!==void 0&&Q!=="literal"}var rK=/^[A-Za-z_][A-Za-z0-9_]*=/;function M4($,Z){return $?.provenance==="literal"&&!$.quoted&&$.raw===Z&&$.text===Z}function F4($){let Z=M4($.words[0],"time")?1:0,J=Z===1&&M4($.words[Z],"-p")?Z+1:Z,Q=Z===1&&M4($.words[J],"--")?J+1:J,X=M4($.words[Q],"!")?Q+1:Q,W=$.words.slice(X).find((K)=>!rK.test(K.text));return W?.provenance==="literal"?W.text:void 0}function n$($,Z){if(Z.escaped)return Z.escaped=!1,!0;if($==="\\"&&!Z.inSingle)return Z.escaped=!0,!0;if($==="'"&&!Z.inDouble)return Z.inSingle=!Z.inSingle,!0;if($==='"'&&!Z.inSingle)return Z.inDouble=!Z.inDouble,!0;return!1}function H$($){let Z={inSingle:!1,inDouble:!1,escaped:!1};for(let J of nK($))n$(J,Z);return Z.inSingle||Z.inDouble}function nK($){let Z="",J={inSingle:!1,inDouble:!1,escaped:!1},Q=!1,X=!0;for(let W=0;W<$.length;W++){let K=$[W];if(!K)break;if(Q){if(K===`
38
- `||K==="\r")Z+=K,Q=!1,J.escaped=!1;continue}if(K==="#"&&!J.inSingle&&!J.inDouble&&X){Q=!0;continue}if(Z+=K,!J.inSingle&&!J.inDouble&&!J.escaped)X=/[\s;&|()<>]/.test(K);n$(K,J)}return Z}var aK=new Set(["&&","||","|&","|","&",";"]),oK=new Set(["<<","<<<",">|"]),tK=/[*@#?$!_-]/,P6=Object.freeze([]),eK=Object.freeze([]),$Y=256;function s8($,Z){let J=Z.status==="complete"?new Set(A6(Z)):new Set,Q=[...J].reduce((K,Y)=>K.slice(0,Y.start)+" ".repeat(Y.end-Y.start)+K.slice(Y.end),$);if(H$(Q))return N4("unclosed-quote",Q,P6);let X={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},W=a$(Z,{source:Q,suppressed:J,flags:X,depth:0,functions:new Map});if(X.limited)return N4("structural-limit",Q,P6);if(X.invalid)return N4("invalid",Q,P6);return N4("complete",Q,W,X.assignmentFallbacks)}function N4($,Z,J,Q=eK){return Object.freeze({status:$,source:Z,entries:Object.freeze(J),assignmentFallbacks:Object.freeze(Q)})}function a$($,Z){return $.nodes.flatMap((J,Q)=>ZY(J,$,Q,Z)).sort((J,Q)=>J.start-Q.start).flatMap((J)=>[...J.entries])}function ZY($,Z,J,Q){if($.kind==="connector")return[{start:$.span.start,entries:[u1(KY($.operator))]}];if($.kind==="unknown")return[{start:$.span.start,entries:[u1($.source)]}];if($.kind==="function")return Q.functions.set($.name,$.body),[];if($.kind==="group"){let W=$.style!=="subshell",K=Q.source[$.span.end-1]===(W?"}":")"),Y=W?Q:{...Q,functions:new Map(Q.functions)};return[{start:$.span.start,entries:[W?V4("{"):u1("("),...a$($.body,Y),...K?[W?V4("}"):u1(")")]:[]]}]}let X=BY($,Q.functions);if(X){if(Q.depth>=h0.maxDepth||++Q.flags.expansions>$Y)return Q.flags.limited=!0,[];return[{start:$.span.start,entries:[...p8($,Q),V4(";"),...a$(X,{...Q,depth:Q.depth+1}),V4(";")]},...c8($,Z,J,Q)]}return[{start:$.span.start,entries:p8($,Q)},...c8($,Z,J,Q)]}function p8($,Z){return[...$.words.map((J)=>({start:J.span.start,entries:n8(J,$,Z,!1)})),...$.redirections.map((J)=>({start:J.span.start,entries:JY(J,$,Z)}))].sort((J,Q)=>J.start-Q.start).flatMap((J)=>J.entries)}function JY($,Z,J){let Q=$.operator==="<<-"?"<<":$.operator,X=$.target?n8($.target,Z,J,!0):[],W=X[0],K=W?.kind==="word"?W.text:void 0;return[...$.fd===void 0?[]:[E6(String($.fd))],Object.freeze({kind:"redirection",operator:Q,role:YY(Q),targetOrder:oK.has(Q)?"legacy-segment":"immediate",...K===void 0?{}:{target:K}}),...K===void 0?X:X.slice(1)]}function c8($,Z,J,Q){let X=$.redirections.filter((W)=>W.operator==="<<"||W.operator==="<<-");return[...X.flatMap((W)=>{let K=W.heredoc;if(!K)return[];let Y=[E6(K.delimiter),.../[\r\n]/.test(Q.source[K.terminatorSpan.end]??"")?[u1(";")]:[]];if(Q.suppressed.has(K.bodySpan))return[{start:K.bodySpan.start,entries:Y}];return[{start:K.bodySpan.start,entries:[...r8(Q.source.slice(K.bodySpan.start,K.bodySpan.end),Q),...Y]}]}),...X.some((W)=>!W.heredoc&&W.target)?QY(Z,J,Q):[]]}function QY($,Z,J){let Q=$.nodes.slice(Z+1).find((X)=>X.kind==="connector");if(!Q||Q.span.end>=$.span.end)return[];return[{start:Q.span.end,entries:r8(J.source.slice(Q.span.end,$.span.end),J)}]}function r8($,Z){if(Z.depth>=h0.maxDepth)return Z.flags.limited=!0,[];let J=v1($,"posix");if(J.status==="limited")return Z.flags.limited=!0,[];let Q={invalid:!1,limited:!1,expansions:Z.flags.expansions,assignmentFallbacks:Z.flags.assignmentFallbacks},X=a$(J,{source:$,suppressed:new Set,flags:Q,depth:Z.depth+1,functions:new Map});return Z.flags.limited||=Q.limited,Z.flags.expansions=Q.expansions,X}function n8($,Z,J,Q){let X=[],W={single:!1,double:!1},K="",Y=!1,B=()=>{if(Y&&!Q)X.push(u1("glob"));else if(K!==""||$.quoted&&X.length===0)X.push(E6(K));K="",Y=!1};for(let q of $.parts){if(q.provenance!=="command-substitution"&&q.provenance!=="arithmetic"){for(let H of C6(q.raw,W,J.flags)){if(typeof H==="string"){B(),X.push(u1(H));continue}K+=H.text,Y||=H.glob}continue}if(W.double){let H=J.source.slice(q.span.start,q.span.end);K+=C6(H,{single:!1,double:!0},J.flags).map((_)=>typeof _==="string"?_:_.text).join("");continue}let U=Z.nested.find((H)=>H.span.start>=q.span.start&&H.span.end<=q.span.end),G=U?a$(U,J):[];if(q.raw.startsWith("`")){K+="${}",B(),X.push(...G);continue}if(q.raw.startsWith("<(")||q.raw.startsWith(">(")){B(),X.push(q.raw.startsWith("<(")?u1("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),...G,...q.raw.endsWith(")")?[u1(")")]:[]);continue}let j=q.raw.startsWith("$((")?2:1;K+="${}",B(),X.push(...Array.from({length:j},()=>u1("(")),...G,...q.raw.endsWith(")".repeat(j))?Array.from({length:j},()=>u1(")")):[])}return B(),X}function C6($,Z,J){let Q=[],X="",W=!1,K=0;while(K<$.length){let Y=$[K]??"";if(!Z.single&&!Z.double&&(Y==="("||Y===")")){Q.push({text:X,glob:W},Y),X="",W=!1,K++;continue}if(Z.single){if(Y==="'")Z.single=!1;else X+=Y;K++;continue}if(Z.double){if(Y==='"'){Z.double=!1,K++;continue}if(Y==="\\"){let B=$[K+1]??"";X+=['"',"\\","$"].includes(B)?B:`\\${B}`,K+=2;continue}if(Y==="$"){let B=d8($,K,Z,J);X+=B.text,K=B.next;continue}X+=Y,K++;continue}if(Y==="'"||Y==='"'){Z.single=Y==="'",Z.double=Y==='"',K++;continue}if(Y==="\\"){let B=$[K+1]??"";W||=B==="*"||B==="?",X+=B,K+=2;continue}if(Y==="$"){let B=d8($,K,Z,J);X+=B.text,K=B.next;continue}W||=Y==="*"||Y==="?",X+=Y,K++}return[...Q,{text:X,glob:W}]}function d8($,Z,J,Q){let X=$[Z+1];if(X==="{"){let K=WY($,Z+2);if(K===-1)return Q.invalid=!0,{text:"",next:$.length};let Y=$.slice(Z,K+1);return XY(Y,J,Q),{text:Y,next:K+1}}if(X!==void 0&&tK.test(X))return{text:`\${${X}}`,next:Z+2};let W=/^\w*/.exec($.slice(Z+1))?.[0]??"";return{text:`\${${W}}`,next:Z+1+W.length}}function XY($,Z,J){let Q=$.slice(2,-1),X=/^[A-Za-z_][A-Za-z0-9_]*/.exec(Q)?.[0];if(!X)return;let W=Q.slice(X.length),K=[":=","="].find((B)=>W.startsWith(B));if(!K)return;let Y=C6(W.slice(K.length),{...Z},J);J.assignmentFallbacks.push(...Y.flatMap((B)=>typeof B==="string"||!B.text?[]:[B.text]))}function WY($,Z){let J=1,Q=Z;while(J>0&&Q<$.length){if($[Q]==="{"&&$[Q-1]==="$")J++;else if($[Q]==="}")J--;Q++}return J===0?Q-1:-1}function KY($){return/^[\r\n]+$/.test($)?";":$}function u1($){return Object.freeze({kind:"operator",operator:$,boundary:aK.has($)})}function V4($){return Object.freeze({kind:"operator",operator:$,boundary:!0})}function E6($){return Object.freeze({kind:"word",text:$})}function YY($){if($==="<<"||$==="<<<")return"here-data";if($==="<"||$==="<&")return"file-read";return"file-write"}function A6($){return $.nodes.flatMap((Z,J)=>{if(Z.kind==="group"||Z.kind==="function")return A6(Z.body);if(Z.kind!=="command")return[];let Q=Z.nested.flatMap((K)=>A6(K)),X=$.nodes[J+1];if(X?.kind==="connector"&&(X.operator==="|"||X.operator==="|&")||!UY(Z))return Q;return[...Q,...Z.redirections.flatMap((K)=>K.heredoc?.quotedDelimiter?[K.heredoc.bodySpan]:[])]})}function BY($,Z){let J=F4($);return J===void 0?void 0:Z.get(J)}function z0($,Z){return $!==void 0&&$.provenance==="literal"&&!$.quoted&&$.raw===$.text&&$.text===Z}function qY($){if(z0($.words[0],"git"))return z0($.words[1],"commit");if(!z0($.words[0],"gh")||!z0($.words[2],"create"))return!1;return z0($.words[1],"pr")||z0($.words[1],"issue")}function UY($){return(z0($.words[0],"cat")||z0($.words[0],"tee")||qY($))&&!$.words.some(i8)&&!$.redirections.some((J)=>i8(J.target))}function i8($){return $?.parts.some((Z)=>Z.provenance==="command-substitution"&&Z.raw.startsWith(">("))??!1}var a8=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),o8=new Set([...a8,"glob"]),GY=new Set([...o8,"pattern"]),HY=[],t8={parseCommand:v1,projectShellSyntax:s8};class I0 extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function R4($,Z={}){let J=jY({...t8,...Z}),Q=q$($.input),X=[];if(($.route.kind==="command"||$.route.kind==="unknown")&&Q)X.push({usage:"input-candidate",source:Q});if($.route.kind==="command"&&"command"in $&&$.command)X.push({usage:"declared-command",source:$.command});let W=X.reduce((K,Y)=>{let B=K.findIndex((G)=>G.source===Y.source);if(B!==-1){let G=K[B];if(!G)return K;return K[B]={...G,usages:[...G.usages,Y.usage]},K}let q=$.route.kind==="command"?$.route.shell:"posix",U=J.getCommandProgram(Y.source,q);return K.push({usages:[Y.usage],source:Y.source,program:U,views:T6(U),uncertainties:U.issues,shell:J.getShellSyntax(Y.source,U)}),K},[]);return{invocation:{toolName:$.toolName,route:$.route,context:$.context},commands:W,paths:_Y($),store:J}}function L1($,Z){return $.commands.find((J)=>J.usages.includes(Z))}function n1($){if(!$.includes("$"))return $;return t2($,G0())}function jY($={}){let Z={...t8,...$},J=new Map,Q=new Map,X=new WeakMap,W=(Y,B)=>{let q=`${B}\x00${Y}`,U=Q.get(q);if(U)return U;let G=Z.parseCommand(Y,B);return Q.set(q,G),G};return{getShellSyntax:(Y,B)=>{if(B&&B.source!==Y)throw TypeError("Shell syntax source does not match command program source.");let q=B??W(Y,"posix");if(q.status==="limited"){let j=X.get(q);if(j)return j;let H={status:"structural-limit",source:Y,entries:HY,assignmentFallbacks:[]};return X.set(q,H),H}let U=J.get(Y);if(U)return U;let G=Z.projectShellSyntax(Y,q);return J.set(Y,G),G},getCommandProgram:W}}function T6($){return $.nodes.flatMap((Z)=>{if(Z.kind==="group")return T6(Z.body);if(Z.kind!=="command")return[];return[...Z.nested.flatMap((J)=>T6(J)),Z]})}function _Y($){let Z=$.route.kind==="grep"?o8:$.route.kind==="glob"?GY:a8;return[...U6($.input,Z),...$.route.kind==="patch"?G6($.input):[]]}function S6($,Z){return{value:$,work:Z}}function V($,Z){if($.work)$.work.units=Math.min(Number.MAX_SAFE_INTEGER,$.work.units+1);return $.value[Z]}function a($){return $.value.length}function o$($,Z,J=1){if($)$.units=Math.min(Number.MAX_SAFE_INTEGER,$.units+Z.length*J)}function M1($,Z){o$($,Z)}function g0($){if(!$)return!1;let Z=$.charCodeAt(0);return Z>=48&&Z<=57||Z>=65&&Z<=90||Z===95||Z>=97&&Z<=122}function c($){if(!$)return!1;let Z=$.charCodeAt(0);return Z===9||Z===10||Z===11||Z===12||Z===13||Z===32||Z===160||Z===65279||Z===5760||Z>=8192&&Z<=8202||Z===8232||Z===8233||Z===8239||Z===8287||Z===12288}function y6($){return $===`
39
- `||$==="\r"||$==="\u2028"||$==="\u2029"}function d($,Z,J){if(Z+J.length>a($))return!1;for(let Q=0;Q<J.length;Q++)if(V($,Z+Q)!==J[Q])return!1;return!0}function H0($,Z,J){return!g0(V($,Z-1))&&d($,Z,J)&&!g0(V($,Z+J.length))}function j0($,Z){return g0(V($,Z-1))!==g0(V($,Z))}function Z1($){return $===`
40
- `||$===";"||$==="&"||$==="|"}function j$($){return $==="|"||$===";"}var F1=new Set(["awk","gawk","nawk","mawk"]),OY=new Set(["-e","--source"]),LY=new Set(["-F","-v","--assign","--field-separator"]),e8=new Set(["-f","--file"]),MY=new Set(["print","printf","return"]),$7=[{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"}],FY="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 I4($,Z,J){let Q=!1;for(let X of NY($)){let W=VY(X,J);if(!W)continue;for(let K of W.commands){let Y=Z(K);if(Y)return Y;if(K.includes("{}")||/[$`]/.test(K))Q=!0}Q||=W.dynamic}return Q?N("awk.system-dynamic",FY):null}function v6($){let Z=[],J=!1,Q=!1,X=!0,W=!0;for(let K=1;K<$.length;K++){let Y=$[K];if(Y===void 0)break;if(X&&Y==="--"){X=!1;continue}if(X&&OY.has(Y)){J=!0;let B=$[K+1];if(B!==void 0)Z.push({tokenIndex:K+1,kind:"inline-code",value:B});else W=!1;K++;continue}if(X&&Y.startsWith("--source=")){J=!0,Z.push({tokenIndex:K,kind:"inline-code",value:Y.slice(9)});continue}if(X&&Y.startsWith("-e")&&Y.length>2){J=!0,Z.push({tokenIndex:K,kind:"inline-code",value:Y.slice(2)});continue}if(X&&(LY.has(Y)||e8.has(Y))){if(e8.has(Y)){Q=!0;let B=$[K+1];if(B!==void 0)Z.push({tokenIndex:K+1,kind:"program-file",value:B});else W=!1}else if($[K+1]===void 0)W=!1;K++;continue}if(X&&(Y.startsWith("-F")||Y.startsWith("-v")&&Y.slice(2).includes("=")))continue;if(X&&Y.startsWith("-f")&&Y.length>2){Q=!0,Z.push({tokenIndex:K,kind:"program-file",value:Y.slice(2)});continue}if(X&&(Y.startsWith("--assign=")||Y.startsWith("--field-separator=")))continue;if(X&&Y.startsWith("--file=")){Q=!0,Z.push({tokenIndex:K,kind:"program-file",value:Y.slice(7)});continue}if(X&&Y.startsWith("-")&&Y!=="-")continue;if(X=!1,!J&&!Q)Z.push({tokenIndex:K,kind:"main-program",value:Y});return{sources:Z,optionsOpen:!1}}return{sources:W?Z:[],optionsOpen:X&&W}}function e$($){return v6($).sources}function NY($){return e$($).filter((Z)=>Z.kind!=="program-file").map((Z)=>Z.value)}function VY($,Z){M1(Z,$);let J=$.includes("system")?u6($,Z):null,Q=RY($,Z);if(!J&&!Q)return null;return{dynamic:!!J?.dynamic||!!Q?.dynamic,commands:[...J?.commands??[],...Q?.commands??[]]}}function u6($,Z){M1(Z,$);let J=[],Q=!1,X=!1,W=0;while(W<$.length){let K=$[W];if(K==='"'||K==="'"){W=z4($,W,K)?.endIndex??W+1;continue}if(K==="#"){W=Z7($,W+1);continue}if(K==="/"&&J7($,W)){W=Q7($,W+1)??W+1;continue}if(!$.startsWith("system",W)){W++;continue}let Y=W;if(W+=6,t$($[Y-1])||t$($[W]))continue;let B=D4($,W);if($[B]!=="(")continue;B=D4($,B+1);let q=$[B];if(q!=='"'&&q!=="'"){Q=!0,X=!0;continue}let U=z4($,B,q);if(!U){Q=!0,X=!0;continue}if(B=D4($,U.endIndex),Q=!0,$[B]!==")"){X=!0,W=U.endIndex;continue}J.push(U.value),W=B+1}if(!Q)return null;return{dynamic:X,commands:J}}function RY($,Z){M1(Z,$);let J=[],Q=!1,X=!1,W=0,K=0,Y=null,B=null,q=0;while(W<$.length){let U=$[W];if(!U)break;if(U==='"'||U==="'"){let H=z4($,W,U);if(H&&q===K)B={...H,startIndex:W};q=H?.endIndex??W+1,W=H?.endIndex??W+1;continue}if(U==="#"){W=Z7($,W+1),K=W,Y=null,B=null,q=W;continue}if(U==="/"&&J7($,W)){let H=Q7($,W+1);q=H??W+1,W=H??W+1;continue}if(`;
41
- {}`.includes(U)){W++,K=W,Y=null,B=null,q=W;continue}if(Y===null&&(w6($,W,"print")||w6($,W,"printf")))Y=W;if(U!=="|"||$[W-1]==="|"||$[W+1]==="|"){if(!/\s/.test(U))q=W+1;W++;continue}let G=$[W+1]==="&"?W+2:W+1,j=D4($,G);if(w6($,j,"getline")){X=!0;let H=IY(K,B,q);if(H===null)Q=!0;else J.push(H);q=G,W=G;continue}if(fY(K,Y)){X=!0;let H=zY($,j);if(!H){Q=!0,q=G,W=G;continue}if(!DY($,H.endIndex)){Q=!0,q=H.endIndex,W=H.endIndex;continue}J.push(H.value),q=H.endIndex,W=H.endIndex;continue}q=G,W++}if(!X)return null;return{dynamic:Q,commands:J}}function t$($){return!!$&&/[A-Za-z0-9_]/.test($)}function D4($,Z){let J=Z;while(/\s/.test($[J]??""))J++;return J}function DY($,Z){let J=Z;while(/[\t\f\v\r ]/.test($[J]??""))J++;let Q=$[J];return!Q||`;
42
- }#`.includes(Q)}function z4($,Z,J){let Q="",X=!1;for(let W=Z+1;W<$.length;W++){let K=$[W];if(!K)break;if(X){let Y=bY($,W);if(!Y)return null;Q+=Y.value,W=Y.endIndex,X=!1;continue}if(K==="\\"){X=!0;continue}if(K===J)return{value:Q,endIndex:W+1};Q+=K}return null}function zY($,Z){let J=$[Z];if(J!=='"'&&J!=="'")return null;return z4($,Z,J)}function IY($,Z,J){if(!Z)return null;return Z.startIndex>=$&&Z.endIndex===J?Z.value:null}function bY($,Z){let J=$[Z];if(!J)return null;if(J==="x"){let X=$.slice(Z+1,Z+3);if(!/^[0-9A-Fa-f]{2}$/.test(X))return null;return{value:String.fromCharCode(Number.parseInt(X,16)),endIndex:Z+2}}if(/[0-7]/.test(J)){let X=/^[0-7]{1,3}/.exec($.slice(Z));if(!X)return null;return{value:String.fromCharCode(Number.parseInt(X[0],8)),endIndex:Z+X[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
43
- `,r:"\r",t:"\t",v:"\v"}[J]??J,endIndex:Z}}function w6($,Z,J){return $.startsWith(J,Z)&&!t$($[Z-1])&&!t$($[Z+J.length])}function fY($,Z){return Z!==null&&Z>=$}function Z7($,Z){let J=$.indexOf(`
44
- `,Z);return J===-1?$.length:J+1}function J7($,Z){let J=PY($,Z);if(J===-1)return!0;if("{([,;!~=".includes($[J]??""))return!0;let Q=J;while(t$($[Q-1]))Q--;return MY.has($.slice(Q,J+1))}function PY($,Z){for(let J=Z-1;J>=0;J--)if(!/\s/.test($[J]??""))return J;return-1}function Q7($,Z){let J=!1;for(let Q=Z;Q<$.length;Q++){let X=$[Q];if(!X)break;if(J){J=!1;continue}if(X==="\\"){J=!0;continue}if(X==="/")return Q+1}return null}import{existsSync as k6,lstatSync as gY,readFileSync as C4,realpathSync as J2,statSync as Z2}from"node:fs";import{dirname as x6,isAbsolute as l6,join as A4,resolve as E4}from"node:path";import{dirname as CY,isAbsolute as AY,parse as EY,sep as TY}from"node:path";function k0($,Z=process.platform){if(Z!=="win32")return!1;return($[0]==="/"||$[0]==="\\")&&($[1]==="/"||$[1]==="\\")}function b0($,Z,J){if(k0(Z))throw Error("Unsupported Windows namespace path");let Q=AY(Z)?yY(Z):"",X=Q||$;for(let W of wY(Q?Z.slice(Q.length):Z)){if(W===""||W===".")continue;if(W===".."){X=CY(X);continue}let K=SY(X,W),Y=J.entryKind(K),B=Y==="symlink"?J.realpath(K):K;if(Y==="missing"||B===null)throw Error(`Cannot resolve path component: ${K}`);X=B}return X}function SY($,Z){return $.endsWith("/")||$.endsWith("\\")?`${$}${Z}`:`${$}${TY}${Z}`}function yY($){return EY($).root}function wY($){let Z=process.platform==="win32"?/[\\/]+/:/\/+/;return $.split(Z)}var h6=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],vY=new Set(h6);var X7=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),b4=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),uY=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function hY($){return vY.has($)}function $2($){return $==="GIT_CONFIG_COUNT"||$==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test($)}function g6($){return hY($)||X7.has($)||b4.has($)||$2($)}function f1($,Z,J){return J?.has($)?J.get($):Z.get($)}function f4($,Z){let J=f1("GIT_CONFIG_COUNT",$,Z);if(J===void 0)return{state:"absent"};if(J==="")return{state:"valid",count:0};if(!/^\d+$/.test(J))return{state:"invalid"};let Q=Number(J);return Number.isSafeInteger(Q)&&Q<=1024?{state:"valid",count:Q}:{state:"invalid"}}function P4($,Z,J){let X=$.match(uY)?.[1];if(!X||!g6(X))return null;let W=$.indexOf("=");return{name:X,value:`${f1(X,Z,J)??""}${$.slice(W+1)}`}}function W7($){return Y7($,b4)}function K7($){return Y7($,X7)}function Y7($,Z){if(!$)return!1;for(let J of $.keys())if(Z.has(J))return!0;return!1}var a1=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]);function U7($,Z){return h6.some((J)=>Z?.has(J)||$.has(J))}function G7($,Z){if(!Z)return{gitCwd:null,hasExplicitGitContext:!1};let J;try{J=J2(E4(Z))}catch{return{gitCwd:null,hasExplicitGitContext:!1}}if(!_7(J))return{gitCwd:null,hasExplicitGitContext:!1};let Q=!1,X=1;while(X<$.length){let W=$[X];if(!W)break;if(W==="--")break;if(!W.startsWith("-"))break;if(W==="-C"){let K=$[X+1];if(!K)return{gitCwd:null,hasExplicitGitContext:Q};let Y=q7(J,K);if(!Y)return{gitCwd:null,hasExplicitGitContext:Q};J=Y,X+=2;continue}if(W.startsWith("-C")&&W.length>2){let K=q7(J,W.slice(2));if(!K)return{gitCwd:null,hasExplicitGitContext:Q};J=K,X++;continue}if(W==="--git-dir"||W==="--work-tree"){Q=!0,X+=2;continue}if(W.startsWith("--git-dir=")||W.startsWith("--work-tree=")){Q=!0,X++;continue}if(a1.has(W))X+=2;else if(W.startsWith("-c")&&W.length>2)X++;else X++}return{gitCwd:J,hasExplicitGitContext:Q}}function H7($){let Z=tY($);if(!Z)return!1;try{let J=gY(Z);if(J.isSymbolicLink()||!J.isFile())return!1;let Q=m6(Z);if(!Q?.commonDir)return!1;if(!lY(Q.gitDir,Z))return!1;return mY(Q.gitDir,x6(Z))}catch{return!1}}function m6($){try{let Z=kY($);if(!Z)return null;let J=J2(l6(Z)?Z:E4(x6($),Z));if(!Z2(J).isDirectory())return null;return{gitDir:J,commonDir:xY(J)}}catch{return null}}function kY($){let Z=C4($,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!Z.startsWith("gitdir:"))return null;return Z.slice(7).trim()||null}function xY($){try{let Z=C4(A4($,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!Z)return null;let J=J2(l6(Z)?Z:E4($,Z));return Z2(J).isDirectory()?J:null}catch{return null}}function lY($,Z){let J=pY($);return J===null?!1:j7($,J,Z)}function mY($,Z){let J=cY($);return J===null?!0:j7($,J,Z)}function pY($){let Z=A4($,"gitdir");if(!k6(Z))return null;let J=C4(Z,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return J===""?null:J}function cY($){let Z=A4($,"config.worktree");return k6(Z)?nY(Z):null}function j7($,Z,J){return iY(dY($,Z),J)}function dY($,Z){return l6(Z)?Z:E4($,Z)}function iY($,Z){try{return sY($,Z)}catch{return!1}}function sY($,Z){try{let J=Z2($),Q=Z2(Z);if(J.ino!==0&&Q.ino!==0&&J.dev===Q.dev&&J.ino===Q.ino)return!0}catch{}return B7($)===B7(Z)}function B7($){return rY(J2.native($))}function rY($){let Z=$.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"");if(Z=Z.replace(/\\/g,"/"),Z.length>1&&Z.endsWith("/"))Z=Z.slice(0,-1);return process.platform==="win32"?Z.toLowerCase():Z}function nY($){let Z=C4($,"utf-8"),J=!1,Q=null;for(let X of Z.split(/\r?\n/)){let W=X.trim();if(W===""||W.startsWith("#")||W.startsWith(";"))continue;if(W.startsWith("[")){J=/^\[core\]$/i.test(W);continue}if(!J)continue;let K=W.match(/^worktree\s*=\s*(.*)$/i);if(K)Q=aY(K[1]??"")}return Q}function aY($){let Z=$.trim();if(!Z.startsWith('"')||!Z.endsWith('"'))return Z;return oY(Z.slice(1,-1))}function oY($){let Z="";for(let J=0;J<$.length;J++){let Q=$[J];if(Q!=="\\"){Z+=Q;continue}let X=$[J+1];if(X===void 0){Z+=Q;continue}switch(X){case"\\":case'"':Z+=X;break;case"n":Z+=`
45
- `;break;case"t":Z+="\t";break;case"b":Z+="\b";break;default:Z+=`\\${X}`;break}J++}return Z}function q7($,Z){try{let J=b0($,Z,b1);return _7(J)?J:null}catch{return null}}function _7($){try{return Z2($).isDirectory()}catch{return!1}}function tY($){try{return Q2(J2($))}catch{return null}}function Q2($){let Z=$;while(!0){let J=A4(Z,".git");if(k6(J))return J;let Q=x6(Z);if(Q===Z)return null;Z=Q}}function T4($,Z,J){let Q=S6($,J);if(Z==="rm")return eY(Q);if(Z==="dd")return ZB(Q);return V7(Q,!0)}function S4($,Z,J){let Q=S6($,J);if(Z==="rm")return JB(Q);if(Z==="reset-hard")return F7(Q,"--ha","rd");if(Z==="reset-merge")return F7(Q,"--me","rge");if(Z==="clean")return KB(Q);if(Z==="checkout")return BB(Q);if(Z==="push-force")return qB(Q);if(Z==="push-refspec")return UB(Q);if(Z==="push-delete")return GB(Q);if(Z==="branch")return HB(Q);if(Z==="tag")return OB(Q);if(Z==="restore")return LB(Q);return V7(Q,!1)}function eY($){let Z=!1,J=!1,Q=!1,X=-1;for(let W=0;W<=a($);W++){let K=V($,W);if(!Z){let B=V($,W+2);if(H0($,W,"rm")&&c(B)&&B!==`
46
- `)Z=!0,W++;continue}let Y=$B($,W);if(K===`
47
- `||Y!==-1){if(Z=!1,J=!1,Q=!1,X=-1,Y!==-1)W=Y-1;continue}if(K===";"||K==="&"||K==="|"||W===a($)){if(X>=0){let B=O7($,X,W);J||=B.recursive,Q||=B.force}if(J&&Q)return!0;Z=!1,J=!1,Q=!1,X=-1;continue}if(c(K)){if(X>=0){if(d($,X,"--")&&W-X===2)Z=!1,J=!1,Q=!1;else{let B=O7($,X,W);if(J||=B.recursive,Q||=B.force,J&&Q)return!0}X=-1}continue}if(X<0)X=W}return!1}function $B($,Z){if(V($,Z)!=="\\"||V($,Z-1)==="\\")return-1;if(d($,Z,String.raw`\n`))return Z+2;if(d($,Z,String.raw`\x0a`)||d($,Z,String.raw`\x0A`))return Z+5;if(d($,Z,String.raw`\u000a`)||d($,Z,String.raw`\u000A`))return Z+7;return d($,Z,String.raw`\012`)?Z+4:-1}function O7($,Z,J){if(L7($,Z,J,"recursive"))return{recursive:!0,force:!1};if(L7($,Z,J,"force"))return{recursive:!1,force:!0};if(V($,Z)!=="-"||V($,Z+1)==="-")return{recursive:!1,force:!1};let Q=!1,X=!1;for(let W=Z+1;W<J;W++){let K=V($,W);Q||=K==="r"||K==="R",X||=K==="f"||K==="F"}return{recursive:Q,force:X}}function L7($,Z,J,Q){let X=J-Z-2;if(X<1||X>Q.length||!d($,Z,"--"))return!1;for(let W=0;W<X;W++)if(V($,Z+W+2)!==Q[W])return!1;return!0}function ZB($){let Z=!1;for(let J=0;J<a($);J++){if(Z1(V($,J))){Z=!1;continue}if(H0($,J,"dd")){Z=!0,J++;continue}if(!Z||!H0($,J,"of")||!d($,J,"of=/dev/"))continue;let Q=J+8;if(Q<a($)&&!c(V($,Q))&&V($,Q)!=="'"&&V($,Q)!=='"')return!0}return!1}function JB($){let Z=!1,J=!1,Q=!1;for(let X=0;X<=a($);){let W=V($,X);if(X===a($)||Z1(W)){Z=!1,J=!1,Q=!1,X++;continue}let K=XB($,X);if(K>=0){if(QB($,K))return!0;let Y=K,B=!1;while(c(V($,Y)))B||=V($,Y)===`
48
- `,Y++;if(B)J=!1,Q=!1;Z=!0,X=Y;continue}if(!Z){X++;continue}if(d($,X,"--")&&(X===0||c(V($,X-1)))&&(!V($,X+2)||c(V($,X+2))||Z1(V($,X+2)))){Z=!1,J=!1,Q=!1,X+=2;continue}if(J||=d($,X,"--recursive")&&j0($,X+11)||p6($,X,"recursive"),Q||=d($,X,"--force")&&j0($,X+7)||p6($,X,"force"),J&&Q)return!0;X++}return!1}function p6($,Z,J){if(!d($,Z,"--"))return!1;let Q=0;while(Q<=J.length){let X=V($,Z+Q+2);if(!X||c(X)||Z1(X))break;if(X!==J[Q])return!1;Q++}return Q>0&&j0($,Z+Q+2)}function QB($,Z){let J=Z,Q=!1,X=!1;while(J<a($)){while(c(V($,J)))J++;let W=J;while(J<a($)&&!c(V($,J)))J++;if(V($,W)!=="-"||J-W===2&&d($,W,"--"))return!1;let K=M7($,W,"recursive"),Y=M7($,W,"force");if(Q&&Y||X&&K)return!0;if(Q||=K,X||=Y,V($,W+1)==="-")continue;let B=WB($,W,J);if(B.combined||Q&&B.forceAtBoundary||X&&B.recursiveAtBoundary)return!0;Q||=B.recursive,X||=B.force}return!1}function M7($,Z,J){return d($,Z,`--${J}`)&&j0($,Z+J.length+2)||p6($,Z,J)}function XB($,Z){if(Z>0&&g0(V($,Z-1)))return-1;let J=Z;if(V($,J)==="\\")J++;if(V($,J)!=="r")return-1;if(J++,V($,J)==="\\")J++;if(V($,J)!=="m"||!c(V($,J+1)))return-1;return J+1}function WB($,Z,J){let Q=!1,X=!1,W=!1,K=!1,Y=!1;if(V($,Z)!=="-")return{recursive:Q,force:X,recursiveAtBoundary:W,forceAtBoundary:K,combined:Y};let B="";for(let q=Z+1;q<J;q++){let U=V($,q)??"",G=(U==="r"||U==="f")&&j0($,q+1);Q||=U==="r",X||=U==="f",W||=U==="r"&&G,K||=U==="f"&&G,Y||=(B==="r"&&U==="f"||B==="f"&&U==="r")&&G,B=U}return{recursive:Q,force:X,recursiveAtBoundary:W,forceAtBoundary:K,combined:Y}}function F7($,Z,J){return W2($,"reset",j$,!0,(Q)=>V($,Q)==="-"&&_$($,Q,Z,J)?!0:Q)}function KB($){return W2($,"clean",j$,!0,(Z)=>{if(V($,Z)!=="-")return Z;if(_$($,Z,"--fo","rce"))return!0;let J=X2($,Z,j$);for(let Q=Z+1;Q<J;Q++)if(V($,Q)==="f")return!0;return J-1})}function y4($,Z,J){if(!H0($,Z,"git"))return null;let Q=Z+3;if(!c(V($,Q)))return{commandEnd:-1,next:Q};while(c(V($,Q)))Q++;while(Q<a($)){if(Z1(V($,Q)))return{commandEnd:-1,next:Q};let X=X2($,Q,Z1);if(H0($,Q,J))return{commandEnd:Q+J.length,next:X};if(V($,Q)!=="-")return{commandEnd:-1,next:X};let W=X-Q===2&&d($,Q,"--"),K=YB($,Q,X);Q=X;while(c(V($,Q)))Q++;if(W)return{commandEnd:H0($,Q,J)?Q+J.length:-1,next:X2($,Q,Z1)};if(!K)continue;if(Q>=a($)||Z1(V($,Q)))return{commandEnd:-1,next:Q};Q=X2($,Q,Z1);while(c(V($,Q)))Q++}return{commandEnd:-1,next:Q}}function YB($,Z,J){for(let Q of a1)if(J-Z===Q.length&&d($,Z,Q))return!0;return!1}function BB($){return N7($,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function qB($){return W2($,"push",j$,!0,(Z)=>{if(V($,Z)!=="-")return Z;if(V($,Z+1)==="f"&&!g0(V($,Z+2))&&!d($,Z+2,"-with-lease"))return!0;let J=R7($,Z,"--fo","rce");if(J>=0&&!d($,J,"-with-lease"))return!0;return Z})}function UB($){return W2($,"push",Z1,!1,(Z)=>{if(c(V($,Z))&&V($,Z+1)==="+"&&Z+2<a($)&&!Z1(V($,Z+2))&&!c(V($,Z+2)))return!0;if(V($,Z)===":"&&V($,Z+1)==="+")return!0;return Z})}function GB($){return W2($,"push",Z1,!1,(Z)=>{if(V($,Z)==="-"&&_$($,Z,"--de","lete"))return!0;if(c(V($,Z))&&V($,Z+1)===":"&&Z+2<a($)&&!c(V($,Z+2))&&!Z1(V($,Z+2)))return!0;return Z})}function HB($){let Z=!1,J=!1,Q=!1;for(let X=0;X<=a($);X++){if(X===a($)||Z1(V($,X))){if(J&&Q)return!0;Z=!1,J=!1,Q=!1;continue}if(!Z){let Y=y4($,X,"branch");if(Y){Z=Y.commandEnd>=0,X=Math.max(X,(Z?Y.commandEnd:Y.next)-1);continue}}if(!Z||V($,X)!=="-")continue;let W=X2($,X,Z1),K=jB($,X,W);if(J||=K.deletion,Q||=K.force,J&&Q)return!0;X=W-1}return!1}function jB($,Z,J){let Q=!1,X=!1;for(let W=Z;W<J;W++){if(V($,W)!=="-")continue;if(_$($,W,"--de","lete"))Q=!0;if(_$($,W,"--fo","rce"))X=!0;if(V($,W+1)==="-")continue;let K=W+1,Y=!1,B=!1,q=!1;while(K<J&&_B(V($,K))){let U=V($,K);Y||=U==="d"||U==="D",B||=U==="f",q||=U==="D",K++}if(!j0($,K))continue;Q||=Y,X||=B||q}return{deletion:Q,force:X}}function _B($){if(!$)return!1;let Z=$.charCodeAt(0);return Z>=65&&Z<=90||Z>=97&&Z<=122}function OB($){return N7($,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function N7($,Z){let J=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let Q=0;Q<a($);Q++){let X=V($,Q),W=J[J.length-1];if(!W)return!1;let K=W.escaped;if(W.escaped=!K&&W.quote!=="'"&&X==="\\",!K&&X==="'"&&W.quote!=='"')W.quote=W.quote==="'"?"":"'";if(!K&&X==='"'&&W.quote!=="'")W.quote=W.quote==='"'?"":'"';if(X==="$"&&V($,Q+1)==="("&&(J.length===1||!K&&W.quote!=="'")){J.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),Q++;continue}if(!K&&!W.quote&&J.length>1&&X==="("){W.depth++;continue}if(!K&&!W.quote&&J.length>1&&X===")"){if(W.depth--,W.depth===0)J.pop();continue}if(c(X))W.shortActive=!1,W.hasShortFlag=!1;if(!W.outerActive){let Y=y4($,Q,Z.command);if(Y){W.outerActive=Y.commandEnd>=0&&c(V($,Y.commandEnd)),W.shortActive=!1,W.hasShortFlag=!1,Q=Math.max(Q,(W.outerActive?Y.commandEnd:Y.next)-1);continue}}if(W.outerActive&&X==="-"){if(_$($,Q,Z.longPrefix,Z.longOptional))return!0;W.shortActive||=!Z.excludedShortStarts.includes(V($,Q+1)??"")}if(W.hasShortFlag||=W.shortActive&&X===Z.shortFlag,W.hasShortFlag&&j0($,Q+1))return!0;if(j$(X))W.outerActive=!1}return!1}function W2($,Z,J,Q,X){let W=!1;for(let K=0;K<a($);K++){let Y=V($,K),B=J(Y);if(!W&&!B){let q=y4($,K,Z);if(q){W=q.commandEnd>=0&&(!Q||c(V($,q.commandEnd))),K=Math.max(K,(W?q.commandEnd:q.next)-1);continue}}if(W){let q=X(K);if(q===!0)return!0;for(let U=K;U<=q;U++)if(J(V($,U)))W=!1;K=q}if(B)W=!1}return!1}function LB($){let Z=!1;for(let J=0;J<a($);J++){if(y6(V($,J))){if(Z)return!0;Z=!1;continue}if(!Z){let Q=y4($,J,"restore");if(Q){Z=Q.commandEnd>=0,J=Math.max(J,(Z?Q.commandEnd:Q.next)-1);continue}}if(Z&&V($,J)==="-"&&V($,J+1)==="-"&&(d($,J+2,"staged")||d($,J+2,"help")))Z=!1}return Z}function V7($,Z){let J=!1;for(let Q=0;Q<a($);Q++){let X=V($,Q),W=Z?y6(X):Z1(X);if(J&&c(X)&&V($,Q+1)==="-"&&H0($,Q+2,"delete"))return!0;if(W){J=!1;continue}if(H0($,Q,"find"))J=!0,Q+=3}return!1}function X2($,Z,J){let Q=Z;while(Q<a($)&&!c(V($,Q))&&!J(V($,Q)))Q++;return Q}function R7($,Z,J,Q){if(!d($,Z,J))return-1;let X=Z+J.length;for(let W=0;W<Q.length&&V($,X)===Q[W];W++)X++;return j0($,X)?X:-1}function _$($,Z,J,Q){return R7($,Z,J,Q)>=0}function l($){return u($).toLowerCase()}function u($){return $.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??$}var x0="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",O$="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.",w4=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),MB=new Set(["-p","--print"]),FB=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),NB=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"])]]),VB=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),RB=new Map([["python",new Set(["m"])]]),DB=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"])]]),zB=new Set(["always","default","never"]),IB=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),bB=/\\\r?\n/g,fB=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 v4($){return h4($).code}function u4($){return h4($).sources}function z7($){return fB.get(k4($))??[]}function h4($){let Z=k4($[0]??"");if(!w4.has(Z))return{code:null,sources:[],optionsOpen:!1};let J=[],Q=[],X=!0;for(let W=1;W<$.length;W++){let K=$[W];if(K===void 0)break;if(K==="--")return h1(Z,J,Q,X,$[W+1]===void 0?void 0:W+1,$[W+1]);if(K===""||K==="-"||!K.startsWith("-"))return h1(Z,J,Q,X,W,K);if(Z==="node"&&MB.has(K)){let G=$[W+1];if(G===void 0)return h1(Z,J,Q,X);if(G.startsWith("-"))continue;J.push({tokenIndex:W+1,value:G}),Q.push({tokenIndex:W+1,kind:"inline-code",value:G}),W++;continue}if(CB(Z,K)){let G=$[W+1];if(G===void 0)return h1(Z,J,Q,X);if(J.push({tokenIndex:W+1,value:G}),Q.push({tokenIndex:W+1,kind:"inline-code",value:G}),Z==="python")return h1(Z,J,Q,X);W++;continue}let Y=/^--eval=(.*)$/s.exec(K);if(AB(Z)&&Y){let G=Y[1]??"";J.push({tokenIndex:W,value:G}),Q.push({tokenIndex:W,kind:"inline-code",value:G});continue}if(Z==="node"){let G=PB(K);if(G){if(G.attached){if(X&&=G.value!=="",G.value!=="")Q.push({tokenIndex:W,kind:"module-file",value:G.value});continue}let j=$[W+1];if(j===void 0||j.startsWith("-"))return X=!1,h1(Z,J,Q,X);Q.push({tokenIndex:W+1,kind:"module-file",value:j}),W++;continue}}if(Z==="python"&&K.startsWith("--check-hash-based-pycs=")||Z==="node"&&(K==="--conditions="||K==="--diagnostic-dir="||K==="--title=")||Z==="ruby"&&(K==="--disable="||K==="--enable="))return h1(Z,J,Q,X);if(DB.get(Z)?.has(K)){let G=$[W+1];if(G===void 0||G.startsWith("-")&&!(Z==="ruby"&&IB.has(K))||Z==="python"&&!zB.has(G))return h1(Z,J,Q,X);W++;continue}if(K.startsWith("--"))continue;let B,q=!1;for(let G=1;G<K.length;G++){let j=K[G];if(j===void 0)break;if(RB.get(Z)?.has(j)){let H=K.slice(G+1),_=H||$[W+1];if(_!==void 0)Q.push({tokenIndex:H?W:W+1,kind:"module-file",value:_});return h1(Z,J,Q,X)}if(FB.get(Z)?.has(j)){B=K.slice(G+1)||$[W+1],q=G+1===K.length;break}if(Z==="node"&&j==="r"){if(K==="-r"){let H=$[W+1];if(X&&=H!==void 0&&!H.startsWith("-"),X&&H!==void 0)Q.push({tokenIndex:W+1,kind:"module-file",value:H});W++}else X=!1;break}if(Z==="ruby"&&j==="r"){let H=K.slice(G+1),_=H||$[W+1];if(X&&=_!==void 0,_!==void 0)Q.push({tokenIndex:H?W:W+1,kind:"module-file",value:_});if(!H)W++;break}if(Z==="perl"&&(j==="M"||j==="m")){let H=K.slice(G+1);if(H)Q.push({tokenIndex:W,kind:"module-file",value:H});else if(X=!1,G+1===K.length)W++;break}if(NB.get(Z)?.has(j)){if(G+1===K.length)W++;break}if(VB.get(Z)?.has(j)&&G+1<K.length)break}if(B===void 0)continue;let U=q?W+1:W;if(J.push({tokenIndex:U,value:B}),Q.push({tokenIndex:U,kind:"inline-code",value:B}),Z==="python")return h1(Z,J,Q,X);if(q)W++}return h1(Z,J,Q,X,void 0,void 0,!0)}function h1($,Z,J,Q,X,W,K=!1){let Y=$==="node"?Z.slice(-1):Z,B=new Set(Y.map((U)=>U.tokenIndex)),q=J.filter((U)=>U.kind!=="inline-code"||B.has(U.tokenIndex));if(Q&&Z.length===0&&X!==void 0&&W!==void 0)q.push({tokenIndex:X,kind:"main-script",value:W});return{code:($==="node"?Y[0]?.value:Y.map((U)=>U.value).join(`
49
- `))||null,sources:Q?q:[],optionsOpen:Q&&K}}function PB($){for(let Z of["--import","--loader","--experimental-loader","--require"]){if($===Z)return{attached:!1,value:""};if($.startsWith(`${Z}=`))return{attached:!0,value:$.slice(Z.length+1)}}return}function N1($){return w4.has(k4($))}function g4($,Z){return k4($)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(Z)}function k4($){let Z=u($).toLowerCase();return K8.test(Z)?"python":Z}function CB($,Z){return w4.get($)?.has(Z)??!1}function AB($){return w4.get($)?.has("--eval")??!1}function L$($,Z){let J=SB($,Z);if(!D7(J,Z))return!1;M1(Z,J);let Q=TB(J);if(D7(Q,Z))return!0;return M1(Z,Q),EB.test(Q)}var EB=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function TB($){let Z=[],J=0,Q=0;while(Q<$.length){let X=$[Q];if(X!=="'"&&X!=='"'){Q++;continue}let W=$.startsWith(X.repeat(3),Q)?X.repeat(3):X,K=Q+W.length;while(K<$.length&&!$.startsWith(W,K))K+=$[K]==="\\"?2:1;if(K>=$.length)break;Z.push($.slice(J,Q)," "),Q=K+W.length,J=Q}return Z.push($.slice(J)),Z.join("")}function D7($,Z){if(T4($,"rm",Z))return!0;for(let Q of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(M1(Z,$),Q.test($))return!0;if(T4($,"dd",Z))return!0;for(let Q of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(M1(Z,$),Q.test($))return!0;if(T4($,"find",Z))return!0;let J=$.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((Q)=>{return M1(Z,$),J.some((X)=>S4(X,Q))})}function SB($,Z){return M1(Z,$),$.replace(bB,"")}function H1($,Z){let J=new Set,Q=!1;for(let X of $){if(X==="--"){Q=!0;continue}if(Q)continue;if(X.startsWith("-")&&!X.startsWith("--")&&X.length>1)for(let W=1;W<X.length;W++){let K=X[W];if(!K||!/[a-zA-Z]/.test(K))break;let Y=`-${K}`;if(J.add(Y),Z?.shortOptsWithValue?.has(Y))break}}return J}var yB=new Map([["bash",new Set(["O","o"])],["dash",new Set(["o"])],["ksh",new Set(["o"])],["sh",new Set(["o"])],["zsh",new Set(["o"])]]),wB=new Map([["zsh",new Set(["o"])]]),vB=new Map([["bash",new Set(["--init-file","--rcfile"])]]);function I7($,Z){for(let J=0;J<Z.length;J++){let Q=Z[J];if(Q===void 0||Q==="--"||Q==="-"||Q[0]!=="-"&&Q[0]!=="+")return null;if(Q.startsWith("--")){let K=vB.get($);if(hB(Q,K))continue;if(!K?.has(Q))continue;if(Z[J+1]===void 0)return null;J++;continue}let X=uB($,Q);if(X.commandSelected)return Z[J+X.followingValues+1]??null;let W=Z[J+1];if($==="ksh"&&(Q==="-o"||Q==="+o")&&W!==void 0&&W[0]!=="-"&&W[0]!=="+")J++;J+=X.followingValues}return null}function uB($,Z){let J=yB.get($),Q=wB.get($),X=!1,W=0;for(let K=1;K<Z.length;K++){let Y=Z[K];if(Y===void 0)break;if(Z[0]==="-"&&Y==="c")X=!0;if($==="ksh"&&Y==="o"){if(K+1<Z.length){let B=Z.slice(K+1);if(!X&&Z[0]==="-"&&B==="c")continue;if(!X&&Z[0]==="-"&&B[0]==="-"&&B.endsWith("c"))X=!0;break}if(X)W++;continue}if(!J?.has(Y))continue;if(Q?.has(Y)&&K+1<Z.length)break;W++}return{commandSelected:X,followingValues:W}}function hB($,Z){return Z!==void 0&&[...Z].some((J)=>$.startsWith(`${J}=`))}var b7=new Set(["rm","find","xargs","parallel"]),gB=new Set(["sudo","env","command","builtin"]),kB=new Set(["git","busybox",...b7,...t,...W8,...F1]);function x4($,Z){let J=$[0];if(!J||!Z.transparentWrappers.includes(u(J)))return null;let Q=u(J),X=$[1]==="--"?2:1,W=xB($,X,Q,Z),K=W[0];if(K===void 0)return null;return{wrapper:Q,tokens:[...$.slice(K)],childIndex:K,alternativeChildIndices:W.slice(1)}}function xB($,Z,J,Q){let X=$[1]==="--",W=[];for(let K=Z;K<$.length;K++){let Y=$[K];if(!Y)continue;if(u(Y)!==J&&lB(Y,Q))W.push(K);else if(J4.has(l(Y)))break;if(X)break}return W}function lB($,Z){let J=u($),Q=l($);return Q==="git"||J==="busybox"||l0($)||b7.has(J)||Z.transparentWrappers.includes(J)||t.has(Q)||$==="$SHELL"||N1(Q)||F1.has(Q)||Z.rules.some((X)=>X.command===J)}function l0($){return gB.has($.toLowerCase())}function f7($){let Z=l($);return kB.has(Z)||N1(Z)}var J1={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"}},l4=["standard","strict","paranoid"];function mB($){return{failClosed:$==="strict"||$==="paranoid",paranoidRm:$==="paranoid",paranoidInterpreters:$==="paranoid"}}function pB($,Z){if(!Z)return $;return l4.indexOf(Z)>l4.indexOf($)?Z:$}function cB(){let $=d6(J1.level);if($===void 0||$==="")return;if(l4.includes($))return $;console.error(`CC Safety Net: ignored invalid ${J1.level.name}=${JSON.stringify($.slice(0,40))}. Use ${l4.join(", ")}.`);return}function dB($){if($===void 0||$==="all")return"all";if($==="blocked")return"blocked";return"invalid"}function iB(){return dB(d6(J1.auditScope))==="all"}function c6($){if($.failClosed&&$.paranoidRm&&$.paranoidInterpreters)return"paranoid";if($.failClosed&&!$.paranoidRm&&!$.paranoidInterpreters)return"strict";if(!$.failClosed&&!$.paranoidRm&&!$.paranoidInterpreters)return"standard";return"custom"}function m4($={}){let Z=$.safety?.level??"standard",J=cB(),Q=pB(Z,J),X=mB(Q),W={failClosed:Q===Z?"preset":"environment",paranoidRm:Q===Z?"preset":"environment",paranoidInterpreters:Q===Z?"preset":"environment"},K={failClosed:[`policy safety.level=${Z}`],paranoidRm:[`policy safety.level=${Z}`],paranoidInterpreters:[`policy safety.level=${Z}`]};if(Q!==Z)K.failClosed.push(`env ${J1.level.name}=${J}`),K.paranoidRm.push(`env ${J1.level.name}=${J}`),K.paranoidInterpreters.push(`env ${J1.level.name}=${J}`);if($.safety?.overrides?.failClosed!==void 0)X.failClosed=$.safety.overrides.failClosed,W.failClosed="capability_override",K.failClosed.push("policy safety.overrides.fail_closed");if($.safety?.overrides?.paranoidRm!==void 0)X.paranoidRm=$.safety.overrides.paranoidRm,W.paranoidRm="capability_override",K.paranoidRm.push("policy safety.overrides.paranoid_rm");if($.safety?.overrides?.paranoidInterpreters!==void 0)X.paranoidInterpreters=$.safety.overrides.paranoidInterpreters,W.paranoidInterpreters="capability_override",K.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(M$(J1.strict))X.failClosed=!0,W.failClosed="environment",K.failClosed.push(`env ${J1.strict.name}`);if(M$(J1.paranoid))X.paranoidRm=!0,X.paranoidInterpreters=!0,W.paranoidRm="environment",W.paranoidInterpreters="environment",K.paranoidRm.push(`env ${J1.paranoid.name}`),K.paranoidInterpreters.push(`env ${J1.paranoid.name}`);if(M$(J1.paranoidRm))X.paranoidRm=!0,W.paranoidRm="environment",K.paranoidRm.push(`env ${J1.paranoidRm.name}`);if(M$(J1.paranoidInterpreters))X.paranoidInterpreters=!0,W.paranoidInterpreters="environment",K.paranoidInterpreters.push(`env ${J1.paranoidInterpreters.name}`);let Y=!!$.worktreeMode||M$(J1.worktree);return{strict:X.failClosed,paranoidRm:X.paranoidRm,paranoidInterpreters:X.paranoidInterpreters,worktreeMode:Y,effectiveLevel:c6(X),capabilities:{fail_closed:{enabled:X.failClosed,source:W.failClosed,sources:K.failClosed},paranoid_rm:{enabled:X.paranoidRm,source:W.paranoidRm,sources:K.paranoidRm},paranoid_interpreters:{enabled:X.paranoidInterpreters,source:W.paranoidInterpreters,sources:K.paranoidInterpreters}}}}function M$($){let Z=typeof $==="string"?K2($):d6($);return Z==="1"||Z?.toLowerCase()==="true"}function K2($){return Object.hasOwn(process.env,$)?process.env[$]:void 0}function d6($){let Z=K2($.name);if(Z!==void 0)return Z;if($.legacyName)return K2($.legacyName);return}function VN($){return K2($.name)!==void 0||!!$.legacyName&&K2($.legacyName)!==void 0}function P7($,Z,J,Q,X){if(J.kind!=="command")return{toolName:$,input:Z,route:J,context:Q};return{toolName:$,input:Z,route:J,context:Q,command:X}}var i6=[{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"}],p4={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},sB=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],rB=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],s6=[{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"]},...rB.flatMap(($)=>sB.map((Z)=>({id:["secret.home",$.idSlug,Z.slice(1)].join("."),category:"Home path",label:[$.label,Z].join(""),description:["Blocks home ",$.label,Z," credential backup files."].join(""),suffixParts:[...$.directoryParts,[$.basename,Z].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 c4=[{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"]}],C7=[{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"}],nB=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],r6=C7.map(($)=>({id:`secret.variant.${$.slug}.separator`,category:"Variant",label:`${$.label}-* / ${$.label}_*`,description:`Blocks ${$.label} variants with dash or underscore suffixes.`,prefix:$.prefix})),n6=C7.flatMap(($)=>nB.map((Z)=>({id:`secret.variant.${$.slug}.${Z.slice(1)}`,category:"Variant",label:`${$.label}${Z}`,description:`Blocks ${$.label}${Z} private credential variants.`,prefix:$.prefix,suffix:Z}))),Y2={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)$/},a6=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map(($)=>({id:`secret.ext.${$}`,category:"Extension",label:`.${$}`,description:`Blocks files with the .${$} extension.`,extension:$})),o6=[{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?$/}],A7=[...i6,p4,...s6,...r6,...n6,Y2,...a6,...o6,...c4].map(($)=>({id:$.id,category:$.category,label:$.label,...$.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in $?{paths:$.paths}:{description:$.description}})),E7=new Set(c4.flatMap(($)=>$.category==="Coding CLI config"?[$.id]:[])),aB=A7.map(($)=>$.id),d4=new Set(aB);import{createRequire as Qq}from"node:module";var T7=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);import{isAbsolute as t6,join as oB,normalize as tB,sep as i4}from"node:path";var S7=process.platform==="win32",eB=/[*?]/;function B2($,Z){if($==="~")return Z;if($.startsWith("~/"))return`${Z}${$.slice(1)}`;return $}function r4($,Z){if(typeof $!=="string"||$.trim()==="")return"must be a non-empty path string";let J=B2($.trim(),Z);if(!t6(J))return"must be an absolute path or start with ~/";return q2(J,Z)}function n4($,Z){let J=y7($,Z);if(J===null)return"must be a non-empty path string";if(!t6(J))return null;if(q2(J,Z)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var $q="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Zq="cannot cover the guard's own configuration";function y7($,Z){if(typeof $!=="string"||$.trim()==="")return null;return B2($.trim().replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),Z)}function a4($,Z){let J=y7($,Z);if(J===null)return"must be a non-empty path string";if(eB.test(J))return"cannot contain glob characters (* or ?); list the exact file or directory";if(!t6(J))return null;if(q2(J,Z)!==null)return $q;return Jq(J,Z)?Zq:null}function Jq($,Z){let J=s4($),Q=s4(oB(Z,".cc-safety-net"));return J===Q||J.startsWith(`${Q}${i4}`)}function q2($,Z){let J=s4($),Q=s4(Z);if(J===Q)return"cannot be the home directory";let X=J.endsWith(i4)?J:`${J}${i4}`;if(Q.startsWith(X))return"cannot contain the home directory";return null}function s4($){let Z=tB($);if(S7)Z=Z.replace(/\//g,"\\").toLowerCase();if(Z.length>(S7?3:1)&&Z.endsWith(i4))Z=Z.slice(0,-1);return Z}var U2=64,v7="Rule config exceeds CC Safety Net's safe source limit.";var w7=Object.freeze({maxSources:64,concurrency:4,maxRequests:131,maxResponseBytes:67108864});function o4($={}){return{requests:0,responseBytes:0,maxRequests:$.maxRequests??w7.maxRequests,maxResponseBytes:$.maxResponseBytes??w7.maxResponseBytes}}function t4($){return{controller:new AbortController,budget:o4(),resolveUrl:$}}function u7($){if($.requests>=$.maxRequests)throw Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");$.requests++}function h7($,Z){if(Z>$.maxResponseBytes-$.responseBytes)throw $.responseBytes+=Z,Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");$.responseBytes+=Z}var Xq=Qq(import.meta.url),g7,Wq=Array(U2+1).fill("over-limit"),k7=/^[^/]+\/[^/]+$/,Kq=/^sha256:[a-f0-9]{64}$/,e4=`must be an integer between ${o3} and ${t3}`,Yq=["version","rules","overrides","transparent_wrappers"],Bq=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function x7($){if(!P1($)||!Array.isArray($.rules)||$.rules.length<=U2)return $;return{$schema:$.$schema,version:$.version,rules:Wq,overrides:$.overrides,transparent_wrappers:$.transparent_wrappers}}function qq(){let $=Xq("../vendor/zod.cjs"),Z=(F)=>{let R=$.superRefine(F);return R._zod.def.when=()=>!0,R},J=$.enum(T7),Q=$.union([$.literal("off"),$.looseObject({reason:$.string({error:"required non-empty string"}).min(1,"required non-empty string").max(B$,`must be at most ${B$} characters`).describe("Replacement block reason"),intent:J.optional()})],{error:'must be "off" or an object'}).describe("Disable a rule or replace its block reason and intent."),X=$.string({error:"must be a rulebook source string"}).min(1,"must be a non-empty rulebook source string"),W=$.string({error:"must be a command string"}).regex(w0,"must match command pattern").describe("Command name such as 'git', 'docker', or 'rtk'."),K=$.looseObject({$schema:$.unknown().optional().describe("JSON Schema reference for IDE support"),version:$.literal(1).describe("Schema version (must be 1)"),rules:$.array(X,{error:"must be an array of rulebook source strings"}).max(U2,v7).default([]).describe("Rulebook source strings such as project-rules or owner/repo#main/team-rules"),overrides:$.record($.string().meta({pattern:k7.source}),Q).default({}).describe("Rule overrides by id"),transparent_wrappers:$.array(W,{error:"must be an array of command strings"}).default([]).describe("Commands that transparently execute a visible protected child command")}),Y=(F,R)=>{if(!P1(F))return;if(Array.isArray(F.rules)&&F.rules.length<=U2){let b=new Set;F.rules.forEach((P,y)=>{if(typeof P!=="string"||P==="")return;if(P.trim()===""){R.addIssue({code:"custom",message:"must be a non-empty rulebook source string",path:["rules",y]});return}let w=p$(P);if(w){R.addIssue({code:"custom",message:w,path:["rules",y]});return}if(b.has(P)){R.addIssue({code:"custom",message:`duplicate rulebook source "${P}"`,path:["rules",y]});return}b.add(P)})}if(P1(F.overrides))for(let b of Object.keys(F.overrides)){if(k7.test(b))continue;R.addIssue({code:"custom",message:"must use <rulebook-name>/<rule-name>",path:["overrides",b]})}if(!Array.isArray(F.transparent_wrappers))return;let I=new Set;F.transparent_wrappers.forEach((b,P)=>{if(typeof b!=="string"||!w0.test(b))return;if(I.has(b)){R.addIssue({code:"custom",message:`duplicate command "${b}"`,path:["transparent_wrappers",P]});return}if(f7(b)){R.addIssue({code:"custom",message:`reserved command "${b}" cannot be a wrapper`,path:["transparent_wrappers",P]});return}I.add(b)})},B=$.preprocess(x7,K.check($.superRefine(Y))),q=$.preprocess(x7,K.check(Z(Y))),U=$.strictObject({fail_closed:$.boolean().optional(),paranoid_rm:$.boolean().optional(),paranoid_interpreters:$.boolean().optional()}),G=(F,R)=>$.intersection($.record($.string().refine((I)=>F.has(I),{error:(I)=>`unknown ${R} rule id "${String(I.input)}"`}),$.unknown()),$.record($.string(),$.enum(["on","off"]))),j=(F)=>$.array($.string({error:"must be a non-empty path string"}),{error:"must be an array of paths"}).check(Z((R,I)=>{if(!Array.isArray(R))return;let b=u0();R.forEach((P,y)=>{if(typeof P!=="string")return;let w=F(P,b);if(w)I.addIssue({code:"custom",message:w,path:[y]})})})),H=$.strictObject({version:$.literal(1),safety:$.strictObject({level:$.enum(["standard","strict","paranoid"]).optional(),overrides:U.optional()}).optional(),workflow:$.strictObject({worktree_mode:$.boolean().optional()}).optional(),destructive_command_protection:$.strictObject({enabled:$.boolean().optional(),overrides:G(e2,"destructive command").optional(),allow_paths:j(r4).optional()}).optional(),secret_protection:$.strictObject({enabled:$.boolean().optional(),overrides:G(d4,"secret protection").optional(),deny_paths:j(n4).optional(),allow_paths:j(a4).optional()}).optional(),audit:$.strictObject({retention_days:$.number({error:e4}).int(e4).min(o3,e4).max(t3,e4).optional().describe("Days of audit log history to keep before the sweep deletes it")}).optional()}),_=(F)=>{let R=(y,w)=>F==="legacy"?y:w,I=R("must match pattern (letters, numbers, hyphens, underscores)","must match command pattern"),b=`required non-empty string up to ${B$} characters`,P=$.looseObject({name:$.string({error:"required string"}).regex(I1,R("must match pattern (letters, numbers, hyphens, underscores; max 64 chars)","must match rule name pattern")),command:$.string({error:R("required string","required string matching command pattern")}).regex(w0,R(I,"required string matching command pattern")),subcommand:$.string({error:R("must be a string if provided","must match command pattern")}).regex(w0,I).optional(),block_args:$.array($.string({error:R("must be a string","must be a non-empty string")}).refine((y)=>y!=="",{error:R("must not be empty","must be a non-empty string")}),{error:R("required array","required non-empty array")}).refine((y)=>y.length>0,{error:R("must have at least one element","required non-empty array")}),reason:$.string({error:R("required string",b)}).refine((y)=>y!=="",{error:R("must not be empty",b)}).refine((y)=>y.length<=B$,{error:R(`must be at most ${B$} characters`,b)}),intent:J.optional()},{error:"must be an object"});return $.array(P,{error:R("must be an array","required array")}).check(Z((y,w)=>{if(!Array.isArray(y))return;let x=new Set;y.forEach((Y1,C)=>{let v=P1(Y1)?Y1.name:void 0;if(typeof v!=="string")return;if(x.has(v.toLowerCase())){w.addIssue({code:"custom",message:`duplicate rule name "${v}"`,path:[C,"name"]});return}x.add(v.toLowerCase())})}))},O=$.looseObject({version:$.literal(1),rules:_("legacy").optional()}),M="required string matching rule name pattern",L=$.looseObject({command:$.string({error:"required non-empty string"}).refine((F)=>F.trim()!=="",{error:"required non-empty string"}),expect:$.enum(["blocked","allowed"]),rule:$.string({error:"must be a string if provided"}).optional()},{error:"must be an object"}).check(Z((F,R)=>{if(!P1(F))return;if(F.expect!=="blocked"||typeof F.rule==="string")return;R.addIssue({code:"custom",message:"required string for blocked fixtures",path:["rule"]})})),D=$.looseObject({name:$.string({error:"required string matching rule name pattern"}).regex(I1,"required string matching rule name pattern"),version:$.string({error:"required non-empty string"}).refine((F)=>F!=="",{error:"required non-empty string"}),allowed_commands:$.array($.string({error:"must match command pattern"}).regex(w0,"must match command pattern"),{error:"required array"}).check(Z((F,R)=>{if(!Array.isArray(F))return;let I=new Set;F.forEach((b,P)=>{if(typeof b!=="string"||!w0.test(b))return;if(I.has(b)){R.addIssue({code:"custom",message:`duplicate command "${b}"`,path:[P]});return}I.add(b)})})),rules:_("rulebook"),tests:$.array(L,{error:"must be an array if provided"}).optional()}).check(Z((F,R)=>{if(!P1(F))return;let I=new Set(e6(F));if(Array.isArray(F.tests)){let P=new Set(F.tests.flatMap((y)=>P1(y)&&y.expect==="blocked"&&typeof y.rule==="string"?[y.rule]:[]));for(let y of P){if(I.has(y))continue;R.addIssue({code:"custom",message:`blocked fixture references unknown rule "${y}"`,path:["tests"]})}}if(!Array.isArray(F.allowed_commands)||!Array.isArray(F.rules))return;let b=new Set(F.allowed_commands.filter((P)=>typeof P==="string"));F.rules.forEach((P,y)=>{let w=P1(P)?P.command:void 0;if(typeof w!=="string"||b.has(w))return;R.addIssue({code:"custom",message:`"${w}" must be listed in allowed_commands`,path:["rules",y,"command"]})})})),z=$.string({error:"required string"}).refine((F)=>F.trim()!=="",{error:"required string"}),f=$.looseObject({spec:z,name:z,version:z,digest:$.string({error:"required sha256 digest"}).regex(Kq,"required sha256 digest")},{error:"must be an object"}),A=$.looseObject({rulebooks:$.array($.intersection(f,$.discriminatedUnion("kind",[$.object({kind:$.literal("local-directory"),path:z}),$.object({kind:$.literal("github"),owner:z,repo:z,ref:z,commit:z,path:z,display_ref:$.unknown().optional()})],{error:(F)=>{if(!P1(F.input))return"must be an object";let R=F.input.kind;return typeof R==="string"?`unknown kind "${R}"`:"required string"}})))});return{RulesConfigSchema:B,RulesConfigDiagnosticSchema:q,RuleOverrideSchema:Q,UserPolicySchema:H,LegacyConfigSchema:O,RulebookSchema:D,RulesLockfileSchema:A}}function F$(){return g7??=qq(),g7}function l7(){return F$().RulesConfigSchema}function Uq(){return F$().UserPolicySchema}function kN(){return F$().LegacyConfigSchema}function m7(){return F$().RulebookSchema}function p7(){return F$().RulesLockfileSchema}function e6($){let Z=P1($)?$.rules:void 0;return(Array.isArray(Z)?Z:[]).flatMap((J)=>{let Q=P1(J)?J.name:void 0;return typeof Q==="string"?[Q]:[]})}function c7($){let Z=F$().RulesConfigDiagnosticSchema.safeParse($);if(Z.success)return{errors:[],sources:new Set(Z.data.rules)};return{errors:N$(i7(Z.error.issues,Yq)),sources:_q($,Z.error.issues)}}function G2($){let Z=Uq().safeParse($);if(Z.success)return[];return N$(i7(Z.error.issues,Bq)," ")}function N$($,Z=": ",J=" "){return[...new Set($.flatMap((Q)=>d7(Q,Z,J,[])))]}function d7($,Z,J,Q){let X=[...Q,...$.path],W=jq(X);if($.code==="unrecognized_keys")return $.keys.map((K)=>`${W?`${W}.`:""}unknown field "${K}"`);if($.code==="invalid_key")return $.issues.map((K)=>K.message);if($.code==="invalid_union"){let K=$.errors.flat().filter((Y)=>Y.path.length>0);if(K.length>0)return K.flatMap((Y)=>d7(Y,Z,J,X))}if(X.length===0)return[$.code==="invalid_type"?"Config must be an object":$.message];if(X.length===1&&($.code==="too_big"||$.code==="too_small")&&$.origin==="array")return[$.message];return[`${W}${X.length===1?J:Z}${Gq($)}`]}function Gq($){if($.code==="invalid_value")return`must be ${Hq($.values)}`;if($.code!=="invalid_type"||!$.message.startsWith("Invalid input:"))return $.message;if($.expected==="object"||$.expected==="record")return"must be an object if provided";return $.expected==="boolean"?"must be a boolean":$.message}function Hq($){if($.length>3)return`one of ${$.join(", ")}`;let Z=$.map((J)=>typeof J==="string"?`"${J}"`:String(J));if(Z.length<2)return`${Z[0]}`;return`${Z.slice(0,-1).join(", ")}${Z.length>2?",":""} or ${Z.at(-1)}`}function jq($){return $.map((Z,J)=>{if(typeof Z==="number")return`[${Z}]`;return J===0?String(Z):`.${String(Z)}`}).join("")}function i7($,Z){let J=$.map((W)=>W.path[1]),Q=[...new Set(J.filter((W)=>typeof W==="string"))],X=(W,K)=>[W.path.length===0?-1:Z.indexOf(String(W.path[0])),typeof K==="number"?K:Q.indexOf(String(K)),W.code==="custom"?0:1];return $.map((W,K)=>({issue:W,rank:X(W,J[K])})).sort((W,K)=>W.rank[0]-K.rank[0]||W.rank[1]-K.rank[1]||W.rank[2]-K.rank[2]).map((W)=>W.issue)}function _q($,Z){let J=P1($)?$.rules:void 0;if(!Array.isArray(J))return new Set;if(Z.some((X)=>X.path.length===1&&X.path[0]==="rules"))return new Set;let Q=new Set(Z.filter((X)=>X.path[0]==="rules"&&typeof X.path[1]==="number").map((X)=>X.path[1]));return new Set(J.filter((X,W)=>typeof X==="string"&&!Q.has(W)))}function P1($){return!!$&&typeof $==="object"&&!Array.isArray($)}var s7={version:1,rules:[],overrides:{},transparent_wrappers:[]};function Oq($){return c7($)}function V$($){try{let Z=K0(r7($));if(Z===null)return{config:null,errors:[]};if(!Z.trim())return{config:null,errors:["Config file is empty"]};let J=JSON.parse(Z),Q=Oq(J);if(Q.errors.length>0)return{config:null,errors:Q.errors};let X=l7().parse(J);return{config:{version:1,rules:X.rules??[],overrides:X.overrides??{},transparent_wrappers:X.transparent_wrappers??[]},errors:[]}}catch(Z){if(Z instanceof h)return{config:null,errors:[Z.message]};let J=Z instanceof Error?Z.message:String(Z);return{config:null,errors:[Z instanceof SyntaxError?"Invalid JSON":J]}}}function dN($){let Z=V$($);if(Z.errors.length>0)return{ok:!1,result:{ok:!1,errors:Z.errors,warnings:[],entries:[]}};return{ok:!0,config:Z.config??s7}}function iN($,Z=[]){$3($,{version:1,rules:Z,overrides:{},transparent_wrappers:[]})}function sN($,Z="project-rules"){$3($,{rulebook_version:1,name:Z,version:"1.0.0",description:Z==="project-rules"?"Project-specific CC Safety Net rules.":"User-specific CC Safety Net rules.",author:Z==="project-rules"?"project":"user",allowed_commands:["docker"],rules:[{name:"block-docker-system-prune",command:"docker",subcommand:"system",block_args:["prune"],reason:"Use targeted cleanup instead."}],tests:[{command:"docker system prune",expect:"blocked",rule:"block-docker-system-prune"}]})}function $3($,Z,J,Q){VZ(r7($),`${JSON.stringify(Z,null,2)}
50
- `,J,Q)}function r7($){return typeof $==="string"?k2($):$}import{chmodSync as Lq,existsSync as $9,mkdirSync as Mq,readFileSync as Z9}from"node:fs";import{dirname as o7,join as Fq}from"node:path";var Nq=new Set(["standard","strict","paranoid"]),J3={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:i2}};function z$($){return Fq(o7(Y0($)),p2)}function KV($={}){let Z=z$($);if(!$9(Z))return{path:Z,exists:!1,raw:"",policy:R$(),errors:[]};let J=Z9(Z,"utf-8");if(!J.trim())return{path:Z,exists:!0,raw:J,policy:R$(),errors:["Config file is empty"]};try{let Q=JSON.parse(J),X=G2(Q);return{path:Z,exists:!0,raw:J,policy:X.length>0?R$():D$(Q),errors:X}}catch(Q){return{path:Z,exists:!0,raw:J,policy:R$(),errors:[`Invalid JSON: ${Q instanceof Error?Q.message:String(Q)}`]}}}function Z3($,Z={}){let J=z$(Z),Q=G2($),X=Q.length>0?R$():D$($);if(Q.length>0)return{path:J,policy:X,errors:Q};return Mq(o7(J),{recursive:!0,mode:448}),$3(J,X,384),Lq(J,384),{path:J,policy:X,errors:[]}}function YV($){let Z=G2($);if(Z.length>0)return{errors:Z};return{preview:Vq(D$($)),errors:[]}}function Vq($){let Z=m4({safety:$5($.safety)}),J=K6({destructiveCommandProtectionEnabled:$.destructive_command_protection.enabled,destructiveCommandRuleOverrides:$.destructive_command_protection.overrides},Z.capabilities),Q=Object.values(J),X=Q.filter((W)=>W.source!=="catastrophic");return{selectedPreset:$.safety.level,effectiveLevel:Z.effectiveLevel,capabilities:Z.capabilities,rules:J,counts:{enabled:X.filter((W)=>W.enabled).length,disabled:X.filter((W)=>!W.enabled).length,effectiveCustomizations:Q.filter((W)=>W.changesInherited).length}}}function BV($={}){let Z=z$($);if(!$9(Z))return Z3(J3,$);let J=Z9(Z,"utf-8");if(!J.trim())return Z3(J3,$);try{return Z3(D$(JSON.parse(J)),$)}catch{return Z3(J3,$)}}function t7($={}){let Z=Iq(z$($));return{safety:Z.policy.safety,worktreeMode:Z.policy.worktreeMode,destructiveCommandProtectionEnabled:Z.policy.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:Z.policy.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:Z.policy.destructiveCommandAllowPaths,secretProtection:Z.policy.secretProtection,errors:Z.errors,...Z.fallback?{fallback:Z.fallback}:{}}}function D$($){if(!o1($))return R$();let Z=o1($.safety)?$.safety:{},J=o1(Z.overrides)?Z.overrides:{},Q=o1($.workflow)?$.workflow:{},X=o1($.destructive_command_protection)?$.destructive_command_protection:{},W=o1($.secret_protection)?$.secret_protection:{};return{version:1,safety:{level:Nq.has(Z.level)?Z.level:"standard",overrides:{...typeof J.fail_closed==="boolean"?{fail_closed:J.fail_closed}:{},...typeof J.paranoid_rm==="boolean"?{paranoid_rm:J.paranoid_rm}:{},...typeof J.paranoid_interpreters==="boolean"?{paranoid_interpreters:J.paranoid_interpreters}:{}}},workflow:{worktree_mode:typeof Q.worktree_mode==="boolean"?Q.worktree_mode:!1},destructive_command_protection:{enabled:typeof X.enabled==="boolean"?X.enabled:!0,overrides:n7(X.overrides,e2),allow_paths:Dq(X.allow_paths)},secret_protection:{enabled:typeof W.enabled==="boolean"?W.enabled:!0,overrides:n7(W.overrides,d4),deny_paths:Rq(W.deny_paths),allow_paths:zq(W.allow_paths)},audit:{retention_days:s2(o1($.audit)?$.audit.retention_days:void 0)}}}function n7($,Z){if(!o1($))return{};return Object.fromEntries(Object.entries($).flatMap(([J,Q])=>Z.has(J)&&(Q==="on"||Q==="off")?[[J,Q]]:[]))}function Rq($){if(!Array.isArray($))return[];let Z=u0();return $.filter((J)=>n4(J,Z)===null)}function Dq($){if(!Array.isArray($))return[];let Z=u0();return $.filter((J)=>r4(J,Z)===null)}function zq($){if(!Array.isArray($))return[];let Z=u0();return $.filter((J)=>a4(J,Z)===null)}function o1($){return!!$&&typeof $==="object"&&!Array.isArray($)}function R$(){return structuredClone(J3)}function Iq($){let Z=bq();if(!$9($)){let J=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!o1(J))return{policy:Z,errors:[]};return{policy:a7(D$(J)),errors:[]}}try{let J=Z9($,"utf-8");if(!J.trim())return{policy:Z,errors:[`${$}: Config file is empty`],fallback:"defaults"};let Q=JSON.parse(J),X=G2(Q),W=a7(D$(Q));if(X.length>0)return{policy:W,errors:X.map((K)=>`${$}: ${K}`),fallback:o1(Q)?"salvaged":"defaults"};return{policy:W,errors:[]}}catch(J){let Q=J instanceof Error?J.message:String(J);return{policy:Z,errors:[`${$}: ${J instanceof SyntaxError?"Invalid JSON":Q}`],fallback:"defaults"}}}function e7($){let Z=Object.entries($),J=new Set(Z.flatMap(([Q,X])=>X==="on"?[Q]:[]));return new Set([...[...E7].filter((Q)=>!J.has(Q)),...Z.flatMap(([Q,X])=>X==="off"?[Q]:[])])}function bq(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:e7({}),denyPaths:[],allowPaths:[]}}}function a7($){return{safety:$5($.safety),worktreeMode:$.workflow.worktree_mode,destructiveCommandProtectionEnabled:$.destructive_command_protection.enabled,destructiveCommandRuleOverrides:$.destructive_command_protection.overrides,destructiveCommandAllowPaths:$.destructive_command_protection.allow_paths,secretProtection:{enabled:$.secret_protection.enabled,disabledRules:e7($.secret_protection.overrides),denyPaths:$.secret_protection.deny_paths,allowPaths:$.secret_protection.allow_paths}}}function $5($){let Z={...$.overrides.fail_closed!==void 0?{failClosed:$.overrides.fail_closed}:{},...$.overrides.paranoid_rm!==void 0?{paranoidRm:$.overrides.paranoid_rm}:{},...$.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:$.overrides.paranoid_interpreters}:{}};return{level:$.level,...Object.keys(Z).length>0?{overrides:Z}:{}}}import{dirname as _0}from"node:path";var Z5="Rulebook exceeds CC Safety Net's safe validation limits.",J5="Additional rulebook validation errors were omitted.",g1=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Q5($){if(J9($.allowed_commands,g1.maxAllowedCommands)||J9($.rules,g1.maxRules)||J9($.tests,g1.maxTests))return!1;let{maxAggregateStringCodeUnits:Z,maxTotalBlockArgs:J}=g1,Q=(X,W=!1)=>{if(typeof X!=="string")return!0;if(X.length>g1.maxStringCodeUnits||W&&X.length>g1.maxFixtureCommandCodeUnits||X.length>Z)return!1;return Z-=X.length,!0};if(!Q($.name)||!Q($.version)||!Q($.description)||!Q($.author)||!Q($.migrated_from))return!1;if(Array.isArray($.allowed_commands)){for(let X of $.allowed_commands)if(!Q(X))return!1}if(Array.isArray($.rules))for(let X of $.rules){if(!X||typeof X!=="object")continue;let W=X;if(!Q(W.name)||!Q(W.command)||!Q(W.subcommand)||!Q(W.reason)||!Q(W.intent))return!1;if(!Array.isArray(W.block_args))continue;if(W.block_args.length>g1.maxBlockArgsPerRule||W.block_args.length>J)return!1;J-=W.block_args.length;for(let K of W.block_args)if(!Q(K))return!1}if(Array.isArray($.tests))for(let X of $.tests){if(!X||typeof X!=="object")continue;let W=X;if(!Q(W.command,!0)||!Q(W.expect)||!Q(W.rule))return!1}return!0}function J9($,Z){return Array.isArray($)&&$.length>Z}function fq($){if(!Pq($))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Q5($))return{errors:[Z5],ruleNames:new Set};let Z=m7().safeParse($),J=[...$.rulebook_version===1?[]:["rulebook_version must be 1"],...Z.success?[]:N$(Z.error.issues,": ",": ")];return{errors:J.length>g1.maxValidationErrors?[...J.slice(0,g1.maxValidationErrors),J5]:J,ruleNames:new Set(e6($).map((Q)=>Q.toLowerCase()))}}function I$($){let Z=fq($);if(Z.errors.length>0)throw Error(Z.errors.join("; "));return $}function Pq($){return!!$&&typeof $==="object"&&!Array.isArray($)}var Cq=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#([A-Za-z0-9._-]+)$/;function Q3($){if(W$($.spec))return Eq($);return Aq($)}function Aq($){if(!I1.test($.spec))return`Local rulebook sources must be bare names matching ${I1}: ${$.spec}`;if($.kind!=="local-directory")return`lock entry for ${$.spec} must use local-directory kind`;if($.path===$.spec&&$.name===$.spec)return null;return`lock entry for ${$.spec} does not match local source identity`}function Eq($){let Z=p$($.spec);if(Z)return Z;let J=X$($.spec);if($.kind!=="github")return`lock entry for ${$.spec} must use github kind`;if($.owner===J.owner&&$.repo===J.repo&&$.ref===J.ref&&$.path===J.path&&$.name===J.name)return null;return`lock entry for ${$.spec} does not match GitHub source identity`}function FV($,Z,J){let Q=W5($.rules,J);if(Q.length>0)return{ok:!0,specs:Q};if(!Z)return{ok:!1,result:{ok:!1,errors:[`No lockfile available to match rulebook name ${J}; use the exact source or run ${w1}`],warnings:[],entries:[]}};let X=new Set($.rules),W=Z.rulebooks.filter((K)=>K.name===J&&X.has(K.spec)).map((K)=>K.spec);if(W.length===1)return{ok:!0,specs:W};return X5(J,W)}function NV($,Z,J){let Q=W5($,J);if(Q.length>0)return{ok:!0,specs:Q};let X=Tq($,J);if(X.length>0)return{ok:!0,specs:X};let W=Sq($,J);if(!W.ok)return W;if(W.specs.length>0)return{ok:!0,specs:W.specs};let K=Z?$.filter((Y)=>Z.rulebooks.find((B)=>B.spec===Y)?.name===J):[];if(K.length===1)return{ok:!0,specs:K};return X5(J,K)}function X5($,Z){return{ok:!1,result:{ok:!1,errors:Z.length===0?[`No configured rulebook matches ${$}`]:[`Ambiguous rulebook match ${$}: ${Z.join(", ")}`],warnings:[],entries:[]}}}function W5($,Z){return $.filter((J)=>J===Z)}function Tq($,Z){let J=Z.match(Cq),Q=J?.[1],X=J?.[2],W=J?.[3];if(!Q||!X||!W)return[];return Y5($,(K)=>{return K.owner===Q&&K.repo===X&&K.ref===W})}function Sq($,Z){if(!CZ(Z))return{ok:!0,specs:[]};let[J,Q]=Z.split("/"),X=Y5($,(K)=>{return K.owner===J&&K.repo===Q});if(new Set(X.map((K)=>K5(K)?.ref).filter((K)=>!!K)).size<2)return{ok:!0,specs:X};return{ok:!1,result:{ok:!1,errors:[`Multiple refs are configured for ${Z}. Use an explicit ref:`,` cc-safety-net rule remove ${Z}#<ref>`],warnings:[],entries:[]}}}function K5($){try{return X$($)}catch{return null}}function Y5($,Z){return $.filter((J)=>{let Q=K5(J);return Q?Z(Q):!1})}function Q9($){let Z=typeof $==="string"?$:$.path;try{let J=K0(typeof $==="string"?k2($):$);if(J===null)return{lock:null,errors:[]};let Q=JSON.parse(J);if(!Q||typeof Q!=="object")return{lock:null,errors:[`malformed lockfile ${Z}: must be an object`]};let X=Q;if(X.version!==1||!Array.isArray(X.rulebooks))return{lock:null,errors:[`malformed lockfile ${Z}`]};let W=p7().safeParse(X),K=X.rulebooks.flatMap((B,q)=>{let U=W.success?[]:W.error.issues.filter((j)=>j.path[1]===q);if(U.length>0)return N$(U).map((j)=>`${Z}: ${j}`);let G=Q3(B);return G?[`${Z}: rulebooks[${q}]: ${G}`]:[]});if(!W.success||K.length>0)return{lock:null,errors:[`malformed lockfile ${Z}`,...K]};return{lock:{version:1,rulebooks:W.data.rulebooks.map((B)=>{if(B.kind==="local-directory")return{spec:B.spec,kind:B.kind,path:B.path,name:B.name,version:B.version,digest:B.digest};let q={spec:B.spec,kind:B.kind,owner:B.owner,repo:B.repo,ref:B.ref,commit:B.commit,path:B.path,name:B.name,version:B.version,digest:B.digest};return typeof B.display_ref==="string"&&B.display_ref!==""?{...q,display_ref:B.display_ref}:q})},errors:[]}}catch(J){if(J instanceof h)return{lock:null,errors:[J.message]};return{lock:null,errors:["malformed lockfile"]}}}import{createHash as yq}from"node:crypto";import{dirname as X3,join as wq}from"node:path";var U5=Object.freeze({timeoutMs:15000,metadataBytes:524288,commitBytes:262144,treeBytes:16777216,rawBytes:4194304});async function B5($,Z,J,Q=z1(X3(X3(Z)),"rules policy"),X=t4()){if(W$($))return uq($,X);return vq($,Z,J,Q)}async function yV($,Z,J,Q,X,W=t4()){if(!W$($)||J.refresh)return B5($,Z,J,X,W);let K=Q?.rulebooks.find((Y)=>Y.spec===$);if(!K||K.kind!=="github")return B5($,Z,J,X,W);return hq(K,Z,J,X,W)}async function wV($,Z=t4()){let[J,Q]=$.split("/");if(!J||!Q)throw Error(`Invalid GitHub repository source: ${$}`);let X=await H2(`https://api.github.com/repos/${J}/${Q}`,"metadata",Z),W=X.response;if(!W.ok)throw Error(`Failed to inspect ${$}: GitHub returned ${W.status}`);let K=JSON.parse(X.content);if(!K.default_branch)throw Error(`Failed to inspect ${$}: missing default branch`);let Y=await H5(J,Q,K.default_branch,$,Z),B=await H2(`https://api.github.com/repos/${J}/${Q}/git/trees/${Y}?recursive=1`,"tree",Z),q=B.response;if(!q.ok)throw Error(`Failed to inspect ${$}: GitHub tree returned ${q.status}`);let G=(JSON.parse(B.content).tree??[]).flatMap((j)=>{if(j.type!=="blob"||typeof j.path!=="string")return[];let H=j.path.match(n3);return H?.[1]?[H[1]]:[]}).sort();if(G.length===0)throw Error(`No rulebooks found in ${$} under ${m2}/`);return G.map((j)=>({spec:`${J}/${Q}#${Y}/${j}`,display_ref:K.default_branch}))}function vq($,Z,J,Q){a3($);let X=lq(Z,$),W=K0(X1(Q,X));if(W===null)throw Error(`Rulebook source not found: ${$}`);let K=I$(X9(W,"Invalid local rulebook source."));if(K.name!==$)throw Error(`rulebook name "${K.name}" must match local source "${$}"`);return{rulebook:K,content:W,entry:{spec:$,kind:"local-directory",path:$,name:K.name,version:K.version,digest:b$(W)}}}async function uq($,Z){let J=X$($),Q=await H5(J.owner,J.repo,J.ref,$,Z),X=await H2(`https://raw.githubusercontent.com/${J.owner}/${J.repo}/${Q}/${J.path}`,"raw",Z),W=X.response;if(!W.ok)throw Error(`Failed to fetch ${$}: GitHub raw returned ${W.status}`);let K=X.content,Y=I$(X9(K,"Invalid GitHub rulebook response."));if(Y.name!==J.name)throw Error(`rulebook name "${Y.name}" must match GitHub source "${J.name}"`);return{rulebook:Y,content:K,entry:{spec:$,kind:"github",owner:J.owner,repo:J.repo,ref:J.ref,commit:Q,path:J.path,name:Y.name,version:Y.version,digest:b$(K)}}}async function hq($,Z,J,Q=z1(X3(X3(Z)),"rules policy"),X){let W=Q3($);if(W)throw Error(`${W}; run ${w1}`);let K=c2($,d2(Z,J)),Y=K0(X1(Q,K));if(Y!==null){if(b$(Y)===$.digest)return{entry:$,rulebook:G5(Y,$),content:Y}}return gq($,X)}async function gq($,Z){let J=await H2(`https://raw.githubusercontent.com/${$.owner}/${$.repo}/${$.commit}/${$.path}`,"raw",Z),Q=J.response;if(!Q.ok)throw Error(`Failed to restore ${$.spec}: GitHub raw returned ${Q.status}`);let X=J.content;if(b$(X)!==$.digest)throw Error(`locked GitHub digest mismatch for ${$.spec}; run ${w1}`);return{entry:$,rulebook:G5(X,$),content:X}}function G5($,Z){let J=I$(X9($,"Invalid cached rulebook."));if(J.name!==Z.name)throw Error(`rulebook name "${J.name}" must match lock entry "${Z.name}"`);return J}function X9($,Z){try{return JSON.parse($)}catch{throw Error(Z)}}async function H5($,Z,J,Q,X){let W=await H2(`https://api.github.com/repos/${$}/${Z}/commits/${encodeURIComponent(J)}`,"commit",X),K=W.response;if(!K.ok)throw Error(`Failed to resolve ${Q}: GitHub returned ${K.status}`);let Y=JSON.parse(W.content);if(!Y.sha)throw Error(`Failed to resolve commit for ${Q}`);return Y.sha}async function kq($,Z,J={}){if(J.signal?.aborted)throw J.signal.reason;let Q=J.budget??o4(),X=new AbortController,W=()=>X.abort(J.signal?.reason);J.signal?.addEventListener("abort",W,{once:!0});let K=!1,Y=setTimeout(()=>{if(X.signal.aborted)return;K=!0,X.abort()},J.timeoutMs??U5.timeoutMs);try{if(J.signal?.aborted)throw J.signal.reason;u7(Q);let B=await(J.fetch??fetch)($,{signal:X.signal,redirect:"error"});if(!B.ok)return j5(B),{response:B,content:""};return{response:B,content:await xq(B,Z,Q,()=>X.abort())}}catch(B){if(K)throw Error("GitHub request timed out",{cause:B});if(J.signal?.aborted)throw J.signal.reason;throw B}finally{clearTimeout(Y),J.signal?.removeEventListener("abort",W)}}function H2($,Z,J){return kq(J.resolveUrl?.($)??$,Z,{budget:J.budget,signal:J.controller.signal})}async function xq($,Z,J=o4(),Q){let X=U5[`${Z}Bytes`],W=Number($.headers.get("content-length"));if(Number.isFinite(W)&&W>X)throw j5($),Error(`GitHub ${Z} response exceeds ${X} bytes`);if(!$.body)return"";let K=$.body.getReader(),Y=[],B=0;while(!0){let q=await K.read();if(q.done)break;try{h7(J,q.value.byteLength)}catch(U){throw Q?.(),q5(K),U}if(B+=q.value.byteLength,B>X)throw Q?.(),q5(K),Error(`GitHub ${Z} response exceeds ${X} bytes`);Y.push(Buffer.from(q.value))}return Buffer.concat(Y,B).toString("utf-8")}function j5($){if(!$.body)return;_5(()=>$.body?.cancel())}function q5($){_5(()=>$.cancel())}function _5($){try{Promise.resolve($()).catch(()=>{})}catch{}}function lq($,Z){return wq($,Z,l2)}function b$($){return`sha256:${yq("sha256").update($).digest("hex")}`}function M5($={}){let Z=vZ($),J=!1;try{J=RZ(Z.userConfigTarget,Z.projectConfigTarget)}catch(j){if(j instanceof h)return sq(Z,j.message);throw j}let Q=V$(Z.userConfigTarget),X=J?{config:null,errors:[]}:V$(Z.projectConfigTarget),W=L5(Z.userConfigPath,Q.errors),K=L5(Z.projectConfigPath,X.errors),Y=new Set,B=Q.config?W9(Q.config,Z.userLockPath,_0(Z.userConfigPath),$,"user",Z.userScope,Y):j2(),q=X.config?W9(X.config,Z.projectLockPath,_0(Z.projectConfigPath),$,"project",Z.projectScope,Y):j2(),U=Q.config?.overrides??{},G=X.config?.overrides??{};return{rules:[...O5(B.rules,U),...O5(q.rules,G)],transparent_wrappers:dq(Q.config,X.config),rulebooks:[...B.rulebooks,...q.rulebooks],errors:[...W,...K,...B.errors,...q.errors],warnings:[...B.warnings,...q.warnings,...B.canValidateOverrides?K9(U,B.knownRuleIds,Z.userConfigPath):[],...B.canValidateOverrides?iq(G,B.knownRuleIds,Z.projectConfigPath):[],...q.canValidateOverrides?K9(G,q.knownRuleIds,Z.projectConfigPath):[]],userConfig:Q.config??void 0,projectConfig:X.config??void 0,...Z}}function pV($,Z){let J=Z??z1(_0(_0($)),"rules policy"),Q=V$(X1(J,$)).config,X=Q9(X1(J,S0($))).lock;if(!Q||!X)return new Map;let W=new Set(Q.rules);return new Map(X.rulebooks.filter((K)=>W.has(K.spec)).map((K)=>[K.spec,gZ(K)]))}function cV($,Z,J,Q){let X=mq($,Z,J,Q);if(!X)return[];return[...X.scope.errors,...X.scope.warnings,...pq(X.config,X.scope,$)]}function mq($,Z,J,Q){let X=Q??z1(_0(_0($)),"rules policy"),W=V$(X1(X,$)).config;if(!W)return null;return{config:W,scope:W9(W,Z,_0($),J,"project",X)}}function pq($,Z,J){return Z.canValidateOverrides?K9($.overrides??{},Z.knownRuleIds,J):[]}function W9($,Z,J,Q,X,W=z1(_0(_0(J)),X==="user"?"user policy":"project policy"),K=new Set){let Y;try{Y=X1(W,Z)}catch(M){if(M instanceof h)return{...j2(),errors:[M.message],canValidateOverrides:!1};throw M}let B=Q9(Y);if(B.errors.length>0)return{...j2(),errors:B.errors,canValidateOverrides:!1};let q=B.lock;if(!q&&$.rules.length>0)return{...j2(),errors:[`missing lockfile ${Z}; run ${w1}`],canValidateOverrides:!1};let U=q?.rulebooks??[],G=new Map(U.map((M)=>[M.spec,M])),j=[],H=[],_=$.rules.flatMap((M)=>{let L=G.get(M);if(!L)return j.push(`missing lock entry for ${M}; run ${w1}`),[];let D=cq(L,J,Q,W);if(D.errors.length>0||!D.rulebook)return j.push(...D.errors),[];let z=D.rulebook;if(K.has(z.name))return H.push(`duplicate active rulebook name "${z.name}" for ${M}; keeping the first and ignoring this one, so its rules are not active; rename one of them, then run ${w1}`),[];return K.add(z.name),[{rules:z.rules.map((f)=>({...f,name:`${z.name}/${f.name}`})),rulebook:{source:X,spec:L.spec,name:z.name,version:z.version,rules:z.rules.map((f)=>`${z.name}/${f.name}`)}}]}),O=_.flatMap((M)=>M.rules);return{rules:O,rulebooks:_.map((M)=>M.rulebook),entries:U,knownRuleIds:new Set(O.map((M)=>M.name)),errors:j,warnings:H,canValidateOverrides:j.length===0}}function cq($,Z,J,Q){let X=c2($,d2(Z,J)),W;try{W=K0(X1(Q,X))}catch(Y){if(Y instanceof h)return{rulebook:null,errors:[Y.message]};throw Y}if(W===null)return{rulebook:null,errors:[`missing cache entry for ${$.spec}; run ${w1}`]};if(b$(W)!==$.digest)return{rulebook:null,errors:[`cache digest mismatch for ${$.spec}; run ${w1}`]};let K;try{K=JSON.parse(W)}catch{return{rulebook:null,errors:[`invalid cached rulebook for ${$.spec}`]}}try{I$(K)}catch(Y){return{rulebook:null,errors:[`invalid cached rulebook for ${$.spec}: ${Y instanceof Error?Y.message:"invalid rulebook"}`]}}return{rulebook:K,errors:[]}}function dq($,Z){return[...new Set([...$?.transparent_wrappers??[],...Z?.transparent_wrappers??[]])]}function O5($,Z){return $.flatMap((J)=>{let Q=Z[J.name];if(Q==="off")return[];if(Q&&typeof Q==="object")return[{...J,intent:Q.intent??J.intent,reason:Q.reason}];return[J]})}function K9($,Z,J){return Object.keys($).filter((Q)=>!Z.has(Q)).map((Q)=>`unknown override key "${Q}" in ${J}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function iq($,Z,J){return Object.keys($).filter((Q)=>Z.has(Q)).map((Q)=>`project override cannot target user-scoped rule "${Q}" in ${J}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function L5($,Z){return Z.map((J)=>J.startsWith("Unable to access ")?J:`${$}: ${J}`)}function sq($,Z){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[Z],warnings:[],userConfigPath:$.userConfigPath,projectConfigPath:$.projectConfigPath,userLockPath:$.userLockPath,projectLockPath:$.projectLockPath}}function j2(){return{rules:[],rulebooks:[],entries:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}function F5($={}){let Z=M5($),J=t7($),Q={rules:Z.rules,transparentWrappers:Z.transparent_wrappers,safety:J.safety,worktreeMode:J.worktreeMode,destructiveCommandProtectionEnabled:J.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:J.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:J.destructiveCommandAllowPaths,secretProtection:{enabled:J.secretProtection.enabled??!0,disabledRules:[...J.secretProtection.disabledRules??[]],denyPaths:J.secretProtection.denyPaths,allowPaths:J.secretProtection.allowPaths??[]}},X={...Z.userConfig?.overrides??{},...Z.projectConfig?.overrides??{}},W=Object.freeze(Object.fromEntries(Q.rules.map((K)=>{let Y=Z.rulebooks.find((q)=>q.rules.includes(K.name)),B=X[K.name];return[K.name,Object.freeze({id:K.name,...Y?{rulebook:Object.freeze({name:Y.name,version:Y.version}),...oq(Y.spec)?{source:Y.spec}:{}}:{},...B&&typeof B==="object"?{override:Object.freeze({type:"reason",reason:B.reason})}:{}})]})));return tq(Q,rq(Z,J),W)}function rV($){if($.state==="ready")return{state:$.state};return{state:$.state,reason:$.reason}}function rq($,Z){let J=aq(Z);if($.errors.length===0&&$.warnings.length===0&&!J)return;return{diagnostics:[...$.errors,...$.warnings,...Z.errors],reason:eq($.errors.length>0?nq($.errors):void 0,$.warnings.length>0?Y9($.warnings.join("; ")):void 0,J)}}function nq($){return`${Y9($.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function aq($){if($.errors.length===0)return;let Z=$.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${$.errors.join("; ")}. Enforcing ${Z}; the invalid values are not active. Fix the policy file manually`}function oq($){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test($)}function tq($,Z,J=Object.freeze({})){let Q=N5(structuredClone($));if(!Z)return Object.freeze({state:"ready",policy:Q,diagnostics:Object.freeze([]),ruleMetadata:J});return Object.freeze({state:"degraded",policy:Q,diagnostics:Object.freeze([...Z.diagnostics]),reason:Z.reason,ruleMetadata:J})}function N5($){if(typeof $!=="object"||$===null)return $;for(let Z of Object.values($))N5(Z);return Object.freeze($)}function eq(...$){return Y9($.filter((Z)=>!!Z).join("; "))}function Y9($){return/[.!?]$/.test($)?$:`${$}.`}function E($){return $.provenance==="command-substitution"?$.raw:$.text}function f$($,Z){return $==="posix"?Z:g(Z.map((J)=>J.text))}function W3($,Z){return $&&$.provenance!=="unknown"?$.provenance==="literal":!/[$`*?[\]]/.test(Z)}function g($){return $.map((Z)=>({kind:"word",text:Z,raw:Z,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function _2($,Z){o$(Z,$,2);let J=$.toLowerCase(),Q=J.trimStart(),X=Q.startsWith("echo ")||Q.startsWith("rg "),W=[{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}];for(let K of W){if(K.skipForEchoRg&&X)continue;let Y=K.caseSensitive?$:J;if(K.regex)M1(Z,Y);if((K.regex?.test(Y)??!1)||K.scan&&S4(Y,K.scan,Z))return N("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${K.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var $U=/^[A-Za-z_][A-Za-z0-9_]*=/;function R5($,Z,J){let Q=$.words[0];if(!Z||!Q||$.words.length!==1||$.dialect!=="posix")return!1;if(!Q.quoted||Q.provenance!=="literal")return!1;let X=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(Q.text)?.[1];if(!X)return!1;o$(J,Z.source,2);let W={anchored:new RegExp(`^\\$\\{?${X}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${X}(?![A-Za-z0-9_])`)};return D5(Z.nodes,Q,W)}function D5($,Z,J){return $.every((Q)=>{if(Q.kind==="connector")return!0;if(Q.kind==="group"||Q.kind==="function")return D5(Q.body.nodes,Z,J);if(Q.kind==="unknown")return!J.loose.test(Q.source);return ZU(Q,Z,J)})}function ZU($,Z,J){if($.nested.some((X)=>J.loose.test(X.source)))return!1;let Q=$.words.findIndex((X)=>!$U.test(X.text));return $.words.every((X,W)=>X===Z||V5(X.raw,J.anchored,W!==Q))&&$.redirections.every((X)=>(!X.heredoc||X.heredoc.quotedDelimiter||!J.loose.test(X.heredoc.body))&&(!X.target||V5(X.target.raw,J.anchored,!0)))}function V5($,Z,J){let Q=!1,X=!1;for(let W=0;W<$.length;W++){let K=$[W];if(K==="\\"&&!Q){W++;continue}if(!X&&K==="'"){Q=!Q;continue}if(!Q&&K==='"'){X=!X;continue}if(Q||K!=="$")continue;if(!Z.test($.slice(W)))continue;if(!X||!J)return!1}return!0}var z5=Object.freeze({maxDerivedTokens:16384}),I5="Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry.",b5="env -S split-string expansion exceeds the 16,384-token analysis limit and cannot be verified safely. Expand the command explicitly.";class C1 extends Error{constructor(){super("Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry.");this.name="DerivedCommandWorkLimitError"}}class m0 extends Error{constructor(){super("env -S split-string expansion exceeds the 16,384-token analysis limit and cannot be verified safely. Expand the command explicitly.");this.name="EnvSplitStringExpansionError"}}function K3(){return{derivedTokens:0}}function t1($,Z){if(!Number.isSafeInteger($.derivedTokens)||$.derivedTokens<0||$.derivedTokens>z5.maxDerivedTokens||!Number.isSafeInteger(Z)||Z<0||Z>z5.maxDerivedTokens-$.derivedTokens)throw new C1;$.derivedTokens+=Z}import{isAbsolute as JU,resolve as f5}from"node:path";var P5=64;function O2($,Z,J){let Q=JU($)?f5($):Z?f5(Z,$):void 0;if(!Q)return;try{return m(Q,J)}catch{return Q}}function C5($){return!["/dev","/proc","/sys"].some((Z)=>$===Z||$.startsWith(`${Z}/`))}var S=Object.freeze({maxChildAnalyses:1024,maxDerivedTokens:16384,maxDerivedBytes:1048576,maxPlaceholderReplacements:16384}),A5="Parallel command expands beyond CC Safety Net's analysis limits. Reduce the template or explicit argument list and retry.";class B3 extends Error{constructor(){super("Parallel command expands beyond CC Safety Net's analysis limits. Reduce the template or explicit argument list and retry.");this.name="ParallelAnalysisLimitError"}}function E5(){return{childAnalyses:0,derivedTokens:0,derivedBytes:0,placeholderReplacements:0}}function V1($,Z){let J=Z.childAnalyses??0,Q=Z.derivedTokens??0,X=Z.derivedBytes??0,W=Z.placeholderReplacements??0;if(Y3($.childAnalyses,J,S.maxChildAnalyses)||Y3($.derivedTokens,Q,S.maxDerivedTokens)||Y3($.derivedBytes,X,S.maxDerivedBytes)||Y3($.placeholderReplacements,W,S.maxPlaceholderReplacements))throw new B3;$.childAnalyses+=J,$.derivedTokens+=Q,$.derivedBytes+=X,$.placeholderReplacements+=W}function Y3($,Z,J){return!Number.isSafeInteger($)||$<0||$>J||!Number.isSafeInteger(Z)||Z<0||Z>J-$}import{isAbsolute as L9,normalize as xU,parse as lU,posix as e5,resolve as C$,sep as O9}from"node:path";import{isAbsolute as QU,join as T5,normalize as w5,parse as XU,sep as S5}from"node:path";var WU=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],KU=`
51
- `;function L2($,Z){if(e1($,Z))return!0;if(!$.has("TMPDIR"))return!1;return!B9($.get("TMPDIR")??"",Z)}function O0($,Z){if($.has("TMPDIR"))return B9($.get("TMPDIR")??"",Z);let J=q9($,Z);if(J===void 0)return!0;return B9(J,Z)}function q9($,Z){return h5($,Z,"TMPDIR")}function B9($,Z){if(!$)return!1;if(BU($))return!1;return U9($,Z)}function e1($,Z){let J=h5($,Z,"IFS");return J!==void 0&&J!==""&&J!==KU}function U9($,Z){let J=q3($,Z.paths);return J!==null&&u5(Z).some((Q)=>UU(J,Q))}function v5($,Z){let J=q3($,Z.paths);return J!==null&&u5(Z).includes(J)}var y5=new WeakMap;function u5($){let Z=y5.get($);if(Z)return Z;let J=YU($);return y5.set($,J),J}function YU($){let Z=WU.map((Q)=>q3(Q,$.paths)??w5(Q)),J=q3($.tmpdir,$.paths);if(!J)return Z;if(process.platform==="win32")return[...Z,J];if(process.platform==="darwin"&&qU(J))return[...Z,J];return Z}function BU($){return/[\s$`*?[]/.test($)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test($)||/[+@!]\([^)]*\)/.test($)}function h5($,Z,J){return $.has(J)?$.get(J):Z.env.get(J)}function qU($){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test($)}function q3($,Z){try{let J=w5($);if(!QU(J))return J;let Q=XU(J).root,X=J.slice(Q.length).split(/[\\/]+/).filter(Boolean),W=Q;for(let K=0;K<X.length;K++){let Y=T5(W,X[K]??"");if(Z.entryKind(Y)==="missing")return T5(Y,...X.slice(K+1));let B=Z.realpath(Y);if(B===null)return null;W=B}return W}catch{return null}}function UU($,Z){if($===Z)return!0;let J=Z.endsWith(S5)?Z:`${Z}${S5}`;return $.startsWith(J)}import{statSync as SU}from"node:fs";import{isAbsolute as i5,join as yU,relative as s5}from"node:path";import{isAbsolute as g5,parse as GU}from"node:path";var l5=/^[A-Za-z_][A-Za-z0-9_]*=/,HU=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}/,m5=131072,jU=16384;function x1($){if(!l5.test($))return null;let Z=$.indexOf("=");return{name:$.slice(0,Z),value:$.slice(Z+1)}}function U3($){let Z=new Map,J=0;while(J<$.length){let Q=$[J];if(!Q)break;let X=x1(E(Q));if(!X)break;Z.set(X.name,X.value),J++}return{words:$.slice(J),envAssignments:Z}}function p5($){let Z=$.toLowerCase();return $.includes("=")||Z==="sudo"||Z==="env"||Z==="command"||Z==="builtin"}function p0($,Z,J,Q){if(!p5(P$($)))return{words:$,envAssignments:new Map,cwd:J,rewritten:!1};let X=new Set($),W=$,K=new Map,Y=new Map(Q??[]),B=J;for(let U=0;U<Y$;U++){let G=x5(W),j=U3(W);for(let[_,O]of j.envAssignments)K.set(_,O),Y.set(_,O);if(W=j.words,W.length===0)break;while(W.length>0&&P$(W).includes("=")&&!_U(W)){let _=OU(P$(W),Y,Z.env)??P4(P$(W),Z.env,Y);if(_)K.set(_.name,_.value),Y.set(_.name,_.value);W=W.slice(1)}if(W.length===0)break;let H=P$(W).toLowerCase();if(H!=="sudo"&&H!=="env"&&H!=="command"&&H!=="builtin")break;if(H==="sudo"){let _=MU(W,Z.paths,B);if(W=_.words,_.cwd!==void 0)B=_.cwd}if(H==="env"){let _=VU(W,B,Y,Z);if(_.unverifiableEnvSplit)return{words:W,envAssignments:K,cwd:B,unverifiableEnvSplit:!0,rewritten:k5(W,X)};if(W=_.words,_.cwd!==void 0)B=_.cwd;for(let[O,M]of _.envAssignments)K.set(O,M),Y.set(O,M)}if(H==="command")W=fU(W);if(H==="builtin")W=W.slice(k1(W,1)==="--"?2:1);if(x5(W)===G)break}let q=U3(W);for(let[U,G]of q.envAssignments)K.set(U,G),Y.set(U,G);return{words:q.words,envAssignments:K,cwd:B,rewritten:k5(q.words,X)}}function k5($,Z){return $.some((J)=>!Z.has(J))}function x5($){return $.map(E).join(" ")}function P$($){let Z=$[0];return Z?E(Z):""}function k1($,Z){let J=$[Z];return J?E(J):void 0}function _U($){return l5.test(P$($))}function OU($,Z,J){if(!$.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${Z.get("TMPDIR")??J.get("TMPDIR")??""}${$.slice(8)}`}}var LU=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function MU($,Z,J){let Q=1,X=J;while(Q<$.length){let W=k1($,Q);if(!W)break;if(W==="--")return{words:$.slice(Q+1),cwd:X};if(!W.startsWith("-"))break;if(W==="-D"||W==="--chdir"){let K=k1($,Q+1);X=K?M2(X,K,Z):null,Q+=2;continue}if(W.startsWith("--chdir=")){X=M2(X,W.slice(8),Z),Q++;continue}if(W.startsWith("-D")&&W.length>2){X=M2(X,W.slice(2),Z),Q++;continue}if(W==="-i"||W==="--login"){X=null,Q++;continue}if(LU.has(W)){Q+=2;continue}Q++}return{words:$.slice(Q),cwd:X}}var FU=new Set(["-i","-0","--null"]),NU=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]);function VU($,Z,J,Q){let X=new Map,W=Z,K=$,Y=new Set,B=1;while(B<K.length){let q=k1(K,B);if(!q)break;if(q==="--")return{words:K.slice(B+1),envAssignments:X,cwd:W};if(q==="-i"||q==="--ignore-environment"||q==="-"){X.clear();for(let G of J.keys())X.set(G,"");X.set("TMPDIR",""),B++;continue}if(FU.has(q)){B++;continue}if(q==="-u"||q==="--unset"){let G=k1(K,B+1);if(G!==void 0)Y.add(G),X.set(G,"");B+=2;continue}if(q.startsWith("-u")&&q.length>2&&!q.startsWith("-u=")){let G=q.slice(2);Y.add(G),X.set(G,""),B++;continue}if(q.startsWith("--unset=")){let G=q.slice(8);Y.add(G),X.set(G,""),B++;continue}let U=q==="-S"||q==="--split-string"?{value:k1(K,B+1),consumed:2}:q.startsWith("-S")&&q.length>2?{value:q.slice(2),consumed:1}:q.startsWith("--split-string=")?{value:q.slice(15),consumed:1}:null;if(U){let G=RU(K,B,U.value,U.consumed,J,Y,W,Q.env);if(G.done)return G.result;K=G.expanded,W=G.currentCwd,B=G.nextIndex;continue}if(NU.has(q)){if(q==="-C"||q==="--chdir"){let G=k1(K,B+1);W=G?M2(W,G,Q.paths):null}B+=2;continue}if(q.startsWith("-u=")){B++;continue}if(q.startsWith("-C")&&q.length>2||q.startsWith("--chdir=")){let G=q.startsWith("--chdir=")?q.slice(8):q.startsWith("-C=")?q.slice(3):q.slice(2);W=M2(W,G,Q.paths),B++;continue}if(q.startsWith("-P")){B++;continue}if(q.startsWith("-")){B++;continue}if(!x1(q))break;while(B<K.length){let G=x1(k1(K,B)??"");if(!G)break;X.set(G.name,G.value),B++}if(k1(K,B)==="--")B++;return{words:K.slice(B),envAssignments:X,cwd:W}}return{words:K.slice(B),envAssignments:X,cwd:W}}function RU($,Z,J,Q,X,W,K,Y){let B=J!==void 0?DU(J,X,W,Y):{tokens:null,unverifiableEnvSplit:!1};if(B.unverifiableEnvSplit)return{done:!0,result:{words:$,envAssignments:new Map,cwd:K,unverifiableEnvSplit:!0}};if(!B.tokens)return{done:!1,expanded:$,currentCwd:null,nextIndex:Z+Q};return{done:!1,expanded:[...$.slice(0,Z),...g(B.tokens),...$.slice(Z+Q)],currentCwd:K,nextIndex:Z}}function DU($,Z,J,Q){if($.length>m5)return{tokens:null,unverifiableEnvSplit:!0};let X=zU($,(W)=>{if(J.has(W))return"";if(Z.has(W))return Z.get(W)??"";return Q.get(W)??""});return{tokens:X.tokens,unverifiableEnvSplit:X.limited}}function zU($,Z){let J=[],Q=[],X=0,W=!1,K=!1,Y=!1,B=!1,q=(G)=>{if(X+G.length>m5)return B=!0,!1;return Q.push(G),X+=G.length,W=!0,!0},U=()=>{if(!W)return!0;if(J.length>=jU)return B=!0,!1;return J.push(Q.join("")),Q=[],W=!1,!0};for(let G=0;G<$.length;G++){let j=$[G]??"";if(j==="'"&&!Y){K=!K,W=!0;continue}if(j==='"'&&!K){Y=!Y,W=!0;continue}if(!K&&!Y&&bU(j)){if(!U())return{tokens:null,limited:B};continue}if(!K&&!Y&&j==="#"&&!W)break;if(j==="$"&&!K){let O=$.slice(G).match(HU);if(!O?.[1]||!q(Z(O[1])))return{tokens:null,limited:B};G+=O[0].length-1;continue}if(j!=="\\"){if(!q(j))return{tokens:null,limited:B};continue}let H=$[G+1];if(H===void 0)return{tokens:null,limited:B};if(K&&H!=="'"&&H!=="\\"){if(!q("\\"))return{tokens:null,limited:B};continue}if(H==="c"){if(Y)return{tokens:null,limited:B};break}if(H==="_"&&!K&&!Y){if(!U())return{tokens:null,limited:B};G++;continue}let _=IU(H);if(_===void 0||!q(_))return{tokens:null,limited:B};G++}if(K||Y||!U())return{tokens:null,limited:B};return{tokens:J,limited:!1}}function IU($){if($==="f")return"\f";if($==="n")return`
52
- `;if($==="r")return"\r";if($==="t")return"\t";if($==="v")return"\v";if($==="_")return" ";if($==="#"||$==="$"||$==='"'||$==="'")return $;if($==="\\")return"\\";return}function bU($){return $===" "||$==="\t"||$===`
53
- `||$==="\r"||$==="\f"||$==="\v"}function M2($,Z,J){if(Z==="")return null;if(!$&&!g5(Z))return null;let Q=g5(Z)?GU(Z).root:J.realpath($??"/");if(Q===null)return null;try{return b0(Q,Z,J)}catch{return null}}function fU($){if(k1($,1)==="-v")return[...g(["type"]),...$.slice(2)];let Z=1;while(Z<$.length){let J=k1($,Z);if(!J)break;if(J==="-p"||J==="-v"||J==="-V"){Z++;continue}if(J==="--")return $.slice(Z+1);if(J.startsWith("-")&&!J.startsWith("--")&&J.length>1){if(!/^[pvV]+$/.test(J.slice(1)))break;Z++;continue}break}return $.slice(Z)}function A1($,Z,J){return G9($,Z,J).tokens}function G9($,Z,J,Q){if(!p5($[0]??""))return{tokens:[...$],envAssignments:new Map,cwd:J};let X=p0(g($),Z,J,Q);return{tokens:X.words.map(E),envAssignments:X.envAssignments,cwd:X.cwd,unverifiableEnvSplit:X.unverifiableEnvSplit}}import{isAbsolute as PU,normalize as CU,resolve as c5}from"node:path";var AU=new Set(["-S","--suffix"]);function G3($,Z,J,Q){if($.status==="structural-limit")throw new I0;if($.status!=="complete")return Q.findMalformedTarget($.source);let X={cwd:Z,variables:new Map},W=[];for(let K of $.entries){if(K.kind==="operator"){if(!K.boundary)continue;let Y=Q.findSegmentTarget(W,X);if(Y)return Y;X=EU(W,X,J,Q.normalizeCwd),W=[];continue}if(K.kind==="redirection"){if(K.role==="file-write"&&K.target&&Q.isRedirectionTarget(R1(K.target,X.variables),X))return K.target;continue}W.push(K.text)}return Q.findSegmentTarget(W,X)}function R1($,Z){return $.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(J,Q,X,W)=>{let K=Z.get(Q);if(K===void 0)return J;let Y=X.startsWith(":")?K!=="":!0;if(X.endsWith("-"))return Y?K:R1(W,Z);return Y?R1(W,Z):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(J,Q)=>Z.get(Q)??J).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(J,Q)=>Z.get(Q)??J)}function F2($){return $.length>0&&$.every((Z)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(Z))}function W1($,Z,J){let Q=J.environment.home,X=t2($.trim(),J.environment).replace(/\\/g,"/");if(!X)return"";let W=X==="~"?Q:X.startsWith("~/")?c5(Q,X.slice(2)):X;return m(CU(PU(W)?W:c5(Z,W)),J.environment.paths,J).replace(/\\/g,"/")}function H3($){let Z=[],J=null,Q=!1;for(let X=0;X<$.length;X++){let W=$[X];if(W===void 0)break;if(!Q&&W==="--"){Q=!0;continue}if(!Q&&(W==="-t"||W==="--target-directory")){J=$[++X]??null;continue}if(!Q&&W.startsWith("--target-directory=")){J=W.slice(19);continue}if(!Q&&W.startsWith("-t")&&W.length>2){J=W.slice(2);continue}if(!Q&&AU.has(W)){X++;continue}if(!Q&&(W.startsWith("--suffix=")||W.startsWith("--backup=")))continue;if(!Q&&W.startsWith("-"))continue;Z.push(W)}return J?{sources:Z,destination:J}:{sources:Z.slice(0,-1),destination:Z.at(-1)??null}}function EU($,Z,J,Q){let X=F2($)?new Map([...Z.variables,...TU($,Z.variables)]):Z.variables,W=A1([...$],J.environment),K=u(W[0]??"").toLowerCase()==="cd"?W[1]:void 0;return{cwd:!K||K==="-"?Z.cwd:Q(R1(K,X),Z.cwd,J),variables:X}}function TU($,Z){return $.flatMap((J)=>{let Q=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(J),X=Q?.[2]?.startsWith("=")?Q[2].slice(1):void 0;return Q?.[1]!==void 0&&X!==void 0?[[Q[1],R1(X,Z)]]:[]})}var E1="Git metadata and hooks are protected. Ask the user before modifying them.";function r5($,Z=j9($.invocation.context.executionCwd)){let J=y0(G0()),Q=$.invocation.context.executionCwd;if(!Z)return null;if($.invocation.route.kind==="patch"||$.invocation.route.kind==="path"||$.invocation.route.kind==="unknown"){if(X4($.invocation.toolName))return null;let K=$.paths.find((Y)=>hU(Y,Q,Z,J));return K?{target:K}:null}if($.invocation.route.kind!=="command")return null;let X=L1($,"input-candidate");if(!X)return null;let W=G3(X.shell,Q,J,{findSegmentTarget:(K,Y)=>kU(K,Y,Z,J),isRedirectionTarget:(K,Y)=>gU(K,Y.cwd,Z,J),findMalformedTarget:()=>null,normalizeCwd:W1});return W?{target:W}:null}function j9($,Z=y0(G0())){if(typeof $!=="string"||!$)return null;let J=Q2(W1($,$,Z));if(!J)return null;try{let Q=W1(J,$,Z),X=SU(J),W=X.isFile()?Q:null,K=X.isFile()?m6(J):null,Y=(X.isDirectory()?[Q]:[K?.gitDir,K?.commonDir]).flatMap((q)=>q?[$0(W1(q,$,Z))]:[]),B=[...new Set(X.isDirectory()?[$0(J.replace(/\\/g,"/")),...Y]:Y)];return Object.freeze({entry:$0(Q),markerFile:W?$0(W):null,directories:Object.freeze(B),hooksDirectories:Object.freeze([...new Set(B.flatMap((q)=>{let U=$0(yU(q,"hooks"));return[U,$0(W1(U,$,Z))]}))])})}catch{return null}}function c0($,Z,J,Q,X,W=!1){if(!J)return!1;let K=$0(W1($,Z,X)),Y=K.replace(/(\/\.?\*+)+$/,"");if(Y!==K&&Y!==""){if(H9(Y,J))return!0;let B=W||K.slice(Y.length).includes("/."),q=(U)=>B?j3(U,Y):wU(U,Y);if(J.markerFile&&q(J.markerFile))return!0;return Q&&d5(J).some(q)}if(H9(K,J))return!0;return Q&&d5(J).some((B)=>j3(B,K))}function wU($,Z){let J=s5(Z,$);if(J===""||J.startsWith("..")||i5(J))return!1;return!J.split(/[\\/]/)[0]?.startsWith(".")}function vU($,Z,J,Q){return c0($,Z,J,!0,Q)}function uU($,Z,J,Q){if(!J)return!1;return H9($0(W1($,Z,Q)),J)}function hU($,Z,J,Q){if(!J)return!1;return n5($,Z,J,Q,J.entry)}function gU($,Z,J,Q){if(!J)return!1;return n5($,Z,J,Q,J.markerFile)}function n5($,Z,J,Q,X){let W=$0(W1($,Z,Q));return W===X||o5(W,J)}function a5($,Z,J,Q){if(!J)return!1;return J.hooksDirectories.some((X)=>$.some((W)=>j3(X,$0(W1(W,Z,Q)))))}function H9($,Z){return $===Z.entry||Z.directories.includes($)||o5($,Z)}function o5($,Z){return Z.hooksDirectories.some((J)=>j3($,J))}function d5($){return[$.entry,...$.directories,...$.hooksDirectories]}function j3($,Z){let J=s5(Z,$);return J===""||!/^\.\.(?:[\\/]|$)/.test(J)&&!i5(J)}function $0($){return process.platform==="win32"?$.toLowerCase():$}function kU($,Z,J,Q){if(F2($))return null;let X=A1([...$],Q.environment);if(u(X[0]??"").toLowerCase()!=="mv")return null;let W=H3(X.slice(1)),K=W.sources.find((Y)=>vU(R1(Y,Z.variables),Z.cwd,J,Q));if(K)return K;return W.destination&&uU(R1(W.destination,Z.variables),Z.cwd,J,Q)?W.destination:null}var mU=process.platform==="win32",t5=64,pU=16384;function N2($){let Z=S8($,t5,t5,pU);return{expandedTargets:Z&&"words"in Z?Z.words:void 0,unsafeBraceExpansion:Z!==void 0&&"limited"in Z,targetIsLiteral:Z===void 0&&$.provenance==="literal"&&($.quoted||$.raw!==$.text),tmpdirWordSplittingProtected:cU($)}}function cU($){let Z=$.parts.filter((J)=>J.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(J.raw));return Z.length>0&&Z.every((J)=>dU($.raw,J.span.start-$.span.start))}function dU($,Z){let J=null,Q=!1;for(let X=0;X<Z;X++){let W=$[X];if(Q){Q=!1;continue}if(W==="\\"&&J!=="'"){Q=!0;continue}if(J===W){J=null;continue}if(J===null&&(W==="'"||W==='"'))J=W}return J==='"'}function d0($){let Z=$.environment.home,J=$.environment.paths,Q=y0($.environment);return{anchoredCwd:$.originalCwd??$.cwd??null,resolvedCwd:$.cwd??null,strict:$.strict??!1,paranoid:$.paranoid??!1,trustTmpdirVar:$.allowTmpdirVar??!0,posixShell:$.posixShell??!1,tmpdirWordSplittingUnsafe:$.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:$.trustedTmpdirValue??$.allowTmpdirVar??!0,environment:$.environment,allowRoots:aU($.allowPaths,Z,J,Q),protectedGitMetadata:$.protectedGitMetadata,pathCanonicalizationContext:Q}}function l1($,Z,J={}){let Q=J.targetIsLiteral??!1;if(!Q&&Z.tmpdirWordSplittingUnsafe&&!J.tmpdirWordSplittingProtected&&tU($))return{kind:"outside_anchored_cwd"};let X=!Q&&JJ($,Z.posixShell);if(k0($))return{kind:"outside_anchored_cwd"};if(M9($,Q))return{kind:"root_or_home_target"};if(iU($,Z,Q))return{kind:"root_or_home_target"};if(Z.resolvedCwd&&c0($,Z.resolvedCwd,Z.protectedGitMetadata,!0,Z.pathCanonicalizationContext,!Z.posixShell))return{kind:"git_metadata_target"};if(sU($,Z.trustTmpdirVar,Z.posixShell,X,Q,J.tmpdirWordSplittingProtected??!1,Z.trustedTmpdirValue,Z.environment))return{kind:"temp_target"};if(X)return{kind:"dynamic_target"};if(oU($,Z,Q))return{kind:"temp_target"};let W=Z.anchoredCwd;if(W){if(!J.skipHomeCwd&&JG(W,Z.environment.home,Z.environment.paths,Z.pathCanonicalizationContext))return{kind:"home_cwd_target"};if(!J.skipCwdSelf&&QG($,Z.resolvedCwd??W,Z.environment.paths,Z.pathCanonicalizationContext))return{kind:"cwd_self_target"};if(XG($,W,Z.resolvedCwd??W,X,Q,Z.environment.paths,Z.pathCanonicalizationContext))return{kind:"within_anchored_cwd"}}return{kind:"outside_anchored_cwd"}}function $J($,Z,J={}){let{containmentTarget:Q,...X}=J;if(l1($,Z,X).kind!=="temp_target")return!1;let W=$.trim();if(nU(W))return!1;if(v5(W,Z.environment))return!1;return![Z.anchoredCwd,Z.resolvedCwd].some((K)=>WG(Q??W,K,Z.environment.paths,Z.pathCanonicalizationContext))}function M9($,Z=!1){let J=$.trim(),Q=e5.normalize(J),X=J.replace(/\\/g,"/"),W=Q==="/"?Q:Q.replace(/\/+$/,"");if(W==="/"||W.startsWith("/")&&W.slice(1).split("/").every((K)=>/^\*+$/.test(K)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(X)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(X))return!0;if(!Z&&(Q==="~"||Q==="~/"||Q==="~/*"))return!0;if(!Z&&(Q==="$HOME"||Q==="$HOME/"||Q==="$HOME/*"))return!0;if(!Z&&(Q==="${HOME}"||Q==="${HOME}/"||Q==="${HOME}/*"))return!0;return!1}function iU($,Z,J){let Q=$.trim(),X=J?Q:Q==="*"?".":Q.endsWith("/*")?Q.slice(0,-2):Q;if(!X)return!1;try{let W=L9(X)?X:Z.resolvedCwd?C$(Z.resolvedCwd,X):null;if(!W)return!1;let K=j1(m(W,Z.environment.paths,Z.pathCanonicalizationContext));if(K===lU(K).root)return!0;return K===j1(m(Z.environment.home,Z.environment.paths,Z.pathCanonicalizationContext))}catch{return!1}}function j1($){let Z=xU($);if(mU){if(Z=Z.replace(/\//g,"\\").toLowerCase(),Z.length>3&&Z.endsWith("\\"))Z=Z.slice(0,-1);return Z}if(Z.length>1&&Z.endsWith("/"))Z=Z.slice(0,-1);return Z}function sU($,Z,J,Q,X,W,K,Y){let B=$.trim();if(ZJ(B))return!1;if(!Q&&U9(B,Y))return!0;return(Z||W&&K)&&J&&!X&&rU(B,J)}function rU($,Z){return["$TMPDIR","${TMPDIR}"].some((J)=>{if($===J)return!0;if(!$.startsWith(`${J}/`))return!1;return!JJ($.slice(J.length+1),Z)})}function nU($){let Z=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec($);if(!Z)return!1;return e5.normalize(`/${Z[1]??""}`)==="/"}function ZJ($){return $.split(/[\\/]+/).includes("..")}function aU($,Z,J,Q){if(!$?.length)return[];return $.flatMap((X)=>{let W=B2(X.trim(),Z);if(!L9(W))return[];try{let K=m(W,J,Q);if(q2(K,m(Z,J,Q)))return[];return[j1(K)]}catch{return[]}})}function oU($,Z,J){if(Z.allowRoots.length===0)return!1;let Q=$.trim();if(ZJ(Q))return!1;let X=J?Q:B2(Q,Z.environment.home),W=Z.resolvedCwd??Z.anchoredCwd,K=L9(X)?X:W?C$(W,X):null;if(!K)return!1;try{let Y=j1(m(K,Z.environment.paths,Z.pathCanonicalizationContext));return Z.allowRoots.some((B)=>Y===B||Y.startsWith(B.endsWith(O9)?B:`${B}${O9}`))}catch{return!1}}function tU($){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test($)}function JJ($,Z=!1){return $.includes("$")||$.includes("`")||eU($)||Z&&$G($)}function eU($){let Z=!1;for(let J of $){if(Z){Z=!1;continue}if(J==="\\"){Z=!0;continue}if(J==="*"||J==="?"||J==="[")return!0}return!1}function $G($){let Z=!1;for(let J=0;J<$.length;J++){let Q=$[J];if(Z){Z=!1;continue}if(Q==="\\"){Z=!0;continue}if(Q==="{"&&ZG($,J)||(Q==="+"||Q==="@"||Q==="!")&&$[J+1]==="(")return!0}return!1}function ZG($,Z){let J=$.indexOf("}",Z+1);if(J===-1)return!1;let Q=$.slice(Z+1,J);return Q.includes(",")||Q.includes("..")}function JG($,Z,J,Q){try{return j1(m($,J,Q))===j1(m(Z,J,Q))}catch{try{return j1($)===j1(Z)}catch{return!1}}}function QG($,Z,J,Q){if($==="."||$==="./"||$===".\\")return!0;try{return j1(m(C$(Z,$),J,Q))===j1(m(Z,J,Q))}catch{try{return j1(C$(Z,$))===j1(Z)}catch{return!1}}}function XG($,Z,J,Q,X,W,K){let Y=J??Z;if(!X&&($.startsWith("~")||$.startsWith("$HOME")||$.startsWith("${HOME}")))return!1;if(Q)return!1;if($.startsWith("/")||/^[A-Za-z]:[\\/]/.test($))try{return _9($,Z,W,K)}catch{return!1}if($.startsWith("./")||$.startsWith(".\\")||!$.includes("/")&&!$.includes("\\"))try{return _9(C$(Y,$),Z,W,K)}catch{return!1}if($.startsWith("../"))return!1;try{return _9(C$(Y,$),Z,W,K)}catch{return!1}}function _9($,Z,J,Q){try{return QJ(m($,J,Q),m(Z,J,Q))}catch{return!1}}function WG($,Z,J,Q){if(!Z)return!1;try{return QJ(m(Z,J,Q),m($,J,Q))}catch{return!0}}function QJ($,Z){let J=j1($),Q=j1(Z);return J.startsWith(`${Q}${O9}`)||J===Q}var KG=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),XJ="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",YG="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.",WJ="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",KJ="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",BG="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",qG="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.";function YJ($,Z,J,Q=d0({...J,allowPaths:J.policy?.destructiveCommandAllowPaths})){return UG($.words.map((X)=>({kind:"word",text:X.text,dynamic:X.provenance!=="literal"})),Z,Q,J.policy)}function UG($,Z,J,Q){let X=$.filter((B)=>B.kind==="word"),W=HG(X),K=X[W];if(!K||!KG.has(RG(K.text)))return null;let Y=GG(X.slice(W+1));if(Y.whatIfProtected)return null;if(o(Q,"powershell.remove-item-pipeline-dynamic-target",J.strict)&&Z&&(Y.targets.length===0||Y.recursive))return N("powershell.remove-item-pipeline-dynamic-target",qG);for(let B of Y.targets)if(!k0(B.text)&&M9(N9(B.text)))return N(Y.recursive&&Y.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",KJ);for(let B of Y.targets)if(J.resolvedCwd&&c0(N9(B.text),J.resolvedCwd,J.protectedGitMetadata,Y.recursive,J.pathCanonicalizationContext,!0))return N("powershell.remove-item-git-metadata",E1);if(!Y.recursive||!Y.force)return null;if(o(Q,"powershell.remove-item-recursive-force-dynamic-target",J.strict)&&(Y.hasDynamicTarget||Y.targets.length===0))return N("powershell.remove-item-recursive-force-dynamic-target",WJ);for(let B of Y.targets){let q=DG(l1(N9(B.text),J),J,Q);if(q)return q}return null}function GG($){let Z=[],J=!1,Q=!1,X=!1,W=!1,K=!1;for(let Y=0;Y<$.length;Y++){let B=$[Y];if(!B||B.kind!=="word")continue;if(jG(B))continue;if(K){Z.push(F9(B)),W=W||B.dynamic;continue}if(B.text==="--"){K=!0;continue}let q=OG(B.text);if(!q){Z.push(F9(B)),W=W||B.dynamic;continue}if(LG(q.name)){let U=q.value?_G(q.value,B):$[++Y];if(U?.kind==="word")Z.push(F9(U)),W=W||U.dynamic;else W=!0;continue}if(MG(q.name)){J=!0;continue}if(FG(q.name)){Q=!0;continue}if(NG(q.name))X=VG(q.value)}return{targets:Z,recursive:J,force:Q,whatIfProtected:X,hasDynamicTarget:W}}function HG($){let Z=$[0];if(Z?.kind==="word"&&Z.text==="&"||Z?.text===".")return $.length>1?1:0;return 0}function F9($){return{text:$.kind==="word"?$.text:"",dynamic:$.kind==="word"&&$.dynamic}}function jG($){return $.kind==="word"&&$.text===","}function N9($){let Z=$.replace(/\\/g,"/"),J=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(Z);return J?`$HOME${Z.slice(J[0].length)}`:Z}function _G($,Z){return{kind:"word",text:$,dynamic:Z.kind==="word"&&(Z.dynamic||$.includes("$"))}}function OG($){if(!$.startsWith("-")||$==="-")return null;let Z=$.slice(1),J=Z.indexOf(":");if(J===-1)return{name:Z.toLowerCase()};return{name:Z.slice(0,J).toLowerCase(),value:Z.slice(J+1)}}function LG($){return"path".startsWith($)||"literalpath".startsWith($)}function MG($){return"recurse".startsWith($)}function FG($){return $.length>=2&&"force".startsWith($)}function NG($){return $==="wi"||"whatif".startsWith($)}function VG($){if($===void 0||$==="")return!0;let Z=$.toLowerCase();return Z==="$true"||Z==="true"}function RG($){return $.toLowerCase()}function DG($,Z,J){switch($.kind){case"root_or_home_target":return N("powershell.remove-item-recursive-force-root-or-home",KJ);case"git_metadata_target":return N("powershell.remove-item-git-metadata",E1);case"temp_target":return null;case"dynamic_target":if(!o(J,"powershell.remove-item-recursive-force-dynamic-target",Z.strict))return null;return N("powershell.remove-item-recursive-force-dynamic-target",WJ);case"home_cwd_target":return N("powershell.remove-item-recursive-force-home-cwd",BG);case"cwd_self_target":return N("powershell.remove-item-recursive-force-cwd-self",XJ);case"within_anchored_cwd":if(!o(J,"powershell.remove-item-recursive-force-paranoid",Z.paranoid))return null;return N("powershell.remove-item-recursive-force-paranoid",YG);case"outside_anchored_cwd":return N("powershell.remove-item-recursive-force-outside-cwd",XJ)}}import{normalize as f3}from"node:path";function m1($,Z){let J=Z.policy??{rules:[],transparentWrappers:[]};return V9([...$],Z.environment,Z.cwd,Z.cwd,new Map,new Map(Z.envAssignments??[]),J,{iterations:0},!1)}function*V9($,Z,J,Q,X,W,K,Y,B){let q=G9($,Z,J,W);if(q.unverifiableEnvSplit)throw new m0;for(let[H,_]of q.envAssignments)W.set(H,_),X.set(H,_);let{tokens:U,cwd:G}=q;if(l0(U[0]??""))throw new C1;let j=x4(U,K);if(j){for(let H of[j.childIndex,...j.alternativeChildIndices])BJ(Y),yield*V9(H===j.childIndex?j.tokens:[...U.slice(H)],Z,G,Q,new Map(X),new Map(W),K,Y,!0);return}if(IG(U)){BJ(Y),yield*V9([...U.slice(1)],Z,G,Q,X,W,K,Y,B);return}yield zG(U,G,Q,X,W,B)}function zG($,Z,J,Q,X,W){return{tokens:$,cwd:Z===null?void 0:Z??J,wrapperCwd:Z,wrapperEnvAssignments:Q,envAssignments:X,head:u($[0]??"").toLowerCase(),wrappedByTransparent:W}}function BJ($){if($.iterations>=Y$)throw new C1;$.iterations++}function IG($){return u($[0]??"").toLowerCase()==="busybox"&&$.length>1}function R9($,Z){let J=[],Q=Z;while(Q<$.length){let X=$[Q];if(X===void 0||X===":::")break;J.push(X),Q++}return{markerIndex:Q<$.length&&$[Q]===":::"?Q:-1,templateTokens:J}}function p1($){let Z=!1,J=!1;for(let Q of $){if(Q==="--")break;if(Q==="-r"||Q==="-R"||D9(Q,"recursive"))Z=!0;else if(Q==="-f"||D9(Q,"force"))J=!0;else if(Q.startsWith("-")&&!Q.startsWith("--")){if(Q.includes("r")||Q.includes("R"))Z=!0;if(Q.includes("f"))J=!0}}return Z&&J}function qJ($){let Z=$.indexOf("--");return $.slice(1,Z===-1?void 0:Z).some((J)=>D9(J,"recursive")||/^-[A-Za-z]+$/.test(J)&&/[rR]/.test(J.slice(1)))}function D9($,Z){return $.length>2&&$.startsWith("--")&&Z.startsWith($.slice(2))}var bG="find -delete permanently removes files. Use -print first to preview.",fG="find -exec rm -rf is dangerous. Use explicit file list instead.",PG=new Set(["-exec","-execdir","-ok","-okdir"]),CG=new Map([...["-Bmin","-Bnewer","-Btime","-amin","-anewer","-atime","-cmin","-cnewer","-context","-ctime","-f","-flags","-fprint","-fprint0","-fls","-fstype","-gid","-group","-ilname","-iname","-inum","-ipath","-iwholename","-iregex","-links","-lname","-maxdepth","-mindepth","-mmin","-mnewer","-mtime","-name","-newer","-newerXY","-newermt","-path","-perm","-printf","-regex","-samefile","-size","-type","-uid","-used","-user","-wholename","-xattrname","-xtype"].map(($)=>[$,1]),["-fprintf",2]]);function _3($,Z){let J=$.map(E),Q=AG($,J,Z);if(Q)return Q;if(L3(J,1)&&!TG($,J,Z)){let K=T(N("find.delete",bG),Z.policy);if(K)return K}let X=Z.derivedCommandWorkBudget??K3(),W=0;while(W<J.length){let K=J[W],Y=f0(K??"");if(Y>0){W+=Y+1;continue}if(!L0(K)){W++;continue}t1(X,J.length-W-1);let B=V2(J,W);W=B.nextIndex;let q=yG(B.tokens,Z.environment);if(q){let H=T(q,Z.policy);if(H)return H}let U=K==="-execdir"||K==="-okdir",G=Z.analyzeTokens?Z.analyzeTokens(B.tokens,U?null:Z.cwd):Z.analyzeNested?Z.analyzeNested(B.tokens.join(" "),{effectiveCwd:U?void 0:Z.cwd,envAssignments:Z.envAssignments}):null,j=G?.id.startsWith("custom.")?G:T(G,Z.policy);if(j)return j}return null}function AG($,Z,J){if(!L3(Z,1)&&!z9(Z,J.environment))return null;let X=O3($)??g(["."]),W=d0({...J,allowPaths:J.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let K of X){let Y=N2(K);for(let B of Y.expandedTargets??[E(K)]){let q=l1(B,W,{targetIsLiteral:Y.expandedTargets!==void 0||Y.targetIsLiteral,tmpdirWordSplittingProtected:Y.tmpdirWordSplittingProtected});if(q.kind==="root_or_home_target")return N("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(q.kind==="git_metadata_target")return N("find.delete-git-metadata",E1)}}if(EG(Z)&&W.resolvedCwd&&a5(X.map(E),W.resolvedCwd,W.protectedGitMetadata,W.pathCanonicalizationContext))return N("find.delete-git-metadata",E1);return null}function z9($,Z){let J=0;while(J<$.length){if(!L0($[J])){J++;continue}let Q=V2($,J),X=A1([...Q.tokens],Z),W=u(X[0]??"").toLowerCase();if((W==="rm"||W==="rmdir")&&X.some((K)=>K.includes("{}")))return!0;J=Q.nextIndex}return!1}function EG($){return $.some((Z,J)=>{if(!["-name","-iname"].includes(Z))return!1;return $[J+1]?.toLowerCase()==="hooks"})}function TG($,Z,J){if(Z.includes("-L")||Z.includes("-f")||Z.includes("-follow"))return!1;let Q=O3($);if(!Q)return!1;let X=J.envAssignments??new Map,W=q9(X,J.environment),K=J.trustedTmpdirValue??O0(X,J.environment),Y=J.allowTmpdirVar??!L2(X,J.environment),B=d0({environment:J.environment,protectedGitMetadata:J.protectedGitMetadata,cwd:J.cwd,originalCwd:J.originalCwd,strict:J.strict,allowTmpdirVar:Y&&K&&Boolean(W),allowPaths:J.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:J.tmpdirWordSplittingUnsafe??e1(X,J.environment),trustedTmpdirValue:K});return Q.every((q)=>{let U=N2(q);if(U.unsafeBraceExpansion)return!1;return(U.expandedTargets??[E(q)]).every((G)=>$J(G,B,{containmentTarget:SG(G,W),targetIsLiteral:U.expandedTargets!==void 0||U.targetIsLiteral,tmpdirWordSplittingProtected:U.tmpdirWordSplittingProtected}))})}function SG($,Z){if(!Z)return $;return $.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>Z)}function O3($){let Z=(X)=>{let W=$[X];return W?E(W):void 0},J=1;while(Z(J)==="-H"||Z(J)==="-P")J++;if(Z(J)==="--")J++;let Q=[];while(J<$.length){let X=Z(J),W=$[J];if(!X||!W||X.startsWith("-")||["!","(",")"].includes(X))break;Q.push(W),J++}return Q.length>0?Q:null}function yG($,Z){let J=A1([...$],Z);if(J.length===0)return null;let Q=u(J[0]??"");if(Q==="busybox"&&J.length>1)J=J.slice(1),Q=u(J[0]??"");if(Q==="rm"&&p1(J))return N("find.exec-rm-recursive-force",fG);return null}function V2($,Z){let J=Z+1;while(J<$.length&&$[J]!==";"&&!($[J]==="+"&&$[J-1]==="{}"))J++;return{tokens:$.slice(Z+1,J),nextIndex:Math.min(J+1,$.length)}}function L3($,Z){let J=Z;while(J<$.length){let Q=$[J];if(!Q){J++;continue}if(L0(Q)){J=V2($,J).nextIndex;continue}let X=f0(Q);if(X>0){J+=X+1;continue}if(Q==="-delete")return!0;J++}return!1}function f0($){return CG.get($)??(/^-newer[A-Za-z]{2}$/.test($)?1:0)}function L0($){return $!==void 0&&PG.has($)}function*I9($){for(let Z of $.nodes)yield*vG(Z)}function wG($){return Object.freeze([...I9($)])}function UD($){return Object.freeze(wG($).map((Z)=>Object.freeze(Z.words.map((J)=>J.text))))}function R2($){let Z=v1($,"posix");if(Z.status!=="complete"||Z.nodes.length!==1)return null;let J=Z.nodes[0];if(J?.kind!=="command")return null;if(J.redirections.length>0||J.nested.length>0)return null;if(J.words.some((Q)=>Q.provenance==="command-substitution"))return null;return J.words.map((Q)=>Q.text)}function*vG($){if($.kind==="command"){yield $;for(let Z of $.nested)yield*I9(Z);return}if($.kind==="group")yield*I9($.body)}var uG=5,b9="Git aliases supplied through command-line or environment config can hide or execute commands. Run git without Git alias overrides, or ask the user to run it manually.";function q1($){let Z=$.indexOf("--");if(Z===-1)return{index:-1,before:$,after:[]};return{index:Z,before:$.slice(0,Z),after:$.slice(Z+1)}}function GJ($,Z,J){let Q=jJ($,Z,J),X=hG(Q.entries);if(X.size===0)return{blockedReason:Q.blockedReason,expanded:!1,tokens:$};let W=$,K=!1;for(let Y=0;Y<uG;Y++){let{subcommand:B,rest:q}=c1(W),U=B?.toLowerCase();if(!U||!X.has(U))return{blockedReason:Q.blockedReason,expanded:K,tokens:W};let G=X.get(U),j=mG(G);if(j===null||j.length===0)return{blockedReason:b9,expanded:!0,tokens:W};W=["git",...j,...q],K=!0}return{blockedReason:b9,expanded:!0,tokens:W}}function HJ($,Z,J){return jJ($,Z,J).entries.some((Q)=>Q.key.toLowerCase()==="core.sshcommand")}function c1($){if($.length===0)return{subcommand:null,rest:[]};let Z=$[0];if((Z?u(Z).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let Q=1;while(Q<$.length){let X=$[Q];if(!X)break;if(X==="--"){let W=$[Q+1];if(W&&!W.startsWith("-"))return{subcommand:W,rest:$.slice(Q+2)};return{subcommand:null,rest:$.slice(Q+1)}}if(X.startsWith("-"))if(a1.has(X))Q+=2;else if(X.startsWith("-c")&&X.length>2)Q++;else if(X.startsWith("-C")&&X.length>2)Q++;else Q++;else return{subcommand:X,rest:$.slice(Q+1)}}return{subcommand:null,rest:[]}}function hG($){let Z=new Map;for(let J of $){let Q=J.key.toLowerCase();if(!Q.startsWith("alias."))continue;let X=Q.slice(6);if(X!=="")Z.set(X,J.value)}return Z}function jJ($,Z,J){if($.length===0)return{blockedReason:null,entries:[]};let Q=$[0];if((Q?u(Q).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let W=kG(Z,J);return{blockedReason:W.blockedReason,entries:[...W.entries,...gG($,Z,J)]}}function gG($,Z,J){let Q=[],X=1;while(X<$.length){let W=$[X];if(!W||W==="--"||!W.startsWith("-"))return Q;if(W==="-c"){let K=f9($[X+1]);if(K)Q.push(K);X+=2;continue}if(W.startsWith("-c")&&W.length>2){let K=f9(W.slice(2));if(K)Q.push(K);X++;continue}if(W==="--config-env"){let K=UJ($[X+1],Z,J);if(K)Q.push(K);X+=2;continue}if(W.startsWith("--config-env=")){let K=UJ(W.slice(13),Z,J);if(K)Q.push(K);X++;continue}if(a1.has(W)){X+=2;continue}X++}return Q}function kG($,Z){let J=xG($,Z),Q=lG($,Z);return{blockedReason:J===null||Q===null?b9:null,entries:[...J??[],...Q??[]]}}function xG($,Z){let J=f1("GIT_CONFIG_PARAMETERS",$,Z);if(J===void 0)return[];let Q=[],X=R2(J);if(!X)return null;for(let W of X){let K=f9(W);if(!K)return null;Q.push(K)}return Q}function lG($,Z){let J=f4($,Z);if(J.state==="absent")return[];if(J.state==="invalid")return null;let Q=[];for(let X=0;X<J.count;X++){let W=f1(`GIT_CONFIG_KEY_${X}`,$,Z)?.trim(),K=f1(`GIT_CONFIG_VALUE_${X}`,$,Z);if(!W||K===void 0)return null;Q.push({key:W,value:K})}return Q}function f9($){if(!$)return null;let Z=$.indexOf("=");return{key:(Z===-1?$:$.slice(0,Z)).trim(),value:Z===-1?void 0:$.slice(Z+1)}}function UJ($,Z,J){let Q=$?.indexOf("=")??-1;if(!$||Q===-1)return null;return{key:$.slice(0,Q).trim(),value:f1($.slice(Q+1),Z,J)}}function mG($){let Z=$?.trimStart();if(!Z||Z.startsWith("!"))return null;return R2(Z)}var pG="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",cG="git checkout --force discards uncommitted changes. Use 'git stash' first.",dG="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",iG="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",sG="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",rG="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",nG="git switch --force discards uncommitted changes. Use 'git stash' first.",aG="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",oG="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",tG="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",eG="git reset --merge can lose uncommitted changes. Use 'git stash' first.",$H="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",ZH="git rm --force removes tracked files from the working tree. Use 'git rm --cached' to keep the files, or 'git rm --dry-run' to preview first.",JH="git push --force destroys remote history. Use --force-with-lease for safer force push.",QH="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",XH="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",WH="git branch -D force-deletes without merge check. Use -d for safe delete.",KH="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",YH="git merge --abort discards merge conflict resolutions. Use 'git status' first.",BH="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",qH="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",UH="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",GH="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",HH="git worktree remove --force can delete uncommitted changes. Remove --force flag.",_J=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),OJ=new Set(["--recurse-submodules","--track","-t"]),P9=new Set(["-b","-B","-U"]),C9=new Set(["-c","-C"]),jH=new Set(["--source","--conflict","--unified","--inter-hunk-context"]),_H=new Set(["-q","--quiet","--no-quiet","-f","--force","--no-force","-d","--detach","--no-detach","-m","--merge","--no-merge","-p","--patch","--no-patch","--guess","--no-guess","--overlay","--no-overlay","--ours","--theirs","--ignore-skip-worktree-bits","--no-ignore-skip-worktree-bits","--no-track","--overwrite-ignore","--no-overwrite-ignore","--ignore-other-worktrees","--no-ignore-other-worktrees","--progress","--no-progress","--pathspec-file-nul","--no-pathspec-file-nul","--no-recurse-submodules"]);function k($,Z){let J=$.split("=",1)[0]??$;return J.length>=4&&Z.startsWith(J)&&J.startsWith("--")&&J.slice(2).length>=2}var M3=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function MJ($){let{subcommand:Z,rest:J}=c1($);if(!Z)return null;switch(Z.toLowerCase()){case"checkout":return P0(OH(J));case"switch":return P0(LH(J));case"restore":return P0(FH(J));case"reset":return VH(J);case"clean":return P0(DH(J));case"rm":return P0(zH(J));case"push":return i0(IH(J));case"branch":return i0(PH(J));case"stash":return i0(SH(J));case"worktree":return i0(yH(J));case"rebase":return P0(CH(J));case"merge":return P0(AH(J));case"tag":return i0(EH(J));case"reflog":return i0(TH(J));default:return null}}function P0($){return $?{...$,localDiscard:!0}:null}function i0($){return $?{...$,localDiscard:!1}:null}function OH($){let{index:Z,before:J}=q1($),Q=H1(J,{shortOptsWithValue:P9});if(J.some((W)=>k(W,"--force"))||Q.has("-f"))return N("git.checkout-force",cG);for(let W of $){if(W==="-b"||W==="-B"||W==="--orphan")return null;if(k(W,"--pathspec-from-file"))return N("git.checkout-pathspec-from-file",iG)}if(Z!==-1){if(J.some((K)=>!K.startsWith("-")))return N("git.checkout-ref-path",dG);return N("git.checkout-double-dash",pG)}if(MH($).length>=2)return N("git.checkout-ambiguous",sG);return null}function LH($){let{before:Z}=q1($);if(Z.some((Q)=>k(Q,"--discard-changes")))return N("git.switch-discard-changes",rG);let J=H1(Z,{shortOptsWithValue:C9});if(Z.some((Q)=>k(Q,"--force"))||J.has("-f"))return N("git.switch-force",nG);return null}function MH($){let Z=[],J=0;while(J<$.length){let Q=$[J];if(!Q)break;if(Q==="--")break;if(Q.startsWith("-"))if(_J.has(Q))J+=2;else if(Q.startsWith("--")&&Q.includes("="))J++;else if(OJ.has(Q)){let X=$[J+1];if(X&&!X.startsWith("-")&&(Q==="--recurse-submodules"||Q==="--track"||Q==="-t"))if((Q==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"]).includes(X))J+=2;else J++;else J++}else if(Q.startsWith("--")&&!_H.has(Q)&&!_J.has(Q)&&!OJ.has(Q))J++;else J++;else Z.push(Q),J++}return Z}function FH($){let Z=NH($);if(Z.isTerminal||!Z.hasPathspec&&!Z.hasPatch||!Z.hasWorktree)return null;return Z.hasExplicitLocation?N("git.restore-worktree",oG):N("git.restore-unstaged",aG)}function NH($){let Z=!1,J=!1,Q=!0,X=!1,W=(K)=>{if(!X)Q=!1,X=!0;if(K!==void 0)Q=K};for(let K=0;K<$.length;K++){let Y=$[K];if(Y===void 0)break;if(Y==="--"){Z||=K+1<$.length;break}if(Y==="--pathspec-from-file"){Z=!0,K++;continue}if(Y.startsWith("--pathspec-from-file=")){Z=!0;continue}if(Y==="-h"||Y==="--help"||Y==="--version")return{hasPathspec:Z,hasPatch:J,hasWorktree:Q,hasExplicitLocation:X,isTerminal:!0};if(Y==="--staged"){W();continue}if(Y==="--no-staged"){W();continue}if(Y==="--worktree"){W(!0);continue}if(Y==="--no-worktree"){W(!1);continue}if(Y==="--patch"){J=!0;continue}if(Y==="--no-patch"){J=!1;continue}if(jH.has(Y)){K++;continue}if(Y.startsWith("--"))continue;if(Y==="-"){Z=!0;continue}if(!Y.startsWith("-")){Z=!0;continue}for(let B=1;B<Y.length;B++){let q=Y.charAt(B);if(q==="h")return{hasPathspec:Z,hasPatch:J,hasWorktree:Q,hasExplicitLocation:X,isTerminal:!0};if(q==="S"){W();continue}if(q==="W"){W(!0);continue}if(q==="p"){J=!0;continue}if(q==="s"||q==="U"){if(B===Y.length-1)K++;break}}}return{hasPathspec:Z,hasPatch:J,hasWorktree:Q,hasExplicitLocation:X,isTerminal:!1}}function VH($){let Z=null;for(let J of $){if(k(J,"--hard")){Z=N("git.reset-hard",tG);break}if(k(J,"--merge")){Z=N("git.reset-merge",eG);break}}if(!Z)return null;return RH($)?i0(Z):P0(Z)}function RH($){for(let Z of $){if(Z==="--")return!1;if(!Z.startsWith("-"))return!0}return!1}function DH($){for(let J of $)if(J==="-n"||k(J,"--dry-run"))return null;let Z=H1($.filter((J)=>J!=="--"));if($.some((J)=>k(J,"--force"))||Z.has("-f"))return N("git.clean-force",$H);return null}function zH($){let Z=!1,J=!1,Q=!1;for(let X of q1($).before){if(k(X,"--no-force")){Z=!1;continue}if(k(X,"--force")){Z=!0;continue}if(k(X,"--no-cached")){J=!1;continue}if(k(X,"--cached")){J=!0;continue}if(k(X,"--no-dry-run")){Q=!1;continue}if(k(X,"--dry-run")){Q=!0;continue}let W=H1([X]);Z||=W.has("-f"),Q||=W.has("-n")}return Z&&!J&&!Q?N("git.rm-force",ZH):null}function IH($){let{before:Z,after:J}=q1($),Q=H1(Z);if(Z.some((K)=>k(K,"--mirror")))return N("git.push-mirror",XH);if(Z.some((K)=>k(K,"--force"))||Q.has("-f")||LJ(Z,J).some(bH))return N("git.push-force",JH);if(Z.some((K)=>k(K,"--delete"))||Q.has("-d")||LJ(Z,J).some(fH))return N("git.push-delete",QH);return null}function LJ($,Z){return[...$.filter((J)=>J!==""&&!J.startsWith("-")),...Z]}function bH($){return $.startsWith("+")||$.includes(":+")}function fH($){return $.length>1&&$.startsWith(":")}function PH($){let{before:Z}=q1($),J=H1(Z),Q=J.has("-D")||J.has("-d")||Z.some((W)=>k(W,"--delete")),X=J.has("-D")||J.has("-f")||Z.some((W)=>k(W,"--force"));if(Q&&X)return N("git.branch-force-delete",WH);return null}function CH($){let{before:Z}=q1($);return Z.some((J)=>k(J,"--abort"))?N("git.rebase-abort",KH):null}function AH($){let{before:Z}=q1($);return Z.some((J)=>k(J,"--abort"))?N("git.merge-abort",YH):null}function EH($){let{before:Z}=q1($);return H1(Z).has("-d")||Z.some((Q)=>k(Q,"--delete"))?N("git.tag-delete",BH):null}function TH($){return $[0]==="delete"?N("git.reflog-delete",qH):null}function SH($){for(let Z of $){if(Z==="drop")return N("git.stash-drop",UH);if(Z==="clear")return N("git.stash-clear",GH)}return null}function yH($){let{before:Z}=q1($);if(!Z.includes("remove"))return null;let Q=H1(Z);if(Z.some((X)=>k(X,"--force"))||Q.has("-f"))return N("git.worktree-remove-force",HH);return null}import{execFileSync as wH}from"node:child_process";import{existsSync as E9,readFileSync as T9}from"node:fs";import{dirname as vH,isAbsolute as VJ,join as A9,resolve as RJ}from"node:path";var uH=["/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"];function DJ($,Z,J,Q){let X=hH($,Z,J);if(X!==null)return X;let W=gH(Z,J);if(W!==null)return W;if(K7(J))return!0;return kH(Q)}function hH($,Z,J){let Q=null,X=1;while(X<$.length){let W=$[X];if(!W||W==="--")return Q;if(!W.startsWith("-"))return Q;if(W==="-c"){let K=FJ($[X+1]);if(K!==null)Q=K;X+=2;continue}if(W.startsWith("-c")&&W.length>2){let K=FJ(W.slice(2));if(K!==null)Q=K;X++;continue}if(W==="--config-env"){let K=NJ($[X+1],Z,J);if(K!==null)Q=K;X+=2;continue}if(W.startsWith("--config-env=")){let K=NJ(W.slice(13),Z,J);if(K!==null)Q=K;X++;continue}if(a1.has(W))X+=2;else X++}return Q}function gH($,Z){if(f1("GIT_CONFIG_PARAMETERS",$,Z)!==void 0)return!0;let J=f4($,Z);if(J.state==="absent")return null;if(J.state==="invalid")return!0;let Q=null;for(let X=0;X<J.count;X++){let W=f1(`GIT_CONFIG_KEY_${X}`,$,Z),K=f1(`GIT_CONFIG_VALUE_${X}`,$,Z);if(!W?.trim()||K===void 0)return!0;let Y=W.trim().toLowerCase();if(S9(Y))return!0;if(Y!=="submodule.recurse")continue;Q=D2(K)}return Q}function kH($,Z=lH()){let J=xH($);if(J===null||J)return!0;if(Z===null)return!0;try{let Q=wH(Z,["config","--get","submodule.recurse"],{cwd:$,encoding:"utf8",env:mH(process.env),stdio:["ignore","pipe","ignore"]}).trim();return D2(Q)}catch(Q){return!pH(Q)}}function xH($){let Z=cH($);if(Z===null)return null;for(let J of Z){if(!E9(J))continue;if(sH(J))return!0}return!1}function lH(){for(let $ of uH)if(E9($))return $;return null}function mH($){let Z={...$};for(let J of Object.keys(Z))if($2(J))delete Z[J];return Z}function pH($){return typeof $==="object"&&$!==null&&"status"in $&&$.status===1}function cH($){let Z=Q2($);if(Z===null)return null;let J=dH(Z);if(J===null)return null;let Q=iH(J);if(Q===null)return null;return[A9(Q,"config"),A9(J,"config.worktree")]}function dH($){try{let J=T9($,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!J.startsWith("gitdir:"))return $;let Q=J.slice(7).trim();if(Q==="")return null;return VJ(Q)?Q:RJ(vH($),Q)}catch{return null}}function iH($){let Z=A9($,"commondir");if(!E9(Z))return $;try{let J=T9(Z,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(J==="")return null;return VJ(J)?J:RJ($,J)}catch{return null}}function sH($){let Z;try{Z=T9($,"utf-8")}catch{return!0}let J="",Q=!1;for(let X of Z.split(/\r?\n/)){let W=X.trim();if(W===""||W.startsWith("#")||W.startsWith(";"))continue;let K=W.match(/^\[([^\]]+)\]$/);if(K){J=K[1]?.trim().toLowerCase()??"";continue}let Y=W.indexOf("="),B=(Y===-1?W:W.slice(0,Y)).trim().toLowerCase(),q=Y===-1?"true":W.slice(Y+1).trim();if(rH(J)&&B==="path")return!0;if(J==="submodule"&&B==="recurse")Q=D2(q)}return Q}function rH($){return $==="include"||$.startsWith("includeif ")}function FJ($){if(!$)return null;let Z=$.indexOf("="),J=(Z===-1?$:$.slice(0,Z)).toLowerCase();if(S9(J))return!0;if(J!=="submodule.recurse")return null;let Q=Z===-1?"true":$.slice(Z+1).toLowerCase();return D2(Q)}function D2($){let Z=$.toLowerCase();return Z!=="false"&&Z!=="no"&&Z!=="off"&&Z!=="0"}function NJ($,Z,J){let Q=$?.indexOf("=")??-1;if(!$||Q===-1)return null;let X=$.slice(0,Q).toLowerCase();if(S9(X))return!0;if(X!=="submodule.recurse")return null;let W=f1($.slice(Q+1),Z,J);return W===void 0||D2(W)}function S9($){return $==="include.path"||$.startsWith("includeif.")&&$.endsWith(".path")}function zJ($,Z,J){if(!Z.localDiscard||!J.worktreeMode||U7(J.env,J.envAssignments))return null;let Q=G7($,J.cwd);if(!Q.gitCwd||Q.hasExplicitGitContext)return null;if(!H7(Q.gitCwd))return null;if(nH($,J,Q.gitCwd))return null;return{originalReason:Z.reason,gitCwd:Q.gitCwd}}function nH($,Z,J){let{subcommand:Q,rest:X}=c1($),W=Q?.toLowerCase();if(Z.dynamicArguments||aH(X)||DJ($,Z.env,Z.envAssignments,J)||eH(X)||oH(W,X))return!0;return W==="clean"&&$j(X)>1}function aH($){return $.some((Z)=>/[$*?[]/.test(Z))}function oH($,Z){if($==="checkout"){let{before:J}=q1(Z),Q=H1(J,{shortOptsWithValue:P9}),X=J.some((K)=>k(K,"--force"))||Q.has("-f"),W=Q.has("-B")||J.some((K)=>K==="-B"||K.startsWith("-B"));return X&&W}if($==="switch"){let{before:J}=q1(Z),Q=H1(J,{shortOptsWithValue:C9}),X=J.some((K)=>k(K,"--force"))||J.some((K)=>k(K,"--discard-changes"))||Q.has("-f"),W=J.some((K)=>K==="-C"||K.startsWith("-C")||tH(K))||Q.has("-C");return X&&W}return!1}function tH($){let Z=$.split("=",1)[0]??$;return Z==="--force-create"||Z.length>=9&&"--force-create".startsWith(Z)}function eH($){return $.some((Z)=>Z.startsWith("--recurse-sub"))}function $j($){let Z=0;for(let J of $){if(J==="--force"){Z++;continue}if(J.startsWith("-")&&!J.startsWith("--")){for(let Q of J.slice(1))if(Q==="f")Z++}}return Z}var Zj="Git SSH environment overrides can execute arbitrary commands during network operations. Run git without GIT_SSH/GIT_SSH_COMMAND overrides, or ask the user to run it manually.",Jj=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function A$($,Z){return IJ($.map(E),Z)}function IJ($,Z,J){let Q=GJ($,Z.env,Z.envAssignments),X=Z.policy?.destructiveCommandRuleOverrides["git.alias-config"]==="off";if(Q.blockedReason&&!X)return N("git.alias-config",Q.blockedReason);let W=Q.tokens;if((W7(Z.envAssignments)||HJ($,Z.env,Z.envAssignments))&&Qj(W))return N("git.ssh-env",Zj);let K=MJ(W);if(!K)return null;if(Q.expanded||Q.blockedReason)return K;let Y=zJ($,K,Z);if(!Y)return K;return J?.(Y),null}function bJ($,Z){let J=null;return{match:IJ($.map(E),Z,(X)=>{J=X}),relaxation:J}}function Qj($){let{subcommand:Z,rest:J}=c1($),Q=Z?.toLowerCase();if(!Q)return!1;if(Jj.has(Q))return!0;if(Q==="archive")return q1(J).before.some((X)=>k(X,"--remote"));return Q==="remote"&&Xj(J)}function Xj($){return $.find((Z)=>!Wj(Z))?.toLowerCase()==="update"}function Wj($){return $==="-v"||k($,"--verbose")||k($,"--no-verbose")}import{isAbsolute as aj}from"node:path";var fJ="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Kj="rm -rf for non-temporary paths is blocked by the active safety policy. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Yj="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",CJ="rm -rf targeting root or home directory is extremely dangerous and always blocked.",Bj="rm -rf in home directory is dangerous. Change to a project directory first.";function E$($,Z){let J=d0({...Z,allowPaths:Z.policy?.destructiveCommandAllowPaths,posixShell:!0}),Q=$.map(E),X=p1(Q),W=qJ(Q),K=Uj($);for(let Y of K){let B=N2(Y.word);if(X&&B.unsafeBraceExpansion){let q=T(PJ({kind:"outside_anchored_cwd"},J,Z.policy),Z.policy);if(q)return q;continue}for(let q of B.expandedTargets??[Y.text]){let U={targetIsLiteral:B.expandedTargets!==void 0||B.targetIsLiteral,tmpdirWordSplittingProtected:B.tmpdirWordSplittingProtected};if(!W&&J.resolvedCwd&&c0(q,J.resolvedCwd,J.protectedGitMetadata,W,J.pathCanonicalizationContext))return N("rm.git-metadata",E1);if(W&&!X){let G=l1(q,J,U);if(G.kind==="root_or_home_target")return N("rm.recursive-force-root-or-home",CJ);if(G.kind==="git_metadata_target")return N("rm.git-metadata",E1);continue}if(!X)continue;for(let G of qj(q,J,U)){let j=PJ(G,J,Z.policy),H=T(j,Z.policy);if(H)return H}}}return null}function qj($,Z,J){let Q=l1($,Z,J);if(Q.kind==="cwd_self_target")return[Q,l1($,Z,{...J,skipCwdSelf:!0})];if(Q.kind!=="home_cwd_target")return[Q];let X=l1($,Z,{...J,skipHomeCwd:!0});if(X.kind!=="cwd_self_target")return[Q,X];return[Q,X,l1($,Z,{...J,skipHomeCwd:!0,skipCwdSelf:!0})]}function Uj($){let Z=[],J=!1;for(let Q of $.slice(1)){let X=E(Q);if(!X)continue;if(X==="--"){J=!0;continue}if(J){Z.push({text:X,word:Q});continue}if(!X.startsWith("-"))Z.push({text:X,word:Q})}return Z}function PJ($,Z,J){switch($.kind){case"root_or_home_target":return N("rm.recursive-force-root-or-home",CJ);case"git_metadata_target":return N("rm.git-metadata",E1);case"temp_target":return null;case"dynamic_target":if(!o(J,"rm.recursive-force-dynamic-target",Z.strict))return null;return N("rm.recursive-force-dynamic-target",Yj);case"home_cwd_target":return N("rm.recursive-force-home-cwd",Bj);case"cwd_self_target":return N("rm.recursive-force-cwd-self",fJ);case"within_anchored_cwd":if(o(J,"rm.recursive-force-paranoid",Z.paranoid))return N("rm.recursive-force-paranoid",Kj);return null;case"outside_anchored_cwd":return N("rm.recursive-force-outside-cwd",fJ)}}var Gj={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},EJ=new Set(["--init-file","--rcfile"]),Hj=["--init-file","--rcfile"],jj=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function Z0($){for(let Z=1;Z<$.length;Z++){let J=$[Z];if(!J)continue;if(J==="-c")return AJ($,Z,!0);if(J.startsWith("-")&&J.includes("c")&&!J.startsWith("--")){let Q=AJ($,Z,!1);if(Q!==null)return Q}}return null}function T1($){let Z=u($[0]??"").toLowerCase();if(Z==="zsh"||Z==="ksh")return J0($).syntaxCheck;let J=!1;for(let Q of $.slice(1)){if(Q==="--")return J;if(Q.startsWith("+")&&!Q.startsWith("++")){if(Q.slice(1).includes("n"))J=!1;continue}if(!Q.startsWith("-")||Q.startsWith("--"))return J;let X=Q.slice(1);if(X.includes("n"))J=!0;if(X.includes("c"))return J}return J}function AJ($,Z,J){if($[Z+1]==="--")return $[Z+2]||null;let Q=$[Z+1];if(!Q||!J&&Q.startsWith("-"))return null;return Q}function TJ($){let Z=u($[0]??"").toLowerCase(),J=_j($,Z),Q=jj.get(Z)??null,X=J.argvSource?.kind!=="absent";return{argvSource:Z==="bash"?J.argvSource:null,argvSourceApplies:Z==="bash"&&J.interactive&&J.argvSource?.kind==="literal",envName:Q,envSourceApplies:X&&(Q==="BASH_ENV"?!J.interactive:Q==="ENV"&&J.interactive)}}function _j($,Z){let J=J0($),Q=J.commandIndex??J.scriptIndex??$.length,X=[],W=!1,K=!0;for(let Y=1;Y<Q;Y++){let B=$[Y];if(B===void 0||B==="--"||B==="-"||B[0]!=="-"&&B[0]!=="+")break;if(B.startsWith("--")){if(Z==="bash"&&K?Hj.find((j)=>B===j):void 0){let j=$[Y+1];X.push(j===void 0?{kind:"absent"}:{kind:"literal",value:j}),Y++;continue}let G=B.split("=",1)[0]??B;if(Z==="bash"&&EJ.has(G)&&!B.includes("="))Y++;continue}if(Z==="bash")K=!1;let q=SJ(Z,B,$[Y+1],"startup");if(q.interactive)W=B[0]==="-";Y+=q.followingValues}return{argvSource:X.at(-1)??null,interactive:W}}function SJ($,Z,J,Q){let X=!1,W=0,K=!1,Y=!1,B=!1;for(let q=1;q<Z.length;q++){let U=Z[q];if(U===void 0)break;if($==="ksh"&&U==="o"&&q+1<Z.length){if(Q==="argv"){let G=Z.slice(q+1);if(Z[0]==="-"&&(G==="c"||G[0]==="-"&&G.endsWith("c")))K=!0}break}if($==="ksh"&&U==="o"&&q+1===Z.length&&(J?.startsWith("-")||J?.startsWith("+")))break;if($==="zsh"&&U==="o"&&q+1<Z.length)break;if(Q==="startup"&&U==="i")X=Z[0]==="-";if(Q==="argv"&&Z[0]==="-"&&U==="c")K=!0;if(Q==="argv"&&U==="n")B=Z[0]==="-";if(Q==="argv"&&U==="s")Y=Z[0]==="-";if(!Gj[$]?.includes(U))continue;if(q+1===Z.length)W++;break}return{interactive:X,followingValues:W,commandSelected:K,stdinMode:Y,syntaxCheck:B}}function J0($){let Z=u($[0]??"").toLowerCase(),J=!1,Q=!1,X=!1;for(let W=1;W<$.length;W++){let K=$[W];if(K===void 0)break;if(K==="--"){let B=J&&$[W+1]!==void 0?W+1:null;return{command:B===null?null:$[B]??null,commandIndex:B,scriptIndex:!J&&!Q&&$[W+1]!==void 0?W+1:null,readsStdinAsCommands:!J&&(Q||$[W+1]===void 0),syntaxCheck:X}}if(K==="-"||K[0]!=="-"&&K[0]!=="+")return{command:J?K:null,commandIndex:J?W:null,scriptIndex:!J&&!Q&&K!=="-"?W:null,readsStdinAsCommands:!J&&(Q||K==="-"),syntaxCheck:X};if(K.startsWith("--")){let B=K.split("=",1)[0]??K;if(Z==="bash"&&EJ.has(B)&&!K.includes("="))W++;continue}let Y=SJ(Z,K,$[W+1],"argv");if(Y.commandSelected)J=!0;if(Y.syntaxCheck)X=!0;if(Y.stdinMode)Q=!0;W+=Y.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!J,syntaxCheck:X}}var C0={kind:"none"},s0={kind:"dynamic"},Oj=new Set(["<","<<","<<-","<<<","<&","<>"]),wJ=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,Lj=/^(?:[0-9]+|[@*])$/,Mj=h0.maxWords,Fj=h0.maxInputLength;function vJ($){if(!$||u(l($.words[0]?.text??""))!=="printf")return;if($.words.some((X)=>X.provenance!=="literal"))return;let Z=$.words.slice($.words[1]?.text==="--"?2:1),J=Z[0]?.text;if(J===void 0)return"";let Q=Z.slice(1).map((X)=>X.text);if(J==="%s")return Q.join("");if(J==="%s\\n"||J===`%s
54
- `)return`${Q.join(`
55
- `)}
56
- `;if(J.includes("%")||/\\(?![\\nrt])/.test(J))return;return J.replaceAll("\\n",`
57
- `).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function T$($){let Z=z2($[1])==="--"?2:1;if($.length<=Z)return C0;let J=$.slice(Z);if(!J.every(N3))return s0;return{kind:"literal",source:J.map(E).join(" ")}}function uJ($){let Z=z2($[1])==="--"?2:1,J=$[Z],Q=z2(J);if(J===void 0||$.length<=Z+1||Q==="-"||Q===""||Q==="-l"||Q==="-p")return C0;if(!N3(J))return s0;return{kind:"literal",source:Q}}function F3($,Z){let J=Vj($);if(J===-1)return C0;let Q=Rj(Z);if(!Q)return C0;let X=[],W=Q.command?.length??0;for(let K of Q.references){let Y=zj(K,$,J,Q.ifs);if(!Y)return s0;if(W+=Y.reduce((B,q)=>B+q.length+3,0),X.length+Y.length>Mj||W>Fj)return s0;X.push(...Y)}if(Q.command==="eval")return{kind:"literal",source:X.join(" ")};if(X.length===0||/\s/.test(X[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[Q.command,Q.command&&Q.optionTerminator?"--":null,...X.map(bj)].filter((K)=>K!==null).join(" ")}}function hJ($,Z,J,Q){if(!J0($.map(E)).readsStdinAsCommands)return C0;let X=Z.filter((W)=>(W.fd===void 0||W.fd===0)&&Oj.has(W.operator)).at(-1);if(X){if(X.operator==="<<"||X.operator==="<<-")return C0;if(X.operator!=="<<<"||X.target?.provenance!=="literal")return s0;return{kind:"literal",source:X.target.text}}if(!J)return C0;return Q===void 0?s0:{kind:"literal",source:Q}}function Q0($){let Z=J0($.map(E)).scriptIndex;if(Z===null)return C0;let J=$[Z],Q=z2(J);return W3(J,Q)?{kind:"literal",source:Q}:s0}var Nj=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function u9($){if($.words.length!==2||$.redirections.length!==0||$.nested.length!==1)return!1;let Z=$.words[0],J=$.words[1];if(!Z||Z.provenance!=="literal"||Z.quoted||Z.raw!==Z.text||!J)return!1;if(!(Z.text==="eval"&&J.quoted&&J.parts.length===3&&J.parts[0]?.raw==='"'&&J.parts[1]?.provenance==="command-substitution"&&J.parts[1].raw.startsWith("$(")&&J.parts[2]?.raw==='"'||(Z.text==="source"||Z.text===".")&&!J.quoted&&J.parts.length===1&&J.parts[0]?.provenance==="command-substitution"&&J.parts[0].raw.startsWith("<(")))return!1;let X=$.nested[0];if(X?.status!=="complete"||X.nodes.length!==1)return!1;let W=X.nodes[0];if(W?.kind!=="command"||W.redirections.length!==0||W.nested.length!==0||W.words.some((B)=>B.provenance!=="literal"||B.parts.some((q)=>q.provenance!=="literal")))return!1;let K=W.words[0]?.text;if(K===void 0||x1(K)!==null)return!1;let Y=u(l(K));return!Nj.has(Y)&&!t.has(Y)&&!l0(Y)}function Vj($){return J0($.map(E)).commandIndex??-1}function Rj($){let Z=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec($.trim()),J=Z?.[4]??$.trim(),Q=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(J),X=(Q?.[3]??J).split(/\s+/).map(Dj);if(X.length===0||X.some((W)=>W===null))return null;return{command:Q?.[1]??null,optionTerminator:Q?.[2]!==void 0,references:X.filter((W)=>!!W),ifs:Z?Z[1]??Z[2]??Z[3]??"":`
58
- `}}function Dj($){let Z=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec($),J=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec($),Q=Z??J;if(!Q)return null;let X=Q[1]??Q[2];return{parameter:X==="@"||X==="*"?X:Number(X),quoted:Z!==null}}function zj($,Z,J,Q){let X=Z.slice(J+2);if($.parameter==="@")return $.quoted?y9(X):Ij(X,Q);if($.parameter==="*"){let Y=y9(X);if(!Y)return;let B=Y.join(Q[0]??"");return $.quoted?[B]:w9(B,Q)}let W=Z[J+1+$.parameter];if(W&&!N3(W))return;let K=z2(W);return $.quoted?[K]:w9(K,Q)}function y9($){return $.every(N3)?$.map(E):void 0}function Ij($,Z){let J=y9($);if(!J)return;let Q=J.map((X)=>w9(X,Z));return Q.some((X)=>X===void 0)?void 0:Q.flatMap((X)=>X??[])}function w9($,Z){if(["*","?","[","]"].some((J)=>$.includes(J)))return;if(Z==="")return $===""?[]:[$];if(Z===`
59
- `)return $.trim().split(/\s+/).filter(Boolean);if(Z.length!==1)return;return Z===" "||Z==="\t"||Z===`
60
- `?$.trim().split(/\s+/).filter(Boolean):$.split(Z).filter(Boolean)}function N3($){if(!$)return!0;return $.provenance==="unknown"?!/[$`]/.test(E($)):$.provenance==="literal"}function z2($){return $?E($):""}function bj($){return`'${$.replaceAll("'",`'"'"'`)}'`}function h9($,Z){return v9(v1($,"posix"),Z)}function S$($){return h9($,new Set(Array.from($.matchAll(wJ)).flatMap((Z)=>{let J=Z[1]??Z[2];return J===void 0?[]:[J]})))}function v9($,Z){if($.status==="invalid"||$.status==="limited")return!1;let J=new Set(Z);for(let Q of $.nodes){if(Q.kind==="group"){if(v9(Q.body,J))return!0;continue}if(Q.kind!=="command")continue;if(Q.nested.some((X)=>v9(X,J))||gJ(Q.words,J))return!0;Ej(Q,J)}return!1}function gJ($,Z){let J=$.findIndex((K)=>x1(K.text)===null);if(J===-1)return!1;let Q=$[J];if(!Q)return!1;if(I2(Q,Z))return!0;let X=l(Q.text);if(X==="source"||X==="."){let K=$[J+1]?.text==="--"?J+2:J+1;return yJ($[K],Z)}if(t.has(X)){let K=$.slice(J),Y=J0(K.map((q)=>q.text)),B=Y.commandIndex??Y.scriptIndex;return!Y.syntaxCheck&&B!==null&&yJ(K[B],Z)}let W=fj($,J,Z);if(W===null)return!1;if(W===-1)return!0;return gJ($.slice(W),Z)}function fj($,Z,J){let Q=l($[Z]?.text??"");if(Q==="command")return Pj($,Z+1);if(Q==="exec")return Cj($,Z+1);if(Q==="env")return Aj($,Z+1,J);return null}function Pj($,Z){for(let J=Z;J<$.length;J++){let Q=$[J]?.text??"";if(Q==="--")return $[J+1]?J+1:null;if(/^-[p]*[vV][pvV]*$/.test(Q))return null;if(/^-p+$/.test(Q))continue;return J}return null}function Cj($,Z){for(let J=Z;J<$.length;J++){let Q=$[J]?.text??"";if(Q==="--")return $[J+1]?J+1:null;if(Q==="-a"){J++;continue}if(/^-a.+/.test(Q)||/^-[cl]+$/.test(Q))continue;return J}return null}function Aj($,Z,J){for(let Q=Z;Q<$.length;Q++){let X=$[Q],W=X?.text??"";if(W==="--")return $[Q+1]?Q+1:null;if(W==="-S"||W==="--split-string")return I2($[Q+1],J)?-1:Q+2;if(W.startsWith("-S")||W.startsWith("--split-string="))return I2(X,J)?-1:Q+1;if(W==="-u"||W==="--unset"||W==="-C"||W==="--chdir"||W==="-P"){Q++;continue}if(W==="-i"||W==="-0"||W==="--null"||W.startsWith("-u=")||W.startsWith("--unset=")||W.startsWith("-C")||W.startsWith("--chdir=")||W.startsWith("-P"))continue;if(W.startsWith("-"))continue;if(x1(W))continue;return Q}return null}function Ej($,Z){if(!$.words.every((J)=>x1(J.text)!==null))return;for(let J of $.words){let Q=x1(J.text);if(!Q)continue;if(I2(J,Z))Z.add(Q.name)}}function I2($,Z){if(!$)return!1;return $.parts.filter((J)=>J.provenance==="variable").some((J)=>Array.from(J.raw.matchAll(wJ)).some((Q)=>{let X=Q[1]??Q[2];return X!==void 0&&(Lj.test(X)||Z.has(X))}))}function yJ($,Z){return!!$&&($.parts.some((J)=>J.provenance!=="literal"&&J.provenance!=="variable")||I2($,Z))}var Tj=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--config-env"]),Sj=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),yj=new Set;function kJ($){if($==="git")return Tj;if($==="docker")return Sj;return yj}function Q1($,Z){if($.length===0||Z.length===0)return null;let J=l($[0]??""),Q=H1($);for(let X of Z){if(!wj(J,X.command))continue;if(!vj(J,$,X.subcommand))continue;if(hj($,new Set(X.block_args),Q))return{id:`custom.${X.name}`,reason:`[${X.name}] ${X.reason}`,intent:X.intent??"manual_only"}}return null}function wj($,Z){return $===l(Z)}function vj($,Z,J){if(!J)return!0;return xJ(Z,1,J,kJ($))}function xJ($,Z,J,Q){let X=!1;for(let W=Z;W<$.length;W++){let K=$[W];if(!K)continue;if(X){X=!1;continue}if(K==="--"){let Y=$[W+1];if(Y&&!Y.startsWith("-"))return Y===J;return!1}if(Q.has(K)){X=!0;continue}if(K.startsWith("-")){if(!K.includes("=")&&uj($,W,J,Q))return!0;continue}return K===J}return!1}function uj($,Z,J,Q){let X=$[Z+1];if(!X||X.startsWith("-"))return!1;return xJ($,Z+2,J,Q)}function hj($,Z,J){for(let Q of $)if(Z.has(Q))return!0;for(let Q of J)if(Z.has(Q))return!0;return!1}function A0($,Z,J={}){if($.length===0)return null;let Q=$[0];if(!Q)return null;let X=l(Q);if(X==="eval"){let W=T$(g($));if(W.kind==="dynamic")return y$(J,Z);if(W.kind==="literal"&&Z.analyzeNested){let K=Z.analyzeNested(W.source,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments});if(K)return K}return X0(J,Z)}if(t.has(X)){if(T1($))return null;let W=Z0($);if(W){if(J.dynamicSourceInput??J.dynamicInput){let B=y$(J,Z);if(B)return B}if(S$(W)){let B=y$(J,Z);if(B)return B}if(!Z.analyzeNested)return null;let Y=Z.analyzeNested(W,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments});if(Y)return Y;return null}let K=Q0(g($));if(K.kind==="dynamic")return y$(J,Z);if(K.kind==="literal"){if(J.dynamicSourceInput)return y$(J,Z);return null}if(J.dynamicSourceInput??J.dynamicInput)return y$(J,Z);return null}if(F1.has(X))return T(I4($,(W)=>Z.analyzeNested?Z.analyzeNested(W,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments}):null),Z.policy)??Q1($,Z.policy?.rules??[])??X0(J,Z);if(N1(X)){let W=v4($);if(!W)return X0(J,Z);if(o(Z.policy,"interpreter.one-liner-paranoid",!!Z.paranoidInterpreters)){let Y=T(N("interpreter.one-liner-paranoid",O$),Z.policy);if(Y)return Y}if(g4(X,W))return X0(J,Z);let K=Z.analyzeNested?.(W,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments});if(K&&K.id!=="raw-text.dangerous-command"&&(K.reason!==D0||H$(W)))return K;if(L$(W,Z.scanWork))return T(N("interpreter.dangerous-command",x0),Z.policy)??X0(J,Z);return X0(J,Z)}if(X==="rm"||X==="rmdir"){let W=X==="rm"&&(p1($)||J.dynamicRmInput);return T(E$(g($),{environment:Z.environment,cwd:Z.cwd,originalCwd:Z.originalCwd,strict:Z.strict,paranoid:Z.paranoidRm,allowTmpdirVar:Z.allowTmpdirVar,tmpdirWordSplittingUnsafe:e1(Z.envAssignments,Z.environment),trustedTmpdirValue:O0(Z.envAssignments,Z.environment),protectedGitMetadata:Z.protectedGitMetadata,policy:Z.policy}),Z.policy)??(W&&J.dynamicRmInput?X0(J,Z):null)??(W?gj(J,Z):null)}if(X==="find")return _3(g($),{...Z,derivedCommandWorkBudget:Z.derivedCommandWorkBudget,analyzeTokens:(W,K)=>A0(W,{...Z,cwd:K??void 0,derivedCommandWorkBudget:Z.derivedCommandWorkBudget},J)})??Q1($,Z.policy?.rules??[])??X0(J,Z);if(X==="git")return T(A$(g($),{env:Z.environment.env,cwd:Z.cwd,envAssignments:Z.envAssignments,policy:Z.policy,worktreeMode:J.dynamicInput?!1:Z.worktreeMode}),Z.policy)??Q1($,Z.policy?.rules??[])??X0(J,Z);return Q1($,Z.policy?.rules??[])??X0(J,Z)}function y$($,Z){return $.shellDynamicMatch?T($.shellDynamicMatch,Z.policy):null}function X0($,Z){return $.dynamicSourceInput&&$.dynamicSourceMatch?T($.dynamicSourceMatch,Z.policy):null}function gj($,Z){return $.dynamicInput&&$.rmDynamicMatch?T($.rmDynamicMatch,Z.policy):null}var g9="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",k9="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",kj="__CC_SAFETY_NET_XARGS_INPUT__",V3="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",R3="rm",xj=/(?:^|[;&|]\s*|\b(?:eval|source)\s+|\b(?:ba|da|z|k)?sh\s+-c\s+)\s*["']?\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,lj=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,mj=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,pj=/^(?:[0-9]+|[@*])$/,cj=new Set(["branch","checkout","clean","push","reset","restore","switch","tag"]);function pJ($,Z){let J=$.map(E),{childStart:Q,replacementToken:X}=r0(J),W=J.slice(Q),K=N("xargs.shell-dynamic",k9);if(ij(W,X,Z)&&T(K,Z.policy))return T(K,Z.policy);for(let Y of m1(W,Z)){let B=Y.tokens,q=X!==null&&B[0]!==W[0]&&(B[0]?.includes(X)??!1)?T(K,Z.policy):null;if(q)return q;let U=sJ(B,X,Y.wrapperEnvAssignments),G=Y.head==="rm"&&X!==null&&dJ(B,X),j=A0(B,{...Z,cwd:Y.cwd,envAssignments:Y.envAssignments},{dynamicInput:U,dynamicSourceInput:G||cJ(B,Y.head,X,Y.wrapperEnvAssignments,U,Z.scanWork,Z.environment),dynamicRmInput:G,shellDynamicMatch:K,dynamicSourceMatch:K,rmDynamicMatch:N("xargs.rm-recursive-force-dynamic",g9)});if(j)return j;let H=dj(B,X,Z.policy?.rules??[]);if(H)return H;if(Y.head==="git"){let O=X===null?[...B,kj]:B,M=X!==null&&(B.some((D)=>D.includes(X))||Array.from(Y.envAssignments.values()).some((D)=>D.includes(X))),L=A0(O,{...Z,cwd:Y.cwd,envAssignments:Y.envAssignments,worktreeMode:X===null||M?!1:Z.worktreeMode});if(L)return L}let _=Q1(B,Z.policy?.rules??[]);if(_)return _}return null}function dj($,Z,J){if(J.length===0)return null;if(Z===null){for(let X of J){let W=Q1([...$,...X.subcommand?[X.subcommand]:[],...X.block_args],J);if(W)return W}return null}let Q=new Set(J.flatMap((X)=>[X.subcommand,...X.block_args].flatMap((W)=>W?$.flatMap((K)=>x9(K,Z,W)):[])));for(let X of Q){let W=Q1($.map((K)=>K.replaceAll(Z,X)),J);if(W)return W}return null}function x9($,Z,J){let Q=$.indexOf(Z);if(Q===-1||$.indexOf(Z,Q+Z.length)!==-1)return[];let X=$.slice(0,Q),W=$.slice(Q+Z.length);return J.startsWith(X)&&J.endsWith(W)?[J.slice(X.length,J.length-W.length)]:[]}function cJ($,Z,J,Q,X,W,K){if(t.has(Z)){if(T1($))return!1;if(J!==null&&sj($,J))return!0;let Y=Z0($);if(!Y){let B=Q0(g($));if(B.kind==="literal")return J!==null&&B.source.includes(J);return B.kind==="none"&&X}if(J!==null&&Y.includes(J))return!0;if(_2(Y,W))return!0;return rj(Y,J,Q)}if(N1(Z))return lJ($,J,h4,z7(Z));if(F1.has(Z))return lJ($,J,v6,$7);if(Z==="eval"){let Y=T$(g($));if(Y.kind==="dynamic")return!0;if(J!==null)return Y.kind==="literal"&&Y.source.includes(J);return X}if(Z==="find")return nj($,J,W,K);if(Z==="git"){let Y=c1($);return J===null?Y.subcommand===null:(Y.subcommand?.includes(J)??!1)||Y.subcommand!==null&&cj.has(Y.subcommand.toLowerCase())&&iJ(Y.rest,J).some((B)=>B.includes(J))}return!1}function lJ($,Z,J,Q){let X=J($);if(Z===null)return X.optionsOpen||J([...$,V3]).sources.some((B)=>B.value===V3);if(X.sources.some((B)=>B.value.includes(Z)))return!0;let W=new Set(X.sources.map((B)=>`${B.tokenIndex}\x00${B.kind}\x00${B.value}`)),K=Q.flatMap((B)=>[B.selector,...B.valueForm==="attached-only"||B.valueForm==="attached-or-separate"?[`${B.selector}${V3}`]:[],...B.valueForm==="equals-or-separate"?[`${B.selector}=${V3}`]:[]]),Y=new Set(K.flatMap((B)=>$.flatMap((q)=>x9(q,Z,B))));return Array.from(Y).some((B)=>J($.map((q)=>q.replaceAll(Z,B))).sources.some((q)=>!W.has(`${q.tokenIndex}\x00${q.kind}\x00${q.value}`)))}function ij($,Z,J){if($.length===0||($[0]??"").toLowerCase()==="command")return!1;let Q=new Set(Array.from(m1($,J),(W)=>W.head)),X=Z===null?[...$,R3]:$.map((W,K)=>K===0?W:W.replaceAll(Z,R3));return Array.from(m1(X,J)).some((W)=>W.head===R3&&!Q.has(R3))}function dJ($,Z){return iJ($.slice(1),Z).some((J)=>J.includes(Z)&&(J.startsWith("-")||J.startsWith(Z)))}function iJ($,Z){let J=$.findIndex((Q)=>Q==="--"&&!Q.includes(Z));return J===-1?$:$.slice(0,J)}function sJ($,Z,J){if(Z===null)return!0;return $.some((Q)=>Q.includes(Z))||Array.from(J.values()).some((Q)=>Q.includes(Z))}function sj($,Z){let J=J0($);if(J.commandIndex!==null&&($[J.commandIndex]??"").includes(Z)||J.scriptIndex!==null&&($[J.scriptIndex]??"").includes(Z))return!0;return["-c","-nc","-cn",`--${Z}`,Z].some((X)=>$.some((W,K)=>{if(K===0||!W.includes(Z))return!1;return x9(W,Z,X).some((B)=>{let q=$.map((G,j)=>j===K?G.replaceAll(Z,B):G),U=J0(q);if(U.commandIndex===null&&U.scriptIndex===null)return!1;if(J.commandIndex===null&&U.commandIndex!==null)return!0;if(J.scriptIndex===null&&U.scriptIndex!==null)return!0;if(U.commandIndex!==null&&(q[U.commandIndex]??"").includes(B))return!0;return U.scriptIndex!==null&&(q[U.scriptIndex]??"").includes(B)})}))}function rj($,Z,J){let Q=new Set(Z===null?[]:Array.from(J).filter(([,X])=>X.includes(Z)).map(([X])=>X));for(let X of $.matchAll(xj))if(mJ(X,Q))return!0;for(let X of $.matchAll(lj))for(let W of(X[1]??"").matchAll(mj))if(mJ(W,Q))return!0;return h9($,Q)}function mJ($,Z){let J=$[1]??$[2];return J!==void 0&&(pj.test(J)||Z.has(J))}function nj($,Z,J,Q){if(Z===null)return!0;let X=!1,W=0;for(let K=1;K<$.length;K++){let Y=$[K]??"";if(!X&&!Y.startsWith("-")&&Y!=="!"&&Y!=="("){if(Y.indexOf(Z)===0)return!0;continue}if(X=!0,W>0){W--;continue}if(L0(Y)){let q=V2($,K);K=q.nextIndex-1;for(let U of m1(q.tokens,{environment:Q,cwd:void 0})){let G=sJ(U.tokens,Z,U.wrapperEnvAssignments);if(U.head==="rm"&&dJ(U.tokens,Z)||cJ(U.tokens,U.head,Z,U.wrapperEnvAssignments,G,J,Q))return!0}continue}let B=f0(Y);if(B>0){if(W=B,Y.includes(Z))return!0;continue}if(Y.includes(Z))return!0}return!1}function r0($){let Z=new Set(["-L","-n","-P","-s","-a","-E","-R","-S","-e","-d","-J","--max-args","--max-procs","--max-chars","--arg-file","--eof","--delimiter","--max-lines","--process-slot-var"]),J=null,Q=1;while(Q<$.length){let X=$[Q];if(!X)break;if(X==="--")return{childStart:Q+1,replacementToken:J};if(X.startsWith("-")){if(X==="-I"){J=$[Q+1]??"{}",Q+=2;continue}if(X.startsWith("-I")&&X.length>2){J=X.slice(2),Q++;continue}if(X==="--replace"){J="{}",Q++;continue}if(X.startsWith("--replace=")){let W=X.slice(10);J=W===""?"{}":W,Q++;continue}if(X==="-J"){J=$[Q+1]??"{}",Q+=2;continue}if(Z.has(X))Q+=2;else Q++}else return{childStart:Q,replacementToken:J}}return{childStart:$.length,replacementToken:J}}var b2="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",f2="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",oj="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",tj="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",ej=/\{[^{}\s]*\}/,JQ=/\{\}|\{-?\d+\}/g,$_=["e","f","source","file","-e","-f","--source","--file"],Z_=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],J_=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),Q_=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),rJ=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),X_=new Set(["--workdir","--wd"]),nJ="__CC_SAFETY_NET_PARALLEL_SOURCE__",W_=new TextEncoder,z3=S.maxDerivedBytes+4*S.maxPlaceholderReplacements;function U1($,Z){for(let J of $){let Q=Z(J);if(Q)return Q}return null}function QQ($,Z){let J=$.map(E);if((Z.envAssignments?.has("PARALLEL")?Z.envAssignments.get("PARALLEL"):Z.environment.env.get("PARALLEL"))?.trim()){let O=a0(Z);if(O)return O}if(J.length===2&&(J[1]==="--version"||J[1]==="--help"))return null;let X=OQ(J),{template:W,jobs:K,runsRemotely:Y,envNames:B,readsCommandsFromInput:q,unsupported:U,workdir:G,dryRun:j}=X;if(U){let O=a0(Z);if(O)return O}if(q){let O=j_(Z);if(O)return O}if(G!==void 0&&Y){let O=a0(Z);if(O)return O}let H=F_(G,Z.cwd,Z.environment.paths);if(H===null){let O=a0(Z);if(O)return O}let _=Y?{...Z,cwd:void 0,originalCwd:void 0}:H===null||H===void 0||H===Z.cwd?Z:{...Z,cwd:H};if(j){let O=[...m1(W,_)];if((O.length===0?p9(B,Z.envAssignments,new Map).values:O.flatMap((L)=>p9(B,Z.envAssignments,L.envAssignments).values)).some(i9)){let L=a0(Z);if(L)return L}return null}if(W.length===0){if(B.length>0||K.some((L)=>L.length!==1)){let L=a0(Z);if(L)return L}let O=K.map((L)=>L[0]??"");V1(Z.budget,m9(O));let M=GQ(_.envAssignments,_.cwd,Y);return U1(O,(L)=>Z.analyzeNested(L,M))}return U1(m1(W,_),(O)=>K_(O,X,Z,_))}function K_($,Z,J,Q){let{jobs:X,templateHasPlaceholder:W,runsRemotely:K,usesStdin:Y,envNames:B}=Z,q=$.tokens,U={...Q,cwd:$.cwd,envAssignments:$.envAssignments},G=p9(B,J.envAssignments,$.envAssignments);if(G.entries.some((L)=>jQ(L.value))){let L=a0(J);if(L)return L}let j=G.entries.some((L)=>L.hasPlaceholder),H=W||j,_=Y&&H,O=GQ($.envAssignments,$.wrapperCwd,K||_);if(t.has($.head)){let L=()=>{if(!W||X.length===0)return null;return V1(J.budget,D3(q,X,"generic")),U1(X,(f)=>A0(q.map((A)=>W0(A,f)),U))};if(T1(q))return L();let D=Z0(q);if(D){if(_Q(D)){let I=n0(J);if(I)return I;if(X.length===0)return null;return V1(J.budget,$Q(D,X)),U1(X,(b)=>J.analyzeNested(W0(D,b),O))}if(p(D)){if(X.length>0)return V1(J.budget,$Q(D,X)),U1(X,(P)=>J.analyzeNested(W0(D,P),O));V1(J.budget,tJ(D));let I=R2(D);if(I?.[0]&&l(I[0])==="rm"&&p1(I)){let P=oJ(J);if(P)return P}let b=I?A0(I,U,{dynamicInput:Y,shellDynamicMatch:N("parallel.shell-dynamic",f2),rmDynamicMatch:N("parallel.rm-recursive-force-dynamic",b2)}):null;if(b)return b;return J.analyzeNested(D,O)}let f=!j&&(!W||X.length>0)?(X.length>0?X:[void 0]).map((I)=>F3(g(I===void 0?q:W?q.map((b)=>W0(b,I)):[...q,...I]),D)):[];if(f.some((I)=>I.kind==="dynamic")){let I=n0(J);if(I)return I}let A=f.flatMap((I)=>I.kind==="literal"?[I.source]:[]);if(A.length>0)return V1(J.budget,m9(A)),U1(A,(I)=>J.analyzeNested(I,O));V1(J.budget,O_(tJ(D),__(G.entries,X)));let F=S$(D);if(F&&G.entries.length>0){let I=ZQ(G,X,Q,K);if(I)return I}if(F){let I=n0(J);if(I)return I}let R=J.analyzeNested(D,O);if(R)return R;if(!F){let I=ZQ(G,X,Q,K);if(I)return I}if(H)return n0(J);return null}let z=Q0(g(q));if(z.kind==="dynamic"||z.kind==="literal"&&p(z.source))return n0(J)??L();if(z.kind==="literal")return L();if(X.length>0){let f=n0(J);if(f)return f;let A=L();if(A)return A;if(W)return null;let F=X.flatMap((R)=>R[0]===void 0?[]:[R[0]]);return V1(J.budget,m9(F)),U1(F,(R)=>J.analyzeNested(R,O))}if(H||Y)return n0(J)??L();return null}if($.head==="rm"&&p1(q)){if(W&&X.length>0)return V1(J.budget,D3(q,X,"rm")),U1(X,(D)=>l9(q.map((z)=>c9(z,D)),$.cwd,Q));if(X.length>0)return V1(J.budget,eJ(q,X)),U1(X,(D)=>l9([...q,...D],$.cwd,Q));let L=l9(q.flatMap((D,z)=>{if(z===0||!p(D))return[D];return D.startsWith("-")?[c9(D,[""])]:[]}),$.cwd,Q);if(L)return L;return oJ(J)}V1(J.budget,W&&X.length>0?D3(q,X,"generic"):X.length>0?eJ(q,X):YQ(q));let M=X.length>0?X:[void 0];return U1(M,(L)=>{let D=L===void 0?q:W?q.map((P)=>W0(P,L)):[...q,...L],z=N("parallel.shell-dynamic",f2),f=Y&&$.head==="find"?H_(D,Q):null,A=WQ(D,Y,J.policy?.rules??[],J.budget)??f?.customResult??null,F=l($.head),R=Y&&(F==="rm"&&d9(D)||F==="xargs"&&KQ(D)||f?.rmOptions===!0),I=Y&&(R||f?.executedSource===!0||f===null&&XQ(D,F)),b=A0(D,{...U,worktreeMode:K||Y||H?!1:J.worktreeMode},{dynamicInput:Y||H,dynamicRmInput:R,dynamicSourceInput:A!==null||I,shellDynamicMatch:z,dynamicSourceMatch:z,rmDynamicMatch:N("parallel.rm-recursive-force-dynamic",b2)});if(I){let P=T(z,J.policy);if(P)return P}return b??A??Q1(D,J.policy?.rules??[])})}function XQ($,Z){if(p($[0]??""))return!0;if(Z==="eval"||Z==="source"||Z===".")return!0;if(Z==="parallel"||Z==="xargs")return!0;if(t.has(Z))return q_($);if(Z==="git")return Y_($);if(Z==="find")return!0;if(F1.has(Z))return aJ($,$_,e$);if(N1(Z))return aJ($,Z_,u4);return!1}function d9($){let Z=$.indexOf("--"),J=$.slice(1,Z===-1?void 0:Z);if(!$.some(p))return Z===-1;return J.some((X)=>p(X)&&(X.startsWith("-")||_Q(X)))}function Y_($){if(B_($))return!0;let Z=c1($);if(Z.subcommand===null||p(Z.subcommand))return!0;if(!M3.has(Z.subcommand.toLowerCase()))return!1;let J=Z.rest.indexOf("--"),Q=Z.rest.slice(0,J===-1?void 0:J);if(!$.some(p))return J===-1;return Q.some(p)}function B_($){for(let Z=1;Z<$.length;Z++){let J=$[Z];if(!J||J==="--"||!J.startsWith("-"))return!1;if(J==="-c"||J==="--config-env"){if(p($[Z+1]??""))return!0;Z++;continue}if(J.startsWith("-c")&&J.length>2||J.startsWith("--config-env=")){if(p(J))return!0;continue}if(p(J))return!0}return!1}function q_($){if(T1($))return!1;let Z=Z0($);if(Z!==null)return p(Z);let J=Q0(g($));if(J.kind==="literal")return p(J.source);if(J.kind==="dynamic")return!0;return!$.some(p)}function aJ($,Z,J){let Q=J($);if(Q.some((W)=>p(W.value)))return!0;if(!$.some(p))return J([...$,nJ]).some((W)=>W.value===nJ);let X=new Set(Q.map((W)=>`${W.tokenIndex}\x00${W.kind}\x00${W.value}`));return Z.some((W)=>J($.map((K)=>W0(K,[W]))).some((K)=>!X.has(`${K.tokenIndex}\x00${K.kind}\x00${K.value}`)))}function WQ($,Z,J,Q){if(!Z||J.length===0)return null;let X=J.filter((K)=>l(K.command)===l($[0]??""));if(X.length===0)return null;let W=$.some(p);if(V1(Q,U_($,X,W)),!W)return U1(X,(K)=>Q1([...$,...K.subcommand?[K.subcommand]:[],...K.block_args],[K]));return U1(X,(K)=>{let Y=new Set([K.subcommand,...K.block_args].flatMap((B)=>B?G_($,B):[]));return U1(Y,(B)=>Q1($.map((q)=>W0(q,[B])),[K]))})}function U_($,Z,J){let Q=J?_1(e(Z.map((X)=>X.block_args.length+(X.subcommand?1:0)),S.maxChildAnalyses),2*Math.max($.length,1),S.maxChildAnalyses):Z.length;return{childAnalyses:Q,derivedTokens:_1(Q,$.length,S.maxDerivedTokens)}}function G_($,Z){return $.flatMap((J)=>{let Q=[...J.matchAll(/\{[^{}\s]*\}/g)];if(Q.length!==1)return[];let X=Q[0];if(!X||X.index===void 0)return[];let W=J.slice(0,X.index),K=J.slice(X.index+X[0].length);if(!Z.startsWith(W)||!Z.endsWith(K))return[Z];let Y=Z.slice(W.length,Z.length-K.length);return Y!==Z?[Z,Y]:[Z]})}function H_($,Z){let J={customResult:null,executedSource:!$.some(p),rmOptions:!1},Q=!1,X=0,W=null,K=()=>{if(!W?.some(p))return;for(let Y of m1(W,Z))J.executedSource||=XQ(Y.tokens,Y.head),J.rmOptions||=Y.head==="rm"&&d9(Y.tokens)||Y.head==="xargs"&&KQ(Y.tokens),J.customResult??=WQ(Y.tokens,!0,Z.policy?.rules??[],Z.budget)};for(let Y of $.slice(1)){if(!Q&&!Y.startsWith("-")&&Y!=="!"&&Y!=="("){J.executedSource||=p(Y);continue}if(Q=!0,W){if(Y===";"||Y==="+"){K(),W=null;continue}W.push(Y);continue}if(X>0){X--;continue}if(L0(Y)){W=[],J.executedSource||=p(Y);continue}let B=f0(Y);if(B>0){X=B,J.executedSource||=p(Y);continue}J.executedSource||=p(Y)}return K(),J}function KQ($){let Z=$.slice(r0($).childStart);return l(Z[0]??"")==="rm"&&d9(Z)}function I3($,Z){return(J)=>T(N($,Z),J.policy)}var n0=I3("parallel.shell-dynamic",f2),j_=I3("parallel.command-stream-dynamic",oj),a0=I3("parallel.command-stream-dynamic",tj),oJ=I3("parallel.rm-recursive-force-dynamic",b2);function l9($,Z,J){return T(E$(g($),{environment:J.environment,cwd:Z,originalCwd:J.originalCwd,strict:J.strict,paranoid:J.paranoidRm,allowTmpdirVar:J.allowTmpdirVar,tmpdirWordSplittingUnsafe:e1(J.envAssignments??new Map,J.environment),trustedTmpdirValue:O0(J.envAssignments??new Map,J.environment),protectedGitMetadata:J.protectedGitMetadata,policy:J.policy}),J.policy)}function m9($){return{childAnalyses:$.length,derivedTokens:$.length,derivedBytes:v$($)}}function tJ($){return YQ([$])}function YQ($){return{childAnalyses:1,derivedTokens:$.length,derivedBytes:v$($)}}function eJ($,Z){if(Z.length>S.maxChildAnalyses)return{childAnalyses:Z.length};return{childAnalyses:Z.length,derivedTokens:e(Z.map((J)=>$.length+J.length),S.maxDerivedTokens),derivedBytes:e([_1(v$($),Z.length,S.maxDerivedBytes),e(Z.map((J)=>v$(J)),S.maxDerivedBytes)],S.maxDerivedBytes)}}function $Q($,Z){return D3([$],Z,"generic")}function D3($,Z,J){if(Z.length>S.maxChildAnalyses)return{childAnalyses:Z.length};let Q=_1($.length,Z.length,S.maxDerivedTokens);if(Q>S.maxDerivedTokens)return{childAnalyses:Z.length,derivedTokens:Q};let X=UQ($.map((B)=>qQ(B,J))),W=_1(X.occurrences,Z.length,S.maxPlaceholderReplacements);if(W>S.maxPlaceholderReplacements)return{childAnalyses:Z.length,derivedTokens:Q,placeholderReplacements:W};if(BQ(X,Z,W))return{childAnalyses:Z.length,derivedTokens:Q,derivedBytes:S.maxDerivedBytes+1,placeholderReplacements:W};let K=J==="generic"?W0:c9,Y=e(Z.map((B)=>v$($.map((q)=>K(q,B)))),S.maxDerivedBytes);return{childAnalyses:Z.length,derivedTokens:Q,derivedBytes:Y,placeholderReplacements:W}}function BQ($,Z,J){let Q=S.maxDerivedBytes+4*J;return e([_1($.fixedBytes,Z.length,Q),_1($.occurrences,e(Z.map((X)=>X.reduce((W,K)=>Math.max(W,w$(K)),0)),Q),Q)],Q)>Q}function __($,Z){let J=$.filter((U)=>U.hasPlaceholder),Q=Math.max(Z.length,1),X=e(J.map((U)=>U.frequency),S.maxChildAnalyses),W=_1(X,Q,S.maxChildAnalyses),K=_1(X,Q,S.maxDerivedTokens);if(W>S.maxChildAnalyses||K>S.maxDerivedTokens)return{childAnalyses:W,derivedTokens:K};if(Z.length===0)return{childAnalyses:W,derivedTokens:K,derivedBytes:e(J.map((U)=>_1(w$(U.value),U.frequency,S.maxDerivedBytes)),S.maxDerivedBytes)};let Y=UQ(J.map((U)=>L_(qQ(U.value,"generic"),U.frequency))),B=_1(Y.occurrences,Q,S.maxPlaceholderReplacements);if(B>S.maxPlaceholderReplacements)return{childAnalyses:W,placeholderReplacements:B};if(BQ(Y,Z,B))return{childAnalyses:W,derivedTokens:K,derivedBytes:S.maxDerivedBytes+1,placeholderReplacements:B};let q=e(J.map((U)=>_1(v$(Z.map((G)=>W0(U.value,G))),U.frequency,S.maxDerivedBytes)),S.maxDerivedBytes);return{childAnalyses:W,derivedTokens:K,derivedBytes:q,placeholderReplacements:B}}function O_($,Z){return{childAnalyses:e([$.childAnalyses??0,Z.childAnalyses??0],S.maxChildAnalyses),derivedTokens:e([$.derivedTokens??0,Z.derivedTokens??0],S.maxDerivedTokens),derivedBytes:e([$.derivedBytes??0,Z.derivedBytes??0],S.maxDerivedBytes),placeholderReplacements:e([$.placeholderReplacements??0,Z.placeholderReplacements??0],S.maxPlaceholderReplacements)}}function qQ($,Z){let J=Z==="generic"?$.matchAll(/\{[^{}\s]*\}/g):$.matchAll(JQ),Q=0,X=0,W=0;for(let K of J){if(Q>=S.maxPlaceholderReplacements)return{occurrences:S.maxPlaceholderReplacements+1,fixedBytes:0};X=e([X,w$($.slice(W,K.index))],z3),Q++,W=K.index+K[0].length}return{occurrences:Q,fixedBytes:Q===0?w$($):e([X,w$($.slice(W))],z3)}}function L_($,Z){return{occurrences:_1($.occurrences,Z,S.maxPlaceholderReplacements),fixedBytes:_1($.fixedBytes,Z,z3)}}function UQ($){return{occurrences:e($.map((Z)=>Z.occurrences),S.maxPlaceholderReplacements),fixedBytes:e($.map((Z)=>Z.fixedBytes),z3)}}function v$($,Z=S.maxDerivedBytes){return e($.map(w$),Z)}function w$($){return W_.encode($).byteLength}function e($,Z){let J=0;for(let Q of $){if(!Number.isSafeInteger(Q)||Q<0||Q>Z-J)return Z+1;J+=Q}return J}function _1($,Z,J){if(!Number.isSafeInteger($)||!Number.isSafeInteger(Z)||$<0||Z<0||$!==0&&Z>Math.floor(J/$))return J+1;return $*Z}function p9($,Z,J){let Q=[];for(let X of $){let W=J.get(X)??Z?.get(X);if(W!==void 0)Q.push(W)}return Q.push(...J.values()),M_(Q)}function M_($){let Z=new Map;for(let Q of $)Z.set(Q,(Z.get(Q)??0)+1);let J=[...Z].map(([Q,X])=>({value:Q,frequency:X,hasPlaceholder:p(Q)}));return{values:$,entries:J,byValue:new Map(J.map((Q)=>[Q.value,Q]))}}function ZQ($,Z,J,Q){return U1($.values,(X)=>{if(!$.byValue.get(X)?.hasPlaceholder)return null;let W=Z.length>0?Z:[void 0];return U1(W,(K)=>{let Y=K===void 0?X:W0(X,K);return J.analyzeNested(Y,{envAssignments:J.envAssignments,effectiveCwd:Q?null:J.cwd})})})}function GQ($,Z,J){let Q={};if($)Q.envAssignments=$;if(J)return Q.effectiveCwd=null,Q.worktreeMode=!1,Q;if(Z!==void 0)Q.effectiveCwd=Z;return Object.keys(Q).length>0?Q:void 0}function W0($,Z){return $.replace(/\{[^{}\s]*\}/g,(J)=>HQ(J,Z))}function c9($,Z){return $.replace(JQ,(J)=>HQ(J,Z))}function HQ($,Z){let J=/^\{(-?\d+)[^{}\s]*\}$/.exec($)?.[1];if(J===void 0)return Z[0]??"";let Q=Number(J),X=Q>0?Q-1:Z.length+Q;return Z[X]??""}function p($){return ej.test($)}function jQ($){if(i9($))return!0;for(let Z of $.matchAll(/\{[^{}\s]*\}/g))if(!/^(?:\{\}|\{-?\d+\})$/.test(Z[0]))return!0;return!1}function i9($){let Z=$.indexOf("{=");return Z!==-1&&$.indexOf("=}",Z+2)!==-1}function _Q($){return/^\{[^{}\s]*\}$/.test($)}function OQ($){let Z=1,J=[],Q=$.length,X=-1,W=!1,K=!1,Y=!1,B,q=$.some((O)=>O==="::::"||O==="::::+"||O===":::+"),U=[];while(Z<$.length){let O=$[Z];if(O===void 0)break;if(O===":::"){X=Z;break}if(O==="--"){let f=R9($,Z+1);J.push(...f.templateTokens),Q=Z+1,X=f.markerIndex;break}if(!O.startsWith("-")){let f=R9($,Z);J.push(...f.templateTokens),Q=Z,X=f.markerIndex;break}let M=$[Z+1],L=O.indexOf("="),D=L===-1?O:O.slice(0,L),z=L===-1?void 0:O.slice(L+1);if(O==="--dry-run"){Y=!0,Z++;continue}if(O==="-I"||O.startsWith("-I")&&O.length>2){q||=(O==="-I"?M:O.slice(2))!=="{}",Z+=O==="-I"?2:1;continue}if(O==="--replace"||O==="-i"){q=!0,Z+=2;continue}if(D==="--replace"||O.startsWith("-i")&&O.length>2){let f=D==="--replace"?z:O.slice(2);q||=f!==""&&f!=="{}",Z++;continue}if(O==="-a"||Q_.has(D)){q=!0,Z+=z===void 0?2:1;continue}if(O==="--pipe"||O==="--pipepart"){K=!0,Z++;continue}if(D==="--env"){U.push(...V_(z??M)),Z+=z===void 0?2:1;continue}if(rJ.has(D)||O.startsWith("-S")&&O.length>2){W=!0,Z+=rJ.has(O)?2:1;continue}if(X_.has(D)){let f=z??M;if(f===void 0||f===":::"||f==="--"){q=!0,Z++;continue}B=f,q||=z!==void 0&&f==="",Z+=z===void 0?2:1;continue}if(O.startsWith("-j")&&O.length>2&&/^\d+$/.test(O.slice(2))){Z++;continue}if(O.startsWith("--")&&z!==void 0){Z++;continue}if(J_.has(O)){if(M===void 0||M===":::"||M==="--"){q=!0,Z++;continue}Z+=2;continue}Z+=O==="-j"||O==="--jobs"?2:1}q||=J.some(Y?i9:jQ);let G=[];if(X!==-1){let O=[];for(let M=X+1;M<$.length;M++){let L=$[M];if(L===":::"){G.push(O),O=[];continue}if(L!==void 0)O.push(L)}G.push(O)}let j=N_(G),H=J.some(p),_=J.length===0&&X===-1;return{template:J,jobs:j,childStart:Q,templateHasPlaceholder:H,runsRemotely:W,usesStdin:K||X===-1,envNames:U,readsCommandsFromInput:_,unsupported:q,workdir:B,dryRun:Y}}function F_($,Z,J){if($===void 0)return;if($==="..."||/[{}$`*?~[]/.test($))return null;if(!Z&&!aj($))return null;try{return b0(Z??$,$,J)}catch{return null}}function N_($){if($.length===0||$.some((J)=>J.length===0))return[];let Z=[[]];for(let J of $){if(J.length===1){let X=J[0];if(X===void 0)return[];for(let W of Z)W.push(X);continue}let Q=[];for(let X of Z)for(let W of J)if(Q.push([...X,W]),Q.length>S.maxChildAnalyses)return Q;Z=Q}return Z}function V_($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}function LQ($){return OQ($).childStart}var R_="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",b3="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function r9($){return $?.parts.some((Z)=>Z.provenance==="command-substitution")??!1}function s9($){return $?.parts.some((Z)=>Z.provenance==="literal"&&Z.raw.replace(/^["']/,"").startsWith("-"))??!1}function FQ($,Z,J,Q,X=!1,W){let Y=(f6($,Z)||Q&&$!=="powershell"&&Z[0]?.provenance==="variable")&&o(W,"shell.dynamic-executable",X)?N("shell.dynamic-executable",R_):null;return T(Y,W)??NQ($,Z,J,X,W)}function NQ($,Z,J,Q,X){if(Z.length<2)return null;let W=Z.flatMap((Y,B)=>r9(Y)?[B]:[]);if(W.length===0)return null;let K=l(Z[0]?.text??"");if(K==="git"){let Y=f$($,Z),B=z_(Y);if(o(X,"shell.dynamic-structure",Q)&&W.some((G)=>G<=B))return T(N("shell.dynamic-structure",b3),X);if(T(A$(Y,{env:J.env}),X))return null;let q=Z[B]?.text.toLowerCase(),U=Y.findIndex((G,j)=>j>B&&E(G)==="--");if(o(X,"shell.dynamic-structure",Q)&&q&&M3.has(q)&&W.some((G)=>G>B&&(U===-1||G<U)))return T(N("shell.dynamic-structure",b3),X);return null}if(K==="find")return o(X,"shell.dynamic-structure",Q)&&I_(Z)?T(N("shell.dynamic-structure",b3),X):null;if(K==="rm"){let Y=Z.findIndex((q,U)=>U>0&&E(q)==="--"),B=p1(Z.map(E));return o(X,"shell.dynamic-structure",Q)&&W.some((q)=>(Y===-1||q<Y)&&(q<Z.length-1||!B))?T(N("shell.dynamic-structure",b3),X):null}if(K==="xargs")return MQ($,Z.slice(r0(Z.map(E)).childStart),"xargs",J,Q,X);if(K==="parallel")return MQ($,Z.slice(LQ(Z.map(E))),"parallel",J,Q,X);return null}function MQ($,Z,J,Q,X,W){if(Z.length===0)return null;let K=D_(Z,Q);if(f6($,K)){let B=T(N(`${J}.shell-dynamic`,J==="xargs"?k9:f2),W);if(B)return B}let Y=NQ($,K,Q,X,W);if(Y)return Y;if(K[0]?.text==="rm"&&K.slice(1).some((B)=>r9(B)&&s9(B)))return T(N(`${J}.rm-recursive-force-dynamic`,J==="xargs"?g9:b2),W);return null}function D_($,Z){let J=p0($,Z),Q=J.rewritten?g(J.words.map(E)):J.words,X=Q[0];return X&&E(X)==="busybox"?Q.slice(1):Q}function z_($){let Z=1;while(Z<$.length){let J=$[Z],Q=J?E(J):"";if(a1.has(Q)){Z+=2;continue}if(Q.startsWith("-")){Z++;continue}return Z}return Z}function I_($){let Z=!1,J=0,Q=!1,X=!1;for(let W=1;W<$.length;W++){let K=$[W];if(!K)continue;let Y=r9(K);if(J>0){J--;continue}if(X){if(K.text===";"||K.text==="+"){X=!1,Z=!0,Q=!1;continue}if(Y&&(Q||s9(K)))return!0;Q=!1;continue}if(!Z&&!K.text.startsWith("-")){if(Y&&(W>1||s9(K)))return!0;continue}if(Z=!0,Y)return!0;let B=f0(K.text);if(B>0){J=B;continue}if(L0(K.text))X=!0,Q=!0}return!1}function n9($,Z){return $.some((J)=>{if(J.value==="-"&&(J.kind==="main-script"||J.kind==="program-file"))return!0;return!W3(Z[J.tokenIndex],J.value)})}var b_="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",f_="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",P_="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function VQ($,Z){let J=Z.slice(1);if($==="dd"&&J.some((Q)=>/^of=\/dev\/.+/.test(Q)))return N("dd.device-write",b_);if(($==="mkfs"||$.startsWith("mkfs."))&&J.some((Q)=>Q.startsWith("/dev/")))return N("mkfs.device",f_);if($==="shred"&&J.length>0)return N("shred.target",P_);return null}var DQ=[{heads:new Set(["rm","rmdir"]),analyze:($)=>E$($.words,{environment:$.options.environment,cwd:$.cwd,originalCwd:$.originalCwd,strict:$.options.strict,paranoid:$.options.paranoidRm,allowTmpdirVar:$.allowTmpdirVar,tmpdirWordSplittingUnsafe:e1($.envAssignments,$.options.environment),trustedTmpdirValue:O0($.envAssignments,$.options.environment),protectedGitMetadata:$.options.protectedGitMetadata,policy:$.options.policy})},{heads:new Set(["git"]),analyze:($)=>A$($.words,a9($))},{heads:new Set(["find"]),analyze:($)=>_3($.words,{environment:$.options.environment,cwd:$.cwd,originalCwd:$.originalCwd,strict:$.options.strict,allowTmpdirVar:$.allowTmpdirVar,tmpdirWordSplittingUnsafe:e1($.envAssignments,$.options.environment),trustedTmpdirValue:O0($.envAssignments,$.options.environment),protectedGitMetadata:$.options.protectedGitMetadata,derivedCommandWorkBudget:$.options.derivedCommandWorkBudget,envAssignments:$.envAssignments,policy:$.options.policy,analyzeTokens:$.analyzeChildTokens,analyzeNested:(Z,J)=>o0($.options.analyzeNested(Z,J))})},{heads:new Set(["xargs"]),analyze:($)=>pJ($.words,{...RQ($),analyzeNested:(Z,J)=>o0($.options.analyzeNested(Z,J))})},{heads:new Set(["parallel"]),analyze:($)=>QQ($.words,{...RQ($),budget:$.options.parallelBudget,analyzeNested:(Z,J)=>o0($.options.analyzeNested(Z,J))})}];function RQ($){return{environment:$.options.environment,cwd:$.cwd,originalCwd:$.originalCwd,strict:$.options.strict,paranoidRm:$.options.paranoidRm,paranoidInterpreters:$.options.paranoidInterpreters,allowTmpdirVar:$.allowTmpdirVar,protectedGitMetadata:$.options.protectedGitMetadata,derivedCommandWorkBudget:$.options.derivedCommandWorkBudget,envAssignments:$.envAssignments,worktreeMode:$.options.worktreeMode,policy:$.options.policy,scanWork:$.options.scanWork}}function o0($){return $?{id:$.ruleId??"",reason:$.reason,intent:$.intent??"manual_only"}:null}function a9($){return{env:$.options.environment.env,cwd:$.cwd,dynamicArguments:$.dynamicArguments,envAssignments:$.envAssignments,policy:$.options.policy,worktreeMode:$.options.worktreeMode}}var fQ="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function PQ($){return DQ.find((Z)=>Z.heads.has($))?.analyze}function P2($,Z,J){let Q=J.trace;if($.length===0)return null;let X=J.commandView?.dialect??"posix",W=(C)=>C.map((v)=>X==="posix"?E(v):v.text),K=J.effectiveCwd===null,Y=K?void 0:J.effectiveCwd??J.cwd,B=K?void 0:J.cwd,q=U3($);if(q.envAssignments.size>0)Q?.recordSegment({type:"env-strip",input:W($),envVars:[...q.envAssignments.keys()],output:W(q.words)});let U=p0(q.words,J.environment,Y,new Map([...J.envAssignments??[],...q.envAssignments]));if(U.unverifiableEnvSplit)throw new m0;let G=U.rewritten?g(W(U.words)):f$(X,U.words),j=W(G),H={...J,wrapperNormalizationBudget:J.wrapperNormalizationBudget??{iterations:0}};if(Q&&q.words.length>G.length){let C=W(q.words);Q.recordSegment({type:"leading-tokens-stripped",input:C,removed:C.slice(0,C.length-G.length),output:j})}let _=new Map([...J.envAssignments??[],...q.envAssignments,...U.envAssignments]),O=j[0];if(!O)return null;if(l0(O))throw new C1;let M=l(O),L=U.cwd===null?void 0:U.cwd??Y,D=U.cwd===null?void 0:B,z=U.cwd===void 0?J.effectiveCwd:U.cwd,f=!L2(_,J.environment),A=FQ(X,U.words,J.environment,Z===0,J.strict,J.policy);if(A)return Q?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:A.reason}),M0(A);let F=x4(j,J.policy);if(F){for(let C of[F.childIndex,...F.alternativeChildIndices]){zQ(H.wrapperNormalizationBudget);let v=G.slice(C);Q?.recordSegment({type:"transparent-wrapper",wrapper:F.wrapper,output:W(v)});let n=P2(v,Z,{...H,effectiveCwd:z,envAssignments:_});if(n)return n}return null}let R=M==="eval"?T$(G):M==="trap"?uJ(G):void 0;if(R?.kind==="dynamic"&&(J.strict||!J.commandView||!u9(J.commandView)))return S1(Q);if(R?.kind==="literal"){Q?.recordSegment({type:"recurse",reason:M==="eval"?"shell-eval":"shell-trap",innerCommand:R.source,depth:Z+1});let C=J.analyzeNested(R.source,{effectiveCwd:z,envAssignments:_,functionDefinitions:J.functionDefinitions});if(C)return C}if(AQ(O,M)){if(T1(j))return null;let C=C_(j,_,z,J,Q,Z);if(C)return C;let v=Z0(j);if(v){let J$=F3(G,v);if(J$.kind==="dynamic")return S1(Q);let x3=J$.kind==="literal"?J$.source:v,jZ=A_(x3);Q?.recordSegment({type:"shell-wrapper",wrapper:M,innerCommand:jZ}),Q?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:jZ,depth:Z+1});let _Z=J.analyzeNested(x3,{effectiveCwd:z,envAssignments:_});if(_Z)return _Z;return S$(x3)?S1(Q):null}let n=Q0(G);if(n.kind==="dynamic")return S1(Q);if(n.kind==="literal")return C3(n.source,z,_,J,Q,Z);let $1=hJ(G,J.commandView?.redirections??[],J.hasPipelineInput??!1,J.literalShellInput);if($1.kind==="dynamic")return S1(Q);if($1.kind==="literal")return Q?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:$1.source,depth:Z+1}),J.analyzeNested($1.source,{effectiveCwd:z,envAssignments:_})}if(M==="source"||M==="."){let C=j[1]==="-p"?2:null;if(C!==null){let J$=J.commandView?G[C]:void 0;if(!J$)return null;if(J$.provenance!=="literal")return S1(Q)}let v=C===null?1:3,n=j[v]==="--"?v+1:v,$1=J.commandView?G[n]:void 0;if(!$1)return null;if($1.provenance==="literal")return C3($1.text,z,_,J,Q,Z);if(J.strict||!J.commandView||!u9(J.commandView))return S1(Q)}if(F1.has(M)){if(J.strict&&n9(e$(j),G))return S1(Q);let C=I4(j,(n)=>o0(J.analyzeNested(n,{effectiveCwd:z,envAssignments:_}))),v=T(C,J.policy);if(v)return Q?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:v.reason}),M0(v)}if(N1(M)){if(J.strict&&n9(u4(j),G))return S1(Q);let C=v4(j);if(C){let v=o(J.policy,"interpreter.one-liner-paranoid",!!J.paranoidInterpreters);if(Q?.recordSegment({type:"interpreter",interpreter:M,codeArg:C,paranoidBlocked:v}),v){let $1=T(N("interpreter.one-liner-paranoid",O$),J.policy);if($1)return M0($1)}if(g4(M,C))return null;Q?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:C,depth:Z+1});let n=J.analyzeNested(C,{effectiveCwd:z,envAssignments:_});if(n&&n.ruleId!=="raw-text.dangerous-command"&&(n.reason!==D0||H$(C)))return n;if(L$(C,J.scanWork)){let $1=T(N("interpreter.dangerous-command",x0),J.policy);if($1)return Q?.recordSegment({type:"dangerous-text",token:C,matched:!0,reason:x0}),M0($1)}Q=void 0}}if(M==="busybox"&&j.length>1)return zQ(H.wrapperNormalizationBudget),Q?.recordSegment({type:"busybox",subcommand:j[1]??"unknown"}),Q?.recordSegment({type:"recurse",reason:"busybox",innerCommand:j.slice(1).join(" "),depth:Z+1}),P2(G.slice(1),Z,{...H,effectiveCwd:z,envAssignments:_});let I=T(VQ(M,j),J.policy);if(I)return Q?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:I.reason}),M0(I);let b=Q===H.trace?H:{...H,trace:Q},P={words:G,head:M,cwd:L,originalCwd:D,envAssignments:_,allowTmpdirVar:f,dynamicArguments:U.words.some((C)=>C.provenance==="command-substitution"),depth:Z,effectiveCwd:z,options:b,analyzeChildTokens:(C,v)=>o0(P2(g(C),Z+1,{...b,commandView:void 0,effectiveCwd:v,envAssignments:_}))??Q1(C,b.policy.rules)},y=PQ(M);if(M==="rm"||M==="xargs"||M==="parallel")Q?.recordSegment({type:"tmpdir-check",tmpdirValue:_.has("TMPDIR")||J.environment.env.has("TMPDIR")?"<redacted>":null,isOverriddenToNonTemp:!f,allowTmpdirVar:f});let w=Q&&M==="git"?bJ(P.words,a9(P)):void 0,x=IQ(w?w.match:y?.(P)??null,J.policy);if(Q)E_(P,x,w?.relaxation??null);if(x)return M0(x);let Y1=y!==void 0;if(!Y1)if(!J4.has(M)){let C=Q?[]:void 0;for(let v=1;v<j.length;v++){let n=j[v];if(!n)continue;C?.push(n);let $1=IQ(T_(P,j,v),J.policy);if($1)return Q?.recordSegment({type:"fallback-scan",tokensScanned:C??[],embeddedCommandFound:l(n)}),M0($1)}Q?.recordSegment({type:"fallback-scan",tokensScanned:C??[]})}else Q?.recordSegment({type:"fallback-scan",tokensScanned:[]});else Q?.recordSegment({type:"fallback-scan",tokensScanned:[]});if(Z===0||!Y1){let C=Q1(j,J.policy.rules);if(Q?.recordSegment({type:"custom-rules-check",rulesChecked:J.policy.rules.length>0,matched:!!C,reason:C?.reason}),C)return M0(C)}else Q?.recordSegment({type:"custom-rules-check",rulesChecked:!1,matched:!1});return null}function C_($,Z,J,Q,X,W){let K=TJ($);if(K.argvSource?.kind==="absent")return S1(X);if(K.argvSourceApplies&&K.argvSource){let B=C3(K.argvSource.value,J,Z,Q,X,W,!0);if(B)return B}if(!K.envSourceApplies||!K.envName)return null;let Y=Z.get(K.envName);if(!Y)return null;return C3(Y,J,Z,Q,X,W,!0)}function C3($,Z,J,Q,X,W,K=!1){if(K&&/[$`*?[\]]/.test($))return S1(X);let Y=O2($,Z,Q.environment.paths),B=Y?Q.literalHeredocFiles?.get(Y):void 0;if(B===void 0)return K?S1(X):null;return t1(Q.derivedCommandWorkBudget,1),X?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:B,depth:W+1}),Q.analyzeNested(B,{effectiveCwd:Z,envAssignments:J})}function A_($){let Z=$[0];return $.length>=2&&(Z==='"'||Z==="'")&&$.at(-1)===Z?$.slice(1,-1):$}function E_($,Z,J){let Q={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[$.head];if(!Q)return;if($.options.trace?.recordSegment({type:"rule-check",rule:Q,matched:!!Z||!!J,reason:Z?.reason??J?.originalReason}),J)$.options.trace?.recordSegment({type:"worktree-relaxation",originalReason:J.originalReason,gitCwd:J.gitCwd})}function zQ($){if($.iterations>=Y$)throw new C1;$.iterations++}function M0($){return{reason:$.reason,ruleId:$.id||void 0,intent:$.intent}}function S1($){return $?.recordSegment({type:"error",message:fQ}),M0(CQ())}function CQ(){return{id:"",reason:fQ,intent:"stop_and_explain"}}function AQ($,Z){return t.has(Z)||$==="$SHELL"||$==="${SHELL}"||t.has(u(Z))}function T_($,Z,J){let Q=m1(Z.slice(J),{environment:$.options.environment,cwd:$.cwd,envAssignments:$.envAssignments,policy:$.options.policy});for(let X of Q){let W=S_($,J,X);if(W)return W}return null}function S_($,Z,J){let Q=J.tokens[0];if(!Q)return null;let X=l(Q);if(AQ(Q,X)){t1($.options.derivedCommandWorkBudget,$.words.length-Z);let B=J.tokens;if(T1(B))return null;let q=Z0(B);if(!q){if(Q0(g(B)).kind==="dynamic")return CQ();return P3($,J)}let U=$.options.analyzeNested(q,{effectiveCwd:J.wrapperCwd===void 0?$.effectiveCwd:J.wrapperCwd,envAssignments:J.envAssignments});return U?o0(U):P3($,J)}let W=PQ(X);if(!W||X==="xargs"||X==="parallel"){if(J.wrappedByTransparent&&$.options.policy.rules.length>0)t1($.options.derivedCommandWorkBudget,$.words.length-Z);return P3($,J)}t1($.options.derivedCommandWorkBudget,$.words.length-Z);let K=[X,...J.tokens.slice(1)],Y={...$,words:g(K),head:X,cwd:J.cwd,originalCwd:J.wrapperCwd===null?void 0:$.originalCwd,envAssignments:J.envAssignments,allowTmpdirVar:!L2(J.envAssignments,$.options.environment),effectiveCwd:J.wrapperCwd===void 0?$.effectiveCwd:J.wrapperCwd,options:X==="git"?{...$.options,worktreeMode:!1}:$.options};return W(Y)??P3($,J)}function P3($,Z){return Z.wrappedByTransparent?Q1(Z.tokens,$.options.policy.rules):null}function IQ($,Z){return $?.id.startsWith("custom.")?$:T($,Z)}var y_=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,w_=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function v_($,Z){let J=SQ($,Z);if(J.length===0)return!1;let Q=J[TQ(J)];if(Q==="cd"||Q==="pushd"||Q==="popd")return!0;return y_.test($.join(" "))}function EQ($,Z,J,Q){if($.dialect==="powershell"){let Y=u_($.words,Q);if(Y.kind==="none")return;if(!Z||Y.kind==="unknown")return null;return bQ(x_(Y.target),Z,J.paths)}let X=$.words.map(E);if(!v_(X,J))return;if(!Z)return null;let W=SQ(X,J,Z),K=TQ(W);if(K===-1||W[K]!=="cd")return null;return bQ(W[K+1],Z,J.paths)}function bQ($,Z,J){if(!$||$==="-"||$.includes("$")||$.includes("`"))return null;try{return l_(b0(Z,$,J),Z,J)?Z:null}catch{return null}}function u_($,Z){let J=h_($[0])?1:0,Q=$[J];if(!g_(Q,J===1))return{kind:"none"};let X=Q.text.toLowerCase(),W=X.split(/[\\/]/).pop()??X;if(!w_.has(W))return{kind:"none"};if(X!==W||W==="pop-location"||W==="popd")return{kind:"unknown"};return k_($.slice(J+1),Z)}function h_($){return $?.provenance==="literal"&&!$.quoted&&$.raw===$.text&&($.text==="&"||$.text===".")}function g_($,Z){return $?.provenance==="literal"&&(Z||!$.quoted&&$.raw===$.text)}function k_($,Z){let J;for(let Q of $){if(Q.provenance!=="literal"||J!==void 0)return{kind:"unknown"};J=Q.text}if(J!==void 0)return{kind:"target",target:J};return Z===void 0?{kind:"unknown"}:{kind:"target",target:Z}}function x_($){return $.includes("::")?void 0:$.replaceAll("\\","/")}function TQ($){let Z=0;if($[0]==="builtin"&&$.length>1)Z=1;if($[Z]!=="time")return Z;let J=Z+1;while($[J]?.startsWith("-"))J++;return J}function SQ($,Z,J){let Q=m_($);return A1([...Q],Z,J)}function l_($,Z,J){let Q=J.realpath($),X=J.realpath(Z);if(Q===null||X===null)return f3($)===f3(Z);return f3(Q)===f3(X)}function m_($){let Z=0;while(Z<$.length){let J=$[Z];if(J==="{"||J==="("||J==="$(")Z++;else break}return $.slice(Z)}var C2="TMPDIR",A2="IFS",p_=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,o9=/^[A-Za-z_][A-Za-z0-9_]*$/;function wQ($,Z){let J=r_($,Z);return{env:$,effectiveEnvAssignments:J,shellAssignments:new Map,exportedNames:n_($,J),allexport:!1,keywordExport:!1}}function vQ($){return{env:$.env,effectiveEnvAssignments:$.effectiveEnvAssignments?new Map($.effectiveEnvAssignments):void 0,shellAssignments:new Map($.shellAssignments),exportedNames:new Set($.exportedNames),allexport:$.allexport,keywordExport:$.keywordExport}}function t9($,Z){let J=c_($,Z);if(!J)return;let{command:Q,commandIndex:X,leadingAssignments:W,prefixAssignmentsPersist:K}=J;if(Q===null){for(let B of W.values())yQ(Z,B);return}if(K)for(let B of W.values())Z.shellAssignments.set(B.name,B.value),Z.exportedNames.add(B.name),E0(Z,B);if(Q==="set"){let B=JO($,X);if(B.allexport!==null)Z.allexport=B.allexport;if(B.keywordExport!==null)Z.keywordExport=B.keywordExport;return}if(Q==="unset"){let B=e_($,X);if(B===null)return;for(let q of $.slice(B))t_(Z,q);return}if(Q!=="export"&&Q!=="typeset"&&Q!=="declare"&&Q!=="readonly")return;for(let B of W.values())yQ(Z,B);if(Q==="export"){let B=$O($,X);if(B===null)return;for(let q of $.slice(B))a_(Z,q);return}let Y=ZO($,X);if(Y===null)return;for(let B of $.slice(Y.operandsStart))o_(Z,B,Y.exports,Q==="readonly"?W:void 0)}function uQ($,Z){if(!Z.keywordExport)return Z.effectiveEnvAssignments;let J=null,Q=T3(Z);for(let X of $){let W=E3(X,Q,Z.env);if(!W)continue;J??=new Map(Z.effectiveEnvAssignments??[]),J.set(W.name,W.value),Q.set(W.name,W.value)}return J??Z.effectiveEnvAssignments}function c_($,Z){let J=new Map,Q=0;while(Q<$.length){let Y=$[Q];if(!Y)return null;let B=E3(Y,T3(Z,J),Z.env);if(!B)break;J.set(B.name,B),Q++}if(Q>=$.length)return{command:null,commandIndex:Q,leadingAssignments:J,prefixAssignmentsPersist:!1};let X=Q,W=Q,K=$[W]??null;while(K==="builtin"||K==="command"||K==="time"){if(K==="builtin"){if(W++,$[W]==="--")W++;K=$[W]??null;continue}if(K==="command"){let B=d_($,W);if(!B)return null;W=B.commandIndex,K=B.command;continue}let Y=i_($,W);if(!Y)return null;W=Y.commandIndex,K=Y.command}if(K===null)return null;return{command:K,commandIndex:W,leadingAssignments:J,prefixAssignmentsPersist:W===X&&(K==="unset"||K==="set"||K==="export"||K==="readonly")}}function d_($,Z){return hQ($,Z,(J)=>{if(J==="-p")return"skip";return J==="-v"||J==="-V"?"abort":"stop"})}function i_($,Z){return hQ($,Z,(J)=>J.startsWith("-")?"skip":"stop")}function hQ($,Z,J){let Q=Z+1;while(Q<$.length){let W=$[Q];if(!W)return null;if(W==="--"){Q++;break}let K=J(W);if(K==="abort")return null;if(K==="skip"){Q++;continue}break}let X=$[Q];return X?{command:X,commandIndex:Q}:null}function E3($,Z,J){return x1($)??s_($,Z,J)}function s_($,Z,J){let Q=P4($,J,Z);if(Q)return Q;let X=$.match(p_)?.[1];if(!X)return null;let W=$.indexOf("=");return{name:X,value:`${Z.has(X)?Z.get(X):J.get(X)??""}${$.slice(W+1)}`}}function A3($){return $===C2||$===A2||g6($)}function T3($,Z){return new Map([...$.effectiveEnvAssignments??[],...$.shellAssignments,...[...Z?.values()??[]].map((J)=>[J.name,J.value])])}function r_($,Z){let J=[...b4,C2,A2].map((Q)=>{let X=$.get(Q);return X===void 0?null:[Q,X]}).filter((Q)=>Q!==null);if(J.length===0)return Z;return new Map([...J,...Z??[]])}function n_($,Z){let J=new Set;for(let Q of $.keys())if(A3(Q))J.add(Q);for(let Q of Z?.keys()??[])if(A3(Q))J.add(Q);return J}function yQ($,Z){if($.shellAssignments.set(Z.name,Z.value),Z.name===C2||Z.name===A2||$.allexport||$.exportedNames.has(Z.name))E0($,Z)}function E0($,Z){let J=new Map($.effectiveEnvAssignments??[]);J.set(Z.name,Z.value),$.effectiveEnvAssignments=J}function a_($,Z){let J=E3(Z,T3($),$.env);if(J){$.shellAssignments.set(J.name,J.value),$.exportedNames.add(J.name),E0($,J);return}if(o9.test(Z))gQ($,Z)}function o_($,Z,J,Q){let X=E3(Z,T3($),$.env);if(X){if($.shellAssignments.set(X.name,X.value),J)$.exportedNames.add(X.name),E0($,X);else if(X.name===C2||X.name===A2||$.allexport||$.exportedNames.has(X.name))E0($,X);return}let W=Q?.get(Z);if(W){$.exportedNames.add(Z),E0($,W);return}if(J&&o9.test(Z))gQ($,Z)}function gQ($,Z){$.exportedNames.add(Z),E0($,{name:Z,value:$.shellAssignments.get(Z)??$.effectiveEnvAssignments?.get(Z)??$.env.get(Z)??""})}function t_($,Z){if(!A3(Z)&&!o9.test(Z))return;if($.shellAssignments.set(Z,""),$.exportedNames.delete(Z),!A3(Z)||Z===C2||Z===A2||$2(Z)){E0($,{name:Z,value:""});return}if(!$.effectiveEnvAssignments?.has(Z))return;let J=new Map($.effectiveEnvAssignments);J.delete(Z),$.effectiveEnvAssignments=J.size===0?void 0:J}function e_($,Z){return kQ($,Z,(J)=>J==="-v")}function $O($,Z){return kQ($,Z,(J)=>J==="-p")}function kQ($,Z,J){let Q=Z+1;while(Q<$.length){let X=$[Q];if(!X)return null;if(X==="--")return Q+1;if(J(X)){Q++;continue}if(X.startsWith("-"))return null;return Q}return Q}function ZO($,Z){let J=Z+1,Q=!1;while(J<$.length){let X=$[J];if(!X)return null;if(X==="--")return{operandsStart:J+1,exports:Q};if(X.startsWith("-")){if(X.slice(1).includes("x"))Q=!0;J++;continue}if(X.startsWith("+")){if(X.slice(1).includes("x"))Q=!1;J++;continue}return{operandsStart:J,exports:Q}}return{operandsStart:J,exports:Q}}function JO($,Z){let J={allexport:null,keywordExport:null},Q=Z+1;while(Q<$.length){let X=$[Q];if(!X)return J;if(X==="--")return J;if(X==="-o"||X==="+o"){if($[Q+1]==="allexport")J.allexport=X==="-o";if($[Q+1]==="keyword")J.keywordExport=X==="-o";Q+=2;continue}if(X.startsWith("-")&&X.length>1){let W=X.slice(1);if(W.includes("a"))J.allexport=!0;if(W.includes("k"))J.keywordExport=!0;Q++;continue}if(X.startsWith("+")&&X.length>1){let W=X.slice(1);if(W.includes("a"))J.allexport=!1;if(W.includes("k"))J.keywordExport=!1;Q++;continue}return J}return J}var QO="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",t0="This heredoc form or stdin consumer is not supported safely. Use a quoted heredoc with a supported consumer (cat, tee, git apply, git commit, gh pr create, gh issue create), or ask the user to verify.",XO=64;function QZ($,Z,J,Q){let X=J.derivedCommandWorkBudget===void 0,W=J.parallelBudget===void 0;try{return WO($,Z,{...J,derivedCommandWorkBudget:J.derivedCommandWorkBudget??K3(),parallelBudget:J.parallelBudget??E5()},Q)}catch(K){let Y=K instanceof m0?b5:K instanceof C1&&X?I5:K instanceof B3&&W?A5:void 0;if(!Y)throw K;if(J.trace?.currentSegmentIndex!==void 0)J.trace.recordSegment({type:"error",message:Y});else J.trace?.recordGlobal({type:"error",message:Y});return{reason:Y,segment:$,intent:"stop_and_explain"}}}function WO($,Z,J,Q){if(Z>=Z4)return J.trace?.recordSegment({type:"error",message:q0}),{reason:q0,segment:$,intent:"stop_and_explain"};let X=Q??J.factStore?.getCommandProgram($,J.shell??"auto")??v1($,J.shell);if(X.status==="limited")return J.trace?.recordSegment({type:"error",message:q0}),{reason:q0,segment:$,intent:"stop_and_explain"};if(X.status==="invalid"){let q=X.issues.find((U)=>U.code.includes("heredoc"));if(q){if(!J.strict)return JZ($,J);let U=`Unsupported heredoc syntax: ${q.message}`;return J.trace?.recordGlobal({type:"error",message:U}),{reason:U,segment:$,intent:"stop_and_explain"}}return dQ($,J),{reason:D0,segment:$,intent:"stop_and_explain"}}if(J.strict&&X.status==="partial")return dQ($,J),{reason:D0,segment:$,intent:"stop_and_explain"};if(X.issues.some((q)=>q.code.includes("quote"))&&!J.analyzePartialProgram)return JZ($,J);let K=J.cwd,Y=J.effectiveCwd!==void 0?J.effectiveCwd:J.cwd,B=wQ(J.environment.env,J.envAssignments);return w3(X,Z,{...J,rootProgram:X},K,[{effectiveCwd:Y,shellGitContextState:B,literalHeredocFiles:new Map(J.literalHeredocFiles),functionDefinitions:new Map(J.functionDefinitions)}]).result}function w3($,Z,J,Q,X){let W=[...X],K,Y;for(let[B,q]of $.nodes.entries()){if(q.kind==="connector"){Y=q.operator;continue}let U=$.nodes[B+1],G=U?.kind==="connector"?U.operator:void 0,j=KO($,B,q,Y,G),H=Y==="&&"||Y==="||",_=H?K:void 0,O=Y==="&&"?_?.success??W:Y==="||"?_?.failure??W:W,M=Y==="||"?_?.success??[]:[],L=Y==="&&"?_?.failure??[]:[],D=H||u$(G);if(q.kind==="function"){let b=O.flatMap((y)=>{let w=E2(y);return w.functionDefinitions.set(q.name,q.body),e9(y,[w],j,G==="&",u$(G))}),P=$Z(b,[],M,L,Y,G);W=P.states,K=P.conditionalStates,Y=void 0;continue}if(q.kind==="group"){let b=[],P=[];for(let w of O){let x=w3(q.body,Z,J,Q,[E2(w)]);if(x.result)return x;if(b.push(...e9(w,x.states,j,G==="&",u$(G))),D)P.push(w,...j?x.states.map((Y1)=>S3(w,Y1)):x.states)}let y=$Z(b,P,M,L,Y,G);W=y.states,K=y.conditionalStates,Y=void 0;continue}if(q.kind!=="command")continue;let z=J.trace?.flattenNested?J.trace.currentSegmentIndex:J.trace?.allocateSegment(),f=$.nodes[B-2],A=v3(Y)&&f?.kind==="command"?vJ(f)??BO(f):void 0,F=[],R=[];for(let b of O){let P=qO(q,Z,J,Q,[E2(b)]);if(P.result)return{result:P.result,states:W};let y=$.dialect==="powershell"?P.states:P.states.map((w)=>S3(b,w));for(let w of y){let x=E2(w),Y1=HO(q,Z,J.trace?{...J,trace:iQ(J.trace,z)}:J,Q,x,v3(Y),A);if(Y1)return{result:Y1,states:W};let C=bO(q,x.functionDefinitions);if(C)t1(J.derivedCommandWorkBudget,u3(C));let v=C?Z+1>=Z4?ZZ(q.displayText,J,[x]):w3(C,Z+1,J,Q,[x]):{result:null,states:[x]};if(v.result)return v;if(F.push(...e9(b,v.states,j,G==="&",u$(G))),D)R.push(b),R.push(...v.states.map((n)=>j?S3(b,n):n))}}let I=$Z(F,R,M,L,Y,G);W=I.states,K=I.conditionalStates,Y=void 0}return{result:null,states:W}}function KO($,Z,J,Q,X){if(J.kind==="group"&&J.style==="subshell")return!0;if($.dialect==="posix"&&(v3(Q)||v3(X)))return!0;if(X==="&")return!0;return $.dialect==="powershell"&&J.kind==="group"&&J.style==="brace"&&YO($,Z)}function e9($,Z,J,Q,X){let W=J?Z.map((Y)=>S3($,Y)):[...Z],K=X?W.flatMap((Y)=>T2($.literalHeredocFiles,Y.literalHeredocFiles)?[Y]:[{...Y,literalHeredocFiles:new Map($.literalHeredocFiles)},Y]):W;return Q?[$,...K]:K}function S3($,Z){return{...$,literalHeredocFiles:new Map(Z.literalHeredocFiles)}}function YO($,Z){let J=[...$.nodes.slice(0,Z)].reverse().find((X)=>X.kind==="command"||X.kind==="connector");if(!J||J.kind!=="command")return!0;let Q=J.words[0]?.text.toLowerCase();if(Q==="&"||Q===".")return!1;if(Q==="write-output"||Q==="function"||Q==="start-job")return!0;if(UO(J))return!0;return J.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function v3($){return $==="|"||$==="|&"}function BO($){if($?.dialect!=="powershell")return;if($.words.length===1&&$.words[0]?.quoted&&$.words[0].provenance==="literal")return $.words[0].text;if($.words[0]?.text.toLowerCase()==="write-output"&&$.words.length===2&&$.words[1]?.provenance==="literal")return $.words[1].text;return}function u$($){return $==="&&"||$==="||"}function $Z($,Z,J,Q,X,W){let K={success:y3([...J,...$]),failure:y3([...Q,...Z])},Y=u$(W)?K:void 0;return{states:u$(X)||Y?y3([...K.success,...K.failure]):K.success,conditionalStates:Y}}function iQ($,Z,J=$.flattenNested){return{currentSegmentIndex:Z,flattenNested:J,allocateSegment:$.allocateSegment,getNextSegmentIndex:$.getNextSegmentIndex,recordGlobal:$.recordGlobal,recordSegment:(Q,X=Z)=>$.recordSegment(Q,X)}}function qO($,Z,J,Q,X){let W=$.nested.map((K)=>({program:K,depth:Z}));if($.dialect==="powershell"){let K=GO($);if(K){if(Z+1>=Z4)return ZZ(K,J,X);let Y=v1(K,"powershell");if(Y.status==="limited")return ZZ(K,J,X);if(Y.status!=="complete")return xQ(W,J,Q,X);t1(J.derivedCommandWorkBudget,u3(Y)),W.push({program:Y,depth:Z+1})}}return xQ(W,J,Q,X)}function UO($){let Z=$.words[0];return Z?.provenance==="variable"&&$.words.at(-1)?.text==="="?Z.text.toLowerCase():void 0}function xQ($,Z,J,Q){let X=[...Q];for(let W of $){let K=[];for(let Y of X){let B=w3(W.program,W.depth,Z,J,[E2(Y)]);if(B.result)return B;K.push(...B.states)}X=y3(K)}return{result:null,states:X}}function GO($){let Z=$.words[0]?.provenance==="literal"&&!$.words[0].quoted&&$.words[0].raw===$.words[0].text&&($.words[0].text==="&"||$.words[0].text==="."),J=Z?1:0,Q=$.words[J];if(Q?.provenance!=="literal"||!Z&&(Q.quoted||Q.raw!==Q.text)||!["iex","invoke-expression"].includes(Q.text.toLowerCase()))return;let X=$.words.slice(J+1),W=X[0]&&!X[0].quoted&&X[0].raw===X[0].text&&["-c","-command"].includes(X[0].text.toLowerCase())?1:0,K=X[W];return X.length===W+1&&K?.quoted&&K.provenance==="literal"?K.text:void 0}function u3($){return $.nodes.reduce((Z,J)=>Z+(J.kind==="command"?J.words.length+J.nested.reduce((Q,X)=>Q+u3(X),0):J.kind==="group"||J.kind==="function"?u3(J.body):0),0)}function ZZ($,Z,J){return Z.trace?.recordSegment({type:"error",message:q0}),{result:{reason:q0,segment:$,intent:"stop_and_explain"},states:[...J]}}function HO($,Z,J,Q,X,W,K){let Y=NO($);if(Y&&J.strict)return J.trace?.recordSegment({type:"error",message:Y}),{reason:Y,segment:$.source,intent:"stop_and_explain"};sQ($,X,"before-consumer",J.environment.paths);let B=f$($.dialect,$.words).map(E),q=$.displayText,U=uQ(B,X.shellGitContextState);if($.dialect==="powershell"){let H=T(YJ($,W,CO(J,X.effectiveCwd)),J.policy);if(J.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!H,reason:H?.reason}),H)return PO(q,H)}if(B.length===1&&B[0]?.includes(" ")&&!$.dynamicExecutable){let H=T(_2(B[0],J.scanWork),J.policy),_=H!==null&&!J.strict&&R5($,J.rootProgram,J.scanWork);if(H&&!_)return J.trace?.recordSegment({type:"dangerous-text",token:B[0],matched:!0,reason:H.reason}),{reason:H.reason,segment:q,ruleId:H.id,intent:H.intent};J.trace?.recordSegment({type:"dangerous-text",token:B[0],matched:!1});let O=lQ($,Y,X,U,K,J);if(O)return O;return t9(B,X.shellGitContextState),null}let G=P2($.words,Z,{...J,commandView:$,cwd:Q,effectiveCwd:X.effectiveCwd,envAssignments:U,literalHeredocFiles:X.literalHeredocFiles,functionDefinitions:X.functionDefinitions,hasPipelineInput:W,literalShellInput:K,analyzeNested:(H,_)=>{let O=_&&Object.hasOwn(_,"effectiveCwd")?_.effectiveCwd:X.effectiveCwd,M=QZ(H,Z+1,{...J,derivedCommandWorkBudget:J.derivedCommandWorkBudget,effectiveCwd:O,envAssignments:_?.envAssignments??U,literalHeredocFiles:X.literalHeredocFiles,functionDefinitions:_?.functionDefinitions,worktreeMode:_?.worktreeMode??J.worktreeMode,trace:J.trace?iQ(J.trace,J.trace.currentSegmentIndex,!0):void 0});return M?{reason:M.reason,ruleId:M.ruleId,intent:M.intent}:null}});if(G)return{...G,segment:q};let j=lQ($,Y,X,U,K,J);if(j)return j;return t9(B,X.shellGitContextState),null}function lQ($,Z,J,Q,X,W){let K=VO($,Z,J,Q??new Map,W);if(K)return K;return sQ($,J,"after-consumer",W.environment.paths),J.literalHeredocFiles.clear(),OO($,Z,J,W.environment.paths),zO($,J,X,W.environment,W.trace),null}var jO=new Set([">>","<>"]);function sQ($,Z,J,Q){for(let W of $.redirections){if(!(J==="before-consumer"?_O(W):jO.has(W.operator)))continue;mQ(W.target,Z,Q)}if(J!=="before-consumer"||!D1($.words[0],"tee"))return;let X=rQ($.words.slice(1));if(!X)return;for(let W of X.operands)mQ(W,Z,Q)}function _O($){if($.operator===">"||$.operator===">|")return!0;return $.operator===">&"&&$.fd===void 0&&$.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test($.target.text)}function mQ($,Z,J){let Q=$?.provenance==="literal"?O2($.text,Z.effectiveCwd,J):void 0;if(!Q)return;Z.literalHeredocFiles.delete(Q)}function OO($,Z,J,Q){if(Z)return;let X=$.redirections.find((W)=>W.operator==="<<"||W.operator==="<<-")?.heredoc;if(!X?.quotedDelimiter)return;for(let W of LO($)){let K=O2(W.text,J.effectiveCwd,Q);if(!K||!C5(K))continue;if(!J.literalHeredocFiles.has(K)&&J.literalHeredocFiles.size>=P5)throw new C1;J.literalHeredocFiles.set(K,X.body)}}function LO($){let Z=FO($.redirections)?.target,J=pQ(Z)?[Z]:[];if(D1($.words[0],"cat"))return MO($.words)?J:[];if(!D1($.words[0],"tee"))return[];let Q=rQ($.words.slice(1));if(!Q||Q.append||Q.hasUnsupportedOptions||!Q.operands.every(pQ))return[];return[...Q.operands,...J]}function MO($){let Z=!1;for(let J of $.slice(1)){if(Z||J.provenance!=="literal")return!1;if(J.text==="--"){Z=!0;continue}if(!/^-u+$/.test(J.text))return!1}return!0}function FO($){let Z=$.findLast((J)=>(J.fd??([">",">|",">>",">&"].includes(J.operator)?1:0))===1);return Z?.operator===">"||Z?.operator===">|"?Z:void 0}function rQ($){let Z=[],J=!0,Q=!1,X=!1;for(let W of $){if(W.provenance!=="literal")return;if(J&&D1(W,"--")){J=!1;continue}if(J&&!W.quoted&&W.raw===W.text&&/^-[^-]/.test(W.text)){Q||=W.text.slice(1).includes("a"),X||=[...W.text.slice(1)].some((K)=>K!=="a"&&K!=="i");continue}if(J&&!W.quoted&&W.raw===W.text&&W.text.startsWith("--")){Q||=W.text==="--append",X||=W.text!=="--append"&&W.text!=="--ignore-interrupts";continue}Z.push(W)}return{operands:Z,append:Q,hasUnsupportedOptions:X}}function pQ($){if(!$||$.provenance!=="literal"||$.text.length===0)return!1;if($.quoted||$.raw!==$.text)return!0;return!$.raw.startsWith("~")&&!/[{}]/.test($.raw)}function D1($,Z){return $?.text===Z&&$.raw===Z&&$.provenance==="literal"&&!$.quoted}function NO($){let Z=$.redirections.filter((K)=>K.operator==="<<"||K.operator==="<<-");if(Z.length===0)return;if(Z.length!==1)return t0;let J=Z[0];if(!J?.heredoc)return t0;if(!J.heredoc.quotedDelimiter)return QO;if(J.fd!==void 0&&J.fd!==0)return t0;if($.redirections.some((K)=>K!==J&&["<","<<","<<-","<<<","<&","<>"].includes(K.operator)))return t0;let Q=$.redirections.some((K)=>K!==J&&cQ(K.target));if(D1($.words[0],"cat"))return Q?t0:void 0;if(D1($.words[0],"tee"))return Q||$.words.slice(1).some(cQ)?t0:void 0;let X=$.words[0],W=$.words[1];if(D1(X,"git")&&(D1(W,"apply")||D1(W,"commit")))return;if(D1(X,"gh")&&(D1(W,"pr")||D1(W,"issue"))&&D1($.words[2],"create"))return;return t0}function cQ($){return $?.parts.some((Z)=>Z.provenance==="command-substitution"&&Z.raw.startsWith(">("))??!1}function VO($,Z,J,Q,X){if(!Z)return null;let W=$.redirections.filter((q)=>q.operator==="<<"||q.operator==="<<-"),K=W.flatMap((q)=>q.heredoc?[q.heredoc.body]:[]);if(DO($,W,J,Q,X))return null;let Y=RO($,W,X);if(Y!==void 0)return Y?{reason:Y.reason,segment:$.displayText,ruleId:Y.id,intent:Y.intent}:null;let B=JZ(K.length===W.length?K.join(`
61
- `):$.source,X);return B?{...B,segment:$.displayText}:null}function RO($,Z,J){let Q=Z.length===1?Z[0]:void 0;if(!Q?.heredoc?.quotedDelimiter||Q.fd!==void 0&&Q.fd!==0)return;let X=$.words[0];if(X?.provenance!=="literal"||!N1(X.text))return;if(!$.words.slice(1).every((q)=>q.provenance==="literal"&&q.text.startsWith("-")))return;let K=Q.heredoc.body,Y=o(J.policy,"interpreter.one-liner-paranoid",!!J.paranoidInterpreters);if(J.trace?.recordSegment({type:"interpreter",interpreter:X.text,codeArg:K,paranoidBlocked:Y}),Y){let q=T(N("interpreter.one-liner-paranoid",O$),J.policy);if(q)return q}if(!L$(K,J.scanWork))return null;let B=T(N("interpreter.dangerous-command",x0),J.policy);if(!B)return null;return J.trace?.recordSegment({type:"dangerous-text",token:K,matched:!0,reason:B.reason}),B}function DO($,Z,J,Q,X){let W=Z.length===1?Z[0]:void 0;if(!W?.heredoc?.quotedDelimiter||W.fd!==void 0&&W.fd!==0)return!1;let K=p0($.words,X.environment,J.effectiveCwd,Q),Y=K.words.map(E),B=l(Y[0]??"");if(K.unverifiableEnvSplit||!t.has(B)&&!t.has(u(B)))return!1;return T1(Y)}function zO($,Z,J,Q,X){let W=EQ($,Z.effectiveCwd,Q,J);if(W===null)X?.recordSegment({type:"cwd-change",segment:$.words.map(E).join(" "),effectiveCwdNowUnknown:!0});if(W!==void 0)Z.effectiveCwd=W}function E2($){return{effectiveCwd:$.effectiveCwd,shellGitContextState:vQ($.shellGitContextState),literalHeredocFiles:new Map($.literalHeredocFiles),functionDefinitions:new Map($.functionDefinitions)}}function y3($){let Z=[];for(let J of $){if(!Z.some((Q)=>IO(Q,J)))Z.push(J);if(Z.length>XO)throw new C1}return Z}function IO($,Z){return $.effectiveCwd===Z.effectiveCwd&&T2($.literalHeredocFiles,Z.literalHeredocFiles)&&T2($.functionDefinitions,Z.functionDefinitions)&&T2($.shellGitContextState.effectiveEnvAssignments,Z.shellGitContextState.effectiveEnvAssignments)&&T2($.shellGitContextState.shellAssignments,Z.shellGitContextState.shellAssignments)&&fO($.shellGitContextState.exportedNames,Z.shellGitContextState.exportedNames)&&$.shellGitContextState.allexport===Z.shellGitContextState.allexport&&$.shellGitContextState.keywordExport===Z.shellGitContextState.keywordExport}function T2($,Z){if($===Z)return!0;if(!$||!Z||$.size!==Z.size)return!1;return[...$].every(([J,Q])=>Z.get(J)===Q&&Z.has(J))}function bO($,Z){let J=F4($);return J===void 0?void 0:Z.get(J)}function fO($,Z){return $.size===Z.size&&[...$].every((J)=>Z.has(J))}function PO($,Z){if(!Z)return null;return{reason:Z.reason,segment:$,ruleId:Z.id,intent:Z.intent}}function CO($,Z=$.effectiveCwd){let J=Z===null;return{environment:$.environment,cwd:J?void 0:Z??$.cwd,originalCwd:J?void 0:$.cwd,strict:$.strict,paranoid:$.paranoidRm,allowTmpdirVar:$.allowTmpdirVar,protectedGitMetadata:$.protectedGitMetadata,policy:$.policy}}function JZ($,Z){let J=T(_2($,Z.scanWork),Z.policy),Q=Z.trace?.currentSegmentIndex??Z.trace?.allocateSegment(),X={type:"dangerous-text",token:$,matched:!!J,reason:J?.reason};if(Z.trace?.recordSegment(X,Q),!J&&/^(?:cd|pushd)\s/.test($))Z.trace?.recordSegment({type:"cwd-change",segment:$,effectiveCwdNowUnknown:!0},Q);return J?{reason:J.reason,segment:$,ruleId:J.id,intent:J.intent}:null}function dQ($,Z){let J={type:"strict-unparseable",rawCommand:$,reason:D0};if(Z.trace?.currentSegmentIndex===void 0)Z.trace?.recordGlobal(J);else Z.trace.recordSegment(J)}function nQ($){let Z=$.effectiveCapabilities,J=$.strict??Z.fail_closed.enabled,Q=$.paranoidRm??Z.paranoid_rm.enabled,X=$.paranoidInterpreters??Z.paranoid_interpreters.enabled,W={fail_closed:XZ(Z.fail_closed,$.strict,"strict"),paranoid_rm:XZ(Z.paranoid_rm,$.paranoidRm,"paranoidRm"),paranoid_interpreters:XZ(Z.paranoid_interpreters,$.paranoidInterpreters,"paranoidInterpreters")};return{policy:X8($.policySnapshot.policy,W),effectiveCapabilities:W,effectiveLevel:c6({failClosed:J,paranoidRm:Q,paranoidInterpreters:X}),strict:J,paranoidRm:Q,paranoidInterpreters:X,worktreeMode:$.worktreeMode??!1}}function XZ($,Z,J){if(Z===void 0||Z===$.enabled)return $;return{enabled:Z,source:"capability_override",sources:[...$.sources,`analysis options.${J}`]}}function fb($,Z){return WZ($,Z)}function WZ($,Z,J,Q){let X=QZ($,0,{...Z,...nQ(Z),factStore:Q},J);if(!X)return null;return{kind:"deny",reason:X.reason,intent:X.intent??"manual_only",...X.ruleId?{ruleId:X.ruleId}:{},evidence:[{kind:"command",command:$,segment:X.segment}]}}import{dirname as KZ}from"node:path";var eQ="This path contains the protected policy config and you must not modify or delete it.",AO=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function $X($){let Z=y0(G0()),J=vO($.invocation.context.executionCwd,Z);if($.invocation.route.kind==="patch")return aQ($.paths,!1,$.invocation.context.executionCwd,J,Z);let Q=L1($,"input-candidate");if($.invocation.route.kind==="command")return Q?oQ(Q.shell,$.invocation.context.executionCwd,J,Z):null;if($.invocation.route.kind==="unknown"&&Q){let X=oQ(Q.shell,$.invocation.context.executionCwd,J,Z);if(X)return X}return aQ($.paths,$.invocation.route.kind==="grep"||$.invocation.route.kind==="glob"||X4($.invocation.toolName),$.invocation.context.executionCwd,J,Z)}function aQ($,Z,J,Q,X){if(Z)return null;let W=$.find((K)=>S2(K,J,Q,X));return W?{target:W}:null}function oQ($,Z,J,Q){let X=G3($,Z,Q,{findSegmentTarget:(W,K)=>EO(W,K,J,Q)?.target??null,isRedirectionTarget:(W,K)=>S2(W,K.cwd,J,Q),findMalformedTarget:(W)=>wO(W,Z,J,Q)?.target??null,normalizeCwd:W1});return X?{target:X}:null}function EO($,Z,J,Q){if(F2($))return null;let X=Q.environment,W=A1([...$],X),K=u(W[0]??"").toLowerCase(),Y=W.slice(1);if(K==="rm"&&TO(Y)){let B=SO(Y).find((q)=>tQ(R1(q,Z.variables),Z.cwd,J,Q));if(B)return{target:B}}if(K==="find"){if(L3(W,1)||z9(W,X)){let q=(O3(g(W))??g(["."])).find((U)=>{let G=R1(U.text,Z.variables);return S2(G,Z.cwd,J,Q)||tQ(G,Z.cwd,J,Q)})?.text;if(q)return{target:q}}}if(K==="mv"){let B=H3(Y).sources.find((q)=>uO(R1(q,Z.variables),Z.cwd,J,Q));if(B)return{target:B}}if(yO($,X))return null;for(let B of $)for(let q of ZX(B))if(S2(R1(q,Z.variables),Z.cwd,J,Q))return{target:q};return null}function TO($){return $.some((Z)=>Z==="--recursive"||Z.startsWith("-")&&!Z.startsWith("--")&&/[rR]/.test(Z.slice(1)))}function SO($){let Z=$.indexOf("--");if(Z!==-1)return[...$.slice(0,Z).filter((J)=>!J.startsWith("-")),...$.slice(Z+1)];return $.filter((J)=>!J.startsWith("-"))}function yO($,Z){let J=A1([...$],Z);if(J.length===0)return!1;let Q=u(J[0]??"").toLowerCase();if(!AO.has(Q))return!1;if(Q!=="sed")return!0;return!J.slice(1).some((X)=>X.startsWith("-i")||X==="--in-place"||X.startsWith("--in-place="))}function wO($,Z,J,Q){for(let X of $.split(/\s+/))for(let W of ZX(X))if(S2(W,Z,J,Q))return{target:W};return null}function ZX($){let Z=$.trim().replace(/^['"]|['"]$/g,""),J=Z.indexOf("=");return J===-1||J===Z.length-1?[Z]:[Z,Z.slice(J+1)]}function vO($,Z){let J=W1(z$(),$,Z),Q=KZ(J),X=new Set;for(let W=Q;;W=KZ(W))if(X.add(y2(W)),KZ(W)===W)break;return{file:y2(J),directoryAndAncestors:X}}function S2($,Z,J,Q){return y2(W1($,Z,Q))===J.file}function tQ($,Z,J,Q){return J.directoryAndAncestors.has(y2(W1($,Z,Q)))}function uO($,Z,J,Q){let X=y2(W1($,Z,Q));return X===J.file||J.directoryAndAncestors.has(X)}function y2($){return process.platform==="win32"?$.toLowerCase():$}import{homedir as BZ}from"node:os";import{isAbsolute as h3,posix as hO,resolve as k3,win32 as gO}from"node:path";import{fileURLToPath as kO}from"node:url";var HX="Access to a sensitive path is not allowed.",jX=new Set(["echo","printf"]),xO=new Set(["find"]),lO=new Set(["-exec","-execdir"]),mO=new Set([";","+"]),pO=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),cO=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),dO=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),iO=new Set(["node","bun"]),sO=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),rO=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","popen","read","remove","rename","require","rg","rm","sed","shell","source","spawn","strings","system","tail","tar","truncate","unlink","write","xxd","zip"]),_X=new Set(["-c","-e","-r","-E","--eval","--exec"]),nO=new Set(["src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js"]),JX=new Set(["cc-safety-net","ccsn"]),aO=new Set(["bunx","npx","pnpx"]),oO=new Set(["bun","node"]),tO=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"])]]),eO=new Set(["grep","rg"]),QX="f",XX="file",$L="files",ZL=new Set(["e","f"]),JL=new Set(["regexp","file"]),QL=new Set(["e","f","A","B","C","m"]),XL=new Set(["regexp","file","after-context","before-context","context","max-count"]),WL=new Set(["|","|&"]),YZ="__CC_SAFETY_NET_PIPE_INPUT__",OX=new Set(["bash","sh","zsh","dash","ksh"]),KL=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 WX($,Z,J,Q,X){let W=c$();for(let K of $){if(sL(K,Z,J?.denyPaths??[],Q,W))return{target:K,ruleId:"secret.deny-path"};if(X&&!X.has(K))continue;let Y=dL(K,Z,J,W);if(Y){if(!Y.startsWith("secret.cli.")&&rL(K,Z,J?.allowPaths??[],Q,W))continue;return{target:K,ruleId:Y}}}return null}function LX($,Z,J={}){let Q=KX($),X=WX(Q,$.invocation.context.executionCwd,Z,$.invocation.context.configCwd),W=X?.ruleId!=="secret.deny-path"&&J.strict===!1?KX($,{refineJavaScriptInlineData:!0}):Q,K=W.length===Q.length?X:WX(Q,$.invocation.context.executionCwd,Z,$.invocation.context.configCwd,new Set(W));if(K?.ruleId!=="secret.deny-path"&&J.strict===!1&&YL($))return null;return K}function YL($){if($.invocation.route.kind!=="command")return!1;let Z=L1($,"input-candidate")??L1($,"declared-command");if(!Z)return!1;if(Z.program.nodes.some((K)=>K.kind==="command"&&K.nested.length>0))return!1;let J=[];for(let K of Z.shell.entries){if(K.kind==="operator"&&K.boundary)return!1;if(K.kind==="redirection")return!1;if(K.kind!=="operator")J.push(n1(K.text))}let Q=h$(J);if(Q.length===0)return!1;let X=$$(Q[0]??"").toLowerCase(),W=Q.slice(1);if(X==="ls"||X==="stat")return!0;if(X==="test")return W.length===2&&(W[0]==="-e"||W[0]==="-f");if(X!=="find")return!1;return!W.some((K)=>pO.has(K))}function KX($,Z={}){if($.invocation.route.kind==="command"){let Q=L1($,"input-candidate");return Q?u2(Q.shell,$.store,Z):[]}if($.invocation.route.kind!=="unknown")return[...$.paths];let J=L1($,"input-candidate");return[...J?u2(J.shell,$.store,Z):[],...$.paths]}function u2($,Z,J){if($.status==="structural-limit")throw new I0;if($.status==="unclosed-quote")return[];if($.status==="invalid")throw Error("Unable to parse command for secret protection");let Q=[...$.assignmentFallbacks,...PL(n1($.source),Z,J)],X=[],W=null;for(let K of $.entries){if(K.kind==="operator"){if(!K.boundary)continue;if(X.length>0){if(Q.push(...g3(X,Z,J)),W!==null)Q.push(...BX(W,X,Z,J));W=WL.has(K.operator)?X:null,X=[]}else W=null;continue}if(K.kind==="redirection"){let Y=K.target?n1(K.target):void 0;if(Y&&K.targetOrder==="legacy-segment")X.push(Y);else if(Y)Q.push(Y);continue}X.push(n1(K.text))}if(X.length>0){if(Q.push(...g3(X,Z,J)),W!==null)Q.push(...BX(W,X,Z,J))}return Q}function g3($,Z,J){let Q=ML($),X=h$($);if(X.length===0)return Q;let W=X[0]??"",K=$$(W).toLowerCase(),Y=X.slice(1),B=qL(W,K,Y);if(B)return[...Q,...B];if(jX.has(K))return Q;if(eO.has(K))return[...Q,...vL(Y)];if(xO.has(K))return[...Q,...FL(Y,Z,J)];if(F1.has(K))return[...Q,...Y.flatMap((q)=>qX("awk",q)),...Y.flatMap((q)=>VL(q,Z,J)),...Y.flatMap(RL)];if(NX(K)){if(OX.has(K)){let q=I7(K,Y);if(q!==null&&Z.getShellSyntax(q).status==="structural-limit")throw new I0}return[...Q,...NL(K,Y,J)]}return[...Q,...Y.flatMap((q)=>qX(K,q))]}function BL($,Z){if(JX.has($))return Z[0]==="explain"?0:null;if(aO.has($)){let J=Z[0]==="-y"||Z[0]==="--yes"?1:0;return JX.has(Z[J]??"")&&Z[J+1]==="explain"?J+1:null}if(oO.has($)){if(YX(Z[0])&&Z[1]==="explain")return 1;if($==="bun"&&Z[0]==="run"&&YX(Z[1])&&Z[2]==="explain")return 2}return null}function qL($,Z,J){let Q=BL(Z,J);if(Q===null)return null;let X=[$,...J.slice(0,Q)],W=J.slice(Q+1);for(let K=0;K<W.length;K++){let Y=W[K];if(Y==="--json"||Y==="--help"||Y==="-h")continue;if(Y==="--cwd"){let B=W[K+1];if(B&&!B.startsWith("--"))X.push(B);K++;continue}return X}return X}function YX($){let Z=$?.replaceAll("\\","/");return[...nO].some((J)=>Z===J||Z?.endsWith(`/${J}`))}function BX($,Z,J,Q){if(_L(Z,J,Q))return UL($);let X=OL(Z);if(X===null)return[];return GL($).flatMap((W)=>OX.has(X)?u2(J.getShellSyntax(W),J,Q):RX(W))}function UL($){let Z=h$($);if(Z.length===0)return[];let J=$$(Z[0]??"").toLowerCase();if(!jX.has(J))return[];return Z.slice(1)}function GL($){let Z=h$($);if(Z.length===0)return[];let J=$$(Z[0]??"").toLowerCase(),Q=Z.slice(1);if(J==="echo"){let X=Q.findIndex((W)=>!/^-[neE]+$/.test(W));return[(X===-1?[]:Q.slice(X)).join(" ")]}if(J==="printf")return HL(Q);return[]}function HL($){let Z=$[0];if(Z===void 0)return[];let J=(Z.match(/%%|%[bqs]/g)??[]).filter((X)=>X!=="%%").length;if(J===0||$.length===1)return[MX(Z)];let Q=$.slice(1);return Array.from({length:Math.ceil(Q.length/J)},(X,W)=>jL(Z,Q.slice(W*J,(W+1)*J)))}function jL($,Z){let J=0;return MX($.replace(/%%|%[bqs]/g,(Q)=>{if(Q==="%%")return"%";let X=Z[J]??"";return J++,X}))}function MX($){return $.replace(/\\n/g,`
62
- `).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function _L($,Z,J){let Q=h$($);if(Q.length===0||$$(Q[0]??"").toLowerCase()!=="xargs")return!1;let X=r0(Q),W=Q.slice(X.childStart);if(W.length===0)return!1;if(X.replacementToken==="")return!1;let K=X.replacementToken,Y=K===null?[...W,YZ]:W.map((B)=>B.split(K).join(YZ));return g3(Y,Z,J).some((B)=>B.includes(YZ))}function OL($){let Z=h$($);if(Z.length===0)return null;let J=$$(Z[0]??"").toLowerCase();if(!NX(J))return null;return LL(J,Z.slice(1))?J:null}function LL($,Z){let J=FX($);for(let Q=0;Q<Z.length;Q++){let X=Z[Q];if(X===void 0)break;if(_X.has(X)||VX($,X)||/^--(?:eval|exec)=/.test(X))return!1;if(X==="-")return!0;if(X.startsWith("-")){if(J==="python"&&X==="-m")return!1;if(KL.get(J)?.has(X))Q++;continue}return!1}return!0}function FX($){return/^python\d/.test($)?"python":$}function ML($){let Z=[];for(let J of $){if(IX(J))continue;let Q=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(J);if(Q===null)break;if(Q[1]!==void 0&&Q[1]!=="")Z.push(Q[1])}return Z}function qX($,Z){if(Z==="--")return[];let J=[],Q=Z.indexOf("=");if(Q>0&&Q<Z.length-1)J.push(Z.slice(Q+1));if(Z.startsWith("-"))return J;if($==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(Z))return J;if($==="zip"&&/\.zip$/i.test(Z))return J;return J.push(Z),J}function FL($,Z,J){let Q=$.findIndex((W)=>W.startsWith("-")||W==="("||W==="!"||W===";"),X=[...$.slice(0,Q===-1?$.length:Q)];for(let W=0;W<$.length;W++){if(!lO.has($[W]??""))continue;let K=$.slice(W+1),Y=K.findIndex((U)=>mO.has(U)),B=Y===-1?K:K.slice(0,Y),q=g3(B,Z,J);if(X.push(...q.filter((U)=>U!=="{}")),!q.includes("{}"))continue;X.push(...$.slice(0,W).flatMap((U,G,j)=>{if(!cO.has(U))return[];let H=j[G+1];return H===void 0?[]:[H,H.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return X}function NX($){return dO.has($)||/^python\d/.test($)}function NL($,Z,J){let Q=[];for(let X=0;X<Z.length;X++){let W=Z[X];if(W===void 0)break;if(_X.has(W)||VX($,W)){let Y=Z[X+1];if(Y!==void 0)Q.push(...UX($,Y,J)),X++;continue}let K=/^--(?:eval|exec)=(.*)$/.exec(W);if(K!==null&&K[1]!==void 0){Q.push(...UX($,K[1],J));continue}if(!W.startsWith("-"))Q.push(W)}return Q}function VX($,Z){if(!Z.startsWith("-")||Z.startsWith("--")||Z.length<=2)return!1;return tO.get(Z[Z.length-1]??"")?.has(FX($))??!1}function VL($,Z,J){if(!$.includes("system"))return[];return u6($)?.commands.flatMap((Q)=>u2(Z.getShellSyntax(Q),Z,J))??[]}function RL($){return Array.from($.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((Z)=>Z[1]).filter((Z)=>Z!==void 0&&Z!=="")}function RX($){let Z=Array.from($.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((Q)=>Q[2]).filter((Q)=>Q!==void 0&&Q!==""),J=($.match(/[\w./~@+-]*[./~][\w./~@+-]*/g)??[]).filter((Q)=>Q!=="process.versions.sqlite"||Z.some((X)=>X.includes(Q)));return[...Z,...Z.flatMap(DX),...J]}function UX($,Z,J){let Q=RX(Z);if(!J.refineJavaScriptInlineData||!iO.has($)||Q.length===0)return Q;let X=DL(Z);return X!==null&&!IL(X)?[]:Q}function DL($){let Z=$.split("");for(let J=0;J<$.length;J++){let Q=$[J];if(Q!=="'"&&Q!=='"'&&Q!=="`")continue;if(Q==="`"&&zL($,J))return null;Z[J]=" ";let X=!1;for(let W=J+1;W<$.length;W++){let K=$[W];if(Z[W]=" ",K==="\\"){if(W++,W<$.length)Z[W]=" ";continue}if(Q==="`"&&K==="$"&&$[W+1]==="{")return null;if(Q!=="`"&&(K===`
63
- `||K==="\r"))return null;if(K!==Q)continue;J=W,X=!0;break}if(!X)return null}return Z.join("")}function zL($,Z){for(let J=Z-1;J>=0;J--){let Q=$[J];if(!Q||/\s/.test(Q))continue;return/[\w$\])]/.test(Q)}return!1}function IL($){for(let Z of $.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let J=Z[0],Q=Z.index;if(sO.has(J.toLowerCase()))return!0;let X=J.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((W)=>W.toLowerCase());if(!X.some((W)=>rO.has(W)))continue;if(X.length>1)return!0;if(bL($,Q)===".")return!0;if(fL($,Q+J.length)==="(")return!0}return!1}function bL($,Z){for(let J=Z-1;J>=0;J--)if(!/\s/.test($[J]??""))return $[J];return}function fL($,Z){for(let J=Z;J<$.length;J++)if(!/\s/.test($[J]??""))return $[J];return}function PL($,Z,J){return SL($).flatMap((Q)=>{let X=Z.getShellSyntax(Q);if(X.status==="invalid")return[];return[...u2(X,Z,J),...CL(X)?AL(X):[]]})}function CL($){let Z=$.entries;for(let J=0;J<Z.length;J++){let Q=Z[J];if(Q?.kind!=="word"||$$(n1(Q.text)).toLowerCase()!=="base64")continue;for(let X=J+1;X<Z.length;X++){let W=Z[X];if(W?.kind==="operator")break;if(W?.kind!=="word")continue;let K=n1(W.text);if(K==="--decode"||!K.startsWith("--")&&K.startsWith("-")&&/[dD]/.test(K))return!0}}return!1}function AL($){return $.entries.flatMap((Z)=>Z.kind==="word"?[n1(Z.text)]:Z.kind==="redirection"&&Z.target?[n1(Z.target)]:[]).flatMap(DX)}function DX($){let Z=TL($);if(Z===null)return[];let J=Buffer.from(Z,"base64").toString("utf8");if(J===""||EL(J))return[];return Buffer.from(J,"utf8").toString("base64").replace(/=+$/g,"")===Z.replace(/=+$/g,"")?[J]:[]}function EL($){return Array.from($).some((Z)=>{let J=Z.charCodeAt(0);return J<32||J===127})}function TL($){if($.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test($))return null;if(/=/.test($.replace(/=+$/g,"")))return null;let Z=$.replace(/=+$/g,"");if(Z.length%4===1)return null;return`${Z.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-Z.length%4)%4)}`}function SL($){let Z=[],J={inSingle:!1,inDouble:!1,escaped:!1};for(let Q=0;Q<$.length;Q++){let X=$[Q];if(!X)break;if(n$(X,J))continue;if(zX($,Q,J)){let W=yL($,Q+1);if(W!==null)Z.push(W.body),Q=W.endIndex;continue}if(!J.inSingle&&X==="`"){let W=wL($,Q);if(W!==null)Z.push(W.body),Q=W.endIndex}}return Z}function yL($,Z){let J={inSingle:!1,inDouble:!1,escaped:!1},Q=1;for(let X=Z+1;X<$.length;X++){let W=$[X];if(!W)break;if(n$(W,J))continue;if(zX($,X,J)){Q++,X++;continue}if(!J.inSingle&&!J.inDouble&&W===")"){if(Q--,Q===0)return{body:$.slice(Z+1,X),endIndex:X}}}return null}function wL($,Z){let J=!1;for(let Q=Z+1;Q<$.length;Q++){let X=$[Q];if(!X)break;if(J){J=!1;continue}if(X==="\\"){J=!0;continue}if(X==="`")return{body:$.slice(Z+1,Q),endIndex:Q}}return null}function zX($,Z,J){return!J.inSingle&&$[Z]==="$"&&$[Z+1]==="("&&$[Z+2]!=="("}function vL($){let Z=[],J=[],Q=!1,X=!1,W=!1;for(let B=0;B<$.length;B++){let q=$[B];if(q===void 0)break;if(!W&&q==="--"){W=!0;continue}if(W){J.push(q);continue}let U=/^--([^=]+)(?:=(.*))?$/.exec(q);if(U!==null){let G=U[1]??"",j=U[2];if(G===$L)X=!0;if(JL.has(G))Q=!0;if(j!==void 0){if(G===XX)Z.push(j);continue}if(XL.has(G)){let H=$[B+1];if(G===XX&&H!==void 0)Z.push(H);B++}continue}if(q.startsWith("-")&&q.length>1){let G=q.slice(1),j="",H="";for(let _=0;_<G.length;_++){let O=G[_]??"";if(ZL.has(O))Q=!0;if(QL.has(O)){j=O,H=G.slice(_+1);break}}if(j!=="")if(H.length>0){if(j===QX)Z.push(H)}else{let _=$[B+1];if(j===QX&&_!==void 0)Z.push(_);B++}continue}J.push(q)}let Y=!Q&&!X?J.slice(1):J;return[...Z,...Y]}function h$($){let Z=$.findIndex((J)=>!IX(J)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(J));return Z===-1?[]:[...$.slice(Z)]}function IX($){return $==="env"||$==="command"||$==="builtin"||$==="sudo"}var uL=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),hL=".env.",gL=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),kL=[".env.example.",".env.sample."];function xL($){let Z;try{Z=new URL($.trim())}catch{return!1}return Z.protocol!=="file:"&&Z.host!==""}function lL($){return $.length>0&&!/\s/.test($)}function mL($,Z,J){try{let Q=h2($,Z,J);return Q!==""&&b1.entryKind(Q)!=="missing"}catch(Q){if(Q instanceof O1)throw Q;return!1}}var pL=new Set(["node_modules","__pycache__"]),cL=[["vendor","bundle"],["vendor","cache"]];function dL($,Z,J,Q){if(xL($))return null;let X=N0($,Z,Q);if(!X)return null;let W=s(X.split("/").pop()??""),K=s(X),Y=()=>lL(W)||mL($,Z,Q);if(gL.has(W)||kL.some((G)=>W.startsWith(G)))return null;let B=s(oL($,Z,Q));for(let G of s6){let j=`~/${G.suffixParts.join("/")}`;if((GX(K,j)||GX(B,j))&&F0(G.id,J))return G.id}let q=iL(X,Z,J,Q);if(q)return q;if(uL.has(W))return null;for(let G of i6)if(W===G.basename&&F0(G.id,J))return G.id;if(W.startsWith(hL)&&F0(p4.id,J)&&Y())return p4.id;for(let G of r6)if(W.length>G.prefix.length&&W.startsWith(G.prefix)){let j=W.slice(G.prefix.length)[0];if((j==="-"||j==="_")&&F0(G.id,J)&&Y())return G.id}for(let G of n6)if(W.length>G.prefix.length&&W.startsWith(G.prefix)){if(W.slice(G.prefix.length)===G.suffix&&F0(G.id,J))return G.id}if(nL(K))return null;if(!W.includes(".")&&Y2.pattern.test(W)&&F0(Y2.id,J))return Y2.id;let U=aL(W,J);if(U)return U;return null}function iL($,Z,J,Q){return c4.find((X)=>{if(!F0(X.id,J))return!1;switch(X.id){case"secret.cli.claude-code":return i($,r(process.env.CLAUDE_CONFIG_DIR,"~/.claude",Z,Q),[".credentials.json"]);case"secret.cli.claude-code.config":{let W=s($).split("/");return i($,r(process.env.CLAUDE_CONFIG_DIR,"~/.claude",Z,Q),["settings.json","settings.local.json"])||v2($,"~/.claude.json",Z,Q)||W.at(-1)==="settings.local.json"&&W.at(-2)===".claude"||W.at(-1)===".mcp.json"}case"secret.cli.antigravity":return i($,N0("~/.gemini/config",Z,Q),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let W=r(process.env.CODEX_HOME,"~/.codex",Z,Q);return i($,W,["auth.json",".credentials.json"])||w2($,W,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let W=r(process.env.CODEX_HOME,"~/.codex",Z,Q),K=s($).split("/").at(-1)??"";return i($,W,["config.toml"])||K.endsWith(".config.toml")&&i($,W,[K])}case"secret.cli.gemini":return i($,K1(r(process.env.GEMINI_CLI_HOME,"~",Z,Q),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let W=s($).split("/"),K=process.env.ProgramData?[K1(r(process.env.ProgramData,"",Z,Q),"gemini-cli")]:[];return i($,K1(r(process.env.GEMINI_CLI_HOME,"~",Z,Q),".gemini"),["settings.json","google_accounts.json"])||W.at(-1)==="settings.json"&&W.at(-2)===".gemini"||(process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH?.trim()?v2($,process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH,Z,Q):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...K].some((Y)=>i($,N0(Y,Z,Q),["settings.json"]))}case"secret.cli.copilot-cli":{let W=r(process.env.COPILOT_HOME,"~/.copilot",Z,Q);return i($,W,["config.json"])||w2($,W,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return i($,r(process.env.COPILOT_HOME,"~/.copilot",Z,Q),["mcp-config.json"]);case"secret.cli.kimi-code":{let W=r(process.env.KIMI_CODE_HOME,"~/.kimi-code",Z,Q),K=r(process.env.KIMI_SHARE_DIR,"~/.kimi",Z,Q);return i($,W,["server.token"])||w2($,W,["credentials"])||w2($,K,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let W=["config.toml","mcp.json"],K=s($).split("/");return K.at(-1)==="mcp.json"&&K.at(-2)===".kimi-code"||i($,r(process.env.KIMI_CODE_HOME,"~/.kimi-code",Z,Q),W)||i($,r(process.env.KIMI_SHARE_DIR,"~/.kimi",Z,Q),[...W,"config.json","config.json.bak"])}case"secret.cli.opencode":{let W=K1(r(process.env.XDG_DATA_HOME,"~/.local/share",Z,Q),"opencode"),K=s($).split("/").at(-1)??"",Y=process.env.OPENCODE_DB?.trim(),B=Y&&Y!==":memory:"?[Y,`${Y}-wal`,`${Y}-shm`]:[];return i($,W,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(K)&&i($,W,[K])||B.some((q)=>v2($,q,Z,Q))}case"secret.cli.opencode.config":{let W=process.env.OPENCODE_CONFIG_DIR?r(process.env.OPENCODE_CONFIG_DIR,"~/.config/opencode",Z,Q):K1(r(process.env.XDG_CONFIG_HOME,"~/.config",Z,Q),"opencode"),K=process.env.ProgramData?[K1(r(process.env.ProgramData,"",Z,Q),"opencode")]:[],Y=["opencode.json","opencode.jsonc"];return Y.includes(s($).split("/").at(-1)??"")||i($,W,Y)||(process.env.OPENCODE_CONFIG?.trim()?v2($,process.env.OPENCODE_CONFIG,Z,Q):!1)||["/Library/Application Support/opencode","/etc/opencode",...K].some((B)=>i($,N0(B,Z,Q),Y))}case"secret.cli.pi":return i($,r(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",Z,Q),["auth.json"]);case"secret.cli.pi.config":return i($,r(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",Z,Q),["models.json"]);case"secret.cli.amp":{let W=N0("~",Z,Q);return[K1(r(process.env.XDG_DATA_HOME,"~/.local/share",Z,Q),"amp"),K1(W,".local","share","amp")].some((Y)=>i($,Y,["secrets.json"]))||w2($,K1(W,".amp"),["oauth"])}case"secret.cli.amp.config":{let W=["settings.json","settings.jsonc"],K=[K1(r(process.env.XDG_CONFIG_HOME,"~/.config",Z,Q),"amp"),K1(N0("~",Z,Q),".config","amp")],Y=s($).split("/");return K.some((B)=>i($,B,W))||Y.at(-2)===".amp"&&W.includes(Y.at(-1)??"")||(process.env.AMP_SETTINGS_FILE?.trim()?v2($,process.env.AMP_SETTINGS_FILE,Z,Q):!1)}case"secret.cli.cursor":{let W=K1(r(process.env.XDG_CONFIG_HOME,"~/.config",Z,Q),"cursor"),K=K1(r(process.env.CURSOR_DATA_DIR,"~/.cursor",Z,Q),"projects");return i($,N0("~/.cursor",Z,Q),["auth.json"])||i($,W,["auth.json"])||s($).split("/").at(-1)==="mcp-auth.json"&&e0(s($),s(K))}case"secret.cli.cursor.config":{let W=s($).split("/");return W.at(-1)==="mcp.json"&&W.at(-2)===".cursor"}default:return!1}})?.id??null}function r($,Z,J,Q){return N0($?.trim()?$:Z,J,Q)}function i($,Z,J){return J.some((Q)=>bX($,K1(Z,Q)))}function w2($,Z,J){return J.some((Q)=>e0(s($),s(K1(Z,Q))))}function v2($,Z,J,Q){return bX($,N0(Z,J,Q))}function bX($,Z){return s($)===s(Z)}function K1($,...Z){return d1([$,...Z].filter(Boolean).join("/"))}function sL($,Z,J,Q,X){if(J.length===0)return!1;let W=s(h2($,Z,X));return J.some((K)=>e0(W,s(h2(K,Q,X))))}function rL($,Z,J,Q,X){if(J.length===0)return!1;let W=s(h2($,Z,X));if(!W)return!1;let K=process.env.HOME??BZ(),Y=K?d1(m(K,b1,X)):"",B=s(Y),q=process.env.CC_SAFETY_NET_HOME,U=s(q?d1(m(k3(q),b1,X)):Y&&d1(m(`${Y}/.cc-safety-net`,b1,X)));if(U&&e0(W,U))return!1;return J.some((G)=>{let j=s(h2(G,Q,X));if(!j)return!1;if(B&&(B===j||B.startsWith(j.endsWith("/")?j:`${j}/`)))return!1;return e0(W,j)})}function nL($){let Z=$.split("/");return Z.some((J)=>pL.has(J))||cL.some(([J,Q])=>Z.some((X,W)=>X===J&&Z[W+1]===Q))}function aL($,Z){let J=$.lastIndexOf("."),Q=J>0&&J<$.length-1?$.slice(J+1):"";if(Q==="")return null;for(let X of a6)if(Q===X.extension&&F0(X.id,Z))return X.id;for(let X of o6)if(X.pattern.test(Q)&&F0(X.id,Z))return X.id;return null}function s($){return $.toLowerCase()}function F0($,Z){if(!Z?.disabledRules)return!0;if(Array.isArray(Z.disabledRules))return!Z.disabledRules.includes($);return!Z.disabledRules.has($)}function N0($,Z,J){let{home:Q,normalized:X}=qZ($,J);if(!X)return"";if(!Q)return X;let W=UZ(X,Q),K=h3(W)?W:d1(k3(Z,W)),Y=d1(m(K,b1,J));if(!e0(Y,Q)){if(h3(W))return Y;return Y===K?X:Y}let B=Y.slice(Q.length);return B?`~${B}`:"~"}function GX($,Z){return $===Z||$.startsWith(`${Z}/`)}function oL($,Z,J){let{home:Q,normalized:X}=qZ($,J);if(!X||!Q)return"";let W=UZ(X,Q),K=hO.normalize(h3(W)?W:d1(k3(Z,W))),Y=d1(process.env.HOME??BZ()),B=(G)=>process.platform==="win32"?G.toLowerCase():G,q=[Q,Y].find((G)=>G!==""&&e0(B(K),B(G)));if(q===void 0)return"";let U=K.slice(q.length);return U?`~${U}`:"~"}function h2($,Z,J){let{home:Q,normalized:X}=qZ($,J);if(!X)return"";let W=Q?UZ(X,Q):X;return d1(m(h3(W)?W:k3(Z,W),b1,J))}function qZ($,Z){let J=process.env.HOME??BZ(),Q=J?d1(m(J,b1,Z)):"",X=d1(tL(n1($)));return{home:Q,normalized:X}}function tL($){if(!$.trim().toLowerCase().startsWith("file:"))return $;try{return kO($)}catch{return $}}function UZ($,Z){if($==="~")return Z;if($.startsWith("~/"))return K1(Z,$.slice(2));return $}function eL($){if(process.platform==="win32")return!0;return gO.parse($).root.length>1}function d1($){let Z=$.trim(),J=(eL(Z)?Z.replace(/\\/g,"/"):Z).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(J==="/")return J;return J.replace(/\/+$/g,"")}function e0($,Z){return $===Z||$.startsWith(Z.endsWith("/")?Z:`${Z}/`)}function $$($){return $.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??$}class g$ extends Error{stage;evaluation;name="GuardEvaluationError";constructor($,Z,J){super(`CC Safety Net ${$} dependency failed`,{cause:J});this.stage=$;this.evaluation=Z}}var $M={findPolicyMutation:$X,findGitMetadataMutation:r5,resolveGitMetadata:j9,loadPolicySnapshot:F5,findSensitiveTarget:LX,analyzeCommand:WZ,getModes:m4};function fX($,Z={}){let J={...$M,...Z.dependencies},Q=QM($),X=g2($)?$.command:Q,W=Z$("policy-protection",X,()=>R4($,Z.factParserDependencies)),K=L1(W,"declared-command");if(g2($)&&$.command?.trim()&&K?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:q0,intent:"stop_and_explain",evidence:[{kind:"command",command:$.command,segment:$.command}]}};if(L1(W,"input-candidate")?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:eZ,intent:"stop_and_explain",evidence:[]}};let Y=Z$("policy-protection",X,()=>J.resolveGitMetadata($.context.executionCwd)),B=Z$("policy-protection",X,()=>J.findPolicyMutation(W));if(B){let M=X??B.target;return{stage:"policy-protection",decision:{kind:"deny",reason:eQ,intent:"hard_stop",evidence:[{kind:"command",command:M,segment:B.target},{kind:"path",target:B.target}]}}}let q=Z$("policy-protection",X,()=>J.findGitMetadataMutation(W,Y));if(q){let M=X??q.target;return{stage:"policy-protection",decision:{kind:"deny",reason:E1,intent:"hard_stop",evidence:[{kind:"command",command:M,segment:q.target},{kind:"path",target:q.target}]}}}let U=Z$("config-load",X,()=>J.loadPolicySnapshot({...Z.policyOptions,cwd:$.context.configCwd})),G=U.policy,j=J.getModes(G),H={level:j.effectiveLevel,...ZM(U)},_=G.secretProtection.enabled===!1?null:Z$("secret-protection",X,()=>J.findSensitiveTarget(W,G.secretProtection,{strict:g2($)?j.strict:void 0}));if(_){let M=X??_.target;return{stage:"secret-protection",...H,decision:{kind:"deny",reason:HX,intent:"hard_stop",ruleId:_.ruleId,evidence:[{kind:"command",command:M,segment:_.target},{kind:"path",target:_.target}]}}}if(!g2($))return{stage:"non-command",...H,decision:{kind:"allow"}};if(!$.command||$.command.trim()==="")return{...GZ("command-validation",X),...H};let O=Z$("command-analysis",X,()=>{return J.analyzeCommand($.command,{cwd:$.context.executionCwd,shell:$.route.shell,policySnapshot:U,environment:G0(),protectedGitMetadata:Y,effectiveCapabilities:j.capabilities,strict:j.strict,paranoidRm:j.paranoidRm,paranoidInterpreters:j.paranoidInterpreters,worktreeMode:j.worktreeMode},JM(W),W.store)});if(O)return{stage:"command-analysis",...H,decision:O};return{stage:"command-analysis",...H,decision:{kind:"allow"}}}function ZM($){if($.state==="ready")return{};return{configFallback:{reason:$.reason}}}function JM($){return L1($,"declared-command")?.program}function QM($){try{return q$($.input)}catch(Z){let J=g2($)?$.command:void 0;throw new g$("policy-protection",GZ("policy-protection",Z instanceof U0?void 0:J),Z)}}function Z$($,Z,J){try{return J()}catch(Q){throw new g$($,GZ($,Q instanceof U0?void 0:Z),Q)}}function GZ($,Z){return{stage:$,decision:{kind:"deny",reason:n2,intent:"stop_and_explain",evidence:Z?[{kind:"command",command:Z,segment:Z}]:[]}}}function g2($){return $.route.kind==="command"}import{realpathSync as XM,statSync as WM}from"node:fs";import{isAbsolute as PX,relative as KM,resolve as YM,sep as BM}from"node:path";function qM($,Z){if(k0($))return;let J=Z.flatMap((X)=>HZ(X));if(!J[0])return;let Q=HZ(PX($)?$:YM(J[0],$))[0];if(!Q)return;return J.some((X)=>CX(Q,X))?Q:void 0}function UM($){return $.flatMap((Z)=>HZ(Z))[0]}function HZ($){try{let Z=XM($);return WM(Z).isDirectory()?[Z]:[]}catch{return[]}}function CX($,Z){let J=KM(Z,$);return J===""||J!==".."&&!J.startsWith(`..${BM}`)&&!PX(J)}function Rf($,Z){try{let J=fX($,Z.guard);return AX($,J,Z),J}catch(J){if(!(J instanceof g$))throw J;throw AX($,J.evaluation,Z,!(J.cause instanceof U0),{stage:J.stage,errorCode:GM(J.cause)}),J}}function AX($,Z,J,Q=!0,X){tZ(oZ($,Z,J.guard?.auditAllowed??!1,Q,X),J.audit.getSessionId,{agent:J.audit.agent,shape:J.audit.shape,homeDir:J.audit.homeDir})}function GM($){if($ instanceof O1)return"path-canonicalization-limit";if($ instanceof U0)return"tool-input-limit";if($ instanceof I0)return"structural-shell-syntax-limit";return"unexpected-error"}
64
- export{sZ as b,RW as c,kM as d,xM as e,lM as f,h as g,X1 as h,k2 as i,K0 as j,VZ as k,RZ as l,OM as m,LM as n,MM as o,FM as p,xX as q,I1 as r,l2 as s,m2 as t,CZ as u,w1 as v,yZ as w,wZ as x,fM as y,S0 as z,PM as A,CM as B,vZ as C,AM as D,gZ as E,c2 as F,EM as G,d2 as H,LW as I,dZ as J,nZ as K,hW as L,tM as M,WF as N,KF as O,YF as P,BF as Q,O1 as R,c$ as S,m as T,b1 as U,G0 as V,$4 as W,K6 as X,w0 as Y,U0 as Z,ZK as _,q$ as $,U6 as aa,G6 as ba,I0 as ca,R4 as da,jY as ea,E1 as fa,r5 as ga,j9 as ha,f7 as ia,UD as ja,J1 as ka,dB as la,iB as ma,m4 as na,M$ as oa,d6 as pa,VN as qa,nQ as ra,fb as sa,WZ as ta,P7 as ua,U2 as va,v7 as wa,w7 as xa,t4 as ya,A7 as za,kN as Aa,e6 as Ba,G2 as Ca,N$ as Da,Oq as Ea,V$ as Fa,dN as Ga,iN as Ha,sN as Ia,$3 as Ja,J3 as Ka,z$ as La,KV as Ma,Z3 as Na,YV as Oa,Vq as Pa,BV as Qa,D$ as Ra,e7 as Sa,$5 as Ta,eQ as Ua,$X as Va,HX as Wa,LX as Xa,I$ as Ya,FV as Za,NV as _a,Q9 as $a,yV as ab,wV as bb,M5 as cb,pV as db,cV as eb,W9 as fb,F5 as gb,rV as hb,tq as ib,g$ as jb,qM as kb,UM as lb,CX as mb,Rf as nb};