cc-safety-net 2.6.8 → 2.6.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/amp/cc-safety-net/index.ts +44 -43
- package/dist/api.js +1 -1
- package/dist/bin/hook.js +43 -42
- package/dist/chunks/{index-j7c6979z.js → index-0kd1ygaw.js} +42 -41
- package/dist/chunks/{index-zwavdh1s.js → index-vnz6t1vd.js} +1 -1
- package/dist/chunks/{index-0d9zqgyg.js → index-xrc55d5p.js} +2 -2
- package/dist/cli.js +3 -3
- package/dist/deepseek-harness/index.js +1 -1
- package/dist/index.js +1 -1
- package/dist/openclaw/cc-safety-net/index.js +44 -43
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +1 -1
- package/package.json +2 -2
|
@@ -1,49 +1,50 @@
|
|
|
1
|
-
var da="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Un="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",ko="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var ca={errorCode:"path-canonicalization-limit",reason:"CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry."},Io={errorCode:"structural-shell-syntax-limit",reason:"Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry."},a=Object.freeze({realpathAttempts:{cap:16384,...ca},processedCandidateBytes:{cap:4194304,...ca},pathEnvironmentExpansion:{cap:64,...ca},recursionDepth:{cap:10,errorCode:"structural-shell-syntax-limit",reason:"Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry."},derivedTokens:{cap:16384,...Io},trackedHeredocFiles:{cap:64,...Io},controlFlowStates:{cap:64,...Io},wrapperPeelIterations:{cap:20,...Io},derivedCommandShape:Io});class s extends Error{kind;name="AnalysisLimit";constructor(G){super(a[G].reason);this.kind=G}}function Pn(){let G=new Map;return{counters:G,resolvedPaths:new Map,charge(U,j=1){let K=(G.get(U)??0)+j;if(G.set(U,K),K>a[U].cap)throw new s(U)}}}var
|
|
1
|
+
var da="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Un="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",ko="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var ca={errorCode:"path-canonicalization-limit",reason:"CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry."},Io={errorCode:"structural-shell-syntax-limit",reason:"Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry."},a=Object.freeze({realpathAttempts:{cap:16384,...ca},processedCandidateBytes:{cap:4194304,...ca},pathEnvironmentExpansion:{cap:64,...ca},recursionDepth:{cap:10,errorCode:"structural-shell-syntax-limit",reason:"Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry."},derivedTokens:{cap:16384,...Io},trackedHeredocFiles:{cap:64,...Io},controlFlowStates:{cap:64,...Io},wrapperPeelIterations:{cap:20,...Io},derivedCommandShape:Io});class s extends Error{kind;name="AnalysisLimit";constructor(G){super(a[G].reason);this.kind=G}}function Pn(){let G=new Map;return{counters:G,resolvedPaths:new Map,charge(U,j=1){let K=(G.get(U)??0)+j;if(G.set(U,K),K>a[U].cap)throw new s(U)}}}var rh=[/\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 J(G){return Pe(G.replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_DSN|CONNECTION_STRING)=("[^"]*"|'[^']*'|[^\s]+(?:\s+[A-Z_][A-Z0-9_]*=[^\s]+)*)/gi,"$1=<redacted>").replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_(?:URL|URI|CONNECTION_STRING))=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIALS)[A-Z0-9_]*)=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>"))}function Pe(G){return rh.reduce((U,j)=>U.replace(j,"<redacted>"),G.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi,"<redacted>").replace(/((?:(['"])(?:authorization|cookie|x-api-key|api-key)\2|(?:authorization|cookie|x-api-key|api-key))\s*:\s*)(['"])(?:\\[^\r\n]|(?!\3)[^\\\r\n])*\3/gi,"$1$3<redacted>$3").replace(/(['"]?\s*(?:authorization|cookie|x-api-key|api-key)\s*:(?!\s*(?:"<redacted>"|'<redacted>'))\s*)([^'"\r\n]+)(['"]?)/gi,"$1<redacted>$3").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s@/]+)@/gi,"$1<redacted>:<redacted>@").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+)@/gi,"$1<redacted>@").replace(/(^|[\s?&;|])((?:x-amz-signature|x-goog-signature|sig|signature)=)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^&#\s'"`;|<>()]*)/gi,"$1$2<redacted>").replace(/(^|\s)((?:-u|--user)(?:\s+|=))([^\s:]+):([^\s]+)/g,"$1$2<redacted>:<redacted>")).replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"<redacted>").replace(/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,"<redacted>")}function Be(G){return Jc(G).reduceRight((U,j)=>`${U.slice(0,j.valueStart)}<redacted>${U.slice(j.valueEnd)}`,G)}function R(G){return Pe(Be(G))}function nt(G){return Jc(G).map((U)=>G.slice(U.valueStart,U.valueEnd))}function ze(G){return/[A-Za-z_][A-Za-z0-9_]*=/.test(G)}function Jc(G){return[...G.matchAll(/[A-Za-z_][A-Za-z0-9_]*=/g)].flatMap((U)=>{let j=G[U.index-1];if(U.index>0&&j&&!/[\s"'([{]/.test(j))return[];let K=U.index+U[0].length;if(K>=G.length)return[];return[{valueStart:K,valueEnd:oh(G,K)}]})}function oh(G,U){if(G.startsWith("$(",U))return ih(G,U);let j=G[U];if(j==='"'||j==="'"){for(let re=U+1;re<G.length;re++){if(j==='"'&&G[re]==="\\"){re++;continue}if(G[re]===j)return re+1}return G.length}let K=U;while(K<G.length&&!/\s/.test(G[K]??""))K++;return K}function ih(G,U){let j=0,K;for(let re=U;re<G.length;re++){let oe=G[re];if(K){if(K==='"'&&oe==="\\"){re++;continue}if(oe===K)K=void 0;continue}if(oe==='"'||oe==="'"){K=oe;continue}if(oe==="$"&&G[re+1]==="("){j++,re++;continue}if(oe!==")")continue;if(j--,j===0)return re+1}return G.length}var sh={hard_stop:"Do not retry this operation or attempt any workaround (other tools, flags, or paths). Report the block to the user and continue with the rest of the task.",use_alternative:"Do not retry the blocked form. Continue the task using the safer alternative described above.",scope_down:"Retry with a narrower, explicit target as described above. Escalate to the user if the broad operation is truly required.",manual_only:"If this operation is truly needed, ask the user for explicit permission and have them run the command manually.",stop_and_explain:"Do not brute-force variants. Simplify or restructure the command so it can be analyzed, or report the block to the user."};function ah(G){let U=G.maxLen??200,j=G.redact??((re)=>re),K=(re)=>re.length>U?`${re.slice(0,U)}...`:re;return[G.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${j(G.reason)}`,G.ruleId?`Rule: ${G.ruleId}`:void 0,G.toolName?`Tool: ${G.toolName}`:void 0,G.command?`Command: ${K(j(G.command))}`:void 0,G.segment&&G.segment!==G.command?`Segment: ${K(j(G.segment))}`:void 0,G.cwd?`Working directory: ${K(j(G.cwd))}`:void 0,G.configWarning?`Config warning: ${j(G.configWarning)}`:void 0,G.askUser?"Approve only if you expected this command.":sh[G.intent??"manual_only"]].filter((re)=>re!==void 0).join(`
|
|
2
2
|
|
|
3
|
-
`)}function Ce(G,U){if(G.decision.kind!=="deny")return;let j=U.includeEvidence?G.decision.evidence:void 0;return{reason:G.decision.reason,ruleId:G.decision.ruleId,intent:G.decision.intent,command:j?.command,segment:j?.segment,toolName:U.toolName,...G.configFallback?{configWarning:G.configFallback.reason}:{},...G.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function O(G={}){return{reason:ko,ruleId:"analysis.failed-closed",intent:"stop_and_explain",command:G.command,segment:G.segment??G.command,toolName:G.toolName}}var
|
|
4
|
-
`,t:"\t",b:"\b"};function
|
|
5
|
-
`,r:"\r",t:"\t",v:"\v"}[G]??G}function py(G){return Wo(yy(G))}function va(G,U){if(G==="/dev/null")return fd(U);if(U==="/dev/null")return fd(G);if(G.startsWith("a/")&&U.startsWith("b/"))return[G.slice(2),U.slice(2)].flatMap(Wo);let j=gy(G,U)??(G===U?_d(G):null);return[G,U,...j?[j]:[]].flatMap(Wo)}function fd(G){let U=_d(G);return[G,...U?[U]:[]].flatMap(Wo)}function _d(G){let U=G.indexOf("/");return U>0&&U<G.length-1?G.slice(U+1):null}function gy(G,U){let j=G.indexOf("/"),K=U.indexOf("/");if(j<1||K<1)return null;if(G.slice(0,j)===U.slice(0,K))return null;let re=G.slice(j+1);return re===U.slice(K+1)?re:null}function pd(G){return py(Ti(G,!0))}function hy(G){return Wo(Ti(G,!1))}function Ti(G,U){let j=G.trim(),K=j[0]==='"'||j[0]==="'"?j[0]:void 0;if(K){let re=xd(j,0,K);if(re&&(U||j.slice(re.end).trim()===""))return re.value}return U?j.split("\t",1)[0]?.trim()??"":j}function yy(G){return G.startsWith("a/")||G.startsWith("b/")?G.slice(2):G}function Wo(G){return G===""||G==="/dev/null"?[]:[G]}function gd(G){let U=G.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return U===""||U==="/dev/null"?[]:[U]}function fe(G){try{if(!Cy(G).isDirectory())return!1;return by(G,wd.R_OK|wd.X_OK),!0}catch{return!1}}function it(G,U,j){if(sr(G))return;let K=U.flatMap((oe)=>Ea(oe,j));if(!K[0])return;let re=Ea(Ad(G)?G:vy(K[0],G),j)[0];if(!re)return;return K.some((oe)=>Ry(re,oe))?re:void 0}function qe(G,U){return G.flatMap((j)=>Ea(j,U))[0]}function Ea(G,U){let j=U.realpath(G);if(j===null)return[];return U.isDirectory(j)?[j]:[]}function Ry(G,U){let j=Sy(U,G);return j===""||j!==".."&&!j.startsWith(`..${Ey}`)&&!Ad(j)}var xy=8388608;async function Ke(G){let U=[],j=0;for await(let K of G){let re=typeof K==="string"?Buffer.from(K,"utf-8"):Buffer.from(K.buffer,K.byteOffset,K.byteLength);if(j+=re.byteLength,j>xy)throw _y(G),Error("hook input byte limit exceeded");U.push(re)}return Buffer.concat(U,j).toString("utf-8")}function _y(G){let U=G.destroy??G.cancel;if(!U)return;try{Promise.resolve(U.call(G)).catch(()=>{})}catch{}}function u(G,U,j,K,re){if(j.kind!=="command")return{toolName:G,input:U,route:j,context:K};return{toolName:G,input:U,route:j,context:K,command:re}}var Zr=["fail_closed","paranoid_rm","paranoid_interpreters"],ki={standard:{fail_closed:!1,paranoid_rm:!1,paranoid_interpreters:!1},strict:{fail_closed:!0,paranoid_rm:!1,paranoid_interpreters:!1},paranoid:{fail_closed:!0,paranoid_rm:!0,paranoid_interpreters:!0}};var n={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"},projectTightenOnly:{name:"CC_SAFETY_NET_PROJECT_TIGHTEN_ONLY"}},Oi=["standard","strict","paranoid"];function Pd(G,U){if(!U)return G;return Oi.indexOf(U)>Oi.indexOf(G)?U:G}function Td(G){let U=pe(n.level,G);return Oi.find((j)=>j===U)}function Id(G,U){return Pd(G,Td(U))}function wy(G){let U=pe(n.level,G);if(!U)return;let j=Td(G);if(j)return j;console.error(`CC Safety Net: ignored invalid ${n.level.name}=${JSON.stringify(U.slice(0,40))}. Use ${Oi.join(", ")}.`);return}function Ve(G){if(G===void 0||G==="all")return"all";if(G==="blocked")return"blocked";return"invalid"}function Ee(G){return Ve(pe(n.auditScope,G))==="all"}function Ra(G){if(G.failClosed&&G.paranoidRm&&G.paranoidInterpreters)return"paranoid";if(G.failClosed&&!G.paranoidRm&&!G.paranoidInterpreters)return"strict";if(!G.failClosed&&!G.paranoidRm&&!G.paranoidInterpreters)return"standard";return"custom"}function T(G={},U){let j=G.safety?.level??"standard",K=wy(U),re=Pd(j,K),oe=ki[re],de={failClosed:oe.fail_closed,paranoidRm:oe.paranoid_rm,paranoidInterpreters:oe.paranoid_interpreters},Se={failClosed:re===j?"preset":"environment",paranoidRm:re===j?"preset":"environment",paranoidInterpreters:re===j?"preset":"environment"},we={failClosed:[`policy safety.level=${j}`],paranoidRm:[`policy safety.level=${j}`],paranoidInterpreters:[`policy safety.level=${j}`]};if(re!==j)we.failClosed.push(`env ${n.level.name}=${K}`),we.paranoidRm.push(`env ${n.level.name}=${K}`),we.paranoidInterpreters.push(`env ${n.level.name}=${K}`);if(G.safety?.overrides?.failClosed!==void 0)de.failClosed=G.safety.overrides.failClosed,Se.failClosed="capability_override",we.failClosed.push("policy safety.overrides.fail_closed");if(G.safety?.overrides?.paranoidRm!==void 0)de.paranoidRm=G.safety.overrides.paranoidRm,Se.paranoidRm="capability_override",we.paranoidRm.push("policy safety.overrides.paranoid_rm");if(G.safety?.overrides?.paranoidInterpreters!==void 0)de.paranoidInterpreters=G.safety.overrides.paranoidInterpreters,Se.paranoidInterpreters="capability_override",we.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(v(n.strict,U))de.failClosed=!0,Se.failClosed="environment",we.failClosed.push(`env ${n.strict.name}`);if(v(n.paranoid,U))de.paranoidRm=!0,de.paranoidInterpreters=!0,Se.paranoidRm="environment",Se.paranoidInterpreters="environment",we.paranoidRm.push(`env ${n.paranoid.name}`),we.paranoidInterpreters.push(`env ${n.paranoid.name}`);if(v(n.paranoidRm,U))de.paranoidRm=!0,Se.paranoidRm="environment",we.paranoidRm.push(`env ${n.paranoidRm.name}`);if(v(n.paranoidInterpreters,U))de.paranoidInterpreters=!0,Se.paranoidInterpreters="environment",we.paranoidInterpreters.push(`env ${n.paranoidInterpreters.name}`);let We=!!G.worktreeMode||v(n.worktree,U);return{strict:de.failClosed,paranoidRm:de.paranoidRm,paranoidInterpreters:de.paranoidInterpreters,worktreeMode:We,effectiveLevel:Ra(de),capabilities:{fail_closed:{enabled:de.failClosed,source:Se.failClosed,sources:we.failClosed},paranoid_rm:{enabled:de.paranoidRm,source:Se.paranoidRm,sources:we.paranoidRm},paranoid_interpreters:{enabled:de.paranoidInterpreters,source:Se.paranoidInterpreters,sources:we.paranoidInterpreters}}}}function v(G,U){let j=typeof G==="string"?Fo(G,U):pe(G,U);return j==="1"||j?.toLowerCase()==="true"}function Fo(G,U){return U.get(G)}function pe(G,U){let j=Fo(G.name,U);if(j!==void 0)return j;if(G.legacyName)return Fo(G.legacyName,U);return}function ot(G,U){return Fo(G.name,U)!==void 0||!!G.legacyName&&Fo(G.legacyName,U)!==void 0}import{dirname as wr}from"node:path";import{closeSync as Ay,constants as Go,fstatSync as xa,fsyncSync as Py,lstatSync as Tn,mkdirSync as kd,openSync as Od,readdirSync as wa,readFileSync as Ty,realpathSync as Xr,renameSync as Iy,rmdirSync as Md,statSync as _a,unlinkSync as Aa,writeFileSync as ky}from"node:fs";import{isAbsolute as Dd,join as Rr,normalize as Oy,parse as Mi,relative as Pa,resolve as Ta,sep as Di}from"node:path";function Ie(){let G=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${G()}${G()}`}var My=Symbol("PolicyFilesystemScope"),Dy=Symbol("PolicyFilesystemTarget"),Nd=Go.O_NOFOLLOW??0;class o extends Error{name="PolicyFilesystemError";constructor(G){super(`Unable to access ${G} filesystem safely.`)}}function S(G,U){return{[My]:!0,root:Ta(G),label:U}}function zo(G,U){let j=Oy(U);if(U===""||Dd(U)||j===".."||j.startsWith(`..${Di}`))throw new o(G.label);return{[Dy]:!0,scope:G,relativePath:j,path:Rr(G.root,j)}}function i(G,U){return zo(G,Pa(G.root,Ta(U)))}function se(G,U="rules policy"){let j=Ta(G),K=Mi(j).dir;return zo(S(K,U),Pa(K,j))}function r(G){return Zn(G.scope.label,()=>{if(!nn(G))return null;let U=Od(G.path,Go.O_RDONLY|Nd);return Wd(U,()=>{let j=xa(U);if(!j.isFile())throw new o(G.scope.label);let K=Ty(U,"utf-8"),re=Tn(G.path);if(!re.isFile()||re.isSymbolicLink()||j.dev!==re.dev||j.ino!==re.ino)throw new o(G.scope.label);return nn(G),K})})}function g(G,U,j=384,K){let re=`${G.path}.${Ie()}.tmp`;Zn(G.scope.label,()=>{Ly(G),nn(G);let oe=Od(re,Go.O_CREAT|Go.O_EXCL|Go.O_WRONLY|Nd,j),de=Wd(oe,()=>{let Se=xa(oe);if(!Se.isFile())throw new o(G.scope.label);ky(oe,U,"utf-8"),Py(oe);let we=xa(oe);if(!we.isFile()||we.dev!==Se.dev||we.ino!==Se.ino)throw new o(G.scope.label);return we});nn(G),Fy(G,re,de.dev,de.ino),Iy(re,G.path),K?.(G.path),nn(G)},()=>Gy(re))}function Ld(G,U){if(G.path===U.path)return!0;return Zn(G.scope.label,()=>{if(!nn(G)||!nn(U))return!1;let j=(K)=>Rr(Xr(Mi(K).dir),Mi(K).base);return j(G.path)===j(U.path)})}function me(G){let U=Zn(G.scope.label,()=>{if(!nn(G,"directory"))return null;let j=wa(G.path);return nn(G,"directory"),j});if(!U)return null;return Zn(G.scope.label,()=>{let j=U.map((K)=>{let re=zo(G.scope,Rr(G.relativePath,K)),oe=Tn(re.path);if(oe.isSymbolicLink()||!oe.isFile()&&!oe.isDirectory())throw new o(G.scope.label);return Ni(Ia(G.scope),Xr(re.path),G.scope.label),{name:K,kind:oe.isDirectory()?"directory":"file"}});return nn(G,"directory"),j})}function H(G){Zn(G.scope.label,()=>{if(!nn(G))return;Aa(G.path),nn(G)})}function st(G){Zn(G.scope.label,()=>{if(!Ny(G))return;Gd(G),nn(G,"directory")})}function at(G){Zn(G.scope.label,()=>{if(!nn(G,"directory"))return;Md(G.path),nn(G,"directory")})}function Ny(G){return Zn(G.scope.label,()=>{if(!nn(G,"directory"))return!1;return Fd(G),!0})}function Zn(G,U,j){try{return U()}catch(K){if(j?.(),K instanceof o)throw K;throw new o(G)}}function Wd(G,U){try{return U()}finally{Ay(G)}}function nn(G,U="file"){let j=zd(G.scope);if(!j)return!1;let K=G.relativePath.split(Di);for(let re of K.keys()){let oe=Rr(G.scope.root,...K.slice(0,re+1)),de=Tn(oe,{throwIfNoEntry:!1});if(!de)return!1;if(de.isSymbolicLink())throw new o(G.scope.label);if(re<K.length-1&&!de.isDirectory())throw new o(G.scope.label);if(re===K.length-1&&(U==="file"?!de.isFile():!de.isDirectory()))throw new o(G.scope.label);Ni(j,Xr(oe),G.scope.label)}return!0}function Fd(G){for(let U of wa(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=Tn(j.path);if(K.isSymbolicLink()||!K.isDirectory()&&!K.isFile())throw new o(G.scope.label);if(K.isDirectory())Fd(j)}nn(G,"directory")}function Gd(G){for(let U of wa(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=Tn(j.path);if(K.isSymbolicLink())throw new o(G.scope.label);if(K.isDirectory()){Gd(j);continue}if(!K.isFile())throw new o(G.scope.label);Aa(j.path)}Md(G.path)}function Ly(G){Wy(G.scope);let U=Ia(G.scope),j=G.relativePath.split(Di).slice(0,-1);for(let K of j.keys()){let re=Rr(G.scope.root,...j.slice(0,K+1));if(!Tn(re,{throwIfNoEntry:!1}))kd(re,{mode:448});let oe=Tn(re);if(!oe.isDirectory()||oe.isSymbolicLink())throw new o(G.scope.label);Ni(U,Xr(re),G.scope.label)}}function Wy(G){if(Tn(G.root,{throwIfNoEntry:!1})){if(!_a(G.root).isDirectory())throw new o(G.label);return}let U=[],j=G.root;while(!Tn(j,{throwIfNoEntry:!1})){U.unshift(j);let K=Mi(j).dir;if(K===j)throw new o(G.label);j=K}if(!_a(j).isDirectory())throw new o(G.label);for(let K of U){kd(K,{mode:448});let re=Tn(K);if(!re.isDirectory()||re.isSymbolicLink())throw new o(G.label)}}function zd(G){if(!Tn(G.root,{throwIfNoEntry:!1}))return null;if(!_a(G.root).isDirectory())throw new o(G.label);return Xr(G.root)}function Ia(G){let U=zd(G);if(!U)throw new o(G.label);return U}function Fy(G,U,j,K){let re=Tn(U);if(!re.isFile()||re.isSymbolicLink()||re.dev!==j||re.ino!==K)throw new o(G.scope.label);Ni(Ia(G.scope),Xr(U),G.scope.label)}function Ni(G,U,j){let K=Pa(G,U);if(K===".."||K.startsWith(`..${Di}`)||Dd(K))throw new o(j)}function Gy(G){try{Aa(G)}catch{}}import{dirname as xr,isAbsolute as Hy,join as _r,relative as jy,resolve as ar,sep as Vy}from"node:path";var d=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ge="rulebook.json",he=".cc-safety-net/rules";var $d=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,zy=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,Bd=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,$y=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),By="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ct=new RegExp(`^${$y}/(${d.source.slice(1,-1)})/${By}$`);function Uy(G){return`.cc-safety-net/rules/${G}/rulebook.json`}function Ud(G){if(w(G))try{return N(G),null}catch(U){return U instanceof Error?U.message:String(U)}return d.test(G)?null:`Local rulebook sources must be bare names matching ${d}: ${G}`}function N(G){if(G.startsWith("github:"))throw Error(`Invalid rulebook source: ${G}`);let U=G.match($d);if(!U?.[1]||!U[2]||!U[3])throw Error(`Invalid GitHub rulebook source: ${G}`);let j=U[3].lastIndexOf("/");if(j<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${G}`);let K=U[3].slice(0,j),re=U[3].slice(j+1);if(!K||!Bd.test(K))throw Error(`GitHub rulebook refs must use valid path segments: ${G}`);if(!re||!d.test(re))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${G}`);return{owner:U[1],repo:U[2],ref:K,path:Uy(re),name:re}}function Z(G){return zy.test(G)}function ae(G){return Bd.test(G)}function w(G){return $d.test(G)}function lt(G){if(!d.test(G))throw Error(`Local rulebook sources must be bare names matching ${d}: ${G}`)}var Hd="rule.json",Li="policy.json",jd=".cc-safety-net",Ky="rules",qy="CC_SAFETY_NET_HOME",Vd="`cc-safety-net rule update`";function Yy(G){return ar(G,he)}function _(G){return _r(Yy(G),Hd)}function h(G){return _r(ar(G),jd,Li)}function ke(G,U={}){return U.userConfigDir??(U.userConfigPath?xr(U.userConfigPath):_r(Zy(G),Ky))}function Zy(G){let U=G.env.get(qy);return U?ar(cn(U)):_r(G.home,jd)}function W(G,U={}){return _r(ke(G,U),Hd)}function l(G,U={}){return _r(xr(ke(G,U)),Li)}function L(G,U){let j=Pn();return Nt(h(U.cwd),G.paths,j)===Nt(ar(l(G,U)),G.paths,j)}function X(G,U){let j=U.userConfigPath??W(G,U),K=U.projectConfigPath??_(U.cwd),re=Je(G,U),oe=Ye(K,U.cwd);return{userConfigPath:j,projectConfigPath:K,userScope:re,projectScope:oe,userConfigTarget:i(re,j),projectConfigTarget:i(oe,K)}}function Je(G,U){let j=U.userConfigPath?xr(xr(ar(U.userConfigPath))):xr(ar(U.userConfigDir??ke(G,U)));return S(j,"user policy")}function Ye(G,U){let j=ar(U),K=ar(G),re=jy(j,K);if(re!==".."&&!re.startsWith(`..${Vy}`)&&!Hy(re))return S(j,"project policy");return S(xr(xr(K)),"project policy")}function M(G,U){return _r(G,U,ge)}var vn=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),C=/^[a-zA-Z][a-zA-Z0-9_-]*$/,I=256,qt=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Kd=new Set(["python","python3","python2","node","ruby","perl"]),Wi=/^python(?:[23](?:\.\d+)*)?$/,In=new Set(["awk","gawk","nawk","mawk"]),Fi=new Set(["echo","printf","cat","head","tail","less","more","grep","rg","ag","ack","sed","awk","cut","tr","sort","uniq","wc","tee","man","help","info","type","which","whereis","whatis","apropos","file","stat","ls","ll","dir","tree","pwd","date","cal","uptime","whoami","id","groups","hostname","uname","env","printenv","set","export","alias","history","jobs","fg","bg","test","true","false","read","return","exit","break","continue","shift","wait","trap","basename","dirname","realpath","readlink","md5sum","sha256sum","base64","xxd","od","hexdump","strings","diff","cmp","comm","join","paste","column","fmt","fold","nl","pr","expand","unexpand","rev","tac","shuf","seq","yes","sleep","logger","write","wall","mesg","notify-send"]);var qd="Rulebook exceeds CC Safety Net's safe validation limits.",Yd="Additional rulebook validation errors were omitted.",Nn=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Zd(G){if(ka(G.allowed_commands,Nn.maxAllowedCommands)||ka(G.rules,Nn.maxRules)||ka(G.tests,Nn.maxTests))return!1;let{maxAggregateStringCodeUnits:U,maxTotalBlockArgs:j}=Nn,K=(re,oe=!1)=>{if(typeof re!=="string")return!0;if(re.length>Nn.maxStringCodeUnits||oe&&re.length>Nn.maxFixtureCommandCodeUnits||re.length>U)return!1;return U-=re.length,!0};if(!K(G.name)||!K(G.version)||!K(G.description)||!K(G.author)||!K(G.migrated_from))return!1;if(Array.isArray(G.allowed_commands)){for(let re of G.allowed_commands)if(!K(re))return!1}if(Array.isArray(G.rules))for(let re of G.rules){if(!re||typeof re!=="object")continue;let oe=re;if(!K(oe.name)||!K(oe.command)||!K(oe.subcommand)||!K(oe.reason)||!K(oe.intent))return!1;let de=oe.match&&typeof oe.match==="object"?oe.match:{};for(let Se of[oe.block_args,de.command_path,de.any_args,de.exclude_args]){if(!Array.isArray(Se))continue;if(Se.length>Nn.maxBlockArgsPerRule||Se.length>j)return!1;j-=Se.length;for(let we of Se)if(!K(we))return!1}}if(Array.isArray(G.tests))for(let re of G.tests){if(!re||typeof re!=="object")continue;let oe=re;if(!K(oe.command,!0)||!K(oe.expect)||!K(oe.rule))return!1}return!0}function ka(G,U){return Array.isArray(G)&&G.length>U}var Oa=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var ye=64,be="Rule config exceeds CC Safety Net's safe source limit.";function Mt(G){return kt(G).toLowerCase()}function kt(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}function fn(G,U){let j=new Set,K=!1;for(let re of G){if(re==="--"){K=!0;continue}if(K)continue;if(re.startsWith("-")&&!re.startsWith("--")&&re.length>1)for(let oe=1;oe<re.length;oe++){let de=re[oe];if(!de||!/[a-zA-Z]/.test(de))break;let Se=`-${de}`;if(j.add(Se),U?.shortOptsWithValue?.has(Se))break}}return j}var Xy={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Ma=new Set(["--init-file","--rcfile"]);function Da(G,U,j,K){let re=!1,oe=0,de=!1,Se=!1,we=!1;for(let We=1;We<U.length;We++){let mt=U[We];if(mt===void 0)break;if(G==="ksh"&&mt==="o"&&We+1<U.length){if(K==="argv"){let gt=U.slice(We+1);if(U[0]==="-"&&(gt==="c"||gt[0]==="-"&>.endsWith("c")))de=!0}break}if(G==="ksh"&&mt==="o"&&We+1===U.length&&(j?.startsWith("-")||j?.startsWith("+")))break;if(G==="zsh"&&mt==="o"&&We+1<U.length)break;if(K==="startup"&&mt==="i")re=U[0]==="-";if(K==="argv"&&U[0]==="-"&&mt==="c")de=!0;if(K==="argv"&&mt==="n")we=U[0]==="-";if(K==="argv"&&mt==="s")Se=U[0]==="-";if(!Xy[G]?.includes(mt))continue;if(We+1===U.length)oe++;break}return{interactive:re,followingValues:oe,commandSelected:de,stdinMode:Se,syntaxCheck:we}}function En(G){let U=kt(G[0]??"").toLowerCase(),j=!1,K=!1,re=!1;for(let oe=1;oe<G.length;oe++){let de=G[oe];if(de===void 0)break;if(de==="--"){let we=j&&G[oe+1]!==void 0?oe+1:null;return{command:we===null?null:G[we]??null,commandIndex:we,scriptIndex:!j&&!K&&G[oe+1]!==void 0?oe+1:null,readsStdinAsCommands:!j&&(K||G[oe+1]===void 0),syntaxCheck:re}}if(de==="-"||de[0]!=="-"&&de[0]!=="+")return{command:j?de:null,commandIndex:j?oe:null,scriptIndex:!j&&!K&&de!=="-"?oe:null,readsStdinAsCommands:!j&&(K||de==="-"),syntaxCheck:re};if(de.startsWith("--")){let we=de.split("=",1)[0]??de;if(U==="bash"&&Ma.has(we)&&!de.includes("="))oe++;continue}let Se=Da(U,de,G[oe+1],"argv");if(Se.commandSelected)j=!0;if(Se.syntaxCheck)re=!0;if(Se.stdinMode)K=!0;oe+=Se.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!j,syntaxCheck:re}}function $o(G,U){if(U.escaped)return U.escaped=!1,!0;if(G==="\\"&&!U.inSingle)return U.escaped=!0,!0;if(G==="'"&&!U.inDouble)return U.inSingle=!U.inSingle,!0;if(G==='"'&&!U.inSingle)return U.inDouble=!U.inDouble,!0;return!1}function Gi(G){let U={inSingle:!1,inDouble:!1,escaped:!1};for(let j of Jy(G))$o(j,U);return U.inSingle||U.inDouble}function Jy(G){let U="",j={inSingle:!1,inDouble:!1,escaped:!1},K=!1,re=!0;for(let oe=0;oe<G.length;oe++){let de=G[oe];if(!de)break;if(K){if(de===`
|
|
6
|
-
`||de==="\r")U+=de,K=!1,j.escaped=!1;continue}if(de==="#"&&!j.inSingle&&!j.inDouble&&re){K=!0;continue}if(U+=de,!j.inSingle&&!j.inDouble&&!j.escaped)re=/[\s;&|()<>]/.test(de);$o(de,j)}return U}var Na=new Set(["rm","find","xargs","parallel"]),Qy=new Set(["git","busybox",...Na,...qt,...Kd,...In]),eb=new Set(["python","node","ruby","perl"]);function Ae(G){let U=Mt(G);return Qy.has(U)||Ln(U)}function Ln(G){return eb.has(tb(G))}function tb(G){let U=kt(G).toLowerCase();return Wi.test(U)?"python":U}var ut={version:1,rules:[],overrides:{},transparent_wrappers:[]};function m(G){try{let U=r(nb(G));if(U===null)return{config:null,errors:[]};if(!U.trim())return{config:null,errors:["Config file is empty"]};let j=JSON.parse(U),K=Ze(j);if(K.errors.length>0)return{config:null,errors:K.errors};return{config:{version:1,rules:j.rules??[],overrides:j.overrides??{},transparent_wrappers:j.transparent_wrappers??[]},errors:[]}}catch(U){if(U instanceof o)return{config:null,errors:[U.message]};let j=U instanceof Error?U.message:String(U);return{config:null,errors:[U instanceof SyntaxError?"Invalid JSON":j]}}}function nb(G){return typeof G==="string"?se(G):G}var e=(G,U)=>({path:G,message:U,kind:"typed"}),rn=(G,U)=>({path:G,message:U,kind:"custom"});function Oe(G){let U=new Set;return G.flatMap((j,K)=>{let re=Jr(j)?j.name:void 0;if(typeof re!=="string")return[];if(U.has(re.toLowerCase()))return[rn(["rules",K,"name"],`duplicate rule name "${re}"`)];return U.add(re.toLowerCase()),[]})}var Re=`must be one of ${Oa.join(", ")}`,rb=/^[^/]+\/[^/]+$/,ob=["version","rules","overrides","transparent_wrappers"];function Ze(G){let U=ib(G);return{errors:ce(Xe(U,ob,(j)=>j.kind==="custom"),": "," "),sources:fb(G,U)}}function ib(G){if(!Jr(G))return[e([],"Config must be an object")];let U=Array.isArray(G.rules)&&G.rules.length>ye;return[...G.version===1?[]:[e(["version"],"must be 1")],...sb(G.rules,U),...cb(G.overrides),...ub(G.transparent_wrappers),...U?[]:lb(G.rules),...Jr(G.overrides)?Object.keys(G.overrides).filter((j)=>!rb.test(j)).map((j)=>rn(["overrides",j],"must use <rulebook-name>/<rule-name>")):[],...mb(G.transparent_wrappers)]}function sb(G,U){if(G===void 0)return[];if(!Array.isArray(G))return[e(["rules"],"must be an array of rulebook source strings"),...Xd(G,ye)?[e(["rules"],be)]:[]];if(U)return[{path:["rules"],message:be,kind:"limit"}];return G.flatMap((j,K)=>{if(typeof j!=="string")return[e(["rules",K],"must be a rulebook source string"),...ab(j,1)?[e(["rules",K],"must be a non-empty rulebook source string")]:[]];return j===""?[e(["rules",K],"must be a non-empty rulebook source string")]:[]})}function Xd(G,U){let j=Jd(G);return j!==void 0&&!(j<=U)}function ab(G,U){let j=Jd(G);return j!==void 0&&!(j>=U)}function Jd(G){if(G===null||G===void 0)return;let U=G.length;return U===void 0?void 0:Number(U)}function lb(G){if(!Array.isArray(G))return[];let U=new Set;return G.flatMap((j,K)=>{if(typeof j!=="string"||j==="")return[];if(j.trim()==="")return[rn(["rules",K],"must be a non-empty rulebook source string")];let re=Ud(j);if(re)return[rn(["rules",K],re)];if(U.has(j))return[rn(["rules",K],`duplicate rulebook source "${j}"`)];return U.add(j),[]})}function cb(G){if(G===void 0)return[];if(!Jr(G))return[e(["overrides"],"must be an object if provided")];return Object.keys(G).flatMap((U)=>{let j=G[U];if(j==="off")return[];if(!Jr(j))return[e(["overrides",U],'must be "off" or an object')];return[...db(j.reason,["overrides",U,"reason"]),...j.intent===void 0||Te(j.intent)?[]:[e(["overrides",U,"intent"],Re)]]})}function db(G,U){if(typeof G!=="string")return[e(U,"required non-empty string"),...Xd(G,I)?[e(U,`must be at most ${I} characters`)]:[]];if(G==="")return[e(U,"required non-empty string")];return G.length>I?[e(U,`must be at most ${I} characters`)]:[]}function ub(G){if(G===void 0)return[];if(!Array.isArray(G))return[e(["transparent_wrappers"],"must be an array of command strings")];return G.flatMap((U,j)=>{if(typeof U!=="string")return[e(["transparent_wrappers",j],"must be a command string")];return C.test(U)?[]:[e(["transparent_wrappers",j],"must match command pattern")]})}function mb(G){if(!Array.isArray(G))return[];let U=new Set;return G.flatMap((j,K)=>{if(typeof j!=="string"||!C.test(j))return[];if(U.has(j))return[rn(["transparent_wrappers",K],`duplicate command "${j}"`)];if(Ae(j))return[rn(["transparent_wrappers",K],`reserved command "${j}" cannot be a wrapper`)];return U.add(j),[]})}function fb(G,U){let j=Jr(G)?G.rules:void 0;if(!Array.isArray(j))return new Set;if(U.some((re)=>re.path.length===1&&re.path[0]==="rules"))return new Set;let K=new Set(U.filter((re)=>re.path[0]==="rules"&&typeof re.path[1]==="number").map((re)=>re.path[1]));return new Set(j.filter((re,oe)=>typeof re==="string"&&!K.has(oe)))}function Xe(G,U,j){let K=G.map((de)=>de.path[1]),re=[...new Set(K.filter((de)=>typeof de==="string"))],oe=(de,Se)=>[de.path.length===0?-1:U.indexOf(String(de.path[0])),typeof Se==="number"?Se:re.indexOf(String(Se)),j(de)?0:1];return G.map((de,Se)=>({issue:de,rank:oe(de,K[Se])})).sort((de,Se)=>de.rank[0]-Se.rank[0]||de.rank[1]-Se.rank[1]||de.rank[2]-Se.rank[2]).map((de)=>de.issue)}function ce(G,U,j){return[...new Set(G.map((K)=>{let re=La(K.path);if(K.kind==="unknownKeys")return`${re?`${re}.`:""}unknown field "${K.message}"`;if(K.kind==="key"||K.kind==="limit"||K.path.length===0)return K.message;return`${re}${K.path.length===1?j:U}${K.message}`}))]}function La(G){return G.map((U,j)=>{if(typeof U==="number")return`[${U}]`;return j===0?String(U):`.${String(U)}`}).join("")}function Te(G){return Oa.includes(G)}function Jr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function le(G){let U=hb(G);if(U.errors.length>0)throw Error(U.errors.join("; "));return G}var pb=`required non-empty string up to ${I} characters`,Qd="must be a non-empty array of unique non-empty strings",gb="required non-empty array of non-empty strings";function hb(G){if(!lr(G))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Zd(G))return{errors:[qd],ruleNames:new Set};let U=[...G.rulebook_version===1||G.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ce(yb(G,G.rulebook_version===2),": ",": ")];return{errors:U.length>Nn.maxValidationErrors?[...U.slice(0,Nn.maxValidationErrors),Yd]:U,ruleNames:new Set(De(G).map((j)=>j.toLowerCase()))}}function De(G){let U=lr(G)?G.rules:void 0;return(Array.isArray(U)?U:[]).flatMap((j)=>{let K=lr(j)?j.name:void 0;return typeof K==="string"?[K]:[]})}function yb(G,U){return[...typeof G.name==="string"&&d.test(G.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof G.version==="string"&&G.version!==""?[]:[e(["version"],"required non-empty string")],...bb(G.allowed_commands),...Cb(G.rules,U),...Rb(G.tests),...xb(G),..._b(G)]}function bb(G){if(!Array.isArray(G))return[e(["allowed_commands"],"required array")];let U=new Set;return[...G.flatMap((j,K)=>typeof j==="string"&&C.test(j)?[]:[e(["allowed_commands",K],"must match command pattern")]),...G.flatMap((j,K)=>{if(typeof j!=="string"||!C.test(j))return[];if(U.has(j))return[rn(["allowed_commands",K],`duplicate command "${j}"`)];return U.add(j),[]})]}function Cb(G,U){if(!Array.isArray(G))return[e(["rules"],"required array")];return[...G.flatMap((j,K)=>{if(!lr(j))return[e(["rules",K],"must be an object")];return U?vb(j,["rules",K]):Sb(j,["rules",K])}),...Oe(G)]}function Sb(G,U){return[...eu(G.name,U),...tu(G.command,U),...G.subcommand===void 0||typeof G.subcommand==="string"&&C.test(G.subcommand)?[]:[e([...U,"subcommand"],"must match command pattern")],...zi(G.block_args,[...U,"block_args"],"required non-empty array",!1),...nu(G.reason,U),...ru(G.intent,U)]}function vb(G,U){return[...eu(G.name,U),...tu(G.command,U),...nu(G.reason,U),...ru(G.intent,U),...Eb(G.match,[...U,"match"]),...G.subcommand===void 0?[]:[e([...U,"subcommand"],"not supported in rulebook_version 2")],...G.block_args===void 0?[]:[e([...U,"block_args"],"not supported in rulebook_version 2")]]}function eu(G,U){if(typeof G!=="string")return[e([...U,"name"],"required string")];return d.test(G)?[]:[e([...U,"name"],"must match rule name pattern")]}function tu(G,U){return typeof G==="string"&&C.test(G)?[]:[e([...U,"command"],"required string matching command pattern")]}function nu(G,U){return typeof G==="string"&&G!==""&&G.length<=I?[]:[e([...U,"reason"],pb)]}function ru(G,U){return G===void 0||Te(G)?[]:[e([...U,"intent"],Re)]}function Eb(G,U){if(!lr(G))return[e(U,"required object")];return[...zi(G.command_path,[...U,"command_path"],gb,!1),...G.any_args===void 0?[]:zi(G.any_args,[...U,"any_args"],Qd,!0),...G.exclude_args===void 0?[]:zi(G.exclude_args,[...U,"exclude_args"],Qd,!0)]}function zi(G,U,j,K){if(!Array.isArray(G))return[e(U,j)];let re=G.flatMap((oe,de)=>{if(typeof oe!=="string")return[e([...U,de],"must be a non-empty string")];return oe===""?[rn([...U,de],"must be a non-empty string")]:[]});if(G.some((oe)=>typeof oe!=="string"))return re;return[...re,...G.length===0?[rn(U,j)]:[],...K&&new Set(G).size!==G.length?[rn(U,"must not contain duplicate values")]:[]]}function Rb(G){if(G===void 0)return[];if(!Array.isArray(G))return[e(["tests"],"must be an array if provided")];return G.flatMap((U,j)=>{if(!lr(U))return[e(["tests",j],"must be an object")];return[...typeof U.command==="string"&&U.command.trim()!==""?[]:[e(["tests",j,"command"],"required non-empty string")],...U.expect==="blocked"||U.expect==="allowed"?[]:[e(["tests",j,"expect"],'must be "blocked" or "allowed"')],...U.rule===void 0||typeof U.rule==="string"?[]:[e(["tests",j,"rule"],"must be a string if provided")],...U.expect==="blocked"&&typeof U.rule!=="string"?[rn(["tests",j,"rule"],"required string for blocked fixtures")]:[]]})}function xb(G){if(!Array.isArray(G.tests))return[];let U=new Set(De(G));return[...new Set(G.tests.flatMap((j)=>lr(j)&&j.expect==="blocked"&&typeof j.rule==="string"?[j.rule]:[]))].filter((j)=>!U.has(j)).map((j)=>rn(["tests"],`blocked fixture references unknown rule "${j}"`))}function _b(G){if(!Array.isArray(G.allowed_commands)||!Array.isArray(G.rules))return[];let U=new Set(G.allowed_commands.filter((j)=>typeof j==="string"));return G.rules.flatMap((j,K)=>{let re=lr(j)?j.command:void 0;if(typeof re!=="string"||U.has(re))return[];return[rn(["rules",K,"command"],`"${re}" must be listed in allowed_commands`)]})}function lr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function Q(G,U){let j=X(G,U),K;try{K=Ld(j.userConfigTarget,j.projectConfigTarget)}catch(pt){if(pt instanceof o)return Db(j,pt.message);throw pt}let re=m(j.userConfigTarget),oe=K?{config:null,errors:[]}:m(j.projectConfigTarget),de=iu(j.userConfigPath,re.errors),Se=iu(j.projectConfigPath,oe.errors),we=new Set,We=re.config?Wa(re.config,wr(j.userConfigPath),"user",j.userScope,we):su(),mt=oe.config?Wa(oe.config,wr(j.projectConfigPath),"project",j.projectScope,we):su(),gt=re.config?.overrides??{},ft=oe.config?.overrides??{};return{rules:[...ou(We.rules,gt),...ou(mt.rules,ft)],transparent_wrappers:Ob(re.config,oe.config),rulebooks:[...We.rulebooks,...mt.rulebooks],errors:[...de,...Se,...We.errors,...mt.errors],warnings:[...We.warnings,...mt.warnings,...We.canValidateOverrides?Fa(gt,We.knownRuleIds,j.userConfigPath):[],...We.canValidateOverrides?Mb(ft,We.knownRuleIds,j.projectConfigPath):[],...mt.canValidateOverrides?Fa(ft,mt.knownRuleIds,j.projectConfigPath):[]],userConfig:re.config??void 0,projectConfig:oe.config??void 0,...j}}function B(G,U){let j=wb(G,U);if(!j)return[];return[...j.scope.errors,...j.scope.warnings,...Ab(j.config,j.scope,G)]}function wb(G,U){let j=U??S(wr(wr(G)),"rules policy"),K=m(i(j,G)).config;if(!K)return null;return{config:K,scope:Wa(K,wr(G),"project",j)}}function Ab(G,U,j){return U.canValidateOverrides?Fa(G.overrides??{},U.knownRuleIds,j):[]}function Wa(G,U,j,K=S(wr(wr(U)),j==="user"?"user policy":"project policy"),re=new Set){let oe=[],de=[],Se=G.rules.flatMap((We)=>{let mt=Tb(We,U,K);if(mt.errors.length>0||!mt.rulebook)return oe.push(...mt.errors),[];let gt=mt.rulebook;if(re.has(gt.name))return de.push(`duplicate active rulebook name "${gt.name}" for ${We}; keeping the first and ignoring this one, so its rules are not active; rename one of them in its rulebook file and in the rules config that lists it`),[];return re.add(gt.name),[{rules:Pb(gt),rulebook:{source:j,spec:We,name:gt.name,version:gt.version,rules:gt.rules.map((ft)=>`${gt.name}/${ft.name}`)}}]}),we=Se.flatMap((We)=>We.rules);return{rules:we,rulebooks:Se.map((We)=>We.rulebook),knownRuleIds:new Set(we.map((We)=>We.name)),errors:oe,warnings:de,canValidateOverrides:oe.length===0}}function Pb(G){if(G.rulebook_version===2)return G.rules.map((U)=>({name:`${G.name}/${U.name}`,command:U.command,block_args:[],match:U.match,reason:U.reason,intent:U.intent}));return G.rules.map((U)=>({...U,name:`${G.name}/${U.name}`,match:void 0}))}function Tb(G,U,j){let K=Ne(G),re=M(U,K),oe=kb(re,j);if("error"in oe)return{rulebook:null,errors:[oe.error]};if(oe.content===null)return{rulebook:null,errors:[`missing rulebook file ${re} for ${G}; ${Ib(G)}`]};let de=xe(oe.content);if("problem"in de)return{rulebook:null,errors:[`invalid rulebook ${re}: ${de.problem}; fix that file`]};if(de.rulebook.name!==K)return{rulebook:null,errors:[`rulebook name "${de.rulebook.name}" in ${re} must match source "${G}"; fix that file`]};return{rulebook:de.rulebook,errors:[]}}function Ne(G){return w(G)?N(G).name:G}function Ib(G){return w(G)?`run ${Vd} to vendor ${G}`:"create that file or remove that source from the rules config"}function kb(G,U){try{return{content:r(i(U,G))}}catch(j){if(j instanceof o)return{error:j.message};throw j}}function xe(G){let U;try{U=JSON.parse(G)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:le(U)}}catch(j){return{problem:j instanceof Error?j.message:"invalid rulebook"}}}function Ob(G,U){return[...new Set([...G?.transparent_wrappers??[],...U?.transparent_wrappers??[]])]}function ou(G,U){return G.flatMap((j)=>{let K=U[j.name];if(K==="off")return[];if(K&&typeof K==="object")return[{...j,intent:K.intent??j.intent,reason:K.reason}];return[j]})}function Fa(G,U,j){return Object.keys(G).filter((K)=>!U.has(K)).map((K)=>`unknown override key "${K}" in ${j}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function Mb(G,U,j){return Object.keys(G).filter((K)=>U.has(K)).map((K)=>`project override cannot target user-scoped rule "${K}" in ${j}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function iu(G,U){return U.map((j)=>j.startsWith("Unable to access ")?j:`${G}: ${j}`)}function Db(G,U){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[U],warnings:[],userConfigPath:G.userConfigPath,projectConfigPath:G.projectConfigPath}}function su(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as jb,readFileSync as Vb}from"node:fs";var au=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores, with or without --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.nested-recursive-delete-unread",category:"PowerShell",label:"Nested PowerShell recursive delete not read",description:"Blocks a recursive delete handed to powershell or pwsh in any form other than literal -Command script words.",example:"pwsh -WorkingDirectory C:\\ -c 'Remove-Item -Recurse -Force *'",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-root-or-home",category:"Command Prompt",label:"cmd recursive delete root or home",description:"Blocks cmd rmdir /s or del /s of root or home paths.",example:"cmd /c rmdir /s /q C:\\",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-escaped-quote",category:"Command Prompt",label:"cmd recursive delete with escaped quotes",description:"Blocks cmd rmdir /s or del /s whose quoting can reach cmd as \\\" and split the target down to the drive root.",example:'cmd /c "rmdir /s /q \\"build output\\""',intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-git-metadata",category:"Command Prompt",label:"cmd recursive delete Git metadata",description:"Blocks cmd rmdir /s or del /s of protected Git metadata and hooks.",example:"cmd /c rmdir /s /q .git",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-dynamic-target",category:"Command Prompt",label:"cmd recursive delete dynamic target",description:"Blocks cmd rmdir /s or del /s with wildcard or variable targets in strict mode.",example:"cmd /c del /s /q *.log",intent:"scope_down",activationCapability:"fail_closed"},{id:"cmd.recursive-delete-home-cwd",category:"Command Prompt",label:"cmd recursive delete from home cwd",description:"Blocks cmd rmdir /s or del /s while working in home.",example:"Set-Location $HOME; cmd /c rmdir /s /q build",intent:"scope_down"},{id:"cmd.recursive-delete-cwd-self",category:"Command Prompt",label:"cmd recursive delete current directory",description:"Blocks cmd rmdir /s or del /s of the current directory.",example:"cmd /c rmdir /s /q .",intent:"scope_down"},{id:"cmd.recursive-delete-outside-cwd",category:"Command Prompt",label:"cmd recursive delete outside cwd",description:"Blocks cmd rmdir /s or del /s outside the original cwd.",example:"cmd /c rmdir /s /q ..\\outside",intent:"scope_down"},{id:"cmd.recursive-delete-paranoid",category:"Command Prompt",label:"cmd recursive delete paranoid mode",description:"Blocks non-temp cmd rmdir /s or del /s when paranoid rm is enabled.",example:"cmd /c rmdir /s /q build",intent:"scope_down",activationCapability:"paranoid_rm"},{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 other than /dev/null, /dev/zero, or /dev/full.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"Filesystem format on a device",description:"Blocks mkfs, mke2fs, and newfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"disk.erase",category:"Filesystem",label:"Disk erase or repartition",description:"Blocks diskutil erase and partition verbs, wipefs -a/-o, sgdisk writes, and parted label or partition edits on a /dev device.",example:"diskutil eraseDisk APFS Untitled disk4",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:"redirect.block-device",category:"Filesystem",label:"Redirect onto a disk device",description:"Blocks output redirects whose literal target is a disk device path under /dev.",example:"cat disk.img > /dev/sda",intent:"manual_only"},{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"}],Ga=new Set(au.map((G)=>G.id)),z=au,Nb=new Map(z.map((G)=>[G.id,G.intent]));function Rt(G,U){return{id:G,reason:U,intent:Nb.get(G)??"manual_only"}}var za=[{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"}],$i={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Lb=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Wb=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],$a=[{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"]},...Wb.flatMap((G)=>Lb.map((U)=>({id:["secret.home",G.idSlug,U.slice(1)].join("."),category:"Home path",label:[G.label,U].join(""),description:["Blocks home ",G.label,U," credential backup files."].join(""),suffixParts:[...G.directoryParts,[G.basename,U].join("")]}))),{id:"secret.home.gh-hosts",category:"Home path",label:"~/.config/gh/hosts.yml",description:"Blocks GitHub CLI host credential files.",suffixParts:[".config","gh","hosts.yml"]}];var Bi=[{id:"secret.cli.claude-code",category:"Coding CLI credential",label:"Claude Code credentials",paths:["~/.claude/.credentials.json"]},{id:"secret.cli.claude-code.config",category:"Coding CLI config",label:"Claude Code config",paths:["~/.claude/settings.json","~/.claude/settings.local.json","~/.claude.json","<project>/.claude/settings.local.json","<project>/.mcp.json"]},{id:"secret.cli.antigravity",category:"Coding CLI config",label:"Antigravity CLI hook config",paths:["~/.gemini/config/hooks.json","~/.gemini/config/mcp_config.json"]},{id:"secret.cli.codex",category:"Coding CLI credential",label:"Codex credentials",paths:["~/.codex/auth.json","~/.codex/.credentials.json","~/.codex/secrets","~/.codex/.sandbox-secrets"]},{id:"secret.cli.codex.config",category:"Coding CLI config",label:"Codex config",paths:["~/.codex/config.toml","~/.codex/<name>.config.toml"]},{id:"secret.cli.gemini",category:"Coding CLI credential",label:"Gemini CLI credentials",paths:["~/.gemini/oauth_creds.json","~/.gemini/mcp-oauth-tokens.json","~/.gemini/a2a-oauth-tokens.json","~/.gemini/gemini-credentials.json"]},{id:"secret.cli.gemini.config",category:"Coding CLI config",label:"Gemini CLI config",paths:["~/.gemini/settings.json","~/.gemini/google_accounts.json","<project>/.gemini/settings.json","/Library/Application Support/GeminiCli/settings.json","/etc/gemini-cli/settings.json"]},{id:"secret.cli.copilot-cli",category:"Coding CLI credential",label:"GitHub Copilot CLI credentials",paths:["~/.copilot/config.json","~/.copilot/mcp-oauth-config","~/.copilot/mcp-secrets"]},{id:"secret.cli.copilot-cli.config",category:"Coding CLI config",label:"GitHub Copilot CLI config",paths:["~/.copilot/mcp-config.json"]},{id:"secret.cli.kimi-code",category:"Coding CLI credential",label:"Kimi Code credentials",paths:["~/.kimi-code/server.token","~/.kimi-code/credentials","~/.kimi/credentials","~/.kimi/mcp-oauth"]},{id:"secret.cli.kimi-code.config",category:"Coding CLI config",label:"Kimi Code config",paths:["~/.kimi-code/config.toml","~/.kimi-code/mcp.json","~/.kimi/config.toml","~/.kimi/config.json","~/.kimi/config.json.bak","~/.kimi/mcp.json","<project>/.kimi-code/mcp.json"]},{id:"secret.cli.opencode",category:"Coding CLI credential",label:"OpenCode credentials",paths:["~/.local/share/opencode/auth.json","~/.local/share/opencode/mcp-auth.json","~/.local/share/opencode/opencode.db"]},{id:"secret.cli.opencode.config",category:"Coding CLI config",label:"OpenCode config",paths:["~/.config/opencode/opencode.json","~/.config/opencode/opencode.jsonc","~/.config/opencode/config.json","/Library/Application Support/opencode/opencode.json","/etc/opencode/opencode.json","<project>/opencode.json","<project>/opencode.jsonc"]},{id:"secret.cli.pi",category:"Coding CLI credential",label:"Pi credentials",paths:["~/.pi/agent/auth.json"]},{id:"secret.cli.pi.config",category:"Coding CLI config",label:"Pi config",paths:["~/.pi/agent/models.json"]},{id:"secret.cli.amp",category:"Coding CLI credential",label:"Amp Code credentials",paths:["~/.local/share/amp/secrets.json","~/.amp/oauth"]},{id:"secret.cli.amp.config",category:"Coding CLI config",label:"Amp Code config",paths:["~/.config/amp/settings.json","~/.config/amp/settings.jsonc","<project>/.amp/settings.json","<project>/.amp/settings.jsonc"]},{id:"secret.cli.cursor",category:"Coding CLI credential",label:"Cursor CLI credentials",paths:["~/.cursor/auth.json","~/.config/cursor/auth.json","~/.cursor/projects/<name>/mcp-auth.json"]},{id:"secret.cli.cursor.config",category:"Coding CLI config",label:"Cursor CLI config",paths:["~/.cursor/mcp.json","<project>/.cursor/mcp.json"]},{id:"secret.cli.grok-build",category:"Coding CLI credential",label:"Grok Build credentials",paths:["~/.grok/auth.json","~/.grok/mcp_credentials.json"]},{id:"secret.cli.grok-build.config",category:"Coding CLI config",label:"Grok Build config",paths:["~/.grok/config.toml","~/.grok/managed_config.toml","~/.grok/requirements.toml","<project>/.grok/config.toml","/etc/grok/managed_config.toml","/etc/grok/requirements.toml"]},{id:"secret.cli.droid",category:"Coding CLI credential",label:"Factory Droid credentials",paths:["~/.factory/auth.encrypted","~/.factory/auth.v2.file","~/.factory/auth.v2.key","~/.factory/auth.v2.loginkeychain"]},{id:"secret.cli.droid.config",category:"Coding CLI config",label:"Factory Droid config",paths:["~/.factory/settings.json","~/.factory/hooks.json","~/.factory/mcp.json","<project>/.factory/mcp.json"]},{id:"secret.cli.devin",category:"Coding CLI credential",label:"Devin CLI credentials",paths:["~/.local/share/devin/credentials.toml","~/.local/share/devin/mcp/oauth"]},{id:"secret.cli.devin.config",category:"Coding CLI config",label:"Devin CLI config",paths:["~/.config/devin/config.json"]}],lu=[{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"}],Fb=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Ba=lu.map((G)=>({id:`secret.variant.${G.slug}.separator`,category:"Variant",label:`${G.label}-* / ${G.label}_*`,description:`Blocks ${G.label} variants with dash or underscore suffixes.`,prefix:G.prefix})),Ua=lu.flatMap((G)=>Fb.map((U)=>({id:`secret.variant.${G.slug}.${U.slice(1)}`,category:"Variant",label:`${G.label}${U}`,description:`Blocks ${G.label}${U} private credential variants.`,prefix:G.prefix,suffix:U}))),Bo={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)$/},Ha=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((G)=>({id:`secret.ext.${G}`,category:"Extension",label:`.${G}`,description:`Blocks files with the .${G} extension.`,extension:G})),ja=[{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?$/}],Qe=[...za,$i,...$a,...Ba,...Ua,Bo,...Ha,...ja,...Bi].map((G)=>({id:G.id,category:G.category,label:G.label,...G.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in G?{paths:G.paths}:{description:G.description}})),Ui=new Set(Bi.flatMap((G)=>G.category==="Coding CLI config"?[G.id]:[])),Va=new Set(Qe.map((G)=>G.id));import{isAbsolute as Ka,join as Gb,normalize as zb,sep as Hi}from"node:path";var ji=process.platform==="win32",cu=/[*?]/;function qa(G){let U=G.trim(),j=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(ji?U.replaceAll("\\","/"):U);if(!j)return null;let K=j[1]??"",re=j[2]??"";if(cu.test(K)||re==="."||re==="..")return null;return{root:K||"/",name:re}}function Uo(G,U){if(G==="~")return U;if(G.startsWith("~/"))return`${U}${G.slice(1)}`;return G}function Ya(G,U){if(typeof G!=="string"||G.trim()==="")return"must be a non-empty path string";let j=Uo(G.trim(),U);if(!Ka(j))return"must be an absolute path or start with ~/";return Ho(j,U)}function Za(G,U){let j=du(G,U);if(j===null)return"must be a non-empty path string";if(!Ka(j))return null;if(Ho(j,U)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var $b="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Bb="cannot cover the guard's own configuration";function du(G,U){if(typeof G!=="string"||G.trim()==="")return null;let j=G.trim(),K=ji?j.replaceAll("\\","/"):j;return Uo(K.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),U)}function Xa(G,U){let j=du(G,U);if(j===null)return"must be a non-empty path string";let K=qa(j)?.root??j;if(cu.test(K))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Ka(K))return null;if(Ho(K,U)!==null)return $b;return Ub(K,U)?Bb:null}function Ub(G,U){let j=Vi(G),K=Vi(Gb(U,".cc-safety-net"));return j===K||j.startsWith(`${K}${Hi}`)}function Ho(G,U){let j=Vi(G),K=Vi(U);if(j===K)return"cannot be the home directory";let re=j.endsWith(Hi)?j:`${j}${Hi}`;if(K.startsWith(re))return"cannot contain the home directory";return null}function Vi(G){let U=zb(G);if(ji)U=U.replace(/\//g,"\\").toLowerCase();if(U.length>(ji?3:1)&&U.endsWith(Hi))U=U.slice(0,-1);return U}var uu=30,Ki=1,qi=365;function mu(G){if(typeof G!=="number"||!Number.isInteger(G))return 30;if(G<1)return 1;return G>365?365:G}var fu=new Set(z.filter((G)=>G.catastrophic).map((G)=>G.id));function Tt(G,U){if(!G)return null;if(fu.has(G.id))return G;if(U?.destructiveCommandProtectionEnabled===!1)return null;let j=U?.effectiveDestructiveCommandRules[G.id];return j&&!j.enabled?null:G}function Jt(G,U,j){if(fu.has(U))return!0;if(G?.destructiveCommandProtectionEnabled===!1)return!1;return G?.effectiveDestructiveCommandRules[U]?.enabled??j}function V(G,U){return Object.freeze(Object.fromEntries(z.map((j)=>{let K=j.activationCapability?U[j.activationCapability]:void 0,re=K?.enabled??!0,oe=G.destructiveCommandRuleOverrides[j.id],de=j.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...oe?{override:oe}:{}}:G.destructiveCommandProtectionEnabled?oe?{enabled:oe==="on",inheritedEnabled:re,changesInherited:oe==="on"!==re,source:"rule_override",...j.activationCapability?{activationCapability:j.activationCapability}:{},override:oe}:{enabled:re,inheritedEnabled:re,changesInherited:!1,source:K?.source??"built_in_default",...j.activationCapability?{activationCapability:j.activationCapability}:{}}:{enabled:!1,inheritedEnabled:re,changesInherited:!1,source:"master_disabled",...j.activationCapability?{activationCapability:j.activationCapability}:{},...oe?{override:oe}:{}};return[j.id,Object.freeze(de)]})))}function pu(G,U){return Object.freeze({...G,effectiveDestructiveCommandRules:V(G,U)})}var gu={standard:0,strict:1,paranoid:2};function ee(G,U,j=!1,K=G.safety.level){let re=Hb(G,U,K),oe=new Set(j?re.map((mt)=>mt.field):[]),de=(mt,gt)=>oe.has(mt)?void 0:gt,Se=(mt,gt)=>Object.fromEntries(Object.entries(gt??{}).filter(([ft])=>!oe.has(`${mt}.${ft}`))),we=(mt,gt)=>gt?.filter((ft)=>!oe.has(`${mt}.${ft}`));return{policy:{version:1,safety:{level:de("safety.level",U.safety?.level)??G.safety.level,overrides:{...G.safety.overrides,...Se("safety.overrides",U.safety?.overrides)}},workflow:{worktree_mode:de("workflow.worktree_mode",U.workflow?.worktree_mode)??G.workflow.worktree_mode},destructive_command_protection:{enabled:de("destructive_command_protection.enabled",U.destructive_command_protection?.enabled)??G.destructive_command_protection.enabled,overrides:{...G.destructive_command_protection.overrides,...Se("destructive_command_protection.overrides",U.destructive_command_protection?.overrides)},allow_paths:Ja(G.destructive_command_protection.allow_paths,we("destructive_command_protection.allow_paths",U.destructive_command_protection?.allow_paths))},secret_protection:{enabled:de("secret_protection.enabled",U.secret_protection?.enabled)??G.secret_protection.enabled,overrides:{...G.secret_protection.overrides,...Se("secret_protection.overrides",U.secret_protection?.overrides)},deny_paths:Ja(G.secret_protection.deny_paths,U.secret_protection?.deny_paths),allow_paths:Ja(G.secret_protection.allow_paths,we("secret_protection.allow_paths",U.secret_protection?.allow_paths))},audit:G.audit},weakenings:re.map((mt)=>mt.message)}}function Ja(G,U){return[...new Set([...G,...U??[]])]}function Hb(G,U,j){let K=U.safety?.level,re=ki[j];return[...K&&gu[K]<gu[G.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${G.safety.level} -> ${K}`}]:[],...Zr.flatMap((oe)=>U.safety?.overrides?.[oe]===!1&&(G.safety.overrides[oe]??re[oe])?[{field:`safety.overrides.${oe}`,message:`project policy disables ${oe}`}]:[]),...U.workflow?.worktree_mode===!0&&!G.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...U.destructive_command_protection?.enabled===!1&&G.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...U.secret_protection?.enabled===!1&&G.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...hu("destructive_command_protection.overrides",U.destructive_command_protection?.overrides,(oe)=>G.destructive_command_protection.enabled&&G.destructive_command_protection.overrides[oe]!=="off"),...hu("secret_protection.overrides",U.secret_protection?.overrides,(oe)=>G.secret_protection.enabled&&(G.secret_protection.overrides[oe]==="on"?!0:G.secret_protection.overrides[oe]!=="off"&&!Ui.has(oe))),...G.destructive_command_protection.enabled?yu(G.destructive_command_protection.allow_paths,U.destructive_command_protection?.allow_paths).map((oe)=>({field:`destructive_command_protection.allow_paths.${oe}`,message:`project policy adds destructive allow path: ${oe}`})):[],...G.secret_protection.enabled?yu(G.secret_protection.allow_paths,U.secret_protection?.allow_paths).map((oe)=>({field:`secret_protection.allow_paths.${oe}`,message:`project policy adds secret allow path: ${oe}`})):[]]}function hu(G,U,j){return Object.entries(U??{}).flatMap(([K,re])=>re==="off"&&j(K)?[{field:`${G}.${K}`,message:`project policy disables rule ${K}`}]:[])}function yu(G,U){return(U??[]).filter((j)=>!G.includes(j))}var tl=new Set(["standard","strict","paranoid"]),te={version:1,safety:{level:"standard",overrides:{}},workflow:{worktree_mode:!1},destructive_command_protection:{enabled:!0,overrides:{},allow_paths:[]},secret_protection:{enabled:!0,overrides:{},deny_paths:[],allow_paths:[]},audit:{retention_days:uu}};function vu(G,U){let j=Jb(l(G,U),G.home),K=L(G,U)?{exists:!1,policy:F(),errors:[]}:Me(h(U.cwd),G.home),re=ue(K.parsed,G.home),oe=v(n.projectTightenOnly,G.env),de=j.gui??te,Se=Object.keys(re.policy).length>0?ee(de,re.policy,oe,Id(de.safety.level,G.env)):void 0,we=[...j.errors,...K.errors,...re.diagnostics],We=(j.fallback==="defaults"&&Se?"salvaged":j.fallback)??(j.gui?void 0:K.fallback)??(we.length>0?"salvaged":void 0),mt=re.policy.safety?.level&&Se?.policy.safety.level===re.policy.safety.level?"project":j.levelPresent?"user":"default";return{...Se?el(Se.policy):j.policy,errors:we,...We?{fallback:We}:{},...K.exists?{policyScopes:{levelScope:mt,weakenings:Se?.weakenings??[],weakeningsIgnored:oe}}:{}}}var Kb="project policy audit settings are ignored; audit is user scope only";function ue(G,U){if(!Rn(G))return{policy:{},diagnostics:[]};let j=Rn(G.safety)?G.safety:{},K=Rn(G.workflow)?G.workflow:{},re=Rn(G.destructive_command_protection)?G.destructive_command_protection:{},oe=Rn(G.secret_protection)?G.secret_protection:{},de={...tl.has(j.level)?{level:j.level}:{},...Rn(j.overrides)?bu({overrides:Eu(j.overrides,Zr,["safety","overrides"],Ar)}):{}},Se={...typeof re.enabled==="boolean"?{enabled:re.enabled}:{},...re.overrides!==void 0?{overrides:Yi(re.overrides,Ga,xu,Ar)}:{},...re.allow_paths!==void 0?{allow_paths:eo(re.allow_paths,Ya,U,["destructive_command_protection","allow_paths"],Ar)}:{}},we={...typeof oe.enabled==="boolean"?{enabled:oe.enabled}:{},...oe.overrides!==void 0?{overrides:Yi(oe.overrides,Va,_u,Ar)}:{},...oe.deny_paths!==void 0?{deny_paths:eo(oe.deny_paths,Za,U,["secret_protection","deny_paths"],Ar)}:{},...oe.allow_paths!==void 0?{allow_paths:eo(oe.allow_paths,Xa,U,["secret_protection","allow_paths"],Ar)}:{}};return{policy:bu({safety:de,workflow:typeof K.worktree_mode==="boolean"?{worktree_mode:K.worktree_mode}:{},destructive_command_protection:Se,secret_protection:we}),diagnostics:G.audit===void 0?[]:[Kb]}}function Eu(G,U,j,K){return Object.fromEntries(U.flatMap((re)=>{let oe=G[re];if(typeof oe==="boolean")return[[re,oe]];if(oe!==void 0)K(e([...j,re],nl));return[]}))}function bu(G){return Object.fromEntries(Object.entries(G).flatMap((U)=>Object.keys(U[1]).length>0?[U]:[]))}var Ar=()=>{return},nl="must be a boolean",rl="must be an object if provided",Ru=`must be an integer between ${Ki} and ${qi}`,xu={path:["destructive_command_protection","overrides"],label:"destructive command"},_u={path:["secret_protection","overrides"],label:"secret protection"},et=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function tt(G,U){let j=[];return{policy:wu(G,U,(re)=>{j.push(re)}),issues:j}}function E(G,U){return wu(G,U,Ar)}function wu(G,U,j){if(!Rn(G))return j(e([],"Config must be an object")),F();if(G.version!==1)j(e(["version"],"must be 1"));let K=Qr(G.safety,["safety"],["level","overrides"],j),re=Qr(K.overrides,["safety","overrides"],Zr,j),oe=Qr(G.workflow,["workflow"],["worktree_mode"],j),de=Qr(G.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],j),Se=Qr(G.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],j),we=Qr(G.audit,["audit"],["retention_days"],j);return Au(G,et,[],j),{version:1,safety:{level:qb(K.level,j),overrides:Eu(re,Zr,["safety","overrides"],j)},workflow:{worktree_mode:Qa(oe.worktree_mode,["workflow","worktree_mode"],!1,j)},destructive_command_protection:{enabled:Qa(de.enabled,["destructive_command_protection","enabled"],!0,j),overrides:Yi(de.overrides,Ga,xu,j),allow_paths:eo(de.allow_paths,Ya,U,["destructive_command_protection","allow_paths"],j)},secret_protection:{enabled:Qa(Se.enabled,["secret_protection","enabled"],!0,j),overrides:Yi(Se.overrides,Va,_u,j),deny_paths:eo(Se.deny_paths,Za,U,["secret_protection","deny_paths"],j),allow_paths:eo(Se.allow_paths,Xa,U,["secret_protection","allow_paths"],j)},audit:{retention_days:Yb(we.retention_days,j)}}}function Qr(G,U,j,K){if(G===void 0)return{};if(!Rn(G))return K(e(U,rl)),{};return Au(G,j,U,K),G}function Au(G,U,j,K){for(let re of Object.keys(G).filter((oe)=>!U.includes(oe)))K({path:j,message:re,kind:"unknownKeys"})}function qb(G,U){if(G===void 0)return"standard";if(tl.has(G))return G;return U(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Qa(G,U,j,K){if(typeof G==="boolean")return G;if(G!==void 0)K(e(U,nl));return j}function Yb(G,U){if(!(G===void 0||typeof G==="number"&&Number.isInteger(G)&&G>=Ki&&G<=qi))U(e(["audit","retention_days"],Ru));return mu(G)}function Yi(G,U,j,K){if(G===void 0)return{};if(!Rn(G))return K(e(j.path,rl)),{};return Object.fromEntries(Object.entries(G).flatMap(([re,oe])=>{if(!U.has(re))return K({path:[...j.path,re],message:`unknown ${j.label} rule id "${re}"`,kind:"key"}),[];if(oe==="on"||oe==="off")return[[re,oe]];return K(e([...j.path,re],'must be "on" or "off"')),[]}))}function eo(G,U,j,K,re){if(G===void 0)return[];if(!Array.isArray(G))return re(e(K,"must be an array of paths")),[];return G.flatMap((oe,de)=>{let Se=U(oe,j);if(Se===null)return[oe];return re(typeof oe==="string"?rn([...K,de],Se):e([...K,de],Se)),[]})}function Rn(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function F(){return structuredClone(te)}function Le(G,U){let j=T({safety:$e(G.safety)},U),K=V({destructiveCommandProtectionEnabled:G.destructive_command_protection.enabled,destructiveCommandRuleOverrides:G.destructive_command_protection.overrides},j.capabilities),re=Object.values(K),oe=re.filter((de)=>de.source!=="catastrophic");return{selectedPreset:G.safety.level,effectiveLevel:j.effectiveLevel,capabilities:j.capabilities,rules:K,counts:{enabled:oe.filter((de)=>de.enabled).length,disabled:oe.filter((de)=>!de.enabled).length,effectiveCustomizations:re.filter((de)=>de.changesInherited).length}}}function Me(G,U){if(!jb(G))return{exists:!1,policy:F(),errors:[]};try{let j=Vb(G,"utf-8");if(!j.trim())return{exists:!0,policy:F(),errors:[`${G}: Config file is empty`],fallback:"defaults"};let K=JSON.parse(j),re=tt(K,U);if(re.issues.length===0)return{exists:!0,parsed:K,policy:re.policy,errors:[]};return{exists:!0,parsed:K,policy:re.policy,errors:re.issues.map((oe)=>`${G}: ${Xb(oe)}`),fallback:Rn(K)?"salvaged":"defaults"}}catch(j){let K=j instanceof Error?j.message:String(j);return{exists:!0,policy:F(),errors:[`${G}: ${j instanceof SyntaxError?"Invalid JSON":K}`],fallback:"defaults"}}}var Zb=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[rl,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[nl,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Ru,`not an integer between ${Ki} and ${qi}`]]);function Xb(G){let U=La(G.path);if(G.kind==="unknownKeys")return`${U===""?"":`${U}.`}${G.message}: unknown field`;if(G.kind==="key")return`${U}: unknown rule id`;let j=Zb.get(G.message)??G.message;return U===""?j:`${U}: ${j}`}function Jb(G,U){let j=Me(G,U);if(!j.exists){let K=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!Rn(K))return{policy:Su(),errors:[]};let re=E(K,U);return{policy:el(re),gui:re,errors:[],levelPresent:Cu(K)}}if(j.parsed===void 0)return{policy:Su(),errors:j.errors,...j.fallback?{fallback:j.fallback}:{}};return{policy:el(j.policy),gui:j.policy,errors:j.errors,...j.fallback?{fallback:j.fallback}:{},levelPresent:Cu(j.parsed)}}function Cu(G){let U=Rn(G)&&Rn(G.safety)?G.safety:{};return tl.has(U.level)}function Fe(G){let U=Object.entries(G),j=new Set(U.flatMap(([K,re])=>re==="on"?[K]:[]));return[...new Set([...[...Ui].filter((K)=>!j.has(K)),...U.flatMap(([K,re])=>re==="off"?[K]:[])])]}function Su(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Fe({}),denyPaths:[],allowPaths:[]}}}function el(G){return{safety:$e(G.safety),worktreeMode:G.workflow.worktree_mode,destructiveCommandProtectionEnabled:G.destructive_command_protection.enabled,destructiveCommandRuleOverrides:G.destructive_command_protection.overrides,destructiveCommandAllowPaths:G.destructive_command_protection.allow_paths,secretProtection:{enabled:G.secret_protection.enabled,disabledRules:Fe(G.secret_protection.overrides),denyPaths:G.secret_protection.deny_paths,allowPaths:G.secret_protection.allow_paths}}}function $e(G){let U={...G.overrides.fail_closed!==void 0?{failClosed:G.overrides.fail_closed}:{},...G.overrides.paranoid_rm!==void 0?{paranoidRm:G.overrides.paranoid_rm}:{},...G.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:G.overrides.paranoid_interpreters}:{}};return{level:G.level,...Object.keys(U).length>0?{overrides:U}:{}}}function k(G,U){let j=Q(G,U),K=vu(G,U),re={rules:j.rules,transparentWrappers:j.transparent_wrappers,safety:K.safety,worktreeMode:K.worktreeMode,destructiveCommandProtectionEnabled:K.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:K.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:K.destructiveCommandAllowPaths,secretProtection:{enabled:K.secretProtection.enabled??!0,disabledRules:K.secretProtection.disabledRules??[],denyPaths:K.secretProtection.denyPaths,allowPaths:K.secretProtection.allowPaths??[]}},oe={...j.userConfig?.overrides,...j.projectConfig?.overrides},de=Object.freeze(Object.fromEntries(re.rules.map((Se)=>{let we=j.rulebooks.find((mt)=>mt.rules.includes(Se.name)),We=oe[Se.name];return[Se.name,Object.freeze({id:Se.name,...we?{rulebook:Object.freeze({name:we.name,version:we.version}),...nC(we.spec)?{source:we.spec}:{}}:{},...We&&typeof We==="object"?{override:Object.freeze({type:"reason",reason:We.reason})}:{}})]})));return _e(re,Qb(j,K),de,K.policyScopes)}function je(G){if(G.state==="ready")return{state:G.state};return{state:G.state,reason:G.reason}}function Qb(G,U){let j=tC(U);if(G.errors.length===0&&G.warnings.length===0&&!j)return;return{diagnostics:[...G.errors,...G.warnings,...U.errors],reason:rC(G.errors.length>0?eC(G.errors):void 0,G.warnings.length>0?il(G.warnings.join("; ")):void 0,j)}}function eC(G){return`${il(G.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function tC(G){if(G.errors.length===0)return;let U=G.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${G.errors.join("; ")}. Enforcing ${U}; the invalid values are not active. Fix the policy file manually`}function nC(G){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(G)}function _e(G,U,j=Object.freeze({}),K){let re=ol(structuredClone(G)),oe=K?{policyScopes:ol(structuredClone(K))}:{};if(!U)return Object.freeze({state:"ready",policy:re,diagnostics:Object.freeze([]),ruleMetadata:j,...oe});return Object.freeze({state:"degraded",policy:re,diagnostics:Object.freeze([...U.diagnostics]),reason:U.reason,ruleMetadata:j,...oe})}function ol(G){if(typeof G!=="object"||G===null)return G;for(let U of Object.values(G))ol(U);return Object.freeze(G)}function rC(...G){return il(G.filter((U)=>!!U).join("; "))}function il(G){return/[.!?]$/.test(G)?G:`${G}.`}function Ue(G){let U=G.effectiveCapabilities,j=G.strict??U.fail_closed.enabled,K=G.paranoidRm??U.paranoid_rm.enabled,re=G.paranoidInterpreters??U.paranoid_interpreters.enabled,oe={fail_closed:sl(U.fail_closed,G.strict,"strict"),paranoid_rm:sl(U.paranoid_rm,G.paranoidRm,"paranoidRm"),paranoid_interpreters:sl(U.paranoid_interpreters,G.paranoidInterpreters,"paranoidInterpreters")};return{policy:pu(G.policySnapshot.policy,oe),effectiveCapabilities:oe,effectiveLevel:Ra({failClosed:j,paranoidRm:K,paranoidInterpreters:re}),strict:j,paranoidRm:K,paranoidInterpreters:re,worktreeMode:G.worktreeMode??!1}}function sl(G,U,j){if(U===void 0||U===G.enabled)return G;return{enabled:U,source:"capability_override",sources:[...G.sources,`analysis options.${j}`]}}import{dirname as oA,isAbsolute as iA,join as sA,parse as aA,resolve as lA,sep as cA}from"node:path";function jo(G,U){if(G!=="powershell")return U[0]?.provenance==="command-substitution";let j=U[0]?.text==="&"||U[0]?.text==="."?1:0,K=U[j]?.provenance;return K!==void 0&&K!=="literal"}var oC=/^[A-Za-z_][A-Za-z0-9_]*=/;function Zi(G,U){return G?.provenance==="literal"&&!G.quoted&&G.raw===U&&G.text===U}function Vo(G){let U=Zi(G.words[0],"time")?1:0,j=U===1&&Zi(G.words[U],"-p")?U+1:U,K=U===1&&Zi(G.words[j],"--")?j+1:j,re=Zi(G.words[K],"!")?K+1:K,oe=G.words.slice(re).find((de)=>!oC.test(de.text));return oe?.provenance==="literal"?oe.text:void 0}var cr=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Xi(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function iC(G){return Object.freeze({...G,span:Object.freeze(G.span),words:Object.freeze(G.words),redirections:Object.freeze(G.redirections.map((U)=>Object.freeze({...U,span:Object.freeze(U.span),...U.heredoc?{heredoc:Object.freeze({...U.heredoc,bodySpan:Object.freeze(U.heredoc.bodySpan),terminatorSpan:Object.freeze(U.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(G.nested.map((U)=>pn(U)))})}function Ji(G,U,j){G.push(j),U.reset()}function Qi(G){let U=[];return{parts:U,push:(j,K,re)=>{if(K<=j)return;U.push({raw:G.slice(j,K),span:{start:j,end:K},provenance:re})}}}function al(G){let U=G.parts??[{raw:G.raw,span:G.span,provenance:G.provenance}];return Object.freeze({kind:"word",...G,span:Object.freeze(G.span),parts:Object.freeze(U.map((j)=>Object.freeze({...j,span:Object.freeze(j.span)})))})}function to(G,U,j,K,re,oe,de){return al({text:K,raw:G.slice(U,j),span:{start:U,end:j},provenance:re,quoted:oe,...de?{parts:de}:{}})}function pn(G){return Object.freeze({...G,span:Object.freeze(G.span),issues:Object.freeze(G.issues.map((U)=>Object.freeze({...U}))),nodes:Object.freeze(G.nodes.map((U)=>{if(U.kind==="command")return iC(U);if(U.kind==="group"||U.kind==="function")return Object.freeze({...U,span:Object.freeze(U.span),body:pn(U.body)});return Object.freeze({...U,span:Object.freeze(U.span)})}))})}function ll(G,U,j){if(U>=j||Tu(G[U]??""))return null;let K="",re=!1,oe=!1,de=U;while(de<j&&!Tu(G[de]??"")){let Se=G[de]??"";if(Se==="'"){re=!0;let we=Pu(G,de+1,j,"'");K+=we.text,oe||=!we.closed,de=we.next;continue}if(Se==='"'){re=!0;let we=Pu(G,de+1,j,'"');K+=we.text,oe||=!we.closed,de=we.next;continue}if(Se==="\\"){re=!0;let we=G[de+1];if(!we||we===`
|
|
7
|
-
`||we==="\r"){oe=!0;break}K+=we,de+=2;continue}if(Se==="`"||G.startsWith("$(",de)||G.startsWith("${",de)||G.startsWith("<(",de)||G.startsWith(">(",de))oe=!0;K+=Se,de++}return{delimiter:K,quoted:re,next:de,ambiguous:oe}}function cl(G,U,j,K){let re=[],oe=U;for(let de of K){let Se=oe,we=!1;while(oe<j){let We=
|
|
8
|
-
`&&G[oe]!=="\r"){let de=G[oe]??"";if(de===K)return{text:re,next:oe+1,closed:!0};if(K==='"'&&de==="\\"&&G[oe+1]){let Se=G[oe+1]??"";re+=["$","`",'"',"\\"].includes(Se)?Se:`\\${Se}`,oe+=2;continue}re+=de,oe++}return{text:re,next:oe,closed:!1}}function Tu(G){return G!=="\r"&&(/[\s;&|<>)]/u.test(G)||G==="`")}function
|
|
9
|
-
`)K++;let re=K>=j?j:K+1;return{text:G.slice(U,K),contentEnd:K,next:re}}function
|
|
10
|
-
`||pt==="\r"){gt();let
|
|
11
|
-
`?ft+2:ft+1,
|
|
12
|
-
`&&G[ft]!=="\r")ft++;continue}let ht=We.start===-1?
|
|
13
|
-
`){Se+=2;continue}de+=
|
|
3
|
+
`)}function Ce(G,U){if(G.decision.kind!=="deny")return;let j=U.includeEvidence?G.decision.evidence:void 0;return{reason:G.decision.reason,ruleId:G.decision.ruleId,intent:G.decision.intent,command:j?.command,segment:j?.segment,toolName:U.toolName,...G.configFallback?{configWarning:G.configFallback.reason}:{},...G.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function O(G={}){return{reason:ko,ruleId:"analysis.failed-closed",intent:"stop_and_explain",command:G.command,segment:G.segment??G.command,toolName:G.toolName}}var lh={session:{unusable:{reason:"CC Safety Net cannot check tool calls because the session's working directory or workspace root no longer exists, is inaccessible, is not a directory, or uses an unsupported path form. Ask the user to restart the session from an existing directory.",intent:"hard_stop",ruleId:"cwd.session-unusable"},"outside-workspace":{reason:"CC Safety Net cannot check tool calls because the session's working directory is outside its workspace roots. Ask the user to restart the session from a directory inside the workspace.",intent:"hard_stop",ruleId:"cwd.session-outside-workspace"}},requested:{unusable:{reason:"CC Safety Net could not use the requested working directory because it does not exist, is inaccessible, is not a directory, or uses an unsupported path form. Use an existing accessible working directory. If the requested directory is missing, create it from an accessible location before retrying the command.",intent:"use_alternative",ruleId:"cwd.requested-unusable"},"outside-workspace":{reason:"CC Safety Net could not use the requested working directory because it is outside the session's workspace. Use a working directory inside the workspace.",intent:"use_alternative",ruleId:"cwd.requested-outside-workspace"}}};function D(G,U={}){return{...lh[G.directory][G.problem],command:U.command,toolName:U.toolName,cwd:G.cwd}}function Y(G){return ah({...G,redact:J})}function rt(G){return J(G instanceof Error?G.message:String(G))}import{lstatSync as Hh,realpathSync as jh,statSync as Vh}from"node:fs";import{homedir as Kh,tmpdir as qh}from"node:os";import{statSync as $h}from"node:fs";import{join as Bh}from"node:path";import{basename as td,dirname as ch,isAbsolute as dh,join as uh,normalize as mh,resolve as Qc}from"node:path";var fh=256,Ai=new Set(["CC_SAFETY_NET_HOME","CLAUDE_CONFIG_DIR","CODEX_HOME","COPILOT_HOME","GEMINI_CLI_HOME","GROK_HOME","HOME","KIMI_CODE_HOME","KIMI_SHARE_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","ProgramData","TMPDIR","XDG_CONFIG_HOME","XDG_DATA_HOME"]);function cn(G,U=process.platform){if(U!=="win32")return G;return G.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function sr(G,U=process.platform){if(U!=="win32")return!1;return(G[0]==="/"||G[0]==="\\")&&(G[1]==="/"||G[1]==="\\")}function pa(G,U){return ua(G,0,U)}function ua(G,U,j){let K="",re=0,oe=0;while(re<G.length){if(G[re]!=="$"){K+=G[re],re++;continue}if(G[re+1]==="{"){let Se=ma(G,re+2),we=ph(G,re,U);if(we===null){if(Ai.has(Se))throw new s("pathEnvironmentExpansion");if(oe++,oe>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");K+="${",re+=2;continue}let We=G.slice(re,we+1);K+=gh(We,U,j),re=we+1;continue}let de=ma(G,re+1);if(!de){K+="$",re++;continue}K+=fa(de,j)??`$${de}`,re+=de.length+1}return K}function ph(G,U,j){let K=1;for(let re=U+2;re<G.length;re++){if(G[re]==="\\"){re++;continue}if(G[re]==="$"&&G[re+1]==="{"){if(K++,j+K>a.pathEnvironmentExpansion.cap)throw new s("pathEnvironmentExpansion");re++;continue}if(G[re]!=="}")continue;if(K--,K===0)return re}return null}function gh(G,U,j){let K=G.slice(2,-1),re=ma(K,0);if(!re)return G;let oe=K.slice(re.length);if(!oe)return fa(re,j)??G;let de=[":-",":+",":=",":?","-","+","=","?"].find((We)=>oe.startsWith(We));if(!de){if(Ai.has(re))throw new s("pathEnvironmentExpansion");return G}if(!Ai.has(re))return G;if(de.endsWith("="))throw new s("pathEnvironmentExpansion");let Se=fa(re,j),we=de.startsWith(":")?Se!==null&&Se!=="":Se!==null;if(de.endsWith("?")&&!we)throw new s("pathEnvironmentExpansion");if(de.endsWith("-")||de.endsWith("?"))return we?Se??"":ua(oe.slice(de.length),U+1,j);return we?ua(oe.slice(de.length),U+1,j):""}function ma(G,U){if(!/[A-Za-z_]/.test(G[U]??""))return"";let j=U+1;while(/[A-Za-z0-9_]/.test(G[j]??""))j++;return G.slice(U,j)}function fa(G,U){if(!Ai.has(G))return null;if(G==="HOME")return U.env.get("HOME")??U.home;return U.env.get(G)??null}function Wt(G,U,j){if(!G)return G;let K=j.resolvedPaths.get(G);if(K!==void 0)return K;let re=[],oe=G;while(!0){nd(j,oe);let de=U.realpath(oe);if(de!==null)return ed(j,G,de,re);let Se=ch(oe);if(Se===oe||re.length>=fh)return ed(j,G,oe,re);re.push(td(oe)),oe=Se}}function ed(G,U,j,K){let re=K.length===0?j:uh(j,...K.reverse());return G.resolvedPaths.set(U,re),re}function hh(G,U,j){let K=j.resolvedPaths.get(G);if(K!==void 0)return K;nd(j,G);let re=U.realpath(G);if(re!==null)j.resolvedPaths.set(G,re);return re}function nd(G,U){G.charge("realpathAttempts"),G.charge("processedCandidateBytes",Buffer.byteLength(U))}function dn(G,U,j,K){let re=od(G,U,j);if(!re)return"";return Wt(re,j.paths,K).replace(/\\/g,"/")}function rd(G,U,j,K,re){let oe=od(G,U,j);if(!oe)return null;if(re(td(oe)))return Wt(oe,j.paths,K).replace(/\\/g,"/");let de=hh(oe,j.paths,K);return de===null?null:de.replace(/\\/g,"/")}function od(G,U,j){let K=j.home,re=pa(G.trim(),j).replace(/\\/g,"/");if(!re)return"";let oe=re==="~"?K:re.startsWith("~/")?Qc(K,re.slice(2)):re,de=cn(oe);return mh(dh(de)?de:Qc(U,de))}import{spawnSync as yh}from"node:child_process";import{existsSync as Mo,lstatSync as bh,readFileSync as Do,realpathSync as qr,statSync as Oo}from"node:fs";import{dirname as ga,isAbsolute as ha,join as Yr,resolve as Pi}from"node:path";var Sh=["/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"],Ch=5000;function sd(G,U=Wh(),j=Ch){let K=vh(G),re=K===null?null:Eh(K);if(K===null||re===null)return null;let oe=Nh(K,re,U,j);return oe===null?null:{recursiveSubmodules:oe}}function vh(G){try{let U=qr(Pi(G));return Oo(U).isDirectory()?U:null}catch{return null}}function Eh(G){let U=Dh(G);if(!U)return null;try{let j=bh(U);if(j.isSymbolicLink()||!j.isFile())return null;let K=ya(U);if(!K?.commonDir)return null;if(!_h(K.gitDir,U))return null;return wh(K.gitDir,ga(U))?{gitDir:K.gitDir,commonDir:K.commonDir}:null}catch{return null}}function ya(G){try{let U=Rh(G);if(!U)return null;let j=qr(ha(U)?U:Pi(ga(G),U));if(!Oo(j).isDirectory())return null;return{gitDir:j,commonDir:xh(j)}}catch{return null}}function Rh(G){let U=Do(G,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!U.startsWith("gitdir:"))return null;return U.slice(7).trim()||null}function xh(G){try{let U=Do(Yr(G,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!U)return null;let j=qr(ha(U)?U:Pi(G,U));return Oo(j).isDirectory()?j:null}catch{return null}}function _h(G,U){let j=Ah(G);return j===null?!1:ad(G,j,U)}function wh(G,U){let j=Ph(G);return j===null?!0:ad(G,j,U)}function Ah(G){let U=Yr(G,"gitdir");if(!Mo(U))return null;let j=Do(U,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return j===""?null:j}function Ph(G){let U=Yr(G,"config.worktree");return Mo(U)?Ih(U):null}function ad(G,U,j){try{return Th(ha(U)?U:Pi(G,U),j)}catch{return!1}}function Th(G,U){try{let j=Oo(G),K=Oo(U);if(j.ino!==0&&K.ino!==0&&j.dev===K.dev&&j.ino===K.ino)return!0}catch{}return id(qr.native(G))===id(qr.native(U))}function id(G){let U=G.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),j=U.length>1&&U.endsWith("/")?U.slice(0,-1):U;return process.platform==="win32"?j.toLowerCase():j}function Ih(G){let U=Do(G,"utf-8"),j=!1,K=null;for(let re of U.split(/\r?\n/)){let oe=re.trim();if(oe===""||oe.startsWith("#")||oe.startsWith(";"))continue;if(oe.startsWith("[")){j=/^\[core\]$/i.test(oe);continue}if(!j)continue;let de=oe.match(/^worktree\s*=\s*(.*)$/i);if(de)K=kh(de[1]??"")}return K}function kh(G){let U=G.trim();if(!U.startsWith('"')||!U.endsWith('"'))return U;return Mh(U.slice(1,-1))}var Oh={"\\":"\\",'"':'"',n:`
|
|
4
|
+
`,t:"\t",b:"\b"};function Mh(G){return G.replace(/\\(.?)/gs,(U,j)=>j===""?U:Oh[j]??U)}function Dh(G){try{return ba(qr(G))}catch{return null}}function ba(G){let U=G;while(!0){let j=Yr(U,".git");if(Mo(j))return j;let K=ga(U);if(K===U)return null;U=K}}function Nh(G,U,j,K){if(Lh(U))return!0;if(j===null)return!0;let re=yh(j,["config","--get","submodule.recurse"],{cwd:G,encoding:"utf8",env:Fh(process.env),stdio:["ignore","pipe","ignore"],timeout:K});if(re.error!==void 0||re.status!==0&&re.status!==1)return null;return re.status===0&&ld(re.stdout.trim())}function Lh(G){return[Yr(G.commonDir,"config"),Yr(G.gitDir,"config.worktree")].filter((U)=>Mo(U)).some((U)=>Gh(U))}function Wh(){return Sh.find((G)=>Mo(G))??null}function No(G){return G==="GIT_CONFIG_COUNT"||G==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(G)}function Fh(G){return Object.fromEntries(Object.entries(G).filter(([U])=>!No(U)))}function Gh(G){let U;try{U=Do(G,"utf-8")}catch{return!0}let j="",K=!1;for(let re of U.split(/\r?\n/)){let oe=re.trim();if(oe===""||oe.startsWith("#")||oe.startsWith(";"))continue;let de=oe.match(/^\[([^\]]+)\]$/);if(de){j=de[1]?.trim().toLowerCase()??"";continue}let Se=oe.indexOf("="),we=(Se===-1?oe:oe.slice(0,Se)).trim().toLowerCase(),We=Se===-1?"true":oe.slice(Se+1).trim();if(zh(j)&&we==="path")return!0;if(j==="submodule"&&we==="recurse")K=ld(We)}return K}function zh(G){return G==="include"||G.startsWith("includeif ")}function ld(G){let U=G.toLowerCase();return U!=="false"&&U!=="no"&&U!=="off"&&U!=="0"}function cd(G,U){if(G==="")return null;let j=Pn(),K=ba(dn(G,G,U,j)),re=K?Uh(K,G,U,j):null;if(!re)return null;return Object.freeze({entries:Object.freeze([re.entry]),markerFiles:Object.freeze(re.markerFile?[re.markerFile]:[]),directories:Object.freeze(re.directories),hooksDirectories:Object.freeze(re.hooksDirectories)})}function Uh(G,U,j,K){try{let re=dn(G,U,j,K),oe=$h(G),de=oe.isFile()?re:null,Se=oe.isFile()?ya(G):null,we=(oe.isDirectory()?[re]:[Se?.gitDir,Se?.commonDir]).flatMap((mt)=>mt?[Zr(dn(mt,U,j,K))]:[]),We=[...new Set(oe.isDirectory()?[Zr(G.replace(/\\/g,"/")),...we]:we)];return{entry:Zr(re),markerFile:de?Zr(de):null,directories:We,hooksDirectories:[...new Set(We.flatMap((mt)=>{let gt=Zr(Bh(mt,"hooks").replace(/\\/g,"/"));return[gt,Zr(dn(gt,U,j,K))]}))]}}catch{return null}}function Zr(G){return process.platform==="win32"?G.toLowerCase():G}var Yh={realpath:(G)=>{try{return jh(G)}catch{return null}},entryKind:(G)=>{try{let U=Hh(G,{throwIfNoEntry:!1});if(!U)return"missing";return U.isSymbolicLink()?"symlink":"present"}catch(U){if(U.code==="ENAMETOOLONG")return"missing";throw U}},isDirectory:(G)=>{try{return Vh(G).isDirectory()}catch{return!1}}};function c(){return Zh({env:new Map(Object.entries(process.env).flatMap(([G,U])=>U===void 0?[]:[[G,U]])),home:cn(process.env.HOME||Kh()),tmpdir:qh(),paths:Yh})}function Zh(G,U={}){let j=new Map,K=new Map,re={...G,gitMetadata:(oe)=>dd(j,oe,()=>cd(oe,re)),worktreeFacts:(oe)=>dd(K,oe,()=>sd(oe)),...U};return re}function dd(G,U,j){let K=G.get(U);if(K!==void 0)return K;let re=j();return G.set(U,re),re}import{accessSync as Sy,constants as wd,statSync as Cy}from"node:fs";import{isAbsolute as Ad,relative as vy,resolve as Ey,sep as Ry}from"node:path";import{types as Xh}from"node:util";var Jh=new Set(["applypatch","patch"]),Qh=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),ey=new Set(["grep","grepsearch","rg"]),ty=new Set(["find","findbyname","glob"]),ny=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),ry=new Set(["command","diff","input","patch","patchtext"]),ud=new TextEncoder,oy=new TextDecoder,iy=/\s/,sy=64;class f extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var Lo=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function hd(G){return G.replace(/[-_\s]/g,"").toLowerCase()}function Ii(G){return ny.has(hd(G))}function P(G){let U=hd(G);if(Jh.has(U))return"patch";if(ey.has(U))return"grep";if(ty.has(U))return"glob";if(Qh.has(U))return"path";return"unknown"}function ie(G){if(!G||typeof G!=="object")return;Rd(G);let U=Object.getOwnPropertyDescriptor(G,"command");if(!U){if("command"in G)Hn();return}if(U.get||U.set)Hn();let j=U.value;return typeof j==="string"&&j!==""?j:void 0}function yd(G,U){return bd(G,U,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function bd(G,U,j,K,re){let oe=Ed(G,K,re);if(typeof G==="string")return j?[G]:[];if(!oe)return[];let de=oe.entries.flatMap(([Se,we])=>bd(we,U,oe.array?j:U.has(Sd(Se)),K,re+1));return K.ancestors.delete(oe.object),de}function Sd(G){return G.replace(/-/g,"_").toLowerCase()}function Cd(G){return vd(G,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(ly)}function vd(G,U,j,K){let re=Ed(G,j,K);if(typeof G==="string")return U?[G]:[];if(!re)return[];let oe=re.entries.flatMap(([de,Se])=>vd(Se,re.array?U:ry.has(Sd(de)),j,K+1));return j.ancestors.delete(re.object),oe}function ay(G,U,j){if(U.nodes++,G!==null&&typeof G==="object"&&j>Lo.maxDepth||U.nodes>Lo.maxNodes)Hn();if(typeof G!=="string")return;let K=Buffer.byteLength(G);if(U.stringBytes+=K,K>Lo.maxStringBytes||U.stringBytes>Lo.maxAggregateStringBytes)Hn()}function Ed(G,U,j){if(ay(G,U,j),!G||typeof G!=="object")return null;let K=Rd(G);if(U.ancestors.has(G))Hn();let re=Reflect.ownKeys(G);if(U.keys+=re.length,U.keys>Lo.maxKeys)Hn();let oe=re.flatMap((de)=>{let Se=Object.getOwnPropertyDescriptor(G,de);if(!Se||Se.get||Se.set)Hn();return typeof de==="string"&&Se.enumerable?[[de,Se.value]]:[]});return U.ancestors.add(G),{object:G,array:K,entries:oe}}function Rd(G){if(Xh.isProxy(G))Hn();let U=Array.isArray(G),j=Object.getPrototypeOf(G);if(U&&j!==Array.prototype||!U&&j!==Object.prototype&&j!==null)Hn();return U}function Hn(){throw new f}function ly(G){let U=[],j=G.split(/\r?\n/),K=!1,re=!1,oe=null,de=null,Se=()=>{re=!1,oe=null,de=null};for(let we=0;we<j.length;we++){let We=j[we]??"";if(We==="*** Begin Patch"){K=!0,Se();continue}if(We==="*** End Patch"){K=!1,Se();continue}if(We.startsWith("@@")){let mt=cy(We);if(re=!0,oe=mt?.oldLines??null,de=mt?.newLines??null,oe===0&&de===0)Se();continue}if(re&&oe!==null&&de!==null){let mt=We.startsWith(" ")||We.startsWith("-")?1:0,gt=We.startsWith(" ")||We.startsWith("+")?1:0;if(oe=Math.max(0,oe-mt),de=Math.max(0,de-gt),oe===0&&de===0)Se();continue}if(We.startsWith("*** ")){Se(),U.push(...Sa(We));continue}if(re)continue;if(We.startsWith("diff --git ")){U.push(...Sa(We));continue}if(We.startsWith("--- ")){let mt=j[we+1]??"";if(!mt.startsWith("+++ "))continue;U.push(...va(Ti(We.slice(4),!0),Ti(mt.slice(4),!0))),we++;continue}if(!K)U.push(...Sa(We))}return U}function cy(G){let U=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(G);if(!U)return null;return{oldLines:Number(U[1]??1),newLines:Number(U[2]??1)}}function Sa(G){let U=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(G);if(U?.[1])return gd(U[1]);let j=/^\*\*\* Move to: (.+)$/.exec(G);if(j?.[1])return gd(j[1]);if(G.startsWith("diff --git "))return dy(G.slice(11));let K=/^--- (.+)$/.exec(G);if(K?.[1])return pd(K[1]);let re=/^\+\+\+ (.+)$/.exec(G);if(re?.[1])return pd(re[1]);let oe=/^(?:rename|copy) (?:from|to) (.+)$/.exec(G);if(oe?.[1])return yy(oe[1]);return[]}function dy(G){let U=uy(G);if(U.length===2&&U[0]&&U[1])return va(U[0],U[1]);let j=my(G);return j?va(G.slice(j.oldStart,j.oldEnd),G.slice(j.newStart,j.newEnd)):[]}function uy(G){let U=[],j=0;while(j<G.length&&U.length<2){while(Er(G[j]))j++;if(j>=G.length)break;let K=G[j]==='"'||G[j]==="'"?G[j]:void 0;if(!K){let oe=j;while(j<G.length&&!Er(G[j]))j++;U.push(G.slice(oe,j));continue}let re=xd(G,j,K);if(!re)return[];U.push(re.value),j=re.end}while(Er(G[j]))j++;return j===G.length?U:[]}function my(G){let U=0;while(U<G.length&&Er(G[U]))U++;let j=G.length;while(j>U&&Er(G[j-1]))j--;let K=0,re=U;while(re<j){if(!Er(G[re])){re++;continue}let oe=re;while(re<j&&Er(G[re]))re++;if(oe===U||re===j)continue;if(K++,K>sy)Hn();if(fy(G,U,oe,re,j))return{oldStart:U,oldEnd:oe,newStart:re,newEnd:j}}return null}function fy(G,U,j,K,re){if(Ca(G,U,j,K,re))return!0;let oe=md(G,"/",U,j),de=md(G,"/",K,re);if(oe<=U||de<=K)return!1;if(Ca(G,U,oe,K,de))return!1;return Ca(G,oe+1,j,de+1,re)}function Ca(G,U,j,K,re){if(j-U!==re-K)return!1;for(let oe=0;oe<j-U;oe++)if(G[U+oe]!==G[K+oe])return!1;return!0}function md(G,U,j,K){for(let re=j;re<K;re++)if(G[re]===U)return re;return-1}function Er(G){return G!==void 0&&iy.test(G)}function xd(G,U,j){let K=[],re=U+1;while(re<G.length){let oe=String.fromCodePoint(G.codePointAt(re)??0);if(oe===j)return{value:oy.decode(Uint8Array.from(K)),end:re+1};if(oe!=="\\"||j==="'"){K.push(...ud.encode(oe)),re+=oe.length;continue}let de=G.slice(re+1),Se=/^[0-7]{1,3}/.exec(de)?.[0];if(Se){K.push(Number.parseInt(Se,8)),re+=Se.length+1;continue}K.push(...ud.encode(py(de[0]??""))),re+=2}return null}function py(G){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
5
|
+
`,r:"\r",t:"\t",v:"\v"}[G]??G}function gy(G){return Wo(by(G))}function va(G,U){if(G==="/dev/null")return fd(U);if(U==="/dev/null")return fd(G);if(G.startsWith("a/")&&U.startsWith("b/"))return[G.slice(2),U.slice(2)].flatMap(Wo);let j=hy(G,U)??(G===U?_d(G):null);return[G,U,...j?[j]:[]].flatMap(Wo)}function fd(G){let U=_d(G);return[G,...U?[U]:[]].flatMap(Wo)}function _d(G){let U=G.indexOf("/");return U>0&&U<G.length-1?G.slice(U+1):null}function hy(G,U){let j=G.indexOf("/"),K=U.indexOf("/");if(j<1||K<1)return null;if(G.slice(0,j)===U.slice(0,K))return null;let re=G.slice(j+1);return re===U.slice(K+1)?re:null}function pd(G){return gy(Ti(G,!0))}function yy(G){return Wo(Ti(G,!1))}function Ti(G,U){let j=G.trim(),K=j[0]==='"'||j[0]==="'"?j[0]:void 0;if(K){let re=xd(j,0,K);if(re&&(U||j.slice(re.end).trim()===""))return re.value}return U?j.split("\t",1)[0]?.trim()??"":j}function by(G){return G.startsWith("a/")||G.startsWith("b/")?G.slice(2):G}function Wo(G){return G===""||G==="/dev/null"?[]:[G]}function gd(G){let U=G.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return U===""||U==="/dev/null"?[]:[U]}function fe(G){try{if(!Cy(G).isDirectory())return!1;return Sy(G,wd.R_OK|wd.X_OK),!0}catch{return!1}}function it(G,U,j){if(sr(G))return;let K=U.flatMap((oe)=>Ea(oe,j));if(!K[0])return;let re=Ea(Ad(G)?G:Ey(K[0],G),j)[0];if(!re)return;return K.some((oe)=>xy(re,oe))?re:void 0}function qe(G,U){return G.flatMap((j)=>Ea(j,U))[0]}function Ea(G,U){let j=U.realpath(G);if(j===null)return[];return U.isDirectory(j)?[j]:[]}function xy(G,U){let j=vy(U,G);return j===""||j!==".."&&!j.startsWith(`..${Ry}`)&&!Ad(j)}var _y=8388608;async function Ke(G){let U=[],j=0;for await(let K of G){let re=typeof K==="string"?Buffer.from(K,"utf-8"):Buffer.from(K.buffer,K.byteOffset,K.byteLength);if(j+=re.byteLength,j>_y)throw wy(G),Error("hook input byte limit exceeded");U.push(re)}return Buffer.concat(U,j).toString("utf-8")}function wy(G){let U=G.destroy??G.cancel;if(!U)return;try{Promise.resolve(U.call(G)).catch(()=>{})}catch{}}function u(G,U,j,K,re){if(j.kind!=="command")return{toolName:G,input:U,route:j,context:K};return{toolName:G,input:U,route:j,context:K,command:re}}var Xr=["fail_closed","paranoid_rm","paranoid_interpreters"],ki={standard:{fail_closed:!1,paranoid_rm:!1,paranoid_interpreters:!1},strict:{fail_closed:!0,paranoid_rm:!1,paranoid_interpreters:!1},paranoid:{fail_closed:!0,paranoid_rm:!0,paranoid_interpreters:!0}};var n={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"},projectTightenOnly:{name:"CC_SAFETY_NET_PROJECT_TIGHTEN_ONLY"}},Oi=["standard","strict","paranoid"];function Pd(G,U){if(!U)return G;return Oi.indexOf(U)>Oi.indexOf(G)?U:G}function Td(G){let U=pe(n.level,G);return Oi.find((j)=>j===U)}function Id(G,U){return Pd(G,Td(U))}function Ay(G){let U=pe(n.level,G);if(!U)return;let j=Td(G);if(j)return j;console.error(`CC Safety Net: ignored invalid ${n.level.name}=${JSON.stringify(U.slice(0,40))}. Use ${Oi.join(", ")}.`);return}function Ve(G){if(G===void 0||G==="all")return"all";if(G==="blocked")return"blocked";return"invalid"}function Ee(G){return Ve(pe(n.auditScope,G))==="all"}function Ra(G){if(G.failClosed&&G.paranoidRm&&G.paranoidInterpreters)return"paranoid";if(G.failClosed&&!G.paranoidRm&&!G.paranoidInterpreters)return"strict";if(!G.failClosed&&!G.paranoidRm&&!G.paranoidInterpreters)return"standard";return"custom"}function T(G={},U){let j=G.safety?.level??"standard",K=Ay(U),re=Pd(j,K),oe=ki[re],de={failClosed:oe.fail_closed,paranoidRm:oe.paranoid_rm,paranoidInterpreters:oe.paranoid_interpreters},Se={failClosed:re===j?"preset":"environment",paranoidRm:re===j?"preset":"environment",paranoidInterpreters:re===j?"preset":"environment"},we={failClosed:[`policy safety.level=${j}`],paranoidRm:[`policy safety.level=${j}`],paranoidInterpreters:[`policy safety.level=${j}`]};if(re!==j)we.failClosed.push(`env ${n.level.name}=${K}`),we.paranoidRm.push(`env ${n.level.name}=${K}`),we.paranoidInterpreters.push(`env ${n.level.name}=${K}`);if(G.safety?.overrides?.failClosed!==void 0)de.failClosed=G.safety.overrides.failClosed,Se.failClosed="capability_override",we.failClosed.push("policy safety.overrides.fail_closed");if(G.safety?.overrides?.paranoidRm!==void 0)de.paranoidRm=G.safety.overrides.paranoidRm,Se.paranoidRm="capability_override",we.paranoidRm.push("policy safety.overrides.paranoid_rm");if(G.safety?.overrides?.paranoidInterpreters!==void 0)de.paranoidInterpreters=G.safety.overrides.paranoidInterpreters,Se.paranoidInterpreters="capability_override",we.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(v(n.strict,U))de.failClosed=!0,Se.failClosed="environment",we.failClosed.push(`env ${n.strict.name}`);if(v(n.paranoid,U))de.paranoidRm=!0,de.paranoidInterpreters=!0,Se.paranoidRm="environment",Se.paranoidInterpreters="environment",we.paranoidRm.push(`env ${n.paranoid.name}`),we.paranoidInterpreters.push(`env ${n.paranoid.name}`);if(v(n.paranoidRm,U))de.paranoidRm=!0,Se.paranoidRm="environment",we.paranoidRm.push(`env ${n.paranoidRm.name}`);if(v(n.paranoidInterpreters,U))de.paranoidInterpreters=!0,Se.paranoidInterpreters="environment",we.paranoidInterpreters.push(`env ${n.paranoidInterpreters.name}`);let We=!!G.worktreeMode||v(n.worktree,U);return{strict:de.failClosed,paranoidRm:de.paranoidRm,paranoidInterpreters:de.paranoidInterpreters,worktreeMode:We,effectiveLevel:Ra(de),capabilities:{fail_closed:{enabled:de.failClosed,source:Se.failClosed,sources:we.failClosed},paranoid_rm:{enabled:de.paranoidRm,source:Se.paranoidRm,sources:we.paranoidRm},paranoid_interpreters:{enabled:de.paranoidInterpreters,source:Se.paranoidInterpreters,sources:we.paranoidInterpreters}}}}function v(G,U){let j=typeof G==="string"?Fo(G,U):pe(G,U);return j==="1"||j?.toLowerCase()==="true"}function Fo(G,U){return U.get(G)}function pe(G,U){let j=Fo(G.name,U);if(j!==void 0)return j;if(G.legacyName)return Fo(G.legacyName,U);return}function ot(G,U){return Fo(G.name,U)!==void 0||!!G.legacyName&&Fo(G.legacyName,U)!==void 0}import{dirname as wr}from"node:path";import{closeSync as Py,constants as Go,fstatSync as xa,fsyncSync as Ty,lstatSync as Tn,mkdirSync as kd,openSync as Od,readdirSync as wa,readFileSync as Iy,realpathSync as Jr,renameSync as ky,rmdirSync as Md,statSync as _a,unlinkSync as Aa,writeFileSync as Oy}from"node:fs";import{isAbsolute as Dd,join as Rr,normalize as My,parse as Mi,relative as Pa,resolve as Ta,sep as Di}from"node:path";function Ie(){let G=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${G()}${G()}`}var Dy=Symbol("PolicyFilesystemScope"),Ny=Symbol("PolicyFilesystemTarget"),Nd=Go.O_NOFOLLOW??0;class o extends Error{name="PolicyFilesystemError";constructor(G){super(`Unable to access ${G} filesystem safely.`)}}function S(G,U){return{[Dy]:!0,root:Ta(G),label:U}}function zo(G,U){let j=My(U);if(U===""||Dd(U)||j===".."||j.startsWith(`..${Di}`))throw new o(G.label);return{[Ny]:!0,scope:G,relativePath:j,path:Rr(G.root,j)}}function i(G,U){return zo(G,Pa(G.root,Ta(U)))}function se(G,U="rules policy"){let j=Ta(G),K=Mi(j).dir;return zo(S(K,U),Pa(K,j))}function r(G){return Zn(G.scope.label,()=>{if(!nn(G))return null;let U=Od(G.path,Go.O_RDONLY|Nd);return Wd(U,()=>{let j=xa(U);if(!j.isFile())throw new o(G.scope.label);let K=Iy(U,"utf-8"),re=Tn(G.path);if(!re.isFile()||re.isSymbolicLink()||j.dev!==re.dev||j.ino!==re.ino)throw new o(G.scope.label);return nn(G),K})})}function g(G,U,j=384,K){let re=`${G.path}.${Ie()}.tmp`;Zn(G.scope.label,()=>{Wy(G),nn(G);let oe=Od(re,Go.O_CREAT|Go.O_EXCL|Go.O_WRONLY|Nd,j),de=Wd(oe,()=>{let Se=xa(oe);if(!Se.isFile())throw new o(G.scope.label);Oy(oe,U,"utf-8"),Ty(oe);let we=xa(oe);if(!we.isFile()||we.dev!==Se.dev||we.ino!==Se.ino)throw new o(G.scope.label);return we});nn(G),Gy(G,re,de.dev,de.ino),ky(re,G.path),K?.(G.path),nn(G)},()=>zy(re))}function Ld(G,U){if(G.path===U.path)return!0;return Zn(G.scope.label,()=>{if(!nn(G)||!nn(U))return!1;let j=(K)=>Rr(Jr(Mi(K).dir),Mi(K).base);return j(G.path)===j(U.path)})}function me(G){let U=Zn(G.scope.label,()=>{if(!nn(G,"directory"))return null;let j=wa(G.path);return nn(G,"directory"),j});if(!U)return null;return Zn(G.scope.label,()=>{let j=U.map((K)=>{let re=zo(G.scope,Rr(G.relativePath,K)),oe=Tn(re.path);if(oe.isSymbolicLink()||!oe.isFile()&&!oe.isDirectory())throw new o(G.scope.label);return Ni(Ia(G.scope),Jr(re.path),G.scope.label),{name:K,kind:oe.isDirectory()?"directory":"file"}});return nn(G,"directory"),j})}function H(G){Zn(G.scope.label,()=>{if(!nn(G))return;Aa(G.path),nn(G)})}function st(G){Zn(G.scope.label,()=>{if(!Ly(G))return;Gd(G),nn(G,"directory")})}function at(G){Zn(G.scope.label,()=>{if(!nn(G,"directory"))return;Md(G.path),nn(G,"directory")})}function Ly(G){return Zn(G.scope.label,()=>{if(!nn(G,"directory"))return!1;return Fd(G),!0})}function Zn(G,U,j){try{return U()}catch(K){if(j?.(),K instanceof o)throw K;throw new o(G)}}function Wd(G,U){try{return U()}finally{Py(G)}}function nn(G,U="file"){let j=zd(G.scope);if(!j)return!1;let K=G.relativePath.split(Di);for(let re of K.keys()){let oe=Rr(G.scope.root,...K.slice(0,re+1)),de=Tn(oe,{throwIfNoEntry:!1});if(!de)return!1;if(de.isSymbolicLink())throw new o(G.scope.label);if(re<K.length-1&&!de.isDirectory())throw new o(G.scope.label);if(re===K.length-1&&(U==="file"?!de.isFile():!de.isDirectory()))throw new o(G.scope.label);Ni(j,Jr(oe),G.scope.label)}return!0}function Fd(G){for(let U of wa(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=Tn(j.path);if(K.isSymbolicLink()||!K.isDirectory()&&!K.isFile())throw new o(G.scope.label);if(K.isDirectory())Fd(j)}nn(G,"directory")}function Gd(G){for(let U of wa(G.path)){let j=zo(G.scope,Rr(G.relativePath,U)),K=Tn(j.path);if(K.isSymbolicLink())throw new o(G.scope.label);if(K.isDirectory()){Gd(j);continue}if(!K.isFile())throw new o(G.scope.label);Aa(j.path)}Md(G.path)}function Wy(G){Fy(G.scope);let U=Ia(G.scope),j=G.relativePath.split(Di).slice(0,-1);for(let K of j.keys()){let re=Rr(G.scope.root,...j.slice(0,K+1));if(!Tn(re,{throwIfNoEntry:!1}))kd(re,{mode:448});let oe=Tn(re);if(!oe.isDirectory()||oe.isSymbolicLink())throw new o(G.scope.label);Ni(U,Jr(re),G.scope.label)}}function Fy(G){if(Tn(G.root,{throwIfNoEntry:!1})){if(!_a(G.root).isDirectory())throw new o(G.label);return}let U=[],j=G.root;while(!Tn(j,{throwIfNoEntry:!1})){U.unshift(j);let K=Mi(j).dir;if(K===j)throw new o(G.label);j=K}if(!_a(j).isDirectory())throw new o(G.label);for(let K of U){kd(K,{mode:448});let re=Tn(K);if(!re.isDirectory()||re.isSymbolicLink())throw new o(G.label)}}function zd(G){if(!Tn(G.root,{throwIfNoEntry:!1}))return null;if(!_a(G.root).isDirectory())throw new o(G.label);return Jr(G.root)}function Ia(G){let U=zd(G);if(!U)throw new o(G.label);return U}function Gy(G,U,j,K){let re=Tn(U);if(!re.isFile()||re.isSymbolicLink()||re.dev!==j||re.ino!==K)throw new o(G.scope.label);Ni(Ia(G.scope),Jr(U),G.scope.label)}function Ni(G,U,j){let K=Pa(G,U);if(K===".."||K.startsWith(`..${Di}`)||Dd(K))throw new o(j)}function zy(G){try{Aa(G)}catch{}}import{dirname as xr,isAbsolute as jy,join as _r,relative as Vy,resolve as ar,sep as Ky}from"node:path";var d=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ge="rulebook.json",he=".cc-safety-net/rules";var $d=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,$y=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,Bd=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,By=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Uy="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ct=new RegExp(`^${By}/(${d.source.slice(1,-1)})/${Uy}$`);function Hy(G){return`.cc-safety-net/rules/${G}/rulebook.json`}function Ud(G){if(w(G))try{return N(G),null}catch(U){return U instanceof Error?U.message:String(U)}return d.test(G)?null:`Local rulebook sources must be bare names matching ${d}: ${G}`}function N(G){if(G.startsWith("github:"))throw Error(`Invalid rulebook source: ${G}`);let U=G.match($d);if(!U?.[1]||!U[2]||!U[3])throw Error(`Invalid GitHub rulebook source: ${G}`);let j=U[3].lastIndexOf("/");if(j<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${G}`);let K=U[3].slice(0,j),re=U[3].slice(j+1);if(!K||!Bd.test(K))throw Error(`GitHub rulebook refs must use valid path segments: ${G}`);if(!re||!d.test(re))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${G}`);return{owner:U[1],repo:U[2],ref:K,path:Hy(re),name:re}}function Z(G){return $y.test(G)}function ae(G){return Bd.test(G)}function w(G){return $d.test(G)}function lt(G){if(!d.test(G))throw Error(`Local rulebook sources must be bare names matching ${d}: ${G}`)}var Hd="rule.json",Li="policy.json",jd=".cc-safety-net",qy="rules",Yy="CC_SAFETY_NET_HOME",Vd="`cc-safety-net rule update`";function Zy(G){return ar(G,he)}function _(G){return _r(Zy(G),Hd)}function h(G){return _r(ar(G),jd,Li)}function ke(G,U={}){return U.userConfigDir??(U.userConfigPath?xr(U.userConfigPath):_r(Xy(G),qy))}function Xy(G){let U=G.env.get(Yy);return U?ar(cn(U)):_r(G.home,jd)}function W(G,U={}){return _r(ke(G,U),Hd)}function l(G,U={}){return _r(xr(ke(G,U)),Li)}function L(G,U){let j=Pn();return Wt(h(U.cwd),G.paths,j)===Wt(ar(l(G,U)),G.paths,j)}function X(G,U){let j=U.userConfigPath??W(G,U),K=U.projectConfigPath??_(U.cwd),re=Je(G,U),oe=Ye(K,U.cwd);return{userConfigPath:j,projectConfigPath:K,userScope:re,projectScope:oe,userConfigTarget:i(re,j),projectConfigTarget:i(oe,K)}}function Je(G,U){let j=U.userConfigPath?xr(xr(ar(U.userConfigPath))):xr(ar(U.userConfigDir??ke(G,U)));return S(j,"user policy")}function Ye(G,U){let j=ar(U),K=ar(G),re=Vy(j,K);if(re!==".."&&!re.startsWith(`..${Ky}`)&&!jy(re))return S(j,"project policy");return S(xr(xr(K)),"project policy")}function M(G,U){return _r(G,U,ge)}var vn=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),C=/^[a-zA-Z][a-zA-Z0-9_-]*$/,I=256,qt=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Kd=new Set(["python","python3","python2","node","ruby","perl"]),Wi=/^python(?:[23](?:\.\d+)*)?$/,In=new Set(["awk","gawk","nawk","mawk"]),Fi=new Set(["echo","printf","cat","head","tail","less","more","grep","rg","ag","ack","sed","awk","cut","tr","sort","uniq","wc","tee","man","help","info","type","which","whereis","whatis","apropos","file","stat","ls","ll","dir","tree","pwd","date","cal","uptime","whoami","id","groups","hostname","uname","env","printenv","set","export","alias","history","jobs","fg","bg","test","true","false","read","return","exit","break","continue","shift","wait","trap","basename","dirname","realpath","readlink","md5sum","sha256sum","base64","xxd","od","hexdump","strings","diff","cmp","comm","join","paste","column","fmt","fold","nl","pr","expand","unexpand","rev","tac","shuf","seq","yes","sleep","logger","write","wall","mesg","notify-send"]);var qd="Rulebook exceeds CC Safety Net's safe validation limits.",Yd="Additional rulebook validation errors were omitted.",Nn=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Zd(G){if(ka(G.allowed_commands,Nn.maxAllowedCommands)||ka(G.rules,Nn.maxRules)||ka(G.tests,Nn.maxTests))return!1;let{maxAggregateStringCodeUnits:U,maxTotalBlockArgs:j}=Nn,K=(re,oe=!1)=>{if(typeof re!=="string")return!0;if(re.length>Nn.maxStringCodeUnits||oe&&re.length>Nn.maxFixtureCommandCodeUnits||re.length>U)return!1;return U-=re.length,!0};if(!K(G.name)||!K(G.version)||!K(G.description)||!K(G.author)||!K(G.migrated_from))return!1;if(Array.isArray(G.allowed_commands)){for(let re of G.allowed_commands)if(!K(re))return!1}if(Array.isArray(G.rules))for(let re of G.rules){if(!re||typeof re!=="object")continue;let oe=re;if(!K(oe.name)||!K(oe.command)||!K(oe.subcommand)||!K(oe.reason)||!K(oe.intent))return!1;let de=oe.match&&typeof oe.match==="object"?oe.match:{};for(let Se of[oe.block_args,de.command_path,de.any_args,de.exclude_args]){if(!Array.isArray(Se))continue;if(Se.length>Nn.maxBlockArgsPerRule||Se.length>j)return!1;j-=Se.length;for(let we of Se)if(!K(we))return!1}}if(Array.isArray(G.tests))for(let re of G.tests){if(!re||typeof re!=="object")continue;let oe=re;if(!K(oe.command,!0)||!K(oe.expect)||!K(oe.rule))return!1}return!0}function ka(G,U){return Array.isArray(G)&&G.length>U}var Oa=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var ye=64,be="Rule config exceeds CC Safety Net's safe source limit.";function Dt(G){return Ot(G).toLowerCase()}function Ot(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}function fn(G,U){let j=new Set,K=!1;for(let re of G){if(re==="--"){K=!0;continue}if(K)continue;if(re.startsWith("-")&&!re.startsWith("--")&&re.length>1)for(let oe=1;oe<re.length;oe++){let de=re[oe];if(!de||!/[a-zA-Z]/.test(de))break;let Se=`-${de}`;if(j.add(Se),U?.shortOptsWithValue?.has(Se))break}}return j}var Jy={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Ma=new Set(["--init-file","--rcfile"]);function Da(G,U,j,K){let re=!1,oe=0,de=!1,Se=!1,we=!1;for(let We=1;We<U.length;We++){let mt=U[We];if(mt===void 0)break;if(G==="ksh"&&mt==="o"&&We+1<U.length){if(K==="argv"){let gt=U.slice(We+1);if(U[0]==="-"&&(gt==="c"||gt[0]==="-"&>.endsWith("c")))de=!0}break}if(G==="ksh"&&mt==="o"&&We+1===U.length&&(j?.startsWith("-")||j?.startsWith("+")))break;if(G==="zsh"&&mt==="o"&&We+1<U.length)break;if(K==="startup"&&mt==="i")re=U[0]==="-";if(K==="argv"&&U[0]==="-"&&mt==="c")de=!0;if(K==="argv"&&mt==="n")we=U[0]==="-";if(K==="argv"&&mt==="s")Se=U[0]==="-";if(!Jy[G]?.includes(mt))continue;if(We+1===U.length)oe++;break}return{interactive:re,followingValues:oe,commandSelected:de,stdinMode:Se,syntaxCheck:we}}function En(G){let U=Ot(G[0]??"").toLowerCase(),j=!1,K=!1,re=!1;for(let oe=1;oe<G.length;oe++){let de=G[oe];if(de===void 0)break;if(de==="--"){let we=j&&G[oe+1]!==void 0?oe+1:null;return{command:we===null?null:G[we]??null,commandIndex:we,scriptIndex:!j&&!K&&G[oe+1]!==void 0?oe+1:null,readsStdinAsCommands:!j&&(K||G[oe+1]===void 0),syntaxCheck:re}}if(de==="-"||de[0]!=="-"&&de[0]!=="+")return{command:j?de:null,commandIndex:j?oe:null,scriptIndex:!j&&!K&&de!=="-"?oe:null,readsStdinAsCommands:!j&&(K||de==="-"),syntaxCheck:re};if(de.startsWith("--")){let we=de.split("=",1)[0]??de;if(U==="bash"&&Ma.has(we)&&!de.includes("="))oe++;continue}let Se=Da(U,de,G[oe+1],"argv");if(Se.commandSelected)j=!0;if(Se.syntaxCheck)re=!0;if(Se.stdinMode)K=!0;oe+=Se.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!j,syntaxCheck:re}}function $o(G,U){if(U.escaped)return U.escaped=!1,!0;if(G==="\\"&&!U.inSingle)return U.escaped=!0,!0;if(G==="'"&&!U.inDouble)return U.inSingle=!U.inSingle,!0;if(G==='"'&&!U.inSingle)return U.inDouble=!U.inDouble,!0;return!1}function Gi(G){let U={inSingle:!1,inDouble:!1,escaped:!1};for(let j of Qy(G))$o(j,U);return U.inSingle||U.inDouble}function Qy(G){let U="",j={inSingle:!1,inDouble:!1,escaped:!1},K=!1,re=!0;for(let oe=0;oe<G.length;oe++){let de=G[oe];if(!de)break;if(K){if(de===`
|
|
6
|
+
`||de==="\r")U+=de,K=!1,j.escaped=!1;continue}if(de==="#"&&!j.inSingle&&!j.inDouble&&re){K=!0;continue}if(U+=de,!j.inSingle&&!j.inDouble&&!j.escaped)re=/[\s;&|()<>]/.test(de);$o(de,j)}return U}var Na=new Set(["rm","find","xargs","parallel"]),eb=new Set(["git","busybox",...Na,...qt,...Kd,...In]),tb=new Set(["python","node","ruby","perl"]);function Ae(G){let U=Dt(G);return eb.has(U)||Ln(U)}function Ln(G){return tb.has(nb(G))}function nb(G){let U=Ot(G).toLowerCase();return Wi.test(U)?"python":U}var ut={version:1,rules:[],overrides:{},transparent_wrappers:[]};function m(G){try{let U=r(rb(G));if(U===null)return{config:null,errors:[]};if(!U.trim())return{config:null,errors:["Config file is empty"]};let j=JSON.parse(U),K=Ze(j);if(K.errors.length>0)return{config:null,errors:K.errors};return{config:{version:1,rules:j.rules??[],overrides:j.overrides??{},transparent_wrappers:j.transparent_wrappers??[]},errors:[]}}catch(U){if(U instanceof o)return{config:null,errors:[U.message]};let j=U instanceof Error?U.message:String(U);return{config:null,errors:[U instanceof SyntaxError?"Invalid JSON":j]}}}function rb(G){return typeof G==="string"?se(G):G}var e=(G,U)=>({path:G,message:U,kind:"typed"}),rn=(G,U)=>({path:G,message:U,kind:"custom"});function Oe(G){let U=new Set;return G.flatMap((j,K)=>{let re=Qr(j)?j.name:void 0;if(typeof re!=="string")return[];if(U.has(re.toLowerCase()))return[rn(["rules",K,"name"],`duplicate rule name "${re}"`)];return U.add(re.toLowerCase()),[]})}var Re=`must be one of ${Oa.join(", ")}`,ob=/^[^/]+\/[^/]+$/,ib=["version","rules","overrides","transparent_wrappers"];function Ze(G){let U=sb(G);return{errors:ce(Xe(U,ib,(j)=>j.kind==="custom"),": "," "),sources:pb(G,U)}}function sb(G){if(!Qr(G))return[e([],"Config must be an object")];let U=Array.isArray(G.rules)&&G.rules.length>ye;return[...G.version===1?[]:[e(["version"],"must be 1")],...ab(G.rules,U),...db(G.overrides),...mb(G.transparent_wrappers),...U?[]:cb(G.rules),...Qr(G.overrides)?Object.keys(G.overrides).filter((j)=>!ob.test(j)).map((j)=>rn(["overrides",j],"must use <rulebook-name>/<rule-name>")):[],...fb(G.transparent_wrappers)]}function ab(G,U){if(G===void 0)return[];if(!Array.isArray(G))return[e(["rules"],"must be an array of rulebook source strings"),...Xd(G,ye)?[e(["rules"],be)]:[]];if(U)return[{path:["rules"],message:be,kind:"limit"}];return G.flatMap((j,K)=>{if(typeof j!=="string")return[e(["rules",K],"must be a rulebook source string"),...lb(j,1)?[e(["rules",K],"must be a non-empty rulebook source string")]:[]];return j===""?[e(["rules",K],"must be a non-empty rulebook source string")]:[]})}function Xd(G,U){let j=Jd(G);return j!==void 0&&!(j<=U)}function lb(G,U){let j=Jd(G);return j!==void 0&&!(j>=U)}function Jd(G){if(G===null||G===void 0)return;let U=G.length;return U===void 0?void 0:Number(U)}function cb(G){if(!Array.isArray(G))return[];let U=new Set;return G.flatMap((j,K)=>{if(typeof j!=="string"||j==="")return[];if(j.trim()==="")return[rn(["rules",K],"must be a non-empty rulebook source string")];let re=Ud(j);if(re)return[rn(["rules",K],re)];if(U.has(j))return[rn(["rules",K],`duplicate rulebook source "${j}"`)];return U.add(j),[]})}function db(G){if(G===void 0)return[];if(!Qr(G))return[e(["overrides"],"must be an object if provided")];return Object.keys(G).flatMap((U)=>{let j=G[U];if(j==="off")return[];if(!Qr(j))return[e(["overrides",U],'must be "off" or an object')];return[...ub(j.reason,["overrides",U,"reason"]),...j.intent===void 0||Te(j.intent)?[]:[e(["overrides",U,"intent"],Re)]]})}function ub(G,U){if(typeof G!=="string")return[e(U,"required non-empty string"),...Xd(G,I)?[e(U,`must be at most ${I} characters`)]:[]];if(G==="")return[e(U,"required non-empty string")];return G.length>I?[e(U,`must be at most ${I} characters`)]:[]}function mb(G){if(G===void 0)return[];if(!Array.isArray(G))return[e(["transparent_wrappers"],"must be an array of command strings")];return G.flatMap((U,j)=>{if(typeof U!=="string")return[e(["transparent_wrappers",j],"must be a command string")];return C.test(U)?[]:[e(["transparent_wrappers",j],"must match command pattern")]})}function fb(G){if(!Array.isArray(G))return[];let U=new Set;return G.flatMap((j,K)=>{if(typeof j!=="string"||!C.test(j))return[];if(U.has(j))return[rn(["transparent_wrappers",K],`duplicate command "${j}"`)];if(Ae(j))return[rn(["transparent_wrappers",K],`reserved command "${j}" cannot be a wrapper`)];return U.add(j),[]})}function pb(G,U){let j=Qr(G)?G.rules:void 0;if(!Array.isArray(j))return new Set;if(U.some((re)=>re.path.length===1&&re.path[0]==="rules"))return new Set;let K=new Set(U.filter((re)=>re.path[0]==="rules"&&typeof re.path[1]==="number").map((re)=>re.path[1]));return new Set(j.filter((re,oe)=>typeof re==="string"&&!K.has(oe)))}function Xe(G,U,j){let K=G.map((de)=>de.path[1]),re=[...new Set(K.filter((de)=>typeof de==="string"))],oe=(de,Se)=>[de.path.length===0?-1:U.indexOf(String(de.path[0])),typeof Se==="number"?Se:re.indexOf(String(Se)),j(de)?0:1];return G.map((de,Se)=>({issue:de,rank:oe(de,K[Se])})).sort((de,Se)=>de.rank[0]-Se.rank[0]||de.rank[1]-Se.rank[1]||de.rank[2]-Se.rank[2]).map((de)=>de.issue)}function ce(G,U,j){return[...new Set(G.map((K)=>{let re=La(K.path);if(K.kind==="unknownKeys")return`${re?`${re}.`:""}unknown field "${K.message}"`;if(K.kind==="key"||K.kind==="limit"||K.path.length===0)return K.message;return`${re}${K.path.length===1?j:U}${K.message}`}))]}function La(G){return G.map((U,j)=>{if(typeof U==="number")return`[${U}]`;return j===0?String(U):`.${String(U)}`}).join("")}function Te(G){return Oa.includes(G)}function Qr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function le(G){let U=yb(G);if(U.errors.length>0)throw Error(U.errors.join("; "));return G}var gb=`required non-empty string up to ${I} characters`,Qd="must be a non-empty array of unique non-empty strings",hb="required non-empty array of non-empty strings";function yb(G){if(!lr(G))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Zd(G))return{errors:[qd],ruleNames:new Set};let U=[...G.rulebook_version===1||G.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ce(bb(G,G.rulebook_version===2),": ",": ")];return{errors:U.length>Nn.maxValidationErrors?[...U.slice(0,Nn.maxValidationErrors),Yd]:U,ruleNames:new Set(De(G).map((j)=>j.toLowerCase()))}}function De(G){let U=lr(G)?G.rules:void 0;return(Array.isArray(U)?U:[]).flatMap((j)=>{let K=lr(j)?j.name:void 0;return typeof K==="string"?[K]:[]})}function bb(G,U){return[...typeof G.name==="string"&&d.test(G.name)?[]:[e(["name"],"required string matching rule name pattern")],...typeof G.version==="string"&&G.version!==""?[]:[e(["version"],"required non-empty string")],...Sb(G.allowed_commands),...Cb(G.rules,U),...xb(G.tests),..._b(G),...wb(G)]}function Sb(G){if(!Array.isArray(G))return[e(["allowed_commands"],"required array")];let U=new Set;return[...G.flatMap((j,K)=>typeof j==="string"&&C.test(j)?[]:[e(["allowed_commands",K],"must match command pattern")]),...G.flatMap((j,K)=>{if(typeof j!=="string"||!C.test(j))return[];if(U.has(j))return[rn(["allowed_commands",K],`duplicate command "${j}"`)];return U.add(j),[]})]}function Cb(G,U){if(!Array.isArray(G))return[e(["rules"],"required array")];return[...G.flatMap((j,K)=>{if(!lr(j))return[e(["rules",K],"must be an object")];return U?Eb(j,["rules",K]):vb(j,["rules",K])}),...Oe(G)]}function vb(G,U){return[...eu(G.name,U),...tu(G.command,U),...G.subcommand===void 0||typeof G.subcommand==="string"&&C.test(G.subcommand)?[]:[e([...U,"subcommand"],"must match command pattern")],...zi(G.block_args,[...U,"block_args"],"required non-empty array",!1),...nu(G.reason,U),...ru(G.intent,U)]}function Eb(G,U){return[...eu(G.name,U),...tu(G.command,U),...nu(G.reason,U),...ru(G.intent,U),...Rb(G.match,[...U,"match"]),...G.subcommand===void 0?[]:[e([...U,"subcommand"],"not supported in rulebook_version 2")],...G.block_args===void 0?[]:[e([...U,"block_args"],"not supported in rulebook_version 2")]]}function eu(G,U){if(typeof G!=="string")return[e([...U,"name"],"required string")];return d.test(G)?[]:[e([...U,"name"],"must match rule name pattern")]}function tu(G,U){return typeof G==="string"&&C.test(G)?[]:[e([...U,"command"],"required string matching command pattern")]}function nu(G,U){return typeof G==="string"&&G!==""&&G.length<=I?[]:[e([...U,"reason"],gb)]}function ru(G,U){return G===void 0||Te(G)?[]:[e([...U,"intent"],Re)]}function Rb(G,U){if(!lr(G))return[e(U,"required object")];return[...zi(G.command_path,[...U,"command_path"],hb,!1),...G.any_args===void 0?[]:zi(G.any_args,[...U,"any_args"],Qd,!0),...G.exclude_args===void 0?[]:zi(G.exclude_args,[...U,"exclude_args"],Qd,!0)]}function zi(G,U,j,K){if(!Array.isArray(G))return[e(U,j)];let re=G.flatMap((oe,de)=>{if(typeof oe!=="string")return[e([...U,de],"must be a non-empty string")];return oe===""?[rn([...U,de],"must be a non-empty string")]:[]});if(G.some((oe)=>typeof oe!=="string"))return re;return[...re,...G.length===0?[rn(U,j)]:[],...K&&new Set(G).size!==G.length?[rn(U,"must not contain duplicate values")]:[]]}function xb(G){if(G===void 0)return[];if(!Array.isArray(G))return[e(["tests"],"must be an array if provided")];return G.flatMap((U,j)=>{if(!lr(U))return[e(["tests",j],"must be an object")];return[...typeof U.command==="string"&&U.command.trim()!==""?[]:[e(["tests",j,"command"],"required non-empty string")],...U.expect==="blocked"||U.expect==="allowed"?[]:[e(["tests",j,"expect"],'must be "blocked" or "allowed"')],...U.rule===void 0||typeof U.rule==="string"?[]:[e(["tests",j,"rule"],"must be a string if provided")],...U.expect==="blocked"&&typeof U.rule!=="string"?[rn(["tests",j,"rule"],"required string for blocked fixtures")]:[]]})}function _b(G){if(!Array.isArray(G.tests))return[];let U=new Set(De(G));return[...new Set(G.tests.flatMap((j)=>lr(j)&&j.expect==="blocked"&&typeof j.rule==="string"?[j.rule]:[]))].filter((j)=>!U.has(j)).map((j)=>rn(["tests"],`blocked fixture references unknown rule "${j}"`))}function wb(G){if(!Array.isArray(G.allowed_commands)||!Array.isArray(G.rules))return[];let U=new Set(G.allowed_commands.filter((j)=>typeof j==="string"));return G.rules.flatMap((j,K)=>{let re=lr(j)?j.command:void 0;if(typeof re!=="string"||U.has(re))return[];return[rn(["rules",K,"command"],`"${re}" must be listed in allowed_commands`)]})}function lr(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function Q(G,U){let j=X(G,U),K;try{K=Ld(j.userConfigTarget,j.projectConfigTarget)}catch(pt){if(pt instanceof o)return Nb(j,pt.message);throw pt}let re=m(j.userConfigTarget),oe=K?{config:null,errors:[]}:m(j.projectConfigTarget),de=iu(j.userConfigPath,re.errors),Se=iu(j.projectConfigPath,oe.errors),we=new Set,We=re.config?Wa(re.config,wr(j.userConfigPath),"user",j.userScope,we):su(),mt=oe.config?Wa(oe.config,wr(j.projectConfigPath),"project",j.projectScope,we):su(),gt=re.config?.overrides??{},ft=oe.config?.overrides??{};return{rules:[...ou(We.rules,gt),...ou(mt.rules,ft)],transparent_wrappers:Mb(re.config,oe.config),rulebooks:[...We.rulebooks,...mt.rulebooks],errors:[...de,...Se,...We.errors,...mt.errors],warnings:[...We.warnings,...mt.warnings,...We.canValidateOverrides?Fa(gt,We.knownRuleIds,j.userConfigPath):[],...We.canValidateOverrides?Db(ft,We.knownRuleIds,j.projectConfigPath):[],...mt.canValidateOverrides?Fa(ft,mt.knownRuleIds,j.projectConfigPath):[]],userConfig:re.config??void 0,projectConfig:oe.config??void 0,...j}}function B(G,U){let j=Ab(G,U);if(!j)return[];return[...j.scope.errors,...j.scope.warnings,...Pb(j.config,j.scope,G)]}function Ab(G,U){let j=U??S(wr(wr(G)),"rules policy"),K=m(i(j,G)).config;if(!K)return null;return{config:K,scope:Wa(K,wr(G),"project",j)}}function Pb(G,U,j){return U.canValidateOverrides?Fa(G.overrides??{},U.knownRuleIds,j):[]}function Wa(G,U,j,K=S(wr(wr(U)),j==="user"?"user policy":"project policy"),re=new Set){let oe=[],de=[],Se=G.rules.flatMap((We)=>{let mt=Ib(We,U,K);if(mt.errors.length>0||!mt.rulebook)return oe.push(...mt.errors),[];let gt=mt.rulebook;if(re.has(gt.name))return de.push(`duplicate active rulebook name "${gt.name}" for ${We}; keeping the first and ignoring this one, so its rules are not active; rename one of them in its rulebook file and in the rules config that lists it`),[];return re.add(gt.name),[{rules:Tb(gt),rulebook:{source:j,spec:We,name:gt.name,version:gt.version,rules:gt.rules.map((ft)=>`${gt.name}/${ft.name}`)}}]}),we=Se.flatMap((We)=>We.rules);return{rules:we,rulebooks:Se.map((We)=>We.rulebook),knownRuleIds:new Set(we.map((We)=>We.name)),errors:oe,warnings:de,canValidateOverrides:oe.length===0}}function Tb(G){if(G.rulebook_version===2)return G.rules.map((U)=>({name:`${G.name}/${U.name}`,command:U.command,block_args:[],match:U.match,reason:U.reason,intent:U.intent}));return G.rules.map((U)=>({...U,name:`${G.name}/${U.name}`,match:void 0}))}function Ib(G,U,j){let K=Ne(G),re=M(U,K),oe=Ob(re,j);if("error"in oe)return{rulebook:null,errors:[oe.error]};if(oe.content===null)return{rulebook:null,errors:[`missing rulebook file ${re} for ${G}; ${kb(G)}`]};let de=xe(oe.content);if("problem"in de)return{rulebook:null,errors:[`invalid rulebook ${re}: ${de.problem}; fix that file`]};if(de.rulebook.name!==K)return{rulebook:null,errors:[`rulebook name "${de.rulebook.name}" in ${re} must match source "${G}"; fix that file`]};return{rulebook:de.rulebook,errors:[]}}function Ne(G){return w(G)?N(G).name:G}function kb(G){return w(G)?`run ${Vd} to vendor ${G}`:"create that file or remove that source from the rules config"}function Ob(G,U){try{return{content:r(i(U,G))}}catch(j){if(j instanceof o)return{error:j.message};throw j}}function xe(G){let U;try{U=JSON.parse(G)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:le(U)}}catch(j){return{problem:j instanceof Error?j.message:"invalid rulebook"}}}function Mb(G,U){return[...new Set([...G?.transparent_wrappers??[],...U?.transparent_wrappers??[]])]}function ou(G,U){return G.flatMap((j)=>{let K=U[j.name];if(K==="off")return[];if(K&&typeof K==="object")return[{...j,intent:K.intent??j.intent,reason:K.reason}];return[j]})}function Fa(G,U,j){return Object.keys(G).filter((K)=>!U.has(K)).map((K)=>`unknown override key "${K}" in ${j}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function Db(G,U,j){return Object.keys(G).filter((K)=>U.has(K)).map((K)=>`project override cannot target user-scoped rule "${K}" in ${j}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function iu(G,U){return U.map((j)=>j.startsWith("Unable to access ")?j:`${G}: ${j}`)}function Nb(G,U){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[U],warnings:[],userConfigPath:G.userConfigPath,projectConfigPath:G.projectConfigPath}}function su(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as Vb,readFileSync as Kb}from"node:fs";var au=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores, with or without --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.nested-recursive-delete-unread",category:"PowerShell",label:"Nested PowerShell recursive delete not read",description:"Blocks a recursive delete handed to powershell or pwsh in any form other than literal -Command script words.",example:"pwsh -WorkingDirectory C:\\ -c 'Remove-Item -Recurse -Force *'",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-root-or-home",category:"Command Prompt",label:"cmd recursive delete root or home",description:"Blocks cmd rmdir /s or del /s of root or home paths.",example:"cmd /c rmdir /s /q C:\\",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-escaped-quote",category:"Command Prompt",label:"cmd recursive delete with escaped quotes",description:"Blocks cmd rmdir /s or del /s whose quoting can reach cmd as \\\" and split the target down to the drive root.",example:'cmd /c "rmdir /s /q \\"build output\\""',intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-git-metadata",category:"Command Prompt",label:"cmd recursive delete Git metadata",description:"Blocks cmd rmdir /s or del /s of protected Git metadata and hooks.",example:"cmd /c rmdir /s /q .git",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-dynamic-target",category:"Command Prompt",label:"cmd recursive delete dynamic target",description:"Blocks cmd rmdir /s or del /s with wildcard or variable targets in strict mode.",example:"cmd /c del /s /q *.log",intent:"scope_down",activationCapability:"fail_closed"},{id:"cmd.recursive-delete-home-cwd",category:"Command Prompt",label:"cmd recursive delete from home cwd",description:"Blocks cmd rmdir /s or del /s while working in home.",example:"Set-Location $HOME; cmd /c rmdir /s /q build",intent:"scope_down"},{id:"cmd.recursive-delete-cwd-self",category:"Command Prompt",label:"cmd recursive delete current directory",description:"Blocks cmd rmdir /s or del /s of the current directory.",example:"cmd /c rmdir /s /q .",intent:"scope_down"},{id:"cmd.recursive-delete-outside-cwd",category:"Command Prompt",label:"cmd recursive delete outside cwd",description:"Blocks cmd rmdir /s or del /s outside the original cwd.",example:"cmd /c rmdir /s /q ..\\outside",intent:"scope_down"},{id:"cmd.recursive-delete-paranoid",category:"Command Prompt",label:"cmd recursive delete paranoid mode",description:"Blocks non-temp cmd rmdir /s or del /s when paranoid rm is enabled.",example:"cmd /c rmdir /s /q build",intent:"scope_down",activationCapability:"paranoid_rm"},{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 other than /dev/null, /dev/zero, or /dev/full.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"Filesystem format on a device",description:"Blocks mkfs, mke2fs, and newfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"disk.erase",category:"Filesystem",label:"Disk erase or repartition",description:"Blocks diskutil erase and partition verbs, wipefs -a/-o, sgdisk writes, and parted label or partition edits on a /dev device.",example:"diskutil eraseDisk APFS Untitled disk4",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:"redirect.block-device",category:"Filesystem",label:"Redirect onto a disk device",description:"Blocks output redirects whose literal target is a disk device path under /dev.",example:"cat disk.img > /dev/sda",intent:"manual_only"},{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"}],Ga=new Set(au.map((G)=>G.id)),z=au,Lb=new Map(z.map((G)=>[G.id,G.intent]));function xt(G,U){return{id:G,reason:U,intent:Lb.get(G)??"manual_only"}}var za=[{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"}],$i={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Wb=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Fb=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],$a=[{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"]},...Fb.flatMap((G)=>Wb.map((U)=>({id:["secret.home",G.idSlug,U.slice(1)].join("."),category:"Home path",label:[G.label,U].join(""),description:["Blocks home ",G.label,U," credential backup files."].join(""),suffixParts:[...G.directoryParts,[G.basename,U].join("")]}))),{id:"secret.home.gh-hosts",category:"Home path",label:"~/.config/gh/hosts.yml",description:"Blocks GitHub CLI host credential files.",suffixParts:[".config","gh","hosts.yml"]}];var Bi=[{id:"secret.cli.claude-code",category:"Coding CLI credential",label:"Claude Code credentials",paths:["~/.claude/.credentials.json"]},{id:"secret.cli.claude-code.config",category:"Coding CLI config",label:"Claude Code config",paths:["~/.claude/settings.json","~/.claude/settings.local.json","~/.claude.json","<project>/.claude/settings.local.json","<project>/.mcp.json"]},{id:"secret.cli.antigravity",category:"Coding CLI config",label:"Antigravity CLI hook config",paths:["~/.gemini/config/hooks.json","~/.gemini/config/mcp_config.json"]},{id:"secret.cli.codex",category:"Coding CLI credential",label:"Codex credentials",paths:["~/.codex/auth.json","~/.codex/.credentials.json","~/.codex/secrets","~/.codex/.sandbox-secrets"]},{id:"secret.cli.codex.config",category:"Coding CLI config",label:"Codex config",paths:["~/.codex/config.toml","~/.codex/<name>.config.toml"]},{id:"secret.cli.gemini",category:"Coding CLI credential",label:"Gemini CLI credentials",paths:["~/.gemini/oauth_creds.json","~/.gemini/mcp-oauth-tokens.json","~/.gemini/a2a-oauth-tokens.json","~/.gemini/gemini-credentials.json"]},{id:"secret.cli.gemini.config",category:"Coding CLI config",label:"Gemini CLI config",paths:["~/.gemini/settings.json","~/.gemini/google_accounts.json","<project>/.gemini/settings.json","/Library/Application Support/GeminiCli/settings.json","/etc/gemini-cli/settings.json"]},{id:"secret.cli.copilot-cli",category:"Coding CLI credential",label:"GitHub Copilot CLI credentials",paths:["~/.copilot/config.json","~/.copilot/mcp-oauth-config","~/.copilot/mcp-secrets"]},{id:"secret.cli.copilot-cli.config",category:"Coding CLI config",label:"GitHub Copilot CLI config",paths:["~/.copilot/mcp-config.json"]},{id:"secret.cli.kimi-code",category:"Coding CLI credential",label:"Kimi Code credentials",paths:["~/.kimi-code/server.token","~/.kimi-code/credentials","~/.kimi/credentials","~/.kimi/mcp-oauth"]},{id:"secret.cli.kimi-code.config",category:"Coding CLI config",label:"Kimi Code config",paths:["~/.kimi-code/config.toml","~/.kimi-code/mcp.json","~/.kimi/config.toml","~/.kimi/config.json","~/.kimi/config.json.bak","~/.kimi/mcp.json","<project>/.kimi-code/mcp.json"]},{id:"secret.cli.opencode",category:"Coding CLI credential",label:"OpenCode credentials",paths:["~/.local/share/opencode/auth.json","~/.local/share/opencode/mcp-auth.json","~/.local/share/opencode/opencode.db"]},{id:"secret.cli.opencode.config",category:"Coding CLI config",label:"OpenCode config",paths:["~/.config/opencode/opencode.json","~/.config/opencode/opencode.jsonc","~/.config/opencode/config.json","/Library/Application Support/opencode/opencode.json","/etc/opencode/opencode.json","<project>/opencode.json","<project>/opencode.jsonc"]},{id:"secret.cli.pi",category:"Coding CLI credential",label:"Pi credentials",paths:["~/.pi/agent/auth.json"]},{id:"secret.cli.pi.config",category:"Coding CLI config",label:"Pi config",paths:["~/.pi/agent/models.json"]},{id:"secret.cli.amp",category:"Coding CLI credential",label:"Amp Code credentials",paths:["~/.local/share/amp/secrets.json","~/.amp/oauth"]},{id:"secret.cli.amp.config",category:"Coding CLI config",label:"Amp Code config",paths:["~/.config/amp/settings.json","~/.config/amp/settings.jsonc","<project>/.amp/settings.json","<project>/.amp/settings.jsonc"]},{id:"secret.cli.cursor",category:"Coding CLI credential",label:"Cursor CLI credentials",paths:["~/.cursor/auth.json","~/.config/cursor/auth.json","~/.cursor/projects/<name>/mcp-auth.json"]},{id:"secret.cli.cursor.config",category:"Coding CLI config",label:"Cursor CLI config",paths:["~/.cursor/mcp.json","<project>/.cursor/mcp.json"]},{id:"secret.cli.grok-build",category:"Coding CLI credential",label:"Grok Build credentials",paths:["~/.grok/auth.json","~/.grok/mcp_credentials.json"]},{id:"secret.cli.grok-build.config",category:"Coding CLI config",label:"Grok Build config",paths:["~/.grok/config.toml","~/.grok/managed_config.toml","~/.grok/requirements.toml","<project>/.grok/config.toml","/etc/grok/managed_config.toml","/etc/grok/requirements.toml"]},{id:"secret.cli.droid",category:"Coding CLI credential",label:"Factory Droid credentials",paths:["~/.factory/auth.encrypted","~/.factory/auth.v2.file","~/.factory/auth.v2.key","~/.factory/auth.v2.loginkeychain"]},{id:"secret.cli.droid.config",category:"Coding CLI config",label:"Factory Droid config",paths:["~/.factory/settings.json","~/.factory/hooks.json","~/.factory/mcp.json","<project>/.factory/mcp.json"]},{id:"secret.cli.devin",category:"Coding CLI credential",label:"Devin CLI credentials",paths:["~/.local/share/devin/credentials.toml","~/.local/share/devin/mcp/oauth"]},{id:"secret.cli.devin.config",category:"Coding CLI config",label:"Devin CLI config",paths:["~/.config/devin/config.json"]}],lu=[{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"}],Gb=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Ba=lu.map((G)=>({id:`secret.variant.${G.slug}.separator`,category:"Variant",label:`${G.label}-* / ${G.label}_*`,description:`Blocks ${G.label} variants with dash or underscore suffixes.`,prefix:G.prefix})),Ua=lu.flatMap((G)=>Gb.map((U)=>({id:`secret.variant.${G.slug}.${U.slice(1)}`,category:"Variant",label:`${G.label}${U}`,description:`Blocks ${G.label}${U} private credential variants.`,prefix:G.prefix,suffix:U}))),Bo={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)$/},Ha=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((G)=>({id:`secret.ext.${G}`,category:"Extension",label:`.${G}`,description:`Blocks files with the .${G} extension.`,extension:G})),ja=[{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?$/}],Qe=[...za,$i,...$a,...Ba,...Ua,Bo,...Ha,...ja,...Bi].map((G)=>({id:G.id,category:G.category,label:G.label,...G.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in G?{paths:G.paths}:{description:G.description}})),Ui=new Set(Bi.flatMap((G)=>G.category==="Coding CLI config"?[G.id]:[])),Va=new Set(Qe.map((G)=>G.id));import{isAbsolute as Ka,join as zb,normalize as $b,sep as Hi}from"node:path";var ji=process.platform==="win32",cu=/[*?]/;function qa(G){let U=G.trim(),j=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(ji?U.replaceAll("\\","/"):U);if(!j)return null;let K=j[1]??"",re=j[2]??"";if(cu.test(K)||re==="."||re==="..")return null;return{root:K||"/",name:re}}function Uo(G,U){if(G==="~")return U;if(G.startsWith("~/"))return`${U}${G.slice(1)}`;return G}function Ya(G,U){if(typeof G!=="string"||G.trim()==="")return"must be a non-empty path string";let j=Uo(G.trim(),U);if(!Ka(j))return"must be an absolute path or start with ~/";return Ho(j,U)}function Za(G,U){let j=du(G,U);if(j===null)return"must be a non-empty path string";if(!Ka(j))return null;if(Ho(j,U)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var Bb="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Ub="cannot cover the guard's own configuration";function du(G,U){if(typeof G!=="string"||G.trim()==="")return null;let j=G.trim(),K=ji?j.replaceAll("\\","/"):j;return Uo(K.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),U)}function Xa(G,U){let j=du(G,U);if(j===null)return"must be a non-empty path string";let K=qa(j)?.root??j;if(cu.test(K))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Ka(K))return null;if(Ho(K,U)!==null)return Bb;return Hb(K,U)?Ub:null}function Hb(G,U){let j=Vi(G),K=Vi(zb(U,".cc-safety-net"));return j===K||j.startsWith(`${K}${Hi}`)}function Ho(G,U){let j=Vi(G),K=Vi(U);if(j===K)return"cannot be the home directory";let re=j.endsWith(Hi)?j:`${j}${Hi}`;if(K.startsWith(re))return"cannot contain the home directory";return null}function Vi(G){let U=$b(G);if(ji)U=U.replace(/\//g,"\\").toLowerCase();if(U.length>(ji?3:1)&&U.endsWith(Hi))U=U.slice(0,-1);return U}var uu=30,Ki=1,qi=365;function mu(G){if(typeof G!=="number"||!Number.isInteger(G))return 30;if(G<1)return 1;return G>365?365:G}var fu=new Set(z.filter((G)=>G.catastrophic).map((G)=>G.id));function At(G,U){if(!G)return null;if(fu.has(G.id))return G;if(U?.destructiveCommandProtectionEnabled===!1)return null;let j=U?.effectiveDestructiveCommandRules[G.id];return j&&!j.enabled?null:G}function Jt(G,U,j){if(fu.has(U))return!0;if(G?.destructiveCommandProtectionEnabled===!1)return!1;return G?.effectiveDestructiveCommandRules[U]?.enabled??j}function V(G,U){return Object.freeze(Object.fromEntries(z.map((j)=>{let K=j.activationCapability?U[j.activationCapability]:void 0,re=K?.enabled??!0,oe=G.destructiveCommandRuleOverrides[j.id],de=j.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...oe?{override:oe}:{}}:G.destructiveCommandProtectionEnabled?oe?{enabled:oe==="on",inheritedEnabled:re,changesInherited:oe==="on"!==re,source:"rule_override",...j.activationCapability?{activationCapability:j.activationCapability}:{},override:oe}:{enabled:re,inheritedEnabled:re,changesInherited:!1,source:K?.source??"built_in_default",...j.activationCapability?{activationCapability:j.activationCapability}:{}}:{enabled:!1,inheritedEnabled:re,changesInherited:!1,source:"master_disabled",...j.activationCapability?{activationCapability:j.activationCapability}:{},...oe?{override:oe}:{}};return[j.id,Object.freeze(de)]})))}function pu(G,U){return Object.freeze({...G,effectiveDestructiveCommandRules:V(G,U)})}var gu={standard:0,strict:1,paranoid:2};function ee(G,U,j=!1,K=G.safety.level){let re=jb(G,U,K),oe=new Set(j?re.map((mt)=>mt.field):[]),de=(mt,gt)=>oe.has(mt)?void 0:gt,Se=(mt,gt)=>Object.fromEntries(Object.entries(gt??{}).filter(([ft])=>!oe.has(`${mt}.${ft}`))),we=(mt,gt)=>gt?.filter((ft)=>!oe.has(`${mt}.${ft}`));return{policy:{version:1,safety:{level:de("safety.level",U.safety?.level)??G.safety.level,overrides:{...G.safety.overrides,...Se("safety.overrides",U.safety?.overrides)}},workflow:{worktree_mode:de("workflow.worktree_mode",U.workflow?.worktree_mode)??G.workflow.worktree_mode},destructive_command_protection:{enabled:de("destructive_command_protection.enabled",U.destructive_command_protection?.enabled)??G.destructive_command_protection.enabled,overrides:{...G.destructive_command_protection.overrides,...Se("destructive_command_protection.overrides",U.destructive_command_protection?.overrides)},allow_paths:Ja(G.destructive_command_protection.allow_paths,we("destructive_command_protection.allow_paths",U.destructive_command_protection?.allow_paths))},secret_protection:{enabled:de("secret_protection.enabled",U.secret_protection?.enabled)??G.secret_protection.enabled,overrides:{...G.secret_protection.overrides,...Se("secret_protection.overrides",U.secret_protection?.overrides)},deny_paths:Ja(G.secret_protection.deny_paths,U.secret_protection?.deny_paths),allow_paths:Ja(G.secret_protection.allow_paths,we("secret_protection.allow_paths",U.secret_protection?.allow_paths))},audit:G.audit},weakenings:re.map((mt)=>mt.message)}}function Ja(G,U){return[...new Set([...G,...U??[]])]}function jb(G,U,j){let K=U.safety?.level,re=ki[j];return[...K&&gu[K]<gu[G.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${G.safety.level} -> ${K}`}]:[],...Xr.flatMap((oe)=>U.safety?.overrides?.[oe]===!1&&(G.safety.overrides[oe]??re[oe])?[{field:`safety.overrides.${oe}`,message:`project policy disables ${oe}`}]:[]),...U.workflow?.worktree_mode===!0&&!G.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...U.destructive_command_protection?.enabled===!1&&G.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...U.secret_protection?.enabled===!1&&G.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...hu("destructive_command_protection.overrides",U.destructive_command_protection?.overrides,(oe)=>G.destructive_command_protection.enabled&&G.destructive_command_protection.overrides[oe]!=="off"),...hu("secret_protection.overrides",U.secret_protection?.overrides,(oe)=>G.secret_protection.enabled&&(G.secret_protection.overrides[oe]==="on"?!0:G.secret_protection.overrides[oe]!=="off"&&!Ui.has(oe))),...G.destructive_command_protection.enabled?yu(G.destructive_command_protection.allow_paths,U.destructive_command_protection?.allow_paths).map((oe)=>({field:`destructive_command_protection.allow_paths.${oe}`,message:`project policy adds destructive allow path: ${oe}`})):[],...G.secret_protection.enabled?yu(G.secret_protection.allow_paths,U.secret_protection?.allow_paths).map((oe)=>({field:`secret_protection.allow_paths.${oe}`,message:`project policy adds secret allow path: ${oe}`})):[]]}function hu(G,U,j){return Object.entries(U??{}).flatMap(([K,re])=>re==="off"&&j(K)?[{field:`${G}.${K}`,message:`project policy disables rule ${K}`}]:[])}function yu(G,U){return(U??[]).filter((j)=>!G.includes(j))}var tl=new Set(["standard","strict","paranoid"]),te={version:1,safety:{level:"standard",overrides:{}},workflow:{worktree_mode:!1},destructive_command_protection:{enabled:!0,overrides:{},allow_paths:[]},secret_protection:{enabled:!0,overrides:{},deny_paths:[],allow_paths:[]},audit:{retention_days:uu}};function vu(G,U){let j=Qb(l(G,U),G.home),K=L(G,U)?{exists:!1,policy:F(),errors:[]}:Me(h(U.cwd),G.home),re=ue(K.parsed,G.home),oe=v(n.projectTightenOnly,G.env),de=j.gui??te,Se=Object.keys(re.policy).length>0?ee(de,re.policy,oe,Id(de.safety.level,G.env)):void 0,we=[...j.errors,...K.errors,...re.diagnostics],We=(j.fallback==="defaults"&&Se?"salvaged":j.fallback)??(j.gui?void 0:K.fallback)??(we.length>0?"salvaged":void 0),mt=re.policy.safety?.level&&Se?.policy.safety.level===re.policy.safety.level?"project":j.levelPresent?"user":"default";return{...Se?el(Se.policy):j.policy,errors:we,...We?{fallback:We}:{},...K.exists?{policyScopes:{levelScope:mt,weakenings:Se?.weakenings??[],weakeningsIgnored:oe}}:{}}}var qb="project policy audit settings are ignored; audit is user scope only";function ue(G,U){if(!Rn(G))return{policy:{},diagnostics:[]};let j=Rn(G.safety)?G.safety:{},K=Rn(G.workflow)?G.workflow:{},re=Rn(G.destructive_command_protection)?G.destructive_command_protection:{},oe=Rn(G.secret_protection)?G.secret_protection:{},de={...tl.has(j.level)?{level:j.level}:{},...Rn(j.overrides)?bu({overrides:Eu(j.overrides,Xr,["safety","overrides"],Ar)}):{}},Se={...typeof re.enabled==="boolean"?{enabled:re.enabled}:{},...re.overrides!==void 0?{overrides:Yi(re.overrides,Ga,xu,Ar)}:{},...re.allow_paths!==void 0?{allow_paths:to(re.allow_paths,Ya,U,["destructive_command_protection","allow_paths"],Ar)}:{}},we={...typeof oe.enabled==="boolean"?{enabled:oe.enabled}:{},...oe.overrides!==void 0?{overrides:Yi(oe.overrides,Va,_u,Ar)}:{},...oe.deny_paths!==void 0?{deny_paths:to(oe.deny_paths,Za,U,["secret_protection","deny_paths"],Ar)}:{},...oe.allow_paths!==void 0?{allow_paths:to(oe.allow_paths,Xa,U,["secret_protection","allow_paths"],Ar)}:{}};return{policy:bu({safety:de,workflow:typeof K.worktree_mode==="boolean"?{worktree_mode:K.worktree_mode}:{},destructive_command_protection:Se,secret_protection:we}),diagnostics:G.audit===void 0?[]:[qb]}}function Eu(G,U,j,K){return Object.fromEntries(U.flatMap((re)=>{let oe=G[re];if(typeof oe==="boolean")return[[re,oe]];if(oe!==void 0)K(e([...j,re],nl));return[]}))}function bu(G){return Object.fromEntries(Object.entries(G).flatMap((U)=>Object.keys(U[1]).length>0?[U]:[]))}var Ar=()=>{return},nl="must be a boolean",rl="must be an object if provided",Ru=`must be an integer between ${Ki} and ${qi}`,xu={path:["destructive_command_protection","overrides"],label:"destructive command"},_u={path:["secret_protection","overrides"],label:"secret protection"},et=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function tt(G,U){let j=[];return{policy:wu(G,U,(re)=>{j.push(re)}),issues:j}}function E(G,U){return wu(G,U,Ar)}function wu(G,U,j){if(!Rn(G))return j(e([],"Config must be an object")),F();if(G.version!==1)j(e(["version"],"must be 1"));let K=eo(G.safety,["safety"],["level","overrides"],j),re=eo(K.overrides,["safety","overrides"],Xr,j),oe=eo(G.workflow,["workflow"],["worktree_mode"],j),de=eo(G.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],j),Se=eo(G.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],j),we=eo(G.audit,["audit"],["retention_days"],j);return Au(G,et,[],j),{version:1,safety:{level:Yb(K.level,j),overrides:Eu(re,Xr,["safety","overrides"],j)},workflow:{worktree_mode:Qa(oe.worktree_mode,["workflow","worktree_mode"],!1,j)},destructive_command_protection:{enabled:Qa(de.enabled,["destructive_command_protection","enabled"],!0,j),overrides:Yi(de.overrides,Ga,xu,j),allow_paths:to(de.allow_paths,Ya,U,["destructive_command_protection","allow_paths"],j)},secret_protection:{enabled:Qa(Se.enabled,["secret_protection","enabled"],!0,j),overrides:Yi(Se.overrides,Va,_u,j),deny_paths:to(Se.deny_paths,Za,U,["secret_protection","deny_paths"],j),allow_paths:to(Se.allow_paths,Xa,U,["secret_protection","allow_paths"],j)},audit:{retention_days:Zb(we.retention_days,j)}}}function eo(G,U,j,K){if(G===void 0)return{};if(!Rn(G))return K(e(U,rl)),{};return Au(G,j,U,K),G}function Au(G,U,j,K){for(let re of Object.keys(G).filter((oe)=>!U.includes(oe)))K({path:j,message:re,kind:"unknownKeys"})}function Yb(G,U){if(G===void 0)return"standard";if(tl.has(G))return G;return U(e(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Qa(G,U,j,K){if(typeof G==="boolean")return G;if(G!==void 0)K(e(U,nl));return j}function Zb(G,U){if(!(G===void 0||typeof G==="number"&&Number.isInteger(G)&&G>=Ki&&G<=qi))U(e(["audit","retention_days"],Ru));return mu(G)}function Yi(G,U,j,K){if(G===void 0)return{};if(!Rn(G))return K(e(j.path,rl)),{};return Object.fromEntries(Object.entries(G).flatMap(([re,oe])=>{if(!U.has(re))return K({path:[...j.path,re],message:`unknown ${j.label} rule id "${re}"`,kind:"key"}),[];if(oe==="on"||oe==="off")return[[re,oe]];return K(e([...j.path,re],'must be "on" or "off"')),[]}))}function to(G,U,j,K,re){if(G===void 0)return[];if(!Array.isArray(G))return re(e(K,"must be an array of paths")),[];return G.flatMap((oe,de)=>{let Se=U(oe,j);if(Se===null)return[oe];return re(typeof oe==="string"?rn([...K,de],Se):e([...K,de],Se)),[]})}function Rn(G){return!!G&&typeof G==="object"&&!Array.isArray(G)}function F(){return structuredClone(te)}function Le(G,U){let j=T({safety:$e(G.safety)},U),K=V({destructiveCommandProtectionEnabled:G.destructive_command_protection.enabled,destructiveCommandRuleOverrides:G.destructive_command_protection.overrides},j.capabilities),re=Object.values(K),oe=re.filter((de)=>de.source!=="catastrophic");return{selectedPreset:G.safety.level,effectiveLevel:j.effectiveLevel,capabilities:j.capabilities,rules:K,counts:{enabled:oe.filter((de)=>de.enabled).length,disabled:oe.filter((de)=>!de.enabled).length,effectiveCustomizations:re.filter((de)=>de.changesInherited).length}}}function Me(G,U){if(!Vb(G))return{exists:!1,policy:F(),errors:[]};try{let j=Kb(G,"utf-8");if(!j.trim())return{exists:!0,policy:F(),errors:[`${G}: Config file is empty`],fallback:"defaults"};let K=JSON.parse(j),re=tt(K,U);if(re.issues.length===0)return{exists:!0,parsed:K,policy:re.policy,errors:[]};return{exists:!0,parsed:K,policy:re.policy,errors:re.issues.map((oe)=>`${G}: ${Jb(oe)}`),fallback:Rn(K)?"salvaged":"defaults"}}catch(j){let K=j instanceof Error?j.message:String(j);return{exists:!0,policy:F(),errors:[`${G}: ${j instanceof SyntaxError?"Invalid JSON":K}`],fallback:"defaults"}}}var Xb=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[rl,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[nl,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Ru,`not an integer between ${Ki} and ${qi}`]]);function Jb(G){let U=La(G.path);if(G.kind==="unknownKeys")return`${U===""?"":`${U}.`}${G.message}: unknown field`;if(G.kind==="key")return`${U}: unknown rule id`;let j=Xb.get(G.message)??G.message;return U===""?j:`${U}: ${j}`}function Qb(G,U){let j=Me(G,U);if(!j.exists){let K=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!Rn(K))return{policy:Cu(),errors:[]};let re=E(K,U);return{policy:el(re),gui:re,errors:[],levelPresent:Su(K)}}if(j.parsed===void 0)return{policy:Cu(),errors:j.errors,...j.fallback?{fallback:j.fallback}:{}};return{policy:el(j.policy),gui:j.policy,errors:j.errors,...j.fallback?{fallback:j.fallback}:{},levelPresent:Su(j.parsed)}}function Su(G){let U=Rn(G)&&Rn(G.safety)?G.safety:{};return tl.has(U.level)}function Fe(G){let U=Object.entries(G),j=new Set(U.flatMap(([K,re])=>re==="on"?[K]:[]));return[...new Set([...[...Ui].filter((K)=>!j.has(K)),...U.flatMap(([K,re])=>re==="off"?[K]:[])])]}function Cu(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Fe({}),denyPaths:[],allowPaths:[]}}}function el(G){return{safety:$e(G.safety),worktreeMode:G.workflow.worktree_mode,destructiveCommandProtectionEnabled:G.destructive_command_protection.enabled,destructiveCommandRuleOverrides:G.destructive_command_protection.overrides,destructiveCommandAllowPaths:G.destructive_command_protection.allow_paths,secretProtection:{enabled:G.secret_protection.enabled,disabledRules:Fe(G.secret_protection.overrides),denyPaths:G.secret_protection.deny_paths,allowPaths:G.secret_protection.allow_paths}}}function $e(G){let U={...G.overrides.fail_closed!==void 0?{failClosed:G.overrides.fail_closed}:{},...G.overrides.paranoid_rm!==void 0?{paranoidRm:G.overrides.paranoid_rm}:{},...G.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:G.overrides.paranoid_interpreters}:{}};return{level:G.level,...Object.keys(U).length>0?{overrides:U}:{}}}function k(G,U){let j=Q(G,U),K=vu(G,U),re={rules:j.rules,transparentWrappers:j.transparent_wrappers,safety:K.safety,worktreeMode:K.worktreeMode,destructiveCommandProtectionEnabled:K.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:K.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:K.destructiveCommandAllowPaths,secretProtection:{enabled:K.secretProtection.enabled??!0,disabledRules:K.secretProtection.disabledRules??[],denyPaths:K.secretProtection.denyPaths,allowPaths:K.secretProtection.allowPaths??[]}},oe={...j.userConfig?.overrides,...j.projectConfig?.overrides},de=Object.freeze(Object.fromEntries(re.rules.map((Se)=>{let we=j.rulebooks.find((mt)=>mt.rules.includes(Se.name)),We=oe[Se.name];return[Se.name,Object.freeze({id:Se.name,...we?{rulebook:Object.freeze({name:we.name,version:we.version}),...rS(we.spec)?{source:we.spec}:{}}:{},...We&&typeof We==="object"?{override:Object.freeze({type:"reason",reason:We.reason})}:{}})]})));return _e(re,eS(j,K),de,K.policyScopes)}function je(G){if(G.state==="ready")return{state:G.state};return{state:G.state,reason:G.reason}}function eS(G,U){let j=nS(U);if(G.errors.length===0&&G.warnings.length===0&&!j)return;return{diagnostics:[...G.errors,...G.warnings,...U.errors],reason:oS(G.errors.length>0?tS(G.errors):void 0,G.warnings.length>0?il(G.warnings.join("; ")):void 0,j)}}function tS(G){return`${il(G.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function nS(G){if(G.errors.length===0)return;let U=G.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${G.errors.join("; ")}. Enforcing ${U}; the invalid values are not active. Fix the policy file manually`}function rS(G){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(G)}function _e(G,U,j=Object.freeze({}),K){let re=ol(structuredClone(G)),oe=K?{policyScopes:ol(structuredClone(K))}:{};if(!U)return Object.freeze({state:"ready",policy:re,diagnostics:Object.freeze([]),ruleMetadata:j,...oe});return Object.freeze({state:"degraded",policy:re,diagnostics:Object.freeze([...U.diagnostics]),reason:U.reason,ruleMetadata:j,...oe})}function ol(G){if(typeof G!=="object"||G===null)return G;for(let U of Object.values(G))ol(U);return Object.freeze(G)}function oS(...G){return il(G.filter((U)=>!!U).join("; "))}function il(G){return/[.!?]$/.test(G)?G:`${G}.`}function Ue(G){let U=G.effectiveCapabilities,j=G.strict??U.fail_closed.enabled,K=G.paranoidRm??U.paranoid_rm.enabled,re=G.paranoidInterpreters??U.paranoid_interpreters.enabled,oe={fail_closed:sl(U.fail_closed,G.strict,"strict"),paranoid_rm:sl(U.paranoid_rm,G.paranoidRm,"paranoidRm"),paranoid_interpreters:sl(U.paranoid_interpreters,G.paranoidInterpreters,"paranoidInterpreters")};return{policy:pu(G.policySnapshot.policy,oe),effectiveCapabilities:oe,effectiveLevel:Ra({failClosed:j,paranoidRm:K,paranoidInterpreters:re}),strict:j,paranoidRm:K,paranoidInterpreters:re,worktreeMode:G.worktreeMode??!1}}function sl(G,U,j){if(U===void 0||U===G.enabled)return G;return{enabled:U,source:"capability_override",sources:[...G.sources,`analysis options.${j}`]}}import{dirname as iA,isAbsolute as sA,join as aA,parse as lA,resolve as cA,sep as dA}from"node:path";function jo(G,U){if(G!=="powershell")return U[0]?.provenance==="command-substitution";let j=U[0]?.text==="&"||U[0]?.text==="."?1:0,K=U[j]?.provenance;return K!==void 0&&K!=="literal"}var iS=/^[A-Za-z_][A-Za-z0-9_]*=/;function Zi(G,U){return G?.provenance==="literal"&&!G.quoted&&G.raw===U&&G.text===U}function Vo(G){let U=Zi(G.words[0],"time")?1:0,j=U===1&&Zi(G.words[U],"-p")?U+1:U,K=U===1&&Zi(G.words[j],"--")?j+1:j,re=Zi(G.words[K],"!")?K+1:K,oe=G.words.slice(re).find((de)=>!iS.test(de.text));return oe?.provenance==="literal"?oe.text:void 0}var cr=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Xi(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function sS(G){return Object.freeze({...G,span:Object.freeze(G.span),words:Object.freeze(G.words),redirections:Object.freeze(G.redirections.map((U)=>Object.freeze({...U,span:Object.freeze(U.span),...U.heredoc?{heredoc:Object.freeze({...U.heredoc,bodySpan:Object.freeze(U.heredoc.bodySpan),terminatorSpan:Object.freeze(U.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(G.nested.map((U)=>pn(U)))})}function Ji(G,U,j){G.push(j),U.reset()}function Qi(G){let U=[];return{parts:U,push:(j,K,re)=>{if(K<=j)return;U.push({raw:G.slice(j,K),span:{start:j,end:K},provenance:re})}}}function al(G){let U=G.parts??[{raw:G.raw,span:G.span,provenance:G.provenance}];return Object.freeze({kind:"word",...G,span:Object.freeze(G.span),parts:Object.freeze(U.map((j)=>Object.freeze({...j,span:Object.freeze(j.span)})))})}function no(G,U,j,K,re,oe,de){return al({text:K,raw:G.slice(U,j),span:{start:U,end:j},provenance:re,quoted:oe,...de?{parts:de}:{}})}function pn(G){return Object.freeze({...G,span:Object.freeze(G.span),issues:Object.freeze(G.issues.map((U)=>Object.freeze({...U}))),nodes:Object.freeze(G.nodes.map((U)=>{if(U.kind==="command")return sS(U);if(U.kind==="group"||U.kind==="function")return Object.freeze({...U,span:Object.freeze(U.span),body:pn(U.body)});return Object.freeze({...U,span:Object.freeze(U.span)})}))})}function ll(G,U,j){if(U>=j||Tu(G[U]??""))return null;let K="",re=!1,oe=!1,de=U;while(de<j&&!Tu(G[de]??"")){let Se=G[de]??"";if(Se==="'"){re=!0;let we=Pu(G,de+1,j,"'");K+=we.text,oe||=!we.closed,de=we.next;continue}if(Se==='"'){re=!0;let we=Pu(G,de+1,j,'"');K+=we.text,oe||=!we.closed,de=we.next;continue}if(Se==="\\"){re=!0;let we=G[de+1];if(!we||we===`
|
|
7
|
+
`||we==="\r"){oe=!0;break}K+=we,de+=2;continue}if(Se==="`"||G.startsWith("$(",de)||G.startsWith("${",de)||G.startsWith("<(",de)||G.startsWith(">(",de))oe=!0;K+=Se,de++}return{delimiter:K,quoted:re,next:de,ambiguous:oe}}function cl(G,U,j,K){let re=[],oe=U;for(let de of K){let Se=oe,we=!1;while(oe<j){let We=aS(G,oe,j);if((de.stripTabs?We.text.replace(/^\t+/,""):We.text)===de.delimiter){de.attach({body:de.stripTabs?lS(G.slice(Se,oe)):G.slice(Se,oe),delimiter:de.delimiter,quotedDelimiter:de.quotedDelimiter,bodySpan:{start:Se,end:oe},terminatorSpan:{start:oe,end:We.contentEnd}}),oe=We.next,we=!0;break}if(We.next<=oe)break;oe=We.next}if(we)continue;return re.push({code:"unterminated-heredoc",message:`heredoc delimiter ${de.delimiter} was not found`}),{next:j,issues:re,terminated:!1}}return{next:oe,issues:re,terminated:!0}}function Pu(G,U,j,K){let re="",oe=U;while(oe<j&&G[oe]!==`
|
|
8
|
+
`&&G[oe]!=="\r"){let de=G[oe]??"";if(de===K)return{text:re,next:oe+1,closed:!0};if(K==='"'&&de==="\\"&&G[oe+1]){let Se=G[oe+1]??"";re+=["$","`",'"',"\\"].includes(Se)?Se:`\\${Se}`,oe+=2;continue}re+=de,oe++}return{text:re,next:oe,closed:!1}}function Tu(G){return G!=="\r"&&(/[\s;&|<>)]/u.test(G)||G==="`")}function aS(G,U,j){let K=U;while(K<j&&G[K]!==`
|
|
9
|
+
`)K++;let re=K>=j?j:K+1;return{text:G.slice(U,K),contentEnd:K,next:re}}function lS(G){return G.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Du=new Set(["&&","||","|","|&"]),cS=new Set(["!","do","elif","else","if","then","until","while"]);function Nu(G,U){let j={start:0,end:G.length};if(G.length>U.maxInputLength)return pn({kind:"program",dialect:"posix",source:G,span:j,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${U.maxInputLength} UTF-16 code units`}],nodes:[]});let K={wordsUsed:0,maxWords:U.maxWords,quotedExpansionEnd:1/0},re=ns(G,0,G.length,U,K,0),oe=bS(G,K.quotedExpansionEnd,re.nodes)?[...re.issues,Fu]:re.issues;return pn({kind:"program",dialect:"posix",source:G,span:j,status:os(oe,re.limited),issues:oe,nodes:re.nodes})}function ns(G,U,j,K,re,oe,de){let Se=[],we=[],We=Xi(),mt=[],gt=()=>{if(We.words.length===0&&We.redirections.length===0)return;let pt={start:We.start,end:We.end},ht=We.words.map((yt)=>yt.text);Ji(Se,We,{kind:"command",dialect:"posix",source:G.slice(pt.start,pt.end),span:pt,words:We.words,redirections:We.redirections,nested:We.nested,displayText:we.length>0&&Se.length===0?G.slice(U,j):ht.join(" ")})},ft=U;while(ft<j){let pt=G[ft];if(!pt)break;if(de&&pt===de)return gt(),Mu(Se,we),{nodes:Se,issues:we,next:ft+1,closed:!0,limited:!1,pendingHeredocs:mt};if(qo(pt)){if(pt===`
|
|
10
|
+
`||pt==="\r"){gt();let Pt=pt==="\r"&&G[ft+1]===`
|
|
11
|
+
`?ft+2:ft+1,Tt=Se.at(-1);if(Tt?.kind!=="connector"||!Du.has(Tt.operator))Se.push(Object.freeze({kind:"connector",operator:G.slice(ft,Pt),span:Object.freeze({start:ft,end:Pt})}));if(mt.length>0){let kt=cl(G,Pt,j,mt.splice(0));we.push(...kt.issues),ft=kt.next;continue}ft=Pt;continue}ft++;continue}if(pt==="#"){while(ft<j&&G[ft]!==`
|
|
12
|
+
`&&G[ft]!=="\r")ft++;continue}let ht=We.start===-1?LS(G,ft,j):void 0;if(ht){if(ul(Se,we),oe>=K.maxDepth)return ro(Se,we,ft,"depth-limit",K.maxDepth);if(!dl(re))return ro(Se,we,ft,"word-limit",K.maxWords);let Pt=ns(G,ht.braceIndex+1,j,K,re,oe+1,"}"),Tt=Pt.next,kt={start:ht.braceIndex+1,end:Pt.closed?Tt-1:Tt},vt=Iu(G,kt,Pt);if(Se.push({kind:"function",name:ht.name,span:{start:ft,end:Tt},body:vt}),we.push(...Pt.issues),Pt.pendingHeredocs.length>0||Yo(Pt.nodes))we.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(mt.push(...Pt.pendingHeredocs),Pt.limited)return ts(Se,we,Pt.next);if(!Pt.closed)we.push({code:"unclosed-function-body",message:"function body is not closed"});ft=Tt;continue}let yt=rs(G,ft);if(yt){if(gt(),!ju(Se.at(-1)))we.push({code:"unexpected-connector",message:`connector ${yt} has no preceding command`});Se.push(Object.freeze({kind:"connector",operator:yt,span:Object.freeze({start:ft,end:ft+yt.length})})),ft+=yt.length;continue}if(pt===")"){gt(),we.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),Se.push({kind:"unknown",source:pt,span:{start:ft,end:ft+1}}),ft++;continue}if((pt==="("||pt==="{"&&RS(G,ft,j))&&We.start===-1){if(ul(Se,we),oe>=K.maxDepth)return ro(Se,we,ft,"depth-limit",K.maxDepth);let Pt=pt==="("?")":"}",Tt=ns(G,ft+1,j,K,re,oe+1,Pt),kt=Tt.next,vt={start:ft+1,end:Tt.closed?kt-1:kt},It=Iu(G,vt,Tt);if(Se.push({kind:"group",style:pt==="("?"subshell":"brace",span:{start:ft,end:kt},body:It}),we.push(...Tt.issues),Tt.pendingHeredocs.length>0||Yo(Tt.nodes))we.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(mt.push(...Tt.pendingHeredocs),Tt.limited)return ts(Se,we,Tt.next);if(!Tt.closed)we.push({code:pt==="("?"unclosed-subshell":"unclosed-brace-group",message:`${pt} group is not closed`});ft=kt;continue}let bt=(pt==="<"||pt===">")&&G[ft+1]!=="("?fS(G,ft):null;if(bt){let Pt=We.words.at(-1),Tt=Pt&&Pt.span.end===ft&&/^[0-9]+$/.test(Pt.raw)?Number(Pt.raw):void 0;if(Tt!==void 0)We.words.pop();let kt=Tt===void 0?ft:Pt?.span.start??ft;We.start=We.start===-1?ft:We.start;let vt=ft+bt.length;while(vt<j&&/[ \t]/.test(G[vt]??""))vt++;let It=G[vt],Lt=vt>ft+bt.length&&It==="#",en=!It||qo(It)||!!rs(G,vt)||It===de||It===")"||Lt||(It==="<"||It===">")&&G[vt+1]!=="(",Cr=bt==="<<"||bt==="<<-",Ut=Cr?ll(G,vt,j):void 0,Gt=Ut?{word:no(G,vt,Ut.next,Ut.delimiter,"literal",Ut.quoted),nested:[],issues:[],next:Ut.next,limited:!1}:!en?ml(G,vt,j,K,re,oe):void 0;if(Gt){if(we.push(...Gt.issues),Gt.limited)return ts(Se,we,Gt.next);if(!dl(re))return ro(Se,we,Gt.next,"word-limit",K.maxWords)}let ln=Gt?.next??ft+bt.length,Zt={kind:"redirection",operator:bt,span:{start:kt,end:ln},...Tt===void 0?{}:{fd:Tt},...Gt?{target:Gt.word}:{}};if(We.redirections.push(Zt),Cr&&!Ut)we.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if(Ut){if(Ut.ambiguous||Ut.delimiter.length===0)we.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let Xt=We.nested;mt.push({delimiter:Ut.delimiter,quotedDelimiter:Ut.quoted,stripTabs:bt==="<<-",attach:(Cn)=>{if(Zt.heredoc=Cn,Cn.quotedDelimiter)return;let Yn=uS(G,Cn.bodySpan.start,Cn.bodySpan.end,K,re,oe+1);Xt.push(...Yn.programs),we.push(...Yn.issues)}})}if(!Cr&&!Gt)we.push({code:"missing-redirection-target",message:`redirection ${bt} requires a target word`});if(Gt)We.nested.push(...Gt.nested);We.end=ln,ft=ln;continue}let St=We.start===-1;if(St)ul(Se,we);let Et=ml(G,ft,j,K,re,oe);if(we.push(...Et.issues),Et.limited)return ts(Se,we,Et.next);let Ct=wS(We.words)?kS(G,Et.word,re.maxWords-re.wordsUsed,K.maxDepth,K.maxInputLength):void 0;if(Ct?.limitCode)return ro(Se,we,Et.next,Ct.limitCode,Ct.limitCode==="word-limit"?K.maxWords:Ct.limitCode==="depth-limit"?K.maxDepth:K.maxInputLength);let Rt=Ct?.words??[Et.word];for(let Pt of Rt){if(!dl(re))return ro(Se,we,Et.next,"word-limit",K.maxWords);We.words.push(Pt)}if(We.start=We.start===-1?ft:We.start,We.end=Et.next,We.nested.push(...Et.nested),St&&Vu(Et.word))gt();ft=Et.next>ft?Et.next:ft+1}return gt(),Mu(Se,we),we.push(...WS(mt)),{nodes:Se,issues:we,next:ft,closed:de===void 0,limited:!1,pendingHeredocs:[]}}function Iu(G,U,j){return{kind:"program",dialect:"posix",source:G.slice(U.start,U.end),span:U,status:os(j.issues,j.limited),issues:j.issues,nodes:j.nodes}}function ml(G,U,j,K,re,oe){let de="",Se=U,we=!1,We="literal",mt=[],gt=[],ft=!1;while(Se<j){let pt=G[Se],ht=(pt==="<"||pt===">")&&G[Se+1]==="(";if(!pt||qo(pt)||(pt===";"||pt==="|"||pt==="&")&&rs(G,Se)||(pt==="<"||pt===">")&&!ht)break;if(pt===")")break;if(pt==="'"){we=!0;let St=G.indexOf("'",Se+1);if(St===-1||St>=j){de+=G.slice(Se+1,j),gt.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),Se=j;break}de+=G.slice(Se+1,St),Se=St+1;continue}if(pt==='"'){we=!0;let St=dS(G,Se,j,K,re,oe);if(de+=St.text,mt.push(...St.nested),gt.push(...St.issues),ft||=St.limited,We=Ko(We,St.provenance),Se=St.next,ft)break;continue}if(G.startsWith("$'",Se)){we=!0;let St=CS(G,Se+2,j);if(de+=St.text,gt.push(...St.issues),!St.closed)gt.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});Se=St.next;continue}if(pt==="\\"){let St=G[Se+1];if(!St){gt.push({code:"trailing-escape",message:"escape has no following character"}),Se++;break}if(St===`
|
|
13
|
+
`){Se+=2;continue}de+=St,Se+=2;continue}if(Tr(G,Se))gt.push(Pr);let yt=pt==="$"||pt==="<"||pt===">"||pt==="`"?Zo(G,Se,j,K,re,oe):null,bt=yt?pl(yt,mt,gt):Gu(G,Se,j,K,re,oe,mt,gt);if(bt){if(bt.provenance==="variable")de+=G.slice(Se,bt.next);if(ft||=bt.limited,We=Ko(We,bt.provenance),Se=bt.next,ft)break;continue}if(pt==="$"){let St=$u(G,Se,j,de,We);de=St.text,We=St.provenance,Se=St.next;continue}if(pt==="*"||pt==="?"||pt==="[")We=Ko(We,"glob");de+=pt,Se++}return{word:no(G,U,Se,de,We,we,We==="literal"?void 0:ES(G,U,Se)),nested:mt,issues:gt,next:Se,limited:ft}}function dS(G,U,j,K,re,oe){let de="",Se="literal",we=[],We=[],mt=!1,gt=U+1;while(gt<j){let ft=G[gt];if(ft==='"')return{text:de,provenance:Se,nested:we,issues:We,next:gt+1,limited:mt};if(ft==="\\"&&G[gt+1]){let yt=G[gt+1]??"";if(yt===`
|
|
14
14
|
`){gt+=2;continue}if(yt==="\r"&&G[gt+2]===`
|
|
15
|
-
`){gt+=3;continue}de+=["$","`",'"',"\\"].includes(yt)?yt:`\\${yt}`,gt+=2;continue}if(Tr(G,gt))We.push(Pr);let pt=Zo(G,gt,j,K,re,oe),ht=pt?pl(pt,we,We):Gu(G,gt,j,K,re,oe,we,We);if(ht){if(ht.provenance!=="command-substitution")de+=G.slice(gt,ht.next);if(gt=ht.next,mt||=ht.limited,Se=Ko(Se,ht.provenance),mt)return{text:de,provenance:Se,nested:we,issues:We,next:gt,limited:mt};continue}if(ft==="$"){let yt=$u(G,gt,j,de,Se);de=yt.text,Se=yt.provenance,gt=yt.next;continue}de+=ft??"",gt++}return We.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:de,provenance:Se,nested:we,issues:We,next:j,limited:mt}}function Zo(G,U,j,K,re,oe){let de=Wu(G,U);if(!de)return null;let{length:Se,closing:we}=de,We=we==="))",mt=we==="`",gt=G[U]==="<"||G[U]===">",ft=gl(G,U+Se,j,we),pt=ft===-1?j:ft,ht=ft===-1?j:ft+we.length;if(oe>=K.maxDepth)return{program:
|
|
15
|
+
`){gt+=3;continue}de+=["$","`",'"',"\\"].includes(yt)?yt:`\\${yt}`,gt+=2;continue}if(Tr(G,gt))We.push(Pr);let pt=Zo(G,gt,j,K,re,oe),ht=pt?pl(pt,we,We):Gu(G,gt,j,K,re,oe,we,We);if(ht){if(ht.provenance!=="command-substitution")de+=G.slice(gt,ht.next);if(gt=ht.next,mt||=ht.limited,Se=Ko(Se,ht.provenance),mt)return{text:de,provenance:Se,nested:we,issues:We,next:gt,limited:mt};continue}if(ft==="$"){let yt=$u(G,gt,j,de,Se);de=yt.text,Se=yt.provenance,gt=yt.next;continue}de+=ft??"",gt++}return We.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:de,provenance:Se,nested:we,issues:We,next:j,limited:mt}}function Zo(G,U,j,K,re,oe){let de=Wu(G,U);if(!de)return null;let{length:Se,closing:we}=de,We=we==="))",mt=we==="`",gt=G[U]==="<"||G[U]===">",ft=gl(G,U+Se,j,we),pt=ft===-1?j:ft,ht=ft===-1?j:ft+we.length;if(oe>=K.maxDepth)return{program:NS(G,U+Se,pt,"depth-limit"),next:ht,provenance:We?"arithmetic":"command-substitution"};if(We){let Rt=[],Pt=[],Tt=!1,kt=U+Se;while(kt<pt){let vt=Zo(G,kt,pt,K,re,oe+1);if(!vt){if(Tr(G,kt))Pt.push(Pr);kt++;continue}if(Rt.push(...vt.program.nodes),Pt.push(...vt.program.issues),Tt||=vt.program.status==="limited",kt=vt.next,Tt)break}if(ft===-1)Pt.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:pn({kind:"program",dialect:"posix",source:G.slice(U+Se,pt),span:{start:U+Se,end:pt},status:os(Pt,Tt),issues:Pt,nodes:Rt}),next:ht,provenance:"arithmetic"}}let yt=ns(G,U+Se,pt,K,re,oe+1),bt=ft===-1?[{code:"unclosed-command-substitution",message:`${G.slice(U,U+Se)} substitution is not closed`}]:[],St=(mt||gt)&&Yo(yt.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[],Et=mt&&/\\[\\$`\n]/.test(G.slice(U+Se,pt))?[SS]:[],Ct=[...yt.issues,...bt,...St,...Et];return{program:pn({kind:"program",dialect:"posix",source:G.slice(U+Se,pt),span:{start:U+Se,end:pt},status:os(Ct,yt.limited),issues:Ct,nodes:yt.nodes}),next:ht,provenance:"command-substitution"}}function uS(G,U,j,K,re,oe){let de=[],Se=[],we=U;while(we<j){let We=G[we];if(We==="\\"){we+=2;continue}let mt=We==="$"||We==="`"?Zo(G,we,j,K,re,oe):null;if(!mt){if(Tr(G,we))Se.push(Pr);we++;continue}if(de.push(mt.program),pS(G,we,mt.next)&&gS(mt.program))Se.push(Pr);we=mt.next}return{programs:de,issues:Se}}function pl(G,U,j){return U.push(G.program),j.push(...G.program.issues),{provenance:G.provenance,next:G.next,limited:G.program.status==="limited"}}function gl(G,U,j,K){if(K==="`"){for(let Se=U;Se<j;Se++){if(G[Se]==="\\"){Se++;continue}if(G[Se]==="`")return Se}return-1}let re={single:!1,double:!1},oe=[],de=[];for(let Se=U;Se<j;Se++){let we=G[Se];if((we===`
|
|
16
16
|
`||we==="\r")&&de.length>0){let gt=we==="\r"&&G[Se+1]===`
|
|
17
|
-
`?Se+2:Se+1,ft=cl(G,gt,j,de.splice(0));if(!ft.terminated)return-1;Se=ft.next-1;continue}let We=Lu(G,Se,U,j,re);if(We!==null){Se=We;continue}if(!re.double&&G.startsWith("$((",Se)){let gt=
|
|
18
|
-
`&&G[de+1]!=="\r")de++;return de}function rs(G,U){let j=G[U];if(j===";")return";";if(j==="&")return G[U+1]==="&"?"&&":"&";if(j==="|")return G[U+1]==="|"?"||":G[U+1]==="&"?"|&":"|";return null}function
|
|
19
|
-
`,j))j+=G[j+1]==="\r"?3:2;return j}function Wu(G,U){if(G.startsWith("$((",U))return{length:3,closing:"))"};if(G.startsWith("$(",U)||G.startsWith("<(",U)||G.startsWith(">(",U))return{length:2,closing:")"};return G[U]==="`"?{length:1,closing:"`"}:null}var
|
|
20
|
-
`,Se+=we==="\\"?2:1;continue}let We=Wu(G,Se);if(We){K.push(Se);let mt=gl(G,Se+We.length,j,We.closing);if(mt===-1)break;Se=mt+We.closing.length;continue}if(we==="$"&&G[Se+1]==="{"){de++,Se+=2;continue}if(we==="}"&&--de===0)return{close:Se,substitutions:K,quoted:re,continued:oe};Se++}return{close:-1,substitutions:K,quoted:re,continued:oe}}function zu(G,U,j){if(G[U+1]==="{"){let re=is(G,U+2,j).close;return re===-1?j:re+1}if(G[U+1]==="$")return U+2;let K=U+1;while(K<j&&/[A-Za-z0-9_?@#!*-]/.test(G[K]??""))K++;return K===U+1?U+1:K}function
|
|
21
|
-
`],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(re.has(K))return{text:re.get(K)??K,next:U+1};if(K==="x")return es(G,U+1,j,16,2,U+1);if(K==="u")return es(G,U+1,j,16,4,U+1);if(K==="U")return es(G,U+1,j,16,8,U+1);if(/[0-7]/.test(K))return es(G,U,j,8,3,U+1);return{text:K,next:U+1}}function es(G,U,j,K,re,oe){let de=K===16?/[0-9a-fA-F]/:/[0-7]/,Se="",we=U;while(we<j&&Se.length<re&&de.test(G[we]??""))Se+=G[we],we++;if(!Se)return{text:G[oe-1]??"",next:oe};let We=Number.parseInt(Se,K);return We>1114111||We>=55296&&We<=57343?{text:"�",next:we,invalidCodePoint:We}:{text:String.fromCodePoint(We),next:we}}function os(G,U=!1){if(U)return"limited";if(G.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"||j.code==="unsupported-function-substitution"||j.code==="unsupported-backtick-escape"||j.code==="unclosed-parameter-expansion"||j.code==="unsupported-parameter-expansion"))return"invalid";return G.length>0?"partial":"complete"}function $u(G,U,j,K,re){let oe=zu(G,U,j);return{text:K+G.slice(U,oe),provenance:Ko(re,"variable"),next:oe}}function vC(G,U,j){let K=Qi(G),re=U,oe=!1,de=!1,Se=U;while(Se<j){let we=G[Se];if(we==="\\"&&!oe){Se+=2;continue}if(!de&&we==="'"){oe=!oe,Se++;continue}if(!oe&&we==='"'){de=!de,Se++;continue}if(oe){Se++;continue}let We=G.startsWith("$((",Se),mt=G.startsWith("$(",Se)&&!We,gt=!de&&(G.startsWith("<(",Se)||G.startsWith(">(",Se)),ft=we==="`";if(We||mt||gt||ft){let pt=We?3:ft?1:2,ht=We?"))":ft?"`":")",yt=gl(G,Se+pt,j,ht),bt=yt===-1?j:yt+ht.length;K.push(re,Se,"literal"),K.push(Se,bt,We?"arithmetic":"command-substitution"),Se=bt,re=bt;continue}if(we==="$"){let pt=zu(G,Se,j);if(pt>Se+1){K.push(re,Se,"literal"),K.push(Se,pt,"variable"),Se=pt,re=pt;continue}}if(!de&&(we==="*"||we==="?"||we==="[")){K.push(re,Se,"literal"),K.push(Se,Se+1,"glob"),Se++,re=Se;continue}Se++}return K.push(re,j,"literal"),K.parts}function Ko(G,U){if(U==="command-substitution"||G==="command-substitution")return"command-substitution";if(U==="arithmetic"||G==="arithmetic")return"arithmetic";if(U==="variable"||G==="variable")return"variable";if(U==="glob"||G==="glob")return"glob";return G}function EC(G,U,j){return U+1>=j||qo(G[U+1]??"")||rs(G,U+1)!==null}var RC=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),xC=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function _C(G){let U=0;while(U<=G.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(G[U]?.text??""))U++;if(U===G.length)return!0;let j=wC(G,U);if(j===void 0||j===null)return!1;U=j}return!1}function wC(G,U){let j=G[U]?.text.toLowerCase();if(j==="command")return AC(G,U);if(j==="env")return PC(G,U);if(j==="sudo")return TC(G,U);return}function AC(G,U){if(G[U+1]?.text==="-v")return null;for(let j=U+1;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return j+1;if(K==="-p"||K==="-v"||K==="-V"||/^-[pvV]+$/.test(K))continue;return j}return G.length}function PC(G,U){for(let j=U+1;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return j+1;if(RC.has(K)){if(G[j+1]===void 0)return null;j++;continue}if(K.startsWith("-u=")||K.startsWith("--unset=")||K.startsWith("-C")&&K.length>2||K.startsWith("--chdir=")||K.startsWith("-S")&&K.length>2||K.startsWith("--split-string=")||K.startsWith("-P"))continue;if(K.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(K))continue;return j}return G.length}function TC(G,U){for(let j=U+1;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return j+1;if(xC.has(K)){if(G[j+1]===void 0)return null;j++;continue}if(K.startsWith("-"))continue;return j}return G.length}function Bu(G,U,j,K){if(G.provenance!=="literal"||!G.raw.includes("{"))return;let re=Uu(G.raw,U,j,K,!0);if(!re)return;if("limited"in re)return{limited:!0};let oe=re.values.map((de)=>Hu(de,j));if(oe.some((de)=>de===null))return{limited:!0};return{words:[...new Set(oe.filter((de)=>de!==null&&de!==""))]}}function IC(G,U,j,K,re){if(U.provenance!=="literal"||!U.raw.includes("{"))return;let oe=Uu(U.raw,j,K,re,!1);if(!oe)return;if("limited"in oe){if(oe.limited==="expansions")return{limitCode:"depth-limit"};return{limitCode:oe.limited==="length"?"brace-expansion-limit":"word-limit"}}let de=oe.values.map((Se)=>Hu(Se,K));if(de.some((Se)=>Se===null))return;return{words:de.filter((Se)=>Se!==null&&Se!=="").map((Se)=>to(G,U.span.start,U.span.end,Se,"literal",!1))}}function Uu(G,U,j,K,re){let oe=[G],de=G.length,Se=0;while(!0){let we=oe.findIndex((pt)=>Ou(pt,re));if(we===-1)break;if(++Se>j)return{limited:"expansions"};let We=oe[we]??"",mt=Ou(We,re);if(!mt||mt.kind==="range")return{limited:"expansions"};let gt=mt.start+We.length-mt.end,ft=mt.alternatives.reduce((pt,ht)=>pt+gt+ht.length,0);if(de-We.length+ft>K)return{limited:"length"};if(oe.length-1+mt.alternatives.length>U)return{limited:"words"};oe.splice(we,1,...kC(We,mt)),de+=ft-We.length}return Se===0?void 0:{values:oe}}function Ou(G,U){let j=[],K,re=null,oe=!1;for(let de=0;de<G.length;de++){let Se=G[de];if(oe){oe=!1;continue}if(Se==="\\"&&re!=="'"){oe=!0;continue}if(Se===re){re=null;continue}if(re===null&&(Se==="'"||Se==='"')){re=Se;continue}if(re!==null)continue;if(Se==="{"){j.push({start:de,commas:[]});continue}if(Se===","&&j.length>0){j.at(-1)?.commas.push(de);continue}if(Se!=="}"||j.length===0)continue;let we=j.pop();if(!we)continue;let We=we.commas.length>0?{kind:"alternatives",start:we.start,end:de+1,commas:we.commas}:U&&MC(G.slice(we.start+1,de))?{kind:"range",start:we.start,end:de+1}:void 0;if(We&&(!K||We.start<K.start))K=We}if(!K||K.kind==="range")return K;return{kind:K.kind,start:K.start,end:K.end,alternatives:OC(G,K)}}function kC(G,U){return U.alternatives.map((j)=>`${G.slice(0,U.start)}${j}${G.slice(U.end)}`)}function OC(G,U){let j=[U.start,...U.commas,U.end-1];return j.slice(0,-1).map((K,re)=>G.slice(K+1,j[re+1]))}function MC(G){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(G)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(G)}function Hu(G,U){let j=`x${G}`,K=ml(j,0,j.length,{maxInputLength:j.length,maxWords:1,maxDepth:U},{wordsUsed:0,maxWords:1,quotedExpansionEnd:1/0},0);if(K.limited||K.issues.length>0||K.next!==j.length||K.word.provenance!=="literal")return null;return K.word.text.slice(1)}function DC(G,U,j,K){return pn({kind:"program",dialect:"posix",source:G.slice(U,j),span:{start:U,end:j},status:"limited",issues:[{code:K,message:"command structure exceeds parser limit"}],nodes:[]})}function no(G,U,j,K,re){return{nodes:G,issues:[...U,{code:K,message:`command structure exceeds parser limit ${re}`}],next:j,closed:!1,limited:!0,pendingHeredocs:[]}}function ts(G,U,j){return{nodes:G,issues:U,next:j,closed:!1,limited:!0,pendingHeredocs:[]}}function dl(G){return G.wordsUsed++,G.wordsUsed<=G.maxWords}function NC(G,U,j){let K=G.slice(U,j),re=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(K)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(K),oe=re?.[1];if(!re||!oe)return;return{name:oe,braceIndex:U+re[0].lastIndexOf("{")}}function Yo(G){return G.some((U)=>{if(U.kind==="command")return U.redirections.some((j)=>j.heredoc)||U.nested.some((j)=>Yo(j.nodes));return(U.kind==="group"||U.kind==="function")&&Yo(U.body.nodes)})}function LC(G){return G.map((U)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${U.delimiter} was not found`}))}function ju(G){return G?.kind==="command"||G?.kind==="group"||G?.kind==="function"}function Mu(G,U){let j=G.at(-1);if(j?.kind!=="connector"||!Du.has(j.operator))return;U.push({code:"missing-command-after-connector",message:`connector ${j.operator} requires a following command`})}function Vu(G){return G?.provenance==="literal"&&!G.quoted&&G.raw===G.text&&lC.has(G.text)}function ul(G,U){let j=G.at(-1);if(!ju(j))return;if(j?.kind==="command"&&Vu(j.words[0]))return;U.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function WC(G,U,j){return U===j||/[\s;&|()]/u.test(G[U-1]??"")}var qu=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),FC=new Set(["gc","cat","type","cp","mv","rm"]),Yu=["-rec","-for","-path","-literalpath","-whatif"],GC=/^\$env:\w/i,zC=/^(?:\$\{?\w+\}?|~)\\./;function Zu(G,U){let j=G.toLowerCase().replaceAll("`","");if(![...qu].some((re)=>j.includes(re))&&!(j.includes("rm")&&Yu.some((re)=>j.includes(re)))&&!j.includes("<#")&&!$C(j))return!1;let K=Cl(G,U);if(Xu(K))return!1;return K.issues.some((re)=>re.code==="unclosed-block-comment"||re.code==="comment-depth-limit")||bl(K).some(BC)}function Xu(G){return G.nodes.some((U)=>{if(U.kind==="group")return Xu(U.body);if(U.kind!=="command")return!1;return U.redirections.some((j)=>j.operator==="<<")})}function $C(G){if(G.includes("$env:"))return!0;return G.includes("\\")&&(G.includes("$")||G.includes("~"))}function BC(G){let U=G[0]==="&"||G[0]==="."?1:0,j=G[U]?.toLowerCase();if(j&&qu.has(j))return!0;let K=G.slice(U+1);if(j&&FC.has(j)&&K.some(UC))return!0;if(j!=="rm")return!1;return K.some((re)=>{let oe=re.toLowerCase().split(":",1)[0]??"";return Yu.some((de)=>oe.startsWith(de))})}function UC(G){return GC.test(G)||zC.test(G)}function Cl(G,U){let j={start:0,end:G.length};if(G.length>U.maxInputLength)return pn({kind:"program",dialect:"powershell",source:G,span:j,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${U.maxInputLength} UTF-16 code units`}],nodes:[]});let K=Sl(G,0,G.length,U,0);return pn({kind:"program",dialect:"powershell",source:G,span:j,status:qC(K.issues,K.limited),issues:K.issues,nodes:K.nodes})}function Sl(G,U,j,K,re,oe=!1){let de=[],Se=[],we=Xi(),We=0,mt=!1,gt=()=>{if(we.words.length===0&&we.redirections.length===0)return;let pt={start:we.start,end:we.end};Ji(de,we,{kind:"command",dialect:"powershell",source:G.slice(pt.start,pt.end),span:pt,words:we.words,redirections:we.redirections,nested:we.nested,displayText:we.words.map((ht)=>ht.text).join(" ")})},ft=U;while(ft<j){let pt=G[ft];if(!pt)break;if(oe&&pt==="}")return gt(),{nodes:de,issues:Se,next:ft+1,closed:!0,words:We,limited:mt};let ht=KC(G,ft,j,K.maxDepth);if(ht){if(ht.issue)Se.push(ht.issue);if(ht.limited)return gt(),{nodes:de,issues:Se,next:ht.next,closed:!1,words:We,limited:!0};ft=ht.next;continue}if(/\s/.test(pt)){if(pt==="\r"||pt===`
|
|
22
|
-
`){gt();let
|
|
23
|
-
`?ft+2:ft+1;de.push(hl(G,ft,
|
|
24
|
-
`)de++;return{next:de,limited:!1}}if(!G.startsWith("<#",U))return null;let re=1,oe=U+2;while(oe<j){if(G.startsWith("<#",oe)){if(re++,re>K)return{next:j,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${K}`},limited:!0};oe+=2;continue}if(G.startsWith("#>",oe)){if(re--,oe+=2,re===0)return{next:oe,limited:!1};continue}oe++}return{next:j,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function
|
|
25
|
-
`||G==="\r"||G==="\u2028"||G==="\u2029"}function Vt(G,U,j){if(U+j.length>Yt(G))return!1;for(let K=0;K<j.length;K++)if(
|
|
26
|
-
`||G===";"||G==="&"||G==="|"}function
|
|
27
|
-
`)U=!0,oe++;continue}let Se=
|
|
28
|
-
`||Se!==-1){if(U=!1,j=!1,K=!1,re=-1,Se!==-1)oe=Se-1;continue}if(de===";"||de==="&"||de==="|"||oe===Yt(G)){if(re>=0){let we=tm(G,re,oe);j||=we.recursive,K||=we.force}if(j&&K)return!0;U=!1,j=!1,K=!1,re=-1;continue}if(jt(de)){if(re<0)continue;if(Vt(G,re,"--")&&oe-re===2){U=!1,j=!1,K=!1,re=-1;continue}let we=tm(G,re,oe);if(j||=we.recursive,K||=we.force,j&&K)return!0;re=-1;continue}if(re<0)re=oe}return!1}function
|
|
29
|
-
`,Se++;if(we)j=!1,K=!1;U=!0,re=Se;continue}if(!U){re++;continue}if(Vt(G,re,"--")&&(re===0||jt(xt(G,re-1)))&&(!xt(G,re+2)||jt(xt(G,re+2))||on(xt(G,re+2)))){U=!1,j=!1,K=!1,re+=2;continue}if(j||=Vt(G,re,"--recursive")&&Jn(G,re+11)||Rl(G,re,"recursive"),K||=Vt(G,re,"--force")&&Jn(G,re+7)||Rl(G,re,"force"),j&&K)return!0;re++}return!1}function Rl(G,U,j){if(!Vt(G,U,"--"))return!1;let K=0;while(K<=j.length){let re=xt(G,U+K+2);if(!re||jt(re)||on(re))break;if(re!==j[K])return!1;K++}return K>0&&Jn(G,U+K+2)}function QC(G,U){let j=U,K=!1,re=!1;while(j<Yt(G)){while(jt(xt(G,j)))j++;let oe=j;while(j<Yt(G)&&!jt(xt(G,j)))j++;if(xt(G,oe)!=="-"||j-oe===2&&Vt(G,oe,"--"))return!1;let de=rm(G,oe,"recursive"),Se=rm(G,oe,"force");if(K&&Se||re&&de)return!0;if(K||=de,re||=Se,xt(G,oe+1)==="-")continue;let we=tS(G,oe,j);if(we.combined||K&&we.forceAtBoundary||re&&we.recursiveAtBoundary)return!0;K||=we.recursive,re||=we.force}return!1}function rm(G,U,j){return Vt(G,U,`--${j}`)&&Jn(G,U+j.length+2)||Rl(G,U,j)}function eS(G,U){if(U>0&&Ir(xt(G,U-1)))return-1;let j=U;if(xt(G,j)==="\\")j++;if(xt(G,j)!=="r")return-1;if(j++,xt(G,j)==="\\")j++;if(xt(G,j)!=="m"||!jt(xt(G,j+1)))return-1;return j+1}function tS(G,U,j){let K=!1,re=!1,oe=!1,de=!1,Se=!1;if(xt(G,U)!=="-")return{recursive:K,force:re,recursiveAtBoundary:oe,forceAtBoundary:de,combined:Se};let we="";for(let We=U+1;We<j;We++){let mt=xt(G,We)??"",gt=(mt==="r"||mt==="f")&&Jn(G,We+1);K||=mt==="r",re||=mt==="f",oe||=mt==="r"&>,de||=mt==="f"&>,Se||=(we==="r"&&mt==="f"||we==="f"&&mt==="r")&>,we=mt}return{recursive:K,force:re,recursiveAtBoundary:oe,forceAtBoundary:de,combined:Se}}function om(G,U,j){return Qo(G,"reset",oo,!0,(K)=>xt(G,K)==="-"&&io(G,K,U,j)?!0:K)}function nS(G){return Qo(G,"clean",oo,!0,(U)=>{if(xt(G,U)!=="-")return U;if(io(G,U,"--fo","rce"))return!0;let j=Jo(G,U,oo);for(let K=U+1;K<j;K++)if(xt(G,K)==="f")return!0;return j-1})}function ls(G,U,j){if(!Xn(G,U,"git"))return null;let K=U+3;if(!jt(xt(G,K)))return{commandEnd:-1,next:K};while(jt(xt(G,K)))K++;while(K<Yt(G)){if(on(xt(G,K)))return{commandEnd:-1,next:K};let re=Jo(G,K,on);if(Xn(G,K,j))return{commandEnd:K+j.length,next:re};if(xt(G,K)!=="-")return{commandEnd:-1,next:re};let oe=re-K===2&&Vt(G,K,"--"),de=rS(G,K,re);K=re;while(jt(xt(G,K)))K++;if(oe)return{commandEnd:Xn(G,K,j)?K+j.length:-1,next:Jo(G,K,on)};if(!de)continue;if(K>=Yt(G)||on(xt(G,K)))return{commandEnd:-1,next:K};K=Jo(G,K,on);while(jt(xt(G,K)))K++}return{commandEnd:-1,next:K}}function rS(G,U,j){for(let K of vn)if(j-U===K.length&&Vt(G,U,K))return!0;return!1}function oS(G){return im(G,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function iS(G){return Qo(G,"push",oo,!0,(U)=>{if(xt(G,U)!=="-")return U;if(xt(G,U+1)==="f"&&!Ir(xt(G,U+2))&&!Vt(G,U+2,"-with-lease"))return!0;let j=am(G,U,"--fo","rce");if(j>=0&&!Vt(G,j,"-with-lease"))return!0;return U})}function sS(G){return Qo(G,"push",on,!1,(U)=>{if(jt(xt(G,U))&&xt(G,U+1)==="+"&&U+2<Yt(G)&&!on(xt(G,U+2))&&!jt(xt(G,U+2)))return!0;if(xt(G,U)===":"&&xt(G,U+1)==="+")return!0;return U})}function aS(G){return Qo(G,"push",on,!1,(U)=>{if(xt(G,U)==="-"&&io(G,U,"--de","lete"))return!0;if(jt(xt(G,U))&&xt(G,U+1)===":"&&U+2<Yt(G)&&!jt(xt(G,U+2))&&!on(xt(G,U+2)))return!0;return U})}function lS(G){let U=!1,j=!1,K=!1;for(let re=0;re<=Yt(G);re++){if(re===Yt(G)||on(xt(G,re))){if(j&&K)return!0;U=!1,j=!1,K=!1;continue}if(!U){let Se=ls(G,re,"branch");if(Se){U=Se.commandEnd>=0,re=Math.max(re,(U?Se.commandEnd:Se.next)-1);continue}}if(!U||xt(G,re)!=="-")continue;let oe=Jo(G,re,on),de=cS(G,re,oe);if(j||=de.deletion,K||=de.force,j&&K)return!0;re=oe-1}return!1}function cS(G,U,j){let K=!1,re=!1;for(let oe=U;oe<j;oe++){if(xt(G,oe)!=="-")continue;if(io(G,oe,"--de","lete"))K=!0;if(io(G,oe,"--fo","rce"))re=!0;if(xt(G,oe+1)==="-")continue;let de=oe+1,Se=!1,we=!1,We=!1;while(de<j&&dS(xt(G,de))){let mt=xt(G,de);Se||=mt==="d"||mt==="D",we||=mt==="f",We||=mt==="D",de++}if(!Jn(G,de))continue;K||=Se,re||=we||We}return{deletion:K,force:re}}function dS(G){if(!G)return!1;let U=G.charCodeAt(0);return U>=65&&U<=90||U>=97&&U<=122}function uS(G){return im(G,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function im(G,U){let j=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let K=0;K<Yt(G);K++){let re=xt(G,K),oe=j[j.length-1];if(!oe)return!1;let de=oe.escaped;if(oe.escaped=!de&&oe.quote!=="'"&&re==="\\",!de&&re==="'"&&oe.quote!=='"')oe.quote=oe.quote==="'"?"":"'";if(!de&&re==='"'&&oe.quote!=="'")oe.quote=oe.quote==='"'?"":'"';if(re==="$"&&xt(G,K+1)==="("&&(j.length===1||!de&&oe.quote!=="'")){j.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),K++;continue}if(!de&&!oe.quote&&j.length>1&&re==="("){oe.depth++;continue}if(!de&&!oe.quote&&j.length>1&&re===")"){if(oe.depth--,oe.depth===0)j.pop();continue}if(jt(re))oe.shortActive=!1,oe.hasShortFlag=!1;if(!oe.outerActive){let Se=ls(G,K,U.command);if(Se){oe.outerActive=Se.commandEnd>=0&&jt(xt(G,Se.commandEnd)),oe.shortActive=!1,oe.hasShortFlag=!1,K=Math.max(K,(oe.outerActive?Se.commandEnd:Se.next)-1);continue}}if(oe.outerActive&&re==="-"){if(io(G,K,U.longPrefix,U.longOptional))return!0;oe.shortActive||=!U.excludedShortStarts.includes(xt(G,K+1)??"")}if(oe.hasShortFlag||=oe.shortActive&&re===U.shortFlag,oe.hasShortFlag&&Jn(G,K+1))return!0;if(oo(re))oe.outerActive=!1}return!1}function Qo(G,U,j,K,re){let oe=!1;for(let de=0;de<Yt(G);de++){let Se=xt(G,de),we=j(Se);if(!oe&&!we){let We=ls(G,de,U);if(We){oe=We.commandEnd>=0&&(!K||jt(xt(G,We.commandEnd))),de=Math.max(de,(oe?We.commandEnd:We.next)-1);continue}}if(oe){let We=re(de);if(We===!0)return!0;for(let mt=de;mt<=We;mt++)if(j(xt(G,mt)))oe=!1;de=We}if(we)oe=!1}return!1}function mS(G){let U=!1;for(let j=0;j<Yt(G);j++){if(El(xt(G,j))){if(U)return!0;U=!1;continue}if(!U){let K=ls(G,j,"restore");if(K){U=K.commandEnd>=0,j=Math.max(j,(U?K.commandEnd:K.next)-1);continue}}if(U&&xt(G,j)==="-"&&xt(G,j+1)==="-"&&(Vt(G,j+2,"staged")||Vt(G,j+2,"help")))U=!1}return U}function sm(G,U){let j=!1;for(let K=0;K<Yt(G);K++){let re=xt(G,K),oe=U?El(re):on(re);if(j&&jt(re)&&xt(G,K+1)==="-"&&Xn(G,K+2,"delete"))return!0;if(oe){j=!1;continue}if(Xn(G,K,"find"))j=!0,K+=3}return!1}function Jo(G,U,j){let K=U;while(K<Yt(G)&&!jt(xt(G,K))&&!j(xt(G,K)))K++;return K}function am(G,U,j,K){if(!Vt(G,U,j))return-1;let re=U+j.length;for(let oe=0;oe<K.length&&xt(G,re)===K[oe];oe++)re++;return Jn(G,re)?re:-1}function io(G,U,j,K){return am(G,U,j,K)>=0}function kn(G,U){Xo(U,G,2);let j=G.toLowerCase(),K=j.trimStart(),re=K.startsWith("echo ")||K.startsWith("rg "),oe=[{scan:"rm",label:"rm -rf"},{scan:"reset-hard",label:"git reset --hard"},{scan:"reset-merge",label:"git reset --merge"},{scan:"clean",label:"git clean -f"},{scan:"checkout",label:"git checkout --force"},{scan:"push-force",label:"git push --force"},{scan:"push-refspec",label:"git push --force"},{scan:"push-delete",label:"git push delete"},{scan:"branch",label:"git branch -D",caseSensitive:!0},{scan:"tag",label:"git tag -d"},{regex:/\bgit\s+stash\s+(drop|clear)\b/,label:"git stash drop/clear"},{regex:/\bgit\s+checkout\s+--\s/,label:"git checkout --"},{scan:"restore",label:"git restore without --staged"},{scan:"find",label:"find -delete",skipForEchoRg:!0},{regex:/\bdd\b[^\n|;&]*\bof=\/dev\/\S/,label:"dd of=/dev/",skipForEchoRg:!0},{regex:/\bmkfs(?:\.[a-z0-9_-]+)?\s+\/dev\/\S/,label:"mkfs /dev/",skipForEchoRg:!0},{regex:/\bshred\b\s+\S/,label:"shred",skipForEchoRg:!0},{regex:/\b(?:curl|wget|fetch|aria2c|https?|xhs?|ncat|netcat|nc)\b(?:[^\n|;&]|\\\n)*\|(?:\s|\\\n)*(?:(?:sudo|env|command|builtin)(?:\s+(?:-\S+|\w+=\S*))*\s+)?(?:[^\s|;&]*\/)?(?:ba|da|z|k)?sh(?![^\s;&|])/,label:"download piped to shell",skipForEchoRg:!0}];for(let de of oe){if(de.skipForEchoRg&&re)continue;let Se=de.caseSensitive?G:j;if(de.regex)xn(U,Se);if((de.regex?.test(Se)??!1)||de.scan&&as(Se,de.scan,U))return Rt("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${de.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var fS=/^[A-Za-z_][A-Za-z0-9_]*=/;function cm(G,U,j){let K=G.words[0];if(!U||!K||G.words.length!==1||G.dialect!=="posix")return!1;if(!K.quoted||K.provenance!=="literal")return!1;let re=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(K.text)?.[1];if(!re)return!1;Xo(j,U.source,2);let oe={anchored:new RegExp(`^\\$\\{?${re}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${re}(?![A-Za-z0-9_])`)};return dm(U.nodes,K,oe)}function dm(G,U,j){return G.every((K)=>{if(K.kind==="connector")return!0;if(K.kind==="group"||K.kind==="function")return dm(K.body.nodes,U,j);if(K.kind==="unknown")return!j.loose.test(K.source);return pS(K,U,j)})}function pS(G,U,j){if(G.nested.some((re)=>j.loose.test(re.source)))return!1;let K=G.words.findIndex((re)=>!fS.test(re.text));return G.words.every((re,oe)=>re===U||lm(re.raw,j.anchored,oe!==K))&&G.redirections.every((re)=>(!re.heredoc||re.heredoc.quotedDelimiter||!j.loose.test(re.heredoc.body))&&(!re.target||lm(re.target.raw,j.anchored,!0)))}function lm(G,U,j){let K=!1,re=!1;for(let oe=0;oe<G.length;oe++){let de=G[oe];if(de==="\\"&&!K){oe++;continue}if(!re&&de==="'"){K=!K;continue}if(!K&&de==='"'){re=!re;continue}if(K||de!=="$")continue;if(!U.test(G.slice(oe)))continue;if(!re||!j)return!1}return!0}var gS="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",hS="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",yS="This erases or repartitions a disk. Run disk erase and partition commands manually after confirming the target.",bS="This output redirect overwrites a disk device. Run device writes manually after confirming the target.",CS="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.",SS=new Set(["of=/dev/null","of=/dev/zero","of=/dev/full"]),um=/^(?:mkfs(?:\..+)?|mke2fs|newfs(?:_.+)?)$/,vS=new Set(["diskutil","wipefs","sgdisk","parted"]),ES=new Set(["erasedisk","erasevolume","reformat","partitiondisk","zerodisk","randomdisk","secureerase"]),RS=/^(?:-[^-]*[ao]|--all$|--offset(?:=|$))/,xS=new Set(["-p","--print","-i","--info","-v","--verify","-O","--print-mbr","-E","--end-of-largest","-F","--first-in-largest","-f","--first-aligned-in-largest","-D","--display-alignment","-L","--list-types","-P","--pretend","-b","--backup","-V","--version","-?","--help","--usage"]),_S=new Set(["p","v","O","E","F","f","D","L","P","V","?"]),wS=new Set(["i","b"]),AS=/^\/dev\/(?:r?disk\d|sd[a-z]|hd[a-z]|vd[a-z]|xvd[a-z]|nvme\d|mmcblk\d|md\d|dm-\d|loop\d|mapper\/|disk\/)/,PS=new Set([">",">|",">>","<>",">&"]),TS=new Set(["mklabel","mktable","mkpart","rm","resizepart"]);function mm(G){return G==="dd"||G==="shred"||um.test(G)||vS.has(G)}function IS(G,U){let j=U.some((K)=>K.startsWith("/dev/"));if(G==="diskutil"){let K=U.find((re)=>!re.startsWith("-"));return K!==void 0&&ES.has(K.toLowerCase())}if(G==="wipefs")return j&&U.some((K)=>RS.test(K));if(G==="sgdisk")return j&&U.some((K)=>K.startsWith("-")&&!kS(K));return G==="parted"&&j&&U.some((K)=>TS.has(K.toLowerCase()))}function kS(G){if(xS.has(G.split("=",1)[0]??G))return!0;if(G.startsWith("--"))return!1;let U=G.slice(1).split("");return wS.has(U[0]??"")||U.every((j)=>_S.has(j))}function fm(G,U){let j=U.slice(1);if(G==="dd"&&j.some((K)=>/^of=\/dev\/.+/.test(K)&&!SS.has(K)))return Rt("dd.device-write",gS);if(um.test(G)&&j.some((K)=>K.startsWith("/dev/")))return Rt("mkfs.device",hS);if(IS(G,j))return Rt("disk.erase",yS);if(G==="shred"&&j.length>0)return Rt("shred.target",CS);return null}function pm(G){return G.some((U)=>PS.has(U.operator)&&U.target?.provenance==="literal"&&AS.test(U.target.text))?Rt("redirect.block-device",bS):null}import{isAbsolute as OS,resolve as gm}from"node:path";function ei(G,U,j,K){let re=OS(G)?gm(G):U?gm(U,G):void 0;if(!re)return;try{return Nt(re,j,K)}catch{return re}}function hm(G){return!["/dev","/proc","/sys"].some((U)=>G===U||G.startsWith(`${U}/`))}var so="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",ti="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.",_l=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),MS=new Set(["-p","--print"]),DS=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),NS=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"])]]),LS=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),WS=new Map([["python",new Set(["m"])]]),FS=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"])]]),GS=new Set(["always","default","never"]),zS=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),$S=/\\\r?\n/g,BS=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 ym(G){return ds(G).code}function cs(G){return ds(G).sources}function bm(G){return BS.get(Al(G))??[]}function ds(G){let U=Al(G[0]??"");if(!_l.has(U))return{code:null,sources:[],optionsOpen:!1};let j=[],K=[],re=!0;for(let oe=1;oe<G.length;oe++){let de=G[oe];if(de===void 0)break;if(de==="--")return Wn(U,j,K,re,G[oe+1]===void 0?void 0:oe+1,G[oe+1]);if(de===""||de==="-"||!de.startsWith("-"))return Wn(U,j,K,re,oe,de);if(U==="node"&&MS.has(de)){let gt=G[oe+1];if(gt===void 0)return Wn(U,j,K,re);if(gt.startsWith("-"))continue;j.push({tokenIndex:oe+1,value:gt}),K.push({tokenIndex:oe+1,kind:"inline-code",value:gt}),oe++;continue}if(HS(U,de)){let gt=G[oe+1];if(gt===void 0)return Wn(U,j,K,re);if(j.push({tokenIndex:oe+1,value:gt}),K.push({tokenIndex:oe+1,kind:"inline-code",value:gt}),U==="python")return Wn(U,j,K,re);oe++;continue}let Se=/^--eval=(.*)$/s.exec(de);if(jS(U)&&Se){let gt=Se[1]??"";j.push({tokenIndex:oe,value:gt}),K.push({tokenIndex:oe,kind:"inline-code",value:gt});continue}if(U==="node"){let gt=US(de);if(gt){if(gt.attached){if(re&&=gt.value!=="",gt.value!=="")K.push({tokenIndex:oe,kind:"module-file",value:gt.value});continue}let ft=G[oe+1];if(ft===void 0||ft.startsWith("-"))return re=!1,Wn(U,j,K,re);K.push({tokenIndex:oe+1,kind:"module-file",value:ft}),oe++;continue}}if(U==="python"&&de.startsWith("--check-hash-based-pycs=")||U==="node"&&(de==="--conditions="||de==="--diagnostic-dir="||de==="--title=")||U==="ruby"&&(de==="--disable="||de==="--enable="))return Wn(U,j,K,re);if(FS.get(U)?.has(de)){let gt=G[oe+1];if(gt===void 0||gt.startsWith("-")&&!(U==="ruby"&&zS.has(de))||U==="python"&&!GS.has(gt))return Wn(U,j,K,re);oe++;continue}if(de.startsWith("--"))continue;let we,We=!1;for(let gt=1;gt<de.length;gt++){let ft=de[gt];if(ft===void 0)break;if(WS.get(U)?.has(ft)){let pt=de.slice(gt+1),ht=pt||G[oe+1];if(ht!==void 0)K.push({tokenIndex:pt?oe:oe+1,kind:"module-file",value:ht});return Wn(U,j,K,re)}if(DS.get(U)?.has(ft)){we=de.slice(gt+1)||G[oe+1],We=gt+1===de.length;break}if(U==="node"&&ft==="r"){if(re&&=de==="-r",de==="-r"){let pt=G[oe+1];if(re&&=pt!==void 0&&!pt.startsWith("-"),re&&pt!==void 0)K.push({tokenIndex:oe+1,kind:"module-file",value:pt});oe++}break}if(U==="ruby"&&ft==="r"){let pt=de.slice(gt+1),ht=pt||G[oe+1];if(re&&=ht!==void 0,ht!==void 0)K.push({tokenIndex:pt?oe:oe+1,kind:"module-file",value:ht});if(!pt)oe++;break}if(U==="perl"&&(ft==="M"||ft==="m")){let pt=de.slice(gt+1);if(!pt){if(re=!1,gt+1===de.length)oe++;break}K.push({tokenIndex:oe,kind:"module-file",value:pt});break}if(NS.get(U)?.has(ft)){if(gt+1===de.length)oe++;break}if(LS.get(U)?.has(ft)&>+1<de.length)break}if(we===void 0)continue;let mt=We?oe+1:oe;if(j.push({tokenIndex:mt,value:we}),K.push({tokenIndex:mt,kind:"inline-code",value:we}),U==="python")return Wn(U,j,K,re);if(We)oe++}return Wn(U,j,K,re,void 0,void 0,!0)}function Wn(G,U,j,K,re,oe,de=!1){let Se=G==="node"?U.slice(-1):U,we=new Set(Se.map((mt)=>mt.tokenIndex)),We=j.filter((mt)=>mt.kind!=="inline-code"||we.has(mt.tokenIndex));if(K&&U.length===0&&re!==void 0&&oe!==void 0)We.push({tokenIndex:re,kind:"main-script",value:oe});return{code:(G==="node"?Se[0]?.value:Se.map((mt)=>mt.value).join(`
|
|
30
|
-
`))||null,sources:K?We:[],optionsOpen:K&&de}}function US(G){for(let U of["--import","--loader","--experimental-loader","--require"]){if(G===U)return{attached:!1,value:""};if(G.startsWith(`${U}=`))return{attached:!0,value:G.slice(U.length+1)}}return}function wl(G,U){return Al(G)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(U)}function Al(G){let U=kt(G).toLowerCase();return Wi.test(U)?"python":U}function HS(G,U){return _l.get(G)?.has(U)??!1}function jS(G){return _l.get(G)?.has("--eval")??!1}function ni(G,U,j=!1){let K=qS(G,U);if(!xl(K,U))return!1;xn(U,K);let re=KS(K);if(xl(re,U))return!0;if(xn(U,re),!Cm.test(re))return!1;return!j||VS(K,U)}function VS(G,U){if(/`|%x|\bqx\b/.test(G))return!0;let K=G.split(""),re=[];for(let we=0;we<G.length;we++){let We=G[we];if(We!=="'"&&We!=='"')continue;let mt=G.startsWith(We.repeat(3),we)?We.repeat(3):We,gt=we+mt.length,ft=gt;while(ft<G.length&&!G.startsWith(mt,ft))ft+=G[ft]==="\\"?2:1;if(ft>=G.length)return!0;re.push({start:gt,text:G.slice(gt,ft)}),K.fill(" ",we,ft+mt.length),we=ft+mt.length-1}let oe=K.join(""),de=Array.from(oe.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((we)=>Cm.test(we[1]??"")).map((we)=>{let We=we.index+we[0].length;return{start:We,end:us(oe,We)}});if(de.some((we)=>Pl(oe,we.start)))return!0;return re.some((we)=>{let We=/\b(?:system|exec|spawn|popen)\s*$/.test(oe.slice(0,we.start)),mt=de.some((gt)=>we.start>=gt.start&&we.start<gt.end);return(We||mt)&&xl(we.text,U)})}function us(G,U){let j=1;for(let K=U;K<G.length;K++){if(G[K]==="(")j++;if(G[K]===")")j--;if(j===0)return K}return G.length}function Pl(G,U){let j=0;for(let K=U;K<G.length;K++){let re=G[K]??"";if("([{".includes(re))j++;if(")]}".includes(re)&&j--===0)return!1;if(re===","&&j===0)return!1;if(/[A-Za-z_$]/.test(re))return!0}return!1}var Cm=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function KS(G){let U=[],j=0,K=0;while(K<G.length){let re=G[K];if(re!=="'"&&re!=='"'){K++;continue}let oe=G.startsWith(re.repeat(3),K)?re.repeat(3):re,de=K+oe.length;while(de<G.length&&!G.startsWith(oe,de))de+=G[de]==="\\"?2:1;if(de>=G.length)break;U.push(G.slice(j,K)," "),K=de+oe.length,j=K}return U.push(G.slice(j)),U.join("")}function xl(G,U){if(ss(G,"rm",U))return!0;for(let K of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(xn(U,G),K.test(G))return!0;if(ss(G,"dd",U))return!0;for(let K of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(xn(U,G),K.test(G))return!0;if(ss(G,"find",U))return!0;let j=G.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((K)=>(xn(U,G),j.some((re)=>as(re,K))))}function qS(G,U){return xn(U,G),G.replace($S,"")}import{lstatSync as Hv,readdirSync as jv}from"node:fs";import{basename as Vv,isAbsolute as Vm,join as Kv,relative as Km}from"node:path";import{isAbsolute as wm,parse as ov}from"node:path";import{dirname as YS,isAbsolute as ZS,parse as XS,sep as JS}from"node:path";function dr(G,U,j){if(sr(U))throw Error("Unsupported Windows namespace path");let K=ZS(U)?XS(U).root:"",re=K||G;for(let oe of ev(K?U.slice(K.length):U)){if(oe===""||oe===".")continue;if(oe===".."){re=YS(re);continue}let de=QS(re,oe),Se=j.entryKind(de),we=Se==="symlink"?j.realpath(de):de;if(Se==="missing"||we===null)throw Error(`Cannot resolve path component: ${de}`);re=we}return re}function QS(G,U){return G.endsWith("/")||G.endsWith("\\")?`${G}${U}`:`${G}${JS}${U}`}function ev(G){let U=process.platform==="win32"?/[\\/]+/:/\/+/;return G.split(U)}var Tl=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],tv=new Set(Tl),nv=1024,Sm=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),vm=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),rv=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ms(G){return tv.has(G)}function Il(G){return ms(G)||Sm.has(G)||vm.has(G)||No(G)}function Qn(G,U,j){return j?.has(G)?j.get(G):U.get(G)}function Em(G,U){let j=Qn("GIT_CONFIG_COUNT",G,U);if(j===void 0)return{state:"absent"};if(j==="")return{state:"valid",count:0};if(!/^\d+$/.test(j))return{state:"invalid"};let K=Number(j);return Number.isSafeInteger(K)&&K<=nv?{state:"valid",count:K}:{state:"invalid"}}function fs(G,U,j){let re=G.match(rv)?.[1];if(!re||!Il(re))return null;let oe=G.indexOf("=");return{name:re,value:`${Qn(re,U,j)??""}${G.slice(oe+1)}`}}function Rm(G){return _m(G,vm)}function xm(G){return _m(G,Sm)}function _m(G,U){if(!G)return!1;for(let j of G.keys())if(U.has(j))return!0;return!1}var Pm=/^[A-Za-z_][A-Za-z0-9_]*=/;function On(G){if(!Pm.test(G))return null;let U=G.indexOf("=");return{name:G.slice(0,U),value:G.slice(U+1)}}function ve(G){let U=new Map,j=0;while(j<G.length){let K=G[j];if(!K)break;let re=On(t(K));if(!re)break;U.set(re.name,re.value),j++}return{words:G.slice(j),envAssignments:U}}function Tm(G){let U=Mt(G);return G.includes("=")||U==="sudo"||U==="env"||U==="command"||U==="builtin"}function kr(G,U,j,K){if(!Tm(ao(G)))return{words:G,envAssignments:new Map,cwd:j,rewritten:!1};let re=new Set(G),oe=G,de=new Map,Se=new Map(K??[]),we=[],We=j;for(let gt=0;gt<a.wrapperPeelIterations.cap;gt++){let ft=Am(oe),pt=ve(oe);for(let[yt,bt]of pt.envAssignments)de.set(yt,bt),Se.set(yt,bt);if(oe=pt.words,oe.length===0)break;while(oe.length>0&&ao(oe).includes("=")&&!sv(oe)){let yt=av(ao(oe),Se,U.env)??fs(ao(oe),U.env,Se);if(yt)de.set(yt.name,yt.value),Se.set(yt.name,yt.value);oe=oe.slice(1)}if(oe.length===0)break;let ht=Mt(ao(oe));if(ht!=="sudo"&&ht!=="env"&&ht!=="command"&&ht!=="builtin")break;if(ht==="sudo"){let yt=cv(oe,U.paths,We);if(oe=yt.words,yt.cwd!==void 0)We=yt.cwd}if(ht==="env"){let yt=mv(oe,We,Se,U);if(we.push(...yt.envSplitValues??[]),oe=yt.words,yt.cwd!==void 0)We=yt.cwd;for(let[bt,Ct]of yt.envAssignments)de.set(bt,Ct),Se.set(bt,Ct)}if(ht==="command")oe=fv(oe);if(ht==="builtin")oe=oe.slice(Fn(oe,1)==="--"?2:1);if(Am(oe)===ft)break}let mt=ve(oe);for(let[gt,ft]of mt.envAssignments)de.set(gt,ft),Se.set(gt,ft);return{words:mt.words,envAssignments:de,cwd:We,envSplitValues:we.length>0?we:void 0,rewritten:iv(mt.words,re)}}function iv(G,U){return G.some((j)=>!U.has(j))}function Am(G){return G.map(t).join(" ")}function ao(G){let U=G[0];return U?t(U):""}function Fn(G,U){let j=G[U];return j?t(j):void 0}function sv(G){return Pm.test(ao(G))}function av(G,U,j){if(!G.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${U.get("TMPDIR")??j.get("TMPDIR")??""}${G.slice(8)}`}}var lv=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function cv(G,U,j){let K=1,re=j;while(K<G.length){let oe=Fn(G,K);if(!oe)break;if(oe==="--")return{words:G.slice(K+1),cwd:re};if(!oe.startsWith("-"))break;if(oe==="-D"||oe==="--chdir"){let de=Fn(G,K+1);re=de?ri(re,de,U):null,K+=2;continue}if(oe.startsWith("--chdir=")){re=ri(re,oe.slice(8),U),K++;continue}if(oe.startsWith("-D")&&oe.length>2){re=ri(re,oe.slice(2),U),K++;continue}if(oe==="-i"||oe==="--login"){re=null,K++;continue}if(lv.has(oe)){K+=2;continue}K++}return{words:G.slice(K),cwd:re}}var dv=new Set(["-i","-0","--null"]),uv=new Set(["-u","--unset","-C","--chdir","-P"]);function mv(G,U,j,K){let re=new Map,oe=[],de=U,Se=1,we=(We)=>({words:G.slice(We),envAssignments:re,cwd:de,envSplitValues:oe.length>0?oe:void 0});while(Se<G.length){let We=Fn(G,Se);if(!We)break;if(We==="--")return we(Se+1);if(We==="-i"||We==="--ignore-environment"||We==="-"){re.clear();for(let gt of j.keys())re.set(gt,"");re.set("TMPDIR",""),Se++;continue}if(dv.has(We)){Se++;continue}if(We==="-u"||We==="--unset"){let gt=Fn(G,Se+1);if(gt!==void 0)re.set(gt,"");Se+=2;continue}if(We.startsWith("-u")&&We.length>2&&!We.startsWith("-u=")){re.set(We.slice(2),""),Se++;continue}if(We.startsWith("--unset=")){re.set(We.slice(8),""),Se++;continue}let mt=We==="-S"||We==="--split-string"?{value:Fn(G,Se+1),consumed:2}:We.startsWith("-S")&&We.length>2?{value:We.slice(2),consumed:1}:We.startsWith("--split-string=")?{value:We.slice(15),consumed:1}:null;if(mt){if(mt.value!==void 0)oe.push(mt.value);return de=null,we(Se+mt.consumed)}if(uv.has(We)){if(We==="-C"||We==="--chdir"){let gt=Fn(G,Se+1);de=gt?ri(de,gt,K.paths):null}Se+=2;continue}if(We.startsWith("-u=")){Se++;continue}if(We.startsWith("-C")&&We.length>2||We.startsWith("--chdir=")){let gt=We.startsWith("--chdir=")?We.slice(8):We.startsWith("-C=")?We.slice(3):We.slice(2);de=ri(de,gt,K.paths),Se++;continue}if(We.startsWith("-P")){Se++;continue}if(We.startsWith("-")){Se++;continue}if(!On(We))break;while(Se<G.length){let gt=On(Fn(G,Se)??"");if(!gt)break;re.set(gt.name,gt.value),Se++}if(Fn(G,Se)==="--")Se++;return we(Se)}return we(Se)}function ri(G,U,j){if(U==="")return null;if(!G&&!wm(U))return null;let K=wm(U)?ov(U).root:j.realpath(G??"/");if(K===null)return null;try{return dr(K,U,j)}catch{return null}}function fv(G){if(Fn(G,1)==="-v")return[...Kt(["type"]),...G.slice(2)];let U=1;while(U<G.length){let j=Fn(G,U);if(!j)break;if(j==="-p"||j==="-v"||j==="-V"){U++;continue}if(j==="--")return G.slice(U+1);if(j.startsWith("-")&&!j.startsWith("--")&&j.length>1){if(!/^[pvV]+$/.test(j.slice(1)))break;U++;continue}break}return G.slice(U)}var pv=/['"\\$`{}#]/;function ps(G,U){if(G.some((K)=>pv.test(K)))return null;let j=[...G.flatMap((K)=>K.split(/\s+/).filter((re)=>re.length>0)),...U];return j.length<=64?j:null}function ur(G,U,j){return gs(G,U,j).tokens}function gv(G){let U=[],j="",K=0;while(K<G.length){let re=G.charAt(K);if(re==='"'||re==="'"){let oe=G.indexOf(re,K+1);if(oe===-1)return G.split(/\s+/).map((de)=>de.replace(/["']/g,"")).filter((de)=>de.length>0);j+=G.slice(K+1,oe),K=oe+1;continue}if(/\s/.test(re)){if(j.length>0)U.push(j);j="",K++;continue}j+=re,K++}if(j.length>0)U.push(j);return U}function mr(G,U,j,K=0){let re=gs(G,U,j),oe=(re.envSplitValues??[]).flatMap(gv);if(oe.length===0)return re.tokens;let de=[...oe,...re.tokens];if(K>=8)return de;return mr(de,U,j,K+1)}function gs(G,U,j,K){if(!Tm(G[0]??""))return{tokens:[...G],envAssignments:new Map,cwd:j};let re=kr(Kt(G),U,j,K);return{tokens:re.words.map(t),envAssignments:re.envAssignments,cwd:re.cwd,envSplitValues:re.envSplitValues}}var Ml=Symbol("adopt-as-operand"),hv=new Set(["env","sudo","command","builtin"]),yv=new Set(["&&","||","|&","|","&",";"]),bv=new Set(["<<","<<<",">|"]),Im=new Set(["|","|&"]),Cv=/[*@#?$!_-]/,Sv=/^\w+(?::\w+)*/,vv=Object.freeze([]),oi=Object.freeze({kind:"scope",edge:"enter"}),ii=Object.freeze({kind:"scope",edge:"exit"}),Ev=Object.freeze([]),Rv=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),si=new Set(["bash","sh","zsh","dash","ksh"]),xv=256,Nm=new WeakMap;function Lm(G,U){let j=U.status==="complete"?new Set(Ol(U)):new Set,K=Av(G,j);if(Gi(K))return hs("unclosed-quote",K,U);let re={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},oe=Or(U,{source:K,suppressed:j,flags:re,depth:0,functions:new Map,powershell:U.dialect==="powershell"});if(re.limited)return hs("structural-limit",K,U);if(re.invalid)return hs("invalid",K,U);let de=hs("complete",K,U,re.assignmentFallbacks);return Nm.set(de,Object.freeze(oe)),de}function Cs(G,U,j,K,re){let oe=re.word??((ht)=>ht),de={cwd:U,variables:new Map,previous:null},Se=[],we=new Set,We=null,mt=[],gt=Wm(G),ft=gt.findLastIndex((ht)=>ht.kind==="operator"&&Im.has(ht.operator)),pt=ft!==-1&>.some((ht)=>ht.kind==="redirection"&&ht.operator==="<<"&&ht.body===void 0);for(let[ht,yt]of gt.entries()){let bt=pt||ht<=ft;if(yt.kind==="scope"){if(yt.edge==="enter"){mt.push({state:de,segment:[...Se],shellWords:new Set(we),pipeProducer:We});continue}let Ct=re.segment(Se,de,We,null,we,bt);if(Ct)return Ct;let vt=mt.pop();if(vt===void 0)throw Error("scope exit without a matching enter");de=vt.state,Se=vt.segment,we=vt.shellWords,We=vt.pipeProducer;continue}if(yt.kind==="operator"){if(!yt.boundary)continue;let Ct=re.segment(Se,de,We,yt.operator,we,bt);if(Ct)return Ct;de=_v(Se,de,j,K),We=Se.length>0&&Im.has(yt.operator)?Se:null,Se=[],we=new Set;continue}if(yt.kind==="redirection"){if(yt.fd!==void 0)we.add(Se.length-1);if(yt.target===void 0)continue;let Ct=re.redirection({operator:yt.operator,role:yt.role,targetOrder:yt.targetOrder,target:yt.target,...yt.body===void 0?{}:{body:yt.body,consumer:yt.consumer}},de,bt);if(Ct===Ml){we.add(Se.length),Se.push(oe(yt.target));continue}if(Ct)return Ct;continue}Se.push(oe(yt.text))}return re.segment(Se,de,We,null,we,pt)}function Ss(G){return Wm(G).flatMap((U)=>{if(U.kind==="word")return[{kind:"word",text:U.text}];if(U.kind==="operator")return[{kind:"operator",boundary:U.boundary}];if(U.kind==="redirection")return[{kind:"redirection",target:U.target}];return[]})}function gn(G,U){return G.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(j,K,re,oe)=>{let de=U.get(K);if(de===void 0)return j;let Se=re.startsWith(":")?de!=="":!0;if(re.endsWith("-"))return Se?de:gn(oe,U);return Se?gn(oe,U):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(j,K)=>U.get(K)??j).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(j,K)=>U.get(K)??j)}function ai(G){return G.length>0&&G.every((U)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(U))}function _v(G,U,j,K){let re=ai(G)?new Map([...U.variables,...wv(G,U.variables)]):U.variables,oe=ur([...G],j),de=kt(oe[0]??"").toLowerCase()==="cd"?oe[1]:void 0;if(!de)return{...U,variables:re};if(de==="-"){if(U.previous===null)return{...U,variables:re};return{cwd:U.previous,variables:re,previous:U.cwd}}return{cwd:dn(gn(de,re),U.cwd,j,K),variables:re,previous:U.cwd}}function wv(G,U){return G.flatMap((j)=>{let K=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(j),re=K?.[2]?.startsWith("=")?K[2].slice(1):void 0;return K?.[1]!==void 0&&re!==void 0?[[K[1],gn(re,U)]]:[]})}function Wm(G){return Nm.get(G)??vv}function Av(G,U){return[...U].reduce((j,K)=>j.slice(0,K.start)+" ".repeat(K.end-K.start)+j.slice(K.end),G)}function hs(G,U,j,K=Ev){return Object.freeze({status:G,source:U,program:j,assignmentFallbacks:Object.freeze(K)})}function Or(G,U){return G.nodes.flatMap((j,K)=>Pv(j,G,K,U)).sort((j,K)=>j.start-K.start).flatMap((j)=>[...j.events])}function Pv(G,U,j,K){if(G.kind==="connector")return[{start:G.span.start,events:[Gn(Mv(G.operator))]}];if(G.kind==="unknown")return[{start:G.span.start,events:[Gn(G.source)]}];if(G.kind==="function")return K.functions.set(G.name,G.body),[];if(G.kind==="group"){let oe=G.style!=="subshell",de=K.source[G.span.end-1]===(oe?"}":")"),Se=oe?K:{...K,functions:new Map(K.functions)};return[{start:G.span.start,events:oe?[ys("{"),...Or(G.body,Se),...de?[ys("}")]:[]]:[oi,Gn("("),...Or(G.body,Se),...de?[Gn(")")]:[],ii]}]}let re=Wv(G,K.functions);if(re){if(K.depth>=cr.maxDepth||++K.flags.expansions>xv)return K.flags.limited=!0,[];return[{start:G.span.start,events:[...km(G,K),ys(";"),...Or(re,{...K,depth:K.depth+1}),ys(";")]},...Om(G,U,j,K)]}return[{start:G.span.start,events:km(G,K)},...Om(G,U,j,K)]}function km(G,U){return[...G.words.map((j)=>({start:j.span.start,events:Gm(j,G,U,!1)})),...G.redirections.map((j)=>({start:j.span.start,events:Tv(j,G,U)}))].sort((j,K)=>j.start-K.start).flatMap((j)=>j.events)}function Tv(G,U,j){let K=G.operator==="<<-"?"<<":G.operator,re=G.target?Gm(G.target,U,j,!0):[],oe=re[0],de=oe?.kind==="word"?oe.text:void 0;return[...G.fd===void 0?[]:[Dl(String(G.fd))],Object.freeze({kind:"redirection",operator:K,...G.fd===void 0?{}:{fd:G.fd},role:Dv(K),targetOrder:bv.has(K)?"legacy-segment":"immediate",...de===void 0?{}:{target:de},...G.heredoc&&j.suppressed.has(G.heredoc.bodySpan)?{body:G.heredoc.body,consumer:$m(U)}:{}}),...de===void 0?re:re.slice(1)]}function Om(G,U,j,K){let re=G.redirections.filter((oe)=>oe.operator==="<<"||oe.operator==="<<-");return[...re.flatMap((oe)=>{let de=oe.heredoc;if(!de)return[];let Se=[Dl(de.delimiter),.../[\r\n]/.test(K.source[de.terminatorSpan.end]??"")?[Gn(";")]:[]];if(K.suppressed.has(de.bodySpan))return[{start:de.bodySpan.start,events:Se}];return[{start:de.bodySpan.start,events:[...Fm(K.source.slice(de.bodySpan.start,de.bodySpan.end),K),...Se]}]}),...re.some((oe)=>!oe.heredoc&&oe.target)?Iv(U,j,K):[]]}function Iv(G,U,j){let K=G.nodes.slice(U+1).find((re)=>re.kind==="connector");if(!K||K.span.end>=G.span.end)return[];return[{start:K.span.end,events:Fm(j.source.slice(K.span.end,G.span.end),j)}]}function Fm(G,U){if(U.depth>=cr.maxDepth)return U.flags.limited=!0,[];let j=y(G,"posix");if(j.status==="limited")return U.flags.limited=!0,[];let K={invalid:!1,limited:!1,expansions:U.flags.expansions,assignmentFallbacks:U.flags.assignmentFallbacks},re=Or(j,{source:G,suppressed:new Set,flags:K,depth:U.depth+1,functions:new Map,powershell:!1});return U.flags.limited||=K.limited,U.flags.expansions=K.expansions,re}function Gm(G,U,j,K){let re=[],oe={single:!1,double:!1},de="",Se=!1,we=()=>{let We=Se&&!K?Gn("glob"):de!==""||G.quoted&&re.length===0?Dl(de):void 0;if(We)re.push(We);de="",Se=!1};for(let We of G.parts){if(We.provenance!=="command-substitution"&&We.provenance!=="arithmetic"){for(let pt of kl(We.raw,oe,j.flags,j.powershell)){if(typeof pt==="string"){we(),re.push(Gn(pt));continue}de+=pt.text,Se||=pt.glob}continue}let mt=U.nested.find((pt)=>pt.span.start>=We.span.start&&pt.span.end<=We.span.end);if(oe.double){let pt=j.source.slice(We.span.start,We.span.end);de+=kl(pt,{single:!1,double:!0},j.flags,j.powershell).map((yt)=>typeof yt==="string"?yt:yt.text).join("");let ht=mt?Or(mt,j).filter((yt)=>yt.kind==="redirection"&&yt.body!==void 0):[];if(ht.length>0)re.push(oi,...ht,ii);continue}let gt=mt?Or(mt,j):[];if(We.raw.startsWith("`")){de+="${}",we(),re.push(oi,...gt,ii);continue}if(We.raw.startsWith("<(")||We.raw.startsWith(">(")){we(),re.push(We.raw.startsWith("<(")?Gn("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),oi,...gt,...We.raw.endsWith(")")?[Gn(")")]:[],ii);continue}let ft=We.raw.startsWith("$((")?2:1;de+="${}",we(),re.push(...Array.from({length:ft},()=>Gn("(")),...ft===1?[oi]:[],...gt,...We.raw.endsWith(")".repeat(ft))?Array.from({length:ft},()=>Gn(")")):[],...ft===1?[ii]:[])}return we(),re}function kl(G,U,j,K){let re=[],oe="",de=!1,Se=0;while(Se<G.length){let we=G[Se]??"";if(!U.single&&!U.double&&(we==="("||we===")")){re.push({text:oe,glob:de},we),oe="",de=!1,Se++;continue}if(K&&we==="`"&&!U.single){oe+=G[Se+1]??"",Se+=2;continue}if(U.single&&we==="'"){U.single=!1,Se++;continue}if(U.single){oe+=we,Se++;continue}if(U.double){if(we==='"'){U.double=!1,Se++;continue}if(!K&&we==="\\"){let We=G[Se+1]??"";oe+=['"',"\\","$"].includes(We)?We:`\\${We}`,Se+=2;continue}if(we==="$"){let We=Mm(G,Se,U,j,K);oe+=We.text,Se=We.next;continue}oe+=we,Se++;continue}if(we==="'"||we==='"'){U.single=we==="'",U.double=we==='"',Se++;continue}if(!K&&we==="\\"){let We=G[Se+1]??"";de||=We==="*"||We==="?",oe+=We,Se+=2;continue}if(we==="$"){let We=Mm(G,Se,U,j,K);oe+=We.text,Se=We.next;continue}de||=we==="*"||we==="?",oe+=we,Se++}return[...re,{text:oe,glob:de}]}function Mm(G,U,j,K,re){let oe=G[U+1];if(oe==="{"){let Se=re?Ov(G,U+2):is(G,U+2,G.length).close;if(Se===-1)return K.invalid=!0,{text:"",next:G.length};let we=G.slice(U,Se+1);return kv(we,j,K,re),{text:we,next:Se+1}}if(oe!==void 0&&Cv.test(oe))return{text:`\${${oe}}`,next:U+2};let de=(re?Sv:/^\w*/).exec(G.slice(U+1))?.[0]??"";return{text:`\${${de}}`,next:U+1+de.length}}function kv(G,U,j,K){let re=G.slice(2,-1),oe=/^[A-Za-z_][A-Za-z0-9_]*/.exec(re)?.[0];if(!oe)return;let de=re.slice(oe.length),Se=[":=","="].find((We)=>de.startsWith(We));if(!Se)return;let we=kl(de.slice(Se.length),{...U},j,K);j.assignmentFallbacks.push(...we.flatMap((We)=>typeof We==="string"||!We.text?[]:[We.text]))}function Ov(G,U){let j=1,K=U;while(j>0&&K<G.length){if(G[K]==="{"&&G[K-1]==="$")j++;if(G[K]==="}")j--;K++}return j===0?K-1:-1}function Mv(G){return/^[\r\n]+$/.test(G)?";":G}function Gn(G){return Object.freeze({kind:"operator",operator:G,boundary:yv.has(G)})}function ys(G){return Object.freeze({kind:"operator",operator:G,boundary:!0})}function Dl(G){return Object.freeze({kind:"word",text:G})}function Dv(G){if(G==="<<"||G==="<<<")return"here-data";if(G==="<"||G==="<&")return"file-read";return"file-write"}function lo(G){return Rv.has(G)||/^python\d/.test(G)}var Nv=new Map([["sudo",new Set(["-u","-g","-h","-p","-C","-D","-r","-t","-T","-U","--user","--group","--host","--prompt","--chdir","--role","--type","--other-user"])],["env",new Set(["-u","-C","-P","-S","--unset","--chdir","--split-string"])]]);function zm(G,U){let j=U[0];if(j===void 0||!j.startsWith("-"))return U;let K=Nv.get(G)?.has(j)??!1;return zm(G,U.slice(K?2:1))}function bs(G){let U=G[0];if(U===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(U))return bs(G.slice(1));if(U==="uv"&&G[1]==="run")return bs(G.slice(2));if(!hv.has(U))return[...G];return bs(zm(U,G.slice(1)))}function $m(G){let U=Vo(G),j=G.words.findIndex((K)=>K.provenance==="literal"&&K.text===U);return bs(j<0?[]:G.words.slice(j).map((K)=>K.text))}function Lv(G){let U=$m(G)[0];if(U===void 0)return!1;let j=kt(U).toLowerCase();return lo(j)&&!si.has(j)}function Ol(G){return G.nodes.flatMap((U,j)=>{if(U.kind==="group"||U.kind==="function")return Ol(U.body);if(U.kind!=="command")return[];let K=U.nested.flatMap((Se)=>Ol(Se)),re=U.redirections.flatMap((Se)=>Se.heredoc?.quotedDelimiter?[Se.heredoc.bodySpan]:[]);if(Lv(U))return[...K,...re];let oe=G.nodes[j+1];if(oe?.kind==="connector"&&(oe.operator==="|"||oe.operator==="|&")||!Gv(U))return K;return[...K,...re]})}function Wv(G,U){let j=Vo(G);return j===void 0?void 0:U.get(j)}function fr(G,U){return G!==void 0&&G.provenance==="literal"&&!G.quoted&&G.raw===G.text&&G.text===U}function Fv(G){if(fr(G.words[0],"git"))return fr(G.words[1],"commit");if(!fr(G.words[0],"gh")||!fr(G.words[2],"create"))return!1;return fr(G.words[1],"pr")||fr(G.words[1],"issue")}function Gv(G){return(fr(G.words[0],"cat")||fr(G.words[0],"tee")||Fv(G))&&!G.words.some(Dm)&&!G.redirections.some((j)=>Dm(j.target))}function Dm(G){return G?.parts.some((U)=>U.provenance==="command-substitution"&&U.raw.startsWith(">("))??!1}var Bm=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Um=new Set([...Bm,"glob"]),zv=new Set([...Um,"folder","pattern","patterns"]);class b extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Hm(G){let U=$v(),j=ie(G.input),K=[];if((G.route.kind==="command"||G.route.kind==="unknown")&&j)K.push({usage:"input-candidate",source:j});if(G.route.kind==="command"&&"command"in G&&G.command)K.push({usage:"declared-command",source:G.command});let re=K.reduce((oe,de)=>{let Se=oe.findIndex((mt)=>mt.source===de.source);if(Se!==-1){let mt=oe[Se];if(!mt)return oe;return oe[Se]={...mt,usages:[...mt.usages,de.usage]},oe}let we=G.route.kind==="command"?G.route.shell:process.platform==="win32"?"powershell":"posix",We=U.getCommandProgram(de.source,we);return oe.push({usages:[de.usage],source:de.source,program:We,shell:U.getShellSyntax(de.source,We)}),oe},[]);return{invocation:{toolName:G.toolName,route:G.route,context:G.context},commands:re,paths:Bv(G),store:U}}function hn(G,U){return G.commands.find((j)=>j.usages.includes(U))}function er(G,U){if(!G.includes("$"))return G;return pa(G,U)}function $v(){let G=new Map,U=new WeakMap,j=(re,oe)=>{let de=`${oe}\x00${re}`,Se=G.get(de);if(Se)return Se;let we=y(re,oe);return G.set(de,we),we};return{getShellSyntax:(re,oe)=>{if(oe&&oe.source!==re)throw TypeError("Shell syntax source does not match command program source.");let de=oe??j(re,"posix"),Se=U.get(de);if(Se)return Se;let we=de.status==="limited"?{status:"structural-limit",source:re,program:de,assignmentFallbacks:[]}:Lm(re,de);return U.set(de,we),we},getCommandProgram:j}}function Bv(G){let U=G.route.kind==="grep"?Um:G.route.kind==="glob"?zv:Bm;return[...yd(G.input,U),...G.route.kind==="patch"||typeof G.input==="string"?Sd(G.input):[]]}var Uv=new Set(["-S","--suffix"]);function co(G,U,j,K,re){if(G.status==="structural-limit")throw new b;if(G.status!=="complete")return re.findMalformedTarget(G.source);return Cs(G,U,j,K,{segment:(oe,de)=>re.findSegmentTarget(oe,de),redirection:(oe,de)=>oe.role==="file-write"&&re.isRedirectionTarget(gn(oe.target,de.variables),de)?oe.target:null})}function vs(G){let U=[],j=null,K=!1;for(let re=0;re<G.length;re++){let oe=G[re];if(oe===void 0)break;if(!K&&oe==="--"){K=!0;continue}if(!K&&(oe==="-t"||oe==="--target-directory")){j=G[++re]??null;continue}if(!K&&oe.startsWith("--target-directory=")){j=oe.slice(19);continue}if(!K&&oe.startsWith("-t")&&oe.length>2){j=oe.slice(2);continue}if(!K&&Uv.has(oe)){re++;continue}if(!K&&(oe.startsWith("--suffix=")||oe.startsWith("--backup=")))continue;if(!K&&oe.startsWith("-"))continue;U.push(oe)}return j?{sources:U,destination:j}:{sources:U.slice(0,-1),destination:U.at(-1)??null}}var x="Git metadata and hooks are protected. Ask the user before modifying them.";function qm(G,U,j,K){let re=G.invocation.context.executionCwd;if(!U)return null;if(G.invocation.route.kind==="patch"||G.invocation.route.kind==="path"||G.invocation.route.kind==="unknown"){if(Ii(G.invocation.toolName))return null;let Se=G.paths.find((we)=>jm(we,re,U,j,K,U.entries));return Se?{target:Se}:null}if(G.invocation.route.kind!=="command")return null;let oe=hn(G,"input-candidate");if(!oe)return null;let de=co(oe.shell,re,j,K,{findSegmentTarget:(Se,we)=>Qv(Se,we,U,j,K),isRedirectionTarget:(Se,we)=>jm(Se,we.cwd,U,j,K,U.markerFiles),findMalformedTarget:()=>null});return de?{target:de}:null}function Mr(G,U,j,K,re,oe,de=!1){if(!j)return!1;let Se=Rs(dn(G,U,re,oe)),we=Se.replace(/(\/\.?\*+)+$/,"");if(we!==Se&&we!==""){if(Nl(we,j))return!0;let We=de||Se.slice(we.length).includes("/."),mt=(gt)=>We?Es(gt,we):qv(gt,we);if(j.markerFiles.some(mt))return!0;return K&&Ll(j).some(mt)}if(Nl(Se,j))return!0;return K&&Ll(j).some((We)=>Es(We,Se))}function qv(G,U){let j=Km(U,G);if(j===""||j.startsWith("..")||Vm(j))return!1;return!j.split(/[\\/]/)[0]?.startsWith(".")}function Yv(G,U,j,K,re){return Mr(G,U,j,!0,K,re)}function Zv(G,U,j,K,re){if(!j)return!1;return Nl(Rs(dn(G,U,K,re)),j)}function jm(G,U,j,K,re,oe){let de=Rs(dn(G,U,K,re));return oe.includes(de)||Zm(de,j)}function Ym(G,U,j,K,re){if(!j)return!1;return j.hooksDirectories.some((oe)=>G.some((de)=>Es(oe,Rs(dn(de,U,K,re)))))}function Nl(G,U){return U.entries.includes(G)||U.directories.includes(G)||Zm(G,U)}function Zm(G,U){return U.hooksDirectories.some((j)=>Es(G,j))}var Xv=50000;function Xm(G,U){let j=[...new Set(Ll(G))];if(j.some((re)=>U(Vv(re))))return!0;let K=0;while(j.length>0){let re=j.pop()??"",oe=Jv(re);if(!oe)return!0;if(K+=oe.length,K>Xv)return!0;if(oe.some((de)=>U(de.name)))return!0;j.push(...oe.filter((de)=>de.isDirectory()).map((de)=>Kv(re,de.name)))}return!1}function Jv(G){try{let U=Hv(G,{throwIfNoEntry:!1});if(!U)return[];if(!U.isDirectory())return U.isSymbolicLink()?null:[];return jv(G,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function Ll(G){return[...G.entries,...G.directories,...G.hooksDirectories]}function Es(G,U){let j=Km(U,G);return j===""||!/^\.\.(?:[\\/]|$)/.test(j)&&!Vm(j)}function Rs(G){return process.platform==="win32"?G.toLowerCase():G}function Qv(G,U,j,K,re){if(ai(G))return null;let oe=mr([...G],K);if(kt(oe[0]??"").toLowerCase()!=="mv")return null;let de=vs(oe.slice(1)),Se=de.sources.find((we)=>Yv(gn(we,U.variables),U.cwd,j,K,re));if(Se)return Se;return de.destination&&Zv(gn(de.destination,U.variables),U.cwd,j,K,re)?de.destination:null}import{isAbsolute as As,normalize as aE,parse as lE,posix as sf,resolve as Nr,sep as zl}from"node:path";import{isAbsolute as eE,join as Jm,normalize as tf,parse as tE,sep as Qm}from"node:path";var nE=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],rE=`
|
|
31
|
-
`;function li(G,U){if(Dr(G,U))return!0;if(!G.has("TMPDIR"))return!1;return!Wl(G.get("TMPDIR")??"",U)}function uo(G,U){if(G.has("TMPDIR"))return Wl(G.get("TMPDIR")??"",U);let j=Fl(G,U);if(j===void 0)return!0;return Wl(j,U)}function Fl(G,U){return rf(G,U,"TMPDIR")}function Wl(G,U){if(!G)return!1;if(iE(G))return!1;return mo(G,U)}function Dr(G,U){let j=rf(G,U,"IFS");return j!==void 0&&j!==""&&j!==rE}function mo(G,U){let j=xs(G,U.paths);if(j===null)return!1;return nf(U).some((K)=>fo(j,K))}function ws(G,U){let j=xs(G,U.paths);if(j===null)return!1;return nf(U).some((K)=>_s(K)===_s(j))}var ef=new WeakMap;function nf(G){let U=ef.get(G);if(U)return U;let j=oE(G);return ef.set(G,j),j}function oE(G){let U=nE.map((K)=>xs(K,G.paths)??tf(K)),j=xs(G.tmpdir,G.paths);if(!j)return U;if(process.platform==="win32")return[...U,j];if(process.platform==="darwin"&&sE(j))return[...U,j];return U}function iE(G){return/[\s$`*?[]/.test(G)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(G)||/[+@!]\([^)]*\)/.test(G)}function rf(G,U,j){return G.has(j)?G.get(j):U.env.get(j)}function sE(G){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(G)}function xs(G,U){try{let j=tf(G);if(!eE(j))return j;let K=tE(j).root,re=j.slice(K.length).split(/[\\/]+/).filter(Boolean),oe=K;for(let de=0;de<re.length;de++){let Se=Jm(oe,re[de]??"");if(U.entryKind(Se)==="missing")return Jm(Se,...re.slice(de+1));let we=U.realpath(Se);if(we===null)return null;oe=we}return oe}catch{return null}}function fo(G,U){let j=_s(G),K=_s(U);if(j===K)return!0;let re=K.endsWith(Qm)?K:`${K}${Qm}`;return j.startsWith(re)}function _s(G){return process.platform==="win32"?G.toLowerCase():G}var cE=process.platform==="win32",of=64,dE=16384;function Lr(G,U,j,K){if(G.kind==="temp_target")return null;let re=K[G.kind];if(G.kind==="dynamic_target"&&!Jt(j,re.id,U.strict))return null;if(G.kind==="within_anchored_cwd"&&!Jt(j,re.id,U.paranoid))return null;return Rt(re.id,re.reason)}function ci(G){let U=Bu(G,of,of,dE);return{expandedTargets:U&&"words"in U?U.words:void 0,unsafeBraceExpansion:U!==void 0&&"limited"in U,targetIsLiteral:U===void 0&&G.provenance==="literal"&&(G.quoted||G.raw!==G.text),tmpdirWordSplittingProtected:uE(G)}}function uE(G){let U=G.parts.filter((j)=>j.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(j.raw));return U.length>0&&U.every((j)=>mE(G.raw,j.span.start-G.span.start))}function mE(G,U){let j=null,K=!1;for(let re=0;re<U;re++){let oe=G[re];if(K){K=!1;continue}if(oe==="\\"&&j!=="'"){K=!0;continue}if(j===oe){j=null;continue}if(j===null&&(oe==="'"||oe==='"'))j=oe}return j==='"'}function jn(G){let U=G.environment.home,j=G.environment.paths,K=G.budget??Pn();return{anchoredCwd:G.originalCwd??G.cwd??null,resolvedCwd:G.cwd??null,strict:G.strict??!1,paranoid:G.paranoid??!1,trustTmpdirVar:G.allowTmpdirVar??!0,posixShell:G.posixShell??!1,tmpdirWordSplittingUnsafe:G.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:G.trustedTmpdirValue??G.allowTmpdirVar??!0,environment:G.environment,allowRoots:bE(G.allowPaths,U,j,K),protectedGitMetadata:G.protectedGitMetadata,budget:K}}function _n(G,U,j={}){let K=j.targetIsLiteral??!1;if(!K&&U.tmpdirWordSplittingUnsafe&&!j.tmpdirWordSplittingProtected&&SE(G))return{kind:"outside_anchored_cwd"};let re=!K&&lf(G,U.posixShell);if(sr(G))return{kind:"outside_anchored_cwd"};if($l(G,K))return{kind:"root_or_home_target"};if(pE(G,U,K))return{kind:"root_or_home_target"};if(U.resolvedCwd&&Mr(G,U.resolvedCwd,U.protectedGitMetadata,!0,U.environment,U.budget,!U.posixShell))return{kind:"git_metadata_target"};if(gE(G,U.trustTmpdirVar,U.posixShell,re,K,j.tmpdirWordSplittingProtected??!1,U.trustedTmpdirValue,U.environment))return{kind:"temp_target"};if(re)return{kind:"dynamic_target"};if(CE(G,U,K))return{kind:"temp_target"};let oe=U.anchoredCwd;if(oe){if(!j.skipHomeCwd&&xE(oe,U.environment.home,U.environment.paths,U.budget))return{kind:"home_cwd_target"};if(!j.skipCwdSelf&&[U.resolvedCwd??oe,oe].some((de)=>_E(G,U.resolvedCwd??oe,U.environment.paths,U.budget,de)))return{kind:"cwd_self_target"};if(wE(G,oe,U.resolvedCwd??oe,re,K,U.environment.paths,U.budget))return{kind:"within_anchored_cwd"}}if(fE(G,U,re))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function fE(G,U,j){let K=G.trim();if(j||!U.resolvedCwd||!U.anchoredCwd||!K)return!1;if(As(K)||K.startsWith("~"))return!1;if(Bl(K))return!1;if(cf(U.resolvedCwd,U.anchoredCwd,U.environment.paths,U.budget))return!1;return mo(Nr(U.resolvedCwd,K),U.environment)}function af(G,U,j={}){let{containmentTarget:K,...re}=j;if(_n(G,U,re).kind!=="temp_target")return!1;let oe=G.trim();if(yE(oe))return!1;if(ws(oe,U.environment))return!1;return![U.anchoredCwd,U.resolvedCwd].some((de)=>cf(K??oe,de,U.environment.paths,U.budget))}function $l(G,U=!1){let j=G.trim(),K=sf.normalize(j),re=j.replace(/\\/g,"/"),oe=K==="/"?K:K.replace(/\/+$/,"");if(oe==="/"||oe.startsWith("/")&&oe.slice(1).split("/").every((de)=>/^\*+$/.test(de)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(re)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(re))return!0;if(!U&&(K==="~"||K==="~/"||K==="~/*"))return!0;if(!U&&(K==="$HOME"||K==="$HOME/"||K==="$HOME/*"))return!0;if(!U&&(K==="${HOME}"||K==="${HOME}/"||K==="${HOME}/*"))return!0;return!1}function pE(G,U,j){let K=G.trim(),re=j?K:K==="*"?".":K.endsWith("/*")?K.slice(0,-2):K;if(!re)return!1;try{let oe=As(re)?re:U.resolvedCwd?Nr(U.resolvedCwd,re):null;if(!oe)return!1;let de=yn(Nt(oe,U.environment.paths,U.budget));if(de===lE(de).root)return!0;return de===yn(Nt(U.environment.home,U.environment.paths,U.budget))}catch{return!1}}function yn(G){let U=aE(G);if(cE){if(U=U.replace(/\//g,"\\").toLowerCase(),U.length>3&&U.endsWith("\\"))U=U.slice(0,-1);return U}if(U.length>1&&U.endsWith("/"))U=U.slice(0,-1);return U}function gE(G,U,j,K,re,oe,de,Se){let we=G.trim();if(Bl(we))return!1;if(!K&&mo(we,Se))return!0;return(U||oe&&de)&&j&&!re&&hE(we,j)}function hE(G,U){return["$TMPDIR","${TMPDIR}"].some((j)=>{if(G===j)return!0;if(!G.startsWith(`${j}/`))return!1;return!lf(G.slice(j.length+1),U)})}function yE(G){let U=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(G);if(!U)return!1;return sf.normalize(`/${U[1]??""}`)==="/"}function Bl(G){return G.split(/[\\/]+/).includes("..")}function bE(G,U,j,K){if(!G?.length)return[];return G.flatMap((re)=>{let oe=Uo(re.trim(),U);if(!As(oe))return[];try{let de=Nt(oe,j,K);if(Ho(de,Nt(U,j,K)))return[];return[yn(de)]}catch{return[]}})}function CE(G,U,j){if(U.allowRoots.length===0)return!1;let K=G.trim();if(Bl(K))return!1;let re=j?K:Uo(K,U.environment.home),oe=U.resolvedCwd??U.anchoredCwd,de=As(re)?re:oe?Nr(oe,re):null;if(!de)return!1;try{let Se=yn(Nt(de,U.environment.paths,U.budget));return U.allowRoots.some((we)=>Se===we||Se.startsWith(we.endsWith(zl)?we:`${we}${zl}`))}catch{return!1}}function SE(G){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(G)}function lf(G,U=!1){return G.includes("$")||G.includes("`")||vE(G)||U&&EE(G)}function vE(G){let U=!1;for(let j of G){if(U){U=!1;continue}if(j==="\\"){U=!0;continue}if(j==="*"||j==="?"||j==="[")return!0}return!1}function EE(G){let U=!1;for(let j=0;j<G.length;j++){let K=G[j];if(U){U=!1;continue}if(K==="\\"){U=!0;continue}if(K==="{"&&RE(G,j)||(K==="+"||K==="@"||K==="!")&&G[j+1]==="(")return!0}return!1}function RE(G,U){let j=G.indexOf("}",U+1);if(j===-1)return!1;let K=G.slice(U+1,j);return K.includes(",")||K.includes("..")}function xE(G,U,j,K){try{return yn(Nt(G,j,K))===yn(Nt(U,j,K))}catch{try{return yn(G)===yn(U)}catch{return!1}}}function _E(G,U,j,K,re=U){if(re===U&&(G==="."||G==="./"||G===".\\"))return!0;try{return yn(Nt(Nr(U,G),j,K))===yn(Nt(re,j,K))}catch{try{return yn(Nr(U,G))===yn(re)}catch{return!1}}}function wE(G,U,j,K,re,oe,de){let Se=j??U;if(!re&&(G.startsWith("~")||G.startsWith("$HOME")||G.startsWith("${HOME}")))return!1;if(K)return!1;if(G.startsWith("/")||/^[A-Za-z]:[\\/]/.test(G))try{return Gl(G,U,oe,de)}catch{return!1}if(G.startsWith("./")||G.startsWith(".\\")||!G.includes("/")&&!G.includes("\\"))try{return Gl(Nr(Se,G),U,oe,de)}catch{return!1}if(G.startsWith("../"))return!1;try{return Gl(Nr(Se,G),U,oe,de)}catch{return!1}}function Gl(G,U,j,K){try{return df(Nt(G,j,K),Nt(U,j,K))}catch{return!1}}function cf(G,U,j,K){if(!U)return!1;try{return df(Nt(U,j,K),Nt(G,j,K))}catch{return!0}}function df(G,U){let j=yn(G),K=yn(U);return j.startsWith(`${K}${zl}`)||j===K}var AE=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),uf="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",PE="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.",mf="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",ff="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",TE="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",IE="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",kE={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:ff},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:x},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:mf},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:TE},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:uf},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:PE},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:uf}};function pf(G,U,j){return OE(G.words.map((K)=>({kind:"word",text:K.text,dynamic:K.provenance!=="literal"})),U,jn({...j,allowPaths:j.policy?.destructiveCommandAllowPaths}),j.policy)}function OE(G,U,j,K){let re=G.filter((we)=>we.kind==="word"),oe=DE(re),de=re[oe];if(!de||!AE.has(UE(de.text)))return null;let Se=ME(re.slice(oe+1));if(Se.whatIfProtected)return null;if(Jt(K,"powershell.remove-item-pipeline-dynamic-target",j.strict)&&U&&(Se.targets.length===0||Se.recursive))return Rt("powershell.remove-item-pipeline-dynamic-target",IE);for(let we of Se.targets)if(!sr(we.text)&&$l(di(we.text)))return Rt(Se.recursive&&Se.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",ff);for(let we of Se.targets)if(j.resolvedCwd&&Mr(di(we.text),j.resolvedCwd,j.protectedGitMetadata,Se.recursive,j.environment,j.budget,!0))return Rt("powershell.remove-item-git-metadata",x);if(!Se.recursive||!Se.force)return null;if(Jt(K,"powershell.remove-item-recursive-force-dynamic-target",j.strict)&&(Se.hasDynamicTarget||Se.targets.length===0))return Rt("powershell.remove-item-recursive-force-dynamic-target",mf);for(let we of Se.targets){let We=Lr(_n(di(we.text),j),j,K,kE);if(We)return We}return null}function ME(G){let U=[],j=!1,K=!1,re=!1,oe=!1,de=!1;for(let Se=0;Se<G.length;Se++){let we=G[Se];if(!we||we.kind!=="word")continue;if(NE(we))continue;if(de){U.push(Ul(we)),oe=oe||we.dynamic;continue}if(we.text==="--"){de=!0;continue}let We=WE(we.text);if(!We){U.push(Ul(we)),oe=oe||we.dynamic;continue}if(FE(We.name)){let mt=We.value?LE(We.value,we):G[++Se];if(mt?.kind==="word"){U.push(Ul(mt)),oe=oe||mt.dynamic;continue}oe=!0;continue}if(GE(We.name)){j=!0;continue}if(zE(We.name)){K=!0;continue}if($E(We.name))re=BE(We.value)}return{targets:U,recursive:j,force:K,whatIfProtected:re,hasDynamicTarget:oe}}function DE(G){let U=G[0];if(U?.kind==="word"&&U.text==="&"||U?.text===".")return G.length>1?1:0;return 0}function Ul(G){return{text:G.kind==="word"?G.text:"",dynamic:G.kind==="word"&&G.dynamic}}function NE(G){return G.kind==="word"&&G.text===","}function di(G){let U=G.replace(/\\/g,"/"),j=/^(?:\$env:(?:userprofile|home)|\$home|\$\{home\})(?=$|\/)/i.exec(U);return j?`$HOME${U.slice(j[0].length)}`:U}function LE(G,U){return{kind:"word",text:G,dynamic:U.kind==="word"&&(U.dynamic||G.includes("$"))}}function WE(G){if(!G.startsWith("-")||G==="-")return null;let U=G.slice(1),j=U.indexOf(":");if(j===-1)return{name:U.toLowerCase()};return{name:U.slice(0,j).toLowerCase(),value:U.slice(j+1)}}function FE(G){return"path".startsWith(G)||"literalpath".startsWith(G)}function GE(G){return"recurse".startsWith(G)}function zE(G){return G.length>=2&&"force".startsWith(G)}function $E(G){return G==="wi"||"whatif".startsWith(G)}function BE(G){if(G===void 0||G==="")return!0;let U=G.toLowerCase();return U==="$true"||U==="true"}function UE(G){return G.toLowerCase()}var po="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",Ps="Unsupported heredoc syntax",ui="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function go(){return{id:"analysis.dynamic-shell-source",reason:ui,intent:"stop_and_explain"}}var gf="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var HE=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),jE=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),VE=new Set(["-o","--output","--query","--subscription"]),KE=new Set;function hf(G){if(G==="aws")return HE;if(G==="gcloud")return jE;if(G==="az")return VE;return KE}var qE=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),YE=new Set;function yf(G){if(G==="git")return vn;if(G==="docker")return qE;return YE}function A(G,U){if(G.length===0||U.length===0)return null;let j=Mt(G[0]??""),K=fn(G);for(let re of U){if(!JE(j,re.command))continue;if(re.match){if(ZE(j,G,re.match))return bf(re);continue}if(!QE(j,G,re.subcommand))continue;if(tR(G,new Set(re.block_args),K))return bf(re)}return null}function bf(G){return{id:`custom.${G.name}`,reason:`[${G.name}] ${G.reason}`,intent:G.intent??"manual_only"}}function ZE(G,U,j){let K=U.slice(1);if(j.exclude_args?.some((re)=>K.includes(re)))return!1;if(j.any_args&&!j.any_args.some((re)=>K.includes(re)))return!1;return XE(K,j.command_path,hf(G))}function XE(G,U,j){let K=0,re=!1;for(let oe of G){if(K>=U.length)return!0;if(re){re=!1;continue}if(oe.startsWith("-")){re=!oe.includes("=")&&j.has(oe);continue}if(oe!==U[K])return!1;K++}return K>=U.length}function JE(G,U){return G===Mt(U)}function QE(G,U,j){if(!j)return!0;return Cf(U,1,j,yf(G))}function Cf(G,U,j,K){let re=!1;for(let oe=U;oe<G.length;oe++){let de=G[oe];if(!de)continue;if(re){re=!1;continue}if(de==="--"){let Se=G[oe+1];if(Se&&!Se.startsWith("-"))return Se===j;return!1}if(K.has(de)){re=!0;continue}if(de.startsWith("-")){if(!de.includes("=")&&eR(G,oe,j,K))return!0;continue}return de===j}return!1}function eR(G,U,j,K){let re=G[U+1];if(!re||re.startsWith("-"))return!1;return Cf(G,U+2,j,K)}function tR(G,U,j){return G.some((K)=>U.has(K))||[...j].some((K)=>U.has(K))}var nR=new Set(["-e","--source"]),rR=new Set(["-F","-v","--assign","--field-separator"]),Sf=new Set(["-f","--file"]),oR=new Set(["print","printf","return"]),vf=[{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"}],iR="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 Ef(G,U,j){let K=!1;for(let re of sR(G)){let oe=aR(re,j);if(!oe)continue;for(let de of oe.commands){let Se=U(de);if(Se)return Se;if(de.includes("{}")||/[$`]/.test(de))K=!0}K||=oe.dynamic}return K?Rt("awk.system-dynamic",iR):null}function jl(G){let U=[],j=!1,K=!1,re=!0,oe=!0;for(let de=1;de<G.length;de++){let Se=G[de];if(Se===void 0)break;if(re&&Se==="--"){re=!1;continue}if(re&&nR.has(Se)){j=!0;let we=G[de+1];if(oe&&=we!==void 0,we!==void 0)U.push({tokenIndex:de+1,kind:"inline-code",value:we});de++;continue}if(re&&Se.startsWith("--source=")){j=!0,U.push({tokenIndex:de,kind:"inline-code",value:Se.slice(9)});continue}if(re&&Se.startsWith("-e")&&Se.length>2){j=!0,U.push({tokenIndex:de,kind:"inline-code",value:Se.slice(2)});continue}if(re&&(rR.has(Se)||Sf.has(Se))){let we=G[de+1];if(oe&&=we!==void 0,Sf.has(Se)){if(K=!0,we!==void 0)U.push({tokenIndex:de+1,kind:"program-file",value:we})}de++;continue}if(re&&(Se.startsWith("-F")||Se.startsWith("-v")&&Se.slice(2).includes("=")))continue;if(re&&Se.startsWith("-f")&&Se.length>2){K=!0,U.push({tokenIndex:de,kind:"program-file",value:Se.slice(2)});continue}if(re&&(Se.startsWith("--assign=")||Se.startsWith("--field-separator=")))continue;if(re&&Se.startsWith("--file=")){K=!0,U.push({tokenIndex:de,kind:"program-file",value:Se.slice(7)});continue}if(re&&Se.startsWith("-")&&Se!=="-")continue;if(!j&&!K)U.push({tokenIndex:de,kind:"main-program",value:Se});return{sources:U,optionsOpen:!1}}return{sources:oe?U:[],optionsOpen:re&&oe}}function fi(G){return jl(G).sources}function sR(G){return fi(G).filter((U)=>U.kind!=="program-file").map((U)=>U.value)}function aR(G,U){xn(U,G);let j=G.includes("system")?Vl(G,U):null,K=lR(G,U);if(!j&&!K)return null;return{dynamic:!!j?.dynamic||!!K?.dynamic,commands:[...j?.commands??[],...K?.commands??[]]}}function Vl(G,U){xn(U,G);let j=[],K=!1,re=!1,oe=0;while(oe<G.length){let de=G[oe];if(de==='"'||de==="'"){oe=Is(G,oe,de)?.endIndex??oe+1;continue}if(de==="#"){oe=Rf(G,oe+1);continue}if(de==="/"&&xf(G,oe)){oe=_f(G,oe+1)??oe+1;continue}if(!G.startsWith("system",oe)){oe++;continue}let Se=oe;if(oe+=6,mi(G[Se-1])||mi(G[oe]))continue;let we=Ts(G,oe);if(G[we]!=="(")continue;we=Ts(G,we+1);let We=G[we];if(We!=='"'&&We!=="'"){K=!0,re=!0;continue}let mt=Is(G,we,We);if(!mt){K=!0,re=!0;continue}if(we=Ts(G,mt.endIndex),K=!0,G[we]!==")"){re=!0,oe=mt.endIndex;continue}j.push(mt.value),oe=we+1}if(!K)return null;return{dynamic:re,commands:j}}function lR(G,U){xn(U,G);let j=[],K=!1,re=!1,oe=0,de=0,Se=null,we=null,We=0;while(oe<G.length){let mt=G[oe];if(!mt)break;if(mt==='"'||mt==="'"){let pt=Is(G,oe,mt);if(pt&&We===de)we={...pt,startIndex:oe};We=pt?.endIndex??oe+1,oe=pt?.endIndex??oe+1;continue}if(mt==="#"){oe=Rf(G,oe+1),de=oe,Se=null,we=null,We=oe;continue}if(mt==="/"&&xf(G,oe)){let pt=_f(G,oe+1);We=pt??oe+1,oe=pt??oe+1;continue}if(`;
|
|
32
|
-
{}`.includes(mt)){oe++,de=oe,Se=null,we=null,We=oe;continue}if(Se===null&&(Hl(G,oe,"print")||Hl(G,oe,"printf")))Se=oe;if(mt!=="|"||G[oe-1]==="|"||G[oe+1]==="|"){if(!/\s/.test(mt))We=oe+1;oe++;continue}let gt=G[oe+1]==="&"?oe+2:oe+1,ft=Ts(G,gt);if(Hl(G,ft,"getline")){re=!0;let pt=
|
|
33
|
-
}#`.includes(K)}function Is(G,U,j){let K="",re=!1;for(let oe=U+1;oe<G.length;oe++){let de=G[oe];if(!de)break;if(re){let Se=
|
|
34
|
-
`,r:"\r",t:"\t",v:"\v"}[j]??j,endIndex:U}}function Hl(G,U,j){return G.startsWith(j,U)&&!mi(G[U-1])&&!mi(G[U+j.length])}function
|
|
35
|
-
`,U);return j===-1?G.length:j+1}function xf(G,U){let j=pR(G,U);if(j===-1)return!0;if("{([,;!~=".includes(G[j]??""))return!0;let K=j;while(mi(G[K-1]))K--;return oR.has(G.slice(K,j+1))}function pR(G,U){for(let j=U-1;j>=0;j--)if(!/\s/.test(G[j]??""))return j;return-1}function _f(G,U){let j=!1;for(let K=U;K<G.length;K++){let re=G[K];if(!re)break;if(j){j=!1;continue}if(re==="\\"){j=!0;continue}if(re==="/")return K+1}return null}var gR=new Set(["sudo","env","command","builtin"]),hR=new Set(["caffeinate","exec","nice","nohup","setsid","stdbuf","time","timeout"]);function ks(G,U){let j=G[0];if(!j||!wf(kt(j),U))return null;let K=kt(j),re=G[1]==="--"?2:1,oe=yR(G,re,K,U),de=oe[0];if(de===void 0)return null;return{wrapper:K,tokens:G.slice(de),childIndex:de,alternativeChildIndices:oe.slice(1)}}function yR(G,U,j,K){let re=G[1]==="--",oe=[];for(let de=U;de<G.length;de++){let Se=G[de];if(!Se)continue;let we=kt(Se)!==j&&bR(Se,K);if(we)oe.push(de);if(!we&&Fi.has(Mt(Se)))break;if(re)break}return oe}function bR(G,U){let j=kt(G),K=Mt(G);return K==="git"||j==="busybox"||Wr(G)||Na.has(j)||mm(K)||wf(j,U)||qt.has(K)||G==="$SHELL"||Ln(K)||In.has(K)||U.rules.some((re)=>re.command===j)}function wf(G,U){return hR.has(G)||U.transparentWrappers.includes(G)}function Wr(G){return gR.has(G.toLowerCase())}function Fr(G,U){return{embedded:!1,cwd:G.cwd,originalCwd:U.originalCwd,effectiveCwd:G.cwd,envAssignments:G.envAssignments,allowTmpdirVar:U.allowTmpdirVar,worktreeMode:U.worktreeMode,wrappedByTransparent:!1}}function zn(G,U){let j=U.policy??{rules:[],transparentWrappers:[]};return Os([...G],U.environment,U.cwd,U.cwd,new Map,new Map(U.envAssignments??[]),j,{iterations:0},!1)}function*Os(G,U,j,K,re,oe,de,Se,we){let We=gs(G,U,j,oe);for(let[pt,ht]of We.envAssignments)oe.set(pt,ht),re.set(pt,ht);let{tokens:mt,cwd:gt}=We;if(We.envSplitValues){let pt=ps(We.envSplitValues,mt);if(!pt)throw new s("derivedCommandShape");Kl(Se),yield*Os(pt,U,gt,K,re,oe,de,Se,we);return}if(Wr(mt[0]??""))throw new s("wrapperPeelIterations");let ft=ks(mt,de);if(ft){for(let pt of[ft.childIndex,...ft.alternativeChildIndices])Kl(Se),yield*Os(pt===ft.childIndex?ft.tokens:mt.slice(pt),U,gt,K,new Map(re),new Map(oe),de,Se,!0);return}if(SR(mt)){Kl(Se),yield*Os(mt.slice(1),U,gt,K,re,oe,de,Se,we);return}yield CR(mt,gt,K,re,oe,we)}function CR(G,U,j,K,re,oe){return{tokens:G,cwd:U===null?void 0:U??j,wrapperCwd:U,wrapperEnvAssignments:K,envAssignments:re,head:kt(G[0]??"").toLowerCase(),wrappedByTransparent:oe}}function Kl(G){if(G.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");G.iterations++}function SR(G){return kt(G[0]??"").toLowerCase()==="busybox"&&G.length>1}function ql(G,U){let j=[],K=U;while(K<G.length){let re=G[K];if(re===void 0||re===":::")break;j.push(re),K++}return{markerIndex:K<G.length&&G[K]===":::"?K:-1,templateTokens:j}}function tr(G){let U=!1,j=!1;for(let K of G){if(K==="--")break;if(K==="-r"||K==="-R"||Yl(K,"recursive")){U=!0;continue}if(K==="-f"||Yl(K,"force")){j=!0;continue}if(K.startsWith("-")&&!K.startsWith("--")){if(K.includes("r")||K.includes("R"))U=!0;if(K.includes("f"))j=!0}}return U&&j}function Ms(G){let U=G.indexOf("--");return G.slice(1,U===-1?void 0:U).some((j)=>Yl(j,"recursive")||/^-[A-Za-z]+$/.test(j)&&/[rR]/.test(j.slice(1)))}function Yl(G,U){return G.length>2&&G.startsWith("--")&&U.startsWith(G.slice(2))}var vR=["--init-file","--rcfile"],ER=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function $n(G){for(let U=1;U<G.length;U++){let j=G[U];if(!j)continue;if(j==="-c")return Af(G,U,!0);if(j.startsWith("-")&&j.includes("c")&&!j.startsWith("--")){let K=Af(G,U,!1);if(K!==null)return K}}return null}function nr(G){let U=kt(G[0]??"").toLowerCase();if(U==="zsh"||U==="ksh")return En(G).syntaxCheck;let j=!1;for(let K of G.slice(1)){if(K==="--")return j;if(K.startsWith("+")&&!K.startsWith("++")){if(K.slice(1).includes("n"))j=!1;continue}if(!K.startsWith("-")||K.startsWith("--"))return j;let re=K.slice(1);if(re.includes("n"))j=!0;if(re.includes("c"))return j}return j}function Af(G,U,j){if(G[U+1]==="--")return G[U+2]||null;let K=G[U+1];if(!K||!j&&K.startsWith("-"))return null;return K}function Pf(G){let U=kt(G[0]??"").toLowerCase(),j=RR(G,U),K=ER.get(U)??null,re=j.argvSource?.kind!=="absent";return{argvSource:U==="bash"?j.argvSource:null,argvSourceApplies:U==="bash"&&j.interactive&&j.argvSource?.kind==="literal",envName:K,envSourceApplies:re&&(K==="BASH_ENV"?!j.interactive:K==="ENV"&&j.interactive)}}function RR(G,U){let j=En(G),K=j.commandIndex??j.scriptIndex??G.length,re=[],oe=!1,de=!0;for(let Se=1;Se<K;Se++){let we=G[Se];if(we===void 0||we==="--"||we==="-"||we[0]!=="-"&&we[0]!=="+")break;if(we.startsWith("--")){if(U==="bash"&&de?vR.find((ft)=>we===ft):void 0){let ft=G[Se+1];re.push(ft===void 0?{kind:"absent"}:{kind:"literal",value:ft}),Se++;continue}let gt=we.split("=",1)[0]??we;if(U==="bash"&&Ma.has(gt)&&!we.includes("="))Se++;continue}if(U==="bash")de=!1;let We=Da(U,we,G[Se+1],"startup");if(We.interactive)oe=we[0]==="-";Se+=We.followingValues}return{argvSource:re.at(-1)??null,interactive:oe}}var xR="find -delete permanently removes files. Use -print first to preview.",_R="find -exec rm -rf is dangerous. Use explicit file list instead.",wR=new Set(["-exec","-execdir","-ok","-okdir"]),AR=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((G)=>[G,1]),["-fprintf",2]]);function Tf(G,U){let j=G.map(t),K=PR(G,j,U);if(K)return K;if(Ds(j,1)&&!DR(G,j,U)){let de=Tt(Rt("find.delete",xR),U.policy);if(de)return de}let re=U.budget??Pn(),oe=0;while(oe<j.length){let de=j[oe],Se=rr(de??"");if(Se>0){oe+=Se+1;continue}if(!Vn(de)){oe++;continue}re.charge("derivedTokens",j.length-oe-1);let we=ho(j,oe);oe=we.nextIndex;let We=LR(we.tokens,U.environment);if(We){let pt=Tt(We,U.policy);if(pt)return pt}let mt=de==="-execdir"||de==="-okdir",gt=U.analyzeTokens?.(we.tokens,mt?null:U.cwd)??null,ft=gt?.id.startsWith("custom.")?gt:Tt(gt,U.policy);if(ft)return ft}return null}function PR(G,U,j){if(!Ds(U,1)&&!Zl(U,j.environment))return null;let re=pi(G)??Kt(["."]),oe=jn({...j,allowPaths:j.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let de of re){let Se=ci(de);for(let we of Se.expandedTargets??[t(de)]){let We=_n(we,oe,{targetIsLiteral:Se.expandedTargets!==void 0||Se.targetIsLiteral,tmpdirWordSplittingProtected:Se.tmpdirWordSplittingProtected});if(We.kind==="root_or_home_target")return Rt("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(We.kind==="git_metadata_target"&&!TR(G,oe.protectedGitMetadata,j.environment))return Rt("find.delete-git-metadata",x)}}if(MR(U)&&oe.resolvedCwd&&Ym(re.map(t),oe.resolvedCwd,oe.protectedGitMetadata,oe.environment,oe.budget))return Rt("find.delete-git-metadata",x);return null}function TR(G,U,j){if(!U)return!1;let K=G.map(t),re=[],oe=!1,de=pi(G)?.at(-1),Se=de?G.indexOf(de)+1:1;while(Se<K.length){let we=K[Se]??"";if(Vn(we)){let We=ho(K,Se),mt=mr([...We.tokens],j),gt=Ms(mt),ft=qt.has(kt(mt[0]??"").toLowerCase()),pt=We.tokens.some((yt)=>yt!=="{}"&&yt.includes("{}")),ht=(we==="-execdir"||we==="-okdir")&&mt.slice(1).some((yt)=>yt!=="{}"&&!yt.startsWith("-"));if(gt||ft||pt||ht)return!1;oe=!0,Se=We.nextIndex;continue}if(we==="-delete"){oe=!0,Se++;continue}if(we==="-name"||we==="-iname"){let We=G[Se+1];if(!(We?.provenance==="literal"&&!/[[\\]/.test(We.text)))return!1;if(!oe)re.push(kR(We.text,we==="-iname"));Se+=2;continue}if(!IR.has(we))return!1;Se+=1+rr(we)}return re.length>0&&!Xm(U,(we)=>re.every((We)=>We.test(we)))}var IR=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function kR(G,U){let j=G.replace(/[*?]|[.+^${}()|\]/]/g,(K)=>K==="*"?".*":K==="?"?".":`\\${K}`);return new RegExp(`^${j}$`,U?"isu":"su")}var OR=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function Zl(G,U){let j=0;while(j<G.length){if(!Vn(G[j])){j++;continue}let K=ho(G,j),re=mr([...K.tokens],U),oe=kt(re[0]??"").toLowerCase(),de=qt.has(oe)&&OR.test(($n(re)??"").replace(/["'\\]/g,""));if((oe==="rm"||oe==="rmdir"||de)&&re.some((we)=>we.includes("{}")))return!0;j=K.nextIndex}return!1}function MR(G){return G.some((U,j)=>{if(!["-name","-iname"].includes(U))return!1;return G[j+1]?.toLowerCase()==="hooks"})}function DR(G,U,j){if(U.includes("-L")||U.includes("-f")||U.includes("-follow"))return!1;let K=pi(G);if(!K)return!1;let re=j.envAssignments??new Map,oe=Fl(re,j.environment),de=j.trustedTmpdirValue??uo(re,j.environment),Se=j.allowTmpdirVar??!li(re,j.environment),we={environment:j.environment,protectedGitMetadata:j.protectedGitMetadata,cwd:j.cwd,originalCwd:j.originalCwd,strict:j.strict,allowTmpdirVar:Se&&de&&Boolean(oe),allowPaths:j.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:j.tmpdirWordSplittingUnsafe??Dr(re,j.environment),trustedTmpdirValue:de,budget:j.budget},We=jn(we),mt=jn({...we,cwd:j.originalCwd??j.cwd}),gt=j.originalCwd&&j.environment.paths.realpath(j.originalCwd),ft=j.cwd&&j.environment.paths.realpath(j.cwd),pt=gt&&ft&&!fo(ft,gt)?j.cwd:void 0;return K.every((ht)=>{let yt=ci(ht);if(yt.unsafeBraceExpansion)return!1;return(yt.expandedTargets??[t(ht)]).every((bt)=>{let Ct=/^\.\/*$/.test(bt)?pt:void 0,vt=Ct??bt,St={targetIsLiteral:yt.expandedTargets!==void 0||yt.targetIsLiteral,tmpdirWordSplittingProtected:yt.tmpdirWordSplittingProtected};if(!Jt(j.policy,"rm.recursive-force-paranoid",j.paranoid??!1)&&!Ct&&_n(vt,We,St).kind==="within_anchored_cwd")return!0;return af(vt,Ct?mt:We,{...St,containmentTarget:NR(vt,oe)})})})}function NR(G,U){if(!U)return G;return G.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>U)}function pi(G){let U=(re)=>{let oe=G[re];return oe?t(oe):void 0},j=1;while(U(j)==="-H"||U(j)==="-P")j++;if(U(j)==="--")j++;let K=[];while(j<G.length){let re=U(j),oe=G[j];if(!re||!oe||re.startsWith("-")||["!","(",")"].includes(re))break;K.push(oe),j++}return K.length>0?K:null}function LR(G,U){let j=ur([...G],U);if(j.length===0)return null;let K=kt(j[0]??"");if(K==="busybox"&&j.length>1)j=j.slice(1),K=kt(j[0]??"");if(K==="rm"&&tr(j))return Rt("find.exec-rm-recursive-force",_R);return null}function ho(G,U){let j=U+1;while(j<G.length&&G[j]!==";"&&!(G[j]==="+"&&G[j-1]==="{}"))j++;return{tokens:G.slice(U+1,j),nextIndex:Math.min(j+1,G.length)}}function Ds(G,U){let j=U;while(j<G.length){let K=G[j];if(!K){j++;continue}if(Vn(K)){j=ho(G,j).nextIndex;continue}let re=rr(K);if(re>0){j+=re+1;continue}if(K==="-delete")return!0;j++}return!1}function rr(G){return AR.get(G)??(/^-newer[A-Za-z]{2}$/.test(G)?1:0)}function Vn(G){return G!==void 0&&wR.has(G)}import{resolve as u_}from"node:path";function*Xl(G){for(let U of G.nodes)yield*FR(U)}function WR(G){return Object.freeze([...Xl(G)])}function dt(G){return Object.freeze(WR(G).map((U)=>Object.freeze(U.words.map((j)=>j.text))))}function gi(G){let U=y(G,"posix");if(U.status!=="complete"||U.nodes.length!==1)return null;let j=U.nodes[0];if(j?.kind!=="command")return null;if(j.redirections.length>0||j.nested.length>0)return null;if(j.words.some((K)=>K.provenance==="command-substitution"))return null;return j.words.map((K)=>K.text)}function*FR(G){if(G.kind==="command"){yield G;for(let U of G.nested)yield*Xl(U);return}if(G.kind==="group")yield*Xl(G.body)}var GR=5,Jl="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 sn(G){let U=G.indexOf("--");if(U===-1)return{index:-1,before:G,after:[]};return{index:U,before:G.slice(0,U),after:G.slice(U+1)}}function kf(G,U,j){let K=Ns(G,U,j),re=zR(K.entries);if(re.size===0)return{blockedReason:K.blockedReason,expanded:!1,tokens:G};let oe=G,de=!1;for(let Se=0;Se<GR;Se++){let{subcommand:we,rest:We}=wn(oe),mt=we?.toLowerCase();if(!mt||!re.has(mt))return{blockedReason:K.blockedReason,expanded:de,tokens:oe};let gt=re.get(mt),ft=jR(gt);if(ft===null||ft.length===0)return{blockedReason:Jl,expanded:!0,tokens:oe};oe=["git",...ft,...We],de=!0}return{blockedReason:Jl,expanded:!0,tokens:oe}}function Of(G,U,j){return Ns(G,U,j).entries.some((K)=>K.key.toLowerCase()==="core.sshcommand")}function wn(G){if(G.length===0)return{subcommand:null,rest:[]};let U=G[0];if((U?kt(U).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let K=1;while(K<G.length){let re=G[K];if(!re)break;if(re==="--"){let oe=G[K+1];if(oe&&!oe.startsWith("-"))return{subcommand:oe,rest:G.slice(K+2)};return{subcommand:null,rest:G.slice(K+1)}}if(!re.startsWith("-"))return{subcommand:re,rest:G.slice(K+1)};K+=vn.has(re)?2:1}return{subcommand:null,rest:[]}}function zR(G){let U=new Map;for(let j of G){let K=j.key.toLowerCase();if(!K.startsWith("alias."))continue;let re=K.slice(6);if(re!=="")U.set(re,j.value)}return U}function Ns(G,U,j){if(G.length===0)return{blockedReason:null,entries:[]};let K=G[0];if((K?kt(K).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let oe=BR(U,j);return{blockedReason:oe.blockedReason,entries:[...oe.entries,...$R(G,U,j)]}}function $R(G,U,j){let K=[],re=1;while(re<G.length){let oe=G[re];if(!oe||oe==="--"||!oe.startsWith("-"))return K;if(oe==="-c"){let de=Ql(G[re+1]);if(de)K.push(de);re+=2;continue}if(oe.startsWith("-c")&&oe.length>2){let de=Ql(oe.slice(2));if(de)K.push(de);re++;continue}if(oe==="--config-env"){let de=If(G[re+1],U,j);if(de)K.push(de);re+=2;continue}if(oe.startsWith("--config-env=")){let de=If(oe.slice(13),U,j);if(de)K.push(de);re++;continue}if(vn.has(oe)){re+=2;continue}re++}return K}function BR(G,U){let j=UR(G,U),K=HR(G,U);return{blockedReason:j===null||K===null?Jl:null,entries:[...j??[],...K??[]]}}function UR(G,U){let j=Qn("GIT_CONFIG_PARAMETERS",G,U);if(j===void 0)return[];let K=[],re=gi(j);if(!re)return null;for(let oe of re){let de=Ql(oe);if(!de)return null;K.push(de)}return K}function HR(G,U){let j=Em(G,U);if(j.state==="absent")return[];if(j.state==="invalid")return null;let K=[];for(let re=0;re<j.count;re++){let oe=Qn(`GIT_CONFIG_KEY_${re}`,G,U)?.trim(),de=Qn(`GIT_CONFIG_VALUE_${re}`,G,U);if(!oe||de===void 0)return null;K.push({key:oe,value:de})}return K}function Ql(G){if(!G)return null;let U=G.indexOf("=");return{key:(U===-1?G:G.slice(0,U)).trim(),value:U===-1?void 0:G.slice(U+1)}}function If(G,U,j){let K=G?.indexOf("=")??-1;if(!G||K===-1)return null;return{key:G.slice(0,K).trim(),value:Qn(G.slice(K+1),U,j)}}function jR(G){let U=G?.trimStart();if(!U||U.startsWith("!"))return null;return gi(U)}var VR="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",KR="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",qR="git checkout --force discards uncommitted changes. Use 'git stash' first.",YR="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",ZR="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",XR="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",JR="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",QR="git switch --force discards uncommitted changes. Use 'git stash' first.",ex="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",tx="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",nx="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",rx="git reset --merge can lose uncommitted changes. Use 'git stash' first.",ox="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",ix="git rm --force removes tracked files from the working tree. Use 'git rm --cached' to keep the files, or 'git rm --dry-run' to preview first.",sx="git push --force destroys remote history. Use --force-with-lease for safer force push.",ax="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",lx="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",cx="git branch -D force-deletes without merge check. Use -d for safe delete.",dx="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",ux="git merge --abort discards merge conflict resolutions. Use 'git status' first.",mx="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",fx="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",px="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",gx="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",hx="git worktree remove --force can delete uncommitted changes. Remove --force flag.",yx=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),bx=new Set(["--recurse-submodules","--track","-t"]),ec=new Set(["-b","-B","-U"]),tc=new Set(["-c","-C"]),Cx=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function Dt(G,U){let j=G.split("=",1)[0]??G;return j.length>=4&&U.startsWith(j)&&j.startsWith("--")&&j.slice(2).length>=2}var yo=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function Df(G,U){let{subcommand:j,rest:K}=wn(G);if(!j)return null;switch(j.toLowerCase()){case"checkout":return pr(Sx(K,U));case"switch":return pr(Ex(K));case"restore":return pr(xx(K));case"reset":return wx(K);case"clean":return pr(Px(K));case"rm":return pr(Tx(K));case"push":return Gr(Ix(K));case"branch":return Gr(Mx(K));case"stash":return Gr(Fx(K));case"worktree":return Gr(Gx(K));case"rebase":return pr(Dx(K));case"merge":return pr(Nx(K));case"tag":return Gr(Lx(K));case"reflog":return Gr(Wx(K));default:return null}}function pr(G){return G?{...G,localDiscard:!0}:null}function Gr(G){return G?{...G,localDiscard:!1}:null}function Sx(G,U){let{index:j,before:K}=sn(G),re=fn(K,{shortOptsWithValue:ec});if(K.some((Se)=>Dt(Se,"--force"))||re.has("-f"))return Rt("git.checkout-force",qR);for(let Se of G){if(Se==="-b"||Se==="-B"||Se==="--orphan")return null;if(Dt(Se,"--pathspec-from-file"))return Rt("git.checkout-pathspec-from-file",ZR)}if(j!==-1){if(K.some((we)=>!we.startsWith("-")))return Rt("git.checkout-ref-path",YR);return Rt("git.checkout-double-dash",VR)}let oe=Rx(G);if(oe.length>=2)return Rt("git.checkout-ambiguous",XR);let de=oe[0];if(de===void 0||re.has("-d")||re.has("-t")||G.some((Se)=>Dt(Se,"--detach")||Dt(Se,"--track")))return null;if(vx(de)||U(de))return Rt("git.checkout-double-dash",KR);return null}function vx(G){return G==="."||G===".."||/^\.\.?[/\\]/.test(G)||/^([/\\]|[A-Za-z]:[/\\])/.test(G)||G.endsWith("/")||G.startsWith(":")||/[*?[]/.test(G)}function Ex(G){let{before:U}=sn(G);if(U.some((K)=>Dt(K,"--discard-changes")))return Rt("git.switch-discard-changes",JR);let j=fn(U,{shortOptsWithValue:tc});if(U.some((K)=>Dt(K,"--force"))||j.has("-f"))return Rt("git.switch-force",QR);return null}function Rx(G){let U=[],j=0;while(j<G.length){let K=G[j];if(!K)break;if(K==="--")break;if(!K.startsWith("-")){U.push(K),j++;continue}if(yx.has(K)){j+=2;continue}if(bx.has(K)){let re=G[j+1],oe=K==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"];j+=re&&!re.startsWith("-")&&oe.includes(re)?2:1;continue}j++}return U}function xx(G){let U=_x(G);if(U.isTerminal||!U.hasPathspec&&!U.hasPatch||!U.hasWorktree)return null;return U.hasExplicitLocation?Rt("git.restore-worktree",tx):Rt("git.restore-unstaged",ex)}function _x(G){let U=!1,j=!1,K=!0,re=!1,oe=(de)=>{if(!re)K=!1,re=!0;if(de!==void 0)K=de};for(let de=0;de<G.length;de++){let Se=G[de];if(Se===void 0)break;if(Se==="--"){U||=de+1<G.length;break}if(Se==="--pathspec-from-file"){U=!0,de++;continue}if(Se.startsWith("--pathspec-from-file=")){U=!0;continue}if(Se==="-h"||Se==="--help"||Se==="--version")return{hasPathspec:U,hasPatch:j,hasWorktree:K,hasExplicitLocation:re,isTerminal:!0};if(Se==="--staged"){oe();continue}if(Se==="--no-staged"){oe();continue}if(Se==="--worktree"){oe(!0);continue}if(Se==="--no-worktree"){oe(!1);continue}if(Se==="--patch"){j=!0;continue}if(Se==="--no-patch"){j=!1;continue}if(Cx.has(Se)){de++;continue}if(Se.startsWith("--"))continue;if(Se==="-"){U=!0;continue}if(!Se.startsWith("-")){U=!0;continue}for(let we=1;we<Se.length;we++){let We=Se.charAt(we);if(We==="h")return{hasPathspec:U,hasPatch:j,hasWorktree:K,hasExplicitLocation:re,isTerminal:!0};if(We==="S"){oe();continue}if(We==="W"){oe(!0);continue}if(We==="p"){j=!0;continue}if(We==="s"||We==="U"){if(we===Se.length-1)de++;break}}}return{hasPathspec:U,hasPatch:j,hasWorktree:K,hasExplicitLocation:re,isTerminal:!1}}function wx(G){let U=null;for(let j of G){if(Dt(j,"--hard")){U=Rt("git.reset-hard",nx);break}if(Dt(j,"--merge")){U=Rt("git.reset-merge",rx);break}}if(!U)return null;return Ax(G)?Gr(U):pr(U)}function Ax(G){for(let U of G){if(U==="--")return!1;if(!U.startsWith("-"))return!0}return!1}function Px(G){for(let j of G)if(j==="-n"||Dt(j,"--dry-run"))return null;let U=fn(G.filter((j)=>j!=="--"));if(G.some((j)=>Dt(j,"--force"))||U.has("-f"))return Rt("git.clean-force",ox);return null}function Tx(G){let U=!1,j=!1,K=!1;for(let re of sn(G).before){if(Dt(re,"--no-force")){U=!1;continue}if(Dt(re,"--force")){U=!0;continue}if(Dt(re,"--no-cached")){j=!1;continue}if(Dt(re,"--cached")){j=!0;continue}if(Dt(re,"--no-dry-run")){K=!1;continue}if(Dt(re,"--dry-run")){K=!0;continue}let oe=fn([re]);U||=oe.has("-f"),K||=oe.has("-n")}return U&&!j&&!K?Rt("git.rm-force",ix):null}function Ix(G){let{before:U,after:j}=sn(G),K=fn(U);if(U.some((de)=>Dt(de,"--mirror")))return Rt("git.push-mirror",lx);if(U.some((de)=>Dt(de,"--force"))||K.has("-f")||Mf(U,j).some(kx))return Rt("git.push-force",sx);if(U.some((de)=>Dt(de,"--delete"))||K.has("-d")||Mf(U,j).some(Ox))return Rt("git.push-delete",ax);return null}function Mf(G,U){return[...G.filter((j)=>j!==""&&!j.startsWith("-")),...U]}function kx(G){return G.startsWith("+")||G.includes(":+")}function Ox(G){return G.length>1&&G.startsWith(":")}function Mx(G){let{before:U}=sn(G),j=fn(U),K=j.has("-D")||j.has("-d")||U.some((oe)=>Dt(oe,"--delete")),re=j.has("-D")||j.has("-f")||U.some((oe)=>Dt(oe,"--force"));if(K&&re)return Rt("git.branch-force-delete",cx);return null}function Dx(G){let{before:U}=sn(G);return U.some((j)=>Dt(j,"--abort"))?Rt("git.rebase-abort",dx):null}function Nx(G){let{before:U}=sn(G);return U.some((j)=>Dt(j,"--abort"))?Rt("git.merge-abort",ux):null}function Lx(G){let{before:U}=sn(G);return fn(U).has("-d")||U.some((K)=>Dt(K,"--delete"))?Rt("git.tag-delete",mx):null}function Wx(G){return G[0]==="delete"?Rt("git.reflog-delete",fx):null}function Fx(G){for(let U of G){if(U==="drop")return Rt("git.stash-drop",px);if(U==="clear")return Rt("git.stash-clear",gx)}return null}function Gx(G){let{before:U}=sn(G);if(!U.includes("remove"))return null;let K=fn(U);if(U.some((re)=>Dt(re,"--force"))||K.has("-f"))return Rt("git.worktree-remove-force",hx);return null}import{dirname as s_,isAbsolute as a_,join as Yf,resolve as l_}from"node:path";var rc="TMPDIR",oc="IFS",Lf=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Wf=/^[A-Za-z_][A-Za-z0-9_]*$/,Ff=new Set(["export","typeset","declare","readonly"]),zx=new Set(["builtin","command","time"]),$x=new Set(["do","then","else"]),Bx=new Set(["do","then","case"]),Nf=new Set(["done","fi","esac"]),Ux=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function Gf(G,U){return G.map((j)=>j.provenance==="variable"&&Vf(j.text)?zf(j.text,U.shellAssignments):t(j))}function zf(G,U){return G.replace(Ux,(j,K,re)=>U.get(K??re??"")??j)}function Kn(G,U){let j=G.parts.every((re)=>re.provenance!=="literal"||!/[$`]/.test(re.raw));if(G.provenance!=="variable"||!j)return null;let K=zf(G.text,U);return/^[~-]/.test(K)||/[\s$`*?[]/.test(K)?null:K}function $f(G,U){return{env:G,effectiveEnvAssignments:Kx(G,U),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function Bf(G){return{env:G.env,effectiveEnvAssignments:G.effectiveEnvAssignments?new Map(G.effectiveEnvAssignments):void 0,shellAssignments:new Map(G.shellAssignments),bodyDepth:G.bodyDepth,bodyAssignments:new Set(G.bodyAssignments)}}function ic(G,U){let j=Hf(G,U),K=G[0]??"";if(Bx.has(K))U.bodyDepth+=1;if(K==="elif"||Nf.has(K))U.bodyDepth=Math.max(0,U.bodyDepth-1);if(Nf.has(K)&&U.bodyDepth===0)U.bodyAssignments.forEach((Se)=>{U.shellAssignments.delete(Se)}),U.bodyAssignments.clear();j.assignments.filter((Se)=>Se.persists).forEach((Se)=>{if(U.shellAssignments.set(Se.name,Se.value),U.bodyDepth>0)U.bodyAssignments.add(Se.name);sc(U,Se)});let re=j.commandIndex;if(re!==-1&&Ff.has(G[re]??""))G.filter((Se)=>Wf.test(Se)&&nc(Se)).forEach((Se)=>{qx(U,Se)});let oe=re===-1?-1:jf(G,re);if(oe===-1||G[oe]!=="unset")return;let de=Zx(G,oe);if(de===null)return;G.slice(de).forEach((Se)=>{if(U.bodyDepth>0){U.shellAssignments.set(Se,"");return}Yx(U,Se)})}function Uf(G,U){let j=Hf(G,U).assignments;if(j.length===0)return U.effectiveEnvAssignments;let K=new Map(U.effectiveEnvAssignments??[]);return j.forEach((re)=>{K.set(re.name,re.value)}),K}function Hf(G,U){let j=$x.has(G[0]??"")?1:0,K=G.findIndex((Se,we)=>we>=j&&!Vf(Se)),re=K!==-1&&Ff.has(G[jf(G,K)]??""),oe=Vx(U);return{assignments:G.flatMap((Se,we)=>{let We=Hx(Se,oe,U.env);if(!We)return[];if(K!==-1&&we>K&&!re&&!ms(We.name))return[];return oe.set(We.name,We.value),[{...We,persists:K===-1||re}]}),commandIndex:K}}function jf(G,U){let j=U;while(zx.has(G[j]??"")){j+=1;while(G[j]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(G[j]??""))return U;j+=1}}return j}function Vf(G){return On(G)!==null||Lf.test(G)}function Hx(G,U,j){return On(G)??jx(G,U,j)}function jx(G,U,j){let K=fs(G,j,U);if(K)return K;let re=G.match(Lf)?.[1];if(!re)return null;let oe=G.indexOf("=");return{name:re,value:`${U.has(re)?U.get(re):j.get(re)??""}${G.slice(oe+1)}`}}function nc(G){return G===rc||G===oc||Il(G)}function Vx(G){return new Map([...G.effectiveEnvAssignments??[],...G.shellAssignments])}function Kx(G,U){let j=[rc,oc].map((K)=>{let re=G.get(K);return re===void 0?null:[K,re]}).filter((K)=>K!==null);if(j.length===0)return U;return new Map([...j,...U??[]])}function sc(G,U){let j=new Map(G.effectiveEnvAssignments??[]);j.set(U.name,U.value),G.effectiveEnvAssignments=j}function qx(G,U){sc(G,{name:U,value:G.shellAssignments.get(U)??G.effectiveEnvAssignments?.get(U)??G.env.get(U)??""})}function Yx(G,U){if(!nc(U)&&!Wf.test(U))return;if(G.shellAssignments.set(U,""),ms(U)&&G.env.has(U)){let K=new Map(G.env);K.delete(U),G.env=K}if(!nc(U)||U===rc||U===oc||No(U)){sc(G,{name:U,value:""});return}if(!G.effectiveEnvAssignments?.has(U))return;let j=new Map(G.effectiveEnvAssignments);j.delete(U),G.effectiveEnvAssignments=j.size===0?void 0:j}function Zx(G,U){let j=U+1;while(j<G.length){let K=G[j];if(!K)return null;if(K==="--")return j+1;if(K==="-v"){j++;continue}if(K.startsWith("-"))return null;return j}return j}import{resolve as Xx}from"node:path";function Ls(G,U){return Tl.some((j)=>U?.has(j)||G.has(j))}function bo(G,U,j){if(!U)return{gitCwd:null,hasExplicitGitContext:!1};let K=j.realpath(Xx(U));if(K===null||!j.isDirectory(K))return{gitCwd:null,hasExplicitGitContext:!1};let re=K,oe=!1,de=1;while(de<G.length){let Se=G[de];if(!Se)break;if(Se==="--")break;if(!Se.startsWith("-"))break;if(Se==="-C"){let we=G[de+1];if(!we)return{gitCwd:null,hasExplicitGitContext:oe};let We=Kf(re,we,j);if(!We)return{gitCwd:null,hasExplicitGitContext:oe};re=We,de+=2;continue}if(Se.startsWith("-C")&&Se.length>2){let we=Kf(re,Se.slice(2),j);if(!we)return{gitCwd:null,hasExplicitGitContext:oe};re=we,de++;continue}if(Se==="--git-dir"||Se==="--work-tree"){oe=!0,de+=2;continue}if(Se.startsWith("--git-dir=")||Se.startsWith("--work-tree=")){oe=!0,de++;continue}de+=vn.has(Se)?2:1}return{gitCwd:re,hasExplicitGitContext:oe}}function Kf(G,U,j){try{let K=dr(G,U,j);return j.isDirectory(K)?K:null}catch{return null}}function qf(G,U,j){if(!U.localDiscard||!j.worktreeMode||Ls(j.environment.env,j.envAssignments))return null;let K=bo(G,j.cwd,j.environment.paths);if(!K.gitCwd||K.hasExplicitGitContext)return null;let re=j.environment.worktreeFacts(K.gitCwd);if(!re)return null;if(ac(G,j,re))return null;return{kind:"worktree",originalReason:U.reason,gitCwd:K.gitCwd}}function ac(G,U,j){let{subcommand:K,rest:re}=wn(G),oe=K?.toLowerCase();if(U.dynamicArguments||Jx(re)||r_(G,U.environment.env,U.envAssignments,j)||t_(re)||Qx(oe,re))return!0;return oe==="clean"&&n_(re)>1}function Jx(G){return G.some((U)=>/[$*?[]/.test(U))}function Qx(G,U){if(G==="checkout"){let{before:j}=sn(U),K=fn(j,{shortOptsWithValue:ec}),re=j.some((de)=>Dt(de,"--force"))||K.has("-f"),oe=K.has("-B")||j.some((de)=>de==="-B"||de.startsWith("-B"));return re&&oe}if(G==="switch"){let{before:j}=sn(U),K=fn(j,{shortOptsWithValue:tc}),re=j.some((de)=>Dt(de,"--force"))||j.some((de)=>Dt(de,"--discard-changes"))||K.has("-f"),oe=j.some((de)=>de==="-C"||de.startsWith("-C")||e_(de))||K.has("-C");return re&&oe}return!1}function e_(G){let U=G.split("=",1)[0]??G;return U==="--force-create"||U.length>=9&&"--force-create".startsWith(U)}function t_(G){return G.some((U)=>U.startsWith("--recurse-sub"))}function n_(G){let U=0;for(let j of G){if(j==="--force"){U++;continue}if(j.startsWith("-")&&!j.startsWith("--")){for(let K of j.slice(1))if(K==="f")U++}}return U}function r_(G,U,j,K){if(Qn("GIT_CONFIG_PARAMETERS",U,j)!==void 0)return!0;let re=Ns(G,U,j);if(re.blockedReason!==null)return!0;let oe=re.entries.map((Se)=>({key:Se.key.toLowerCase(),value:Se.value}));if(oe.some((Se)=>i_(Se.key)))return!0;let de=oe.filter((Se)=>Se.key==="submodule.recurse").at(-1);if(de)return de.value===void 0||o_(de.value);if(xm(j))return!0;return K.recursiveSubmodules}function o_(G){let U=G.toLowerCase();return U!=="false"&&U!=="no"&&U!=="off"&&U!=="0"}function i_(G){return G==="include.path"||G.startsWith("includeif.")&&G.endsWith(".path")}function Zf(G,U,j){let K=G.map((we)=>Kn(we,j.shellAssignments??new Map)??t(we)),re=j.environment.paths,oe=bo(K,j.cwd,re),de=j.originalCwd?re.realpath(l_(j.originalCwd)):null;if(U.id.startsWith("git.push-")||de===null||oe.gitCwd===null||oe.hasExplicitGitContext||Ls(j.environment.env,j.envAssignments))return null;let Se=U.id==="git.worktree-remove-force"?d_(G,j.shellAssignments,re):Xf(oe.gitCwd,re);if(Se===null||U.id!=="git.worktree-remove-force"&&!c_(Se,K,U,j)||!mo(Se,j.environment)||ws(Se,j.environment)||fo(de,Se)||fo(Se,de))return null;return{kind:"temp-root",originalReason:U.reason,gitCwd:oe.gitCwd}}function c_(G,U,j,K){let re=K.environment.paths,oe=Yf(G,".git");if(re.entryKind(oe)!=="present")return!1;if(re.isDirectory(oe))return!0;if(!j.localDiscard)return!1;let Se=K.environment.worktreeFacts(G);return Se!==null&&!ac(U,K,Se)}function d_(G,U,j){let K=wn(G.map(t)).rest,{before:re,after:oe}=sn(K.slice(K.indexOf("remove")+1)),de=[...re.filter((mt)=>!mt.startsWith("-")),...oe],Se=de.length===1?de[0]??"":"",we=G.find((mt)=>mt.text===Se),We=(we&&Kn(we,U??new Map))??Se;if(!a_(We)||/[\s$`*?[]/.test(We)||j.entryKind(We)!=="present"||!j.isDirectory(We))return null;return j.realpath(We)}function Xf(G,U){if(U.entryKind(Yf(G,".git"))!=="missing")return G;let j=s_(G);return j===G?null:Xf(j,U)}var m_="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.",f_=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function Ws(G,U){return Jf(G,U)}function Jf(G,U,j){let K=G.map(t),re=kf(K,U.environment.env,U.envAssignments),oe=re.blockedReason?Tt(Rt("git.alias-config",re.blockedReason),U.policy):null;if(oe)return oe;let de=re.tokens;if((Rm(U.envAssignments)||Of(K,U.environment.env,U.envAssignments))&&p_(de))return Rt("git.ssh-env",m_);let Se=Df(de,(We)=>{let mt=bo(K,U.cwd,U.environment.paths).gitCwd;return mt!==null&&U.environment.paths.entryKind(u_(mt,We))!=="missing"});if(!Se)return null;if(re.expanded||re.blockedReason)return Se;let we=qf(K,Se,U)??Zf(G,Se,U);if(!we)return Se;return j?.(we),null}function Qf(G,U){let j=null;return{match:Jf(G,U,(re)=>{j=re}),relaxation:j}}function p_(G){let{subcommand:U,rest:j}=wn(G),K=U?.toLowerCase();if(!K)return!1;if(f_.has(K))return!0;if(K==="archive")return sn(j).before.some((re)=>Dt(re,"--remote"));return K==="remote"&&g_(j)}function g_(G){return G.find((U)=>!h_(U))?.toLowerCase()==="update"}function h_(G){return G==="-v"||Dt(G,"--verbose")||Dt(G,"--no-verbose")}import{isAbsolute as V_}from"node:path";function ep(G,U,j,K){let re=G.slice(0,U),oe=G.slice(U+j);return K.startsWith(re)&&K.endsWith(oe)?K.slice(re.length,K.length-oe.length):null}function Fs(G,U,j){let K=(oe)=>`${oe.tokenIndex}\x00${oe.kind}\x00${oe.value}`,re=new Set(G.map(K));return Array.from(U).some((oe)=>j(oe).some((de)=>!re.has(K(de))))}var tp="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",y_="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.",b_="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",C_="rm -rf targeting root or home directory is extremely dangerous and always blocked.",S_="rm -rf in home directory is dangerous. Change to a project directory first.",np={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:C_},git_metadata_target:{id:"rm.git-metadata",reason:x},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:b_},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:S_},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:tp},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:y_},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:tp}};function Gs(G,U){let j=jn({...U,allowPaths:U.policy?.destructiveCommandAllowPaths,posixShell:!0}),K=G.map(t),re=Ms(K),oe=E_(G);for(let de of oe){let Se=ci(de.word);if(re&&Se.unsafeBraceExpansion){let we=Tt(Lr({kind:"outside_anchored_cwd"},j,U.policy,np),U.policy);if(we)return we;continue}for(let we of Se.expandedTargets??[de.text]){let We=cn(we),mt={targetIsLiteral:Se.expandedTargets!==void 0||Se.targetIsLiteral,tmpdirWordSplittingProtected:Se.tmpdirWordSplittingProtected};if(!re&&j.resolvedCwd&&Mr(We,j.resolvedCwd,j.protectedGitMetadata,re,j.environment,j.budget))return Rt("rm.git-metadata",x);if(!re)continue;for(let gt of v_(We,j,mt)){let ft=Lr(gt,j,U.policy,np),pt=Tt(ft,U.policy);if(pt)return pt}}}return null}function v_(G,U,j){let K=_n(G,U,j);if(K.kind==="cwd_self_target")return[K,_n(G,U,{...j,skipCwdSelf:!0})];if(K.kind!=="home_cwd_target")return[K];let re=_n(G,U,{...j,skipHomeCwd:!0});if(re.kind!=="cwd_self_target")return[K,re];return[K,re,_n(G,U,{...j,skipHomeCwd:!0,skipCwdSelf:!0})]}function E_(G){let U=[],j=!1;for(let K of G.slice(1)){let re=t(K);if(!re)continue;if(re==="--"){j=!0;continue}if(j){U.push({text:re,word:K});continue}if(!re.startsWith("-"))U.push({text:re,word:K})}return U}var gr={kind:"none"},zr={kind:"dynamic"},R_=new Set(["<","<<","<<-","<<<","<&","<>"]),op=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,x_=/^(?:[0-9]+|[@*])$/,__=cr.maxWords,ip=cr.maxInputLength;function sp(G){if(!G||kt(Mt(G.words[0]?.text??""))!=="printf")return;if(G.words.some((re)=>re.provenance!=="literal"))return;let U=G.words.slice(G.words[1]?.text==="--"?2:1),j=U[0]?.text;if(j===void 0)return"";let K=U.slice(1).map((re)=>re.text);if(j==="%s")return K.join("");if(j==="%s\\n"||j===`%s
|
|
17
|
+
`?Se+2:Se+1,ft=cl(G,gt,j,de.splice(0));if(!ft.terminated)return-1;Se=ft.next-1;continue}let We=Lu(G,Se,U,j,re);if(We!==null){Se=We;continue}if(!re.double&&G.startsWith("$((",Se)){let gt=mS(G,Se+3,j);if(gt===-1)return-1;Se=gt+1;continue}if(K===")"&&!re.double&&we==="<"&&G[Se+1]==="<"&&G[Se+2]!=="<"){let gt=G[Se+2]==="-",ft=Se+(gt?3:2);while(ft<j&&/[ \t]/.test(G[ft]??""))ft++;let pt=ll(G,ft,j);if(pt){de.push({delimiter:pt.delimiter,quotedDelimiter:pt.quoted,stripTabs:gt,attach:()=>{return}}),Se=pt.next-1;continue}}if(G.startsWith("$(",Se)&&!G.startsWith("$((",Se)){oe.push(re),re={single:!1,double:!1},Se++;continue}if(we==="("&&!re.double){oe.push(re),re={single:!1,double:!1};continue}if(we!==")"||re.double)continue;let mt=oe.pop();if(mt){re=mt;continue}return K==="))"&&G[Se+1]!==")"?-1:Se}return-1}function mS(G,U,j){let K=1,re={single:!1,double:!1};for(let oe=U;oe<j;oe++){let de=G[oe],Se=Lu(G,oe,U,j,re);if(Se!==null){oe=Se;continue}if(G.startsWith("$(",oe)&&!G.startsWith("$((",oe)){K++,oe++;continue}if(de==="("&&!re.double)K++;if(de!==")"||re.double)continue;if(K--,K===0)return G[oe+1]===")"?oe:-1}return-1}function Lu(G,U,j,K,re){let oe=G[U];if(oe==="\\"&&!re.single)return U+1;if(!re.double&&oe==="'")re.single=!re.single;if(!re.single&&oe==='"')re.double=!re.double;if(re.single)return U;if(re.double||oe!=="#"||!FS(G,U,j))return null;let de=U;while(de+1<K&&G[de+1]!==`
|
|
18
|
+
`&&G[de+1]!=="\r")de++;return de}function rs(G,U){let j=G[U];if(j===";")return";";if(j==="&")return G[U+1]==="&"?"&&":"&";if(j==="|")return G[U+1]==="|"?"||":G[U+1]==="&"?"|&":"|";return null}function fS(G,U){let j=G[U];if(j===">"){if(G[U+1]===">")return">>";if(G[U+1]==="&")return">&";return G[U+1]==="|"?">|":">"}if(j!=="<")return null;if(G.startsWith("<<<",U))return"<<<";if(G.startsWith("<<-",U))return"<<-";if(G[U+1]==="<")return"<<";if(G[U+1]==="&")return"<&";if(G[U+1]===">")return"<>";return"<"}function qo(G){let U=G.charCodeAt(0);if(U===32||U>=9&&U<=13)return!0;if(U<128)return!1;return/\s/u.test(G)}var Pr=Object.freeze({code:"unsupported-function-substitution",message:"${ list; } function substitutions run in the current shell and cannot be analyzed"});function Tr(G,U){if(G[U]!=="$")return!1;let j=ku(G,U+1);if(G[j]!=="{")return!1;let K=G[ku(G,j+1)]??"";return K==="|"||qo(K)}function pS(G,U,j){for(let K=G.indexOf("$",U);K!==-1&&K<j;K=G.indexOf("$",K+1))if(Tr(G,K))return!0;return!1}function gS(G){return G?.status==="limited"||(G?.issues??[]).some((U)=>U.code===Pr.code)}function ku(G,U){let j=U;while(G.startsWith("\\\n",j)||G.startsWith(`\\\r
|
|
19
|
+
`,j))j+=G[j+1]==="\r"?3:2;return j}function Wu(G,U){if(G.startsWith("$((",U))return{length:3,closing:"))"};if(G.startsWith("$(",U)||G.startsWith("<(",U)||G.startsWith(">(",U))return{length:2,closing:")"};return G[U]==="`"?{length:1,closing:"`"}:null}var hS=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"}),Fu=Object.freeze({code:"unsupported-parameter-expansion",message:"a line continuation inside ${ }, or a quote or backslash inside ${ } with a substitution in or after it, cannot be analyzed"}),yS=/\$\(|`|[<>]\(/g;function bS(G,U,j){let K=fl(j);return[...G.slice(U).matchAll(yS)].some((re)=>{let oe=U+re.index;return!K.some((de)=>oe>=de.start&&oe<de.end)})}function fl(G){return G.flatMap((U)=>{if(U.kind==="command")return[...U.redirections.flatMap((j)=>j.heredoc?[j.heredoc.bodySpan]:[]),...U.nested.flatMap((j)=>fl(j.nodes))];return U.kind==="group"||U.kind==="function"?fl(U.body.nodes):[]})}var SS=Object.freeze({code:"unsupported-backtick-escape",message:"a backslash escape inside backticks changes the command the shell runs and cannot be analyzed"});function Gu(G,U,j,K,re,oe,de,Se){if(G[U]!=="$"||G[U+1]!=="{")return null;let we=is(G,U+2,j),We=we.close===-1?j:we.close+1;if(we.close===-1)Se.push(hS);if(we.quoted&&we.substitutions.length>0||we.continued)Se.push(Fu);if(we.quoted)re.quotedExpansionEnd=Math.min(re.quotedExpansionEnd,We);let mt=we.substitutions.some((gt)=>{if(Tr(G,gt))return Se.push(Pr),!1;let ft=Zo(G,gt,We,K,re,oe);return ft!==null&&pl(ft,de,Se).limited});return{provenance:"variable",next:We,limited:mt}}function is(G,U,j){let K=[],re=!1,oe=!1,de=1,Se=U;while(Se<j){let we=G[Se];if(we==="$"&&Tr(G,Se))K.push(Se);if(we==="\\"||we==="'"||we==='"'){re=!0,oe||=we==="\\"&&G[Se+1]===`
|
|
20
|
+
`,Se+=we==="\\"?2:1;continue}let We=Wu(G,Se);if(We){K.push(Se);let mt=gl(G,Se+We.length,j,We.closing);if(mt===-1)break;Se=mt+We.closing.length;continue}if(we==="$"&&G[Se+1]==="{"){de++,Se+=2;continue}if(we==="}"&&--de===0)return{close:Se,substitutions:K,quoted:re,continued:oe};Se++}return{close:-1,substitutions:K,quoted:re,continued:oe}}function zu(G,U,j){if(G[U+1]==="{"){let re=is(G,U+2,j).close;return re===-1?j:re+1}if(G[U+1]==="$")return U+2;let K=U+1;while(K<j&&/[A-Za-z0-9_?@#!*-]/.test(G[K]??""))K++;return K===U+1?U+1:K}function CS(G,U,j){let K="",re=[],oe=U;while(oe<j){let de=G[oe];if(de==="'")return{text:K,next:oe+1,closed:!0,issues:re};if(de!=="\\"){K+=de??"",oe++;continue}let Se=vS(G,oe+1,j);if(K+=Se.text,Se.invalidCodePoint!==void 0)re.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${Se.invalidCodePoint}`});oe=Se.next}return{text:K,next:j,closed:!1,issues:re}}function vS(G,U,j){let K=G[U];if(!K||U>=j)return{text:"\\",next:U};let re=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
|
|
21
|
+
`],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(re.has(K))return{text:re.get(K)??K,next:U+1};if(K==="x")return es(G,U+1,j,16,2,U+1);if(K==="u")return es(G,U+1,j,16,4,U+1);if(K==="U")return es(G,U+1,j,16,8,U+1);if(/[0-7]/.test(K))return es(G,U,j,8,3,U+1);return{text:K,next:U+1}}function es(G,U,j,K,re,oe){let de=K===16?/[0-9a-fA-F]/:/[0-7]/,Se="",we=U;while(we<j&&Se.length<re&&de.test(G[we]??""))Se+=G[we],we++;if(!Se)return{text:G[oe-1]??"",next:oe};let We=Number.parseInt(Se,K);return We>1114111||We>=55296&&We<=57343?{text:"�",next:we,invalidCodePoint:We}:{text:String.fromCodePoint(We),next:we}}function os(G,U=!1){if(U)return"limited";if(G.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"||j.code==="unsupported-function-substitution"||j.code==="unsupported-backtick-escape"||j.code==="unclosed-parameter-expansion"||j.code==="unsupported-parameter-expansion"))return"invalid";return G.length>0?"partial":"complete"}function $u(G,U,j,K,re){let oe=zu(G,U,j);return{text:K+G.slice(U,oe),provenance:Ko(re,"variable"),next:oe}}function ES(G,U,j){let K=Qi(G),re=U,oe=!1,de=!1,Se=U;while(Se<j){let we=G[Se];if(we==="\\"&&!oe){Se+=2;continue}if(!de&&we==="'"){oe=!oe,Se++;continue}if(!oe&&we==='"'){de=!de,Se++;continue}if(oe){Se++;continue}let We=G.startsWith("$((",Se),mt=G.startsWith("$(",Se)&&!We,gt=!de&&(G.startsWith("<(",Se)||G.startsWith(">(",Se)),ft=we==="`";if(We||mt||gt||ft){let pt=We?3:ft?1:2,ht=We?"))":ft?"`":")",yt=gl(G,Se+pt,j,ht),bt=yt===-1?j:yt+ht.length;K.push(re,Se,"literal"),K.push(Se,bt,We?"arithmetic":"command-substitution"),Se=bt,re=bt;continue}if(we==="$"){let pt=zu(G,Se,j);if(pt>Se+1){K.push(re,Se,"literal"),K.push(Se,pt,"variable"),Se=pt,re=pt;continue}}if(!de&&(we==="*"||we==="?"||we==="[")){K.push(re,Se,"literal"),K.push(Se,Se+1,"glob"),Se++,re=Se;continue}Se++}return K.push(re,j,"literal"),K.parts}function Ko(G,U){if(U==="command-substitution"||G==="command-substitution")return"command-substitution";if(U==="arithmetic"||G==="arithmetic")return"arithmetic";if(U==="variable"||G==="variable")return"variable";if(U==="glob"||G==="glob")return"glob";return G}function RS(G,U,j){return U+1>=j||qo(G[U+1]??"")||rs(G,U+1)!==null}var xS=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),_S=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function wS(G){let U=0;while(U<=G.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(G[U]?.text??""))U++;if(U===G.length)return!0;let j=AS(G,U);if(j===void 0||j===null)return!1;U=j}return!1}function AS(G,U){let j=G[U]?.text.toLowerCase();if(j==="command")return PS(G,U);if(j==="env")return TS(G,U);if(j==="sudo")return IS(G,U);return}function PS(G,U){if(G[U+1]?.text==="-v")return null;for(let j=U+1;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return j+1;if(K==="-p"||K==="-v"||K==="-V"||/^-[pvV]+$/.test(K))continue;return j}return G.length}function TS(G,U){for(let j=U+1;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return j+1;if(xS.has(K)){if(G[j+1]===void 0)return null;j++;continue}if(K.startsWith("-u=")||K.startsWith("--unset=")||K.startsWith("-C")&&K.length>2||K.startsWith("--chdir=")||K.startsWith("-S")&&K.length>2||K.startsWith("--split-string=")||K.startsWith("-P"))continue;if(K.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(K))continue;return j}return G.length}function IS(G,U){for(let j=U+1;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return j+1;if(_S.has(K)){if(G[j+1]===void 0)return null;j++;continue}if(K.startsWith("-"))continue;return j}return G.length}function Bu(G,U,j,K){if(G.provenance!=="literal"||!G.raw.includes("{"))return;let re=Uu(G.raw,U,j,K,!0);if(!re)return;if("limited"in re)return{limited:!0};let oe=re.values.map((de)=>Hu(de,j));if(oe.some((de)=>de===null))return{limited:!0};return{words:[...new Set(oe.filter((de)=>de!==null&&de!==""))]}}function kS(G,U,j,K,re){if(U.provenance!=="literal"||!U.raw.includes("{"))return;let oe=Uu(U.raw,j,K,re,!1);if(!oe)return;if("limited"in oe){if(oe.limited==="expansions")return{limitCode:"depth-limit"};return{limitCode:oe.limited==="length"?"brace-expansion-limit":"word-limit"}}let de=oe.values.map((Se)=>Hu(Se,K));if(de.some((Se)=>Se===null))return;return{words:de.filter((Se)=>Se!==null&&Se!=="").map((Se)=>no(G,U.span.start,U.span.end,Se,"literal",!1))}}function Uu(G,U,j,K,re){let oe=[G],de=G.length,Se=0;while(!0){let we=oe.findIndex((pt)=>Ou(pt,re));if(we===-1)break;if(++Se>j)return{limited:"expansions"};let We=oe[we]??"",mt=Ou(We,re);if(!mt||mt.kind==="range")return{limited:"expansions"};let gt=mt.start+We.length-mt.end,ft=mt.alternatives.reduce((pt,ht)=>pt+gt+ht.length,0);if(de-We.length+ft>K)return{limited:"length"};if(oe.length-1+mt.alternatives.length>U)return{limited:"words"};oe.splice(we,1,...OS(We,mt)),de+=ft-We.length}return Se===0?void 0:{values:oe}}function Ou(G,U){let j=[],K,re=null,oe=!1;for(let de=0;de<G.length;de++){let Se=G[de];if(oe){oe=!1;continue}if(Se==="\\"&&re!=="'"){oe=!0;continue}if(Se===re){re=null;continue}if(re===null&&(Se==="'"||Se==='"')){re=Se;continue}if(re!==null)continue;if(Se==="{"){j.push({start:de,commas:[]});continue}if(Se===","&&j.length>0){j.at(-1)?.commas.push(de);continue}if(Se!=="}"||j.length===0)continue;let we=j.pop();if(!we)continue;let We=we.commas.length>0?{kind:"alternatives",start:we.start,end:de+1,commas:we.commas}:U&&DS(G.slice(we.start+1,de))?{kind:"range",start:we.start,end:de+1}:void 0;if(We&&(!K||We.start<K.start))K=We}if(!K||K.kind==="range")return K;return{kind:K.kind,start:K.start,end:K.end,alternatives:MS(G,K)}}function OS(G,U){return U.alternatives.map((j)=>`${G.slice(0,U.start)}${j}${G.slice(U.end)}`)}function MS(G,U){let j=[U.start,...U.commas,U.end-1];return j.slice(0,-1).map((K,re)=>G.slice(K+1,j[re+1]))}function DS(G){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(G)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(G)}function Hu(G,U){let j=`x${G}`,K=ml(j,0,j.length,{maxInputLength:j.length,maxWords:1,maxDepth:U},{wordsUsed:0,maxWords:1,quotedExpansionEnd:1/0},0);if(K.limited||K.issues.length>0||K.next!==j.length||K.word.provenance!=="literal")return null;return K.word.text.slice(1)}function NS(G,U,j,K){return pn({kind:"program",dialect:"posix",source:G.slice(U,j),span:{start:U,end:j},status:"limited",issues:[{code:K,message:"command structure exceeds parser limit"}],nodes:[]})}function ro(G,U,j,K,re){return{nodes:G,issues:[...U,{code:K,message:`command structure exceeds parser limit ${re}`}],next:j,closed:!1,limited:!0,pendingHeredocs:[]}}function ts(G,U,j){return{nodes:G,issues:U,next:j,closed:!1,limited:!0,pendingHeredocs:[]}}function dl(G){return G.wordsUsed++,G.wordsUsed<=G.maxWords}function LS(G,U,j){let K=G.slice(U,j),re=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(K)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(K),oe=re?.[1];if(!re||!oe)return;return{name:oe,braceIndex:U+re[0].lastIndexOf("{")}}function Yo(G){return G.some((U)=>{if(U.kind==="command")return U.redirections.some((j)=>j.heredoc)||U.nested.some((j)=>Yo(j.nodes));return(U.kind==="group"||U.kind==="function")&&Yo(U.body.nodes)})}function WS(G){return G.map((U)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${U.delimiter} was not found`}))}function ju(G){return G?.kind==="command"||G?.kind==="group"||G?.kind==="function"}function Mu(G,U){let j=G.at(-1);if(j?.kind!=="connector"||!Du.has(j.operator))return;U.push({code:"missing-command-after-connector",message:`connector ${j.operator} requires a following command`})}function Vu(G){return G?.provenance==="literal"&&!G.quoted&&G.raw===G.text&&cS.has(G.text)}function ul(G,U){let j=G.at(-1);if(!ju(j))return;if(j?.kind==="command"&&Vu(j.words[0]))return;U.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function FS(G,U,j){return U===j||/[\s;&|()]/u.test(G[U-1]??"")}var qu=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item","foreach-object","where-object"]),GS=new Set(["gc","cat","type","cp","mv","rm"]),Yu=["-rec","-for","-path","-literalpath","-whatif"],zS=/^\$env:\w/i,$S=/^(?:\$\{?\w+\}?|~)\\./;function Zu(G,U){let j=G.toLowerCase().replaceAll("`","");if(![...qu].some((re)=>j.includes(re))&&!(j.includes("rm")&&Yu.some((re)=>j.includes(re)))&&!j.includes("<#")&&!BS(j))return!1;let K=Sl(G,U);if(Xu(K))return!1;return K.issues.some((re)=>re.code==="unclosed-block-comment"||re.code==="comment-depth-limit")||bl(K).some(US)}function Xu(G){return G.nodes.some((U)=>{if(U.kind==="group")return Xu(U.body);if(U.kind!=="command")return!1;return U.redirections.some((j)=>j.operator==="<<")})}function BS(G){if(G.includes("$env:"))return!0;return G.includes("\\")&&(G.includes("$")||G.includes("~"))}function US(G){let U=G[0]==="&"||G[0]==="."?1:0,j=G[U]?.toLowerCase();if(j&&qu.has(j))return!0;let K=G.slice(U+1);if(j&&GS.has(j)&&K.some(HS))return!0;if(j!=="rm")return!1;return K.some((re)=>{let oe=re.toLowerCase().split(":",1)[0]??"";return Yu.some((de)=>oe.startsWith(de))})}function HS(G){return zS.test(G)||$S.test(G)}function Sl(G,U){let j={start:0,end:G.length};if(G.length>U.maxInputLength)return pn({kind:"program",dialect:"powershell",source:G,span:j,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${U.maxInputLength} UTF-16 code units`}],nodes:[]});let K=Cl(G,0,G.length,U,0);return pn({kind:"program",dialect:"powershell",source:G,span:j,status:YS(K.issues,K.limited),issues:K.issues,nodes:K.nodes})}function Cl(G,U,j,K,re,oe=!1){let de=[],Se=[],we=Xi(),We=0,mt=!1,gt=()=>{if(we.words.length===0&&we.redirections.length===0)return;let pt={start:we.start,end:we.end};Ji(de,we,{kind:"command",dialect:"powershell",source:G.slice(pt.start,pt.end),span:pt,words:we.words,redirections:we.redirections,nested:we.nested,displayText:we.words.map((ht)=>ht.text).join(" ")})},ft=U;while(ft<j){let pt=G[ft];if(!pt)break;if(oe&&pt==="}")return gt(),{nodes:de,issues:Se,next:ft+1,closed:!0,words:We,limited:mt};let ht=qS(G,ft,j,K.maxDepth);if(ht){if(ht.issue)Se.push(ht.issue);if(ht.limited)return gt(),{nodes:de,issues:Se,next:ht.next,closed:!1,words:We,limited:!0};ft=ht.next;continue}if(/\s/.test(pt)){if(pt==="\r"||pt===`
|
|
22
|
+
`){gt();let St=pt==="\r"&&G[ft+1]===`
|
|
23
|
+
`?ft+2:ft+1;de.push(hl(G,ft,St)),ft=St;continue}ft++;continue}let yt=em(G,ft);if(yt){gt(),de.push(hl(G,ft,ft+yt.length)),ft+=yt.length;continue}if(pt==="{"){if(gt(),re>=K.maxDepth)return Se.push(Qu(K.maxDepth)),{nodes:de,issues:Se,next:j,closed:!1,words:We,limited:!0};let St=Cl(G,ft+1,j,K,re+1,!0),Et=St.closed?St.next-1:St.next,Ct=pn({kind:"program",dialect:"powershell",source:G.slice(ft+1,Et),span:{start:ft+1,end:Et},status:St.limited?"limited":St.issues.length>0?"partial":"complete",issues:St.issues,nodes:St.nodes});if(de.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:ft,end:St.next}),body:Ct})),Se.push(...St.issues),!St.closed)Se.push({code:"unclosed-script-block",message:"PowerShell script block is not closed"});We+=St.words,mt||=St.limited,ft=St.next;continue}if(pt==="}"){gt(),de.push(hl(G,ft,ft+1)),ft++;continue}if(pt===">"||pt==="<"){we.start=we.start===-1?ft:we.start;let St=G[ft+1]===pt?ft+2:ft+1,Et=St;while(/[ \t]/.test(G[Et]??""))Et++;let Ct=Et<j?Ku(G,Et,j,K,re):void 0,Rt=Ct?.next??St;if(we.redirections.push(Object.freeze({kind:"redirection",operator:G.slice(ft,St),span:Object.freeze({start:ft,end:Rt}),...Ct?{target:Ct.word}:{}})),Ct)Se.push(...Ct.issues),we.nested.push(...Ct.nested),We+=Ct.words,mt||=Ct.limited;we.end=Rt,ft=Rt;continue}if(pt===","){we.start=we.start===-1?ft:we.start,we.words.push(al({text:",",raw:",",span:{start:ft,end:ft+1},provenance:"literal",quoted:!1})),we.end=++ft;continue}let bt=Ku(G,ft,j,K,re);if(we.start=we.start===-1?ft:we.start,we.end=bt.next,we.words.push(bt.word),Se.push(...bt.issues),we.nested.push(...bt.nested),We+=1+bt.words,mt||=bt.limited,We>K.maxWords)return Se.push({code:"word-limit",message:`command exceeds ${K.maxWords} words`}),gt(),{nodes:de,issues:Se,next:bt.next,closed:!1,words:We,limited:!0};ft=bt.next>ft?bt.next:ft+1}return gt(),{nodes:de,issues:Se,next:ft,closed:!oe,words:We,limited:mt}}function Ku(G,U,j,K,re){let oe="",de="literal",Se=!1,we=[],We=[],mt=0,gt=!1,ft=(ht)=>{let yt=jS(G,ht,j,K,re);return oe+=G.slice(ht,yt.next),We.push(yt.program),we.push(...yt.program.issues),mt+=yl(yt.program),gt||=yt.program.status==="limited",de="command-substitution",yt.next},pt=U;while(pt<j){let ht=G[pt];if(!ht||/\s/.test(ht)||em(G,pt)||ht===">"||ht==="<"||ht==="#")break;if(ht===",")break;if(ht==="`"){let yt=G[pt+1];if(!yt){we.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),pt++;break}oe+=yt,pt+=2;continue}if(G.startsWith("$(",pt)){pt=ft(pt);continue}if(ht==="'"){Se=!0,pt++;let yt=!1;while(pt<G.length){if(G[pt]==="'"&&G[pt+1]==="'"){oe+="'",pt+=2;continue}if(G[pt]==="'"){yt=!0,pt++;break}oe+=G[pt]??"",pt++}if(!yt)we.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(ht==='"'){Se=!0,pt++;let yt=!1;while(pt<j){let bt=G[pt];if(bt==="`"&&G[pt+1]){oe+=G[pt+1],pt+=2;continue}if(bt==='"'){yt=!0,pt++;break}if(G.startsWith("$(",pt)){pt=ft(pt);continue}if(bt==="$")de=G[pt+1]==="("?"command-substitution":"variable";oe+=bt??"",pt++}if(!yt)we.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(ht==="$")de=G[pt+1]==="("?"command-substitution":"variable";if(ht==="@"&&pt===U)de="variable";oe+=ht,pt++}return{word:no(G,U,pt,oe,de,Se,de==="literal"?void 0:VS(G,U,pt)),next:pt,issues:we,nested:We,words:mt,limited:gt}}function jS(G,U,j,K,re){let oe=Ju(G,U+2,j),de=oe===-1?j:oe,Se=oe===-1?j:oe+1;if(re>=K.maxDepth)return{program:pn({kind:"program",dialect:"powershell",source:G.slice(U+2,de),span:{start:U+2,end:de},status:"limited",issues:[Qu(K.maxDepth)],nodes:[]}),next:Se};let we=Cl(G,U+2,de,K,re+1),We=oe===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:pn({kind:"program",dialect:"powershell",source:G.slice(U+2,de),span:{start:U+2,end:de},status:we.limited?"limited":we.issues.length+We.length>0?"partial":"complete",issues:[...we.issues,...We],nodes:we.nodes}),next:Se}}function Ju(G,U,j){let K=1,re=!1,oe=!1;for(let de=U;de<j;de++){let Se=G[de];if(Se==="`"){de++;continue}if(!oe&&Se==="'"){if(re&&G[de+1]==="'"){de++;continue}re=!re;continue}if(!re&&Se==='"'){oe=!oe;continue}if(re)continue;if(G.startsWith("$(",de)){K++,de++;continue}if(!oe&&Se==="(")K++;if(Se!==")")continue;if(K--,K===0)return de}return-1}function yl(G){let U=0;for(let j of G.nodes){if(j.kind==="group")U+=yl(j.body);if(j.kind==="command"){U+=j.words.length;for(let K of j.nested)U+=yl(K)}}return U}function VS(G,U,j){let K=Qi(G),re=U,oe=!1,de=U;while(de<j){let Se=G[de];if(Se==="`"){de+=2;continue}if(Se==="'"){if(oe&&G[de+1]==="'"){de+=2;continue}oe=!oe,de++;continue}if(oe){de++;continue}if(G.startsWith("$(",de)){let we=Ju(G,de+2,j),We=we===-1?j:we+1;K.push(re,de,"literal"),K.push(de,We,"command-substitution"),de=We,re=We;continue}if(Se==="$"||Se==="@"&&de===U){let we=KS(G,de+1,j);K.push(re,de,"literal"),K.push(de,we,"variable"),de=we,re=we;continue}de++}return K.push(re,j,"literal"),K.parts}function KS(G,U,j){if(G[U]==="{"){let re=G.indexOf("}",U+1);return re===-1||re>=j?j:re+1}let K=U;while(K<j&&/[A-Za-z0-9_:?]/.test(G[K]??""))K++;return K}function Qu(G){return{code:"depth-limit",message:`command structure exceeds parser limit ${G}`}}function bl(G){return G.nodes.flatMap((U)=>{if(U.kind==="group")return bl(U.body);if(U.kind!=="command")return[];return[[...U.words,...U.redirections.flatMap((j)=>j.target?[j.target]:[])].sort((j,K)=>j.span.start-K.span.start).filter((j)=>j.text!==""&&j.raw!==",").map((j)=>j.text),...U.nested.flatMap(bl)]})}function em(G,U){for(let j of["&&","||",";","|"])if(G.startsWith(j,U))return j;return null}function qS(G,U,j,K){if(G[U]==="#"&&G[U+1]!==">"){let de=U+1;while(de<j&&G[de]!=="\r"&&G[de]!==`
|
|
24
|
+
`)de++;return{next:de,limited:!1}}if(!G.startsWith("<#",U))return null;let re=1,oe=U+2;while(oe<j){if(G.startsWith("<#",oe)){if(re++,re>K)return{next:j,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${K}`},limited:!0};oe+=2;continue}if(G.startsWith("#>",oe)){if(re--,oe+=2,re===0)return{next:oe,limited:!1};continue}oe++}return{next:j,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function YS(G,U){if(U)return"limited";if(G.some((j)=>j.code==="unclosed-block-comment"))return"invalid";return G.length>0?"partial":"complete"}function hl(G,U,j){return Object.freeze({kind:"connector",operator:G.slice(U,j),span:Object.freeze({start:U,end:j})})}function y(G,U="auto",j=cr){if(U==="powershell"||U==="auto"&&Zu(G.slice(0,j.maxInputLength),j))return Sl(G,j);return Nu(G,j)}function t(G){return G.provenance==="command-substitution"?G.raw:G.text}function ne(G,U){return G==="posix"?U:Kt(U.map((j)=>j.text))}function oo(G,U){return G&&G.provenance!=="unknown"?G.provenance==="literal":!/[$`*?[\]]/.test(U)}function Kt(G){return G.map((U)=>({kind:"word",text:U,raw:U,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function vl(G,U){return{value:G,work:U}}function _t(G,U){if(G.work)G.work.units=Math.min(Number.MAX_SAFE_INTEGER,G.work.units+1);return G.value[U]}function Yt(G){return G.value.length}function Xo(G,U,j=1){if(G)G.units=Math.min(Number.MAX_SAFE_INTEGER,G.units+U.length*j)}function xn(G,U){Xo(G,U)}function Ir(G){if(!G)return!1;let U=G.charCodeAt(0);return U>=48&&U<=57||U>=65&&U<=90||U===95||U>=97&&U<=122}function jt(G){if(!G)return!1;let U=G.charCodeAt(0);return U===9||U===10||U===11||U===12||U===13||U===32||U===160||U===65279||U===5760||U>=8192&&U<=8202||U===8232||U===8233||U===8239||U===8287||U===12288}function El(G){return G===`
|
|
25
|
+
`||G==="\r"||G==="\u2028"||G==="\u2029"}function Vt(G,U,j){if(U+j.length>Yt(G))return!1;for(let K=0;K<j.length;K++)if(_t(G,U+K)!==j[K])return!1;return!0}function Xn(G,U,j){return!Ir(_t(G,U-1))&&Vt(G,U,j)&&!Ir(_t(G,U+j.length))}function Jn(G,U){return Ir(_t(G,U-1))!==Ir(_t(G,U))}function on(G){return G===`
|
|
26
|
+
`||G===";"||G==="&"||G==="|"}function io(G){return G==="|"||G===";"}function ss(G,U,j){let K=vl(G,j);if(U==="rm")return ZS(K);if(U==="dd")return JS(K);return sm(K,!0)}function as(G,U,j){let K=vl(G,j);if(U==="rm")return QS(K);if(U==="reset-hard")return om(K,"--ha","rd");if(U==="reset-merge")return om(K,"--me","rge");if(U==="clean")return rC(K);if(U==="checkout")return iC(K);if(U==="push-force")return sC(K);if(U==="push-refspec")return aC(K);if(U==="push-delete")return lC(K);if(U==="branch")return cC(K);if(U==="tag")return mC(K);if(U==="restore")return fC(K);return sm(K,!1)}function ZS(G){let U=!1,j=!1,K=!1,re=-1;for(let oe=0;oe<=Yt(G);oe++){let de=_t(G,oe);if(!U){let we=_t(G,oe+2);if(Xn(G,oe,"rm")&&jt(we)&&we!==`
|
|
27
|
+
`)U=!0,oe++;continue}let Se=XS(G,oe);if(de===`
|
|
28
|
+
`||Se!==-1){if(U=!1,j=!1,K=!1,re=-1,Se!==-1)oe=Se-1;continue}if(de===";"||de==="&"||de==="|"||oe===Yt(G)){if(re>=0){let we=tm(G,re,oe);j||=we.recursive,K||=we.force}if(j&&K)return!0;U=!1,j=!1,K=!1,re=-1;continue}if(jt(de)){if(re<0)continue;if(Vt(G,re,"--")&&oe-re===2){U=!1,j=!1,K=!1,re=-1;continue}let we=tm(G,re,oe);if(j||=we.recursive,K||=we.force,j&&K)return!0;re=-1;continue}if(re<0)re=oe}return!1}function XS(G,U){if(_t(G,U)!=="\\"||_t(G,U-1)==="\\")return-1;if(Vt(G,U,String.raw`\n`))return U+2;if(Vt(G,U,String.raw`\x0a`)||Vt(G,U,String.raw`\x0A`))return U+5;if(Vt(G,U,String.raw`\u000a`)||Vt(G,U,String.raw`\u000A`))return U+7;return Vt(G,U,String.raw`\012`)?U+4:-1}function tm(G,U,j){if(nm(G,U,j,"recursive"))return{recursive:!0,force:!1};if(nm(G,U,j,"force"))return{recursive:!1,force:!0};if(_t(G,U)!=="-"||_t(G,U+1)==="-")return{recursive:!1,force:!1};let K=!1,re=!1;for(let oe=U+1;oe<j;oe++){let de=_t(G,oe);K||=de==="r"||de==="R",re||=de==="f"||de==="F"}return{recursive:K,force:re}}function nm(G,U,j,K){let re=j-U-2;if(re<1||re>K.length||!Vt(G,U,"--"))return!1;for(let oe=0;oe<re;oe++)if(_t(G,U+oe+2)!==K[oe])return!1;return!0}function JS(G){let U=!1;for(let j=0;j<Yt(G);j++){if(on(_t(G,j))){U=!1;continue}if(Xn(G,j,"dd")){U=!0,j++;continue}if(!U||!Xn(G,j,"of")||!Vt(G,j,"of=/dev/"))continue;let K=j+8;if(K<Yt(G)&&!jt(_t(G,K))&&_t(G,K)!=="'"&&_t(G,K)!=='"')return!0}return!1}function QS(G){let U=!1,j=!1,K=!1;for(let re=0;re<=Yt(G);){let oe=_t(G,re);if(re===Yt(G)||on(oe)){U=!1,j=!1,K=!1,re++;continue}let de=tC(G,re);if(de>=0){if(eC(G,de))return!0;let Se=de,we=!1;while(jt(_t(G,Se)))we||=_t(G,Se)===`
|
|
29
|
+
`,Se++;if(we)j=!1,K=!1;U=!0,re=Se;continue}if(!U){re++;continue}if(Vt(G,re,"--")&&(re===0||jt(_t(G,re-1)))&&(!_t(G,re+2)||jt(_t(G,re+2))||on(_t(G,re+2)))){U=!1,j=!1,K=!1,re+=2;continue}if(j||=Vt(G,re,"--recursive")&&Jn(G,re+11)||Rl(G,re,"recursive"),K||=Vt(G,re,"--force")&&Jn(G,re+7)||Rl(G,re,"force"),j&&K)return!0;re++}return!1}function Rl(G,U,j){if(!Vt(G,U,"--"))return!1;let K=0;while(K<=j.length){let re=_t(G,U+K+2);if(!re||jt(re)||on(re))break;if(re!==j[K])return!1;K++}return K>0&&Jn(G,U+K+2)}function eC(G,U){let j=U,K=!1,re=!1;while(j<Yt(G)){while(jt(_t(G,j)))j++;let oe=j;while(j<Yt(G)&&!jt(_t(G,j)))j++;if(_t(G,oe)!=="-"||j-oe===2&&Vt(G,oe,"--"))return!1;let de=rm(G,oe,"recursive"),Se=rm(G,oe,"force");if(K&&Se||re&&de)return!0;if(K||=de,re||=Se,_t(G,oe+1)==="-")continue;let we=nC(G,oe,j);if(we.combined||K&&we.forceAtBoundary||re&&we.recursiveAtBoundary)return!0;K||=we.recursive,re||=we.force}return!1}function rm(G,U,j){return Vt(G,U,`--${j}`)&&Jn(G,U+j.length+2)||Rl(G,U,j)}function tC(G,U){if(U>0&&Ir(_t(G,U-1)))return-1;let j=U;if(_t(G,j)==="\\")j++;if(_t(G,j)!=="r")return-1;if(j++,_t(G,j)==="\\")j++;if(_t(G,j)!=="m"||!jt(_t(G,j+1)))return-1;return j+1}function nC(G,U,j){let K=!1,re=!1,oe=!1,de=!1,Se=!1;if(_t(G,U)!=="-")return{recursive:K,force:re,recursiveAtBoundary:oe,forceAtBoundary:de,combined:Se};let we="";for(let We=U+1;We<j;We++){let mt=_t(G,We)??"",gt=(mt==="r"||mt==="f")&&Jn(G,We+1);K||=mt==="r",re||=mt==="f",oe||=mt==="r"&>,de||=mt==="f"&>,Se||=(we==="r"&&mt==="f"||we==="f"&&mt==="r")&>,we=mt}return{recursive:K,force:re,recursiveAtBoundary:oe,forceAtBoundary:de,combined:Se}}function om(G,U,j){return Qo(G,"reset",io,!0,(K)=>_t(G,K)==="-"&&so(G,K,U,j)?!0:K)}function rC(G){return Qo(G,"clean",io,!0,(U)=>{if(_t(G,U)!=="-")return U;if(so(G,U,"--fo","rce"))return!0;let j=Jo(G,U,io);for(let K=U+1;K<j;K++)if(_t(G,K)==="f")return!0;return j-1})}function ls(G,U,j){if(!Xn(G,U,"git"))return null;let K=U+3;if(!jt(_t(G,K)))return{commandEnd:-1,next:K};while(jt(_t(G,K)))K++;while(K<Yt(G)){if(on(_t(G,K)))return{commandEnd:-1,next:K};let re=Jo(G,K,on);if(Xn(G,K,j))return{commandEnd:K+j.length,next:re};if(_t(G,K)!=="-")return{commandEnd:-1,next:re};let oe=re-K===2&&Vt(G,K,"--"),de=oC(G,K,re);K=re;while(jt(_t(G,K)))K++;if(oe)return{commandEnd:Xn(G,K,j)?K+j.length:-1,next:Jo(G,K,on)};if(!de)continue;if(K>=Yt(G)||on(_t(G,K)))return{commandEnd:-1,next:K};K=Jo(G,K,on);while(jt(_t(G,K)))K++}return{commandEnd:-1,next:K}}function oC(G,U,j){for(let K of vn)if(j-U===K.length&&Vt(G,U,K))return!0;return!1}function iC(G){return im(G,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function sC(G){return Qo(G,"push",io,!0,(U)=>{if(_t(G,U)!=="-")return U;if(_t(G,U+1)==="f"&&!Ir(_t(G,U+2))&&!Vt(G,U+2,"-with-lease"))return!0;let j=am(G,U,"--fo","rce");if(j>=0&&!Vt(G,j,"-with-lease"))return!0;return U})}function aC(G){return Qo(G,"push",on,!1,(U)=>{if(jt(_t(G,U))&&_t(G,U+1)==="+"&&U+2<Yt(G)&&!on(_t(G,U+2))&&!jt(_t(G,U+2)))return!0;if(_t(G,U)===":"&&_t(G,U+1)==="+")return!0;return U})}function lC(G){return Qo(G,"push",on,!1,(U)=>{if(_t(G,U)==="-"&&so(G,U,"--de","lete"))return!0;if(jt(_t(G,U))&&_t(G,U+1)===":"&&U+2<Yt(G)&&!jt(_t(G,U+2))&&!on(_t(G,U+2)))return!0;return U})}function cC(G){let U=!1,j=!1,K=!1;for(let re=0;re<=Yt(G);re++){if(re===Yt(G)||on(_t(G,re))){if(j&&K)return!0;U=!1,j=!1,K=!1;continue}if(!U){let Se=ls(G,re,"branch");if(Se){U=Se.commandEnd>=0,re=Math.max(re,(U?Se.commandEnd:Se.next)-1);continue}}if(!U||_t(G,re)!=="-")continue;let oe=Jo(G,re,on),de=dC(G,re,oe);if(j||=de.deletion,K||=de.force,j&&K)return!0;re=oe-1}return!1}function dC(G,U,j){let K=!1,re=!1;for(let oe=U;oe<j;oe++){if(_t(G,oe)!=="-")continue;if(so(G,oe,"--de","lete"))K=!0;if(so(G,oe,"--fo","rce"))re=!0;if(_t(G,oe+1)==="-")continue;let de=oe+1,Se=!1,we=!1,We=!1;while(de<j&&uC(_t(G,de))){let mt=_t(G,de);Se||=mt==="d"||mt==="D",we||=mt==="f",We||=mt==="D",de++}if(!Jn(G,de))continue;K||=Se,re||=we||We}return{deletion:K,force:re}}function uC(G){if(!G)return!1;let U=G.charCodeAt(0);return U>=65&&U<=90||U>=97&&U<=122}function mC(G){return im(G,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function im(G,U){let j=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let K=0;K<Yt(G);K++){let re=_t(G,K),oe=j[j.length-1];if(!oe)return!1;let de=oe.escaped;if(oe.escaped=!de&&oe.quote!=="'"&&re==="\\",!de&&re==="'"&&oe.quote!=='"')oe.quote=oe.quote==="'"?"":"'";if(!de&&re==='"'&&oe.quote!=="'")oe.quote=oe.quote==='"'?"":'"';if(re==="$"&&_t(G,K+1)==="("&&(j.length===1||!de&&oe.quote!=="'")){j.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),K++;continue}if(!de&&!oe.quote&&j.length>1&&re==="("){oe.depth++;continue}if(!de&&!oe.quote&&j.length>1&&re===")"){if(oe.depth--,oe.depth===0)j.pop();continue}if(jt(re))oe.shortActive=!1,oe.hasShortFlag=!1;if(!oe.outerActive){let Se=ls(G,K,U.command);if(Se){oe.outerActive=Se.commandEnd>=0&&jt(_t(G,Se.commandEnd)),oe.shortActive=!1,oe.hasShortFlag=!1,K=Math.max(K,(oe.outerActive?Se.commandEnd:Se.next)-1);continue}}if(oe.outerActive&&re==="-"){if(so(G,K,U.longPrefix,U.longOptional))return!0;oe.shortActive||=!U.excludedShortStarts.includes(_t(G,K+1)??"")}if(oe.hasShortFlag||=oe.shortActive&&re===U.shortFlag,oe.hasShortFlag&&Jn(G,K+1))return!0;if(io(re))oe.outerActive=!1}return!1}function Qo(G,U,j,K,re){let oe=!1;for(let de=0;de<Yt(G);de++){let Se=_t(G,de),we=j(Se);if(!oe&&!we){let We=ls(G,de,U);if(We){oe=We.commandEnd>=0&&(!K||jt(_t(G,We.commandEnd))),de=Math.max(de,(oe?We.commandEnd:We.next)-1);continue}}if(oe){let We=re(de);if(We===!0)return!0;for(let mt=de;mt<=We;mt++)if(j(_t(G,mt)))oe=!1;de=We}if(we)oe=!1}return!1}function fC(G){let U=!1;for(let j=0;j<Yt(G);j++){if(El(_t(G,j))){if(U)return!0;U=!1;continue}if(!U){let K=ls(G,j,"restore");if(K){U=K.commandEnd>=0,j=Math.max(j,(U?K.commandEnd:K.next)-1);continue}}if(U&&_t(G,j)==="-"&&_t(G,j+1)==="-"&&(Vt(G,j+2,"staged")||Vt(G,j+2,"help")))U=!1}return U}function sm(G,U){let j=!1;for(let K=0;K<Yt(G);K++){let re=_t(G,K),oe=U?El(re):on(re);if(j&&jt(re)&&_t(G,K+1)==="-"&&Xn(G,K+2,"delete"))return!0;if(oe){j=!1;continue}if(Xn(G,K,"find"))j=!0,K+=3}return!1}function Jo(G,U,j){let K=U;while(K<Yt(G)&&!jt(_t(G,K))&&!j(_t(G,K)))K++;return K}function am(G,U,j,K){if(!Vt(G,U,j))return-1;let re=U+j.length;for(let oe=0;oe<K.length&&_t(G,re)===K[oe];oe++)re++;return Jn(G,re)?re:-1}function so(G,U,j,K){return am(G,U,j,K)>=0}function kn(G,U){Xo(U,G,2);let j=G.toLowerCase(),K=j.trimStart(),re=K.startsWith("echo ")||K.startsWith("rg "),oe=[{scan:"rm",label:"rm -rf"},{scan:"reset-hard",label:"git reset --hard"},{scan:"reset-merge",label:"git reset --merge"},{scan:"clean",label:"git clean -f"},{scan:"checkout",label:"git checkout --force"},{scan:"push-force",label:"git push --force"},{scan:"push-refspec",label:"git push --force"},{scan:"push-delete",label:"git push delete"},{scan:"branch",label:"git branch -D",caseSensitive:!0},{scan:"tag",label:"git tag -d"},{regex:/\bgit\s+stash\s+(drop|clear)\b/,label:"git stash drop/clear"},{regex:/\bgit\s+checkout\s+--\s/,label:"git checkout --"},{scan:"restore",label:"git restore without --staged"},{scan:"find",label:"find -delete",skipForEchoRg:!0},{regex:/\bdd\b[^\n|;&]*\bof=\/dev\/\S/,label:"dd of=/dev/",skipForEchoRg:!0},{regex:/\bmkfs(?:\.[a-z0-9_-]+)?\s+\/dev\/\S/,label:"mkfs /dev/",skipForEchoRg:!0},{regex:/\bshred\b\s+\S/,label:"shred",skipForEchoRg:!0},{regex:/\b(?:curl|wget|fetch|aria2c|https?|xhs?|ncat|netcat|nc)\b(?:[^\n|;&]|\\\n)*\|(?:\s|\\\n)*(?:(?:sudo|env|command|builtin)(?:\s+(?:-\S+|\w+=\S*))*\s+)?(?:[^\s|;&]*\/)?(?:ba|da|z|k)?sh(?![^\s;&|])/,label:"download piped to shell",skipForEchoRg:!0}];for(let de of oe){if(de.skipForEchoRg&&re)continue;let Se=de.caseSensitive?G:j;if(de.regex)xn(U,Se);if((de.regex?.test(Se)??!1)||de.scan&&as(Se,de.scan,U))return xt("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${de.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var pC=/^[A-Za-z_][A-Za-z0-9_]*=/;function cm(G,U,j){let K=G.words[0];if(!U||!K||G.words.length!==1||G.dialect!=="posix")return!1;if(!K.quoted||K.provenance!=="literal")return!1;let re=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(K.text)?.[1];if(!re)return!1;Xo(j,U.source,2);let oe={anchored:new RegExp(`^\\$\\{?${re}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${re}(?![A-Za-z0-9_])`)};return dm(U.nodes,K,oe)}function dm(G,U,j){return G.every((K)=>{if(K.kind==="connector")return!0;if(K.kind==="group"||K.kind==="function")return dm(K.body.nodes,U,j);if(K.kind==="unknown")return!j.loose.test(K.source);return gC(K,U,j)})}function gC(G,U,j){if(G.nested.some((re)=>j.loose.test(re.source)))return!1;let K=G.words.findIndex((re)=>!pC.test(re.text));return G.words.every((re,oe)=>re===U||lm(re.raw,j.anchored,oe!==K))&&G.redirections.every((re)=>(!re.heredoc||re.heredoc.quotedDelimiter||!j.loose.test(re.heredoc.body))&&(!re.target||lm(re.target.raw,j.anchored,!0)))}function lm(G,U,j){let K=!1,re=!1;for(let oe=0;oe<G.length;oe++){let de=G[oe];if(de==="\\"&&!K){oe++;continue}if(!re&&de==="'"){K=!K;continue}if(!K&&de==='"'){re=!re;continue}if(K||de!=="$")continue;if(!U.test(G.slice(oe)))continue;if(!re||!j)return!1}return!0}var hC="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",yC="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",bC="This erases or repartitions a disk. Run disk erase and partition commands manually after confirming the target.",SC="This output redirect overwrites a disk device. Run device writes manually after confirming the target.",CC="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.",vC=new Set(["of=/dev/null","of=/dev/zero","of=/dev/full"]),um=/^(?:mkfs(?:\..+)?|mke2fs|newfs(?:_.+)?)$/,EC=new Set(["diskutil","wipefs","sgdisk","parted"]),RC=new Set(["erasedisk","erasevolume","reformat","partitiondisk","zerodisk","randomdisk","secureerase"]),xC=/^(?:-[^-]*[ao]|--all$|--offset(?:=|$))/,_C=new Set(["-p","--print","-i","--info","-v","--verify","-O","--print-mbr","-E","--end-of-largest","-F","--first-in-largest","-f","--first-aligned-in-largest","-D","--display-alignment","-L","--list-types","-P","--pretend","-b","--backup","-V","--version","-?","--help","--usage"]),wC=new Set(["p","v","O","E","F","f","D","L","P","V","?"]),AC=new Set(["i","b"]),PC=/^\/dev\/(?:r?disk\d|sd[a-z]|hd[a-z]|vd[a-z]|xvd[a-z]|nvme\d|mmcblk\d|md\d|dm-\d|loop\d|mapper\/|disk\/)/,TC=new Set([">",">|",">>","<>",">&"]),IC=new Set(["mklabel","mktable","mkpart","rm","resizepart"]);function mm(G){return G==="dd"||G==="shred"||um.test(G)||EC.has(G)}function kC(G,U){let j=U.some((K)=>K.startsWith("/dev/"));if(G==="diskutil"){let K=U.find((re)=>!re.startsWith("-"));return K!==void 0&&RC.has(K.toLowerCase())}if(G==="wipefs")return j&&U.some((K)=>xC.test(K));if(G==="sgdisk")return j&&U.some((K)=>K.startsWith("-")&&!OC(K));return G==="parted"&&j&&U.some((K)=>IC.has(K.toLowerCase()))}function OC(G){if(_C.has(G.split("=",1)[0]??G))return!0;if(G.startsWith("--"))return!1;let U=G.slice(1).split("");return AC.has(U[0]??"")||U.every((j)=>wC.has(j))}function fm(G,U){let j=U.slice(1);if(G==="dd"&&j.some((K)=>/^of=\/dev\/.+/.test(K)&&!vC.has(K)))return xt("dd.device-write",hC);if(um.test(G)&&j.some((K)=>K.startsWith("/dev/")))return xt("mkfs.device",yC);if(kC(G,j))return xt("disk.erase",bC);if(G==="shred"&&j.length>0)return xt("shred.target",CC);return null}function pm(G){return G.some((U)=>TC.has(U.operator)&&U.target?.provenance==="literal"&&PC.test(U.target.text))?xt("redirect.block-device",SC):null}import{isAbsolute as MC,resolve as gm}from"node:path";function ei(G,U,j,K){let re=MC(G)?gm(G):U?gm(U,G):void 0;if(!re)return;try{return Wt(re,j,K)}catch{return re}}function hm(G){return!["/dev","/proc","/sys"].some((U)=>G===U||G.startsWith(`${U}/`))}var ao="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",ti="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.",_l=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),DC=new Set(["-p","--print"]),NC=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),LC=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"])]]),WC=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),FC=new Map([["python",new Set(["m"])]]),GC=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"])]]),zC=new Set(["always","default","never"]),$C=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),BC=/\\\r?\n/g,UC=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 ym(G){return ds(G).code}function cs(G){return ds(G).sources}function bm(G){return UC.get(Al(G))??[]}function ds(G){let U=Al(G[0]??"");if(!_l.has(U))return{code:null,sources:[],optionsOpen:!1};let j=[],K=[],re=!0;for(let oe=1;oe<G.length;oe++){let de=G[oe];if(de===void 0)break;if(de==="--")return Wn(U,j,K,re,G[oe+1]===void 0?void 0:oe+1,G[oe+1]);if(de===""||de==="-"||!de.startsWith("-"))return Wn(U,j,K,re,oe,de);if(U==="node"&&DC.has(de)){let gt=G[oe+1];if(gt===void 0)return Wn(U,j,K,re);if(gt.startsWith("-"))continue;j.push({tokenIndex:oe+1,value:gt}),K.push({tokenIndex:oe+1,kind:"inline-code",value:gt}),oe++;continue}if(jC(U,de)){let gt=G[oe+1];if(gt===void 0)return Wn(U,j,K,re);if(j.push({tokenIndex:oe+1,value:gt}),K.push({tokenIndex:oe+1,kind:"inline-code",value:gt}),U==="python")return Wn(U,j,K,re);oe++;continue}let Se=/^--eval=(.*)$/s.exec(de);if(VC(U)&&Se){let gt=Se[1]??"";j.push({tokenIndex:oe,value:gt}),K.push({tokenIndex:oe,kind:"inline-code",value:gt});continue}if(U==="node"){let gt=HC(de);if(gt){if(gt.attached){if(re&&=gt.value!=="",gt.value!=="")K.push({tokenIndex:oe,kind:"module-file",value:gt.value});continue}let ft=G[oe+1];if(ft===void 0||ft.startsWith("-"))return re=!1,Wn(U,j,K,re);K.push({tokenIndex:oe+1,kind:"module-file",value:ft}),oe++;continue}}if(U==="python"&&de.startsWith("--check-hash-based-pycs=")||U==="node"&&(de==="--conditions="||de==="--diagnostic-dir="||de==="--title=")||U==="ruby"&&(de==="--disable="||de==="--enable="))return Wn(U,j,K,re);if(GC.get(U)?.has(de)){let gt=G[oe+1];if(gt===void 0||gt.startsWith("-")&&!(U==="ruby"&&$C.has(de))||U==="python"&&!zC.has(gt))return Wn(U,j,K,re);oe++;continue}if(de.startsWith("--"))continue;let we,We=!1;for(let gt=1;gt<de.length;gt++){let ft=de[gt];if(ft===void 0)break;if(FC.get(U)?.has(ft)){let pt=de.slice(gt+1),ht=pt||G[oe+1];if(ht!==void 0)K.push({tokenIndex:pt?oe:oe+1,kind:"module-file",value:ht});return Wn(U,j,K,re)}if(NC.get(U)?.has(ft)){we=de.slice(gt+1)||G[oe+1],We=gt+1===de.length;break}if(U==="node"&&ft==="r"){if(re&&=de==="-r",de==="-r"){let pt=G[oe+1];if(re&&=pt!==void 0&&!pt.startsWith("-"),re&&pt!==void 0)K.push({tokenIndex:oe+1,kind:"module-file",value:pt});oe++}break}if(U==="ruby"&&ft==="r"){let pt=de.slice(gt+1),ht=pt||G[oe+1];if(re&&=ht!==void 0,ht!==void 0)K.push({tokenIndex:pt?oe:oe+1,kind:"module-file",value:ht});if(!pt)oe++;break}if(U==="perl"&&(ft==="M"||ft==="m")){let pt=de.slice(gt+1);if(!pt){if(re=!1,gt+1===de.length)oe++;break}K.push({tokenIndex:oe,kind:"module-file",value:pt});break}if(LC.get(U)?.has(ft)){if(gt+1===de.length)oe++;break}if(WC.get(U)?.has(ft)&>+1<de.length)break}if(we===void 0)continue;let mt=We?oe+1:oe;if(j.push({tokenIndex:mt,value:we}),K.push({tokenIndex:mt,kind:"inline-code",value:we}),U==="python")return Wn(U,j,K,re);if(We)oe++}return Wn(U,j,K,re,void 0,void 0,!0)}function Wn(G,U,j,K,re,oe,de=!1){let Se=G==="node"?U.slice(-1):U,we=new Set(Se.map((mt)=>mt.tokenIndex)),We=j.filter((mt)=>mt.kind!=="inline-code"||we.has(mt.tokenIndex));if(K&&U.length===0&&re!==void 0&&oe!==void 0)We.push({tokenIndex:re,kind:"main-script",value:oe});return{code:(G==="node"?Se[0]?.value:Se.map((mt)=>mt.value).join(`
|
|
30
|
+
`))||null,sources:K?We:[],optionsOpen:K&&de}}function HC(G){for(let U of["--import","--loader","--experimental-loader","--require"]){if(G===U)return{attached:!1,value:""};if(G.startsWith(`${U}=`))return{attached:!0,value:G.slice(U.length+1)}}return}function wl(G,U){return Al(G)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(U)}function Al(G){let U=Ot(G).toLowerCase();return Wi.test(U)?"python":U}function jC(G,U){return _l.get(G)?.has(U)??!1}function VC(G){return _l.get(G)?.has("--eval")??!1}function ni(G,U,j=!1){let K=YC(G,U);if(!xl(K,U))return!1;xn(U,K);let re=qC(K);if(xl(re,U))return!0;if(xn(U,re),!Sm.test(re))return!1;return!j||KC(K,U)}function KC(G,U){if(/`|%x|\bqx\b/.test(G))return!0;let K=G.split(""),re=[];for(let we=0;we<G.length;we++){let We=G[we];if(We!=="'"&&We!=='"')continue;let mt=G.startsWith(We.repeat(3),we)?We.repeat(3):We,gt=we+mt.length,ft=gt;while(ft<G.length&&!G.startsWith(mt,ft))ft+=G[ft]==="\\"?2:1;if(ft>=G.length)return!0;re.push({start:gt,text:G.slice(gt,ft)}),K.fill(" ",we,ft+mt.length),we=ft+mt.length-1}let oe=K.join(""),de=Array.from(oe.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((we)=>Sm.test(we[1]??"")).map((we)=>{let We=we.index+we[0].length;return{start:We,end:us(oe,We)}});if(de.some((we)=>Pl(oe,we.start)))return!0;return re.some((we)=>{let We=/\b(?:system|exec|spawn|popen)\s*$/.test(oe.slice(0,we.start)),mt=de.some((gt)=>we.start>=gt.start&&we.start<gt.end);return(We||mt)&&xl(we.text,U)})}function us(G,U){let j=1;for(let K=U;K<G.length;K++){if(G[K]==="(")j++;if(G[K]===")")j--;if(j===0)return K}return G.length}function Pl(G,U){let j=0;for(let K=U;K<G.length;K++){let re=G[K]??"";if("([{".includes(re))j++;if(")]}".includes(re)&&j--===0)return!1;if(re===","&&j===0)return!1;if(/[A-Za-z_$]/.test(re))return!0}return!1}var Sm=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function qC(G){let U=[],j=0,K=0;while(K<G.length){let re=G[K];if(re!=="'"&&re!=='"'){K++;continue}let oe=G.startsWith(re.repeat(3),K)?re.repeat(3):re,de=K+oe.length;while(de<G.length&&!G.startsWith(oe,de))de+=G[de]==="\\"?2:1;if(de>=G.length)break;U.push(G.slice(j,K)," "),K=de+oe.length,j=K}return U.push(G.slice(j)),U.join("")}function xl(G,U){if(ss(G,"rm",U))return!0;for(let K of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(xn(U,G),K.test(G))return!0;if(ss(G,"dd",U))return!0;for(let K of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(xn(U,G),K.test(G))return!0;if(ss(G,"find",U))return!0;let j=G.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((K)=>(xn(U,G),j.some((re)=>as(re,K))))}function YC(G,U){return xn(U,G),G.replace(BC,"")}import{lstatSync as jv,readdirSync as Vv}from"node:fs";import{basename as Kv,isAbsolute as Vm,join as qv,relative as Km}from"node:path";import{isAbsolute as wm,parse as iv}from"node:path";import{dirname as ZC,isAbsolute as XC,parse as JC,sep as QC}from"node:path";function dr(G,U,j){if(sr(U))throw Error("Unsupported Windows namespace path");let K=XC(U)?JC(U).root:"",re=K||G;for(let oe of tv(K?U.slice(K.length):U)){if(oe===""||oe===".")continue;if(oe===".."){re=ZC(re);continue}let de=ev(re,oe),Se=j.entryKind(de),we=Se==="symlink"?j.realpath(de):de;if(Se==="missing"||we===null)throw Error(`Cannot resolve path component: ${de}`);re=we}return re}function ev(G,U){return G.endsWith("/")||G.endsWith("\\")?`${G}${U}`:`${G}${QC}${U}`}function tv(G){let U=process.platform==="win32"?/[\\/]+/:/\/+/;return G.split(U)}var Tl=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],nv=new Set(Tl),rv=1024,Cm=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),vm=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),ov=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ms(G){return nv.has(G)}function Il(G){return ms(G)||Cm.has(G)||vm.has(G)||No(G)}function Qn(G,U,j){return j?.has(G)?j.get(G):U.get(G)}function Em(G,U){let j=Qn("GIT_CONFIG_COUNT",G,U);if(j===void 0)return{state:"absent"};if(j==="")return{state:"valid",count:0};if(!/^\d+$/.test(j))return{state:"invalid"};let K=Number(j);return Number.isSafeInteger(K)&&K<=rv?{state:"valid",count:K}:{state:"invalid"}}function fs(G,U,j){let re=G.match(ov)?.[1];if(!re||!Il(re))return null;let oe=G.indexOf("=");return{name:re,value:`${Qn(re,U,j)??""}${G.slice(oe+1)}`}}function Rm(G){return _m(G,vm)}function xm(G){return _m(G,Cm)}function _m(G,U){if(!G)return!1;for(let j of G.keys())if(U.has(j))return!0;return!1}var Pm=/^[A-Za-z_][A-Za-z0-9_]*=/;function On(G){if(!Pm.test(G))return null;let U=G.indexOf("=");return{name:G.slice(0,U),value:G.slice(U+1)}}function ve(G){let U=new Map,j=0;while(j<G.length){let K=G[j];if(!K)break;let re=On(t(K));if(!re)break;U.set(re.name,re.value),j++}return{words:G.slice(j),envAssignments:U}}function Tm(G){let U=Dt(G);return G.includes("=")||U==="sudo"||U==="env"||U==="command"||U==="builtin"}function kr(G,U,j,K){if(!Tm(lo(G)))return{words:G,envAssignments:new Map,cwd:j,rewritten:!1};let re=new Set(G),oe=G,de=new Map,Se=new Map(K??[]),we=[],We=j;for(let gt=0;gt<a.wrapperPeelIterations.cap;gt++){let ft=Am(oe),pt=ve(oe);for(let[yt,bt]of pt.envAssignments)de.set(yt,bt),Se.set(yt,bt);if(oe=pt.words,oe.length===0)break;while(oe.length>0&&lo(oe).includes("=")&&!av(oe)){let yt=lv(lo(oe),Se,U.env)??fs(lo(oe),U.env,Se);if(yt)de.set(yt.name,yt.value),Se.set(yt.name,yt.value);oe=oe.slice(1)}if(oe.length===0)break;let ht=Dt(lo(oe));if(ht!=="sudo"&&ht!=="env"&&ht!=="command"&&ht!=="builtin")break;if(ht==="sudo"){let yt=dv(oe,U.paths,We);if(oe=yt.words,yt.cwd!==void 0)We=yt.cwd}if(ht==="env"){let yt=fv(oe,We,Se,U);if(we.push(...yt.envSplitValues??[]),oe=yt.words,yt.cwd!==void 0)We=yt.cwd;for(let[bt,St]of yt.envAssignments)de.set(bt,St),Se.set(bt,St)}if(ht==="command")oe=pv(oe);if(ht==="builtin")oe=oe.slice(Fn(oe,1)==="--"?2:1);if(Am(oe)===ft)break}let mt=ve(oe);for(let[gt,ft]of mt.envAssignments)de.set(gt,ft),Se.set(gt,ft);return{words:mt.words,envAssignments:de,cwd:We,envSplitValues:we.length>0?we:void 0,rewritten:sv(mt.words,re)}}function sv(G,U){return G.some((j)=>!U.has(j))}function Am(G){return G.map(t).join(" ")}function lo(G){let U=G[0];return U?t(U):""}function Fn(G,U){let j=G[U];return j?t(j):void 0}function av(G){return Pm.test(lo(G))}function lv(G,U,j){if(!G.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${U.get("TMPDIR")??j.get("TMPDIR")??""}${G.slice(8)}`}}var cv=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function dv(G,U,j){let K=1,re=j;while(K<G.length){let oe=Fn(G,K);if(!oe)break;if(oe==="--")return{words:G.slice(K+1),cwd:re};if(!oe.startsWith("-"))break;if(oe==="-D"||oe==="--chdir"){let de=Fn(G,K+1);re=de?ri(re,de,U):null,K+=2;continue}if(oe.startsWith("--chdir=")){re=ri(re,oe.slice(8),U),K++;continue}if(oe.startsWith("-D")&&oe.length>2){re=ri(re,oe.slice(2),U),K++;continue}if(oe==="-i"||oe==="--login"){re=null,K++;continue}if(cv.has(oe)){K+=2;continue}K++}return{words:G.slice(K),cwd:re}}var uv=new Set(["-i","-0","--null"]),mv=new Set(["-u","--unset","-C","--chdir","-P"]);function fv(G,U,j,K){let re=new Map,oe=[],de=U,Se=1,we=(We)=>({words:G.slice(We),envAssignments:re,cwd:de,envSplitValues:oe.length>0?oe:void 0});while(Se<G.length){let We=Fn(G,Se);if(!We)break;if(We==="--")return we(Se+1);if(We==="-i"||We==="--ignore-environment"||We==="-"){re.clear();for(let gt of j.keys())re.set(gt,"");re.set("TMPDIR",""),Se++;continue}if(uv.has(We)){Se++;continue}if(We==="-u"||We==="--unset"){let gt=Fn(G,Se+1);if(gt!==void 0)re.set(gt,"");Se+=2;continue}if(We.startsWith("-u")&&We.length>2&&!We.startsWith("-u=")){re.set(We.slice(2),""),Se++;continue}if(We.startsWith("--unset=")){re.set(We.slice(8),""),Se++;continue}let mt=We==="-S"||We==="--split-string"?{value:Fn(G,Se+1),consumed:2}:We.startsWith("-S")&&We.length>2?{value:We.slice(2),consumed:1}:We.startsWith("--split-string=")?{value:We.slice(15),consumed:1}:null;if(mt){if(mt.value!==void 0)oe.push(mt.value);return de=null,we(Se+mt.consumed)}if(mv.has(We)){if(We==="-C"||We==="--chdir"){let gt=Fn(G,Se+1);de=gt?ri(de,gt,K.paths):null}Se+=2;continue}if(We.startsWith("-u=")){Se++;continue}if(We.startsWith("-C")&&We.length>2||We.startsWith("--chdir=")){let gt=We.startsWith("--chdir=")?We.slice(8):We.startsWith("-C=")?We.slice(3):We.slice(2);de=ri(de,gt,K.paths),Se++;continue}if(We.startsWith("-P")){Se++;continue}if(We.startsWith("-")){Se++;continue}if(!On(We))break;while(Se<G.length){let gt=On(Fn(G,Se)??"");if(!gt)break;re.set(gt.name,gt.value),Se++}if(Fn(G,Se)==="--")Se++;return we(Se)}return we(Se)}function ri(G,U,j){if(U==="")return null;if(!G&&!wm(U))return null;let K=wm(U)?iv(U).root:j.realpath(G??"/");if(K===null)return null;try{return dr(K,U,j)}catch{return null}}function pv(G){if(Fn(G,1)==="-v")return[...Kt(["type"]),...G.slice(2)];let U=1;while(U<G.length){let j=Fn(G,U);if(!j)break;if(j==="-p"||j==="-v"||j==="-V"){U++;continue}if(j==="--")return G.slice(U+1);if(j.startsWith("-")&&!j.startsWith("--")&&j.length>1){if(!/^[pvV]+$/.test(j.slice(1)))break;U++;continue}break}return G.slice(U)}var gv=/['"\\$`{}#]/;function ps(G,U){if(G.some((K)=>gv.test(K)))return null;let j=[...G.flatMap((K)=>K.split(/\s+/).filter((re)=>re.length>0)),...U];return j.length<=64?j:null}function ur(G,U,j){return gs(G,U,j).tokens}function hv(G){let U=[],j="",K=0;while(K<G.length){let re=G.charAt(K);if(re==='"'||re==="'"){let oe=G.indexOf(re,K+1);if(oe===-1)return G.split(/\s+/).map((de)=>de.replace(/["']/g,"")).filter((de)=>de.length>0);j+=G.slice(K+1,oe),K=oe+1;continue}if(/\s/.test(re)){if(j.length>0)U.push(j);j="",K++;continue}j+=re,K++}if(j.length>0)U.push(j);return U}function mr(G,U,j,K=0){let re=gs(G,U,j),oe=(re.envSplitValues??[]).flatMap(hv);if(oe.length===0)return re.tokens;let de=[...oe,...re.tokens];if(K>=8)return de;return mr(de,U,j,K+1)}function gs(G,U,j,K){if(!Tm(G[0]??""))return{tokens:[...G],envAssignments:new Map,cwd:j};let re=kr(Kt(G),U,j,K);return{tokens:re.words.map(t),envAssignments:re.envAssignments,cwd:re.cwd,envSplitValues:re.envSplitValues}}var Ml=Symbol("adopt-as-operand"),yv=new Set(["env","sudo","command","builtin"]),bv=new Set(["&&","||","|&","|","&",";"]),Sv=new Set(["<<","<<<",">|"]),Im=new Set(["|","|&"]),Cv=/[*@#?$!_-]/,vv=/^\w+(?::\w+)*/,Ev=Object.freeze([]),oi=Object.freeze({kind:"scope",edge:"enter"}),ii=Object.freeze({kind:"scope",edge:"exit"}),Rv=Object.freeze([]),xv=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),si=new Set(["bash","sh","zsh","dash","ksh"]),_v=256,Nm=new WeakMap;function Lm(G,U){let j=U.status==="complete"?new Set(Ol(U)):new Set,K=Pv(G,j);if(Gi(K))return hs("unclosed-quote",K,U);let re={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},oe=Or(U,{source:K,suppressed:j,flags:re,depth:0,functions:new Map,powershell:U.dialect==="powershell"});if(re.limited)return hs("structural-limit",K,U);if(re.invalid)return hs("invalid",K,U);let de=hs("complete",K,U,re.assignmentFallbacks);return Nm.set(de,Object.freeze(oe)),de}function Ss(G,U,j,K,re){let oe=re.word??((ht)=>ht),de={cwd:U,variables:new Map,previous:null},Se=[],we=new Set,We=null,mt=[],gt=Wm(G),ft=gt.findLastIndex((ht)=>ht.kind==="operator"&&Im.has(ht.operator)),pt=ft!==-1&>.some((ht)=>ht.kind==="redirection"&&ht.operator==="<<"&&ht.body===void 0);for(let[ht,yt]of gt.entries()){let bt=pt||ht<=ft;if(yt.kind==="scope"){if(yt.edge==="enter"){mt.push({state:de,segment:[...Se],shellWords:new Set(we),pipeProducer:We});continue}let St=re.segment(Se,de,We,null,we,bt);if(St)return St;let Et=mt.pop();if(Et===void 0)throw Error("scope exit without a matching enter");de=Et.state,Se=Et.segment,we=Et.shellWords,We=Et.pipeProducer;continue}if(yt.kind==="operator"){if(!yt.boundary)continue;let St=re.segment(Se,de,We,yt.operator,we,bt);if(St)return St;de=wv(Se,de,j,K),We=Se.length>0&&Im.has(yt.operator)?Se:null,Se=[],we=new Set;continue}if(yt.kind==="redirection"){if(yt.fd!==void 0)we.add(Se.length-1);if(yt.target===void 0)continue;let St=re.redirection({operator:yt.operator,role:yt.role,targetOrder:yt.targetOrder,target:yt.target,...yt.body===void 0?{}:{body:yt.body,consumer:yt.consumer}},de,bt);if(St===Ml){we.add(Se.length),Se.push(oe(yt.target));continue}if(St)return St;continue}Se.push(oe(yt.text))}return re.segment(Se,de,We,null,we,pt)}function Cs(G){return Wm(G).flatMap((U)=>{if(U.kind==="word")return[{kind:"word",text:U.text}];if(U.kind==="operator")return[{kind:"operator",boundary:U.boundary}];if(U.kind==="redirection")return[{kind:"redirection",target:U.target}];return[]})}function gn(G,U){return G.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(j,K,re,oe)=>{let de=U.get(K);if(de===void 0)return j;let Se=re.startsWith(":")?de!=="":!0;if(re.endsWith("-"))return Se?de:gn(oe,U);return Se?gn(oe,U):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(j,K)=>U.get(K)??j).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(j,K)=>U.get(K)??j)}function ai(G){return G.length>0&&G.every((U)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(U))}function wv(G,U,j,K){let re=ai(G)?new Map([...U.variables,...Av(G,U.variables)]):U.variables,oe=ur([...G],j),de=Ot(oe[0]??"").toLowerCase()==="cd"?oe[1]:void 0;if(!de)return{...U,variables:re};if(de==="-"){if(U.previous===null)return{...U,variables:re};return{cwd:U.previous,variables:re,previous:U.cwd}}return{cwd:dn(gn(de,re),U.cwd,j,K),variables:re,previous:U.cwd}}function Av(G,U){return G.flatMap((j)=>{let K=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(j),re=K?.[2]?.startsWith("=")?K[2].slice(1):void 0;return K?.[1]!==void 0&&re!==void 0?[[K[1],gn(re,U)]]:[]})}function Wm(G){return Nm.get(G)??Ev}function Pv(G,U){return[...U].reduce((j,K)=>j.slice(0,K.start)+" ".repeat(K.end-K.start)+j.slice(K.end),G)}function hs(G,U,j,K=Rv){return Object.freeze({status:G,source:U,program:j,assignmentFallbacks:Object.freeze(K)})}function Or(G,U){return G.nodes.flatMap((j,K)=>Tv(j,G,K,U)).sort((j,K)=>j.start-K.start).flatMap((j)=>[...j.events])}function Tv(G,U,j,K){if(G.kind==="connector")return[{start:G.span.start,events:[Gn(Dv(G.operator))]}];if(G.kind==="unknown")return[{start:G.span.start,events:[Gn(G.source)]}];if(G.kind==="function")return K.functions.set(G.name,G.body),[];if(G.kind==="group"){let oe=G.style!=="subshell",de=K.source[G.span.end-1]===(oe?"}":")"),Se=oe?K:{...K,functions:new Map(K.functions)};return[{start:G.span.start,events:oe?[ys("{"),...Or(G.body,Se),...de?[ys("}")]:[]]:[oi,Gn("("),...Or(G.body,Se),...de?[Gn(")")]:[],ii]}]}let re=Fv(G,K.functions);if(re){if(K.depth>=cr.maxDepth||++K.flags.expansions>_v)return K.flags.limited=!0,[];return[{start:G.span.start,events:[...km(G,K),ys(";"),...Or(re,{...K,depth:K.depth+1}),ys(";")]},...Om(G,U,j,K)]}return[{start:G.span.start,events:km(G,K)},...Om(G,U,j,K)]}function km(G,U){return[...G.words.map((j)=>({start:j.span.start,events:Gm(j,G,U,!1)})),...G.redirections.map((j)=>({start:j.span.start,events:Iv(j,G,U)}))].sort((j,K)=>j.start-K.start).flatMap((j)=>j.events)}function Iv(G,U,j){let K=G.operator==="<<-"?"<<":G.operator,re=G.target?Gm(G.target,U,j,!0):[],oe=re[0],de=oe?.kind==="word"?oe.text:void 0;return[...G.fd===void 0?[]:[Dl(String(G.fd))],Object.freeze({kind:"redirection",operator:K,...G.fd===void 0?{}:{fd:G.fd},role:Nv(K),targetOrder:Sv.has(K)?"legacy-segment":"immediate",...de===void 0?{}:{target:de},...G.heredoc&&j.suppressed.has(G.heredoc.bodySpan)?{body:G.heredoc.body,consumer:$m(U)}:{}}),...de===void 0?re:re.slice(1)]}function Om(G,U,j,K){let re=G.redirections.filter((oe)=>oe.operator==="<<"||oe.operator==="<<-");return[...re.flatMap((oe)=>{let de=oe.heredoc;if(!de)return[];let Se=[Dl(de.delimiter),.../[\r\n]/.test(K.source[de.terminatorSpan.end]??"")?[Gn(";")]:[]];if(K.suppressed.has(de.bodySpan))return[{start:de.bodySpan.start,events:Se}];return[{start:de.bodySpan.start,events:[...Fm(K.source.slice(de.bodySpan.start,de.bodySpan.end),K),...Se]}]}),...re.some((oe)=>!oe.heredoc&&oe.target)?kv(U,j,K):[]]}function kv(G,U,j){let K=G.nodes.slice(U+1).find((re)=>re.kind==="connector");if(!K||K.span.end>=G.span.end)return[];return[{start:K.span.end,events:Fm(j.source.slice(K.span.end,G.span.end),j)}]}function Fm(G,U){if(U.depth>=cr.maxDepth)return U.flags.limited=!0,[];let j=y(G,"posix");if(j.status==="limited")return U.flags.limited=!0,[];let K={invalid:!1,limited:!1,expansions:U.flags.expansions,assignmentFallbacks:U.flags.assignmentFallbacks},re=Or(j,{source:G,suppressed:new Set,flags:K,depth:U.depth+1,functions:new Map,powershell:!1});return U.flags.limited||=K.limited,U.flags.expansions=K.expansions,re}function Gm(G,U,j,K){let re=[],oe={single:!1,double:!1},de="",Se=!1,we=()=>{let We=Se&&!K?Gn("glob"):de!==""||G.quoted&&re.length===0?Dl(de):void 0;if(We)re.push(We);de="",Se=!1};for(let We of G.parts){if(We.provenance!=="command-substitution"&&We.provenance!=="arithmetic"){for(let pt of kl(We.raw,oe,j.flags,j.powershell)){if(typeof pt==="string"){we(),re.push(Gn(pt));continue}de+=pt.text,Se||=pt.glob}continue}let mt=U.nested.find((pt)=>pt.span.start>=We.span.start&&pt.span.end<=We.span.end);if(oe.double){let pt=j.source.slice(We.span.start,We.span.end);de+=kl(pt,{single:!1,double:!0},j.flags,j.powershell).map((yt)=>typeof yt==="string"?yt:yt.text).join("");let ht=mt?Or(mt,j).filter((yt)=>yt.kind==="redirection"&&yt.body!==void 0):[];if(ht.length>0)re.push(oi,...ht,ii);continue}let gt=mt?Or(mt,j):[];if(We.raw.startsWith("`")){de+="${}",we(),re.push(oi,...gt,ii);continue}if(We.raw.startsWith("<(")||We.raw.startsWith(">(")){we(),re.push(We.raw.startsWith("<(")?Gn("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),oi,...gt,...We.raw.endsWith(")")?[Gn(")")]:[],ii);continue}let ft=We.raw.startsWith("$((")?2:1;de+="${}",we(),re.push(...Array.from({length:ft},()=>Gn("(")),...ft===1?[oi]:[],...gt,...We.raw.endsWith(")".repeat(ft))?Array.from({length:ft},()=>Gn(")")):[],...ft===1?[ii]:[])}return we(),re}function kl(G,U,j,K){let re=[],oe="",de=!1,Se=0;while(Se<G.length){let we=G[Se]??"";if(!U.single&&!U.double&&(we==="("||we===")")){re.push({text:oe,glob:de},we),oe="",de=!1,Se++;continue}if(K&&we==="`"&&!U.single){oe+=G[Se+1]??"",Se+=2;continue}if(U.single&&we==="'"){U.single=!1,Se++;continue}if(U.single){oe+=we,Se++;continue}if(U.double){if(we==='"'){U.double=!1,Se++;continue}if(!K&&we==="\\"){let We=G[Se+1]??"";oe+=['"',"\\","$"].includes(We)?We:`\\${We}`,Se+=2;continue}if(we==="$"){let We=Mm(G,Se,U,j,K);oe+=We.text,Se=We.next;continue}oe+=we,Se++;continue}if(we==="'"||we==='"'){U.single=we==="'",U.double=we==='"',Se++;continue}if(!K&&we==="\\"){let We=G[Se+1]??"";de||=We==="*"||We==="?",oe+=We,Se+=2;continue}if(we==="$"){let We=Mm(G,Se,U,j,K);oe+=We.text,Se=We.next;continue}de||=we==="*"||we==="?",oe+=we,Se++}return[...re,{text:oe,glob:de}]}function Mm(G,U,j,K,re){let oe=G[U+1];if(oe==="{"){let Se=re?Mv(G,U+2):is(G,U+2,G.length).close;if(Se===-1)return K.invalid=!0,{text:"",next:G.length};let we=G.slice(U,Se+1);return Ov(we,j,K,re),{text:we,next:Se+1}}if(oe!==void 0&&Cv.test(oe))return{text:`\${${oe}}`,next:U+2};let de=(re?vv:/^\w*/).exec(G.slice(U+1))?.[0]??"";return{text:`\${${de}}`,next:U+1+de.length}}function Ov(G,U,j,K){let re=G.slice(2,-1),oe=/^[A-Za-z_][A-Za-z0-9_]*/.exec(re)?.[0];if(!oe)return;let de=re.slice(oe.length),Se=[":=","="].find((We)=>de.startsWith(We));if(!Se)return;let we=kl(de.slice(Se.length),{...U},j,K);j.assignmentFallbacks.push(...we.flatMap((We)=>typeof We==="string"||!We.text?[]:[We.text]))}function Mv(G,U){let j=1,K=U;while(j>0&&K<G.length){if(G[K]==="{"&&G[K-1]==="$")j++;if(G[K]==="}")j--;K++}return j===0?K-1:-1}function Dv(G){return/^[\r\n]+$/.test(G)?";":G}function Gn(G){return Object.freeze({kind:"operator",operator:G,boundary:bv.has(G)})}function ys(G){return Object.freeze({kind:"operator",operator:G,boundary:!0})}function Dl(G){return Object.freeze({kind:"word",text:G})}function Nv(G){if(G==="<<"||G==="<<<")return"here-data";if(G==="<"||G==="<&")return"file-read";return"file-write"}function co(G){return xv.has(G)||/^python\d/.test(G)}var Lv=new Map([["sudo",new Set(["-u","-g","-h","-p","-C","-D","-r","-t","-T","-U","--user","--group","--host","--prompt","--chdir","--role","--type","--other-user"])],["env",new Set(["-u","-C","-P","-S","--unset","--chdir","--split-string"])]]);function zm(G,U){let j=U[0];if(j===void 0||!j.startsWith("-"))return U;let K=Lv.get(G)?.has(j)??!1;return zm(G,U.slice(K?2:1))}function bs(G){let U=G[0];if(U===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(U))return bs(G.slice(1));if(U==="uv"&&G[1]==="run")return bs(G.slice(2));if(!yv.has(U))return[...G];return bs(zm(U,G.slice(1)))}function $m(G){let U=Vo(G),j=G.words.findIndex((K)=>K.provenance==="literal"&&K.text===U);return bs(j<0?[]:G.words.slice(j).map((K)=>K.text))}function Wv(G){let U=$m(G)[0];if(U===void 0)return!1;let j=Ot(U).toLowerCase();return co(j)&&!si.has(j)}function Ol(G){return G.nodes.flatMap((U,j)=>{if(U.kind==="group"||U.kind==="function")return Ol(U.body);if(U.kind!=="command")return[];let K=U.nested.flatMap((Se)=>Ol(Se)),re=U.redirections.flatMap((Se)=>Se.heredoc?.quotedDelimiter?[Se.heredoc.bodySpan]:[]);if(Wv(U))return[...K,...re];let oe=G.nodes[j+1];if(oe?.kind==="connector"&&(oe.operator==="|"||oe.operator==="|&")||!zv(U))return K;return[...K,...re]})}function Fv(G,U){let j=Vo(G);return j===void 0?void 0:U.get(j)}function fr(G,U){return G!==void 0&&G.provenance==="literal"&&!G.quoted&&G.raw===G.text&&G.text===U}function Gv(G){if(fr(G.words[0],"git"))return fr(G.words[1],"commit");if(!fr(G.words[0],"gh")||!fr(G.words[2],"create"))return!1;return fr(G.words[1],"pr")||fr(G.words[1],"issue")}function zv(G){return(fr(G.words[0],"cat")||fr(G.words[0],"tee")||Gv(G))&&!G.words.some(Dm)&&!G.redirections.some((j)=>Dm(j.target))}function Dm(G){return G?.parts.some((U)=>U.provenance==="command-substitution"&&U.raw.startsWith(">("))??!1}var Bm=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Um=new Set([...Bm,"glob"]),$v=new Set([...Um,"folder","pattern","patterns"]);class b extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Hm(G){let U=Bv(),j=ie(G.input),K=[];if((G.route.kind==="command"||G.route.kind==="unknown")&&j)K.push({usage:"input-candidate",source:j});if(G.route.kind==="command"&&"command"in G&&G.command)K.push({usage:"declared-command",source:G.command});let re=K.reduce((oe,de)=>{let Se=oe.findIndex((mt)=>mt.source===de.source);if(Se!==-1){let mt=oe[Se];if(!mt)return oe;return oe[Se]={...mt,usages:[...mt.usages,de.usage]},oe}let we=G.route.kind==="command"?G.route.shell:process.platform==="win32"?"powershell":"posix",We=U.getCommandProgram(de.source,we);return oe.push({usages:[de.usage],source:de.source,program:We,shell:U.getShellSyntax(de.source,We)}),oe},[]);return{invocation:{toolName:G.toolName,route:G.route,context:G.context},commands:re,paths:Uv(G),store:U}}function hn(G,U){return G.commands.find((j)=>j.usages.includes(U))}function er(G,U){if(!G.includes("$"))return G;return pa(G,U)}function Bv(){let G=new Map,U=new WeakMap,j=(re,oe)=>{let de=`${oe}\x00${re}`,Se=G.get(de);if(Se)return Se;let we=y(re,oe);return G.set(de,we),we};return{getShellSyntax:(re,oe)=>{if(oe&&oe.source!==re)throw TypeError("Shell syntax source does not match command program source.");let de=oe??j(re,"posix"),Se=U.get(de);if(Se)return Se;let we=de.status==="limited"?{status:"structural-limit",source:re,program:de,assignmentFallbacks:[]}:Lm(re,de);return U.set(de,we),we},getCommandProgram:j}}function Uv(G){let U=G.route.kind==="grep"?Um:G.route.kind==="glob"?$v:Bm;return[...yd(G.input,U),...G.route.kind==="patch"||typeof G.input==="string"?Cd(G.input):[]]}var Hv=new Set(["-S","--suffix"]);function uo(G,U,j,K,re){if(G.status==="structural-limit")throw new b;if(G.status!=="complete")return re.findMalformedTarget(G.source);return Ss(G,U,j,K,{segment:(oe,de)=>re.findSegmentTarget(oe,de),redirection:(oe,de)=>oe.role==="file-write"&&re.isRedirectionTarget(gn(oe.target,de.variables),de)?oe.target:null})}function vs(G){let U=[],j=null,K=!1;for(let re=0;re<G.length;re++){let oe=G[re];if(oe===void 0)break;if(!K&&oe==="--"){K=!0;continue}if(!K&&(oe==="-t"||oe==="--target-directory")){j=G[++re]??null;continue}if(!K&&oe.startsWith("--target-directory=")){j=oe.slice(19);continue}if(!K&&oe.startsWith("-t")&&oe.length>2){j=oe.slice(2);continue}if(!K&&Hv.has(oe)){re++;continue}if(!K&&(oe.startsWith("--suffix=")||oe.startsWith("--backup=")))continue;if(!K&&oe.startsWith("-"))continue;U.push(oe)}return j?{sources:U,destination:j}:{sources:U.slice(0,-1),destination:U.at(-1)??null}}var x="Git metadata and hooks are protected. Ask the user before modifying them.";function qm(G,U,j,K){let re=G.invocation.context.executionCwd;if(!U)return null;if(G.invocation.route.kind==="patch"||G.invocation.route.kind==="path"||G.invocation.route.kind==="unknown"){if(Ii(G.invocation.toolName))return null;let Se=G.paths.find((we)=>jm(we,re,U,j,K,U.entries));return Se?{target:Se}:null}if(G.invocation.route.kind!=="command")return null;let oe=hn(G,"input-candidate");if(!oe)return null;let de=uo(oe.shell,re,j,K,{findSegmentTarget:(Se,we)=>eE(Se,we,U,j,K),isRedirectionTarget:(Se,we)=>jm(Se,we.cwd,U,j,K,U.markerFiles),findMalformedTarget:()=>null});return de?{target:de}:null}function Mr(G,U,j,K,re,oe,de=!1){if(!j)return!1;let Se=Rs(dn(G,U,re,oe)),we=Se.replace(/(\/\.?\*+)+$/,"");if(we!==Se&&we!==""){if(Nl(we,j))return!0;let We=de||Se.slice(we.length).includes("/."),mt=(gt)=>We?Es(gt,we):Yv(gt,we);if(j.markerFiles.some(mt))return!0;return K&&Ll(j).some(mt)}if(Nl(Se,j))return!0;return K&&Ll(j).some((We)=>Es(We,Se))}function Yv(G,U){let j=Km(U,G);if(j===""||j.startsWith("..")||Vm(j))return!1;return!j.split(/[\\/]/)[0]?.startsWith(".")}function Zv(G,U,j,K,re){return Mr(G,U,j,!0,K,re)}function Xv(G,U,j,K,re){if(!j)return!1;return Nl(Rs(dn(G,U,K,re)),j)}function jm(G,U,j,K,re,oe){let de=Rs(dn(G,U,K,re));return oe.includes(de)||Zm(de,j)}function Ym(G,U,j,K,re){if(!j)return!1;return j.hooksDirectories.some((oe)=>G.some((de)=>Es(oe,Rs(dn(de,U,K,re)))))}function Nl(G,U){return U.entries.includes(G)||U.directories.includes(G)||Zm(G,U)}function Zm(G,U){return U.hooksDirectories.some((j)=>Es(G,j))}var Jv=50000;function Xm(G,U){let j=[...new Set(Ll(G))];if(j.some((re)=>U(Kv(re))))return!0;let K=0;while(j.length>0){let re=j.pop()??"",oe=Qv(re);if(!oe)return!0;if(K+=oe.length,K>Jv)return!0;if(oe.some((de)=>U(de.name)))return!0;j.push(...oe.filter((de)=>de.isDirectory()).map((de)=>qv(re,de.name)))}return!1}function Qv(G){try{let U=jv(G,{throwIfNoEntry:!1});if(!U)return[];if(!U.isDirectory())return U.isSymbolicLink()?null:[];return Vv(G,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function Ll(G){return[...G.entries,...G.directories,...G.hooksDirectories]}function Es(G,U){let j=Km(U,G);return j===""||!/^\.\.(?:[\\/]|$)/.test(j)&&!Vm(j)}function Rs(G){return process.platform==="win32"?G.toLowerCase():G}function eE(G,U,j,K,re){if(ai(G))return null;let oe=mr([...G],K);if(Ot(oe[0]??"").toLowerCase()!=="mv")return null;let de=vs(oe.slice(1)),Se=de.sources.find((we)=>Zv(gn(we,U.variables),U.cwd,j,K,re));if(Se)return Se;return de.destination&&Xv(gn(de.destination,U.variables),U.cwd,j,K,re)?de.destination:null}import{isAbsolute as As,normalize as lE,parse as cE,posix as sf,resolve as Nr,sep as zl}from"node:path";import{isAbsolute as tE,join as Jm,normalize as tf,parse as nE,sep as Qm}from"node:path";var rE=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],oE=`
|
|
31
|
+
`;function li(G,U){if(Dr(G,U))return!0;if(!G.has("TMPDIR"))return!1;return!Wl(G.get("TMPDIR")??"",U)}function mo(G,U){if(G.has("TMPDIR"))return Wl(G.get("TMPDIR")??"",U);let j=Fl(G,U);if(j===void 0)return!0;return Wl(j,U)}function Fl(G,U){return rf(G,U,"TMPDIR")}function Wl(G,U){if(!G)return!1;if(sE(G))return!1;return fo(G,U)}function Dr(G,U){let j=rf(G,U,"IFS");return j!==void 0&&j!==""&&j!==oE}function fo(G,U){let j=xs(G,U.paths);if(j===null)return!1;return nf(U).some((K)=>po(j,K))}function ws(G,U){let j=xs(G,U.paths);if(j===null)return!1;return nf(U).some((K)=>_s(K)===_s(j))}var ef=new WeakMap;function nf(G){let U=ef.get(G);if(U)return U;let j=iE(G);return ef.set(G,j),j}function iE(G){let U=rE.map((K)=>xs(K,G.paths)??tf(K)),j=xs(G.tmpdir,G.paths);if(!j)return U;if(process.platform==="win32")return[...U,j];if(process.platform==="darwin"&&aE(j))return[...U,j];return U}function sE(G){return/[\s$`*?[]/.test(G)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(G)||/[+@!]\([^)]*\)/.test(G)}function rf(G,U,j){return G.has(j)?G.get(j):U.env.get(j)}function aE(G){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(G)}function xs(G,U){try{let j=tf(G);if(!tE(j))return j;let K=nE(j).root,re=j.slice(K.length).split(/[\\/]+/).filter(Boolean),oe=K;for(let de=0;de<re.length;de++){let Se=Jm(oe,re[de]??"");if(U.entryKind(Se)==="missing")return Jm(Se,...re.slice(de+1));let we=U.realpath(Se);if(we===null)return null;oe=we}return oe}catch{return null}}function po(G,U){let j=_s(G),K=_s(U);if(j===K)return!0;let re=K.endsWith(Qm)?K:`${K}${Qm}`;return j.startsWith(re)}function _s(G){return process.platform==="win32"?G.toLowerCase():G}var dE=process.platform==="win32",of=64,uE=16384;function Lr(G,U,j,K){if(G.kind==="temp_target")return null;let re=K[G.kind];if(G.kind==="dynamic_target"&&!Jt(j,re.id,U.strict))return null;if(G.kind==="within_anchored_cwd"&&!Jt(j,re.id,U.paranoid))return null;return xt(re.id,re.reason)}function ci(G){let U=Bu(G,of,of,uE);return{expandedTargets:U&&"words"in U?U.words:void 0,unsafeBraceExpansion:U!==void 0&&"limited"in U,targetIsLiteral:U===void 0&&G.provenance==="literal"&&(G.quoted||G.raw!==G.text),tmpdirWordSplittingProtected:mE(G)}}function mE(G){let U=G.parts.filter((j)=>j.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(j.raw));return U.length>0&&U.every((j)=>fE(G.raw,j.span.start-G.span.start))}function fE(G,U){let j=null,K=!1;for(let re=0;re<U;re++){let oe=G[re];if(K){K=!1;continue}if(oe==="\\"&&j!=="'"){K=!0;continue}if(j===oe){j=null;continue}if(j===null&&(oe==="'"||oe==='"'))j=oe}return j==='"'}function jn(G){let U=G.environment.home,j=G.environment.paths,K=G.budget??Pn();return{anchoredCwd:G.originalCwd??G.cwd??null,resolvedCwd:G.cwd??null,strict:G.strict??!1,paranoid:G.paranoid??!1,trustTmpdirVar:G.allowTmpdirVar??!0,posixShell:G.posixShell??!1,tmpdirWordSplittingUnsafe:G.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:G.trustedTmpdirValue??G.allowTmpdirVar??!0,environment:G.environment,allowRoots:SE(G.allowPaths,U,j,K),protectedGitMetadata:G.protectedGitMetadata,budget:K}}function _n(G,U,j={}){let K=j.targetIsLiteral??!1;if(!K&&U.tmpdirWordSplittingUnsafe&&!j.tmpdirWordSplittingProtected&&vE(G))return{kind:"outside_anchored_cwd"};let re=!K&&lf(G,U.posixShell);if(sr(G))return{kind:"outside_anchored_cwd"};if($l(G,K))return{kind:"root_or_home_target"};if(gE(G,U,K))return{kind:"root_or_home_target"};if(U.resolvedCwd&&Mr(G,U.resolvedCwd,U.protectedGitMetadata,!0,U.environment,U.budget,!U.posixShell))return{kind:"git_metadata_target"};if(hE(G,U.trustTmpdirVar,U.posixShell,re,K,j.tmpdirWordSplittingProtected??!1,U.trustedTmpdirValue,U.environment))return{kind:"temp_target"};if(re)return{kind:"dynamic_target"};if(CE(G,U,K))return{kind:"temp_target"};let oe=U.anchoredCwd;if(oe){if(!j.skipHomeCwd&&_E(oe,U.environment.home,U.environment.paths,U.budget))return{kind:"home_cwd_target"};if(!j.skipCwdSelf&&[U.resolvedCwd??oe,oe].some((de)=>wE(G,U.resolvedCwd??oe,U.environment.paths,U.budget,de)))return{kind:"cwd_self_target"};if(AE(G,oe,U.resolvedCwd??oe,re,K,U.environment.paths,U.budget))return{kind:"within_anchored_cwd"}}if(pE(G,U,re))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function pE(G,U,j){let K=G.trim();if(j||!U.resolvedCwd||!U.anchoredCwd||!K)return!1;if(As(K)||K.startsWith("~"))return!1;if(Bl(K))return!1;if(cf(U.resolvedCwd,U.anchoredCwd,U.environment.paths,U.budget))return!1;return fo(Nr(U.resolvedCwd,K),U.environment)}function af(G,U,j={}){let{containmentTarget:K,...re}=j;if(_n(G,U,re).kind!=="temp_target")return!1;let oe=G.trim();if(bE(oe))return!1;if(ws(oe,U.environment))return!1;return![U.anchoredCwd,U.resolvedCwd].some((de)=>cf(K??oe,de,U.environment.paths,U.budget))}function $l(G,U=!1){let j=G.trim(),K=sf.normalize(j),re=j.replace(/\\/g,"/"),oe=K==="/"?K:K.replace(/\/+$/,"");if(oe==="/"||oe.startsWith("/")&&oe.slice(1).split("/").every((de)=>/^\*+$/.test(de)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(re)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(re))return!0;if(!U&&(K==="~"||K==="~/"||K==="~/*"))return!0;if(!U&&(K==="$HOME"||K==="$HOME/"||K==="$HOME/*"))return!0;if(!U&&(K==="${HOME}"||K==="${HOME}/"||K==="${HOME}/*"))return!0;return!1}function gE(G,U,j){let K=G.trim(),re=j?K:K==="*"?".":K.endsWith("/*")?K.slice(0,-2):K;if(!re)return!1;try{let oe=As(re)?re:U.resolvedCwd?Nr(U.resolvedCwd,re):null;if(!oe)return!1;let de=yn(Wt(oe,U.environment.paths,U.budget));if(de===cE(de).root)return!0;return de===yn(Wt(U.environment.home,U.environment.paths,U.budget))}catch{return!1}}function yn(G){let U=lE(G);if(dE){if(U=U.replace(/\//g,"\\").toLowerCase(),U.length>3&&U.endsWith("\\"))U=U.slice(0,-1);return U}if(U.length>1&&U.endsWith("/"))U=U.slice(0,-1);return U}function hE(G,U,j,K,re,oe,de,Se){let we=G.trim();if(Bl(we))return!1;if(!K&&fo(we,Se))return!0;return(U||oe&&de)&&j&&!re&&yE(we,j)}function yE(G,U){return["$TMPDIR","${TMPDIR}"].some((j)=>{if(G===j)return!0;if(!G.startsWith(`${j}/`))return!1;return!lf(G.slice(j.length+1),U)})}function bE(G){let U=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(G);if(!U)return!1;return sf.normalize(`/${U[1]??""}`)==="/"}function Bl(G){return G.split(/[\\/]+/).includes("..")}function SE(G,U,j,K){if(!G?.length)return[];return G.flatMap((re)=>{let oe=Uo(re.trim(),U);if(!As(oe))return[];try{let de=Wt(oe,j,K);if(Ho(de,Wt(U,j,K)))return[];return[yn(de)]}catch{return[]}})}function CE(G,U,j){if(U.allowRoots.length===0)return!1;let K=G.trim();if(Bl(K))return!1;let re=j?K:Uo(K,U.environment.home),oe=U.resolvedCwd??U.anchoredCwd,de=As(re)?re:oe?Nr(oe,re):null;if(!de)return!1;try{let Se=yn(Wt(de,U.environment.paths,U.budget));return U.allowRoots.some((we)=>Se===we||Se.startsWith(we.endsWith(zl)?we:`${we}${zl}`))}catch{return!1}}function vE(G){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(G)}function lf(G,U=!1){return G.includes("$")||G.includes("`")||EE(G)||U&&RE(G)}function EE(G){let U=!1;for(let j of G){if(U){U=!1;continue}if(j==="\\"){U=!0;continue}if(j==="*"||j==="?"||j==="[")return!0}return!1}function RE(G){let U=!1;for(let j=0;j<G.length;j++){let K=G[j];if(U){U=!1;continue}if(K==="\\"){U=!0;continue}if(K==="{"&&xE(G,j)||(K==="+"||K==="@"||K==="!")&&G[j+1]==="(")return!0}return!1}function xE(G,U){let j=G.indexOf("}",U+1);if(j===-1)return!1;let K=G.slice(U+1,j);return K.includes(",")||K.includes("..")}function _E(G,U,j,K){try{return yn(Wt(G,j,K))===yn(Wt(U,j,K))}catch{try{return yn(G)===yn(U)}catch{return!1}}}function wE(G,U,j,K,re=U){if(re===U&&(G==="."||G==="./"||G===".\\"))return!0;try{return yn(Wt(Nr(U,G),j,K))===yn(Wt(re,j,K))}catch{try{return yn(Nr(U,G))===yn(re)}catch{return!1}}}function AE(G,U,j,K,re,oe,de){let Se=j??U;if(!re&&(G.startsWith("~")||G.startsWith("$HOME")||G.startsWith("${HOME}")))return!1;if(K)return!1;if(G.startsWith("/")||/^[A-Za-z]:[\\/]/.test(G))try{return Gl(G,U,oe,de)}catch{return!1}if(G.startsWith("./")||G.startsWith(".\\")||!G.includes("/")&&!G.includes("\\"))try{return Gl(Nr(Se,G),U,oe,de)}catch{return!1}if(G.startsWith("../"))return!1;try{return Gl(Nr(Se,G),U,oe,de)}catch{return!1}}function Gl(G,U,j,K){try{return df(Wt(G,j,K),Wt(U,j,K))}catch{return!1}}function cf(G,U,j,K){if(!U)return!1;try{return df(Wt(U,j,K),Wt(G,j,K))}catch{return!0}}function df(G,U){let j=yn(G),K=yn(U);return j.startsWith(`${K}${zl}`)||j===K}var PE=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),uf="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",TE="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.",mf="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",ff="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",IE="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",kE="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",OE={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:ff},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:x},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:mf},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:IE},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:uf},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:TE},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:uf}};function pf(G,U,j){return ME(G.words.map((K)=>({kind:"word",text:K.text,dynamic:K.provenance!=="literal"})),U,jn({...j,allowPaths:j.policy?.destructiveCommandAllowPaths}),j.policy)}function ME(G,U,j,K){let re=G.filter((we)=>we.kind==="word"),oe=NE(re),de=re[oe];if(!de||!PE.has(HE(de.text)))return null;let Se=DE(re.slice(oe+1));if(Se.whatIfProtected)return null;if(Jt(K,"powershell.remove-item-pipeline-dynamic-target",j.strict)&&U&&(Se.targets.length===0||Se.recursive))return xt("powershell.remove-item-pipeline-dynamic-target",kE);for(let we of Se.targets)if(!sr(we.text)&&$l(di(we.text)))return xt(Se.recursive&&Se.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",ff);for(let we of Se.targets)if(j.resolvedCwd&&Mr(di(we.text),j.resolvedCwd,j.protectedGitMetadata,Se.recursive,j.environment,j.budget,!0))return xt("powershell.remove-item-git-metadata",x);if(!Se.recursive||!Se.force)return null;if(Jt(K,"powershell.remove-item-recursive-force-dynamic-target",j.strict)&&(Se.hasDynamicTarget||Se.targets.length===0))return xt("powershell.remove-item-recursive-force-dynamic-target",mf);for(let we of Se.targets){let We=Lr(_n(di(we.text),j),j,K,OE);if(We)return We}return null}function DE(G){let U=[],j=!1,K=!1,re=!1,oe=!1,de=!1;for(let Se=0;Se<G.length;Se++){let we=G[Se];if(!we||we.kind!=="word")continue;if(LE(we))continue;if(de){U.push(Ul(we)),oe=oe||we.dynamic;continue}if(we.text==="--"){de=!0;continue}let We=FE(we.text);if(!We){U.push(Ul(we)),oe=oe||we.dynamic;continue}if(GE(We.name)){let mt=We.value?WE(We.value,we):G[++Se];if(mt?.kind==="word"){U.push(Ul(mt)),oe=oe||mt.dynamic;continue}oe=!0;continue}if(zE(We.name)){j=!0;continue}if($E(We.name)){K=!0;continue}if(BE(We.name))re=UE(We.value)}return{targets:U,recursive:j,force:K,whatIfProtected:re,hasDynamicTarget:oe}}function NE(G){let U=G[0];if(U?.kind==="word"&&U.text==="&"||U?.text===".")return G.length>1?1:0;return 0}function Ul(G){return{text:G.kind==="word"?G.text:"",dynamic:G.kind==="word"&&G.dynamic}}function LE(G){return G.kind==="word"&&G.text===","}function di(G){let U=G.replace(/\\/g,"/"),j=/^(?:\$env:(?:userprofile|home)|\$home|\$\{home\})(?=$|\/)/i.exec(U);return j?`$HOME${U.slice(j[0].length)}`:U}function WE(G,U){return{kind:"word",text:G,dynamic:U.kind==="word"&&(U.dynamic||G.includes("$"))}}function FE(G){if(!G.startsWith("-")||G==="-")return null;let U=G.slice(1),j=U.indexOf(":");if(j===-1)return{name:U.toLowerCase()};return{name:U.slice(0,j).toLowerCase(),value:U.slice(j+1)}}function GE(G){return"path".startsWith(G)||"literalpath".startsWith(G)}function zE(G){return"recurse".startsWith(G)}function $E(G){return G.length>=2&&"force".startsWith(G)}function BE(G){return G==="wi"||"whatif".startsWith(G)}function UE(G){if(G===void 0||G==="")return!0;let U=G.toLowerCase();return U==="$true"||U==="true"}function HE(G){return G.toLowerCase()}var go="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",Ps="Unsupported heredoc syntax",ui="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function ho(){return{id:"analysis.dynamic-shell-source",reason:ui,intent:"stop_and_explain"}}var gf="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var jE=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),VE=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),KE=new Set(["-o","--output","--query","--subscription"]),qE=new Set;function hf(G){if(G==="aws")return jE;if(G==="gcloud")return VE;if(G==="az")return KE;return qE}var YE=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),ZE=new Set;function yf(G){if(G==="git")return vn;if(G==="docker")return YE;return ZE}function A(G,U){if(G.length===0||U.length===0)return null;let j=Dt(G[0]??""),K=fn(G);for(let re of U){if(!QE(j,re.command))continue;if(re.match){if(XE(j,G,re.match))return bf(re);continue}if(!eR(j,G,re.subcommand))continue;if(nR(G,new Set(re.block_args),K))return bf(re)}return null}function bf(G){return{id:`custom.${G.name}`,reason:`[${G.name}] ${G.reason}`,intent:G.intent??"manual_only"}}function XE(G,U,j){let K=U.slice(1);if(j.exclude_args?.some((re)=>K.includes(re)))return!1;if(j.any_args&&!j.any_args.some((re)=>K.includes(re)))return!1;return JE(K,j.command_path,hf(G))}function JE(G,U,j){let K=0,re=!1;for(let oe of G){if(K>=U.length)return!0;if(re){re=!1;continue}if(oe.startsWith("-")){re=!oe.includes("=")&&j.has(oe);continue}if(oe!==U[K])return!1;K++}return K>=U.length}function QE(G,U){return G===Dt(U)}function eR(G,U,j){if(!j)return!0;return Sf(U,1,j,yf(G))}function Sf(G,U,j,K){let re=!1;for(let oe=U;oe<G.length;oe++){let de=G[oe];if(!de)continue;if(re){re=!1;continue}if(de==="--"){let Se=G[oe+1];if(Se&&!Se.startsWith("-"))return Se===j;return!1}if(K.has(de)){re=!0;continue}if(de.startsWith("-")){if(!de.includes("=")&&tR(G,oe,j,K))return!0;continue}return de===j}return!1}function tR(G,U,j,K){let re=G[U+1];if(!re||re.startsWith("-"))return!1;return Sf(G,U+2,j,K)}function nR(G,U,j){return G.some((K)=>U.has(K))||[...j].some((K)=>U.has(K))}var rR=new Set(["-e","--source"]),oR=new Set(["-F","-v","--assign","--field-separator"]),Cf=new Set(["-f","--file"]),iR=new Set(["print","printf","return"]),vf=[{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"}],sR="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 Ef(G,U,j){let K=!1;for(let re of aR(G)){let oe=lR(re,j);if(!oe)continue;for(let de of oe.commands){let Se=U(de);if(Se)return Se;if(de.includes("{}")||/[$`]/.test(de))K=!0}K||=oe.dynamic}return K?xt("awk.system-dynamic",sR):null}function jl(G){let U=[],j=!1,K=!1,re=!0,oe=!0;for(let de=1;de<G.length;de++){let Se=G[de];if(Se===void 0)break;if(re&&Se==="--"){re=!1;continue}if(re&&rR.has(Se)){j=!0;let we=G[de+1];if(oe&&=we!==void 0,we!==void 0)U.push({tokenIndex:de+1,kind:"inline-code",value:we});de++;continue}if(re&&Se.startsWith("--source=")){j=!0,U.push({tokenIndex:de,kind:"inline-code",value:Se.slice(9)});continue}if(re&&Se.startsWith("-e")&&Se.length>2){j=!0,U.push({tokenIndex:de,kind:"inline-code",value:Se.slice(2)});continue}if(re&&(oR.has(Se)||Cf.has(Se))){let we=G[de+1];if(oe&&=we!==void 0,Cf.has(Se)){if(K=!0,we!==void 0)U.push({tokenIndex:de+1,kind:"program-file",value:we})}de++;continue}if(re&&(Se.startsWith("-F")||Se.startsWith("-v")&&Se.slice(2).includes("=")))continue;if(re&&Se.startsWith("-f")&&Se.length>2){K=!0,U.push({tokenIndex:de,kind:"program-file",value:Se.slice(2)});continue}if(re&&(Se.startsWith("--assign=")||Se.startsWith("--field-separator=")))continue;if(re&&Se.startsWith("--file=")){K=!0,U.push({tokenIndex:de,kind:"program-file",value:Se.slice(7)});continue}if(re&&Se.startsWith("-")&&Se!=="-")continue;if(!j&&!K)U.push({tokenIndex:de,kind:"main-program",value:Se});return{sources:U,optionsOpen:!1}}return{sources:oe?U:[],optionsOpen:re&&oe}}function fi(G){return jl(G).sources}function aR(G){return fi(G).filter((U)=>U.kind!=="program-file").map((U)=>U.value)}function lR(G,U){xn(U,G);let j=G.includes("system")?Vl(G,U):null,K=cR(G,U);if(!j&&!K)return null;return{dynamic:!!j?.dynamic||!!K?.dynamic,commands:[...j?.commands??[],...K?.commands??[]]}}function Vl(G,U){xn(U,G);let j=[],K=!1,re=!1,oe=0;while(oe<G.length){let de=G[oe];if(de==='"'||de==="'"){oe=Is(G,oe,de)?.endIndex??oe+1;continue}if(de==="#"){oe=Rf(G,oe+1);continue}if(de==="/"&&xf(G,oe)){oe=_f(G,oe+1)??oe+1;continue}if(!G.startsWith("system",oe)){oe++;continue}let Se=oe;if(oe+=6,mi(G[Se-1])||mi(G[oe]))continue;let we=Ts(G,oe);if(G[we]!=="(")continue;we=Ts(G,we+1);let We=G[we];if(We!=='"'&&We!=="'"){K=!0,re=!0;continue}let mt=Is(G,we,We);if(!mt){K=!0,re=!0;continue}if(we=Ts(G,mt.endIndex),K=!0,G[we]!==")"){re=!0,oe=mt.endIndex;continue}j.push(mt.value),oe=we+1}if(!K)return null;return{dynamic:re,commands:j}}function cR(G,U){xn(U,G);let j=[],K=!1,re=!1,oe=0,de=0,Se=null,we=null,We=0;while(oe<G.length){let mt=G[oe];if(!mt)break;if(mt==='"'||mt==="'"){let pt=Is(G,oe,mt);if(pt&&We===de)we={...pt,startIndex:oe};We=pt?.endIndex??oe+1,oe=pt?.endIndex??oe+1;continue}if(mt==="#"){oe=Rf(G,oe+1),de=oe,Se=null,we=null,We=oe;continue}if(mt==="/"&&xf(G,oe)){let pt=_f(G,oe+1);We=pt??oe+1,oe=pt??oe+1;continue}if(`;
|
|
32
|
+
{}`.includes(mt)){oe++,de=oe,Se=null,we=null,We=oe;continue}if(Se===null&&(Hl(G,oe,"print")||Hl(G,oe,"printf")))Se=oe;if(mt!=="|"||G[oe-1]==="|"||G[oe+1]==="|"){if(!/\s/.test(mt))We=oe+1;oe++;continue}let gt=G[oe+1]==="&"?oe+2:oe+1,ft=Ts(G,gt);if(Hl(G,ft,"getline")){re=!0;let pt=mR(de,we,We);if(K||=pt===null,pt!==null)j.push(pt);We=gt,oe=gt;continue}if(pR(de,Se)){re=!0;let pt=uR(G,ft);if(!pt){K=!0,We=gt,oe=gt;continue}if(!dR(G,pt.endIndex)){K=!0,We=pt.endIndex,oe=pt.endIndex;continue}j.push(pt.value),We=pt.endIndex,oe=pt.endIndex;continue}We=gt,oe++}if(!re)return null;return{dynamic:K,commands:j}}function mi(G){return!!G&&/[A-Za-z0-9_]/.test(G)}function Ts(G,U){let j=U;while(/\s/.test(G[j]??""))j++;return j}function dR(G,U){let j=U;while(/[\t\f\v\r ]/.test(G[j]??""))j++;let K=G[j];return!K||`;
|
|
33
|
+
}#`.includes(K)}function Is(G,U,j){let K="",re=!1;for(let oe=U+1;oe<G.length;oe++){let de=G[oe];if(!de)break;if(re){let Se=fR(G,oe);if(!Se)return null;K+=Se.value,oe=Se.endIndex,re=!1;continue}if(de==="\\"){re=!0;continue}if(de===j)return{value:K,endIndex:oe+1};K+=de}return null}function uR(G,U){let j=G[U];if(j!=='"'&&j!=="'")return null;return Is(G,U,j)}function mR(G,U,j){if(!U)return null;return U.startIndex>=G&&U.endIndex===j?U.value:null}function fR(G,U){let j=G[U];if(!j)return null;if(j==="x"){let re=G.slice(U+1,U+3);if(!/^[0-9A-Fa-f]{2}$/.test(re))return null;return{value:String.fromCharCode(Number.parseInt(re,16)),endIndex:U+2}}if(/[0-7]/.test(j)){let re=/^[0-7]{1,3}/.exec(G.slice(U));if(!re)return null;return{value:String.fromCharCode(Number.parseInt(re[0],8)),endIndex:U+re[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
|
|
34
|
+
`,r:"\r",t:"\t",v:"\v"}[j]??j,endIndex:U}}function Hl(G,U,j){return G.startsWith(j,U)&&!mi(G[U-1])&&!mi(G[U+j.length])}function pR(G,U){return U!==null&&U>=G}function Rf(G,U){let j=G.indexOf(`
|
|
35
|
+
`,U);return j===-1?G.length:j+1}function xf(G,U){let j=gR(G,U);if(j===-1)return!0;if("{([,;!~=".includes(G[j]??""))return!0;let K=j;while(mi(G[K-1]))K--;return iR.has(G.slice(K,j+1))}function gR(G,U){for(let j=U-1;j>=0;j--)if(!/\s/.test(G[j]??""))return j;return-1}function _f(G,U){let j=!1;for(let K=U;K<G.length;K++){let re=G[K];if(!re)break;if(j){j=!1;continue}if(re==="\\"){j=!0;continue}if(re==="/")return K+1}return null}var hR=new Set(["sudo","env","command","builtin"]),yR=new Set(["caffeinate","exec","nice","nohup","setsid","stdbuf","time","timeout"]);function ks(G,U){let j=G[0];if(!j||!wf(Ot(j),U))return null;let K=Ot(j),re=G[1]==="--"?2:1,oe=bR(G,re,K,U),de=oe[0];if(de===void 0)return null;return{wrapper:K,tokens:G.slice(de),childIndex:de,alternativeChildIndices:oe.slice(1)}}function bR(G,U,j,K){let re=G[1]==="--",oe=[];for(let de=U;de<G.length;de++){let Se=G[de];if(!Se)continue;let we=Ot(Se)!==j&&SR(Se,K);if(we)oe.push(de);if(!we&&Fi.has(Dt(Se)))break;if(re)break}return oe}function SR(G,U){let j=Ot(G),K=Dt(G);return K==="git"||j==="busybox"||Wr(G)||Na.has(j)||mm(K)||wf(j,U)||qt.has(K)||G==="$SHELL"||Ln(K)||In.has(K)||U.rules.some((re)=>re.command===j)}function wf(G,U){return yR.has(G)||U.transparentWrappers.includes(G)}function Wr(G){return hR.has(G.toLowerCase())}function Fr(G,U){return{embedded:!1,cwd:G.cwd,originalCwd:U.originalCwd,effectiveCwd:G.cwd,envAssignments:G.envAssignments,allowTmpdirVar:U.allowTmpdirVar,worktreeMode:U.worktreeMode,wrappedByTransparent:!1}}function zn(G,U){let j=U.policy??{rules:[],transparentWrappers:[]};return Os([...G],U.environment,U.cwd,U.cwd,new Map,new Map(U.envAssignments??[]),j,{iterations:0},!1)}function*Os(G,U,j,K,re,oe,de,Se,we){let We=gs(G,U,j,oe);for(let[pt,ht]of We.envAssignments)oe.set(pt,ht),re.set(pt,ht);let{tokens:mt,cwd:gt}=We;if(We.envSplitValues){let pt=ps(We.envSplitValues,mt);if(!pt)throw new s("derivedCommandShape");Kl(Se),yield*Os(pt,U,gt,K,re,oe,de,Se,we);return}if(Wr(mt[0]??""))throw new s("wrapperPeelIterations");let ft=ks(mt,de);if(ft){for(let pt of[ft.childIndex,...ft.alternativeChildIndices])Kl(Se),yield*Os(pt===ft.childIndex?ft.tokens:mt.slice(pt),U,gt,K,new Map(re),new Map(oe),de,Se,!0);return}if(vR(mt)){Kl(Se),yield*Os(mt.slice(1),U,gt,K,re,oe,de,Se,we);return}yield CR(mt,gt,K,re,oe,we)}function CR(G,U,j,K,re,oe){return{tokens:G,cwd:U===null?void 0:U??j,wrapperCwd:U,wrapperEnvAssignments:K,envAssignments:re,head:Ot(G[0]??"").toLowerCase(),wrappedByTransparent:oe}}function Kl(G){if(G.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");G.iterations++}function vR(G){return Ot(G[0]??"").toLowerCase()==="busybox"&&G.length>1}function ql(G,U){let j=[],K=U;while(K<G.length){let re=G[K];if(re===void 0||re===":::")break;j.push(re),K++}return{markerIndex:K<G.length&&G[K]===":::"?K:-1,templateTokens:j}}function tr(G){let U=!1,j=!1;for(let K of G){if(K==="--")break;if(K==="-r"||K==="-R"||Yl(K,"recursive")){U=!0;continue}if(K==="-f"||Yl(K,"force")){j=!0;continue}if(K.startsWith("-")&&!K.startsWith("--")){if(K.includes("r")||K.includes("R"))U=!0;if(K.includes("f"))j=!0}}return U&&j}function Ms(G){let U=G.indexOf("--");return G.slice(1,U===-1?void 0:U).some((j)=>Yl(j,"recursive")||/^-[A-Za-z]+$/.test(j)&&/[rR]/.test(j.slice(1)))}function Yl(G,U){return G.length>2&&G.startsWith("--")&&U.startsWith(G.slice(2))}var ER=["--init-file","--rcfile"],RR=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function $n(G){for(let U=1;U<G.length;U++){let j=G[U];if(!j)continue;if(j==="-c")return Af(G,U,!0);if(j.startsWith("-")&&j.includes("c")&&!j.startsWith("--")){let K=Af(G,U,!1);if(K!==null)return K}}return null}function nr(G){let U=Ot(G[0]??"").toLowerCase();if(U==="zsh"||U==="ksh")return En(G).syntaxCheck;let j=!1;for(let K of G.slice(1)){if(K==="--")return j;if(K.startsWith("+")&&!K.startsWith("++")){if(K.slice(1).includes("n"))j=!1;continue}if(!K.startsWith("-")||K.startsWith("--"))return j;let re=K.slice(1);if(re.includes("n"))j=!0;if(re.includes("c"))return j}return j}function Af(G,U,j){if(G[U+1]==="--")return G[U+2]||null;let K=G[U+1];if(!K||!j&&K.startsWith("-"))return null;return K}function Pf(G){let U=Ot(G[0]??"").toLowerCase(),j=xR(G,U),K=RR.get(U)??null,re=j.argvSource?.kind!=="absent";return{argvSource:U==="bash"?j.argvSource:null,argvSourceApplies:U==="bash"&&j.interactive&&j.argvSource?.kind==="literal",envName:K,envSourceApplies:re&&(K==="BASH_ENV"?!j.interactive:K==="ENV"&&j.interactive)}}function xR(G,U){let j=En(G),K=j.commandIndex??j.scriptIndex??G.length,re=[],oe=!1,de=!0;for(let Se=1;Se<K;Se++){let we=G[Se];if(we===void 0||we==="--"||we==="-"||we[0]!=="-"&&we[0]!=="+")break;if(we.startsWith("--")){if(U==="bash"&&de?ER.find((ft)=>we===ft):void 0){let ft=G[Se+1];re.push(ft===void 0?{kind:"absent"}:{kind:"literal",value:ft}),Se++;continue}let gt=we.split("=",1)[0]??we;if(U==="bash"&&Ma.has(gt)&&!we.includes("="))Se++;continue}if(U==="bash")de=!1;let We=Da(U,we,G[Se+1],"startup");if(We.interactive)oe=we[0]==="-";Se+=We.followingValues}return{argvSource:re.at(-1)??null,interactive:oe}}var _R="find -delete permanently removes files. Use -print first to preview.",wR="find -exec rm -rf is dangerous. Use explicit file list instead.",AR=new Set(["-exec","-execdir","-ok","-okdir"]),PR=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((G)=>[G,1]),["-fprintf",2]]);function Tf(G,U){let j=G.map(t),K=TR(G,j,U);if(K)return K;if(Ds(j,1)&&!NR(G,j,U)){let de=At(xt("find.delete",_R),U.policy);if(de)return de}let re=U.budget??Pn(),oe=0;while(oe<j.length){let de=j[oe],Se=rr(de??"");if(Se>0){oe+=Se+1;continue}if(!Vn(de)){oe++;continue}re.charge("derivedTokens",j.length-oe-1);let we=yo(j,oe);oe=we.nextIndex;let We=WR(we.tokens,U.environment);if(We){let pt=At(We,U.policy);if(pt)return pt}let mt=de==="-execdir"||de==="-okdir",gt=U.analyzeTokens?.(we.tokens,mt?null:U.cwd)??null,ft=gt?.id.startsWith("custom.")?gt:At(gt,U.policy);if(ft)return ft}return null}function TR(G,U,j){if(!Ds(U,1)&&!Zl(U,j.environment))return null;let re=pi(G)??Kt(["."]),oe=jn({...j,allowPaths:j.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let de of re){let Se=ci(de);for(let we of Se.expandedTargets??[t(de)]){let We=_n(we,oe,{targetIsLiteral:Se.expandedTargets!==void 0||Se.targetIsLiteral,tmpdirWordSplittingProtected:Se.tmpdirWordSplittingProtected});if(We.kind==="root_or_home_target")return xt("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(We.kind==="git_metadata_target"&&!IR(G,oe.protectedGitMetadata,j.environment))return xt("find.delete-git-metadata",x)}}if(DR(U)&&oe.resolvedCwd&&Ym(re.map(t),oe.resolvedCwd,oe.protectedGitMetadata,oe.environment,oe.budget))return xt("find.delete-git-metadata",x);return null}function IR(G,U,j){if(!U)return!1;let K=G.map(t),re=[],oe=!1,de=pi(G)?.at(-1),Se=de?G.indexOf(de)+1:1;while(Se<K.length){let we=K[Se]??"";if(Vn(we)){let We=yo(K,Se),mt=mr([...We.tokens],j),gt=Ms(mt),ft=qt.has(Ot(mt[0]??"").toLowerCase()),pt=We.tokens.some((yt)=>yt!=="{}"&&yt.includes("{}")),ht=(we==="-execdir"||we==="-okdir")&&mt.slice(1).some((yt)=>yt!=="{}"&&!yt.startsWith("-"));if(gt||ft||pt||ht)return!1;oe=!0,Se=We.nextIndex;continue}if(we==="-delete"){oe=!0,Se++;continue}if(we==="-name"||we==="-iname"){let We=G[Se+1];if(!(We?.provenance==="literal"&&!/[[\\]/.test(We.text)))return!1;if(!oe)re.push(OR(We.text,we==="-iname"));Se+=2;continue}if(!kR.has(we))return!1;Se+=1+rr(we)}return re.length>0&&!Xm(U,(we)=>re.every((We)=>We.test(we)))}var kR=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function OR(G,U){let j=G.replace(/[*?]|[.+^${}()|\]/]/g,(K)=>K==="*"?".*":K==="?"?".":`\\${K}`);return new RegExp(`^${j}$`,U?"isu":"su")}var MR=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function Zl(G,U){let j=0;while(j<G.length){if(!Vn(G[j])){j++;continue}let K=yo(G,j),re=mr([...K.tokens],U),oe=Ot(re[0]??"").toLowerCase(),de=qt.has(oe)&&MR.test(($n(re)??"").replace(/["'\\]/g,""));if((oe==="rm"||oe==="rmdir"||de)&&re.some((we)=>we.includes("{}")))return!0;j=K.nextIndex}return!1}function DR(G){return G.some((U,j)=>{if(!["-name","-iname"].includes(U))return!1;return G[j+1]?.toLowerCase()==="hooks"})}function NR(G,U,j){if(U.includes("-L")||U.includes("-f")||U.includes("-follow"))return!1;let K=pi(G);if(!K)return!1;let re=j.envAssignments??new Map,oe=Fl(re,j.environment),de=j.trustedTmpdirValue??mo(re,j.environment),Se=j.allowTmpdirVar??!li(re,j.environment),we={environment:j.environment,protectedGitMetadata:j.protectedGitMetadata,cwd:j.cwd,originalCwd:j.originalCwd,strict:j.strict,allowTmpdirVar:Se&&de&&Boolean(oe),allowPaths:j.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:j.tmpdirWordSplittingUnsafe??Dr(re,j.environment),trustedTmpdirValue:de,budget:j.budget},We=jn(we),mt=jn({...we,cwd:j.originalCwd??j.cwd}),gt=j.originalCwd&&j.environment.paths.realpath(j.originalCwd),ft=j.cwd&&j.environment.paths.realpath(j.cwd),pt=gt&&ft&&!po(ft,gt)?j.cwd:void 0;return K.every((ht)=>{let yt=ci(ht);if(yt.unsafeBraceExpansion)return!1;return(yt.expandedTargets??[t(ht)]).every((bt)=>{let St=/^\.\/*$/.test(bt)?pt:void 0,Et=St??bt,Ct={targetIsLiteral:yt.expandedTargets!==void 0||yt.targetIsLiteral,tmpdirWordSplittingProtected:yt.tmpdirWordSplittingProtected};if(!Jt(j.policy,"rm.recursive-force-paranoid",j.paranoid??!1)&&!St&&_n(Et,We,Ct).kind==="within_anchored_cwd")return!0;return af(Et,St?mt:We,{...Ct,containmentTarget:LR(Et,oe)})})})}function LR(G,U){if(!U)return G;return G.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>U)}function pi(G){let U=(re)=>{let oe=G[re];return oe?t(oe):void 0},j=1;while(U(j)==="-H"||U(j)==="-P")j++;if(U(j)==="--")j++;let K=[];while(j<G.length){let re=U(j),oe=G[j];if(!re||!oe||re.startsWith("-")||["!","(",")"].includes(re))break;K.push(oe),j++}return K.length>0?K:null}function WR(G,U){let j=ur([...G],U);if(j.length===0)return null;let K=Ot(j[0]??"");if(K==="busybox"&&j.length>1)j=j.slice(1),K=Ot(j[0]??"");if(K==="rm"&&tr(j))return xt("find.exec-rm-recursive-force",wR);return null}function yo(G,U){let j=U+1;while(j<G.length&&G[j]!==";"&&!(G[j]==="+"&&G[j-1]==="{}"))j++;return{tokens:G.slice(U+1,j),nextIndex:Math.min(j+1,G.length)}}function Ds(G,U){let j=U;while(j<G.length){let K=G[j];if(!K){j++;continue}if(Vn(K)){j=yo(G,j).nextIndex;continue}let re=rr(K);if(re>0){j+=re+1;continue}if(K==="-delete")return!0;j++}return!1}function rr(G){return PR.get(G)??(/^-newer[A-Za-z]{2}$/.test(G)?1:0)}function Vn(G){return G!==void 0&&AR.has(G)}import{resolve as m_}from"node:path";function*Xl(G){for(let U of G.nodes)yield*GR(U)}function FR(G){return Object.freeze([...Xl(G)])}function dt(G){return Object.freeze(FR(G).map((U)=>Object.freeze(U.words.map((j)=>j.text))))}function gi(G){let U=y(G,"posix");if(U.status!=="complete"||U.nodes.length!==1)return null;let j=U.nodes[0];if(j?.kind!=="command")return null;if(j.redirections.length>0||j.nested.length>0)return null;if(j.words.some((K)=>K.provenance==="command-substitution"))return null;return j.words.map((K)=>K.text)}function*GR(G){if(G.kind==="command"){yield G;for(let U of G.nested)yield*Xl(U);return}if(G.kind==="group")yield*Xl(G.body)}var zR=5,Jl="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 sn(G){let U=G.indexOf("--");if(U===-1)return{index:-1,before:G,after:[]};return{index:U,before:G.slice(0,U),after:G.slice(U+1)}}function kf(G,U,j){let K=Ns(G,U,j),re=$R(K.entries);if(re.size===0)return{blockedReason:K.blockedReason,expanded:!1,tokens:G};let oe=G,de=!1;for(let Se=0;Se<zR;Se++){let{subcommand:we,rest:We}=wn(oe),mt=we?.toLowerCase();if(!mt||!re.has(mt))return{blockedReason:K.blockedReason,expanded:de,tokens:oe};let gt=re.get(mt),ft=VR(gt);if(ft===null||ft.length===0)return{blockedReason:Jl,expanded:!0,tokens:oe};oe=["git",...ft,...We],de=!0}return{blockedReason:Jl,expanded:!0,tokens:oe}}function Of(G,U,j){return Ns(G,U,j).entries.some((K)=>K.key.toLowerCase()==="core.sshcommand")}function wn(G){if(G.length===0)return{subcommand:null,rest:[]};let U=G[0];if((U?Ot(U).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let K=1;while(K<G.length){let re=G[K];if(!re)break;if(re==="--"){let oe=G[K+1];if(oe&&!oe.startsWith("-"))return{subcommand:oe,rest:G.slice(K+2)};return{subcommand:null,rest:G.slice(K+1)}}if(!re.startsWith("-"))return{subcommand:re,rest:G.slice(K+1)};K+=vn.has(re)?2:1}return{subcommand:null,rest:[]}}function $R(G){let U=new Map;for(let j of G){let K=j.key.toLowerCase();if(!K.startsWith("alias."))continue;let re=K.slice(6);if(re!=="")U.set(re,j.value)}return U}function Ns(G,U,j){if(G.length===0)return{blockedReason:null,entries:[]};let K=G[0];if((K?Ot(K).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let oe=UR(U,j);return{blockedReason:oe.blockedReason,entries:[...oe.entries,...BR(G,U,j)]}}function BR(G,U,j){let K=[],re=1;while(re<G.length){let oe=G[re];if(!oe||oe==="--"||!oe.startsWith("-"))return K;if(oe==="-c"){let de=Ql(G[re+1]);if(de)K.push(de);re+=2;continue}if(oe.startsWith("-c")&&oe.length>2){let de=Ql(oe.slice(2));if(de)K.push(de);re++;continue}if(oe==="--config-env"){let de=If(G[re+1],U,j);if(de)K.push(de);re+=2;continue}if(oe.startsWith("--config-env=")){let de=If(oe.slice(13),U,j);if(de)K.push(de);re++;continue}if(vn.has(oe)){re+=2;continue}re++}return K}function UR(G,U){let j=HR(G,U),K=jR(G,U);return{blockedReason:j===null||K===null?Jl:null,entries:[...j??[],...K??[]]}}function HR(G,U){let j=Qn("GIT_CONFIG_PARAMETERS",G,U);if(j===void 0)return[];let K=[],re=gi(j);if(!re)return null;for(let oe of re){let de=Ql(oe);if(!de)return null;K.push(de)}return K}function jR(G,U){let j=Em(G,U);if(j.state==="absent")return[];if(j.state==="invalid")return null;let K=[];for(let re=0;re<j.count;re++){let oe=Qn(`GIT_CONFIG_KEY_${re}`,G,U)?.trim(),de=Qn(`GIT_CONFIG_VALUE_${re}`,G,U);if(!oe||de===void 0)return null;K.push({key:oe,value:de})}return K}function Ql(G){if(!G)return null;let U=G.indexOf("=");return{key:(U===-1?G:G.slice(0,U)).trim(),value:U===-1?void 0:G.slice(U+1)}}function If(G,U,j){let K=G?.indexOf("=")??-1;if(!G||K===-1)return null;return{key:G.slice(0,K).trim(),value:Qn(G.slice(K+1),U,j)}}function VR(G){let U=G?.trimStart();if(!U||U.startsWith("!"))return null;return gi(U)}var KR="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",qR="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",YR="git checkout --force discards uncommitted changes. Use 'git stash' first.",ZR="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",XR="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",JR="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",QR="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",ex="git switch --force discards uncommitted changes. Use 'git stash' first.",tx="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",nx="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",rx="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",ox="git reset --merge can lose uncommitted changes. Use 'git stash' first.",ix="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",sx="git rm --force removes tracked files from the working tree. Use 'git rm --cached' to keep the files, or 'git rm --dry-run' to preview first.",ax="git push --force destroys remote history. Use --force-with-lease for safer force push.",lx="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",cx="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",dx="git branch -D force-deletes without merge check. Use -d for safe delete.",ux="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",mx="git merge --abort discards merge conflict resolutions. Use 'git status' first.",fx="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",px="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",gx="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",hx="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",yx="git worktree remove --force can delete uncommitted changes. Remove --force flag.",bx=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),Sx=new Set(["--recurse-submodules","--track","-t"]),ec=new Set(["-b","-B","-U"]),tc=new Set(["-c","-C"]),Cx=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function Nt(G,U){let j=G.split("=",1)[0]??G;return j.length>=4&&U.startsWith(j)&&j.startsWith("--")&&j.slice(2).length>=2}var bo=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function Df(G,U){let{subcommand:j,rest:K}=wn(G);if(!j)return null;switch(j.toLowerCase()){case"checkout":return pr(vx(K,U));case"switch":return pr(Rx(K));case"restore":return pr(_x(K));case"reset":return Ax(K);case"clean":return pr(Tx(K));case"rm":return pr(Ix(K));case"push":return Gr(kx(K));case"branch":return Gr(Dx(K));case"stash":return Gr(Gx(K));case"worktree":return Gr(zx(K));case"rebase":return pr(Nx(K));case"merge":return pr(Lx(K));case"tag":return Gr(Wx(K));case"reflog":return Gr(Fx(K));default:return null}}function pr(G){return G?{...G,localDiscard:!0}:null}function Gr(G){return G?{...G,localDiscard:!1}:null}function vx(G,U){let{index:j,before:K}=sn(G),re=fn(K,{shortOptsWithValue:ec});if(K.some((Se)=>Nt(Se,"--force"))||re.has("-f"))return xt("git.checkout-force",YR);for(let Se of G){if(Se==="-b"||Se==="-B"||Se==="--orphan")return null;if(Nt(Se,"--pathspec-from-file"))return xt("git.checkout-pathspec-from-file",XR)}if(j!==-1){if(K.some((we)=>!we.startsWith("-")))return xt("git.checkout-ref-path",ZR);return xt("git.checkout-double-dash",KR)}let oe=xx(G);if(oe.length>=2)return xt("git.checkout-ambiguous",JR);let de=oe[0];if(de===void 0||re.has("-d")||re.has("-t")||G.some((Se)=>Nt(Se,"--detach")||Nt(Se,"--track")))return null;if(Ex(de)||U(de))return xt("git.checkout-double-dash",qR);return null}function Ex(G){return G==="."||G===".."||/^\.\.?[/\\]/.test(G)||/^([/\\]|[A-Za-z]:[/\\])/.test(G)||G.endsWith("/")||G.startsWith(":")||/[*?[]/.test(G)}function Rx(G){let{before:U}=sn(G);if(U.some((K)=>Nt(K,"--discard-changes")))return xt("git.switch-discard-changes",QR);let j=fn(U,{shortOptsWithValue:tc});if(U.some((K)=>Nt(K,"--force"))||j.has("-f"))return xt("git.switch-force",ex);return null}function xx(G){let U=[],j=0;while(j<G.length){let K=G[j];if(!K)break;if(K==="--")break;if(!K.startsWith("-")){U.push(K),j++;continue}if(bx.has(K)){j+=2;continue}if(Sx.has(K)){let re=G[j+1],oe=K==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"];j+=re&&!re.startsWith("-")&&oe.includes(re)?2:1;continue}j++}return U}function _x(G){let U=wx(G);if(U.isTerminal||!U.hasPathspec&&!U.hasPatch||!U.hasWorktree)return null;return U.hasExplicitLocation?xt("git.restore-worktree",nx):xt("git.restore-unstaged",tx)}function wx(G){let U=!1,j=!1,K=!0,re=!1,oe=(de)=>{if(!re)K=!1,re=!0;if(de!==void 0)K=de};for(let de=0;de<G.length;de++){let Se=G[de];if(Se===void 0)break;if(Se==="--"){U||=de+1<G.length;break}if(Se==="--pathspec-from-file"){U=!0,de++;continue}if(Se.startsWith("--pathspec-from-file=")){U=!0;continue}if(Se==="-h"||Se==="--help"||Se==="--version")return{hasPathspec:U,hasPatch:j,hasWorktree:K,hasExplicitLocation:re,isTerminal:!0};if(Se==="--staged"){oe();continue}if(Se==="--no-staged"){oe();continue}if(Se==="--worktree"){oe(!0);continue}if(Se==="--no-worktree"){oe(!1);continue}if(Se==="--patch"){j=!0;continue}if(Se==="--no-patch"){j=!1;continue}if(Cx.has(Se)){de++;continue}if(Se.startsWith("--"))continue;if(Se==="-"){U=!0;continue}if(!Se.startsWith("-")){U=!0;continue}for(let we=1;we<Se.length;we++){let We=Se.charAt(we);if(We==="h")return{hasPathspec:U,hasPatch:j,hasWorktree:K,hasExplicitLocation:re,isTerminal:!0};if(We==="S"){oe();continue}if(We==="W"){oe(!0);continue}if(We==="p"){j=!0;continue}if(We==="s"||We==="U"){if(we===Se.length-1)de++;break}}}return{hasPathspec:U,hasPatch:j,hasWorktree:K,hasExplicitLocation:re,isTerminal:!1}}function Ax(G){let U=null;for(let j of G){if(Nt(j,"--hard")){U=xt("git.reset-hard",rx);break}if(Nt(j,"--merge")){U=xt("git.reset-merge",ox);break}}if(!U)return null;return Px(G)?Gr(U):pr(U)}function Px(G){for(let U of G){if(U==="--")return!1;if(!U.startsWith("-"))return!0}return!1}function Tx(G){for(let j of G)if(j==="-n"||Nt(j,"--dry-run"))return null;let U=fn(G.filter((j)=>j!=="--"));if(G.some((j)=>Nt(j,"--force"))||U.has("-f"))return xt("git.clean-force",ix);return null}function Ix(G){let U=!1,j=!1,K=!1;for(let re of sn(G).before){if(Nt(re,"--no-force")){U=!1;continue}if(Nt(re,"--force")){U=!0;continue}if(Nt(re,"--no-cached")){j=!1;continue}if(Nt(re,"--cached")){j=!0;continue}if(Nt(re,"--no-dry-run")){K=!1;continue}if(Nt(re,"--dry-run")){K=!0;continue}let oe=fn([re]);U||=oe.has("-f"),K||=oe.has("-n")}return U&&!j&&!K?xt("git.rm-force",sx):null}function kx(G){let{before:U,after:j}=sn(G),K=fn(U);if(U.some((de)=>Nt(de,"--mirror")))return xt("git.push-mirror",cx);if(U.some((de)=>Nt(de,"--force"))||K.has("-f")||Mf(U,j).some(Ox))return xt("git.push-force",ax);if(U.some((de)=>Nt(de,"--delete"))||K.has("-d")||Mf(U,j).some(Mx))return xt("git.push-delete",lx);return null}function Mf(G,U){return[...G.filter((j)=>j!==""&&!j.startsWith("-")),...U]}function Ox(G){return G.startsWith("+")||G.includes(":+")}function Mx(G){return G.length>1&&G.startsWith(":")}function Dx(G){let{before:U}=sn(G),j=fn(U),K=j.has("-D")||j.has("-d")||U.some((oe)=>Nt(oe,"--delete")),re=j.has("-D")||j.has("-f")||U.some((oe)=>Nt(oe,"--force"));if(K&&re)return xt("git.branch-force-delete",dx);return null}function Nx(G){let{before:U}=sn(G);return U.some((j)=>Nt(j,"--abort"))?xt("git.rebase-abort",ux):null}function Lx(G){let{before:U}=sn(G);return U.some((j)=>Nt(j,"--abort"))?xt("git.merge-abort",mx):null}function Wx(G){let{before:U}=sn(G);return fn(U).has("-d")||U.some((K)=>Nt(K,"--delete"))?xt("git.tag-delete",fx):null}function Fx(G){return G[0]==="delete"?xt("git.reflog-delete",px):null}function Gx(G){for(let U of G){if(U==="drop")return xt("git.stash-drop",gx);if(U==="clear")return xt("git.stash-clear",hx)}return null}function zx(G){let{before:U}=sn(G);if(!U.includes("remove"))return null;let K=fn(U);if(U.some((re)=>Nt(re,"--force"))||K.has("-f"))return xt("git.worktree-remove-force",yx);return null}import{dirname as a_,isAbsolute as l_,join as Yf,resolve as c_}from"node:path";var rc="TMPDIR",oc="IFS",Lf=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Wf=/^[A-Za-z_][A-Za-z0-9_]*$/,Ff=new Set(["export","typeset","declare","readonly"]),$x=new Set(["builtin","command","time"]),Bx=new Set(["do","then","else"]),Ux=new Set(["do","then","case"]),Nf=new Set(["done","fi","esac"]),Hx=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function Gf(G,U){return G.map((j)=>j.provenance==="variable"&&Vf(j.text)?zf(j.text,U.shellAssignments):t(j))}function zf(G,U){return G.replace(Hx,(j,K,re)=>U.get(K??re??"")??j)}function Kn(G,U){let j=G.parts.every((re)=>re.provenance!=="literal"||!/[$`]/.test(re.raw));if(G.provenance!=="variable"||!j)return null;let K=zf(G.text,U);return/^[~-]/.test(K)||/[\s$`*?[]/.test(K)?null:K}function $f(G,U){return{env:G,effectiveEnvAssignments:qx(G,U),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function Bf(G){return{env:G.env,effectiveEnvAssignments:G.effectiveEnvAssignments?new Map(G.effectiveEnvAssignments):void 0,shellAssignments:new Map(G.shellAssignments),bodyDepth:G.bodyDepth,bodyAssignments:new Set(G.bodyAssignments)}}function ic(G,U){let j=Hf(G,U),K=G[0]??"";if(Ux.has(K))U.bodyDepth+=1;if(K==="elif"||Nf.has(K))U.bodyDepth=Math.max(0,U.bodyDepth-1);if(Nf.has(K)&&U.bodyDepth===0)U.bodyAssignments.forEach((Se)=>{U.shellAssignments.delete(Se)}),U.bodyAssignments.clear();j.assignments.filter((Se)=>Se.persists).forEach((Se)=>{if(U.shellAssignments.set(Se.name,Se.value),U.bodyDepth>0)U.bodyAssignments.add(Se.name);sc(U,Se)});let re=j.commandIndex;if(re!==-1&&Ff.has(G[re]??""))G.filter((Se)=>Wf.test(Se)&&nc(Se)).forEach((Se)=>{Yx(U,Se)});let oe=re===-1?-1:jf(G,re);if(oe===-1||G[oe]!=="unset")return;let de=Xx(G,oe);if(de===null)return;G.slice(de).forEach((Se)=>{if(U.bodyDepth>0){U.shellAssignments.set(Se,"");return}Zx(U,Se)})}function Uf(G,U){let j=Hf(G,U).assignments;if(j.length===0)return U.effectiveEnvAssignments;let K=new Map(U.effectiveEnvAssignments??[]);return j.forEach((re)=>{K.set(re.name,re.value)}),K}function Hf(G,U){let j=Bx.has(G[0]??"")?1:0,K=G.findIndex((Se,we)=>we>=j&&!Vf(Se)),re=K!==-1&&Ff.has(G[jf(G,K)]??""),oe=Kx(U);return{assignments:G.flatMap((Se,we)=>{let We=jx(Se,oe,U.env);if(!We)return[];if(K!==-1&&we>K&&!re&&!ms(We.name))return[];return oe.set(We.name,We.value),[{...We,persists:K===-1||re}]}),commandIndex:K}}function jf(G,U){let j=U;while($x.has(G[j]??"")){j+=1;while(G[j]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(G[j]??""))return U;j+=1}}return j}function Vf(G){return On(G)!==null||Lf.test(G)}function jx(G,U,j){return On(G)??Vx(G,U,j)}function Vx(G,U,j){let K=fs(G,j,U);if(K)return K;let re=G.match(Lf)?.[1];if(!re)return null;let oe=G.indexOf("=");return{name:re,value:`${U.has(re)?U.get(re):j.get(re)??""}${G.slice(oe+1)}`}}function nc(G){return G===rc||G===oc||Il(G)}function Kx(G){return new Map([...G.effectiveEnvAssignments??[],...G.shellAssignments])}function qx(G,U){let j=[rc,oc].map((K)=>{let re=G.get(K);return re===void 0?null:[K,re]}).filter((K)=>K!==null);if(j.length===0)return U;return new Map([...j,...U??[]])}function sc(G,U){let j=new Map(G.effectiveEnvAssignments??[]);j.set(U.name,U.value),G.effectiveEnvAssignments=j}function Yx(G,U){sc(G,{name:U,value:G.shellAssignments.get(U)??G.effectiveEnvAssignments?.get(U)??G.env.get(U)??""})}function Zx(G,U){if(!nc(U)&&!Wf.test(U))return;if(G.shellAssignments.set(U,""),ms(U)&&G.env.has(U)){let K=new Map(G.env);K.delete(U),G.env=K}if(!nc(U)||U===rc||U===oc||No(U)){sc(G,{name:U,value:""});return}if(!G.effectiveEnvAssignments?.has(U))return;let j=new Map(G.effectiveEnvAssignments);j.delete(U),G.effectiveEnvAssignments=j.size===0?void 0:j}function Xx(G,U){let j=U+1;while(j<G.length){let K=G[j];if(!K)return null;if(K==="--")return j+1;if(K==="-v"){j++;continue}if(K.startsWith("-"))return null;return j}return j}import{resolve as Jx}from"node:path";function Ls(G,U){return Tl.some((j)=>U?.has(j)||G.has(j))}function So(G,U,j){if(!U)return{gitCwd:null,hasExplicitGitContext:!1};let K=j.realpath(Jx(U));if(K===null||!j.isDirectory(K))return{gitCwd:null,hasExplicitGitContext:!1};let re=K,oe=!1,de=1;while(de<G.length){let Se=G[de];if(!Se)break;if(Se==="--")break;if(!Se.startsWith("-"))break;if(Se==="-C"){let we=G[de+1];if(!we)return{gitCwd:null,hasExplicitGitContext:oe};let We=Kf(re,we,j);if(!We)return{gitCwd:null,hasExplicitGitContext:oe};re=We,de+=2;continue}if(Se.startsWith("-C")&&Se.length>2){let we=Kf(re,Se.slice(2),j);if(!we)return{gitCwd:null,hasExplicitGitContext:oe};re=we,de++;continue}if(Se==="--git-dir"||Se==="--work-tree"){oe=!0,de+=2;continue}if(Se.startsWith("--git-dir=")||Se.startsWith("--work-tree=")){oe=!0,de++;continue}de+=vn.has(Se)?2:1}return{gitCwd:re,hasExplicitGitContext:oe}}function Kf(G,U,j){try{let K=dr(G,U,j);return j.isDirectory(K)?K:null}catch{return null}}function qf(G,U,j){if(!U.localDiscard||!j.worktreeMode||Ls(j.environment.env,j.envAssignments))return null;let K=So(G,j.cwd,j.environment.paths);if(!K.gitCwd||K.hasExplicitGitContext)return null;let re=j.environment.worktreeFacts(K.gitCwd);if(!re)return null;if(ac(G,j,re))return null;return{kind:"worktree",originalReason:U.reason,gitCwd:K.gitCwd}}function ac(G,U,j){let{subcommand:K,rest:re}=wn(G),oe=K?.toLowerCase();if(U.dynamicArguments||Qx(re)||o_(G,U.environment.env,U.envAssignments,j)||n_(re)||e_(oe,re))return!0;return oe==="clean"&&r_(re)>1}function Qx(G){return G.some((U)=>/[$*?[]/.test(U))}function e_(G,U){if(G==="checkout"){let{before:j}=sn(U),K=fn(j,{shortOptsWithValue:ec}),re=j.some((de)=>Nt(de,"--force"))||K.has("-f"),oe=K.has("-B")||j.some((de)=>de==="-B"||de.startsWith("-B"));return re&&oe}if(G==="switch"){let{before:j}=sn(U),K=fn(j,{shortOptsWithValue:tc}),re=j.some((de)=>Nt(de,"--force"))||j.some((de)=>Nt(de,"--discard-changes"))||K.has("-f"),oe=j.some((de)=>de==="-C"||de.startsWith("-C")||t_(de))||K.has("-C");return re&&oe}return!1}function t_(G){let U=G.split("=",1)[0]??G;return U==="--force-create"||U.length>=9&&"--force-create".startsWith(U)}function n_(G){return G.some((U)=>U.startsWith("--recurse-sub"))}function r_(G){let U=0;for(let j of G){if(j==="--force"){U++;continue}if(j.startsWith("-")&&!j.startsWith("--")){for(let K of j.slice(1))if(K==="f")U++}}return U}function o_(G,U,j,K){if(Qn("GIT_CONFIG_PARAMETERS",U,j)!==void 0)return!0;let re=Ns(G,U,j);if(re.blockedReason!==null)return!0;let oe=re.entries.map((Se)=>({key:Se.key.toLowerCase(),value:Se.value}));if(oe.some((Se)=>s_(Se.key)))return!0;let de=oe.filter((Se)=>Se.key==="submodule.recurse").at(-1);if(de)return de.value===void 0||i_(de.value);if(xm(j))return!0;return K.recursiveSubmodules}function i_(G){let U=G.toLowerCase();return U!=="false"&&U!=="no"&&U!=="off"&&U!=="0"}function s_(G){return G==="include.path"||G.startsWith("includeif.")&&G.endsWith(".path")}function Zf(G,U,j){let K=G.map((we)=>Kn(we,j.shellAssignments??new Map)??t(we)),re=j.environment.paths,oe=So(K,j.cwd,re),de=j.originalCwd?re.realpath(c_(j.originalCwd)):null;if(U.id.startsWith("git.push-")||de===null||oe.gitCwd===null||oe.hasExplicitGitContext||Ls(j.environment.env,j.envAssignments))return null;let Se=U.id==="git.worktree-remove-force"?u_(G,j.shellAssignments,re):Xf(oe.gitCwd,re);if(Se===null||U.id!=="git.worktree-remove-force"&&!d_(Se,K,U,j)||!fo(Se,j.environment)||ws(Se,j.environment)||po(de,Se)||po(Se,de))return null;return{kind:"temp-root",originalReason:U.reason,gitCwd:oe.gitCwd}}function d_(G,U,j,K){let re=K.environment.paths,oe=Yf(G,".git");if(re.entryKind(oe)!=="present")return!1;if(re.isDirectory(oe))return!0;if(!j.localDiscard)return!1;let Se=K.environment.worktreeFacts(G);return Se!==null&&!ac(U,K,Se)}function u_(G,U,j){let K=wn(G.map(t)).rest,{before:re,after:oe}=sn(K.slice(K.indexOf("remove")+1)),de=[...re.filter((mt)=>!mt.startsWith("-")),...oe],Se=de.length===1?de[0]??"":"",we=G.find((mt)=>mt.text===Se),We=(we&&Kn(we,U??new Map))??Se;if(!l_(We)||/[\s$`*?[]/.test(We)||j.entryKind(We)!=="present"||!j.isDirectory(We))return null;return j.realpath(We)}function Xf(G,U){if(U.entryKind(Yf(G,".git"))!=="missing")return G;let j=a_(G);return j===G?null:Xf(j,U)}var f_="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.",p_=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function Ws(G,U){return Jf(G,U)}function Jf(G,U,j){let K=G.map(t),re=kf(K,U.environment.env,U.envAssignments),oe=re.blockedReason?At(xt("git.alias-config",re.blockedReason),U.policy):null;if(oe)return oe;let de=re.tokens;if((Rm(U.envAssignments)||Of(K,U.environment.env,U.envAssignments))&&g_(de))return xt("git.ssh-env",f_);let Se=Df(de,(We)=>{let mt=So(K,U.cwd,U.environment.paths).gitCwd;return mt!==null&&U.environment.paths.entryKind(m_(mt,We))!=="missing"});if(!Se)return null;if(re.expanded||re.blockedReason)return Se;let we=qf(K,Se,U)??Zf(G,Se,U);if(!we)return Se;return j?.(we),null}function Qf(G,U){let j=null;return{match:Jf(G,U,(re)=>{j=re}),relaxation:j}}function g_(G){let{subcommand:U,rest:j}=wn(G),K=U?.toLowerCase();if(!K)return!1;if(p_.has(K))return!0;if(K==="archive")return sn(j).before.some((re)=>Nt(re,"--remote"));return K==="remote"&&h_(j)}function h_(G){return G.find((U)=>!y_(U))?.toLowerCase()==="update"}function y_(G){return G==="-v"||Nt(G,"--verbose")||Nt(G,"--no-verbose")}import{isAbsolute as K_}from"node:path";function ep(G,U,j,K){let re=G.slice(0,U),oe=G.slice(U+j);return K.startsWith(re)&&K.endsWith(oe)?K.slice(re.length,K.length-oe.length):null}function Fs(G,U,j){let K=(oe)=>`${oe.tokenIndex}\x00${oe.kind}\x00${oe.value}`,re=new Set(G.map(K));return Array.from(U).some((oe)=>j(oe).some((de)=>!re.has(K(de))))}var tp="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",b_="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.",S_="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",C_="rm -rf targeting root or home directory is extremely dangerous and always blocked.",v_="rm -rf in home directory is dangerous. Change to a project directory first.",np={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:C_},git_metadata_target:{id:"rm.git-metadata",reason:x},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:S_},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:v_},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:tp},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:b_},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:tp}};function Gs(G,U){let j=jn({...U,allowPaths:U.policy?.destructiveCommandAllowPaths,posixShell:!0}),K=G.map(t),re=Ms(K),oe=R_(G);for(let de of oe){let Se=ci(de.word);if(re&&Se.unsafeBraceExpansion){let we=At(Lr({kind:"outside_anchored_cwd"},j,U.policy,np),U.policy);if(we)return we;continue}for(let we of Se.expandedTargets??[de.text]){let We=cn(we),mt={targetIsLiteral:Se.expandedTargets!==void 0||Se.targetIsLiteral,tmpdirWordSplittingProtected:Se.tmpdirWordSplittingProtected};if(!re&&j.resolvedCwd&&Mr(We,j.resolvedCwd,j.protectedGitMetadata,re,j.environment,j.budget))return xt("rm.git-metadata",x);if(!re)continue;for(let gt of E_(We,j,mt)){let ft=Lr(gt,j,U.policy,np),pt=At(ft,U.policy);if(pt)return pt}}}return null}function E_(G,U,j){let K=_n(G,U,j);if(K.kind==="cwd_self_target")return[K,_n(G,U,{...j,skipCwdSelf:!0})];if(K.kind!=="home_cwd_target")return[K];let re=_n(G,U,{...j,skipHomeCwd:!0});if(re.kind!=="cwd_self_target")return[K,re];return[K,re,_n(G,U,{...j,skipHomeCwd:!0,skipCwdSelf:!0})]}function R_(G){let U=[],j=!1;for(let K of G.slice(1)){let re=t(K);if(!re)continue;if(re==="--"){j=!0;continue}if(j){U.push({text:re,word:K});continue}if(!re.startsWith("-"))U.push({text:re,word:K})}return U}var gr={kind:"none"},zr={kind:"dynamic"},x_=new Set(["<","<<","<<-","<<<","<&","<>"]),op=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,__=/^(?:[0-9]+|[@*])$/,w_=cr.maxWords,ip=cr.maxInputLength;function sp(G){if(!G||Ot(Dt(G.words[0]?.text??""))!=="printf")return;if(G.words.some((re)=>re.provenance!=="literal"))return;let U=G.words.slice(G.words[1]?.text==="--"?2:1),j=U[0]?.text;if(j===void 0)return"";let K=U.slice(1).map((re)=>re.text);if(j==="%s")return K.join("");if(j==="%s\\n"||j===`%s
|
|
36
36
|
`)return`${K.join(`
|
|
37
37
|
`)}
|
|
38
38
|
`;if(j.includes("%")||/\\(?![\\nrt])/.test(j))return;return j.replaceAll("\\n",`
|
|
39
|
-
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function zs(G){let U=Co(G[1])==="--"?2:1;if(G.length<=U)return gr;let j=G.slice(U);if(!j.every(yi))return zr;return{kind:"literal",source:j.map(t).join(" ")}}function ap(G){let U=Co(G[1])==="--"?2:1,j=G[U],K=Co(j);if(j===void 0||G.length<=U+1||K==="-"||K===""||K==="-l"||K==="-p")return gr;if(!yi(j))return zr;return{kind:"literal",source:K}}function $s(G,U){let j=dp(G);if(j===-1)return gr;let K=
|
|
40
|
-
`}}function
|
|
39
|
+
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function zs(G){let U=Co(G[1])==="--"?2:1;if(G.length<=U)return gr;let j=G.slice(U);if(!j.every(yi))return zr;return{kind:"literal",source:j.map(t).join(" ")}}function ap(G){let U=Co(G[1])==="--"?2:1,j=G[U],K=Co(j);if(j===void 0||G.length<=U+1||K==="-"||K===""||K==="-l"||K==="-p")return gr;if(!yi(j))return zr;return{kind:"literal",source:K}}function $s(G,U){let j=dp(G);if(j===-1)return gr;let K=P_(U);if(!K)return gr;let re=[],oe=K.command?.length??0;for(let de of K.references){let Se=I_(de,G,j,K.ifs);if(!Se)return zr;if(oe+=Se.reduce((we,We)=>we+We.length+3,0),re.length+Se.length>w_||oe>ip)return zr;re.push(...Se)}if(K.command==="eval")return{kind:"literal",source:re.join(" ")};if(re.length===0||/\s/.test(re[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[K.command,K.command&&K.optionTerminator?"--":null,...re.map(Bs)].filter((de)=>de!==null).join(" ")}}function lp(G,U){let j=dp(G),K=G.slice(j+1),re=/\bIFS\b/.test(U);if(j===-1||!K.every(yi)||re)return U;let oe=K.map(Co),de="",Se=null,we=0;while(we<U.length){let We=U[we]??"",mt=Se==="'"?null:/^\$(?:\{([0-9]+|[@*])\}|([0-9@*]))/.exec(U.slice(we));if(mt){let gt=mt[1]??mt[2],ft=gt==="@"||gt==="*"?oe.slice(1):[oe[Number(gt)]??""];if(Se!=='"'&&ft.some((ht)=>/[*?[]/.test(ht)))return U;if(de+=Se==='"'?ft.map((ht)=>ht.replace(/["$`\\]/g,"\\$&")).join(gt==="@"?'" "':" "):ft.map((ht)=>ht.split(/[ \t\n]+/).map((yt)=>yt?Bs(yt):"").join(" ")).join(" "),de.length>ip)return U;we+=mt[0].length;continue}if(We==="\\"&&Se!=="'"){de+=U.slice(we,we+2),we+=2;continue}if(We==="'"&&Se!=='"'||We==='"'&&Se!=="'")Se=Se?null:We;de+=We,we++}return de}function cp(G,U,j,K){if(!En(G.map(t)).readsStdinAsCommands)return gr;let re=U.filter((oe)=>(oe.fd===void 0||oe.fd===0)&&x_.has(oe.operator)).at(-1);if(re){if(re.operator==="<<"||re.operator==="<<-")return gr;if(re.operator!=="<<<"||re.target?.provenance!=="literal")return zr;return{kind:"literal",source:re.target.text}}if(!j)return gr;return K===void 0?zr:{kind:"literal",source:K}}function or(G,U=new Map){let j=En(G.map(t)).scriptIndex;if(j===null)return gr;let K=G[j],re=Co(K);if(oo(K,re))return{kind:"literal",source:re};let oe=K?Kn(K,U):null;return oe===null?zr:{kind:"literal",source:oe}}var A_=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function uc(G){if(G.words.length!==2||G.redirections.length!==0||G.nested.length!==1)return!1;let U=G.words[0],j=G.words[1];if(!U||U.provenance!=="literal"||U.quoted||U.raw!==U.text||!j)return!1;if(!(U.text==="eval"&&j.quoted&&j.parts.length===3&&j.parts[0]?.raw==='"'&&j.parts[1]?.provenance==="command-substitution"&&j.parts[1].raw.startsWith("$(")&&j.parts[2]?.raw==='"'||U.text==="eval"&&!j.quoted&&j.parts.length===1&&j.parts[0]?.provenance==="command-substitution"&&j.parts[0].raw.startsWith("$(")||(U.text==="source"||U.text===".")&&!j.quoted&&j.parts.length===1&&j.parts[0]?.provenance==="command-substitution"&&j.parts[0].raw.startsWith("<(")))return!1;let re=G.nested[0];if(re?.status!=="complete"||re.nodes.length!==1)return!1;let oe=re.nodes[0];if(oe?.kind!=="command"||oe.redirections.length!==0||oe.nested.length!==0||oe.words.some((we)=>we.provenance!=="literal"||we.parts.some((We)=>We.provenance!=="literal")))return!1;let de=oe.words[0]?.text;if(de===void 0||On(de)!==null)return!1;let Se=Ot(Dt(de));return!A_.has(Se)&&!qt.has(Se)&&!Wr(Se)}function dp(G){return En(G.map(t)).commandIndex??-1}function P_(G){let U=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(G.trim()),j=U?.[4]??G.trim(),K=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(j),re=(K?.[3]??j).split(/\s+/).map(T_);if(re.length===0||re.some((oe)=>oe===null))return null;return{command:K?.[1]??null,optionTerminator:K?.[2]!==void 0,references:re.filter((oe)=>!!oe),ifs:U?U[1]??U[2]??U[3]??"":`
|
|
40
|
+
`}}function T_(G){let U=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(G),j=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(G),K=U??j;if(!K)return null;let re=K[1]??K[2];return{parameter:re==="@"||re==="*"?re:Number(re),quoted:U!==null}}function I_(G,U,j,K){let re=U.slice(j+2);if(G.parameter==="@")return G.quoted?lc(re):k_(re,K);if(G.parameter==="*"){let Se=lc(re);if(!Se)return;let we=Se.join(K[0]??"");return G.quoted?[we]:cc(we,K)}let oe=U[j+1+G.parameter];if(oe&&!yi(oe))return;let de=Co(oe);return G.quoted?[de]:cc(de,K)}function lc(G){return G.every(yi)?G.map(t):void 0}function k_(G,U){let j=lc(G);if(!j)return;let K=j.map((re)=>cc(re,U));return K.some((re)=>re===void 0)?void 0:K.flatMap((re)=>re??[])}function cc(G,U){if(["*","?","[","]"].some((j)=>G.includes(j)))return;if(U==="")return G===""?[]:[G];if(U===`
|
|
41
41
|
`)return G.trim().split(/\s+/).filter(Boolean);if(U.length!==1)return;return U===" "||U==="\t"||U===`
|
|
42
|
-
`?G.trim().split(/\s+/).filter(Boolean):G.split(U).filter(Boolean)}function yi(G){if(!G)return!0;return G.provenance==="unknown"?!/[$`]/.test(t(G)):G.provenance==="literal"}function Co(G){return G?t(G):""}function Bs(G){return`'${G.replaceAll("'",`'"'"'`)}'`}function mc(G,U){return dc(y(G,"posix"),U)}function bi(G){return mc(G,new Set(Array.from(G.matchAll(op)).flatMap((U)=>{let j=U[1]??U[2];return j===void 0?[]:[j]})))}function dc(G,U){if(G.status==="invalid"||G.status==="limited")return!1;let j=new Set(U);for(let K of G.nodes){if(K.kind==="group"){if(dc(K.body,j))return!0;continue}if(K.kind!=="command")continue;if(K.nested.some((re)=>dc(re,j))||up(K.words,j))return!0;N_(K,j)}return!1}function up(G,U){let j=G.findIndex((de)=>On(de.text)===null);if(j===-1)return!1;let K=G[j];if(!K)return!1;if(hi(K,U))return!0;let re=Mt(K.text);if(re==="source"||re==="."){let de=G[j+1]?.text==="--"?j+2:j+1;return rp(G[de],U)}if(qt.has(re)){let de=G.slice(j),Se=En(de.map((We)=>We.text)),we=Se.commandIndex??Se.scriptIndex;return!Se.syntaxCheck&&we!==null&&rp(de[we],U)}let oe=k_(G,j,U);if(oe===null)return!1;if(oe===-1)return!0;return up(G.slice(oe),U)}function k_(G,U,j){let K=Mt(G[U]?.text??"");if(K==="command")return O_(G,U+1);if(K==="exec")return M_(G,U+1);if(K==="env")return D_(G,U+1,j);return null}function O_(G,U){for(let j=U;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return G[j+1]?j+1:null;if(/^-[p]*[vV][pvV]*$/.test(K))return null;if(/^-p+$/.test(K))continue;return j}return null}function M_(G,U){for(let j=U;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return G[j+1]?j+1:null;if(K==="-a"){j++;continue}if(/^-a.+/.test(K)||/^-[cl]+$/.test(K))continue;return j}return null}function D_(G,U,j){for(let K=U;K<G.length;K++){let re=G[K],oe=re?.text??"";if(oe==="--")return G[K+1]?K+1:null;if(oe==="-S"||oe==="--split-string")return hi(G[K+1],j)?-1:K+2;if(oe.startsWith("-S")||oe.startsWith("--split-string="))return hi(re,j)?-1:K+1;if(oe==="-u"||oe==="--unset"||oe==="-C"||oe==="--chdir"||oe==="-P"){K++;continue}if(oe==="-i"||oe==="-0"||oe==="--null"||oe.startsWith("-u=")||oe.startsWith("--unset=")||oe.startsWith("-C")||oe.startsWith("--chdir=")||oe.startsWith("-P"))continue;if(oe.startsWith("-"))continue;if(On(oe))continue;return K}return null}function N_(G,U){if(!G.words.every((j)=>On(j.text)!==null))return;for(let j of G.words){let K=On(j.text);if(!K)continue;if(hi(j,U))U.add(K.name)}}function hi(G,U){if(!G)return!1;return G.parts.filter((j)=>j.provenance==="variable").some((j)=>Array.from(j.raw.matchAll(op)).some((K)=>{let re=K[1]??K[2];return re!==void 0&&(x_.test(re)||U.has(re))}))}function rp(G,U){return!!G&&(G.parts.some((j)=>j.provenance!=="literal"&&j.provenance!=="variable")||hi(G,U))}var fc="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",pc="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",L_="__CC_SAFETY_NET_XARGS_INPUT__",Us="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",Hs="rm",W_=/(?:^|[;&|]\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,F_=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,G_=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,z_=/^(?:[0-9]+|[@*])$/;function pp(G,U){let j=G.map(t),{childStart:K,replacementToken:re}=$r(j),oe=j.slice(K),de=Rt("xargs.shell-dynamic",pc);if(B_(oe,re,U)&&Tt(de,U.policy))return Tt(de,U.policy);for(let Se of zn(oe,U)){let we=Se.tokens,We=re!==null&&we[0]!==oe[0]&&(we[0]?.includes(re)??!1)?Tt(de,U.policy):null;if(We)return We;let mt=Sp(we,re,Se.wrapperEnvAssignments),gt=Se.head==="rm"&&re!==null&&bp(we,re),ft=U.analyzeChild(we,{...Fr(Se,U),dynamicInput:mt,dynamicSourceInput:gt||hp(we,Se.head,re,Se.wrapperEnvAssignments,mt,U.environment,U.strict?void 0:U.analyzeNested),dynamicRmInput:gt,shellDynamicMatch:de,dynamicSourceMatch:de,rmDynamicMatch:Rt("xargs.rm-recursive-force-dynamic",fc)});if(ft)return ft;let pt=$_(we,re,U.policy?.rules??[],Tt(de,U.policy));if(pt)return pt;if(Se.head==="git"){let yt=re===null?[...we,L_]:we,bt=re!==null&&(we.some((vt)=>vt.includes(re))||Array.from(Se.envAssignments.values()).some((vt)=>vt.includes(re))),Ct=U.analyzeChild(yt,{...Fr(Se,U),worktreeMode:re===null||bt?!1:U.worktreeMode});if(Ct)return Ct}let ht=A(we,U.policy?.rules??[]);if(ht)return ht}return null}function $_(G,U,j,K){if(j.length===0)return null;if(U===null){for(let oe of j){let de=A([...G,...oe.subcommand?[oe.subcommand]:[],...oe.block_args],j);if(de)return de}return null}let re=Mt(G[0]??"");if(!j.some((oe)=>Mt(oe.command)===re))return null;return G.slice(1).some((oe)=>oe.includes(U))?K:null}function gp(G,U,j){let K=G.indexOf(U);if(K===-1||G.indexOf(U,K+U.length)!==-1)return[];let re=ep(G,K,U.length,j);return re===null?[]:[re]}function hp(G,U,j,K,re,oe,de){if(qt.has(U)){if(nr(G))return!1;if(j!==null&&U_(G,j,de))return!0;let Se=$n(G);if(!Se){let we=or(Kt(G));if(we.kind==="literal")return j!==null&&we.source.includes(j);return we.kind==="none"&&re}if(j!==null&&Se.includes(j)&&!yp(Se,j,de))return!0;if(kn(Se))return!0;return H_(Se,j,K)}if(Ln(U))return mp(G,j,ds,bm(U));if(In.has(U))return mp(G,j,jl,vf);if(U==="eval"){let Se=zs(Kt(G));if(Se.kind==="dynamic")return!0;if(j!==null)return Se.kind==="literal"&&Se.source.includes(j);return re}if(U==="find")return j_(G,j,oe);if(U==="git"){let Se=wn(G);return j===null?Se.subcommand===null:(Se.subcommand?.includes(j)??!1)||Se.subcommand!==null&&yo.has(Se.subcommand.toLowerCase())&&Cp(Se.rest,j).some((we)=>we.includes(j))}return!1}function yp(G,U,j){if(j===void 0)return!1;let K=U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`(?:^|[;&|({!\`\\n]|\\b(?:then|do|else|elif|if|while|until|time|command|builtin|nohup|eval|exec|source))\\s*(?:[A-Za-z_][A-Za-z0-9_]*=\\S*\\s+)*["']?${K}`).test(G)||/\bcase\b/.test(G))return!1;let oe=G.replaceAll(U,"/");return kn(oe)===null&&j(oe)===null}function mp(G,U,j,K){let re=j(G);if(U===null)return re.optionsOpen||j([...G,Us]).sources.some((Se)=>Se.value===Us);if(re.sources.some((Se)=>Se.value.includes(U)))return!0;let oe=K.flatMap((Se)=>[Se.selector,...Se.valueForm==="attached-only"||Se.valueForm==="attached-or-separate"?[`${Se.selector}${Us}`]:[],...Se.valueForm==="equals-or-separate"?[`${Se.selector}=${Us}`]:[]]),de=new Set(oe.flatMap((Se)=>G.flatMap((we)=>gp(we,U,Se))));return Fs(re.sources,de,(Se)=>j(G.map((we)=>we.replaceAll(U,Se))).sources)}function B_(G,U,j){if(G.length===0||(G[0]??"").toLowerCase()==="command")return!1;let K=new Set(Array.from(zn(G,j),(oe)=>oe.head)),re=U===null?[...G,Hs]:G.map((oe,de)=>de===0?oe:oe.replaceAll(U,Hs));return Array.from(zn(re,j)).some((oe)=>oe.head===Hs&&!K.has(Hs))}function bp(G,U){return Cp(G.slice(1),U).some((j)=>j.includes(U)&&(j.startsWith("-")||j.startsWith(U)))}function Cp(G,U){let j=G.findIndex((K)=>K==="--"&&!K.includes(U));return j===-1?G:G.slice(0,j)}function Sp(G,U,j){if(U===null)return!0;return G.some((K)=>K.includes(U))||Array.from(j.values()).some((K)=>K.includes(U))}function U_(G,U,j){let K=En(G),re=K.commandIndex===null?"":G[K.commandIndex]??"";if(re.includes(U)&&!yp(re,U,j)||K.scriptIndex!==null&&(G[K.scriptIndex]??"").includes(U))return!0;return["-c","-nc","-cn",`--${U}`,U].some((de)=>G.some((Se,we)=>{if(we===0||!Se.includes(U))return!1;return gp(Se,U,de).some((mt)=>{let gt=G.map((pt,ht)=>ht===we?pt.replaceAll(U,mt):pt),ft=En(gt);if(ft.commandIndex===null&&ft.scriptIndex===null)return!1;if(K.commandIndex===null&&ft.commandIndex!==null)return!0;if(K.scriptIndex===null&&ft.scriptIndex!==null)return!0;if(ft.commandIndex!==null&&(gt[ft.commandIndex]??"").includes(mt))return!0;return ft.scriptIndex!==null&&(gt[ft.scriptIndex]??"").includes(mt)})}))}function H_(G,U,j){let K=new Set(U===null?[]:Array.from(j).filter(([,re])=>re.includes(U)).map(([re])=>re));for(let re of G.matchAll(W_))if(fp(re,K))return!0;for(let re of G.matchAll(F_))for(let oe of(re[1]??"").matchAll(G_))if(fp(oe,K))return!0;return mc(G,K)}function fp(G,U){let j=G[1]??G[2];return j!==void 0&&(z_.test(j)||U.has(j))}function j_(G,U,j){if(U===null)return!0;let K=!1,re=0;for(let oe=1;oe<G.length;oe++){let de=G[oe]??"";if(!K&&!de.startsWith("-")&&de!=="!"&&de!=="("){if(de.indexOf(U)===0)return!0;continue}if(K=!0,re>0){re--;continue}if(Vn(de)){let we=ho(G,oe);oe=we.nextIndex-1;for(let We of zn(we.tokens,{environment:j,cwd:void 0})){let mt=Sp(We.tokens,U,We.wrapperEnvAssignments);if(We.head==="rm"&&bp(We.tokens,U)||hp(We.tokens,We.head,U,We.wrapperEnvAssignments,mt,j))return!0}continue}let Se=rr(de);if(Se>0){if(re=Se,de.includes(U))return!0;continue}if(de.includes(U))return!0}return!1}function $r(G){let U=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,K=1;while(K<G.length){let re=G[K];if(!re)break;if(re==="--")return{childStart:K+1,replacementToken:j};if(!re.startsWith("-"))return{childStart:K,replacementToken:j};if(re==="-I"){j=G[K+1]??"{}",K+=2;continue}if(re.startsWith("-I")&&re.length>2){j=re.slice(2),K++;continue}if(re==="--replace"){j="{}",K++;continue}if(re.startsWith("--replace=")){let oe=re.slice(10);j=oe===""?"{}":oe,K++;continue}if(re==="-J"){j=G[K+1]??"{}",K+=2;continue}K+=U.has(re)?2:1}return{childStart:G.length,replacementToken:j}}var Ci="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",Si="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",K_="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",q_="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Vs=/\{[^{}\s]*\}/g,vp=/\{\}|\{-?\d+\}/g,Ep=/[\s;&|<>()$`\\"']/,Y_=["e","f","source","file","-e","-f","--source","--file"],Z_=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],X_=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),J_=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),Rp=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),Q_=new Set(["--workdir","--wd"]),xp="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Mn(G,U){for(let j of G){let K=U(j);if(K)return K}return null}function Ap(G){return Mn([...G],(U)=>kn(U))}function Pp(G,U){let j=G.map(t);if((U.envAssignments?.has("PARALLEL")?U.envAssignments.get("PARALLEL"):U.environment.env.get("PARALLEL"))?.trim()){let ht=So(U);if(ht)return ht}if(j.length===2&&(j[1]==="--version"||j[1]==="--help"))return null;let re=zp(j),{template:oe,jobs:de,runsRemotely:Se,readsCommandsFromInput:we,unsupported:We,workdir:mt,dryRun:gt}=re;if(We){let ht=So(U);if(ht)return ht;let yt=Ap(U.envAssignments?.values()??[]);if(yt)return yt}if(we){let ht=sw(U);if(ht)return ht}if(mt!==void 0&&Se){let ht=So(U);if(ht)return ht}let ft=aw(mt,U.cwd,U.environment.paths);if(ft===null){let ht=So(U);if(ht)return ht}let pt=Se?{...U,cwd:void 0,originalCwd:void 0}:ft===null||ft===void 0||ft===U.cwd?U:{...U,cwd:ft};if(gt){if([...zn(oe,pt)].flatMap((yt)=>[...yt.envAssignments.values()]).some(yc)){let yt=So(U);if(yt)return yt}return null}if(oe.length===0){let ht=de.map((bt)=>bt[0]??"");U.budget.charge("derivedTokens",ht.length);let yt=Dp(pt.envAssignments,pt.cwd,Se);return Mn(ht,(bt)=>U.analyzeNested(bt,yt))}return Mn(zn(oe,pt),(ht)=>ew(ht,re,U,pt))}function ew(G,U,j,K){let{templateHasPlaceholder:re,runsRemotely:oe,usesStdin:de}=U,Se=G.tokens,we=[...G.envAssignments.values()];if(we.some(Fp)){let Et=So(j);if(Et)return Et}let We=Ap(we);if(We)return We;let mt=we.some(Gt),gt=re||mt,ft=de&>,pt=Dp(G.envAssignments,G.wrapperCwd,oe||ft),ht=gt?{...pt,worktreeMode:!1}:pt,yt=Se.join(" "),bt=Gt(yt.split(/[ \t\n=]/,1)[0]??""),Ct=!U.quotesCommand&&(bt||Se.some((Et)=>Ep.test(Et))),vt=bt||Ep.test(Se[0]??""),St=Ct&&vt&&U.jobs.length>0?null:tw(G,U,j,K,ht,mt);if(St||!Ct)return St;return Tp(Gt(yt)?yt:`${yt} {}`,!bt,G,U,j,K,ht)}function tw(G,U,j,K,re,oe){let{jobs:de,templateHasPlaceholder:Se,runsRemotely:we,usesStdin:We}=U,mt=G.tokens,gt=Se||oe;if(qt.has(G.head)){let pt=()=>{if(!Se||de.length===0)return null;return Mn(de,(bt)=>j.analyzeChild(js(mt,bt,j.budget),Fr(G,K)))};if(nr(mt))return pt();let ht=$n(mt);if(ht){if(Gp(ht)){let St=hr(j);if(St)return St;if(de.length===0)return null;return Mn(de,(Et)=>j.analyzeNested(Lp(ht,Et,j.budget),re))}if(Gt(ht))return Tp(ht,!1,G,U,j,K,re);let bt=!oe&&(!Se||de.length>0)?(de.length>0?de:[void 0]).map((St)=>$s(Kt(St===void 0?mt:Se?mt.map((Et)=>Np(Et,St)):[...mt,...St]),ht)):[];if(bt.some((St)=>St.kind==="dynamic")){let St=hr(j);if(St)return St}let Ct=bt.flatMap((St)=>St.kind==="literal"?[St.source]:[]);if(Ct.length>0)return j.budget.charge("derivedTokens",Ct.length),Mn(Ct,(St)=>j.analyzeNested(St,re));if(bi(ht)){let St=hr(j);if(St)return St}let vt=j.analyzeNested(ht,re);if(vt)return vt;if(gt)return hr(j);return null}let yt=or(Kt(mt));if(yt.kind==="dynamic"||yt.kind==="literal"&&Gt(yt.source))return hr(j)??pt();if(yt.kind==="literal")return pt();if(de.length>0){let bt=hr(j);if(bt)return bt;let Ct=pt();if(Ct)return Ct;if(Se)return null;let vt=de.flatMap((St)=>St[0]===void 0?[]:[St[0]]);return j.budget.charge("derivedTokens",vt.length),Mn(vt,(St)=>j.analyzeNested(St,re))}if(gt||We)return hr(j)??pt();return null}if(G.head==="rm"&&tr(mt)){if(Se&&de.length>0)return Mn(de,(ht)=>gc(js(mt,ht,j.budget,vp),G.cwd,K));if(de.length>0)return Mn(de,(ht)=>gc(wp(mt,ht,j.budget),G.cwd,K));let pt=gc(mt.flatMap((ht,yt)=>{if(yt===0||!Gt(ht))return[ht];return ht.startsWith("-")?[ht.replace(vp,"")]:[]}),G.cwd,K);if(pt)return pt;return Mp(j)}let ft=de.length>0?de:[void 0];return Mn(ft,(pt)=>{let ht=pt===void 0?mt:Se?js(mt,pt,j.budget):wp(mt,pt,j.budget),yt=Rt("parallel.shell-dynamic",Si),bt=We&&G.head==="find"?iw(ht,K):null,Ct=kp(ht,We,j)??bt?.customResult??null,vt=Mt(G.head),St=We&&(vt==="rm"&&hc(ht)||vt==="xargs"&&Op(ht)||bt?.rmOptions===!0),Et=We&&(St||bt?.executedSource===!0||bt===null&&Ip(ht,vt)),_t=j.analyzeChild(ht,{...Fr(G,K),worktreeMode:we||We||gt?!1:j.worktreeMode,dynamicInput:We||gt,dynamicRmInput:St,dynamicSourceInput:Ct!==null||Et,shellDynamicMatch:yt,dynamicSourceMatch:yt,rmDynamicMatch:Rt("parallel.rm-recursive-force-dynamic",Ci)});if(Et){let Pt=Tt(yt,j.policy);if(Pt)return Pt}return _t??Ct??A(ht,j.policy?.rules??[])})}function Tp(G,U,j,K,re,oe,de){if(K.jobs.length>0)return Mn(K.jobs,(We)=>re.analyzeNested(Lp(G,U?We.map(Bs):We,re.budget),de));let Se=gi(G);if(Se?.[0]&&Mt(Se[0])==="rm"&&tr(Se)){let We=Mp(re);if(We)return We}return(Se?re.analyzeChild(Se,{...Fr(j,oe),dynamicInput:K.usesStdin,shellDynamicMatch:Rt("parallel.shell-dynamic",Si),rmDynamicMatch:Rt("parallel.rm-recursive-force-dynamic",Ci)}):null)??re.analyzeNested(G,de)}function Ip(G,U){if(Gt(G[0]??""))return!0;if(U==="eval"||U==="source"||U===".")return!0;if(U==="parallel"||U==="xargs")return!0;if(qt.has(U))return ow(G);if(U==="git")return nw(G);if(U==="find")return!0;if(In.has(U))return _p(G,Y_,fi);if(Ln(U))return _p(G,Z_,cs);return!1}function hc(G){let U=G.indexOf("--"),j=G.slice(1,U===-1?void 0:U);if(!G.some(Gt))return U===-1;return j.some((re)=>Gt(re)&&(re.startsWith("-")||Gp(re)))}function nw(G){if(rw(G))return!0;let U=wn(G);if(U.subcommand===null||Gt(U.subcommand))return!0;if(!yo.has(U.subcommand.toLowerCase()))return!1;let j=U.rest.indexOf("--"),K=U.rest.slice(0,j===-1?void 0:j);if(!G.some(Gt))return j===-1;return K.some(Gt)}function rw(G){for(let U=1;U<G.length;U++){let j=G[U];if(!j||j==="--"||!j.startsWith("-"))return!1;if(j==="-c"||j==="--config-env"){if(Gt(G[U+1]??""))return!0;U++;continue}if(j.startsWith("-c")&&j.length>2||j.startsWith("--config-env=")){if(Gt(j))return!0;continue}if(Gt(j))return!0}return!1}function ow(G){if(nr(G))return!1;let U=$n(G);if(U!==null)return Gt(U);let j=or(Kt(G));if(j.kind==="literal")return Gt(j.source);if(j.kind==="dynamic")return!0;return!G.some(Gt)}function _p(G,U,j){let K=j(G);if(K.some((re)=>Gt(re.value)))return!0;if(!G.some(Gt))return j([...G,xp]).some((re)=>re.value===xp);return Fs(K,U,(re)=>j(G.map((oe)=>Np(oe,[re]))))}function kp(G,U,j){let K=j.policy?.rules??[];if(!U||K.length===0)return null;let re=K.filter((oe)=>Mt(oe.command)===Mt(G[0]??""));if(re.length===0)return null;if(G.slice(1).some(Gt))return hr(j);return Mn(re,(oe)=>A([...G,...oe.subcommand?[oe.subcommand]:[],...oe.block_args],[oe]))}function iw(G,U){let j={customResult:null,executedSource:!G.some(Gt),rmOptions:!1},K=!1,re=0,oe=null,de=()=>{if(!oe?.some(Gt))return;for(let Se of zn(oe,U))j.executedSource||=Ip(Se.tokens,Se.head),j.rmOptions||=Se.head==="rm"&&hc(Se.tokens)||Se.head==="xargs"&&Op(Se.tokens),j.customResult??=kp(Se.tokens,!0,U)};for(let Se of G.slice(1)){if(!K&&!Se.startsWith("-")&&Se!=="!"&&Se!=="("){j.executedSource||=Gt(Se);continue}if(K=!0,oe){if(Se===";"||Se==="+"){de(),oe=null;continue}oe.push(Se);continue}if(re>0){re--;continue}if(Vn(Se)){oe=[],j.executedSource||=Gt(Se);continue}let we=rr(Se);if(we>0){re=we,j.executedSource||=Gt(Se);continue}j.executedSource||=Gt(Se)}return de(),j}function Op(G){let U=G.slice($r(G).childStart);return Mt(U[0]??"")==="rm"&&hc(U)}function Ks(G,U){return(j)=>Tt(Rt(G,U),j.policy)}var hr=Ks("parallel.shell-dynamic",Si),sw=Ks("parallel.command-stream-dynamic",K_),So=Ks("parallel.command-stream-dynamic",q_),Mp=Ks("parallel.rm-recursive-force-dynamic",Ci);function gc(G,U,j){return Tt(Gs(Kt(G),{environment:j.environment,cwd:U,budget:j.budget,originalCwd:j.originalCwd,strict:j.strict,paranoid:j.paranoidRm,allowTmpdirVar:j.allowTmpdirVar,tmpdirWordSplittingUnsafe:Dr(j.envAssignments??new Map,j.environment),trustedTmpdirValue:uo(j.envAssignments??new Map,j.environment),protectedGitMetadata:j.protectedGitMetadata,policy:j.policy}),j.policy)}function Dp(G,U,j){let K={};if(G)K.envAssignments=G;if(j)return K.effectiveCwd=null,K.worktreeMode=!1,K;if(U!==void 0)K.effectiveCwd=U;return Object.keys(K).length>0?K:void 0}function Np(G,U){return G.replace(Vs,(j)=>Wp(j,U))}function js(G,U,j,K=Vs){return j.charge("derivedTokens",G.reduce((re,oe)=>re+1+Math.floor(oe.length/64),0)),G.map((re)=>re.replace(K,(oe)=>{let de=Wp(oe,U);return j.charge("derivedTokens",Math.max(1,Math.ceil(de.length/64))),de}))}function Lp(G,U,j){return js([G],U,j)[0]??""}function wp(G,U,j){return j.charge("derivedTokens",G.length+U.length),[...G,...U]}function Wp(G,U){let j=/^\{(-?\d+)[^{}\s]*\}$/.exec(G)?.[1];if(j===void 0)return U[0]??"";let K=Number(j);return U[K>0?K-1:U.length+K]??""}function Gt(G){return G.search(Vs)!==-1}function Fp(G){if(yc(G))return!0;for(let U of G.matchAll(Vs))if(!/^(?:\{\}|\{\d+\})$/.test(U[0]))return!0;return!1}function yc(G){let U=G.indexOf("{=");return U!==-1&&G.indexOf("=}",U+2)!==-1}function Gp(G){return/^\{[^{}\s]*\}$/.test(G)}function aw(G,U,j){if(G===void 0)return;if(G==="..."||/^~|[{}$`*?[]/.test(G))return null;if(!U&&!V_(G))return null;try{return dr(U??G,G,j)}catch{return null}}function zp(G){let U=1,j=[],K=G.length,re=-1,oe=!1,de=!1,Se=!1,we,We=!1,mt=G.some((yt)=>yt==="::::"||yt==="::::+"||yt===":::+");while(U<G.length){let yt=G[U];if(yt===void 0)break;if(yt===":::"){re=U;break}if(yt==="--"){let Et=ql(G,U+1);j.push(...Et.templateTokens),K=U+1,re=Et.markerIndex;break}if(!yt.startsWith("-")){let Et=ql(G,U);j.push(...Et.templateTokens),K=U,re=Et.markerIndex;break}let bt=G[U+1],Ct=yt.indexOf("="),vt=Ct===-1?yt:yt.slice(0,Ct),St=Ct===-1?void 0:yt.slice(Ct+1);if(yt==="--dry-run"){We=!0,U++;continue}if(yt==="-I"||yt.startsWith("-I")&&yt.length>2){mt||=(yt==="-I"?bt:yt.slice(2))!=="{}",U+=yt==="-I"?2:1;continue}if(yt==="--replace"||yt==="-i"){mt=!0,U+=2;continue}if(vt==="--replace"||yt.startsWith("-i")&&yt.length>2){let Et=vt==="--replace"?St:yt.slice(2);mt||=Et!==""&&Et!=="{}",U++;continue}if(yt==="-a"||J_.has(vt)){mt=!0,U+=St===void 0?2:1;continue}if(yt==="-q"||yt==="--quote"){de=!0,U++;continue}if(yt==="--pipe"||yt==="--pipepart"){Se=!0,U++;continue}if(vt==="--env"){mt=!0,U+=St===void 0?2:1;continue}if(Rp.has(vt)||yt.startsWith("-S")&&yt.length>2){oe=!0,U+=Rp.has(yt)?2:1;continue}if(Q_.has(vt)){mt=!0;let Et=St??bt;if(Et===void 0||Et===":::"||Et==="--"){U++;continue}we=Et,U+=St===void 0?2:1;continue}if(yt.startsWith("-j")&&yt.length>2&&/^\d+$/.test(yt.slice(2))){U++;continue}if(yt.startsWith("--")&&St!==void 0){U++;continue}if(X_.has(yt)){if(bt===void 0||bt===":::"||bt==="--"){mt=!0,U++;continue}U+=2;continue}U+=yt==="-j"||yt==="--jobs"?2:1}mt||=j.some(We?yc:Fp);let gt=[];if(re!==-1){let yt=[];for(let bt=re+1;bt<G.length;bt++){let Ct=G[bt];if(Ct===":::"){gt.push(yt),yt=[];continue}if(Ct!==void 0)yt.push(Ct)}gt.push(yt)}mt||=gt.length>1;let ft=lw(gt),pt=j.some(Gt),ht=j.length===0&&re===-1;return{template:j,jobs:ft,childStart:K,templateHasPlaceholder:pt,runsRemotely:oe,quotesCommand:de,usesStdin:Se||re===-1,readsCommandsFromInput:ht,unsupported:mt,workdir:we,dryRun:We}}function lw(G){if(G.length===0||G.some((j)=>j.length===0))return[];let U=[[]];for(let[j,K]of G.entries()){if(K.length===1){let oe=K[0];if(oe===void 0)return[];for(let de of U)de.push(oe);if(U.length*(j+1)>a.derivedTokens.cap)throw new s("derivedTokens");continue}let re=[];for(let oe of U)for(let de of K){if((re.length+1)*(j+1)>a.derivedTokens.cap)throw new s("derivedTokens");re.push([...oe,de])}U=re}return U}function $p(G){return zp(G).childStart}var cw="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",qs="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function Cc(G){return G?.parts.some((U)=>U.provenance==="command-substitution")??!1}function bc(G){return G?.parts.some((U)=>U.provenance==="literal"&&U.raw.replace(/^["']/,"").startsWith("-"))??!1}function Up(G,U,j,K,re=!1,oe){let Se=(jo(G,U)||K&&G!=="powershell"&&U[0]?.provenance==="variable")&&Jt(oe,"shell.dynamic-executable",re)?Rt("shell.dynamic-executable",cw):null;return Tt(Se,oe)??Hp(G,U,j,re,oe)}function Hp(G,U,j,K,re){if(U.length<2)return null;let oe=U.flatMap((Se,we)=>Cc(Se)?[we]:[]);if(oe.length===0)return null;let de=Mt(U[0]?.text??"");if(de==="git"){let Se=ne(G,U),we=uw(Se);if(Jt(re,"shell.dynamic-structure",K)&&oe.some((gt)=>gt<=we))return Tt(Rt("shell.dynamic-structure",qs),re);if(Tt(Ws(Se,{environment:j}),re))return null;let We=U[we]?.text.toLowerCase(),mt=Se.findIndex((gt,ft)=>ft>we&&t(gt)==="--");if(Jt(re,"shell.dynamic-structure",K)&&We&&yo.has(We)&&oe.some((gt)=>gt>we&&(mt===-1||gt<mt)))return Tt(Rt("shell.dynamic-structure",qs),re);return null}if(de==="find")return Jt(re,"shell.dynamic-structure",K)&&mw(U)?Tt(Rt("shell.dynamic-structure",qs),re):null;if(de==="rm"){let Se=U.findIndex((We,mt)=>mt>0&&t(We)==="--"),we=tr(U.map(t));return Jt(re,"shell.dynamic-structure",K)&&oe.some((We)=>(Se===-1||We<Se)&&(We<U.length-1||!we))?Tt(Rt("shell.dynamic-structure",qs),re):null}if(de==="xargs")return Bp(G,U.slice($r(U.map(t)).childStart),"xargs",j,K,re);if(de==="parallel")return Bp(G,U.slice($p(U.map(t))),"parallel",j,K,re);return null}function Bp(G,U,j,K,re,oe){if(U.length===0)return null;let de=dw(U,K);if(jo(G,de)){let we=Tt(Rt(`${j}.shell-dynamic`,j==="xargs"?pc:Si),oe);if(we)return we}let Se=Hp(G,de,K,re,oe);if(Se)return Se;if(de[0]?.text==="rm"&&de.slice(1).some((we)=>Cc(we)&&bc(we)))return Tt(Rt(`${j}.rm-recursive-force-dynamic`,j==="xargs"?fc:Ci),oe);return null}function dw(G,U){let j=kr(G,U),K=j.rewritten?Kt(j.words.map(t)):j.words,re=K[0];return re&&t(re)==="busybox"?K.slice(1):K}function uw(G){let U=1;while(U<G.length){let j=G[U],K=j?t(j):"";if(vn.has(K)){U+=2;continue}if(K.startsWith("-")){U++;continue}return U}return U}function mw(G){let U=!1,j=0,K=!1,re=!1;for(let oe=1;oe<G.length;oe++){let de=G[oe];if(!de)continue;let Se=Cc(de);if(j>0){j--;continue}if(re){if(de.text===";"||de.text==="+"){re=!1,U=!0,K=!1;continue}if(Se&&(K||bc(de)))return!0;K=!1;continue}if(!U&&!de.text.startsWith("-")){if(Se&&(oe>1||bc(de)))return!0;continue}if(U=!0,Se)return!0;let we=rr(de.text);if(we>0){j=we;continue}if(Vn(de.text))re=!0,K=!0}return!1}function Sc(G,U){return G.some((j)=>{if(j.value==="-"&&(j.kind==="main-script"||j.kind==="program-file"))return!0;return!ro(U[j.tokenIndex],j.value)})}var jp="cmd rmdir /s or del /s outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",fw="cmd rmdir /s or del /s 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.",pw="cmd rmdir /s or del /s target contains wildcards or variables that cannot be verified safely. Use literal paths within cwd.",gw="cmd rmdir /s or del /s targeting root or home directory is extremely dangerous and always blocked.",hw="cmd rmdir /s or del /s with \\\" quoting or a \\\\?\\ path is blocked: cmd does not treat \\\" as an escape, so the target can split down to the root of the drive. Pass each path as its own quoted argument, or use Remove-Item -LiteralPath.",yw="cmd rmdir /s or del /s in home directory is dangerous. Change to a project directory first.",bw={root_or_home_target:{id:"cmd.recursive-delete-root-or-home",reason:gw},git_metadata_target:{id:"cmd.recursive-delete-git-metadata",reason:x},dynamic_target:{id:"cmd.recursive-delete-dynamic-target",reason:pw},home_cwd_target:{id:"cmd.recursive-delete-home-cwd",reason:yw},cwd_self_target:{id:"cmd.recursive-delete-cwd-self",reason:jp},within_anchored_cwd:{id:"cmd.recursive-delete-paranoid",reason:fw},outside_anchored_cwd:{id:"cmd.recursive-delete-outside-cwd",reason:jp}},Cw=/^\/\/?[ck]$/i,Vp=/[&|]+/,Sw=/(?:"[^"]*"|[^\s"])+/g,vw=/[\^%!]/,Ew=/\\"./s,Rw=/(^|\/)[*.]*\*[*.]*$/,xw=/^"?[\\/]+[?.][\\/]/,_w=new Set(["rmdir","rd","del","erase"]),ww=/(?<![\w-])(?:rmdir|rd|del|erase)(?!\w)/i,Aw=/\/s(?!\w)/i,Pw=/(?<![\w-])(?:cd|chdir|pushd|popd)(?!\w)/i;function Kp(G,U){let j=G.map(t),K=j.findIndex((ft)=>Cw.test(ft));if(K===-1)return null;let re=j.slice(K+1).join(" "),oe=/^".*"$/s.test(re)?re.slice(1,-1):re,de=oe.split(Vp).map((ft)=>{let pt=ft.match(Sw)??[],ht=pt.findIndex((bt)=>_w.has(bt.replace(/^@/,"").toLowerCase())),yt=ht===-1?[]:pt.slice(ht);return{piece:ft,tokens:pt,deleteTokens:yt,recursiveDelete:yt.slice(1).some((bt)=>bt.startsWith("/")&&bt.toLowerCase().split("/").includes("s"))}}),Se=de.filter((ft)=>ft.recursiveDelete),we=Se.length>0||ww.test(oe)&&Aw.test(oe);if(we&&(oe.includes("\\\"")||U.gitBashEscapesBodyQuotes&&oe.includes('"')||U.powerShellRawWords.some((ft)=>Ew.test(ft))||Se.some((ft)=>ft.tokens.some((pt)=>xw.test(pt)))))return Rt("cmd.recursive-delete-escaped-quote",hw);let We=jn({...U,allowPaths:U.policy?.destructiveCommandAllowPaths}),mt=de.reduce((ft,pt)=>ft??(pt.recursiveDelete?Tw(pt.deleteTokens,We,U.policy):U.analyzeNested(pt.piece)),null),gt=we&&(Se.length===0||vw.test(oe)||Pw.test(oe)||oe.includes('"')&&Vp.test(oe));return mt??(gt?go():null)}function Tw(G,U,j){return G.slice(1).filter((K)=>!K.startsWith("/")).reduce((K,re)=>K??Tt(Lr(_n(di(re.replaceAll('"',"")).replace(Rw,"$1*"),U),U,j,bw),j),null)}var Iw="Recursive delete handed to powershell or pwsh in a form CC Safety Net does not read is blocked: pass the script as a single -Command with literal paths, after only -NoProfile, -NonInteractive, -NoLogo, or -ExecutionPolicy.",kw=/^-(?:noprofile|nop|noninteractive|noni|nologo)$/i,Ow=/^-(?:executionpolicy|ep)$/i,Mw=/^-(?:command|c)$/i,Dw=/^(?:--?|[/\u2013\u2014\u2015])(\w+)$/,Nw="encodedcommand",Lw=/(?<![\w-])(?:remove-item|ri|rm|rmdir|rd|del|erase)(?![\w-])/i,Ww=/(?<![\w-])(?:[-\u2013\u2014\u2015]{1,2}r(?:e(?:c(?:u(?:r(?:s(?:e|ive?)?)?)?)?)?)?(?!\w)|-[dfipvwx]*r[dfipvwx]*(?!\w))|\/s(?!\w)/i,Fw=/[$`]/,Gw="--%";function qp(G,U){let j=G.map(t),K=j.every((oe,de)=>de===0||oe!==Gw&&zw(G[de],oe))?Ec(j):void 0;if(K!==void 0)return U(K);if(j.some($w))return go();let re=j.join(" ");return Lw.test(re)&&Ww.test(re)?Rt("powershell.nested-recursive-delete-unread",Iw):null}function Ec(G){let U=vc(G,1),j=U===void 0?[]:G.slice(U+1);return j.length>0?j.join(" "):void 0}function vc(G,U){let j=G[U]??"";if(Mw.test(j))return U;if(kw.test(j))return vc(G,U+1);return Ow.test(j)?vc(G,U+2):void 0}function zw(G,U){return G?.provenance==="unknown"?!Fw.test(U):ro(G,U)}function $w(G){let U=Dw.exec(G)?.[1]?.toLowerCase();return U!==void 0&&(U==="ec"||Nw.startsWith(U))}var Zp=[{heads:new Set(["rm","rmdir"]),analyze:(G)=>Gs(G.words,Rc(G))},{heads:new Set(["cmd"]),analyze:(G)=>Kp(G.words,{...Rc(G),powerShellRawWords:G.options.commandView?.dialect==="powershell"?G.options.commandView.words.map((U)=>U.raw):[],gitBashEscapesBodyQuotes:G.options.commandView?.dialect!=="powershell",analyzeNested:(U)=>yr(G.options.analyzeNested(U,{effectiveCwd:G.effectiveCwd,envAssignments:G.envAssignments}))})},{heads:new Set(["powershell","pwsh"]),analyze:(G)=>qp(G.parsedWords,(U)=>yr(G.options.analyzeNested(U,{effectiveCwd:G.effectiveCwd,envAssignments:G.envAssignments,shell:"powershell"})))},{heads:new Set(["git"]),analyze:(G)=>Ws(G.words,xc(G))},{heads:new Set(["find"]),analyze:(G)=>Tf(G.words,{...Rc(G),envAssignments:G.envAssignments,analyzeTokens:G.analyzeChildTokens})},{heads:new Set(["xargs"]),analyze:(G)=>pp(G.words,{...Yp(G),analyzeChild:G.analyzeChild,analyzeNested:(U,j)=>yr(G.options.analyzeNested(U,j))})},{heads:new Set(["parallel"]),analyze:(G)=>Pp(G.words,{...Yp(G),analyzeChild:G.analyzeChild,analyzeNested:(U,j)=>yr(G.options.analyzeNested(U,j))})}];function Yp(G){return{environment:G.options.environment,cwd:G.cwd,originalCwd:G.originalCwd,strict:G.options.strict,paranoidRm:G.options.paranoidRm,paranoidInterpreters:G.options.paranoidInterpreters,allowTmpdirVar:G.allowTmpdirVar,protectedGitMetadata:G.options.protectedGitMetadata,budget:G.options.budget,envAssignments:G.envAssignments,worktreeMode:G.options.worktreeMode,policy:G.options.policy}}function yr(G){return G?{id:G.ruleId,reason:G.reason,intent:G.intent??"manual_only"}:null}function Rc(G){return{environment:G.options.environment,cwd:G.cwd,originalCwd:G.originalCwd,strict:G.options.strict,paranoid:G.options.paranoidRm,allowTmpdirVar:G.allowTmpdirVar,tmpdirWordSplittingUnsafe:Dr(G.envAssignments,G.options.environment),trustedTmpdirValue:uo(G.envAssignments,G.options.environment),protectedGitMetadata:G.options.protectedGitMetadata,policy:G.options.policy,budget:G.options.budget}}function xc(G){return{environment:G.options.environment,cwd:G.cwd,originalCwd:G.originalCwd,dynamicArguments:G.dynamicArguments,envAssignments:G.envAssignments,shellAssignments:G.options.shellAssignments,policy:G.options.policy,worktreeMode:G.options.worktreeMode}}function Qp(G){return Zp.find((U)=>U.heads.has(G))?.analyze}function Eo(G,U,j){let K=j.trace;if(G.length===0)return null;let re=j.commandView?.dialect??"posix",oe=(At)=>At.map((Ot)=>re==="posix"?t(Ot):Ot.text),de=j.child,Se=de!==void 0&&!de.embedded,we=de?.embedded===!0,We=j.effectiveCwd===null,mt=de?de.cwd:We?void 0:j.effectiveCwd??j.cwd,gt=de?de.originalCwd:We?void 0:j.cwd,ft=ve(G);if(ft.envAssignments.size>0)K?.recordSegment({type:"env-strip",input:oe(G),envVars:[...ft.envAssignments.keys()],output:oe(ft.words)});let pt=kr(ft.words,j.environment,mt,new Map([...j.envAssignments??[],...ft.envAssignments])),ht=pt.envSplitValues??[];if(ht.length>0){let At=[...ht,...oe(pt.words)].join(" "),Ot=kn(At);if(Ot)return K?.recordSegment({type:"dangerous-text",token:At,matched:!0,reason:Ot.reason}),un(Ot);if(j.strict)return bn(K);let zt=ps(ht,oe(pt.words));if(zt){j.budget.charge("derivedTokens",zt.length);let tn=j.analyzeNested(zt.join(" "),{effectiveCwd:pt.cwd===void 0?j.effectiveCwd:pt.cwd,envAssignments:new Map([...j.envAssignments??[],...ft.envAssignments,...pt.envAssignments])});if(tn)return tn}}let yt=pt.rewritten?Kt(oe(pt.words)):ne(re,pt.words),bt=oe(yt),Ct={...j,wrapperNormalizationBudget:j.wrapperNormalizationBudget??{iterations:0}};if(K&&ft.words.length>yt.length){let At=oe(ft.words);K.recordSegment({type:"leading-tokens-stripped",input:At,removed:At.slice(0,At.length-yt.length),output:bt})}let vt=new Map([...j.envAssignments??[],...ft.envAssignments,...pt.envAssignments]),St=bt[0];if(!St)return null;if(Wr(St))throw new s("wrapperPeelIterations");let Et=Mt(St),_t=pt.cwd===null?void 0:pt.cwd??mt,Pt=pt.cwd===null?void 0:gt,It=pt.cwd===void 0?j.effectiveCwd:pt.cwd,wt=de?de.allowTmpdirVar:!li(vt,j.environment),Lt=Up(re,pt.words,j.environment,U===0,j.strict,j.policy);if(Lt)return K?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:Lt.reason}),un(Lt);let Bt=ks(bt,j.policy);if(Bt){for(let At of[Bt.childIndex,...Bt.alternativeChildIndices]){Xp(Ct.wrapperNormalizationBudget);let Ot=yt.slice(At);K?.recordSegment({type:"transparent-wrapper",wrapper:Bt.wrapper,output:oe(Ot)});let zt=Eo(Ot,U,{...Ct,effectiveCwd:It,envAssignments:vt});if(zt)return zt}return null}let en=we?void 0:Et==="eval"?zs(yt):Et==="trap"&&!Se?ap(yt):void 0;if(Se&&de&&Et==="eval"){if(en?.kind==="dynamic")return vo(de,j.policy);if(en?.kind==="literal"){let At=j.analyzeNested(en.source,{effectiveCwd:It,envAssignments:vt});if(At)return At}return Ro(de,j.policy)}if(en?.kind==="dynamic"&&(j.strict||!j.commandView||!uc(j.commandView)))return bn(K);if(en?.kind==="literal"){K?.recordSegment({type:"recurse",reason:Et==="eval"?"shell-eval":"shell-trap",innerCommand:en.source,depth:U+1});let At=j.analyzeNested(en.source,{effectiveCwd:It,envAssignments:vt,functionDefinitions:j.functionDefinitions});if(At)return At}if(Se?qt.has(Et):tg(St,Et)){if(nr(bt))return null;if(Se&&de){let At=$n(bt);if(At){if(de.dynamicSourceInput??de.dynamicInput){let zt=vo(de,j.policy);if(zt)return zt}if(bi(At)){let zt=vo(de,j.policy);if(zt)return zt}return j.analyzeNested(At,{effectiveCwd:It,envAssignments:vt})}let Ot=or(yt);if(Ot.kind==="dynamic")return vo(de,j.policy);if(Ot.kind==="literal")return de.dynamicSourceInput?vo(de,j.policy):null;return de.dynamicSourceInput??de.dynamicInput?vo(de,j.policy):null}if(we){let At=$n(bt),Ot=At?j.analyzeNested(At,{effectiveCwd:It,envAssignments:vt}):or(yt).kind==="dynamic"?bn(K):null;if(Ot)return Ot}if(de===void 0){let At=jw(bt,vt,It,j,K,U);if(At)return At;let Ot=$n(bt);if(Ot){let Vr=$s(yt,Ot);if(Vr.kind==="dynamic")return bn(K);let la=Vr.kind==="literal"?Vr.source:lp(yt,Ot),Zc=Vw(la);K?.recordSegment({type:"shell-wrapper",wrapper:Et,innerCommand:Zc}),K?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:Zc,depth:U+1});let Xc=j.analyzeNested(la,{effectiveCwd:It,envAssignments:vt});if(Xc)return Xc;return bi(la)?bn(K):null}let zt=or(yt,j.strict?void 0:j.shellAssignments);if(zt.kind==="dynamic")return bn(K);if(zt.kind==="literal")return Ys(zt.source,It,vt,j,K,U);let tn=cp(yt,j.commandView?.redirections??[],j.hasPipelineInput??!1,j.literalShellInput);if(tn.kind==="dynamic")return bn(K);if(tn.kind==="literal")return K?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:tn.source,depth:U+1}),j.analyzeNested(tn.source,{effectiveCwd:It,envAssignments:vt})}}if(!de&&(Et==="source"||Et===".")){let At=bt[1]==="-p"?2:null;if(At!==null){let Vr=j.commandView?yt[At]:void 0;if(!Vr)return null;if(Vr.provenance!=="literal")return bn(K)}let Ot=At===null?1:3,zt=bt[Ot]==="--"?Ot+1:Ot,tn=j.commandView?yt[zt]:void 0;if(!tn)return null;if(tn.provenance==="literal")return Ys(tn.text,It,vt,j,K,U);if(j.strict||!j.commandView||!uc(j.commandView))return bn(K)}if(In.has(Et)&&!we){if(!de&&j.strict&&Sc(fi(bt),yt))return bn(K);let At=Ef(bt,(zt)=>yr(j.analyzeNested(zt,{effectiveCwd:It,envAssignments:vt}))),Ot=Tt(At,j.policy);if(Ot)return K?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:Ot.reason}),un(Ot)}if(Ln(Et)&&!we){if(!de&&j.strict&&Sc(cs(bt),yt))return bn(K);let At=ym(bt);if(Se&&de)return Uw(Et,At,It,vt,j,de);if(At){let Ot=Jt(j.policy,"interpreter.one-liner-paranoid",!!j.paranoidInterpreters);if(K?.recordSegment({type:"interpreter",interpreter:Et,codeArg:At,paranoidBlocked:Ot}),Ot){let tn=Tt(Rt("interpreter.one-liner-paranoid",ti),j.policy);if(tn)return un(tn)}if(wl(Et,At))return null;K?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:At,depth:U+1});let zt=j.analyzeNested(At,{effectiveCwd:It,envAssignments:vt});if(zt&&!eg(zt,At))return zt;if(ni(At,void 0,!j.strict)){let tn=Tt(Rt("interpreter.dangerous-command",so),j.policy);if(tn)return K?.recordSegment({type:"dangerous-text",token:At,matched:!0,reason:so}),un(tn)}K=void 0}}if(Et==="busybox"&&bt.length>1)return Xp(Ct.wrapperNormalizationBudget),K?.recordSegment({type:"busybox",subcommand:bt[1]??"unknown"}),K?.recordSegment({type:"recurse",reason:"busybox",innerCommand:bt.slice(1).join(" "),depth:U+1}),Eo(yt.slice(1),U,{...Ct,effectiveCwd:It,envAssignments:vt});let Ut=de?null:Tt(fm(Et,bt),j.policy);if(Ut)return K?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:Ut.reason}),un(Ut);let Ft=K===Ct.trace?Ct:{...Ct,trace:K},ln={words:yt,parsedWords:pt.words,head:Et,cwd:_t,originalCwd:Pt,envAssignments:vt,allowTmpdirVar:wt,dynamicArguments:pt.words.some((At)=>At.provenance==="command-substitution"),depth:U,effectiveCwd:It,options:Ft,analyzeChildTokens:(At,Ot)=>Se&&de?wc(At,U,Ft,{...de,cwd:Ot??void 0,effectiveCwd:Ot??void 0}):yr(Eo(Kt(At),U+1,{...Ft,child:void 0,commandView:void 0,effectiveCwd:Ot,envAssignments:vt}))??A(At,Ft.policy.rules),analyzeChild:(At,Ot)=>wc(At,U,Ft,Ot)},Zt=de&&(Et==="xargs"||Et==="parallel")?void 0:Qp(Et);if(Et==="rm"||Et==="xargs"||Et==="parallel")K?.recordSegment({type:"tmpdir-check",tmpdirValue:vt.has("TMPDIR")||j.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:wt});let Xt=K&&Et==="git"?Qf(ln.words,xc(ln)):void 0,Sn=Jp(Xt?Xt.match:Zt?.(ln)??null,j.policy);if(K)Kw(ln,Sn,Xt?.relaxation??null);if(Sn)return un(Sn);if(Se&&de&&(Et==="rm"||Et==="rmdir")){if(!(Et==="rm"&&(tr(bt)||de.dynamicRmInput)))return null;return(de.dynamicRmInput?Ro(de,j.policy):null)??Hw(de,j.policy)}let Yn=Zt!==void 0&&!Yw.has(Et),vr=!de&&!Yn&&!Fi.has(Et),To=K&&vr?[]:void 0;if(vr)for(let At=1;At<bt.length;At++){let Ot=bt[At];if(!Ot)continue;To?.push(Ot);let zt=Jp(Bw(bt,At,U,Ft,_t,Pt,It,vt),j.policy);if(zt)return K?.recordSegment({type:"fallback-scan",tokensScanned:To??[],embeddedCommandFound:Mt(Ot)}),un(zt)}if(K?.recordSegment({type:"fallback-scan",tokensScanned:To??[]}),we&&de&&!de.wrappedByTransparent)return null;let An=A(bt,j.policy.rules);if(K?.recordSegment({type:"custom-rules-check",rulesChecked:j.policy.rules.length>0,matched:!!An,reason:An?.reason}),An)return un(An);return Se&&de?Ro(de,j.policy):null}function wc(G,U,j,K){return yr(Eo(Kt(G),U+1,{...j,trace:void 0,commandView:void 0,hasPipelineInput:void 0,literalShellInput:void 0,functionDefinitions:void 0,cwd:K.originalCwd,effectiveCwd:K.effectiveCwd,envAssignments:K.envAssignments,worktreeMode:K.dynamicInput?!1:K.worktreeMode,wrapperNormalizationBudget:{iterations:0},child:K}))}function Bw(G,U,j,K,re,oe,de,Se){for(let we of zn(G.slice(U),{environment:K.environment,cwd:re,envAssignments:Se,policy:K.policy})){let We=we.tokens[0];if(!We)continue;let mt=Mt(We);if(tg(We,mt)||Qp(mt)!==void 0&&mt!=="xargs"&&mt!=="parallel"||we.wrappedByTransparent&&K.policy.rules.length>0)K.budget.charge("derivedTokens",G.length-U);let ft=wc(we.tokens,j,K,{embedded:!0,cwd:we.cwd,originalCwd:we.wrapperCwd===null?void 0:oe,effectiveCwd:we.wrapperCwd===void 0?de:we.wrapperCwd,envAssignments:we.envAssignments,allowTmpdirVar:!li(we.envAssignments,K.environment),worktreeMode:!1,wrappedByTransparent:we.wrappedByTransparent});if(ft)return ft}return null}function Uw(G,U,j,K,re,oe){if(!U)return Ro(oe,re.policy);if(Jt(re.policy,"interpreter.one-liner-paranoid",!!re.paranoidInterpreters)){let Se=Tt(Rt("interpreter.one-liner-paranoid",ti),re.policy);if(Se)return un(Se)}if(wl(G,U))return Ro(oe,re.policy);let de=re.analyzeNested(U,{effectiveCwd:j,envAssignments:K});if(de&&!eg(de,U))return de;if(ni(U,void 0,!re.strict)){let Se=Tt(Rt("interpreter.dangerous-command",so),re.policy);if(Se)return un(Se)}return Ro(oe,re.policy)}function eg(G,U){let j=G.ruleId==="raw-text.dangerous-command",K=(G.reason.startsWith(Ps)||G.reason===po)&&!Gi(U);return j||K}function vo(G,U){let j=G.shellDynamicMatch?Tt(G.shellDynamicMatch,U):null;return j?un(j):null}function Ro(G,U){let j=G.dynamicSourceInput&&G.dynamicSourceMatch?Tt(G.dynamicSourceMatch,U):null;return j?un(j):null}function Hw(G,U){let j=G.dynamicInput&&G.rmDynamicMatch?Tt(G.rmDynamicMatch,U):null;return j?un(j):null}function jw(G,U,j,K,re,oe){let de=Pf(G);if(de.argvSource?.kind==="absent")return bn(re);if(de.argvSourceApplies&&de.argvSource){let we=Ys(de.argvSource.value,j,U,K,re,oe,!0);if(we)return we}if(!de.envSourceApplies||!de.envName)return null;let Se=U.get(de.envName);if(!Se)return null;return Ys(Se,j,U,K,re,oe,!0)}function Ys(G,U,j,K,re,oe,de=!1){if(de&&/[$`*?[\]]/.test(G))return bn(re);let Se=ei(G,U,K.environment.paths,K.budget),we=Se?K.literalHeredocFiles?.get(Se):void 0;if(we===void 0)return de?bn(re):null;return K.budget.charge("derivedTokens",1),re?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:we,depth:oe+1}),K.analyzeNested(we,{effectiveCwd:U,envAssignments:j})}function Vw(G){let U=G[0];return G.length>=2&&(U==='"'||U==="'")&&G.at(-1)===U?G.slice(1,-1):G}function Kw(G,U,j){let K={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",cmd:"analyzer/cmd.ts:analyzeCmdMatch",powershell:"analyzer/powershell-wrapper.ts:analyzePowerShellWrapperMatch",pwsh:"analyzer/powershell-wrapper.ts:analyzePowerShellWrapperMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[G.head];if(!K)return;if(G.options.trace?.recordSegment({type:"rule-check",rule:K,matched:!!U||!!j,reason:U?.reason??j?.originalReason}),j)G.options.trace?.recordSegment({type:j.kind==="worktree"?"worktree-relaxation":"temp-root-relaxation",originalReason:j.originalReason,gitCwd:j.gitCwd})}function Xp(G){if(G.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");G.iterations++}function un(G){return{reason:G.reason,ruleId:G.id,intent:G.intent}}function bn(G){return G?.recordSegment({type:"error",message:ui}),un(go())}function tg(G,U){return qt.has(U)||G==="$SHELL"||G==="${SHELL}"||qt.has(kt(U))}function Jp(G,U){return G?.id.startsWith("custom.")||G?.id==="raw-text.dangerous-command"?G:Tt(G,U)}var qw=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,Yw=new Set(["powershell","pwsh"]),Zw=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function Xw(G,U){let j=og(G,U);if(j.length===0)return!1;let K=j[rg(j)];if(K==="cd"||K==="pushd"||K==="popd")return!0;return qw.test(G.join(" "))}function ng(G,U,j,K,re){if(G.dialect==="powershell"){let St=Jw(G.words,re);if(St.kind==="none")return;if(!U||St.kind==="unknown")return null;return _c(nA(St.target),U,j.paths)}let oe=G.words.map(t),de=oe.some((St)=>/^CDPATH\+?=/.test(St));if(!Xw(oe,j))return de?null:void 0;if(!U)return null;let Se=og(oe,j,U),we=rg(Se);if(we===-1||Se[we]!=="cd")return null;let We=Se.slice(we+1),mt=We.findIndex((St)=>St.length<=1||!St.startsWith("-")||St==="--");if((mt===-1?We:We.slice(0,mt)).some((St)=>!/^-[LP]+$/.test(St)))return null;let ft=mt===-1?[]:We.slice(mt),pt=ft[0]==="--"?ft.slice(1):ft;if(pt.length>1)return null;let ht=pt[0],yt=K.get("HOME")||j.home;if(ht===void 0)return _c(cn(yt),U,j.paths);let bt=G.words.find((St)=>St.provenance==="variable"&&St.text===ht),Ct=G.words.find((St)=>St.text===ht&&/^~(?:\/|$)/.test(St.raw)),vt=bt?Kn(bt,new Map([...K,["HOME",yt]])):Ct?`${yt}${ht.slice(1)}`:ht;if(vt===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(vt)&&(de||j.env.has("CDPATH")))return null;return _c(cn(vt),U,j.paths)}function _c(G,U,j){if(!G||G==="-"||G.startsWith("~")||G.includes("$")||G.includes("`"))return null;try{let K=dr(U,G,j);return j.isDirectory(K)?K:null}catch{return null}}function Jw(G,U){let j=Qw(G[0])?1:0,K=G[j];if(!eA(K,j===1))return{kind:"none"};let re=K.text.toLowerCase(),oe=re.split(/[\\/]/).pop()??re;if(!Zw.has(oe))return{kind:"none"};if(re!==oe||oe==="pop-location"||oe==="popd")return{kind:"unknown"};return tA(G.slice(j+1),U)}function Qw(G){return G?.provenance==="literal"&&!G.quoted&&G.raw===G.text&&(G.text==="&"||G.text===".")}function eA(G,U){return G?.provenance==="literal"&&(U||!G.quoted&&G.raw===G.text)}function tA(G,U){let j;for(let K of G){if(K.provenance!=="literal"||j!==void 0)return{kind:"unknown"};j=K.text}if(j!==void 0)return{kind:"target",target:j};return U===void 0?{kind:"unknown"}:{kind:"target",target:U}}function nA(G){return G.includes("::")?void 0:G.replaceAll("\\","/")}function rg(G){let U=0;if(G[0]==="builtin"&&G.length>1)U=1;if(G[U]!=="time")return U;let j=U+1;while(G[j]?.startsWith("-"))j++;return j}function og(G,U,j){let K=rA(G);return ur([...K],U,j)}function rA(G){let U=0;while(U<G.length){let j=G[U];if(j!=="{"&&j!=="("&&j!=="$(")break;U++}return G.slice(U)}var dA="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Br="This heredoc form or stdin consumer is not supported safely. Use a quoted heredoc with a supported consumer (cat, tee, git apply, git commit, gh pr create, gh issue create), or ask the user to verify.";function Oc(G,U,j,K){if(U>=a.recursionDepth.cap)return j.trace?.recordSegment({type:"error",message:Un}),{reason:Un,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};let re=K??j.factStore?.getCommandProgram(G,j.shell??"auto")??y(G,j.shell);if(re.status==="limited")return j.trace?.recordSegment({type:"error",message:Un}),{reason:Un,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};if(re.status==="invalid"){let We=re.issues.find((mt)=>mt.code.includes("heredoc"));if(We){if(!j.strict)return kc(G,j);let mt=`${Ps}: ${We.message}`;return j.trace?.recordGlobal({type:"error",message:mt}),{reason:mt,segment:G,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"}}return ug(G,j),{reason:po,segment:G,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"}}if(j.strict&&re.status==="partial")return ug(G,j),{reason:po,segment:G,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"};if(re.issues.some((We)=>We.code.includes("quote")))return kc(G,j);let de=j.cwd,Se=j.effectiveCwd!==void 0?j.effectiveCwd:j.cwd,we=$f(j.environment.env,j.envAssignments);return Js(re,U,{...j,rootProgram:re},de,[{effectiveCwd:Se,shellGitContextState:we,literalHeredocFiles:new Map(j.literalHeredocFiles),functionDefinitions:new Map(j.functionDefinitions),createdDirectories:new Set,compoundBodies:[]}]).result}function Js(G,U,j,K,re){let oe=[...re],de,Se,we;for(let[We,mt]of G.nodes.entries()){if(mt.kind==="connector"){Se=mt.operator;continue}let gt=G.nodes[We+1],ft=gt?.kind==="connector"?gt.operator:void 0,pt=uA(G,We,mt,Se,ft),yt=Se==="&&"||Se==="||"?de:void 0,bt=Se==="&&"?yt?.success??oe:Se==="||"?yt?.failure??oe:oe,Ct=Se==="||"?yt?.success??[]:[],vt=Se==="&&"?yt?.failure??[]:[],St={connector:Se,skippedSuccessStates:Ct,skippedFailureStates:vt};if(br(ft)&&!br(Se))we=St;let Et=br(ft)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:br(Se)?we??St:St,_t=Ur(Et.connector)||Ur(ft);if(mt.kind==="function"){let Ut=bt.flatMap((ln)=>{let Zt=Hr(ln);return Zt.functionDefinitions.set(mt.name,mt.body),Ac(ln,[Zt],pt,ft==="&",Ur(ft))}),Ft=Pc(Ut,[],Et.skippedSuccessStates,Et.skippedFailureStates,Et.connector,ft);oe=Ft.states,de=Ft.conditionalStates,Se=void 0;continue}if(mt.kind==="group"){let Ut=[],Ft=[];for(let Zt of bt){let Xt=Js(mt.body,U,j,K,[Hr(Zt)]);if(Xt.result)return Xt;if(Ut.push(...Ac(Zt,Xt.states,pt,ft==="&",Ur(ft))),_t)Ft.push(Zt,...pt?Xt.states.map((Sn)=>Zs(Zt,Sn)):Xt.states)}let ln=Pc(Ut,Ft,Et.skippedSuccessStates,Et.skippedFailureStates,Et.connector,ft);oe=ln.states,de=ln.conditionalStates,Se=void 0;continue}if(mt.kind!=="command")continue;let Pt=DA(G.nodes[We-1]),It=j.trace?.flattenNested?j.trace.currentSegmentIndex:j.trace?.allocateSegment(),wt=G.nodes[We-2],Lt=br(Se)&&wt?.kind==="command"?sp(wt)??fA(wt):void 0,Bt=[],en=[];for(let Ut of bt){let Ft=pA(mt,U,j,K,[Hr(Ut)]);if(Ft.result)return{result:Ft.result,states:oe};let ln=G.dialect==="powershell"?Ft.states:Ft.states.map((Zt)=>Zs(Ut,Zt));for(let Zt of ln){let Xt=Hr(Zt),Sn=yA(mt,U,j.trace?{...j,trace:mg(j.trace,It)}:j,K,Xt,br(Se),Lt);if(Sn)return{result:Sn,states:oe};let Yn=$A(mt,Xt.functionDefinitions);if(Yn)j.budget.charge("derivedTokens",Qs(Yn));let vr=Yn?U+1>=a.recursionDepth.cap?Tc(mt.displayText,j,[Xt]):Js(Yn,U+1,j,K,[Xt]):{result:null,states:GA(mt,Xt).flatMap((An)=>NA(mt,Zt,An,Pt))};if(vr.result)return vr;Bt.push(...Ac(Ut,vr.states,pt,ft==="&",Ur(ft)));let To=typeof Xt.effectiveCwd==="string"&&Xt.effectiveCwd!==Zt.effectiveCwd&&mt.redirections.every((An)=>["<",">",">>",">|"].includes(An.operator)&&An.target?.text==="/dev/null");if(_t&&(Pt||!To))en.push(Ut),en.push(...vr.states.map((An)=>pt?Zs(Ut,An):An))}}let Sr=Pc(Bt,en,Et.skippedSuccessStates,Et.skippedFailureStates,Et.connector,ft);oe=Sr.states,de=Sr.conditionalStates,Se=void 0}return{result:null,states:oe}}function uA(G,U,j,K,re){if(j.kind==="group"&&j.style==="subshell")return!0;if(G.dialect==="posix"&&(br(K)||br(re)))return!0;if(re==="&")return!0;return G.dialect==="powershell"&&j.kind==="group"&&j.style==="brace"&&mA(G,U)}function Ac(G,U,j,K,re){let oe=j?U.map((Se)=>Zs(G,Se)):[...U],de=re?oe.flatMap((Se)=>xo(G.literalHeredocFiles,Se.literalHeredocFiles)?[Se]:[{...Se,literalHeredocFiles:new Map(G.literalHeredocFiles)},Se]):oe;return K?[G,...de]:de}function Zs(G,U){return{...G,literalHeredocFiles:new Map(U.literalHeredocFiles),createdDirectories:new Set(U.createdDirectories)}}function mA(G,U){let j=G.nodes.slice(0,U).reverse().find((re)=>re.kind==="command"||re.kind==="connector");if(!j||j.kind!=="command")return!0;let K=j.words[0]?.text.toLowerCase();if(K==="&"||K===".")return!1;if(K==="write-output"||K==="function"||K==="start-job")return!0;if(gA(j))return!0;return j.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function br(G){return G==="|"||G==="|&"}function fA(G){if(G?.dialect!=="powershell")return;if(G.words.length===1&&G.words[0]?.quoted&&G.words[0].provenance==="literal")return G.words[0].text;if(G.words[0]?.text.toLowerCase()==="write-output"&&G.words.length===2&&G.words[1]?.provenance==="literal")return G.words[1].text;return}function Ur(G){return G==="&&"||G==="||"}function Pc(G,U,j,K,re,oe){let de={success:Xs([...j,...G]),failure:Xs([...K,...U])},Se=Ur(oe)?de:void 0;return{states:Ur(re)||Se?Xs([...de.success,...de.failure]):de.success,conditionalStates:Se}}function mg(G,U,j=G.flattenNested){return{currentSegmentIndex:U,flattenNested:j,allocateSegment:G.allocateSegment,getNextSegmentIndex:G.getNextSegmentIndex,recordGlobal:G.recordGlobal,recordSegment:(K,re=U)=>G.recordSegment(K,re)}}function pA(G,U,j,K,re){let oe=G.nested.map((de)=>({program:de,depth:U}));if(G.dialect==="powershell"){let de=hA(G);if(de){if(U+1>=a.recursionDepth.cap)return Tc(de,j,re);let Se=y(de,"powershell");if(Se.status==="limited")return Tc(de,j,re);if(Se.status!=="complete")return ig(oe,j,K,re);j.budget.charge("derivedTokens",Qs(Se)),oe.push({program:Se,depth:U+1})}}return ig(oe,j,K,re)}function gA(G){let U=G.words[0];return U?.provenance==="variable"&&G.words.at(-1)?.text==="="?U.text.toLowerCase():void 0}function ig(G,U,j,K){let re=[...K];for(let oe of G){let de=[];for(let Se of re){let we=Js(oe.program,oe.depth,U,j,[Hr(Se)]);if(we.result)return we;de.push(...we.states)}re=Xs(de)}return{result:null,states:re}}function hA(G){let U=G.words[0]?.provenance==="literal"&&!G.words[0].quoted&&G.words[0].raw===G.words[0].text&&(G.words[0].text==="&"||G.words[0].text==="."),j=U?1:0,K=G.words[j];if(K?.provenance!=="literal"||!U&&(K.quoted||K.raw!==K.text)||!["iex","invoke-expression"].includes(K.text.toLowerCase()))return;let re=G.words.slice(j+1),oe=re[0]&&!re[0].quoted&&re[0].raw===re[0].text&&["-c","-command"].includes(re[0].text.toLowerCase())?1:0,de=re[oe];return re.length===oe+1&&de?.quoted&&de.provenance==="literal"?de.text:void 0}function Qs(G){return G.nodes.reduce((U,j)=>U+(j.kind==="command"?j.words.length+j.nested.reduce((K,re)=>K+Qs(re),0):j.kind==="group"||j.kind==="function"?Qs(j.body):0),0)}function Tc(G,U,j){return U.trace?.recordSegment({type:"error",message:Un}),{result:{reason:Un,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"},states:[...j]}}function yA(G,U,j,K,re,oe,de){let Se={...j,environment:{...j.environment,env:re.shellGitContextState.env,paths:EA(j.environment.paths,re.createdDirectories,j.budget)}},we=PA(G,!Se.strict);if(we&&Se.strict)return Se.trace?.recordSegment({type:"error",message:we}),{reason:we,segment:G.source,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"};fg(G,re,"before-consumer",Se.environment.paths,Se.budget);let We=ne(G.dialect,G.words),mt=We.map(t),gt=G.displayText,ft=Gf(We,re.shellGitContextState),pt=Uf(ft,re.shellGitContextState);if(G.dialect==="powershell"){let Ct=Tt(pf(G,oe,BA(Se,re.effectiveCwd)),Se.policy);if(Se.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!Ct,reason:Ct?.reason}),Ct)return dg(gt,Ct)}let ht=Tt(pm(G.redirections),Se.policy);if(ht)return Se.trace?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceRedirectionMatch",matched:!0,reason:ht.reason}),dg(gt,ht);if(mt.length===1&&mt[0]?.includes(" ")&&!jo(G.dialect,G.words)){let Ct=Tt(kn(mt[0]),Se.policy),vt=Ct!==null&&!Se.strict&&cm(G,Se.rootProgram);if(Ct&&!vt)return Se.trace?.recordSegment({type:"dangerous-text",token:mt[0],matched:!0,reason:Ct.reason}),{reason:Ct.reason,segment:gt,ruleId:Ct.id,intent:Ct.intent};Se.trace?.recordSegment({type:"dangerous-text",token:mt[0],matched:!1});let St=sg(G,we,re,pt,de,Se);if(St)return St;return ic(ft,re.shellGitContextState),null}let yt=Eo(G.words,U,{...Se,commandView:G,cwd:K,effectiveCwd:re.effectiveCwd,envAssignments:pt,shellAssignments:re.shellGitContextState.shellAssignments,literalHeredocFiles:re.literalHeredocFiles,functionDefinitions:re.functionDefinitions,hasPipelineInput:oe,literalShellInput:de,analyzeNested:(Ct,vt)=>{let St=vt&&Object.hasOwn(vt,"effectiveCwd")?vt.effectiveCwd:re.effectiveCwd,Et=Oc(Ct,U+1,{...Se,effectiveCwd:St,envAssignments:vt?.envAssignments??pt,literalHeredocFiles:re.literalHeredocFiles,functionDefinitions:vt?.functionDefinitions,worktreeMode:vt?.worktreeMode??Se.worktreeMode,shell:vt?.shell??Se.shell,trace:Se.trace?mg(Se.trace,Se.trace.currentSegmentIndex,!0):void 0});return Et?{reason:Et.reason,ruleId:Et.ruleId,intent:Et.intent}:null}});if(yt)return{...yt,segment:gt};let bt=sg(G,we,re,pt,de,Se);if(bt)return bt;return ic(ft,re.shellGitContextState),null}function sg(G,U,j,K,re,oe){let de=TA(G,U,j,K??new Map,oe);if(de)return de;return fg(G,j,"after-consumer",oe.environment.paths,oe.budget),j.literalHeredocFiles.clear(),SA(G,U,j,oe.environment.paths,oe.budget),RA(G,j,oe.environment.paths,oe.budget),OA(G,j,re,oe.environment,oe.trace),null}var bA=new Set([">>","<>"]);function fg(G,U,j,K,re){for(let de of G.redirections){if(!(j==="before-consumer"?CA(de):bA.has(de.operator)))continue;ag(de.target,U,K,re)}if(j!=="before-consumer"||!an(G.words[0],"tee"))return;let oe=gg(G.words.slice(1));if(!oe)return;for(let de of oe.operands)ag(de,U,K,re)}function CA(G){if(G.operator===">"||G.operator===">|")return!0;return G.operator===">&"&&G.fd===void 0&&G.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(G.target.text)}function ag(G,U,j,K){let re=G?.provenance==="literal"?ei(G.text,U.effectiveCwd,j,K):void 0;if(!re)return;U.literalHeredocFiles.delete(re)}function SA(G,U,j,K,re){if(U)return;let oe=G.redirections.find((de)=>de.operator==="<<"||de.operator==="<<-")?.heredoc;if(!oe)return;for(let de of vA(G,j.shellGitContextState.shellAssignments)){let Se=ei(de,j.effectiveCwd,K,re);if(!Se||!hm(Se))continue;if(!j.literalHeredocFiles.has(Se)&&j.literalHeredocFiles.size>=a.trackedHeredocFiles.cap)throw new s("trackedHeredocFiles");j.literalHeredocFiles.set(Se,oe.body)}}function vA(G,U){let j=Ic(wA(G.redirections)?.target,U),K=j===void 0?[]:[j];if(an(G.words[0],"cat"))return _A(G.words)?K:[];if(!an(G.words[0],"tee"))return[];let re=gg(G.words.slice(1),U);if(!re||re.append||re.hasUnsupportedOptions)return[];let oe=re.operands.map((de)=>Ic(de,U));if(!oe.every((de)=>de!==void 0))return[];return[...oe,...K]}function Ic(G,U){if(AA(G))return G.text;return(G&&Kn(G,U))??void 0}function EA(G,U,j){if(U.size===0)return G;let K=(re)=>{let oe=Nt(re,G,j);return[...U].some((de)=>de===oe||de.startsWith(`${oe}${cA}`))};return{realpath:(re)=>G.realpath(re)??(K(re)?Nt(re,G,j):null),entryKind:(re)=>{let oe=G.entryKind(re);return oe==="missing"&&K(re)?"present":oe},isDirectory:(re)=>G.isDirectory(re)||K(re)}}function RA(G,U,j,K){if(U.shellGitContextState.bodyDepth>0||!an(G.words[0],"mkdir"))return;let re=G.words.slice(1).map((We)=>Ic(We,U.shellGitContextState.shellAssignments));if(!re.every((We)=>We!==void 0))return;let oe=re.findIndex((We)=>We==="--"||We==="-"||!We.startsWith("-")),de=re.slice(0,oe);if(oe===-1||!de.every((We)=>/^(?:-[pv]+|--parents|--verbose)$/.test(We)))return;let Se=de.some((We)=>We==="--parents"||/^-v*p/.test(We)),we=U.effectiveCwd;for(let We of re.slice(re[oe]==="--"?oe+1:oe)){if(We.split(/[\\/]/).includes("..")||!iA(We)&&!we)continue;let mt=Nt(lA(we??"",We),j,K);if(Se?xA(mt,j):j.isDirectory(oA(mt))&&pg(mt,j))U.createdDirectories.add(mt)}}function xA(G,U){let j=aA(G).root,K=G.slice(j.length).split(/[\\/]+/).filter(Boolean),re=(de)=>sA(j,...K.slice(0,de+1)),oe=K.findIndex((de,Se)=>!U.isDirectory(re(Se)));return oe===-1||pg(re(oe),U)}function pg(G,U){try{return U.entryKind(G)==="missing"}catch{return!1}}function _A(G){let U=!1;for(let j of G.slice(1)){if(U||j.provenance!=="literal")return!1;if(j.text==="--"){U=!0;continue}if(!/^-u+$/.test(j.text))return!1}return!0}function wA(G){let U=G.findLast((j)=>(j.fd??([">",">|",">>",">&"].includes(j.operator)?1:0))===1);return U?.operator===">"||U?.operator===">|"?U:void 0}function gg(G,U=new Map){let j=[],K=!0,re=!1,oe=!1;for(let de of G){if(de.provenance!=="literal"&&Kn(de,U)===null)return;if(K&&an(de,"--")){K=!1;continue}if(K&&!de.quoted&&de.raw===de.text&&/^-[^-]/.test(de.text)){re||=de.text.slice(1).includes("a"),oe||=Array.from(de.text.slice(1)).some((Se)=>Se!=="a"&&Se!=="i");continue}if(K&&!de.quoted&&de.raw===de.text&&de.text.startsWith("--")){re||=de.text==="--append",oe||=de.text!=="--append"&&de.text!=="--ignore-interrupts";continue}j.push(de)}return{operands:j,append:re,hasUnsupportedOptions:oe}}function AA(G){if(!G||G.provenance!=="literal"||G.text.length===0)return!1;if(G.quoted||G.raw!==G.text)return!0;return!G.raw.startsWith("~")&&!/[{}]/.test(G.raw)}function an(G,U){return G?.text===U&&G.raw===U&&G.provenance==="literal"&&!G.quoted}function Mc(G){return G.quotedDelimiter||!/[$`\\]/.test(G.body)}function PA(G,U){let j=G.redirections.filter((we)=>we.operator==="<<"||we.operator==="<<-");if(j.length===0)return;if(j.length!==1)return Br;let K=j[0];if(!K?.heredoc)return Br;let re=/\$\(|`/.test(K.heredoc.body);if(!Mc(K.heredoc)&&(!U||re))return dA;if(K.fd!==void 0&&K.fd!==0)return Br;if(G.redirections.some((we)=>we!==K&&["<","<<","<<-","<<<","<&","<>"].includes(we.operator)))return Br;let oe=G.redirections.some((we)=>we!==K&&lg(we.target));if(an(G.words[0],"cat"))return oe?Br:void 0;if(an(G.words[0],"tee"))return oe||G.words.slice(1).some(lg)?Br:void 0;let de=G.words[0],Se=G.words[1];if(an(de,"git")&&(an(Se,"apply")||an(Se,"commit")))return;if(an(de,"gh")&&(an(Se,"pr")||an(Se,"issue"))&&an(G.words[2],"create"))return;return Br}function lg(G){return G?.parts.some((U)=>U.provenance==="command-substitution"&&U.raw.startsWith(">("))??!1}function TA(G,U,j,K,re){if(!U)return null;let oe=G.redirections.filter((We)=>We.operator==="<<"||We.operator==="<<-"),de=oe.flatMap((We)=>We.heredoc?[We.heredoc.body]:[]);if(kA(G,oe,j,K,re))return null;let Se=IA(G,oe,re);if(Se!==void 0)return Se?{reason:Se.reason,segment:G.displayText,ruleId:Se.id,intent:Se.intent}:null;let we=kc(de.length===oe.length?de.join(`
|
|
43
|
-
`):G.source,re);return we?{...we,segment:G.displayText}:null}function IA(G,U,j){let K=U.length===1?U[0]:void 0;if(!K?.heredoc||!Mc(K.heredoc)||K.fd!==void 0&&K.fd!==0)return;let re=an(G.words[0],"uv")&&an(G.words[1],"run")?G.words.slice(2):G.words,oe=re[0];if(oe?.provenance!=="literal"||!Ln(oe.text))return;let de=re.findIndex((gt)=>an(gt,"-"));if(!re.slice(1,de===-1?void 0:de).every((gt)=>gt.provenance==="literal"&>.text.startsWith("-")))return;let we=K.heredoc.body,We=Jt(j.policy,"interpreter.one-liner-paranoid",!!j.paranoidInterpreters);if(j.trace?.recordSegment({type:"interpreter",interpreter:oe.text,codeArg:we,paranoidBlocked:We}),We){let gt=Tt(Rt("interpreter.one-liner-paranoid",ti),j.policy);if(gt)return gt}if(!ni(we,void 0,!j.strict))return null;let mt=Tt(Rt("interpreter.dangerous-command",so),j.policy);if(!mt)return null;return j.trace?.recordSegment({type:"dangerous-text",token:we,matched:!0,reason:mt.reason}),mt}function kA(G,U,j,K,re){let oe=U.length===1?U[0]:void 0;if(!oe?.heredoc||!Mc(oe.heredoc)||oe.fd!==void 0&&oe.fd!==0)return!1;let de=kr(G.words,re.environment,j.effectiveCwd,K),Se=de.words.map(t),we=Mt(Se[0]??"");if((de.envSplitValues?.length??0)>0||!qt.has(we)&&!qt.has(kt(we)))return!1;return nr(Se)}function OA(G,U,j,K,re){let oe=ng(G,U.effectiveCwd,K,U.shellGitContextState.shellAssignments,j);if(oe===null)re?.recordSegment({type:"cwd-change",segment:G.words.map(t).join(" "),effectiveCwdNowUnknown:!0});if(oe!==void 0)U.effectiveCwd=oe}var MA=new Set(["fi","done","esac"]);function DA(G){return G?.kind==="command"&&G.words.length===1&&G.words[0]?.raw==="!"}function NA(G,U,j,K){let re=G.words[0]?.text??"",oe=U.shellGitContextState.bodyDepth,de=j.shellGitContextState.bodyDepth,Se=j.compoundBodies;if(de>oe)return j.compoundBodies=[...Se.slice(0,oe),{entryCwd:U.effectiveCwd,branchCwds:Se[oe]?.branchCwds??[],hasElse:!1}],[j];let we=oe>0?Se[oe-1]:void 0;if(we&&(re==="else"||re==="elif"))return j.compoundBodies=[...Se.slice(0,oe-1),{entryCwd:we.entryCwd,branchCwds:[...we.branchCwds,j.effectiveCwd],hasElse:re==="else"}],j.effectiveCwd=we.entryCwd,[j];let We=we!==void 0&&MA.has(re);if(We)j.compoundBodies=Se.slice(0,de);return[...new Set([j.effectiveCwd,...We?we.branchCwds:[],...We&&!we.hasElse?[we.entryCwd]:[],...K?[U.effectiveCwd]:[]])].map((gt)=>{if(gt===j.effectiveCwd)return j;let ft=Hr(j);return ft.effectiveCwd=gt,ft})}function LA(G,U){return G.length===U.length&&G.every((j,K)=>{let re=U[K];return re!==void 0&&j.entryCwd===re.entryCwd&&j.hasElse===re.hasElse&&j.branchCwds.length===re.branchCwds.length&&j.branchCwds.every((oe,de)=>oe===re.branchCwds[de])})}var WA=/^[A-Za-z_][A-Za-z0-9_]*$/,FA=8;function GA(G,U){let j=G.words[1]?.text;if(G.dialect!=="posix"||G.words[0]?.text!=="for"||j===void 0||!WA.test(j))return[U];let K=G.words.slice(3);if(!(G.words[2]?.text==="in"&&K.length>=1&&K.length<=FA&&K.every((oe)=>oe.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(oe.text))))return U.shellGitContextState.shellAssignments.delete(j),[U];return K.map((oe)=>{let de=Hr(U);return de.shellGitContextState.shellAssignments.set(j,oe.text),de})}function Hr(G){return{effectiveCwd:G.effectiveCwd,shellGitContextState:Bf(G.shellGitContextState),literalHeredocFiles:new Map(G.literalHeredocFiles),functionDefinitions:new Map(G.functionDefinitions),createdDirectories:new Set(G.createdDirectories),compoundBodies:G.compoundBodies}}function Xs(G){let U=[];for(let j of G){if(!U.some((K)=>zA(K,j)))U.push(j);if(U.length>a.controlFlowStates.cap)throw new s("controlFlowStates")}return U}function zA(G,U){return G.effectiveCwd===U.effectiveCwd&&LA(G.compoundBodies,U.compoundBodies)&&xo(G.shellGitContextState.env,U.shellGitContextState.env)&&xo(G.literalHeredocFiles,U.literalHeredocFiles)&&xo(G.functionDefinitions,U.functionDefinitions)&&xo(G.shellGitContextState.effectiveEnvAssignments,U.shellGitContextState.effectiveEnvAssignments)&&xo(G.shellGitContextState.shellAssignments,U.shellGitContextState.shellAssignments)&&G.shellGitContextState.bodyDepth===U.shellGitContextState.bodyDepth&&cg(G.shellGitContextState.bodyAssignments,U.shellGitContextState.bodyAssignments)&&cg(G.createdDirectories,U.createdDirectories)}function cg(G,U){return G.size===U.size&&[...G].every((j)=>U.has(j))}function xo(G,U){if(G===U)return!0;if(!G||!U||G.size!==U.size)return!1;return[...G].every(([j,K])=>U.get(j)===K&&U.has(j))}function $A(G,U){let j=Vo(G);return j===void 0?void 0:U.get(j)}function dg(G,U){if(!U)return null;return{reason:U.reason,segment:G,ruleId:U.id,intent:U.intent}}function BA(G,U=G.effectiveCwd){let j=U===null;return{environment:G.environment,cwd:j?void 0:U??G.cwd,originalCwd:j?void 0:G.cwd,strict:G.strict,paranoid:G.paranoidRm,allowTmpdirVar:G.allowTmpdirVar,protectedGitMetadata:G.protectedGitMetadata,policy:G.policy,budget:G.budget}}function kc(G,U){let j=Tt(kn(G),U.policy),K=U.trace?.currentSegmentIndex??U.trace?.allocateSegment(),re={type:"dangerous-text",token:G,matched:!!j,reason:j?.reason};if(U.trace?.recordSegment(re,K),!j&&/^(?:cd|pushd)\s/.test(G))U.trace?.recordSegment({type:"cwd-change",segment:G,effectiveCwdNowUnknown:!0},K);return j?{reason:j.reason,segment:G,ruleId:j.id,intent:j.intent}:null}function ug(G,U){let j={type:"strict-unparseable",rawCommand:G,reason:po},K=U.trace?.currentSegmentIndex;if(K===void 0)U.trace?.recordGlobal(j);if(K!==void 0)U.trace?.recordSegment(j)}var UA=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function hg(G,U,j,K){let re=Oc(G,0,{...U,...Ue(U),budget:U.budget??Pn(),factStore:K},j);if(!re)return null;return{kind:"deny",reason:re.reason,intent:re.intent??"manual_only",ruleId:re.ruleId,evidence:{command:G,segment:re.segment}}}function yg(G,U,j){try{return{decision:G()}}catch(K){let re=HA(K,U,j);if(!re)throw K;return re}}function HA(G,U,j){if(!(G instanceof s)||!UA.has(G.kind))return null;let K=a[G.kind];if(j?.currentSegmentIndex!==void 0)j.recordSegment({type:"error",message:K.reason});if(j?.currentSegmentIndex===void 0)j?.recordGlobal({type:"error",message:K.reason});return{decision:{kind:"deny",reason:K.reason,ruleId:"analysis.derived-command-limit",intent:"stop_and_explain",evidence:{command:U,segment:U}},errorCode:K.errorCode}}var jA=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),Nc=new Set(["cc-safety-net","ccsn"]),VA=new Set(["bunx","npx","pnpx"]),KA=new Set(["pnpm","yarn"]),qA=new Set(["npm","pnpm","yarn"]),YA=new Set(["bun","node"]);function ta(G,U,j={}){if(Nc.has(G))return 0;if(VA.has(G)){if(j.broad)return Dc(U);let re=U[0]==="-y"||U[0]==="--yes"?1:0;return ea(U[re])?re+1:null}let K=j.broad?U.findIndex((re)=>!re.startsWith("-")):0;if(K!==-1&&qA.has(G)&&j.broad&&U[K]==="exec"){let re=Dc(U.slice(K+1));return re===null?null:K+1+re}if(KA.has(G)){if(G==="yarn"&&!j.broad)return null;if(!j.broad)return U[0]==="dlx"&&ea(U[1])?2:null;if(K===-1||U[K]!=="dlx")return null;let re=Dc(U.slice(K+1));return re===null?null:K+1+re}if(YA.has(G)){let re=j.broad&&K!==-1?K:0;if(bg(U[re]))return re+1;if(G==="bun"&&U[re]==="run"&&bg(U[re+1]))return re+2}return null}function Dc(G){let U=G.findIndex((K)=>ea(K));if(U===-1)return null;let j=U;while(j<G.length){let K=G[j]??"";if(!K.startsWith("-")&&!ea(K))break;j++}return j}function ea(G){if(!G)return!1;let U=G.indexOf("@");if(U===-1)return Nc.has(G);if(U===0)return!1;let j=G.slice(U+1);if(j===""||j.includes("/")||j.includes(":"))return!1;return Nc.has(G.slice(0,U))}function bg(G){let U=G?.replaceAll("\\","/");return[...jA].some((j)=>U===j||U?.endsWith(`/${j}`))}var Ge="Only the user may apply a policy proposal, because it rewrites the configuration CC Safety Net enforces. Ask them to run `cc-safety-net policy apply <file>` themselves in a terminal; you can run `cc-safety-net policy check <file>` to show them what it would change.";function Cg(G,U,j){let K=hn(G,"input-candidate");if(!K)return null;let re=co(K.shell,G.invocation.context.executionCwd,U,j,{findSegmentTarget:(oe)=>ZA(oe,U),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return re?{target:re}:null}function ZA(G,U){let j=ur([...G],U),K=j.slice(1),re=ta(kt(j[0]??"").toLowerCase(),K,{broad:!0});if(re===null)return null;let oe=K.slice(re).filter((de)=>de!=="-g"&&de!=="--global");return oe[0]==="policy"&&oe[1]==="apply"?j.join(" "):null}import{dirname as na}from"node:path";var He="This path contains the protected policy config and you must not modify or delete it.",XA=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Rg(G,U,j){let K=rP(G.invocation.context,U,j);if(G.invocation.route.kind==="patch")return Sg(G.paths,!1,G.invocation.context.executionCwd,K,U,j);let re=hn(G,"input-candidate");if(G.invocation.route.kind==="command")return re?vg(re.shell,G.invocation.context.executionCwd,K,U,j):null;if(G.invocation.route.kind==="unknown"&&re){let oe=vg(re.shell,G.invocation.context.executionCwd,K,U,j);if(oe)return oe}return Sg(G.paths,G.invocation.route.kind==="grep"||G.invocation.route.kind==="glob"||Ii(G.invocation.toolName),G.invocation.context.executionCwd,K,U,j)}function Sg(G,U,j,K,re,oe){if(U)return null;let de=G.find((Se)=>vi(Se,j,K,re,oe));return de?{target:de}:null}function vg(G,U,j,K,re){let oe=co(G,U,K,re,{findSegmentTarget:(de,Se)=>JA(de,Se,j,K,re)?.target??null,isRedirectionTarget:(de,Se)=>vi(de,Se.cwd,j,K,re),findMalformedTarget:(de)=>nP(de,U,j,K,re)?.target??null});return oe?{target:oe}:null}function JA(G,U,j,K,re){if(ai(G))return null;let oe=mr([...G],K),de=kt(oe[0]??"").toLowerCase(),Se=oe.slice(1);if(de==="rm"&&QA(Se)){let we=eP(Se).find((We)=>Eg(gn(We,U.variables),U.cwd,j,K,re));if(we)return{target:we}}if(de==="find"){if(Ds(oe,1)||Zl(oe,K)){let We=(pi(Kt(oe))??Kt(["."])).find((mt)=>{let gt=gn(mt.text,U.variables);return vi(gt,U.cwd,j,K,re)||Eg(gt,U.cwd,j,K,re)})?.text;if(We)return{target:We}}}if(de==="mv"){let we=vs(Se).sources.find((We)=>oP(gn(We,U.variables),U.cwd,j,K,re));if(we)return{target:we}}if(tP(oe,de))return null;for(let we of[...G,...oe])for(let We of xg(we))if(vi(gn(We,U.variables),U.cwd,j,K,re))return{target:We};return null}function QA(G){return G.some((U)=>U==="--recursive"||U.startsWith("-")&&!U.startsWith("--")&&/[rR]/.test(U.slice(1)))}function eP(G){let U=G.indexOf("--");if(U!==-1)return[...G.slice(0,U).filter((j)=>!j.startsWith("-")),...G.slice(U+1)];return G.filter((j)=>!j.startsWith("-"))}function tP(G,U){if(!XA.has(U))return!1;if(U!=="sed")return!0;return!G.slice(1).some((j)=>j.startsWith("-i")||j==="--in-place"||j.startsWith("--in-place="))}function nP(G,U,j,K,re){for(let oe of G.split(/\s+/))for(let de of xg(oe))if(vi(de,U,j,K,re))return{target:de};return null}function xg(G){let U=G.trim().replace(/^['"]|['"]$/g,""),j=U.indexOf("=");return j===-1||j===U.length-1?[U]:[U,U.slice(j+1)]}function rP(G,U,j){let K=(Se)=>Ei(dn(Se,G.executionCwd,U,j)),re=K(l(U)),oe=[K(h(G.executionCwd)),K(h(G.configCwd))],de=new Set(oe.map((Se)=>na(Se)));for(let Se=na(re);;Se=na(Se))if(de.add(Se),na(Se)===Se)break;return{files:new Set([re,...oe]),directoriesAndAncestors:de}}function vi(G,U,j,K,re){let oe=rd(G,U,K,re,(de)=>Ei(de)===Li);return oe!==null&&j.files.has(Ei(oe))}function Eg(G,U,j,K,re){return j.directoriesAndAncestors.has(Ei(dn(G,U,K,re)))}function oP(G,U,j,K,re){let oe=Ei(dn(G,U,K,re));return j.files.has(oe)||j.directoriesAndAncestors.has(oe)}function Ei(G){return process.platform==="win32"?G.toLowerCase():G}import{isAbsolute as ra,posix as Lg,resolve as aa,win32 as iP}from"node:path";import{fileURLToPath as sP}from"node:url";var Wg="Access to a sensitive path is not allowed.",Fg=new Set(["echo","printf"]),aP=new Set(["find"]),lP=new Set(["!","do","elif","else","if","then","until","while"]),cP=new Set(["-exec","-execdir"]),dP=new Set([";","+"]),uP=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),mP=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Gg=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),fP=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),pP=new Set(["append","awk","base64","cat","chmod","chown","connect","copy","cp","database","dd","eval","exec","fetch","file","function","grep","head","include","load","move","mv","open","fopen","popen","read","readfile","remove","rename","require","rg","rm","sed","shell","source","spawn","strings","system","tail","tar","truncate","unlink","write","xxd","zip"]),zc=new Set(["-c","-e","-r","-E","--eval","--exec"]),gP=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"])]]),$c=new Set(["grep","rg"]),zg=new Set(["files-with-matches","files-without-match","count","quiet"]),hP=new Set([...zg,"ignore-case","fixed-strings","hidden"]),yP=new Set(["wc",...$c]),bP=new Set(["cd","grep","head","openssl","tail","tailscale"]),CP=/^(?:-[lwcm]+|--(?:lines|words|bytes|chars))$/,SP=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),vP=new Set(["commit","merge","notes","stash","tag"]),EP=new Set(["-m","--message"]),RP=new Set(["--grep"]),xP=new Set(["powershell","pwsh"]),_g=new Set(["jq","gojq","jaq"]),wg="f",Ag="file",_P="files",wP=new Set(["e","f"]),AP=new Set(["regexp","file"]),PP=new Set(["e","f","A","B","C","m"]),TP=new Set(["regexp","file","after-context","before-context","context","max-count"]),Lc="__CC_SAFETY_NET_PIPE_INPUT__",Fc=/[\w./~@+-]*[./~][\w./~@+-]*/g,IP=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,kP=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,OP=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,Pg=/\b(?:subprocess\s*\.\s*(?:run|call|Popen|check_output|check_call|getoutput|getstatusoutput)|(?:[\w$]+\s*\.\s*)*(?:exec(?:File)?(?:Sync)?|spawn(?:File)?(?:Sync)?|system|popen|shell_exec|passthru|child_process|eval))\s*\(/g,Tg=/\b(?:system|exec|spawn|popen)\s*$/,MP=/\b(?:eval|exec)\s*\(/g,DP=/\b(?:eval|exec)\s*$/,NP=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 Ig(G,U,j,K,re,oe){for(let de of G){let Se=de.target;if(ZT(Se,de.cwd,U?.denyPaths??[],j,K,re))return{target:Se,ruleId:"secret.deny-path"};if(oe&&!oe.has(Se))continue;let we=qT(Se,de.cwd,U,K,re);if(we){let We=oe!==void 0&&!we.startsWith("secret.home.")&&!we.startsWith("secret.cli.");if(We&&K.paths.isDirectory(eh(Se,de.cwd,K,re)))continue;if(We&&oe?.get(Se)==="data")continue;if(We&&(de.isRedirectionWriteTarget===!0||oe?.get(Se)==="write")&&!Se.includes("$")&&!sa(Se,de.cwd,K,re))continue;if(We&&(de.isCreatedPath===!0||de.isCertificateInput===!0))continue;if(We&&/\s/.test(Se)&&!Se.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(Se)&&!sa(Se,de.cwd,K,re))continue;if(!we.startsWith("secret.cli.")&&XT(Se,de.cwd,U?.allowPaths??[],j,K,re))continue;return{target:Se,ruleId:we}}}return null}function $g(G,U,j,K,re={}){let oe=kg(G,j,K),de=Ig(oe,U,G.invocation.context.configCwd,j,K);if(de===null||de.ruleId==="secret.deny-path"||re.strict!==!1)return de;let Se=kg(G,j,K,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}),we=new Map;Se.forEach((ht)=>Bg(ht.target).forEach((yt)=>we.set(yt,(we.get(yt)??new Set).add(ht.loopVariable))));let We=(ht,yt)=>(we.get(ht)?.size??0)>(we.get(ht)?.has(yt)?1:0),mt=Se.filter(({loopVariable:ht})=>ht===void 0||We(ht,ht)||We("!",ht)),gt=new Set(mt.filter((ht)=>ht.literalRole===void 0).map((ht)=>ht.target)),ft=new Set(mt.filter((ht)=>ht.literalRole==="write").map((ht)=>ht.target)),pt=Ig(oe,U,G.invocation.context.configCwd,j,K,new Map(mt.map((ht)=>[ht.target,gt.has(ht.target)?"path":ft.has(ht.target)?"write":"data"])));return pt?.ruleId!=="secret.deny-path"&&LP(G,j)?null:pt}function LP(G,U){let j=hn(G,"input-candidate")??hn(G,"declared-command");if(!j)return!1;if(j.program.nodes.some((de)=>de.kind==="command"&&de.nested.length>0))return!1;let K=[];for(let de of Ss(j.shell)){if(de.kind==="operator"&&de.boundary)return!1;if(de.kind==="redirection")return!1;if(de.kind==="operator")continue;K.push(er(de.text,U))}let re=qn(K);if(re.length===0)return!1;let oe=mn(re[0]??"").toLowerCase();if(G.invocation.route.kind==="unknown")return j.program.dialect==="powershell"&&(oe==="ls"||oe==="stat");return Bc(oe,re.slice(1))}function Bc(G,U){if(G==="ls"||G==="stat")return!0;if(G==="test")return U.length===2&&(U[0]==="-e"||U[0]==="-f");if(G==="[")return U.length===3&&(U[0]==="-e"||U[0]==="-f")&&U[2]==="]";if(G==="git")return U[0]==="check-ignore";if(G==="wc")return U.every((j)=>!j.startsWith("-")||CP.test(j));if($c.has(G))return WP(G,U);if(G!=="find")return!1;return!U.some((j)=>uP.has(j))}function WP(G,U){let j=U.includes("--")?U.slice(0,U.indexOf("--")):U;if(j.some((We)=>/^--(?:(?:file|pre)(?:=|$)|json|format)/.test(We)||/^-[^-]*f/.test(We)))return!1;let K=G==="rg"?/[ABCEMTdegjmrt]/:/[ABCDdefm]/,re=G==="rg"?/[clq]/:/[Lclq]/,oe=(We)=>/^-[^-]/.test(We),de=(We)=>{let mt=j[We-1]??"";return/^--[^=]+$/.test(mt)&&!hP.has(mt.slice(2))||oe(mt)&&mt.slice(1).search(K)===mt.length-2},Se=j.findIndex((We,mt)=>!We.startsWith("-")&&!de(mt));return(G==="grep"&&Se>=0?j.slice(0,Se):j).some((We,mt)=>{if(de(mt))return!1;if(We.startsWith("--"))return zg.has(We.slice(2));return oe(We)&&re.test(We.slice(1).split(K)[0]??"")})}function kg(G,U,j,K={}){let re=G.invocation.context.executionCwd,oe=G.invocation.route.kind;if(oe!=="command"&&oe!=="unknown")return G.paths.map((Se)=>({target:Se,cwd:re}));let de=hn(G,"input-candidate");return[...de?Po(de.shell,G.store,K,U,re,j,FP(de)):[],...oe==="unknown"?G.paths.map((Se)=>({target:Se,cwd:re})):[]]}function FP(G){return G.program.dialect==="powershell"}function Po(G,U,j,K,re,oe,de=!1){if(G.status==="structural-limit")throw new b;if(G.status==="unclosed-quote")return[];if(G.status==="invalid")throw Error("Unable to parse command for secret protection");let Se=[...G.assignmentFallbacks.map((bt)=>({target:bt,cwd:re})),...IT(er(G.source,K),U,j,K,re,oe)],we=(bt)=>er(ZP(bt,de),K),We=/[<>=]\(/.test(G.source),mt=/\bcoproc\b|\|&/.test(G.source),gt=[],ft=[],pt=(bt)=>({...j,commandHoldsPipe:j.commandHoldsPipe===!0||bt||mt});Cs(G,re,K,oe,{word:we,segment:(bt,Ct,vt,St,Et,_t)=>{if(bt.length===0)return null;let Pt=pt(_t);if(Pt.commandHoldsPipe)gt.push(...bt);if(ft.push(mn(Ug(qn(bt))[0]??"").toLowerCase()),Se.push(...xi(bt,U,We||St==="|"||St==="|&"?{...Pt,segmentMayFeedReader:!0}:Pt,K,Ct.cwd,oe,Et)),vt!==null)Se.push(...$P(vt,bt,U,Pt,K,Ct.cwd,oe));return null},redirection:(bt,Ct,vt)=>{if(bt.body!==void 0&&bt.consumer!==void 0){let St=pt(vt);Se.push(...Hg(bt.consumer,[bt.body],U,St,K,Ct.cwd,oe,(Et)=>BP(bt.consumer??[],Et,U,St,K,Ct.cwd,oe)))}if(bt.targetOrder==="legacy-segment")return Ml;return Se.push({target:we(bt.target),cwd:Ct.cwd,...bt.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}});let ht=new Set(gt.flatMap(Bg)),yt=We||/\$\(|`/.test(G.source)||!ft.every((bt)=>bP.has(bt));return Se.map(({loopVariable:bt,...Ct})=>{if(Ct.certificateOutputMayFeedReader===!0&&yt)return{target:Ct.target,cwd:Ct.cwd};return bt===void 0||We||ht.has(bt)||ht.has("!")?Ct:{...Ct,loopVariable:bt}})}function Bg(G){return[.../^[A-Za-z_][A-Za-z0-9_]*$/.test(G)?[G]:[],...Array.from(G.matchAll(/\$(?:\{(!)|\{?([A-Za-z_][A-Za-z0-9_]*))/g),(U)=>U[1]??U[2]??"")]}function oa(G,U,j,K,re,oe,de=!1){let Se=U.getShellSyntax(G,de?U.getCommandProgram(G,"powershell"):void 0);if(Se.status==="structural-limit")throw new b;return Se.status==="complete"?Po(Se,U,j,K,re,oe,de):null}function xi(G,U,j,K,re,oe,de){let Se=(wt)=>({target:wt,cwd:re}),we=G.findIndex((wt)=>!lP.has(wt));if(j.skipMetadataOnlySegments===!0&&we>0)return xi(G.slice(we),U,j,K,re,oe,new Set([...de??[]].map((wt)=>wt-we)));let We=G[1]??"";if(j.skipMetadataOnlySegments===!0&&G[0]==="for"&&G[2]==="in"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(We))return G.slice(3).flatMap((wt)=>Dn("for",wt)).map((wt)=>({...Se(wt),loopVariable:We}));if(de?.size){let wt=G.filter((Lt,Bt)=>!de.has(Bt));if(_g.has(mn(qn(wt)[0]??"").toLowerCase()))return[...G.filter((Lt,Bt)=>de.has(Bt)).map(Se),...xi(wt,U,j,K,re,oe)]}let mt=YP(G).map(Se),gt=qn(G);if(gt.length===0)return mt;let ft=gt[0]??"",pt=mn(ft).toLowerCase(),ht=gt.slice(1),yt=j.segmentMayFeedReader===!0||j.commandHoldsPipe===!0||j.displayOperandsAreCapturedOutput===!0,bt=yt&&yP.has(pt);if(j.skipMetadataOnlySegments===!0&&!bt&&Bc(pt,ht))return mt;let Ct=zP(ft,pt,ht);if(Ct)return[...mt,...Ct.map(Se)];if(Fg.has(pt))return j.displayOperandsAreCapturedOutput===!0?[...mt,...jg(G).map(Se)]:mt;if(pt==="eval")return[...mt,...oa(ht.join(" "),U,j,K,re,oe)??ht.map(Se)];let vt=xP.has(Mt(ft))?Ec(gt):void 0;if(vt!==void 0)oe.charge("derivedTokens",gt.length);let St=vt===void 0?null:oa(vt,U,j,K,re,oe,!0);if(St?.length)return[...mt,...St];if(pt==="export")return[...mt,...ht.flatMap((wt)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(wt)?[wt.slice(wt.indexOf("=")+1)]:Dn(pt,wt)).map(Se)];if(pt==="git")return[...mt,...JP(ht).map(Se)];if(pt==="gh")return[...mt,...Gc(pt,ht,SP).map(Se)];if(_g.has(pt))return[...mt,...XP(ht).map(Se)];if($c.has(pt))return[...mt,...FT(ht).map(Se)];if(aP.has(pt))return[...mt,...eT(ht,U,j,K,re,oe).map(Se)];if(pt==="mkdir"||pt==="touch"){let wt=new Set(G.filter((Bt,en)=>de?.has(en))),Lt=j.segmentMayFeedReader!==!0&&!(pt==="touch"&&ht.some((Bt)=>/^(?:--r|-[^-]*r)/.test(Bt)));return[...mt,...ht.flatMap((Bt)=>Dn(pt,Bt).map((en)=>Lt&&!Bt.startsWith("-")&&!wt.has(Bt)?{...Se(en),isCreatedPath:!0}:Se(en)))]}if(In.has(pt))return[...mt,...ht.flatMap((wt)=>Dn("awk",wt)).map(Se),...ht.flatMap((wt)=>nT(wt,U,j,K,re,oe)),...ht.flatMap(rT).map(Se)];if(pt==="curl")return[...mt,...ht.filter((wt,Lt)=>Kg(wt)===null&&Vg(ht[Lt-1])===null).flatMap((wt)=>Dn(pt,wt)).map(Se),...QP(ht).map(Se)];if(lo(pt)){let wt=si.has(pt)?En([pt,...ht]):null;if(wt!==null&&wt.command!==null&&wt.commandIndex!==null){let Lt=U.getShellSyntax(wt.command);if(Lt.status==="structural-limit")throw new b;if(Lt.status==="complete")return[...mt,...Po(Lt,U,j,K,re,oe),...ht.slice(wt.commandIndex).filter((Bt)=>!Bt.startsWith("-")).map(Se)]}return[...mt,...tT(pt,ht,U,j,K,re,oe)]}let Et=(wt,Lt)=>new RegExp(`^--?${wt}=`).test(ht[Lt]??"")||new RegExp(`^--?${wt}$`).test(ht[Lt-1]??""),_t=GP(gt),Pt=pt==="openssl"&&ht[0]==="x509",It=yt?{certificateOutputMayFeedReader:!0}:{};return[...mt,...ht.flatMap((wt,Lt)=>Dn(pt,wt).map((Bt)=>_t&&Et("(?:cert|key)-file",Lt)?{...Se(Bt),isCreatedPath:!0,...It}:Pt&&Et("in",Lt)?{...Se(Bt),isCertificateInput:!0,...It}:Se(Bt)))]}function Ug(G){return mn(G[0]??"").toLowerCase()==="timeout"?G.slice(2):G}function GP(G){let U=Ug(G);return mn(U[0]??"").toLowerCase()==="tailscale"&&U[1]==="cert"}function zP(G,U,j){let K=ta(U,j);if(K===null||j[K]!=="explain")return null;let re=[G,...j.slice(0,K)],oe=j.slice(K+1);for(let de=0;de<oe.length;de++){let Se=oe[de];if(Se==="--json"||Se==="--help"||Se==="-h")continue;if(Se==="--cwd"){let we=oe[de+1];if(we&&!we.startsWith("--"))re.push(we);de++;continue}return re}return re}function $P(G,U,j,K,re,oe,de){if(VP(U,j,K,re,oe,de)){let Se=qn(G),we=Bc(mn(Se[0]??"").toLowerCase(),Se.slice(1))?Se.slice(1).filter((We)=>!We.startsWith("-")):[];return[...jg(G),...we].map((We)=>({target:We,cwd:oe}))}return Hg(U,UP(G),j,K,re,oe,de,()=>[])}function BP(G,U,j,K,re,oe,de){let Se=qn(G);if(!lo(mn(Se[0]??"").toLowerCase()))return[];return oa(U,j,K,re,oe,de)??[{target:U,cwd:oe}]}function Hg(G,U,j,K,re,oe,de,Se){let we=KP(G);if(we===null)return U.flatMap(Se);return U.flatMap((We)=>si.has(we)?Po(j.getShellSyntax(We),j,K,re,oe,de):ia(we,We,j,K,re,oe,de))}function jg(G){let U=qn(G);if(U.length===0)return[];let j=mn(U[0]??"").toLowerCase();if(!Fg.has(j))return[];let K=U[U[1]==="--"?2:1];if(j==="printf"&&K!==void 0&&!K.startsWith("-")&&!K.replaceAll("%%","").includes("%"))return[Uc(K.replaceAll("%%","%"))];return U.slice(1)}function UP(G){let U=qn(G);if(U.length===0)return[];let j=mn(U[0]??"").toLowerCase(),K=U.slice(1);if(j==="echo"){let re=K.findIndex((oe)=>!/^-[neE]+$/.test(oe));return[(re===-1?[]:K.slice(re)).join(" ")]}if(j==="printf")return HP(K);return[]}function HP(G){let U=G[0];if(U===void 0)return[];let j=(U.match(/%%|%[bqs]/g)??[]).filter((re)=>re!=="%%").length;if(j===0||G.length===1)return[Uc(U)];let K=G.slice(1);return Array.from({length:Math.ceil(K.length/j)},(re,oe)=>jP(U,K.slice(oe*j,(oe+1)*j)))}function jP(G,U){let j=0;return Uc(G.replace(/%%|%[bqs]/g,(K)=>{if(K==="%%")return"%";let re=U[j]??"";return j++,re}))}function Uc(G){return G.replace(/\\n/g,`
|
|
44
|
-
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function
|
|
45
|
-
`:
|
|
46
|
-
`).some((j)=>{let K=j.indexOf(U);return K>=0&&/[()[\]{}]/.test(j.slice(K))})}function
|
|
47
|
-
|
|
48
|
-
`||oe==="\r"))return null;if(G.startsWith(j,re))return re}return null}function PT(G,U){for(let j=U-1;j>=0;j--){let K=G[j];if(!K||/\s/.test(K))continue;return/[\w$\])]/.test(K)}return!1}function TT(G){for(let U of G.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let j=U[0],K=U.index;if(fP.has(j.toLowerCase()))return!0;let re=Xg(j);if(!re.some((oe)=>pP.has(oe)))continue;if(re.length>1)return!0;if(G[wo(G,K)]===".")return!0;if(G[Ao(G,K+j.length)]==="(")return!0}return!1}function Xg(G){return G.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((U)=>U.toLowerCase())}function wo(G,U){for(let j=U-1;j>=0;j--)if(!/\s/.test(G[j]??""))return j;return-1}function Ao(G,U){for(let j=U;j<G.length;j++)if(!/\s/.test(G[j]??""))return j;return G.length}function IT(G,U,j,K,re,oe){return NT(G).flatMap((de)=>{let Se=U.getShellSyntax(de);if(Se.status==="invalid")return[];return[...Po(Se,U,{...j,displayOperandsAreCapturedOutput:!0},K,re,oe),...kT(Se,K)?OT(Se,K).map((we)=>({target:we,cwd:re})):[]]})}function kT(G,U){let j=Ss(G);for(let K=0;K<j.length;K++){let re=j[K];if(re?.kind!=="word"||mn(er(re.text,U)).toLowerCase()!=="base64")continue;for(let oe=K+1;oe<j.length;oe++){let de=j[oe];if(de?.kind==="operator")break;if(de?.kind!=="word")continue;let Se=er(de.text,U);if(Se==="--decode"||!Se.startsWith("--")&&Se.startsWith("-")&&/[dD]/.test(Se))return!0}}return!1}function OT(G,U){return Ss(G).flatMap((j)=>j.kind==="word"?[er(j.text,U)]:j.kind==="redirection"&&j.target?[er(j.target,U)]:[]).flatMap(Vc)}function Vc(G){let U=DT(G);if(U===null)return[];let j=Buffer.from(U,"base64").toString("utf8");if(j===""||MT(j))return[];return Buffer.from(j,"utf8").toString("base64").replace(/=+$/g,"")===U.replace(/=+$/g,"")?[j]:[]}function MT(G){return Array.from(G).some((U)=>{let j=U.charCodeAt(0);return j<32||j===127})}function DT(G){if(G.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(G))return null;if(/=/.test(G.replace(/=+$/g,"")))return null;let U=G.replace(/=+$/g,"");if(U.length%4===1)return null;return`${U.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-U.length%4)%4)}`}function NT(G){let U=[],j={inSingle:!1,inDouble:!1,escaped:!1};for(let K=0;K<G.length;K++){let re=G[K];if(!re)break;if($o(re,j))continue;if(Jg(G,K,j)){let oe=LT(G,K+1);if(oe!==null)U.push(oe.body),K=oe.endIndex;continue}if(!j.inSingle&&re==="`"){let oe=WT(G,K);if(oe!==null)U.push(oe.body),K=oe.endIndex}}return U}function LT(G,U){let j={inSingle:!1,inDouble:!1,escaped:!1},K=1;for(let re=U+1;re<G.length;re++){let oe=G[re];if(!oe)break;if($o(oe,j))continue;if(Jg(G,re,j)){K++,re++;continue}if(!j.inSingle&&!j.inDouble&&oe===")"){if(K--,K===0)return{body:G.slice(U+1,re),endIndex:re}}}return null}function WT(G,U){let j=!1;for(let K=U+1;K<G.length;K++){let re=G[K];if(!re)break;if(j){j=!1;continue}if(re==="\\"){j=!0;continue}if(re==="`")return{body:G.slice(U+1,K),endIndex:K}}return null}function Jg(G,U,j){return!j.inSingle&&G[U]==="$"&&G[U+1]==="("&&G[U+2]!=="("}function FT(G){let U=[],j=[],K=!1,re=!1,oe=!1;for(let we=0;we<G.length;we++){let We=G[we];if(We===void 0)break;if(!oe&&We==="--"){oe=!0;continue}if(oe){j.push(We);continue}let mt=/^--([^=]+)(?:=(.*))?$/.exec(We);if(mt!==null){let gt=mt[1]??"",ft=mt[2];if(gt===_P)re=!0;if(AP.has(gt))K=!0;if(ft!==void 0){if(gt===Ag)U.push(ft);continue}if(TP.has(gt)){let pt=G[we+1];if(gt===Ag&&pt!==void 0)U.push(pt);we++}continue}if(We.startsWith("-")&&We.length>1){let gt=We.slice(1),ft="",pt="";for(let yt=0;yt<gt.length;yt++){let bt=gt[yt]??"";if(wP.has(bt))K=!0;if(PP.has(bt)){ft=bt,pt=gt.slice(yt+1);break}}if(ft==="")continue;if(pt.length>0){if(ft===wg)U.push(pt);continue}let ht=G[we+1];if(ft===wg&&ht!==void 0)U.push(ht);we++;continue}j.push(We)}let Se=!K&&!re?j.slice(1):j;return[...U,...Se]}function qn(G){let U=G.findIndex((j)=>!Qg(j)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(j));return U===-1?[]:G.slice(U)}function Qg(G){return G==="env"||G==="command"||G==="builtin"||G==="sudo"}var GT=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),zT=".env.",$T=new Set([".env.example",".env.sample",".env.template",".env.tpl",".env.defaults"]),BT=[".env.example.",".env.sample."];function UT(G){let U;try{U=new URL(G.trim())}catch{return!1}return U.protocol!=="file:"&&U.host!==""}function HT(G){return G.length>0&&!/\s/.test(G)}function sa(G,U,j,K){let re=eh(G,U,j,K);return re!==""&&j.paths.entryKind(re)!=="missing"}function eh(G,U,j,K){try{return _i(G,U,j,K)}catch(re){if(re instanceof s)throw re;return""}}var jT=/[?&][^?&=/]+=/,VT=new Set(["node_modules","__pycache__"]),KT=[["vendor","bundle"],["vendor","cache"]];function qT(G,U,j,K,re){if(UT(G))return null;let oe=Cn(G,U,K,re);if(!oe)return null;let de=$t(oe.split("/").pop()??""),Se=$t(oe),we=()=>HT(de)||sa(G,U,K,re),We=$t(eI(G,U,K,re));for(let ft of $a){let pt=`~/${ft.suffixParts.join("/")}`;if((Ng(Se,pt)||Ng(We,pt))&&ir(ft.id,j))return ft.id}if($T.has(de)||BT.some((ft)=>de.startsWith(ft)))return null;let mt=YT(oe,U,j,K,re);if(mt)return mt;if(GT.has(de))return null;for(let ft of za)if(de===ft.basename&&ir(ft.id,j))return ft.id;if(de.startsWith(zT)&&ir($i.id,j)&&we())return $i.id;for(let ft of Ba)if(de.length>ft.prefix.length&&de.startsWith(ft.prefix)){let pt=de.slice(ft.prefix.length)[0];if((pt==="-"||pt==="_")&&ir(ft.id,j)&&we())return ft.id}for(let ft of Ua)if(de.length>ft.prefix.length&&de.startsWith(ft.prefix)){if(de.slice(ft.prefix.length)===ft.suffix&&ir(ft.id,j))return ft.id}if(JT(Se))return null;if(!de.includes(".")&&Bo.pattern.test(de)&&ir(Bo.id,j))return Bo.id;if(jT.test(G)&&!sa(G,U,K,re))return null;let gt=QT(de,j);if(gt)return gt;return null}function YT(G,U,j,K,re){return Bi.find((oe)=>{if(!ir(oe.id,j))return!1;switch(oe.id){case"secret.cli.claude-code":return Wt(G,Ht(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),[".credentials.json"]);case"secret.cli.claude-code.config":{let de=$t(G).split("/");return Wt(G,Ht(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),["settings.json","settings.local.json"])||Ri(G,"~/.claude.json",U,K,re)||de.at(-1)==="settings.local.json"&&de.at(-2)===".claude"||de.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Wt(G,Cn("~/.gemini/config",U,K,re),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let de=Ht(K.env.get("CODEX_HOME"),"~/.codex",U,K,re);return Wt(G,de,["auth.json",".credentials.json"])||_o(G,de,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let de=Ht(K.env.get("CODEX_HOME"),"~/.codex",U,K,re),Se=$t(G).split("/").at(-1)??"";return Wt(G,de,["config.toml"])||Se.endsWith(".config.toml")&&Wt(G,de,[Se])}case"secret.cli.gemini":return Wt(G,Qt(Ht(K.env.get("GEMINI_CLI_HOME"),"~",U,K,re),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let de=$t(G).split("/"),Se=K.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),we=K.env.get("ProgramData")?[Qt(Ht(K.env.get("ProgramData"),"",U,K,re),"gemini-cli")]:[];return Wt(G,Qt(Ht(K.env.get("GEMINI_CLI_HOME"),"~",U,K,re),".gemini"),["settings.json","google_accounts.json"])||de.at(-1)==="settings.json"&&de.at(-2)===".gemini"||(Se?.trim()?Ri(G,Se,U,K,re):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...we].some((We)=>Wt(G,Cn(We,U,K,re),["settings.json"]))}case"secret.cli.copilot-cli":{let de=Ht(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re);return Wt(G,de,["config.json"])||_o(G,de,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Wt(G,Ht(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re),["mcp-config.json"]);case"secret.cli.kimi-code":{let de=Ht(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),Se=Ht(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re);return Wt(G,de,["server.token"])||_o(G,de,["credentials"])||_o(G,Se,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let de=["config.toml","mcp.json"],Se=$t(G).split("/");return Se.at(-1)==="mcp.json"&&Se.at(-2)===".kimi-code"||Wt(G,Ht(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),de)||Wt(G,Ht(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re),[...de,"config.json","config.json.bak"])}case"secret.cli.opencode":{let de=Qt(Ht(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"opencode"),Se=$t(G).split("/").at(-1)??"",we=K.env.get("OPENCODE_DB")?.trim(),We=we&&we!==":memory:"?[we,`${we}-wal`,`${we}-shm`]:[];return Wt(G,de,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Se)&&Wt(G,de,[Se])||We.some((mt)=>Ri(G,mt,U,K,re))}case"secret.cli.opencode.config":{let de=Qt(Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"opencode"),Se=K.env.get("ProgramData")?[Qt(Ht(K.env.get("ProgramData"),"",U,K,re),"opencode")]:[],we=["opencode.json","opencode.jsonc"],We=K.env.get("OPENCODE_CONFIG");return we.includes($t(G).split("/").at(-1)??"")||Wt(G,de,["config.json"])||(We?.trim()?Ri(G,We,U,K,re):!1)||["/Library/Application Support/opencode","/etc/opencode",...Se].some((mt)=>Wt(G,Cn(mt,U,K,re),we))}case"secret.cli.pi":return Wt(G,Ht(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["auth.json"]);case"secret.cli.pi.config":return Wt(G,Ht(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["models.json"]);case"secret.cli.amp":{let de=Cn("~",U,K,re);return[Qt(Ht(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"amp"),Qt(de,".local","share","amp")].some((we)=>Wt(G,we,["secrets.json"]))||_o(G,Qt(de,".amp"),["oauth"])}case"secret.cli.amp.config":{let de=["settings.json","settings.jsonc"],Se=[Qt(Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"amp"),Qt(Cn("~",U,K,re),".config","amp")],we=$t(G).split("/"),We=K.env.get("AMP_SETTINGS_FILE");return Se.some((mt)=>Wt(G,mt,de))||we.at(-2)===".amp"&&de.includes(we.at(-1)??"")||(We?.trim()?Ri(G,We,U,K,re):!1)}case"secret.cli.cursor":{let de=Qt(Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"cursor"),Se=Qt(Ht(K.env.get("CURSOR_DATA_DIR"),"~/.cursor",U,K,re),"projects");return Wt(G,Cn("~/.cursor",U,K,re),["auth.json"])||Wt(G,de,["auth.json"])||$t(G).split("/").at(-1)==="mcp-auth.json"&&jr($t(G),$t(Se))}case"secret.cli.cursor.config":{let de=$t(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".cursor"}case"secret.cli.grok-build":return Wt(G,Ht(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let de=$t(G).split("/");return de.at(-1)==="config.toml"&&de.at(-2)===".grok"||Wt(G,Ht(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["config.toml","managed_config.toml","requirements.toml"])||Wt(G,Cn("/etc/grok",U,K,re),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return Wt(G,Cn("~/.factory",U,K,re),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let de=$t(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".factory"||Wt(G,Cn("~/.factory",U,K,re),["settings.json","hooks.json"])}case"secret.cli.devin":return[Ht(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),Cn("~/.local/share",U,K,re)].some((de)=>Wt(G,Qt(de,"devin"),["credentials.toml"])||_o(G,Qt(de,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),Cn("~/.config",U,K,re)].some((de)=>Wt(G,Qt(de,"devin"),["config.json"]));default:return!1}})?.id??null}var Dg=new WeakMap;function Ht(G,U,j,K,re){let oe=Dg.get(re)??new Map;Dg.set(re,oe);let de=`${j}\x00${G??""}\x00${U}`,Se=oe.get(de);if(Se!==void 0)return Se;let we=Cn(G?.trim()?G:U,j,K,re);return oe.set(de,we),we}function Wt(G,U,j){return j.some((K)=>th(G,Qt(U,K)))}function _o(G,U,j){return j.some((K)=>jr($t(G),$t(Qt(U,K))))}function Ri(G,U,j,K,re){return th(G,Cn(U,j,K,re))}function th(G,U){return $t(G)===$t(U)}function Qt(G,...U){return Bn([G,...U].filter(Boolean).join("/"))}function ZT(G,U,j,K,re,oe){if(j.length===0)return!1;let de=$t(_i(G,U,re,oe));return j.some((Se)=>jr(de,$t(_i(Se,K,re,oe))))}function XT(G,U,j,K,re,oe){if(j.length===0)return!1;let de=$t(_i(G,U,re,oe));if(!de)return!1;let Se=re.env.get("HOME")??re.home,we=Se?Bn(Nt(cn(Se),re.paths,oe)):"",We=$t(we),mt=re.env.get("CC_SAFETY_NET_HOME"),gt=$t(mt?Bn(Nt(aa(cn(mt)),re.paths,oe)):we&&Bn(Nt(`${we}/.cc-safety-net`,re.paths,oe)));if(gt&&jr(de,gt))return!1;return j.some((ft)=>{let pt=qa(ft);if(pt&&Lg.basename(de)!==$t(pt.name))return!1;let ht=$t(_i(pt?.root??ft,K,re,oe));if(!ht)return!1;if(We&&(We===ht||We.startsWith(ht.endsWith("/")?ht:`${ht}/`)))return!1;return jr(de,ht)&&!(pt&&de===ht)})}function JT(G){let U=G.split("/");return U.some((j)=>VT.has(j))||KT.some(([j,K])=>U.some((re,oe)=>re===j&&U[oe+1]===K))}function QT(G,U){let j=G.lastIndexOf("."),K=j>0&&j<G.length-1?G.slice(j+1):"";if(K==="")return null;for(let re of Ha)if(K===re.extension&&ir(re.id,U))return re.id;for(let re of ja)if(re.pattern.test(K)&&ir(re.id,U))return re.id;return null}function $t(G){return G.toLowerCase()}function ir(G,U){return!U?.disabledRules?.includes(G)}function Cn(G,U,j,K){let{home:re,normalized:oe}=Kc(G,j,K);if(!oe)return"";if(!re)return oe;let de=qc(oe,re),Se=ra(de)?de:Bn(aa(U,de)),we=Bn(Nt(Se,j.paths,K));if(!jr(we,re)){if(ra(de))return we;return we===Se?oe:we}let We=we.slice(re.length);return We?`~${We}`:"~"}function Ng(G,U){return G===U||G.startsWith(`${U}/`)}function eI(G,U,j,K){let{home:re,normalized:oe}=Kc(G,j,K);if(!oe||!re)return"";let de=qc(oe,re),Se=Lg.normalize(ra(de)?de:Bn(aa(U,de))),we=Bn(cn(j.env.get("HOME")??j.home)),We=(ft)=>process.platform==="win32"?ft.toLowerCase():ft,mt=[re,we].find((ft)=>ft!==""&&jr(We(Se),We(ft)));if(mt===void 0)return"";let gt=Se.slice(mt.length);return gt?`~${gt}`:"~"}function _i(G,U,j,K){let{home:re,normalized:oe}=Kc(G,j,K);if(!oe)return"";let de=re?qc(oe,re):oe;return Bn(Nt(ra(de)?de:aa(U,de),j.paths,K))}function Kc(G,U,j){let K=U.env.get("HOME")??U.home,re=K?Bn(Nt(cn(K),U.paths,j)):"",oe=Bn(cn(tI(er(G,U))));return{home:re,normalized:oe}}function tI(G){if(!G.trim().toLowerCase().startsWith("file:"))return G;try{return sP(G)}catch{return G}}function qc(G,U){if(G==="~")return U;if(G.startsWith("~/"))return Qt(U,G.slice(2));return G}function nI(G){if(process.platform==="win32")return!0;return iP.parse(G).root.length>1}function Bn(G){let U=G.trim(),j=(U.includes("\\")&&nI(U)?U.replace(/\\/g,"/"):U).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(j==="/")return j;return j.replace(/\/+$/g,"")}function jr(G,U){return G===U||G.startsWith(U.endsWith("/")?U:`${U}/`)}function mn(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}class p extends Error{stage;evaluation;name="GuardEvaluationError";constructor(G,U,j){super(`CC Safety Net ${G} dependency failed`,{cause:j});this.stage=G;this.evaluation=U}}var rI={findPolicyMutation:Rg,findGitMetadataMutation:qm,resolveGitMetadata:iI,loadPolicySnapshot:k,findSensitiveTarget:$g,analyzeCommand:hg,getModes:T},oI=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function q(G,U){let j={...rI,...U.dependencies},K=lI(G),re=wi(G)?G.command:K,oe=Cr("policy-protection",re,()=>Hm(G)),de=hn(oe,"input-candidate"),Se=hn(oe,"declared-command");if(wi(G)&&G.command?.trim()&&Se?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Un,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:G.command,segment:G.command}}};if(de?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:gf,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let we=Pn(),We=Cr("policy-protection",re,()=>j.resolveGitMetadata([G.context.executionCwd,G.context.configCwd],U.environment)),mt=Cr("policy-protection",re,()=>j.findPolicyMutation(oe,U.environment,we));if(mt){let St=re??mt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:He,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:St,segment:mt.target}}}}let gt=Cr("policy-protection",re,()=>Cg(oe,U.environment,we));if(gt){let St=re??gt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Ge,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:St,segment:gt.target}}}}let ft=Cr("policy-protection",re,()=>j.findGitMetadataMutation(oe,We,U.environment,we));if(ft){let St=re??ft.target;return{stage:"policy-protection",decision:{kind:"deny",reason:x,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:St,segment:ft.target}}}}let pt=Cr("config-load",re,()=>j.loadPolicySnapshot(U.environment,{...U.policyOptions,cwd:G.context.configCwd})),ht=pt.policy,yt=j.getModes(ht,U.environment.env),bt={level:yt.effectiveLevel,...sI(pt)},Ct=ht.secretProtection.enabled===!1?null:Cr("secret-protection",re,()=>j.findSensitiveTarget(oe,ht.secretProtection,U.environment,we,{strict:wi(G)||de?.program.dialect==="powershell"?yt.strict:void 0}));if(Ct){let St=re??Ct.target;return{stage:"secret-protection",...bt,decision:{kind:"deny",reason:Wg,intent:"hard_stop",ruleId:Ct.ruleId,evidence:{command:St,segment:Ct.target}}}}if(!wi(G))return{stage:"non-command",...bt,decision:{kind:"allow"}};if(!G.command||G.command.trim()==="")return{...Yc("command-validation",re),...bt};let vt=Cr("command-analysis",re,()=>yg(()=>j.analyzeCommand(G.command,{cwd:G.context.executionCwd,shell:G.route.shell,policySnapshot:pt,environment:U.environment,protectedGitMetadata:We,effectiveCapabilities:yt.capabilities,strict:yt.strict,paranoidRm:yt.paranoidRm,paranoidInterpreters:yt.paranoidInterpreters,worktreeMode:yt.worktreeMode,budget:we,...U.trace?{trace:U.trace}:{}},aI(oe),oe.store),G.command,U.trace));if(vt.decision){let St=!yt.strict&&(vt.decision.ruleId==="raw-text.dangerous-command"||vt.decision.reason===ui&&!oI.test(vt.decision.evidence?.segment??"")&&kn(G.command)===null);return{stage:"command-analysis",...bt,..."errorCode"in vt?{errorCode:vt.errorCode}:{},decision:St?{...vt.decision,unverifiedByStandardMode:!0}:vt.decision}}return{stage:"command-analysis",...bt,decision:{kind:"allow"}}}function iI(G,U){let j=[...new Set(G.filter((K)=>typeof K==="string"&&K!==""))].flatMap((K)=>U.gitMetadata(K)??[]);if(j.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(j.flatMap((K)=>K.entries))]),markerFiles:Object.freeze([...new Set(j.flatMap((K)=>K.markerFiles))]),directories:Object.freeze([...new Set(j.flatMap((K)=>K.directories))]),hooksDirectories:Object.freeze([...new Set(j.flatMap((K)=>K.hooksDirectories))])})}function sI(G){if(G.state==="ready")return{};return{configFallback:{reason:G.reason}}}function aI(G){return hn(G,"declared-command")?.program}function lI(G){try{return ie(G.input)}catch(U){let j=wi(G)?G.command:void 0;throw new p("policy-protection",Yc("policy-protection",U instanceof f?void 0:j,U),U)}}function Cr(G,U,j){try{return j()}catch(K){throw new p(G,Yc(G,K instanceof f?void 0:U,K),K)}}function Yc(G,U,j){let K=j instanceof s||j instanceof b;return{stage:G,decision:{kind:"deny",reason:K?da:ko,ruleId:K?"analysis.limit":"analysis.failed-closed",intent:"stop_and_explain",...U?{evidence:{command:U,segment:U}}:{}}}}function wi(G){return G.route.kind==="command"}
|
|
42
|
+
`?G.trim().split(/\s+/).filter(Boolean):G.split(U).filter(Boolean)}function yi(G){if(!G)return!0;return G.provenance==="unknown"?!/[$`]/.test(t(G)):G.provenance==="literal"}function Co(G){return G?t(G):""}function Bs(G){return`'${G.replaceAll("'",`'"'"'`)}'`}function mc(G,U){return dc(y(G,"posix"),U)}function bi(G){return mc(G,new Set(Array.from(G.matchAll(op)).flatMap((U)=>{let j=U[1]??U[2];return j===void 0?[]:[j]})))}function dc(G,U){if(G.status==="invalid"||G.status==="limited")return!1;let j=new Set(U);for(let K of G.nodes){if(K.kind==="group"){if(dc(K.body,j))return!0;continue}if(K.kind!=="command")continue;if(K.nested.some((re)=>dc(re,j))||up(K.words,j))return!0;L_(K,j)}return!1}function up(G,U){let j=G.findIndex((de)=>On(de.text)===null);if(j===-1)return!1;let K=G[j];if(!K)return!1;if(hi(K,U))return!0;let re=Dt(K.text);if(re==="source"||re==="."){let de=G[j+1]?.text==="--"?j+2:j+1;return rp(G[de],U)}if(qt.has(re)){let de=G.slice(j),Se=En(de.map((We)=>We.text)),we=Se.commandIndex??Se.scriptIndex;return!Se.syntaxCheck&&we!==null&&rp(de[we],U)}let oe=O_(G,j,U);if(oe===null)return!1;if(oe===-1)return!0;return up(G.slice(oe),U)}function O_(G,U,j){let K=Dt(G[U]?.text??"");if(K==="command")return M_(G,U+1);if(K==="exec")return D_(G,U+1);if(K==="env")return N_(G,U+1,j);return null}function M_(G,U){for(let j=U;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return G[j+1]?j+1:null;if(/^-[p]*[vV][pvV]*$/.test(K))return null;if(/^-p+$/.test(K))continue;return j}return null}function D_(G,U){for(let j=U;j<G.length;j++){let K=G[j]?.text??"";if(K==="--")return G[j+1]?j+1:null;if(K==="-a"){j++;continue}if(/^-a.+/.test(K)||/^-[cl]+$/.test(K))continue;return j}return null}function N_(G,U,j){for(let K=U;K<G.length;K++){let re=G[K],oe=re?.text??"";if(oe==="--")return G[K+1]?K+1:null;if(oe==="-S"||oe==="--split-string")return hi(G[K+1],j)?-1:K+2;if(oe.startsWith("-S")||oe.startsWith("--split-string="))return hi(re,j)?-1:K+1;if(oe==="-u"||oe==="--unset"||oe==="-C"||oe==="--chdir"||oe==="-P"){K++;continue}if(oe==="-i"||oe==="-0"||oe==="--null"||oe.startsWith("-u=")||oe.startsWith("--unset=")||oe.startsWith("-C")||oe.startsWith("--chdir=")||oe.startsWith("-P"))continue;if(oe.startsWith("-"))continue;if(On(oe))continue;return K}return null}function L_(G,U){if(!G.words.every((j)=>On(j.text)!==null))return;for(let j of G.words){let K=On(j.text);if(!K)continue;if(hi(j,U))U.add(K.name)}}function hi(G,U){if(!G)return!1;return G.parts.filter((j)=>j.provenance==="variable").some((j)=>Array.from(j.raw.matchAll(op)).some((K)=>{let re=K[1]??K[2];return re!==void 0&&(__.test(re)||U.has(re))}))}function rp(G,U){return!!G&&(G.parts.some((j)=>j.provenance!=="literal"&&j.provenance!=="variable")||hi(G,U))}var fc="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",pc="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",W_="__CC_SAFETY_NET_XARGS_INPUT__",Us="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",Hs="rm",F_=/(?:^|[;&|]\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,G_=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,z_=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,$_=/^(?:[0-9]+|[@*])$/;function pp(G,U){let j=G.map(t),{childStart:K,replacementToken:re}=$r(j),oe=j.slice(K),de=xt("xargs.shell-dynamic",pc);if(U_(oe,re,U)&&At(de,U.policy))return At(de,U.policy);for(let Se of zn(oe,U)){let we=Se.tokens,We=re!==null&&we[0]!==oe[0]&&(we[0]?.includes(re)??!1)?At(de,U.policy):null;if(We)return We;let mt=Cp(we,re,Se.wrapperEnvAssignments),gt=Se.head==="rm"&&re!==null&&bp(we,re),ft=U.analyzeChild(we,{...Fr(Se,U),dynamicInput:mt,dynamicSourceInput:gt||hp(we,Se.head,re,Se.wrapperEnvAssignments,mt,U.environment,U.strict?void 0:U.analyzeNested),dynamicRmInput:gt,shellDynamicMatch:de,dynamicSourceMatch:de,rmDynamicMatch:xt("xargs.rm-recursive-force-dynamic",fc)});if(ft)return ft;let pt=B_(we,re,U.policy?.rules??[],At(de,U.policy));if(pt)return pt;if(Se.head==="git"){let yt=re===null?[...we,W_]:we,bt=re!==null&&(we.some((Et)=>Et.includes(re))||Array.from(Se.envAssignments.values()).some((Et)=>Et.includes(re))),St=U.analyzeChild(yt,{...Fr(Se,U),worktreeMode:re===null||bt?!1:U.worktreeMode});if(St)return St}let ht=A(we,U.policy?.rules??[]);if(ht)return ht}return null}function B_(G,U,j,K){if(j.length===0)return null;if(U===null){for(let oe of j){let de=A([...G,...oe.subcommand?[oe.subcommand]:[],...oe.block_args],j);if(de)return de}return null}let re=Dt(G[0]??"");if(!j.some((oe)=>Dt(oe.command)===re))return null;return G.slice(1).some((oe)=>oe.includes(U))?K:null}function gp(G,U,j){let K=G.indexOf(U);if(K===-1||G.indexOf(U,K+U.length)!==-1)return[];let re=ep(G,K,U.length,j);return re===null?[]:[re]}function hp(G,U,j,K,re,oe,de){if(qt.has(U)){if(nr(G))return!1;if(j!==null&&H_(G,j,de))return!0;let Se=$n(G);if(!Se){let we=or(Kt(G));if(we.kind==="literal")return j!==null&&we.source.includes(j);return we.kind==="none"&&re}if(j!==null&&Se.includes(j)&&!yp(Se,j,de))return!0;if(kn(Se))return!0;return j_(Se,j,K)}if(Ln(U))return mp(G,j,ds,bm(U));if(In.has(U))return mp(G,j,jl,vf);if(U==="eval"){let Se=zs(Kt(G));if(Se.kind==="dynamic")return!0;if(j!==null)return Se.kind==="literal"&&Se.source.includes(j);return re}if(U==="find")return V_(G,j,oe);if(U==="git"){let Se=wn(G);return j===null?Se.subcommand===null:(Se.subcommand?.includes(j)??!1)||Se.subcommand!==null&&bo.has(Se.subcommand.toLowerCase())&&Sp(Se.rest,j).some((we)=>we.includes(j))}return!1}function yp(G,U,j){if(j===void 0)return!1;let K=U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`(?:^|[;&|({!\`\\n]|\\b(?:then|do|else|elif|if|while|until|time|command|builtin|nohup|eval|exec|source))\\s*(?:[A-Za-z_][A-Za-z0-9_]*=\\S*\\s+)*["']?${K}`).test(G)||/\bcase\b/.test(G))return!1;let oe=G.replaceAll(U,"/");return kn(oe)===null&&j(oe)===null}function mp(G,U,j,K){let re=j(G);if(U===null)return re.optionsOpen||j([...G,Us]).sources.some((Se)=>Se.value===Us);if(re.sources.some((Se)=>Se.value.includes(U)))return!0;let oe=K.flatMap((Se)=>[Se.selector,...Se.valueForm==="attached-only"||Se.valueForm==="attached-or-separate"?[`${Se.selector}${Us}`]:[],...Se.valueForm==="equals-or-separate"?[`${Se.selector}=${Us}`]:[]]),de=new Set(oe.flatMap((Se)=>G.flatMap((we)=>gp(we,U,Se))));return Fs(re.sources,de,(Se)=>j(G.map((we)=>we.replaceAll(U,Se))).sources)}function U_(G,U,j){if(G.length===0||(G[0]??"").toLowerCase()==="command")return!1;let K=new Set(Array.from(zn(G,j),(oe)=>oe.head)),re=U===null?[...G,Hs]:G.map((oe,de)=>de===0?oe:oe.replaceAll(U,Hs));return Array.from(zn(re,j)).some((oe)=>oe.head===Hs&&!K.has(Hs))}function bp(G,U){return Sp(G.slice(1),U).some((j)=>j.includes(U)&&(j.startsWith("-")||j.startsWith(U)))}function Sp(G,U){let j=G.findIndex((K)=>K==="--"&&!K.includes(U));return j===-1?G:G.slice(0,j)}function Cp(G,U,j){if(U===null)return!0;return G.some((K)=>K.includes(U))||Array.from(j.values()).some((K)=>K.includes(U))}function H_(G,U,j){let K=En(G),re=K.commandIndex===null?"":G[K.commandIndex]??"";if(re.includes(U)&&!yp(re,U,j)||K.scriptIndex!==null&&(G[K.scriptIndex]??"").includes(U))return!0;return["-c","-nc","-cn",`--${U}`,U].some((de)=>G.some((Se,we)=>{if(we===0||!Se.includes(U))return!1;return gp(Se,U,de).some((mt)=>{let gt=G.map((pt,ht)=>ht===we?pt.replaceAll(U,mt):pt),ft=En(gt);if(ft.commandIndex===null&&ft.scriptIndex===null)return!1;if(K.commandIndex===null&&ft.commandIndex!==null)return!0;if(K.scriptIndex===null&&ft.scriptIndex!==null)return!0;if(ft.commandIndex!==null&&(gt[ft.commandIndex]??"").includes(mt))return!0;return ft.scriptIndex!==null&&(gt[ft.scriptIndex]??"").includes(mt)})}))}function j_(G,U,j){let K=new Set(U===null?[]:Array.from(j).filter(([,re])=>re.includes(U)).map(([re])=>re));for(let re of G.matchAll(F_))if(fp(re,K))return!0;for(let re of G.matchAll(G_))for(let oe of(re[1]??"").matchAll(z_))if(fp(oe,K))return!0;return mc(G,K)}function fp(G,U){let j=G[1]??G[2];return j!==void 0&&($_.test(j)||U.has(j))}function V_(G,U,j){if(U===null)return!0;let K=!1,re=0;for(let oe=1;oe<G.length;oe++){let de=G[oe]??"";if(!K&&!de.startsWith("-")&&de!=="!"&&de!=="("){if(de.indexOf(U)===0)return!0;continue}if(K=!0,re>0){re--;continue}if(Vn(de)){let we=yo(G,oe);oe=we.nextIndex-1;for(let We of zn(we.tokens,{environment:j,cwd:void 0})){let mt=Cp(We.tokens,U,We.wrapperEnvAssignments);if(We.head==="rm"&&bp(We.tokens,U)||hp(We.tokens,We.head,U,We.wrapperEnvAssignments,mt,j))return!0}continue}let Se=rr(de);if(Se>0){if(re=Se,de.includes(U))return!0;continue}if(de.includes(U))return!0}return!1}function $r(G){let U=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,K=1;while(K<G.length){let re=G[K];if(!re)break;if(re==="--")return{childStart:K+1,replacementToken:j};if(!re.startsWith("-"))return{childStart:K,replacementToken:j};if(re==="-I"){j=G[K+1]??"{}",K+=2;continue}if(re.startsWith("-I")&&re.length>2){j=re.slice(2),K++;continue}if(re==="--replace"){j="{}",K++;continue}if(re.startsWith("--replace=")){let oe=re.slice(10);j=oe===""?"{}":oe,K++;continue}if(re==="-J"){j=G[K+1]??"{}",K+=2;continue}K+=U.has(re)?2:1}return{childStart:G.length,replacementToken:j}}var Si="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",Ci="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",q_="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",Y_="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Vs=/\{[^{}\s]*\}/g,vp=/\{\}|\{-?\d+\}/g,Ep=/[\s;&|<>()$`\\"']/,Z_=["e","f","source","file","-e","-f","--source","--file"],X_=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],J_=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),Q_=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),Rp=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),ew=new Set(["--workdir","--wd"]),xp="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Mn(G,U){for(let j of G){let K=U(j);if(K)return K}return null}function Ap(G){return Mn([...G],(U)=>kn(U))}function Pp(G,U){let j=G.map(t);if((U.envAssignments?.has("PARALLEL")?U.envAssignments.get("PARALLEL"):U.environment.env.get("PARALLEL"))?.trim()){let ht=vo(U);if(ht)return ht}if(j.length===2&&(j[1]==="--version"||j[1]==="--help"))return null;let re=zp(j),{template:oe,jobs:de,runsRemotely:Se,readsCommandsFromInput:we,unsupported:We,workdir:mt,dryRun:gt}=re;if(We){let ht=vo(U);if(ht)return ht;let yt=Ap(U.envAssignments?.values()??[]);if(yt)return yt}if(we){let ht=aw(U);if(ht)return ht}if(mt!==void 0&&Se){let ht=vo(U);if(ht)return ht}let ft=lw(mt,U.cwd,U.environment.paths);if(ft===null){let ht=vo(U);if(ht)return ht}let pt=Se?{...U,cwd:void 0,originalCwd:void 0}:ft===null||ft===void 0||ft===U.cwd?U:{...U,cwd:ft};if(gt){if([...zn(oe,pt)].flatMap((yt)=>[...yt.envAssignments.values()]).some(yc)){let yt=vo(U);if(yt)return yt}return null}if(oe.length===0){let ht=de.map((bt)=>bt[0]??"");U.budget.charge("derivedTokens",ht.length);let yt=Dp(pt.envAssignments,pt.cwd,Se);return Mn(ht,(bt)=>U.analyzeNested(bt,yt))}return Mn(zn(oe,pt),(ht)=>tw(ht,re,U,pt))}function tw(G,U,j,K){let{templateHasPlaceholder:re,runsRemotely:oe,usesStdin:de}=U,Se=G.tokens,we=[...G.envAssignments.values()];if(we.some(Fp)){let Rt=vo(j);if(Rt)return Rt}let We=Ap(we);if(We)return We;let mt=we.some(zt),gt=re||mt,ft=de&>,pt=Dp(G.envAssignments,G.wrapperCwd,oe||ft),ht=gt?{...pt,worktreeMode:!1}:pt,yt=Se.join(" "),bt=zt(yt.split(/[ \t\n=]/,1)[0]??""),St=!U.quotesCommand&&(bt||Se.some((Rt)=>Ep.test(Rt))),Et=bt||Ep.test(Se[0]??""),Ct=St&&Et&&U.jobs.length>0?null:nw(G,U,j,K,ht,mt);if(Ct||!St)return Ct;return Tp(zt(yt)?yt:`${yt} {}`,!bt,G,U,j,K,ht)}function nw(G,U,j,K,re,oe){let{jobs:de,templateHasPlaceholder:Se,runsRemotely:we,usesStdin:We}=U,mt=G.tokens,gt=Se||oe;if(qt.has(G.head)){let pt=()=>{if(!Se||de.length===0)return null;return Mn(de,(bt)=>j.analyzeChild(js(mt,bt,j.budget),Fr(G,K)))};if(nr(mt))return pt();let ht=$n(mt);if(ht){if(Gp(ht)){let Ct=hr(j);if(Ct)return Ct;if(de.length===0)return null;return Mn(de,(Rt)=>j.analyzeNested(Lp(ht,Rt,j.budget),re))}if(zt(ht))return Tp(ht,!1,G,U,j,K,re);let bt=!oe&&(!Se||de.length>0)?(de.length>0?de:[void 0]).map((Ct)=>$s(Kt(Ct===void 0?mt:Se?mt.map((Rt)=>Np(Rt,Ct)):[...mt,...Ct]),ht)):[];if(bt.some((Ct)=>Ct.kind==="dynamic")){let Ct=hr(j);if(Ct)return Ct}let St=bt.flatMap((Ct)=>Ct.kind==="literal"?[Ct.source]:[]);if(St.length>0)return j.budget.charge("derivedTokens",St.length),Mn(St,(Ct)=>j.analyzeNested(Ct,re));if(bi(ht)){let Ct=hr(j);if(Ct)return Ct}let Et=j.analyzeNested(ht,re);if(Et)return Et;if(gt)return hr(j);return null}let yt=or(Kt(mt));if(yt.kind==="dynamic"||yt.kind==="literal"&&zt(yt.source))return hr(j)??pt();if(yt.kind==="literal")return pt();if(de.length>0){let bt=hr(j);if(bt)return bt;let St=pt();if(St)return St;if(Se)return null;let Et=de.flatMap((Ct)=>Ct[0]===void 0?[]:[Ct[0]]);return j.budget.charge("derivedTokens",Et.length),Mn(Et,(Ct)=>j.analyzeNested(Ct,re))}if(gt||We)return hr(j)??pt();return null}if(G.head==="rm"&&tr(mt)){if(Se&&de.length>0)return Mn(de,(ht)=>gc(js(mt,ht,j.budget,vp),G.cwd,K));if(de.length>0)return Mn(de,(ht)=>gc(wp(mt,ht,j.budget),G.cwd,K));let pt=gc(mt.flatMap((ht,yt)=>{if(yt===0||!zt(ht))return[ht];return ht.startsWith("-")?[ht.replace(vp,"")]:[]}),G.cwd,K);if(pt)return pt;return Mp(j)}let ft=de.length>0?de:[void 0];return Mn(ft,(pt)=>{let ht=pt===void 0?mt:Se?js(mt,pt,j.budget):wp(mt,pt,j.budget),yt=xt("parallel.shell-dynamic",Ci),bt=We&&G.head==="find"?sw(ht,K):null,St=kp(ht,We,j)??bt?.customResult??null,Et=Dt(G.head),Ct=We&&(Et==="rm"&&hc(ht)||Et==="xargs"&&Op(ht)||bt?.rmOptions===!0),Rt=We&&(Ct||bt?.executedSource===!0||bt===null&&Ip(ht,Et)),Pt=j.analyzeChild(ht,{...Fr(G,K),worktreeMode:we||We||gt?!1:j.worktreeMode,dynamicInput:We||gt,dynamicRmInput:Ct,dynamicSourceInput:St!==null||Rt,shellDynamicMatch:yt,dynamicSourceMatch:yt,rmDynamicMatch:xt("parallel.rm-recursive-force-dynamic",Si)});if(Rt){let Tt=At(yt,j.policy);if(Tt)return Tt}return Pt??St??A(ht,j.policy?.rules??[])})}function Tp(G,U,j,K,re,oe,de){if(K.jobs.length>0)return Mn(K.jobs,(We)=>re.analyzeNested(Lp(G,U?We.map(Bs):We,re.budget),de));let Se=gi(G);if(Se?.[0]&&Dt(Se[0])==="rm"&&tr(Se)){let We=Mp(re);if(We)return We}return(Se?re.analyzeChild(Se,{...Fr(j,oe),dynamicInput:K.usesStdin,shellDynamicMatch:xt("parallel.shell-dynamic",Ci),rmDynamicMatch:xt("parallel.rm-recursive-force-dynamic",Si)}):null)??re.analyzeNested(G,de)}function Ip(G,U){if(zt(G[0]??""))return!0;if(U==="eval"||U==="source"||U===".")return!0;if(U==="parallel"||U==="xargs")return!0;if(qt.has(U))return iw(G);if(U==="git")return rw(G);if(U==="find")return!0;if(In.has(U))return _p(G,Z_,fi);if(Ln(U))return _p(G,X_,cs);return!1}function hc(G){let U=G.indexOf("--"),j=G.slice(1,U===-1?void 0:U);if(!G.some(zt))return U===-1;return j.some((re)=>zt(re)&&(re.startsWith("-")||Gp(re)))}function rw(G){if(ow(G))return!0;let U=wn(G);if(U.subcommand===null||zt(U.subcommand))return!0;if(!bo.has(U.subcommand.toLowerCase()))return!1;let j=U.rest.indexOf("--"),K=U.rest.slice(0,j===-1?void 0:j);if(!G.some(zt))return j===-1;return K.some(zt)}function ow(G){for(let U=1;U<G.length;U++){let j=G[U];if(!j||j==="--"||!j.startsWith("-"))return!1;if(j==="-c"||j==="--config-env"){if(zt(G[U+1]??""))return!0;U++;continue}if(j.startsWith("-c")&&j.length>2||j.startsWith("--config-env=")){if(zt(j))return!0;continue}if(zt(j))return!0}return!1}function iw(G){if(nr(G))return!1;let U=$n(G);if(U!==null)return zt(U);let j=or(Kt(G));if(j.kind==="literal")return zt(j.source);if(j.kind==="dynamic")return!0;return!G.some(zt)}function _p(G,U,j){let K=j(G);if(K.some((re)=>zt(re.value)))return!0;if(!G.some(zt))return j([...G,xp]).some((re)=>re.value===xp);return Fs(K,U,(re)=>j(G.map((oe)=>Np(oe,[re]))))}function kp(G,U,j){let K=j.policy?.rules??[];if(!U||K.length===0)return null;let re=K.filter((oe)=>Dt(oe.command)===Dt(G[0]??""));if(re.length===0)return null;if(G.slice(1).some(zt))return hr(j);return Mn(re,(oe)=>A([...G,...oe.subcommand?[oe.subcommand]:[],...oe.block_args],[oe]))}function sw(G,U){let j={customResult:null,executedSource:!G.some(zt),rmOptions:!1},K=!1,re=0,oe=null,de=()=>{if(!oe?.some(zt))return;for(let Se of zn(oe,U))j.executedSource||=Ip(Se.tokens,Se.head),j.rmOptions||=Se.head==="rm"&&hc(Se.tokens)||Se.head==="xargs"&&Op(Se.tokens),j.customResult??=kp(Se.tokens,!0,U)};for(let Se of G.slice(1)){if(!K&&!Se.startsWith("-")&&Se!=="!"&&Se!=="("){j.executedSource||=zt(Se);continue}if(K=!0,oe){if(Se===";"||Se==="+"){de(),oe=null;continue}oe.push(Se);continue}if(re>0){re--;continue}if(Vn(Se)){oe=[],j.executedSource||=zt(Se);continue}let we=rr(Se);if(we>0){re=we,j.executedSource||=zt(Se);continue}j.executedSource||=zt(Se)}return de(),j}function Op(G){let U=G.slice($r(G).childStart);return Dt(U[0]??"")==="rm"&&hc(U)}function Ks(G,U){return(j)=>At(xt(G,U),j.policy)}var hr=Ks("parallel.shell-dynamic",Ci),aw=Ks("parallel.command-stream-dynamic",q_),vo=Ks("parallel.command-stream-dynamic",Y_),Mp=Ks("parallel.rm-recursive-force-dynamic",Si);function gc(G,U,j){return At(Gs(Kt(G),{environment:j.environment,cwd:U,budget:j.budget,originalCwd:j.originalCwd,strict:j.strict,paranoid:j.paranoidRm,allowTmpdirVar:j.allowTmpdirVar,tmpdirWordSplittingUnsafe:Dr(j.envAssignments??new Map,j.environment),trustedTmpdirValue:mo(j.envAssignments??new Map,j.environment),protectedGitMetadata:j.protectedGitMetadata,policy:j.policy}),j.policy)}function Dp(G,U,j){let K={};if(G)K.envAssignments=G;if(j)return K.effectiveCwd=null,K.worktreeMode=!1,K;if(U!==void 0)K.effectiveCwd=U;return Object.keys(K).length>0?K:void 0}function Np(G,U){return G.replace(Vs,(j)=>Wp(j,U))}function js(G,U,j,K=Vs){return j.charge("derivedTokens",G.reduce((re,oe)=>re+1+Math.floor(oe.length/64),0)),G.map((re)=>re.replace(K,(oe)=>{let de=Wp(oe,U);return j.charge("derivedTokens",Math.max(1,Math.ceil(de.length/64))),de}))}function Lp(G,U,j){return js([G],U,j)[0]??""}function wp(G,U,j){return j.charge("derivedTokens",G.length+U.length),[...G,...U]}function Wp(G,U){let j=/^\{(-?\d+)[^{}\s]*\}$/.exec(G)?.[1];if(j===void 0)return U[0]??"";let K=Number(j);return U[K>0?K-1:U.length+K]??""}function zt(G){return G.search(Vs)!==-1}function Fp(G){if(yc(G))return!0;for(let U of G.matchAll(Vs))if(!/^(?:\{\}|\{\d+\})$/.test(U[0]))return!0;return!1}function yc(G){let U=G.indexOf("{=");return U!==-1&&G.indexOf("=}",U+2)!==-1}function Gp(G){return/^\{[^{}\s]*\}$/.test(G)}function lw(G,U,j){if(G===void 0)return;if(G==="..."||/^~|[{}$`*?[]/.test(G))return null;if(!U&&!K_(G))return null;try{return dr(U??G,G,j)}catch{return null}}function zp(G){let U=1,j=[],K=G.length,re=-1,oe=!1,de=!1,Se=!1,we,We=!1,mt=G.some((yt)=>yt==="::::"||yt==="::::+"||yt===":::+");while(U<G.length){let yt=G[U];if(yt===void 0)break;if(yt===":::"){re=U;break}if(yt==="--"){let Rt=ql(G,U+1);j.push(...Rt.templateTokens),K=U+1,re=Rt.markerIndex;break}if(!yt.startsWith("-")){let Rt=ql(G,U);j.push(...Rt.templateTokens),K=U,re=Rt.markerIndex;break}let bt=G[U+1],St=yt.indexOf("="),Et=St===-1?yt:yt.slice(0,St),Ct=St===-1?void 0:yt.slice(St+1);if(yt==="--dry-run"){We=!0,U++;continue}if(yt==="-I"||yt.startsWith("-I")&&yt.length>2){mt||=(yt==="-I"?bt:yt.slice(2))!=="{}",U+=yt==="-I"?2:1;continue}if(yt==="--replace"||yt==="-i"){mt=!0,U+=2;continue}if(Et==="--replace"||yt.startsWith("-i")&&yt.length>2){let Rt=Et==="--replace"?Ct:yt.slice(2);mt||=Rt!==""&&Rt!=="{}",U++;continue}if(yt==="-a"||Q_.has(Et)){mt=!0,U+=Ct===void 0?2:1;continue}if(yt==="-q"||yt==="--quote"){de=!0,U++;continue}if(yt==="--pipe"||yt==="--pipepart"){Se=!0,U++;continue}if(Et==="--env"){mt=!0,U+=Ct===void 0?2:1;continue}if(Rp.has(Et)||yt.startsWith("-S")&&yt.length>2){oe=!0,U+=Rp.has(yt)?2:1;continue}if(ew.has(Et)){mt=!0;let Rt=Ct??bt;if(Rt===void 0||Rt===":::"||Rt==="--"){U++;continue}we=Rt,U+=Ct===void 0?2:1;continue}if(yt.startsWith("-j")&&yt.length>2&&/^\d+$/.test(yt.slice(2))){U++;continue}if(yt.startsWith("--")&&Ct!==void 0){U++;continue}if(J_.has(yt)){if(bt===void 0||bt===":::"||bt==="--"){mt=!0,U++;continue}U+=2;continue}U+=yt==="-j"||yt==="--jobs"?2:1}mt||=j.some(We?yc:Fp);let gt=[];if(re!==-1){let yt=[];for(let bt=re+1;bt<G.length;bt++){let St=G[bt];if(St===":::"){gt.push(yt),yt=[];continue}if(St!==void 0)yt.push(St)}gt.push(yt)}mt||=gt.length>1;let ft=cw(gt),pt=j.some(zt),ht=j.length===0&&re===-1;return{template:j,jobs:ft,childStart:K,templateHasPlaceholder:pt,runsRemotely:oe,quotesCommand:de,usesStdin:Se||re===-1,readsCommandsFromInput:ht,unsupported:mt,workdir:we,dryRun:We}}function cw(G){if(G.length===0||G.some((j)=>j.length===0))return[];let U=[[]];for(let[j,K]of G.entries()){if(K.length===1){let oe=K[0];if(oe===void 0)return[];for(let de of U)de.push(oe);if(U.length*(j+1)>a.derivedTokens.cap)throw new s("derivedTokens");continue}let re=[];for(let oe of U)for(let de of K){if((re.length+1)*(j+1)>a.derivedTokens.cap)throw new s("derivedTokens");re.push([...oe,de])}U=re}return U}function $p(G){return zp(G).childStart}var dw="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",qs="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function Sc(G){return G?.parts.some((U)=>U.provenance==="command-substitution")??!1}function bc(G){return G?.parts.some((U)=>U.provenance==="literal"&&U.raw.replace(/^["']/,"").startsWith("-"))??!1}function Up(G,U,j,K,re=!1,oe){let Se=(jo(G,U)||K&&G!=="powershell"&&U[0]?.provenance==="variable")&&Jt(oe,"shell.dynamic-executable",re)?xt("shell.dynamic-executable",dw):null;return At(Se,oe)??Hp(G,U,j,re,oe)}function Hp(G,U,j,K,re){if(U.length<2)return null;let oe=U.flatMap((Se,we)=>Sc(Se)?[we]:[]);if(oe.length===0)return null;let de=Dt(U[0]?.text??"");if(de==="git"){let Se=ne(G,U),we=mw(Se);if(Jt(re,"shell.dynamic-structure",K)&&oe.some((gt)=>gt<=we))return At(xt("shell.dynamic-structure",qs),re);if(At(Ws(Se,{environment:j}),re))return null;let We=U[we]?.text.toLowerCase(),mt=Se.findIndex((gt,ft)=>ft>we&&t(gt)==="--");if(Jt(re,"shell.dynamic-structure",K)&&We&&bo.has(We)&&oe.some((gt)=>gt>we&&(mt===-1||gt<mt)))return At(xt("shell.dynamic-structure",qs),re);return null}if(de==="find")return Jt(re,"shell.dynamic-structure",K)&&fw(U)?At(xt("shell.dynamic-structure",qs),re):null;if(de==="rm"){let Se=U.findIndex((We,mt)=>mt>0&&t(We)==="--"),we=tr(U.map(t));return Jt(re,"shell.dynamic-structure",K)&&oe.some((We)=>(Se===-1||We<Se)&&(We<U.length-1||!we))?At(xt("shell.dynamic-structure",qs),re):null}if(de==="xargs")return Bp(G,U.slice($r(U.map(t)).childStart),"xargs",j,K,re);if(de==="parallel")return Bp(G,U.slice($p(U.map(t))),"parallel",j,K,re);return null}function Bp(G,U,j,K,re,oe){if(U.length===0)return null;let de=uw(U,K);if(jo(G,de)){let we=At(xt(`${j}.shell-dynamic`,j==="xargs"?pc:Ci),oe);if(we)return we}let Se=Hp(G,de,K,re,oe);if(Se)return Se;if(de[0]?.text==="rm"&&de.slice(1).some((we)=>Sc(we)&&bc(we)))return At(xt(`${j}.rm-recursive-force-dynamic`,j==="xargs"?fc:Si),oe);return null}function uw(G,U){let j=kr(G,U),K=j.rewritten?Kt(j.words.map(t)):j.words,re=K[0];return re&&t(re)==="busybox"?K.slice(1):K}function mw(G){let U=1;while(U<G.length){let j=G[U],K=j?t(j):"";if(vn.has(K)){U+=2;continue}if(K.startsWith("-")){U++;continue}return U}return U}function fw(G){let U=!1,j=0,K=!1,re=!1;for(let oe=1;oe<G.length;oe++){let de=G[oe];if(!de)continue;let Se=Sc(de);if(j>0){j--;continue}if(re){if(de.text===";"||de.text==="+"){re=!1,U=!0,K=!1;continue}if(Se&&(K||bc(de)))return!0;K=!1;continue}if(!U&&!de.text.startsWith("-")){if(Se&&(oe>1||bc(de)))return!0;continue}if(U=!0,Se)return!0;let we=rr(de.text);if(we>0){j=we;continue}if(Vn(de.text))re=!0,K=!0}return!1}function Cc(G,U){return G.some((j)=>{if(j.value==="-"&&(j.kind==="main-script"||j.kind==="program-file"))return!0;return!oo(U[j.tokenIndex],j.value)})}var jp="cmd rmdir /s or del /s outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",pw="cmd rmdir /s or del /s 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.",gw="cmd rmdir /s or del /s target contains wildcards or variables that cannot be verified safely. Use literal paths within cwd.",hw="cmd rmdir /s or del /s targeting root or home directory is extremely dangerous and always blocked.",yw="cmd rmdir /s or del /s with \\\" quoting or a \\\\?\\ path is blocked: cmd does not treat \\\" as an escape, so the target can split down to the root of the drive. Pass each path as its own quoted argument, or use Remove-Item -LiteralPath.",bw="cmd rmdir /s or del /s in home directory is dangerous. Change to a project directory first.",Sw={root_or_home_target:{id:"cmd.recursive-delete-root-or-home",reason:hw},git_metadata_target:{id:"cmd.recursive-delete-git-metadata",reason:x},dynamic_target:{id:"cmd.recursive-delete-dynamic-target",reason:gw},home_cwd_target:{id:"cmd.recursive-delete-home-cwd",reason:bw},cwd_self_target:{id:"cmd.recursive-delete-cwd-self",reason:jp},within_anchored_cwd:{id:"cmd.recursive-delete-paranoid",reason:pw},outside_anchored_cwd:{id:"cmd.recursive-delete-outside-cwd",reason:jp}},Cw=/^\/\/?[ck]$/i,Vp=/[&|]+/,vw=/(?:"[^"]*"|[^\s"])+/g,Ew=/[\^%!]/,Rw=/\\"./s,xw=/(^|\/)[*.]*\*[*.]*$/,_w=/^"?[\\/]+[?.][\\/]/,ww=new Set(["rmdir","rd","del","erase"]),Aw=/(?<![\w-])(?:rmdir|rd|del|erase)(?!\w)/i,Pw=/\/s(?!\w)/i,Tw=/(?<![\w-])(?:cd|chdir|pushd|popd)(?!\w)/i;function Kp(G,U){let j=G.map(t),K=j.findIndex((ft)=>Cw.test(ft));if(K===-1)return null;let re=j.slice(K+1).join(" "),oe=/^".*"$/s.test(re)?re.slice(1,-1):re,de=oe.split(Vp).map((ft)=>{let pt=ft.match(vw)??[],ht=pt.findIndex((bt)=>ww.has(bt.replace(/^@/,"").toLowerCase())),yt=ht===-1?[]:pt.slice(ht);return{piece:ft,tokens:pt,deleteTokens:yt,recursiveDelete:yt.slice(1).some((bt)=>bt.startsWith("/")&&bt.toLowerCase().split("/").includes("s"))}}),Se=de.filter((ft)=>ft.recursiveDelete),we=Se.length>0||Aw.test(oe)&&Pw.test(oe);if(we&&(oe.includes("\\\"")||U.gitBashEscapesBodyQuotes&&oe.includes('"')||U.powerShellRawWords.some((ft)=>Rw.test(ft))||Se.some((ft)=>ft.tokens.some((pt)=>_w.test(pt)))))return xt("cmd.recursive-delete-escaped-quote",yw);let We=jn({...U,allowPaths:U.policy?.destructiveCommandAllowPaths}),mt=de.reduce((ft,pt)=>ft??(pt.recursiveDelete?Iw(pt.deleteTokens,We,U.policy):U.analyzeNested(pt.piece)),null),gt=we&&(Se.length===0||Ew.test(oe)||Tw.test(oe)||oe.includes('"')&&Vp.test(oe));return mt??(gt?ho():null)}function Iw(G,U,j){return G.slice(1).filter((K)=>!K.startsWith("/")).reduce((K,re)=>K??At(Lr(_n(di(re.replaceAll('"',"")).replace(xw,"$1*"),U),U,j,Sw),j),null)}var kw="Recursive delete handed to powershell or pwsh in a form CC Safety Net does not read is blocked: pass the script as a single -Command with literal paths, after only -NoProfile, -NonInteractive, -NoLogo, or -ExecutionPolicy.",Ow=/^-(?:noprofile|nop|noninteractive|noni|nologo)$/i,Mw=/^-(?:executionpolicy|ep)$/i,Dw=/^-(?:command|c)$/i,Nw=/^(?:--?|[/\u2013\u2014\u2015])(\w+)$/,Lw="encodedcommand",Ww=/(?<![\w-])(?:remove-item|ri|rm|rmdir|rd|del|erase)(?![\w-])/i,Fw=/(?<![\w-])(?:[-\u2013\u2014\u2015]{1,2}r(?:e(?:c(?:u(?:r(?:s(?:e|ive?)?)?)?)?)?)?(?!\w)|-[dfipvwx]*r[dfipvwx]*(?!\w))|\/s(?!\w)/i,Gw=/[$`]/,zw="--%";function qp(G,U){let j=G.map(t),K=j.every((oe,de)=>de===0||oe!==zw&&$w(G[de],oe))?Ec(j):void 0;if(K!==void 0)return U(K);if(j.some(Bw))return ho();let re=j.join(" ");return Ww.test(re)&&Fw.test(re)?xt("powershell.nested-recursive-delete-unread",kw):null}function Ec(G){let U=vc(G,1),j=U===void 0?[]:G.slice(U+1);return j.length>0?j.join(" "):void 0}function vc(G,U){let j=G[U]??"";if(Dw.test(j))return U;if(Ow.test(j))return vc(G,U+1);return Mw.test(j)?vc(G,U+2):void 0}function $w(G,U){return G?.provenance==="unknown"?!Gw.test(U):oo(G,U)}function Bw(G){let U=Nw.exec(G)?.[1]?.toLowerCase();return U!==void 0&&(U==="ec"||Lw.startsWith(U))}var Zp=[{heads:new Set(["rm","rmdir"]),analyze:(G)=>Gs(G.words,Rc(G))},{heads:new Set(["cmd"]),analyze:(G)=>Kp(G.words,{...Rc(G),powerShellRawWords:G.options.commandView?.dialect==="powershell"?G.options.commandView.words.map((U)=>U.raw):[],gitBashEscapesBodyQuotes:G.options.commandView?.dialect!=="powershell",analyzeNested:(U)=>yr(G.options.analyzeNested(U,{effectiveCwd:G.effectiveCwd,envAssignments:G.envAssignments}))})},{heads:new Set(["powershell","pwsh"]),analyze:(G)=>qp(G.parsedWords,(U)=>yr(G.options.analyzeNested(U,{effectiveCwd:G.effectiveCwd,envAssignments:G.envAssignments,shell:"powershell"})))},{heads:new Set(["git"]),analyze:(G)=>Ws(G.words,xc(G))},{heads:new Set(["find"]),analyze:(G)=>Tf(G.words,{...Rc(G),envAssignments:G.envAssignments,analyzeTokens:G.analyzeChildTokens})},{heads:new Set(["xargs"]),analyze:(G)=>pp(G.words,{...Yp(G),analyzeChild:G.analyzeChild,analyzeNested:(U,j)=>yr(G.options.analyzeNested(U,j))})},{heads:new Set(["parallel"]),analyze:(G)=>Pp(G.words,{...Yp(G),analyzeChild:G.analyzeChild,analyzeNested:(U,j)=>yr(G.options.analyzeNested(U,j))})}];function Yp(G){return{environment:G.options.environment,cwd:G.cwd,originalCwd:G.originalCwd,strict:G.options.strict,paranoidRm:G.options.paranoidRm,paranoidInterpreters:G.options.paranoidInterpreters,allowTmpdirVar:G.allowTmpdirVar,protectedGitMetadata:G.options.protectedGitMetadata,budget:G.options.budget,envAssignments:G.envAssignments,worktreeMode:G.options.worktreeMode,policy:G.options.policy}}function yr(G){return G?{id:G.ruleId,reason:G.reason,intent:G.intent??"manual_only"}:null}function Rc(G){return{environment:G.options.environment,cwd:G.cwd,originalCwd:G.originalCwd,strict:G.options.strict,paranoid:G.options.paranoidRm,allowTmpdirVar:G.allowTmpdirVar,tmpdirWordSplittingUnsafe:Dr(G.envAssignments,G.options.environment),trustedTmpdirValue:mo(G.envAssignments,G.options.environment),protectedGitMetadata:G.options.protectedGitMetadata,policy:G.options.policy,budget:G.options.budget}}function xc(G){return{environment:G.options.environment,cwd:G.cwd,originalCwd:G.originalCwd,dynamicArguments:G.dynamicArguments,envAssignments:G.envAssignments,shellAssignments:G.options.shellAssignments,policy:G.options.policy,worktreeMode:G.options.worktreeMode}}function Qp(G){return Zp.find((U)=>U.heads.has(G))?.analyze}function Ro(G,U,j){let K=j.trace;if(G.length===0)return null;let re=j.commandView?.dialect??"posix",oe=(wt)=>wt.map((Mt)=>re==="posix"?t(Mt):Mt.text),de=j.child,Se=de!==void 0&&!de.embedded,we=de?.embedded===!0,We=j.effectiveCwd===null,mt=de?de.cwd:We?void 0:j.effectiveCwd??j.cwd,gt=de?de.originalCwd:We?void 0:j.cwd,ft=ve(G);if(ft.envAssignments.size>0)K?.recordSegment({type:"env-strip",input:oe(G),envVars:[...ft.envAssignments.keys()],output:oe(ft.words)});let pt=kr(ft.words,j.environment,mt,new Map([...j.envAssignments??[],...ft.envAssignments])),ht=pt.envSplitValues??[];if(ht.length>0){let wt=[...ht,...oe(pt.words)].join(" "),Mt=kn(wt);if(Mt)return K?.recordSegment({type:"dangerous-text",token:wt,matched:!0,reason:Mt.reason}),un(Mt);if(j.strict)return bn(K);let $t=ps(ht,oe(pt.words));if($t){j.budget.charge("derivedTokens",$t.length);let tn=j.analyzeNested($t.join(" "),{effectiveCwd:pt.cwd===void 0?j.effectiveCwd:pt.cwd,envAssignments:new Map([...j.envAssignments??[],...ft.envAssignments,...pt.envAssignments])});if(tn)return tn}}let yt=pt.rewritten?Kt(oe(pt.words)):ne(re,pt.words),bt=oe(yt),St={...j,wrapperNormalizationBudget:j.wrapperNormalizationBudget??{iterations:0}};if(K&&ft.words.length>yt.length){let wt=oe(ft.words);K.recordSegment({type:"leading-tokens-stripped",input:wt,removed:wt.slice(0,wt.length-yt.length),output:bt})}let Et=new Map([...j.envAssignments??[],...ft.envAssignments,...pt.envAssignments]),Ct=bt[0];if(!Ct)return null;if(Wr(Ct))throw new s("wrapperPeelIterations");let Rt=Dt(Ct),Pt=pt.cwd===null?void 0:pt.cwd??mt,Tt=pt.cwd===null?void 0:gt,kt=pt.cwd===void 0?j.effectiveCwd:pt.cwd,vt=de?de.allowTmpdirVar:!li(Et,j.environment),It=Up(re,pt.words,j.environment,U===0,j.strict,j.policy);if(It)return K?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:It.reason}),un(It);let Lt=ks(bt,j.policy);if(Lt){for(let wt of[Lt.childIndex,...Lt.alternativeChildIndices]){Xp(St.wrapperNormalizationBudget);let Mt=yt.slice(wt);K?.recordSegment({type:"transparent-wrapper",wrapper:Lt.wrapper,output:oe(Mt)});let $t=Ro(Mt,U,{...St,effectiveCwd:kt,envAssignments:Et});if($t)return $t}return null}let en=we?void 0:Rt==="eval"?zs(yt):Rt==="trap"&&!Se?ap(yt):void 0;if(Se&&de&&Rt==="eval"){if(en?.kind==="dynamic")return Eo(de,j.policy);if(en?.kind==="literal"){let wt=j.analyzeNested(en.source,{effectiveCwd:kt,envAssignments:Et});if(wt)return wt}return xo(de,j.policy)}if(en?.kind==="dynamic"&&(j.strict||!j.commandView||!uc(j.commandView)))return bn(K);if(en?.kind==="literal"){K?.recordSegment({type:"recurse",reason:Rt==="eval"?"shell-eval":"shell-trap",innerCommand:en.source,depth:U+1});let wt=j.analyzeNested(en.source,{effectiveCwd:kt,envAssignments:Et,functionDefinitions:j.functionDefinitions});if(wt)return wt}if(Se?qt.has(Rt):tg(Ct,Rt)){if(nr(bt))return null;if(Se&&de){let wt=$n(bt);if(wt){if(de.dynamicSourceInput??de.dynamicInput){let $t=Eo(de,j.policy);if($t)return $t}if(bi(wt)){let $t=Eo(de,j.policy);if($t)return $t}return j.analyzeNested(wt,{effectiveCwd:kt,envAssignments:Et})}let Mt=or(yt);if(Mt.kind==="dynamic")return Eo(de,j.policy);if(Mt.kind==="literal")return de.dynamicSourceInput?Eo(de,j.policy):null;return de.dynamicSourceInput??de.dynamicInput?Eo(de,j.policy):null}if(we){let wt=$n(bt),Mt=wt?j.analyzeNested(wt,{effectiveCwd:kt,envAssignments:Et}):or(yt).kind==="dynamic"?bn(K):null;if(Mt)return Mt}if(de===void 0){let wt=Vw(bt,Et,kt,j,K,U);if(wt)return wt;let Mt=$n(bt);if(Mt){let Kr=$s(yt,Mt);if(Kr.kind==="dynamic")return bn(K);let la=Kr.kind==="literal"?Kr.source:lp(yt,Mt),Zc=Kw(la);K?.recordSegment({type:"shell-wrapper",wrapper:Rt,innerCommand:Zc}),K?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:Zc,depth:U+1});let Xc=j.analyzeNested(la,{effectiveCwd:kt,envAssignments:Et});if(Xc)return Xc;return bi(la)?bn(K):null}let $t=or(yt,j.strict?void 0:j.shellAssignments);if($t.kind==="dynamic")return bn(K);if($t.kind==="literal")return Ys($t.source,kt,Et,j,K,U);let tn=cp(yt,j.commandView?.redirections??[],j.hasPipelineInput??!1,j.literalShellInput);if(tn.kind==="dynamic")return bn(K);if(tn.kind==="literal")return K?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:tn.source,depth:U+1}),j.analyzeNested(tn.source,{effectiveCwd:kt,envAssignments:Et})}}if(!de&&(Rt==="source"||Rt===".")){let wt=bt[1]==="-p"?2:null;if(wt!==null){let Kr=j.commandView?yt[wt]:void 0;if(!Kr)return null;if(Kr.provenance!=="literal")return bn(K)}let Mt=wt===null?1:3,$t=bt[Mt]==="--"?Mt+1:Mt,tn=j.commandView?yt[$t]:void 0;if(!tn)return null;if(tn.provenance==="literal")return Ys(tn.text,kt,Et,j,K,U);if(j.strict||!j.commandView||!uc(j.commandView))return bn(K)}if(In.has(Rt)&&!we){if(!de&&j.strict&&Cc(fi(bt),yt))return bn(K);let wt=Ef(bt,($t)=>yr(j.analyzeNested($t,{effectiveCwd:kt,envAssignments:Et}))),Mt=At(wt,j.policy);if(Mt)return K?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:Mt.reason}),un(Mt)}if(Ln(Rt)&&!we){if(!de&&j.strict&&Cc(cs(bt),yt))return bn(K);let wt=ym(bt);if(Se&&de)return Hw(Rt,wt,kt,Et,j,de);if(wt){let Mt=Jt(j.policy,"interpreter.one-liner-paranoid",!!j.paranoidInterpreters);if(K?.recordSegment({type:"interpreter",interpreter:Rt,codeArg:wt,paranoidBlocked:Mt}),Mt){let tn=At(xt("interpreter.one-liner-paranoid",ti),j.policy);if(tn)return un(tn)}if(wl(Rt,wt))return null;K?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:wt,depth:U+1});let $t=j.analyzeNested(wt,{effectiveCwd:kt,envAssignments:Et});if($t&&!eg($t,wt))return $t;if(ni(wt,void 0,!j.strict)){let tn=At(xt("interpreter.dangerous-command",ao),j.policy);if(tn)return K?.recordSegment({type:"dangerous-text",token:wt,matched:!0,reason:ao}),un(tn)}K=void 0}}if(Rt==="busybox"&&bt.length>1)return Xp(St.wrapperNormalizationBudget),K?.recordSegment({type:"busybox",subcommand:bt[1]??"unknown"}),K?.recordSegment({type:"recurse",reason:"busybox",innerCommand:bt.slice(1).join(" "),depth:U+1}),Ro(yt.slice(1),U,{...St,effectiveCwd:kt,envAssignments:Et});let Ut=de?null:At(fm(Rt,bt),j.policy);if(Ut)return K?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:Ut.reason}),un(Ut);let Gt=K===St.trace?St:{...St,trace:K},ln={words:yt,parsedWords:pt.words,head:Rt,cwd:Pt,originalCwd:Tt,envAssignments:Et,allowTmpdirVar:vt,dynamicArguments:pt.words.some((wt)=>wt.provenance==="command-substitution"),depth:U,effectiveCwd:kt,options:Gt,analyzeChildTokens:(wt,Mt)=>Se&&de?wc(wt,U,Gt,{...de,cwd:Mt??void 0,effectiveCwd:Mt??void 0}):yr(Ro(Kt(wt),U+1,{...Gt,child:void 0,commandView:void 0,effectiveCwd:Mt,envAssignments:Et}))??A(wt,Gt.policy.rules),analyzeChild:(wt,Mt)=>wc(wt,U,Gt,Mt)},Zt=de&&(Rt==="xargs"||Rt==="parallel")?void 0:Qp(Rt);if(Rt==="rm"||Rt==="xargs"||Rt==="parallel")K?.recordSegment({type:"tmpdir-check",tmpdirValue:Et.has("TMPDIR")||j.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:vt});let Xt=K&&Rt==="git"?Qf(ln.words,xc(ln)):void 0,Cn=Jp(Xt?Xt.match:Zt?.(ln)??null,j.policy);if(K)qw(ln,Cn,Xt?.relaxation??null);if(Cn)return un(Cn);if(Se&&de&&(Rt==="rm"||Rt==="rmdir")){if(!(Rt==="rm"&&(tr(bt)||de.dynamicRmInput)))return null;return(de.dynamicRmInput?xo(de,j.policy):null)??jw(de,j.policy)}let Yn=Zt!==void 0&&!Zw.has(Rt),vr=!de&&!Yn&&!Fi.has(Rt),To=K&&vr?[]:void 0;if(vr)for(let wt=1;wt<bt.length;wt++){let Mt=bt[wt];if(!Mt)continue;To?.push(Mt);let $t=Jp(Uw(bt,wt,U,Gt,Pt,Tt,kt,Et),j.policy);if($t)return K?.recordSegment({type:"fallback-scan",tokensScanned:To??[],embeddedCommandFound:Dt(Mt)}),un($t)}if(K?.recordSegment({type:"fallback-scan",tokensScanned:To??[]}),we&&de&&!de.wrappedByTransparent)return null;let An=A(bt,j.policy.rules);if(K?.recordSegment({type:"custom-rules-check",rulesChecked:j.policy.rules.length>0,matched:!!An,reason:An?.reason}),An)return un(An);return Se&&de?xo(de,j.policy):null}function wc(G,U,j,K){return yr(Ro(Kt(G),U+1,{...j,trace:void 0,commandView:void 0,hasPipelineInput:void 0,literalShellInput:void 0,functionDefinitions:void 0,cwd:K.originalCwd,effectiveCwd:K.effectiveCwd,envAssignments:K.envAssignments,worktreeMode:K.dynamicInput?!1:K.worktreeMode,wrapperNormalizationBudget:{iterations:0},child:K}))}function Uw(G,U,j,K,re,oe,de,Se){for(let we of zn(G.slice(U),{environment:K.environment,cwd:re,envAssignments:Se,policy:K.policy})){let We=we.tokens[0];if(!We)continue;let mt=Dt(We);if(tg(We,mt)||Qp(mt)!==void 0&&mt!=="xargs"&&mt!=="parallel"||we.wrappedByTransparent&&K.policy.rules.length>0)K.budget.charge("derivedTokens",G.length-U);let ft=wc(we.tokens,j,K,{embedded:!0,cwd:we.cwd,originalCwd:we.wrapperCwd===null?void 0:oe,effectiveCwd:we.wrapperCwd===void 0?de:we.wrapperCwd,envAssignments:we.envAssignments,allowTmpdirVar:!li(we.envAssignments,K.environment),worktreeMode:!1,wrappedByTransparent:we.wrappedByTransparent});if(ft)return ft}return null}function Hw(G,U,j,K,re,oe){if(!U)return xo(oe,re.policy);if(Jt(re.policy,"interpreter.one-liner-paranoid",!!re.paranoidInterpreters)){let Se=At(xt("interpreter.one-liner-paranoid",ti),re.policy);if(Se)return un(Se)}if(wl(G,U))return xo(oe,re.policy);let de=re.analyzeNested(U,{effectiveCwd:j,envAssignments:K});if(de&&!eg(de,U))return de;if(ni(U,void 0,!re.strict)){let Se=At(xt("interpreter.dangerous-command",ao),re.policy);if(Se)return un(Se)}return xo(oe,re.policy)}function eg(G,U){let j=G.ruleId==="raw-text.dangerous-command",K=(G.reason.startsWith(Ps)||G.reason===go)&&!Gi(U);return j||K}function Eo(G,U){let j=G.shellDynamicMatch?At(G.shellDynamicMatch,U):null;return j?un(j):null}function xo(G,U){let j=G.dynamicSourceInput&&G.dynamicSourceMatch?At(G.dynamicSourceMatch,U):null;return j?un(j):null}function jw(G,U){let j=G.dynamicInput&&G.rmDynamicMatch?At(G.rmDynamicMatch,U):null;return j?un(j):null}function Vw(G,U,j,K,re,oe){let de=Pf(G);if(de.argvSource?.kind==="absent")return bn(re);if(de.argvSourceApplies&&de.argvSource){let we=Ys(de.argvSource.value,j,U,K,re,oe,!0);if(we)return we}if(!de.envSourceApplies||!de.envName)return null;let Se=U.get(de.envName);if(!Se)return null;return Ys(Se,j,U,K,re,oe,!0)}function Ys(G,U,j,K,re,oe,de=!1){if(de&&/[$`*?[\]]/.test(G))return bn(re);let Se=ei(G,U,K.environment.paths,K.budget),we=Se?K.literalHeredocFiles?.get(Se):void 0;if(we===void 0)return de?bn(re):null;return K.budget.charge("derivedTokens",1),re?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:we,depth:oe+1}),K.analyzeNested(we,{effectiveCwd:U,envAssignments:j})}function Kw(G){let U=G[0];return G.length>=2&&(U==='"'||U==="'")&&G.at(-1)===U?G.slice(1,-1):G}function qw(G,U,j){let K={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",cmd:"analyzer/cmd.ts:analyzeCmdMatch",powershell:"analyzer/powershell-wrapper.ts:analyzePowerShellWrapperMatch",pwsh:"analyzer/powershell-wrapper.ts:analyzePowerShellWrapperMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[G.head];if(!K)return;if(G.options.trace?.recordSegment({type:"rule-check",rule:K,matched:!!U||!!j,reason:U?.reason??j?.originalReason}),j)G.options.trace?.recordSegment({type:j.kind==="worktree"?"worktree-relaxation":"temp-root-relaxation",originalReason:j.originalReason,gitCwd:j.gitCwd})}function Xp(G){if(G.iterations>=a.wrapperPeelIterations.cap)throw new s("wrapperPeelIterations");G.iterations++}function un(G){return{reason:G.reason,ruleId:G.id,intent:G.intent}}function bn(G){return G?.recordSegment({type:"error",message:ui}),un(ho())}function tg(G,U){return qt.has(U)||G==="$SHELL"||G==="${SHELL}"||qt.has(Ot(U))}function Jp(G,U){return G?.id.startsWith("custom.")||G?.id==="raw-text.dangerous-command"?G:At(G,U)}var Yw=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,Zw=new Set(["powershell","pwsh"]),Xw=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function Jw(G,U){let j=og(G,U);if(j.length===0)return!1;let K=j[rg(j)];if(K==="cd"||K==="pushd"||K==="popd")return!0;return Yw.test(G.join(" "))}function ng(G,U,j,K,re){if(G.dialect==="powershell"){let Ct=Qw(G.words,re);if(Ct.kind==="none")return;if(!U||Ct.kind==="unknown")return null;return _c(rA(Ct.target),U,j.paths)}let oe=G.words.map(t),de=oe.some((Ct)=>/^CDPATH\+?=/.test(Ct));if(!Jw(oe,j))return de?null:void 0;if(!U)return null;let Se=og(oe,j,U),we=rg(Se);if(we===-1||Se[we]!=="cd")return null;let We=Se.slice(we+1),mt=We.findIndex((Ct)=>Ct.length<=1||!Ct.startsWith("-")||Ct==="--");if((mt===-1?We:We.slice(0,mt)).some((Ct)=>!/^-[LP]+$/.test(Ct)))return null;let ft=mt===-1?[]:We.slice(mt),pt=ft[0]==="--"?ft.slice(1):ft;if(pt.length>1)return null;let ht=pt[0],yt=K.get("HOME")||j.home;if(ht===void 0)return _c(cn(yt),U,j.paths);let bt=G.words.find((Ct)=>Ct.provenance==="variable"&&Ct.text===ht),St=G.words.find((Ct)=>Ct.text===ht&&/^~(?:\/|$)/.test(Ct.raw)),Et=bt?Kn(bt,new Map([...K,["HOME",yt]])):St?`${yt}${ht.slice(1)}`:ht;if(Et===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(Et)&&(de||j.env.has("CDPATH")))return null;return _c(cn(Et),U,j.paths)}function _c(G,U,j){if(!G||G==="-"||G.startsWith("~")||G.includes("$")||G.includes("`"))return null;try{let K=dr(U,G,j);return j.isDirectory(K)?K:null}catch{return null}}function Qw(G,U){let j=eA(G[0])?1:0,K=G[j];if(!tA(K,j===1))return{kind:"none"};let re=K.text.toLowerCase(),oe=re.split(/[\\/]/).pop()??re;if(!Xw.has(oe))return{kind:"none"};if(re!==oe||oe==="pop-location"||oe==="popd")return{kind:"unknown"};return nA(G.slice(j+1),U)}function eA(G){return G?.provenance==="literal"&&!G.quoted&&G.raw===G.text&&(G.text==="&"||G.text===".")}function tA(G,U){return G?.provenance==="literal"&&(U||!G.quoted&&G.raw===G.text)}function nA(G,U){let j;for(let K of G){if(K.provenance!=="literal"||j!==void 0)return{kind:"unknown"};j=K.text}if(j!==void 0)return{kind:"target",target:j};return U===void 0?{kind:"unknown"}:{kind:"target",target:U}}function rA(G){return G.includes("::")?void 0:G.replaceAll("\\","/")}function rg(G){let U=0;if(G[0]==="builtin"&&G.length>1)U=1;if(G[U]!=="time")return U;let j=U+1;while(G[j]?.startsWith("-"))j++;return j}function og(G,U,j){let K=oA(G);return ur([...K],U,j)}function oA(G){let U=0;while(U<G.length){let j=G[U];if(j!=="{"&&j!=="("&&j!=="$(")break;U++}return G.slice(U)}var uA="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Br="This heredoc form or stdin consumer is not supported safely. Use a quoted heredoc with a supported consumer (cat, tee, git apply, git commit, gh pr create, gh issue create), or ask the user to verify.";function Oc(G,U,j,K){if(U>=a.recursionDepth.cap)return j.trace?.recordSegment({type:"error",message:Un}),{reason:Un,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};let re=K??j.factStore?.getCommandProgram(G,j.shell??"auto")??y(G,j.shell);if(re.status==="limited")return j.trace?.recordSegment({type:"error",message:Un}),{reason:Un,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};if(re.status==="invalid"){let We=re.issues.find((mt)=>mt.code.includes("heredoc"));if(We){if(!j.strict)return kc(G,j);let mt=`${Ps}: ${We.message}`;return j.trace?.recordGlobal({type:"error",message:mt}),{reason:mt,segment:G,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"}}return ug(G,j),{reason:go,segment:G,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"}}if(j.strict&&re.status==="partial")return ug(G,j),{reason:go,segment:G,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"};if(re.issues.some((We)=>We.code.includes("quote")))return kc(G,j);let de=j.cwd,Se=j.effectiveCwd!==void 0?j.effectiveCwd:j.cwd,we=$f(j.environment.env,j.envAssignments);return Js(re,U,{...j,rootProgram:re},de,[{effectiveCwd:Se,shellGitContextState:we,literalHeredocFiles:new Map(j.literalHeredocFiles),functionDefinitions:new Map(j.functionDefinitions),createdDirectories:new Set,compoundBodies:[]}]).result}function Js(G,U,j,K,re){let oe=[...re],de,Se,we;for(let[We,mt]of G.nodes.entries()){if(mt.kind==="connector"){Se=mt.operator;continue}let gt=G.nodes[We+1],ft=gt?.kind==="connector"?gt.operator:void 0,pt=mA(G,We,mt,Se,ft),yt=Se==="&&"||Se==="||"?de:void 0,bt=Se==="&&"?yt?.success??oe:Se==="||"?yt?.failure??oe:oe,St=Se==="||"?yt?.success??[]:[],Et=Se==="&&"?yt?.failure??[]:[],Ct={connector:Se,skippedSuccessStates:St,skippedFailureStates:Et};if(br(ft)&&!br(Se))we=Ct;let Rt=br(ft)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:br(Se)?we??Ct:Ct,Pt=Ur(Rt.connector)||Ur(ft);if(mt.kind==="function"){let Ut=bt.flatMap((ln)=>{let Zt=Hr(ln);return Zt.functionDefinitions.set(mt.name,mt.body),Ac(ln,[Zt],pt,ft==="&",Ur(ft))}),Gt=Pc(Ut,[],Rt.skippedSuccessStates,Rt.skippedFailureStates,Rt.connector,ft);oe=Gt.states,de=Gt.conditionalStates,Se=void 0;continue}if(mt.kind==="group"){let Ut=[],Gt=[];for(let Zt of bt){let Xt=Js(mt.body,U,j,K,[Hr(Zt)]);if(Xt.result)return Xt;if(Ut.push(...Ac(Zt,Xt.states,pt,ft==="&",Ur(ft))),Pt)Gt.push(Zt,...pt?Xt.states.map((Cn)=>Zs(Zt,Cn)):Xt.states)}let ln=Pc(Ut,Gt,Rt.skippedSuccessStates,Rt.skippedFailureStates,Rt.connector,ft);oe=ln.states,de=ln.conditionalStates,Se=void 0;continue}if(mt.kind!=="command")continue;let Tt=NA(G.nodes[We-1]),kt=j.trace?.flattenNested?j.trace.currentSegmentIndex:j.trace?.allocateSegment(),vt=G.nodes[We-2],It=br(Se)&&vt?.kind==="command"?sp(vt)??pA(vt):void 0,Lt=[],en=[];for(let Ut of bt){let Gt=gA(mt,U,j,K,[Hr(Ut)]);if(Gt.result)return{result:Gt.result,states:oe};let ln=G.dialect==="powershell"?Gt.states:Gt.states.map((Zt)=>Zs(Ut,Zt));for(let Zt of ln){let Xt=Hr(Zt),Cn=bA(mt,U,j.trace?{...j,trace:mg(j.trace,kt)}:j,K,Xt,br(Se),It);if(Cn)return{result:Cn,states:oe};let Yn=BA(mt,Xt.functionDefinitions);if(Yn)j.budget.charge("derivedTokens",Qs(Yn));let vr=Yn?U+1>=a.recursionDepth.cap?Tc(mt.displayText,j,[Xt]):Js(Yn,U+1,j,K,[Xt]):{result:null,states:zA(mt,Xt).flatMap((An)=>LA(mt,Zt,An,Tt))};if(vr.result)return vr;Lt.push(...Ac(Ut,vr.states,pt,ft==="&",Ur(ft)));let To=typeof Xt.effectiveCwd==="string"&&Xt.effectiveCwd!==Zt.effectiveCwd&&mt.redirections.every((An)=>["<",">",">>",">|"].includes(An.operator)&&An.target?.text==="/dev/null");if(Pt&&(Tt||!To))en.push(Ut),en.push(...vr.states.map((An)=>pt?Zs(Ut,An):An))}}let Cr=Pc(Lt,en,Rt.skippedSuccessStates,Rt.skippedFailureStates,Rt.connector,ft);oe=Cr.states,de=Cr.conditionalStates,Se=void 0}return{result:null,states:oe}}function mA(G,U,j,K,re){if(j.kind==="group"&&j.style==="subshell")return!0;if(G.dialect==="posix"&&(br(K)||br(re)))return!0;if(re==="&")return!0;return G.dialect==="powershell"&&j.kind==="group"&&j.style==="brace"&&fA(G,U)}function Ac(G,U,j,K,re){let oe=j?U.map((Se)=>Zs(G,Se)):[...U],de=re?oe.flatMap((Se)=>_o(G.literalHeredocFiles,Se.literalHeredocFiles)?[Se]:[{...Se,literalHeredocFiles:new Map(G.literalHeredocFiles)},Se]):oe;return K?[G,...de]:de}function Zs(G,U){return{...G,literalHeredocFiles:new Map(U.literalHeredocFiles),createdDirectories:new Set(U.createdDirectories)}}function fA(G,U){let j=G.nodes.slice(0,U).reverse().find((re)=>re.kind==="command"||re.kind==="connector");if(!j||j.kind!=="command")return!0;let K=j.words[0]?.text.toLowerCase();if(K==="&"||K===".")return!1;if(K==="write-output"||K==="function"||K==="start-job")return!0;if(hA(j))return!0;return j.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function br(G){return G==="|"||G==="|&"}function pA(G){if(G?.dialect!=="powershell")return;if(G.words.length===1&&G.words[0]?.quoted&&G.words[0].provenance==="literal")return G.words[0].text;if(G.words[0]?.text.toLowerCase()==="write-output"&&G.words.length===2&&G.words[1]?.provenance==="literal")return G.words[1].text;return}function Ur(G){return G==="&&"||G==="||"}function Pc(G,U,j,K,re,oe){let de={success:Xs([...j,...G]),failure:Xs([...K,...U])},Se=Ur(oe)?de:void 0;return{states:Ur(re)||Se?Xs([...de.success,...de.failure]):de.success,conditionalStates:Se}}function mg(G,U,j=G.flattenNested){return{currentSegmentIndex:U,flattenNested:j,allocateSegment:G.allocateSegment,getNextSegmentIndex:G.getNextSegmentIndex,recordGlobal:G.recordGlobal,recordSegment:(K,re=U)=>G.recordSegment(K,re)}}function gA(G,U,j,K,re){let oe=G.nested.map((de)=>({program:de,depth:U}));if(G.dialect==="powershell"){let de=yA(G);if(de){if(U+1>=a.recursionDepth.cap)return Tc(de,j,re);let Se=y(de,"powershell");if(Se.status==="limited")return Tc(de,j,re);if(Se.status!=="complete")return ig(oe,j,K,re);j.budget.charge("derivedTokens",Qs(Se)),oe.push({program:Se,depth:U+1})}}return ig(oe,j,K,re)}function hA(G){let U=G.words[0];return U?.provenance==="variable"&&G.words.at(-1)?.text==="="?U.text.toLowerCase():void 0}function ig(G,U,j,K){let re=[...K];for(let oe of G){let de=[];for(let Se of re){let we=Js(oe.program,oe.depth,U,j,[Hr(Se)]);if(we.result)return we;de.push(...we.states)}re=Xs(de)}return{result:null,states:re}}function yA(G){let U=G.words[0]?.provenance==="literal"&&!G.words[0].quoted&&G.words[0].raw===G.words[0].text&&(G.words[0].text==="&"||G.words[0].text==="."),j=U?1:0,K=G.words[j];if(K?.provenance!=="literal"||!U&&(K.quoted||K.raw!==K.text)||!["iex","invoke-expression"].includes(K.text.toLowerCase()))return;let re=G.words.slice(j+1),oe=re[0]&&!re[0].quoted&&re[0].raw===re[0].text&&["-c","-command"].includes(re[0].text.toLowerCase())?1:0,de=re[oe];return re.length===oe+1&&de?.quoted&&de.provenance==="literal"?de.text:void 0}function Qs(G){return G.nodes.reduce((U,j)=>U+(j.kind==="command"?j.words.length+j.nested.reduce((K,re)=>K+Qs(re),0):j.kind==="group"||j.kind==="function"?Qs(j.body):0),0)}function Tc(G,U,j){return U.trace?.recordSegment({type:"error",message:Un}),{result:{reason:Un,segment:G,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"},states:[...j]}}function bA(G,U,j,K,re,oe,de){let Se={...j,environment:{...j.environment,env:re.shellGitContextState.env,paths:RA(j.environment.paths,re.createdDirectories,j.budget)}},we=TA(G,!Se.strict);if(we&&Se.strict)return Se.trace?.recordSegment({type:"error",message:we}),{reason:we,segment:G.source,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"};fg(G,re,"before-consumer",Se.environment.paths,Se.budget);let We=ne(G.dialect,G.words),mt=We.map(t),gt=G.displayText,ft=Gf(We,re.shellGitContextState),pt=Uf(ft,re.shellGitContextState);if(G.dialect==="powershell"){let St=At(pf(G,oe,UA(Se,re.effectiveCwd)),Se.policy);if(Se.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!St,reason:St?.reason}),St)return dg(gt,St)}let ht=At(pm(G.redirections),Se.policy);if(ht)return Se.trace?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceRedirectionMatch",matched:!0,reason:ht.reason}),dg(gt,ht);if(mt.length===1&&mt[0]?.includes(" ")&&!jo(G.dialect,G.words)){let St=At(kn(mt[0]),Se.policy),Et=St!==null&&!Se.strict&&cm(G,Se.rootProgram);if(St&&!Et)return Se.trace?.recordSegment({type:"dangerous-text",token:mt[0],matched:!0,reason:St.reason}),{reason:St.reason,segment:gt,ruleId:St.id,intent:St.intent};Se.trace?.recordSegment({type:"dangerous-text",token:mt[0],matched:!1});let Ct=sg(G,we,re,pt,de,Se);if(Ct)return Ct;return ic(ft,re.shellGitContextState),null}let yt=Ro(G.words,U,{...Se,commandView:G,cwd:K,effectiveCwd:re.effectiveCwd,envAssignments:pt,shellAssignments:re.shellGitContextState.shellAssignments,literalHeredocFiles:re.literalHeredocFiles,functionDefinitions:re.functionDefinitions,hasPipelineInput:oe,literalShellInput:de,analyzeNested:(St,Et)=>{let Ct=Et&&Object.hasOwn(Et,"effectiveCwd")?Et.effectiveCwd:re.effectiveCwd,Rt=Oc(St,U+1,{...Se,effectiveCwd:Ct,envAssignments:Et?.envAssignments??pt,literalHeredocFiles:re.literalHeredocFiles,functionDefinitions:Et?.functionDefinitions,worktreeMode:Et?.worktreeMode??Se.worktreeMode,shell:Et?.shell??Se.shell,trace:Se.trace?mg(Se.trace,Se.trace.currentSegmentIndex,!0):void 0});return Rt?{reason:Rt.reason,ruleId:Rt.ruleId,intent:Rt.intent}:null}});if(yt)return{...yt,segment:gt};let bt=sg(G,we,re,pt,de,Se);if(bt)return bt;return ic(ft,re.shellGitContextState),null}function sg(G,U,j,K,re,oe){let de=IA(G,U,j,K??new Map,oe);if(de)return de;return fg(G,j,"after-consumer",oe.environment.paths,oe.budget),j.literalHeredocFiles.clear(),vA(G,U,j,oe.environment.paths,oe.budget),xA(G,j,oe.environment.paths,oe.budget),MA(G,j,re,oe.environment,oe.trace),null}var SA=new Set([">>","<>"]);function fg(G,U,j,K,re){for(let de of G.redirections){if(!(j==="before-consumer"?CA(de):SA.has(de.operator)))continue;ag(de.target,U,K,re)}if(j!=="before-consumer"||!an(G.words[0],"tee"))return;let oe=gg(G.words.slice(1));if(!oe)return;for(let de of oe.operands)ag(de,U,K,re)}function CA(G){if(G.operator===">"||G.operator===">|")return!0;return G.operator===">&"&&G.fd===void 0&&G.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(G.target.text)}function ag(G,U,j,K){let re=G?.provenance==="literal"?ei(G.text,U.effectiveCwd,j,K):void 0;if(!re)return;U.literalHeredocFiles.delete(re)}function vA(G,U,j,K,re){if(U)return;let oe=G.redirections.find((de)=>de.operator==="<<"||de.operator==="<<-")?.heredoc;if(!oe)return;for(let de of EA(G,j.shellGitContextState.shellAssignments)){let Se=ei(de,j.effectiveCwd,K,re);if(!Se||!hm(Se))continue;if(!j.literalHeredocFiles.has(Se)&&j.literalHeredocFiles.size>=a.trackedHeredocFiles.cap)throw new s("trackedHeredocFiles");j.literalHeredocFiles.set(Se,oe.body)}}function EA(G,U){let j=Ic(AA(G.redirections)?.target,U),K=j===void 0?[]:[j];if(an(G.words[0],"cat"))return wA(G.words)?K:[];if(!an(G.words[0],"tee"))return[];let re=gg(G.words.slice(1),U);if(!re||re.append||re.hasUnsupportedOptions)return[];let oe=re.operands.map((de)=>Ic(de,U));if(!oe.every((de)=>de!==void 0))return[];return[...oe,...K]}function Ic(G,U){if(PA(G))return G.text;return(G&&Kn(G,U))??void 0}function RA(G,U,j){if(U.size===0)return G;let K=(re)=>{let oe=Wt(re,G,j);return[...U].some((de)=>de===oe||de.startsWith(`${oe}${dA}`))};return{realpath:(re)=>G.realpath(re)??(K(re)?Wt(re,G,j):null),entryKind:(re)=>{let oe=G.entryKind(re);return oe==="missing"&&K(re)?"present":oe},isDirectory:(re)=>G.isDirectory(re)||K(re)}}function xA(G,U,j,K){if(U.shellGitContextState.bodyDepth>0||!an(G.words[0],"mkdir"))return;let re=G.words.slice(1).map((We)=>Ic(We,U.shellGitContextState.shellAssignments));if(!re.every((We)=>We!==void 0))return;let oe=re.findIndex((We)=>We==="--"||We==="-"||!We.startsWith("-")),de=re.slice(0,oe);if(oe===-1||!de.every((We)=>/^(?:-[pv]+|--parents|--verbose)$/.test(We)))return;let Se=de.some((We)=>We==="--parents"||/^-v*p/.test(We)),we=U.effectiveCwd;for(let We of re.slice(re[oe]==="--"?oe+1:oe)){if(We.split(/[\\/]/).includes("..")||!sA(We)&&!we)continue;let mt=Wt(cA(we??"",We),j,K);if(Se?_A(mt,j):j.isDirectory(iA(mt))&&pg(mt,j))U.createdDirectories.add(mt)}}function _A(G,U){let j=lA(G).root,K=G.slice(j.length).split(/[\\/]+/).filter(Boolean),re=(de)=>aA(j,...K.slice(0,de+1)),oe=K.findIndex((de,Se)=>!U.isDirectory(re(Se)));return oe===-1||pg(re(oe),U)}function pg(G,U){try{return U.entryKind(G)==="missing"}catch{return!1}}function wA(G){let U=!1;for(let j of G.slice(1)){if(U||j.provenance!=="literal")return!1;if(j.text==="--"){U=!0;continue}if(!/^-u+$/.test(j.text))return!1}return!0}function AA(G){let U=G.findLast((j)=>(j.fd??([">",">|",">>",">&"].includes(j.operator)?1:0))===1);return U?.operator===">"||U?.operator===">|"?U:void 0}function gg(G,U=new Map){let j=[],K=!0,re=!1,oe=!1;for(let de of G){if(de.provenance!=="literal"&&Kn(de,U)===null)return;if(K&&an(de,"--")){K=!1;continue}if(K&&!de.quoted&&de.raw===de.text&&/^-[^-]/.test(de.text)){re||=de.text.slice(1).includes("a"),oe||=Array.from(de.text.slice(1)).some((Se)=>Se!=="a"&&Se!=="i");continue}if(K&&!de.quoted&&de.raw===de.text&&de.text.startsWith("--")){re||=de.text==="--append",oe||=de.text!=="--append"&&de.text!=="--ignore-interrupts";continue}j.push(de)}return{operands:j,append:re,hasUnsupportedOptions:oe}}function PA(G){if(!G||G.provenance!=="literal"||G.text.length===0)return!1;if(G.quoted||G.raw!==G.text)return!0;return!G.raw.startsWith("~")&&!/[{}]/.test(G.raw)}function an(G,U){return G?.text===U&&G.raw===U&&G.provenance==="literal"&&!G.quoted}function Mc(G){return G.quotedDelimiter||!/[$`\\]/.test(G.body)}function TA(G,U){let j=G.redirections.filter((we)=>we.operator==="<<"||we.operator==="<<-");if(j.length===0)return;if(j.length!==1)return Br;let K=j[0];if(!K?.heredoc)return Br;let re=/\$\(|`/.test(K.heredoc.body);if(!Mc(K.heredoc)&&(!U||re))return uA;if(K.fd!==void 0&&K.fd!==0)return Br;if(G.redirections.some((we)=>we!==K&&["<","<<","<<-","<<<","<&","<>"].includes(we.operator)))return Br;let oe=G.redirections.some((we)=>we!==K&&lg(we.target));if(an(G.words[0],"cat"))return oe?Br:void 0;if(an(G.words[0],"tee"))return oe||G.words.slice(1).some(lg)?Br:void 0;let de=G.words[0],Se=G.words[1];if(an(de,"git")&&(an(Se,"apply")||an(Se,"commit")))return;if(an(de,"gh")&&(an(Se,"pr")||an(Se,"issue"))&&an(G.words[2],"create"))return;return Br}function lg(G){return G?.parts.some((U)=>U.provenance==="command-substitution"&&U.raw.startsWith(">("))??!1}function IA(G,U,j,K,re){if(!U)return null;let oe=G.redirections.filter((We)=>We.operator==="<<"||We.operator==="<<-"),de=oe.flatMap((We)=>We.heredoc?[We.heredoc.body]:[]);if(OA(G,oe,j,K,re))return null;let Se=kA(G,oe,re);if(Se!==void 0)return Se?{reason:Se.reason,segment:G.displayText,ruleId:Se.id,intent:Se.intent}:null;let we=kc(de.length===oe.length?de.join(`
|
|
43
|
+
`):G.source,re);return we?{...we,segment:G.displayText}:null}function kA(G,U,j){let K=U.length===1?U[0]:void 0;if(!K?.heredoc||!Mc(K.heredoc)||K.fd!==void 0&&K.fd!==0)return;let re=an(G.words[0],"uv")&&an(G.words[1],"run")?G.words.slice(2):G.words,oe=re[0];if(oe?.provenance!=="literal"||!Ln(oe.text))return;let de=re.findIndex((gt)=>an(gt,"-"));if(!re.slice(1,de===-1?void 0:de).every((gt)=>gt.provenance==="literal"&>.text.startsWith("-")))return;let we=K.heredoc.body,We=Jt(j.policy,"interpreter.one-liner-paranoid",!!j.paranoidInterpreters);if(j.trace?.recordSegment({type:"interpreter",interpreter:oe.text,codeArg:we,paranoidBlocked:We}),We){let gt=At(xt("interpreter.one-liner-paranoid",ti),j.policy);if(gt)return gt}if(!ni(we,void 0,!j.strict))return null;let mt=At(xt("interpreter.dangerous-command",ao),j.policy);if(!mt)return null;return j.trace?.recordSegment({type:"dangerous-text",token:we,matched:!0,reason:mt.reason}),mt}function OA(G,U,j,K,re){let oe=U.length===1?U[0]:void 0;if(!oe?.heredoc||!Mc(oe.heredoc)||oe.fd!==void 0&&oe.fd!==0)return!1;let de=kr(G.words,re.environment,j.effectiveCwd,K),Se=de.words.map(t),we=Dt(Se[0]??"");if((de.envSplitValues?.length??0)>0||!qt.has(we)&&!qt.has(Ot(we)))return!1;return nr(Se)}function MA(G,U,j,K,re){let oe=ng(G,U.effectiveCwd,K,U.shellGitContextState.shellAssignments,j);if(oe===null)re?.recordSegment({type:"cwd-change",segment:G.words.map(t).join(" "),effectiveCwdNowUnknown:!0});if(oe!==void 0)U.effectiveCwd=oe}var DA=new Set(["fi","done","esac"]);function NA(G){return G?.kind==="command"&&G.words.length===1&&G.words[0]?.raw==="!"}function LA(G,U,j,K){let re=G.words[0]?.text??"",oe=U.shellGitContextState.bodyDepth,de=j.shellGitContextState.bodyDepth,Se=j.compoundBodies;if(de>oe)return j.compoundBodies=[...Se.slice(0,oe),{entryCwd:U.effectiveCwd,branchCwds:Se[oe]?.branchCwds??[],hasElse:!1}],[j];let we=oe>0?Se[oe-1]:void 0;if(we&&(re==="else"||re==="elif"))return j.compoundBodies=[...Se.slice(0,oe-1),{entryCwd:we.entryCwd,branchCwds:[...we.branchCwds,j.effectiveCwd],hasElse:re==="else"}],j.effectiveCwd=we.entryCwd,[j];let We=we!==void 0&&DA.has(re);if(We)j.compoundBodies=Se.slice(0,de);return[...new Set([j.effectiveCwd,...We?we.branchCwds:[],...We&&!we.hasElse?[we.entryCwd]:[],...K?[U.effectiveCwd]:[]])].map((gt)=>{if(gt===j.effectiveCwd)return j;let ft=Hr(j);return ft.effectiveCwd=gt,ft})}function WA(G,U){return G.length===U.length&&G.every((j,K)=>{let re=U[K];return re!==void 0&&j.entryCwd===re.entryCwd&&j.hasElse===re.hasElse&&j.branchCwds.length===re.branchCwds.length&&j.branchCwds.every((oe,de)=>oe===re.branchCwds[de])})}var FA=/^[A-Za-z_][A-Za-z0-9_]*$/,GA=8;function zA(G,U){let j=G.words[1]?.text;if(G.dialect!=="posix"||G.words[0]?.text!=="for"||j===void 0||!FA.test(j))return[U];let K=G.words.slice(3);if(!(G.words[2]?.text==="in"&&K.length>=1&&K.length<=GA&&K.every((oe)=>oe.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(oe.text))))return U.shellGitContextState.shellAssignments.delete(j),[U];return K.map((oe)=>{let de=Hr(U);return de.shellGitContextState.shellAssignments.set(j,oe.text),de})}function Hr(G){return{effectiveCwd:G.effectiveCwd,shellGitContextState:Bf(G.shellGitContextState),literalHeredocFiles:new Map(G.literalHeredocFiles),functionDefinitions:new Map(G.functionDefinitions),createdDirectories:new Set(G.createdDirectories),compoundBodies:G.compoundBodies}}function Xs(G){let U=[];for(let j of G){if(!U.some((K)=>$A(K,j)))U.push(j);if(U.length>a.controlFlowStates.cap)throw new s("controlFlowStates")}return U}function $A(G,U){return G.effectiveCwd===U.effectiveCwd&&WA(G.compoundBodies,U.compoundBodies)&&_o(G.shellGitContextState.env,U.shellGitContextState.env)&&_o(G.literalHeredocFiles,U.literalHeredocFiles)&&_o(G.functionDefinitions,U.functionDefinitions)&&_o(G.shellGitContextState.effectiveEnvAssignments,U.shellGitContextState.effectiveEnvAssignments)&&_o(G.shellGitContextState.shellAssignments,U.shellGitContextState.shellAssignments)&&G.shellGitContextState.bodyDepth===U.shellGitContextState.bodyDepth&&cg(G.shellGitContextState.bodyAssignments,U.shellGitContextState.bodyAssignments)&&cg(G.createdDirectories,U.createdDirectories)}function cg(G,U){return G.size===U.size&&[...G].every((j)=>U.has(j))}function _o(G,U){if(G===U)return!0;if(!G||!U||G.size!==U.size)return!1;return[...G].every(([j,K])=>U.get(j)===K&&U.has(j))}function BA(G,U){let j=Vo(G);return j===void 0?void 0:U.get(j)}function dg(G,U){if(!U)return null;return{reason:U.reason,segment:G,ruleId:U.id,intent:U.intent}}function UA(G,U=G.effectiveCwd){let j=U===null;return{environment:G.environment,cwd:j?void 0:U??G.cwd,originalCwd:j?void 0:G.cwd,strict:G.strict,paranoid:G.paranoidRm,allowTmpdirVar:G.allowTmpdirVar,protectedGitMetadata:G.protectedGitMetadata,policy:G.policy,budget:G.budget}}function kc(G,U){let j=At(kn(G),U.policy),K=U.trace?.currentSegmentIndex??U.trace?.allocateSegment(),re={type:"dangerous-text",token:G,matched:!!j,reason:j?.reason};if(U.trace?.recordSegment(re,K),!j&&/^(?:cd|pushd)\s/.test(G))U.trace?.recordSegment({type:"cwd-change",segment:G,effectiveCwdNowUnknown:!0},K);return j?{reason:j.reason,segment:G,ruleId:j.id,intent:j.intent}:null}function ug(G,U){let j={type:"strict-unparseable",rawCommand:G,reason:go},K=U.trace?.currentSegmentIndex;if(K===void 0)U.trace?.recordGlobal(j);if(K!==void 0)U.trace?.recordSegment(j)}var HA=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function hg(G,U,j,K){let re=Oc(G,0,{...U,...Ue(U),budget:U.budget??Pn(),factStore:K},j);if(!re)return null;return{kind:"deny",reason:re.reason,intent:re.intent??"manual_only",ruleId:re.ruleId,evidence:{command:G,segment:re.segment}}}function yg(G,U,j){try{return{decision:G()}}catch(K){let re=jA(K,U,j);if(!re)throw K;return re}}function jA(G,U,j){if(!(G instanceof s)||!HA.has(G.kind))return null;let K=a[G.kind];if(j?.currentSegmentIndex!==void 0)j.recordSegment({type:"error",message:K.reason});if(j?.currentSegmentIndex===void 0)j?.recordGlobal({type:"error",message:K.reason});return{decision:{kind:"deny",reason:K.reason,ruleId:"analysis.derived-command-limit",intent:"stop_and_explain",evidence:{command:U,segment:U}},errorCode:K.errorCode}}var VA=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),Nc=new Set(["cc-safety-net","ccsn"]),KA=new Set(["bunx","npx","pnpx"]),qA=new Set(["pnpm","yarn"]),YA=new Set(["npm","pnpm","yarn"]),ZA=new Set(["bun","node"]);function ta(G,U,j={}){if(Nc.has(G))return 0;if(KA.has(G)){if(j.broad)return Dc(U);let re=U[0]==="-y"||U[0]==="--yes"?1:0;return ea(U[re])?re+1:null}let K=j.broad?U.findIndex((re)=>!re.startsWith("-")):0;if(K!==-1&&YA.has(G)&&j.broad&&U[K]==="exec"){let re=Dc(U.slice(K+1));return re===null?null:K+1+re}if(qA.has(G)){if(G==="yarn"&&!j.broad)return null;if(!j.broad)return U[0]==="dlx"&&ea(U[1])?2:null;if(K===-1||U[K]!=="dlx")return null;let re=Dc(U.slice(K+1));return re===null?null:K+1+re}if(ZA.has(G)){let re=j.broad&&K!==-1?K:0;if(bg(U[re]))return re+1;if(G==="bun"&&U[re]==="run"&&bg(U[re+1]))return re+2}return null}function Dc(G){let U=G.findIndex((K)=>ea(K));if(U===-1)return null;let j=U;while(j<G.length){let K=G[j]??"";if(!K.startsWith("-")&&!ea(K))break;j++}return j}function ea(G){if(!G)return!1;let U=G.indexOf("@");if(U===-1)return Nc.has(G);if(U===0)return!1;let j=G.slice(U+1);if(j===""||j.includes("/")||j.includes(":"))return!1;return Nc.has(G.slice(0,U))}function bg(G){let U=G?.replaceAll("\\","/");return[...VA].some((j)=>U===j||U?.endsWith(`/${j}`))}var Ge="Only the user may apply a policy proposal, because it rewrites the configuration CC Safety Net enforces. Ask them to run `cc-safety-net policy apply <file>` themselves in a terminal; you can run `cc-safety-net policy check <file>` to show them what it would change.";function Sg(G,U,j){let K=hn(G,"input-candidate");if(!K)return null;let re=uo(K.shell,G.invocation.context.executionCwd,U,j,{findSegmentTarget:(oe)=>XA(oe,U),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return re?{target:re}:null}function XA(G,U){let j=ur([...G],U),K=j.slice(1),re=ta(Ot(j[0]??"").toLowerCase(),K,{broad:!0});if(re===null)return null;let oe=K.slice(re).filter((de)=>de!=="-g"&&de!=="--global");return oe[0]==="policy"&&oe[1]==="apply"?j.join(" "):null}import{dirname as na}from"node:path";var He="This path contains the protected policy config and you must not modify or delete it.",JA=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Rg(G,U,j){let K=oP(G.invocation.context,U,j);if(G.invocation.route.kind==="patch")return Cg(G.paths,!1,G.invocation.context.executionCwd,K,U,j);let re=hn(G,"input-candidate");if(G.invocation.route.kind==="command")return re?vg(re.shell,G.invocation.context.executionCwd,K,U,j):null;if(G.invocation.route.kind==="unknown"&&re){let oe=vg(re.shell,G.invocation.context.executionCwd,K,U,j);if(oe)return oe}return Cg(G.paths,G.invocation.route.kind==="grep"||G.invocation.route.kind==="glob"||Ii(G.invocation.toolName),G.invocation.context.executionCwd,K,U,j)}function Cg(G,U,j,K,re,oe){if(U)return null;let de=G.find((Se)=>vi(Se,j,K,re,oe));return de?{target:de}:null}function vg(G,U,j,K,re){let oe=uo(G,U,K,re,{findSegmentTarget:(de,Se)=>QA(de,Se,j,K,re)?.target??null,isRedirectionTarget:(de,Se)=>vi(de,Se.cwd,j,K,re),findMalformedTarget:(de)=>rP(de,U,j,K,re)?.target??null});return oe?{target:oe}:null}function QA(G,U,j,K,re){if(ai(G))return null;let oe=mr([...G],K),de=Ot(oe[0]??"").toLowerCase(),Se=oe.slice(1);if(de==="rm"&&eP(Se)){let we=tP(Se).find((We)=>Eg(gn(We,U.variables),U.cwd,j,K,re));if(we)return{target:we}}if(de==="find"){if(Ds(oe,1)||Zl(oe,K)){let We=(pi(Kt(oe))??Kt(["."])).find((mt)=>{let gt=gn(mt.text,U.variables);return vi(gt,U.cwd,j,K,re)||Eg(gt,U.cwd,j,K,re)})?.text;if(We)return{target:We}}}if(de==="mv"){let we=vs(Se).sources.find((We)=>iP(gn(We,U.variables),U.cwd,j,K,re));if(we)return{target:we}}if(nP(oe,de))return null;for(let we of[...G,...oe])for(let We of xg(we))if(vi(gn(We,U.variables),U.cwd,j,K,re))return{target:We};return null}function eP(G){return G.some((U)=>U==="--recursive"||U.startsWith("-")&&!U.startsWith("--")&&/[rR]/.test(U.slice(1)))}function tP(G){let U=G.indexOf("--");if(U!==-1)return[...G.slice(0,U).filter((j)=>!j.startsWith("-")),...G.slice(U+1)];return G.filter((j)=>!j.startsWith("-"))}function nP(G,U){if(!JA.has(U))return!1;if(U!=="sed")return!0;return!G.slice(1).some((j)=>j.startsWith("-i")||j==="--in-place"||j.startsWith("--in-place="))}function rP(G,U,j,K,re){for(let oe of G.split(/\s+/))for(let de of xg(oe))if(vi(de,U,j,K,re))return{target:de};return null}function xg(G){let U=G.trim().replace(/^['"]|['"]$/g,""),j=U.indexOf("=");return j===-1||j===U.length-1?[U]:[U,U.slice(j+1)]}function oP(G,U,j){let K=(Se)=>Ei(dn(Se,G.executionCwd,U,j)),re=K(l(U)),oe=[K(h(G.executionCwd)),K(h(G.configCwd))],de=new Set(oe.map((Se)=>na(Se)));for(let Se=na(re);;Se=na(Se))if(de.add(Se),na(Se)===Se)break;return{files:new Set([re,...oe]),directoriesAndAncestors:de}}function vi(G,U,j,K,re){let oe=rd(G,U,K,re,(de)=>Ei(de)===Li);return oe!==null&&j.files.has(Ei(oe))}function Eg(G,U,j,K,re){return j.directoriesAndAncestors.has(Ei(dn(G,U,K,re)))}function iP(G,U,j,K,re){let oe=Ei(dn(G,U,K,re));return j.files.has(oe)||j.directoriesAndAncestors.has(oe)}function Ei(G){return process.platform==="win32"?G.toLowerCase():G}import{isAbsolute as ra,posix as Wg,resolve as aa,win32 as sP}from"node:path";import{fileURLToPath as aP}from"node:url";var Fg="Access to a sensitive path is not allowed.",Gg=new Set(["echo","printf"]),lP=new Set(["find"]),cP=new Set(["!","do","elif","else","if","then","until","while"]),dP=new Set(["-exec","-execdir"]),uP=new Set([";","+"]),mP=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),fP=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),zg=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),pP=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),gP=new Set(["append","awk","base64","cat","chmod","chown","connect","copy","cp","database","dd","eval","exec","fetch","file","function","grep","head","include","load","move","mv","open","fopen","popen","read","readfile","remove","rename","require","rg","rm","sed","shell","source","spawn","strings","system","tail","tar","truncate","unlink","write","xxd","zip"]),zc=new Set(["-c","-e","-r","-E","--eval","--exec"]),hP=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"])]]),$c=new Set(["grep","rg"]),$g=new Set(["files-with-matches","files-without-match","count","quiet"]),yP=new Set([...$g,"ignore-case","fixed-strings","hidden"]),bP=new Set(["wc",...$c]),SP=new Set(["cd","grep","head","openssl","tail","tailscale"]),CP=/^(?:-[lwcm]+|--(?:lines|words|bytes|chars))$/,vP=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),EP=new Set(["commit","merge","notes","stash","tag"]),RP=new Set(["-m","--message"]),xP=new Set(["--grep"]),_P=new Set(["powershell","pwsh"]),_g=new Set(["jq","gojq","jaq"]),wg="f",Ag="file",wP="files",AP=new Set(["e","f"]),PP=new Set(["regexp","file"]),TP=new Set(["e","f","A","B","C","m"]),IP=new Set(["regexp","file","after-context","before-context","context","max-count"]),Lc="__CC_SAFETY_NET_PIPE_INPUT__",Fc=/[\w./~@+-]*[./~][\w./~@+-]*/g,kP=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,OP=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,MP=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,Pg=/\b(?:subprocess\s*\.\s*(?:run|call|Popen|check_output|check_call|getoutput|getstatusoutput)|(?:[\w$]+\s*\.\s*)*(?:exec(?:File)?(?:Sync)?|spawn(?:File)?(?:Sync)?|system|popen|shell_exec|passthru|child_process|eval))\s*\(/g,Tg=/\b(?:system|exec|spawn|popen)\s*$/,DP=/\b(?:eval|exec)\s*\(/g,NP=/\b(?:eval|exec)\s*$/,LP=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 Ig(G,U,j,K,re,oe){for(let de of G){let Se=de.target;if(nI(Se,de.cwd,U?.denyPaths??[],j,K,re))return{target:Se,ruleId:"secret.deny-path"};if(oe&&!oe.has(Se))continue;let we=eI(Se,de.cwd,U,K,re);if(we){let We=oe!==void 0&&!we.startsWith("secret.home.")&&!we.startsWith("secret.cli.");if(We&&K.paths.isDirectory(th(Se,de.cwd,K,re)))continue;if(We&&oe?.get(Se)==="data")continue;if(We&&(de.isRedirectionWriteTarget===!0||oe?.get(Se)==="write")&&!Se.includes("$")&&!sa(Se,de.cwd,K,re))continue;if(We&&(de.isCreatedPath===!0||de.isCertificateInput===!0))continue;if(We&&/\s/.test(Se)&&!Se.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(Se)&&!sa(Se,de.cwd,K,re))continue;if(!we.startsWith("secret.cli.")&&rI(Se,de.cwd,U?.allowPaths??[],j,K,re))continue;return{target:Se,ruleId:we}}}return null}function Bg(G,U,j,K,re={}){let oe=kg(G,j,K),de=Ig(oe,U,G.invocation.context.configCwd,j,K);if(de===null||de.ruleId==="secret.deny-path"||re.strict!==!1)return de;let Se=kg(G,j,K,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}),we=new Map;Se.forEach((ht)=>Ug(ht.target).forEach((yt)=>we.set(yt,(we.get(yt)??new Set).add(ht.loopVariable))));let We=(ht,yt)=>(we.get(ht)?.size??0)>(we.get(ht)?.has(yt)?1:0),mt=Se.filter(({loopVariable:ht})=>ht===void 0||We(ht,ht)||We("!",ht)),gt=new Set(mt.filter((ht)=>ht.literalRole===void 0).map((ht)=>ht.target)),ft=new Set(mt.filter((ht)=>ht.literalRole==="write").map((ht)=>ht.target)),pt=Ig(oe,U,G.invocation.context.configCwd,j,K,new Map(mt.map((ht)=>[ht.target,gt.has(ht.target)?"path":ft.has(ht.target)?"write":"data"])));return pt?.ruleId!=="secret.deny-path"&&WP(G,j)?null:pt}function WP(G,U){let j=hn(G,"input-candidate")??hn(G,"declared-command");if(!j)return!1;if(j.program.nodes.some((de)=>de.kind==="command"&&de.nested.length>0))return!1;let K=[];for(let de of Cs(j.shell)){if(de.kind==="operator"&&de.boundary)return!1;if(de.kind==="redirection")return!1;if(de.kind==="operator")continue;K.push(er(de.text,U))}let re=qn(K);if(re.length===0)return!1;let oe=mn(re[0]??"").toLowerCase();if(G.invocation.route.kind==="unknown")return j.program.dialect==="powershell"&&(oe==="ls"||oe==="stat");return Bc(oe,re.slice(1))}function Bc(G,U){if(G==="ls"||G==="stat")return!0;if(G==="test")return U.length===2&&(U[0]==="-e"||U[0]==="-f");if(G==="[")return U.length===3&&(U[0]==="-e"||U[0]==="-f")&&U[2]==="]";if(G==="git")return U[0]==="check-ignore";if(G==="wc")return U.every((j)=>!j.startsWith("-")||CP.test(j));if($c.has(G))return FP(G,U);if(G!=="find")return!1;return!U.some((j)=>mP.has(j))}function FP(G,U){let j=U.includes("--")?U.slice(0,U.indexOf("--")):U;if(j.some((We)=>/^--(?:(?:file|pre)(?:=|$)|json|format)/.test(We)||/^-[^-]*f/.test(We)))return!1;let K=G==="rg"?/[ABCEMTdegjmrt]/:/[ABCDdefm]/,re=G==="rg"?/[clq]/:/[Lclq]/,oe=(We)=>/^-[^-]/.test(We),de=(We)=>{let mt=j[We-1]??"";return/^--[^=]+$/.test(mt)&&!yP.has(mt.slice(2))||oe(mt)&&mt.slice(1).search(K)===mt.length-2},Se=j.findIndex((We,mt)=>!We.startsWith("-")&&!de(mt));return(G==="grep"&&Se>=0?j.slice(0,Se):j).some((We,mt)=>{if(de(mt))return!1;if(We.startsWith("--"))return $g.has(We.slice(2));return oe(We)&&re.test(We.slice(1).split(K)[0]??"")})}function kg(G,U,j,K={}){let re=G.invocation.context.executionCwd,oe=G.invocation.route.kind;if(oe!=="command"&&oe!=="unknown")return G.paths.map((Se)=>({target:Se,cwd:re}));let de=hn(G,"input-candidate");return[...de?Po(de.shell,G.store,K,U,re,j,GP(de)):[],...oe==="unknown"?G.paths.map((Se)=>({target:Se,cwd:re})):[]]}function GP(G){return G.program.dialect==="powershell"}function Po(G,U,j,K,re,oe,de=!1){if(G.status==="structural-limit")throw new b;if(G.status==="unclosed-quote")return[];if(G.status==="invalid")throw Error("Unable to parse command for secret protection");let Se=[...G.assignmentFallbacks.map((bt)=>({target:bt,cwd:re})),...LT(er(G.source,K),U,j,K,re,oe)],we=(bt)=>er(XP(bt,de),K),We=/[<>=]\(/.test(G.source),mt=/\bcoproc\b|\|&/.test(G.source),gt=[],ft=[],pt=(bt)=>({...j,commandHoldsPipe:j.commandHoldsPipe===!0||bt||mt});Ss(G,re,K,oe,{word:we,segment:(bt,St,Et,Ct,Rt,Pt)=>{if(bt.length===0)return null;let Tt=pt(Pt);if(Tt.commandHoldsPipe)gt.push(...bt);if(ft.push(mn(Hg(qn(bt))[0]??"").toLowerCase()),Se.push(...xi(bt,U,We||Ct==="|"||Ct==="|&"?{...Tt,segmentMayFeedReader:!0}:Tt,K,St.cwd,oe,Rt)),Et!==null)Se.push(...BP(Et,bt,U,Tt,K,St.cwd,oe));return null},redirection:(bt,St,Et)=>{if(bt.body!==void 0&&bt.consumer!==void 0){let Ct=pt(Et);Se.push(...jg(bt.consumer,[bt.body],U,Ct,K,St.cwd,oe,(Rt)=>UP(bt.consumer??[],Rt,U,Ct,K,St.cwd,oe)))}if(bt.targetOrder==="legacy-segment")return Ml;return Se.push({target:we(bt.target),cwd:St.cwd,...bt.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}});let ht=new Set(gt.flatMap(Ug)),yt=We||/\$\(|`/.test(G.source)||!ft.every((bt)=>SP.has(bt));return Se.map(({loopVariable:bt,...St})=>{if(St.certificateOutputMayFeedReader===!0&&yt)return{target:St.target,cwd:St.cwd};return bt===void 0||We||ht.has(bt)||ht.has("!")?St:{...St,loopVariable:bt}})}function Ug(G){return[.../^[A-Za-z_][A-Za-z0-9_]*$/.test(G)?[G]:[],...Array.from(G.matchAll(/\$(?:\{(!)|\{?([A-Za-z_][A-Za-z0-9_]*))/g),(U)=>U[1]??U[2]??"")]}function oa(G,U,j,K,re,oe,de=!1){let Se=U.getShellSyntax(G,de?U.getCommandProgram(G,"powershell"):void 0);if(Se.status==="structural-limit")throw new b;return Se.status==="complete"?Po(Se,U,j,K,re,oe,de):null}function xi(G,U,j,K,re,oe,de){let Se=(vt)=>({target:vt,cwd:re}),we=G.findIndex((vt)=>!cP.has(vt));if(j.skipMetadataOnlySegments===!0&&we>0)return xi(G.slice(we),U,j,K,re,oe,new Set([...de??[]].map((vt)=>vt-we)));let We=G[1]??"";if(j.skipMetadataOnlySegments===!0&&G[0]==="for"&&G[2]==="in"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(We))return G.slice(3).flatMap((vt)=>Dn("for",vt)).map((vt)=>({...Se(vt),loopVariable:We}));if(de?.size){let vt=G.filter((It,Lt)=>!de.has(Lt));if(_g.has(mn(qn(vt)[0]??"").toLowerCase()))return[...G.filter((It,Lt)=>de.has(Lt)).map(Se),...xi(vt,U,j,K,re,oe)]}let mt=ZP(G).map(Se),gt=qn(G);if(gt.length===0)return mt;let ft=gt[0]??"",pt=mn(ft).toLowerCase(),ht=gt.slice(1),yt=j.segmentMayFeedReader===!0||j.commandHoldsPipe===!0||j.displayOperandsAreCapturedOutput===!0,bt=yt&&bP.has(pt);if(j.skipMetadataOnlySegments===!0&&!bt&&Bc(pt,ht))return mt;let St=$P(ft,pt,ht);if(St)return[...mt,...St.map(Se)];if(Gg.has(pt))return j.displayOperandsAreCapturedOutput===!0?[...mt,...Vg(G).map(Se)]:mt;if(pt==="eval")return[...mt,...oa(ht.join(" "),U,j,K,re,oe)??ht.map(Se)];let Et=_P.has(Dt(ft))?Ec(gt):void 0;if(Et!==void 0)oe.charge("derivedTokens",gt.length);let Ct=Et===void 0?null:oa(Et,U,j,K,re,oe,!0);if(Ct?.length)return[...mt,...Ct];if(pt==="export")return[...mt,...ht.flatMap((vt)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(vt)?[vt.slice(vt.indexOf("=")+1)]:Dn(pt,vt)).map(Se)];if(pt==="git")return[...mt,...QP(ht).map(Se)];if(pt==="gh")return[...mt,...Gc(pt,ht,vP).map(Se)];if(_g.has(pt))return[...mt,...JP(ht).map(Se)];if($c.has(pt))return[...mt,...HT(ht).map(Se)];if(lP.has(pt))return[...mt,...tT(ht,U,j,K,re,oe).map(Se)];if(pt==="mkdir"||pt==="touch"){let vt=new Set(G.filter((Lt,en)=>de?.has(en))),It=j.segmentMayFeedReader!==!0&&!(pt==="touch"&&ht.some((Lt)=>/^(?:--r|-[^-]*r)/.test(Lt)));return[...mt,...ht.flatMap((Lt)=>Dn(pt,Lt).map((en)=>It&&!Lt.startsWith("-")&&!vt.has(Lt)?{...Se(en),isCreatedPath:!0}:Se(en)))]}if(In.has(pt))return[...mt,...ht.flatMap((vt)=>Dn("awk",vt)).map(Se),...ht.flatMap((vt)=>rT(vt,U,j,K,re,oe)),...ht.flatMap(oT).map(Se)];if(pt==="curl")return[...mt,...ht.filter((vt,It)=>qg(vt)===null&&Kg(ht[It-1])===null).flatMap((vt)=>Dn(pt,vt)).map(Se),...eT(ht).map(Se)];if(co(pt)){let vt=si.has(pt)?En([pt,...ht]):null;if(vt!==null&&vt.command!==null&&vt.commandIndex!==null){let It=U.getShellSyntax(vt.command);if(It.status==="structural-limit")throw new b;if(It.status==="complete")return[...mt,...Po(It,U,j,K,re,oe),...ht.slice(vt.commandIndex).filter((Lt)=>!Lt.startsWith("-")).map(Se)]}return[...mt,...nT(pt,ht,U,j,K,re,oe)]}let Rt=(vt,It)=>new RegExp(`^--?${vt}=`).test(ht[It]??"")||new RegExp(`^--?${vt}$`).test(ht[It-1]??""),Pt=zP(gt),Tt=pt==="openssl"&&ht[0]==="x509",kt=yt?{certificateOutputMayFeedReader:!0}:{};return[...mt,...ht.flatMap((vt,It)=>Dn(pt,vt).map((Lt)=>Pt&&Rt("(?:cert|key)-file",It)?{...Se(Lt),isCreatedPath:!0,...kt}:Tt&&Rt("in",It)?{...Se(Lt),isCertificateInput:!0,...kt}:Se(Lt)))]}function Hg(G){return mn(G[0]??"").toLowerCase()==="timeout"?G.slice(2):G}function zP(G){let U=Hg(G);return mn(U[0]??"").toLowerCase()==="tailscale"&&U[1]==="cert"}function $P(G,U,j){let K=ta(U,j);if(K===null||j[K]!=="explain")return null;let re=[G,...j.slice(0,K)],oe=j.slice(K+1);for(let de=0;de<oe.length;de++){let Se=oe[de];if(Se==="--json"||Se==="--help"||Se==="-h")continue;if(Se==="--cwd"){let we=oe[de+1];if(we&&!we.startsWith("--"))re.push(we);de++;continue}return re}return re}function BP(G,U,j,K,re,oe,de){if(KP(U,j,K,re,oe,de)){let Se=qn(G),we=Bc(mn(Se[0]??"").toLowerCase(),Se.slice(1))?Se.slice(1).filter((We)=>!We.startsWith("-")):[];return[...Vg(G),...we].map((We)=>({target:We,cwd:oe}))}return jg(U,HP(G),j,K,re,oe,de,()=>[])}function UP(G,U,j,K,re,oe,de){let Se=qn(G);if(!co(mn(Se[0]??"").toLowerCase()))return[];return oa(U,j,K,re,oe,de)??[{target:U,cwd:oe}]}function jg(G,U,j,K,re,oe,de,Se){let we=qP(G);if(we===null)return U.flatMap(Se);return U.flatMap((We)=>si.has(we)?Po(j.getShellSyntax(We),j,K,re,oe,de):ia(we,We,j,K,re,oe,de))}function Vg(G){let U=qn(G);if(U.length===0)return[];let j=mn(U[0]??"").toLowerCase();if(!Gg.has(j))return[];let K=U[U[1]==="--"?2:1];if(j==="printf"&&K!==void 0&&!K.startsWith("-")&&!K.replaceAll("%%","").includes("%"))return[Uc(K.replaceAll("%%","%"))];return U.slice(1)}function HP(G){let U=qn(G);if(U.length===0)return[];let j=mn(U[0]??"").toLowerCase(),K=U.slice(1);if(j==="echo"){let re=K.findIndex((oe)=>!/^-[neE]+$/.test(oe));return[(re===-1?[]:K.slice(re)).join(" ")]}if(j==="printf")return jP(K);return[]}function jP(G){let U=G[0];if(U===void 0)return[];let j=(U.match(/%%|%[bqs]/g)??[]).filter((re)=>re!=="%%").length;if(j===0||G.length===1)return[Uc(U)];let K=G.slice(1);return Array.from({length:Math.ceil(K.length/j)},(re,oe)=>VP(U,K.slice(oe*j,(oe+1)*j)))}function VP(G,U){let j=0;return Uc(G.replace(/%%|%[bqs]/g,(K)=>{if(K==="%%")return"%";let re=U[j]??"";return j++,re}))}function Uc(G){return G.replace(/\\n/g,`
|
|
44
|
+
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function KP(G,U,j,K,re,oe){let de=qn(G);if(de.length===0||mn(de[0]??"").toLowerCase()!=="xargs")return!1;let Se=$r(de),we=de.slice(Se.childStart);if(we.length===0)return!1;if(Se.replacementToken==="")return!1;let We=Se.replacementToken,mt=We===null?[...we,Lc]:we.map((gt)=>gt.split(We).join(Lc));return xi(mt,U,j,K,re,oe).some((gt)=>gt.target.includes(Lc))}function qP(G){let U=qn(G);if(U.length===0)return null;let j=mn(U[0]??"").toLowerCase();if(!co(j))return null;return YP(j,U.slice(1))?j:null}function YP(G,U){let j=Hc(G);for(let K=0;K<U.length;K++){let re=U[K];if(re===void 0)break;if(zc.has(re)||Yg(G,re)||/^--(?:eval|exec)=/.test(re))return!1;if(re==="-")return!0;if(re.startsWith("-")){if(j==="python"&&re==="-m")return!1;if(LP.get(j)?.has(re))K++;continue}return!1}return!0}function Hc(G){return/^python\d/.test(G)?"python":G}function ZP(G){let U=[];for(let j of G){if(eh(j))continue;let K=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(j);if(K===null)break;if(K[1]!==void 0&&K[1]!=="")U.push(K[1])}return U}var Og=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function XP(G,U){if(!U||!Og.test(G))return G;return`~${G.replace(Og,"").replace(/\\/g,"/")}`}function Dn(G,U){if(U==="--")return[];let j=[],K=U.indexOf("=");if(K>0&&K<U.length-1&&!U.slice(0,K).includes("?"))j.push(U.slice(K+1));if(U.startsWith("-"))return j;if(G==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(U))return j;if(G==="zip"&&/\.zip$/i.test(U))return j;return j.push(U),j}function JP(G){let U=-1,j=!1;for(let K=0;K<G.length;K++){let re=G[K]??"";if(!j&&re==="--"){j=!0;continue}if(j||!/^-(?:[A-Za-z]|-)/.test(re)){if(U===-1)U=K;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(re)){K+=2;continue}if(re==="--indent"||re==="-L"){K++;continue}if(re.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(re)||/^--(?:slurp|raw-output0?|join-output|compact-output|color-output|monochrome-output|ascii-output|unbuffered|sort-keys|raw-input|null-input|binary|tab|seq|stream|stream-errors|exit-status|args|jsonargs|help|version|build-configuration)$/.test(re))continue;return G.flatMap((oe)=>Dn("jq",oe))}return G.flatMap((K,re)=>re===U?[]:Dn("jq",K))}function QP(G){let U=[];for(let j=0;j<G.length;j++){let K=G[j]??"";if(K==="--"||!K.startsWith("-"))return[...U,...EP.has(K)?Gc("git",G.slice(j).map((oe)=>/^-[aeinopqsv]+m$/.test(oe)?"-m":oe),RP):Gc("git",G.slice(j),xP)];if(U.push(...Dn("git",K)),!vn.has(K))continue;let re=G[j+1];if(re===void 0)break;U.push(...K==="-c"&&re.includes("=")?[re.slice(re.indexOf("=")+1)]:Dn("git",re)),j++}return U}function Gc(G,U,j){let K=[];for(let re=0;re<U.length;re++){let oe=U[re]??"";if(oe==="--")return[...K,...U.slice(re).flatMap((de)=>Dn(G,de))];if(j.has(oe)){re++;continue}if(oe.includes("=")&&j.has(oe.slice(0,oe.indexOf("="))))continue;K.push(...Dn(G,oe))}return K}function eT(G){return G.flatMap((U,j)=>{let K=qg(U);if(K!==null)return Mg(K.flag,K.value);let re=Kg(G[j-1]);return re===null?[]:Mg(re,U)})}function Mg(G,U){if(G==="-F"||G==="--form"){let j=U.indexOf("="),K=j===-1?U:U.slice(j+1);if(!K.startsWith("@")&&!K.startsWith("<"))return[];return Wc(K.slice(1).split(";")[0]??"")}if(G==="--data-urlencode"){let j=U.indexOf("@"),K=U.indexOf("=");if(j===-1||K!==-1&&K<j)return[];return Wc(U.slice(j+1))}return U.startsWith("@")?Wc(U.slice(1)):[]}function Kg(G){if(G===void 0)return null;if(zg.has(G))return G;return/^-[A-Za-z]+[dF]$/.test(G)?`-${G.slice(-1)}`:null}function qg(G){let U=G.slice(0,2);if(G.length>2&&(U==="-d"||U==="-F"))return{flag:U,value:G.slice(2)};let j=G.indexOf("=");if(j===-1)return null;let K=G.slice(0,j);return zg.has(K)?{flag:K,value:G.slice(j+1)}:null}function Wc(G){return G===""||G==="-"?[]:[G]}function tT(G,U,j,K,re,oe){let de=G.findIndex((we)=>we.startsWith("-")||we==="("||we==="!"||we===";"),Se=[...G.slice(0,de===-1?G.length:de),...G.flatMap((we,We)=>we==="-files0-from"&&G[We+1]!==void 0?[G[We+1]??""]:[])];for(let we=0;we<G.length;we++){if(!dP.has(G[we]??""))continue;let We=G.slice(we+1),mt=We.findIndex((pt)=>uP.has(pt)),gt=mt===-1?We:We.slice(0,mt),ft=xi(gt,U,j,K,re,oe).map((pt)=>pt.target);if(Se.push(...ft.filter((pt)=>pt!=="{}")),!ft.includes("{}"))continue;Se.push(...G.slice(0,we).flatMap((pt,ht,yt)=>{if(!fP.has(pt))return[];let bt=yt[ht+1];return bt===void 0?[]:[bt,bt.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return Se}function nT(G,U,j,K,re,oe,de){let Se=[];for(let we=0;we<U.length;we++){let We=U[we];if(We===void 0)break;if(zc.has(We)||Yg(G,We)){let gt=U[we+1];if(gt!==void 0)Se.push(...ia(G,gt,j,K,re,oe,de)),we++;continue}let mt=/^--(?:eval|exec)=(.*)$/.exec(We);if(mt!==null&&mt[1]!==void 0){Se.push(...ia(G,mt[1],j,K,re,oe,de));continue}if(!We.startsWith("-"))Se.push({target:We,cwd:oe})}return Se}function Yg(G,U){if(!U.startsWith("-")||U.startsWith("--")||U.length<=2)return!1;return hP.get(U[U.length-1]??"")?.has(Hc(G))??!1}function rT(G,U,j,K,re,oe){if(!G.includes("system"))return[];return Vl(G)?.commands.flatMap((de)=>Po(U.getShellSyntax(de),U,j,K,re,oe))??[]}function oT(G){return Array.from(G.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((U)=>U[1]).filter((U)=>U!==void 0&&U!=="")}function iT(G){let U=Array.from(G.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((j)=>j[2]).filter((j)=>j!==void 0&&j!=="");return[...U,...U.flatMap(Vc),...G.match(Fc)??[]]}function ia(G,U,j,K,re,oe,de){let Se=(vt)=>({target:vt,cwd:oe}),we=PT(G),We=IT(U,we);if(We.kind==="unmaskable")return iT(U).map(Se);let mt=We.masked.match(Pg)!==null||We.literals.some((vt)=>Tg.test(We.masked.slice(0,vt.start))),gt=We.masked.match(DP)!==null||We.literals.some((vt)=>NP.test(We.masked.slice(0,vt.start))),ft=K.inlineLiteralsPresumedData===!0&&!si.has(G),pt=ft&&(we==="python"||we==="javascript"),ht=ft&&!(NT(We.masked)||mt||gt)?[]:We.literals,yt=ft?Array.from(We.masked.matchAll(Pg),(vt)=>{let It=vt.index+vt[0].length;return{start:It,end:us(We.masked,It)}}):[],bt=!ft||yt.some((vt)=>Pl(We.masked,vt.start)&&!fT(We,vt.start))?We.literals:We.literals.filter((vt)=>Tg.test(We.masked.slice(0,vt.start))||yt.some((It)=>vt.start>=It.start&&vt.start<It.end)),St=new Set(mt?bt:[]),Et=pt&&ht.length>0&&!cT(We.masked,we==="python"?"#":"//"),Ct=Et?pT(We.masked):[],Rt=Et?Array.from(We.masked.matchAll(/[A-Za-z_$][\w$]*/g),(vt)=>({name:vt[0],index:vt.index})):[],Pt=uT(Rt),Tt=!dT(We.masked,Rt),kt=Rt.filter((vt)=>!Dg(We.masked,{start:vt.index,text:vt.name,tokenStart:vt.index,tokenEnd:vt.index+vt.name.length},Ct,Pt,Tt)).reduce((vt,It)=>{let Lt=vt.get(It.name)??[];return Lt.push(It.index),vt.set(It.name,Lt)},new Map);return[...ht.filter((vt)=>vt.text!=="").map((vt)=>{if(!Et||St.has(vt))return Se(vt.text);if(Dg(We.masked,vt,Ct,Pt,Tt)||gT(We.masked,vt,Ct,kt))return{...Se(vt.text),literalRole:"data"};return _T(We,vt,Ct)?{...Se(vt.text),literalRole:"write"}:Se(vt.text)}),...ht.flatMap((vt)=>Vc(vt.text)).map(Se),...ft?[]:We.literals.flatMap((vt)=>vt.text.match(Fc)??[]).map(Se),...mt?bt.flatMap((vt)=>oa(vt.text,j,{...K,commandHoldsPipe:!0},re,oe,de)??[Se(vt.text)]):[],...gt?We.literals.flatMap((vt)=>ia(G,vt.text.replace(/\\(.)/g,(It,Lt)=>Lt==="n"?`
|
|
45
|
+
`:Lt),j,K,re,oe,de)):[],...pt?[]:(We.masked.match(Fc)??[]).map(Se),...ft?(U.match(/\$\{[^}]*\}|\$[A-Za-z_]\w*/g)??[]).map(Se):[]]}var jc={"(":")","[":"]","{":"}"},Zg="and|elif|else|if|in|is|not|of|or|return|while|yield",sT=new RegExp(`(?:^|[^\\w$])(?:${Zg})$`),aT=new RegExp(`(?:\\*|\\.\\.\\.)\\s*[([{]|\\.\\s*(?:${Zg})\\s*\\(|/\\*`),lT=/^(?:exec|spawn)|^(?:popen|system|subprocess)$/;function cT(G,U){return aT.test(G)||G.split(`
|
|
46
|
+
`).some((j)=>{let K=j.indexOf(U);return K>=0&&/[()[\]{}]/.test(j.slice(K))})}function dT(G,U){return bT.test(G)||U.some((j)=>{let K=yT.get(j.name),re=j.index+j.name.length;return K!==void 0&&!K.test(G.slice(re,re+40))})}function uT(G){return G.some((U)=>Jg(U.name).some((j)=>lT.test(j)))}var mT=new Set(["cmd","powershell","pwsh"]);function fT(G,U){let j=jr(G.masked,U),K=jc[G.masked[j]??""];if(K===void 0||K==="}")return!1;let re=G.masked.indexOf(K,j+1),oe=G.masked.slice(j+1,re);return re!==-1&&/^\s*,[\w\s,]*$/.test(oe)&&/^[,)]/.test(G.masked.slice(jr(G.masked,re+1)))&&!G.literals.some((de)=>de.tokenStart>j&&de.tokenStart<re&&(zc.has(de.text)||co(mn(de.text).toLowerCase())||mT.has(mn(de.text).toLowerCase().replace(/\.exe$/,""))))}function pT(G){let U=[];return G.split("").map((j,K)=>{let re=U.at(-1)??-1;if(j in jc)U.push(K);if(j===")"||j==="]"||j==="}")U.pop();return re})}function Dg(G,U,j,K,re){let oe=j[U.tokenStart]??-1,de=G[oe]??"",Se=Ao(G,U.tokenStart),we=jr(G,U.tokenEnd);if(/(?:^|[^\w$])in$|[=!]=$/.test(G.slice(Math.max(0,Se-3),Se+1)))return!0;if(/^(?:(?:not\s+)?in(?![\w$])|[=!]=)/.test(G.slice(we,we+8)))return!0;if(K&&(de==="["||de==="("))return!1;let We=G[Se],mt=G[we];if(de==="{"&&We===":")return wT(G,Se);let gt=(We===de||We===",")&&(mt===","||mt===jc[de]||de==="{"&&mt===":");if(de!=="(")return gt&&de!=="";return gt&&(re&&hT.test(G.slice(Math.max(0,oe-20),oe))||(We===","||mt===",")&&AT(G,oe))}function gT(G,U,j,K){let re=Math.max(0,U.tokenStart-80),oe=`${re===0?`
|
|
47
|
+
`:""}${G.slice(re,U.tokenStart)}`,de=ST.exec(oe)?.[1],Se=G[j[U.tokenStart]??-1];if(de===void 0||Se==="("||Se==="[")return!1;let we=jr(G,U.tokenEnd)+1;if(!/^\s*(?:[;\n]|$)/.test(G.slice(U.tokenEnd,we)))return!1;let We=U.tokenStart-oe.length+oe.lastIndexOf(de);return(K.get(de)??[]).every((mt)=>mt===We)}var hT=/(?:^|[^\w$.])(?:print|console\s*\.\s*log)\s*$/,yT=new Map([["print",/^\s*\(/],["console",/^\s*\.\s*[\w$]+\s*\(/]]),bT=/(?:^|[^\w$])(?:as|class|const|def|function|import|let|var)\s+(?:print|console)(?![\w$])/,ST=/[;\n{]\s*(?:(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*=\s*$/,CT=/(?:^|[^\w$.])(?:pathlib\s*\.\s*)?Path\s*$/,vT=/^\s*\.\s*write_(?:text|bytes)\s*\(/,ET=/(?:^|[^\w$.])open\s*$/,RT=/^[bt]*[awx][abtwx]*$/,xT=/(?:^|[^\w$])(?:writeFile|writeFileSync|appendFile|appendFileSync|Bun\s*\.\s*write)\s*$/;function _T(G,U,j){let K=j[U.tokenStart]??-1;if(G.masked[K]!=="(")return!1;let re=Ao(G.masked,U.tokenStart),oe=jr(G.masked,U.tokenEnd),de=G.masked[oe],Se=G.masked.slice(Math.max(0,K-40),K);if(CT.test(Se))return(re===K||G.masked[re]===",")&&(de===","||de===")")&&!G.literals.some((We)=>We.tokenStart>K&&We.tokenStart<U.tokenStart)&&vT.test(G.masked.slice(us(G.masked,K+1)+1));if(re!==K||de!==",")return!1;if(xT.test(Se))return!0;if(!ET.test(Se))return!1;let we=G.literals.find((We)=>/^,\s*(?:mode\s*=\s*)?$/.test(G.masked.slice(oe,We.tokenStart)));return we!==void 0&&RT.test(we.text)&&/^[,)]/.test(G.masked.slice(jr(G.masked,we.tokenEnd)))}function wT(G,U){let j=Ao(G,U),K=/[\w$]*$/.exec(G.slice(Math.max(0,j-63),j+1))?.[0]??"",re=G[Ao(G,j+1-K.length)];return re==="{"||re===","}function AT(G,U){let j=Ao(G,U),K=G.slice(Math.max(0,j-7),j+1);return!/[\w$)\]]$/.test(K)||sT.test(K)}function PT(G){let U=Hc(G);if(U==="python")return"python";if(U==="osascript")return"opaque";return U==="node"||U==="bun"||U==="deno"?"javascript":"simple"}var TT={python:"#",javascript:"/"};function IT(G,U){if(U==="opaque")return{kind:"unmaskable"};let j={masked:G.split(""),literals:[]};return Xg(G,0,U,j,!1)===null?{kind:"unmaskable"}:{kind:"masked",masked:j.masked.join(""),literals:j.literals}}function Xg(G,U,j,K,re){let oe=0;for(let de=U;de<G.length;de++){let Se=G[de]??"";if(re&&Se==="}"&&oe===0)return de;if(re&&Se===TT[j])return null;if(Se==="{")oe++;if(Se==="}")oe--;if(j==="simple"&&(Se==="`"||Se==="%"||Se==="<")){if(OP.test(G.slice(de)))return null}let we=Se==="'"||Se==='"'||j==="javascript"&&Se==="`"?Se:null;if(we===null)continue;if(we==="`"&&DT(G,de))return null;let We=j==="python"?OT(G,de):"",mt=j==="python"&&G.startsWith(we.repeat(3),de)?we.repeat(3):we,gt=de+mt.length,ft=we==="`"||/[fF]/.test(We),pt=de-We.length,ht=ft?kT(G,pt,gt,mt,j,K):MT(G,gt,mt);if(ht===null)return null;if(!ft){let yt=G.slice(gt,ht);if(j==="simple"&&we==='"'&&MP.test(yt))return null;K.literals.push({start:gt,text:yt,tokenStart:pt,tokenEnd:ht+mt.length}),K.masked.fill(" ",gt,ht)}K.masked.fill(" ",de,gt),K.masked.fill(" ",ht,ht+mt.length),de=ht+mt.length-1}return re?null:G.length}function kT(G,U,j,K,re,oe){let de=re==="python"?"{":"${",Se=K==="`"||K.length===3,we="";for(let We=j;We<G.length;We++){let mt=G[We]??"";if(G.startsWith(K,We))return oe.literals.push({start:j,text:we,tokenStart:U,tokenEnd:We+K.length}),We;if(!Se&&(mt===`
|
|
48
|
+
`||mt==="\r"))return null;let gt=re==="python"&&(mt==="{"||mt==="}")&&G[We+1]===mt;if(!gt&&G.startsWith(de,We)){let ht=Xg(G,We+de.length,re,oe,!0);if(ht===null)return null;we+=`${de}}`,oe.masked.fill(" ",We,We+de.length),oe.masked[ht]=" ",We=ht;continue}let pt=mt==="\\"&&!(re==="python"&&G[We+1]==="{")||gt?2:1;we+=G.slice(We,We+pt),oe.masked.fill(" ",We,We+pt),We+=pt-1}return null}function OT(G,U){return kP.exec(G.slice(Math.max(0,U-3),U))?.[1]??""}function MT(G,U,j){let K=j.length===3;for(let re=U;re<G.length;re++){let oe=G[re];if(oe==="\\"){re++;continue}if(!K&&(oe===`
|
|
49
|
+
`||oe==="\r"))return null;if(G.startsWith(j,re))return re}return null}function DT(G,U){for(let j=U-1;j>=0;j--){let K=G[j];if(!K||/\s/.test(K))continue;return/[\w$\])]/.test(K)}return!1}function NT(G){for(let U of G.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let j=U[0],K=U.index;if(pP.has(j.toLowerCase()))return!0;let re=Jg(j);if(!re.some((oe)=>gP.has(oe)))continue;if(re.length>1)return!0;if(G[Ao(G,K)]===".")return!0;if(G[jr(G,K+j.length)]==="(")return!0}return!1}function Jg(G){return G.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((U)=>U.toLowerCase())}function Ao(G,U){for(let j=U-1;j>=0;j--)if(!/\s/.test(G[j]??""))return j;return-1}function jr(G,U){for(let j=U;j<G.length;j++)if(!/\s/.test(G[j]??""))return j;return G.length}function LT(G,U,j,K,re,oe){return $T(G).flatMap((de)=>{let Se=U.getShellSyntax(de);if(Se.status==="invalid")return[];return[...Po(Se,U,{...j,displayOperandsAreCapturedOutput:!0},K,re,oe),...WT(Se,K)?FT(Se,K).map((we)=>({target:we,cwd:re})):[]]})}function WT(G,U){let j=Cs(G);for(let K=0;K<j.length;K++){let re=j[K];if(re?.kind!=="word"||mn(er(re.text,U)).toLowerCase()!=="base64")continue;for(let oe=K+1;oe<j.length;oe++){let de=j[oe];if(de?.kind==="operator")break;if(de?.kind!=="word")continue;let Se=er(de.text,U);if(Se==="--decode"||!Se.startsWith("--")&&Se.startsWith("-")&&/[dD]/.test(Se))return!0}}return!1}function FT(G,U){return Cs(G).flatMap((j)=>j.kind==="word"?[er(j.text,U)]:j.kind==="redirection"&&j.target?[er(j.target,U)]:[]).flatMap(Vc)}function Vc(G){let U=zT(G);if(U===null)return[];let j=Buffer.from(U,"base64").toString("utf8");if(j===""||GT(j))return[];return Buffer.from(j,"utf8").toString("base64").replace(/=+$/g,"")===U.replace(/=+$/g,"")?[j]:[]}function GT(G){return Array.from(G).some((U)=>{let j=U.charCodeAt(0);return j<32||j===127})}function zT(G){if(G.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(G))return null;if(/=/.test(G.replace(/=+$/g,"")))return null;let U=G.replace(/=+$/g,"");if(U.length%4===1)return null;return`${U.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-U.length%4)%4)}`}function $T(G){let U=[],j={inSingle:!1,inDouble:!1,escaped:!1};for(let K=0;K<G.length;K++){let re=G[K];if(!re)break;if($o(re,j))continue;if(Qg(G,K,j)){let oe=BT(G,K+1);if(oe!==null)U.push(oe.body),K=oe.endIndex;continue}if(!j.inSingle&&re==="`"){let oe=UT(G,K);if(oe!==null)U.push(oe.body),K=oe.endIndex}}return U}function BT(G,U){let j={inSingle:!1,inDouble:!1,escaped:!1},K=1;for(let re=U+1;re<G.length;re++){let oe=G[re];if(!oe)break;if($o(oe,j))continue;if(Qg(G,re,j)){K++,re++;continue}if(!j.inSingle&&!j.inDouble&&oe===")"){if(K--,K===0)return{body:G.slice(U+1,re),endIndex:re}}}return null}function UT(G,U){let j=!1;for(let K=U+1;K<G.length;K++){let re=G[K];if(!re)break;if(j){j=!1;continue}if(re==="\\"){j=!0;continue}if(re==="`")return{body:G.slice(U+1,K),endIndex:K}}return null}function Qg(G,U,j){return!j.inSingle&&G[U]==="$"&&G[U+1]==="("&&G[U+2]!=="("}function HT(G){let U=[],j=[],K=!1,re=!1,oe=!1;for(let we=0;we<G.length;we++){let We=G[we];if(We===void 0)break;if(!oe&&We==="--"){oe=!0;continue}if(oe){j.push(We);continue}let mt=/^--([^=]+)(?:=(.*))?$/.exec(We);if(mt!==null){let gt=mt[1]??"",ft=mt[2];if(gt===wP)re=!0;if(PP.has(gt))K=!0;if(ft!==void 0){if(gt===Ag)U.push(ft);continue}if(IP.has(gt)){let pt=G[we+1];if(gt===Ag&&pt!==void 0)U.push(pt);we++}continue}if(We.startsWith("-")&&We.length>1){let gt=We.slice(1),ft="",pt="";for(let yt=0;yt<gt.length;yt++){let bt=gt[yt]??"";if(AP.has(bt))K=!0;if(TP.has(bt)){ft=bt,pt=gt.slice(yt+1);break}}if(ft==="")continue;if(pt.length>0){if(ft===wg)U.push(pt);continue}let ht=G[we+1];if(ft===wg&&ht!==void 0)U.push(ht);we++;continue}j.push(We)}let Se=!K&&!re?j.slice(1):j;return[...U,...Se]}function qn(G){let U=G.findIndex((j)=>!eh(j)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(j));return U===-1?[]:G.slice(U)}function eh(G){return G==="env"||G==="command"||G==="builtin"||G==="sudo"}var jT=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),VT=".env.",KT=new Set([".env.example",".env.sample",".env.template",".env.tpl",".env.defaults"]),qT=[".env.example.",".env.sample."];function YT(G){let U;try{U=new URL(G.trim())}catch{return!1}return U.protocol!=="file:"&&U.host!==""}function ZT(G){return G.length>0&&!/\s/.test(G)}function sa(G,U,j,K){let re=th(G,U,j,K);return re!==""&&j.paths.entryKind(re)!=="missing"}function th(G,U,j,K){try{return _i(G,U,j,K)}catch(re){if(re instanceof s)throw re;return""}}var XT=/[?&][^?&=/]+=/,JT=new Set(["node_modules","__pycache__"]),QT=[["vendor","bundle"],["vendor","cache"]];function eI(G,U,j,K,re){if(YT(G))return null;let oe=Sn(G,U,K,re);if(!oe)return null;let de=Bt(oe.split("/").pop()??""),Se=Bt(oe),we=()=>ZT(de)||sa(G,U,K,re),We=Bt(sI(G,U,K,re));for(let ft of $a){let pt=`~/${ft.suffixParts.join("/")}`;if((Lg(Se,pt)||Lg(We,pt))&&ir(ft.id,j))return ft.id}if(KT.has(de)||qT.some((ft)=>de.startsWith(ft)))return null;let mt=tI(oe,U,j,K,re);if(mt)return mt;if(jT.has(de))return null;for(let ft of za)if(de===ft.basename&&ir(ft.id,j))return ft.id;if(de.startsWith(VT)&&ir($i.id,j)&&we())return $i.id;for(let ft of Ba)if(de.length>ft.prefix.length&&de.startsWith(ft.prefix)){let pt=de.slice(ft.prefix.length)[0];if((pt==="-"||pt==="_")&&ir(ft.id,j)&&we())return ft.id}for(let ft of Ua)if(de.length>ft.prefix.length&&de.startsWith(ft.prefix)){if(de.slice(ft.prefix.length)===ft.suffix&&ir(ft.id,j))return ft.id}if(oI(Se))return null;if(!de.includes(".")&&Bo.pattern.test(de)&&ir(Bo.id,j))return Bo.id;if(XT.test(G)&&!sa(G,U,K,re))return null;let gt=iI(de,j);if(gt)return gt;return null}function tI(G,U,j,K,re){return Bi.find((oe)=>{if(!ir(oe.id,j))return!1;switch(oe.id){case"secret.cli.claude-code":return Ft(G,Ht(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),[".credentials.json"]);case"secret.cli.claude-code.config":{let de=Bt(G).split("/");return Ft(G,Ht(K.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",U,K,re),["settings.json","settings.local.json"])||Ri(G,"~/.claude.json",U,K,re)||de.at(-1)==="settings.local.json"&&de.at(-2)===".claude"||de.at(-1)===".mcp.json"}case"secret.cli.antigravity":return Ft(G,Sn("~/.gemini/config",U,K,re),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let de=Ht(K.env.get("CODEX_HOME"),"~/.codex",U,K,re);return Ft(G,de,["auth.json",".credentials.json"])||wo(G,de,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let de=Ht(K.env.get("CODEX_HOME"),"~/.codex",U,K,re),Se=Bt(G).split("/").at(-1)??"";return Ft(G,de,["config.toml"])||Se.endsWith(".config.toml")&&Ft(G,de,[Se])}case"secret.cli.gemini":return Ft(G,Qt(Ht(K.env.get("GEMINI_CLI_HOME"),"~",U,K,re),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let de=Bt(G).split("/"),Se=K.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),we=K.env.get("ProgramData")?[Qt(Ht(K.env.get("ProgramData"),"",U,K,re),"gemini-cli")]:[];return Ft(G,Qt(Ht(K.env.get("GEMINI_CLI_HOME"),"~",U,K,re),".gemini"),["settings.json","google_accounts.json"])||de.at(-1)==="settings.json"&&de.at(-2)===".gemini"||(Se?.trim()?Ri(G,Se,U,K,re):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...we].some((We)=>Ft(G,Sn(We,U,K,re),["settings.json"]))}case"secret.cli.copilot-cli":{let de=Ht(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re);return Ft(G,de,["config.json"])||wo(G,de,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return Ft(G,Ht(K.env.get("COPILOT_HOME"),"~/.copilot",U,K,re),["mcp-config.json"]);case"secret.cli.kimi-code":{let de=Ht(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),Se=Ht(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re);return Ft(G,de,["server.token"])||wo(G,de,["credentials"])||wo(G,Se,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let de=["config.toml","mcp.json"],Se=Bt(G).split("/");return Se.at(-1)==="mcp.json"&&Se.at(-2)===".kimi-code"||Ft(G,Ht(K.env.get("KIMI_CODE_HOME"),"~/.kimi-code",U,K,re),de)||Ft(G,Ht(K.env.get("KIMI_SHARE_DIR"),"~/.kimi",U,K,re),[...de,"config.json","config.json.bak"])}case"secret.cli.opencode":{let de=Qt(Ht(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"opencode"),Se=Bt(G).split("/").at(-1)??"",we=K.env.get("OPENCODE_DB")?.trim(),We=we&&we!==":memory:"?[we,`${we}-wal`,`${we}-shm`]:[];return Ft(G,de,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Se)&&Ft(G,de,[Se])||We.some((mt)=>Ri(G,mt,U,K,re))}case"secret.cli.opencode.config":{let de=Qt(Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"opencode"),Se=K.env.get("ProgramData")?[Qt(Ht(K.env.get("ProgramData"),"",U,K,re),"opencode")]:[],we=["opencode.json","opencode.jsonc"],We=K.env.get("OPENCODE_CONFIG");return we.includes(Bt(G).split("/").at(-1)??"")||Ft(G,de,["config.json"])||(We?.trim()?Ri(G,We,U,K,re):!1)||["/Library/Application Support/opencode","/etc/opencode",...Se].some((mt)=>Ft(G,Sn(mt,U,K,re),we))}case"secret.cli.pi":return Ft(G,Ht(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["auth.json"]);case"secret.cli.pi.config":return Ft(G,Ht(K.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",U,K,re),["models.json"]);case"secret.cli.amp":{let de=Sn("~",U,K,re);return[Qt(Ht(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),"amp"),Qt(de,".local","share","amp")].some((we)=>Ft(G,we,["secrets.json"]))||wo(G,Qt(de,".amp"),["oauth"])}case"secret.cli.amp.config":{let de=["settings.json","settings.jsonc"],Se=[Qt(Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"amp"),Qt(Sn("~",U,K,re),".config","amp")],we=Bt(G).split("/"),We=K.env.get("AMP_SETTINGS_FILE");return Se.some((mt)=>Ft(G,mt,de))||we.at(-2)===".amp"&&de.includes(we.at(-1)??"")||(We?.trim()?Ri(G,We,U,K,re):!1)}case"secret.cli.cursor":{let de=Qt(Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),"cursor"),Se=Qt(Ht(K.env.get("CURSOR_DATA_DIR"),"~/.cursor",U,K,re),"projects");return Ft(G,Sn("~/.cursor",U,K,re),["auth.json"])||Ft(G,de,["auth.json"])||Bt(G).split("/").at(-1)==="mcp-auth.json"&&Vr(Bt(G),Bt(Se))}case"secret.cli.cursor.config":{let de=Bt(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".cursor"}case"secret.cli.grok-build":return Ft(G,Ht(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let de=Bt(G).split("/");return de.at(-1)==="config.toml"&&de.at(-2)===".grok"||Ft(G,Ht(K.env.get("GROK_HOME"),"~/.grok",U,K,re),["config.toml","managed_config.toml","requirements.toml"])||Ft(G,Sn("/etc/grok",U,K,re),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return Ft(G,Sn("~/.factory",U,K,re),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let de=Bt(G).split("/");return de.at(-1)==="mcp.json"&&de.at(-2)===".factory"||Ft(G,Sn("~/.factory",U,K,re),["settings.json","hooks.json"])}case"secret.cli.devin":return[Ht(K.env.get("XDG_DATA_HOME"),"~/.local/share",U,K,re),Sn("~/.local/share",U,K,re)].some((de)=>Ft(G,Qt(de,"devin"),["credentials.toml"])||wo(G,Qt(de,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[Ht(K.env.get("XDG_CONFIG_HOME"),"~/.config",U,K,re),Sn("~/.config",U,K,re)].some((de)=>Ft(G,Qt(de,"devin"),["config.json"]));default:return!1}})?.id??null}var Ng=new WeakMap;function Ht(G,U,j,K,re){let oe=Ng.get(re)??new Map;Ng.set(re,oe);let de=`${j}\x00${G??""}\x00${U}`,Se=oe.get(de);if(Se!==void 0)return Se;let we=Sn(G?.trim()?G:U,j,K,re);return oe.set(de,we),we}function Ft(G,U,j){return j.some((K)=>nh(G,Qt(U,K)))}function wo(G,U,j){return j.some((K)=>Vr(Bt(G),Bt(Qt(U,K))))}function Ri(G,U,j,K,re){return nh(G,Sn(U,j,K,re))}function nh(G,U){return Bt(G)===Bt(U)}function Qt(G,...U){return Bn([G,...U].filter(Boolean).join("/"))}function nI(G,U,j,K,re,oe){if(j.length===0)return!1;let de=Bt(_i(G,U,re,oe));return j.some((Se)=>Vr(de,Bt(_i(Se,K,re,oe))))}function rI(G,U,j,K,re,oe){if(j.length===0)return!1;let de=Bt(_i(G,U,re,oe));if(!de)return!1;let Se=re.env.get("HOME")??re.home,we=Se?Bn(Wt(cn(Se),re.paths,oe)):"",We=Bt(we),mt=re.env.get("CC_SAFETY_NET_HOME"),gt=Bt(mt?Bn(Wt(aa(cn(mt)),re.paths,oe)):we&&Bn(Wt(`${we}/.cc-safety-net`,re.paths,oe)));if(gt&&Vr(de,gt))return!1;return j.some((ft)=>{let pt=qa(ft);if(pt&&Wg.basename(de)!==Bt(pt.name))return!1;let ht=Bt(_i(pt?.root??ft,K,re,oe));if(!ht)return!1;if(We&&(We===ht||We.startsWith(ht.endsWith("/")?ht:`${ht}/`)))return!1;return Vr(de,ht)&&!(pt&&de===ht)})}function oI(G){let U=G.split("/");return U.some((j)=>JT.has(j))||QT.some(([j,K])=>U.some((re,oe)=>re===j&&U[oe+1]===K))}function iI(G,U){let j=G.lastIndexOf("."),K=j>0&&j<G.length-1?G.slice(j+1):"";if(K==="")return null;for(let re of Ha)if(K===re.extension&&ir(re.id,U))return re.id;for(let re of ja)if(re.pattern.test(K)&&ir(re.id,U))return re.id;return null}function Bt(G){return G.toLowerCase()}function ir(G,U){return!U?.disabledRules?.includes(G)}function Sn(G,U,j,K){let{home:re,normalized:oe}=Kc(G,j,K);if(!oe)return"";if(!re)return oe;let de=qc(oe,re),Se=ra(de)?de:Bn(aa(U,de)),we=Bn(Wt(Se,j.paths,K));if(!Vr(we,re)){if(ra(de))return we;return we===Se?oe:we}let We=we.slice(re.length);return We?`~${We}`:"~"}function Lg(G,U){return G===U||G.startsWith(`${U}/`)}function sI(G,U,j,K){let{home:re,normalized:oe}=Kc(G,j,K);if(!oe||!re)return"";let de=qc(oe,re),Se=Wg.normalize(ra(de)?de:Bn(aa(U,de))),we=Bn(cn(j.env.get("HOME")??j.home)),We=(ft)=>process.platform==="win32"?ft.toLowerCase():ft,mt=[re,we].find((ft)=>ft!==""&&Vr(We(Se),We(ft)));if(mt===void 0)return"";let gt=Se.slice(mt.length);return gt?`~${gt}`:"~"}function _i(G,U,j,K){let{home:re,normalized:oe}=Kc(G,j,K);if(!oe)return"";let de=re?qc(oe,re):oe;return Bn(Wt(ra(de)?de:aa(U,de),j.paths,K))}function Kc(G,U,j){let K=U.env.get("HOME")??U.home,re=K?Bn(Wt(cn(K),U.paths,j)):"",oe=Bn(cn(aI(er(G,U))));return{home:re,normalized:oe}}function aI(G){if(!G.trim().toLowerCase().startsWith("file:"))return G;try{return aP(G)}catch{return G}}function qc(G,U){if(G==="~")return U;if(G.startsWith("~/"))return Qt(U,G.slice(2));return G}function lI(G){if(process.platform==="win32")return!0;return sP.parse(G).root.length>1}function Bn(G){let U=G.trim(),j=(U.includes("\\")&&lI(U)?U.replace(/\\/g,"/"):U).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(j==="/")return j;return j.replace(/\/+$/g,"")}function Vr(G,U){return G===U||G.startsWith(U.endsWith("/")?U:`${U}/`)}function mn(G){return G.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??G}class p extends Error{stage;evaluation;name="GuardEvaluationError";constructor(G,U,j){super(`CC Safety Net ${G} dependency failed`,{cause:j});this.stage=G;this.evaluation=U}}var cI={findPolicyMutation:Rg,findGitMetadataMutation:qm,resolveGitMetadata:uI,loadPolicySnapshot:k,findSensitiveTarget:Bg,analyzeCommand:hg,getModes:T},dI=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function q(G,U){let j={...cI,...U.dependencies},K=pI(G),re=wi(G)?G.command:K,oe=Sr("policy-protection",re,()=>Hm(G)),de=hn(oe,"input-candidate"),Se=hn(oe,"declared-command");if(wi(G)&&G.command?.trim()&&Se?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Un,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:G.command,segment:G.command}}};if(de?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:gf,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let we=Pn(),We=Sr("policy-protection",re,()=>j.resolveGitMetadata([G.context.executionCwd,G.context.configCwd],U.environment)),mt=Sr("policy-protection",re,()=>j.findPolicyMutation(oe,U.environment,we));if(mt){let Ct=re??mt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:He,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:Ct,segment:mt.target}}}}let gt=Sr("policy-protection",re,()=>Sg(oe,U.environment,we));if(gt){let Ct=re??gt.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Ge,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:Ct,segment:gt.target}}}}let ft=Sr("policy-protection",re,()=>j.findGitMetadataMutation(oe,We,U.environment,we));if(ft){let Ct=re??ft.target;return{stage:"policy-protection",decision:{kind:"deny",reason:x,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:Ct,segment:ft.target}}}}let pt=Sr("config-load",re,()=>j.loadPolicySnapshot(U.environment,{...U.policyOptions,cwd:G.context.configCwd})),ht=pt.policy,yt=j.getModes(ht,U.environment.env),bt={level:yt.effectiveLevel,...mI(pt)},St=ht.secretProtection.enabled===!1?null:Sr("secret-protection",re,()=>j.findSensitiveTarget(oe,ht.secretProtection,U.environment,we,{strict:wi(G)||de?.program.dialect==="powershell"?yt.strict:void 0}));if(St){let Ct=re??St.target;return{stage:"secret-protection",...bt,decision:{kind:"deny",reason:Fg,intent:"hard_stop",ruleId:St.ruleId,evidence:{command:Ct,segment:St.target}}}}if(!wi(G))return{stage:"non-command",...bt,decision:{kind:"allow"}};if(!G.command||G.command.trim()==="")return{...Yc("command-validation",re),...bt};let Et=Sr("command-analysis",re,()=>yg(()=>j.analyzeCommand(G.command,{cwd:G.context.executionCwd,shell:G.route.shell,policySnapshot:pt,environment:U.environment,protectedGitMetadata:We,effectiveCapabilities:yt.capabilities,strict:yt.strict,paranoidRm:yt.paranoidRm,paranoidInterpreters:yt.paranoidInterpreters,worktreeMode:yt.worktreeMode,budget:we,...U.trace?{trace:U.trace}:{}},fI(oe),oe.store),G.command,U.trace));if(Et.decision){let Ct=!yt.strict&&(Et.decision.ruleId==="raw-text.dangerous-command"||Et.decision.reason===ui&&!dI.test(Et.decision.evidence?.segment??"")&&kn(G.command)===null);return{stage:"command-analysis",...bt,..."errorCode"in Et?{errorCode:Et.errorCode}:{},decision:Ct?{...Et.decision,unverifiedByStandardMode:!0}:Et.decision}}return{stage:"command-analysis",...bt,decision:{kind:"allow"}}}function uI(G,U){let j=[...new Set(G.filter((K)=>typeof K==="string"&&K!==""))].flatMap((K)=>U.gitMetadata(K)??[]);if(j.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(j.flatMap((K)=>K.entries))]),markerFiles:Object.freeze([...new Set(j.flatMap((K)=>K.markerFiles))]),directories:Object.freeze([...new Set(j.flatMap((K)=>K.directories))]),hooksDirectories:Object.freeze([...new Set(j.flatMap((K)=>K.hooksDirectories))])})}function mI(G){if(G.state==="ready")return{};return{configFallback:{reason:G.reason}}}function fI(G){return hn(G,"declared-command")?.program}function pI(G){try{return ie(G.input)}catch(U){let j=wi(G)?G.command:void 0;throw new p("policy-protection",Yc("policy-protection",U instanceof f?void 0:j,U),U)}}function Sr(G,U,j){try{return j()}catch(K){throw new p(G,Yc(G,K instanceof f?void 0:U,K),K)}}function Yc(G,U,j){let K=j instanceof s||j instanceof b;return{stage:G,decision:{kind:"deny",reason:K?da:ko,ruleId:K?"analysis.limit":"analysis.failed-closed",intent:"stop_and_explain",...U?{evidence:{command:U,segment:U}}:{}}}}function wi(G){return G.route.kind==="command"}
|
|
49
50
|
export{a,s,J,Pe,Be,R,nt,ze,Ce,O,D,Y,rt,c,n,Ve,Ee,T,v,pe,ot,f,P,ie,fe,it,qe,Ke,u,Ie,o,S,i,se,r,g,me,H,st,at,d,ge,he,ct,N,Z,ae,w,lt,_,h,ke,W,l,L,X,Je,Ye,M,C,I,ye,be,Ae,ut,m,e,Oe,Re,Ze,Xe,ce,Te,le,De,Q,B,Ne,xe,z,Qe,V,ee,te,ue,et,tt,E,F,Le,Me,Fe,$e,k,je,_e,Ue,y,t,ne,ve,b,x,A,dt,Ge,He,p,q};
|