cc-safety-net 2.0.4 → 2.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/amp/cc-safety-net.ts +49 -49
- package/dist/bin/cc-safety-net.js +126 -101
- package/dist/chunks/index-3a1zwkma.js +64 -0
- package/dist/index.js +1 -1
- package/dist/openclaw/cc-safety-net/index.js +49 -49
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +1 -1
- package/package.json +3 -3
- package/dist/chunks/index-xvfhq21r.js +0 -64
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
var zX=[/\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 Q0($){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 XZ(Z)}function XZ($){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 zX)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 bX($){return KZ($).reduceRight((J,Q)=>`${J.slice(0,Q.valueStart)}<redacted>${J.slice(Q.valueEnd)}`,$)}function cL($){return XZ(bX($))}function dL($){return KZ($).map((Z)=>$.slice(Z.valueStart,Z.valueEnd))}function iL($){return/[A-Za-z_][A-Za-z0-9_]*=/.test($)}function KZ($){let Z=[],J=/[A-Za-z_][A-Za-z0-9_]*=/g;for(let Q of $.matchAll(J)){let X=Q.index,K=$[X-1];if(X>0&&K&&!/[\s"'([{]/.test(K))continue;let Y=X+Q[0].length;if(Y>=$.length)continue;Z.push({valueStart:Y,valueEnd:IX($,Y)})}return Z}function IX($,Z){if($.startsWith("$(",Z))return fX($,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 fX($,Z){let J=0,Q;for(let X=Z;X<$.length;X++){let K=$[X];if(Q){if(Q==='"'&&K==="\\")X++;else if(K===Q)Q=void 0;continue}if(K==='"'||K==="'"){Q=K;continue}if(K==="$"&&$[X+1]==="("){J++,X++;continue}if(K!==")")continue;if(J--,J===0)return X+1}return $.length}import{randomBytes as PX}from"node:crypto";import{closeSync as v3,constants as g$,fstatSync as y3,fsyncSync as CX,lstatSync as F0,mkdirSync as YZ,openSync as BZ,readdirSync as u3,readFileSync as AX,realpathSync as A0,renameSync as EX,rmdirSync as TX,statSync as w3,unlinkSync as h3,writeFileSync as SX}from"node:fs";import{isAbsolute as WZ,join as $$,normalize as yX,parse as qZ,relative as g3,resolve as k3,sep as x$}from"node:path";var wX=Symbol("PolicyFilesystemScope"),vX=Symbol("PolicyFilesystemTarget"),UZ=g$.O_NOFOLLOW??0;class u extends Error{constructor($){super(`Unable to access ${$} filesystem safely.`);this.name="PolicyFilesystemError"}}function D1($,Z){return{[wX]:!0,root:k3($),label:Z}}function l$($,Z){let J=yX(Z);if(Z===""||WZ(Z)||J===".."||J.startsWith(`..${x$}`))throw new u($.label);return{[vX]:!0,scope:$,relativePath:J,path:$$($.root,J)}}function X1($,Z){let J=g3($.root,k3(Z));return l$($,J)}function u2($,Z="rules policy"){let J=k3($),Q=qZ(J).dir;return l$(D1(Q,Z),g3(Q,J))}function X0($){try{if(!W1($,!1).exists)return null;let J=BZ($.path,g$.O_RDONLY|UZ);try{let Q=y3(J);if(!Q.isFile())throw new u($.scope.label);let X=AX(J,"utf-8"),K=F0($.path);if(!K.isFile()||K.isSymbolicLink()||Q.dev!==K.dev||Q.ino!==K.ino)throw new u($.scope.label);return W1($,!1),X}finally{v3(J)}}catch(Z){N0($.scope.label,Z)}}function GZ($,Z,J=384,Q){let X=`${$.path}.${PX(8).toString("hex")}.tmp`,K=null;try{gX($),W1($,!0),K=BZ(X,g$.O_CREAT|g$.O_EXCL|g$.O_WRONLY|UZ,J);let Y=y3(K);if(!Y.isFile())throw new u($.scope.label);SX(K,Z,"utf-8"),CX(K);let B=y3(K);if(!B.isFile()||B.dev!==Y.dev||B.ino!==Y.ino)throw new u($.scope.label);v3(K),K=null,W1($,!0),xX($,X,B.dev,B.ino),EX(X,$.path),Q?.($.path),W1($,!1)}catch(Y){if(K!==null)mX(K);pX(X),N0($.scope.label,Y)}}function HZ($,Z){if($.path===Z.path)return!0;try{if(!W1($,!1).exists||!W1(Z,!1).exists)return!1;return A0($.path)===A0(Z.path)}catch(J){if(J instanceof u)throw J;throw new u($.scope.label)}}function uX($){try{if(!W1($,!1,"directory").exists)return null;let J=u3($.path);return W1($,!1,"directory"),J}catch(Z){N0($.scope.label,Z)}}function oL($){let Z=uX($);if(!Z)return null;try{let J=Z.map((Q)=>{let X=l$($.scope,$$($.relativePath,Q)),K=F0(X.path);if(K.isSymbolicLink()||!K.isFile()&&!K.isDirectory())throw new u($.scope.label);return h2(LZ($.scope),A0(X.path),$.scope.label),{name:Q,kind:K.isDirectory()?"directory":"file"}});return W1($,!1,"directory"),J}catch(J){N0($.scope.label,J)}}function tL($){try{if(!W1($,!0).exists)return;h3($.path),W1($,!0)}catch(Z){N0($.scope.label,Z)}}function eL($){try{OZ($,$.relativePath.split(x$))}catch(Z){N0($.scope.label,Z)}}function $M($){try{if(!hX($))return;_Z($),W1($,!0,"directory")}catch(Z){N0($.scope.label,Z)}}function hX($){try{if(!W1($,!0,"directory").exists)return!1;return jZ($),!0}catch(Z){N0($.scope.label,Z)}}function W1($,Z,J="file"){let Q=x3($.scope);if(!Q)return{exists:!1};let X=$.relativePath.split(x$);for(let K of X.keys()){let Y=$$($.scope.root,...X.slice(0,K+1)),B=k$(Y);if(!B){if(K===X.length-1&&Z)return{exists:!1};return{exists:!1}}if(B.isSymbolicLink())throw new u($.scope.label);if(K<X.length-1&&!B.isDirectory())throw new u($.scope.label);if(K===X.length-1&&(J==="file"?!B.isFile():!B.isDirectory()))throw new u($.scope.label);h2(Q,A0(Y),$.scope.label)}return{exists:!0}}function jZ($){for(let Z of u3($.path)){let J=l$($.scope,$$($.relativePath,Z)),Q=F0(J.path);if(Q.isSymbolicLink()||!Q.isDirectory()&&!Q.isFile())throw new u($.scope.label);if(Q.isDirectory())jZ(J)}W1($,!1,"directory")}function _Z($){for(let Z of u3($.path)){let J=l$($.scope,$$($.relativePath,Z)),Q=F0(J.path);if(Q.isSymbolicLink())throw new u($.scope.label);if(Q.isDirectory()){_Z(J);continue}if(!Q.isFile())throw new u($.scope.label);h3(J.path)}TX($.path)}function gX($){OZ($,$.relativePath.split(x$).slice(0,-1))}function OZ($,Z){kX($.scope);let J=LZ($.scope);for(let Q of Z.keys()){let X=$$($.scope.root,...Z.slice(0,Q+1));if(!k$(X))YZ(X,{mode:448});let Y=F0(X);if(!Y.isDirectory()||Y.isSymbolicLink())throw new u($.scope.label);h2(J,A0(X),$.scope.label)}}function kX($){if(k$($.root)){if(!w3($.root).isDirectory())throw new u($.label);return}let Z=[],J=$.root;while(!k$(J)){Z.unshift(J);let Q=qZ(J).dir;if(Q===J)throw new u($.label);J=Q}if(!w3(J).isDirectory())throw new u($.label);for(let Q of Z){YZ(Q,{mode:448});let X=F0(Q);if(!X.isDirectory()||X.isSymbolicLink())throw new u($.label)}}function x3($){if(!k$($.root))return null;if(!w3($.root).isDirectory())throw new u($.label);return A0($.root)}function LZ($){let Z=x3($);if(!Z)throw new u($.label);return Z}function xX($,Z,J,Q){let X=F0(Z);if(!X.isFile()||X.isSymbolicLink()||X.dev!==J||X.ino!==Q)throw new u($.scope.label);let K=x3($.scope);if(!K)throw new u($.scope.label);h2(K,A0(Z),$.scope.label)}function h2($,Z,J){let Q=g3($,Z);if(Q===".."||Q.startsWith(`..${x$}`)||WZ(Q))throw new u(J)}function k$($){try{return F0($)}catch(Z){if(lX(Z)&&Z.code==="ENOENT")return null;throw Z}}function N0($,Z){if(Z instanceof u)throw Z;throw new u($)}function lX($){return $ instanceof Error&&"code"in $}function mX($){try{v3($)}catch{}}function pX($){try{h3($)}catch{}}import{homedir as rX}from"node:os";import{dirname as m1,isAbsolute as nX,join as T1,relative as aX,resolve as p1,sep as oX}from"node:path";var z1=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,g2="rulebook.json",k2=".cc-safety-net/rules";var MZ=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,cX=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,dX=/^[A-Za-z0-9._-]+$/,iX=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),sX="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l3=new RegExp(`^${iX}/(${z1.source.slice(1,-1)})/${sX}$`);function FZ($){return`.cc-safety-net/rules/${$}/rulebook.json`}function m$($){if(J$($))try{return Z$($),null}catch(Z){return Z instanceof Error?Z.message:String(Z)}return z1.test($)?null:`Local rulebook sources must be bare names matching ${z1}: ${$}`}function Z$($){if($.startsWith("github:"))throw Error(`Invalid rulebook source: ${$}`);let Z=$.match(MZ);if(!Z?.[1]||!Z[2]||!Z[3])throw Error(`Invalid GitHub rulebook source: ${$}`);let[J,Q,...X]=Z[3].split("/");if(!J||!dX.test(J))throw Error(`GitHub rulebook refs must be a single path segment: ${$}`);if(!Q||X.length>0||!z1.test(Q))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${$}`);return{owner:Z[1],repo:Z[2],ref:J,path:FZ(Q),name:Q}}function NZ($){return cX.test($)}function J$($){return MZ.test($)}function m3($){if(!z1.test($))throw Error(`Local rulebook sources must be bare names matching ${z1}: ${$}`)}var RZ="rule.json",x2="policy.json",DZ="rule.lock",tX="config.json",zZ=".cc-safety-net",eX="rules",VZ="cache",$K="CC_SAFETY_NET_HOME",S1="`cc-safety-net rule sync`";function ZK($){return p1($??process.cwd(),k2)}function bZ($){return T1(ZK($),RZ)}function K0($){return $?.userConfigDir??($?.userConfigPath?m1($.userConfigPath):T1(JK(),eX))}function JK(){let $=process.env[$K];return $?p1($):T1(rX(),zZ)}function IZ($){return T1(K0($),RZ)}function WM($){return T1(K0($),DZ)}function E0($){return T1(m1($),DZ)}function qM($={}){return T1(m1(K0($)),tX)}function UM($={}){return p1($.cwd??process.cwd(),".safety-net.json")}function fZ($){let Z=$.userConfigPath??IZ($),J=$.projectConfigPath??bZ($.cwd),Q=PZ(Z,$),X=CZ(J,$);return{userConfigPath:Z,projectConfigPath:J,userLockPath:E0(Z),projectLockPath:E0(J),userScope:Q,projectScope:X,userConfigTarget:X1(Q,Z),projectConfigTarget:X1(X,J),userLockTarget:X1(Q,E0(Z)),projectLockTarget:X1(X,E0(J))}}function GM($){let Z=$.global?$.userConfigPath??IZ($):$.projectConfigPath??bZ($.cwd),J=$.global?PZ(Z,$):CZ(Z,$),Q=E0(Z);return{configDir:m1(Z),configPath:Z,lockPath:Q,filesystemScope:J,configTarget:X1(J,Z),lockTarget:X1(J,Q)}}function PZ($,Z){let J=Z.userConfigPath?m1(m1(p1(Z.userConfigPath))):m1(p1(Z.userConfigDir??K0(Z)));return D1(J,"user policy")}function CZ($,Z){let J=p1(Z.cwd??process.cwd()),Q=p1($),X=aX(J,Q);if(X!==".."&&!X.startsWith(`..${oX}`)&&!nX(X))return D1(J,"project policy");return D1(m1(m1(Q)),"project policy")}function AZ($){if($.kind==="github"&&$.display_ref)return`${$.owner}/${$.repo}#${$.display_ref}/${$.name}`;return $.spec}function l2($,Z){let J=$.digest.startsWith("sha256:")?$.digest.slice(7):$.digest;return T1(EZ(Z),"rulebooks",`${QK($)}--${J.slice(0,12)}`,g2)}function HM($){return T1(EZ($),"rulebooks")}function m2($,Z){let J=Z;return{cacheConfigDir:$,cwd:Z.cwd,global:J.global}}function QK($){return($.kind==="github"&&$.display_ref?`${$.owner}/${$.repo}#${$.display_ref}/${$.name}`:$.spec).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"rulebook"}function EZ($){let Z=$?.cacheConfigDir??K0($),J=$;if(J&&!J.global&&J.cwd&&p1(Z)===p1(J.cwd))return T1(p1(J.cwd),zZ,VZ);return T1(m1(Z),VZ)}import{lstatSync as TZ,readdirSync as XK,readFileSync as vZ,rmdirSync as KK,statSync as SZ,unlinkSync as YK,utimesSync as BK,writeFileSync as WK}from"node:fs";import{dirname as qK,join as Q$}from"node:path";var p2=30,p3=1,c3=365;function c2($){if(typeof $!=="number"||!Number.isInteger($))return 30;if($<1)return 1;return $>365?365:$}var i3=86400000,UK=".last-prune",GK=/^\d{4}-\d{2}$/,HK=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,yZ=($)=>Math.floor($/i3);function jK($){try{let Z=Q$(qK(K0($)),x2),J=JSON.parse(vZ(Z,"utf-8"));return c2(J?.audit?.retention_days)}catch{return p2}}function uZ($,Z=()=>new Date){try{let J=Z().getTime();if(!SZ($,{throwIfNoEntry:!1})?.isDirectory())return;let Q=Q$($,UK),X=SZ(Q,{throwIfNoEntry:!1})?.mtimeMs;if(X!==void 0&&yZ(X)===yZ(J))return;let K=J-jK()*i3,Y=new Date(J).toISOString().slice(0,7);for(let B of d3($)){if(B.isDirectory()){_K(Q$($,B.name),K,Y);continue}if(B.isFile()&&B.name.endsWith(".jsonl"))OK(Q$($,B.name),K)}WK(Q,"",{mode:384}),BK(Q,J/1000,J/1000)}catch{}}function _K($,Z,J){for(let Q of d3($)){if(!Q.isDirectory()||!GK.test(Q.name))continue;let X=Q$($,Q.name);for(let K of d3(X)){if(!K.isFile())continue;let Y=HK.exec(K.name);if(!Y||Y[2]!==Q.name)continue;let B=Date.parse(`${Y[1]}T00:00:00.000Z`)+i3;if(!Number.isFinite(B)||B>=Z)continue;hZ(Q$(X,K.name))}if(Q.name!==J)wZ(X)}wZ($)}function OK($,Z){try{let J=TZ($);if(J.mtimeMs>=Z)return;let Q=vZ($,"utf-8").split(`
|
|
2
|
-
`).filter((X)=>X.trim()).map(LK);if(Q.length===0)return;if(Q.some((X)=>X===void 0||X>=Z))return;if(TZ($).mtimeMs!==J.mtimeMs)return;hZ($)}catch{}}function LK($){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 d3($){try{return XK($,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function hZ($){try{YK($)}catch{}}function wZ($){try{KK($)}catch{}}import{randomBytes as MK}from"node:crypto";import{appendFileSync as FK,mkdirSync as NK}from"node:fs";import{homedir as VK,userInfo as RK}from"node:os";import{isAbsolute as DK,join as s3}from"node:path";var zK="2.0.4",bK=1e4,IK=2000,fK=256,PK=32768;function CK($){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 AK($){return($??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function r3($,Z,J,Q,X,K={}){let Y=CK($);if(!Y)return;let B=K.homeDir??gZ();if(!B)return;let W=EK(B);if(!W)return;try{let q=(K.now??(()=>new Date))().toISOString(),U=d2(Q0(Z),bK),H=d2(Q0(J),IK),j=K.toolName?d2(Q0(K.toolName),fK):void 0,G=X===null?void 0:d2(Q0(X),PK),_=s3(W,AK(G?.value??null),q.slice(0,7));NK(_,{recursive:!0,mode:448});let O=s3(_,`${q.slice(0,10)}-${Y}.jsonl`),M={ts:q,id:(K.createId??(()=>MK(8).toString("hex")))(),v:zK,sessionId:Y,decision:K.decision??"deny",agent:K.agent,shape:K.shape,level:K.level,configFallback:K.configFallback,toolName:j?.value,command:U.value,segment:H.value,...U.truncated||H.truncated||j?.truncated||G?.truncated?{truncated:!0}:{},reason:Q,ruleId:K.ruleId,intent:K.intent,failureStage:K.failureStage,errorCode:K.errorCode,cwd:G?.value??null};FK(O,`${JSON.stringify(M)}
|
|
3
|
-
`,{encoding:"utf-8",mode:384}),uZ(W,K.now)}catch{}}function d2($,Z){return{value:$.slice(0,Z),truncated:$.length>Z}}function gZ($=process.env.CC_SAFETY_NET_AUDIT_HOME||process.env.HOME){let Z=$||VK()||RK().homedir;return Z&&DK(Z)?Z:null}function EK($=gZ()){return $?s3($,".cc-safety-net","logs"):null}function xZ($,Z,J,Q=!0,X){if(Z.decision.kind==="allow"){if(!J||$.route.kind!=="command")return;let B=kZ($);return{decision:"allow",command:B,segment:B,reason:"allowed",cwd:$.context.executionCwd,toolName:$.toolName,level:Z.level,...Z.configFallback?{configFallback:!0}:{}}}let K=Z.decision.evidence.find((B)=>B.kind==="command"),Y=K?.command??(Q?kZ($):"");return{decision:"deny",command:Y,segment:K?.segment??Y,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 kZ($){return"command"in $?$.command??"":""}function lZ($,Z,J){if(!$)return;let Q;try{Q=Z()}catch{return}if(typeof Q!=="string"||!Q.trim())return;r3(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 EM($,Z,J){let Q;try{Q=Z()}catch{return}if(typeof Q!=="string"||!Q.trim())return;r3(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 V0="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",Y0="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",mZ="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.",i2="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";function cZ($){let{reason:Z,command:J,segment:Q,toolName:X}=$,K=$.maxLen??200,Y=$.redact??((W)=>W),B=`BLOCKED by CC Safety Net
|
|
4
|
-
|
|
5
|
-
Reason: ${Y(Z)}`;if($.ruleId)B+=`
|
|
6
|
-
|
|
7
|
-
Rule: ${$.ruleId}`;if(X)B+=`
|
|
8
|
-
|
|
9
|
-
Tool: ${X}`;if(J){let W=Y(J);B+=`
|
|
10
|
-
|
|
11
|
-
Command: ${pZ(W,K)}`}if(Q&&Q!==J){let W=Y(Q);B+=`
|
|
12
|
-
|
|
13
|
-
Segment: ${pZ(W,K)}`}if($.configWarning)B+=`
|
|
14
|
-
|
|
15
|
-
Config warning: ${Y($.configWarning)}`;return B+=`
|
|
16
|
-
|
|
17
|
-
${TK($.intent??"manual_only")}`,B}function TK($){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 pZ($,Z){return $.length>Z?`${$.slice(0,Z)}...`:$}function hM($,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 gM($={}){return{reason:i2,intent:"stop_and_explain",command:$.command,segment:$.segment??$.command,toolName:$.toolName}}function kM($){return cZ({...$,redact:Q0})}function xM($){return Q0($ instanceof Error?$.message:String($))}import{lstatSync as SK,realpathSync as yK}from"node:fs";import{homedir as wK,tmpdir as vK}from"node:os";var R0={realpath:($)=>{try{return yK($)}catch{return null}},entryKind:($)=>{let Z=SK($,{throwIfNoEntry:!1});if(!Z)return"missing";return Z.isSymbolicLink()?"symlink":"present"}};function X$(){return process.env.HOME||wK()}function B0(){return{env:new Map(Object.entries(process.env).flatMap(([$,Z])=>Z===void 0?[]:[[$,Z]])),home:X$(),tmpdir:vK(),paths:R0}}var uK=["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.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"],s2=new Set(uK),r2=[{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.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"}],hK=new Map(r2.map(($)=>[$.id,$.intent])),dZ=new Set(r2.filter(($)=>$.catastrophic).map(($)=>$.id));function N($,Z){return{id:$,reason:Z,intent:hK.get($)??"manual_only"}}function T($,Z){if(!$)return null;if(dZ.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 a($,Z,J){if(dZ.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 n3($,Z){return Object.freeze(Object.fromEntries(r2.map((J)=>{let Q=J.activationCapability?Z[J.activationCapability]:void 0,X=Q?.enabled??!0,K=$.destructiveCommandRuleOverrides[J.id],Y=J.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...K?{override:K}:{}}:$.destructiveCommandProtectionEnabled?K?{enabled:K==="on",inheritedEnabled:X,changesInherited:K==="on"!==X,source:"rule_override",...J.activationCapability?{activationCapability:J.activationCapability}:{},override:K}:{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}:{},...K?{override:K}:{}};return[J.id,Object.freeze(Y)]})))}function iZ($,Z){return Object.freeze({...$,effectiveDestructiveCommandRules:n3($,Z)})}var n2=10,K$=20,T0=/^[a-zA-Z][a-zA-Z0-9_-]*$/,Y$=256,$1=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),sZ=new Set(["python","python3","python2","node","ruby","perl"]),rZ=/^python(?:[23](?:\.\d+)*)?$/,a2=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 gK}from"node:util";var kK=new Set(["applypatch","patch"]),xK=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),lK=new Set(["grep","grepsearch","rg"]),mK=new Set(["findbyname","glob"]),pK=new Set(["findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),cK=new Set(["command","diff","input","patch","patchtext"]),nZ=new TextEncoder,dK=new TextDecoder,iK=/\s/,sK=64;class W0 extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var p$=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function $8($){return $.replace(/[-_\s]/g,"").toLowerCase()}function t2($){return pK.has($8($))}function rK($){let Z=$8($);if(kK.has(Z))return"patch";if(lK.has(Z))return"grep";if(mK.has(Z))return"glob";if(xK.has(Z))return"path";return"unknown"}function B$($){if(!$||typeof $!=="object")return;K8($);let Z=Object.getOwnPropertyDescriptor($,"command");if(!Z){if("command"in $)c1();return}if(Z.get||Z.set)c1();let J=Z.value;return typeof J==="string"&&J!==""?J:void 0}function e3($,Z){return Z8($,Z,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Z8($,Z,J,Q){let X=X8($,J,Q);if(!X)return[];let K=X.entries.flatMap(([Y,B])=>{let W=Z8(B,Z,J,Q+1);return typeof B==="string"&&Z.has(J8(Y))?[B]:W});return J.ancestors.delete(X.object),K}function J8($){return $.replace(/-/g,"_").toLowerCase()}function $6($){return Q8($,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(aK)}function Q8($,Z,J,Q){let X=X8($,J,Q);if(typeof $==="string")return Z?[$]:[];if(!X)return[];let K=X.entries.flatMap(([Y,B])=>Q8(B,X.array?Z:cK.has(J8(Y)),J,Q+1));return J.ancestors.delete(X.object),K}function nK($,Z,J){if(Z.nodes++,$!==null&&typeof $==="object"&&J>p$.maxDepth||Z.nodes>p$.maxNodes)c1();if(typeof $!=="string")return;let Q=Buffer.byteLength($);if(Z.stringBytes+=Q,Q>p$.maxStringBytes||Z.stringBytes>p$.maxAggregateStringBytes)c1()}function X8($,Z,J){if(nK($,Z,J),!$||typeof $!=="object")return null;let Q=K8($);if(Z.ancestors.has($))c1();let X=Reflect.ownKeys($);if(Z.keys+=X.length,Z.keys>p$.maxKeys)c1();let K=X.flatMap((Y)=>{let B=Object.getOwnPropertyDescriptor($,Y);if(!B||B.get||B.set)c1();return typeof Y==="string"&&B.enumerable?[[Y,B.value]]:[]});return Z.ancestors.add($),{object:$,array:Q,entries:K}}function K8($){if(gK.isProxy($))c1();let Z=Array.isArray($),J=Object.getPrototypeOf($);if(Z&&J!==Array.prototype||!Z&&J!==Object.prototype&&J!==null)c1();return Z}function c1(){throw new W0}function aK($){let Z=[],J=$.split(/\r?\n/),Q=!1,X=!1,K=null,Y=null,B=()=>{X=!1,K=null,Y=null};for(let W=0;W<J.length;W++){let q=J[W]??"";if(q==="*** Begin Patch"){Q=!0,B();continue}if(q==="*** End Patch"){Q=!1,B();continue}if(q.startsWith("@@")){let U=oK(q);if(X=!0,K=U?.oldLines??null,Y=U?.newLines??null,K===0&&Y===0)B();continue}if(X&&K!==null&&Y!==null){let U=q.startsWith(" ")||q.startsWith("-")?1:0,H=q.startsWith(" ")||q.startsWith("+")?1:0;if(K=Math.max(0,K-U),Y=Math.max(0,Y-H),K===0&&Y===0)B();continue}if(q.startsWith("*** ")){B(),Z.push(...a3(q));continue}if(X)continue;if(q.startsWith("diff --git ")){Z.push(...a3(q));continue}if(q.startsWith("--- ")){let U=J[W+1]??"";if(!U.startsWith("+++ "))continue;Z.push(...t3(o2(q.slice(4),!0),o2(U.slice(4),!0))),W++;continue}if(!Q)Z.push(...a3(q))}return Z}function oK($){let Z=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec($);if(!Z)return null;return{oldLines:Number(Z[1]??1),newLines:Number(Z[2]??1)}}function a3($){let Z=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec($);if(Z?.[1])return eZ(Z[1]);let J=/^\*\*\* Move to: (.+)$/.exec($);if(J?.[1])return eZ(J[1]);if($.startsWith("diff --git "))return tK($.slice(11));let Q=/^--- (.+)$/.exec($);if(Q?.[1])return tZ(Q[1]);let X=/^\+\+\+ (.+)$/.exec($);if(X?.[1])return tZ(X[1]);let K=/^(?:rename|copy) (?:from|to) (.+)$/.exec($);if(K?.[1])return KY(K[1]);return[]}function tK($){let Z=eK($);if(Z.length===2&&Z[0]&&Z[1])return t3(Z[0],Z[1]);let J=$Y($);return J?t3($.slice(J.oldStart,J.oldEnd),$.slice(J.newStart,J.newEnd)):[]}function eK($){let Z=[],J=0;while(J<$.length&&Z.length<2){while(S0($[J]))J++;if(J>=$.length)break;let Q=$[J]==='"'||$[J]==="'"?$[J]:void 0;if(!Q){let K=J;while(J<$.length&&!S0($[J]))J++;Z.push($.slice(K,J));continue}let X=Y8($,J,Q);if(!X)return[];Z.push(X.value),J=X.end}while(S0($[J]))J++;return J===$.length?Z:[]}function $Y($){let Z=0;while(Z<$.length&&S0($[Z]))Z++;let J=$.length;while(J>Z&&S0($[J-1]))J--;let Q=0,X=Z;while(X<J){if(!S0($[X])){X++;continue}let K=X;while(X<J&&S0($[X]))X++;if(K===Z||X===J)continue;if(Q++,Q>sK)c1();if(ZY($,Z,K,X,J))return{oldStart:Z,oldEnd:K,newStart:X,newEnd:J}}return null}function ZY($,Z,J,Q,X){if(o3($,Z,J,Q,X))return!0;let K=aZ($,"/",Z,J),Y=aZ($,"/",Q,X);if(K<=Z||Y<=Q)return!1;if(o3($,Z,K,Q,Y))return!1;return o3($,K+1,J,Y+1,X)}function o3($,Z,J,Q,X){if(J-Z!==X-Q)return!1;for(let K=0;K<J-Z;K++)if($[Z+K]!==$[Q+K])return!1;return!0}function aZ($,Z,J,Q){for(let X=J;X<Q;X++)if($[X]===Z)return X;return-1}function S0($){return $!==void 0&&iK.test($)}function Y8($,Z,J){let Q=[],X=Z+1;while(X<$.length){let K=$[X]??"";if(K===J)return{value:dK.decode(Uint8Array.from(Q)),end:X+1};if(K!=="\\"||J==="'"){Q.push(...nZ.encode(K)),X++;continue}let Y=$.slice(X+1),B=/^[0-7]{1,3}/.exec(Y)?.[0];if(B){Q.push(Number.parseInt(B,8)),X+=B.length+1;continue}Q.push(...nZ.encode(JY(Y[0]??""))),X+=2}return null}function JY($){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
18
|
-
`,r:"\r",t:"\t",v:"\v"}[$]??$}function QY($){return c$(YY($))}function t3($,Z){if($==="/dev/null")return oZ(Z);if(Z==="/dev/null")return oZ($);if($.startsWith("a/")&&Z.startsWith("b/"))return[$.slice(2),Z.slice(2)].flatMap(c$);let J=XY($,Z)??($===Z?B8($):null);return[$,Z,...J?[J]:[]].flatMap(c$)}function oZ($){let Z=B8($);return[$,...Z?[Z]:[]].flatMap(c$)}function B8($){let Z=$.indexOf("/");return Z>0&&Z<$.length-1?$.slice(Z+1):null}function XY($,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 tZ($){return QY(o2($,!0))}function KY($){return c$(o2($,!1))}function o2($,Z){let J=$.trim(),Q=J[0]==='"'||J[0]==="'"?J[0]:void 0;if(Q){let X=Y8(J,0,Q);if(X&&(Z||J.slice(X.end).trim()===""))return X.value}return Z?J.split("\t",1)[0]?.trim()??"":J}function YY($){return $.startsWith("a/")||$.startsWith("b/")?$.slice(2):$}function c$($){return $===""||$==="/dev/null"?[]:[$]}function eZ($){let Z=$.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return Z===""||Z==="/dev/null"?[]:[Z]}import{basename as BY,dirname as WY,join as W8}from"node:path";var e2=Object.freeze({maxEnvironmentExpansionDepth:64,maxMissingSuffixComponents:256,maxRealpathAttempts:1024,maxProcessedCandidateBytes:4194304});class y1 extends Error{name="PathCanonicalizationLimitError";constructor(){super("Path canonicalization work limit exceeded.")}}function d$(){return{realpathAttempts:0,processedCandidateBytes:0,resolvedPaths:new Map}}function y0($){return{...d$(),environment:$}}var $4=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 Z4($,Z){return Z6($,0,Z)}function Z6($,Z,J){let Q="",X=0;while(X<$.length){if($[X]!=="$"){Q+=$[X],X++;continue}if($[X+1]==="{"){let Y=J6($,X+2),B=qY($,X,Z);if(B===null){if($4.has(Y))throw new y1;Q+=$.slice(X);break}let W=$.slice(X,B+1);Q+=UY(W,Z,J),X=B+1;continue}let K=J6($,X+1);if(!K){Q+="$",X++;continue}Q+=Q6(K,J)??`$${K}`,X+=K.length+1}return Q}function qY($,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>e2.maxEnvironmentExpansionDepth)throw new y1;X++;continue}if($[X]!=="}")continue;if(Q--,Q===0)return X}return null}function UY($,Z,J){let Q=$.slice(2,-1),X=J6(Q,0);if(!X)return $;let K=Q.slice(X.length);if(!K)return Q6(X,J)??$;let Y=[":-",":+",":=",":?","-","+","=","?"].find((q)=>K.startsWith(q));if(!Y){if($4.has(X))throw new y1;return $}if(!$4.has(X))return $;if(Y.endsWith("="))throw new y1;let B=Q6(X,J),W=Y.startsWith(":")?B!==null&&B!=="":B!==null;if(Y.endsWith("?")&&!W)throw new y1;if(Y.endsWith("-")||Y.endsWith("?"))return W?B??"":Z6(K.slice(Y.length),Z+1,J);return W?Z6(K.slice(Y.length),Z+1,J):""}function J6($,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 i($,Z,J=d$()){if(!$)return $;let Q=J.resolvedPaths.get($);if(Q!==void 0)return Q;let X=[],K=$;while(!0){if(J.realpathAttempts++,J.processedCandidateBytes+=Buffer.byteLength(K),J.realpathAttempts>e2.maxRealpathAttempts||J.processedCandidateBytes>e2.maxProcessedCandidateBytes)throw new y1;let Y=Z.realpath(K);if(Y!==null){let W=X.length===0?Y:W8(Y,...X.reverse());return J.resolvedPaths.set($,W),W}let B=WY(K);if(B===K){let W=X.length===0?K:W8(K,...X.reverse());return J.resolvedPaths.set($,W),W}if(X.length>=e2.maxMissingSuffixComponents)throw new y1;X.push(BY(K)),K=B}}function Q6($,Z){if(!$4.has($))return null;if($==="HOME")return Z.env.get("HOME")??Z.home;return Z.env.get($)??null}function J4(){return[]}function Q4(){return[]}function X4(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function GY($){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)=>U1(Z)))})}function K4($,Z,J){$.push(J),Z.reset()}function HY($,Z,J,Q,X){if(Q<=J)return;$.push({raw:Z.slice(J,Q),span:{start:J,end:Q},provenance:X})}function Y4($){let Z=[];return{parts:Z,push:(J,Q,X)=>HY(Z,$,J,Q,X)}}function X6($){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 W$($,Z,J,Q,X,K,Y){return X6({text:Q,raw:$.slice(Z,J),span:{start:Z,end:J},provenance:X,quoted:K,...Y?{parts:Y}:{}})}function U1($){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 GY(Z);if(Z.kind==="group"||Z.kind==="function")return Object.freeze({...Z,span:Object.freeze(Z.span),body:U1(Z.body)});return Object.freeze({...Z,span:Object.freeze(Z.span)})}))})}function K6($,Z,J){if(Z>=J||U8($[Z]??""))return null;let Q="",X=!1,K=!1,Y=Z;while(Y<J&&!U8($[Y]??"")){let B=$[Y]??"";if(B==="'"){X=!0;let W=q8($,Y+1,J,"'");Q+=W.text,K||=!W.closed,Y=W.next;continue}if(B==='"'){X=!0;let W=q8($,Y+1,J,'"');Q+=W.text,K||=!W.closed,Y=W.next;continue}if(B==="\\"){X=!0;let W=$[Y+1];if(!W||W===`
|
|
19
|
-
`||W==="\r"){K=!0;break}Q+=W,Y+=2;continue}if(B==="`"||$.startsWith("$(",Y)||$.startsWith("${",Y)||$.startsWith("<(",Y)||$.startsWith(">(",Y))K=!0;Q+=B,Y++}return{delimiter:Q,quoted:X,next:Y,span:{start:Z,end:Y},ambiguous:K}}function Y6($,Z,J,Q){let X=[],K=Z;for(let Y of Q){let B=K,W=!1;while(K<J){let q=jY($,K,J);if((Y.stripTabs?q.text.replace(/^\t+/,""):q.text)===Y.delimiter){Y.attach({body:Y.stripTabs?_Y($.slice(B,K)):$.slice(B,K),delimiter:Y.delimiter,quotedDelimiter:Y.quotedDelimiter,stripTabs:Y.stripTabs,bodySpan:{start:B,end:K},terminatorSpan:{start:K,end:q.contentEnd}}),K=q.next,W=!0;break}if(q.next<=K)break;K=q.next}if(W)continue;return X.push({code:"unterminated-heredoc",message:`heredoc delimiter ${Y.delimiter} was not found`,span:Y.declarationSpan}),{next:J,issues:X,terminated:!1}}return{next:K,issues:X,terminated:!0}}function q8($,Z,J,Q){let X="",K=Z;while(K<J&&$[K]!==`
|
|
20
|
-
`&&$[K]!=="\r"){let Y=$[K]??"";if(Y===Q)return{text:X,next:K+1,closed:!0};if(Q==='"'&&Y==="\\"&&$[K+1]){let B=$[K+1]??"";X+=["$","`",'"',"\\"].includes(B)?B:`\\${B}`,K+=2;continue}X+=Y,K++}return{text:X,next:K,closed:!1}}function U8($){return/[\s;&|<>)]/u.test($)||$==="`"}function jY($,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 _Y($){return $.replace(/(^|\r\n?|\n)\t+/g,"$1")}var O8=new Set(["&&","||","|","|&"]);function L8($,Z,J){let Q={start:0,end:$.length};if($.length>J.maxInputLength)return U1({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=q4($,0,$.length,Z,J,{used:0,max:J.maxWords},0);return U1({kind:"program",dialect:Z,source:$,span:Q,status:H4(X.issues,X.limited),issues:X.issues,nodes:X.nodes})}function q4($,Z,J,Q,X,K,Y,B){let W=J4(),q=Q4(),U=X4(),H=[],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);K4(W,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&&W.length===0?$.slice(Z,J):O.join(" ")})},G=Z;while(G<J){let _=$[G];if(!_)break;if(B&&_===B)return j(),_8(W,q),{nodes:W,issues:q,next:G+1,closed:!0,limited:!1,pendingHeredocs:H};if(G4(_)){if(_===`
|
|
23
|
-
`||_==="\r"){j();let A=_==="\r"&&$[G+1]===`
|
|
24
|
-
`?G+2:G+1,F=W.at(-1);if(F?.kind!=="connector"||!O8.has(F.operator))W.push(Object.freeze({kind:"connector",operator:$.slice(G,A),span:Object.freeze({start:G,end:A})}));if(H.length>0){let R=Y6($,A,J,H.splice(0));q.push(...R.issues),G=R.next;continue}G=A;continue}G++;continue}if(_==="#"){while(G<J&&$[G]!==`
|
|
25
|
-
`&&$[G]!=="\r")G++;continue}let O=U.start===-1?yY($,G,J):void 0;if(O){if(W6(W,q,G),Y>=X.maxDepth)return q$(W,q,G,"depth-limit",X.maxDepth);if(!B6(K))return q$(W,q,G,"word-limit",X.maxWords);let A=q4($,O.braceIndex+1,J,Q,X,K,Y+1,"}"),F=A.next,R={start:O.braceIndex+1,end:A.closed?F-1:F},b=G8($,Q,R,A);if(W.push({kind:"function",name:O.name,span:{start:G,end:F},body:b}),q.push(...A.issues),A.pendingHeredocs.length>0||s$(A.nodes))q.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely",span:{start:G,end:F}});if(H.push(...A.pendingHeredocs),A.limited)return W4(W,q,A.next);if(!A.closed)q.push({code:"unclosed-function-body",message:"function body is not closed",span:{start:O.braceIndex,end:F}});G=F;continue}let M=U4($,G);if(M){if(j(),!b8(W.at(-1)))q.push({code:"unexpected-connector",message:`connector ${M} has no preceding command`,span:{start:G,end:G+M.length}});W.push(Object.freeze({kind:"connector",operator:M,span:Object.freeze({start:G,end:G+M.length})})),G+=M.length;continue}if(_===")"){j(),q.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis",span:{start:G,end:G+1}}),W.push({kind:"unknown",source:_,span:{start:G,end:G+1}}),G++;continue}if((_==="("||_==="{"&&RY($,G,J))&&U.start===-1){if(W6(W,q,G),Y>=X.maxDepth)return q$(W,q,G,"depth-limit",X.maxDepth);let A=_==="("?")":"}",F=q4($,G+1,J,Q,X,K,Y+1,A),R=F.next,b={start:G+1,end:F.closed?R-1:R},I=G8($,Q,b,F);if(W.push({kind:"group",style:_==="("?"subshell":"brace",span:{start:G,end:R},body:I}),q.push(...F.issues),F.pendingHeredocs.length>0||s$(F.nodes))q.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely",span:{start:G,end:R}});if(H.push(...F.pendingHeredocs),F.limited)return W4(W,q,F.next);if(!F.closed)q.push({code:_==="("?"unclosed-subshell":"unclosed-brace-group",message:`${_} group is not closed`,span:{start:G,end:R}});G=R;continue}let L=(_==="<"||_===">")&&$[G+1]!=="("?MY($,G):null;if(L){let A=U.words.at(-1),F=A&&A.span.end===G&&/^[0-9]+$/.test(A.raw)?Number(A.raw):void 0;if(F!==void 0)U.words.pop();let R=F===void 0?G:A?.span.start??G;U.start=U.start===-1?G:U.start;let b=G+L.length;while(b<J&&/[ \t]/.test($[b]??""))b++;let I=$[b],C=b>G+L.length&&I==="#",y=!I||G4(I)||!!U4($,b)||I===B||I===")"||C||(I==="<"||I===">")&&$[b+1]!=="(",w=L==="<<"||L==="<<-"?K6($,b,J):void 0,k=w?{word:W$($,b,w.next,w.delimiter,"literal",w.quoted),nested:[],issues:[],next:w.next,limited:!1}:!y?q6($,b,J,Q,X,K,Y):void 0;if(k){if(q.push(...k.issues),k.limited)return W4(W,q,k.next);if(!B6(K))return q$(W,q,k.next,"word-limit",X.maxWords)}let B1=k?.next??G+L.length,P={kind:"redirection",operator:L,span:{start:R,end:B1},...F===void 0?{}:{fd:F},...k?{target:k.word}:{}};if(U.redirections.push(P),L==="<<"||L==="<<-")if(!w)q.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word",span:{start:G,end:G+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});H.push({delimiter:w.delimiter,quotedDelimiter:w.quoted,stripTabs:L==="<<-",declarationSpan:{start:R,end:B1},attach:(v)=>{P.heredoc=v}})}else if(!k)q.push({code:"missing-redirection-target",message:`redirection ${L} requires a target word`,span:{start:G,end:G+L.length}});if(k)U.nested.push(...k.nested);U.end=B1,G=B1;continue}if(U.start===-1)W6(W,q,G);let D=q6($,G,J,Q,X,K,Y);if(q.push(...D.issues),D.limited)return W4(W,q,D.next);let z=bY(U.words)?AY($,D.word,K.max-K.used,X.maxDepth,X.maxInputLength):void 0;if(z?.limitCode)return q$(W,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(!B6(K))return q$(W,q,D.next,"word-limit",X.maxWords);U.words.push(A)}U.start=U.start===-1?G:U.start,U.end=D.next,U.nested.push(...D.nested),G=D.next>G?D.next:G+1}return j(),_8(W,q),q.push(...wY(H)),{nodes:W,issues:q,next:G,closed:B===void 0,limited:!1,pendingHeredocs:[]}}function G8($,Z,J,Q){return{kind:"program",dialect:Z,source:$.slice(J.start,J.end),span:J,status:H4(Q.issues,Q.limited),issues:Q.issues,nodes:Q.nodes}}function q6($,Z,J,Q,X,K,Y){let B="",W=Z,q=!1,U="literal",H=[],j=[],G=!1;while(W<J){let _=$[W],O=(_==="<"||_===">")&&$[W+1]==="(";if(!_||G4(_)||(_===";"||_==="|"||_==="&")&&U4($,W)||(_==="<"||_===">")&&!O)break;if(_===")")break;if(_==="'"){q=!0;let L=$.indexOf("'",W+1);if(L===-1||L>=J){B+=$.slice(W+1,J),j.push({code:"unclosed-single-quote",message:"single-quoted word is not closed",span:{start:W,end:J}}),W=J;break}B+=$.slice(W+1,L),W=L+1;continue}if(_==='"'){q=!0;let L=OY($,W,J,Q,X,K,Y);if(B+=L.text,H.push(...L.nested),j.push(...L.issues),G||=L.limited,U=i$(U,L.provenance),W=L.next,G)break;continue}if($.startsWith("$'",W)){q=!0;let L=FY($,W+2,J);if(B+=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:W,end:J}});W=L.next;continue}if(_==="\\"){let L=$[W+1];if(!L){j.push({code:"trailing-escape",message:"escape has no following character",span:{start:W,end:W+1}}),W++;break}if(L===`
|
|
26
|
-
`){W+=2;continue}B+=L,W+=2;continue}let M=_==="$"||_==="<"||_===">"||_==="`"?U6($,W,J,Q,X,K,Y):null;if(M){let L=M8(M,H,j);if(G||=L.limited,U=i$(U,L.provenance),W=L.next,G)break;continue}if(_==="$"){let L=V8($,W,J,B,U);B=L.text,U=L.provenance,W=L.next;continue}if(_==="*"||_==="?"||_==="[")U=i$(U,"glob");B+=_,W++}return{word:W$($,Z,W,B,U,q,U==="literal"?void 0:VY($,Z,W)),nested:H,issues:j,next:W,limited:G}}function OY($,Z,J,Q,X,K,Y){let B="",W="literal",q=[],U=[],H=!1,j=Z+1;while(j<J){let G=$[j];if(G==='"')return{text:B,provenance:W,nested:q,issues:U,next:j+1,limited:H};if(G==="\\"&&$[j+1]){let O=$[j+1]??"";if(O===`
|
|
27
|
-
`){j+=2;continue}if(O==="\r"&&$[j+2]===`
|
|
28
|
-
`){j+=3;continue}B+=["$","`",'"',"\\"].includes(O)?O:`\\${O}`,j+=2;continue}if($.startsWith("$((",j)){let O=G6($,j+3,J,"))"),M=O===-1?J:O+2;if(B+=$.slice(j,M),O===-1)U.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:j,end:M}});j=M;continue}let _=U6($,j,J,Q,X,K,Y);if(_){let O=M8(_,q,U);if(j=O.next,H||=O.limited,W=i$(W,O.provenance),H)return{text:B,provenance:W,nested:q,issues:U,next:j,limited:H};continue}if(G==="$"){let O=V8($,j,J,B,W);B=O.text,W=O.provenance,j=O.next;continue}B+=G??"",j++}return U.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:Z,end:J}}),{text:B,provenance:W,nested:q,issues:U,next:J,limited:H}}function U6($,Z,J,Q,X,K,Y){let B=$.startsWith("$((",Z),W=$.startsWith("$(",Z)&&!B,q=($.startsWith("<(",Z)||$.startsWith(">(",Z))&&!0,U=$[Z]==="`";if(!B&&!W&&!q&&!U)return null;let H=B?3:U?1:2,j=B?"))":U?"`":")",G=G6($,Z+H,J,j),_=G===-1?J:G,O=G===-1?J:G+j.length;if(Y>=X.maxDepth)return{program:SY($,Z+H,_,Q,"depth-limit"),next:O,provenance:B?"arithmetic":"command-substitution"};if(B){let z=[],f=[],A=!1,F=Z+H;while(F<_){let R=U6($,F,_,Q,X,K,Y+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(G===-1)f.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed",span:{start:Z,end:O}});return{program:U1({kind:"program",dialect:Q,source:$.slice(Z+H,_),span:{start:Z+H,end:_},status:H4(f,A),issues:f,nodes:z}),next:O,provenance:"arithmetic"}}let M=q4($,Z+H,_,Q,X,K,Y+1),L=G===-1?[{code:B?"unclosed-arithmetic":"unclosed-command-substitution",message:`${$.slice(Z,Z+H)} substitution is not closed`,span:{start:Z,end:O}}]:[],D=(U||q)&&s$(M.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions",span:{start:Z,end:O}}]:[];return{program:U1({kind:"program",dialect:Q,source:$.slice(Z+H,_),span:{start:Z+H,end:_},status:H4([...M.issues,...L,...D],M.limited),issues:[...M.issues,...L,...D],nodes:M.nodes}),next:O,provenance:B?"arithmetic":"command-substitution"}}function M8($,Z,J){return Z.push($.program),J.push(...$.program.issues),{provenance:$.provenance,next:$.next,limited:$.program.status==="limited"}}function G6($,Z,J,Q){if(Q==="`"){for(let B=Z;B<J;B++)if($[B]==="\\")B++;else if($[B]==="`")return B;return-1}let X=1,K={single:!1,double:!1},Y=[];for(let B=Z;B<J;B++){let W=$[B];if((W===`
|
|
29
|
-
`||W==="\r")&&Y.length>0){let U=W==="\r"&&$[B+1]===`
|
|
30
|
-
`?B+2:B+1,H=Y6($,U,J,Y.splice(0));if(!H.terminated)return-1;B=H.next-1;continue}let q=F8($,B,Z,J,K);if(q!==null){B=q;continue}if(!K.double&&$.startsWith("$((",B)){let U=LY($,B+3,J);if(U===-1)return-1;B=U+1;continue}if(Q===")"&&!K.double&&W==="<"&&$[B+1]==="<"&&$[B+2]!=="<"){let U=$[B+2]==="-",H=B+(U?3:2);while(H<J&&/[ \t]/.test($[H]??""))H++;let j=K6($,H,J);if(j){Y.push({delimiter:j.delimiter,quotedDelimiter:j.quoted,stripTabs:U,declarationSpan:{start:B,end:j.next},attach:()=>{return}}),B=j.next-1;continue}}if($.startsWith("$(",B)&&!$.startsWith("$((",B)){X++,B++;continue}if(W==="("&&!K.double)X++;if(W===")"&&!K.double){if(X--,X===0)return Q==="))"&&$[B+1]!==")"?-1:B}}return-1}function LY($,Z,J){let Q=1,X={single:!1,double:!1};for(let K=Z;K<J;K++){let Y=$[K],B=F8($,K,Z,J,X);if(B!==null){K=B;continue}if($.startsWith("$(",K)&&!$.startsWith("$((",K)){Q++,K++;continue}if(Y==="("&&!X.double)Q++;if(Y!==")"||X.double)continue;if(Q--,Q===0)return $[K+1]===")"?K:-1}return-1}function F8($,Z,J,Q,X){let K=$[Z];if(K==="\\"&&!X.single)return Z+1;if(!X.double&&K==="'")X.single=!X.single;if(!X.single&&K==='"')X.double=!X.double;if(X.single)return Z;if(X.double||K!=="#"||!vY($,Z,J))return null;let Y=Z;while(Y+1<Q&&$[Y+1]!==`
|
|
31
|
-
`&&$[Y+1]!=="\r")Y++;return Y}function U4($,Z){let J=$[Z];if(J===";")return";";if(J==="&")return $[Z+1]==="&"?"&&":"&";if(J==="|")return $[Z+1]==="|"?"||":$[Z+1]==="&"?"|&":"|";return null}function MY($,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 G4($){let Z=$.charCodeAt(0);if(Z===32||Z>=9&&Z<=13)return!0;if(Z<128)return!1;return/\s/u.test($)}function N8($,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 FY($,Z,J){let Q="",X=[],K=Z;while(K<J){let Y=$[K];if(Y==="'")return{text:Q,next:K+1,closed:!0,issues:X};if(Y!=="\\"){Q+=Y??"",K++;continue}let B=NY($,K+1,J);if(Q+=B.text,B.invalidCodePoint!==void 0)X.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${B.invalidCodePoint}`,span:{start:K,end:B.next}});K=B.next}return{text:Q,next:J,closed:!1,issues:X}}function NY($,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 B4($,Z+1,J,16,2,Z+1);if(Q==="u")return B4($,Z+1,J,16,4,Z+1);if(Q==="U")return B4($,Z+1,J,16,8,Z+1);if(/[0-7]/.test(Q))return B4($,Z,J,8,3,Z+1);return{text:Q,next:Z+1}}function B4($,Z,J,Q,X,K){let Y=Q===16?/[0-9a-fA-F]/:/[0-7]/,B="",W=Z;while(W<J&&B.length<X&&Y.test($[W]??""))B+=$[W],W++;if(!B)return{text:$[K-1]??"",next:K};let q=Number.parseInt(B,Q);return q>1114111||q>=55296&&q<=57343?{text:"�",next:W,invalidCodePoint:q}:{text:String.fromCodePoint(q),next:W}}function H4($,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 V8($,Z,J,Q,X){let K=N8($,Z,J);return{text:Q+$.slice(Z,K),provenance:i$(X,"variable"),next:K}}function VY($,Z,J){let Q=Y4($),X=Z,K=!1,Y=!1,B=Z;while(B<J){let W=$[B];if(W==="\\"&&!K){B+=2;continue}if(!Y&&W==="'"){K=!K,B++;continue}if(!K&&W==='"'){Y=!Y,B++;continue}if(K){B++;continue}let q=$.startsWith("$((",B),U=$.startsWith("$(",B)&&!q,H=!Y&&($.startsWith("<(",B)||$.startsWith(">(",B)),j=W==="`";if(q||U||H||j){let G=q?3:j?1:2,_=q?"))":j?"`":")",O=G6($,B+G,J,_),M=O===-1?J:O+_.length;Q.push(X,B,"literal"),Q.push(B,M,q?"arithmetic":"command-substitution"),B=M,X=M;continue}if(W==="$"){let G=N8($,B,J);if(G>B+1){Q.push(X,B,"literal"),Q.push(B,G,"variable"),B=G,X=G;continue}}if(!Y&&(W==="*"||W==="?"||W==="[")){Q.push(X,B,"literal"),Q.push(B,B+1,"glob"),B++,X=B;continue}B++}return Q.push(X,J,"literal"),Q.parts}function i$($,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 RY($,Z,J){return Z+1>=J||G4($[Z+1]??"")||U4($,Z+1)!==null}var DY=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),zY=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function bY($){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=IY($,Z);if(J===void 0||J===null)return!1;Z=J}return!1}function IY($,Z){let J=$[Z]?.text.toLowerCase();if(J==="command")return fY($,Z);if(J==="env")return PY($,Z);if(J==="sudo")return CY($,Z);return}function fY($,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 PY($,Z){for(let J=Z+1;J<$.length;J++){let Q=$[J]?.text??"";if(Q==="--")return J+1;if(DY.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 CY($,Z){for(let J=Z+1;J<$.length;J++){let Q=$[J]?.text??"";if(Q==="--")return J+1;if(zY.has(Q)){if($[J+1]===void 0)return null;J++;continue}if(Q.startsWith("-"))continue;return J}return $.length}function R8($,Z,J,Q){if($.provenance!=="literal"||!$.raw.includes("{"))return;let X=[$.raw],K=$.raw.length,Y=0;while(!0){let W=X.findIndex((_)=>j8(_));if(W===-1)break;if(++Y>J)return{limited:!0};let q=X[W]??"",U=j8(q);if(!U||U.kind==="range")return{limited:!0};let H=U.start+q.length-U.end,j=U.alternatives.reduce((_,O)=>_+H+O.length,0);if(K-q.length+j>Q||X.length-1+U.alternatives.length>Z)return{limited:!0};let G=D8(q,U);X.splice(W,1,...G),K+=j-q.length}if(Y===0)return;let B=X.map((W)=>TY(W,J));if(B.some((W)=>W===null))return{limited:!0};return{words:[...new Set(B.filter((W)=>W!==null&&W!==""))]}}function AY($,Z,J,Q,X){if(Z.provenance!=="literal"||Z.quoted||Z.raw!==Z.text||!Z.raw.includes("{"))return;let K=[Z.text],Y=Z.text.length,B=0;while(!0){let q=K.findIndex((M)=>H8(M));if(q===-1)break;if(++B>Q)return{limitCode:"depth-limit"};let U=K[q]??"",H=H8(U);if(!H)break;let j=H.start+U.length-H.end,G=H.alternatives.filter((M)=>j+M.length>0),_=G.reduce((M,L)=>M+j+L.length,0);if(Y-U.length+_>X)return{limitCode:"brace-expansion-limit"};if(K.length-1+G.length>J)return{limitCode:"word-limit"};let O=D8(U,{...H,alternatives:G});K.splice(q,1,...O),Y+=_-U.length}let W=K.filter((q)=>q.length>0);if(B===0)return;return{words:W.map((q)=>W$($,Z.span.start,Z.span.end,q,"literal",!1))}}function H8($){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 K=Z.pop();if(!K||K.commas.length===0)continue;if(!J||K.start<J.start)J={start:K.start,end:Q+1,commas:K.commas}}if(!J)return;return{start:J.start,end:J.end,alternatives:z8($,J)}}function j8($){let Z=[],J,Q=null,X=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(X){X=!1;continue}if(Y==="\\"&&Q!=="'"){X=!0;continue}if(Y===Q){Q=null;continue}if(Q===null&&(Y==="'"||Y==='"')){Q=Y;continue}if(Q!==null)continue;if(Y==="{"){Z.push({start:K,commas:[]});continue}if(Y===","&&Z.length>0){Z.at(-1)?.commas.push(K);continue}if(Y!=="}"||Z.length===0)continue;let B=Z.pop();if(!B)continue;let W=B.commas.length>0?{kind:"alternatives",start:B.start,end:K+1,commas:B.commas}:EY($.slice(B.start+1,K))?{kind:"range",start:B.start,end:K+1}:void 0;if(W&&(!J||W.start<J.start))J=W}if(!J||J.kind==="range")return J;return{kind:J.kind,start:J.start,end:J.end,alternatives:z8($,J)}}function D8($,Z){return Z.alternatives.map((J)=>`${$.slice(0,Z.start)}${J}${$.slice(Z.end)}`)}function z8($,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 EY($){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test($)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test($)}function TY($,Z){let J=`x${$}`,Q=q6(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 SY($,Z,J,Q,X){return U1({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 q$($,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 W4($,Z,J){return{nodes:$,issues:Z,next:J,closed:!1,limited:!0,pendingHeredocs:[]}}function B6($){return $.used++,$.used<=$.max}function yY($,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 s$($){return $.some((Z)=>{if(Z.kind==="command")return Z.redirections.some((J)=>J.heredoc)||Z.nested.some((J)=>s$(J.nodes));return(Z.kind==="group"||Z.kind==="function")&&s$(Z.body.nodes)})}function wY($){return $.map((Z)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${Z.delimiter} was not found`,span:Z.declarationSpan}))}function b8($){return $?.kind==="command"||$?.kind==="group"||$?.kind==="function"}function _8($,Z){let J=$.at(-1);if(J?.kind!=="connector"||!O8.has(J.operator))return;Z.push({code:"missing-command-after-connector",message:`connector ${J.operator} requires a following command`,span:J.span})}function W6($,Z,J){if(!b8($.at(-1)))return;Z.push({code:"missing-command-connector",message:"adjacent commands require a connector",span:{start:J,end:J+1}})}function vY($,Z,J){return Z===J||/[\s;&|()]/u.test($[Z-1]??"")}var I8=new Set(["remove-item","ri","del","erase","rd","rmdir"]),f8=["-rec","-for","-path","-literalpath","-whatif"],j4={maxInputLength:131072,maxWords:16384,maxDepth:64};function P8($){let Z=$.toLowerCase().replaceAll("`","");if(![...I8].some((Q)=>Z.includes(Q))&&!(Z.includes("rm")&&f8.some((Q)=>Z.includes(Q)))&&!Z.includes("<#"))return!1;let J=kY($);return J.invalidComment||J.commands.some(uY)}function uY($){let Z=$[0]==="&"||$[0]==="."?1:0,J=$[Z]?.toLowerCase();if(J&&I8.has(J))return!0;if(J!=="rm")return!1;return $.slice(Z+1).some((Q)=>{let X=Q.toLowerCase().split(":",1)[0]??"";return f8.some((K)=>X.startsWith(K))})}function C8($,Z){let J={start:0,end:$.length};if($.length>Z.maxInputLength)return U1({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=L6($,0,$.length,Z,0);return U1({kind:"program",dialect:"powershell",source:$,span:J,status:xY(Q.issues,Q.limited),issues:Q.issues,nodes:Q.nodes})}function L6($,Z,J,Q,X,K=!1){let Y=J4(),B=Q4(),W=X4(),q=0,U=!1,H=()=>{if(W.words.length===0&&W.redirections.length===0)return;let G={start:W.start,end:W.end};K4(Y,W,{kind:"command",dialect:"powershell",source:$.slice(G.start,G.end),span:G,words:W.words,redirections:W.redirections,nested:W.nested,dynamicExecutable:W.words[0]?.provenance!=="literal",displayText:W.words.map((_)=>_.text).join(" ")})},j=Z;while(j<J){let G=$[j];if(!G)break;if(K&&G==="}")return H(),{nodes:Y,issues:B,next:j+1,closed:!0,words:q,limited:U};let _=T8($,j,J,Q.maxDepth);if(_){if(_.issue)B.push(_.issue);if(_.limited)return H(),{nodes:Y,issues:B,next:_.next,closed:!1,words:q,limited:!0};j=_.next;continue}if(/\s/.test(G)){if(G==="\r"||G===`
|
|
33
|
-
`){H();let L=G==="\r"&&$[j+1]===`
|
|
34
|
-
`?j+2:j+1;Y.push(H6($,j,L)),j=L;continue}j++;continue}let O=M6($,j);if(O){H(),Y.push(H6($,j,j+O.length)),j+=O.length;continue}if(G==="{"){if(H(),X>=Q.maxDepth)return B.push(E8(j,Q.maxDepth)),{nodes:Y,issues:B,next:J,closed:!1,words:q,limited:!0};let L=L6($,j+1,J,Q,X+1,!0),D=L.closed?L.next-1:L.next,z=U1({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(Y.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:j,end:L.next}),body:z})),B.push(...L.issues),!L.closed)B.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(G==="}"){H(),Y.push(H6($,j,j+1)),j++;continue}if(G===">"||G==="<"){W.start=W.start===-1?j:W.start;let L=$[j+1]===G?j+2:j+1,D=L;while(/[ \t]/.test($[D]??""))D++;let z=D<J?j6($,D,J,Q,X):void 0,f=z?.next??L;if(W.redirections.push(Object.freeze({kind:"redirection",operator:$.slice(j,L),span:Object.freeze({start:j,end:f}),...z?{target:z.word}:{}})),z)B.push(...z.issues),W.nested.push(...z.nested),q+=z.words,U||=z.limited;W.end=f,j=f;continue}if(G===","){W.start=W.start===-1?j:W.start,W.words.push(X6({text:",",raw:",",span:{start:j,end:j+1},provenance:"literal",quoted:!1})),W.end=++j;continue}let M=j6($,j,J,Q,X);if(W.start=W.start===-1?j:W.start,W.end=M.next,W.words.push(M.word),B.push(...M.issues),W.nested.push(...M.nested),q+=1+M.words,U||=M.limited,q>Q.maxWords)return B.push({code:"word-limit",message:`command exceeds ${Q.maxWords} words`,span:{start:j,end:M.next}}),H(),{nodes:Y,issues:B,next:M.next,closed:!1,words:q,limited:!0};j=M.next>j?M.next:j+1}return H(),{nodes:Y,issues:B,next:j,closed:!K,words:q,limited:U}}function j6($,Z,J,Q,X){let K="",Y="literal",B=!1,W=[],q=[],U=0,H=!1,j=(_)=>{let O=hY($,_,J,Q,X);return K+=$.slice(_,O.next),q.push(O.program),W.push(...O.program.issues),U+=_6(O.program),H||=O.program.status==="limited",Y="command-substitution",O.next},G=Z;while(G<J){let _=$[G];if(!_||/\s/.test(_)||M6($,G)||_===">"||_==="<"||_==="#")break;if(_===",")break;if(_==="`"){let O=$[G+1];if(!O){W.push({code:"trailing-escape",message:"PowerShell escape has no following character",span:{start:G,end:G+1}}),G++;break}K+=O,G+=2;continue}if($.startsWith("$(",G)){G=j(G);continue}if(_==="'"){B=!0,G++;let O=!1;while(G<$.length){if($[G]==="'"&&$[G+1]==="'"){K+="'",G+=2;continue}if($[G]==="'"){O=!0,G++;break}K+=$[G]??"",G++}if(!O)W.push({code:"unclosed-single-quote",message:"single-quoted word is not closed",span:{start:Z,end:$.length}});continue}if(_==='"'){B=!0;let O=G++,M=!1;while(G<J){let L=$[G];if(L==="`"&&$[G+1]){K+=$[G+1],G+=2;continue}if(L==='"'){M=!0,G++;break}if($.startsWith("$(",G)){G=j(G);continue}if(L==="$")Y=$[G+1]==="("?"command-substitution":"variable";K+=L??"",G++}if(!M)W.push({code:"unclosed-double-quote",message:"double-quoted word is not closed",span:{start:O,end:$.length}});continue}if(_==="$")Y=$[G+1]==="("?"command-substitution":"variable";if(_==="@"&&G===Z)Y="variable";K+=_,G++}return{word:W$($,Z,G,K,Y,B,Y==="literal"?void 0:gY($,Z,G)),next:G,issues:W,nested:q,words:U,limited:H}}function hY($,Z,J,Q,X){let K=A8($,Z+2,J),Y=K===-1?J:K,B=K===-1?J:K+1;if(X>=Q.maxDepth)return{program:U1({kind:"program",dialect:"powershell",source:$.slice(Z+2,Y),span:{start:Z+2,end:Y},status:"limited",issues:[E8(Z,Q.maxDepth)],nodes:[]}),next:B};let W=L6($,Z+2,Y,Q,X+1),q=K===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed",span:{start:Z,end:B}}]:[];return{program:U1({kind:"program",dialect:"powershell",source:$.slice(Z+2,Y),span:{start:Z+2,end:Y},status:W.limited?"limited":W.issues.length+q.length>0?"partial":"complete",issues:[...W.issues,...q],nodes:W.nodes}),next:B}}function A8($,Z,J){let Q=1,X=!1,K=!1;for(let Y=Z;Y<J;Y++){let B=$[Y];if(B==="`"){Y++;continue}if(!K&&B==="'"){if(X&&$[Y+1]==="'"){Y++;continue}X=!X;continue}if(!X&&B==='"'){K=!K;continue}if(X)continue;if($.startsWith("$(",Y)){Q++,Y++;continue}if(!K&&B==="(")Q++;if(B!==")")continue;if(Q--,Q===0)return Y}return-1}function _6($){let Z=0;for(let J of $.nodes){if(J.kind==="group")Z+=_6(J.body);if(J.kind==="command"){Z+=J.words.length;for(let Q of J.nested)Z+=_6(Q)}}return Z}function gY($,Z,J){let Q=Y4($),X=Z,K=!1,Y=Z;while(Y<J){let B=$[Y];if(B==="`"){Y+=2;continue}if(B==="'"){if(K&&$[Y+1]==="'"){Y+=2;continue}K=!K,Y++;continue}if(K){Y++;continue}if($.startsWith("$(",Y)){let W=A8($,Y+2,J),q=W===-1?J:W+1;Q.push(X,Y,"literal"),Q.push(Y,q,"command-substitution"),Y=q,X=q;continue}if(B==="$"||B==="@"&&Y===Z){let W=Y+1;if($[W]==="{"){let q=$.indexOf("}",W+1);W=q===-1||q>=J?J:q+1}else while(W<J&&/[A-Za-z0-9_:?]/.test($[W]??""))W++;Q.push(X,Y,"literal"),Q.push(Y,W,"variable"),Y=W,X=W;continue}Y++}return Q.push(X,J,"literal"),Q.parts}function E8($,Z){return{code:"depth-limit",message:`command structure exceeds parser limit ${Z}`,span:{start:$,end:$}}}function kY($){let Z=[],J=[],Q=0,X=0,K=!1,Y=()=>{if(J.length>0)Z.push(J);J=[]};while(Q<$.length&&Q<131072&&X<16384){let B=$[Q];if(B==="\r"||B===`
|
|
35
|
-
`){Y(),Q+=B==="\r"&&$[Q+1]===`
|
|
36
|
-
`?2:1;continue}if(/\s/.test(B??"")){Q++;continue}let W=T8($,Q,Math.min($.length,j4.maxInputLength),j4.maxDepth);if(W){K||=!!W.issue||W.limited,Q=W.next;continue}let q=M6($,Q);if(q){Y(),Q+=q.length;continue}if(B==="{"||B==="}"){Y(),Q++;continue}let U=j6($,Q,Math.min($.length,j4.maxInputLength),j4,0);if(U.word.text)J.push(U.word.text);for(let H of U.nested)Z.push(...O6(H));X++,Q=U.next>Q?U.next:Q+1}return Y(),{commands:Z,invalidComment:K}}function O6($){return $.nodes.flatMap((Z)=>{if(Z.kind==="group")return O6(Z.body);if(Z.kind!=="command")return[];return[Z.words.map((J)=>J.text),...Z.nested.flatMap(O6)]})}function M6($,Z){for(let J of["&&","||",";","|"])if($.startsWith(J,Z))return J;return null}function T8($,Z,J,Q){if($[Z]==="#"&&$[Z+1]!==">"){let Y=Z+1;while(Y<J&&$[Y]!=="\r"&&$[Y]!==`
|
|
37
|
-
`)Y++;return{next:Y,limited:!1}}if(!$.startsWith("<#",Z))return null;let X=1,K=Z+2;while(K<J){if($.startsWith("<#",K)){if(X++,X>Q)return{next:J,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${Q}`,span:{start:Z,end:K+2}},limited:!0};K+=2;continue}if($.startsWith("#>",K)){if(X--,K+=2,X===0)return{next:K,limited:!1};continue}K++}return{next:J,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed",span:{start:Z,end:J}},limited:!1}}function xY($,Z){if(Z)return"limited";if($.some((J)=>J.code==="unclosed-block-comment"))return"invalid";return $.length>0?"partial":"complete"}function H6($,Z,J){return Object.freeze({kind:"connector",operator:$.slice(Z,J),span:Object.freeze({start:Z,end:J})})}var w0=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function w1($,Z="auto",J=w0){if(Z==="powershell"||Z==="auto"&&P8($.slice(0,J.maxInputLength)))return C8($,J);return L8($,"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 lY=/^[A-Za-z_][A-Za-z0-9_]*=/;function _4($,Z){return $?.provenance==="literal"&&!$.quoted&&$.raw===Z&&$.text===Z}function O4($){let Z=_4($.words[0],"time")?1:0,J=Z===1&&_4($.words[Z],"-p")?Z+1:Z,Q=Z===1&&_4($.words[J],"--")?J+1:J,X=_4($.words[Q],"!")?Q+1:Q,K=$.words.slice(X).find((Y)=>!lY.test(Y.text));return K?.provenance==="literal"?K.text:void 0}function r$($,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 U$($){let Z={inSingle:!1,inDouble:!1,escaped:!1};for(let J of mY($))r$(J,Z);return Z.inSingle||Z.inDouble}function mY($){let Z="",J={inSingle:!1,inDouble:!1,escaped:!1},Q=!1,X=!0;for(let K=0;K<$.length;K++){let Y=$[K];if(!Y)break;if(Q){if(Y===`
|
|
38
|
-
`||Y==="\r")Z+=Y,Q=!1,J.escaped=!1;continue}if(Y==="#"&&!J.inSingle&&!J.inDouble&&X){Q=!0;continue}if(Z+=Y,!J.inSingle&&!J.inDouble&&!J.escaped)X=/[\s;&|()<>]/.test(Y);r$(Y,J)}return Z}var pY=new Set(["&&","||","|&","|","&",";"]),cY=new Set(["<<","<<<",">|"]),dY=/[*@#?$!_-]/,N6=Object.freeze([]),iY=Object.freeze([]),sY=256;function u8($,Z){let J=Z.status==="complete"?new Set(R6(Z)):new Set,Q=[...J].reduce((Y,B)=>Y.slice(0,B.start)+" ".repeat(B.end-B.start)+Y.slice(B.end),$);if(U$(Q))return L4("unclosed-quote",Q,N6);let X={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},K=n$(Z,{source:Q,suppressed:J,flags:X,depth:0,functions:new Map});if(X.limited)return L4("structural-limit",Q,N6);if(X.invalid)return L4("invalid",Q,N6);return L4("complete",Q,K,X.assignmentFallbacks)}function L4($,Z,J,Q=iY){return Object.freeze({status:$,source:Z,entries:Object.freeze(J),assignmentFallbacks:Object.freeze(Q)})}function n$($,Z){return $.nodes.flatMap((J,Q)=>rY(J,$,Q,Z)).sort((J,Q)=>J.start-Q.start).flatMap((J)=>[...J.entries])}function rY($,Z,J,Q){if($.kind==="connector")return[{start:$.span.start,entries:[v1(eY($.operator))]}];if($.kind==="unknown")return[{start:$.span.start,entries:[v1($.source)]}];if($.kind==="function")return Q.functions.set($.name,$.body),[];if($.kind==="group"){let K=$.style!=="subshell",Y=Q.source[$.span.end-1]===(K?"}":")"),B=K?Q:{...Q,functions:new Map(Q.functions)};return[{start:$.span.start,entries:[K?M4("{"):v1("("),...n$($.body,B),...Y?[K?M4("}"):v1(")")]:[]]}]}let X=ZB($,Q.functions);if(X){if(Q.depth>=w0.maxDepth||++Q.flags.expansions>sY)return Q.flags.limited=!0,[];return[{start:$.span.start,entries:[...S8($,Q),M4(";"),...n$(X,{...Q,depth:Q.depth+1}),M4(";")]},...y8($,Z,J,Q)]}return[{start:$.span.start,entries:S8($,Q)},...y8($,Z,J,Q)]}function S8($,Z){return[...$.words.map((J)=>({start:J.span.start,entries:g8(J,$,Z,!1)})),...$.redirections.map((J)=>({start:J.span.start,entries:nY(J,$,Z)}))].sort((J,Q)=>J.start-Q.start).flatMap((J)=>J.entries)}function nY($,Z,J){let Q=$.operator==="<<-"?"<<":$.operator,X=$.target?g8($.target,Z,J,!0):[],K=X[0],Y=K?.kind==="word"?K.text:void 0;return[...$.fd===void 0?[]:[D6(String($.fd))],Object.freeze({kind:"redirection",operator:Q,role:$B(Q),targetOrder:cY.has(Q)?"legacy-segment":"immediate",...Y===void 0?{}:{target:Y}}),...Y===void 0?X:X.slice(1)]}function y8($,Z,J,Q){let X=$.redirections.filter((K)=>K.operator==="<<"||K.operator==="<<-");return[...X.flatMap((K)=>{let Y=K.heredoc;if(!Y)return[];let B=[D6(Y.delimiter),.../[\r\n]/.test(Q.source[Y.terminatorSpan.end]??"")?[v1(";")]:[]];if(Q.suppressed.has(Y.bodySpan))return[{start:Y.bodySpan.start,entries:B}];return[{start:Y.bodySpan.start,entries:[...h8(Q.source.slice(Y.bodySpan.start,Y.bodySpan.end),Q),...B]}]}),...X.some((K)=>!K.heredoc&&K.target)?aY(Z,J,Q):[]]}function aY($,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:h8(J.source.slice(Q.span.end,$.span.end),J)}]}function h8($,Z){if(Z.depth>=w0.maxDepth)return Z.flags.limited=!0,[];let J=w1($,"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=n$(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 g8($,Z,J,Q){let X=[],K={single:!1,double:!1},Y="",B=!1,W=()=>{if(B&&!Q)X.push(v1("glob"));else if(Y!==""||$.quoted&&X.length===0)X.push(D6(Y));Y="",B=!1};for(let q of $.parts){if(q.provenance!=="command-substitution"&&q.provenance!=="arithmetic"){for(let G of V6(q.raw,K,J.flags)){if(typeof G==="string"){W(),X.push(v1(G));continue}Y+=G.text,B||=G.glob}continue}if(K.double){let G=J.source.slice(q.span.start,q.span.end);Y+=V6(G,{single:!1,double:!0},J.flags).map((_)=>typeof _==="string"?_:_.text).join("");continue}let U=Z.nested.find((G)=>G.span.start>=q.span.start&&G.span.end<=q.span.end),H=U?n$(U,J):[];if(q.raw.startsWith("`")){Y+="${}",W(),X.push(...H);continue}if(q.raw.startsWith("<(")||q.raw.startsWith(">(")){W(),X.push(q.raw.startsWith("<(")?v1("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),...H,...q.raw.endsWith(")")?[v1(")")]:[]);continue}let j=q.raw.startsWith("$((")?2:1;Y+="${}",W(),X.push(...Array.from({length:j},()=>v1("(")),...H,...q.raw.endsWith(")".repeat(j))?Array.from({length:j},()=>v1(")")):[])}return W(),X}function V6($,Z,J){let Q=[],X="",K=!1,Y=0;while(Y<$.length){let B=$[Y]??"";if(!Z.single&&!Z.double&&(B==="("||B===")")){Q.push({text:X,glob:K},B),X="",K=!1,Y++;continue}if(Z.single){if(B==="'")Z.single=!1;else X+=B;Y++;continue}if(Z.double){if(B==='"'){Z.double=!1,Y++;continue}if(B==="\\"){let W=$[Y+1]??"";X+=['"',"\\","$"].includes(W)?W:`\\${W}`,Y+=2;continue}if(B==="$"){let W=w8($,Y,Z,J);X+=W.text,Y=W.next;continue}X+=B,Y++;continue}if(B==="'"||B==='"'){Z.single=B==="'",Z.double=B==='"',Y++;continue}if(B==="\\"){let W=$[Y+1]??"";K||=W==="*"||W==="?",X+=W,Y+=2;continue}if(B==="$"){let W=w8($,Y,Z,J);X+=W.text,Y=W.next;continue}K||=B==="*"||B==="?",X+=B,Y++}return[...Q,{text:X,glob:K}]}function w8($,Z,J,Q){let X=$[Z+1];if(X==="{"){let Y=tY($,Z+2);if(Y===-1)return Q.invalid=!0,{text:"",next:$.length};let B=$.slice(Z,Y+1);return oY(B,J,Q),{text:B,next:Y+1}}if(X!==void 0&&dY.test(X))return{text:`\${${X}}`,next:Z+2};let K=/^\w*/.exec($.slice(Z+1))?.[0]??"";return{text:`\${${K}}`,next:Z+1+K.length}}function oY($,Z,J){let Q=$.slice(2,-1),X=/^[A-Za-z_][A-Za-z0-9_]*/.exec(Q)?.[0];if(!X)return;let K=Q.slice(X.length),Y=[":=","="].find((W)=>K.startsWith(W));if(!Y)return;let B=V6(K.slice(Y.length),{...Z},J);J.assignmentFallbacks.push(...B.flatMap((W)=>typeof W==="string"||!W.text?[]:[W.text]))}function tY($,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 eY($){return/^[\r\n]+$/.test($)?";":$}function v1($){return Object.freeze({kind:"operator",operator:$,boundary:pY.has($)})}function M4($){return Object.freeze({kind:"operator",operator:$,boundary:!0})}function D6($){return Object.freeze({kind:"word",text:$})}function $B($){if($==="<<"||$==="<<<")return"here-data";if($==="<"||$==="<&")return"file-read";return"file-write"}function R6($){return $.nodes.flatMap((Z,J)=>{if(Z.kind==="group"||Z.kind==="function")return R6(Z.body);if(Z.kind!=="command")return[];let Q=Z.nested.flatMap((Y)=>R6(Y)),X=$.nodes[J+1];if(X?.kind==="connector"&&(X.operator==="|"||X.operator==="|&")||!QB(Z))return Q;return[...Q,...Z.redirections.flatMap((Y)=>Y.heredoc?.quotedDelimiter?[Y.heredoc.bodySpan]:[])]})}function ZB($,Z){let J=O4($);return J===void 0?void 0:Z.get(J)}function D0($,Z){return $!==void 0&&$.provenance==="literal"&&!$.quoted&&$.raw===$.text&&$.text===Z}function JB($){if(D0($.words[0],"git"))return D0($.words[1],"commit");if(!D0($.words[0],"gh")||!D0($.words[2],"create"))return!1;return D0($.words[1],"pr")||D0($.words[1],"issue")}function QB($){return(D0($.words[0],"cat")||D0($.words[0],"tee")||JB($))&&!$.words.some(v8)&&!$.redirections.some((J)=>v8(J.target))}function v8($){return $?.parts.some((Z)=>Z.provenance==="command-substitution"&&Z.raw.startsWith(">("))??!1}var x8=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),l8=new Set([...x8,"glob"]),XB=new Set([...l8,"pattern"]),KB=Object.freeze([]),m8={parseCommand:w1,projectShellSyntax:u8};class z0 extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function F4($,Z={}){let J=YB({...m8,...Z}),Q=B$($.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 K=X.reduce((Y,B)=>{let W=Y.findIndex((H)=>H.source===B.source);if(W!==-1){let H=Y[W];if(!H)return Y;return Y[W]=k8({...H,usages:[...H.usages,B.usage]}),Y}let q=$.route.kind==="command"?$.route.shell:"posix",U=J.getCommandProgram(B.source,q);return Y.push(k8({usages:[B.usage],source:B.source,program:U,views:z6(U),uncertainties:U.issues,shell:J.getShellSyntax(B.source,U)})),Y},[]);return Object.freeze({invocation:Object.freeze({toolName:$.toolName,route:Object.freeze({...$.route}),context:Object.freeze({...$.context,...$.context.policyConfigCwds?{policyConfigCwds:Object.freeze([...$.context.policyConfigCwds])}:{}})}),commands:Object.freeze(K),paths:Object.freeze(BB($)),store:J})}function _1($,Z){return $.commands.find((J)=>J.usages.includes(Z))}function d1($){if(!$.includes("$"))return $;return Z4($,B0())}function YB($={}){let Z={...m8,...$},J=new Map,Q=new Map,X=new WeakMap,K=(B,W)=>{let q=`${W}\x00${B}`,U=Q.get(q);if(U)return U;let H=Z.parseCommand(B,W);return Q.set(q,H),H};return Object.freeze({getShellSyntax:(B,W)=>{if(W&&W.source!==B)throw TypeError("Shell syntax source does not match command program source.");let q=W??K(B,"posix");if(q.status==="limited"){let j=X.get(q);if(j)return j;let G=Object.freeze({status:"structural-limit",source:B,entries:KB,assignmentFallbacks:Object.freeze([])});return X.set(q,G),G}let U=J.get(B);if(U)return U;let H=Z.projectShellSyntax(B,q);return J.set(B,H),H},getCommandProgram:K})}function k8($){return Object.freeze({...$,usages:Object.freeze([...$.usages]),views:Object.freeze([...$.views]),uncertainties:Object.freeze([...$.uncertainties])})}function z6($){return Object.freeze($.nodes.flatMap((Z)=>{if(Z.kind==="group")return[...z6(Z.body)];if(Z.kind!=="command")return[];return[...Z.nested.flatMap((J)=>[...z6(J)]),Z]}))}function BB($){let Z=$.route.kind==="grep"?l8:$.route.kind==="glob"?XB:x8,J=$.route.kind==="grep"||$.route.kind==="glob"?"read":$.route.kind==="patch"?"write":"unknown";return[...e3($.input,Z).map((Q)=>Object.freeze({raw:Q,role:"tool-path",access:J})),...$.route.kind==="patch"?$6($.input).map((Q)=>Object.freeze({raw:Q,role:"patch-target",access:"write"})):[]]}import{statSync as KW}from"node:fs";import{isAbsolute as q7,join as YW,relative as U7}from"node:path";import{existsSync as f6,lstatSync as FB,readFileSync as D4,realpathSync as t$,statSync as o$}from"node:fs";import{dirname as P6,isAbsolute as C6,join as z4,resolve as b4}from"node:path";import{dirname as WB,isAbsolute as qB,parse as UB,sep as GB}from"node:path";function v0($,Z=process.platform){if(Z!=="win32")return!1;return($[0]==="/"||$[0]==="\\")&&($[1]==="/"||$[1]==="\\")}function b0($,Z,J){if(v0(Z))throw Error("Unsupported Windows namespace path");let Q=qB(Z)?jB(Z):"",X=Q||$;for(let K of _B(Q?Z.slice(Q.length):Z)){if(K===""||K===".")continue;if(K===".."){X=WB(X);continue}let Y=HB(X,K),B=J.entryKind(Y),W=B==="symlink"?J.realpath(Y):Y;if(B==="missing"||W===null)throw Error(`Cannot resolve path component: ${Y}`);X=W}return X}function HB($,Z){return $.endsWith("/")||$.endsWith("\\")?`${$}${Z}`:`${$}${GB}${Z}`}function jB($){return UB($).root}function _B($){let Z=process.platform==="win32"?/[\\/]+/:/\/+/;return $.split(Z)}var b6=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],OB=new Set(b6);var p8=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),N4=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),LB=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function MB($){return OB.has($)}function a$($){return $==="GIT_CONFIG_COUNT"||$==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test($)}function I6($){return MB($)||p8.has($)||N4.has($)||a$($)}function b1($,Z,J){return J?.has($)?J.get($):Z.get($)}function V4($,Z){let J=b1("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 R4($,Z,J){let X=$.match(LB)?.[1];if(!X||!I6(X))return null;let K=$.indexOf("=");return{name:X,value:`${b1(X,Z,J)??""}${$.slice(K+1)}`}}function c8($){return i8($,N4)}function d8($){return i8($,p8)}function i8($,Z){if(!$)return!1;for(let J of $.keys())if(Z.has(J))return!0;return!1}var i1=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]);function n8($,Z){return b6.some((J)=>Z?.has(J)||$.has(J))}function a8($,Z){if(!Z)return{gitCwd:null,hasExplicitGitContext:!1};let J;try{J=t$(b4(Z))}catch{return{gitCwd:null,hasExplicitGitContext:!1}}if(!e8(J))return{gitCwd:null,hasExplicitGitContext:!1};let Q=!1,X=1;while(X<$.length){let K=$[X];if(!K)break;if(K==="--")break;if(!K.startsWith("-"))break;if(K==="-C"){let Y=$[X+1];if(!Y)return{gitCwd:null,hasExplicitGitContext:Q};let B=r8(J,Y);if(!B)return{gitCwd:null,hasExplicitGitContext:Q};J=B,X+=2;continue}if(K.startsWith("-C")&&K.length>2){let Y=r8(J,K.slice(2));if(!Y)return{gitCwd:null,hasExplicitGitContext:Q};J=Y,X++;continue}if(K==="--git-dir"||K==="--work-tree"){Q=!0,X+=2;continue}if(K.startsWith("--git-dir=")||K.startsWith("--work-tree=")){Q=!0,X++;continue}if(i1.has(K))X+=2;else if(K.startsWith("-c")&&K.length>2)X++;else X++}return{gitCwd:J,hasExplicitGitContext:Q}}function o8($){let Z=SB($);if(!Z)return!1;try{let J=FB(Z);if(J.isSymbolicLink()||!J.isFile())return!1;let Q=A6(Z);if(!Q?.commonDir)return!1;if(!RB(Q.gitDir,Z))return!1;return DB(Q.gitDir,P6(Z))}catch{return!1}}function A6($){try{let Z=NB($);if(!Z)return null;let J=t$(C6(Z)?Z:b4(P6($),Z));if(!o$(J).isDirectory())return null;return{gitDir:J,commonDir:VB(J)}}catch{return null}}function NB($){let Z=D4($,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!Z.startsWith("gitdir:"))return null;return Z.slice(7).trim()||null}function VB($){try{let Z=D4(z4($,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!Z)return null;let J=t$(C6(Z)?Z:b4($,Z));return o$(J).isDirectory()?J:null}catch{return null}}function RB($,Z){let J=zB($);return J===null?!1:t8($,J,Z)}function DB($,Z){let J=bB($);return J===null?!0:t8($,J,Z)}function zB($){let Z=z4($,"gitdir");if(!f6(Z))return null;let J=D4(Z,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return J===""?null:J}function bB($){let Z=z4($,"config.worktree");return f6(Z)?AB(Z):null}function t8($,Z,J){return fB(IB($,Z),J)}function IB($,Z){return C6(Z)?Z:b4($,Z)}function fB($,Z){try{return PB($,Z)}catch{return!1}}function PB($,Z){try{let J=o$($),Q=o$(Z);if(J.ino!==0&&Q.ino!==0&&J.dev===Q.dev&&J.ino===Q.ino)return!0}catch{}return s8($)===s8(Z)}function s8($){return CB(t$.native($))}function CB($){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 AB($){let Z=D4($,"utf-8"),J=!1,Q=null;for(let X of Z.split(/\r?\n/)){let K=X.trim();if(K===""||K.startsWith("#")||K.startsWith(";"))continue;if(K.startsWith("[")){J=/^\[core\]$/i.test(K);continue}if(!J)continue;let Y=K.match(/^worktree\s*=\s*(.*)$/i);if(Y)Q=EB(Y[1]??"")}return Q}function EB($){let Z=$.trim();if(!Z.startsWith('"')||!Z.endsWith('"'))return Z;return TB(Z.slice(1,-1))}function TB($){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+=`
|
|
39
|
-
`;break;case"t":Z+="\t";break;case"b":Z+="\b";break;default:Z+=`\\${X}`;break}J++}return Z}function r8($,Z){try{let J=b0($,Z,R0);return e8(J)?J:null}catch{return null}}function e8($){try{return o$($).isDirectory()}catch{return!1}}function SB($){try{return e$(t$($))}catch{return null}}function e$($){let Z=$;while(!0){let J=z4(Z,".git");if(f6(J))return J;let Q=P6(Z);if(Q===Z)return null;Z=Q}}import{isAbsolute as $7,parse as yB}from"node:path";function S($){return $.provenance==="command-substitution"?$.raw:$.text}function G$($,Z){return $==="posix"?Z:g(Z.map((J)=>J.text))}function I4($,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:[]}))}var Q7=/^[A-Za-z_][A-Za-z0-9_]*=/,wB=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}/,X7=131072,vB=16384;function s1($){if(!Q7.test($))return null;let Z=$.indexOf("=");return{name:$.slice(0,Z),value:$.slice(Z+1)}}function f4($){let Z=new Map,J=0;while(J<$.length){let Q=$[J];if(!Q)break;let X=s1(S(Q));if(!X)break;Z.set(X.name,X.value),J++}return{words:$.slice(J),envAssignments:Z}}function K7($){let Z=$.toLowerCase();return $.includes("=")||Z==="sudo"||Z==="env"||Z==="command"||Z==="builtin"}function u0($,Z,J,Q){if(!K7(H$($)))return{words:$,envAssignments:new Map,cwd:J,rewritten:!1};let X=new Set($),K=$,Y=new Map,B=new Map(Q??[]),W=J;for(let U=0;U<K$;U++){let H=J7(K),j=f4(K);for(let[_,O]of j.envAssignments)Y.set(_,O),B.set(_,O);if(K=j.words,K.length===0)break;while(K.length>0&&H$(K).includes("=")&&!uB(K)){let _=hB(H$(K),B,Z.env)??R4(H$(K),Z.env,B);if(_)Y.set(_.name,_.value),B.set(_.name,_.value);K=K.slice(1)}if(K.length===0)break;let G=H$(K).toLowerCase();if(G!=="sudo"&&G!=="env"&&G!=="command"&&G!=="builtin")break;if(G==="sudo"){let _=kB(K,Z.paths,W);if(K=_.words,_.cwd!==void 0)W=_.cwd}if(G==="env"){let _=mB(K,W,B,Z);if(_.unverifiableEnvSplit)return{words:K,envAssignments:Y,cwd:W,unverifiableEnvSplit:!0,rewritten:Z7(K,X)};if(K=_.words,_.cwd!==void 0)W=_.cwd;for(let[O,M]of _.envAssignments)Y.set(O,M),B.set(O,M)}if(G==="command")K=rB(K);if(G==="builtin")K=K.slice(u1(K,1)==="--"?2:1);if(J7(K)===H)break}let q=f4(K);for(let[U,H]of q.envAssignments)Y.set(U,H),B.set(U,H);return{words:q.words,envAssignments:Y,cwd:W,rewritten:Z7(q.words,X)}}function Z7($,Z){return $.some((J)=>!Z.has(J))}function J7($){return $.map(S).join(" ")}function H$($){let Z=$[0];return Z?S(Z):""}function u1($,Z){let J=$[Z];return J?S(J):void 0}function uB($){return Q7.test(H$($))}function hB($,Z,J){if(!$.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${Z.get("TMPDIR")??J.get("TMPDIR")??""}${$.slice(8)}`}}var gB=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function kB($,Z,J){let Q=1,X=J;while(Q<$.length){let K=u1($,Q);if(!K)break;if(K==="--")return{words:$.slice(Q+1),cwd:X};if(!K.startsWith("-"))break;if(K==="-D"||K==="--chdir"){let Y=u1($,Q+1);X=Y?$2(X,Y,Z):null,Q+=2;continue}if(K.startsWith("--chdir=")){X=$2(X,K.slice(8),Z),Q++;continue}if(K.startsWith("-D")&&K.length>2){X=$2(X,K.slice(2),Z),Q++;continue}if(K==="-i"||K==="--login"){X=null,Q++;continue}if(gB.has(K)){Q+=2;continue}Q++}return{words:$.slice(Q),cwd:X}}var xB=new Set(["-i","-0","--null"]),lB=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]);function mB($,Z,J,Q){let X=new Map,K=Z,Y=$,B=new Set,W=1;while(W<Y.length){let q=u1(Y,W);if(!q)break;if(q==="--")return{words:Y.slice(W+1),envAssignments:X,cwd:K};if(q==="-i"||q==="--ignore-environment"||q==="-"){X.clear();for(let H of J.keys())X.set(H,"");X.set("TMPDIR",""),W++;continue}if(xB.has(q)){W++;continue}if(q==="-u"||q==="--unset"){let H=u1(Y,W+1);if(H!==void 0)B.add(H),X.set(H,"");W+=2;continue}if(q.startsWith("-u")&&q.length>2&&!q.startsWith("-u=")){let H=q.slice(2);B.add(H),X.set(H,""),W++;continue}if(q.startsWith("--unset=")){let H=q.slice(8);B.add(H),X.set(H,""),W++;continue}let U=q==="-S"||q==="--split-string"?{value:u1(Y,W+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 H=pB(Y,W,U.value,U.consumed,J,B,K,Q.env);if(H.done)return H.result;Y=H.expanded,K=H.currentCwd,W=H.nextIndex;continue}if(lB.has(q)){if(q==="-C"||q==="--chdir"){let H=u1(Y,W+1);K=H?$2(K,H,Q.paths):null}W+=2;continue}if(q.startsWith("-u=")){W++;continue}if(q.startsWith("-C")&&q.length>2||q.startsWith("--chdir=")){let H=q.startsWith("--chdir=")?q.slice(8):q.startsWith("-C=")?q.slice(3):q.slice(2);K=$2(K,H,Q.paths),W++;continue}if(q.startsWith("-P")){W++;continue}if(q.startsWith("-")){W++;continue}if(!s1(q))break;while(W<Y.length){let H=s1(u1(Y,W)??"");if(!H)break;X.set(H.name,H.value),W++}if(u1(Y,W)==="--")W++;return{words:Y.slice(W),envAssignments:X,cwd:K}}return{words:Y.slice(W),envAssignments:X,cwd:K}}function pB($,Z,J,Q,X,K,Y,B){let W=J!==void 0?cB(J,X,K,B):{tokens:null,unverifiableEnvSplit:!1};if(W.unverifiableEnvSplit)return{done:!0,result:{words:$,envAssignments:new Map,cwd:Y,unverifiableEnvSplit:!0}};if(!W.tokens)return{done:!1,expanded:$,currentCwd:null,nextIndex:Z+Q};return{done:!1,expanded:[...$.slice(0,Z),...g(W.tokens),...$.slice(Z+Q)],currentCwd:Y,nextIndex:Z}}function cB($,Z,J,Q){if($.length>X7)return{tokens:null,unverifiableEnvSplit:!0};let X=dB($,(K)=>{if(J.has(K))return"";if(Z.has(K))return Z.get(K)??"";return Q.get(K)??""});return{tokens:X.tokens,unverifiableEnvSplit:X.limited}}function dB($,Z){let J=[],Q=[],X=0,K=!1,Y=!1,B=!1,W=!1,q=(H)=>{if(X+H.length>X7)return W=!0,!1;return Q.push(H),X+=H.length,K=!0,!0},U=()=>{if(!K)return!0;if(J.length>=vB)return W=!0,!1;return J.push(Q.join("")),Q=[],K=!1,!0};for(let H=0;H<$.length;H++){let j=$[H]??"";if(j==="'"&&!B){Y=!Y,K=!0;continue}if(j==='"'&&!Y){B=!B,K=!0;continue}if(!Y&&!B&&sB(j)){if(!U())return{tokens:null,limited:W};continue}if(!Y&&!B&&j==="#"&&!K)break;if(j==="$"&&!Y){let O=$.slice(H).match(wB);if(!O?.[1]||!q(Z(O[1])))return{tokens:null,limited:W};H+=O[0].length-1;continue}if(j!=="\\"){if(!q(j))return{tokens:null,limited:W};continue}let G=$[H+1];if(G===void 0)return{tokens:null,limited:W};if(Y&&G!=="'"&&G!=="\\"){if(!q("\\"))return{tokens:null,limited:W};continue}if(G==="c"){if(B)return{tokens:null,limited:W};break}if(G==="_"&&!Y&&!B){if(!U())return{tokens:null,limited:W};H++;continue}let _=iB(G);if(_===void 0||!q(_))return{tokens:null,limited:W};H++}if(Y||B||!U())return{tokens:null,limited:W};return{tokens:J,limited:!1}}function iB($){if($==="f")return"\f";if($==="n")return`
|
|
40
|
-
`;if($==="r")return"\r";if($==="t")return"\t";if($==="v")return"\v";if($==="_")return" ";if($==="#"||$==="$"||$==='"'||$==="'")return $;if($==="\\")return"\\";return}function sB($){return $===" "||$==="\t"||$===`
|
|
41
|
-
`||$==="\r"||$==="\f"||$==="\v"}function $2($,Z,J){if(Z==="")return null;if(!$&&!$7(Z))return null;let Q=$7(Z)?yB(Z).root:J.realpath($??"/");if(Q===null)return null;try{return b0(Q,Z,J)}catch{return null}}function rB($){if(u1($,1)==="-v")return[...g(["type"]),...$.slice(2)];let Z=1;while(Z<$.length){let J=u1($,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 I1($,Z,J){return E6($,Z,J).tokens}function E6($,Z,J,Q){if(!K7($[0]??""))return{tokens:[...$],envAssignments:new Map,cwd:J};let X=u0(g($),Z,J,Q);return{tokens:X.words.map(S),envAssignments:X.envAssignments,cwd:X.cwd,unverifiableEnvSplit:X.unverifiableEnvSplit}}import{isAbsolute as $W,normalize as ZW,resolve as B7}from"node:path";function x($){return h($).toLowerCase()}function h($){return $.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??$}function O1($,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 K=1;K<X.length;K++){let Y=X[K];if(!Y||!/[a-zA-Z]/.test(Y))break;let B=`-${Y}`;if(J.add(B),Z?.shortOptsWithValue?.has(B))break}}return J}var nB=new Map([["bash",new Set(["O","o"])],["dash",new Set(["o"])],["ksh",new Set(["o"])],["sh",new Set(["o"])],["zsh",new Set(["o"])]]),aB=new Map([["zsh",new Set(["o"])]]),oB=new Map([["bash",new Set(["--init-file","--rcfile"])]]);function Y7($,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 Y=oB.get($);if(eB(Q,Y))continue;if(!Y?.has(Q))continue;if(Z[J+1]===void 0)return null;J++;continue}let X=tB($,Q);if(X.commandSelected)return Z[J+X.followingValues+1]??null;let K=Z[J+1];if($==="ksh"&&(Q==="-o"||Q==="+o")&&K!==void 0&&K[0]!=="-"&&K[0]!=="+")J++;J+=X.followingValues}return null}function tB($,Z){let J=nB.get($),Q=aB.get($),X=!1,K=0;for(let Y=1;Y<Z.length;Y++){let B=Z[Y];if(B===void 0)break;if(Z[0]==="-"&&B==="c")X=!0;if($==="ksh"&&B==="o"){if(Y+1<Z.length){let W=Z.slice(Y+1);if(!X&&Z[0]==="-"&&W==="c")continue;if(!X&&Z[0]==="-"&&W[0]==="-"&&W.endsWith("c"))X=!0;break}if(X)K++;continue}if(!J?.has(B))continue;if(Q?.has(B)&&Y+1<Z.length)break;K++}return{commandSelected:X,followingValues:K}}function eB($,Z){return Z!==void 0&&[...Z].some((J)=>$.startsWith(`${J}=`))}var JW=new Set(["-S","--suffix"]);function P4($,Z,J,Q){if($.status==="structural-limit")throw new z0;if($.status!=="complete")return Q.findMalformedTarget($.source);let X={cwd:Z,variables:new Map},K=[];for(let Y of $.entries){if(Y.kind==="operator"){if(!Y.boundary)continue;let B=Q.findSegmentTarget(K,X);if(B)return B;X=QW(K,X,J,Q.normalizeCwd),K=[];continue}if(Y.kind==="redirection"){if(Y.role==="file-write"&&Y.target&&Q.isRedirectionTarget(L1(Y.target,X.variables),X))return Y.target;continue}K.push(Y.text)}return Q.findSegmentTarget(K,X)}function L1($,Z){return $.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(J,Q,X,K)=>{let Y=Z.get(Q);if(Y===void 0)return J;let B=X.startsWith(":")?Y!=="":!0;if(X.endsWith("-"))return B?Y:L1(K,Z);return B?L1(K,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 Z2($){return $.length>0&&$.every((Z)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(Z))}function K1($,Z,J){let Q=J.environment.home,X=Z4($.trim(),J.environment).replace(/\\/g,"/");if(!X)return"";let K=X==="~"?Q:X.startsWith("~/")?B7(Q,X.slice(2)):X;return i(ZW($W(K)?K:B7(Z,K)),J.environment.paths,J).replace(/\\/g,"/")}function C4($){let Z=[],J=null,Q=!1;for(let X=0;X<$.length;X++){let K=$[X];if(K===void 0)break;if(!Q&&K==="--"){Q=!0;continue}if(!Q&&(K==="-t"||K==="--target-directory")){J=$[++X]??null;continue}if(!Q&&K.startsWith("--target-directory=")){J=K.slice(19);continue}if(!Q&&K.startsWith("-t")&&K.length>2){J=K.slice(2);continue}if(!Q&&JW.has(K)){X++;continue}if(!Q&&(K.startsWith("--suffix=")||K.startsWith("--backup=")))continue;if(!Q&&K.startsWith("-"))continue;Z.push(K)}return J?{sources:Z,destination:J}:{sources:Z.slice(0,-1),destination:Z.at(-1)??null}}function QW($,Z,J,Q){let X=Z2($)?new Map([...Z.variables,...XW($,Z.variables)]):Z.variables,K=I1([...$],J.environment),Y=h(K[0]??"").toLowerCase()==="cd"?K[1]:void 0;return{cwd:!Y||Y==="-"?Z.cwd:Q(L1(Y,X),Z.cwd,J),variables:X}}function XW($,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],L1(X,Z)]]:[]})}var f1="Git metadata and hooks are protected. Ask the user before modifying them.";function G7($,Z=S6($.invocation.context.executionCwd)){let J=y0(B0()),Q=$.invocation.context.executionCwd;if(!Z)return null;if($.invocation.route.kind==="patch"||$.invocation.route.kind==="path"||$.invocation.route.kind==="unknown"){if(t2($.invocation.toolName))return null;let Y=$.paths.find((B)=>UW(B.raw,Q,Z,J))?.raw;return Y?{target:Y}:null}if($.invocation.route.kind!=="command")return null;let X=_1($,"input-candidate");if(!X)return null;let K=P4(X.shell,Q,J,{findSegmentTarget:(Y,B)=>HW(Y,B,Z,J),isRedirectionTarget:(Y,B)=>GW(Y,B.cwd,Z,J),findMalformedTarget:()=>null,normalizeCwd:K1});return K?{target:K}:null}function S6($,Z=y0(B0())){if(typeof $!=="string"||!$)return null;let J=e$(K1($,$,Z));if(!J)return null;try{let Q=K1(J,$,Z),X=KW(J),K=X.isFile()?Q:null,Y=X.isFile()?A6(J):null,B=(X.isDirectory()?[Q]:[Y?.gitDir,Y?.commonDir]).flatMap((q)=>q?[r1(K1(q,$,Z))]:[]),W=[...new Set(X.isDirectory()?[r1(J.replace(/\\/g,"/")),...B]:B)];return Object.freeze({entry:r1(Q),markerFile:K?r1(K):null,directories:Object.freeze(W),hooksDirectories:Object.freeze([...new Set(W.flatMap((q)=>{let U=r1(YW(q,"hooks"));return[U,r1(K1(U,$,Z))]}))])})}catch{return null}}function h0($,Z,J,Q,X,K=!1){if(!J)return!1;let Y=r1(K1($,Z,X)),B=Y.replace(/(\/\.?\*+)+$/,"");if(B!==Y&&B!==""){if(T6(B,J))return!0;let W=K||Y.slice(B.length).includes("/."),q=(U)=>W?A4(U,B):BW(U,B);if(J.markerFile&&q(J.markerFile))return!0;return Q&&W7(J).some(q)}if(T6(Y,J))return!0;return Q&&W7(J).some((W)=>A4(W,Y))}function BW($,Z){let J=U7(Z,$);if(J===""||J.startsWith("..")||q7(J))return!1;return!J.split(/[\\/]/)[0]?.startsWith(".")}function WW($,Z,J,Q){return h0($,Z,J,!0,Q)}function qW($,Z,J,Q){if(!J)return!1;return T6(r1(K1($,Z,Q)),J)}function UW($,Z,J,Q){if(!J)return!1;return H7($,Z,J,Q,J.entry)}function GW($,Z,J,Q){if(!J)return!1;return H7($,Z,J,Q,J.markerFile)}function H7($,Z,J,Q,X){let K=r1(K1($,Z,Q));return K===X||_7(K,J)}function j7($,Z,J,Q){if(!J)return!1;return J.hooksDirectories.some((X)=>$.some((K)=>A4(X,r1(K1(K,Z,Q)))))}function T6($,Z){return $===Z.entry||Z.directories.includes($)||_7($,Z)}function _7($,Z){return Z.hooksDirectories.some((J)=>A4($,J))}function W7($){return[$.entry,...$.directories,...$.hooksDirectories]}function A4($,Z){let J=U7(Z,$);return J===""||!/^\.\.(?:[\\/]|$)/.test(J)&&!q7(J)}function r1($){return process.platform==="win32"?$.toLowerCase():$}function HW($,Z,J,Q){if(Z2($))return null;let X=I1([...$],Q.environment);if(h(X[0]??"").toLowerCase()!=="mv")return null;let K=C4(X.slice(1)),Y=K.sources.find((B)=>WW(L1(B,Z.variables),Z.cwd,J,Q));if(Y)return Y;return K.destination&&qW(L1(K.destination,Z.variables),Z.cwd,J,Q)?K.destination:null}function y6($,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 n($){return $.value.length}function J2($,Z,J=1){if($)$.units=Math.min(Number.MAX_SAFE_INTEGER,$.units+Z.length*J)}function M1($,Z){J2($,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 p($){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 w6($){return $===`
|
|
42
|
-
`||$==="\r"||$==="\u2028"||$==="\u2029"}function c($,Z,J){if(Z+J.length>n($))return!1;for(let Q=0;Q<J.length;Q++)if(V($,Z+Q)!==J[Q])return!1;return!0}function q0($,Z,J){return!g0(V($,Z-1))&&c($,Z,J)&&!g0(V($,Z+J.length))}function U0($,Z){return g0(V($,Z-1))!==g0(V($,Z))}function J1($){return $===`
|
|
43
|
-
`||$===";"||$==="&"||$==="|"}function j$($){return $==="|"||$===";"}var F1=new Set(["awk","gawk","nawk","mawk"]),jW=new Set(["-e","--source"]),_W=new Set(["-F","-v","--assign","--field-separator"]),O7=new Set(["-f","--file"]),OW=new Set(["print","printf","return"]),L7=[{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"}],LW="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 S4($,Z,J){let Q=!1;for(let X of MW($)){let K=FW(X,J);if(!K)continue;for(let Y of K.commands){let B=Z(Y);if(B)return B;if(Y.includes("{}")||/[$`]/.test(Y))Q=!0}Q||=K.dynamic}return Q?N("awk.system-dynamic",LW):null}function u6($){let Z=[],J=!1,Q=!1,X=!0,K=!0;for(let Y=1;Y<$.length;Y++){let B=$[Y];if(B===void 0)break;if(X&&B==="--"){X=!1;continue}if(X&&jW.has(B)){J=!0;let W=$[Y+1];if(W!==void 0)Z.push({tokenIndex:Y+1,kind:"inline-code",value:W});else K=!1;Y++;continue}if(X&&B.startsWith("--source=")){J=!0,Z.push({tokenIndex:Y,kind:"inline-code",value:B.slice(9)});continue}if(X&&B.startsWith("-e")&&B.length>2){J=!0,Z.push({tokenIndex:Y,kind:"inline-code",value:B.slice(2)});continue}if(X&&(_W.has(B)||O7.has(B))){if(O7.has(B)){Q=!0;let W=$[Y+1];if(W!==void 0)Z.push({tokenIndex:Y+1,kind:"program-file",value:W});else K=!1}else if($[Y+1]===void 0)K=!1;Y++;continue}if(X&&(B.startsWith("-F")||B.startsWith("-v")&&B.slice(2).includes("=")))continue;if(X&&B.startsWith("-f")&&B.length>2){Q=!0,Z.push({tokenIndex:Y,kind:"program-file",value:B.slice(2)});continue}if(X&&(B.startsWith("--assign=")||B.startsWith("--field-separator=")))continue;if(X&&B.startsWith("--file=")){Q=!0,Z.push({tokenIndex:Y,kind:"program-file",value:B.slice(7)});continue}if(X&&B.startsWith("-")&&B!=="-")continue;if(X=!1,!J&&!Q)Z.push({tokenIndex:Y,kind:"main-program",value:B});return{sources:Z,optionsOpen:!1}}return{sources:K?Z:[],optionsOpen:X&&K}}function X2($){return u6($).sources}function MW($){return X2($).filter((Z)=>Z.kind!=="program-file").map((Z)=>Z.value)}function FW($,Z){M1(Z,$);let J=$.includes("system")?h6($,Z):null,Q=NW($,Z);if(!J&&!Q)return null;return{dynamic:!!J?.dynamic||!!Q?.dynamic,commands:[...J?.commands??[],...Q?.commands??[]]}}function h6($,Z){M1(Z,$);let J=[],Q=!1,X=!1,K=0;while(K<$.length){let Y=$[K];if(Y==='"'||Y==="'"){K=T4($,K,Y)?.endIndex??K+1;continue}if(Y==="#"){K=M7($,K+1);continue}if(Y==="/"&&F7($,K)){K=N7($,K+1)??K+1;continue}if(!$.startsWith("system",K)){K++;continue}let B=K;if(K+=6,Q2($[B-1])||Q2($[K]))continue;let W=E4($,K);if($[W]!=="(")continue;W=E4($,W+1);let q=$[W];if(q!=='"'&&q!=="'"){Q=!0,X=!0;continue}let U=T4($,W,q);if(!U){Q=!0,X=!0;continue}if(W=E4($,U.endIndex),Q=!0,$[W]!==")"){X=!0,K=U.endIndex;continue}J.push(U.value),K=W+1}if(!Q)return null;return{dynamic:X,commands:J}}function NW($,Z){M1(Z,$);let J=[],Q=!1,X=!1,K=0,Y=0,B=null,W=null,q=0;while(K<$.length){let U=$[K];if(!U)break;if(U==='"'||U==="'"){let G=T4($,K,U);if(G&&q===Y)W={...G,startIndex:K};q=G?.endIndex??K+1,K=G?.endIndex??K+1;continue}if(U==="#"){K=M7($,K+1),Y=K,B=null,W=null,q=K;continue}if(U==="/"&&F7($,K)){let G=N7($,K+1);q=G??K+1,K=G??K+1;continue}if(`;
|
|
44
|
-
{}`.includes(U)){K++,Y=K,B=null,W=null,q=K;continue}if(B===null&&(v6($,K,"print")||v6($,K,"printf")))B=K;if(U!=="|"||$[K-1]==="|"||$[K+1]==="|"){if(!/\s/.test(U))q=K+1;K++;continue}let H=$[K+1]==="&"?K+2:K+1,j=E4($,H);if(v6($,j,"getline")){X=!0;let G=DW(Y,W,q);if(G===null)Q=!0;else J.push(G);q=H,K=H;continue}if(bW(Y,B)){X=!0;let G=RW($,j);if(!G){Q=!0,q=H,K=H;continue}if(!VW($,G.endIndex)){Q=!0,q=G.endIndex,K=G.endIndex;continue}J.push(G.value),q=G.endIndex,K=G.endIndex;continue}q=H,K++}if(!X)return null;return{dynamic:Q,commands:J}}function Q2($){return!!$&&/[A-Za-z0-9_]/.test($)}function E4($,Z){let J=Z;while(/\s/.test($[J]??""))J++;return J}function VW($,Z){let J=Z;while(/[\t\f\v\r ]/.test($[J]??""))J++;let Q=$[J];return!Q||`;
|
|
45
|
-
}#`.includes(Q)}function T4($,Z,J){let Q="",X=!1;for(let K=Z+1;K<$.length;K++){let Y=$[K];if(!Y)break;if(X){let B=zW($,K);if(!B)return null;Q+=B.value,K=B.endIndex,X=!1;continue}if(Y==="\\"){X=!0;continue}if(Y===J)return{value:Q,endIndex:K+1};Q+=Y}return null}function RW($,Z){let J=$[Z];if(J!=='"'&&J!=="'")return null;return T4($,Z,J)}function DW($,Z,J){if(!Z)return null;return Z.startIndex>=$&&Z.endIndex===J?Z.value:null}function zW($,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:`
|
|
46
|
-
`,r:"\r",t:"\t",v:"\v"}[J]??J,endIndex:Z}}function v6($,Z,J){return $.startsWith(J,Z)&&!Q2($[Z-1])&&!Q2($[Z+J.length])}function bW($,Z){return Z!==null&&Z>=$}function M7($,Z){let J=$.indexOf(`
|
|
47
|
-
`,Z);return J===-1?$.length:J+1}function F7($,Z){let J=IW($,Z);if(J===-1)return!0;if("{([,;!~=".includes($[J]??""))return!0;let Q=J;while(Q2($[Q-1]))Q--;return OW.has($.slice(Q,J+1))}function IW($,Z){for(let J=Z-1;J>=0;J--)if(!/\s/.test($[J]??""))return J;return-1}function N7($,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}function y4($,Z,J){let Q=y6($,J);if(Z==="rm")return fW(Q);if(Z==="dd")return CW(Q);return I7(Q,!0)}function w4($,Z,J){let Q=y6($,J);if(Z==="rm")return AW(Q);if(Z==="reset-hard")return z7(Q,"--ha","rd");if(Z==="reset-merge")return z7(Q,"--me","rge");if(Z==="clean")return yW(Q);if(Z==="checkout")return vW(Q);if(Z==="push-force")return uW(Q);if(Z==="push-refspec")return hW(Q);if(Z==="push-delete")return gW(Q);if(Z==="branch")return kW(Q);if(Z==="tag")return mW(Q);if(Z==="restore")return pW(Q);return I7(Q,!1)}function fW($){let Z=!1,J=!1,Q=!1,X=-1;for(let K=0;K<=n($);K++){let Y=V($,K);if(!Z){let W=V($,K+2);if(q0($,K,"rm")&&p(W)&&W!==`
|
|
48
|
-
`)Z=!0,K++;continue}let B=PW($,K);if(Y===`
|
|
49
|
-
`||B!==-1){if(Z=!1,J=!1,Q=!1,X=-1,B!==-1)K=B-1;continue}if(Y===";"||Y==="&"||Y==="|"||K===n($)){if(X>=0){let W=V7($,X,K);J||=W.recursive,Q||=W.force}if(J&&Q)return!0;Z=!1,J=!1,Q=!1,X=-1;continue}if(p(Y)){if(X>=0){if(c($,X,"--")&&K-X===2)Z=!1,J=!1,Q=!1;else{let W=V7($,X,K);if(J||=W.recursive,Q||=W.force,J&&Q)return!0}X=-1}continue}if(X<0)X=K}return!1}function PW($,Z){if(V($,Z)!=="\\"||V($,Z-1)==="\\")return-1;if(c($,Z,String.raw`\n`))return Z+2;if(c($,Z,String.raw`\x0a`)||c($,Z,String.raw`\x0A`))return Z+5;if(c($,Z,String.raw`\u000a`)||c($,Z,String.raw`\u000A`))return Z+7;return c($,Z,String.raw`\012`)?Z+4:-1}function V7($,Z,J){if(R7($,Z,J,"recursive"))return{recursive:!0,force:!1};if(R7($,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 K=Z+1;K<J;K++){let Y=V($,K);Q||=Y==="r"||Y==="R",X||=Y==="f"||Y==="F"}return{recursive:Q,force:X}}function R7($,Z,J,Q){let X=J-Z-2;if(X<1||X>Q.length||!c($,Z,"--"))return!1;for(let K=0;K<X;K++)if(V($,Z+K+2)!==Q[K])return!1;return!0}function CW($){let Z=!1;for(let J=0;J<n($);J++){if(J1(V($,J))){Z=!1;continue}if(q0($,J,"dd")){Z=!0,J++;continue}if(!Z||!q0($,J,"of")||!c($,J,"of=/dev/"))continue;let Q=J+8;if(Q<n($)&&!p(V($,Q))&&V($,Q)!=="'"&&V($,Q)!=='"')return!0}return!1}function AW($){let Z=!1,J=!1,Q=!1;for(let X=0;X<=n($);){let K=V($,X);if(X===n($)||J1(K)){Z=!1,J=!1,Q=!1,X++;continue}let Y=TW($,X);if(Y>=0){if(EW($,Y))return!0;let B=Y,W=!1;while(p(V($,B)))W||=V($,B)===`
|
|
50
|
-
`,B++;if(W)J=!1,Q=!1;Z=!0,X=B;continue}if(!Z){X++;continue}if(c($,X,"--")&&(X===0||p(V($,X-1)))&&(!V($,X+2)||p(V($,X+2))||J1(V($,X+2)))){Z=!1,J=!1,Q=!1,X+=2;continue}if(J||=c($,X,"--recursive")&&U0($,X+11)||g6($,X,"recursive"),Q||=c($,X,"--force")&&U0($,X+7)||g6($,X,"force"),J&&Q)return!0;X++}return!1}function g6($,Z,J){if(!c($,Z,"--"))return!1;let Q=0;while(Q<=J.length){let X=V($,Z+Q+2);if(!X||p(X)||J1(X))break;if(X!==J[Q])return!1;Q++}return Q>0&&U0($,Z+Q+2)}function EW($,Z){let J=Z,Q=!1,X=!1;while(J<n($)){while(p(V($,J)))J++;let K=J;while(J<n($)&&!p(V($,J)))J++;if(V($,K)!=="-"||J-K===2&&c($,K,"--"))return!1;let Y=D7($,K,"recursive"),B=D7($,K,"force");if(Q&&B||X&&Y)return!0;if(Q||=Y,X||=B,V($,K+1)==="-")continue;let W=SW($,K,J);if(W.combined||Q&&W.forceAtBoundary||X&&W.recursiveAtBoundary)return!0;Q||=W.recursive,X||=W.force}return!1}function D7($,Z,J){return c($,Z,`--${J}`)&&U0($,Z+J.length+2)||g6($,Z,J)}function TW($,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"||!p(V($,J+1)))return-1;return J+1}function SW($,Z,J){let Q=!1,X=!1,K=!1,Y=!1,B=!1;if(V($,Z)!=="-")return{recursive:Q,force:X,recursiveAtBoundary:K,forceAtBoundary:Y,combined:B};let W="";for(let q=Z+1;q<J;q++){let U=V($,q)??"",H=(U==="r"||U==="f")&&U0($,q+1);Q||=U==="r",X||=U==="f",K||=U==="r"&&H,Y||=U==="f"&&H,B||=(W==="r"&&U==="f"||W==="f"&&U==="r")&&H,W=U}return{recursive:Q,force:X,recursiveAtBoundary:K,forceAtBoundary:Y,combined:B}}function z7($,Z,J){return Y2($,"reset",j$,!0,(Q)=>V($,Q)==="-"&&_$($,Q,Z,J)?!0:Q)}function yW($){return Y2($,"clean",j$,!0,(Z)=>{if(V($,Z)!=="-")return Z;if(_$($,Z,"--fo","rce"))return!0;let J=K2($,Z,j$);for(let Q=Z+1;Q<J;Q++)if(V($,Q)==="f")return!0;return J-1})}function v4($,Z,J){if(!q0($,Z,"git"))return null;let Q=Z+3;if(!p(V($,Q)))return{commandEnd:-1,next:Q};while(p(V($,Q)))Q++;while(Q<n($)){if(J1(V($,Q)))return{commandEnd:-1,next:Q};let X=K2($,Q,J1);if(q0($,Q,J))return{commandEnd:Q+J.length,next:X};if(V($,Q)!=="-")return{commandEnd:-1,next:X};let K=X-Q===2&&c($,Q,"--"),Y=wW($,Q,X);Q=X;while(p(V($,Q)))Q++;if(K)return{commandEnd:q0($,Q,J)?Q+J.length:-1,next:K2($,Q,J1)};if(!Y)continue;if(Q>=n($)||J1(V($,Q)))return{commandEnd:-1,next:Q};Q=K2($,Q,J1);while(p(V($,Q)))Q++}return{commandEnd:-1,next:Q}}function wW($,Z,J){for(let Q of i1)if(J-Z===Q.length&&c($,Z,Q))return!0;return!1}function vW($){return b7($,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function uW($){return Y2($,"push",j$,!0,(Z)=>{if(V($,Z)!=="-")return Z;if(V($,Z+1)==="f"&&!g0(V($,Z+2))&&!c($,Z+2,"-with-lease"))return!0;let J=f7($,Z,"--fo","rce");if(J>=0&&!c($,J,"-with-lease"))return!0;return Z})}function hW($){return Y2($,"push",J1,!1,(Z)=>{if(p(V($,Z))&&V($,Z+1)==="+"&&Z+2<n($)&&!J1(V($,Z+2))&&!p(V($,Z+2)))return!0;if(V($,Z)===":"&&V($,Z+1)==="+")return!0;return Z})}function gW($){return Y2($,"push",J1,!1,(Z)=>{if(V($,Z)==="-"&&_$($,Z,"--de","lete"))return!0;if(p(V($,Z))&&V($,Z+1)===":"&&Z+2<n($)&&!p(V($,Z+2))&&!J1(V($,Z+2)))return!0;return Z})}function kW($){let Z=!1,J=!1,Q=!1;for(let X=0;X<=n($);X++){if(X===n($)||J1(V($,X))){if(J&&Q)return!0;Z=!1,J=!1,Q=!1;continue}if(!Z){let B=v4($,X,"branch");if(B){Z=B.commandEnd>=0,X=Math.max(X,(Z?B.commandEnd:B.next)-1);continue}}if(!Z||V($,X)!=="-")continue;let K=K2($,X,J1),Y=xW($,X,K);if(J||=Y.deletion,Q||=Y.force,J&&Q)return!0;X=K-1}return!1}function xW($,Z,J){let Q=!1,X=!1;for(let K=Z;K<J;K++){if(V($,K)!=="-")continue;if(_$($,K,"--de","lete"))Q=!0;if(_$($,K,"--fo","rce"))X=!0;if(V($,K+1)==="-")continue;let Y=K+1,B=!1,W=!1,q=!1;while(Y<J&&lW(V($,Y))){let U=V($,Y);B||=U==="d"||U==="D",W||=U==="f",q||=U==="D",Y++}if(!U0($,Y))continue;Q||=B,X||=W||q}return{deletion:Q,force:X}}function lW($){if(!$)return!1;let Z=$.charCodeAt(0);return Z>=65&&Z<=90||Z>=97&&Z<=122}function mW($){return b7($,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function b7($,Z){let J=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let Q=0;Q<n($);Q++){let X=V($,Q),K=J[J.length-1];if(!K)return!1;let Y=K.escaped;if(K.escaped=!Y&&K.quote!=="'"&&X==="\\",!Y&&X==="'"&&K.quote!=='"')K.quote=K.quote==="'"?"":"'";if(!Y&&X==='"'&&K.quote!=="'")K.quote=K.quote==='"'?"":'"';if(X==="$"&&V($,Q+1)==="("&&(J.length===1||!Y&&K.quote!=="'")){J.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),Q++;continue}if(!Y&&!K.quote&&J.length>1&&X==="("){K.depth++;continue}if(!Y&&!K.quote&&J.length>1&&X===")"){if(K.depth--,K.depth===0)J.pop();continue}if(p(X))K.shortActive=!1,K.hasShortFlag=!1;if(!K.outerActive){let B=v4($,Q,Z.command);if(B){K.outerActive=B.commandEnd>=0&&p(V($,B.commandEnd)),K.shortActive=!1,K.hasShortFlag=!1,Q=Math.max(Q,(K.outerActive?B.commandEnd:B.next)-1);continue}}if(K.outerActive&&X==="-"){if(_$($,Q,Z.longPrefix,Z.longOptional))return!0;K.shortActive||=!Z.excludedShortStarts.includes(V($,Q+1)??"")}if(K.hasShortFlag||=K.shortActive&&X===Z.shortFlag,K.hasShortFlag&&U0($,Q+1))return!0;if(j$(X))K.outerActive=!1}return!1}function Y2($,Z,J,Q,X){let K=!1;for(let Y=0;Y<n($);Y++){let B=V($,Y),W=J(B);if(!K&&!W){let q=v4($,Y,Z);if(q){K=q.commandEnd>=0&&(!Q||p(V($,q.commandEnd))),Y=Math.max(Y,(K?q.commandEnd:q.next)-1);continue}}if(K){let q=X(Y);if(q===!0)return!0;for(let U=Y;U<=q;U++)if(J(V($,U)))K=!1;Y=q}if(W)K=!1}return!1}function pW($){let Z=!1;for(let J=0;J<n($);J++){if(w6(V($,J))){if(Z)return!0;Z=!1;continue}if(!Z){let Q=v4($,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)==="-"&&(c($,J+2,"staged")||c($,J+2,"help")))Z=!1}return Z}function I7($,Z){let J=!1;for(let Q=0;Q<n($);Q++){let X=V($,Q),K=Z?w6(X):J1(X);if(J&&p(X)&&V($,Q+1)==="-"&&q0($,Q+2,"delete"))return!0;if(K){J=!1;continue}if(q0($,Q,"find"))J=!0,Q+=3}return!1}function K2($,Z,J){let Q=Z;while(Q<n($)&&!p(V($,Q))&&!J(V($,Q)))Q++;return Q}function f7($,Z,J,Q){if(!c($,Z,J))return-1;let X=Z+J.length;for(let K=0;K<Q.length&&V($,X)===Q[K];K++)X++;return U0($,X)?X:-1}function _$($,Z,J,Q){return f7($,Z,J,Q)>=0}var k0="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.",u4=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),cW=new Set(["-p","--print"]),dW=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),iW=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"])]]),sW=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),rW=new Map([["python",new Set(["m"])]]),nW=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"])]]),aW=new Set(["always","default","never"]),oW=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),tW=/\\\r?\n/g,eW=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 h4($){return k4($).code}function g4($){return k4($).sources}function C7($){return eW.get(l4($))??[]}function k4($){let Z=l4($[0]??"");if(!u4.has(Z))return{code:null,sources:[],optionsOpen:!1};let J=[],Q=[],X=!0;for(let K=1;K<$.length;K++){let Y=$[K];if(Y===void 0)break;if(Y==="--")return h1(Z,J,Q,X,$[K+1]===void 0?void 0:K+1,$[K+1]);if(Y===""||Y==="-"||!Y.startsWith("-"))return h1(Z,J,Q,X,K,Y);if(Z==="node"&&cW.has(Y)){let H=$[K+1];if(H===void 0)return h1(Z,J,Q,X);if(H.startsWith("-"))continue;J.push({tokenIndex:K+1,value:H}),Q.push({tokenIndex:K+1,kind:"inline-code",value:H}),K++;continue}if(Zq(Z,Y)){let H=$[K+1];if(H===void 0)return h1(Z,J,Q,X);if(J.push({tokenIndex:K+1,value:H}),Q.push({tokenIndex:K+1,kind:"inline-code",value:H}),Z==="python")return h1(Z,J,Q,X);K++;continue}let B=/^--eval=(.*)$/s.exec(Y);if(Jq(Z)&&B){let H=B[1]??"";J.push({tokenIndex:K,value:H}),Q.push({tokenIndex:K,kind:"inline-code",value:H});continue}if(Z==="node"){let H=$q(Y);if(H){if(H.attached){if(X&&=H.value!=="",H.value!=="")Q.push({tokenIndex:K,kind:"module-file",value:H.value});continue}let j=$[K+1];if(j===void 0||j.startsWith("-"))return X=!1,h1(Z,J,Q,X);Q.push({tokenIndex:K+1,kind:"module-file",value:j}),K++;continue}}if(Z==="python"&&Y.startsWith("--check-hash-based-pycs=")||Z==="node"&&(Y==="--conditions="||Y==="--diagnostic-dir="||Y==="--title=")||Z==="ruby"&&(Y==="--disable="||Y==="--enable="))return h1(Z,J,Q,X);if(nW.get(Z)?.has(Y)){let H=$[K+1];if(H===void 0||H.startsWith("-")&&!(Z==="ruby"&&oW.has(Y))||Z==="python"&&!aW.has(H))return h1(Z,J,Q,X);K++;continue}if(Y.startsWith("--"))continue;let W,q=!1;for(let H=1;H<Y.length;H++){let j=Y[H];if(j===void 0)break;if(rW.get(Z)?.has(j)){let G=Y.slice(H+1),_=G||$[K+1];if(_!==void 0)Q.push({tokenIndex:G?K:K+1,kind:"module-file",value:_});return h1(Z,J,Q,X)}if(dW.get(Z)?.has(j)){W=Y.slice(H+1)||$[K+1],q=H+1===Y.length;break}if(Z==="node"&&j==="r"){if(Y==="-r"){let G=$[K+1];if(X&&=G!==void 0&&!G.startsWith("-"),X&&G!==void 0)Q.push({tokenIndex:K+1,kind:"module-file",value:G});K++}else X=!1;break}if(Z==="ruby"&&j==="r"){let G=Y.slice(H+1),_=G||$[K+1];if(X&&=_!==void 0,_!==void 0)Q.push({tokenIndex:G?K:K+1,kind:"module-file",value:_});if(!G)K++;break}if(Z==="perl"&&(j==="M"||j==="m")){let G=Y.slice(H+1);if(G)Q.push({tokenIndex:K,kind:"module-file",value:G});else if(X=!1,H+1===Y.length)K++;break}if(iW.get(Z)?.has(j)){if(H+1===Y.length)K++;break}if(sW.get(Z)?.has(j)&&H+1<Y.length)break}if(W===void 0)continue;let U=q?K+1:K;if(J.push({tokenIndex:U,value:W}),Q.push({tokenIndex:U,kind:"inline-code",value:W}),Z==="python")return h1(Z,J,Q,X);if(q)K++}return h1(Z,J,Q,X,void 0,void 0,!0)}function h1($,Z,J,Q,X,K,Y=!1){let B=$==="node"?Z.slice(-1):Z,W=new Set(B.map((U)=>U.tokenIndex)),q=J.filter((U)=>U.kind!=="inline-code"||W.has(U.tokenIndex));if(Q&&Z.length===0&&X!==void 0&&K!==void 0)q.push({tokenIndex:X,kind:"main-script",value:K});return{code:($==="node"?B[0]?.value:B.map((U)=>U.value).join(`
|
|
51
|
-
`))||null,sources:Q?q:[],optionsOpen:Q&&Y}}function $q($){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 u4.has(l4($))}function x4($,Z){return l4($)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(Z)}function l4($){let Z=h($).toLowerCase();return rZ.test(Z)?"python":Z}function Zq($,Z){return u4.get($)?.has(Z)??!1}function Jq($){return u4.get($)?.has("--eval")??!1}function L$($,Z){let J=Kq($,Z);if(!P7(J,Z))return!1;M1(Z,J);let Q=Xq(J);if(P7(Q,Z))return!0;return M1(Z,Q),Qq.test(Q)}var Qq=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function Xq($){let Z=[],J=0,Q=0;while(Q<$.length){let X=$[Q];if(X!=="'"&&X!=='"'){Q++;continue}let K=$.startsWith(X.repeat(3),Q)?X.repeat(3):X,Y=Q+K.length;while(Y<$.length&&!$.startsWith(K,Y))Y+=$[Y]==="\\"?2:1;if(Y>=$.length)break;Z.push($.slice(J,Q)," "),Q=Y+K.length,J=Q}return Z.push($.slice(J)),Z.join("")}function P7($,Z){if(y4($,"rm",Z))return!0;for(let Q of[/\bgit[^\S\n]+reset[^\S\n]+--ha(?:r(?:d)?)?\b/,/\bgit[^\S\n]+reset[^\S\n]+--me(?:r(?:g(?:e)?)?)?\b/,/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+clean[^\S\n]+(-[^\s]*f[^\s]*|--fo(?:r(?:c(?:e)?)?)?)\b/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(M1(Z,$),Q.test($))return!0;if(y4($,"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(y4($,"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)=>w4(X,Q))})}function Kq($,Z){return M1(Z,$),$.replace(tW,"")}var A7=new Set(["rm","find","xargs","parallel"]),Yq=new Set(["sudo","env","command","builtin"]),Bq=new Set(["git","busybox",...A7,...$1,...sZ,...F1]);function m4($,Z){let J=$[0];if(!J||!Z.transparentWrappers.includes(h(J)))return null;let Q=h(J),X=$[1]==="--"?2:1,K=Wq($,X,Q,Z),Y=K[0];if(Y===void 0)return null;return{wrapper:Q,tokens:[...$.slice(Y)],childIndex:Y,alternativeChildIndices:K.slice(1)}}function Wq($,Z,J,Q){let X=$[1]==="--",K=[];for(let Y=Z;Y<$.length;Y++){let B=$[Y];if(!B)continue;if(h(B)!==J&&qq(B,Q))K.push(Y);else if(a2.has(x(B)))break;if(X)break}return K}function qq($,Z){let J=h($),Q=x($);return Q==="git"||J==="busybox"||B2($)||A7.has(J)||Z.transparentWrappers.includes(J)||$1.has(Q)||$==="$SHELL"||N1(Q)||F1.has(Q)||Z.rules.some((X)=>X.command===J)}function B2($){return Yq.has($.toLowerCase())}function E7($){let Z=x($);return Bq.has(Z)||N1(Z)}var o={level:{name:"CC_SAFETY_NET_LEVEL"},strict:{name:"CC_SAFETY_NET_STRICT",legacyName:"SAFETY_NET_STRICT"},paranoid:{name:"CC_SAFETY_NET_PARANOID",legacyName:"SAFETY_NET_PARANOID"},paranoidRm:{name:"CC_SAFETY_NET_PARANOID_RM",legacyName:"SAFETY_NET_PARANOID_RM"},paranoidInterpreters:{name:"CC_SAFETY_NET_PARANOID_INTERPRETERS",legacyName:"SAFETY_NET_PARANOID_INTERPRETERS"},worktree:{name:"CC_SAFETY_NET_WORKTREE",legacyName:"SAFETY_NET_WORKTREE"},debug:{name:"CC_SAFETY_NET_DEBUG"},auditScope:{name:"CC_SAFETY_NET_AUDIT_SCOPE"}},p4=["standard","strict","paranoid"];function Uq($){return{failClosed:$==="strict"||$==="paranoid",paranoidRm:$==="paranoid",paranoidInterpreters:$==="paranoid"}}function Gq($,Z){if(!Z)return $;return p4.indexOf(Z)>p4.indexOf($)?Z:$}function Hq(){let $=x6(o.level);if($===void 0||$==="")return;if(p4.includes($))return $;console.error(`CC Safety Net: ignored invalid ${o.level.name}=${JSON.stringify($.slice(0,40))}. Use ${p4.join(", ")}.`);return}function jq($){if($===void 0||$==="all")return"all";if($==="blocked")return"blocked";return"invalid"}function _q(){return jq(x6(o.auditScope))==="all"}function k6($){if($.failClosed&&$.paranoidRm&&$.paranoidInterpreters)return"paranoid";if($.failClosed&&!$.paranoidRm&&!$.paranoidInterpreters)return"strict";if(!$.failClosed&&!$.paranoidRm&&!$.paranoidInterpreters)return"standard";return"custom"}function c4($={}){let Z=$.safety?.level??"standard",J=Hq(),Q=Gq(Z,J),X=Uq(Q),K={failClosed:Q===Z?"preset":"environment",paranoidRm:Q===Z?"preset":"environment",paranoidInterpreters:Q===Z?"preset":"environment"},Y={failClosed:[`policy safety.level=${Z}`],paranoidRm:[`policy safety.level=${Z}`],paranoidInterpreters:[`policy safety.level=${Z}`],worktreeMode:[]};if(Q!==Z)Y.failClosed.push(`env ${o.level.name}=${J}`),Y.paranoidRm.push(`env ${o.level.name}=${J}`),Y.paranoidInterpreters.push(`env ${o.level.name}=${J}`);if($.safety?.overrides?.failClosed!==void 0)X.failClosed=$.safety.overrides.failClosed,K.failClosed="capability_override",Y.failClosed.push("policy safety.overrides.fail_closed");if($.safety?.overrides?.paranoidRm!==void 0)X.paranoidRm=$.safety.overrides.paranoidRm,K.paranoidRm="capability_override",Y.paranoidRm.push("policy safety.overrides.paranoid_rm");if($.safety?.overrides?.paranoidInterpreters!==void 0)X.paranoidInterpreters=$.safety.overrides.paranoidInterpreters,K.paranoidInterpreters="capability_override",Y.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(x0(o.strict))X.failClosed=!0,K.failClosed="environment",Y.failClosed.push(`env ${o.strict.name}`);if(x0(o.paranoid))X.paranoidRm=!0,X.paranoidInterpreters=!0,K.paranoidRm="environment",K.paranoidInterpreters="environment",Y.paranoidRm.push(`env ${o.paranoid.name}`),Y.paranoidInterpreters.push(`env ${o.paranoid.name}`);if(x0(o.paranoidRm))X.paranoidRm=!0,K.paranoidRm="environment",Y.paranoidRm.push(`env ${o.paranoidRm.name}`);if(x0(o.paranoidInterpreters))X.paranoidInterpreters=!0,K.paranoidInterpreters="environment",Y.paranoidInterpreters.push(`env ${o.paranoidInterpreters.name}`);let B=!!$.worktreeMode||x0(o.worktree);if($.worktreeMode)Y.worktreeMode.push("policy workflow.worktree_mode");if(x0(o.worktree))Y.worktreeMode.push(`env ${o.worktree.name}`);return{strict:X.failClosed,paranoidRm:X.paranoidRm,paranoidInterpreters:X.paranoidInterpreters,worktreeMode:B,effectiveLevel:k6(X),capabilities:{fail_closed:{enabled:X.failClosed,source:K.failClosed,sources:Y.failClosed},paranoid_rm:{enabled:X.paranoidRm,source:K.paranoidRm,sources:Y.paranoidRm},paranoid_interpreters:{enabled:X.paranoidInterpreters,source:K.paranoidInterpreters,sources:Y.paranoidInterpreters}},sources:Y}}function x0($){let Z=typeof $==="string"?W2($):x6($);return Z==="1"||Z?.toLowerCase()==="true"}function W2($){return Object.hasOwn(process.env,$)?process.env[$]:void 0}function x6($){let Z=W2($.name);if(Z!==void 0)return Z;if($.legacyName)return W2($.legacyName);return}function DN($){return W2($.name)!==void 0||!!$.legacyName&&W2($.legacyName)!==void 0}function T7($){let Z=$.effectiveCapabilities,J=$.strict??Z.fail_closed.enabled,Q=$.paranoidRm??Z.paranoid_rm.enabled,X=$.paranoidInterpreters??Z.paranoid_interpreters.enabled,K={fail_closed:l6(Z.fail_closed,$.strict,"strict"),paranoid_rm:l6(Z.paranoid_rm,$.paranoidRm,"paranoidRm"),paranoid_interpreters:l6(Z.paranoid_interpreters,$.paranoidInterpreters,"paranoidInterpreters")};return{policy:iZ($.policySnapshot.policy,K),effectiveCapabilities:K,effectiveLevel:k6({failClosed:J,paranoidRm:Q,paranoidInterpreters:X}),strict:J,paranoidRm:Q,paranoidInterpreters:X,worktreeMode:$.worktreeMode??!1}}function l6($,Z,J){if(Z===void 0||Z===$.enabled)return $;return{enabled:Z,source:"capability_override",sources:[...$.sources,`analysis options.${J}`]}}function q2($,Z){J2(Z,$,2);let J=$.toLowerCase(),Q=J.trimStart(),X=Q.startsWith("echo ")||Q.startsWith("rg "),K=[{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 Y of K){if(Y.skipForEchoRg&&X)continue;let B=Y.caseSensitive?$:J;if(Y.regex)M1(Z,B);if((Y.regex?.test(B)??!1)||Y.scan&&w4(B,Y.scan,Z))return N("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${Y.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var Oq=/^[A-Za-z_][A-Za-z0-9_]*=/;function y7($,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;J2(J,Z.source,2);let K={anchored:new RegExp(`^\\$\\{?${X}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${X}(?![A-Za-z0-9_])`)};return w7(Z.nodes,Q,K)}function w7($,Z,J){return $.every((Q)=>{if(Q.kind==="connector")return!0;if(Q.kind==="group"||Q.kind==="function")return w7(Q.body.nodes,Z,J);if(Q.kind==="unknown")return!J.loose.test(Q.source);return Lq(Q,Z,J)})}function Lq($,Z,J){if($.nested.some((X)=>J.loose.test(X.source)))return!1;let Q=$.words.findIndex((X)=>!Oq.test(X.text));return $.words.every((X,K)=>X===Z||S7(X.raw,J.anchored,K!==Q))&&$.redirections.every((X)=>(!X.heredoc||X.heredoc.quotedDelimiter||!J.loose.test(X.heredoc.body))&&(!X.target||S7(X.target.raw,J.anchored,!0)))}function S7($,Z,J){let Q=!1,X=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(Y==="\\"&&!Q){K++;continue}if(!X&&Y==="'"){Q=!Q;continue}if(!Q&&Y==='"'){X=!X;continue}if(Q||Y!=="$")continue;if(!Z.test($.slice(K)))continue;if(!X||!J)return!1}return!0}var v7=Object.freeze({maxDerivedTokens:16384}),u7="Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry.",h7="env -S split-string variables cannot be resolved safely. Use literal values or expand the command explicitly.";class P1 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 l0 extends Error{constructor(){super("env -S split-string variables cannot be resolved safely. Use literal values or expand the command explicitly.");this.name="EnvSplitStringExpansionError"}}function d4(){return{derivedTokens:0}}function n1($,Z){if(!Number.isSafeInteger($.derivedTokens)||$.derivedTokens<0||$.derivedTokens>v7.maxDerivedTokens||!Number.isSafeInteger(Z)||Z<0||Z>v7.maxDerivedTokens-$.derivedTokens)throw new P1;$.derivedTokens+=Z}import{isAbsolute as Mq,resolve as g7}from"node:path";var k7=64;function U2($,Z,J){let Q=Mq($)?g7($):Z?g7(Z,$):void 0;if(!Q)return;try{return i(Q,J)}catch{return Q}}function x7($){return!["/dev","/proc","/sys"].some((Z)=>$===Z||$.startsWith(`${Z}/`))}var E=Object.freeze({maxChildAnalyses:1024,maxDerivedTokens:16384,maxDerivedBytes:1048576,maxPlaceholderReplacements:16384}),l7="Parallel command expands beyond CC Safety Net's analysis limits. Reduce the template or explicit argument list and retry.";class s4 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 m7(){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,K=Z.placeholderReplacements??0;if(i4($.childAnalyses,J,E.maxChildAnalyses)||i4($.derivedTokens,Q,E.maxDerivedTokens)||i4($.derivedBytes,X,E.maxDerivedBytes)||i4($.placeholderReplacements,K,E.maxPlaceholderReplacements))throw new s4;$.childAnalyses+=J,$.derivedTokens+=Q,$.derivedBytes+=X,$.placeholderReplacements+=K}function i4($,Z,J){return!Number.isSafeInteger($)||$<0||$>J||!Number.isSafeInteger(Z)||Z<0||Z>J-$}import{isAbsolute as r6,normalize as Pq,parse as Cq,posix as $5,resolve as M$,sep as s6}from"node:path";import{isAbsolute as Fq,join as p7,normalize as i7,parse as Nq,sep as c7}from"node:path";var Vq=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],Rq=`
|
|
52
|
-
`;function G2($,Z){if(a1($,Z))return!0;if(!$.has("TMPDIR"))return!1;return!m6($.get("TMPDIR")??"",Z)}function G0($,Z){if($.has("TMPDIR"))return m6($.get("TMPDIR")??"",Z);let J=p6($,Z);if(J===void 0)return!0;return m6(J,Z)}function p6($,Z){return n7($,Z,"TMPDIR")}function m6($,Z){if(!$)return!1;if(zq($))return!1;return c6($,Z)}function a1($,Z){let J=n7($,Z,"IFS");return J!==void 0&&J!==""&&J!==Rq}function c6($,Z){let J=r4($,Z.paths);return J!==null&&r7(Z).some((Q)=>Iq(J,Q))}function s7($,Z){let J=r4($,Z.paths);return J!==null&&r7(Z).includes(J)}var d7=new WeakMap;function r7($){let Z=d7.get($);if(Z)return Z;let J=Dq($);return d7.set($,J),J}function Dq($){let Z=Vq.map((Q)=>r4(Q,$.paths)??i7(Q)),J=r4($.tmpdir,$.paths);if(!J)return Z;if(process.platform==="win32")return[...Z,J];if(process.platform==="darwin"&&bq(J))return[...Z,J];return Z}function zq($){return/[\s$`*?[]/.test($)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test($)||/[+@!]\([^)]*\)/.test($)}function n7($,Z,J){return $.has(J)?$.get(J):Z.env.get(J)}function bq($){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test($)}function r4($,Z){try{let J=i7($);if(!Fq(J))return J;let Q=Nq(J).root,X=J.slice(Q.length).split(/[\\/]+/).filter(Boolean),K=Q;for(let Y=0;Y<X.length;Y++){let B=p7(K,X[Y]??"");if(Z.entryKind(B)==="missing")return p7(B,...X.slice(Y+1));let W=Z.realpath(B);if(W===null)return null;K=W}return K}catch{return null}}function Iq($,Z){if($===Z)return!0;let J=Z.endsWith(c7)?Z:`${Z}${c7}`;return $.startsWith(J)}import{isAbsolute as t7,normalize as fq,sep as d6}from"node:path";var a7=process.platform==="win32";function H2($,Z){if($==="~")return Z;if($.startsWith("~/"))return`${Z}${$.slice(1)}`;return $}function n4($,Z){if(typeof $!=="string"||$.trim()==="")return"must be a non-empty path string";let J=H2($.trim(),Z);if(!t7(J))return"must be an absolute path or start with ~/";return o4(J,Z)}function a4($,Z){if(typeof $!=="string"||$.trim()==="")return"must be a non-empty path string";let J=H2($.trim().replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),Z);if(!t7(J))return null;if(o4(J,Z)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}function o4($,Z){let J=o7($),Q=o7(Z);if(J===Q)return"cannot be the home directory";let X=J.endsWith(d6)?J:`${J}${d6}`;if(Q.startsWith(X))return"cannot contain the home directory";return null}function o7($){let Z=fq($);if(a7)Z=Z.replace(/\//g,"\\").toLowerCase();if(Z.length>(a7?3:1)&&Z.endsWith(d6))Z=Z.slice(0,-1);return Z}var Aq=process.platform==="win32",e7=64,Eq=16384;function j2($){let Z=R8($,e7,e7,Eq);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:Tq($)}}function Tq($){let Z=$.parts.filter((J)=>J.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(J.raw));return Z.length>0&&Z.every((J)=>Sq($.raw,J.span.start-$.span.start))}function Sq($,Z){let J=null,Q=!1;for(let X=0;X<Z;X++){let K=$[X];if(Q){Q=!1;continue}if(K==="\\"&&J!=="'"){Q=!0;continue}if(J===K){J=null;continue}if(J===null&&(K==="'"||K==='"'))J=K}return J==='"'}function m0($){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:hq($.allowPaths,Z,J,Q),protectedGitMetadata:$.protectedGitMetadata,pathCanonicalizationContext:Q}}function g1($,Z,J={}){let Q=J.targetIsLiteral??!1;if(!Q&&Z.tmpdirWordSplittingUnsafe&&!J.tmpdirWordSplittingProtected&&kq($))return{kind:"outside_anchored_cwd"};let X=!Q&&Q5($,Z.posixShell);if(v0($))return{kind:"outside_anchored_cwd"};if(n6($,Q))return{kind:"root_or_home_target"};if(yq($,Z))return{kind:"root_or_home_target"};if(Z.resolvedCwd&&h0($,Z.resolvedCwd,Z.protectedGitMetadata,!0,Z.pathCanonicalizationContext,!Z.posixShell))return{kind:"git_metadata_target"};if(wq($,Z.trustTmpdirVar,Z.posixShell,X,Q,J.tmpdirWordSplittingProtected??!1,Z.trustedTmpdirValue,Z.environment))return{kind:"temp_target"};if(X)return{kind:"dynamic_target"};if(gq($,Z,Q))return{kind:"temp_target"};let K=Z.anchoredCwd;if(K){if(!J.skipHomeCwd&&pq(K,Z.environment.home,Z.environment.paths,Z.pathCanonicalizationContext))return{kind:"home_cwd_target"};if(!J.skipCwdSelf&&cq($,Z.resolvedCwd??K,Z.environment.paths,Z.pathCanonicalizationContext))return{kind:"cwd_self_target"};if(dq($,K,Z.resolvedCwd??K,X,Q,Z.environment.paths,Z.pathCanonicalizationContext))return{kind:"within_anchored_cwd"}}return{kind:"outside_anchored_cwd"}}function Z5($,Z,J={}){let{containmentTarget:Q,...X}=J;if(g1($,Z,X).kind!=="temp_target")return!1;let K=$.trim();if(uq(K))return!1;if(s7(K,Z.environment))return!1;return![Z.anchoredCwd,Z.resolvedCwd].some((Y)=>iq(Q??K,Y,Z.environment.paths,Z.pathCanonicalizationContext))}function n6($,Z=!1){let J=$.trim(),Q=$5.normalize(J),X=J.replace(/\\/g,"/"),K=Q==="/"?Q:Q.replace(/\/+$/,"");if(K==="/"||K.startsWith("/")&&K.slice(1).split("/").every((Y)=>/^\*+$/.test(Y)))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 yq($,Z){let J=$.trim(),Q=J.endsWith("/*")?J.slice(0,-2):J;if(!Q)return!1;try{let X=r6(Q)?Q:Z.resolvedCwd?M$(Z.resolvedCwd,Q):null;if(!X)return!1;let K=G1(i(X,Z.environment.paths,Z.pathCanonicalizationContext));if(K===Cq(K).root)return!0;return K===G1(i(Z.environment.home,Z.environment.paths,Z.pathCanonicalizationContext))}catch{return!1}}function G1($){let Z=Pq($);if(Aq){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 wq($,Z,J,Q,X,K,Y,B){let W=$.trim();if(J5(W))return!1;if(!Q&&c6(W,B))return!0;return(Z||K&&Y)&&J&&!X&&vq(W,J)}function vq($,Z){return["$TMPDIR","${TMPDIR}"].some((J)=>{if($===J)return!0;if(!$.startsWith(`${J}/`))return!1;return!Q5($.slice(J.length+1),Z)})}function uq($){let Z=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec($);if(!Z)return!1;return $5.normalize(`/${Z[1]??""}`)==="/"}function J5($){return $.split(/[\\/]+/).includes("..")}function hq($,Z,J,Q){if(!$?.length)return[];return $.flatMap((X)=>{let K=H2(X.trim(),Z);if(!r6(K))return[];try{let Y=i(K,J,Q);if(o4(Y,i(Z,J,Q)))return[];return[G1(Y)]}catch{return[]}})}function gq($,Z,J){if(Z.allowRoots.length===0)return!1;let Q=$.trim();if(J5(Q))return!1;let X=J?Q:H2(Q,Z.environment.home),K=Z.resolvedCwd??Z.anchoredCwd,Y=r6(X)?X:K?M$(K,X):null;if(!Y)return!1;try{let B=G1(i(Y,Z.environment.paths,Z.pathCanonicalizationContext));return Z.allowRoots.some((W)=>B===W||B.startsWith(W.endsWith(s6)?W:`${W}${s6}`))}catch{return!1}}function kq($){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test($)}function Q5($,Z=!1){return $.includes("$")||$.includes("`")||xq($)||Z&&lq($)}function xq($){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 lq($){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==="{"&&mq($,J)||(Q==="+"||Q==="@"||Q==="!")&&$[J+1]==="(")return!0}return!1}function mq($,Z){let J=$.indexOf("}",Z+1);if(J===-1)return!1;let Q=$.slice(Z+1,J);return Q.includes(",")||Q.includes("..")}function pq($,Z,J,Q){try{return G1(i($,J,Q))===G1(i(Z,J,Q))}catch{try{return G1($)===G1(Z)}catch{return!1}}}function cq($,Z,J,Q){if($==="."||$==="./"||$===".\\")return!0;try{return G1(i(M$(Z,$),J,Q))===G1(i(Z,J,Q))}catch{try{return G1(M$(Z,$))===G1(Z)}catch{return!1}}}function dq($,Z,J,Q,X,K,Y){let B=J??Z;if(!X&&($.startsWith("~")||$.startsWith("$HOME")||$.startsWith("${HOME}")))return!1;if(Q)return!1;if($.startsWith("/")||/^[A-Za-z]:[\\/]/.test($))try{return i6($,Z,K,Y)}catch{return!1}if($.startsWith("./")||$.startsWith(".\\")||!$.includes("/")&&!$.includes("\\"))try{return i6(M$(B,$),Z,K,Y)}catch{return!1}if($.startsWith("../"))return!1;try{return i6(M$(B,$),Z,K,Y)}catch{return!1}}function i6($,Z,J,Q){try{return X5(i($,J,Q),i(Z,J,Q))}catch{return!1}}function iq($,Z,J,Q){if(!Z)return!1;try{return X5(i(Z,J,Q),i($,J,Q))}catch{return!0}}function X5($,Z){let J=G1($),Q=G1(Z);return J.startsWith(`${Q}${s6}`)||J===Q}var sq=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),K5="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",rq="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.",Y5="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",B5="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",nq="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",aq="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.";function W5($,Z,J,Q=m0({...J,allowPaths:J.policy?.destructiveCommandAllowPaths})){return oq($.words.map((X)=>({kind:"word",text:X.text,dynamic:X.provenance!=="literal"})),Z,Q,J.policy)}function oq($,Z,J,Q){let X=$.filter((W)=>W.kind==="word"),K=eq(X),Y=X[K];if(!Y||!sq.has(WU(Y.text)))return null;let B=tq(X.slice(K+1));if(B.whatIfProtected)return null;if(a(Q,"powershell.remove-item-pipeline-dynamic-target",J.strict)&&Z&&(B.targets.length===0||B.recursive))return N("powershell.remove-item-pipeline-dynamic-target",aq);for(let W of B.targets)if(!v0(W.text)&&n6(o6(W.text)))return N(B.recursive&&B.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",B5);for(let W of B.targets)if(J.resolvedCwd&&h0(o6(W.text),J.resolvedCwd,J.protectedGitMetadata,B.recursive,J.pathCanonicalizationContext,!0))return N("powershell.remove-item-git-metadata",f1);if(!B.recursive||!B.force)return null;if(a(Q,"powershell.remove-item-recursive-force-dynamic-target",J.strict)&&(B.hasDynamicTarget||B.targets.length===0))return N("powershell.remove-item-recursive-force-dynamic-target",Y5);for(let W of B.targets){let q=qU(g1(o6(W.text),J),J,Q);if(q)return q}return null}function tq($){let Z=[],J=!1,Q=!1,X=!1,K=!1,Y=!1;for(let B=0;B<$.length;B++){let W=$[B];if(!W||W.kind!=="word")continue;if($U(W))continue;if(Y){Z.push(a6(W)),K=K||W.dynamic;continue}if(W.text==="--"){Y=!0;continue}let q=JU(W.text);if(!q){Z.push(a6(W)),K=K||W.dynamic;continue}if(QU(q.name)){let U=q.value?ZU(q.value,W):$[++B];if(U?.kind==="word")Z.push(a6(U)),K=K||U.dynamic;else K=!0;continue}if(XU(q.name)){J=!0;continue}if(KU(q.name)){Q=!0;continue}if(YU(q.name))X=BU(q.value)}return{targets:Z,recursive:J,force:Q,whatIfProtected:X,hasDynamicTarget:K}}function eq($){let Z=$[0];if(Z?.kind==="word"&&Z.text==="&"||Z?.text===".")return $.length>1?1:0;return 0}function a6($){return{text:$.kind==="word"?$.text:"",dynamic:$.kind==="word"&&$.dynamic}}function $U($){return $.kind==="word"&&$.text===","}function o6($){let Z=$.replace(/\\/g,"/"),J=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(Z);return J?`$HOME${Z.slice(J[0].length)}`:Z}function ZU($,Z){return{kind:"word",text:$,dynamic:Z.kind==="word"&&(Z.dynamic||$.includes("$"))}}function JU($){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 QU($){return"path".startsWith($)||"literalpath".startsWith($)}function XU($){return"recurse".startsWith($)}function KU($){return $.length>=2&&"force".startsWith($)}function YU($){return $==="wi"||"whatif".startsWith($)}function BU($){if($===void 0||$==="")return!0;let Z=$.toLowerCase();return Z==="$true"||Z==="true"}function WU($){return $.toLowerCase()}function qU($,Z,J){switch($.kind){case"root_or_home_target":return N("powershell.remove-item-recursive-force-root-or-home",B5);case"git_metadata_target":return N("powershell.remove-item-git-metadata",f1);case"temp_target":return null;case"dynamic_target":if(!a(J,"powershell.remove-item-recursive-force-dynamic-target",Z.strict))return null;return N("powershell.remove-item-recursive-force-dynamic-target",Y5);case"home_cwd_target":return N("powershell.remove-item-recursive-force-home-cwd",nq);case"cwd_self_target":return N("powershell.remove-item-recursive-force-cwd-self",K5);case"within_anchored_cwd":if(!a(J,"powershell.remove-item-recursive-force-paranoid",Z.paranoid))return null;return N("powershell.remove-item-recursive-force-paranoid",rq);case"outside_anchored_cwd":return N("powershell.remove-item-recursive-force-outside-cwd",K5)}}import{normalize as W3}from"node:path";function k1($,Z){let J=Z.policy??{rules:[],transparentWrappers:[]};return t6([...$],Z.environment,Z.cwd,Z.cwd,new Map,new Map(Z.envAssignments??[]),J,{iterations:0},!1)}function*t6($,Z,J,Q,X,K,Y,B,W){let q=E6($,Z,J,K);if(q.unverifiableEnvSplit)throw new l0;for(let[G,_]of q.envAssignments)K.set(G,_),X.set(G,_);let{tokens:U,cwd:H}=q;if(B2(U[0]??""))throw new P1;let j=m4(U,Y);if(j){for(let G of[j.childIndex,...j.alternativeChildIndices])q5(B),yield*t6(G===j.childIndex?j.tokens:[...U.slice(G)],Z,H,Q,new Map(X),new Map(K),Y,B,!0);return}if(GU(U)){q5(B),yield*t6([...U.slice(1)],Z,H,Q,X,K,Y,B,W);return}yield UU(U,H,Q,X,K,W)}function UU($,Z,J,Q,X,K){return{tokens:$,cwd:Z===null?void 0:Z??J,wrapperCwd:Z,wrapperEnvAssignments:Q,envAssignments:X,head:h($[0]??"").toLowerCase(),wrappedByTransparent:K}}function q5($){if($.iterations>=K$)throw new P1;$.iterations++}function GU($){return h($[0]??"").toLowerCase()==="busybox"&&$.length>1}function e6($,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 H0($){let Z=!1,J=!1;for(let Q of $){if(Q==="--")break;if(Q==="-r"||Q==="-R"||$9(Q,"recursive"))Z=!0;else if(Q==="-f"||$9(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 U5($){let Z=$.indexOf("--");return $.slice(1,Z===-1?void 0:Z).some((J)=>$9(J,"recursive")||/^-[A-Za-z]+$/.test(J)&&/[rR]/.test(J.slice(1)))}function $9($,Z){return $.length>2&&$.startsWith("--")&&Z.startsWith($.slice(2))}var HU="find -delete permanently removes files. Use -print first to preview.",jU="find -exec rm -rf is dangerous. Use explicit file list instead.",_U=new Set(["-exec","-execdir","-ok","-okdir"]),OU=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 t4($,Z){let J=$.map(S),Q=LU($,J,Z);if(Q)return Q;if($3(J,1)&&!FU($,J,Z)){let Y=T(N("find.delete",HU),Z.policy);if(Y)return Y}let X=Z.derivedCommandWorkBudget??d4(),K=0;while(K<J.length){let Y=J[K],B=I0(Y??"");if(B>0){K+=B+1;continue}if(!j0(Y)){K++;continue}n1(X,J.length-K-1);let W=_2(J,K);K=W.nextIndex;let q=VU(W.tokens,Z.environment);if(q){let G=T(q,Z.policy);if(G)return G}let U=Y==="-execdir"||Y==="-okdir",H=Z.analyzeTokens?Z.analyzeTokens(W.tokens,U?null:Z.cwd):Z.analyzeNested?Z.analyzeNested(W.tokens.join(" "),{effectiveCwd:U?void 0:Z.cwd,envAssignments:Z.envAssignments}):null,j=H?.id.startsWith("custom.")?H:T(H,Z.policy);if(j)return j}return null}function LU($,Z,J){if(!$3(Z,1)&&!Z9(Z,J.environment))return null;let X=e4($)??g(["."]),K=m0({...J,allowPaths:J.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let Y of X){let B=j2(Y);for(let W of B.expandedTargets??[S(Y)]){let q=g1(W,K,{targetIsLiteral:B.expandedTargets!==void 0||B.targetIsLiteral,tmpdirWordSplittingProtected:B.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",f1)}}if(MU(Z)&&K.resolvedCwd&&j7(X.map(S),K.resolvedCwd,K.protectedGitMetadata,K.pathCanonicalizationContext))return N("find.delete-git-metadata",f1);return null}function Z9($,Z){let J=0;while(J<$.length){if(!j0($[J])){J++;continue}let Q=_2($,J),X=I1([...Q.tokens],Z),K=h(X[0]??"").toLowerCase();if((K==="rm"||K==="rmdir")&&X.some((Y)=>Y.includes("{}")))return!0;J=Q.nextIndex}return!1}function MU($){return $.some((Z,J)=>{if(!["-name","-iname"].includes(Z))return!1;return $[J+1]?.toLowerCase()==="hooks"})}function FU($,Z,J){if(Z.includes("-L")||Z.includes("-f")||Z.includes("-follow"))return!1;let Q=e4($);if(!Q)return!1;let X=J.envAssignments??new Map,K=p6(X,J.environment),Y=J.trustedTmpdirValue??G0(X,J.environment),B=J.allowTmpdirVar??!G2(X,J.environment),W=m0({environment:J.environment,protectedGitMetadata:J.protectedGitMetadata,cwd:J.cwd,originalCwd:J.originalCwd,strict:J.strict,allowTmpdirVar:B&&Y&&Boolean(K),allowPaths:J.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:J.tmpdirWordSplittingUnsafe??a1(X,J.environment),trustedTmpdirValue:Y});return Q.every((q)=>{let U=j2(q);if(U.unsafeBraceExpansion)return!1;return(U.expandedTargets??[S(q)]).every((H)=>Z5(H,W,{containmentTarget:NU(H,K),targetIsLiteral:U.expandedTargets!==void 0||U.targetIsLiteral,tmpdirWordSplittingProtected:U.tmpdirWordSplittingProtected}))})}function NU($,Z){if(!Z)return $;return $.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>Z)}function e4($){let Z=(X)=>{let K=$[X];return K?S(K):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),K=$[J];if(!X||!K||X.startsWith("-")||["!","(",")"].includes(X))break;Q.push(K),J++}return Q.length>0?Q:null}function VU($,Z){let J=I1([...$],Z);if(J.length===0)return null;let Q=h(J[0]??"");if(Q==="busybox"&&J.length>1)J=J.slice(1),Q=h(J[0]??"");if(Q==="rm"&&H0(J))return N("find.exec-rm-recursive-force",jU);return null}function _2($,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 $3($,Z){let J=Z;while(J<$.length){let Q=$[J];if(!Q){J++;continue}if(j0(Q)){J=_2($,J).nextIndex;continue}let X=I0(Q);if(X>0){J+=X+1;continue}if(Q==="-delete")return!0;J++}return!1}function I0($){return OU.get($)??(/^-newer[A-Za-z]{2}$/.test($)?1:0)}function j0($){return $!==void 0&&_U.has($)}function*J9($){for(let Z of $.nodes)yield*DU(Z)}function RU($){return Object.freeze([...J9($)])}function NV($){return Object.freeze(RU($).map((Z)=>Object.freeze(Z.words.map((J)=>J.text))))}function O2($){let Z=w1($,"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*DU($){if($.kind==="command"){yield $;for(let Z of $.nested)yield*J9(Z);return}if($.kind==="group")yield*J9($.body)}var zU=5,Q9="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 H1($){let Z=$.indexOf("--");if(Z===-1)return{index:-1,before:$,after:[]};return{index:Z,before:$.slice(0,Z),after:$.slice(Z+1)}}function H5($,Z,J){let Q=_5($,Z,J),X=bU(Q.entries);if(X.size===0)return{blockedReason:Q.blockedReason,expanded:!1,tokens:$};let K=$,Y=!1;for(let B=0;B<zU;B++){let{subcommand:W,rest:q}=x1(K),U=W?.toLowerCase();if(!U||!X.has(U))return{blockedReason:Q.blockedReason,expanded:Y,tokens:K};let H=X.get(U),j=AU(H);if(j===null||j.length===0)return{blockedReason:Q9,expanded:!0,tokens:K};K=["git",...j,...q],Y=!0}return{blockedReason:Q9,expanded:!0,tokens:K}}function j5($,Z,J){return _5($,Z,J).entries.some((Q)=>Q.key.toLowerCase()==="core.sshcommand")}function x1($){if($.length===0)return{subcommand:null,rest:[]};let Z=$[0];if((Z?h(Z).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let Q=1;while(Q<$.length){let X=$[Q];if(!X)break;if(X==="--"){let K=$[Q+1];if(K&&!K.startsWith("-"))return{subcommand:K,rest:$.slice(Q+2)};return{subcommand:null,rest:$.slice(Q+1)}}if(X.startsWith("-"))if(i1.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 bU($){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 _5($,Z,J){if($.length===0)return{blockedReason:null,entries:[]};let Q=$[0];if((Q?h(Q).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let K=fU(Z,J);return{blockedReason:K.blockedReason,entries:[...K.entries,...IU($,Z,J)]}}function IU($,Z,J){let Q=[],X=1;while(X<$.length){let K=$[X];if(!K||K==="--"||!K.startsWith("-"))return Q;if(K==="-c"){let Y=X9($[X+1]);if(Y)Q.push(Y);X+=2;continue}if(K.startsWith("-c")&&K.length>2){let Y=X9(K.slice(2));if(Y)Q.push(Y);X++;continue}if(K==="--config-env"){let Y=G5($[X+1],Z,J);if(Y)Q.push(Y);X+=2;continue}if(K.startsWith("--config-env=")){let Y=G5(K.slice(13),Z,J);if(Y)Q.push(Y);X++;continue}if(i1.has(K)){X+=2;continue}X++}return Q}function fU($,Z){let J=PU($,Z),Q=CU($,Z);return{blockedReason:J===null||Q===null?Q9:null,entries:[...J??[],...Q??[]]}}function PU($,Z){let J=b1("GIT_CONFIG_PARAMETERS",$,Z);if(J===void 0)return[];let Q=[],X=O2(J);if(!X)return null;for(let K of X){let Y=X9(K);if(!Y)return null;Q.push(Y)}return Q}function CU($,Z){let J=V4($,Z);if(J.state==="absent")return[];if(J.state==="invalid")return null;let Q=[];for(let X=0;X<J.count;X++){let K=b1(`GIT_CONFIG_KEY_${X}`,$,Z)?.trim(),Y=b1(`GIT_CONFIG_VALUE_${X}`,$,Z);if(!K||Y===void 0)return null;Q.push({key:K,value:Y})}return Q}function X9($){if(!$)return null;let Z=$.indexOf("=");return{key:(Z===-1?$:$.slice(0,Z)).trim(),value:Z===-1?void 0:$.slice(Z+1)}}function G5($,Z,J){let Q=$?.indexOf("=")??-1;if(!$||Q===-1)return null;return{key:$.slice(0,Q).trim(),value:b1($.slice(Q+1),Z,J)}}function AU($){let Z=$?.trimStart();if(!Z||Z.startsWith("!"))return null;return O2(Z)}var EU="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",TU="git checkout --force discards uncommitted changes. Use 'git stash' first.",SU="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",yU="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",wU="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",vU="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",uU="git switch --force discards uncommitted changes. Use 'git stash' first.",hU="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",gU="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",kU="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",xU="git reset --merge can lose uncommitted changes. Use 'git stash' first.",lU="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",mU="git push --force destroys remote history. Use --force-with-lease for safer force push.",pU="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",cU="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",dU="git branch -D force-deletes without merge check. Use -d for safe delete.",iU="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",sU="git merge --abort discards merge conflict resolutions. Use 'git status' first.",rU="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",nU="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",aU="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",oU="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",tU="git worktree remove --force can delete uncommitted changes. Remove --force flag.",O5=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),L5=new Set(["--recurse-submodules","--track","-t"]),K9=new Set(["-b","-B","-U"]),Y9=new Set(["-c","-C"]),eU=new Set(["--source","--conflict","--unified","--inter-hunk-context"]),$G=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 m($,Z){let J=$.split("=",1)[0]??$;return J.length>=4&&Z.startsWith(J)&&J.startsWith("--")&&J.slice(2).length>=2}function F5($){let{subcommand:Z,rest:J}=x1($);if(!Z)return null;switch(Z.toLowerCase()){case"checkout":return p0(ZG(J));case"switch":return p0(JG(J));case"restore":return p0(XG(J));case"reset":return YG(J);case"clean":return p0(WG(J));case"push":return c0(qG(J));case"branch":return c0(HG(J));case"stash":return c0(MG(J));case"worktree":return c0(FG(J));case"rebase":return p0(jG(J));case"merge":return p0(_G(J));case"tag":return c0(OG(J));case"reflog":return c0(LG(J));default:return null}}function p0($){return $?{...$,localDiscard:!0}:null}function c0($){return $?{...$,localDiscard:!1}:null}function ZG($){let{index:Z,before:J}=H1($),Q=O1(J,{shortOptsWithValue:K9});if(J.some((K)=>m(K,"--force"))||Q.has("-f"))return N("git.checkout-force",TU);for(let K of $){if(K==="-b"||K==="-B"||K==="--orphan")return null;if(m(K,"--pathspec-from-file"))return N("git.checkout-pathspec-from-file",yU)}if(Z!==-1){if(J.some((Y)=>!Y.startsWith("-")))return N("git.checkout-ref-path",SU);return N("git.checkout-double-dash",EU)}if(QG($).length>=2)return N("git.checkout-ambiguous",wU);return null}function JG($){let{before:Z}=H1($);if(Z.some((Q)=>m(Q,"--discard-changes")))return N("git.switch-discard-changes",vU);let J=O1(Z,{shortOptsWithValue:Y9});if(Z.some((Q)=>m(Q,"--force"))||J.has("-f"))return N("git.switch-force",uU);return null}function QG($){let Z=[],J=0;while(J<$.length){let Q=$[J];if(!Q)break;if(Q==="--")break;if(Q.startsWith("-"))if(O5.has(Q))J+=2;else if(Q.startsWith("--")&&Q.includes("="))J++;else if(L5.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("--")&&!$G.has(Q)&&!O5.has(Q)&&!L5.has(Q))J++;else J++;else Z.push(Q),J++}return Z}function XG($){let Z=KG($);if(Z.isTerminal||!Z.hasPathspec&&!Z.hasPatch||!Z.hasWorktree)return null;return Z.hasExplicitLocation?N("git.restore-worktree",gU):N("git.restore-unstaged",hU)}function KG($){let Z=!1,J=!1,Q=!0,X=!1,K=(Y)=>{if(!X)Q=!1,X=!0;if(Y!==void 0)Q=Y};for(let Y=0;Y<$.length;Y++){let B=$[Y];if(B===void 0)break;if(B==="--"){Z||=Y+1<$.length;break}if(B==="--pathspec-from-file"){Z=!0,Y++;continue}if(B.startsWith("--pathspec-from-file=")){Z=!0;continue}if(B==="-h"||B==="--help"||B==="--version")return{hasPathspec:Z,hasPatch:J,hasWorktree:Q,hasExplicitLocation:X,isTerminal:!0};if(B==="--staged"){K();continue}if(B==="--no-staged"){K();continue}if(B==="--worktree"){K(!0);continue}if(B==="--no-worktree"){K(!1);continue}if(B==="--patch"){J=!0;continue}if(B==="--no-patch"){J=!1;continue}if(eU.has(B)){Y++;continue}if(B.startsWith("--"))continue;if(B==="-"){Z=!0;continue}if(!B.startsWith("-")){Z=!0;continue}for(let W=1;W<B.length;W++){let q=B.charAt(W);if(q==="h")return{hasPathspec:Z,hasPatch:J,hasWorktree:Q,hasExplicitLocation:X,isTerminal:!0};if(q==="S"){K();continue}if(q==="W"){K(!0);continue}if(q==="p"){J=!0;continue}if(q==="s"||q==="U"){if(W===B.length-1)Y++;break}}}return{hasPathspec:Z,hasPatch:J,hasWorktree:Q,hasExplicitLocation:X,isTerminal:!1}}function YG($){let Z=null;for(let J of $){if(m(J,"--hard")){Z=N("git.reset-hard",kU);break}if(m(J,"--merge")){Z=N("git.reset-merge",xU);break}}if(!Z)return null;return BG($)?c0(Z):p0(Z)}function BG($){for(let Z of $){if(Z==="--")return!1;if(!Z.startsWith("-"))return!0}return!1}function WG($){for(let J of $)if(J==="-n"||m(J,"--dry-run"))return null;let Z=O1($.filter((J)=>J!=="--"));if($.some((J)=>m(J,"--force"))||Z.has("-f"))return N("git.clean-force",lU);return null}function qG($){let{before:Z,after:J}=H1($),Q=O1(Z);if(Z.some((Y)=>m(Y,"--mirror")))return N("git.push-mirror",cU);if(Z.some((Y)=>m(Y,"--force"))||Q.has("-f")||M5(Z,J).some(UG))return N("git.push-force",mU);if(Z.some((Y)=>m(Y,"--delete"))||Q.has("-d")||M5(Z,J).some(GG))return N("git.push-delete",pU);return null}function M5($,Z){return[...$.filter((J)=>J!==""&&!J.startsWith("-")),...Z]}function UG($){return $.startsWith("+")||$.includes(":+")}function GG($){return $.length>1&&$.startsWith(":")}function HG($){let{before:Z}=H1($),J=O1(Z),Q=J.has("-D")||J.has("-d")||Z.some((K)=>m(K,"--delete")),X=J.has("-D")||J.has("-f")||Z.some((K)=>m(K,"--force"));if(Q&&X)return N("git.branch-force-delete",dU);return null}function jG($){let{before:Z}=H1($);return Z.some((J)=>m(J,"--abort"))?N("git.rebase-abort",iU):null}function _G($){let{before:Z}=H1($);return Z.some((J)=>m(J,"--abort"))?N("git.merge-abort",sU):null}function OG($){let{before:Z}=H1($);return O1(Z).has("-d")||Z.some((Q)=>m(Q,"--delete"))?N("git.tag-delete",rU):null}function LG($){return $[0]==="delete"?N("git.reflog-delete",nU):null}function MG($){for(let Z of $){if(Z==="drop")return N("git.stash-drop",aU);if(Z==="clear")return N("git.stash-clear",oU)}return null}function FG($){let{before:Z}=H1($);if(!Z.includes("remove"))return null;let Q=O1(Z);if(Z.some((X)=>m(X,"--force"))||Q.has("-f"))return N("git.worktree-remove-force",tU);return null}import{execFileSync as NG}from"node:child_process";import{existsSync as W9,readFileSync as q9}from"node:fs";import{dirname as VG,isAbsolute as R5,join as B9,resolve as D5}from"node:path";var RG=["/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 z5($,Z,J,Q){let X=DG($,Z,J);if(X!==null)return X;let K=zG(Z,J);if(K!==null)return K;if(d8(J))return!0;return bG(Q)}function DG($,Z,J){let Q=null,X=1;while(X<$.length){let K=$[X];if(!K||K==="--")return Q;if(!K.startsWith("-"))return Q;if(K==="-c"){let Y=N5($[X+1]);if(Y!==null)Q=Y;X+=2;continue}if(K.startsWith("-c")&&K.length>2){let Y=N5(K.slice(2));if(Y!==null)Q=Y;X++;continue}if(K==="--config-env"){let Y=V5($[X+1],Z,J);if(Y!==null)Q=Y;X+=2;continue}if(K.startsWith("--config-env=")){let Y=V5(K.slice(13),Z,J);if(Y!==null)Q=Y;X++;continue}if(i1.has(K))X+=2;else X++}return Q}function zG($,Z){if(b1("GIT_CONFIG_PARAMETERS",$,Z)!==void 0)return!0;let J=V4($,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 K=b1(`GIT_CONFIG_KEY_${X}`,$,Z),Y=b1(`GIT_CONFIG_VALUE_${X}`,$,Z);if(!K?.trim()||Y===void 0)return!0;let B=K.trim().toLowerCase();if(U9(B))return!0;if(B!=="submodule.recurse")continue;Q=L2(Y)}return Q}function bG($,Z=fG()){let J=IG($);if(J===null||J)return!0;if(Z===null)return!0;try{let Q=NG(Z,["config","--get","submodule.recurse"],{cwd:$,encoding:"utf8",env:PG(process.env),stdio:["ignore","pipe","ignore"]}).trim();return L2(Q)}catch(Q){return!CG(Q)}}function IG($){let Z=AG($);if(Z===null)return null;for(let J of Z){if(!W9(J))continue;if(SG(J))return!0}return!1}function fG(){for(let $ of RG)if(W9($))return $;return null}function PG($){let Z={...$};for(let J of Object.keys(Z))if(a$(J))delete Z[J];return Z}function CG($){return typeof $==="object"&&$!==null&&"status"in $&&$.status===1}function AG($){let Z=e$($);if(Z===null)return null;let J=EG(Z);if(J===null)return null;let Q=TG(J);if(Q===null)return null;return[B9(Q,"config"),B9(J,"config.worktree")]}function EG($){try{let J=q9($,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!J.startsWith("gitdir:"))return $;let Q=J.slice(7).trim();if(Q==="")return null;return R5(Q)?Q:D5(VG($),Q)}catch{return null}}function TG($){let Z=B9($,"commondir");if(!W9(Z))return $;try{let J=q9(Z,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(J==="")return null;return R5(J)?J:D5($,J)}catch{return null}}function SG($){let Z;try{Z=q9($,"utf-8")}catch{return!0}let J="",Q=!1;for(let X of Z.split(/\r?\n/)){let K=X.trim();if(K===""||K.startsWith("#")||K.startsWith(";"))continue;let Y=K.match(/^\[([^\]]+)\]$/);if(Y){J=Y[1]?.trim().toLowerCase()??"";continue}let B=K.indexOf("="),W=(B===-1?K:K.slice(0,B)).trim().toLowerCase(),q=B===-1?"true":K.slice(B+1).trim();if(yG(J)&&W==="path")return!0;if(J==="submodule"&&W==="recurse")Q=L2(q)}return Q}function yG($){return $==="include"||$.startsWith("includeif ")}function N5($){if(!$)return null;let Z=$.indexOf("="),J=(Z===-1?$:$.slice(0,Z)).toLowerCase();if(U9(J))return!0;if(J!=="submodule.recurse")return null;let Q=Z===-1?"true":$.slice(Z+1).toLowerCase();return L2(Q)}function L2($){let Z=$.toLowerCase();return Z!=="false"&&Z!=="no"&&Z!=="off"&&Z!=="0"}function V5($,Z,J){let Q=$?.indexOf("=")??-1;if(!$||Q===-1)return null;let X=$.slice(0,Q).toLowerCase();if(U9(X))return!0;if(X!=="submodule.recurse")return null;let K=b1($.slice(Q+1),Z,J);return K===void 0||L2(K)}function U9($){return $==="include.path"||$.startsWith("includeif.")&&$.endsWith(".path")}function b5($,Z,J){if(!Z.localDiscard||!J.worktreeMode||n8(J.env,J.envAssignments))return null;let Q=a8($,J.cwd);if(!Q.gitCwd||Q.hasExplicitGitContext)return null;if(!o8(Q.gitCwd))return null;if(wG($,J,Q.gitCwd))return null;return{originalReason:Z.reason,gitCwd:Q.gitCwd}}function wG($,Z,J){let{subcommand:Q,rest:X}=x1($),K=Q?.toLowerCase();if(Z.dynamicArguments||vG(X)||z5($,Z.env,Z.envAssignments,J)||gG(X)||uG(K,X))return!0;return K==="clean"&&kG(X)>1}function vG($){return $.some((Z)=>/[$*?[]/.test(Z))}function uG($,Z){if($==="checkout"){let{before:J}=H1(Z),Q=O1(J,{shortOptsWithValue:K9}),X=J.some((Y)=>m(Y,"--force"))||Q.has("-f"),K=Q.has("-B")||J.some((Y)=>Y==="-B"||Y.startsWith("-B"));return X&&K}if($==="switch"){let{before:J}=H1(Z),Q=O1(J,{shortOptsWithValue:Y9}),X=J.some((Y)=>m(Y,"--force"))||J.some((Y)=>m(Y,"--discard-changes"))||Q.has("-f"),K=J.some((Y)=>Y==="-C"||Y.startsWith("-C")||hG(Y))||Q.has("-C");return X&&K}return!1}function hG($){let Z=$.split("=",1)[0]??$;return Z==="--force-create"||Z.length>=9&&"--force-create".startsWith(Z)}function gG($){return $.some((Z)=>Z.startsWith("--recurse-sub"))}function kG($){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 xG="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.",lG=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function F$($,Z){return I5($.map(S),Z)}function I5($,Z,J){let Q=H5($,Z.env,Z.envAssignments),X=Z.policy?.destructiveCommandRuleOverrides["git.alias-config"]==="off";if(Q.blockedReason&&!X)return N("git.alias-config",Q.blockedReason);let K=Q.tokens;if((c8(Z.envAssignments)||j5($,Z.env,Z.envAssignments))&&mG(K))return N("git.ssh-env",xG);let Y=F5(K);if(!Y)return null;if(Q.expanded||Q.blockedReason)return Y;let B=b5($,Y,Z);if(!B)return Y;return J?.(B),null}function f5($,Z){let J=null;return{match:I5($.map(S),Z,(X)=>{J=X}),relaxation:J}}function mG($){let{subcommand:Z,rest:J}=x1($),Q=Z?.toLowerCase();if(!Q)return!1;if(lG.has(Q))return!0;if(Q==="archive")return H1(J).before.some((X)=>m(X,"--remote"));return Q==="remote"&&pG(J)}function pG($){return $.find((Z)=>!cG(Z))?.toLowerCase()==="update"}function cG($){return $==="-v"||m($,"--verbose")||m($,"--no-verbose")}import{isAbsolute as wH}from"node:path";var P5="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",dG="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.",iG="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",A5="rm -rf targeting root or home directory is extremely dangerous and always blocked.",sG="rm -rf in home directory is dangerous. Change to a project directory first.";function N$($,Z){let J=m0({...Z,allowPaths:Z.policy?.destructiveCommandAllowPaths,posixShell:!0}),Q=$.map(S),X=H0(Q),K=U5(Q),Y=nG($);for(let B of Y){let W=j2(B.word);if(X&&W.unsafeBraceExpansion){let q=T(C5({kind:"outside_anchored_cwd"},J,Z.policy),Z.policy);if(q)return q;continue}for(let q of W.expandedTargets??[B.text]){let U={targetIsLiteral:W.expandedTargets!==void 0||W.targetIsLiteral,tmpdirWordSplittingProtected:W.tmpdirWordSplittingProtected};if(!K&&J.resolvedCwd&&h0(q,J.resolvedCwd,J.protectedGitMetadata,K,J.pathCanonicalizationContext))return N("rm.git-metadata",f1);if(K&&!X){let H=g1(q,J,U);if(H.kind==="root_or_home_target")return N("rm.recursive-force-root-or-home",A5);if(H.kind==="git_metadata_target")return N("rm.git-metadata",f1);continue}if(!X)continue;for(let H of rG(q,J,U)){let j=C5(H,J,Z.policy),G=T(j,Z.policy);if(G)return G}}}return null}function rG($,Z,J){let Q=g1($,Z,J);if(Q.kind==="cwd_self_target")return[Q,g1($,Z,{...J,skipCwdSelf:!0})];if(Q.kind!=="home_cwd_target")return[Q];let X=g1($,Z,{...J,skipHomeCwd:!0});if(X.kind!=="cwd_self_target")return[Q,X];return[Q,X,g1($,Z,{...J,skipHomeCwd:!0,skipCwdSelf:!0})]}function nG($){let Z=[],J=!1;for(let Q of $.slice(1)){let X=S(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 C5($,Z,J){switch($.kind){case"root_or_home_target":return N("rm.recursive-force-root-or-home",A5);case"git_metadata_target":return N("rm.git-metadata",f1);case"temp_target":return null;case"dynamic_target":if(!a(J,"rm.recursive-force-dynamic-target",Z.strict))return null;return N("rm.recursive-force-dynamic-target",iG);case"home_cwd_target":return N("rm.recursive-force-home-cwd",sG);case"cwd_self_target":return N("rm.recursive-force-cwd-self",P5);case"within_anchored_cwd":if(a(J,"rm.recursive-force-paranoid",Z.paranoid))return N("rm.recursive-force-paranoid",dG);return null;case"outside_anchored_cwd":return N("rm.recursive-force-outside-cwd",P5)}}var aG={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},T5=new Set(["--init-file","--rcfile"]),oG=["--init-file","--rcfile"],tG=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function o1($){for(let Z=1;Z<$.length;Z++){let J=$[Z];if(!J)continue;if(J==="-c")return E5($,Z,!0);if(J.startsWith("-")&&J.includes("c")&&!J.startsWith("--")){let Q=E5($,Z,!1);if(Q!==null)return Q}}return null}function C1($){let Z=h($[0]??"").toLowerCase();if(Z==="zsh"||Z==="ksh")return t1($).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 E5($,Z,J){if($[Z+1]==="--")return $[Z+2]||null;let Q=$[Z+1];if(!Q||!J&&Q.startsWith("-"))return null;return Q}function S5($){let Z=h($[0]??"").toLowerCase(),J=eG($,Z),Q=tG.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 eG($,Z){let J=t1($),Q=J.commandIndex??J.scriptIndex??$.length,X=[],K=!1,Y=!0;for(let B=1;B<Q;B++){let W=$[B];if(W===void 0||W==="--"||W==="-"||W[0]!=="-"&&W[0]!=="+")break;if(W.startsWith("--")){if(Z==="bash"&&Y?oG.find((j)=>W===j):void 0){let j=$[B+1];X.push(j===void 0?{kind:"absent"}:{kind:"literal",value:j}),B++;continue}let H=W.split("=",1)[0]??W;if(Z==="bash"&&T5.has(H)&&!W.includes("="))B++;continue}if(Z==="bash")Y=!1;let q=y5(Z,W,$[B+1],"startup");if(q.interactive)K=W[0]==="-";B+=q.followingValues}return{argvSource:X.at(-1)??null,interactive:K}}function y5($,Z,J,Q){let X=!1,K=0,Y=!1,B=!1,W=!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 H=Z.slice(q+1);if(Z[0]==="-"&&(H==="c"||H[0]==="-"&&H.endsWith("c")))Y=!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")Y=!0;if(Q==="argv"&&U==="n")W=Z[0]==="-";if(Q==="argv"&&U==="s")B=Z[0]==="-";if(!aG[$]?.includes(U))continue;if(q+1===Z.length)K++;break}return{interactive:X,followingValues:K,commandSelected:Y,stdinMode:B,syntaxCheck:W}}function t1($){let Z=h($[0]??"").toLowerCase(),J=!1,Q=!1,X=!1;for(let K=1;K<$.length;K++){let Y=$[K];if(Y===void 0)break;if(Y==="--"){let W=J&&$[K+1]!==void 0?K+1:null;return{command:W===null?null:$[W]??null,commandIndex:W,scriptIndex:!J&&!Q&&$[K+1]!==void 0?K+1:null,readsStdinAsCommands:!J&&(Q||$[K+1]===void 0),syntaxCheck:X}}if(Y==="-"||Y[0]!=="-"&&Y[0]!=="+")return{command:J?Y:null,commandIndex:J?K:null,scriptIndex:!J&&!Q&&Y!=="-"?K:null,readsStdinAsCommands:!J&&(Q||Y==="-"),syntaxCheck:X};if(Y.startsWith("--")){let W=Y.split("=",1)[0]??Y;if(Z==="bash"&&T5.has(W)&&!Y.includes("="))K++;continue}let B=y5(Z,Y,$[K+1],"argv");if(B.commandSelected)J=!0;if(B.syntaxCheck)X=!0;if(B.stdinMode)Q=!0;K+=B.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!J,syntaxCheck:X}}var f0={kind:"none"},d0={kind:"dynamic"},$H=new Set(["<","<<","<<-","<<<","<&","<>"]),v5=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,ZH=/^(?:[0-9]+|[@*])$/,JH=w0.maxWords,QH=w0.maxInputLength;function u5($){if(!$||h(x($.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
|
|
53
|
-
`)return`${Q.join(`
|
|
54
|
-
`)}
|
|
55
|
-
`;if(J.includes("%")||/\\(?![\\nrt])/.test(J))return;return J.replaceAll("\\n",`
|
|
56
|
-
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function V$($){let Z=M2($[1])==="--"?2:1;if($.length<=Z)return f0;let J=$.slice(Z);if(!J.every(J3))return d0;return{kind:"literal",source:J.map(S).join(" ")}}function h5($){let Z=M2($[1])==="--"?2:1,J=$[Z],Q=M2(J);if(J===void 0||$.length<=Z+1||Q==="-"||Q===""||Q==="-l"||Q==="-p")return f0;if(!J3(J))return d0;return{kind:"literal",source:Q}}function Z3($,Z){let J=XH($);if(J===-1)return f0;let Q=KH(Z);if(!Q)return f0;let X=[],K=Q.command?.length??0;for(let Y of Q.references){let B=BH(Y,$,J,Q.ifs);if(!B)return d0;if(K+=B.reduce((W,q)=>W+q.length+3,0),X.length+B.length>JH||K>QH)return d0;X.push(...B)}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(qH)].filter((Y)=>Y!==null).join(" ")}}function g5($,Z,J,Q){if(!t1($.map(S)).readsStdinAsCommands)return f0;let X=Z.filter((K)=>(K.fd===void 0||K.fd===0)&&$H.has(K.operator)).at(-1);if(X){if(X.operator==="<<"||X.operator==="<<-")return f0;if(X.operator!=="<<<"||X.target?.provenance!=="literal")return d0;return{kind:"literal",source:X.target.text}}if(!J)return f0;return Q===void 0?d0:{kind:"literal",source:Q}}function e1($){let Z=t1($.map(S)).scriptIndex;if(Z===null)return f0;let J=$[Z],Q=M2(J);return I4(J,Q)?{kind:"literal",source:Q}:d0}function XH($){return t1($.map(S)).commandIndex??-1}function KH($){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(YH);if(X.length===0||X.some((K)=>K===null))return null;return{command:Q?.[1]??null,optionTerminator:Q?.[2]!==void 0,references:X.filter((K)=>!!K),ifs:Z?Z[1]??Z[2]??Z[3]??"":`
|
|
57
|
-
`}}function YH($){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 BH($,Z,J,Q){let X=Z.slice(J+2);if($.parameter==="@")return $.quoted?G9(X):WH(X,Q);if($.parameter==="*"){let B=G9(X);if(!B)return;let W=B.join(Q[0]??"");return $.quoted?[W]:H9(W,Q)}let K=Z[J+1+$.parameter];if(K&&!J3(K))return;let Y=M2(K);return $.quoted?[Y]:H9(Y,Q)}function G9($){return $.every(J3)?$.map(S):void 0}function WH($,Z){let J=G9($);if(!J)return;let Q=J.map((X)=>H9(X,Z));return Q.some((X)=>X===void 0)?void 0:Q.flatMap((X)=>X??[])}function H9($,Z){if(["*","?","[","]"].some((J)=>$.includes(J)))return;if(Z==="")return $===""?[]:[$];if(Z===`
|
|
58
|
-
`)return $.trim().split(/\s+/).filter(Boolean);if(Z.length!==1)return;return Z===" "||Z==="\t"||Z===`
|
|
59
|
-
`?$.trim().split(/\s+/).filter(Boolean):$.split(Z).filter(Boolean)}function J3($){if(!$)return!0;return $.provenance==="unknown"?!/[$`]/.test(S($)):$.provenance==="literal"}function M2($){return $?S($):""}function qH($){return`'${$.replaceAll("'",`'"'"'`)}'`}function _9($,Z){return j9(w1($,"posix"),Z)}function R$($){return _9($,new Set(Array.from($.matchAll(v5)).flatMap((Z)=>{let J=Z[1]??Z[2];return J===void 0?[]:[J]})))}function j9($,Z){if($.status==="invalid"||$.status==="limited")return!1;let J=new Set(Z);for(let Q of $.nodes){if(Q.kind==="group"){if(j9(Q.body,J))return!0;continue}if(Q.kind!=="command")continue;if(Q.nested.some((X)=>j9(X,J))||k5(Q.words,J))return!0;_H(Q,J)}return!1}function k5($,Z){let J=$.findIndex((Y)=>s1(Y.text)===null);if(J===-1)return!1;let Q=$[J];if(!Q)return!1;if(F2(Q,Z))return!0;let X=x(Q.text);if(X==="source"||X==="."){let Y=$[J+1]?.text==="--"?J+2:J+1;return w5($[Y],Z)}if($1.has(X)){let Y=$.slice(J),B=t1(Y.map((q)=>q.text)),W=B.commandIndex??B.scriptIndex;return!B.syntaxCheck&&W!==null&&w5(Y[W],Z)}let K=UH($,J,Z);if(K===null)return!1;if(K===-1)return!0;return k5($.slice(K),Z)}function UH($,Z,J){let Q=x($[Z]?.text??"");if(Q==="command")return GH($,Z+1);if(Q==="exec")return HH($,Z+1);if(Q==="env")return jH($,Z+1,J);return null}function GH($,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 HH($,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 jH($,Z,J){for(let Q=Z;Q<$.length;Q++){let X=$[Q],K=X?.text??"";if(K==="--")return $[Q+1]?Q+1:null;if(K==="-S"||K==="--split-string")return F2($[Q+1],J)?-1:Q+2;if(K.startsWith("-S")||K.startsWith("--split-string="))return F2(X,J)?-1:Q+1;if(K==="-u"||K==="--unset"||K==="-C"||K==="--chdir"||K==="-P"){Q++;continue}if(K==="-i"||K==="-0"||K==="--null"||K.startsWith("-u=")||K.startsWith("--unset=")||K.startsWith("-C")||K.startsWith("--chdir=")||K.startsWith("-P"))continue;if(K.startsWith("-"))continue;if(s1(K))continue;return Q}return null}function _H($,Z){if(!$.words.every((J)=>s1(J.text)!==null))return;for(let J of $.words){let Q=s1(J.text);if(!Q)continue;if(F2(J,Z))Z.add(Q.name)}}function F2($,Z){if(!$)return!1;return $.parts.filter((J)=>J.provenance==="variable").some((J)=>Array.from(J.raw.matchAll(v5)).some((Q)=>{let X=Q[1]??Q[2];return X!==void 0&&(ZH.test(X)||Z.has(X))}))}function w5($,Z){return!!$&&($.parts.some((J)=>J.provenance!=="literal"&&J.provenance!=="variable")||F2($,Z))}var OH=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--config-env"]),LH=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),MH=new Set;function x5($){if($==="git")return OH;if($==="docker")return LH;return MH}function Q1($,Z){if($.length===0||Z.length===0)return null;let J=x($[0]??""),Q=O1($);for(let X of Z){if(!FH(J,X.command))continue;if(!NH(J,$,X.subcommand))continue;if(RH($,new Set(X.block_args),Q))return{id:`custom.${X.name}`,reason:`[${X.name}] ${X.reason}`,intent:X.intent??"manual_only"}}return null}function FH($,Z){return $===x(Z)}function NH($,Z,J){if(!J)return!0;return l5(Z,1,J,x5($))}function l5($,Z,J,Q){let X=!1;for(let K=Z;K<$.length;K++){let Y=$[K];if(!Y)continue;if(X){X=!1;continue}if(Y==="--"){let B=$[K+1];if(B&&!B.startsWith("-"))return B===J;return!1}if(Q.has(Y)){X=!0;continue}if(Y.startsWith("-")){if(!Y.includes("=")&&VH($,K,J,Q))return!0;continue}return Y===J}return!1}function VH($,Z,J,Q){let X=$[Z+1];if(!X||X.startsWith("-"))return!1;return l5($,Z+2,J,Q)}function RH($,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 P0($,Z,J={}){if($.length===0)return null;let Q=$[0];if(!Q)return null;let X=x(Q);if(X==="eval"){let K=V$(g($));if(K.kind==="dynamic")return D$(J,Z);if(K.kind==="literal"&&Z.analyzeNested){let Y=Z.analyzeNested(K.source,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments});if(Y)return Y}return $0(J,Z)}if($1.has(X)){if(C1($))return null;let K=o1($);if(K){if(J.dynamicSourceInput??J.dynamicInput){let W=D$(J,Z);if(W)return W}if(R$(K)){let W=D$(J,Z);if(W)return W}if(!Z.analyzeNested)return null;let B=Z.analyzeNested(K,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments});if(B)return B;return null}let Y=e1(g($));if(Y.kind==="dynamic")return D$(J,Z);if(Y.kind==="literal"){if(J.dynamicSourceInput)return D$(J,Z);return null}if(J.dynamicSourceInput??J.dynamicInput)return D$(J,Z);return null}if(F1.has(X))return T(S4($,(K)=>Z.analyzeNested?Z.analyzeNested(K,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments}):null),Z.policy)??Q1($,Z.policy?.rules??[])??$0(J,Z);if(N1(X)){let K=h4($);if(!K)return $0(J,Z);if(a(Z.policy,"interpreter.one-liner-paranoid",!!Z.paranoidInterpreters)){let B=T(N("interpreter.one-liner-paranoid",O$),Z.policy);if(B)return B}if(x4(X,K))return $0(J,Z);let Y=Z.analyzeNested?.(K,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments});if(Y&&Y.id!=="raw-text.dangerous-command"&&(Y.reason!==V0||U$(K)))return Y;if(L$(K,Z.scanWork))return T(N("interpreter.dangerous-command",k0),Z.policy)??$0(J,Z);return $0(J,Z)}if(X==="rm"||X==="rmdir"){let K=X==="rm"&&(H0($)||J.dynamicRmInput);return T(N$(g($),{environment:Z.environment,cwd:Z.cwd,originalCwd:Z.originalCwd,strict:Z.strict,paranoid:Z.paranoidRm,allowTmpdirVar:Z.allowTmpdirVar,tmpdirWordSplittingUnsafe:a1(Z.envAssignments,Z.environment),trustedTmpdirValue:G0(Z.envAssignments,Z.environment),protectedGitMetadata:Z.protectedGitMetadata,policy:Z.policy}),Z.policy)??(K&&J.dynamicRmInput?$0(J,Z):null)??(K?DH(J,Z):null)}if(X==="find")return t4(g($),{...Z,derivedCommandWorkBudget:Z.derivedCommandWorkBudget,analyzeTokens:(K,Y)=>P0(K,{...Z,cwd:Y??void 0,derivedCommandWorkBudget:Z.derivedCommandWorkBudget},J)})??Q1($,Z.policy?.rules??[])??$0(J,Z);if(X==="git")return T(F$(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??[])??$0(J,Z);return Q1($,Z.policy?.rules??[])??$0(J,Z)}function D$($,Z){return $.shellDynamicMatch?T($.shellDynamicMatch,Z.policy):null}function $0($,Z){return $.dynamicSourceInput&&$.dynamicSourceMatch?T($.dynamicSourceMatch,Z.policy):null}function DH($,Z){return $.dynamicInput&&$.rmDynamicMatch?T($.rmDynamicMatch,Z.policy):null}var O9="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",L9="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",zH="__CC_SAFETY_NET_XARGS_INPUT__",Q3="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",X3="rm",bH=/(?:^|[;&|]\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,IH=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,fH=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,PH=/^(?:[0-9]+|[@*])$/,CH=new Set(["branch","checkout","clean","push","reset","restore","switch","tag"]);function c5($,Z){let J=$.map(S),{childStart:Q,replacementToken:X}=i0(J),K=J.slice(Q),Y=N("xargs.shell-dynamic",L9);if(EH(K,X,Z)&&T(Y,Z.policy))return T(Y,Z.policy);for(let B of k1(K,Z)){let W=B.tokens,q=X!==null&&W[0]!==K[0]&&(W[0]?.includes(X)??!1)?T(Y,Z.policy):null;if(q)return q;let U=r5(W,X,B.wrapperEnvAssignments),H=B.head==="rm"&&X!==null&&i5(W,X),j=P0(W,{...Z,cwd:B.cwd,envAssignments:B.envAssignments},{dynamicInput:U,dynamicSourceInput:H||d5(W,B.head,X,B.wrapperEnvAssignments,U,Z.scanWork,Z.environment),dynamicRmInput:H,shellDynamicMatch:Y,dynamicSourceMatch:Y,rmDynamicMatch:N("xargs.rm-recursive-force-dynamic",O9)});if(j)return j;let G=AH(W,X,Z.policy?.rules??[]);if(G)return G;if(B.head==="git"){let O=X===null?[...W,zH]:W,M=X!==null&&(W.some((D)=>D.includes(X))||Array.from(B.envAssignments.values()).some((D)=>D.includes(X))),L=P0(O,{...Z,cwd:B.cwd,envAssignments:B.envAssignments,worktreeMode:X===null||M?!1:Z.worktreeMode});if(L)return L}let _=Q1(W,Z.policy?.rules??[]);if(_)return _}return null}function AH($,Z,J){if(J.length===0)return null;if(Z===null){for(let X of J){let K=Q1([...$,...X.subcommand?[X.subcommand]:[],...X.block_args],J);if(K)return K}return null}let Q=new Set(J.flatMap((X)=>[X.subcommand,...X.block_args].flatMap((K)=>K?$.flatMap((Y)=>M9(Y,Z,K)):[])));for(let X of Q){let K=Q1($.map((Y)=>Y.replaceAll(Z,X)),J);if(K)return K}return null}function M9($,Z,J){let Q=$.indexOf(Z);if(Q===-1||$.indexOf(Z,Q+Z.length)!==-1)return[];let X=$.slice(0,Q),K=$.slice(Q+Z.length);return J.startsWith(X)&&J.endsWith(K)?[J.slice(X.length,J.length-K.length)]:[]}function d5($,Z,J,Q,X,K,Y){if($1.has(Z)){if(C1($))return!1;if(J!==null&&TH($,J))return!0;let B=o1($);if(!B){let W=e1(g($));if(W.kind==="literal")return J!==null&&W.source.includes(J);return W.kind==="none"&&X}if(J!==null&&B.includes(J))return!0;if(q2(B,K))return!0;return SH(B,J,Q)}if(N1(Z))return m5($,J,k4,C7(Z));if(F1.has(Z))return m5($,J,u6,L7);if(Z==="eval"){let B=V$(g($));if(B.kind==="dynamic")return!0;if(J!==null)return B.kind==="literal"&&B.source.includes(J);return X}if(Z==="find")return yH($,J,K,Y);if(Z==="git"){let B=x1($);return J===null?B.subcommand===null:(B.subcommand?.includes(J)??!1)||B.subcommand!==null&&CH.has(B.subcommand.toLowerCase())&&s5(B.rest,J).some((W)=>W.includes(J))}return!1}function m5($,Z,J,Q){let X=J($);if(Z===null)return X.optionsOpen||J([...$,Q3]).sources.some((W)=>W.value===Q3);if(X.sources.some((W)=>W.value.includes(Z)))return!0;let K=new Set(X.sources.map((W)=>`${W.tokenIndex}\x00${W.kind}\x00${W.value}`)),Y=Q.flatMap((W)=>[W.selector,...W.valueForm==="attached-only"||W.valueForm==="attached-or-separate"?[`${W.selector}${Q3}`]:[],...W.valueForm==="equals-or-separate"?[`${W.selector}=${Q3}`]:[]]),B=new Set(Y.flatMap((W)=>$.flatMap((q)=>M9(q,Z,W))));return Array.from(B).some((W)=>J($.map((q)=>q.replaceAll(Z,W))).sources.some((q)=>!K.has(`${q.tokenIndex}\x00${q.kind}\x00${q.value}`)))}function EH($,Z,J){if($.length===0||($[0]??"").toLowerCase()==="command")return!1;let Q=new Set(Array.from(k1($,J),(K)=>K.head)),X=Z===null?[...$,X3]:$.map((K,Y)=>Y===0?K:K.replaceAll(Z,X3));return Array.from(k1(X,J)).some((K)=>K.head===X3&&!Q.has(X3))}function i5($,Z){return s5($.slice(1),Z).some((J)=>J.includes(Z)&&(J.startsWith("-")||J.startsWith(Z)))}function s5($,Z){let J=$.findIndex((Q)=>Q==="--"&&!Q.includes(Z));return J===-1?$:$.slice(0,J)}function r5($,Z,J){if(Z===null)return!0;return $.some((Q)=>Q.includes(Z))||Array.from(J.values()).some((Q)=>Q.includes(Z))}function TH($,Z){let J=t1($);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((K,Y)=>{if(Y===0||!K.includes(Z))return!1;return M9(K,Z,X).some((W)=>{let q=$.map((H,j)=>j===Y?H.replaceAll(Z,W):H),U=t1(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(W))return!0;return U.scriptIndex!==null&&(q[U.scriptIndex]??"").includes(W)})}))}function SH($,Z,J){let Q=new Set(Z===null?[]:Array.from(J).filter(([,X])=>X.includes(Z)).map(([X])=>X));for(let X of $.matchAll(bH))if(p5(X,Q))return!0;for(let X of $.matchAll(IH))for(let K of(X[1]??"").matchAll(fH))if(p5(K,Q))return!0;return _9($,Q)}function p5($,Z){let J=$[1]??$[2];return J!==void 0&&(PH.test(J)||Z.has(J))}function yH($,Z,J,Q){if(Z===null)return!0;let X=!1,K=0;for(let Y=1;Y<$.length;Y++){let B=$[Y]??"";if(!X&&!B.startsWith("-")&&B!=="!"&&B!=="("){if(B.indexOf(Z)===0)return!0;continue}if(X=!0,K>0){K--;continue}if(j0(B)){let q=_2($,Y);Y=q.nextIndex-1;for(let U of k1(q.tokens,{environment:Q,cwd:void 0})){let H=r5(U.tokens,Z,U.wrapperEnvAssignments);if(U.head==="rm"&&i5(U.tokens,Z)||d5(U.tokens,U.head,Z,U.wrapperEnvAssignments,H,J,Q))return!0}continue}let W=I0(B);if(W>0){if(K=W,B.includes(Z))return!0;continue}if(B.includes(Z))return!0}return!1}function i0($){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 K=X.slice(10);J=K===""?"{}":K,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 N2="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",V2="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",vH="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",uH="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",hH=/\{[^{}\s]*\}/,QJ=/\{\}|\{-?\d+\}/g,gH=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","stash","switch","tag","worktree"]),kH=["e","f","source","file","-e","-f","--source","--file"],xH=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],lH=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),mH=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),n5=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),pH=new Set(["--workdir","--wd"]),a5="__CC_SAFETY_NET_PARALLEL_SOURCE__",cH=new TextEncoder,Y3=E.maxDerivedBytes+4*E.maxPlaceholderReplacements;function q1($,Z){for(let J of $){let Q=Z(J);if(Q)return Q}return null}function XJ($,Z){let J=$.map(S);if((Z.envAssignments?.has("PARALLEL")?Z.envAssignments.get("PARALLEL"):Z.environment.env.get("PARALLEL"))?.trim()){let O=r0(Z);if(O)return O}if(J.length===2&&(J[1]==="--version"||J[1]==="--help"))return null;let X=LJ(J),{template:K,jobs:Y,runsRemotely:B,envNames:W,readsCommandsFromInput:q,unsupported:U,workdir:H,dryRun:j}=X;if(U){let O=r0(Z);if(O)return O}if(q){let O=tH(Z);if(O)return O}if(H!==void 0&&B){let O=r0(Z);if(O)return O}let G=Qj(H,Z.cwd,Z.environment.paths);if(G===null){let O=r0(Z);if(O)return O}let _=B?{...Z,cwd:void 0,originalCwd:void 0}:G===null||G===void 0||G===Z.cwd?Z:{...Z,cwd:G};if(j){let O=[...k1(K,_)];if((O.length===0?V9(W,Z.envAssignments,new Map).values:O.flatMap((L)=>V9(W,Z.envAssignments,L.envAssignments).values)).some(z9)){let L=r0(Z);if(L)return L}return null}if(K.length===0){if(W.length>0||Y.some((L)=>L.length!==1)){let L=r0(Z);if(L)return L}let O=Y.map((L)=>L[0]??"");V1(Z.budget,N9(O));let M=HJ(_.envAssignments,_.cwd,B);return q1(O,(L)=>Z.analyzeNested(L,M))}return q1(k1(K,_),(O)=>dH(O,X,Z,_))}function dH($,Z,J,Q){let{jobs:X,templateHasPlaceholder:K,runsRemotely:Y,usesStdin:B,envNames:W}=Z,q=$.tokens,U={...Q,cwd:$.cwd,envAssignments:$.envAssignments},H=V9(W,J.envAssignments,$.envAssignments);if(H.entries.some((L)=>_J(L.value))){let L=r0(J);if(L)return L}let j=H.entries.some((L)=>L.hasPlaceholder),G=K||j,_=B&&G,O=HJ($.envAssignments,$.wrapperCwd,Y||_);if($1.has($.head)){let L=()=>{if(!K||X.length===0)return null;return V1(J.budget,K3(q,X,"generic")),q1(X,(f)=>P0(q.map((A)=>Z0(A,f)),U))};if(C1(q))return L();let D=o1(q);if(D){if(OJ(D)){let b=s0(J);if(b)return b;if(X.length===0)return null;return V1(J.budget,ZJ(D,X)),q1(X,(I)=>J.analyzeNested(Z0(D,I),O))}if(l(D)){if(X.length>0)return V1(J.budget,ZJ(D,X)),q1(X,(C)=>J.analyzeNested(Z0(D,C),O));V1(J.budget,e5(D));let b=O2(D);if(b?.[0]&&x(b[0])==="rm"&&H0(b)){let C=t5(J);if(C)return C}let I=b?P0(b,U,{dynamicInput:B,shellDynamicMatch:N("parallel.shell-dynamic",V2),rmDynamicMatch:N("parallel.rm-recursive-force-dynamic",N2)}):null;if(I)return I;return J.analyzeNested(D,O)}let f=!j&&(!K||X.length>0)?(X.length>0?X:[void 0]).map((b)=>Z3(g(b===void 0?q:K?q.map((I)=>Z0(I,b)):[...q,...b]),D)):[];if(f.some((b)=>b.kind==="dynamic")){let b=s0(J);if(b)return b}let A=f.flatMap((b)=>b.kind==="literal"?[b.source]:[]);if(A.length>0)return V1(J.budget,N9(A)),q1(A,(b)=>J.analyzeNested(b,O));V1(J.budget,$j(e5(D),eH(H.entries,X)));let F=R$(D);if(F&&H.entries.length>0){let b=JJ(H,X,Q,Y);if(b)return b}if(F){let b=s0(J);if(b)return b}let R=J.analyzeNested(D,O);if(R)return R;if(!F){let b=JJ(H,X,Q,Y);if(b)return b}if(G)return s0(J);return null}let z=e1(g(q));if(z.kind==="dynamic"||z.kind==="literal"&&l(z.source))return s0(J)??L();if(z.kind==="literal")return L();if(X.length>0){let f=s0(J);if(f)return f;let A=L();if(A)return A;if(K)return null;let F=X.flatMap((R)=>R[0]===void 0?[]:[R[0]]);return V1(J.budget,N9(F)),q1(F,(R)=>J.analyzeNested(R,O))}if(G||B)return s0(J)??L();return null}if($.head==="rm"&&H0(q)){if(K&&X.length>0)return V1(J.budget,K3(q,X,"rm")),q1(X,(D)=>F9(q.map((z)=>R9(z,D)),$.cwd,Q));if(X.length>0)return V1(J.budget,$J(q,X)),q1(X,(D)=>F9([...q,...D],$.cwd,Q));let L=F9(q.flatMap((D,z)=>{if(z===0||!l(D))return[D];return D.startsWith("-")?[R9(D,[""])]:[]}),$.cwd,Q);if(L)return L;return t5(J)}V1(J.budget,K&&X.length>0?K3(q,X,"generic"):X.length>0?$J(q,X):WJ(q));let M=X.length>0?X:[void 0];return q1(M,(L)=>{let D=L===void 0?q:K?q.map((C)=>Z0(C,L)):[...q,...L],z=N("parallel.shell-dynamic",V2),f=B&&$.head==="find"?oH(D,Q):null,A=YJ(D,B,J.policy?.rules??[],J.budget)??f?.customResult??null,F=x($.head),R=B&&(F==="rm"&&D9(D)||F==="xargs"&&BJ(D)||f?.rmOptions===!0),b=B&&(R||f?.executedSource===!0||f===null&&KJ(D,F)),I=P0(D,{...U,worktreeMode:Y||B||G?!1:J.worktreeMode},{dynamicInput:B||G,dynamicRmInput:R,dynamicSourceInput:A!==null||b,shellDynamicMatch:z,dynamicSourceMatch:z,rmDynamicMatch:N("parallel.rm-recursive-force-dynamic",N2)});if(b){let C=T(z,J.policy);if(C)return C}return I??A??Q1(D,J.policy?.rules??[])})}function KJ($,Z){if(l($[0]??""))return!0;if(Z==="eval"||Z==="source"||Z===".")return!0;if(Z==="parallel"||Z==="xargs")return!0;if($1.has(Z))return rH($);if(Z==="git")return iH($);if(Z==="find")return!0;if(F1.has(Z))return o5($,kH,X2);if(N1(Z))return o5($,xH,g4);return!1}function D9($){let Z=$.indexOf("--"),J=$.slice(1,Z===-1?void 0:Z);if(!$.some(l))return Z===-1;return J.some((X)=>l(X)&&(X.startsWith("-")||OJ(X)))}function iH($){if(sH($))return!0;let Z=x1($);if(Z.subcommand===null||l(Z.subcommand))return!0;if(!gH.has(Z.subcommand.toLowerCase()))return!1;let J=Z.rest.indexOf("--"),Q=Z.rest.slice(0,J===-1?void 0:J);if(!$.some(l))return J===-1;return Q.some(l)}function sH($){for(let Z=1;Z<$.length;Z++){let J=$[Z];if(!J||J==="--"||!J.startsWith("-"))return!1;if(J==="-c"||J==="--config-env"){if(l($[Z+1]??""))return!0;Z++;continue}if(J.startsWith("-c")&&J.length>2||J.startsWith("--config-env=")){if(l(J))return!0;continue}if(l(J))return!0}return!1}function rH($){if(C1($))return!1;let Z=o1($);if(Z!==null)return l(Z);let J=e1(g($));if(J.kind==="literal")return l(J.source);if(J.kind==="dynamic")return!0;return!$.some(l)}function o5($,Z,J){let Q=J($);if(Q.some((K)=>l(K.value)))return!0;if(!$.some(l))return J([...$,a5]).some((K)=>K.value===a5);let X=new Set(Q.map((K)=>`${K.tokenIndex}\x00${K.kind}\x00${K.value}`));return Z.some((K)=>J($.map((Y)=>Z0(Y,[K]))).some((Y)=>!X.has(`${Y.tokenIndex}\x00${Y.kind}\x00${Y.value}`)))}function YJ($,Z,J,Q){if(!Z||J.length===0)return null;let X=J.filter((Y)=>x(Y.command)===x($[0]??""));if(X.length===0)return null;let K=$.some(l);if(V1(Q,nH($,X,K)),!K)return q1(X,(Y)=>Q1([...$,...Y.subcommand?[Y.subcommand]:[],...Y.block_args],[Y]));return q1(X,(Y)=>{let B=new Set([Y.subcommand,...Y.block_args].flatMap((W)=>W?aH($,W):[]));return q1(B,(W)=>Q1($.map((q)=>Z0(q,[W])),[Y]))})}function nH($,Z,J){let Q=J?j1(t(Z.map((X)=>X.block_args.length+(X.subcommand?1:0)),E.maxChildAnalyses),2*Math.max($.length,1),E.maxChildAnalyses):Z.length;return{childAnalyses:Q,derivedTokens:j1(Q,$.length,E.maxDerivedTokens)}}function aH($,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 K=J.slice(0,X.index),Y=J.slice(X.index+X[0].length);if(!Z.startsWith(K)||!Z.endsWith(Y))return[Z];let B=Z.slice(K.length,Z.length-Y.length);return B!==Z?[Z,B]:[Z]})}function oH($,Z){let J={customResult:null,executedSource:!$.some(l),rmOptions:!1},Q=!1,X=0,K=null,Y=()=>{if(!K?.some(l))return;for(let B of k1(K,Z))J.executedSource||=KJ(B.tokens,B.head),J.rmOptions||=B.head==="rm"&&D9(B.tokens)||B.head==="xargs"&&BJ(B.tokens),J.customResult??=YJ(B.tokens,!0,Z.policy?.rules??[],Z.budget)};for(let B of $.slice(1)){if(!Q&&!B.startsWith("-")&&B!=="!"&&B!=="("){J.executedSource||=l(B);continue}if(Q=!0,K){if(B===";"||B==="+"){Y(),K=null;continue}K.push(B);continue}if(X>0){X--;continue}if(j0(B)){K=[],J.executedSource||=l(B);continue}let W=I0(B);if(W>0){X=W,J.executedSource||=l(B);continue}J.executedSource||=l(B)}return Y(),J}function BJ($){let Z=$.slice(i0($).childStart);return x(Z[0]??"")==="rm"&&D9(Z)}function B3($,Z){return(J)=>T(N($,Z),J.policy)}var s0=B3("parallel.shell-dynamic",V2),tH=B3("parallel.command-stream-dynamic",vH),r0=B3("parallel.command-stream-dynamic",uH),t5=B3("parallel.rm-recursive-force-dynamic",N2);function F9($,Z,J){return T(N$(g($),{environment:J.environment,cwd:Z,originalCwd:J.originalCwd,strict:J.strict,paranoid:J.paranoidRm,allowTmpdirVar:J.allowTmpdirVar,tmpdirWordSplittingUnsafe:a1(J.envAssignments??new Map,J.environment),trustedTmpdirValue:G0(J.envAssignments??new Map,J.environment),protectedGitMetadata:J.protectedGitMetadata,policy:J.policy}),J.policy)}function N9($){return{childAnalyses:$.length,derivedTokens:$.length,derivedBytes:b$($)}}function e5($){return WJ([$])}function WJ($){return{childAnalyses:1,derivedTokens:$.length,derivedBytes:b$($)}}function $J($,Z){if(Z.length>E.maxChildAnalyses)return{childAnalyses:Z.length};return{childAnalyses:Z.length,derivedTokens:t(Z.map((J)=>$.length+J.length),E.maxDerivedTokens),derivedBytes:t([j1(b$($),Z.length,E.maxDerivedBytes),t(Z.map((J)=>b$(J)),E.maxDerivedBytes)],E.maxDerivedBytes)}}function ZJ($,Z){return K3([$],Z,"generic")}function K3($,Z,J){if(Z.length>E.maxChildAnalyses)return{childAnalyses:Z.length};let Q=j1($.length,Z.length,E.maxDerivedTokens);if(Q>E.maxDerivedTokens)return{childAnalyses:Z.length,derivedTokens:Q};let X=GJ($.map((W)=>UJ(W,J))),K=j1(X.occurrences,Z.length,E.maxPlaceholderReplacements);if(K>E.maxPlaceholderReplacements)return{childAnalyses:Z.length,derivedTokens:Q,placeholderReplacements:K};if(qJ(X,Z,K))return{childAnalyses:Z.length,derivedTokens:Q,derivedBytes:E.maxDerivedBytes+1,placeholderReplacements:K};let Y=J==="generic"?Z0:R9,B=t(Z.map((W)=>b$($.map((q)=>Y(q,W)))),E.maxDerivedBytes);return{childAnalyses:Z.length,derivedTokens:Q,derivedBytes:B,placeholderReplacements:K}}function qJ($,Z,J){let Q=E.maxDerivedBytes+4*J;return t([j1($.fixedBytes,Z.length,Q),j1($.occurrences,t(Z.map((X)=>X.reduce((K,Y)=>Math.max(K,z$(Y)),0)),Q),Q)],Q)>Q}function eH($,Z){let J=$.filter((U)=>U.hasPlaceholder),Q=Math.max(Z.length,1),X=t(J.map((U)=>U.frequency),E.maxChildAnalyses),K=j1(X,Q,E.maxChildAnalyses),Y=j1(X,Q,E.maxDerivedTokens);if(K>E.maxChildAnalyses||Y>E.maxDerivedTokens)return{childAnalyses:K,derivedTokens:Y};if(Z.length===0)return{childAnalyses:K,derivedTokens:Y,derivedBytes:t(J.map((U)=>j1(z$(U.value),U.frequency,E.maxDerivedBytes)),E.maxDerivedBytes)};let B=GJ(J.map((U)=>Zj(UJ(U.value,"generic"),U.frequency))),W=j1(B.occurrences,Q,E.maxPlaceholderReplacements);if(W>E.maxPlaceholderReplacements)return{childAnalyses:K,placeholderReplacements:W};if(qJ(B,Z,W))return{childAnalyses:K,derivedTokens:Y,derivedBytes:E.maxDerivedBytes+1,placeholderReplacements:W};let q=t(J.map((U)=>j1(b$(Z.map((H)=>Z0(U.value,H))),U.frequency,E.maxDerivedBytes)),E.maxDerivedBytes);return{childAnalyses:K,derivedTokens:Y,derivedBytes:q,placeholderReplacements:W}}function $j($,Z){return{childAnalyses:t([$.childAnalyses??0,Z.childAnalyses??0],E.maxChildAnalyses),derivedTokens:t([$.derivedTokens??0,Z.derivedTokens??0],E.maxDerivedTokens),derivedBytes:t([$.derivedBytes??0,Z.derivedBytes??0],E.maxDerivedBytes),placeholderReplacements:t([$.placeholderReplacements??0,Z.placeholderReplacements??0],E.maxPlaceholderReplacements)}}function UJ($,Z){let J=Z==="generic"?$.matchAll(/\{[^{}\s]*\}/g):$.matchAll(QJ),Q=0,X=0,K=0;for(let Y of J){if(Q>=E.maxPlaceholderReplacements)return{occurrences:E.maxPlaceholderReplacements+1,fixedBytes:0};X=t([X,z$($.slice(K,Y.index))],Y3),Q++,K=Y.index+Y[0].length}return{occurrences:Q,fixedBytes:Q===0?z$($):t([X,z$($.slice(K))],Y3)}}function Zj($,Z){return{occurrences:j1($.occurrences,Z,E.maxPlaceholderReplacements),fixedBytes:j1($.fixedBytes,Z,Y3)}}function GJ($){return{occurrences:t($.map((Z)=>Z.occurrences),E.maxPlaceholderReplacements),fixedBytes:t($.map((Z)=>Z.fixedBytes),Y3)}}function b$($,Z=E.maxDerivedBytes){return t($.map(z$),Z)}function z$($){return cH.encode($).byteLength}function t($,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 j1($,Z,J){if(!Number.isSafeInteger($)||!Number.isSafeInteger(Z)||$<0||Z<0||$!==0&&Z>Math.floor(J/$))return J+1;return $*Z}function V9($,Z,J){let Q=[];for(let X of $){let K=J.get(X)??Z?.get(X);if(K!==void 0)Q.push(K)}return Q.push(...J.values()),Jj(Q)}function Jj($){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:l(Q)}));return{values:$,entries:J,byValue:new Map(J.map((Q)=>[Q.value,Q]))}}function JJ($,Z,J,Q){return q1($.values,(X)=>{if(!$.byValue.get(X)?.hasPlaceholder)return null;let K=Z.length>0?Z:[void 0];return q1(K,(Y)=>{let B=Y===void 0?X:Z0(X,Y);return J.analyzeNested(B,{envAssignments:J.envAssignments,effectiveCwd:Q?null:J.cwd})})})}function HJ($,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 Z0($,Z){return $.replace(/\{[^{}\s]*\}/g,(J)=>jJ(J,Z))}function R9($,Z){return $.replace(QJ,(J)=>jJ(J,Z))}function jJ($,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 l($){return hH.test($)}function _J($){if(z9($))return!0;for(let Z of $.matchAll(/\{[^{}\s]*\}/g))if(!/^(?:\{\}|\{-?\d+\})$/.test(Z[0]))return!0;return!1}function z9($){let Z=$.indexOf("{=");return Z!==-1&&$.indexOf("=}",Z+2)!==-1}function OJ($){return/^\{[^{}\s]*\}$/.test($)}function LJ($){let Z=1,J=[],Q=$.length,X=-1,K=!1,Y=!1,B=!1,W,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=e6($,Z+1);J.push(...f.templateTokens),Q=Z+1,X=f.markerIndex;break}if(!O.startsWith("-")){let f=e6($,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"){B=!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"||mH.has(D)){q=!0,Z+=z===void 0?2:1;continue}if(O==="--pipe"||O==="--pipepart"){Y=!0,Z++;continue}if(D==="--env"){U.push(...Kj(z??M)),Z+=z===void 0?2:1;continue}if(n5.has(D)||O.startsWith("-S")&&O.length>2){K=!0,Z+=n5.has(O)?2:1;continue}if(pH.has(D)){let f=z??M;if(f===void 0||f===":::"||f==="--"){q=!0,Z++;continue}W=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(lH.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(B?z9:_J);let H=[];if(X!==-1){let O=[];for(let M=X+1;M<$.length;M++){let L=$[M];if(L===":::"){H.push(O),O=[];continue}if(L!==void 0)O.push(L)}H.push(O)}let j=Xj(H),G=J.some(l),_=J.length===0&&X===-1;return{template:J,jobs:j,childStart:Q,templateHasPlaceholder:G,runsRemotely:K,usesStdin:Y||X===-1,envNames:U,readsCommandsFromInput:_,unsupported:q,workdir:W,dryRun:B}}function Qj($,Z,J){if($===void 0)return;if($==="..."||/[{}$`*?~[]/.test($))return null;if(!Z&&!wH($))return null;try{return b0(Z??$,$,J)}catch{return null}}function Xj($){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 K of Z)K.push(X);continue}let Q=[];for(let X of Z)for(let K of J)if(Q.push([...X,K]),Q.length>E.maxChildAnalyses)return Q;Z=Q}return Z}function Kj($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}function MJ($){return LJ($).childStart}var Yj="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",b9="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.",Bj=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","stash","switch","tag","worktree"]);function f9($){return $?.parts.some((Z)=>Z.provenance==="command-substitution")??!1}function I9($){return $?.parts.some((Z)=>Z.provenance==="literal"&&Z.raw.replace(/^["']/,"").startsWith("-"))??!1}function NJ($,Z,J,Q=!1,X){let K=F6($,Z)&&a(X,"shell.dynamic-executable",Q)?N("shell.dynamic-executable",Yj):null;return T(K,X)??VJ($,Z,J,Q,X)}function VJ($,Z,J,Q,X){if(Z.length<2)return null;let K=Z.flatMap((B,W)=>f9(B)?[W]:[]);if(K.length===0)return null;let Y=x(Z[0]?.text??"");if(Y==="git"){let B=G$($,Z),W=qj(B);if(a(X,"shell.dynamic-structure",Q)&&K.some((H)=>H<=W))return T(N("shell.dynamic-structure",b9),X);if(T(F$(B,{env:J.env}),X))return null;let q=Z[W]?.text.toLowerCase(),U=B.findIndex((H,j)=>j>W&&S(H)==="--");if(a(X,"shell.dynamic-structure",Q)&&q&&Bj.has(q)&&K.some((H)=>H>W&&(U===-1||H<U)))return T(N("shell.dynamic-structure",b9),X);return null}if(Y==="find")return a(X,"shell.dynamic-structure",Q)&&Uj(Z)?T(N("shell.dynamic-structure",b9),X):null;if(Y==="xargs")return FJ($,Z.slice(i0(Z.map(S)).childStart),"xargs",J,Q,X);if(Y==="parallel")return FJ($,Z.slice(MJ(Z.map(S))),"parallel",J,Q,X);return null}function FJ($,Z,J,Q,X,K){if(Z.length===0)return null;let Y=Wj(Z,Q);if(F6($,Y)){let W=T(N(`${J}.shell-dynamic`,J==="xargs"?L9:V2),K);if(W)return W}let B=VJ($,Y,Q,X,K);if(B)return B;if(Y[0]?.text==="rm"&&Y.slice(1).some((W)=>f9(W)&&I9(W)))return T(N(`${J}.rm-recursive-force-dynamic`,J==="xargs"?O9:N2),K);return null}function Wj($,Z){let J=u0($,Z),Q=J.rewritten?g(J.words.map(S)):J.words,X=Q[0];return X&&S(X)==="busybox"?Q.slice(1):Q}function qj($){let Z=1;while(Z<$.length){let J=$[Z],Q=J?S(J):"";if(i1.has(Q)){Z+=2;continue}if(Q.startsWith("-")){Z++;continue}return Z}return Z}function Uj($){let Z=!1,J=0,Q=!1,X=!1;for(let K=1;K<$.length;K++){let Y=$[K];if(!Y)continue;let B=f9(Y);if(J>0){J--;continue}if(X){if(Y.text===";"||Y.text==="+"){X=!1,Z=!0,Q=!1;continue}if(B&&(Q||I9(Y)))return!0;Q=!1;continue}if(!Z&&!Y.text.startsWith("-")){if(B&&(K>1||I9(Y)))return!0;continue}if(Z=!0,B)return!0;let W=I0(Y.text);if(W>0){J=W;continue}if(j0(Y.text))X=!0,Q=!0}return!1}function P9($,Z){return $.some((J)=>{if(J.value==="-"&&(J.kind==="main-script"||J.kind==="program-file"))return!0;return!I4(Z[J.tokenIndex],J.value)})}var Gj="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",Hj="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",jj="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function RJ($,Z){let J=Z.slice(1);if($==="dd"&&J.some((Q)=>/^of=\/dev\/.+/.test(Q)))return N("dd.device-write",Gj);if(($==="mkfs"||$.startsWith("mkfs."))&&J.some((Q)=>Q.startsWith("/dev/")))return N("mkfs.device",Hj);if($==="shred"&&J.length>0)return N("shred.target",jj);return null}var zJ=[{heads:new Set(["rm","rmdir"]),analyze:($)=>N$($.words,{environment:$.options.environment,cwd:$.cwd,originalCwd:$.originalCwd,strict:$.options.strict,paranoid:$.options.paranoidRm,allowTmpdirVar:$.allowTmpdirVar,tmpdirWordSplittingUnsafe:a1($.envAssignments,$.options.environment),trustedTmpdirValue:G0($.envAssignments,$.options.environment),protectedGitMetadata:$.options.protectedGitMetadata,policy:$.options.policy})},{heads:new Set(["git"]),analyze:($)=>F$($.words,C9($))},{heads:new Set(["find"]),analyze:($)=>t4($.words,{environment:$.options.environment,cwd:$.cwd,originalCwd:$.originalCwd,strict:$.options.strict,allowTmpdirVar:$.allowTmpdirVar,tmpdirWordSplittingUnsafe:a1($.envAssignments,$.options.environment),trustedTmpdirValue:G0($.envAssignments,$.options.environment),protectedGitMetadata:$.options.protectedGitMetadata,derivedCommandWorkBudget:$.options.derivedCommandWorkBudget,envAssignments:$.envAssignments,policy:$.options.policy,analyzeTokens:$.analyzeChildTokens,analyzeNested:(Z,J)=>n0($.options.analyzeNested(Z,J))})},{heads:new Set(["xargs"]),analyze:($)=>c5($.words,{...DJ($),analyzeNested:(Z,J)=>n0($.options.analyzeNested(Z,J))})},{heads:new Set(["parallel"]),analyze:($)=>XJ($.words,{...DJ($),budget:$.options.parallelBudget,analyzeNested:(Z,J)=>n0($.options.analyzeNested(Z,J))})}];function DJ($){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 n0($){return $?{id:$.ruleId??"",reason:$.reason,intent:$.intent??"manual_only"}:null}function C9($){return{env:$.options.environment.env,cwd:$.cwd,dynamicArguments:$.dynamicArguments,envAssignments:$.envAssignments,policy:$.options.policy,worktreeMode:$.options.worktreeMode}}var PJ="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function CJ($){return zJ.find((Z)=>Z.heads.has($))?.analyze}function R2($,Z,J){let Q=J.trace;if($.length===0)return null;let X=J.commandView?.dialect??"posix",K=(P)=>P.map((v)=>X==="posix"?S(v):v.text),Y=J.effectiveCwd===null,B=Y?void 0:J.effectiveCwd??J.cwd,W=Y?void 0:J.cwd,q=f4($);if(q.envAssignments.size>0)Q?.recordSegment({type:"env-strip",input:K($),envVars:Object.fromEntries([...q.envAssignments.keys()].map((P)=>[P,"<redacted>"])),output:K(q.words)});let U=u0(q.words,J.environment,B,new Map([...J.envAssignments??[],...q.envAssignments]));if(U.unverifiableEnvSplit)throw new l0;let H=U.rewritten?g(K(U.words)):G$(X,U.words),j=K(H),G={...J,wrapperNormalizationBudget:J.wrapperNormalizationBudget??{iterations:0}};if(Q&&q.words.length>H.length){let P=K(q.words);Q.recordSegment({type:"leading-tokens-stripped",input:P,removed:P.slice(0,P.length-H.length),output:j})}let _=new Map([...J.envAssignments??[],...q.envAssignments,...U.envAssignments]),O=j[0];if(!O)return null;if(B2(O))throw new P1;let M=x(O),L=U.cwd===null?void 0:U.cwd??B,D=U.cwd===null?void 0:W,z=U.cwd===void 0?J.effectiveCwd:U.cwd,f=!G2(_,J.environment),A=NJ(X,U.words,J.environment,J.strict,J.policy);if(A)return Q?.recordSegment({type:"rule-check",ruleModule:"analyze/segment.ts",ruleFunction:"analyzeDynamicCommandStructure",matched:!0,reason:A.reason}),_0(A);let F=m4(j,J.policy);if(F){for(let P of[F.childIndex,...F.alternativeChildIndices]){bJ(G.wrapperNormalizationBudget);let v=H.slice(P);Q?.recordSegment({type:"transparent-wrapper",wrapper:F.wrapper,output:K(v)});let r=R2(v,Z,{...G,effectiveCwd:z,envAssignments:_});if(r)return r}return null}let R=M==="eval"?V$(H):M==="trap"?h5(H):void 0;if(R?.kind==="dynamic")return A1(Q);if(R?.kind==="literal"){Q?.recordSegment({type:"recurse",reason:M==="eval"?"shell-eval":"shell-trap",innerCommand:R.source,depth:Z+1});let P=J.analyzeNested(R.source,{effectiveCwd:z,envAssignments:_,functionDefinitions:J.functionDefinitions});if(P)return P}if(EJ(O,M)){if(C1(j))return null;let P=_j(j,_,z,J,Q,Z);if(P)return P;let v=o1(j);if(v){let e0=Z3(H,v);if(e0.kind==="dynamic")return A1(Q);let S3=e0.kind==="literal"?e0.source:v,JZ=Oj(S3);Q?.recordSegment({type:"shell-wrapper",wrapper:M,innerCommand:JZ}),Q?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:JZ,depth:Z+1});let QZ=J.analyzeNested(S3,{effectiveCwd:z,envAssignments:_});if(QZ)return QZ;return R$(S3)?A1(Q):null}let r=e1(H);if(r.kind==="dynamic")return A1(Q);if(r.kind==="literal")return U3(r.source,z,_,J,Q,Z);let Z1=g5(H,J.commandView?.redirections??[],J.hasPipelineInput??!1,J.literalShellInput);if(Z1.kind==="dynamic")return A1(Q);if(Z1.kind==="literal")return Q?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:Z1.source,depth:Z+1}),J.analyzeNested(Z1.source,{effectiveCwd:z,envAssignments:_})}if(M==="source"||M==="."){let P=j[1]==="-p"?2:null;if(P!==null){let e0=J.commandView?H[P]:void 0;if(!e0)return null;if(e0.provenance!=="literal")return A1(Q)}let v=P===null?1:3,r=j[v]==="--"?v+1:v,Z1=J.commandView?H[r]:void 0;if(!Z1)return null;if(Z1.provenance!=="literal")return A1(Q);return U3(Z1.text,z,_,J,Q,Z)}if(F1.has(M)){if(J.strict&&P9(X2(j),H))return A1(Q);let P=S4(j,(r)=>n0(J.analyzeNested(r,{effectiveCwd:z,envAssignments:_}))),v=T(P,J.policy);if(v)return Q?.recordSegment({type:"rule-check",ruleModule:"awk",ruleFunction:"analyzeAwkSystemCalls",matched:!0,reason:v.reason}),_0(v)}if(N1(M)){if(J.strict&&P9(g4(j),H))return A1(Q);let P=h4(j);if(P){let v=a(J.policy,"interpreter.one-liner-paranoid",!!J.paranoidInterpreters);if(Q?.recordSegment({type:"interpreter",interpreter:M,codeArg:P,paranoidBlocked:v}),v){let Z1=T(N("interpreter.one-liner-paranoid",O$),J.policy);if(Z1)return _0(Z1)}if(x4(M,P))return null;Q?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:P,depth:Z+1});let r=J.analyzeNested(P,{effectiveCwd:z,envAssignments:_});if(r&&r.ruleId!=="raw-text.dangerous-command"&&(r.reason!==V0||U$(P)))return r;if(L$(P,J.scanWork)){let Z1=T(N("interpreter.dangerous-command",k0),J.policy);if(Z1)return Q?.recordSegment({type:"dangerous-text",token:P,matched:!0,reason:k0}),_0(Z1)}Q=void 0}}if(M==="busybox"&&j.length>1)return bJ(G.wrapperNormalizationBudget),Q?.recordSegment({type:"busybox",subcommand:j[1]??"unknown"}),Q?.recordSegment({type:"recurse",reason:"busybox",innerCommand:j.slice(1).join(" "),depth:Z+1}),R2(H.slice(1),Z,{...G,effectiveCwd:z,envAssignments:_});let b=T(RJ(M,j),J.policy);if(b)return Q?.recordSegment({type:"rule-check",ruleModule:"analyze/device.ts",ruleFunction:"analyzeDeviceCommand",matched:!0,reason:b.reason}),_0(b);let I=Q===G.trace?G:{...G,trace:Q},C={words:H,head:M,cwd:L,originalCwd:D,envAssignments:_,allowTmpdirVar:f,dynamicArguments:U.words.some((P)=>P.provenance==="command-substitution"),depth:Z,effectiveCwd:z,options:I,analyzeChildTokens:(P,v)=>n0(R2(g(P),Z+1,{...I,commandView:void 0,effectiveCwd:v,envAssignments:_}))??Q1(P,I.policy.rules)},y=CJ(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"?f5(C.words,C9(C)):void 0,k=IJ(w?w.match:y?.(C)??null,J.policy);if(Q)Lj(C,k,w?.relaxation??null);if(k)return _0(k);let B1=y!==void 0;if(!B1)if(!a2.has(M)){let P=Q?[]:void 0;for(let v=1;v<j.length;v++){let r=j[v];if(!r)continue;P?.push(r);let Z1=IJ(Mj(C,j,v),J.policy);if(Z1)return Q?.recordSegment({type:"fallback-scan",tokensScanned:P??[],embeddedCommandFound:x(r)}),_0(Z1)}Q?.recordSegment({type:"fallback-scan",tokensScanned:P??[]})}else Q?.recordSegment({type:"fallback-scan",tokensScanned:[]});else Q?.recordSegment({type:"fallback-scan",tokensScanned:[]});if(Z===0||!B1){let P=Q1(j,J.policy.rules);if(Q?.recordSegment({type:"custom-rules-check",rulesChecked:J.policy.rules.length>0,matched:!!P,reason:P?.reason}),P)return _0(P)}else Q?.recordSegment({type:"custom-rules-check",rulesChecked:!1,matched:!1});return null}function _j($,Z,J,Q,X,K){let Y=S5($);if(Y.argvSource?.kind==="absent")return A1(X);if(Y.argvSourceApplies&&Y.argvSource){let W=U3(Y.argvSource.value,J,Z,Q,X,K,!0);if(W)return W}if(!Y.envSourceApplies||!Y.envName)return null;let B=Z.get(Y.envName);if(!B)return null;return U3(B,J,Z,Q,X,K,!0)}function U3($,Z,J,Q,X,K,Y=!1){if(Y&&/[$`*?[\]]/.test($))return A1(X);let B=U2($,Z,Q.environment.paths),W=B?Q.literalHeredocFiles?.get(B):void 0;if(W===void 0)return Y?A1(X):null;return n1(Q.derivedCommandWorkBudget,1),X?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:W,depth:K+1}),Q.analyzeNested(W,{effectiveCwd:Z,envAssignments:J})}function Oj($){let Z=$[0];return $.length>=2&&(Z==='"'||Z==="'")&&$.at(-1)===Z?$.slice(1,-1):$}function Lj($,Z,J){let Q={git:["git","analyzeGit"],rm:["analyze/rm.ts","analyzeRm"],find:["analyze/find.ts","analyzeFind"],xargs:["analyze/xargs.ts","analyzeXargs"],parallel:["analyze/parallel.ts","analyzeParallel"]}[$.head];if(!Q)return;if($.options.trace?.recordSegment({type:"rule-check",ruleModule:Q[0]??"",ruleFunction:Q[1]??"",matched:!!Z||!!J,reason:Z?.reason??J?.originalReason}),J)$.options.trace?.recordSegment({type:"worktree-relaxation",originalReason:J.originalReason,gitCwd:J.gitCwd})}function bJ($){if($.iterations>=K$)throw new P1;$.iterations++}function _0($){return{reason:$.reason,ruleId:$.id||void 0,intent:$.intent}}function A1($){return $?.recordSegment({type:"error",message:PJ}),_0(AJ())}function AJ(){return{id:"",reason:PJ,intent:"stop_and_explain"}}function EJ($,Z){return $1.has(Z)||$==="$SHELL"||$==="${SHELL}"||$1.has(h(Z))}function Mj($,Z,J){let Q=k1(Z.slice(J),{environment:$.options.environment,cwd:$.cwd,envAssignments:$.envAssignments,policy:$.options.policy});for(let X of Q){let K=Fj($,J,X);if(K)return K}return null}function Fj($,Z,J){let Q=J.tokens[0];if(!Q)return null;let X=x(Q);if(EJ(Q,X)){n1($.options.derivedCommandWorkBudget,$.words.length-Z);let W=J.tokens;if(C1(W))return null;let q=o1(W);if(!q){if(e1(g(W)).kind==="dynamic")return AJ();return q3($,J)}let U=$.options.analyzeNested(q,{effectiveCwd:J.wrapperCwd===void 0?$.effectiveCwd:J.wrapperCwd,envAssignments:J.envAssignments});return U?n0(U):q3($,J)}let K=CJ(X);if(!K||X==="xargs"||X==="parallel"){if(J.wrappedByTransparent&&$.options.policy.rules.length>0)n1($.options.derivedCommandWorkBudget,$.words.length-Z);return q3($,J)}n1($.options.derivedCommandWorkBudget,$.words.length-Z);let Y=[X,...J.tokens.slice(1)],B={...$,words:g(Y),head:X,cwd:J.cwd,originalCwd:J.wrapperCwd===null?void 0:$.originalCwd,envAssignments:J.envAssignments,allowTmpdirVar:!G2(J.envAssignments,$.options.environment),effectiveCwd:J.wrapperCwd===void 0?$.effectiveCwd:J.wrapperCwd,options:X==="git"?{...$.options,worktreeMode:!1}:$.options};return K(B)??q3($,J)}function q3($,Z){return Z.wrappedByTransparent?Q1(Z.tokens,$.options.policy.rules):null}function IJ($,Z){return $?.id.startsWith("custom.")?$:T($,Z)}var Nj=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,Vj=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function Rj($,Z){let J=yJ($,Z);if(J.length===0)return!1;let Q=J[SJ(J)];if(Q==="cd"||Q==="pushd"||Q==="popd")return!0;return Nj.test($.join(" "))}function TJ($,Z,J,Q){if($.dialect==="powershell"){let B=Dj($.words,Q);if(B.kind==="none")return;if(!Z||B.kind==="unknown")return null;return fJ(fj(B.target),Z,J.paths)}let X=$.words.map(S);if(!Rj(X,J))return;if(!Z)return null;let K=yJ(X,J,Z),Y=SJ(K);if(Y===-1||K[Y]!=="cd")return null;return fJ(K[Y+1],Z,J.paths)}function fJ($,Z,J){if(!$||$==="-"||$.includes("$")||$.includes("`"))return null;try{return Pj(b0(Z,$,J),Z,J)?Z:null}catch{return null}}function Dj($,Z){let J=zj($[0])?1:0,Q=$[J];if(!bj(Q,J===1))return{kind:"none"};let X=Q.text.toLowerCase(),K=X.split(/[\\/]/).pop()??X;if(!Vj.has(K))return{kind:"none"};if(X!==K||K==="pop-location"||K==="popd")return{kind:"unknown"};return Ij($.slice(J+1),Z)}function zj($){return $?.provenance==="literal"&&!$.quoted&&$.raw===$.text&&($.text==="&"||$.text===".")}function bj($,Z){return $?.provenance==="literal"&&(Z||!$.quoted&&$.raw===$.text)}function Ij($,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 fj($){return $.includes("::")?void 0:$.replaceAll("\\","/")}function SJ($){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 yJ($,Z,J){let Q=Cj($);return I1([...Q],Z,J)}function Pj($,Z,J){let Q=J.realpath($),X=J.realpath(Z);if(Q===null||X===null)return W3($)===W3(Z);return W3(Q)===W3(X)}function Cj($){let Z=0;while(Z<$.length){let J=$[Z];if(J==="{"||J==="("||J==="$(")Z++;else break}return $.slice(Z)}var D2="TMPDIR",z2="IFS",Aj=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,A9=/^[A-Za-z_][A-Za-z0-9_]*$/;function vJ($,Z){let J=wj($,Z);return{env:$,effectiveEnvAssignments:J,shellAssignments:new Map,exportedNames:vj($,J),allexport:!1,keywordExport:!1}}function uJ($){return{env:$.env,effectiveEnvAssignments:$.effectiveEnvAssignments?new Map($.effectiveEnvAssignments):void 0,shellAssignments:new Map($.shellAssignments),exportedNames:new Set($.exportedNames),allexport:$.allexport,keywordExport:$.keywordExport}}function hJ($,Z){let J=Ej($,Z);if(!J)return;let{command:Q,commandIndex:X,leadingAssignments:K,prefixAssignmentsPersist:Y}=J;if(Q===null){for(let W of K.values())wJ(Z,W);return}if(Y)for(let W of K.values())Z.shellAssignments.set(W.name,W.value),Z.exportedNames.add(W.name),C0(Z,W);if(Q==="set"){let W=mj($,X);if(W.allexport!==null)Z.allexport=W.allexport;if(W.keywordExport!==null)Z.keywordExport=W.keywordExport;return}if(Q==="unset"){let W=kj($,X);if(W===null)return;for(let q of $.slice(W))gj(Z,q);return}if(Q!=="export"&&Q!=="typeset"&&Q!=="declare"&&Q!=="readonly")return;for(let W of K.values())wJ(Z,W);if(Q==="export"){let W=xj($,X);if(W===null)return;for(let q of $.slice(W))uj(Z,q);return}let B=lj($,X);if(B===null)return;for(let W of $.slice(B.operandsStart))hj(Z,W,B.exports,Q==="readonly"?K:void 0)}function gJ($,Z){if(!Z.keywordExport)return Z.effectiveEnvAssignments;let J=null,Q=j3(Z);for(let X of $){let K=H3(X,Q,Z.env);if(!K)continue;J??=new Map(Z.effectiveEnvAssignments??[]),J.set(K.name,K.value),Q.set(K.name,K.value)}return J??Z.effectiveEnvAssignments}function Ej($,Z){let J=new Map,Q=0;while(Q<$.length){let B=$[Q];if(!B)return null;let W=H3(B,j3(Z,J),Z.env);if(!W)break;J.set(W.name,W),Q++}if(Q>=$.length)return{command:null,commandIndex:Q,leadingAssignments:J,prefixAssignmentsPersist:!1};let X=Q,K=Q,Y=$[K]??null;while(Y==="builtin"||Y==="command"||Y==="time"){if(Y==="builtin"){if(K++,$[K]==="--")K++;Y=$[K]??null;continue}if(Y==="command"){let W=Tj($,K);if(!W)return null;K=W.commandIndex,Y=W.command;continue}let B=Sj($,K);if(!B)return null;K=B.commandIndex,Y=B.command}if(Y===null)return null;return{command:Y,commandIndex:K,leadingAssignments:J,prefixAssignmentsPersist:K===X&&(Y==="unset"||Y==="set"||Y==="export"||Y==="readonly")}}function Tj($,Z){return kJ($,Z,(J)=>{if(J==="-p")return"skip";return J==="-v"||J==="-V"?"abort":"stop"})}function Sj($,Z){return kJ($,Z,(J)=>J.startsWith("-")?"skip":"stop")}function kJ($,Z,J){let Q=Z+1;while(Q<$.length){let K=$[Q];if(!K)return null;if(K==="--"){Q++;break}let Y=J(K);if(Y==="abort")return null;if(Y==="skip"){Q++;continue}break}let X=$[Q];return X?{command:X,commandIndex:Q}:null}function H3($,Z,J){return s1($)??yj($,Z,J)}function yj($,Z,J){let Q=R4($,J,Z);if(Q)return Q;let X=$.match(Aj)?.[1];if(!X)return null;let K=$.indexOf("=");return{name:X,value:`${Z.has(X)?Z.get(X):J.get(X)??""}${$.slice(K+1)}`}}function G3($){return $===D2||$===z2||I6($)}function j3($,Z){return new Map([...$.effectiveEnvAssignments??[],...$.shellAssignments,...[...Z?.values()??[]].map((J)=>[J.name,J.value])])}function wj($,Z){let J=[...N4,D2,z2].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 vj($,Z){let J=new Set;for(let Q of $.keys())if(G3(Q))J.add(Q);for(let Q of Z?.keys()??[])if(G3(Q))J.add(Q);return J}function wJ($,Z){if($.shellAssignments.set(Z.name,Z.value),Z.name===D2||Z.name===z2||$.allexport||$.exportedNames.has(Z.name))C0($,Z)}function C0($,Z){let J=new Map($.effectiveEnvAssignments??[]);J.set(Z.name,Z.value),$.effectiveEnvAssignments=J}function uj($,Z){let J=H3(Z,j3($),$.env);if(J){$.shellAssignments.set(J.name,J.value),$.exportedNames.add(J.name),C0($,J);return}if(A9.test(Z))xJ($,Z)}function hj($,Z,J,Q){let X=H3(Z,j3($),$.env);if(X){if($.shellAssignments.set(X.name,X.value),J)$.exportedNames.add(X.name),C0($,X);else if(X.name===D2||X.name===z2||$.allexport||$.exportedNames.has(X.name))C0($,X);return}let K=Q?.get(Z);if(K){$.exportedNames.add(Z),C0($,K);return}if(J&&A9.test(Z))xJ($,Z)}function xJ($,Z){$.exportedNames.add(Z),C0($,{name:Z,value:$.shellAssignments.get(Z)??$.effectiveEnvAssignments?.get(Z)??$.env.get(Z)??""})}function gj($,Z){if(!G3(Z)&&!A9.test(Z))return;if($.shellAssignments.set(Z,""),$.exportedNames.delete(Z),!G3(Z)||Z===D2||Z===z2||a$(Z)){C0($,{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 kj($,Z){return lJ($,Z,(J)=>J==="-v")}function xj($,Z){return lJ($,Z,(J)=>J==="-p")}function lJ($,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 lj($,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 mj($,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 K=X.slice(1);if(K.includes("a"))J.allexport=!0;if(K.includes("k"))J.keywordExport=!0;Q++;continue}if(X.startsWith("+")&&X.length>1){let K=X.slice(1);if(K.includes("a"))J.allexport=!1;if(K.includes("k"))J.keywordExport=!1;Q++;continue}return J}return J}var pj="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",a0="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.",cj=64;function w9($,Z,J,Q){let X=J.derivedCommandWorkBudget===void 0,K=J.parallelBudget===void 0;try{return dj($,Z,{...J,derivedCommandWorkBudget:J.derivedCommandWorkBudget??d4(),parallelBudget:J.parallelBudget??m7()},Q)}catch(Y){let B=Y instanceof l0?h7:Y instanceof P1&&X?u7:Y instanceof s4&&K?l7:void 0;if(!B)throw Y;if(J.trace?.currentSegmentIndex!==void 0)J.trace.recordSegment({type:"error",message:B});else J.trace?.recordGlobal({type:"error",message:B});return{reason:B,segment:$,intent:"stop_and_explain"}}}function dj($,Z,J,Q){if(Z>=n2)return J.trace?.recordSegment({type:"error",message:Y0}),{reason:Y0,segment:$,intent:"stop_and_explain"};let X=Q??J.factStore?.getCommandProgram($,J.shell??"auto")??w1($,J.shell);if(X.status==="limited")return J.trace?.recordSegment({type:"error",message:Y0}),{reason:Y0,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 y9($,J);let U=`Unsupported heredoc syntax: ${q.message}`;return J.trace?.recordGlobal({type:"error",message:U}),{reason:U,segment:$,intent:"stop_and_explain"}}return sJ($,J),{reason:V0,segment:$,intent:"stop_and_explain"}}if(J.strict&&X.status==="partial")return sJ($,J),{reason:V0,segment:$,intent:"stop_and_explain"};if(X.issues.some((q)=>q.code.includes("quote"))&&!J.analyzePartialProgram)return y9($,J);let Y=J.cwd,B=J.effectiveCwd!==void 0?J.effectiveCwd:J.cwd,W=vJ(J.environment.env,J.envAssignments);return L3(X,Z,{...J,rootProgram:X},Y,[{effectiveCwd:B,shellGitContextState:W,literalHeredocFiles:new Map(J.literalHeredocFiles),functionDefinitions:new Map(J.functionDefinitions)}]).result}function L3($,Z,J,Q,X){let K=[...X],Y,B;for(let[W,q]of $.nodes.entries()){if(q.kind==="connector"){B=q.operator;continue}let U=$.nodes[W+1],H=U?.kind==="connector"?U.operator:void 0,j=ij($,W,q,B,H),G=B==="&&"||B==="||",_=G?Y:void 0,O=B==="&&"?_?.success??K:B==="||"?_?.failure??K:K,M=B==="||"?_?.success??[]:[],L=B==="&&"?_?.failure??[]:[],D=G||I$(H);if(q.kind==="function"){let I=O.flatMap((y)=>{let w=b2(y);return w.functionDefinitions.set(q.name,q.body),E9(y,[w],j,H==="&",I$(H))}),C=T9(I,[],M,L,B,H);K=C.states,Y=C.conditionalStates,B=void 0;continue}if(q.kind==="group"){let I=[],C=[];for(let w of O){let k=L3(q.body,Z,J,Q,[b2(w)]);if(k.result)return k;if(I.push(...E9(w,k.states,j,H==="&",I$(H))),D)C.push(w,...j?k.states.map((B1)=>_3(w,B1)):k.states)}let y=T9(I,C,M,L,B,H);K=y.states,Y=y.conditionalStates,B=void 0;continue}if(q.kind!=="command")continue;let z=J.trace?.flattenNested?J.trace.currentSegmentIndex:J.trace?.allocateSegment(),f=$.nodes[W-2],A=M3(B)&&f?.kind==="command"?u5(f)??rj(f):void 0,F=[],R=[];for(let I of O){let C=nj(q,Z,J,Q,[b2(I)]);if(C.result)return{result:C.result,states:K};let y=$.dialect==="powershell"?C.states:C.states.map((w)=>_3(I,w));for(let w of y){let k=b2(w),B1=tj(q,Z,J.trace?{...J,trace:rJ(J.trace,z)}:J,Q,k,M3(B),A);if(B1)return{result:B1,states:K};let P=G_(q,k.functionDefinitions);if(P)n1(J.derivedCommandWorkBudget,F3(P));let v=P?Z+1>=n2?S9(q.displayText,J,[k]):L3(P,Z+1,J,Q,[k]):{result:null,states:[k]};if(v.result)return v;if(F.push(...E9(I,v.states,j,H==="&",I$(H))),D)R.push(I),R.push(...v.states.map((r)=>j?_3(I,r):r))}}let b=T9(F,R,M,L,B,H);K=b.states,Y=b.conditionalStates,B=void 0}return{result:null,states:K}}function ij($,Z,J,Q,X){if(J.kind==="group"&&J.style==="subshell")return!0;if($.dialect==="posix"&&(M3(Q)||M3(X)))return!0;if(X==="&")return!0;return $.dialect==="powershell"&&J.kind==="group"&&J.style==="brace"&&sj($,Z)}function E9($,Z,J,Q,X){let K=J?Z.map((B)=>_3($,B)):[...Z],Y=X?K.flatMap((B)=>I2($.literalHeredocFiles,B.literalHeredocFiles)?[B]:[{...B,literalHeredocFiles:new Map($.literalHeredocFiles)},B]):K;return Q?[$,...Y]:Y}function _3($,Z){return{...$,literalHeredocFiles:new Map(Z.literalHeredocFiles)}}function sj($,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(aj(J))return!0;return J.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function M3($){return $==="|"||$==="|&"}function rj($){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 I$($){return $==="&&"||$==="||"}function T9($,Z,J,Q,X,K){let Y={success:O3([...J,...$]),failure:O3([...Q,...Z])},B=I$(K)?Y:void 0;return{states:I$(X)||B?O3([...Y.success,...Y.failure]):Y.success,conditionalStates:B}}function rJ($,Z,J=$.flattenNested){return{currentSegmentIndex:Z,flattenNested:J,allocateSegment:$.allocateSegment,getNextSegmentIndex:$.getNextSegmentIndex,recordGlobal:$.recordGlobal,recordSegment:(Q,X=Z)=>$.recordSegment(Q,X)}}function nj($,Z,J,Q,X){let K=$.nested.map((Y)=>({program:Y,depth:Z}));if($.dialect==="powershell"){let Y=oj($);if(Y){if(Z+1>=n2)return S9(Y,J,X);let B=w1(Y,"powershell");if(B.status==="limited")return S9(Y,J,X);if(B.status!=="complete")return mJ(K,J,Q,X);n1(J.derivedCommandWorkBudget,F3(B)),K.push({program:B,depth:Z+1})}}return mJ(K,J,Q,X)}function aj($){let Z=$.words[0];return Z?.provenance==="variable"&&$.words.at(-1)?.text==="="?Z.text.toLowerCase():void 0}function mJ($,Z,J,Q){let X=[...Q];for(let K of $){let Y=[];for(let B of X){let W=L3(K.program,K.depth,Z,J,[b2(B)]);if(W.result)return W;Y.push(...W.states)}X=O3(Y)}return{result:null,states:X}}function oj($){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),K=X[0]&&!X[0].quoted&&X[0].raw===X[0].text&&["-c","-command"].includes(X[0].text.toLowerCase())?1:0,Y=X[K];return X.length===K+1&&Y?.quoted&&Y.provenance==="literal"?Y.text:void 0}function F3($){return $.nodes.reduce((Z,J)=>Z+(J.kind==="command"?J.words.length+J.nested.reduce((Q,X)=>Q+F3(X),0):J.kind==="group"||J.kind==="function"?F3(J.body):0),0)}function S9($,Z,J){return Z.trace?.recordSegment({type:"error",message:Y0}),{result:{reason:Y0,segment:$,intent:"stop_and_explain"},states:[...J]}}function tj($,Z,J,Q,X,K,Y){let B=K_($);if(B&&J.strict)return J.trace?.recordSegment({type:"error",message:B}),{reason:B,segment:$.source,intent:"stop_and_explain"};nJ($,X,"before-consumer",J.environment.paths);let W=G$($.dialect,$.words).map(S),q=$.displayText,U=gJ(W,X.shellGitContextState);if($.dialect==="powershell"){let G=T(W5($,K,__(J,X.effectiveCwd)),J.policy);if(J.trace?.recordSegment({type:"rule-check",ruleModule:"analyze/powershell/remove-item.ts",ruleFunction:"analyzePowerShellCommandViewMatch",matched:!!G,reason:G?.reason}),G)return j_(q,G)}if(W.length===1&&W[0]?.includes(" ")&&!$.dynamicExecutable){let G=T(q2(W[0],J.scanWork),J.policy),_=G!==null&&!J.strict&&y7($,J.rootProgram,J.scanWork);if(G&&!_)return J.trace?.recordSegment({type:"dangerous-text",token:W[0],matched:!0,reason:G.reason}),{reason:G.reason,segment:q,ruleId:G.id,intent:G.intent};return J.trace?.recordSegment({type:"dangerous-text",token:W[0],matched:!1}),pJ($,B,X,U,Y,J)}let H=R2($.words,Z,{...J,commandView:$,cwd:Q,effectiveCwd:X.effectiveCwd,envAssignments:U,literalHeredocFiles:X.literalHeredocFiles,functionDefinitions:X.functionDefinitions,hasPipelineInput:K,literalShellInput:Y,analyzeNested:(G,_)=>{let O=_&&Object.hasOwn(_,"effectiveCwd")?_.effectiveCwd:X.effectiveCwd,M=w9(G,Z+1,{...J,derivedCommandWorkBudget:J.derivedCommandWorkBudget,effectiveCwd:O,envAssignments:_?.envAssignments??U,literalHeredocFiles:X.literalHeredocFiles,functionDefinitions:_?.functionDefinitions,worktreeMode:_?.worktreeMode??J.worktreeMode,trace:J.trace?rJ(J.trace,J.trace.currentSegmentIndex,!0):void 0});return M?{reason:M.reason,ruleId:M.ruleId,intent:M.intent}:null}});if(H)return{...H,segment:q};let j=pJ($,B,X,U,Y,J);if(j)return j;return hJ(W,X.shellGitContextState),null}function pJ($,Z,J,Q,X,K){let Y=Y_($,Z,J,Q??new Map,K);if(Y)return Y;return nJ($,J,"after-consumer",K.environment.paths),J.literalHeredocFiles.clear(),Z_($,Z,J,K.environment.paths),q_($,J,X,K.environment,K.trace),null}var ej=new Set([">>","<>"]);function nJ($,Z,J,Q){for(let K of $.redirections){if(!(J==="before-consumer"?$_(K):ej.has(K.operator)))continue;cJ(K.target,Z,Q)}if(J!=="before-consumer"||!R1($.words[0],"tee"))return;let X=aJ($.words.slice(1));if(!X)return;for(let K of X.operands)cJ(K,Z,Q)}function $_($){if($.operator===">"||$.operator===">|")return!0;return $.operator===">&"&&$.fd===void 0&&$.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test($.target.text)}function cJ($,Z,J){let Q=$?.provenance==="literal"?U2($.text,Z.effectiveCwd,J):void 0;if(!Q)return;Z.literalHeredocFiles.delete(Q)}function Z_($,Z,J,Q){if(Z)return;let X=$.redirections.find((K)=>K.operator==="<<"||K.operator==="<<-")?.heredoc;if(!X?.quotedDelimiter)return;for(let K of J_($)){let Y=U2(K.text,J.effectiveCwd,Q);if(!Y||!x7(Y))continue;if(!J.literalHeredocFiles.has(Y)&&J.literalHeredocFiles.size>=k7)throw new P1;J.literalHeredocFiles.set(Y,X.body)}}function J_($){let Z=X_($.redirections)?.target,J=dJ(Z)?[Z]:[];if(R1($.words[0],"cat"))return Q_($.words)?J:[];if(!R1($.words[0],"tee"))return[];let Q=aJ($.words.slice(1));if(!Q||Q.append||Q.hasUnsupportedOptions||!Q.operands.every(dJ))return[];return[...Q.operands,...J]}function Q_($){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 X_($){let Z=$.findLast((J)=>(J.fd??([">",">|",">>",">&"].includes(J.operator)?1:0))===1);return Z?.operator===">"||Z?.operator===">|"?Z:void 0}function aJ($){let Z=[],J=!0,Q=!1,X=!1;for(let K of $){if(K.provenance!=="literal")return;if(J&&R1(K,"--")){J=!1;continue}if(J&&!K.quoted&&K.raw===K.text&&/^-[^-]/.test(K.text)){Q||=K.text.slice(1).includes("a"),X||=[...K.text.slice(1)].some((Y)=>Y!=="a"&&Y!=="i");continue}if(J&&!K.quoted&&K.raw===K.text&&K.text.startsWith("--")){Q||=K.text==="--append",X||=K.text!=="--append"&&K.text!=="--ignore-interrupts";continue}Z.push(K)}return{operands:Z,append:Q,hasUnsupportedOptions:X}}function dJ($){if(!$||$.provenance!=="literal"||$.text.length===0)return!1;if($.quoted||$.raw!==$.text)return!0;return!$.raw.startsWith("~")&&!/[{}]/.test($.raw)}function R1($,Z){return $?.text===Z&&$.raw===Z&&$.provenance==="literal"&&!$.quoted}function K_($){let Z=$.redirections.filter((Y)=>Y.operator==="<<"||Y.operator==="<<-");if(Z.length===0)return;if(Z.length!==1)return a0;let J=Z[0];if(!J?.heredoc)return a0;if(!J.heredoc.quotedDelimiter)return pj;if(J.fd!==void 0&&J.fd!==0)return a0;if($.redirections.some((Y)=>Y!==J&&["<","<<","<<-","<<<","<&","<>"].includes(Y.operator)))return a0;let Q=$.redirections.some((Y)=>Y!==J&&iJ(Y.target));if(R1($.words[0],"cat"))return Q?a0:void 0;if(R1($.words[0],"tee"))return Q||$.words.slice(1).some(iJ)?a0:void 0;let X=$.words[0],K=$.words[1];if(R1(X,"git")&&(R1(K,"apply")||R1(K,"commit")))return;if(R1(X,"gh")&&(R1(K,"pr")||R1(K,"issue"))&&R1($.words[2],"create"))return;return a0}function iJ($){return $?.parts.some((Z)=>Z.provenance==="command-substitution"&&Z.raw.startsWith(">("))??!1}function Y_($,Z,J,Q,X){if(!Z)return null;let K=$.redirections.filter((q)=>q.operator==="<<"||q.operator==="<<-"),Y=K.flatMap((q)=>q.heredoc?[q.heredoc.body]:[]);if(W_($,K,J,Q,X))return null;let B=B_($,K,X);if(B!==void 0)return B?{reason:B.reason,segment:$.displayText,ruleId:B.id,intent:B.intent}:null;let W=y9(Y.length===K.length?Y.join(`
|
|
60
|
-
`):$.source,X);return W?{...W,segment:$.displayText}:null}function B_($,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 Y=Q.heredoc.body,B=a(J.policy,"interpreter.one-liner-paranoid",!!J.paranoidInterpreters);if(J.trace?.recordSegment({type:"interpreter",interpreter:X.text,codeArg:Y,paranoidBlocked:B}),B){let q=T(N("interpreter.one-liner-paranoid",O$),J.policy);if(q)return q}if(!L$(Y,J.scanWork))return null;let W=T(N("interpreter.dangerous-command",k0),J.policy);if(!W)return null;return J.trace?.recordSegment({type:"dangerous-text",token:Y,matched:!0,reason:W.reason}),W}function W_($,Z,J,Q,X){let K=Z.length===1?Z[0]:void 0;if(!K?.heredoc?.quotedDelimiter||K.fd!==void 0&&K.fd!==0)return!1;let Y=u0($.words,X.environment,J.effectiveCwd,Q),B=Y.words.map(S),W=x(B[0]??"");if(Y.unverifiableEnvSplit||!$1.has(W)&&!$1.has(h(W)))return!1;return C1(B)}function q_($,Z,J,Q,X){let K=TJ($,Z.effectiveCwd,Q,J);if(K===null)X?.recordSegment({type:"cwd-change",segment:$.words.map(S).join(" "),effectiveCwdNowUnknown:!0});if(K!==void 0)Z.effectiveCwd=K}function b2($){return{effectiveCwd:$.effectiveCwd,shellGitContextState:uJ($.shellGitContextState),literalHeredocFiles:new Map($.literalHeredocFiles),functionDefinitions:new Map($.functionDefinitions)}}function O3($){let Z=[];for(let J of $){if(!Z.some((Q)=>U_(Q,J)))Z.push(J);if(Z.length>cj)throw new P1}return Z}function U_($,Z){return $.effectiveCwd===Z.effectiveCwd&&I2($.literalHeredocFiles,Z.literalHeredocFiles)&&I2($.functionDefinitions,Z.functionDefinitions)&&I2($.shellGitContextState.effectiveEnvAssignments,Z.shellGitContextState.effectiveEnvAssignments)&&I2($.shellGitContextState.shellAssignments,Z.shellGitContextState.shellAssignments)&&H_($.shellGitContextState.exportedNames,Z.shellGitContextState.exportedNames)&&$.shellGitContextState.allexport===Z.shellGitContextState.allexport&&$.shellGitContextState.keywordExport===Z.shellGitContextState.keywordExport}function I2($,Z){if($===Z)return!0;if(!$||!Z||$.size!==Z.size)return!1;return[...$].every(([J,Q])=>Z.get(J)===Q&&Z.has(J))}function G_($,Z){let J=O4($);return J===void 0?void 0:Z.get(J)}function H_($,Z){return $.size===Z.size&&[...$].every((J)=>Z.has(J))}function j_($,Z){if(!Z)return null;return{reason:Z.reason,segment:$,ruleId:Z.id,intent:Z.intent}}function __($,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 y9($,Z){let J=T(q2($,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 sJ($,Z){let J={type:"strict-unparseable",rawCommand:$,reason:V0};if(Z.trace?.currentSegmentIndex===void 0)Z.trace?.recordGlobal(J);else Z.trace.recordSegment(J)}function Cz($,Z){return v9($,Z)}function v9($,Z,J,Q){let X=w9($,0,{...Z,...T7(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}]}}function oJ($,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 u9=[{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"}],N3={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},O_=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],L_=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],h9=[{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"]},...L_.flatMap(($)=>O_.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 V3=[{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"]}],tJ=[{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"}],M_=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],g9=tJ.map(($)=>({id:`secret.variant.${$.slug}.separator`,category:"Variant",label:`${$.label}-* / ${$.label}_*`,description:`Blocks ${$.label} variants with dash or underscore suffixes.`,prefix:$.prefix})),k9=tJ.flatMap(($)=>M_.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}))),f2={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)$/},x9=["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:$})),l9=[{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?$/}],eJ=[...u9,N3,...h9,...g9,...k9,f2,...x9,...l9,...V3].map(($)=>({id:$.id,category:$.category,label:$.label,...$.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in $?{paths:$.paths}:{description:$.description}})),$Q=new Set(V3.flatMap(($)=>$.category==="Coding CLI config"?[$.id]:[])),F_=eJ.map(($)=>$.id),R3=new Set(F_);import{createRequire as N_}from"node:module";var ZQ=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var P2=64,QQ="Rule config exceeds CC Safety Net's safe source limit.";var JQ=Object.freeze({maxSources:64,concurrency:4,maxRequests:131,maxResponseBytes:67108864});function D3($={}){return{requests:0,responseBytes:0,maxRequests:$.maxRequests??JQ.maxRequests,maxResponseBytes:$.maxResponseBytes??JQ.maxResponseBytes}}function z3($){return{controller:new AbortController,budget:D3(),resolveUrl:$}}function XQ($){if($.requests>=$.maxRequests)throw Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");$.requests++}function KQ($,Z){if(Z>$.maxResponseBytes-$.responseBytes)throw $.responseBytes+=Z,Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");$.responseBytes+=Z}var V_=N_(import.meta.url),YQ,R_=Array(P2+1).fill("over-limit"),BQ=/^[^/]+\/[^/]+$/,D_=/^sha256:[a-f0-9]{64}$/,b3=`must be an integer between ${p3} and ${c3}`,z_=["version","rules","overrides","transparent_wrappers"],b_=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function WQ($){if(!E1($)||!Array.isArray($.rules)||$.rules.length<=P2)return $;return{$schema:$.$schema,version:$.version,rules:R_,overrides:$.overrides,transparent_wrappers:$.transparent_wrappers}}function I_(){let $=V_("../vendor/zod.cjs"),Z=(F)=>{let R=$.superRefine(F);return R._zod.def.when=()=>!0,R},J=$.enum(ZQ),Q=$.union([$.literal("off"),$.looseObject({reason:$.string({error:"required non-empty string"}).min(1,"required non-empty string").max(Y$,`must be at most ${Y$} 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"),K=$.string({error:"must be a command string"}).regex(T0,"must match command pattern").describe("Command name such as 'git', 'docker', or 'rtk'."),Y=$.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(P2,QQ).default([]).describe("Rulebook source strings such as project-rules or owner/repo#main/team-rules"),overrides:$.record($.string().meta({pattern:BQ.source}),Q).default({}).describe("Rule overrides by id"),transparent_wrappers:$.array(K,{error:"must be an array of command strings"}).default([]).describe("Commands that transparently execute a visible protected child command")}),B=(F,R)=>{if(!E1(F))return;if(Array.isArray(F.rules)&&F.rules.length<=P2){let I=new Set;F.rules.forEach((C,y)=>{if(typeof C!=="string"||C==="")return;if(C.trim()===""){R.addIssue({code:"custom",message:"must be a non-empty rulebook source string",path:["rules",y]});return}let w=m$(C);if(w){R.addIssue({code:"custom",message:w,path:["rules",y]});return}if(I.has(C)){R.addIssue({code:"custom",message:`duplicate rulebook source "${C}"`,path:["rules",y]});return}I.add(C)})}if(E1(F.overrides))for(let I of Object.keys(F.overrides)){if(BQ.test(I))continue;R.addIssue({code:"custom",message:"must use <rulebook-name>/<rule-name>",path:["overrides",I]})}if(!Array.isArray(F.transparent_wrappers))return;let b=new Set;F.transparent_wrappers.forEach((I,C)=>{if(typeof I!=="string"||!T0.test(I))return;if(b.has(I)){R.addIssue({code:"custom",message:`duplicate command "${I}"`,path:["transparent_wrappers",C]});return}if(E7(I)){R.addIssue({code:"custom",message:`reserved command "${I}" cannot be a wrapper`,path:["transparent_wrappers",C]});return}b.add(I)})},W=$.preprocess(WQ,Y.check($.superRefine(B))),q=$.preprocess(WQ,Y.check(Z(B))),U=$.strictObject({fail_closed:$.boolean().optional(),paranoid_rm:$.boolean().optional(),paranoid_interpreters:$.boolean().optional()}),H=(F,R)=>$.intersection($.record($.string().refine((b)=>F.has(b),{error:(b)=>`unknown ${R} rule id "${String(b.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,b)=>{if(!Array.isArray(R))return;let I=X$();R.forEach((C,y)=>{if(typeof C!=="string")return;let w=F(C,I);if(w)b.addIssue({code:"custom",message:w,path:[y]})})})),G=$.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:H(s2,"destructive command").optional(),allow_paths:j(n4).optional()}).optional(),secret_protection:$.strictObject({enabled:$.boolean().optional(),overrides:H(R3,"secret protection").optional(),deny_paths:j(a4).optional()}).optional(),audit:$.strictObject({retention_days:$.number({error:b3}).int(b3).min(p3,b3).max(c3,b3).optional().describe("Days of audit log history to keep before the sweep deletes it")}).optional()}),_=(F)=>{let R=(y,w)=>F==="legacy"?y:w,b=R("must match pattern (letters, numbers, hyphens, underscores)","must match command pattern"),I=`required non-empty string up to ${Y$} characters`,C=$.looseObject({name:$.string({error:"required string"}).regex(z1,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(T0,R(b,"required string matching command pattern")),subcommand:$.string({error:R("must be a string if provided","must match command pattern")}).regex(T0,b).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",I)}).refine((y)=>y!=="",{error:R("must not be empty",I)}).refine((y)=>y.length<=Y$,{error:R(`must be at most ${Y$} characters`,I)}),intent:J.optional()},{error:"must be an object"});return $.array(C,{error:R("must be an array","required array")}).check(Z((y,w)=>{if(!Array.isArray(y))return;let k=new Set;y.forEach((B1,P)=>{let v=E1(B1)?B1.name:void 0;if(typeof v!=="string")return;if(k.has(v.toLowerCase())){w.addIssue({code:"custom",message:`duplicate rule name "${v}"`,path:[P,"name"]});return}k.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(!E1(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(z1,"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(T0,"must match command pattern"),{error:"required array"}).check(Z((F,R)=>{if(!Array.isArray(F))return;let b=new Set;F.forEach((I,C)=>{if(typeof I!=="string"||!T0.test(I))return;if(b.has(I)){R.addIssue({code:"custom",message:`duplicate command "${I}"`,path:[C]});return}b.add(I)})})),rules:_("rulebook"),tests:$.array(L,{error:"must be an array if provided"}).optional()}).check(Z((F,R)=>{if(!E1(F))return;let b=new Set(m9(F));if(Array.isArray(F.tests)){let C=new Set(F.tests.flatMap((y)=>E1(y)&&y.expect==="blocked"&&typeof y.rule==="string"?[y.rule]:[]));for(let y of C){if(b.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 I=new Set(F.allowed_commands.filter((C)=>typeof C==="string"));F.rules.forEach((C,y)=>{let w=E1(C)?C.command:void 0;if(typeof w!=="string"||I.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(D_,"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(!E1(F.input))return"must be an object";let R=F.input.kind;return typeof R==="string"?`unknown kind "${R}"`:"required string"}})))});return{RulesConfigSchema:W,RulesConfigDiagnosticSchema:q,RuleOverrideSchema:Q,UserPolicySchema:G,LegacyConfigSchema:O,RulebookSchema:D,RulesLockfileSchema:A}}function f$(){return YQ??=I_(),YQ}function qQ(){return f$().RulesConfigSchema}function f_(){return f$().UserPolicySchema}function dz(){return f$().LegacyConfigSchema}function UQ(){return f$().RulebookSchema}function GQ(){return f$().RulesLockfileSchema}function m9($){let Z=E1($)?$.rules:void 0;return(Array.isArray(Z)?Z:[]).flatMap((J)=>{let Q=E1(J)?J.name:void 0;return typeof Q==="string"?[Q]:[]})}function HQ($){let Z=f$().RulesConfigDiagnosticSchema.safeParse($);if(Z.success)return{errors:[],sources:new Set(Z.data.rules)};return{errors:P$(_Q(Z.error.issues,z_)),sources:E_($,Z.error.issues)}}function C2($){let Z=f_().safeParse($);if(Z.success)return[];return P$(_Q(Z.error.issues,b_)," ")}function P$($,Z=": ",J=" "){return[...new Set($.flatMap((Q)=>jQ(Q,Z,J,[])))]}function jQ($,Z,J,Q){let X=[...Q,...$.path],K=A_(X);if($.code==="unrecognized_keys")return $.keys.map((Y)=>`${K?`${K}.`:""}unknown field "${Y}"`);if($.code==="invalid_key")return $.issues.map((Y)=>Y.message);if($.code==="invalid_union"){let Y=$.errors.flat().filter((B)=>B.path.length>0);if(Y.length>0)return Y.flatMap((B)=>jQ(B,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[`${K}${X.length===1?J:Z}${P_($)}`]}function P_($){if($.code==="invalid_value")return`must be ${C_($.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 C_($){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 A_($){return $.map((Z,J)=>{if(typeof Z==="number")return`[${Z}]`;return J===0?String(Z):`.${String(Z)}`}).join("")}function _Q($,Z){let J=$.map((K)=>K.path[1]),Q=[...new Set(J.filter((K)=>typeof K==="string"))],X=(K,Y)=>[K.path.length===0?-1:Z.indexOf(String(K.path[0])),typeof Y==="number"?Y:Q.indexOf(String(Y)),K.code==="custom"?0:1];return $.map((K,Y)=>({issue:K,rank:X(K,J[Y])})).sort((K,Y)=>K.rank[0]-Y.rank[0]||K.rank[1]-Y.rank[1]||K.rank[2]-Y.rank[2]).map((K)=>K.issue)}function E_($,Z){let J=E1($)?$.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,K)=>typeof X==="string"&&!Q.has(K)))}function E1($){return!!$&&typeof $==="object"&&!Array.isArray($)}var OQ={version:1,rules:[],overrides:{},transparent_wrappers:[]};function T_($){return HQ($)}function C$($){try{let Z=X0(LQ($));if(Z===null)return{config:null,errors:[]};if(!Z.trim())return{config:null,errors:["Config file is empty"]};let J=JSON.parse(Z),Q=T_(J);if(Q.errors.length>0)return{config:null,errors:Q.errors};let X=qQ().parse(J);return{config:{version:1,rules:X.rules??[],overrides:X.overrides??{},transparent_wrappers:X.transparent_wrappers??[]},errors:[]}}catch(Z){if(Z instanceof u)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 oz($){let Z=C$($);if(Z.errors.length>0)return{ok:!1,result:{ok:!1,errors:Z.errors,warnings:[],entries:[]}};return{ok:!0,config:Z.config??OQ}}function tz($,Z=[]){I3($,{version:1,rules:Z,overrides:{},transparent_wrappers:[]})}function ez($,Z="project-rules"){I3($,{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 I3($,Z,J,Q){GZ(LQ($),`${JSON.stringify(Z,null,2)}
|
|
61
|
-
`,J,Q)}function LQ($){return typeof $==="string"?u2($):$}import{chmodSync as S_,existsSync as p9,mkdirSync as y_,readFileSync as c9}from"node:fs";import{dirname as NQ,join as w_}from"node:path";var v_=new Set(["standard","strict","paranoid"]),P3={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:[]},audit:{retention_days:p2}};function T$($){return w_(NQ(K0($)),x2)}function Hb($={}){let Z=T$($);if(!p9(Z))return{path:Z,exists:!1,raw:"",policy:A$(),errors:[]};let J=c9(Z,"utf-8");if(!J.trim())return{path:Z,exists:!0,raw:J,policy:A$(),errors:["Config file is empty"]};try{let Q=JSON.parse(J),X=C2(Q);return{path:Z,exists:!0,raw:J,policy:X.length>0?A$():E$(Q),errors:X}}catch(Q){return{path:Z,exists:!0,raw:J,policy:A$(),errors:[`Invalid JSON: ${Q instanceof Error?Q.message:String(Q)}`]}}}function f3($,Z={}){let J=T$(Z),Q=C2($),X=Q.length>0?A$():E$($);if(Q.length>0)return{path:J,policy:X,errors:Q};return y_(NQ(J),{recursive:!0,mode:448}),I3(J,X,384),S_(J,384),{path:J,policy:X,errors:[]}}function jb($){let Z=C2($);if(Z.length>0)return{errors:Z};return{preview:u_(E$($)),errors:[]}}function u_($){let Z=c4({safety:DQ($.safety)}),J=n3({destructiveCommandProtectionEnabled:$.destructive_command_protection.enabled,destructiveCommandRuleOverrides:$.destructive_command_protection.overrides},Z.capabilities),Q=Object.values(J),X=Q.filter((Y)=>Y.source!=="catastrophic"),K=Object.values($.destructive_command_protection.overrides);return{selectedPreset:$.safety.level,effectiveLevel:Z.effectiveLevel,capabilities:Z.capabilities,rules:J,counts:{enabled:X.filter((Y)=>Y.enabled).length,disabled:X.filter((Y)=>!Y.enabled).length,explicitOn:K.filter((Y)=>Y==="on").length,explicitOff:K.filter((Y)=>Y==="off").length,effectiveCustomizations:Q.filter((Y)=>Y.changesInherited).length,inheritedRequiresStrict:Q.filter((Y)=>!Y.enabled&&!Y.override&&Y.activationCapability==="fail_closed").length,inheritedRequiresParanoid:Q.filter((Y)=>!Y.enabled&&!Y.override&&(Y.activationCapability==="paranoid_rm"||Y.activationCapability==="paranoid_interpreters")).length}}}function _b($={}){let Z=T$($);if(!p9(Z))return f3(P3,$);let J=c9(Z,"utf-8");if(!J.trim())return f3(P3,$);try{return f3(E$(JSON.parse(J)),$)}catch{return f3(P3,$)}}function VQ($={}){let Z=k_(T$($));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 E$($){if(!J0($))return A$();let Z=J0($.safety)?$.safety:{},J=J0(Z.overrides)?Z.overrides:{},Q=J0($.workflow)?$.workflow:{},X=J0($.destructive_command_protection)?$.destructive_command_protection:{},K=J0($.secret_protection)?$.secret_protection:{};return{version:1,safety:{level:v_.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:MQ(X.overrides,s2),allow_paths:g_(X.allow_paths)},secret_protection:{enabled:typeof K.enabled==="boolean"?K.enabled:!0,overrides:MQ(K.overrides,R3),deny_paths:h_(K.deny_paths)},audit:{retention_days:c2(J0($.audit)?$.audit.retention_days:void 0)}}}function MQ($,Z){if(!J0($))return{};return Object.fromEntries(Object.entries($).flatMap(([J,Q])=>Z.has(J)&&(Q==="on"||Q==="off")?[[J,Q]]:[]))}function h_($){if(!Array.isArray($))return[];let Z=X$();return $.filter((J)=>a4(J,Z)===null)}function g_($){if(!Array.isArray($))return[];let Z=X$();return $.filter((J)=>n4(J,Z)===null)}function J0($){return!!$&&typeof $==="object"&&!Array.isArray($)}function A$(){return structuredClone(P3)}function k_($){let Z=x_();if(!p9($)){let J=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!J0(J))return{policy:Z,errors:[]};return{policy:FQ(E$(J)),errors:[]}}try{let J=c9($,"utf-8");if(!J.trim())return{policy:Z,errors:[`${$}: Config file is empty`],fallback:"defaults"};let Q=JSON.parse(J),X=C2(Q),K=FQ(E$(Q));if(X.length>0)return{policy:K,errors:X.map((Y)=>`${$}: ${Y}`),fallback:J0(Q)?"salvaged":"defaults"};return{policy:K,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 RQ($){let Z=Object.entries($),J=new Set(Z.flatMap(([Q,X])=>X==="on"?[Q]:[]));return new Set([...[...$Q].filter((Q)=>!J.has(Q)),...Z.flatMap(([Q,X])=>X==="off"?[Q]:[])])}function x_(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:RQ({}),denyPaths:[]}}}function FQ($){return{safety:DQ($.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:RQ($.secret_protection.overrides),denyPaths:[...$.secret_protection.deny_paths]}}}function DQ($){return{level:$.level,overrides:{failClosed:$.overrides.fail_closed,paranoidRm:$.overrides.paranoid_rm,paranoidInterpreters:$.overrides.paranoid_interpreters}}}import{dirname as d9}from"node:path";var fQ="This path contains the protected policy config and you must not modify or delete it.",l_=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function PQ($){let Z=y0(B0()),J=s_($.invocation.context.executionCwd,Z);if($.invocation.route.kind==="patch")return zQ($.paths.map((X)=>X.raw),!1,$.invocation.context.executionCwd,J,Z);let Q=_1($,"input-candidate");if($.invocation.route.kind==="command")return Q?bQ(Q.shell,$.invocation.context.executionCwd,J,Z):null;if($.invocation.route.kind==="unknown"&&Q){let X=bQ(Q.shell,$.invocation.context.executionCwd,J,Z);if(X)return X}return zQ($.paths.map((X)=>X.raw),$.invocation.route.kind==="grep"||$.invocation.route.kind==="glob"||t2($.invocation.toolName),$.invocation.context.executionCwd,J,Z)}function zQ($,Z,J,Q,X){if(Z)return null;let K=$.find((Y)=>A2(Y,J,Q,X));return K?{target:K}:null}function bQ($,Z,J,Q){let X=P4($,Z,Q,{findSegmentTarget:(K,Y)=>m_(K,Y,J,Q)?.target??null,isRedirectionTarget:(K,Y)=>A2(K,Y.cwd,J,Q),findMalformedTarget:(K)=>i_(K,Z,J,Q)?.target??null,normalizeCwd:K1});return X?{target:X}:null}function m_($,Z,J,Q){if(Z2($))return null;let X=Q.environment,K=I1([...$],X),Y=h(K[0]??"").toLowerCase(),B=K.slice(1);if(Y==="rm"&&p_(B)){let W=c_(B).find((q)=>IQ(L1(q,Z.variables),Z.cwd,J,Q));if(W)return{target:W}}if(Y==="find"){if($3(K,1)||Z9(K,X)){let q=(e4(g(K))??g(["."])).find((U)=>{let H=L1(U.text,Z.variables);return A2(H,Z.cwd,J,Q)||IQ(H,Z.cwd,J,Q)})?.text;if(q)return{target:q}}}if(Y==="mv"){let W=C4(B).sources.find((q)=>r_(L1(q,Z.variables),Z.cwd,J,Q));if(W)return{target:W}}if(d_($,X))return null;for(let W of $)for(let q of CQ(W))if(A2(L1(q,Z.variables),Z.cwd,J,Q))return{target:q};return null}function p_($){return $.some((Z)=>Z==="--recursive"||Z.startsWith("-")&&!Z.startsWith("--")&&/[rR]/.test(Z.slice(1)))}function c_($){let Z=$.indexOf("--");if(Z!==-1)return[...$.slice(0,Z).filter((J)=>!J.startsWith("-")),...$.slice(Z+1)];return $.filter((J)=>!J.startsWith("-"))}function d_($,Z){let J=I1([...$],Z);if(J.length===0)return!1;let Q=h(J[0]??"").toLowerCase();if(!l_.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 i_($,Z,J,Q){for(let X of $.split(/\s+/))for(let K of CQ(X))if(A2(K,Z,J,Q))return{target:K};return null}function CQ($){let Z=$.trim().replace(/^['"]|['"]$/g,""),J=Z.indexOf("=");return J===-1||J===Z.length-1?[Z]:[Z,Z.slice(J+1)]}function s_($,Z){let J=K1(T$(),$,Z),Q=d9(J),X=new Set;for(let K=Q;;K=d9(K))if(X.add(S$(K)),d9(K)===K)break;return{file:S$(J),directory:S$(Q),directoryAndAncestors:X}}function A2($,Z,J,Q){return S$(K1($,Z,Q))===J.file}function IQ($,Z,J,Q){return J.directoryAndAncestors.has(S$(K1($,Z,Q)))}function r_($,Z,J,Q){let X=S$(K1($,Z,Q));return X===J.file||J.directoryAndAncestors.has(X)}function S$($){return process.platform==="win32"?$.toLowerCase():$}import{homedir as n_}from"node:os";import{isAbsolute as s9,resolve as hQ}from"node:path";import{fileURLToPath as a_}from"node:url";var gQ="Access to a sensitive path is not allowed.",kQ=new Set(["echo","printf"]),o_=new Set(["find"]),t_=new Set(["-exec","-execdir"]),e_=new Set([";","+"]),$O=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),ZO=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),JO=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),QO=new Set(["node","bun"]),XO=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),KO=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"]),xQ=new Set(["-c","-e","-r","-E","--eval","--exec"]),YO=new Set(["src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js"]),BO=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"])]]),WO=new Set(["grep","rg"]),AQ="f",EQ="file",qO="files",UO=new Set(["e","f"]),GO=new Set(["regexp","file"]),HO=new Set(["e","f","A","B","C","m"]),jO=new Set(["regexp","file","after-context","before-context","context","max-count"]),_O=new Set(["|","|&"]),i9="__CC_SAFETY_NET_PIPE_INPUT__",lQ=new Set(["bash","sh","zsh","dash","ksh"]),OO=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 TQ($,Z,J,Q,X){let K=d$();for(let Y of $){if(eO(Y,Z,J?.denyPaths??[],Q,K))return{target:Y,ruleId:"secret.deny-path"};if(X&&!X.has(Y))continue;let B=oO(Y,Z,J,K);if(B)return{target:Y,ruleId:B}}return null}function mQ($,Z,J={}){let Q=SQ($),X=TQ(Q,$.invocation.context.executionCwd,Z,$.invocation.context.configCwd),K=X?.ruleId!=="secret.deny-path"&&J.strict===!1?SQ($,{refineJavaScriptInlineData:!0}):Q,Y=K.length===Q.length?X:TQ(Q,$.invocation.context.executionCwd,Z,$.invocation.context.configCwd,new Set(K));if(Y?.ruleId!=="secret.deny-path"&&J.strict===!1&&LO($))return null;return Y}function LO($){if($.invocation.route.kind!=="command")return!1;let Z=_1($,"input-candidate")??_1($,"declared-command");if(!Z)return!1;if(Z.program.nodes.some((Y)=>Y.kind==="command"&&Y.nested.length>0))return!1;let J=[];for(let Y of Z.shell.entries){if(Y.kind==="operator"&&Y.boundary)return!1;if(Y.kind==="redirection")return!1;if(Y.kind!=="operator")J.push(d1(Y.text))}let Q=w$(J);if(Q.length===0)return!1;let X=o0(Q[0]??"").toLowerCase(),K=Q.slice(1);if(X==="test")return K.length===2&&(K[0]==="-e"||K[0]==="-f");if(X!=="find")return!1;return!K.some((Y)=>$O.has(Y))}function SQ($,Z={}){if($.invocation.route.kind==="command"){let Q=_1($,"input-candidate");return Q?S2(Q.shell,$.store,Z):[]}if($.invocation.route.kind!=="unknown")return $.paths.map((Q)=>Q.raw);let J=_1($,"input-candidate");return[...J?S2(J.shell,$.store,Z):[],...$.paths.map((Q)=>Q.raw)]}function S2($,Z,J){if($.status==="structural-limit")throw new z0;if($.status==="unclosed-quote")return[];if($.status==="invalid")throw Error("Unable to parse command for secret protection");let Q=[...$.assignmentFallbacks,...uO(d1($.source),Z,J)],X=[],K=null;for(let Y of $.entries){if(Y.kind==="operator"){if(!Y.boundary)continue;if(X.length>0){if(Q.push(...C3(X,Z,J)),K!==null)Q.push(...yQ(K,X,Z,J));K=_O.has(Y.operator)?X:null,X=[]}else K=null;continue}if(Y.kind==="redirection"){let B=Y.target?d1(Y.target):void 0;if(B&&Y.targetOrder==="legacy-segment")X.push(B);else if(B)Q.push(B);continue}X.push(d1(Y.text))}if(X.length>0){if(Q.push(...C3(X,Z,J)),K!==null)Q.push(...yQ(K,X,Z,J))}return Q}function C3($,Z,J){let Q=fO($),X=w$($);if(X.length===0)return Q;let K=X[0]??"",Y=o0(K).toLowerCase(),B=X.slice(1),W=MO(K,Y,B);if(W)return[...Q,...W];if(kQ.has(Y))return Q;if(WO.has(Y))return[...Q,...cO(B)];if(o_.has(Y))return[...Q,...PO(B,Z,J)];if(F1.has(Y))return[...Q,...B.flatMap((q)=>wQ("awk",q)),...B.flatMap((q)=>AO(q,Z,J)),...B.flatMap(EO)];if(dQ(Y)){if(lQ.has(Y)){let q=Y7(Y,B);if(q!==null&&Z.getShellSyntax(q).status==="structural-limit")throw new z0}return[...Q,...CO(Y,B,J)]}return[...Q,...B.flatMap((q)=>wQ(Y,q))]}function MO($,Z,J){let Q=Z==="cc-safety-net"&&J[0]==="explain",X=(Z==="bun"||Z==="node")&&FO(J[0])&&J[1]==="explain";if(!Q&&!X)return null;let K=X?[$,J[0]??""]:[$],Y=J.slice(X?2:1);for(let B=0;B<Y.length;B++){let W=Y[B];if(W==="--json"||W==="--help"||W==="-h")continue;if(W==="--cwd"){let q=Y[B+1];if(q&&!q.startsWith("--"))K.push(q);B++;continue}return K}return K}function FO($){let Z=$?.replaceAll("\\","/");return[...YO].some((J)=>Z===J||Z?.endsWith(`/${J}`))}function yQ($,Z,J,Q){if(zO(Z,J,Q))return NO($);let X=bO(Z);if(X===null)return[];return VO($).flatMap((K)=>lQ.has(X)?S2(J.getShellSyntax(K),J,Q):sQ(K))}function NO($){let Z=w$($);if(Z.length===0)return[];let J=o0(Z[0]??"").toLowerCase();if(!kQ.has(J))return[];return Z.slice(1)}function VO($){let Z=w$($);if(Z.length===0)return[];let J=o0(Z[0]??"").toLowerCase(),Q=Z.slice(1);if(J==="echo"){let X=Q.findIndex((K)=>!/^-[neE]+$/.test(K));return[(X===-1?[]:Q.slice(X)).join(" ")]}if(J==="printf")return RO(Q);return[]}function RO($){let Z=$[0];if(Z===void 0)return[];let J=(Z.match(/%%|%[bqs]/g)??[]).filter((X)=>X!=="%%").length;if(J===0||$.length===1)return[pQ(Z)];let Q=$.slice(1);return Array.from({length:Math.ceil(Q.length/J)},(X,K)=>DO(Z,Q.slice(K*J,(K+1)*J)))}function DO($,Z){let J=0;return pQ($.replace(/%%|%[bqs]/g,(Q)=>{if(Q==="%%")return"%";let X=Z[J]??"";return J++,X}))}function pQ($){return $.replace(/\\n/g,`
|
|
62
|
-
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function zO($,Z,J){let Q=w$($);if(Q.length===0||o0(Q[0]??"").toLowerCase()!=="xargs")return!1;let X=i0(Q),K=Q.slice(X.childStart);if(K.length===0)return!1;if(X.replacementToken==="")return!1;let Y=X.replacementToken,B=Y===null?[...K,i9]:K.map((W)=>W.split(Y).join(i9));return C3(B,Z,J).some((W)=>W.includes(i9))}function bO($){let Z=w$($);if(Z.length===0)return null;let J=o0(Z[0]??"").toLowerCase();if(!dQ(J))return null;return IO(J,Z.slice(1))?J:null}function IO($,Z){let J=cQ($);for(let Q=0;Q<Z.length;Q++){let X=Z[Q];if(X===void 0)break;if(xQ.has(X)||iQ($,X)||/^--(?:eval|exec)=/.test(X))return!1;if(X==="-")return!0;if(X.startsWith("-")){if(J==="python"&&X==="-m")return!1;if(OO.get(J)?.has(X))Q++;continue}return!1}return!0}function cQ($){return/^python\d/.test($)?"python":$}function fO($){let Z=[];for(let J of $){if(aQ(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 wQ($,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 PO($,Z,J){let Q=$.findIndex((K)=>K.startsWith("-")||K==="("||K==="!"||K===";"),X=[...$.slice(0,Q===-1?$.length:Q)];for(let K=0;K<$.length;K++){if(!t_.has($[K]??""))continue;let Y=$.slice(K+1),B=Y.findIndex((U)=>e_.has(U)),W=B===-1?Y:Y.slice(0,B),q=C3(W,Z,J);if(X.push(...q.filter((U)=>U!=="{}")),!q.includes("{}"))continue;X.push(...$.slice(0,K).flatMap((U,H,j)=>{if(!ZO.has(U))return[];let G=j[H+1];return G===void 0?[]:[G,G.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return X}function dQ($){return JO.has($)||/^python\d/.test($)}function CO($,Z,J){let Q=[];for(let X=0;X<Z.length;X++){let K=Z[X];if(K===void 0)break;if(xQ.has(K)||iQ($,K)){let B=Z[X+1];if(B!==void 0)Q.push(...vQ($,B,J)),X++;continue}let Y=/^--(?:eval|exec)=(.*)$/.exec(K);if(Y!==null&&Y[1]!==void 0){Q.push(...vQ($,Y[1],J));continue}if(!K.startsWith("-"))Q.push(K)}return Q}function iQ($,Z){if(!Z.startsWith("-")||Z.startsWith("--")||Z.length<=2)return!1;return BO.get(Z[Z.length-1]??"")?.has(cQ($))??!1}function AO($,Z,J){if(!$.includes("system"))return[];return h6($)?.commands.flatMap((Q)=>S2(Z.getShellSyntax(Q),Z,J))??[]}function EO($){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 sQ($){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(rQ),...J]}function vQ($,Z,J){let Q=sQ(Z);if(!J.refineJavaScriptInlineData||!QO.has($)||Q.length===0)return Q;let X=TO(Z);return X!==null&&!yO(X)?[]:Q}function TO($){let Z=$.split("");for(let J=0;J<$.length;J++){let Q=$[J];if(Q!=="'"&&Q!=='"'&&Q!=="`")continue;if(Q==="`"&&SO($,J))return null;Z[J]=" ";let X=!1;for(let K=J+1;K<$.length;K++){let Y=$[K];if(Z[K]=" ",Y==="\\"){if(K++,K<$.length)Z[K]=" ";continue}if(Q==="`"&&Y==="$"&&$[K+1]==="{")return null;if(Q!=="`"&&(Y===`
|
|
63
|
-
`||Y==="\r"))return null;if(Y!==Q)continue;J=K,X=!0;break}if(!X)return null}return Z.join("")}function SO($,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 yO($){for(let Z of $.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let J=Z[0],Q=Z.index;if(XO.has(J.toLowerCase()))return!0;let X=J.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((K)=>K.toLowerCase());if(!X.some((K)=>KO.has(K)))continue;if(X.length>1)return!0;if(wO($,Q)===".")return!0;if(vO($,Q+J.length)==="(")return!0}return!1}function wO($,Z){for(let J=Z-1;J>=0;J--)if(!/\s/.test($[J]??""))return $[J];return}function vO($,Z){for(let J=Z;J<$.length;J++)if(!/\s/.test($[J]??""))return $[J];return}function uO($,Z,J){return lO($).flatMap((Q)=>{let X=Z.getShellSyntax(Q);if(X.status==="invalid")return[];return[...S2(X,Z,J),...hO(X)?gO(X):[]]})}function hO($){let Z=$.entries;for(let J=0;J<Z.length;J++){let Q=Z[J];if(Q?.kind!=="word"||o0(d1(Q.text)).toLowerCase()!=="base64")continue;for(let X=J+1;X<Z.length;X++){let K=Z[X];if(K?.kind==="operator")break;if(K?.kind!=="word")continue;let Y=d1(K.text);if(Y==="--decode"||!Y.startsWith("--")&&Y.startsWith("-")&&/[dD]/.test(Y))return!0}}return!1}function gO($){return $.entries.flatMap((Z)=>Z.kind==="word"?[d1(Z.text)]:Z.kind==="redirection"&&Z.target?[d1(Z.target)]:[]).flatMap(rQ)}function rQ($){let Z=xO($);if(Z===null)return[];let J=Buffer.from(Z,"base64").toString("utf8");if(J===""||kO(J))return[];return Buffer.from(J,"utf8").toString("base64").replace(/=+$/g,"")===Z.replace(/=+$/g,"")?[J]:[]}function kO($){return Array.from($).some((Z)=>{let J=Z.charCodeAt(0);return J<32||J===127})}function xO($){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 lO($){let Z=[],J={inSingle:!1,inDouble:!1,escaped:!1};for(let Q=0;Q<$.length;Q++){let X=$[Q];if(!X)break;if(r$(X,J))continue;if(nQ($,Q,J)){let K=mO($,Q+1);if(K!==null)Z.push(K.body),Q=K.endIndex;continue}if(!J.inSingle&&X==="`"){let K=pO($,Q);if(K!==null)Z.push(K.body),Q=K.endIndex}}return Z}function mO($,Z){let J={inSingle:!1,inDouble:!1,escaped:!1},Q=1;for(let X=Z+1;X<$.length;X++){let K=$[X];if(!K)break;if(r$(K,J))continue;if(nQ($,X,J)){Q++,X++;continue}if(!J.inSingle&&!J.inDouble&&K===")"){if(Q--,Q===0)return{body:$.slice(Z+1,X),endIndex:X}}}return null}function pO($,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 nQ($,Z,J){return!J.inSingle&&$[Z]==="$"&&$[Z+1]==="("&&$[Z+2]!=="("}function cO($){let Z=[],J=[],Q=!1,X=!1,K=!1;for(let W=0;W<$.length;W++){let q=$[W];if(q===void 0)break;if(!K&&q==="--"){K=!0;continue}if(K){J.push(q);continue}let U=/^--([^=]+)(?:=(.*))?$/.exec(q);if(U!==null){let H=U[1]??"",j=U[2];if(H===qO)X=!0;if(GO.has(H))Q=!0;if(j!==void 0){if(H===EQ)Z.push(j);continue}if(jO.has(H)){let G=$[W+1];if(H===EQ&&G!==void 0)Z.push(G);W++}continue}if(q.startsWith("-")&&q.length>1){let H=q.slice(1),j="",G="";for(let _=0;_<H.length;_++){let O=H[_]??"";if(UO.has(O))Q=!0;if(HO.has(O)){j=O,G=H.slice(_+1);break}}if(j!=="")if(G.length>0){if(j===AQ)Z.push(G)}else{let _=$[W+1];if(j===AQ&&_!==void 0)Z.push(_);W++}continue}J.push(q)}let B=!Q&&!X?J.slice(1):J;return[...Z,...B]}function w$($){let Z=$.findIndex((J)=>!aQ(J)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(J));return Z===-1?[]:[...$.slice(Z)]}function aQ($){return $==="env"||$==="command"||$==="builtin"||$==="sudo"}var dO=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),iO=".env.",sO=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),rO=[".env.example.",".env.sample."],nO=new Set(["node_modules","__pycache__"]),aO=[["vendor","bundle"],["vendor","cache"]];function oO($,Z,J,Q){let X=L0($,Z,Q);if(!X)return null;let K=e(X.split("/").pop()??""),Y=e(X);if(sO.has(K)||rO.some((q)=>K.startsWith(q)))return null;for(let q of h9){let U=q.suffixParts.join("/");if((Y===`~/${U}`||Y.startsWith(`~/${U}/`))&&O0(q.id,J))return q.id}let B=tO(X,Z,J,Q);if(B)return B;if(dO.has(K))return null;for(let q of u9)if(K===q.basename&&O0(q.id,J))return q.id;if(K.startsWith(iO)&&O0(N3.id,J))return N3.id;for(let q of g9)if(K.length>q.prefix.length&&K.startsWith(q.prefix)){let U=K.slice(q.prefix.length)[0];if((U==="-"||U==="_")&&O0(q.id,J))return q.id}for(let q of k9)if(K.length>q.prefix.length&&K.startsWith(q.prefix)){if(K.slice(q.prefix.length)===q.suffix&&O0(q.id,J))return q.id}if($L(Y))return null;if(!K.includes(".")&&f2.pattern.test(K)&&O0(f2.id,J))return f2.id;let W=ZL(K,J);if(W)return W;return null}function tO($,Z,J,Q){return V3.find((X)=>{if(!O0(X.id,J))return!1;switch(X.id){case"secret.cli.claude-code":return d($,s(process.env.CLAUDE_CONFIG_DIR,"~/.claude",Z,Q),[".credentials.json"]);case"secret.cli.claude-code.config":{let K=e($).split("/");return d($,s(process.env.CLAUDE_CONFIG_DIR,"~/.claude",Z,Q),["settings.json","settings.local.json"])||T2($,"~/.claude.json",Z,Q)||K.at(-1)==="settings.local.json"&&K.at(-2)===".claude"||K.at(-1)===".mcp.json"}case"secret.cli.antigravity":return d($,L0("~/.gemini/config",Z,Q),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let K=s(process.env.CODEX_HOME,"~/.codex",Z,Q);return d($,K,["auth.json",".credentials.json"])||E2($,K,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let K=s(process.env.CODEX_HOME,"~/.codex",Z,Q),Y=e($).split("/").at(-1)??"";return d($,K,["config.toml"])||Y.endsWith(".config.toml")&&d($,K,[Y])}case"secret.cli.gemini":return d($,Y1(s(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 K=e($).split("/"),Y=process.env.ProgramData?[Y1(s(process.env.ProgramData,"",Z,Q),"gemini-cli")]:[];return d($,Y1(s(process.env.GEMINI_CLI_HOME,"~",Z,Q),".gemini"),["settings.json","google_accounts.json"])||K.at(-1)==="settings.json"&&K.at(-2)===".gemini"||(process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH?.trim()?T2($,process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH,Z,Q):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...Y].some((B)=>d($,L0(B,Z,Q),["settings.json"]))}case"secret.cli.copilot-cli":{let K=s(process.env.COPILOT_HOME,"~/.copilot",Z,Q);return d($,K,["config.json"])||E2($,K,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return d($,s(process.env.COPILOT_HOME,"~/.copilot",Z,Q),["mcp-config.json"]);case"secret.cli.kimi-code":{let K=s(process.env.KIMI_CODE_HOME,"~/.kimi-code",Z,Q),Y=s(process.env.KIMI_SHARE_DIR,"~/.kimi",Z,Q);return d($,K,["server.token"])||E2($,K,["credentials"])||E2($,Y,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let K=["config.toml","mcp.json"],Y=e($).split("/");return Y.at(-1)==="mcp.json"&&Y.at(-2)===".kimi-code"||d($,s(process.env.KIMI_CODE_HOME,"~/.kimi-code",Z,Q),K)||d($,s(process.env.KIMI_SHARE_DIR,"~/.kimi",Z,Q),[...K,"config.json","config.json.bak"])}case"secret.cli.opencode":{let K=Y1(s(process.env.XDG_DATA_HOME,"~/.local/share",Z,Q),"opencode"),Y=e($).split("/").at(-1)??"",B=process.env.OPENCODE_DB?.trim(),W=B&&B!==":memory:"?[B,`${B}-wal`,`${B}-shm`]:[];return d($,K,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Y)&&d($,K,[Y])||W.some((q)=>T2($,q,Z,Q))}case"secret.cli.opencode.config":{let K=process.env.OPENCODE_CONFIG_DIR?s(process.env.OPENCODE_CONFIG_DIR,"~/.config/opencode",Z,Q):Y1(s(process.env.XDG_CONFIG_HOME,"~/.config",Z,Q),"opencode"),Y=process.env.ProgramData?[Y1(s(process.env.ProgramData,"",Z,Q),"opencode")]:[],B=["opencode.json","opencode.jsonc"];return B.includes(e($).split("/").at(-1)??"")||d($,K,B)||(process.env.OPENCODE_CONFIG?.trim()?T2($,process.env.OPENCODE_CONFIG,Z,Q):!1)||["/Library/Application Support/opencode","/etc/opencode",...Y].some((W)=>d($,L0(W,Z,Q),B))}case"secret.cli.pi":return d($,s(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",Z,Q),["auth.json"]);case"secret.cli.pi.config":return d($,s(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",Z,Q),["models.json"]);case"secret.cli.amp":{let K=L0("~",Z,Q);return[Y1(s(process.env.XDG_DATA_HOME,"~/.local/share",Z,Q),"amp"),Y1(K,".local","share","amp")].some((B)=>d($,B,["secrets.json"]))||E2($,Y1(K,".amp"),["oauth"])}case"secret.cli.amp.config":{let K=["settings.json","settings.jsonc"],Y=[Y1(s(process.env.XDG_CONFIG_HOME,"~/.config",Z,Q),"amp"),Y1(L0("~",Z,Q),".config","amp")],B=e($).split("/");return Y.some((W)=>d($,W,K))||B.at(-2)===".amp"&&K.includes(B.at(-1)??"")||(process.env.AMP_SETTINGS_FILE?.trim()?T2($,process.env.AMP_SETTINGS_FILE,Z,Q):!1)}case"secret.cli.cursor":{let K=Y1(s(process.env.XDG_CONFIG_HOME,"~/.config",Z,Q),"cursor"),Y=Y1(s(process.env.CURSOR_DATA_DIR,"~/.cursor",Z,Q),"projects");return d($,L0("~/.cursor",Z,Q),["auth.json"])||d($,K,["auth.json"])||e($).split("/").at(-1)==="mcp-auth.json"&&A3(e($),e(Y))}case"secret.cli.cursor.config":{let K=e($).split("/");return K.at(-1)==="mcp.json"&&K.at(-2)===".cursor"}default:return!1}})?.id??null}function s($,Z,J,Q){return L0($?.trim()?$:Z,J,Q)}function d($,Z,J){return J.some((Q)=>oQ($,Y1(Z,Q)))}function E2($,Z,J){return J.some((Q)=>A3(e($),e(Y1(Z,Q))))}function T2($,Z,J,Q){return oQ($,L0(Z,J,Q))}function oQ($,Z){return e($)===e(Z)}function Y1($,...Z){return y$([$,...Z].filter(Boolean).join("/"))}function eO($,Z,J,Q,X){if(J.length===0)return!1;let K=e(uQ($,Z,X));return J.some((Y)=>A3(K,e(uQ(Y,Q,X))))}function $L($){let Z=$.split("/");return Z.some((J)=>nO.has(J))||aO.some(([J,Q])=>Z.some((X,K)=>X===J&&Z[K+1]===Q))}function ZL($,Z){let J=$.lastIndexOf("."),Q=J>0&&J<$.length-1?$.slice(J+1):"";if(Q==="")return null;for(let X of x9)if(Q===X.extension&&O0(X.id,Z))return X.id;for(let X of l9)if(X.pattern.test(Q)&&O0(X.id,Z))return X.id;return null}function e($){return $.toLowerCase()}function O0($,Z){if(!Z?.disabledRules)return!0;if(Array.isArray(Z.disabledRules))return!Z.disabledRules.includes($);return!Z.disabledRules.has($)}function L0($,Z,J){let{home:Q,normalized:X}=tQ($,J);if(!X)return"";if(!Q)return X;let K=eQ(X,Q),Y=s9(K)?K:y$(hQ(Z,K)),B=y$(i(Y,R0,J));if(!A3(B,Q)){if(s9(K))return B;return B===Y?X:B}let W=B.slice(Q.length);return W?`~${W}`:"~"}function uQ($,Z,J){let{home:Q,normalized:X}=tQ($,J);if(!X)return"";let K=Q?eQ(X,Q):X;return y$(i(s9(K)?K:hQ(Z,K),R0,J))}function tQ($,Z){let J=process.env.HOME??n_(),Q=J?y$(i(J,R0,Z)):"",X=y$(JL(d1($)));return{home:Q,normalized:X}}function JL($){if(!$.trim().toLowerCase().startsWith("file:"))return $;try{return a_($)}catch{return $}}function eQ($,Z){if($==="~")return Z;if($.startsWith("~/"))return Y1(Z,$.slice(2));return $}function y$($){let Z=$.trim().replace(/\\/g,"/").replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(Z==="/")return Z;return Z.replace(/\/+$/g,"")}function A3($,Z){return $===Z||$.startsWith(Z.endsWith("/")?Z:`${Z}/`)}function o0($){return $.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??$}import{dirname as M0}from"node:path";var $X="Rulebook exceeds CC Safety Net's safe validation limits.",ZX="Additional rulebook validation errors were omitted.",l1=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function JX($){if(r9($.allowed_commands,l1.maxAllowedCommands)||r9($.rules,l1.maxRules)||r9($.tests,l1.maxTests))return!1;let{maxAggregateStringCodeUnits:Z,maxTotalBlockArgs:J}=l1,Q=(X,K=!1)=>{if(typeof X!=="string")return!0;if(X.length>l1.maxStringCodeUnits||K&&X.length>l1.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 K=X;if(!Q(K.name)||!Q(K.command)||!Q(K.subcommand)||!Q(K.reason)||!Q(K.intent))return!1;if(!Array.isArray(K.block_args))continue;if(K.block_args.length>l1.maxBlockArgsPerRule||K.block_args.length>J)return!1;J-=K.block_args.length;for(let Y of K.block_args)if(!Q(Y))return!1}if(Array.isArray($.tests))for(let X of $.tests){if(!X||typeof X!=="object")continue;let K=X;if(!Q(K.command,!0)||!Q(K.expect)||!Q(K.rule))return!1}return!0}function r9($,Z){return Array.isArray($)&&$.length>Z}function QL($){if(!XL($))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!JX($))return{errors:[$X],ruleNames:new Set};let Z=UQ().safeParse($),J=[...$.rulebook_version===1?[]:["rulebook_version must be 1"],...Z.success?[]:P$(Z.error.issues,": ",": ")];return{errors:J.length>l1.maxValidationErrors?[...J.slice(0,l1.maxValidationErrors),ZX]:J,ruleNames:new Set(m9($).map((Q)=>Q.toLowerCase()))}}function v$($){let Z=QL($);if(Z.errors.length>0)throw Error(Z.errors.join("; "));return $}function XL($){return!!$&&typeof $==="object"&&!Array.isArray($)}var KL=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#([A-Za-z0-9._-]+)$/;function E3($){if(J$($.spec))return BL($);return YL($)}function YL($){if(!z1.test($.spec))return`Local rulebook sources must be bare names matching ${z1}: ${$.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 BL($){let Z=m$($.spec);if(Z)return Z;let J=Z$($.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 ob($,Z,J){let Q=XX($.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 ${S1}`],warnings:[],entries:[]}};let X=new Set($.rules),K=Z.rulebooks.filter((Y)=>Y.name===J&&X.has(Y.spec)).map((Y)=>Y.spec);if(K.length===1)return{ok:!0,specs:K};return QX(J,K)}function tb($,Z,J){let Q=XX($,J);if(Q.length>0)return{ok:!0,specs:Q};let X=WL($,J);if(X.length>0)return{ok:!0,specs:X};let K=qL($,J);if(!K.ok)return K;if(K.specs.length>0)return{ok:!0,specs:K.specs};let Y=Z?$.filter((B)=>Z.rulebooks.find((W)=>W.spec===B)?.name===J):[];if(Y.length===1)return{ok:!0,specs:Y};return QX(J,Y)}function QX($,Z){return{ok:!1,result:{ok:!1,errors:Z.length===0?[`No configured rulebook matches ${$}`]:[`Ambiguous rulebook match ${$}: ${Z.join(", ")}`],warnings:[],entries:[]}}}function XX($,Z){return $.filter((J)=>J===Z)}function WL($,Z){let J=Z.match(KL),Q=J?.[1],X=J?.[2],K=J?.[3];if(!Q||!X||!K)return[];return YX($,(Y)=>{return Y.owner===Q&&Y.repo===X&&Y.ref===K})}function qL($,Z){if(!NZ(Z))return{ok:!0,specs:[]};let[J,Q]=Z.split("/"),X=YX($,(Y)=>{return Y.owner===J&&Y.repo===Q});if(new Set(X.map((Y)=>KX(Y)?.ref).filter((Y)=>!!Y)).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 KX($){try{return Z$($)}catch{return null}}function YX($,Z){return $.filter((J)=>{let Q=KX(J);return Q?Z(Q):!1})}function n9($){let Z=typeof $==="string"?$:$.path;try{let J=X0(typeof $==="string"?u2($):$);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 K=GQ().safeParse(X),Y=X.rulebooks.flatMap((W,q)=>{let U=K.success?[]:K.error.issues.filter((j)=>j.path[1]===q);if(U.length>0)return P$(U).map((j)=>`${Z}: ${j}`);let H=E3(W);return H?[`${Z}: rulebooks[${q}]: ${H}`]:[]});if(!K.success||Y.length>0)return{lock:null,errors:[`malformed lockfile ${Z}`,...Y]};return{lock:{version:1,rulebooks:K.data.rulebooks.map((W)=>{if(W.kind==="local-directory")return{spec:W.spec,kind:W.kind,path:W.path,name:W.name,version:W.version,digest:W.digest};let q={spec:W.spec,kind:W.kind,owner:W.owner,repo:W.repo,ref:W.ref,commit:W.commit,path:W.path,name:W.name,version:W.version,digest:W.digest};return typeof W.display_ref==="string"&&W.display_ref!==""?{...q,display_ref:W.display_ref}:q})},errors:[]}}catch(J){if(J instanceof u)return{lock:null,errors:[J.message]};return{lock:null,errors:["malformed lockfile"]}}}import{createHash as UL}from"node:crypto";import{dirname as T3,join as GL}from"node:path";var qX=Object.freeze({timeoutMs:15000,metadataBytes:524288,commitBytes:262144,treeBytes:16777216,rawBytes:4194304});async function BX($,Z,J,Q=D1(T3(T3(Z)),"rules policy"),X=z3()){if(J$($))return jL($,X);return HL($,Z,J,Q)}async function HI($,Z,J,Q,X,K=z3()){if(!J$($)||J.refresh)return BX($,Z,J,X,K);let Y=Q?.rulebooks.find((B)=>B.spec===$);if(!Y||Y.kind!=="github")return BX($,Z,J,X,K);return _L(Y,Z,J,X,K)}async function jI($,Z=z3()){let[J,Q]=$.split("/");if(!J||!Q)throw Error(`Invalid GitHub repository source: ${$}`);let X=await y2(`https://api.github.com/repos/${J}/${Q}`,"metadata",Z),K=X.response;if(!K.ok)throw Error(`Failed to inspect ${$}: GitHub returned ${K.status}`);let Y=JSON.parse(X.content);if(!Y.default_branch)throw Error(`Failed to inspect ${$}: missing default branch`);let B=await GX(J,Q,Y.default_branch,$,Z),W=await y2(`https://api.github.com/repos/${J}/${Q}/git/trees/${B}?recursive=1`,"tree",Z),q=W.response;if(!q.ok)throw Error(`Failed to inspect ${$}: GitHub tree returned ${q.status}`);let H=(JSON.parse(W.content).tree??[]).flatMap((j)=>{if(j.type!=="blob"||typeof j.path!=="string")return[];let G=j.path.match(l3);return G?.[1]?[G[1]]:[]}).sort();if(H.length===0)throw Error(`No rulebooks found in ${$} under ${k2}/`);return H.map((j)=>({spec:`${J}/${Q}#${B}/${j}`,display_ref:Y.default_branch}))}function HL($,Z,J,Q){m3($);let X=FL(Z,$),K=X0(X1(Q,X));if(K===null)throw Error(`Rulebook source not found: ${$}`);let Y=v$(a9(K,"Invalid local rulebook source."));if(Y.name!==$)throw Error(`rulebook name "${Y.name}" must match local source "${$}"`);return{rulebook:Y,content:K,entry:{spec:$,kind:"local-directory",path:$,name:Y.name,version:Y.version,digest:u$(K)}}}async function jL($,Z){let J=Z$($),Q=await GX(J.owner,J.repo,J.ref,$,Z),X=await y2(`https://raw.githubusercontent.com/${J.owner}/${J.repo}/${Q}/${J.path}`,"raw",Z),K=X.response;if(!K.ok)throw Error(`Failed to fetch ${$}: GitHub raw returned ${K.status}`);let Y=X.content,B=v$(a9(Y,"Invalid GitHub rulebook response."));if(B.name!==J.name)throw Error(`rulebook name "${B.name}" must match GitHub source "${J.name}"`);return{rulebook:B,content:Y,entry:{spec:$,kind:"github",owner:J.owner,repo:J.repo,ref:J.ref,commit:Q,path:J.path,name:B.name,version:B.version,digest:u$(Y)}}}async function _L($,Z,J,Q=D1(T3(T3(Z)),"rules policy"),X){let K=E3($);if(K)throw Error(`${K}; run ${S1}`);let Y=l2($,m2(Z,J)),B=X0(X1(Q,Y));if(B!==null){if(u$(B)===$.digest)return{entry:$,rulebook:UX(B,$),content:B}}return OL($,X)}async function OL($,Z){let J=await y2(`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(u$(X)!==$.digest)throw Error(`locked GitHub digest mismatch for ${$.spec}; run ${S1}`);return{entry:$,rulebook:UX(X,$),content:X}}function UX($,Z){let J=v$(a9($,"Invalid cached rulebook."));if(J.name!==Z.name)throw Error(`rulebook name "${J.name}" must match lock entry "${Z.name}"`);return J}function a9($,Z){try{return JSON.parse($)}catch{throw Error(Z)}}async function GX($,Z,J,Q,X){let K=await y2(`https://api.github.com/repos/${$}/${Z}/commits/${encodeURIComponent(J)}`,"commit",X),Y=K.response;if(!Y.ok)throw Error(`Failed to resolve ${Q}: GitHub returned ${Y.status}`);let B=JSON.parse(K.content);if(!B.sha)throw Error(`Failed to resolve commit for ${Q}`);return B.sha}async function LL($,Z,J={}){if(J.signal?.aborted)throw J.signal.reason;let Q=J.budget??D3(),X=new AbortController,K=()=>X.abort(J.signal?.reason);J.signal?.addEventListener("abort",K,{once:!0});let Y=!1,B=setTimeout(()=>{if(X.signal.aborted)return;Y=!0,X.abort()},J.timeoutMs??qX.timeoutMs);try{if(J.signal?.aborted)throw J.signal.reason;XQ(Q);let W=await(J.fetch??fetch)($,{signal:X.signal,redirect:"error"});if(!W.ok)return HX(W),{response:W,content:""};return{response:W,content:await ML(W,Z,Q,()=>X.abort())}}catch(W){if(Y)throw Error("GitHub request timed out",{cause:W});if(J.signal?.aborted)throw J.signal.reason;throw W}finally{clearTimeout(B),J.signal?.removeEventListener("abort",K)}}function y2($,Z,J){return LL(J.resolveUrl?.($)??$,Z,{budget:J.budget,signal:J.controller.signal})}async function ML($,Z,J=D3(),Q){let X=qX[`${Z}Bytes`],K=Number($.headers.get("content-length"));if(Number.isFinite(K)&&K>X)throw HX($),Error(`GitHub ${Z} response exceeds ${X} bytes`);if(!$.body)return"";let Y=$.body.getReader(),B=[],W=0;while(!0){let q=await Y.read();if(q.done)break;try{KQ(J,q.value.byteLength)}catch(U){throw Q?.(),WX(Y),U}if(W+=q.value.byteLength,W>X)throw Q?.(),WX(Y),Error(`GitHub ${Z} response exceeds ${X} bytes`);B.push(Buffer.from(q.value))}return Buffer.concat(B,W).toString("utf-8")}function HX($){if(!$.body)return;jX(()=>$.body?.cancel())}function WX($){jX(()=>$.cancel())}function jX($){try{Promise.resolve($()).catch(()=>{})}catch{}}function FL($,Z){return GL($,Z,g2)}function u$($){return`sha256:${UL("sha256").update($).digest("hex")}`}function LX($={}){let Z=fZ($),J=!1;try{J=HZ(Z.userConfigTarget,Z.projectConfigTarget)}catch(j){if(j instanceof u)return bL(Z,j.message);throw j}let Q=C$(Z.userConfigTarget),X=J?{config:null,errors:[]}:C$(Z.projectConfigTarget),K=OX(Z.userConfigPath,Q.errors),Y=OX(Z.projectConfigPath,X.errors),B=new Set,W=Q.config?o9(Q.config,Z.userLockPath,M0(Z.userConfigPath),$,"user",Z.userScope,B):w2(),q=X.config?o9(X.config,Z.projectLockPath,M0(Z.projectConfigPath),$,"project",Z.projectScope,B):w2(),U=Q.config?.overrides??{},H=X.config?.overrides??{};return{rules:[..._X(W.rules,U),..._X(q.rules,H)],transparent_wrappers:DL(Q.config,X.config),rulebooks:[...W.rulebooks,...q.rulebooks],errors:[...K,...Y,...W.errors,...q.errors],warnings:[...W.warnings,...q.warnings,...W.canValidateOverrides?t9(U,W.knownRuleIds,Z.userConfigPath):[],...W.canValidateOverrides?zL(H,W.knownRuleIds,Z.projectConfigPath):[],...q.canValidateOverrides?t9(H,q.knownRuleIds,Z.projectConfigPath):[]],userConfig:Q.config??void 0,projectConfig:X.config??void 0,...Z}}function DI($,Z){let J=Z??D1(M0(M0($)),"rules policy"),Q=C$(X1(J,$)).config,X=n9(X1(J,E0($))).lock;if(!Q||!X)return new Map;let K=new Set(Q.rules);return new Map(X.rulebooks.filter((Y)=>K.has(Y.spec)).map((Y)=>[Y.spec,AZ(Y)]))}function zI($,Z,J,Q){let X=NL($,Z,J,Q);if(!X)return[];return[...X.scope.errors,...X.scope.warnings,...VL(X.config,X.scope,$)]}function NL($,Z,J,Q){let X=Q??D1(M0(M0($)),"rules policy"),K=C$(X1(X,$)).config;if(!K)return null;return{config:K,scope:o9(K,Z,M0($),J,"project",X)}}function VL($,Z,J){return Z.canValidateOverrides?t9($.overrides??{},Z.knownRuleIds,J):[]}function o9($,Z,J,Q,X,K=D1(M0(M0(J)),X==="user"?"user policy":"project policy"),Y=new Set){let B;try{B=X1(K,Z)}catch(M){if(M instanceof u)return{...w2(),errors:[M.message],canValidateOverrides:!1};throw M}let W=n9(B);if(W.errors.length>0)return{...w2(),errors:W.errors,canValidateOverrides:!1};let q=W.lock;if(!q&&$.rules.length>0)return{...w2(),errors:[`missing lockfile ${Z}; run ${S1}`],canValidateOverrides:!1};let U=q?.rulebooks??[],H=new Map(U.map((M)=>[M.spec,M])),j=[],G=[],_=$.rules.flatMap((M)=>{let L=H.get(M);if(!L)return j.push(`missing lock entry for ${M}; run ${S1}`),[];let D=RL(L,J,Q,K);if(D.errors.length>0||!D.rulebook)return j.push(...D.errors),[];let z=D.rulebook;if(Y.has(z.name))return G.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 ${S1}`),[];return Y.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:G,canValidateOverrides:j.length===0}}function RL($,Z,J,Q){let X=l2($,m2(Z,J)),K;try{K=X0(X1(Q,X))}catch(B){if(B instanceof u)return{rulebook:null,errors:[B.message]};throw B}if(K===null)return{rulebook:null,errors:[`missing cache entry for ${$.spec}; run ${S1}`]};if(u$(K)!==$.digest)return{rulebook:null,errors:[`cache digest mismatch for ${$.spec}; run ${S1}`]};let Y;try{Y=JSON.parse(K)}catch{return{rulebook:null,errors:[`invalid cached rulebook for ${$.spec}`]}}try{v$(Y)}catch(B){return{rulebook:null,errors:[`invalid cached rulebook for ${$.spec}: ${B instanceof Error?B.message:"invalid rulebook"}`]}}return{rulebook:Y,errors:[]}}function DL($,Z){return[...new Set([...$?.transparent_wrappers??[],...Z?.transparent_wrappers??[]])]}function _X($,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 t9($,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 zL($,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 OX($,Z){return Z.map((J)=>J.startsWith("Unable to access ")?J:`${$}: ${J}`)}function bL($,Z){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[Z],warnings:[],userConfigPath:$.userConfigPath,projectConfigPath:$.projectConfigPath,userLockPath:$.userLockPath,projectLockPath:$.projectLockPath}}function w2(){return{rules:[],rulebooks:[],entries:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}function MX($={}){let Z=LX($),J=VQ($),Q={rules:Z.rules,transparentWrappers:Z.transparent_wrappers,safety:EL(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]}},X={...Z.userConfig?.overrides??{},...Z.projectConfig?.overrides??{}},K=Object.freeze(Object.fromEntries(Q.rules.map((Y)=>{let B=Z.rulebooks.find((q)=>q.rules.includes(Y.name)),W=X[Y.name];return[Y.name,Object.freeze({id:Y.name,...B?{rulebook:Object.freeze({name:B.name,version:B.version}),...CL(B.spec)?{source:B.spec}:{}}:{},...W&&typeof W==="object"?{override:Object.freeze({type:"reason",reason:W.reason})}:{}})]})));return AL(Q,IL(Z,J),K)}function PI($){if($.state==="ready")return{state:$.state};return{state:$.state,reason:$.reason}}function IL($,Z){let J=PL(Z);if($.errors.length===0&&$.warnings.length===0&&!J)return;return{diagnostics:[...$.errors,...$.warnings,...Z.errors],reason:TL($.errors.length>0?fL($.errors):void 0,$.warnings.length>0?e9($.warnings.join("; ")):void 0,J)}}function fL($){return`${e9($.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function PL($){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 CL($){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test($)}function AL($,Z,J=Object.freeze({})){let Q=FX(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 EL($){let Z=$.overrides,J={...Z?.failClosed!==void 0?{failClosed:Z.failClosed}:{},...Z?.paranoidRm!==void 0?{paranoidRm:Z.paranoidRm}:{},...Z?.paranoidInterpreters!==void 0?{paranoidInterpreters:Z.paranoidInterpreters}:{}};return{...$.level!==void 0?{level:$.level}:{},...Object.keys(J).length>0?{overrides:J}:{}}}function FX($){if(typeof $!=="object"||$===null)return $;for(let Z of Object.values($))FX(Z);return Object.freeze($)}function TL(...$){return e9($.filter((Z)=>!!Z).join("; "))}function e9($){return/[.!?]$/.test($)?$:`${$}.`}class h$ extends Error{stage;evaluation;name="GuardEvaluationError";constructor($,Z,J){super(`CC Safety Net ${$} dependency failed`,{cause:J});this.stage=$;this.evaluation=Z}}var SL={findPolicyMutation:PQ,findGitMetadataMutation:G7,resolveGitMetadata:S6,loadPolicySnapshot:MX,findSensitiveTarget:mQ,analyzeCommand:v9,getModes:c4};function NX($,Z={}){let J={...SL,...Z.dependencies},Q=vL($),X=v2($)?$.command:Q,K=t0("policy-protection",X,()=>F4($,Z.factParserDependencies)),Y=_1(K,"declared-command");if(v2($)&&$.command?.trim()&&Y?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Y0,intent:"stop_and_explain",evidence:[{kind:"command",command:$.command,segment:$.command}]}};if(_1(K,"input-candidate")?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:mZ,intent:"stop_and_explain",evidence:[]}};let B=t0("policy-protection",X,()=>J.resolveGitMetadata($.context.executionCwd)),W=t0("policy-protection",X,()=>J.findPolicyMutation(K));if(W){let M=X??W.target;return{stage:"policy-protection",decision:{kind:"deny",reason:fQ,intent:"hard_stop",evidence:[{kind:"command",command:M,segment:W.target},{kind:"path",target:W.target}]}}}let q=t0("policy-protection",X,()=>J.findGitMetadataMutation(K,B));if(q){let M=X??q.target;return{stage:"policy-protection",decision:{kind:"deny",reason:f1,intent:"hard_stop",evidence:[{kind:"command",command:M,segment:q.target},{kind:"path",target:q.target}]}}}let U=t0("config-load",X,()=>J.loadPolicySnapshot({...Z.policyOptions,cwd:$.context.configCwd})),H=U.policy,j=J.getModes(H),G={level:j.effectiveLevel,...yL(U)},_=H.secretProtection.enabled===!1?null:t0("secret-protection",X,()=>J.findSensitiveTarget(K,H.secretProtection,{strict:v2($)?j.strict:void 0}));if(_){let M=X??_.target;return{stage:"secret-protection",...G,decision:{kind:"deny",reason:gQ,intent:"hard_stop",ruleId:_.ruleId,evidence:[{kind:"command",command:M,segment:_.target},{kind:"path",target:_.target}]}}}if(!v2($))return{stage:"non-command",...G,decision:{kind:"allow"}};if(!$.command||$.command.trim()==="")return{...$Z("command-validation",X),...G};let O=t0("command-analysis",X,()=>{return J.analyzeCommand($.command,{cwd:$.context.executionCwd,shell:$.route.shell,policySnapshot:U,environment:B0(),protectedGitMetadata:B,effectiveCapabilities:j.capabilities,strict:j.strict,paranoidRm:j.paranoidRm,paranoidInterpreters:j.paranoidInterpreters,worktreeMode:j.worktreeMode},wL(K),K.store)});if(O)return{stage:"command-analysis",...G,decision:O};return{stage:"command-analysis",...G,decision:{kind:"allow"}}}function yL($){if($.state==="ready")return{};return{configFallback:{reason:$.reason}}}function wL($){return _1($,"declared-command")?.program}function vL($){try{return B$($.input)}catch(Z){let J=v2($)?$.command:void 0;throw new h$("policy-protection",$Z("policy-protection",Z instanceof W0?void 0:J),Z)}}function t0($,Z,J){try{return J()}catch(Q){throw new h$($,$Z($,Q instanceof W0?void 0:Z),Q)}}function $Z($,Z){return{stage:$,decision:{kind:"deny",reason:i2,intent:"stop_and_explain",evidence:Z?[{kind:"command",command:Z,segment:Z}]:[]}}}function v2($){return $.route.kind==="command"}import{realpathSync as uL,statSync as hL}from"node:fs";import{isAbsolute as VX,relative as gL,resolve as kL,sep as xL}from"node:path";function lL($,Z){if(v0($))return;let J=Z.flatMap((X)=>ZZ(X));if(!J[0])return;let Q=ZZ(VX($)?$:kL(J[0],$))[0];if(!Q)return;return J.some((X)=>RX(Q,X))?Q:void 0}function mL($){return $.flatMap((Z)=>ZZ(Z))[0]}function ZZ($){try{let Z=uL($);return hL(Z).isDirectory()?[Z]:[]}catch{return[]}}function RX($,Z){let J=gL(Z,$);return J===""||J!==".."&&!J.startsWith(`..${xL}`)&&!VX(J)}function nI($,Z){try{let J=NX($,Z.guard);return DX($,J,Z),J}catch(J){if(!(J instanceof h$))throw J;throw DX($,J.evaluation,Z,!(J.cause instanceof W0),{stage:J.stage,errorCode:pL(J.cause)}),J}}function DX($,Z,J,Q=!0,X){lZ(xZ($,Z,J.guard?.auditAllowed??!1,Q,X),J.audit.getSessionId,{agent:J.audit.agent,shape:J.audit.shape,homeDir:J.audit.homeDir})}function pL($){if($ instanceof y1)return"path-canonicalization-limit";if($ instanceof W0)return"tool-input-limit";if($ instanceof z0)return"structural-shell-syntax-limit";return"unexpected-error"}
|
|
64
|
-
export{XZ as b,bX as c,cL as d,dL as e,iL as f,u as g,X1 as h,u2 as i,X0 as j,GZ as k,HZ as l,oL as m,tL as n,eL as o,$M as p,hX as q,z1 as r,g2 as s,k2 as t,NZ as u,S1 as v,bZ as w,IZ as x,WM as y,E0 as z,qM as A,UM as B,fZ as C,GM as D,AZ as E,l2 as F,HM as G,m2 as H,jK as I,uZ as J,gZ as K,EK as L,EM as M,hM as N,gM as O,kM as P,xM as Q,y1 as R,d$ as S,i as T,R0 as U,B0 as V,r2 as W,n3 as X,T0 as Y,W0 as Z,rK as _,B$ as $,e3 as aa,$6 as ba,F4 as ca,YB as da,f1 as ea,G7 as fa,S6 as ga,E7 as ha,NV as ia,o as ja,jq as ka,_q as la,c4 as ma,x0 as na,x6 as oa,DN as pa,T7 as qa,Cz as ra,v9 as sa,oJ as ta,P2 as ua,QQ as va,JQ as wa,z3 as xa,eJ as ya,dz as za,m9 as Aa,C2 as Ba,P$ as Ca,T_ as Da,C$ as Ea,oz as Fa,tz as Ga,ez as Ha,I3 as Ia,P3 as Ja,T$ as Ka,Hb as La,f3 as Ma,jb as Na,u_ as Oa,_b as Pa,E$ as Qa,RQ as Ra,DQ as Sa,fQ as Ta,PQ as Ua,gQ as Va,mQ as Wa,v$ as Xa,ob as Ya,tb as Za,n9 as _a,HI as $a,jI as ab,LX as bb,DI as cb,zI as db,o9 as eb,MX as fb,PI as gb,AL as hb,h$ as ib,lL as jb,mL as kb,RX as lb,nI as mb};
|