cc-safety-net 2.5.2 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,48 +1,50 @@
1
1
  // cc-safety-net managed OpenClaw plugin. Do not edit. Reinstall with: npx -y cc-safety-net install --openclaw
2
- // version: 2.5.2
3
- var xl={id:"cc-safety-net",name:"CC Safety Net",description:"Block destructive commands and secret-file access before OpenClaw runs a tool."};var Ei="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",He="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",Nn="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var vi={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."},Dn={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."},V=Object.freeze({realpathAttempts:{cap:16384,...vi},processedCandidateBytes:{cap:4194304,...vi},pathEnvironmentExpansion:{cap:64,...vi},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,...Dn},trackedHeredocFiles:{cap:64,...Dn},controlFlowStates:{cap:64,...Dn},wrapperPeelIterations:{cap:20,...Dn},derivedCommandShape:Dn});class N extends Error{kind;name="AnalysisLimit";constructor(e){super(V[e].reason);this.kind=e}}function je(){let e=new Map;return{counters:e,resolvedPaths:new Map,charge(t,n=1){let r=(e.get(t)??0)+n;if(e.set(t,r),r>V[t].cap)throw new N(t)}}}var Vp=[/\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 ft(e){return Kp(e.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 Kp(e){return Vp.reduce((t,n)=>t.replace(n,"<redacted>"),e.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>")}var qp={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 Yp(e){let t=e.maxLen??200,n=e.redact??((o)=>o),r=(o)=>o.length>t?`${o.slice(0,t)}...`:o;return[e.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${n(e.reason)}`,e.ruleId?`Rule: ${e.ruleId}`:void 0,e.toolName?`Tool: ${e.toolName}`:void 0,e.command?`Command: ${r(n(e.command))}`:void 0,e.segment&&e.segment!==e.command?`Segment: ${r(n(e.segment))}`:void 0,e.cwd?`Working directory: ${r(n(e.cwd))}`:void 0,e.configWarning?`Config warning: ${n(e.configWarning)}`:void 0,e.askUser?"Approve only if you expected this command.":qp[e.intent??"manual_only"]].filter((o)=>o!==void 0).join(`
2
+ // version: 2.6.0
3
+ var Al={id:"cc-safety-net",name:"CC Safety Net",description:"Block destructive commands and secret-file access before OpenClaw runs a tool."};var wi="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Ve="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",Fn="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var _i={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."},Gn={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."},K=Object.freeze({realpathAttempts:{cap:16384,..._i},processedCandidateBytes:{cap:4194304,..._i},pathEnvironmentExpansion:{cap:64,..._i},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,...Gn},trackedHeredocFiles:{cap:64,...Gn},controlFlowStates:{cap:64,...Gn},wrapperPeelIterations:{cap:20,...Gn},derivedCommandShape:Gn});class W extends Error{kind;name="AnalysisLimit";constructor(e){super(K[e].reason);this.kind=e}}function Ae(){let e=new Map;return{counters:e,resolvedPaths:new Map,charge(t,n=1){let r=(e.get(t)??0)+n;if(e.set(t,r),r>K[t].cap)throw new W(t)}}}var rg=[/\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 mt(e){return og(e.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 og(e){return rg.reduce((t,n)=>t.replace(n,"<redacted>"),e.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>")}var ig={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 sg(e){let t=e.maxLen??200,n=e.redact??((o)=>o),r=(o)=>o.length>t?`${o.slice(0,t)}...`:o;return[e.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${n(e.reason)}`,e.ruleId?`Rule: ${e.ruleId}`:void 0,e.toolName?`Tool: ${e.toolName}`:void 0,e.command?`Command: ${r(n(e.command))}`:void 0,e.segment&&e.segment!==e.command?`Segment: ${r(n(e.segment))}`:void 0,e.cwd?`Working directory: ${r(n(e.cwd))}`:void 0,e.configWarning?`Config warning: ${n(e.configWarning)}`:void 0,e.askUser?"Approve only if you expected this command.":ig[e.intent??"manual_only"]].filter((o)=>o!==void 0).join(`
4
4
 
5
- `)}function Rl(e,t){if(e.decision.kind!=="deny")return;let n=t.includeEvidence?e.decision.evidence:void 0;return{reason:e.decision.reason,ruleId:e.decision.ruleId,intent:e.decision.intent,command:n?.command,segment:n?.segment,toolName:t.toolName,...e.configFallback?{configWarning:e.configFallback.reason}:{},...e.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function Ln(e={}){return{reason:Nn,ruleId:"analysis.failed-closed",intent:"stop_and_explain",command:e.command,segment:e.segment??e.command,toolName:e.toolName}}var Zp={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 xi(e,t={}){return{...Zp[e.directory][e.problem],command:t.command,toolName:t.toolName,cwd:e.cwd}}function _l(e){return Yp({...e,redact:ft})}function wl(e){return ft(e instanceof Error?e.message:String(e))}import{isAbsolute as Oi,relative as Rg,resolve as Kl,sep as _g}from"node:path";import{basename as Il,dirname as Xp,isAbsolute as Jp,join as Qp,normalize as eg,resolve as Al}from"node:path";var tg=256,Or=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 Se(e,t=process.platform){if(t!=="win32")return e;return e.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function Je(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function Ai(e,t){return Ri(e,0,t)}function Ri(e,t,n){let r="",o=0;while(o<e.length){if(e[o]!=="$"){r+=e[o],o++;continue}if(e[o+1]==="{"){let s=_i(e,o+2),a=ng(e,o,t);if(a===null){if(Or.has(s))throw new N("pathEnvironmentExpansion");r+=e.slice(o);break}let l=e.slice(o,a+1);r+=rg(l,t,n),o=a+1;continue}let i=_i(e,o+1);if(!i){r+="$",o++;continue}r+=wi(i,n)??`$${i}`,o+=i.length+1}return r}function ng(e,t,n){let r=1;for(let o=t+2;o<e.length;o++){if(e[o]==="\\"){o++;continue}if(e[o]==="$"&&e[o+1]==="{"){if(r++,n+r>V.pathEnvironmentExpansion.cap)throw new N("pathEnvironmentExpansion");o++;continue}if(e[o]!=="}")continue;if(r--,r===0)return o}return null}function rg(e,t,n){let r=e.slice(2,-1),o=_i(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return wi(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(Or.has(o))throw new N("pathEnvironmentExpansion");return e}if(!Or.has(o))return e;if(s.endsWith("="))throw new N("pathEnvironmentExpansion");let a=wi(o,n),l=s.startsWith(":")?a!==null&&a!=="":a!==null;if(s.endsWith("?")&&!l)throw new N("pathEnvironmentExpansion");if(s.endsWith("-")||s.endsWith("?"))return l?a??"":Ri(i.slice(s.length),t+1,n);return l?Ri(i.slice(s.length),t+1,n):""}function _i(e,t){if(!/[A-Za-z_]/.test(e[t]??""))return"";let n=t+1;while(/[A-Za-z0-9_]/.test(e[n]??""))n++;return e.slice(t,n)}function wi(e,t){if(!Or.has(e))return null;if(e==="HOME")return t.env.get("HOME")??t.home;return t.env.get(e)??null}function L(e,t,n){if(!e)return e;let r=n.resolvedPaths.get(e);if(r!==void 0)return r;let o=[],i=e;while(!0){Tl(n,i);let s=t.realpath(i);if(s!==null)return Pl(n,e,s,o);let a=Xp(i);if(a===i||o.length>=tg)return Pl(n,e,i,o);o.push(Il(i)),i=a}}function Pl(e,t,n,r){let o=r.length===0?n:Qp(n,...r.reverse());return e.resolvedPaths.set(t,o),o}function og(e,t,n){let r=n.resolvedPaths.get(e);if(r!==void 0)return r;Tl(n,e);let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function Tl(e,t){e.charge("realpathAttempts"),e.charge("processedCandidateBytes",Buffer.byteLength(t))}function ae(e,t,n,r){let o=Ol(e,t,n);if(!o)return"";return L(o,n.paths,r).replace(/\\/g,"/")}function kl(e,t,n,r,o){let i=Ol(e,t,n);if(!i)return null;if(o(Il(i)))return L(i,n.paths,r).replace(/\\/g,"/");let s=og(i,n.paths,r);return s===null?null:s.replace(/\\/g,"/")}function Ol(e,t,n){let r=n.home,o=Ai(e.trim(),n).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?Al(r,o.slice(2)):o,s=Se(i);return eg(Jp(s)?s:Al(t,s))}import{types as ig}from"node:util";var sg=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),ag=new Set(["command","diff","input","patch","patchtext"]),Ml=new TextEncoder,lg=new TextDecoder,cg=/\s/,ug=64;class Qe extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var Wn=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function dg(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function Dr(e){return sg.has(dg(e))}function Fn(e){if(!e||typeof e!=="object")return;Hl(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)Ve();return}if(t.get||t.set)Ve();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function Gl(e,t){return Fl(e,t,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Fl(e,t,n,r,o){let i=Ul(e,r,o);if(typeof e==="string")return n?[e]:[];if(!i)return[];let s=i.entries.flatMap(([a,l])=>Fl(l,t,i.array?n:t.has(zl(a)),r,o+1));return r.ancestors.delete(i.object),s}function zl(e){return e.replace(/-/g,"_").toLowerCase()}function Bl(e){return $l(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(mg)}function $l(e,t,n,r){let o=Ul(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>$l(a,o.array?t:ag.has(zl(s)),n,r+1));return n.ancestors.delete(o.object),i}function fg(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>Wn.maxDepth||t.nodes>Wn.maxNodes)Ve();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>Wn.maxStringBytes||t.stringBytes>Wn.maxAggregateStringBytes)Ve()}function Ul(e,t,n){if(fg(e,t,n),!e||typeof e!=="object")return null;let r=Hl(e);if(t.ancestors.has(e))Ve();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>Wn.maxKeys)Ve();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)Ve();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function Hl(e){if(ig.isProxy(e))Ve();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)Ve();return t}function Ve(){throw new Qe}function mg(e){let t=[],n=e.split(/\r?\n/),r=!1,o=!1,i=null,s=null,a=()=>{o=!1,i=null,s=null};for(let l=0;l<n.length;l++){let c=n[l]??"";if(c==="*** Begin Patch"){r=!0,a();continue}if(c==="*** End Patch"){r=!1,a();continue}if(c.startsWith("@@")){let u=pg(c);if(o=!0,i=u?.oldLines??null,s=u?.newLines??null,i===0&&s===0)a();continue}if(o&&i!==null&&s!==null){let u=c.startsWith(" ")||c.startsWith("-")?1:0,f=c.startsWith(" ")||c.startsWith("+")?1:0;if(i=Math.max(0,i-u),s=Math.max(0,s-f),i===0&&s===0)a();continue}if(c.startsWith("*** ")){a(),t.push(...Pi(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...Pi(c));continue}if(c.startsWith("--- ")){let u=n[l+1]??"";if(!u.startsWith("+++ "))continue;t.push(...Ti(Mr(c.slice(4),!0),Mr(u.slice(4),!0))),l++;continue}if(!r)t.push(...Pi(c))}return t}function pg(e){let t=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(e);if(!t)return null;return{oldLines:Number(t[1]??1),newLines:Number(t[2]??1)}}function Pi(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return Wl(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return Wl(n[1]);if(e.startsWith("diff --git "))return gg(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return Ll(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return Ll(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return Eg(i[1]);return[]}function gg(e){let t=hg(e);if(t.length===2&&t[0]&&t[1])return Ti(t[0],t[1]);let n=yg(e);return n?Ti(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function hg(e){let t=[],n=0;while(n<e.length&&t.length<2){while(Tt(e[n]))n++;if(n>=e.length)break;let r=e[n]==='"'||e[n]==="'"?e[n]:void 0;if(!r){let i=n;while(n<e.length&&!Tt(e[n]))n++;t.push(e.slice(i,n));continue}let o=jl(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(Tt(e[n]))n++;return n===e.length?t:[]}function yg(e){let t=0;while(t<e.length&&Tt(e[t]))t++;let n=e.length;while(n>t&&Tt(e[n-1]))n--;let r=0,o=t;while(o<n){if(!Tt(e[o])){o++;continue}let i=o;while(o<n&&Tt(e[o]))o++;if(i===t||o===n)continue;if(r++,r>ug)Ve();if(Cg(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function Cg(e,t,n,r,o){if(Ii(e,t,n,r,o))return!0;let i=Dl(e,"/",t,n),s=Dl(e,"/",r,o);if(i<=t||s<=r)return!1;if(Ii(e,t,i,r,s))return!1;return Ii(e,i+1,n,s+1,o)}function Ii(e,t,n,r,o){if(n-t!==o-r)return!1;for(let i=0;i<n-t;i++)if(e[t+i]!==e[r+i])return!1;return!0}function Dl(e,t,n,r){for(let o=n;o<r;o++)if(e[o]===t)return o;return-1}function Tt(e){return e!==void 0&&cg.test(e)}function jl(e,t,n){let r=[],o=t+1;while(o<e.length){let i=String.fromCodePoint(e.codePointAt(o)??0);if(i===n)return{value:lg.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...Ml.encode(i)),o+=i.length;continue}let s=e.slice(o+1),a=/^[0-7]{1,3}/.exec(s)?.[0];if(a){r.push(Number.parseInt(a,8)),o+=a.length+1;continue}r.push(...Ml.encode(bg(s[0]??""))),o+=2}return null}function bg(e){return{a:"\x07",b:"\b",f:"\f",n:`
6
- `,r:"\r",t:"\t",v:"\v"}[e]??e}function Sg(e){return Gn(xg(e))}function Ti(e,t){if(e==="/dev/null")return Nl(t);if(t==="/dev/null")return Nl(e);if(e.startsWith("a/")&&t.startsWith("b/"))return[e.slice(2),t.slice(2)].flatMap(Gn);let n=vg(e,t)??(e===t?Vl(e):null);return[e,t,...n?[n]:[]].flatMap(Gn)}function Nl(e){let t=Vl(e);return[e,...t?[t]:[]].flatMap(Gn)}function Vl(e){let t=e.indexOf("/");return t>0&&t<e.length-1?e.slice(t+1):null}function vg(e,t){let n=e.indexOf("/"),r=t.indexOf("/");if(n<1||r<1)return null;if(e.slice(0,n)===t.slice(0,r))return null;let o=e.slice(n+1);return o===t.slice(r+1)?o:null}function Ll(e){return Sg(Mr(e,!0))}function Eg(e){return Gn(Mr(e,!1))}function Mr(e,t){let n=e.trim(),r=n[0]==='"'||n[0]==="'"?n[0]:void 0;if(r){let o=jl(n,0,r);if(o&&(t||n.slice(o.end).trim()===""))return o.value}return t?n.split("\t",1)[0]?.trim()??"":n}function xg(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function Gn(e){return e===""||e==="/dev/null"?[]:[e]}function Wl(e){let t=e.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return t===""||t==="/dev/null"?[]:[t]}function Mi(e,t,n){if(Je(e))return;let r=t.flatMap((i)=>ki(i,n));if(!r[0])return;let o=ki(Oi(e)?e:Kl(r[0],e),n)[0];if(!o)return;return r.some((i)=>Ag(o,i))?o:void 0}function wg(e,t,n){if(Je(e))return;return ki(Oi(e)?e:Kl(t,e),n)[0]}function ql(e,t,n){return wg(e,t,n)?"outside-workspace":"unusable"}function ki(e,t){let n=t.realpath(e);if(n===null)return[];return t.isDirectory(n)?[n]:[]}function Ag(e,t){let n=Rg(t,e);return n===""||n!==".."&&!n.startsWith(`..${_g}`)&&!Oi(n)}function Yl(e,t,n,r,o){if(n.kind!=="command")return{toolName:e,input:t,route:n,context:r};return{toolName:e,input:t,route:n,context:r,command:o}}import{lstatSync as th,realpathSync as nh,statSync as rh}from"node:fs";import{homedir as oh,tmpdir as ih}from"node:os";import{statSync as Jg}from"node:fs";import{join as Qg}from"node:path";import{spawnSync as Pg}from"node:child_process";import{existsSync as Bn,lstatSync as Ig,readFileSync as $n,realpathSync as en,statSync as zn}from"node:fs";import{dirname as Di,isAbsolute as Ni,join as tn,resolve as Nr}from"node:path";var Tg=["/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"],kg=5000;function Xl(e,t=qg(),n=kg){let r=Og(e),o=r===null?null:Mg(r);if(r===null||o===null)return null;let i=Vg(r,o,t,n);return i===null?null:{recursiveSubmodules:i}}function Og(e){try{let t=en(Nr(e));return zn(t).isDirectory()?t:null}catch{return null}}function Mg(e){let t=jg(e);if(!t)return null;try{let n=Ig(t);if(n.isSymbolicLink()||!n.isFile())return null;let r=Li(t);if(!r?.commonDir)return null;if(!Lg(r.gitDir,t))return null;return Wg(r.gitDir,Di(t))?{gitDir:r.gitDir,commonDir:r.commonDir}:null}catch{return null}}function Li(e){try{let t=Dg(e);if(!t)return null;let n=en(Ni(t)?t:Nr(Di(e),t));if(!zn(n).isDirectory())return null;return{gitDir:n,commonDir:Ng(n)}}catch{return null}}function Dg(e){let t=$n(e,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!t.startsWith("gitdir:"))return null;return t.slice(7).trim()||null}function Ng(e){try{let t=$n(tn(e,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!t)return null;let n=en(Ni(t)?t:Nr(e,t));return zn(n).isDirectory()?n:null}catch{return null}}function Lg(e,t){let n=Gg(e);return n===null?!1:Jl(e,n,t)}function Wg(e,t){let n=Fg(e);return n===null?!0:Jl(e,n,t)}function Gg(e){let t=tn(e,"gitdir");if(!Bn(t))return null;let n=$n(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return n===""?null:n}function Fg(e){let t=tn(e,"config.worktree");return Bn(t)?Bg(t):null}function Jl(e,t,n){try{return zg(Ni(t)?t:Nr(e,t),n)}catch{return!1}}function zg(e,t){try{let n=zn(e),r=zn(t);if(n.ino!==0&&r.ino!==0&&n.dev===r.dev&&n.ino===r.ino)return!0}catch{}return Zl(en.native(e))===Zl(en.native(t))}function Zl(e){let t=e.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),n=t.length>1&&t.endsWith("/")?t.slice(0,-1):t;return process.platform==="win32"?n.toLowerCase():n}function Bg(e){let t=$n(e,"utf-8"),n=!1,r=null;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i===""||i.startsWith("#")||i.startsWith(";"))continue;if(i.startsWith("[")){n=/^\[core\]$/i.test(i);continue}if(!n)continue;let s=i.match(/^worktree\s*=\s*(.*)$/i);if(s)r=$g(s[1]??"")}return r}function $g(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;return Hg(t.slice(1,-1))}var Ug={"\\":"\\",'"':'"',n:`
7
- `,t:"\t",b:"\b"};function Hg(e){return e.replace(/\\(.?)/gs,(t,n)=>n===""?t:Ug[n]??t)}function jg(e){try{return Wi(en(e))}catch{return null}}function Wi(e){let t=e;while(!0){let n=tn(t,".git");if(Bn(n))return n;let r=Di(t);if(r===t)return null;t=r}}function Vg(e,t,n,r){if(Kg(t))return!0;if(n===null)return!0;let o=Pg(n,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:Yg(process.env),stdio:["ignore","pipe","ignore"],timeout:r});if(o.error!==void 0||o.status!==0&&o.status!==1)return null;return o.status===0&&Ql(o.stdout.trim())}function Kg(e){return[tn(e.commonDir,"config"),tn(e.gitDir,"config.worktree")].filter((t)=>Bn(t)).some((t)=>Zg(t))}function qg(){return Tg.find((e)=>Bn(e))??null}function Un(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function Yg(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Un(t)))}function Zg(e){let t;try{t=$n(e,"utf-8")}catch{return!0}let n="",r=!1;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i===""||i.startsWith("#")||i.startsWith(";"))continue;let s=i.match(/^\[([^\]]+)\]$/);if(s){n=s[1]?.trim().toLowerCase()??"";continue}let a=i.indexOf("="),l=(a===-1?i:i.slice(0,a)).trim().toLowerCase(),c=a===-1?"true":i.slice(a+1).trim();if(Xg(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=Ql(c)}return r}function Xg(e){return e==="include"||e.startsWith("includeif ")}function Ql(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function ec(e,t){if(e==="")return null;let n=je(),r=Wi(ae(e,e,t,n)),o=r?eh(r,e,t,n):null;if(!o)return null;return Object.freeze({entries:Object.freeze([o.entry]),markerFiles:Object.freeze(o.markerFile?[o.markerFile]:[]),directories:Object.freeze(o.directories),hooksDirectories:Object.freeze(o.hooksDirectories)})}function eh(e,t,n,r){try{let o=ae(e,t,n,r),i=Jg(e),s=i.isFile()?o:null,a=i.isFile()?Li(e):null,l=(i.isDirectory()?[o]:[a?.gitDir,a?.commonDir]).flatMap((u)=>u?[nn(ae(u,t,n,r))]:[]),c=[...new Set(i.isDirectory()?[nn(e.replace(/\\/g,"/")),...l]:l)];return{entry:nn(o),markerFile:s?nn(s):null,directories:c,hooksDirectories:[...new Set(c.flatMap((u)=>{let f=nn(Qg(u,"hooks").replace(/\\/g,"/"));return[f,nn(ae(f,t,n,r))]}))]}}catch{return null}}function nn(e){return process.platform==="win32"?e.toLowerCase():e}var sh={realpath:(e)=>{try{return nh(e)}catch{return null}},entryKind:(e)=>{let t=th(e,{throwIfNoEntry:!1});if(!t)return"missing";return t.isSymbolicLink()?"symlink":"present"},isDirectory:(e)=>{try{return rh(e).isDirectory()}catch{return!1}}};function nc(){return ah({env:new Map(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),home:Se(process.env.HOME||oh()),tmpdir:ih(),paths:sh})}function ah(e,t={}){let n=new Map,r=new Map,o={...e,gitMetadata:(i)=>tc(n,i,()=>ec(i,o)),worktreeFacts:(i)=>tc(r,i,()=>Xl(i)),...t};return o}function tc(e,t,n){let r=e.get(t);if(r!==void 0)return r;let o=n();return e.set(t,o),o}var rn=["fail_closed","paranoid_rm","paranoid_interpreters"],Lr={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 Z={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"}},Wr=["standard","strict","paranoid"];function rc(e,t){if(!t)return e;return Wr.indexOf(t)>Wr.indexOf(e)?t:e}function oc(e){let t=Gr(Z.level,e);return Wr.find((n)=>n===t)}function ic(e,t){return rc(e,oc(t))}function lh(e){let t=Gr(Z.level,e);if(!t)return;let n=oc(e);if(n)return n;console.error(`CC Safety Net: ignored invalid ${Z.level.name}=${JSON.stringify(t.slice(0,40))}. Use ${Wr.join(", ")}.`);return}function ch(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function sc(e){return ch(Gr(Z.auditScope,e))==="all"}function Fi(e){if(e.failClosed&&e.paranoidRm&&e.paranoidInterpreters)return"paranoid";if(e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"strict";if(!e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"standard";return"custom"}function zi(e={},t){let n=e.safety?.level??"standard",r=lh(t),o=rc(n,r),i=Lr[o],s={failClosed:i.fail_closed,paranoidRm:i.paranoid_rm,paranoidInterpreters:i.paranoid_interpreters},a={failClosed:o===n?"preset":"environment",paranoidRm:o===n?"preset":"environment",paranoidInterpreters:o===n?"preset":"environment"},l={failClosed:[`policy safety.level=${n}`],paranoidRm:[`policy safety.level=${n}`],paranoidInterpreters:[`policy safety.level=${n}`]};if(o!==n)l.failClosed.push(`env ${Z.level.name}=${r}`),l.paranoidRm.push(`env ${Z.level.name}=${r}`),l.paranoidInterpreters.push(`env ${Z.level.name}=${r}`);if(e.safety?.overrides?.failClosed!==void 0)s.failClosed=e.safety.overrides.failClosed,a.failClosed="capability_override",l.failClosed.push("policy safety.overrides.fail_closed");if(e.safety?.overrides?.paranoidRm!==void 0)s.paranoidRm=e.safety.overrides.paranoidRm,a.paranoidRm="capability_override",l.paranoidRm.push("policy safety.overrides.paranoid_rm");if(e.safety?.overrides?.paranoidInterpreters!==void 0)s.paranoidInterpreters=e.safety.overrides.paranoidInterpreters,a.paranoidInterpreters="capability_override",l.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(et(Z.strict,t))s.failClosed=!0,a.failClosed="environment",l.failClosed.push(`env ${Z.strict.name}`);if(et(Z.paranoid,t))s.paranoidRm=!0,s.paranoidInterpreters=!0,a.paranoidRm="environment",a.paranoidInterpreters="environment",l.paranoidRm.push(`env ${Z.paranoid.name}`),l.paranoidInterpreters.push(`env ${Z.paranoid.name}`);if(et(Z.paranoidRm,t))s.paranoidRm=!0,a.paranoidRm="environment",l.paranoidRm.push(`env ${Z.paranoidRm.name}`);if(et(Z.paranoidInterpreters,t))s.paranoidInterpreters=!0,a.paranoidInterpreters="environment",l.paranoidInterpreters.push(`env ${Z.paranoidInterpreters.name}`);let c=!!e.worktreeMode||et(Z.worktree,t);return{strict:s.failClosed,paranoidRm:s.paranoidRm,paranoidInterpreters:s.paranoidInterpreters,worktreeMode:c,effectiveLevel:Fi(s),capabilities:{fail_closed:{enabled:s.failClosed,source:a.failClosed,sources:l.failClosed},paranoid_rm:{enabled:s.paranoidRm,source:a.paranoidRm,sources:l.paranoidRm},paranoid_interpreters:{enabled:s.paranoidInterpreters,source:a.paranoidInterpreters,sources:l.paranoidInterpreters}}}}function et(e,t){let n=typeof e==="string"?Gi(e,t):Gr(e,t);return n==="1"||n?.toLowerCase()==="true"}function Gi(e,t){return t.get(e)}function Gr(e,t){let n=Gi(e.name,t);if(n!==void 0)return n;if(e.legacyName)return Gi(e.legacyName,t);return}import{dirname as Kr}from"node:path";import{closeSync as uh,constants as ac,fstatSync as dh,fsyncSync as rI,lstatSync as Ui,mkdirSync as oI,openSync as fh,readdirSync as iI,readFileSync as mh,realpathSync as Hi,renameSync as sI,rmdirSync as aI,statSync as ph,unlinkSync as lI,writeFileSync as cI}from"node:fs";import{isAbsolute as lc,join as ji,normalize as gh,parse as $i,relative as Vi,resolve as Ki,sep as qi}from"node:path";function Bi(){let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${e()}${e()}`}var hh=Symbol("PolicyFilesystemScope"),yh=Symbol("PolicyFilesystemTarget"),Ch=ac.O_NOFOLLOW??0;class le extends Error{name="PolicyFilesystemError";constructor(e){super(`Unable to access ${e} filesystem safely.`)}}function kt(e,t){return{[hh]:!0,root:Ki(e),label:t}}function cc(e,t){let n=gh(t);if(t===""||lc(t)||n===".."||n.startsWith(`..${qi}`))throw new le(e.label);return{[yh]:!0,scope:e,relativePath:n,path:ji(e.root,n)}}function Hn(e,t){return cc(e,Vi(e.root,Ki(t)))}function uc(e,t="rules policy"){let n=Ki(e),r=$i(n).dir;return cc(kt(r,t),Vi(r,n))}function zr(e){return fc(e.scope.label,()=>{if(!Fr(e))return null;let t=fh(e.path,ac.O_RDONLY|Ch);return bh(t,()=>{let n=dh(t);if(!n.isFile())throw new le(e.scope.label);let r=mh(t,"utf-8"),o=Ui(e.path);if(!o.isFile()||o.isSymbolicLink()||n.dev!==o.dev||n.ino!==o.ino)throw new le(e.scope.label);return Fr(e),r})})}function dc(e,t){if(e.path===t.path)return!0;return fc(e.scope.label,()=>{if(!Fr(e)||!Fr(t))return!1;let n=(r)=>ji(Hi($i(r).dir),$i(r).base);return n(e.path)===n(t.path)})}function fc(e,t,n){try{return t()}catch(r){if(n?.(),r instanceof le)throw r;throw new le(e)}}function bh(e,t){try{return t()}finally{uh(e)}}function Fr(e,t="file"){let n=Sh(e.scope);if(!n)return!1;let r=e.relativePath.split(qi);for(let o of r.keys()){let i=ji(e.scope.root,...r.slice(0,o+1)),s=Ui(i,{throwIfNoEntry:!1});if(!s)return!1;if(s.isSymbolicLink())throw new le(e.scope.label);if(o<r.length-1&&!s.isDirectory())throw new le(e.scope.label);if(o===r.length-1&&(t==="file"?!s.isFile():!s.isDirectory()))throw new le(e.scope.label);vh(n,Hi(i),e.scope.label)}return!0}function Sh(e){if(!Ui(e.root,{throwIfNoEntry:!1}))return null;if(!ph(e.root).isDirectory())throw new le(e.label);return Hi(e.root)}function vh(e,t,n){let r=Vi(e,t);if(r===".."||r.startsWith(`..${qi}`)||lc(r))throw new le(n)}import{dirname as Mt,isAbsolute as wh,join as Nt,relative as Ah,resolve as Dt,sep as Ph}from"node:path";var Ot=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,mc="rulebook.json",pc=".cc-safety-net/rules";var gc=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/;var Eh=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,xh=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Rh="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),mI=new RegExp(`^${xh}/(${Ot.source.slice(1,-1)})/${Rh}$`);function _h(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function hc(e){if(Br(e))try{return Yi(e),null}catch(t){return t instanceof Error?t.message:String(t)}return Ot.test(e)?null:`Local rulebook sources must be bare names matching ${Ot}: ${e}`}function Yi(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(gc);if(!t?.[1]||!t[2]||!t[3])throw Error(`Invalid GitHub rulebook source: ${e}`);let n=t[3].lastIndexOf("/");if(n<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);let r=t[3].slice(0,n),o=t[3].slice(n+1);if(!r||!Eh.test(r))throw Error(`GitHub rulebook refs must use valid path segments: ${e}`);if(!o||!Ot.test(o))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);return{owner:t[1],repo:t[2],ref:r,path:_h(o),name:o}}function Br(e){return gc.test(e)}var yc="rule.json",$r="policy.json",Cc=".cc-safety-net",Ih="rules",Th="CC_SAFETY_NET_HOME",bc="`cc-safety-net rule update`";function kh(e){return Dt(e,pc)}function Oh(e){return Nt(kh(e),yc)}function jn(e){return Nt(Dt(e),Cc,$r)}function Zi(e,t={}){return t.userConfigDir??(t.userConfigPath?Mt(t.userConfigPath):Nt(Mh(e),Ih))}function Mh(e){let t=e.env.get(Th);return t?Dt(Se(t)):Nt(e.home,Cc)}function Dh(e,t={}){return Nt(Zi(e,t),yc)}function on(e,t={}){return Nt(Mt(Zi(e,t)),$r)}function Sc(e,t){let n=t.userConfigPath??Dh(e,t),r=t.projectConfigPath??Oh(t.cwd),o=Nh(e,t),i=Lh(r,t.cwd);return{userConfigPath:n,projectConfigPath:r,userScope:o,projectScope:i,userConfigTarget:Hn(o,n),projectConfigTarget:Hn(i,r)}}function Nh(e,t){let n=t.userConfigPath?Mt(Mt(Dt(t.userConfigPath))):Mt(Dt(t.userConfigDir??Zi(e,t)));return kt(n,"user policy")}function Lh(e,t){let n=Dt(t),r=Dt(e),o=Ah(n,r);if(o!==".."&&!o.startsWith(`..${Ph}`)&&!wh(o))return kt(n,"project policy");return kt(Mt(Mt(r)),"project policy")}function vc(e,t){return Nt(e,t,mc)}var ve=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),mt=/^[a-zA-Z][a-zA-Z0-9_-]*$/,pt=256,q=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Ec=new Set(["python","python3","python2","node","ruby","perl"]),Ur=/^python(?:[23](?:\.\d+)*)?$/,Ae=new Set(["awk","gawk","nawk","mawk"]),Hr=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 xc="Rulebook exceeds CC Safety Net's safe validation limits.",Rc="Additional rulebook validation errors were omitted.",ke=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function _c(e){if(Xi(e.allowed_commands,ke.maxAllowedCommands)||Xi(e.rules,ke.maxRules)||Xi(e.tests,ke.maxTests))return!1;let{maxAggregateStringCodeUnits:t,maxTotalBlockArgs:n}=ke,r=(o,i=!1)=>{if(typeof o!=="string")return!0;if(o.length>ke.maxStringCodeUnits||i&&o.length>ke.maxFixtureCommandCodeUnits||o.length>t)return!1;return t-=o.length,!0};if(!r(e.name)||!r(e.version)||!r(e.description)||!r(e.author)||!r(e.migrated_from))return!1;if(Array.isArray(e.allowed_commands)){for(let o of e.allowed_commands)if(!r(o))return!1}if(Array.isArray(e.rules))for(let o of e.rules){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.name)||!r(i.command)||!r(i.subcommand)||!r(i.reason)||!r(i.intent))return!1;let s=i.match&&typeof i.match==="object"?i.match:{};for(let a of[i.block_args,s.command_path,s.any_args,s.exclude_args]){if(!Array.isArray(a))continue;if(a.length>ke.maxBlockArgsPerRule||a.length>n)return!1;n-=a.length;for(let l of a)if(!r(l))return!1}}if(Array.isArray(e.tests))for(let o of e.tests){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.command,!0)||!r(i.expect)||!r(i.rule))return!1}return!0}function Xi(e,t){return Array.isArray(e)&&e.length>t}var Ji=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var Qi=64,es="Rule config exceeds CC Safety Net's safe source limit.";function k(e){return A(e).toLowerCase()}function A(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}function fe(e,t){let n=new Set,r=!1;for(let o of e){if(o==="--"){r=!0;continue}if(r)continue;if(o.startsWith("-")&&!o.startsWith("--")&&o.length>1)for(let i=1;i<o.length;i++){let s=o[i];if(!s||!/[a-zA-Z]/.test(s))break;let a=`-${s}`;if(n.add(a),t?.shortOptsWithValue?.has(a))break}}return n}var Wh={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},ts=new Set(["--init-file","--rcfile"]);function ns(e,t,n,r){let o=!1,i=0,s=!1,a=!1,l=!1;for(let c=1;c<t.length;c++){let u=t[c];if(u===void 0)break;if(e==="ksh"&&u==="o"&&c+1<t.length){if(r==="argv"){let f=t.slice(c+1);if(t[0]==="-"&&(f==="c"||f[0]==="-"&&f.endsWith("c")))s=!0}break}if(e==="ksh"&&u==="o"&&c+1===t.length&&(n?.startsWith("-")||n?.startsWith("+")))break;if(e==="zsh"&&u==="o"&&c+1<t.length)break;if(r==="startup"&&u==="i")o=t[0]==="-";if(r==="argv"&&t[0]==="-"&&u==="c")s=!0;if(r==="argv"&&u==="n")l=t[0]==="-";if(r==="argv"&&u==="s")a=t[0]==="-";if(!Wh[e]?.includes(u))continue;if(c+1===t.length)i++;break}return{interactive:o,followingValues:i,commandSelected:s,stdinMode:a,syntaxCheck:l}}function Ee(e){let t=A(e[0]??"").toLowerCase(),n=!1,r=!1,o=!1;for(let i=1;i<e.length;i++){let s=e[i];if(s===void 0)break;if(s==="--"){let l=n&&e[i+1]!==void 0?i+1:null;return{command:l===null?null:e[l]??null,commandIndex:l,scriptIndex:!n&&!r&&e[i+1]!==void 0?i+1:null,readsStdinAsCommands:!n&&(r||e[i+1]===void 0),syntaxCheck:o}}if(s==="-"||s[0]!=="-"&&s[0]!=="+")return{command:n?s:null,commandIndex:n?i:null,scriptIndex:!n&&!r&&s!=="-"?i:null,readsStdinAsCommands:!n&&(r||s==="-"),syntaxCheck:o};if(s.startsWith("--")){let l=s.split("=",1)[0]??s;if(t==="bash"&&ts.has(l)&&!s.includes("="))i++;continue}let a=ns(t,s,e[i+1],"argv");if(a.commandSelected)n=!0;if(a.syntaxCheck)o=!0;if(a.stdinMode)r=!0;i+=a.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!n,syntaxCheck:o}}function Vn(e,t){if(t.escaped)return t.escaped=!1,!0;if(e==="\\"&&!t.inSingle)return t.escaped=!0,!0;if(e==="'"&&!t.inDouble)return t.inSingle=!t.inSingle,!0;if(e==='"'&&!t.inSingle)return t.inDouble=!t.inDouble,!0;return!1}function jr(e){let t={inSingle:!1,inDouble:!1,escaped:!1};for(let n of Gh(e))Vn(n,t);return t.inSingle||t.inDouble}function Gh(e){let t="",n={inSingle:!1,inDouble:!1,escaped:!1},r=!1,o=!0;for(let i=0;i<e.length;i++){let s=e[i];if(!s)break;if(r){if(s===`
8
- `||s==="\r")t+=s,r=!1,n.escaped=!1;continue}if(s==="#"&&!n.inSingle&&!n.inDouble&&o){r=!0;continue}if(t+=s,!n.inSingle&&!n.inDouble&&!n.escaped)o=/[\s;&|()<>]/.test(s);Vn(s,n)}return t}var rs=new Set(["rm","find","xargs","parallel"]),Fh=new Set(["git","busybox",...rs,...q,...Ec,...Ae]),zh=new Set(["python","node","ruby","perl"]);function wc(e){let t=k(e);return Fh.has(t)||Oe(t)}function Oe(e){return zh.has(Bh(e))}function Bh(e){let t=A(e).toLowerCase();return Ur.test(t)?"python":t}function os(e){try{let t=zr($h(e));if(t===null)return{config:null,errors:[]};if(!t.trim())return{config:null,errors:["Config file is empty"]};let n=JSON.parse(t),r=jh(n);if(r.errors.length>0)return{config:null,errors:r.errors};return{config:{version:1,rules:n.rules??[],overrides:n.overrides??{},transparent_wrappers:n.transparent_wrappers??[]},errors:[]}}catch(t){if(t instanceof le)return{config:null,errors:[t.message]};let n=t instanceof Error?t.message:String(t);return{config:null,errors:[t instanceof SyntaxError?"Invalid JSON":n]}}}function $h(e){return typeof e==="string"?uc(e):e}var R=(e,t)=>({path:e,message:t,kind:"typed"}),ne=(e,t)=>({path:e,message:t,kind:"custom"});function Ac(e){let t=new Set;return e.flatMap((n,r)=>{let o=sn(n)?n.name:void 0;if(typeof o!=="string")return[];if(t.has(o.toLowerCase()))return[ne(["rules",r,"name"],`duplicate rule name "${o}"`)];return t.add(o.toLowerCase()),[]})}var is=`must be one of ${Ji.join(", ")}`,Uh=/^[^/]+\/[^/]+$/,Hh=["version","rules","overrides","transparent_wrappers"];function jh(e){let t=Vh(e);return{errors:ss(ty(t,Hh,(n)=>n.kind==="custom"),": "," "),sources:ey(e,t)}}function Vh(e){if(!sn(e))return[R([],"Config must be an object")];let t=Array.isArray(e.rules)&&e.rules.length>Qi;return[...e.version===1?[]:[R(["version"],"must be 1")],...Kh(e.rules,t),...Zh(e.overrides),...Jh(e.transparent_wrappers),...t?[]:Yh(e.rules),...sn(e.overrides)?Object.keys(e.overrides).filter((n)=>!Uh.test(n)).map((n)=>ne(["overrides",n],"must use <rulebook-name>/<rule-name>")):[],...Qh(e.transparent_wrappers)]}function Kh(e,t){if(e===void 0)return[];if(!Array.isArray(e))return[R(["rules"],"must be an array of rulebook source strings"),...Pc(e,Qi)?[R(["rules"],es)]:[]];if(t)return[{path:["rules"],message:es,kind:"limit"}];return e.flatMap((n,r)=>{if(typeof n!=="string")return[R(["rules",r],"must be a rulebook source string"),...qh(n,1)?[R(["rules",r],"must be a non-empty rulebook source string")]:[]];return n===""?[R(["rules",r],"must be a non-empty rulebook source string")]:[]})}function Pc(e,t){let n=Ic(e);return n!==void 0&&!(n<=t)}function qh(e,t){let n=Ic(e);return n!==void 0&&!(n>=t)}function Ic(e){if(e===null||e===void 0)return;let t=e.length;return t===void 0?void 0:Number(t)}function Yh(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||n==="")return[];if(n.trim()==="")return[ne(["rules",r],"must be a non-empty rulebook source string")];let o=hc(n);if(o)return[ne(["rules",r],o)];if(t.has(n))return[ne(["rules",r],`duplicate rulebook source "${n}"`)];return t.add(n),[]})}function Zh(e){if(e===void 0)return[];if(!sn(e))return[R(["overrides"],"must be an object if provided")];return Object.keys(e).flatMap((t)=>{let n=e[t];if(n==="off")return[];if(!sn(n))return[R(["overrides",t],'must be "off" or an object')];return[...Xh(n.reason,["overrides",t,"reason"]),...n.intent===void 0||ls(n.intent)?[]:[R(["overrides",t,"intent"],is)]]})}function Xh(e,t){if(typeof e!=="string")return[R(t,"required non-empty string"),...Pc(e,pt)?[R(t,`must be at most ${pt} characters`)]:[]];if(e==="")return[R(t,"required non-empty string")];return e.length>pt?[R(t,`must be at most ${pt} characters`)]:[]}function Jh(e){if(e===void 0)return[];if(!Array.isArray(e))return[R(["transparent_wrappers"],"must be an array of command strings")];return e.flatMap((t,n)=>{if(typeof t!=="string")return[R(["transparent_wrappers",n],"must be a command string")];return mt.test(t)?[]:[R(["transparent_wrappers",n],"must match command pattern")]})}function Qh(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||!mt.test(n))return[];if(t.has(n))return[ne(["transparent_wrappers",r],`duplicate command "${n}"`)];if(wc(n))return[ne(["transparent_wrappers",r],`reserved command "${n}" cannot be a wrapper`)];return t.add(n),[]})}function ey(e,t){let n=sn(e)?e.rules:void 0;if(!Array.isArray(n))return new Set;if(t.some((o)=>o.path.length===1&&o.path[0]==="rules"))return new Set;let r=new Set(t.filter((o)=>o.path[0]==="rules"&&typeof o.path[1]==="number").map((o)=>o.path[1]));return new Set(n.filter((o,i)=>typeof o==="string"&&!r.has(i)))}function ty(e,t,n){let r=e.map((s)=>s.path[1]),o=[...new Set(r.filter((s)=>typeof s==="string"))],i=(s,a)=>[s.path.length===0?-1:t.indexOf(String(s.path[0])),typeof a==="number"?a:o.indexOf(String(a)),n(s)?0:1];return e.map((s,a)=>({issue:s,rank:i(s,r[a])})).sort((s,a)=>s.rank[0]-a.rank[0]||s.rank[1]-a.rank[1]||s.rank[2]-a.rank[2]).map((s)=>s.issue)}function ss(e,t,n){return[...new Set(e.map((r)=>{let o=as(r.path);if(r.kind==="unknownKeys")return`${o?`${o}.`:""}unknown field "${r.message}"`;if(r.kind==="key"||r.kind==="limit"||r.path.length===0)return r.message;return`${o}${r.path.length===1?n:t}${r.message}`}))]}function as(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function ls(e){return Ji.includes(e)}function sn(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function kc(e){let t=oy(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}var ny=`required non-empty string up to ${pt} characters`,Tc="must be a non-empty array of unique non-empty strings",ry="required non-empty array of non-empty strings";function oy(e){if(!gt(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!_c(e))return{errors:[xc],ruleNames:new Set};let t=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...ss(iy(e,e.rulebook_version===2),": ",": ")];return{errors:t.length>ke.maxValidationErrors?[...t.slice(0,ke.maxValidationErrors),Rc]:t,ruleNames:new Set(Oc(e).map((n)=>n.toLowerCase()))}}function Oc(e){let t=gt(e)?e.rules:void 0;return(Array.isArray(t)?t:[]).flatMap((n)=>{let r=gt(n)?n.name:void 0;return typeof r==="string"?[r]:[]})}function iy(e,t){return[...typeof e.name==="string"&&Ot.test(e.name)?[]:[R(["name"],"required string matching rule name pattern")],...typeof e.version==="string"&&e.version!==""?[]:[R(["version"],"required non-empty string")],...sy(e.allowed_commands),...ay(e.rules,t),...dy(e.tests),...fy(e),...my(e)]}function sy(e){if(!Array.isArray(e))return[R(["allowed_commands"],"required array")];let t=new Set;return[...e.flatMap((n,r)=>typeof n==="string"&&mt.test(n)?[]:[R(["allowed_commands",r],"must match command pattern")]),...e.flatMap((n,r)=>{if(typeof n!=="string"||!mt.test(n))return[];if(t.has(n))return[ne(["allowed_commands",r],`duplicate command "${n}"`)];return t.add(n),[]})]}function ay(e,t){if(!Array.isArray(e))return[R(["rules"],"required array")];return[...e.flatMap((n,r)=>{if(!gt(n))return[R(["rules",r],"must be an object")];return t?cy(n,["rules",r]):ly(n,["rules",r])}),...Ac(e)]}function ly(e,t){return[...Mc(e.name,t),...Dc(e.command,t),...e.subcommand===void 0||typeof e.subcommand==="string"&&mt.test(e.subcommand)?[]:[R([...t,"subcommand"],"must match command pattern")],...Vr(e.block_args,[...t,"block_args"],"required non-empty array",!1),...Nc(e.reason,t),...Lc(e.intent,t)]}function cy(e,t){return[...Mc(e.name,t),...Dc(e.command,t),...Nc(e.reason,t),...Lc(e.intent,t),...uy(e.match,[...t,"match"]),...e.subcommand===void 0?[]:[R([...t,"subcommand"],"not supported in rulebook_version 2")],...e.block_args===void 0?[]:[R([...t,"block_args"],"not supported in rulebook_version 2")]]}function Mc(e,t){if(typeof e!=="string")return[R([...t,"name"],"required string")];return Ot.test(e)?[]:[R([...t,"name"],"must match rule name pattern")]}function Dc(e,t){return typeof e==="string"&&mt.test(e)?[]:[R([...t,"command"],"required string matching command pattern")]}function Nc(e,t){return typeof e==="string"&&e!==""&&e.length<=pt?[]:[R([...t,"reason"],ny)]}function Lc(e,t){return e===void 0||ls(e)?[]:[R([...t,"intent"],is)]}function uy(e,t){if(!gt(e))return[R(t,"required object")];return[...Vr(e.command_path,[...t,"command_path"],ry,!1),...e.any_args===void 0?[]:Vr(e.any_args,[...t,"any_args"],Tc,!0),...e.exclude_args===void 0?[]:Vr(e.exclude_args,[...t,"exclude_args"],Tc,!0)]}function Vr(e,t,n,r){if(!Array.isArray(e))return[R(t,n)];let o=e.flatMap((i,s)=>{if(typeof i!=="string")return[R([...t,s],"must be a non-empty string")];return i===""?[ne([...t,s],"must be a non-empty string")]:[]});if(e.some((i)=>typeof i!=="string"))return o;return[...o,...e.length===0?[ne(t,n)]:[],...r&&new Set(e).size!==e.length?[ne(t,"must not contain duplicate values")]:[]]}function dy(e){if(e===void 0)return[];if(!Array.isArray(e))return[R(["tests"],"must be an array if provided")];return e.flatMap((t,n)=>{if(!gt(t))return[R(["tests",n],"must be an object")];return[...typeof t.command==="string"&&t.command.trim()!==""?[]:[R(["tests",n,"command"],"required non-empty string")],...t.expect==="blocked"||t.expect==="allowed"?[]:[R(["tests",n,"expect"],'must be "blocked" or "allowed"')],...t.rule===void 0||typeof t.rule==="string"?[]:[R(["tests",n,"rule"],"must be a string if provided")],...t.expect==="blocked"&&typeof t.rule!=="string"?[ne(["tests",n,"rule"],"required string for blocked fixtures")]:[]]})}function fy(e){if(!Array.isArray(e.tests))return[];let t=new Set(Oc(e));return[...new Set(e.tests.flatMap((n)=>gt(n)&&n.expect==="blocked"&&typeof n.rule==="string"?[n.rule]:[]))].filter((n)=>!t.has(n)).map((n)=>ne(["tests"],`blocked fixture references unknown rule "${n}"`))}function my(e){if(!Array.isArray(e.allowed_commands)||!Array.isArray(e.rules))return[];let t=new Set(e.allowed_commands.filter((n)=>typeof n==="string"));return e.rules.flatMap((n,r)=>{let o=gt(n)?n.command:void 0;if(typeof o!=="string"||t.has(o))return[];return[ne(["rules",r,"command"],`"${o}" must be listed in allowed_commands`)]})}function gt(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function $c(e,t){let n=Sc(e,t),r;try{r=dc(n.userConfigTarget,n.projectConfigTarget)}catch(m){if(m instanceof le)return Ey(n,m.message);throw m}let o=os(n.userConfigTarget),i=r?{config:null,errors:[]}:os(n.projectConfigTarget),s=zc(n.userConfigPath,o.errors),a=zc(n.projectConfigPath,i.errors),l=new Set,c=o.config?Wc(o.config,Kr(n.userConfigPath),"user",n.userScope,l):Bc(),u=i.config?Wc(i.config,Kr(n.projectConfigPath),"project",n.projectScope,l):Bc(),f=o.config?.overrides??{},d=i.config?.overrides??{};return{rules:[...Gc(c.rules,f),...Gc(u.rules,d)],transparent_wrappers:Sy(o.config,i.config),rulebooks:[...c.rulebooks,...u.rulebooks],errors:[...s,...a,...c.errors,...u.errors],warnings:[...c.warnings,...u.warnings,...c.canValidateOverrides?Fc(f,c.knownRuleIds,n.userConfigPath):[],...c.canValidateOverrides?vy(d,c.knownRuleIds,n.projectConfigPath):[],...u.canValidateOverrides?Fc(d,u.knownRuleIds,n.projectConfigPath):[]],userConfig:o.config??void 0,projectConfig:i.config??void 0,...n}}function Wc(e,t,n,r=kt(Kr(Kr(t)),n==="user"?"user policy":"project policy"),o=new Set){let i=[],s=[],a=e.rules.flatMap((c)=>{let u=gy(c,t,r);if(u.errors.length>0||!u.rulebook)return i.push(...u.errors),[];let f=u.rulebook;if(o.has(f.name))return s.push(`duplicate active rulebook name "${f.name}" for ${c}; 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 o.add(f.name),[{rules:py(f),rulebook:{source:n,spec:c,name:f.name,version:f.version,rules:f.rules.map((d)=>`${f.name}/${d.name}`)}}]}),l=a.flatMap((c)=>c.rules);return{rules:l,rulebooks:a.map((c)=>c.rulebook),knownRuleIds:new Set(l.map((c)=>c.name)),errors:i,warnings:s,canValidateOverrides:i.length===0}}function py(e){if(e.rulebook_version===2)return e.rules.map((t)=>({name:`${e.name}/${t.name}`,command:t.command,block_args:[],match:t.match,reason:t.reason,intent:t.intent}));return e.rules.map((t)=>({...t,name:`${e.name}/${t.name}`,match:void 0}))}function gy(e,t,n){let r=hy(e),o=vc(t,r),i=Cy(o,n);if("error"in i)return{rulebook:null,errors:[i.error]};if(i.content===null)return{rulebook:null,errors:[`missing rulebook file ${o} for ${e}; ${yy(e)}`]};let s=by(i.content);if("problem"in s)return{rulebook:null,errors:[`invalid rulebook ${o}: ${s.problem}; fix that file`]};if(s.rulebook.name!==r)return{rulebook:null,errors:[`rulebook name "${s.rulebook.name}" in ${o} must match source "${e}"; fix that file`]};return{rulebook:s.rulebook,errors:[]}}function hy(e){return Br(e)?Yi(e).name:e}function yy(e){return Br(e)?`run ${bc} to vendor ${e}`:"create that file or remove that source from the rules config"}function Cy(e,t){try{return{content:zr(Hn(t,e))}}catch(n){if(n instanceof le)return{error:n.message};throw n}}function by(e){let t;try{t=JSON.parse(e)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:kc(t)}}catch(n){return{problem:n instanceof Error?n.message:"invalid rulebook"}}}function Sy(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function Gc(e,t){return e.flatMap((n)=>{let r=t[n.name];if(r==="off")return[];if(r&&typeof r==="object")return[{...n,intent:r.intent??n.intent,reason:r.reason}];return[n]})}function Fc(e,t,n){return Object.keys(e).filter((r)=>!t.has(r)).map((r)=>`unknown override key "${r}" in ${n}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function vy(e,t,n){return Object.keys(e).filter((r)=>t.has(r)).map((r)=>`project override cannot target user-scoped rule "${r}" in ${n}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function zc(e,t){return t.map((n)=>n.startsWith("Unable to access ")?n:`${e}: ${n}`)}function Ey(e,t){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath}}function Bc(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as Dy,readFileSync as Ny}from"node:fs";var Uc=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores, with or without --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"find.delete",category:"Filesystem",label:"find delete",description:"Blocks unsafe find -delete operations.",example:"find . -delete",intent:"scope_down"},{id:"find.delete-git-metadata",category:"Filesystem",label:"find delete Git metadata",description:"Blocks find -delete operations selecting protected Git metadata and hooks.",example:"find .git -delete",intent:"hard_stop",catastrophic:!0},{id:"find.exec-rm-recursive-force",category:"Filesystem",label:"find exec rm -rf",description:"Blocks find -exec rm -rf operations.",example:"find . -exec rm -rf {} +",intent:"scope_down"},{id:"dd.device-write",category:"Filesystem",label:"dd device write",description:"Blocks dd writing to a /dev device.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"mkfs device format",description:"Blocks mkfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],cs=new Set(Uc.map((e)=>e.id)),qr=Uc,xy=new Map(qr.map((e)=>[e.id,e.intent]));function v(e,t){return{id:e,reason:t,intent:xy.get(e)??"manual_only"}}var us=[{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"}],Yr={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Ry=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],_y=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],ds=[{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"]},..._y.flatMap((e)=>Ry.map((t)=>({id:["secret.home",e.idSlug,t.slice(1)].join("."),category:"Home path",label:[e.label,t].join(""),description:["Blocks home ",e.label,t," credential backup files."].join(""),suffixParts:[...e.directoryParts,[e.basename,t].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 Zr=[{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"]}],Hc=[{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"}],wy=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],fs=Hc.map((e)=>({id:`secret.variant.${e.slug}.separator`,category:"Variant",label:`${e.label}-* / ${e.label}_*`,description:`Blocks ${e.label} variants with dash or underscore suffixes.`,prefix:e.prefix})),ms=Hc.flatMap((e)=>wy.map((t)=>({id:`secret.variant.${e.slug}.${t.slice(1)}`,category:"Variant",label:`${e.label}${t}`,description:`Blocks ${e.label}${t} private credential variants.`,prefix:e.prefix,suffix:t}))),Kn={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)$/},ps=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((e)=>({id:`secret.ext.${e}`,category:"Extension",label:`.${e}`,description:`Blocks files with the .${e} extension.`,extension:e})),gs=[{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?$/}],Ay=[...us,Yr,...ds,...fs,...ms,Kn,...ps,...gs,...Zr].map((e)=>({id:e.id,category:e.category,label:e.label,...e.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in e?{paths:e.paths}:{description:e.description}})),Xr=new Set(Zr.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),hs=new Set(Ay.map((e)=>e.id));import{isAbsolute as ys,join as Py,normalize as Iy,sep as Jr}from"node:path";var Qr=process.platform==="win32",jc=/[*?]/;function Cs(e){let t=e.trim(),n=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(Qr?t.replaceAll("\\","/"):t);if(!n)return null;let r=n[1]??"",o=n[2]??"";if(jc.test(r)||o==="."||o==="..")return null;return{root:r||"/",name:o}}function qn(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function bs(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=qn(e.trim(),t);if(!ys(n))return"must be an absolute path or start with ~/";return Yn(n,t)}function Ss(e,t){let n=Vc(e,t);if(n===null)return"must be a non-empty path string";if(!ys(n))return null;if(Yn(n,t)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var Ty="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",ky="cannot cover the guard's own configuration";function Vc(e,t){if(typeof e!=="string"||e.trim()==="")return null;let n=e.trim(),r=Qr?n.replaceAll("\\","/"):n;return qn(r.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function vs(e,t){let n=Vc(e,t);if(n===null)return"must be a non-empty path string";let r=Cs(n)?.root??n;if(jc.test(r))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!ys(r))return null;if(Yn(r,t)!==null)return Ty;return Oy(r,t)?ky:null}function Oy(e,t){let n=eo(e),r=eo(Py(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${Jr}`)}function Yn(e,t){let n=eo(e),r=eo(t);if(n===r)return"cannot be the home directory";let o=n.endsWith(Jr)?n:`${n}${Jr}`;if(r.startsWith(o))return"cannot contain the home directory";return null}function eo(e){let t=Iy(e);if(Qr)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(Qr?3:1)&&t.endsWith(Jr))t=t.slice(0,-1);return t}var Kc=30,to=1,no=365;function qc(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var Yc=new Set(qr.filter((e)=>e.catastrophic).map((e)=>e.id));function w(e,t){if(!e)return null;if(Yc.has(e.id))return e;if(t?.destructiveCommandProtectionEnabled===!1)return null;let n=t?.effectiveDestructiveCommandRules[e.id];return n&&!n.enabled?null:e}function ee(e,t,n){if(Yc.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function Zc(e,t){return Object.freeze(Object.fromEntries(qr.map((n)=>{let r=n.activationCapability?t[n.activationCapability]:void 0,o=r?.enabled??!0,i=e.destructiveCommandRuleOverrides[n.id],s=n.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...i?{override:i}:{}}:e.destructiveCommandProtectionEnabled?i?{enabled:i==="on",inheritedEnabled:o,changesInherited:i==="on"!==o,source:"rule_override",...n.activationCapability?{activationCapability:n.activationCapability}:{},override:i}:{enabled:o,inheritedEnabled:o,changesInherited:!1,source:r?.source??"built_in_default",...n.activationCapability?{activationCapability:n.activationCapability}:{}}:{enabled:!1,inheritedEnabled:o,changesInherited:!1,source:"master_disabled",...n.activationCapability?{activationCapability:n.activationCapability}:{},...i?{override:i}:{}};return[n.id,Object.freeze(s)]})))}function Xc(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:Zc(e,t)})}var Jc={standard:0,strict:1,paranoid:2};function tu(e,t,n=!1,r=e.safety.level){let o=My(e,t,r),i=new Set(n?o.map((u)=>u.field):[]),s=(u,f)=>i.has(u)?void 0:f,a=(u,f)=>Object.fromEntries(Object.entries(f??{}).filter(([d])=>!i.has(`${u}.${d}`))),l=(u,f)=>f?.filter((d)=>!i.has(`${u}.${d}`));return{policy:{version:1,safety:{level:s("safety.level",t.safety?.level)??e.safety.level,overrides:{...e.safety.overrides,...a("safety.overrides",t.safety?.overrides)}},workflow:{worktree_mode:s("workflow.worktree_mode",t.workflow?.worktree_mode)??e.workflow.worktree_mode},destructive_command_protection:{enabled:s("destructive_command_protection.enabled",t.destructive_command_protection?.enabled)??e.destructive_command_protection.enabled,overrides:{...e.destructive_command_protection.overrides,...a("destructive_command_protection.overrides",t.destructive_command_protection?.overrides)},allow_paths:Es(e.destructive_command_protection.allow_paths,l("destructive_command_protection.allow_paths",t.destructive_command_protection?.allow_paths))},secret_protection:{enabled:s("secret_protection.enabled",t.secret_protection?.enabled)??e.secret_protection.enabled,overrides:{...e.secret_protection.overrides,...a("secret_protection.overrides",t.secret_protection?.overrides)},deny_paths:Es(e.secret_protection.deny_paths,t.secret_protection?.deny_paths),allow_paths:Es(e.secret_protection.allow_paths,l("secret_protection.allow_paths",t.secret_protection?.allow_paths))},audit:e.audit},weakenings:o.map((u)=>u.message)}}function Es(e,t){return[...new Set([...e,...t??[]])]}function My(e,t,n){let r=t.safety?.level,o=Lr[n];return[...r&&Jc[r]<Jc[e.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${e.safety.level} -> ${r}`}]:[],...rn.flatMap((i)=>t.safety?.overrides?.[i]===!1&&(e.safety.overrides[i]??o[i])?[{field:`safety.overrides.${i}`,message:`project policy disables ${i}`}]:[]),...t.workflow?.worktree_mode===!0&&!e.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...t.destructive_command_protection?.enabled===!1&&e.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...t.secret_protection?.enabled===!1&&e.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...Qc("destructive_command_protection.overrides",t.destructive_command_protection?.overrides,(i)=>e.destructive_command_protection.enabled&&e.destructive_command_protection.overrides[i]!=="off"),...Qc("secret_protection.overrides",t.secret_protection?.overrides,(i)=>e.secret_protection.enabled&&(e.secret_protection.overrides[i]==="on"?!0:e.secret_protection.overrides[i]!=="off"&&!Xr.has(i))),...e.destructive_command_protection.enabled?eu(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths).map((i)=>({field:`destructive_command_protection.allow_paths.${i}`,message:`project policy adds destructive allow path: ${i}`})):[],...e.secret_protection.enabled?eu(e.secret_protection.allow_paths,t.secret_protection?.allow_paths).map((i)=>({field:`secret_protection.allow_paths.${i}`,message:`project policy adds secret allow path: ${i}`})):[]]}function Qc(e,t,n){return Object.entries(t??{}).flatMap(([r,o])=>o==="off"&&n(r)?[{field:`${e}.${r}`,message:`project policy disables rule ${r}`}]:[])}function eu(e,t){return(t??[]).filter((n)=>!e.includes(n))}var _s=new Set(["standard","strict","paranoid"]),iu={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:Kc}};function su(e,t){let n=jy(on(e,t),e.home),r=io(jn(t.cwd),e.home),o=Wy(r.parsed,e.home),i=et(Z.projectTightenOnly,e.env),s=n.gui??iu,a=Object.keys(o.policy).length>0?tu(s,o.policy,i,ic(s.safety.level,e.env)):void 0,l=[...n.errors,...r.errors,...o.diagnostics],c=(n.fallback==="defaults"&&a?"salvaged":n.fallback)??(n.gui?void 0:r.fallback)??(l.length>0?"salvaged":void 0),u=o.policy.safety?.level&&a?.policy.safety.level===o.policy.safety.level?"project":n.levelPresent?"user":"default";return{...a?Rs(a.policy):n.policy,errors:l,...c?{fallback:c}:{},...r.exists?{policyScopes:{levelScope:u,weakenings:a?.weakenings??[],weakeningsIgnored:i}}:{}}}var Ly="project policy audit settings are ignored; audit is user scope only";function Wy(e,t){if(!xe(e))return{policy:{},diagnostics:[]};let n=xe(e.safety)?e.safety:{},r=xe(e.workflow)?e.workflow:{},o=xe(e.destructive_command_protection)?e.destructive_command_protection:{},i=xe(e.secret_protection)?e.secret_protection:{},s={..._s.has(n.level)?{level:n.level}:{},...xe(n.overrides)?nu({overrides:au(n.overrides,rn,["safety","overrides"],Lt)}):{}},a={...typeof o.enabled==="boolean"?{enabled:o.enabled}:{},...o.overrides!==void 0?{overrides:oo(o.overrides,cs,cu,Lt)}:{},...o.allow_paths!==void 0?{allow_paths:ln(o.allow_paths,bs,t,["destructive_command_protection","allow_paths"],Lt)}:{}},l={...typeof i.enabled==="boolean"?{enabled:i.enabled}:{},...i.overrides!==void 0?{overrides:oo(i.overrides,hs,uu,Lt)}:{},...i.deny_paths!==void 0?{deny_paths:ln(i.deny_paths,Ss,t,["secret_protection","deny_paths"],Lt)}:{},...i.allow_paths!==void 0?{allow_paths:ln(i.allow_paths,vs,t,["secret_protection","allow_paths"],Lt)}:{}};return{policy:nu({safety:s,workflow:typeof r.worktree_mode==="boolean"?{worktree_mode:r.worktree_mode}:{},destructive_command_protection:a,secret_protection:l}),diagnostics:e.audit===void 0?[]:[Ly]}}function au(e,t,n,r){return Object.fromEntries(t.flatMap((o)=>{let i=e[o];if(typeof i==="boolean")return[[o,i]];if(i!==void 0)r(R([...n,o],ws));return[]}))}function nu(e){return Object.fromEntries(Object.entries(e).flatMap((t)=>Object.keys(t[1]).length>0?[t]:[]))}var Lt=()=>{return},ws="must be a boolean",As="must be an object if provided",lu=`must be an integer between ${to} and ${no}`,cu={path:["destructive_command_protection","overrides"],label:"destructive command"},uu={path:["secret_protection","overrides"],label:"secret protection"},Gy=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Fy(e,t){let n=[];return{policy:du(e,t,(o)=>{n.push(o)}),issues:n}}function zy(e,t){return du(e,t,Lt)}function du(e,t,n){if(!xe(e))return n(R([],"Config must be an object")),ro();if(e.version!==1)n(R(["version"],"must be 1"));let r=an(e.safety,["safety"],["level","overrides"],n),o=an(r.overrides,["safety","overrides"],rn,n),i=an(e.workflow,["workflow"],["worktree_mode"],n),s=an(e.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],n),a=an(e.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],n),l=an(e.audit,["audit"],["retention_days"],n);return fu(e,Gy,[],n),{version:1,safety:{level:By(r.level,n),overrides:au(o,rn,["safety","overrides"],n)},workflow:{worktree_mode:xs(i.worktree_mode,["workflow","worktree_mode"],!1,n)},destructive_command_protection:{enabled:xs(s.enabled,["destructive_command_protection","enabled"],!0,n),overrides:oo(s.overrides,cs,cu,n),allow_paths:ln(s.allow_paths,bs,t,["destructive_command_protection","allow_paths"],n)},secret_protection:{enabled:xs(a.enabled,["secret_protection","enabled"],!0,n),overrides:oo(a.overrides,hs,uu,n),deny_paths:ln(a.deny_paths,Ss,t,["secret_protection","deny_paths"],n),allow_paths:ln(a.allow_paths,vs,t,["secret_protection","allow_paths"],n)},audit:{retention_days:$y(l.retention_days,n)}}}function an(e,t,n,r){if(e===void 0)return{};if(!xe(e))return r(R(t,As)),{};return fu(e,n,t,r),e}function fu(e,t,n,r){for(let o of Object.keys(e).filter((i)=>!t.includes(i)))r({path:n,message:o,kind:"unknownKeys"})}function By(e,t){if(e===void 0)return"standard";if(_s.has(e))return e;return t(R(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function xs(e,t,n,r){if(typeof e==="boolean")return e;if(e!==void 0)r(R(t,ws));return n}function $y(e,t){if(!(e===void 0||typeof e==="number"&&Number.isInteger(e)&&e>=to&&e<=no))t(R(["audit","retention_days"],lu));return qc(e)}function oo(e,t,n,r){if(e===void 0)return{};if(!xe(e))return r(R(n.path,As)),{};return Object.fromEntries(Object.entries(e).flatMap(([o,i])=>{if(!t.has(o))return r({path:[...n.path,o],message:`unknown ${n.label} rule id "${o}"`,kind:"key"}),[];if(i==="on"||i==="off")return[[o,i]];return r(R([...n.path,o],'must be "on" or "off"')),[]}))}function ln(e,t,n,r,o){if(e===void 0)return[];if(!Array.isArray(e))return o(R(r,"must be an array of paths")),[];return e.flatMap((i,s)=>{let a=t(i,n);if(a===null)return[i];return o(typeof i==="string"?ne([...r,s],a):R([...r,s],a)),[]})}function xe(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function ro(){return structuredClone(iu)}function io(e,t){if(!Dy(e))return{exists:!1,policy:ro(),errors:[]};try{let n=Ny(e,"utf-8");if(!n.trim())return{exists:!0,policy:ro(),errors:[`${e}: Config file is empty`],fallback:"defaults"};let r=JSON.parse(n),o=Fy(r,t);if(o.issues.length===0)return{exists:!0,parsed:r,policy:o.policy,errors:[]};return{exists:!0,parsed:r,policy:o.policy,errors:o.issues.map((i)=>`${e}: ${Hy(i)}`),fallback:xe(r)?"salvaged":"defaults"}}catch(n){let r=n instanceof Error?n.message:String(n);return{exists:!0,policy:ro(),errors:[`${e}: ${n instanceof SyntaxError?"Invalid JSON":r}`],fallback:"defaults"}}}var Uy=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[As,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[ws,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[lu,`not an integer between ${to} and ${no}`]]);function Hy(e){let t=as(e.path);if(e.kind==="unknownKeys")return`${t===""?"":`${t}.`}${e.message}: unknown field`;if(e.kind==="key")return`${t}: unknown rule id`;let n=Uy.get(e.message)??e.message;return t===""?n:`${t}: ${n}`}function jy(e,t){let n=io(e,t);if(!n.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!xe(r))return{policy:ou(),errors:[]};let o=zy(r,t);return{policy:Rs(o),gui:o,errors:[],levelPresent:ru(r)}}if(n.parsed===void 0)return{policy:ou(),errors:n.errors,...n.fallback?{fallback:n.fallback}:{}};return{policy:Rs(n.policy),gui:n.policy,errors:n.errors,...n.fallback?{fallback:n.fallback}:{},levelPresent:ru(n.parsed)}}function ru(e){let t=xe(e)&&xe(e.safety)?e.safety:{};return _s.has(t.level)}function mu(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...Xr].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function ou(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:mu({}),denyPaths:[],allowPaths:[]}}}function Rs(e){return{safety:Vy(e.safety),worktreeMode:e.workflow.worktree_mode,destructiveCommandProtectionEnabled:e.destructive_command_protection.enabled,destructiveCommandRuleOverrides:e.destructive_command_protection.overrides,destructiveCommandAllowPaths:e.destructive_command_protection.allow_paths,secretProtection:{enabled:e.secret_protection.enabled,disabledRules:mu(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function Vy(e){let t={...e.overrides.fail_closed!==void 0?{failClosed:e.overrides.fail_closed}:{},...e.overrides.paranoid_rm!==void 0?{paranoidRm:e.overrides.paranoid_rm}:{},...e.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:e.overrides.paranoid_interpreters}:{}};return{level:e.level,...Object.keys(t).length>0?{overrides:t}:{}}}function pu(e,t){let n=$c(e,t),r=su(e,t),o={rules:n.rules,transparentWrappers:n.transparent_wrappers,safety:r.safety,worktreeMode:r.worktreeMode,destructiveCommandProtectionEnabled:r.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:r.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:r.destructiveCommandAllowPaths,secretProtection:{enabled:r.secretProtection.enabled??!0,disabledRules:r.secretProtection.disabledRules??[],denyPaths:r.secretProtection.denyPaths,allowPaths:r.secretProtection.allowPaths??[]}},i={...n.userConfig?.overrides,...n.projectConfig?.overrides},s=Object.freeze(Object.fromEntries(o.rules.map((a)=>{let l=n.rulebooks.find((u)=>u.rules.includes(a.name)),c=i[a.name];return[a.name,Object.freeze({id:a.name,...l?{rulebook:Object.freeze({name:l.name,version:l.version}),...Zy(l.spec)?{source:l.spec}:{}}:{},...c&&typeof c==="object"?{override:Object.freeze({type:"reason",reason:c.reason})}:{}})]})));return Xy(o,Ky(n,r),s,r.policyScopes)}function Ky(e,t){let n=Yy(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:Jy(e.errors.length>0?qy(e.errors):void 0,e.warnings.length>0?Is(e.warnings.join("; ")):void 0,n)}}function qy(e){return`${Is(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Yy(e){if(e.errors.length===0)return;let t=e.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${e.errors.join("; ")}. Enforcing ${t}; the invalid values are not active. Fix the policy file manually`}function Zy(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function Xy(e,t,n=Object.freeze({}),r){let o=Ps(structuredClone(e)),i=r?{policyScopes:Ps(structuredClone(r))}:{};if(!t)return Object.freeze({state:"ready",policy:o,diagnostics:Object.freeze([]),ruleMetadata:n,...i});return Object.freeze({state:"degraded",policy:o,diagnostics:Object.freeze([...t.diagnostics]),reason:t.reason,ruleMetadata:n,...i})}function Ps(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))Ps(t);return Object.freeze(e)}function Jy(...e){return Is(e.filter((t)=>!!t).join("; "))}function Is(e){return/[.!?]$/.test(e)?e:`${e}.`}function gu(e){let t=e.effectiveCapabilities,n=e.strict??t.fail_closed.enabled,r=e.paranoidRm??t.paranoid_rm.enabled,o=e.paranoidInterpreters??t.paranoid_interpreters.enabled,i={fail_closed:Ts(t.fail_closed,e.strict,"strict"),paranoid_rm:Ts(t.paranoid_rm,e.paranoidRm,"paranoidRm"),paranoid_interpreters:Ts(t.paranoid_interpreters,e.paranoidInterpreters,"paranoidInterpreters")};return{policy:Xc(e.policySnapshot.policy,i),effectiveCapabilities:i,effectiveLevel:Fi({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}function Ts(e,t,n){if(t===void 0||t===e.enabled)return e;return{enabled:t,source:"capability_override",sources:[...e.sources,`analysis options.${n}`]}}import{dirname as r_,isAbsolute as o_,join as i_,parse as s_,resolve as a_,sep as l_}from"node:path";function Zn(e,t){if(e!=="powershell")return t[0]?.provenance==="command-substitution";let n=t[0]?.text==="&"||t[0]?.text==="."?1:0,r=t[n]?.provenance;return r!==void 0&&r!=="literal"}var Qy=/^[A-Za-z_][A-Za-z0-9_]*=/;function so(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function Xn(e){let t=so(e.words[0],"time")?1:0,n=t===1&&so(e.words[t],"-p")?t+1:t,r=t===1&&so(e.words[n],"--")?n+1:n,o=so(e.words[r],"!")?r+1:r,i=e.words.slice(o).find((s)=>!Qy.test(s.text));return i?.provenance==="literal"?i.text:void 0}var ht=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function ao(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function eC(e){return Object.freeze({...e,span:Object.freeze(e.span),words:Object.freeze(e.words),redirections:Object.freeze(e.redirections.map((t)=>Object.freeze({...t,span:Object.freeze(t.span),...t.heredoc?{heredoc:Object.freeze({...t.heredoc,bodySpan:Object.freeze(t.heredoc.bodySpan),terminatorSpan:Object.freeze(t.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(e.nested.map((t)=>me(t)))})}function lo(e,t,n){e.push(n),t.reset()}function co(e){let t=[];return{parts:t,push:(n,r,o)=>{if(r<=n)return;t.push({raw:e.slice(n,r),span:{start:n,end:r},provenance:o})}}}function ks(e){let t=e.parts??[{raw:e.raw,span:e.span,provenance:e.provenance}];return Object.freeze({kind:"word",...e,span:Object.freeze(e.span),parts:Object.freeze(t.map((n)=>Object.freeze({...n,span:Object.freeze(n.span)})))})}function cn(e,t,n,r,o,i,s){return ks({text:r,raw:e.slice(t,n),span:{start:t,end:n},provenance:o,quoted:i,...s?{parts:s}:{}})}function me(e){return Object.freeze({...e,span:Object.freeze(e.span),issues:Object.freeze(e.issues.map((t)=>Object.freeze({...t}))),nodes:Object.freeze(e.nodes.map((t)=>{if(t.kind==="command")return eC(t);if(t.kind==="group"||t.kind==="function")return Object.freeze({...t,span:Object.freeze(t.span),body:me(t.body)});return Object.freeze({...t,span:Object.freeze(t.span)})}))})}function Os(e,t,n){if(t>=n||yu(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!yu(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=hu(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=hu(e,s+1,n,'"');r+=l.text,i||=!l.closed,s=l.next;continue}if(a==="\\"){o=!0;let l=e[s+1];if(!l||l===`
9
- `||l==="\r"){i=!0;break}r+=l,s+=2;continue}if(a==="`"||e.startsWith("$(",s)||e.startsWith("${",s)||e.startsWith("<(",s)||e.startsWith(">(",s))i=!0;r+=a,s++}return{delimiter:r,quoted:o,next:s,ambiguous:i}}function Ms(e,t,n,r){let o=[],i=t;for(let s of r){let a=i,l=!1;while(i<n){let c=tC(e,i,n);if((s.stripTabs?c.text.replace(/^\t+/,""):c.text)===s.delimiter){s.attach({body:s.stripTabs?nC(e.slice(a,i)):e.slice(a,i),delimiter:s.delimiter,quotedDelimiter:s.quotedDelimiter,bodySpan:{start:a,end:i},terminatorSpan:{start:i,end:c.contentEnd}}),i=c.next,l=!0;break}if(c.next<=i)break;i=c.next}if(l)continue;return o.push({code:"unterminated-heredoc",message:`heredoc delimiter ${s.delimiter} was not found`}),{next:n,issues:o,terminated:!1}}return{next:i,issues:o,terminated:!0}}function hu(e,t,n,r){let o="",i=t;while(i<n&&e[i]!==`
10
- `&&e[i]!=="\r"){let s=e[i]??"";if(s===r)return{text:o,next:i+1,closed:!0};if(r==='"'&&s==="\\"&&e[i+1]){let a=e[i+1]??"";o+=["$","`",'"',"\\"].includes(a)?a:`\\${a}`,i+=2;continue}o+=s,i++}return{text:o,next:i,closed:!1}}function yu(e){return e!=="\r"&&(/[\s;&|<>)]/u.test(e)||e==="`")}function tC(e,t,n){let r=t;while(r<n&&e[r]!==`
11
- `)r++;let o=r>=n?n:r+1;return{text:e.slice(t,r),contentEnd:r,next:o}}function nC(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var vu=new Set(["&&","||","|","|&"]),rC=new Set(["!","do","elif","else","if","then","until","while"]);function Eu(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return me({kind:"program",dialect:"posix",source:e,span:n,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${t.maxInputLength} UTF-16 code units`}],nodes:[]});let r=mo(e,0,e.length,t,{used:0,max:t.maxWords},0);return me({kind:"program",dialect:"posix",source:e,span:n,status:ho(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function mo(e,t,n,r,o,i,s){let a=[],l=[],c=ao(),u=[],f=()=>{if(c.words.length===0&&c.redirections.length===0)return;let m={start:c.start,end:c.end},g=c.words.map((p)=>p.text);lo(a,c,{kind:"command",dialect:"posix",source:e.slice(m.start,m.end),span:m,words:c.words,redirections:c.redirections,nested:c.nested,displayText:l.length>0&&a.length===0?e.slice(t,n):g.join(" ")})},d=t;while(d<n){let m=e[d];if(!m)break;if(s&&m===s)return f(),Su(a,l),{nodes:a,issues:l,next:d+1,closed:!0,limited:!1,pendingHeredocs:u};if(go(m)){if(m===`
5
+ `)}function Il(e,t){if(e.decision.kind!=="deny")return;let n=t.includeEvidence?e.decision.evidence:void 0;return{reason:e.decision.reason,ruleId:e.decision.ruleId,intent:e.decision.intent,command:n?.command,segment:n?.segment,toolName:t.toolName,...e.configFallback?{configWarning:e.configFallback.reason}:{},...e.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function zn(e={}){return{reason:Fn,ruleId:"analysis.failed-closed",intent:"stop_and_explain",command:e.command,segment:e.segment??e.command,toolName:e.toolName}}var ag={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 Pi(e,t={}){return{...ag[e.directory][e.problem],command:t.command,toolName:t.toolName,cwd:e.cwd}}function Tl(e){return sg({...e,redact:mt})}function kl(e){return mt(e instanceof Error?e.message:String(e))}import{isAbsolute as Li,relative as Ng,resolve as Jl,sep as Lg}from"node:path";import{basename as Dl,dirname as lg,isAbsolute as cg,join as ug,normalize as dg,resolve as Ol}from"node:path";var fg=256,Wr=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 ve(e,t=process.platform){if(t!=="win32")return e;return e.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function Je(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function ki(e,t){return Ai(e,0,t)}function Ai(e,t,n){let r="",o=0;while(o<e.length){if(e[o]!=="$"){r+=e[o],o++;continue}if(e[o+1]==="{"){let s=Ii(e,o+2),a=mg(e,o,t);if(a===null){if(Wr.has(s))throw new W("pathEnvironmentExpansion");r+=e.slice(o);break}let l=e.slice(o,a+1);r+=pg(l,t,n),o=a+1;continue}let i=Ii(e,o+1);if(!i){r+="$",o++;continue}r+=Ti(i,n)??`$${i}`,o+=i.length+1}return r}function mg(e,t,n){let r=1;for(let o=t+2;o<e.length;o++){if(e[o]==="\\"){o++;continue}if(e[o]==="$"&&e[o+1]==="{"){if(r++,n+r>K.pathEnvironmentExpansion.cap)throw new W("pathEnvironmentExpansion");o++;continue}if(e[o]!=="}")continue;if(r--,r===0)return o}return null}function pg(e,t,n){let r=e.slice(2,-1),o=Ii(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return Ti(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(Wr.has(o))throw new W("pathEnvironmentExpansion");return e}if(!Wr.has(o))return e;if(s.endsWith("="))throw new W("pathEnvironmentExpansion");let a=Ti(o,n),l=s.startsWith(":")?a!==null&&a!=="":a!==null;if(s.endsWith("?")&&!l)throw new W("pathEnvironmentExpansion");if(s.endsWith("-")||s.endsWith("?"))return l?a??"":Ai(i.slice(s.length),t+1,n);return l?Ai(i.slice(s.length),t+1,n):""}function Ii(e,t){if(!/[A-Za-z_]/.test(e[t]??""))return"";let n=t+1;while(/[A-Za-z0-9_]/.test(e[n]??""))n++;return e.slice(t,n)}function Ti(e,t){if(!Wr.has(e))return null;if(e==="HOME")return t.env.get("HOME")??t.home;return t.env.get(e)??null}function D(e,t,n){if(!e)return e;let r=n.resolvedPaths.get(e);if(r!==void 0)return r;let o=[],i=e;while(!0){Nl(n,i);let s=t.realpath(i);if(s!==null)return Ml(n,e,s,o);let a=lg(i);if(a===i||o.length>=fg)return Ml(n,e,i,o);o.push(Dl(i)),i=a}}function Ml(e,t,n,r){let o=r.length===0?n:ug(n,...r.reverse());return e.resolvedPaths.set(t,o),o}function gg(e,t,n){let r=n.resolvedPaths.get(e);if(r!==void 0)return r;Nl(n,e);let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function Nl(e,t){e.charge("realpathAttempts"),e.charge("processedCandidateBytes",Buffer.byteLength(t))}function le(e,t,n,r){let o=Wl(e,t,n);if(!o)return"";return D(o,n.paths,r).replace(/\\/g,"/")}function Ll(e,t,n,r,o){let i=Wl(e,t,n);if(!i)return null;if(o(Dl(i)))return D(i,n.paths,r).replace(/\\/g,"/");let s=gg(i,n.paths,r);return s===null?null:s.replace(/\\/g,"/")}function Wl(e,t,n){let r=n.home,o=ki(e.trim(),n).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?Ol(r,o.slice(2)):o,s=ve(i);return dg(cg(s)?s:Ol(t,s))}import{types as hg}from"node:util";var yg=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),bg=new Set(["command","diff","input","patch","patchtext"]),Gl=new TextEncoder,Cg=new TextDecoder,Sg=/\s/,vg=64;class Qe extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var Bn=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Eg(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function Fr(e){return yg.has(Eg(e))}function Un(e){if(!e||typeof e!=="object")return;Yl(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)Ke();return}if(t.get||t.set)Ke();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function Ul(e,t){return Hl(e,t,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Hl(e,t,n,r,o){let i=ql(e,r,o);if(typeof e==="string")return n?[e]:[];if(!i)return[];let s=i.entries.flatMap(([a,l])=>Hl(l,t,i.array?n:t.has(jl(a)),r,o+1));return r.ancestors.delete(i.object),s}function jl(e){return e.replace(/-/g,"_").toLowerCase()}function Vl(e){return Kl(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Rg)}function Kl(e,t,n,r){let o=ql(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>Kl(a,o.array?t:bg.has(jl(s)),n,r+1));return n.ancestors.delete(o.object),i}function xg(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>Bn.maxDepth||t.nodes>Bn.maxNodes)Ke();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>Bn.maxStringBytes||t.stringBytes>Bn.maxAggregateStringBytes)Ke()}function ql(e,t,n){if(xg(e,t,n),!e||typeof e!=="object")return null;let r=Yl(e);if(t.ancestors.has(e))Ke();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>Bn.maxKeys)Ke();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)Ke();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function Yl(e){if(hg.isProxy(e))Ke();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)Ke();return t}function Ke(){throw new Qe}function Rg(e){let t=[],n=e.split(/\r?\n/),r=!1,o=!1,i=null,s=null,a=()=>{o=!1,i=null,s=null};for(let l=0;l<n.length;l++){let c=n[l]??"";if(c==="*** Begin Patch"){r=!0,a();continue}if(c==="*** End Patch"){r=!1,a();continue}if(c.startsWith("@@")){let u=_g(c);if(o=!0,i=u?.oldLines??null,s=u?.newLines??null,i===0&&s===0)a();continue}if(o&&i!==null&&s!==null){let u=c.startsWith(" ")||c.startsWith("-")?1:0,f=c.startsWith(" ")||c.startsWith("+")?1:0;if(i=Math.max(0,i-u),s=Math.max(0,s-f),i===0&&s===0)a();continue}if(c.startsWith("*** ")){a(),t.push(...Oi(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...Oi(c));continue}if(c.startsWith("--- ")){let u=n[l+1]??"";if(!u.startsWith("+++ "))continue;t.push(...Di(Gr(c.slice(4),!0),Gr(u.slice(4),!0))),l++;continue}if(!r)t.push(...Oi(c))}return t}function _g(e){let t=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(e);if(!t)return null;return{oldLines:Number(t[1]??1),newLines:Number(t[2]??1)}}function Oi(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return $l(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return $l(n[1]);if(e.startsWith("diff --git "))return wg(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return Bl(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return Bl(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return Mg(i[1]);return[]}function wg(e){let t=Pg(e);if(t.length===2&&t[0]&&t[1])return Di(t[0],t[1]);let n=Ag(e);return n?Di(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function Pg(e){let t=[],n=0;while(n<e.length&&t.length<2){while(Ot(e[n]))n++;if(n>=e.length)break;let r=e[n]==='"'||e[n]==="'"?e[n]:void 0;if(!r){let i=n;while(n<e.length&&!Ot(e[n]))n++;t.push(e.slice(i,n));continue}let o=Zl(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(Ot(e[n]))n++;return n===e.length?t:[]}function Ag(e){let t=0;while(t<e.length&&Ot(e[t]))t++;let n=e.length;while(n>t&&Ot(e[n-1]))n--;let r=0,o=t;while(o<n){if(!Ot(e[o])){o++;continue}let i=o;while(o<n&&Ot(e[o]))o++;if(i===t||o===n)continue;if(r++,r>vg)Ke();if(Ig(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function Ig(e,t,n,r,o){if(Mi(e,t,n,r,o))return!0;let i=Fl(e,"/",t,n),s=Fl(e,"/",r,o);if(i<=t||s<=r)return!1;if(Mi(e,t,i,r,s))return!1;return Mi(e,i+1,n,s+1,o)}function Mi(e,t,n,r,o){if(n-t!==o-r)return!1;for(let i=0;i<n-t;i++)if(e[t+i]!==e[r+i])return!1;return!0}function Fl(e,t,n,r){for(let o=n;o<r;o++)if(e[o]===t)return o;return-1}function Ot(e){return e!==void 0&&Sg.test(e)}function Zl(e,t,n){let r=[],o=t+1;while(o<e.length){let i=String.fromCodePoint(e.codePointAt(o)??0);if(i===n)return{value:Cg.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...Gl.encode(i)),o+=i.length;continue}let s=e.slice(o+1),a=/^[0-7]{1,3}/.exec(s)?.[0];if(a){r.push(Number.parseInt(a,8)),o+=a.length+1;continue}r.push(...Gl.encode(Tg(s[0]??""))),o+=2}return null}function Tg(e){return{a:"\x07",b:"\b",f:"\f",n:`
6
+ `,r:"\r",t:"\t",v:"\v"}[e]??e}function kg(e){return $n(Dg(e))}function Di(e,t){if(e==="/dev/null")return zl(t);if(t==="/dev/null")return zl(e);if(e.startsWith("a/")&&t.startsWith("b/"))return[e.slice(2),t.slice(2)].flatMap($n);let n=Og(e,t)??(e===t?Xl(e):null);return[e,t,...n?[n]:[]].flatMap($n)}function zl(e){let t=Xl(e);return[e,...t?[t]:[]].flatMap($n)}function Xl(e){let t=e.indexOf("/");return t>0&&t<e.length-1?e.slice(t+1):null}function Og(e,t){let n=e.indexOf("/"),r=t.indexOf("/");if(n<1||r<1)return null;if(e.slice(0,n)===t.slice(0,r))return null;let o=e.slice(n+1);return o===t.slice(r+1)?o:null}function Bl(e){return kg(Gr(e,!0))}function Mg(e){return $n(Gr(e,!1))}function Gr(e,t){let n=e.trim(),r=n[0]==='"'||n[0]==="'"?n[0]:void 0;if(r){let o=Zl(n,0,r);if(o&&(t||n.slice(o.end).trim()===""))return o.value}return t?n.split("\t",1)[0]?.trim()??"":n}function Dg(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function $n(e){return e===""||e==="/dev/null"?[]:[e]}function $l(e){let t=e.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return t===""||t==="/dev/null"?[]:[t]}function Wi(e,t,n){if(Je(e))return;let r=t.flatMap((i)=>Ni(i,n));if(!r[0])return;let o=Ni(Li(e)?e:Jl(r[0],e),n)[0];if(!o)return;return r.some((i)=>Gg(o,i))?o:void 0}function Wg(e,t,n){if(Je(e))return;return Ni(Li(e)?e:Jl(t,e),n)[0]}function Ql(e,t,n){return Wg(e,t,n)?"outside-workspace":"unusable"}function Ni(e,t){let n=t.realpath(e);if(n===null)return[];return t.isDirectory(n)?[n]:[]}function Gg(e,t){let n=Ng(t,e);return n===""||n!==".."&&!n.startsWith(`..${Lg}`)&&!Li(n)}function ec(e,t,n,r,o){if(n.kind!=="command")return{toolName:e,input:t,route:n,context:r};return{toolName:e,input:t,route:n,context:r,command:o}}import{lstatSync as fh,realpathSync as mh,statSync as ph}from"node:fs";import{homedir as gh,tmpdir as hh}from"node:os";import{statSync as ch}from"node:fs";import{join as uh}from"node:path";import{spawnSync as Fg}from"node:child_process";import{existsSync as jn,lstatSync as zg,readFileSync as Vn,realpathSync as on,statSync as Hn}from"node:fs";import{dirname as Gi,isAbsolute as Fi,join as sn,resolve as zr}from"node:path";var Bg=["/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"],$g=5000;function nc(e,t=ih(),n=$g){let r=Ug(e),o=r===null?null:Hg(r);if(r===null||o===null)return null;let i=rh(r,o,t,n);return i===null?null:{recursiveSubmodules:i}}function Ug(e){try{let t=on(zr(e));return Hn(t).isDirectory()?t:null}catch{return null}}function Hg(e){let t=nh(e);if(!t)return null;try{let n=zg(t);if(n.isSymbolicLink()||!n.isFile())return null;let r=zi(t);if(!r?.commonDir)return null;if(!Kg(r.gitDir,t))return null;return qg(r.gitDir,Gi(t))?{gitDir:r.gitDir,commonDir:r.commonDir}:null}catch{return null}}function zi(e){try{let t=jg(e);if(!t)return null;let n=on(Fi(t)?t:zr(Gi(e),t));if(!Hn(n).isDirectory())return null;return{gitDir:n,commonDir:Vg(n)}}catch{return null}}function jg(e){let t=Vn(e,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!t.startsWith("gitdir:"))return null;return t.slice(7).trim()||null}function Vg(e){try{let t=Vn(sn(e,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!t)return null;let n=on(Fi(t)?t:zr(e,t));return Hn(n).isDirectory()?n:null}catch{return null}}function Kg(e,t){let n=Yg(e);return n===null?!1:rc(e,n,t)}function qg(e,t){let n=Zg(e);return n===null?!0:rc(e,n,t)}function Yg(e){let t=sn(e,"gitdir");if(!jn(t))return null;let n=Vn(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return n===""?null:n}function Zg(e){let t=sn(e,"config.worktree");return jn(t)?Jg(t):null}function rc(e,t,n){try{return Xg(Fi(t)?t:zr(e,t),n)}catch{return!1}}function Xg(e,t){try{let n=Hn(e),r=Hn(t);if(n.ino!==0&&r.ino!==0&&n.dev===r.dev&&n.ino===r.ino)return!0}catch{}return tc(on.native(e))===tc(on.native(t))}function tc(e){let t=e.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),n=t.length>1&&t.endsWith("/")?t.slice(0,-1):t;return process.platform==="win32"?n.toLowerCase():n}function Jg(e){let t=Vn(e,"utf-8"),n=!1,r=null;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i===""||i.startsWith("#")||i.startsWith(";"))continue;if(i.startsWith("[")){n=/^\[core\]$/i.test(i);continue}if(!n)continue;let s=i.match(/^worktree\s*=\s*(.*)$/i);if(s)r=Qg(s[1]??"")}return r}function Qg(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;return th(t.slice(1,-1))}var eh={"\\":"\\",'"':'"',n:`
7
+ `,t:"\t",b:"\b"};function th(e){return e.replace(/\\(.?)/gs,(t,n)=>n===""?t:eh[n]??t)}function nh(e){try{return Bi(on(e))}catch{return null}}function Bi(e){let t=e;while(!0){let n=sn(t,".git");if(jn(n))return n;let r=Gi(t);if(r===t)return null;t=r}}function rh(e,t,n,r){if(oh(t))return!0;if(n===null)return!0;let o=Fg(n,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:sh(process.env),stdio:["ignore","pipe","ignore"],timeout:r});if(o.error!==void 0||o.status!==0&&o.status!==1)return null;return o.status===0&&oc(o.stdout.trim())}function oh(e){return[sn(e.commonDir,"config"),sn(e.gitDir,"config.worktree")].filter((t)=>jn(t)).some((t)=>ah(t))}function ih(){return Bg.find((e)=>jn(e))??null}function Kn(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function sh(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Kn(t)))}function ah(e){let t;try{t=Vn(e,"utf-8")}catch{return!0}let n="",r=!1;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i===""||i.startsWith("#")||i.startsWith(";"))continue;let s=i.match(/^\[([^\]]+)\]$/);if(s){n=s[1]?.trim().toLowerCase()??"";continue}let a=i.indexOf("="),l=(a===-1?i:i.slice(0,a)).trim().toLowerCase(),c=a===-1?"true":i.slice(a+1).trim();if(lh(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=oc(c)}return r}function lh(e){return e==="include"||e.startsWith("includeif ")}function oc(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function ic(e,t){if(e==="")return null;let n=Ae(),r=Bi(le(e,e,t,n)),o=r?dh(r,e,t,n):null;if(!o)return null;return Object.freeze({entries:Object.freeze([o.entry]),markerFiles:Object.freeze(o.markerFile?[o.markerFile]:[]),directories:Object.freeze(o.directories),hooksDirectories:Object.freeze(o.hooksDirectories)})}function dh(e,t,n,r){try{let o=le(e,t,n,r),i=ch(e),s=i.isFile()?o:null,a=i.isFile()?zi(e):null,l=(i.isDirectory()?[o]:[a?.gitDir,a?.commonDir]).flatMap((u)=>u?[an(le(u,t,n,r))]:[]),c=[...new Set(i.isDirectory()?[an(e.replace(/\\/g,"/")),...l]:l)];return{entry:an(o),markerFile:s?an(s):null,directories:c,hooksDirectories:[...new Set(c.flatMap((u)=>{let f=an(uh(u,"hooks").replace(/\\/g,"/"));return[f,an(le(f,t,n,r))]}))]}}catch{return null}}function an(e){return process.platform==="win32"?e.toLowerCase():e}var yh={realpath:(e)=>{try{return mh(e)}catch{return null}},entryKind:(e)=>{let t=fh(e,{throwIfNoEntry:!1});if(!t)return"missing";return t.isSymbolicLink()?"symlink":"present"},isDirectory:(e)=>{try{return ph(e).isDirectory()}catch{return!1}}};function ac(){return bh({env:new Map(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),home:ve(process.env.HOME||gh()),tmpdir:hh(),paths:yh})}function bh(e,t={}){let n=new Map,r=new Map,o={...e,gitMetadata:(i)=>sc(n,i,()=>ic(i,o)),worktreeFacts:(i)=>sc(r,i,()=>nc(i)),...t};return o}function sc(e,t,n){let r=e.get(t);if(r!==void 0)return r;let o=n();return e.set(t,o),o}var ln=["fail_closed","paranoid_rm","paranoid_interpreters"],Br={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 Z={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"}},$r=["standard","strict","paranoid"];function lc(e,t){if(!t)return e;return $r.indexOf(t)>$r.indexOf(e)?t:e}function cc(e){let t=Ur(Z.level,e);return $r.find((n)=>n===t)}function uc(e,t){return lc(e,cc(t))}function Ch(e){let t=Ur(Z.level,e);if(!t)return;let n=cc(e);if(n)return n;console.error(`CC Safety Net: ignored invalid ${Z.level.name}=${JSON.stringify(t.slice(0,40))}. Use ${$r.join(", ")}.`);return}function Sh(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function dc(e){return Sh(Ur(Z.auditScope,e))==="all"}function Ui(e){if(e.failClosed&&e.paranoidRm&&e.paranoidInterpreters)return"paranoid";if(e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"strict";if(!e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"standard";return"custom"}function Hi(e={},t){let n=e.safety?.level??"standard",r=Ch(t),o=lc(n,r),i=Br[o],s={failClosed:i.fail_closed,paranoidRm:i.paranoid_rm,paranoidInterpreters:i.paranoid_interpreters},a={failClosed:o===n?"preset":"environment",paranoidRm:o===n?"preset":"environment",paranoidInterpreters:o===n?"preset":"environment"},l={failClosed:[`policy safety.level=${n}`],paranoidRm:[`policy safety.level=${n}`],paranoidInterpreters:[`policy safety.level=${n}`]};if(o!==n)l.failClosed.push(`env ${Z.level.name}=${r}`),l.paranoidRm.push(`env ${Z.level.name}=${r}`),l.paranoidInterpreters.push(`env ${Z.level.name}=${r}`);if(e.safety?.overrides?.failClosed!==void 0)s.failClosed=e.safety.overrides.failClosed,a.failClosed="capability_override",l.failClosed.push("policy safety.overrides.fail_closed");if(e.safety?.overrides?.paranoidRm!==void 0)s.paranoidRm=e.safety.overrides.paranoidRm,a.paranoidRm="capability_override",l.paranoidRm.push("policy safety.overrides.paranoid_rm");if(e.safety?.overrides?.paranoidInterpreters!==void 0)s.paranoidInterpreters=e.safety.overrides.paranoidInterpreters,a.paranoidInterpreters="capability_override",l.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(et(Z.strict,t))s.failClosed=!0,a.failClosed="environment",l.failClosed.push(`env ${Z.strict.name}`);if(et(Z.paranoid,t))s.paranoidRm=!0,s.paranoidInterpreters=!0,a.paranoidRm="environment",a.paranoidInterpreters="environment",l.paranoidRm.push(`env ${Z.paranoid.name}`),l.paranoidInterpreters.push(`env ${Z.paranoid.name}`);if(et(Z.paranoidRm,t))s.paranoidRm=!0,a.paranoidRm="environment",l.paranoidRm.push(`env ${Z.paranoidRm.name}`);if(et(Z.paranoidInterpreters,t))s.paranoidInterpreters=!0,a.paranoidInterpreters="environment",l.paranoidInterpreters.push(`env ${Z.paranoidInterpreters.name}`);let c=!!e.worktreeMode||et(Z.worktree,t);return{strict:s.failClosed,paranoidRm:s.paranoidRm,paranoidInterpreters:s.paranoidInterpreters,worktreeMode:c,effectiveLevel:Ui(s),capabilities:{fail_closed:{enabled:s.failClosed,source:a.failClosed,sources:l.failClosed},paranoid_rm:{enabled:s.paranoidRm,source:a.paranoidRm,sources:l.paranoidRm},paranoid_interpreters:{enabled:s.paranoidInterpreters,source:a.paranoidInterpreters,sources:l.paranoidInterpreters}}}}function et(e,t){let n=typeof e==="string"?$i(e,t):Ur(e,t);return n==="1"||n?.toLowerCase()==="true"}function $i(e,t){return t.get(e)}function Ur(e,t){let n=$i(e.name,t);if(n!==void 0)return n;if(e.legacyName)return $i(e.legacyName,t);return}import{dirname as Jr}from"node:path";import{closeSync as vh,constants as fc,fstatSync as Eh,fsyncSync as CI,lstatSync as Ki,mkdirSync as SI,openSync as xh,readdirSync as vI,readFileSync as Rh,realpathSync as qi,renameSync as EI,rmdirSync as xI,statSync as _h,unlinkSync as RI,writeFileSync as _I}from"node:fs";import{isAbsolute as mc,join as Yi,normalize as wh,parse as Vi,relative as Zi,resolve as Xi,sep as Ji}from"node:path";function ji(){let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${e()}${e()}`}var Ph=Symbol("PolicyFilesystemScope"),Ah=Symbol("PolicyFilesystemTarget"),Ih=fc.O_NOFOLLOW??0;class ce extends Error{name="PolicyFilesystemError";constructor(e){super(`Unable to access ${e} filesystem safely.`)}}function Mt(e,t){return{[Ph]:!0,root:Xi(e),label:t}}function pc(e,t){let n=wh(t);if(t===""||mc(t)||n===".."||n.startsWith(`..${Ji}`))throw new ce(e.label);return{[Ah]:!0,scope:e,relativePath:n,path:Yi(e.root,n)}}function qn(e,t){return pc(e,Zi(e.root,Xi(t)))}function gc(e,t="rules policy"){let n=Xi(e),r=Vi(n).dir;return pc(Mt(r,t),Zi(r,n))}function jr(e){return yc(e.scope.label,()=>{if(!Hr(e))return null;let t=xh(e.path,fc.O_RDONLY|Ih);return Th(t,()=>{let n=Eh(t);if(!n.isFile())throw new ce(e.scope.label);let r=Rh(t,"utf-8"),o=Ki(e.path);if(!o.isFile()||o.isSymbolicLink()||n.dev!==o.dev||n.ino!==o.ino)throw new ce(e.scope.label);return Hr(e),r})})}function hc(e,t){if(e.path===t.path)return!0;return yc(e.scope.label,()=>{if(!Hr(e)||!Hr(t))return!1;let n=(r)=>Yi(qi(Vi(r).dir),Vi(r).base);return n(e.path)===n(t.path)})}function yc(e,t,n){try{return t()}catch(r){if(n?.(),r instanceof ce)throw r;throw new ce(e)}}function Th(e,t){try{return t()}finally{vh(e)}}function Hr(e,t="file"){let n=kh(e.scope);if(!n)return!1;let r=e.relativePath.split(Ji);for(let o of r.keys()){let i=Yi(e.scope.root,...r.slice(0,o+1)),s=Ki(i,{throwIfNoEntry:!1});if(!s)return!1;if(s.isSymbolicLink())throw new ce(e.scope.label);if(o<r.length-1&&!s.isDirectory())throw new ce(e.scope.label);if(o===r.length-1&&(t==="file"?!s.isFile():!s.isDirectory()))throw new ce(e.scope.label);Oh(n,qi(i),e.scope.label)}return!0}function kh(e){if(!Ki(e.root,{throwIfNoEntry:!1}))return null;if(!_h(e.root).isDirectory())throw new ce(e.label);return qi(e.root)}function Oh(e,t,n){let r=Zi(e,t);if(r===".."||r.startsWith(`..${Ji}`)||mc(r))throw new ce(n)}import{dirname as Nt,isAbsolute as Wh,join as Lt,relative as Gh,resolve as pt,sep as Fh}from"node:path";var Dt=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,bc="rulebook.json",Cc=".cc-safety-net/rules";var Sc=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/;var Mh=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,Dh=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Nh="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),II=new RegExp(`^${Dh}/(${Dt.source.slice(1,-1)})/${Nh}$`);function Lh(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function vc(e){if(Vr(e))try{return Qi(e),null}catch(t){return t instanceof Error?t.message:String(t)}return Dt.test(e)?null:`Local rulebook sources must be bare names matching ${Dt}: ${e}`}function Qi(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(Sc);if(!t?.[1]||!t[2]||!t[3])throw Error(`Invalid GitHub rulebook source: ${e}`);let n=t[3].lastIndexOf("/");if(n<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);let r=t[3].slice(0,n),o=t[3].slice(n+1);if(!r||!Mh.test(r))throw Error(`GitHub rulebook refs must use valid path segments: ${e}`);if(!o||!Dt.test(o))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);return{owner:t[1],repo:t[2],ref:r,path:Lh(o),name:o}}function Vr(e){return Sc.test(e)}var Ec="rule.json",Kr="policy.json",xc=".cc-safety-net",zh="rules",Bh="CC_SAFETY_NET_HOME",Rc="`cc-safety-net rule update`";function $h(e){return pt(e,Cc)}function Uh(e){return Lt($h(e),Ec)}function cn(e){return Lt(pt(e),xc,Kr)}function es(e,t={}){return t.userConfigDir??(t.userConfigPath?Nt(t.userConfigPath):Lt(Hh(e),zh))}function Hh(e){let t=e.env.get(Bh);return t?pt(ve(t)):Lt(e.home,xc)}function jh(e,t={}){return Lt(es(e,t),Ec)}function Wt(e,t={}){return Lt(Nt(es(e,t)),Kr)}function _c(e,t){let n=Ae();return D(cn(t.cwd),e.paths,n)===D(pt(Wt(e,t)),e.paths,n)}function wc(e,t){let n=t.userConfigPath??jh(e,t),r=t.projectConfigPath??Uh(t.cwd),o=Vh(e,t),i=Kh(r,t.cwd);return{userConfigPath:n,projectConfigPath:r,userScope:o,projectScope:i,userConfigTarget:qn(o,n),projectConfigTarget:qn(i,r)}}function Vh(e,t){let n=t.userConfigPath?Nt(Nt(pt(t.userConfigPath))):Nt(pt(t.userConfigDir??es(e,t)));return Mt(n,"user policy")}function Kh(e,t){let n=pt(t),r=pt(e),o=Gh(n,r);if(o!==".."&&!o.startsWith(`..${Fh}`)&&!Wh(o))return Mt(n,"project policy");return Mt(Nt(Nt(r)),"project policy")}function Pc(e,t){return Lt(e,t,bc)}var Ee=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),gt=/^[a-zA-Z][a-zA-Z0-9_-]*$/,ht=256,Y=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Ac=new Set(["python","python3","python2","node","ruby","perl"]),qr=/^python(?:[23](?:\.\d+)*)?$/,Ie=new Set(["awk","gawk","nawk","mawk"]),Yr=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 Ic="Rulebook exceeds CC Safety Net's safe validation limits.",Tc="Additional rulebook validation errors were omitted.",Me=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function kc(e){if(ts(e.allowed_commands,Me.maxAllowedCommands)||ts(e.rules,Me.maxRules)||ts(e.tests,Me.maxTests))return!1;let{maxAggregateStringCodeUnits:t,maxTotalBlockArgs:n}=Me,r=(o,i=!1)=>{if(typeof o!=="string")return!0;if(o.length>Me.maxStringCodeUnits||i&&o.length>Me.maxFixtureCommandCodeUnits||o.length>t)return!1;return t-=o.length,!0};if(!r(e.name)||!r(e.version)||!r(e.description)||!r(e.author)||!r(e.migrated_from))return!1;if(Array.isArray(e.allowed_commands)){for(let o of e.allowed_commands)if(!r(o))return!1}if(Array.isArray(e.rules))for(let o of e.rules){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.name)||!r(i.command)||!r(i.subcommand)||!r(i.reason)||!r(i.intent))return!1;let s=i.match&&typeof i.match==="object"?i.match:{};for(let a of[i.block_args,s.command_path,s.any_args,s.exclude_args]){if(!Array.isArray(a))continue;if(a.length>Me.maxBlockArgsPerRule||a.length>n)return!1;n-=a.length;for(let l of a)if(!r(l))return!1}}if(Array.isArray(e.tests))for(let o of e.tests){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.command,!0)||!r(i.expect)||!r(i.rule))return!1}return!0}function ts(e,t){return Array.isArray(e)&&e.length>t}var ns=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var rs=64,os="Rule config exceeds CC Safety Net's safe source limit.";function O(e){return P(e).toLowerCase()}function P(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}function fe(e,t){let n=new Set,r=!1;for(let o of e){if(o==="--"){r=!0;continue}if(r)continue;if(o.startsWith("-")&&!o.startsWith("--")&&o.length>1)for(let i=1;i<o.length;i++){let s=o[i];if(!s||!/[a-zA-Z]/.test(s))break;let a=`-${s}`;if(n.add(a),t?.shortOptsWithValue?.has(a))break}}return n}var qh={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},is=new Set(["--init-file","--rcfile"]);function ss(e,t,n,r){let o=!1,i=0,s=!1,a=!1,l=!1;for(let c=1;c<t.length;c++){let u=t[c];if(u===void 0)break;if(e==="ksh"&&u==="o"&&c+1<t.length){if(r==="argv"){let f=t.slice(c+1);if(t[0]==="-"&&(f==="c"||f[0]==="-"&&f.endsWith("c")))s=!0}break}if(e==="ksh"&&u==="o"&&c+1===t.length&&(n?.startsWith("-")||n?.startsWith("+")))break;if(e==="zsh"&&u==="o"&&c+1<t.length)break;if(r==="startup"&&u==="i")o=t[0]==="-";if(r==="argv"&&t[0]==="-"&&u==="c")s=!0;if(r==="argv"&&u==="n")l=t[0]==="-";if(r==="argv"&&u==="s")a=t[0]==="-";if(!qh[e]?.includes(u))continue;if(c+1===t.length)i++;break}return{interactive:o,followingValues:i,commandSelected:s,stdinMode:a,syntaxCheck:l}}function xe(e){let t=P(e[0]??"").toLowerCase(),n=!1,r=!1,o=!1;for(let i=1;i<e.length;i++){let s=e[i];if(s===void 0)break;if(s==="--"){let l=n&&e[i+1]!==void 0?i+1:null;return{command:l===null?null:e[l]??null,commandIndex:l,scriptIndex:!n&&!r&&e[i+1]!==void 0?i+1:null,readsStdinAsCommands:!n&&(r||e[i+1]===void 0),syntaxCheck:o}}if(s==="-"||s[0]!=="-"&&s[0]!=="+")return{command:n?s:null,commandIndex:n?i:null,scriptIndex:!n&&!r&&s!=="-"?i:null,readsStdinAsCommands:!n&&(r||s==="-"),syntaxCheck:o};if(s.startsWith("--")){let l=s.split("=",1)[0]??s;if(t==="bash"&&is.has(l)&&!s.includes("="))i++;continue}let a=ss(t,s,e[i+1],"argv");if(a.commandSelected)n=!0;if(a.syntaxCheck)o=!0;if(a.stdinMode)r=!0;i+=a.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!n,syntaxCheck:o}}function Yn(e,t){if(t.escaped)return t.escaped=!1,!0;if(e==="\\"&&!t.inSingle)return t.escaped=!0,!0;if(e==="'"&&!t.inDouble)return t.inSingle=!t.inSingle,!0;if(e==='"'&&!t.inSingle)return t.inDouble=!t.inDouble,!0;return!1}function Zr(e){let t={inSingle:!1,inDouble:!1,escaped:!1};for(let n of Yh(e))Yn(n,t);return t.inSingle||t.inDouble}function Yh(e){let t="",n={inSingle:!1,inDouble:!1,escaped:!1},r=!1,o=!0;for(let i=0;i<e.length;i++){let s=e[i];if(!s)break;if(r){if(s===`
8
+ `||s==="\r")t+=s,r=!1,n.escaped=!1;continue}if(s==="#"&&!n.inSingle&&!n.inDouble&&o){r=!0;continue}if(t+=s,!n.inSingle&&!n.inDouble&&!n.escaped)o=/[\s;&|()<>]/.test(s);Yn(s,n)}return t}var as=new Set(["rm","find","xargs","parallel"]),Zh=new Set(["git","busybox",...as,...Y,...Ac,...Ie]),Xh=new Set(["python","node","ruby","perl"]);function Oc(e){let t=O(e);return Zh.has(t)||De(t)}function De(e){return Xh.has(Jh(e))}function Jh(e){let t=P(e).toLowerCase();return qr.test(t)?"python":t}function ls(e){try{let t=jr(Qh(e));if(t===null)return{config:null,errors:[]};if(!t.trim())return{config:null,errors:["Config file is empty"]};let n=JSON.parse(t),r=ny(n);if(r.errors.length>0)return{config:null,errors:r.errors};return{config:{version:1,rules:n.rules??[],overrides:n.overrides??{},transparent_wrappers:n.transparent_wrappers??[]},errors:[]}}catch(t){if(t instanceof ce)return{config:null,errors:[t.message]};let n=t instanceof Error?t.message:String(t);return{config:null,errors:[t instanceof SyntaxError?"Invalid JSON":n]}}}function Qh(e){return typeof e==="string"?gc(e):e}var R=(e,t)=>({path:e,message:t,kind:"typed"}),re=(e,t)=>({path:e,message:t,kind:"custom"});function Mc(e){let t=new Set;return e.flatMap((n,r)=>{let o=un(n)?n.name:void 0;if(typeof o!=="string")return[];if(t.has(o.toLowerCase()))return[re(["rules",r,"name"],`duplicate rule name "${o}"`)];return t.add(o.toLowerCase()),[]})}var cs=`must be one of ${ns.join(", ")}`,ey=/^[^/]+\/[^/]+$/,ty=["version","rules","overrides","transparent_wrappers"];function ny(e){let t=ry(e);return{errors:us(fy(t,ty,(n)=>n.kind==="custom"),": "," "),sources:dy(e,t)}}function ry(e){if(!un(e))return[R([],"Config must be an object")];let t=Array.isArray(e.rules)&&e.rules.length>rs;return[...e.version===1?[]:[R(["version"],"must be 1")],...oy(e.rules,t),...ay(e.overrides),...cy(e.transparent_wrappers),...t?[]:sy(e.rules),...un(e.overrides)?Object.keys(e.overrides).filter((n)=>!ey.test(n)).map((n)=>re(["overrides",n],"must use <rulebook-name>/<rule-name>")):[],...uy(e.transparent_wrappers)]}function oy(e,t){if(e===void 0)return[];if(!Array.isArray(e))return[R(["rules"],"must be an array of rulebook source strings"),...Dc(e,rs)?[R(["rules"],os)]:[]];if(t)return[{path:["rules"],message:os,kind:"limit"}];return e.flatMap((n,r)=>{if(typeof n!=="string")return[R(["rules",r],"must be a rulebook source string"),...iy(n,1)?[R(["rules",r],"must be a non-empty rulebook source string")]:[]];return n===""?[R(["rules",r],"must be a non-empty rulebook source string")]:[]})}function Dc(e,t){let n=Nc(e);return n!==void 0&&!(n<=t)}function iy(e,t){let n=Nc(e);return n!==void 0&&!(n>=t)}function Nc(e){if(e===null||e===void 0)return;let t=e.length;return t===void 0?void 0:Number(t)}function sy(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||n==="")return[];if(n.trim()==="")return[re(["rules",r],"must be a non-empty rulebook source string")];let o=vc(n);if(o)return[re(["rules",r],o)];if(t.has(n))return[re(["rules",r],`duplicate rulebook source "${n}"`)];return t.add(n),[]})}function ay(e){if(e===void 0)return[];if(!un(e))return[R(["overrides"],"must be an object if provided")];return Object.keys(e).flatMap((t)=>{let n=e[t];if(n==="off")return[];if(!un(n))return[R(["overrides",t],'must be "off" or an object')];return[...ly(n.reason,["overrides",t,"reason"]),...n.intent===void 0||fs(n.intent)?[]:[R(["overrides",t,"intent"],cs)]]})}function ly(e,t){if(typeof e!=="string")return[R(t,"required non-empty string"),...Dc(e,ht)?[R(t,`must be at most ${ht} characters`)]:[]];if(e==="")return[R(t,"required non-empty string")];return e.length>ht?[R(t,`must be at most ${ht} characters`)]:[]}function cy(e){if(e===void 0)return[];if(!Array.isArray(e))return[R(["transparent_wrappers"],"must be an array of command strings")];return e.flatMap((t,n)=>{if(typeof t!=="string")return[R(["transparent_wrappers",n],"must be a command string")];return gt.test(t)?[]:[R(["transparent_wrappers",n],"must match command pattern")]})}function uy(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||!gt.test(n))return[];if(t.has(n))return[re(["transparent_wrappers",r],`duplicate command "${n}"`)];if(Oc(n))return[re(["transparent_wrappers",r],`reserved command "${n}" cannot be a wrapper`)];return t.add(n),[]})}function dy(e,t){let n=un(e)?e.rules:void 0;if(!Array.isArray(n))return new Set;if(t.some((o)=>o.path.length===1&&o.path[0]==="rules"))return new Set;let r=new Set(t.filter((o)=>o.path[0]==="rules"&&typeof o.path[1]==="number").map((o)=>o.path[1]));return new Set(n.filter((o,i)=>typeof o==="string"&&!r.has(i)))}function fy(e,t,n){let r=e.map((s)=>s.path[1]),o=[...new Set(r.filter((s)=>typeof s==="string"))],i=(s,a)=>[s.path.length===0?-1:t.indexOf(String(s.path[0])),typeof a==="number"?a:o.indexOf(String(a)),n(s)?0:1];return e.map((s,a)=>({issue:s,rank:i(s,r[a])})).sort((s,a)=>s.rank[0]-a.rank[0]||s.rank[1]-a.rank[1]||s.rank[2]-a.rank[2]).map((s)=>s.issue)}function us(e,t,n){return[...new Set(e.map((r)=>{let o=ds(r.path);if(r.kind==="unknownKeys")return`${o?`${o}.`:""}unknown field "${r.message}"`;if(r.kind==="key"||r.kind==="limit"||r.path.length===0)return r.message;return`${o}${r.path.length===1?n:t}${r.message}`}))]}function ds(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function fs(e){return ns.includes(e)}function un(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Wc(e){let t=gy(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}var my=`required non-empty string up to ${ht} characters`,Lc="must be a non-empty array of unique non-empty strings",py="required non-empty array of non-empty strings";function gy(e){if(!yt(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!kc(e))return{errors:[Ic],ruleNames:new Set};let t=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...us(hy(e,e.rulebook_version===2),": ",": ")];return{errors:t.length>Me.maxValidationErrors?[...t.slice(0,Me.maxValidationErrors),Tc]:t,ruleNames:new Set(Gc(e).map((n)=>n.toLowerCase()))}}function Gc(e){let t=yt(e)?e.rules:void 0;return(Array.isArray(t)?t:[]).flatMap((n)=>{let r=yt(n)?n.name:void 0;return typeof r==="string"?[r]:[]})}function hy(e,t){return[...typeof e.name==="string"&&Dt.test(e.name)?[]:[R(["name"],"required string matching rule name pattern")],...typeof e.version==="string"&&e.version!==""?[]:[R(["version"],"required non-empty string")],...yy(e.allowed_commands),...by(e.rules,t),...Ey(e.tests),...xy(e),...Ry(e)]}function yy(e){if(!Array.isArray(e))return[R(["allowed_commands"],"required array")];let t=new Set;return[...e.flatMap((n,r)=>typeof n==="string"&&gt.test(n)?[]:[R(["allowed_commands",r],"must match command pattern")]),...e.flatMap((n,r)=>{if(typeof n!=="string"||!gt.test(n))return[];if(t.has(n))return[re(["allowed_commands",r],`duplicate command "${n}"`)];return t.add(n),[]})]}function by(e,t){if(!Array.isArray(e))return[R(["rules"],"required array")];return[...e.flatMap((n,r)=>{if(!yt(n))return[R(["rules",r],"must be an object")];return t?Sy(n,["rules",r]):Cy(n,["rules",r])}),...Mc(e)]}function Cy(e,t){return[...Fc(e.name,t),...zc(e.command,t),...e.subcommand===void 0||typeof e.subcommand==="string"&&gt.test(e.subcommand)?[]:[R([...t,"subcommand"],"must match command pattern")],...Xr(e.block_args,[...t,"block_args"],"required non-empty array",!1),...Bc(e.reason,t),...$c(e.intent,t)]}function Sy(e,t){return[...Fc(e.name,t),...zc(e.command,t),...Bc(e.reason,t),...$c(e.intent,t),...vy(e.match,[...t,"match"]),...e.subcommand===void 0?[]:[R([...t,"subcommand"],"not supported in rulebook_version 2")],...e.block_args===void 0?[]:[R([...t,"block_args"],"not supported in rulebook_version 2")]]}function Fc(e,t){if(typeof e!=="string")return[R([...t,"name"],"required string")];return Dt.test(e)?[]:[R([...t,"name"],"must match rule name pattern")]}function zc(e,t){return typeof e==="string"&&gt.test(e)?[]:[R([...t,"command"],"required string matching command pattern")]}function Bc(e,t){return typeof e==="string"&&e!==""&&e.length<=ht?[]:[R([...t,"reason"],my)]}function $c(e,t){return e===void 0||fs(e)?[]:[R([...t,"intent"],cs)]}function vy(e,t){if(!yt(e))return[R(t,"required object")];return[...Xr(e.command_path,[...t,"command_path"],py,!1),...e.any_args===void 0?[]:Xr(e.any_args,[...t,"any_args"],Lc,!0),...e.exclude_args===void 0?[]:Xr(e.exclude_args,[...t,"exclude_args"],Lc,!0)]}function Xr(e,t,n,r){if(!Array.isArray(e))return[R(t,n)];let o=e.flatMap((i,s)=>{if(typeof i!=="string")return[R([...t,s],"must be a non-empty string")];return i===""?[re([...t,s],"must be a non-empty string")]:[]});if(e.some((i)=>typeof i!=="string"))return o;return[...o,...e.length===0?[re(t,n)]:[],...r&&new Set(e).size!==e.length?[re(t,"must not contain duplicate values")]:[]]}function Ey(e){if(e===void 0)return[];if(!Array.isArray(e))return[R(["tests"],"must be an array if provided")];return e.flatMap((t,n)=>{if(!yt(t))return[R(["tests",n],"must be an object")];return[...typeof t.command==="string"&&t.command.trim()!==""?[]:[R(["tests",n,"command"],"required non-empty string")],...t.expect==="blocked"||t.expect==="allowed"?[]:[R(["tests",n,"expect"],'must be "blocked" or "allowed"')],...t.rule===void 0||typeof t.rule==="string"?[]:[R(["tests",n,"rule"],"must be a string if provided")],...t.expect==="blocked"&&typeof t.rule!=="string"?[re(["tests",n,"rule"],"required string for blocked fixtures")]:[]]})}function xy(e){if(!Array.isArray(e.tests))return[];let t=new Set(Gc(e));return[...new Set(e.tests.flatMap((n)=>yt(n)&&n.expect==="blocked"&&typeof n.rule==="string"?[n.rule]:[]))].filter((n)=>!t.has(n)).map((n)=>re(["tests"],`blocked fixture references unknown rule "${n}"`))}function Ry(e){if(!Array.isArray(e.allowed_commands)||!Array.isArray(e.rules))return[];let t=new Set(e.allowed_commands.filter((n)=>typeof n==="string"));return e.rules.flatMap((n,r)=>{let o=yt(n)?n.command:void 0;if(typeof o!=="string"||t.has(o))return[];return[re(["rules",r,"command"],`"${o}" must be listed in allowed_commands`)]})}function yt(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function qc(e,t){let n=wc(e,t),r;try{r=hc(n.userConfigTarget,n.projectConfigTarget)}catch(m){if(m instanceof ce)return My(n,m.message);throw m}let o=ls(n.userConfigTarget),i=r?{config:null,errors:[]}:ls(n.projectConfigTarget),s=Vc(n.userConfigPath,o.errors),a=Vc(n.projectConfigPath,i.errors),l=new Set,c=o.config?Uc(o.config,Jr(n.userConfigPath),"user",n.userScope,l):Kc(),u=i.config?Uc(i.config,Jr(n.projectConfigPath),"project",n.projectScope,l):Kc(),f=o.config?.overrides??{},d=i.config?.overrides??{};return{rules:[...Hc(c.rules,f),...Hc(u.rules,d)],transparent_wrappers:ky(o.config,i.config),rulebooks:[...c.rulebooks,...u.rulebooks],errors:[...s,...a,...c.errors,...u.errors],warnings:[...c.warnings,...u.warnings,...c.canValidateOverrides?jc(f,c.knownRuleIds,n.userConfigPath):[],...c.canValidateOverrides?Oy(d,c.knownRuleIds,n.projectConfigPath):[],...u.canValidateOverrides?jc(d,u.knownRuleIds,n.projectConfigPath):[]],userConfig:o.config??void 0,projectConfig:i.config??void 0,...n}}function Uc(e,t,n,r=Mt(Jr(Jr(t)),n==="user"?"user policy":"project policy"),o=new Set){let i=[],s=[],a=e.rules.flatMap((c)=>{let u=wy(c,t,r);if(u.errors.length>0||!u.rulebook)return i.push(...u.errors),[];let f=u.rulebook;if(o.has(f.name))return s.push(`duplicate active rulebook name "${f.name}" for ${c}; 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 o.add(f.name),[{rules:_y(f),rulebook:{source:n,spec:c,name:f.name,version:f.version,rules:f.rules.map((d)=>`${f.name}/${d.name}`)}}]}),l=a.flatMap((c)=>c.rules);return{rules:l,rulebooks:a.map((c)=>c.rulebook),knownRuleIds:new Set(l.map((c)=>c.name)),errors:i,warnings:s,canValidateOverrides:i.length===0}}function _y(e){if(e.rulebook_version===2)return e.rules.map((t)=>({name:`${e.name}/${t.name}`,command:t.command,block_args:[],match:t.match,reason:t.reason,intent:t.intent}));return e.rules.map((t)=>({...t,name:`${e.name}/${t.name}`,match:void 0}))}function wy(e,t,n){let r=Py(e),o=Pc(t,r),i=Iy(o,n);if("error"in i)return{rulebook:null,errors:[i.error]};if(i.content===null)return{rulebook:null,errors:[`missing rulebook file ${o} for ${e}; ${Ay(e)}`]};let s=Ty(i.content);if("problem"in s)return{rulebook:null,errors:[`invalid rulebook ${o}: ${s.problem}; fix that file`]};if(s.rulebook.name!==r)return{rulebook:null,errors:[`rulebook name "${s.rulebook.name}" in ${o} must match source "${e}"; fix that file`]};return{rulebook:s.rulebook,errors:[]}}function Py(e){return Vr(e)?Qi(e).name:e}function Ay(e){return Vr(e)?`run ${Rc} to vendor ${e}`:"create that file or remove that source from the rules config"}function Iy(e,t){try{return{content:jr(qn(t,e))}}catch(n){if(n instanceof ce)return{error:n.message};throw n}}function Ty(e){let t;try{t=JSON.parse(e)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:Wc(t)}}catch(n){return{problem:n instanceof Error?n.message:"invalid rulebook"}}}function ky(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function Hc(e,t){return e.flatMap((n)=>{let r=t[n.name];if(r==="off")return[];if(r&&typeof r==="object")return[{...n,intent:r.intent??n.intent,reason:r.reason}];return[n]})}function jc(e,t,n){return Object.keys(e).filter((r)=>!t.has(r)).map((r)=>`unknown override key "${r}" in ${n}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function Oy(e,t,n){return Object.keys(e).filter((r)=>t.has(r)).map((r)=>`project override cannot target user-scoped rule "${r}" in ${n}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function Vc(e,t){return t.map((n)=>n.startsWith("Unable to access ")?n:`${e}: ${n}`)}function My(e,t){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath}}function Kc(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as jy,readFileSync as Vy}from"node:fs";var Yc=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores, with or without --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"find.delete",category:"Filesystem",label:"find delete",description:"Blocks unsafe find -delete operations.",example:"find . -delete",intent:"scope_down"},{id:"find.delete-git-metadata",category:"Filesystem",label:"find delete Git metadata",description:"Blocks find -delete operations selecting protected Git metadata and hooks.",example:"find .git -delete",intent:"hard_stop",catastrophic:!0},{id:"find.exec-rm-recursive-force",category:"Filesystem",label:"find exec rm -rf",description:"Blocks find -exec rm -rf operations.",example:"find . -exec rm -rf {} +",intent:"scope_down"},{id:"dd.device-write",category:"Filesystem",label:"dd device write",description:"Blocks dd writing to a /dev device.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"mkfs device format",description:"Blocks mkfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],ms=new Set(Yc.map((e)=>e.id)),Qr=Yc,Dy=new Map(Qr.map((e)=>[e.id,e.intent]));function v(e,t){return{id:e,reason:t,intent:Dy.get(e)??"manual_only"}}var ps=[{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"}],eo={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Ny=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Ly=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],gs=[{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"]},...Ly.flatMap((e)=>Ny.map((t)=>({id:["secret.home",e.idSlug,t.slice(1)].join("."),category:"Home path",label:[e.label,t].join(""),description:["Blocks home ",e.label,t," credential backup files."].join(""),suffixParts:[...e.directoryParts,[e.basename,t].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 to=[{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"]}],Zc=[{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"}],Wy=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],hs=Zc.map((e)=>({id:`secret.variant.${e.slug}.separator`,category:"Variant",label:`${e.label}-* / ${e.label}_*`,description:`Blocks ${e.label} variants with dash or underscore suffixes.`,prefix:e.prefix})),ys=Zc.flatMap((e)=>Wy.map((t)=>({id:`secret.variant.${e.slug}.${t.slice(1)}`,category:"Variant",label:`${e.label}${t}`,description:`Blocks ${e.label}${t} private credential variants.`,prefix:e.prefix,suffix:t}))),Zn={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)$/},bs=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((e)=>({id:`secret.ext.${e}`,category:"Extension",label:`.${e}`,description:`Blocks files with the .${e} extension.`,extension:e})),Cs=[{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?$/}],Gy=[...ps,eo,...gs,...hs,...ys,Zn,...bs,...Cs,...to].map((e)=>({id:e.id,category:e.category,label:e.label,...e.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in e?{paths:e.paths}:{description:e.description}})),no=new Set(to.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),Ss=new Set(Gy.map((e)=>e.id));import{isAbsolute as vs,join as Fy,normalize as zy,sep as ro}from"node:path";var oo=process.platform==="win32",Xc=/[*?]/;function Es(e){let t=e.trim(),n=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(oo?t.replaceAll("\\","/"):t);if(!n)return null;let r=n[1]??"",o=n[2]??"";if(Xc.test(r)||o==="."||o==="..")return null;return{root:r||"/",name:o}}function Xn(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function xs(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=Xn(e.trim(),t);if(!vs(n))return"must be an absolute path or start with ~/";return Jn(n,t)}function Rs(e,t){let n=Jc(e,t);if(n===null)return"must be a non-empty path string";if(!vs(n))return null;if(Jn(n,t)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var By="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",$y="cannot cover the guard's own configuration";function Jc(e,t){if(typeof e!=="string"||e.trim()==="")return null;let n=e.trim(),r=oo?n.replaceAll("\\","/"):n;return Xn(r.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function _s(e,t){let n=Jc(e,t);if(n===null)return"must be a non-empty path string";let r=Es(n)?.root??n;if(Xc.test(r))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!vs(r))return null;if(Jn(r,t)!==null)return By;return Uy(r,t)?$y:null}function Uy(e,t){let n=io(e),r=io(Fy(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${ro}`)}function Jn(e,t){let n=io(e),r=io(t);if(n===r)return"cannot be the home directory";let o=n.endsWith(ro)?n:`${n}${ro}`;if(r.startsWith(o))return"cannot contain the home directory";return null}function io(e){let t=zy(e);if(oo)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(oo?3:1)&&t.endsWith(ro))t=t.slice(0,-1);return t}var Qc=30,so=1,ao=365;function eu(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var tu=new Set(Qr.filter((e)=>e.catastrophic).map((e)=>e.id));function w(e,t){if(!e)return null;if(tu.has(e.id))return e;if(t?.destructiveCommandProtectionEnabled===!1)return null;let n=t?.effectiveDestructiveCommandRules[e.id];return n&&!n.enabled?null:e}function ee(e,t,n){if(tu.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function nu(e,t){return Object.freeze(Object.fromEntries(Qr.map((n)=>{let r=n.activationCapability?t[n.activationCapability]:void 0,o=r?.enabled??!0,i=e.destructiveCommandRuleOverrides[n.id],s=n.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...i?{override:i}:{}}:e.destructiveCommandProtectionEnabled?i?{enabled:i==="on",inheritedEnabled:o,changesInherited:i==="on"!==o,source:"rule_override",...n.activationCapability?{activationCapability:n.activationCapability}:{},override:i}:{enabled:o,inheritedEnabled:o,changesInherited:!1,source:r?.source??"built_in_default",...n.activationCapability?{activationCapability:n.activationCapability}:{}}:{enabled:!1,inheritedEnabled:o,changesInherited:!1,source:"master_disabled",...n.activationCapability?{activationCapability:n.activationCapability}:{},...i?{override:i}:{}};return[n.id,Object.freeze(s)]})))}function ru(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:nu(e,t)})}var ou={standard:0,strict:1,paranoid:2};function au(e,t,n=!1,r=e.safety.level){let o=Hy(e,t,r),i=new Set(n?o.map((u)=>u.field):[]),s=(u,f)=>i.has(u)?void 0:f,a=(u,f)=>Object.fromEntries(Object.entries(f??{}).filter(([d])=>!i.has(`${u}.${d}`))),l=(u,f)=>f?.filter((d)=>!i.has(`${u}.${d}`));return{policy:{version:1,safety:{level:s("safety.level",t.safety?.level)??e.safety.level,overrides:{...e.safety.overrides,...a("safety.overrides",t.safety?.overrides)}},workflow:{worktree_mode:s("workflow.worktree_mode",t.workflow?.worktree_mode)??e.workflow.worktree_mode},destructive_command_protection:{enabled:s("destructive_command_protection.enabled",t.destructive_command_protection?.enabled)??e.destructive_command_protection.enabled,overrides:{...e.destructive_command_protection.overrides,...a("destructive_command_protection.overrides",t.destructive_command_protection?.overrides)},allow_paths:ws(e.destructive_command_protection.allow_paths,l("destructive_command_protection.allow_paths",t.destructive_command_protection?.allow_paths))},secret_protection:{enabled:s("secret_protection.enabled",t.secret_protection?.enabled)??e.secret_protection.enabled,overrides:{...e.secret_protection.overrides,...a("secret_protection.overrides",t.secret_protection?.overrides)},deny_paths:ws(e.secret_protection.deny_paths,t.secret_protection?.deny_paths),allow_paths:ws(e.secret_protection.allow_paths,l("secret_protection.allow_paths",t.secret_protection?.allow_paths))},audit:e.audit},weakenings:o.map((u)=>u.message)}}function ws(e,t){return[...new Set([...e,...t??[]])]}function Hy(e,t,n){let r=t.safety?.level,o=Br[n];return[...r&&ou[r]<ou[e.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${e.safety.level} -> ${r}`}]:[],...ln.flatMap((i)=>t.safety?.overrides?.[i]===!1&&(e.safety.overrides[i]??o[i])?[{field:`safety.overrides.${i}`,message:`project policy disables ${i}`}]:[]),...t.workflow?.worktree_mode===!0&&!e.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...t.destructive_command_protection?.enabled===!1&&e.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...t.secret_protection?.enabled===!1&&e.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...iu("destructive_command_protection.overrides",t.destructive_command_protection?.overrides,(i)=>e.destructive_command_protection.enabled&&e.destructive_command_protection.overrides[i]!=="off"),...iu("secret_protection.overrides",t.secret_protection?.overrides,(i)=>e.secret_protection.enabled&&(e.secret_protection.overrides[i]==="on"?!0:e.secret_protection.overrides[i]!=="off"&&!no.has(i))),...e.destructive_command_protection.enabled?su(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths).map((i)=>({field:`destructive_command_protection.allow_paths.${i}`,message:`project policy adds destructive allow path: ${i}`})):[],...e.secret_protection.enabled?su(e.secret_protection.allow_paths,t.secret_protection?.allow_paths).map((i)=>({field:`secret_protection.allow_paths.${i}`,message:`project policy adds secret allow path: ${i}`})):[]]}function iu(e,t,n){return Object.entries(t??{}).flatMap(([r,o])=>o==="off"&&n(r)?[{field:`${e}.${r}`,message:`project policy disables rule ${r}`}]:[])}function su(e,t){return(t??[]).filter((n)=>!e.includes(n))}var Is=new Set(["standard","strict","paranoid"]),du={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:Qc}};function fu(e,t){let n=nb(Wt(e,t),e.home),r=_c(e,t)?{exists:!1,policy:Qn(),errors:[]}:co(cn(t.cwd),e.home),o=qy(r.parsed,e.home),i=et(Z.projectTightenOnly,e.env),s=n.gui??du,a=Object.keys(o.policy).length>0?au(s,o.policy,i,uc(s.safety.level,e.env)):void 0,l=[...n.errors,...r.errors,...o.diagnostics],c=(n.fallback==="defaults"&&a?"salvaged":n.fallback)??(n.gui?void 0:r.fallback)??(l.length>0?"salvaged":void 0),u=o.policy.safety?.level&&a?.policy.safety.level===o.policy.safety.level?"project":n.levelPresent?"user":"default";return{...a?As(a.policy):n.policy,errors:l,...c?{fallback:c}:{},...r.exists?{policyScopes:{levelScope:u,weakenings:a?.weakenings??[],weakeningsIgnored:i}}:{}}}var Ky="project policy audit settings are ignored; audit is user scope only";function qy(e,t){if(!Re(e))return{policy:{},diagnostics:[]};let n=Re(e.safety)?e.safety:{},r=Re(e.workflow)?e.workflow:{},o=Re(e.destructive_command_protection)?e.destructive_command_protection:{},i=Re(e.secret_protection)?e.secret_protection:{},s={...Is.has(n.level)?{level:n.level}:{},...Re(n.overrides)?lu({overrides:mu(n.overrides,ln,["safety","overrides"],Gt)}):{}},a={...typeof o.enabled==="boolean"?{enabled:o.enabled}:{},...o.overrides!==void 0?{overrides:lo(o.overrides,ms,gu,Gt)}:{},...o.allow_paths!==void 0?{allow_paths:fn(o.allow_paths,xs,t,["destructive_command_protection","allow_paths"],Gt)}:{}},l={...typeof i.enabled==="boolean"?{enabled:i.enabled}:{},...i.overrides!==void 0?{overrides:lo(i.overrides,Ss,hu,Gt)}:{},...i.deny_paths!==void 0?{deny_paths:fn(i.deny_paths,Rs,t,["secret_protection","deny_paths"],Gt)}:{},...i.allow_paths!==void 0?{allow_paths:fn(i.allow_paths,_s,t,["secret_protection","allow_paths"],Gt)}:{}};return{policy:lu({safety:s,workflow:typeof r.worktree_mode==="boolean"?{worktree_mode:r.worktree_mode}:{},destructive_command_protection:a,secret_protection:l}),diagnostics:e.audit===void 0?[]:[Ky]}}function mu(e,t,n,r){return Object.fromEntries(t.flatMap((o)=>{let i=e[o];if(typeof i==="boolean")return[[o,i]];if(i!==void 0)r(R([...n,o],Ts));return[]}))}function lu(e){return Object.fromEntries(Object.entries(e).flatMap((t)=>Object.keys(t[1]).length>0?[t]:[]))}var Gt=()=>{return},Ts="must be a boolean",ks="must be an object if provided",pu=`must be an integer between ${so} and ${ao}`,gu={path:["destructive_command_protection","overrides"],label:"destructive command"},hu={path:["secret_protection","overrides"],label:"secret protection"},Yy=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Zy(e,t){let n=[];return{policy:yu(e,t,(o)=>{n.push(o)}),issues:n}}function Xy(e,t){return yu(e,t,Gt)}function yu(e,t,n){if(!Re(e))return n(R([],"Config must be an object")),Qn();if(e.version!==1)n(R(["version"],"must be 1"));let r=dn(e.safety,["safety"],["level","overrides"],n),o=dn(r.overrides,["safety","overrides"],ln,n),i=dn(e.workflow,["workflow"],["worktree_mode"],n),s=dn(e.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],n),a=dn(e.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],n),l=dn(e.audit,["audit"],["retention_days"],n);return bu(e,Yy,[],n),{version:1,safety:{level:Jy(r.level,n),overrides:mu(o,ln,["safety","overrides"],n)},workflow:{worktree_mode:Ps(i.worktree_mode,["workflow","worktree_mode"],!1,n)},destructive_command_protection:{enabled:Ps(s.enabled,["destructive_command_protection","enabled"],!0,n),overrides:lo(s.overrides,ms,gu,n),allow_paths:fn(s.allow_paths,xs,t,["destructive_command_protection","allow_paths"],n)},secret_protection:{enabled:Ps(a.enabled,["secret_protection","enabled"],!0,n),overrides:lo(a.overrides,Ss,hu,n),deny_paths:fn(a.deny_paths,Rs,t,["secret_protection","deny_paths"],n),allow_paths:fn(a.allow_paths,_s,t,["secret_protection","allow_paths"],n)},audit:{retention_days:Qy(l.retention_days,n)}}}function dn(e,t,n,r){if(e===void 0)return{};if(!Re(e))return r(R(t,ks)),{};return bu(e,n,t,r),e}function bu(e,t,n,r){for(let o of Object.keys(e).filter((i)=>!t.includes(i)))r({path:n,message:o,kind:"unknownKeys"})}function Jy(e,t){if(e===void 0)return"standard";if(Is.has(e))return e;return t(R(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Ps(e,t,n,r){if(typeof e==="boolean")return e;if(e!==void 0)r(R(t,Ts));return n}function Qy(e,t){if(!(e===void 0||typeof e==="number"&&Number.isInteger(e)&&e>=so&&e<=ao))t(R(["audit","retention_days"],pu));return eu(e)}function lo(e,t,n,r){if(e===void 0)return{};if(!Re(e))return r(R(n.path,ks)),{};return Object.fromEntries(Object.entries(e).flatMap(([o,i])=>{if(!t.has(o))return r({path:[...n.path,o],message:`unknown ${n.label} rule id "${o}"`,kind:"key"}),[];if(i==="on"||i==="off")return[[o,i]];return r(R([...n.path,o],'must be "on" or "off"')),[]}))}function fn(e,t,n,r,o){if(e===void 0)return[];if(!Array.isArray(e))return o(R(r,"must be an array of paths")),[];return e.flatMap((i,s)=>{let a=t(i,n);if(a===null)return[i];return o(typeof i==="string"?re([...r,s],a):R([...r,s],a)),[]})}function Re(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Qn(){return structuredClone(du)}function co(e,t){if(!jy(e))return{exists:!1,policy:Qn(),errors:[]};try{let n=Vy(e,"utf-8");if(!n.trim())return{exists:!0,policy:Qn(),errors:[`${e}: Config file is empty`],fallback:"defaults"};let r=JSON.parse(n),o=Zy(r,t);if(o.issues.length===0)return{exists:!0,parsed:r,policy:o.policy,errors:[]};return{exists:!0,parsed:r,policy:o.policy,errors:o.issues.map((i)=>`${e}: ${tb(i)}`),fallback:Re(r)?"salvaged":"defaults"}}catch(n){let r=n instanceof Error?n.message:String(n);return{exists:!0,policy:Qn(),errors:[`${e}: ${n instanceof SyntaxError?"Invalid JSON":r}`],fallback:"defaults"}}}var eb=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[ks,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[Ts,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[pu,`not an integer between ${so} and ${ao}`]]);function tb(e){let t=ds(e.path);if(e.kind==="unknownKeys")return`${t===""?"":`${t}.`}${e.message}: unknown field`;if(e.kind==="key")return`${t}: unknown rule id`;let n=eb.get(e.message)??e.message;return t===""?n:`${t}: ${n}`}function nb(e,t){let n=co(e,t);if(!n.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!Re(r))return{policy:uu(),errors:[]};let o=Xy(r,t);return{policy:As(o),gui:o,errors:[],levelPresent:cu(r)}}if(n.parsed===void 0)return{policy:uu(),errors:n.errors,...n.fallback?{fallback:n.fallback}:{}};return{policy:As(n.policy),gui:n.policy,errors:n.errors,...n.fallback?{fallback:n.fallback}:{},levelPresent:cu(n.parsed)}}function cu(e){let t=Re(e)&&Re(e.safety)?e.safety:{};return Is.has(t.level)}function Cu(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...no].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function uu(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Cu({}),denyPaths:[],allowPaths:[]}}}function As(e){return{safety:rb(e.safety),worktreeMode:e.workflow.worktree_mode,destructiveCommandProtectionEnabled:e.destructive_command_protection.enabled,destructiveCommandRuleOverrides:e.destructive_command_protection.overrides,destructiveCommandAllowPaths:e.destructive_command_protection.allow_paths,secretProtection:{enabled:e.secret_protection.enabled,disabledRules:Cu(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function rb(e){let t={...e.overrides.fail_closed!==void 0?{failClosed:e.overrides.fail_closed}:{},...e.overrides.paranoid_rm!==void 0?{paranoidRm:e.overrides.paranoid_rm}:{},...e.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:e.overrides.paranoid_interpreters}:{}};return{level:e.level,...Object.keys(t).length>0?{overrides:t}:{}}}function Su(e,t){let n=qc(e,t),r=fu(e,t),o={rules:n.rules,transparentWrappers:n.transparent_wrappers,safety:r.safety,worktreeMode:r.worktreeMode,destructiveCommandProtectionEnabled:r.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:r.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:r.destructiveCommandAllowPaths,secretProtection:{enabled:r.secretProtection.enabled??!0,disabledRules:r.secretProtection.disabledRules??[],denyPaths:r.secretProtection.denyPaths,allowPaths:r.secretProtection.allowPaths??[]}},i={...n.userConfig?.overrides,...n.projectConfig?.overrides},s=Object.freeze(Object.fromEntries(o.rules.map((a)=>{let l=n.rulebooks.find((u)=>u.rules.includes(a.name)),c=i[a.name];return[a.name,Object.freeze({id:a.name,...l?{rulebook:Object.freeze({name:l.name,version:l.version}),...ab(l.spec)?{source:l.spec}:{}}:{},...c&&typeof c==="object"?{override:Object.freeze({type:"reason",reason:c.reason})}:{}})]})));return lb(o,ob(n,r),s,r.policyScopes)}function ob(e,t){let n=sb(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:cb(e.errors.length>0?ib(e.errors):void 0,e.warnings.length>0?Ms(e.warnings.join("; ")):void 0,n)}}function ib(e){return`${Ms(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function sb(e){if(e.errors.length===0)return;let t=e.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${e.errors.join("; ")}. Enforcing ${t}; the invalid values are not active. Fix the policy file manually`}function ab(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function lb(e,t,n=Object.freeze({}),r){let o=Os(structuredClone(e)),i=r?{policyScopes:Os(structuredClone(r))}:{};if(!t)return Object.freeze({state:"ready",policy:o,diagnostics:Object.freeze([]),ruleMetadata:n,...i});return Object.freeze({state:"degraded",policy:o,diagnostics:Object.freeze([...t.diagnostics]),reason:t.reason,ruleMetadata:n,...i})}function Os(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))Os(t);return Object.freeze(e)}function cb(...e){return Ms(e.filter((t)=>!!t).join("; "))}function Ms(e){return/[.!?]$/.test(e)?e:`${e}.`}function vu(e){let t=e.effectiveCapabilities,n=e.strict??t.fail_closed.enabled,r=e.paranoidRm??t.paranoid_rm.enabled,o=e.paranoidInterpreters??t.paranoid_interpreters.enabled,i={fail_closed:Ds(t.fail_closed,e.strict,"strict"),paranoid_rm:Ds(t.paranoid_rm,e.paranoidRm,"paranoidRm"),paranoid_interpreters:Ds(t.paranoid_interpreters,e.paranoidInterpreters,"paranoidInterpreters")};return{policy:ru(e.policySnapshot.policy,i),effectiveCapabilities:i,effectiveLevel:Ui({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}function Ds(e,t,n){if(t===void 0||t===e.enabled)return e;return{enabled:t,source:"capability_override",sources:[...e.sources,`analysis options.${n}`]}}import{dirname as S_,isAbsolute as v_,join as E_,parse as x_,resolve as R_,sep as __}from"node:path";function er(e,t){if(e!=="powershell")return t[0]?.provenance==="command-substitution";let n=t[0]?.text==="&"||t[0]?.text==="."?1:0,r=t[n]?.provenance;return r!==void 0&&r!=="literal"}var ub=/^[A-Za-z_][A-Za-z0-9_]*=/;function uo(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function tr(e){let t=uo(e.words[0],"time")?1:0,n=t===1&&uo(e.words[t],"-p")?t+1:t,r=t===1&&uo(e.words[n],"--")?n+1:n,o=uo(e.words[r],"!")?r+1:r,i=e.words.slice(o).find((s)=>!ub.test(s.text));return i?.provenance==="literal"?i.text:void 0}var bt=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function fo(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function db(e){return Object.freeze({...e,span:Object.freeze(e.span),words:Object.freeze(e.words),redirections:Object.freeze(e.redirections.map((t)=>Object.freeze({...t,span:Object.freeze(t.span),...t.heredoc?{heredoc:Object.freeze({...t.heredoc,bodySpan:Object.freeze(t.heredoc.bodySpan),terminatorSpan:Object.freeze(t.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(e.nested.map((t)=>me(t)))})}function mo(e,t,n){e.push(n),t.reset()}function po(e){let t=[];return{parts:t,push:(n,r,o)=>{if(r<=n)return;t.push({raw:e.slice(n,r),span:{start:n,end:r},provenance:o})}}}function Ns(e){let t=e.parts??[{raw:e.raw,span:e.span,provenance:e.provenance}];return Object.freeze({kind:"word",...e,span:Object.freeze(e.span),parts:Object.freeze(t.map((n)=>Object.freeze({...n,span:Object.freeze(n.span)})))})}function mn(e,t,n,r,o,i,s){return Ns({text:r,raw:e.slice(t,n),span:{start:t,end:n},provenance:o,quoted:i,...s?{parts:s}:{}})}function me(e){return Object.freeze({...e,span:Object.freeze(e.span),issues:Object.freeze(e.issues.map((t)=>Object.freeze({...t}))),nodes:Object.freeze(e.nodes.map((t)=>{if(t.kind==="command")return db(t);if(t.kind==="group"||t.kind==="function")return Object.freeze({...t,span:Object.freeze(t.span),body:me(t.body)});return Object.freeze({...t,span:Object.freeze(t.span)})}))})}function Ls(e,t,n){if(t>=n||xu(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!xu(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=Eu(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=Eu(e,s+1,n,'"');r+=l.text,i||=!l.closed,s=l.next;continue}if(a==="\\"){o=!0;let l=e[s+1];if(!l||l===`
9
+ `||l==="\r"){i=!0;break}r+=l,s+=2;continue}if(a==="`"||e.startsWith("$(",s)||e.startsWith("${",s)||e.startsWith("<(",s)||e.startsWith(">(",s))i=!0;r+=a,s++}return{delimiter:r,quoted:o,next:s,ambiguous:i}}function Ws(e,t,n,r){let o=[],i=t;for(let s of r){let a=i,l=!1;while(i<n){let c=fb(e,i,n);if((s.stripTabs?c.text.replace(/^\t+/,""):c.text)===s.delimiter){s.attach({body:s.stripTabs?mb(e.slice(a,i)):e.slice(a,i),delimiter:s.delimiter,quotedDelimiter:s.quotedDelimiter,bodySpan:{start:a,end:i},terminatorSpan:{start:i,end:c.contentEnd}}),i=c.next,l=!0;break}if(c.next<=i)break;i=c.next}if(l)continue;return o.push({code:"unterminated-heredoc",message:`heredoc delimiter ${s.delimiter} was not found`}),{next:n,issues:o,terminated:!1}}return{next:i,issues:o,terminated:!0}}function Eu(e,t,n,r){let o="",i=t;while(i<n&&e[i]!==`
10
+ `&&e[i]!=="\r"){let s=e[i]??"";if(s===r)return{text:o,next:i+1,closed:!0};if(r==='"'&&s==="\\"&&e[i+1]){let a=e[i+1]??"";o+=["$","`",'"',"\\"].includes(a)?a:`\\${a}`,i+=2;continue}o+=s,i++}return{text:o,next:i,closed:!1}}function xu(e){return e!=="\r"&&(/[\s;&|<>)]/u.test(e)||e==="`")}function fb(e,t,n){let r=t;while(r<n&&e[r]!==`
11
+ `)r++;let o=r>=n?n:r+1;return{text:e.slice(t,r),contentEnd:r,next:o}}function mb(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Au=new Set(["&&","||","|","|&"]),pb=new Set(["!","do","elif","else","if","then","until","while"]);function Iu(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return me({kind:"program",dialect:"posix",source:e,span:n,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${t.maxInputLength} UTF-16 code units`}],nodes:[]});let r={wordsUsed:0,maxWords:t.maxWords,quotedExpansionEnd:1/0},o=yo(e,0,e.length,t,r,0),i=xb(e,r.quotedExpansionEnd,o.nodes)?[...o.issues,Ou]:o.issues;return me({kind:"program",dialect:"posix",source:e,span:n,status:Co(i,o.limited),issues:i,nodes:o.nodes})}function yo(e,t,n,r,o,i,s){let a=[],l=[],c=fo(),u=[],f=()=>{if(c.words.length===0&&c.redirections.length===0)return;let m={start:c.start,end:c.end},g=c.words.map((p)=>p.text);mo(a,c,{kind:"command",dialect:"posix",source:e.slice(m.start,m.end),span:m,words:c.words,redirections:c.redirections,nested:c.nested,displayText:l.length>0&&a.length===0?e.slice(t,n):g.join(" ")})},d=t;while(d<n){let m=e[d];if(!m)break;if(s&&m===s)return f(),Pu(a,l),{nodes:a,issues:l,next:d+1,closed:!0,limited:!1,pendingHeredocs:u};if(rr(m)){if(m===`
12
12
  `||m==="\r"){f();let I=m==="\r"&&e[d+1]===`
13
- `?d+2:d+1,T=a.at(-1);if(T?.kind!=="connector"||!vu.has(T.operator))a.push(Object.freeze({kind:"connector",operator:e.slice(d,I),span:Object.freeze({start:d,end:I})}));if(u.length>0){let M=Ms(e,I,n,u.splice(0));l.push(...M.issues),d=M.next;continue}d=I;continue}d++;continue}if(m==="#"){while(d<n&&e[d]!==`
14
- `&&e[d]!=="\r")d++;continue}let g=c.start===-1?RC(e,d,n):void 0;if(g){if(Ns(a,l),i>=r.maxDepth)return un(a,l,d,"depth-limit",r.maxDepth);if(!Ds(o))return un(a,l,d,"word-limit",r.maxWords);let I=mo(e,g.braceIndex+1,n,r,o,i+1,"}"),T=I.next,M={start:g.braceIndex+1,end:I.closed?T-1:T},Y=Cu(e,M,I);if(a.push({kind:"function",name:g.name,span:{start:d,end:T},body:Y}),l.push(...I.issues),I.pendingHeredocs.length>0||Qn(I.nodes))l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(u.push(...I.pendingHeredocs),I.limited)return fo(a,l,I.next);if(!I.closed)l.push({code:"unclosed-function-body",message:"function body is not closed"});d=T;continue}let p=po(e,d);if(p){if(f(),!Tu(a.at(-1)))l.push({code:"unexpected-connector",message:`connector ${p} has no preceding command`});a.push(Object.freeze({kind:"connector",operator:p,span:Object.freeze({start:d,end:d+p.length})})),d+=p.length;continue}if(m===")"){f(),l.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),a.push({kind:"unknown",source:m,span:{start:d,end:d+1}}),d++;continue}if((m==="("||m==="{"&&dC(e,d,n))&&c.start===-1){if(Ns(a,l),i>=r.maxDepth)return un(a,l,d,"depth-limit",r.maxDepth);let I=m==="("?")":"}",T=mo(e,d+1,n,r,o,i+1,I),M=T.next,Y={start:d+1,end:T.closed?M-1:M},ue=Cu(e,Y,T);if(a.push({kind:"group",style:m==="("?"subshell":"brace",span:{start:d,end:M},body:ue}),l.push(...T.issues),T.pendingHeredocs.length>0||Qn(T.nodes))l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(u.push(...T.pendingHeredocs),T.limited)return fo(a,l,T.next);if(!T.closed)l.push({code:m==="("?"unclosed-subshell":"unclosed-brace-group",message:`${m} group is not closed`});d=M;continue}let h=(m==="<"||m===">")&&e[d+1]!=="("?aC(e,d):null;if(h){let I=c.words.at(-1),T=I&&I.span.end===d&&/^[0-9]+$/.test(I.raw)?Number(I.raw):void 0;if(T!==void 0)c.words.pop();let M=T===void 0?d:I?.span.start??d;c.start=c.start===-1?d:c.start;let Y=d+h.length;while(Y<n&&/[ \t]/.test(e[Y]??""))Y++;let ue=e[Y],Xe=Y>d+h.length&&ue==="#",Ce=!ue||go(ue)||!!po(e,Y)||ue===s||ue===")"||Xe||(ue==="<"||ue===">")&&e[Y+1]!=="(",Pt=h==="<<"||h==="<<-",z=Pt?Os(e,Y,n):void 0,D=z?{word:cn(e,Y,z.next,z.delimiter,"literal",z.quoted),nested:[],issues:[],next:z.next,limited:!1}:!Ce?Ls(e,Y,n,r,o,i):void 0;if(D){if(l.push(...D.issues),D.limited)return fo(a,l,D.next);if(!Ds(o))return un(a,l,D.next,"word-limit",r.maxWords)}let se=D?.next??d+h.length,J={kind:"redirection",operator:h,span:{start:M,end:se},...T===void 0?{}:{fd:T},...D?{target:D.word}:{}};if(c.redirections.push(J),Pt&&!z)l.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if(z){if(z.ambiguous||z.delimiter.length===0)l.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let Q=c.nested;u.push({delimiter:z.delimiter,quotedDelimiter:z.quoted,stripTabs:h==="<<-",attach:(be)=>{if(J.heredoc=be,be.quotedDelimiter)return;Q.push(...iC(e,be.bodySpan.start,be.bodySpan.end,r,o,i+1))}})}if(!Pt&&!D)l.push({code:"missing-redirection-target",message:`redirection ${h} requires a target word`});if(D)c.nested.push(...D.nested);c.end=se,d=se;continue}let C=c.start===-1;if(C)Ns(a,l);let b=Ls(e,d,n,r,o,i);if(l.push(...b.issues),b.limited)return fo(a,l,b.next);let y=pC(c.words)?bC(e,b.word,o.max-o.used,r.maxDepth,r.maxInputLength):void 0;if(y?.limitCode)return un(a,l,b.next,y.limitCode,y.limitCode==="word-limit"?r.maxWords:y.limitCode==="depth-limit"?r.maxDepth:r.maxInputLength);let E=y?.words??[b.word];for(let I of E){if(!Ds(o))return un(a,l,b.next,"word-limit",r.maxWords);c.words.push(I)}if(c.start=c.start===-1?d:c.start,c.end=b.next,c.nested.push(...b.nested),C&&ku(b.word))f();d=b.next>d?b.next:d+1}return f(),Su(a,l),l.push(..._C(u)),{nodes:a,issues:l,next:d,closed:s===void 0,limited:!1,pendingHeredocs:[]}}function Cu(e,t,n){return{kind:"program",dialect:"posix",source:e.slice(t.start,t.end),span:t,status:ho(n.issues,n.limited),issues:n.issues,nodes:n.nodes}}function Ls(e,t,n,r,o,i){let s="",a=t,l=!1,c="literal",u=[],f=[],d=!1;while(a<n){let m=e[a],g=(m==="<"||m===">")&&e[a+1]==="(";if(!m||go(m)||(m===";"||m==="|"||m==="&")&&po(e,a)||(m==="<"||m===">")&&!g)break;if(m===")")break;if(m==="'"){l=!0;let h=e.indexOf("'",a+1);if(h===-1||h>=n){s+=e.slice(a+1,n),f.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),a=n;break}s+=e.slice(a+1,h),a=h+1;continue}if(m==='"'){l=!0;let h=oC(e,a,n,r,o,i);if(s+=h.text,u.push(...h.nested),f.push(...h.issues),d||=h.limited,c=Jn(c,h.provenance),a=h.next,d)break;continue}if(e.startsWith("$'",a)){l=!0;let h=lC(e,a+2,n);if(s+=h.text,f.push(...h.issues),!h.closed)f.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});a=h.next;continue}if(m==="\\"){let h=e[a+1];if(!h){f.push({code:"trailing-escape",message:"escape has no following character"}),a++;break}if(h===`
15
- `){a+=2;continue}s+=h,a+=2;continue}let p=m==="$"||m==="<"||m===">"||m==="`"?yo(e,a,n,r,o,i):null;if(p){let h=xu(p,u,f);if(d||=h.limited,c=Jn(c,h.provenance),a=h.next,d)break;continue}if(m==="$"){let h=wu(e,a,n,s,c);s=h.text,c=h.provenance,a=h.next;continue}if(m==="*"||m==="?"||m==="[")c=Jn(c,"glob");s+=m,a++}return{word:cn(e,t,a,s,c,l,c==="literal"?void 0:uC(e,t,a)),nested:u,issues:f,next:a,limited:d}}function oC(e,t,n,r,o,i){let s="",a="literal",l=[],c=[],u=!1,f=t+1;while(f<n){let d=e[f];if(d==='"')return{text:s,provenance:a,nested:l,issues:c,next:f+1,limited:u};if(d==="\\"&&e[f+1]){let g=e[f+1]??"";if(g===`
16
- `){f+=2;continue}if(g==="\r"&&e[f+2]===`
17
- `){f+=3;continue}s+=["$","`",'"',"\\"].includes(g)?g:`\\${g}`,f+=2;continue}if(e.startsWith("$((",f)){let g=Ws(e,f+3,n,"))"),p=g===-1?n:g+2;if(s+=e.slice(f,p),g===-1)c.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});f=p;continue}let m=yo(e,f,n,r,o,i);if(m){let g=xu(m,l,c);if(f=g.next,u||=g.limited,a=Jn(a,g.provenance),u)return{text:s,provenance:a,nested:l,issues:c,next:f,limited:u};continue}if(d==="$"){let g=wu(e,f,n,s,a);s=g.text,a=g.provenance,f=g.next;continue}s+=d??"",f++}return c.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:s,provenance:a,nested:l,issues:c,next:n,limited:u}}function yo(e,t,n,r,o,i){let s=e.startsWith("$((",t),a=e.startsWith("$(",t)&&!s,l=e.startsWith("<(",t)||e.startsWith(">(",t),c=e[t]==="`";if(!s&&!a&&!l&&!c)return null;let u=s?3:c?1:2,f=s?"))":c?"`":")",d=Ws(e,t+u,n,f),m=d===-1?n:d,g=d===-1?n:d+f.length;if(i>=r.maxDepth)return{program:xC(e,t+u,m,"depth-limit"),next:g,provenance:s?"arithmetic":"command-substitution"};if(s){let b=[],y=[],E=!1,I=t+u;while(I<m){let T=yo(e,I,m,r,o,i+1);if(!T){I++;continue}if(b.push(...T.program.nodes),y.push(...T.program.issues),E||=T.program.status==="limited",I=T.next,E)break}if(d===-1)y.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:me({kind:"program",dialect:"posix",source:e.slice(t+u,m),span:{start:t+u,end:m},status:ho(y,E),issues:y,nodes:b}),next:g,provenance:"arithmetic"}}let p=mo(e,t+u,m,r,o,i+1),h=d===-1?[{code:"unclosed-command-substitution",message:`${e.slice(t,t+u)} substitution is not closed`}]:[],C=(c||l)&&Qn(p.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[];return{program:me({kind:"program",dialect:"posix",source:e.slice(t+u,m),span:{start:t+u,end:m},status:ho([...p.issues,...h,...C],p.limited),issues:[...p.issues,...h,...C],nodes:p.nodes}),next:g,provenance:"command-substitution"}}function iC(e,t,n,r,o,i){let s=[],a=t;while(a<n){let l=e[a];if(l==="\\"){a+=2;continue}let c=l==="$"||l==="`"?yo(e,a,n,r,o,i):null;if(!c){a++;continue}if(s.push(c.program),a=c.next,c.program.status==="limited")break}return s}function xu(e,t,n){return t.push(e.program),n.push(...e.program.issues),{provenance:e.provenance,next:e.next,limited:e.program.status==="limited"}}function Ws(e,t,n,r){if(r==="`"){for(let a=t;a<n;a++){if(e[a]==="\\"){a++;continue}if(e[a]==="`")return a}return-1}let o=1,i={single:!1,double:!1},s=[];for(let a=t;a<n;a++){let l=e[a];if((l===`
18
- `||l==="\r")&&s.length>0){let u=l==="\r"&&e[a+1]===`
19
- `?a+2:a+1,f=Ms(e,u,n,s.splice(0));if(!f.terminated)return-1;a=f.next-1;continue}let c=Ru(e,a,t,n,i);if(c!==null){a=c;continue}if(!i.double&&e.startsWith("$((",a)){let u=sC(e,a+3,n);if(u===-1)return-1;a=u+1;continue}if(r===")"&&!i.double&&l==="<"&&e[a+1]==="<"&&e[a+2]!=="<"){let u=e[a+2]==="-",f=a+(u?3:2);while(f<n&&/[ \t]/.test(e[f]??""))f++;let d=Os(e,f,n);if(d){s.push({delimiter:d.delimiter,quotedDelimiter:d.quoted,stripTabs:u,attach:()=>{return}}),a=d.next-1;continue}}if(e.startsWith("$(",a)&&!e.startsWith("$((",a)){o++,a++;continue}if(l==="("&&!i.double)o++;if(l===")"&&!i.double){if(o--,o===0)return r==="))"&&e[a+1]!==")"?-1:a}}return-1}function sC(e,t,n){let r=1,o={single:!1,double:!1};for(let i=t;i<n;i++){let s=e[i],a=Ru(e,i,t,n,o);if(a!==null){i=a;continue}if(e.startsWith("$(",i)&&!e.startsWith("$((",i)){r++,i++;continue}if(s==="("&&!o.double)r++;if(s!==")"||o.double)continue;if(r--,r===0)return e[i+1]===")"?i:-1}return-1}function Ru(e,t,n,r,o){let i=e[t];if(i==="\\"&&!o.single)return t+1;if(!o.double&&i==="'")o.single=!o.single;if(!o.single&&i==='"')o.double=!o.double;if(o.single)return t;if(o.double||i!=="#"||!wC(e,t,n))return null;let s=t;while(s+1<r&&e[s+1]!==`
20
- `&&e[s+1]!=="\r")s++;return s}function po(e,t){let n=e[t];if(n===";")return";";if(n==="&")return e[t+1]==="&"?"&&":"&";if(n==="|")return e[t+1]==="|"?"||":e[t+1]==="&"?"|&":"|";return null}function aC(e,t){let n=e[t];if(n===">"){if(e[t+1]===">")return">>";if(e[t+1]==="&")return">&";return e[t+1]==="|"?">|":">"}if(n!=="<")return null;if(e.startsWith("<<<",t))return"<<<";if(e.startsWith("<<-",t))return"<<-";if(e[t+1]==="<")return"<<";if(e[t+1]==="&")return"<&";if(e[t+1]===">")return"<>";return"<"}function go(e){let t=e.charCodeAt(0);if(t===32||t>=9&&t<=13)return!0;if(t<128)return!1;return/\s/u.test(e)}function _u(e,t,n){if(e[t+1]==="{"){let o=e.indexOf("}",t+2);return o===-1||o>=n?n:o+1}let r=t+1;while(r<n&&/[A-Za-z0-9_?@#$!*-]/.test(e[r]??""))r++;return r===t+1?t+1:r}function lC(e,t,n){let r="",o=[],i=t;while(i<n){let s=e[i];if(s==="'")return{text:r,next:i+1,closed:!0,issues:o};if(s!=="\\"){r+=s??"",i++;continue}let a=cC(e,i+1,n);if(r+=a.text,a.invalidCodePoint!==void 0)o.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${a.invalidCodePoint}`});i=a.next}return{text:r,next:n,closed:!1,issues:o}}function cC(e,t,n){let r=e[t];if(!r||t>=n)return{text:"\\",next:t};let o=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
21
- `],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(o.has(r))return{text:o.get(r)??r,next:t+1};if(r==="x")return uo(e,t+1,n,16,2,t+1);if(r==="u")return uo(e,t+1,n,16,4,t+1);if(r==="U")return uo(e,t+1,n,16,8,t+1);if(/[0-7]/.test(r))return uo(e,t,n,8,3,t+1);return{text:r,next:t+1}}function uo(e,t,n,r,o,i){let s=r===16?/[0-9a-fA-F]/:/[0-7]/,a="",l=t;while(l<n&&a.length<o&&s.test(e[l]??""))a+=e[l],l++;if(!a)return{text:e[i-1]??"",next:i};let c=Number.parseInt(a,r);return c>1114111||c>=55296&&c<=57343?{text:"�",next:l,invalidCodePoint:c}:{text:String.fromCodePoint(c),next:l}}function ho(e,t=!1){if(t)return"limited";if(e.some((n)=>n.code==="invalid-ansi-c-code-point"||n.code==="missing-heredoc-delimiter"||n.code==="ambiguous-heredoc-delimiter"||n.code==="unterminated-heredoc"||n.code==="unsupported-heredoc-context"))return"invalid";return e.length>0?"partial":"complete"}function wu(e,t,n,r,o){let i=_u(e,t,n);return{text:r+e.slice(t,i),provenance:Jn(o,"variable"),next:i}}function uC(e,t,n){let r=co(e),o=t,i=!1,s=!1,a=t;while(a<n){let l=e[a];if(l==="\\"&&!i){a+=2;continue}if(!s&&l==="'"){i=!i,a++;continue}if(!i&&l==='"'){s=!s,a++;continue}if(i){a++;continue}let c=e.startsWith("$((",a),u=e.startsWith("$(",a)&&!c,f=!s&&(e.startsWith("<(",a)||e.startsWith(">(",a)),d=l==="`";if(c||u||f||d){let m=c?3:d?1:2,g=c?"))":d?"`":")",p=Ws(e,a+m,n,g),h=p===-1?n:p+g.length;r.push(o,a,"literal"),r.push(a,h,c?"arithmetic":"command-substitution"),a=h,o=h;continue}if(l==="$"){let m=_u(e,a,n);if(m>a+1){r.push(o,a,"literal"),r.push(a,m,"variable"),a=m,o=m;continue}}if(!s&&(l==="*"||l==="?"||l==="[")){r.push(o,a,"literal"),r.push(a,a+1,"glob"),a++,o=a;continue}a++}return r.push(o,n,"literal"),r.parts}function Jn(e,t){if(t==="command-substitution"||e==="command-substitution")return"command-substitution";if(t==="arithmetic"||e==="arithmetic")return"arithmetic";if(t==="variable"||e==="variable")return"variable";if(t==="glob"||e==="glob")return"glob";return e}function dC(e,t,n){return t+1>=n||go(e[t+1]??"")||po(e,t+1)!==null}var fC=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),mC=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function pC(e){let t=0;while(t<=e.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]?.text??""))t++;if(t===e.length)return!0;let n=gC(e,t);if(n===void 0||n===null)return!1;t=n}return!1}function gC(e,t){let n=e[t]?.text.toLowerCase();if(n==="command")return hC(e,t);if(n==="env")return yC(e,t);if(n==="sudo")return CC(e,t);return}function hC(e,t){if(e[t+1]?.text==="-v")return null;for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(r==="-p"||r==="-v"||r==="-V"||/^-[pvV]+$/.test(r))continue;return n}return e.length}function yC(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(fC.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-u=")||r.startsWith("--unset=")||r.startsWith("-C")&&r.length>2||r.startsWith("--chdir=")||r.startsWith("-S")&&r.length>2||r.startsWith("--split-string=")||r.startsWith("-P"))continue;if(r.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(r))continue;return n}return e.length}function CC(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(mC.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-"))continue;return n}return e.length}function Au(e,t,n,r){if(e.provenance!=="literal"||!e.raw.includes("{"))return;let o=Pu(e.raw,t,n,r,!0);if(!o)return;if("limited"in o)return{limited:!0};let i=o.values.map((s)=>Iu(s,n));if(i.some((s)=>s===null))return{limited:!0};return{words:[...new Set(i.filter((s)=>s!==null&&s!==""))]}}function bC(e,t,n,r,o){if(t.provenance!=="literal"||!t.raw.includes("{"))return;let i=Pu(t.raw,n,r,o,!1);if(!i)return;if("limited"in i){if(i.limited==="expansions")return{limitCode:"depth-limit"};return{limitCode:i.limited==="length"?"brace-expansion-limit":"word-limit"}}let s=i.values.map((a)=>Iu(a,r));if(s.some((a)=>a===null))return;return{words:s.filter((a)=>a!==null&&a!=="").map((a)=>cn(e,t.span.start,t.span.end,a,"literal",!1))}}function Pu(e,t,n,r,o){let i=[e],s=e.length,a=0;while(!0){let l=i.findIndex((m)=>bu(m,o));if(l===-1)break;if(++a>n)return{limited:"expansions"};let c=i[l]??"",u=bu(c,o);if(!u||u.kind==="range")return{limited:"expansions"};let f=u.start+c.length-u.end,d=u.alternatives.reduce((m,g)=>m+f+g.length,0);if(s-c.length+d>r)return{limited:"length"};if(i.length-1+u.alternatives.length>t)return{limited:"words"};i.splice(l,1,...SC(c,u)),s+=d-c.length}return a===0?void 0:{values:i}}function bu(e,t){let n=[],r,o=null,i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(i){i=!1;continue}if(a==="\\"&&o!=="'"){i=!0;continue}if(a===o){o=null;continue}if(o===null&&(a==="'"||a==='"')){o=a;continue}if(o!==null)continue;if(a==="{"){n.push({start:s,commas:[]});continue}if(a===","&&n.length>0){n.at(-1)?.commas.push(s);continue}if(a!=="}"||n.length===0)continue;let l=n.pop();if(!l)continue;let c=l.commas.length>0?{kind:"alternatives",start:l.start,end:s+1,commas:l.commas}:t&&EC(e.slice(l.start+1,s))?{kind:"range",start:l.start,end:s+1}:void 0;if(c&&(!r||c.start<r.start))r=c}if(!r||r.kind==="range")return r;return{kind:r.kind,start:r.start,end:r.end,alternatives:vC(e,r)}}function SC(e,t){return t.alternatives.map((n)=>`${e.slice(0,t.start)}${n}${e.slice(t.end)}`)}function vC(e,t){let n=[t.start,...t.commas,t.end-1];return n.slice(0,-1).map((r,o)=>e.slice(r+1,n[o+1]))}function EC(e){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(e)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(e)}function Iu(e,t){let n=`x${e}`,r=Ls(n,0,n.length,{maxInputLength:n.length,maxWords:1,maxDepth:t},{used:0,max:1},0);if(r.limited||r.issues.length>0||r.next!==n.length||r.word.provenance!=="literal")return null;return r.word.text.slice(1)}function xC(e,t,n,r){return me({kind:"program",dialect:"posix",source:e.slice(t,n),span:{start:t,end:n},status:"limited",issues:[{code:r,message:"command structure exceeds parser limit"}],nodes:[]})}function un(e,t,n,r,o){return{nodes:e,issues:[...t,{code:r,message:`command structure exceeds parser limit ${o}`}],next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function fo(e,t,n){return{nodes:e,issues:t,next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function Ds(e){return e.used++,e.used<=e.max}function RC(e,t,n){let r=e.slice(t,n),o=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(r)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(r),i=o?.[1];if(!o||!i)return;return{name:i,braceIndex:t+o[0].lastIndexOf("{")}}function Qn(e){return e.some((t)=>{if(t.kind==="command")return t.redirections.some((n)=>n.heredoc)||t.nested.some((n)=>Qn(n.nodes));return(t.kind==="group"||t.kind==="function")&&Qn(t.body.nodes)})}function _C(e){return e.map((t)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${t.delimiter} was not found`}))}function Tu(e){return e?.kind==="command"||e?.kind==="group"||e?.kind==="function"}function Su(e,t){let n=e.at(-1);if(n?.kind!=="connector"||!vu.has(n.operator))return;t.push({code:"missing-command-after-connector",message:`connector ${n.operator} requires a following command`})}function ku(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&rC.has(e.text)}function Ns(e,t){let n=e.at(-1);if(!Tu(n))return;if(n?.kind==="command"&&ku(n.words[0]))return;t.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function wC(e,t,n){return t===n||/[\s;&|()]/u.test(e[t-1]??"")}var Mu=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),AC=new Set(["gc","cat","type","cp","mv","rm"]),Du=["-rec","-for","-path","-literalpath","-whatif"],PC=/^\$env:\w/i,IC=/^(?:\$\{?\w+\}?|~)\\./;function Nu(e,t){let n=e.toLowerCase().replaceAll("`","");if(![...Mu].some((o)=>n.includes(o))&&!(n.includes("rm")&&Du.some((o)=>n.includes(o)))&&!n.includes("<#")&&!TC(n))return!1;let r=Bs(e,t);if(Lu(r))return!1;return r.issues.some((o)=>o.code==="unclosed-block-comment"||o.code==="comment-depth-limit")||zs(r).some(kC)}function Lu(e){return e.nodes.some((t)=>{if(t.kind==="group")return Lu(t.body);if(t.kind!=="command")return!1;return t.redirections.some((n)=>n.operator==="<<")})}function TC(e){if(e.includes("$env:"))return!0;return e.includes("\\")&&(e.includes("$")||e.includes("~"))}function kC(e){let t=e[0]==="&"||e[0]==="."?1:0,n=e[t]?.toLowerCase();if(n&&Mu.has(n))return!0;let r=e.slice(t+1);if(n&&AC.has(n)&&r.some(OC))return!0;if(n!=="rm")return!1;return r.some((o)=>{let i=o.toLowerCase().split(":",1)[0]??"";return Du.some((s)=>i.startsWith(s))})}function OC(e){return PC.test(e)||IC.test(e)}function Bs(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return me({kind:"program",dialect:"powershell",source:e,span:n,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${t.maxInputLength} UTF-16 code units`}],nodes:[]});let r=$s(e,0,e.length,t,0);return me({kind:"program",dialect:"powershell",source:e,span:n,status:WC(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function $s(e,t,n,r,o,i=!1){let s=[],a=[],l=ao(),c=0,u=!1,f=()=>{if(l.words.length===0&&l.redirections.length===0)return;let m={start:l.start,end:l.end};lo(s,l,{kind:"command",dialect:"powershell",source:e.slice(m.start,m.end),span:m,words:l.words,redirections:l.redirections,nested:l.nested,displayText:l.words.map((g)=>g.text).join(" ")})},d=t;while(d<n){let m=e[d];if(!m)break;if(i&&m==="}")return f(),{nodes:s,issues:a,next:d+1,closed:!0,words:c,limited:u};let g=LC(e,d,n,r.maxDepth);if(g){if(g.issue)a.push(g.issue);if(g.limited)return f(),{nodes:s,issues:a,next:g.next,closed:!1,words:c,limited:!0};d=g.next;continue}if(/\s/.test(m)){if(m==="\r"||m===`
22
- `){f();let C=m==="\r"&&e[d+1]===`
23
- `?d+2:d+1;s.push(Gs(e,d,C)),d=C;continue}d++;continue}let p=Fu(e,d);if(p){f(),s.push(Gs(e,d,d+p.length)),d+=p.length;continue}if(m==="{"){if(f(),o>=r.maxDepth)return a.push(Gu(r.maxDepth)),{nodes:s,issues:a,next:n,closed:!1,words:c,limited:!0};let C=$s(e,d+1,n,r,o+1,!0),b=C.closed?C.next-1:C.next,y=me({kind:"program",dialect:"powershell",source:e.slice(d+1,b),span:{start:d+1,end:b},status:C.limited?"limited":C.issues.length>0?"partial":"complete",issues:C.issues,nodes:C.nodes});if(s.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:d,end:C.next}),body:y})),a.push(...C.issues),!C.closed)a.push({code:"unclosed-script-block",message:"PowerShell script block is not closed"});c+=C.words,u||=C.limited,d=C.next;continue}if(m==="}"){f(),s.push(Gs(e,d,d+1)),d++;continue}if(m===">"||m==="<"){l.start=l.start===-1?d:l.start;let C=e[d+1]===m?d+2:d+1,b=C;while(/[ \t]/.test(e[b]??""))b++;let y=b<n?Ou(e,b,n,r,o):void 0,E=y?.next??C;if(l.redirections.push(Object.freeze({kind:"redirection",operator:e.slice(d,C),span:Object.freeze({start:d,end:E}),...y?{target:y.word}:{}})),y)a.push(...y.issues),l.nested.push(...y.nested),c+=y.words,u||=y.limited;l.end=E,d=E;continue}if(m===","){l.start=l.start===-1?d:l.start,l.words.push(ks({text:",",raw:",",span:{start:d,end:d+1},provenance:"literal",quoted:!1})),l.end=++d;continue}let h=Ou(e,d,n,r,o);if(l.start=l.start===-1?d:l.start,l.end=h.next,l.words.push(h.word),a.push(...h.issues),l.nested.push(...h.nested),c+=1+h.words,u||=h.limited,c>r.maxWords)return a.push({code:"word-limit",message:`command exceeds ${r.maxWords} words`}),f(),{nodes:s,issues:a,next:h.next,closed:!1,words:c,limited:!0};d=h.next>d?h.next:d+1}return f(),{nodes:s,issues:a,next:d,closed:!i,words:c,limited:u}}function Ou(e,t,n,r,o){let i="",s="literal",a=!1,l=[],c=[],u=0,f=!1,d=(g)=>{let p=MC(e,g,n,r,o);return i+=e.slice(g,p.next),c.push(p.program),l.push(...p.program.issues),u+=Fs(p.program),f||=p.program.status==="limited",s="command-substitution",p.next},m=t;while(m<n){let g=e[m];if(!g||/\s/.test(g)||Fu(e,m)||g===">"||g==="<"||g==="#")break;if(g===",")break;if(g==="`"){let p=e[m+1];if(!p){l.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),m++;break}i+=p,m+=2;continue}if(e.startsWith("$(",m)){m=d(m);continue}if(g==="'"){a=!0,m++;let p=!1;while(m<e.length){if(e[m]==="'"&&e[m+1]==="'"){i+="'",m+=2;continue}if(e[m]==="'"){p=!0,m++;break}i+=e[m]??"",m++}if(!p)l.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(g==='"'){a=!0,m++;let p=!1;while(m<n){let h=e[m];if(h==="`"&&e[m+1]){i+=e[m+1],m+=2;continue}if(h==='"'){p=!0,m++;break}if(e.startsWith("$(",m)){m=d(m);continue}if(h==="$")s=e[m+1]==="("?"command-substitution":"variable";i+=h??"",m++}if(!p)l.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(g==="$")s=e[m+1]==="("?"command-substitution":"variable";if(g==="@"&&m===t)s="variable";i+=g,m++}return{word:cn(e,t,m,i,s,a,s==="literal"?void 0:DC(e,t,m)),next:m,issues:l,nested:c,words:u,limited:f}}function MC(e,t,n,r,o){let i=Wu(e,t+2,n),s=i===-1?n:i,a=i===-1?n:i+1;if(o>=r.maxDepth)return{program:me({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:"limited",issues:[Gu(r.maxDepth)],nodes:[]}),next:a};let l=$s(e,t+2,s,r,o+1),c=i===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:me({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:l.limited?"limited":l.issues.length+c.length>0?"partial":"complete",issues:[...l.issues,...c],nodes:l.nodes}),next:a}}function Wu(e,t,n){let r=1,o=!1,i=!1;for(let s=t;s<n;s++){let a=e[s];if(a==="`"){s++;continue}if(!i&&a==="'"){if(o&&e[s+1]==="'"){s++;continue}o=!o;continue}if(!o&&a==='"'){i=!i;continue}if(o)continue;if(e.startsWith("$(",s)){r++,s++;continue}if(!i&&a==="(")r++;if(a!==")")continue;if(r--,r===0)return s}return-1}function Fs(e){let t=0;for(let n of e.nodes){if(n.kind==="group")t+=Fs(n.body);if(n.kind==="command"){t+=n.words.length;for(let r of n.nested)t+=Fs(r)}}return t}function DC(e,t,n){let r=co(e),o=t,i=!1,s=t;while(s<n){let a=e[s];if(a==="`"){s+=2;continue}if(a==="'"){if(i&&e[s+1]==="'"){s+=2;continue}i=!i,s++;continue}if(i){s++;continue}if(e.startsWith("$(",s)){let l=Wu(e,s+2,n),c=l===-1?n:l+1;r.push(o,s,"literal"),r.push(s,c,"command-substitution"),s=c,o=c;continue}if(a==="$"||a==="@"&&s===t){let l=NC(e,s+1,n);r.push(o,s,"literal"),r.push(s,l,"variable"),s=l,o=l;continue}s++}return r.push(o,n,"literal"),r.parts}function NC(e,t,n){if(e[t]==="{"){let o=e.indexOf("}",t+1);return o===-1||o>=n?n:o+1}let r=t;while(r<n&&/[A-Za-z0-9_:?]/.test(e[r]??""))r++;return r}function Gu(e){return{code:"depth-limit",message:`command structure exceeds parser limit ${e}`}}function zs(e){return e.nodes.flatMap((t)=>{if(t.kind==="group")return zs(t.body);if(t.kind!=="command")return[];return[[...t.words,...t.redirections.flatMap((n)=>n.target?[n.target]:[])].sort((n,r)=>n.span.start-r.span.start).filter((n)=>n.text!==""&&n.raw!==",").map((n)=>n.text),...t.nested.flatMap(zs)]})}function Fu(e,t){for(let n of["&&","||",";","|"])if(e.startsWith(n,t))return n;return null}function LC(e,t,n,r){if(e[t]==="#"&&e[t+1]!==">"){let s=t+1;while(s<n&&e[s]!=="\r"&&e[s]!==`
24
- `)s++;return{next:s,limited:!1}}if(!e.startsWith("<#",t))return null;let o=1,i=t+2;while(i<n){if(e.startsWith("<#",i)){if(o++,o>r)return{next:n,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${r}`},limited:!0};i+=2;continue}if(e.startsWith("#>",i)){if(o--,i+=2,o===0)return{next:i,limited:!1};continue}i++}return{next:n,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function WC(e,t){if(t)return"limited";if(e.some((n)=>n.code==="unclosed-block-comment"))return"invalid";return e.length>0?"partial":"complete"}function Gs(e,t,n){return Object.freeze({kind:"connector",operator:e.slice(t,n),span:Object.freeze({start:t,end:n})})}function Me(e,t="auto",n=ht){if(t==="powershell"||t==="auto"&&Nu(e.slice(0,n.maxInputLength),n))return Bs(e,n);return Eu(e,n)}function _(e){return e.provenance==="command-substitution"?e.raw:e.text}function dn(e,t){return e==="posix"?t:K(t.map((n)=>n.text))}function Co(e,t){return e&&e.provenance!=="unknown"?e.provenance==="literal":!/[$`*?[\]]/.test(t)}function K(e){return e.map((t)=>({kind:"word",text:t,raw:t,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function Us(e,t){return{value:e,work:t}}function S(e,t){if(e.work)e.work.units=Math.min(Number.MAX_SAFE_INTEGER,e.work.units+1);return e.value[t]}function X(e){return e.value.length}function er(e,t,n=1){if(e)e.units=Math.min(Number.MAX_SAFE_INTEGER,e.units+t.length*n)}function Re(e,t){er(e,t)}function Wt(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t===95||t>=97&&t<=122}function U(e){if(!e)return!1;let t=e.charCodeAt(0);return t===9||t===10||t===11||t===12||t===13||t===32||t===160||t===65279||t===5760||t>=8192&&t<=8202||t===8232||t===8233||t===8239||t===8287||t===12288}function Hs(e){return e===`
25
- `||e==="\r"||e==="\u2028"||e==="\u2029"}function H(e,t,n){if(t+n.length>X(e))return!1;for(let r=0;r<n.length;r++)if(S(e,t+r)!==n[r])return!1;return!0}function tt(e,t,n){return!Wt(S(e,t-1))&&H(e,t,n)&&!Wt(S(e,t+n.length))}function nt(e,t){return Wt(S(e,t-1))!==Wt(S(e,t))}function re(e){return e===`
26
- `||e===";"||e==="&"||e==="|"}function fn(e){return e==="|"||e===";"}function bo(e,t,n){let r=Us(e,n);if(t==="rm")return GC(r);if(t==="dd")return zC(r);return ju(r,!0)}function So(e,t,n){let r=Us(e,n);if(t==="rm")return BC(r);if(t==="reset-hard")return Uu(r,"--ha","rd");if(t==="reset-merge")return Uu(r,"--me","rge");if(t==="clean")return jC(r);if(t==="checkout")return KC(r);if(t==="push-force")return qC(r);if(t==="push-refspec")return YC(r);if(t==="push-delete")return ZC(r);if(t==="branch")return XC(r);if(t==="tag")return eb(r);if(t==="restore")return tb(r);return ju(r,!1)}function GC(e){let t=!1,n=!1,r=!1,o=-1;for(let i=0;i<=X(e);i++){let s=S(e,i);if(!t){let l=S(e,i+2);if(tt(e,i,"rm")&&U(l)&&l!==`
27
- `)t=!0,i++;continue}let a=FC(e,i);if(s===`
28
- `||a!==-1){if(t=!1,n=!1,r=!1,o=-1,a!==-1)i=a-1;continue}if(s===";"||s==="&"||s==="|"||i===X(e)){if(o>=0){let l=zu(e,o,i);n||=l.recursive,r||=l.force}if(n&&r)return!0;t=!1,n=!1,r=!1,o=-1;continue}if(U(s)){if(o<0)continue;if(H(e,o,"--")&&i-o===2){t=!1,n=!1,r=!1,o=-1;continue}let l=zu(e,o,i);if(n||=l.recursive,r||=l.force,n&&r)return!0;o=-1;continue}if(o<0)o=i}return!1}function FC(e,t){if(S(e,t)!=="\\"||S(e,t-1)==="\\")return-1;if(H(e,t,String.raw`\n`))return t+2;if(H(e,t,String.raw`\x0a`)||H(e,t,String.raw`\x0A`))return t+5;if(H(e,t,String.raw`\u000a`)||H(e,t,String.raw`\u000A`))return t+7;return H(e,t,String.raw`\012`)?t+4:-1}function zu(e,t,n){if(Bu(e,t,n,"recursive"))return{recursive:!0,force:!1};if(Bu(e,t,n,"force"))return{recursive:!1,force:!0};if(S(e,t)!=="-"||S(e,t+1)==="-")return{recursive:!1,force:!1};let r=!1,o=!1;for(let i=t+1;i<n;i++){let s=S(e,i);r||=s==="r"||s==="R",o||=s==="f"||s==="F"}return{recursive:r,force:o}}function Bu(e,t,n,r){let o=n-t-2;if(o<1||o>r.length||!H(e,t,"--"))return!1;for(let i=0;i<o;i++)if(S(e,t+i+2)!==r[i])return!1;return!0}function zC(e){let t=!1;for(let n=0;n<X(e);n++){if(re(S(e,n))){t=!1;continue}if(tt(e,n,"dd")){t=!0,n++;continue}if(!t||!tt(e,n,"of")||!H(e,n,"of=/dev/"))continue;let r=n+8;if(r<X(e)&&!U(S(e,r))&&S(e,r)!=="'"&&S(e,r)!=='"')return!0}return!1}function BC(e){let t=!1,n=!1,r=!1;for(let o=0;o<=X(e);){let i=S(e,o);if(o===X(e)||re(i)){t=!1,n=!1,r=!1,o++;continue}let s=UC(e,o);if(s>=0){if($C(e,s))return!0;let a=s,l=!1;while(U(S(e,a)))l||=S(e,a)===`
29
- `,a++;if(l)n=!1,r=!1;t=!0,o=a;continue}if(!t){o++;continue}if(H(e,o,"--")&&(o===0||U(S(e,o-1)))&&(!S(e,o+2)||U(S(e,o+2))||re(S(e,o+2)))){t=!1,n=!1,r=!1,o+=2;continue}if(n||=H(e,o,"--recursive")&&nt(e,o+11)||js(e,o,"recursive"),r||=H(e,o,"--force")&&nt(e,o+7)||js(e,o,"force"),n&&r)return!0;o++}return!1}function js(e,t,n){if(!H(e,t,"--"))return!1;let r=0;while(r<=n.length){let o=S(e,t+r+2);if(!o||U(o)||re(o))break;if(o!==n[r])return!1;r++}return r>0&&nt(e,t+r+2)}function $C(e,t){let n=t,r=!1,o=!1;while(n<X(e)){while(U(S(e,n)))n++;let i=n;while(n<X(e)&&!U(S(e,n)))n++;if(S(e,i)!=="-"||n-i===2&&H(e,i,"--"))return!1;let s=$u(e,i,"recursive"),a=$u(e,i,"force");if(r&&a||o&&s)return!0;if(r||=s,o||=a,S(e,i+1)==="-")continue;let l=HC(e,i,n);if(l.combined||r&&l.forceAtBoundary||o&&l.recursiveAtBoundary)return!0;r||=l.recursive,o||=l.force}return!1}function $u(e,t,n){return H(e,t,`--${n}`)&&nt(e,t+n.length+2)||js(e,t,n)}function UC(e,t){if(t>0&&Wt(S(e,t-1)))return-1;let n=t;if(S(e,n)==="\\")n++;if(S(e,n)!=="r")return-1;if(n++,S(e,n)==="\\")n++;if(S(e,n)!=="m"||!U(S(e,n+1)))return-1;return n+1}function HC(e,t,n){let r=!1,o=!1,i=!1,s=!1,a=!1;if(S(e,t)!=="-")return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a};let l="";for(let c=t+1;c<n;c++){let u=S(e,c)??"",f=(u==="r"||u==="f")&&nt(e,c+1);r||=u==="r",o||=u==="f",i||=u==="r"&&f,s||=u==="f"&&f,a||=(l==="r"&&u==="f"||l==="f"&&u==="r")&&f,l=u}return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a}}function Uu(e,t,n){return nr(e,"reset",fn,!0,(r)=>S(e,r)==="-"&&mn(e,r,t,n)?!0:r)}function jC(e){return nr(e,"clean",fn,!0,(t)=>{if(S(e,t)!=="-")return t;if(mn(e,t,"--fo","rce"))return!0;let n=tr(e,t,fn);for(let r=t+1;r<n;r++)if(S(e,r)==="f")return!0;return n-1})}function vo(e,t,n){if(!tt(e,t,"git"))return null;let r=t+3;if(!U(S(e,r)))return{commandEnd:-1,next:r};while(U(S(e,r)))r++;while(r<X(e)){if(re(S(e,r)))return{commandEnd:-1,next:r};let o=tr(e,r,re);if(tt(e,r,n))return{commandEnd:r+n.length,next:o};if(S(e,r)!=="-")return{commandEnd:-1,next:o};let i=o-r===2&&H(e,r,"--"),s=VC(e,r,o);r=o;while(U(S(e,r)))r++;if(i)return{commandEnd:tt(e,r,n)?r+n.length:-1,next:tr(e,r,re)};if(!s)continue;if(r>=X(e)||re(S(e,r)))return{commandEnd:-1,next:r};r=tr(e,r,re);while(U(S(e,r)))r++}return{commandEnd:-1,next:r}}function VC(e,t,n){for(let r of ve)if(n-t===r.length&&H(e,t,r))return!0;return!1}function KC(e){return Hu(e,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function qC(e){return nr(e,"push",fn,!0,(t)=>{if(S(e,t)!=="-")return t;if(S(e,t+1)==="f"&&!Wt(S(e,t+2))&&!H(e,t+2,"-with-lease"))return!0;let n=Vu(e,t,"--fo","rce");if(n>=0&&!H(e,n,"-with-lease"))return!0;return t})}function YC(e){return nr(e,"push",re,!1,(t)=>{if(U(S(e,t))&&S(e,t+1)==="+"&&t+2<X(e)&&!re(S(e,t+2))&&!U(S(e,t+2)))return!0;if(S(e,t)===":"&&S(e,t+1)==="+")return!0;return t})}function ZC(e){return nr(e,"push",re,!1,(t)=>{if(S(e,t)==="-"&&mn(e,t,"--de","lete"))return!0;if(U(S(e,t))&&S(e,t+1)===":"&&t+2<X(e)&&!U(S(e,t+2))&&!re(S(e,t+2)))return!0;return t})}function XC(e){let t=!1,n=!1,r=!1;for(let o=0;o<=X(e);o++){if(o===X(e)||re(S(e,o))){if(n&&r)return!0;t=!1,n=!1,r=!1;continue}if(!t){let a=vo(e,o,"branch");if(a){t=a.commandEnd>=0,o=Math.max(o,(t?a.commandEnd:a.next)-1);continue}}if(!t||S(e,o)!=="-")continue;let i=tr(e,o,re),s=JC(e,o,i);if(n||=s.deletion,r||=s.force,n&&r)return!0;o=i-1}return!1}function JC(e,t,n){let r=!1,o=!1;for(let i=t;i<n;i++){if(S(e,i)!=="-")continue;if(mn(e,i,"--de","lete"))r=!0;if(mn(e,i,"--fo","rce"))o=!0;if(S(e,i+1)==="-")continue;let s=i+1,a=!1,l=!1,c=!1;while(s<n&&QC(S(e,s))){let u=S(e,s);a||=u==="d"||u==="D",l||=u==="f",c||=u==="D",s++}if(!nt(e,s))continue;r||=a,o||=l||c}return{deletion:r,force:o}}function QC(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function eb(e){return Hu(e,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function Hu(e,t){let n=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let r=0;r<X(e);r++){let o=S(e,r),i=n[n.length-1];if(!i)return!1;let s=i.escaped;if(i.escaped=!s&&i.quote!=="'"&&o==="\\",!s&&o==="'"&&i.quote!=='"')i.quote=i.quote==="'"?"":"'";if(!s&&o==='"'&&i.quote!=="'")i.quote=i.quote==='"'?"":'"';if(o==="$"&&S(e,r+1)==="("&&(n.length===1||!s&&i.quote!=="'")){n.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),r++;continue}if(!s&&!i.quote&&n.length>1&&o==="("){i.depth++;continue}if(!s&&!i.quote&&n.length>1&&o===")"){if(i.depth--,i.depth===0)n.pop();continue}if(U(o))i.shortActive=!1,i.hasShortFlag=!1;if(!i.outerActive){let a=vo(e,r,t.command);if(a){i.outerActive=a.commandEnd>=0&&U(S(e,a.commandEnd)),i.shortActive=!1,i.hasShortFlag=!1,r=Math.max(r,(i.outerActive?a.commandEnd:a.next)-1);continue}}if(i.outerActive&&o==="-"){if(mn(e,r,t.longPrefix,t.longOptional))return!0;i.shortActive||=!t.excludedShortStarts.includes(S(e,r+1)??"")}if(i.hasShortFlag||=i.shortActive&&o===t.shortFlag,i.hasShortFlag&&nt(e,r+1))return!0;if(fn(o))i.outerActive=!1}return!1}function nr(e,t,n,r,o){let i=!1;for(let s=0;s<X(e);s++){let a=S(e,s),l=n(a);if(!i&&!l){let c=vo(e,s,t);if(c){i=c.commandEnd>=0&&(!r||U(S(e,c.commandEnd))),s=Math.max(s,(i?c.commandEnd:c.next)-1);continue}}if(i){let c=o(s);if(c===!0)return!0;for(let u=s;u<=c;u++)if(n(S(e,u)))i=!1;s=c}if(l)i=!1}return!1}function tb(e){let t=!1;for(let n=0;n<X(e);n++){if(Hs(S(e,n))){if(t)return!0;t=!1;continue}if(!t){let r=vo(e,n,"restore");if(r){t=r.commandEnd>=0,n=Math.max(n,(t?r.commandEnd:r.next)-1);continue}}if(t&&S(e,n)==="-"&&S(e,n+1)==="-"&&(H(e,n+2,"staged")||H(e,n+2,"help")))t=!1}return t}function ju(e,t){let n=!1;for(let r=0;r<X(e);r++){let o=S(e,r),i=t?Hs(o):re(o);if(n&&U(o)&&S(e,r+1)==="-"&&tt(e,r+2,"delete"))return!0;if(i){n=!1;continue}if(tt(e,r,"find"))n=!0,r+=3}return!1}function tr(e,t,n){let r=t;while(r<X(e)&&!U(S(e,r))&&!n(S(e,r)))r++;return r}function Vu(e,t,n,r){if(!H(e,t,n))return-1;let o=t+n.length;for(let i=0;i<r.length&&S(e,o)===r[i];i++)o++;return nt(e,o)?o:-1}function mn(e,t,n,r){return Vu(e,t,n,r)>=0}function Pe(e,t){er(t,e,2);let n=e.toLowerCase(),r=n.trimStart(),o=r.startsWith("echo ")||r.startsWith("rg "),i=[{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 s of i){if(s.skipForEchoRg&&o)continue;let a=s.caseSensitive?e:n;if(s.regex)Re(t,a);if((s.regex?.test(a)??!1)||s.scan&&So(a,s.scan,t))return v("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${s.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var nb=/^[A-Za-z_][A-Za-z0-9_]*=/;function qu(e,t,n){let r=e.words[0];if(!t||!r||e.words.length!==1||e.dialect!=="posix")return!1;if(!r.quoted||r.provenance!=="literal")return!1;let o=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r.text)?.[1];if(!o)return!1;er(n,t.source,2);let i={anchored:new RegExp(`^\\$\\{?${o}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${o}(?![A-Za-z0-9_])`)};return Yu(t.nodes,r,i)}function Yu(e,t,n){return e.every((r)=>{if(r.kind==="connector")return!0;if(r.kind==="group"||r.kind==="function")return Yu(r.body.nodes,t,n);if(r.kind==="unknown")return!n.loose.test(r.source);return rb(r,t,n)})}function rb(e,t,n){if(e.nested.some((o)=>n.loose.test(o.source)))return!1;let r=e.words.findIndex((o)=>!nb.test(o.text));return e.words.every((o,i)=>o===t||Ku(o.raw,n.anchored,i!==r))&&e.redirections.every((o)=>(!o.heredoc||o.heredoc.quotedDelimiter||!n.loose.test(o.heredoc.body))&&(!o.target||Ku(o.target.raw,n.anchored,!0)))}function Ku(e,t,n){let r=!1,o=!1;for(let i=0;i<e.length;i++){let s=e[i];if(s==="\\"&&!r){i++;continue}if(!o&&s==="'"){r=!r;continue}if(!r&&s==='"'){o=!o;continue}if(r||s!=="$")continue;if(!t.test(e.slice(i)))continue;if(!o||!n)return!1}return!0}import{isAbsolute as ob,resolve as Zu}from"node:path";function rr(e,t,n,r){let o=ob(e)?Zu(e):t?Zu(t,e):void 0;if(!o)return;try{return L(o,n,r)}catch{return o}}function Xu(e){return!["/dev","/proc","/sys"].some((t)=>e===t||e.startsWith(`${t}/`))}var pn="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",or="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.",Ks=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),ib=new Set(["-p","--print"]),sb=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),ab=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"])]]),lb=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),cb=new Map([["python",new Set(["m"])]]),ub=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"])]]),db=new Set(["always","default","never"]),fb=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),mb=/\\\r?\n/g,pb=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 Ju(e){return xo(e).code}function Eo(e){return xo(e).sources}function Qu(e){return pb.get(Ys(e))??[]}function xo(e){let t=Ys(e[0]??"");if(!Ks.has(t))return{code:null,sources:[],optionsOpen:!1};let n=[],r=[],o=!0;for(let i=1;i<e.length;i++){let s=e[i];if(s===void 0)break;if(s==="--")return De(t,n,r,o,e[i+1]===void 0?void 0:i+1,e[i+1]);if(s===""||s==="-"||!s.startsWith("-"))return De(t,n,r,o,i,s);if(t==="node"&&ib.has(s)){let f=e[i+1];if(f===void 0)return De(t,n,r,o);if(f.startsWith("-"))continue;n.push({tokenIndex:i+1,value:f}),r.push({tokenIndex:i+1,kind:"inline-code",value:f}),i++;continue}if(hb(t,s)){let f=e[i+1];if(f===void 0)return De(t,n,r,o);if(n.push({tokenIndex:i+1,value:f}),r.push({tokenIndex:i+1,kind:"inline-code",value:f}),t==="python")return De(t,n,r,o);i++;continue}let a=/^--eval=(.*)$/s.exec(s);if(yb(t)&&a){let f=a[1]??"";n.push({tokenIndex:i,value:f}),r.push({tokenIndex:i,kind:"inline-code",value:f});continue}if(t==="node"){let f=gb(s);if(f){if(f.attached){if(o&&=f.value!=="",f.value!=="")r.push({tokenIndex:i,kind:"module-file",value:f.value});continue}let d=e[i+1];if(d===void 0||d.startsWith("-"))return o=!1,De(t,n,r,o);r.push({tokenIndex:i+1,kind:"module-file",value:d}),i++;continue}}if(t==="python"&&s.startsWith("--check-hash-based-pycs=")||t==="node"&&(s==="--conditions="||s==="--diagnostic-dir="||s==="--title=")||t==="ruby"&&(s==="--disable="||s==="--enable="))return De(t,n,r,o);if(ub.get(t)?.has(s)){let f=e[i+1];if(f===void 0||f.startsWith("-")&&!(t==="ruby"&&fb.has(s))||t==="python"&&!db.has(f))return De(t,n,r,o);i++;continue}if(s.startsWith("--"))continue;let l,c=!1;for(let f=1;f<s.length;f++){let d=s[f];if(d===void 0)break;if(cb.get(t)?.has(d)){let m=s.slice(f+1),g=m||e[i+1];if(g!==void 0)r.push({tokenIndex:m?i:i+1,kind:"module-file",value:g});return De(t,n,r,o)}if(sb.get(t)?.has(d)){l=s.slice(f+1)||e[i+1],c=f+1===s.length;break}if(t==="node"&&d==="r"){if(o&&=s==="-r",s==="-r"){let m=e[i+1];if(o&&=m!==void 0&&!m.startsWith("-"),o&&m!==void 0)r.push({tokenIndex:i+1,kind:"module-file",value:m});i++}break}if(t==="ruby"&&d==="r"){let m=s.slice(f+1),g=m||e[i+1];if(o&&=g!==void 0,g!==void 0)r.push({tokenIndex:m?i:i+1,kind:"module-file",value:g});if(!m)i++;break}if(t==="perl"&&(d==="M"||d==="m")){let m=s.slice(f+1);if(!m){if(o=!1,f+1===s.length)i++;break}r.push({tokenIndex:i,kind:"module-file",value:m});break}if(ab.get(t)?.has(d)){if(f+1===s.length)i++;break}if(lb.get(t)?.has(d)&&f+1<s.length)break}if(l===void 0)continue;let u=c?i+1:i;if(n.push({tokenIndex:u,value:l}),r.push({tokenIndex:u,kind:"inline-code",value:l}),t==="python")return De(t,n,r,o);if(c)i++}return De(t,n,r,o,void 0,void 0,!0)}function De(e,t,n,r,o,i,s=!1){let a=e==="node"?t.slice(-1):t,l=new Set(a.map((u)=>u.tokenIndex)),c=n.filter((u)=>u.kind!=="inline-code"||l.has(u.tokenIndex));if(r&&t.length===0&&o!==void 0&&i!==void 0)c.push({tokenIndex:o,kind:"main-script",value:i});return{code:(e==="node"?a[0]?.value:a.map((u)=>u.value).join(`
30
- `))||null,sources:r?c:[],optionsOpen:r&&s}}function gb(e){for(let t of["--import","--loader","--experimental-loader","--require"]){if(e===t)return{attached:!1,value:""};if(e.startsWith(`${t}=`))return{attached:!0,value:e.slice(t.length+1)}}return}function qs(e,t){return Ys(e)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(t)}function Ys(e){let t=A(e).toLowerCase();return Ur.test(t)?"python":t}function hb(e,t){return Ks.get(e)?.has(t)??!1}function yb(e){return Ks.get(e)?.has("--eval")??!1}function ir(e,t,n=!1){let r=Sb(e,t);if(!Vs(r,t))return!1;Re(t,r);let o=bb(r);if(Vs(o,t))return!0;if(Re(t,o),!ed.test(o))return!1;return!n||Cb(r,t)}function Cb(e,t){if(/`|%x|\bqx\b/.test(e))return!0;let r=e.split(""),o=[];for(let l=0;l<e.length;l++){let c=e[l];if(c!=="'"&&c!=='"')continue;let u=e.startsWith(c.repeat(3),l)?c.repeat(3):c,f=l+u.length,d=f;while(d<e.length&&!e.startsWith(u,d))d+=e[d]==="\\"?2:1;if(d>=e.length)return!0;o.push({start:f,text:e.slice(f,d)}),r.fill(" ",l,d+u.length),l=d+u.length-1}let i=r.join(""),s=Array.from(i.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((l)=>ed.test(l[1]??"")).map((l)=>{let c=l.index+l[0].length;return{start:c,end:Zs(i,c)}});if(s.some((l)=>Xs(i,l.start)))return!0;return o.some((l)=>{let c=/\b(?:system|exec|spawn|popen)\s*$/.test(i.slice(0,l.start)),u=s.some((f)=>l.start>=f.start&&l.start<f.end);return(c||u)&&Vs(l.text,t)})}function Zs(e,t){let n=1;for(let r=t;r<e.length;r++){if(e[r]==="(")n++;if(e[r]===")")n--;if(n===0)return r}return e.length}function Xs(e,t){let n=0;for(let r=t;r<e.length;r++){let o=e[r]??"";if("([{".includes(o))n++;if(")]}".includes(o)&&n--===0)return!1;if(o===","&&n===0)return!1;if(/[A-Za-z_$]/.test(o))return!0}return!1}var ed=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function bb(e){let t=[],n=0,r=0;while(r<e.length){let o=e[r];if(o!=="'"&&o!=='"'){r++;continue}let i=e.startsWith(o.repeat(3),r)?o.repeat(3):o,s=r+i.length;while(s<e.length&&!e.startsWith(i,s))s+=e[s]==="\\"?2:1;if(s>=e.length)break;t.push(e.slice(n,r)," "),r=s+i.length,n=r}return t.push(e.slice(n)),t.join("")}function Vs(e,t){if(bo(e,"rm",t))return!0;for(let r of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(Re(t,e),r.test(e))return!0;if(bo(e,"dd",t))return!0;for(let r of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(Re(t,e),r.test(e))return!0;if(bo(e,"find",t))return!0;let n=e.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((r)=>(Re(t,e),n.some((o)=>So(o,r))))}function Sb(e,t){return Re(t,e),e.replace(mb,"")}import{lstatSync as yS,readdirSync as CS}from"node:fs";import{basename as bS,isAbsolute as wd,join as SS,relative as Ad}from"node:path";import{isAbsolute as ad,parse as Tb}from"node:path";import{dirname as vb,isAbsolute as Eb,parse as xb,sep as Rb}from"node:path";function yt(e,t,n){if(Je(t))throw Error("Unsupported Windows namespace path");let r=Eb(t)?xb(t).root:"",o=r||e;for(let i of wb(r?t.slice(r.length):t)){if(i===""||i===".")continue;if(i===".."){o=vb(o);continue}let s=_b(o,i),a=n.entryKind(s),l=a==="symlink"?n.realpath(s):s;if(a==="missing"||l===null)throw Error(`Cannot resolve path component: ${s}`);o=l}return o}function _b(e,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${t}`:`${e}${Rb}${t}`}function wb(e){let t=process.platform==="win32"?/[\\/]+/:/\/+/;return e.split(t)}var Js=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],Ab=new Set(Js),Pb=1024,td=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),nd=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),Ib=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function Ro(e){return Ab.has(e)}function Qs(e){return Ro(e)||td.has(e)||nd.has(e)||Un(e)}function rt(e,t,n){return n?.has(e)?n.get(e):t.get(e)}function rd(e,t){let n=rt("GIT_CONFIG_COUNT",e,t);if(n===void 0)return{state:"absent"};if(n==="")return{state:"valid",count:0};if(!/^\d+$/.test(n))return{state:"invalid"};let r=Number(n);return Number.isSafeInteger(r)&&r<=Pb?{state:"valid",count:r}:{state:"invalid"}}function _o(e,t,n){let o=e.match(Ib)?.[1];if(!o||!Qs(o))return null;let i=e.indexOf("=");return{name:o,value:`${rt(o,t,n)??""}${e.slice(i+1)}`}}function od(e){return sd(e,nd)}function id(e){return sd(e,td)}function sd(e,t){if(!e)return!1;for(let n of e.keys())if(t.has(n))return!0;return!1}var cd=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ie(e){if(!cd.test(e))return null;let t=e.indexOf("=");return{name:e.slice(0,t),value:e.slice(t+1)}}function wo(e){let t=new Map,n=0;while(n<e.length){let r=e[n];if(!r)break;let o=Ie(_(r));if(!o)break;t.set(o.name,o.value),n++}return{words:e.slice(n),envAssignments:t}}function ud(e){let t=k(e);return e.includes("=")||t==="sudo"||t==="env"||t==="command"||t==="builtin"}function Gt(e,t,n,r){if(!ud(gn(e)))return{words:e,envAssignments:new Map,cwd:n,rewritten:!1};let o=new Set(e),i=e,s=new Map,a=new Map(r??[]),l=[],c=n;for(let f=0;f<V.wrapperPeelIterations.cap;f++){let d=ld(i),m=wo(i);for(let[p,h]of m.envAssignments)s.set(p,h),a.set(p,h);if(i=m.words,i.length===0)break;while(i.length>0&&gn(i).includes("=")&&!Ob(i)){let p=Mb(gn(i),a,t.env)??_o(gn(i),t.env,a);if(p)s.set(p.name,p.value),a.set(p.name,p.value);i=i.slice(1)}if(i.length===0)break;let g=k(gn(i));if(g!=="sudo"&&g!=="env"&&g!=="command"&&g!=="builtin")break;if(g==="sudo"){let p=Nb(i,t.paths,c);if(i=p.words,p.cwd!==void 0)c=p.cwd}if(g==="env"){let p=Gb(i,c,a,t);if(l.push(...p.envSplitValues??[]),i=p.words,p.cwd!==void 0)c=p.cwd;for(let[h,C]of p.envAssignments)s.set(h,C),a.set(h,C)}if(g==="command")i=Fb(i);if(g==="builtin")i=i.slice(Ne(i,1)==="--"?2:1);if(ld(i)===d)break}let u=wo(i);for(let[f,d]of u.envAssignments)s.set(f,d),a.set(f,d);return{words:u.words,envAssignments:s,cwd:c,envSplitValues:l.length>0?l:void 0,rewritten:kb(u.words,o)}}function kb(e,t){return e.some((n)=>!t.has(n))}function ld(e){return e.map(_).join(" ")}function gn(e){let t=e[0];return t?_(t):""}function Ne(e,t){let n=e[t];return n?_(n):void 0}function Ob(e){return cd.test(gn(e))}function Mb(e,t,n){if(!e.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${t.get("TMPDIR")??n.get("TMPDIR")??""}${e.slice(8)}`}}var Db=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function Nb(e,t,n){let r=1,o=n;while(r<e.length){let i=Ne(e,r);if(!i)break;if(i==="--")return{words:e.slice(r+1),cwd:o};if(!i.startsWith("-"))break;if(i==="-D"||i==="--chdir"){let s=Ne(e,r+1);o=s?sr(o,s,t):null,r+=2;continue}if(i.startsWith("--chdir=")){o=sr(o,i.slice(8),t),r++;continue}if(i.startsWith("-D")&&i.length>2){o=sr(o,i.slice(2),t),r++;continue}if(i==="-i"||i==="--login"){o=null,r++;continue}if(Db.has(i)){r+=2;continue}r++}return{words:e.slice(r),cwd:o}}var Lb=new Set(["-i","-0","--null"]),Wb=new Set(["-u","--unset","-C","--chdir","-P"]);function Gb(e,t,n,r){let o=new Map,i=[],s=t,a=1,l=(c)=>({words:e.slice(c),envAssignments:o,cwd:s,envSplitValues:i.length>0?i:void 0});while(a<e.length){let c=Ne(e,a);if(!c)break;if(c==="--")return l(a+1);if(c==="-i"||c==="--ignore-environment"||c==="-"){o.clear();for(let f of n.keys())o.set(f,"");o.set("TMPDIR",""),a++;continue}if(Lb.has(c)){a++;continue}if(c==="-u"||c==="--unset"){let f=Ne(e,a+1);if(f!==void 0)o.set(f,"");a+=2;continue}if(c.startsWith("-u")&&c.length>2&&!c.startsWith("-u=")){o.set(c.slice(2),""),a++;continue}if(c.startsWith("--unset=")){o.set(c.slice(8),""),a++;continue}let u=c==="-S"||c==="--split-string"?{value:Ne(e,a+1),consumed:2}:c.startsWith("-S")&&c.length>2?{value:c.slice(2),consumed:1}:c.startsWith("--split-string=")?{value:c.slice(15),consumed:1}:null;if(u){if(u.value!==void 0)i.push(u.value);return s=null,l(a+u.consumed)}if(Wb.has(c)){if(c==="-C"||c==="--chdir"){let f=Ne(e,a+1);s=f?sr(s,f,r.paths):null}a+=2;continue}if(c.startsWith("-u=")){a++;continue}if(c.startsWith("-C")&&c.length>2||c.startsWith("--chdir=")){let f=c.startsWith("--chdir=")?c.slice(8):c.startsWith("-C=")?c.slice(3):c.slice(2);s=sr(s,f,r.paths),a++;continue}if(c.startsWith("-P")){a++;continue}if(c.startsWith("-")){a++;continue}if(!Ie(c))break;while(a<e.length){let f=Ie(Ne(e,a)??"");if(!f)break;o.set(f.name,f.value),a++}if(Ne(e,a)==="--")a++;return l(a)}return l(a)}function sr(e,t,n){if(t==="")return null;if(!e&&!ad(t))return null;let r=ad(t)?Tb(t).root:n.realpath(e??"/");if(r===null)return null;try{return yt(r,t,n)}catch{return null}}function Fb(e){if(Ne(e,1)==="-v")return[...K(["type"]),...e.slice(2)];let t=1;while(t<e.length){let n=Ne(e,t);if(!n)break;if(n==="-p"||n==="-v"||n==="-V"){t++;continue}if(n==="--")return e.slice(t+1);if(n.startsWith("-")&&!n.startsWith("--")&&n.length>1){if(!/^[pvV]+$/.test(n.slice(1)))break;t++;continue}break}return e.slice(t)}var zb=/['"\\$`{}#]/;function Ao(e,t){if(e.some((r)=>zb.test(r)))return null;let n=[...e.flatMap((r)=>r.split(/\s+/).filter((o)=>o.length>0)),...t];return n.length<=64?n:null}function Ct(e,t,n){return Po(e,t,n).tokens}function Bb(e){let t=[],n="",r=0;while(r<e.length){let o=e.charAt(r);if(o==='"'||o==="'"){let i=e.indexOf(o,r+1);if(i===-1)return e.split(/\s+/).map((s)=>s.replace(/["']/g,"")).filter((s)=>s.length>0);n+=e.slice(r+1,i),r=i+1;continue}if(/\s/.test(o)){if(n.length>0)t.push(n);n="",r++;continue}n+=o,r++}if(n.length>0)t.push(n);return t}function bt(e,t,n,r=0){let o=Po(e,t,n),i=(o.envSplitValues??[]).flatMap(Bb);if(i.length===0)return o.tokens;let s=[...i,...o.tokens];if(r>=8)return s;return bt(s,t,n,r+1)}function Po(e,t,n,r){if(!ud(e[0]??""))return{tokens:[...e],envAssignments:new Map,cwd:n};let o=Gt(K(e),t,n,r);return{tokens:o.words.map(_),envAssignments:o.envAssignments,cwd:o.cwd,envSplitValues:o.envSplitValues}}var ra=Symbol("adopt-as-operand"),$b=new Set(["env","sudo","command","builtin"]),Ub=new Set(["&&","||","|&","|","&",";"]),Hb=new Set(["<<","<<<",">|"]),jb=new Set(["|","|&"]),Vb=/[*@#?$!_-]/,Kb=/^\w+(?::\w+)*/,qb=Object.freeze([]),ar=Object.freeze({kind:"scope",edge:"enter"}),lr=Object.freeze({kind:"scope",edge:"exit"}),Yb=Object.freeze([]),Zb=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),cr=new Set(["bash","sh","zsh","dash","ksh"]),Xb=256,gd=new WeakMap;function hd(e,t){let n=t.status==="complete"?new Set(na(t)):new Set,r=eS(e,n);if(jr(r))return Io("unclosed-quote",r,t);let o={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},i=Ft(t,{source:r,suppressed:n,flags:o,depth:0,functions:new Map,powershell:t.dialect==="powershell"});if(o.limited)return Io("structural-limit",r,t);if(o.invalid)return Io("invalid",r,t);let s=Io("complete",r,t,o.assignmentFallbacks);return gd.set(s,Object.freeze(i)),s}function ko(e,t,n,r,o){let i=o.word??((f)=>f),s={cwd:t,variables:new Map,previous:null},a=[],l=new Set,c=null,u=[];for(let f of yd(e)){if(f.kind==="scope"){if(f.edge==="enter"){u.push({state:s,segment:[...a],shellWords:new Set(l),pipeProducer:c});continue}let d=o.segment(a,s,c,null,l);if(d)return d;let m=u.pop();if(m===void 0)throw Error("scope exit without a matching enter");s=m.state,a=m.segment,l=m.shellWords,c=m.pipeProducer;continue}if(f.kind==="operator"){if(!f.boundary)continue;let d=o.segment(a,s,c,f.operator,l);if(d)return d;s=Jb(a,s,n,r),c=a.length>0&&jb.has(f.operator)?a:null,a=[],l=new Set;continue}if(f.kind==="redirection"){if(f.fd!==void 0)l.add(a.length-1);if(f.target===void 0)continue;let d=o.redirection({operator:f.operator,role:f.role,targetOrder:f.targetOrder,target:f.target,...f.body===void 0?{}:{body:f.body,consumer:f.consumer}},s);if(d===ra){l.add(a.length),a.push(i(f.target));continue}if(d)return d;continue}a.push(i(f.text))}return o.segment(a,s,c,null,l)}function Oo(e){return yd(e).flatMap((t)=>{if(t.kind==="word")return[{kind:"word",text:t.text}];if(t.kind==="operator")return[{kind:"operator",boundary:t.boundary}];if(t.kind==="redirection")return[{kind:"redirection",target:t.target}];return[]})}function pe(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(n,r,o,i)=>{let s=t.get(r);if(s===void 0)return n;let a=o.startsWith(":")?s!=="":!0;if(o.endsWith("-"))return a?s:pe(i,t);return a?pe(i,t):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(n,r)=>t.get(r)??n).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(n,r)=>t.get(r)??n)}function ur(e){return e.length>0&&e.every((t)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t))}function Jb(e,t,n,r){let o=ur(e)?new Map([...t.variables,...Qb(e,t.variables)]):t.variables,i=Ct([...e],n),s=A(i[0]??"").toLowerCase()==="cd"?i[1]:void 0;if(!s)return{...t,variables:o};if(s==="-"){if(t.previous===null)return{...t,variables:o};return{cwd:t.previous,variables:o,previous:t.cwd}}return{cwd:ae(pe(s,o),t.cwd,n,r),variables:o,previous:t.cwd}}function Qb(e,t){return e.flatMap((n)=>{let r=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(n),o=r?.[2]?.startsWith("=")?r[2].slice(1):void 0;return r?.[1]!==void 0&&o!==void 0?[[r[1],pe(o,t)]]:[]})}function yd(e){return gd.get(e)??qb}function eS(e,t){return[...t].reduce((n,r)=>n.slice(0,r.start)+" ".repeat(r.end-r.start)+n.slice(r.end),e)}function Io(e,t,n,r=Yb){return Object.freeze({status:e,source:t,program:n,assignmentFallbacks:Object.freeze(r)})}function Ft(e,t){return e.nodes.flatMap((n,r)=>tS(n,e,r,t)).sort((n,r)=>n.start-r.start).flatMap((n)=>[...n.events])}function tS(e,t,n,r){if(e.kind==="connector")return[{start:e.span.start,events:[Le(sS(e.operator))]}];if(e.kind==="unknown")return[{start:e.span.start,events:[Le(e.source)]}];if(e.kind==="function")return r.functions.set(e.name,e.body),[];if(e.kind==="group"){let i=e.style!=="subshell",s=r.source[e.span.end-1]===(i?"}":")"),a=i?r:{...r,functions:new Map(r.functions)};return[{start:e.span.start,events:i?[To("{"),...Ft(e.body,a),...s?[To("}")]:[]]:[ar,Le("("),...Ft(e.body,a),...s?[Le(")")]:[],lr]}]}let o=uS(e,r.functions);if(o){if(r.depth>=ht.maxDepth||++r.flags.expansions>Xb)return r.flags.limited=!0,[];return[{start:e.span.start,events:[...dd(e,r),To(";"),...Ft(o,{...r,depth:r.depth+1}),To(";")]},...fd(e,t,n,r)]}return[{start:e.span.start,events:dd(e,r)},...fd(e,t,n,r)]}function dd(e,t){return[...e.words.map((n)=>({start:n.span.start,events:bd(n,e,t,!1)})),...e.redirections.map((n)=>({start:n.span.start,events:nS(n,e,t)}))].sort((n,r)=>n.start-r.start).flatMap((n)=>n.events)}function nS(e,t,n){let r=e.operator==="<<-"?"<<":e.operator,o=e.target?bd(e.target,t,n,!0):[],i=o[0],s=i?.kind==="word"?i.text:void 0;return[...e.fd===void 0?[]:[oa(String(e.fd))],Object.freeze({kind:"redirection",operator:r,...e.fd===void 0?{}:{fd:e.fd},role:aS(r),targetOrder:Hb.has(r)?"legacy-segment":"immediate",...s===void 0?{}:{target:s},...e.heredoc&&n.suppressed.has(e.heredoc.bodySpan)?{body:e.heredoc.body,consumer:vd(t)}:{}}),...s===void 0?o:o.slice(1)]}function fd(e,t,n,r){let o=e.redirections.filter((i)=>i.operator==="<<"||i.operator==="<<-");return[...o.flatMap((i)=>{let s=i.heredoc;if(!s)return[];let a=[oa(s.delimiter),.../[\r\n]/.test(r.source[s.terminatorSpan.end]??"")?[Le(";")]:[]];if(r.suppressed.has(s.bodySpan))return[{start:s.bodySpan.start,events:a}];return[{start:s.bodySpan.start,events:[...Cd(r.source.slice(s.bodySpan.start,s.bodySpan.end),r),...a]}]}),...o.some((i)=>!i.heredoc&&i.target)?rS(t,n,r):[]]}function rS(e,t,n){let r=e.nodes.slice(t+1).find((o)=>o.kind==="connector");if(!r||r.span.end>=e.span.end)return[];return[{start:r.span.end,events:Cd(n.source.slice(r.span.end,e.span.end),n)}]}function Cd(e,t){if(t.depth>=ht.maxDepth)return t.flags.limited=!0,[];let n=Me(e,"posix");if(n.status==="limited")return t.flags.limited=!0,[];let r={invalid:!1,limited:!1,expansions:t.flags.expansions,assignmentFallbacks:t.flags.assignmentFallbacks},o=Ft(n,{source:e,suppressed:new Set,flags:r,depth:t.depth+1,functions:new Map,powershell:!1});return t.flags.limited||=r.limited,t.flags.expansions=r.expansions,o}function bd(e,t,n,r){let o=[],i={single:!1,double:!1},s="",a=!1,l=()=>{let c=a&&!r?Le("glob"):s!==""||e.quoted&&o.length===0?oa(s):void 0;if(c)o.push(c);s="",a=!1};for(let c of e.parts){if(c.provenance!=="command-substitution"&&c.provenance!=="arithmetic"){for(let m of ea(c.raw,i,n.flags,n.powershell)){if(typeof m==="string"){l(),o.push(Le(m));continue}s+=m.text,a||=m.glob}continue}let u=t.nested.find((m)=>m.span.start>=c.span.start&&m.span.end<=c.span.end);if(i.double){let m=n.source.slice(c.span.start,c.span.end);s+=ea(m,{single:!1,double:!0},n.flags,n.powershell).map((p)=>typeof p==="string"?p:p.text).join("");let g=u?Ft(u,n).filter((p)=>p.kind==="redirection"&&p.body!==void 0):[];if(g.length>0)o.push(ar,...g,lr);continue}let f=u?Ft(u,n):[];if(c.raw.startsWith("`")){s+="${}",l(),o.push(ar,...f,lr);continue}if(c.raw.startsWith("<(")||c.raw.startsWith(">(")){l(),o.push(c.raw.startsWith("<(")?Le("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),ar,...f,...c.raw.endsWith(")")?[Le(")")]:[],lr);continue}let d=c.raw.startsWith("$((")?2:1;s+="${}",l(),o.push(...Array.from({length:d},()=>Le("(")),...d===1?[ar]:[],...f,...c.raw.endsWith(")".repeat(d))?Array.from({length:d},()=>Le(")")):[],...d===1?[lr]:[])}return l(),o}function ea(e,t,n,r){let o=[],i="",s=!1,a=0;while(a<e.length){let l=e[a]??"";if(!t.single&&!t.double&&(l==="("||l===")")){o.push({text:i,glob:s},l),i="",s=!1,a++;continue}if(r&&l==="`"&&!t.single){i+=e[a+1]??"",a+=2;continue}if(t.single&&l==="'"){t.single=!1,a++;continue}if(t.single){i+=l,a++;continue}if(t.double){if(l==='"'){t.double=!1,a++;continue}if(!r&&l==="\\"){let c=e[a+1]??"";i+=['"',"\\","$"].includes(c)?c:`\\${c}`,a+=2;continue}if(l==="$"){let c=md(e,a,t,n,r);i+=c.text,a=c.next;continue}i+=l,a++;continue}if(l==="'"||l==='"'){t.single=l==="'",t.double=l==='"',a++;continue}if(!r&&l==="\\"){let c=e[a+1]??"";s||=c==="*"||c==="?",i+=c,a+=2;continue}if(l==="$"){let c=md(e,a,t,n,r);i+=c.text,a=c.next;continue}s||=l==="*"||l==="?",i+=l,a++}return[...o,{text:i,glob:s}]}function md(e,t,n,r,o){let i=e[t+1];if(i==="{"){let a=iS(e,t+2);if(a===-1)return r.invalid=!0,{text:"",next:e.length};let l=e.slice(t,a+1);return oS(l,n,r,o),{text:l,next:a+1}}if(i!==void 0&&Vb.test(i))return{text:`\${${i}}`,next:t+2};let s=(o?Kb:/^\w*/).exec(e.slice(t+1))?.[0]??"";return{text:`\${${s}}`,next:t+1+s.length}}function oS(e,t,n,r){let o=e.slice(2,-1),i=/^[A-Za-z_][A-Za-z0-9_]*/.exec(o)?.[0];if(!i)return;let s=o.slice(i.length),a=[":=","="].find((c)=>s.startsWith(c));if(!a)return;let l=ea(s.slice(a.length),{...t},n,r);n.assignmentFallbacks.push(...l.flatMap((c)=>typeof c==="string"||!c.text?[]:[c.text]))}function iS(e,t){let n=1,r=t;while(n>0&&r<e.length){if(e[r]==="{"&&e[r-1]==="$")n++;if(e[r]==="}")n--;r++}return n===0?r-1:-1}function sS(e){return/^[\r\n]+$/.test(e)?";":e}function Le(e){return Object.freeze({kind:"operator",operator:e,boundary:Ub.has(e)})}function To(e){return Object.freeze({kind:"operator",operator:e,boundary:!0})}function oa(e){return Object.freeze({kind:"word",text:e})}function aS(e){if(e==="<<"||e==="<<<")return"here-data";if(e==="<"||e==="<&")return"file-read";return"file-write"}function dr(e){return Zb.has(e)||/^python\d/.test(e)}var lS=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 Sd(e,t){let n=t[0];if(n===void 0||!n.startsWith("-"))return t;let r=lS.get(e)?.has(n)??!1;return Sd(e,t.slice(r?2:1))}function ta(e){let t=e[0];if(t===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(t))return ta(e.slice(1));if(!$b.has(t))return[...e];return ta(Sd(t,e.slice(1)))}function vd(e){let t=Xn(e),n=e.words.findIndex((r)=>r.provenance==="literal"&&r.text===t);return ta(n<0?[]:e.words.slice(n).map((r)=>r.text))}function cS(e){let t=vd(e)[0];if(t===void 0)return!1;let n=A(t).toLowerCase();return dr(n)&&!cr.has(n)}function na(e){return e.nodes.flatMap((t,n)=>{if(t.kind==="group"||t.kind==="function")return na(t.body);if(t.kind!=="command")return[];let r=t.nested.flatMap((a)=>na(a)),o=t.redirections.flatMap((a)=>a.heredoc?.quotedDelimiter?[a.heredoc.bodySpan]:[]);if(cS(t))return[...r,...o];let i=e.nodes[n+1];if(i?.kind==="connector"&&(i.operator==="|"||i.operator==="|&")||!fS(t))return r;return[...r,...o]})}function uS(e,t){let n=Xn(e);return n===void 0?void 0:t.get(n)}function St(e,t){return e!==void 0&&e.provenance==="literal"&&!e.quoted&&e.raw===e.text&&e.text===t}function dS(e){if(St(e.words[0],"git"))return St(e.words[1],"commit");if(!St(e.words[0],"gh")||!St(e.words[2],"create"))return!1;return St(e.words[1],"pr")||St(e.words[1],"issue")}function fS(e){return(St(e.words[0],"cat")||St(e.words[0],"tee")||dS(e))&&!e.words.some(pd)&&!e.redirections.some((n)=>pd(n.target))}function pd(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}var Ed=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),xd=new Set([...Ed,"glob"]),mS=new Set([...xd,"pattern"]);class We extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Rd(e){let t=pS(),n=Fn(e.input),r=[];if((e.route.kind==="command"||e.route.kind==="unknown")&&n)r.push({usage:"input-candidate",source:n});if(e.route.kind==="command"&&"command"in e&&e.command)r.push({usage:"declared-command",source:e.command});let o=r.reduce((i,s)=>{let a=i.findIndex((u)=>u.source===s.source);if(a!==-1){let u=i[a];if(!u)return i;return i[a]={...u,usages:[...u.usages,s.usage]},i}let l=e.route.kind==="command"?e.route.shell:process.platform==="win32"?"powershell":"posix",c=t.getCommandProgram(s.source,l);return i.push({usages:[s.usage],source:s.source,program:c,shell:t.getShellSyntax(s.source,c)}),i},[]);return{invocation:{toolName:e.toolName,route:e.route,context:e.context},commands:o,paths:gS(e),store:t}}function ge(e,t){return e.commands.find((n)=>n.usages.includes(t))}function ot(e,t){if(!e.includes("$"))return e;return Ai(e,t)}function pS(){let e=new Map,t=new Map,n=new WeakMap,r=(i,s)=>{let a=`${s}\x00${i}`,l=t.get(a);if(l)return l;let c=Me(i,s);return t.set(a,c),c};return{getShellSyntax:(i,s)=>{if(s&&s.source!==i)throw TypeError("Shell syntax source does not match command program source.");let a=s??r(i,"posix");if(a.status==="limited"){let u=n.get(a);if(u)return u;let f={status:"structural-limit",source:i,program:a,assignmentFallbacks:[]};return n.set(a,f),f}let l=e.get(i);if(l)return l;let c=hd(i,a);return e.set(i,c),c},getCommandProgram:r}}function gS(e){let t=e.route.kind==="grep"?xd:e.route.kind==="glob"?mS:Ed;return[...Gl(e.input,t),...e.route.kind==="patch"||typeof e.input==="string"?Bl(e.input):[]]}var hS=new Set(["-S","--suffix"]);function hn(e,t,n,r,o){if(e.status==="structural-limit")throw new We;if(e.status!=="complete")return o.findMalformedTarget(e.source);return ko(e,t,n,r,{segment:(i,s)=>o.findSegmentTarget(i,s),redirection:(i,s)=>i.role==="file-write"&&o.isRedirectionTarget(pe(i.target,s.variables),s)?i.target:null})}function Mo(e){let t=[],n=null,r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i===void 0)break;if(!r&&i==="--"){r=!0;continue}if(!r&&(i==="-t"||i==="--target-directory")){n=e[++o]??null;continue}if(!r&&i.startsWith("--target-directory=")){n=i.slice(19);continue}if(!r&&i.startsWith("-t")&&i.length>2){n=i.slice(2);continue}if(!r&&hS.has(i)){o++;continue}if(!r&&(i.startsWith("--suffix=")||i.startsWith("--backup=")))continue;if(!r&&i.startsWith("-"))continue;t.push(i)}return n?{sources:t,destination:n}:{sources:t.slice(0,-1),destination:t.at(-1)??null}}var Ge="Git metadata and hooks are protected. Ask the user before modifying them.";function Pd(e,t,n,r){let o=e.invocation.context.executionCwd;if(!t)return null;if(e.invocation.route.kind==="patch"||e.invocation.route.kind==="path"||e.invocation.route.kind==="unknown"){if(Dr(e.invocation.toolName))return null;let a=e.paths.find((l)=>_d(l,o,t,n,r,t.entries));return a?{target:a}:null}if(e.invocation.route.kind!=="command")return null;let i=ge(e,"input-candidate");if(!i)return null;let s=hn(i.shell,o,n,r,{findSegmentTarget:(a,l)=>wS(a,l,t,n,r),isRedirectionTarget:(a,l)=>_d(a,l.cwd,t,n,r,t.markerFiles),findMalformedTarget:()=>null});return s?{target:s}:null}function zt(e,t,n,r,o,i,s=!1){if(!n)return!1;let a=No(ae(e,t,o,i)),l=a.replace(/(\/\.?\*+)+$/,"");if(l!==a&&l!==""){if(ia(l,n))return!0;let c=s||a.slice(l.length).includes("/."),u=(f)=>c?Do(f,l):vS(f,l);if(n.markerFiles.some(u))return!0;return r&&sa(n).some(u)}if(ia(a,n))return!0;return r&&sa(n).some((c)=>Do(c,a))}function vS(e,t){let n=Ad(t,e);if(n===""||n.startsWith("..")||wd(n))return!1;return!n.split(/[\\/]/)[0]?.startsWith(".")}function ES(e,t,n,r,o){return zt(e,t,n,!0,r,o)}function xS(e,t,n,r,o){if(!n)return!1;return ia(No(ae(e,t,r,o)),n)}function _d(e,t,n,r,o,i){let s=No(ae(e,t,r,o));return i.includes(s)||Td(s,n)}function Id(e,t,n,r,o){if(!n)return!1;return n.hooksDirectories.some((i)=>e.some((s)=>Do(i,No(ae(s,t,r,o)))))}function ia(e,t){return t.entries.includes(e)||t.directories.includes(e)||Td(e,t)}function Td(e,t){return t.hooksDirectories.some((n)=>Do(e,n))}var RS=50000;function kd(e,t){let n=[...new Set(sa(e))];if(n.some((o)=>t(bS(o))))return!0;let r=0;while(n.length>0){let o=n.pop()??"",i=_S(o);if(!i)return!0;if(r+=i.length,r>RS)return!0;if(i.some((s)=>t(s.name)))return!0;n.push(...i.filter((s)=>s.isDirectory()).map((s)=>SS(o,s.name)))}return!1}function _S(e){try{let t=yS(e,{throwIfNoEntry:!1});if(!t)return[];if(!t.isDirectory())return t.isSymbolicLink()?null:[];return CS(e,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function sa(e){return[...e.entries,...e.directories,...e.hooksDirectories]}function Do(e,t){let n=Ad(t,e);return n===""||!/^\.\.(?:[\\/]|$)/.test(n)&&!wd(n)}function No(e){return process.platform==="win32"?e.toLowerCase():e}function wS(e,t,n,r,o){if(ur(e))return null;let i=bt([...e],r);if(A(i[0]??"").toLowerCase()!=="mv")return null;let s=Mo(i.slice(1)),a=s.sources.find((l)=>ES(pe(l,t.variables),t.cwd,n,r,o));if(a)return a;return s.destination&&xS(pe(s.destination,t.variables),t.cwd,n,r,o)?s.destination:null}import{isAbsolute as Fo,normalize as DS,parse as NS,posix as Fd,resolve as $t,sep as ua}from"node:path";import{isAbsolute as AS,join as Od,normalize as Nd,parse as PS,sep as Md}from"node:path";var IS=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],TS=`
31
- `;function fr(e,t){if(Bt(e,t))return!0;if(!e.has("TMPDIR"))return!1;return!aa(e.get("TMPDIR")??"",t)}function yn(e,t){if(e.has("TMPDIR"))return aa(e.get("TMPDIR")??"",t);let n=la(e,t);if(n===void 0)return!0;return aa(n,t)}function la(e,t){return Wd(e,t,"TMPDIR")}function aa(e,t){if(!e)return!1;if(OS(e))return!1;return Cn(e,t)}function Bt(e,t){let n=Wd(e,t,"IFS");return n!==void 0&&n!==""&&n!==TS}function Cn(e,t){let n=Lo(e,t.paths);if(n===null)return!1;return Ld(t).some((r)=>bn(n,r))}function Go(e,t){let n=Lo(e,t.paths);if(n===null)return!1;return Ld(t).some((r)=>Wo(r)===Wo(n))}var Dd=new WeakMap;function Ld(e){let t=Dd.get(e);if(t)return t;let n=kS(e);return Dd.set(e,n),n}function kS(e){let t=IS.map((r)=>Lo(r,e.paths)??Nd(r)),n=Lo(e.tmpdir,e.paths);if(!n)return t;if(process.platform==="win32")return[...t,n];if(process.platform==="darwin"&&MS(n))return[...t,n];return t}function OS(e){return/[\s$`*?[]/.test(e)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(e)||/[+@!]\([^)]*\)/.test(e)}function Wd(e,t,n){return e.has(n)?e.get(n):t.env.get(n)}function MS(e){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(e)}function Lo(e,t){try{let n=Nd(e);if(!AS(n))return n;let r=PS(n).root,o=n.slice(r.length).split(/[\\/]+/).filter(Boolean),i=r;for(let s=0;s<o.length;s++){let a=Od(i,o[s]??"");if(t.entryKind(a)==="missing")return Od(a,...o.slice(s+1));let l=t.realpath(a);if(l===null)return null;i=l}return i}catch{return null}}function bn(e,t){let n=Wo(e),r=Wo(t);if(n===r)return!0;let o=r.endsWith(Md)?r:`${r}${Md}`;return n.startsWith(o)}function Wo(e){return process.platform==="win32"?e.toLowerCase():e}var LS=process.platform==="win32",Gd=64,WS=16384;function mr(e,t,n,r){if(e.kind==="temp_target")return null;let o=r[e.kind];if(e.kind==="dynamic_target"&&!ee(n,o.id,t.strict))return null;if(e.kind==="within_anchored_cwd"&&!ee(n,o.id,t.paranoid))return null;return v(o.id,o.reason)}function pr(e){let t=Au(e,Gd,Gd,WS);return{expandedTargets:t&&"words"in t?t.words:void 0,unsafeBraceExpansion:t!==void 0&&"limited"in t,targetIsLiteral:t===void 0&&e.provenance==="literal"&&(e.quoted||e.raw!==e.text),tmpdirWordSplittingProtected:GS(e)}}function GS(e){let t=e.parts.filter((n)=>n.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(n.raw));return t.length>0&&t.every((n)=>FS(e.raw,n.span.start-e.span.start))}function FS(e,t){let n=null,r=!1;for(let o=0;o<t;o++){let i=e[o];if(r){r=!1;continue}if(i==="\\"&&n!=="'"){r=!0;continue}if(n===i){n=null;continue}if(n===null&&(i==="'"||i==='"'))n=i}return n==='"'}function vt(e){let t=e.environment.home,n=e.environment.paths,r=e.budget??je();return{anchoredCwd:e.originalCwd??e.cwd??null,resolvedCwd:e.cwd??null,strict:e.strict??!1,paranoid:e.paranoid??!1,trustTmpdirVar:e.allowTmpdirVar??!0,posixShell:e.posixShell??!1,tmpdirWordSplittingUnsafe:e.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:e.trustedTmpdirValue??e.allowTmpdirVar??!0,environment:e.environment,allowRoots:jS(e.allowPaths,t,n,r),protectedGitMetadata:e.protectedGitMetadata,budget:r}}function Fe(e,t,n={}){let r=n.targetIsLiteral??!1;if(!r&&t.tmpdirWordSplittingUnsafe&&!n.tmpdirWordSplittingProtected&&KS(e))return{kind:"outside_anchored_cwd"};let o=!r&&Bd(e,t.posixShell);if(Je(e))return{kind:"outside_anchored_cwd"};if(da(e,r))return{kind:"root_or_home_target"};if(BS(e,t,r))return{kind:"root_or_home_target"};if(t.resolvedCwd&&zt(e,t.resolvedCwd,t.protectedGitMetadata,!0,t.environment,t.budget,!t.posixShell))return{kind:"git_metadata_target"};if($S(e,t.trustTmpdirVar,t.posixShell,o,r,n.tmpdirWordSplittingProtected??!1,t.trustedTmpdirValue,t.environment))return{kind:"temp_target"};if(o)return{kind:"dynamic_target"};if(VS(e,t,r))return{kind:"temp_target"};let i=t.anchoredCwd;if(i){if(!n.skipHomeCwd&&XS(i,t.environment.home,t.environment.paths,t.budget))return{kind:"home_cwd_target"};if(!n.skipCwdSelf&&[t.resolvedCwd??i,i].some((s)=>JS(e,t.resolvedCwd??i,t.environment.paths,t.budget,s)))return{kind:"cwd_self_target"};if(QS(e,i,t.resolvedCwd??i,o,r,t.environment.paths,t.budget))return{kind:"within_anchored_cwd"}}if(zS(e,t,o))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function zS(e,t,n){let r=e.trim();if(n||!t.resolvedCwd||!t.anchoredCwd||!r)return!1;if(Fo(r)||r.startsWith("~"))return!1;if(fa(r))return!1;if($d(t.resolvedCwd,t.anchoredCwd,t.environment.paths,t.budget))return!1;return Cn($t(t.resolvedCwd,r),t.environment)}function zd(e,t,n={}){let{containmentTarget:r,...o}=n;if(Fe(e,t,o).kind!=="temp_target")return!1;let i=e.trim();if(HS(i))return!1;if(Go(i,t.environment))return!1;return![t.anchoredCwd,t.resolvedCwd].some((s)=>$d(r??i,s,t.environment.paths,t.budget))}function da(e,t=!1){let n=e.trim(),r=Fd.normalize(n),o=n.replace(/\\/g,"/"),i=r==="/"?r:r.replace(/\/+$/,"");if(i==="/"||i.startsWith("/")&&i.slice(1).split("/").every((s)=>/^\*+$/.test(s)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(o)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(o))return!0;if(!t&&(r==="~"||r==="~/"||r==="~/*"))return!0;if(!t&&(r==="$HOME"||r==="$HOME/"||r==="$HOME/*"))return!0;if(!t&&(r==="${HOME}"||r==="${HOME}/"||r==="${HOME}/*"))return!0;return!1}function BS(e,t,n){let r=e.trim(),o=n?r:r==="*"?".":r.endsWith("/*")?r.slice(0,-2):r;if(!o)return!1;try{let i=Fo(o)?o:t.resolvedCwd?$t(t.resolvedCwd,o):null;if(!i)return!1;let s=he(L(i,t.environment.paths,t.budget));if(s===NS(s).root)return!0;return s===he(L(t.environment.home,t.environment.paths,t.budget))}catch{return!1}}function he(e){let t=DS(e);if(LS){if(t=t.replace(/\//g,"\\").toLowerCase(),t.length>3&&t.endsWith("\\"))t=t.slice(0,-1);return t}if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);return t}function $S(e,t,n,r,o,i,s,a){let l=e.trim();if(fa(l))return!1;if(!r&&Cn(l,a))return!0;return(t||i&&s)&&n&&!o&&US(l,n)}function US(e,t){return["$TMPDIR","${TMPDIR}"].some((n)=>{if(e===n)return!0;if(!e.startsWith(`${n}/`))return!1;return!Bd(e.slice(n.length+1),t)})}function HS(e){let t=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(e);if(!t)return!1;return Fd.normalize(`/${t[1]??""}`)==="/"}function fa(e){return e.split(/[\\/]+/).includes("..")}function jS(e,t,n,r){if(!e?.length)return[];return e.flatMap((o)=>{let i=qn(o.trim(),t);if(!Fo(i))return[];try{let s=L(i,n,r);if(Yn(s,L(t,n,r)))return[];return[he(s)]}catch{return[]}})}function VS(e,t,n){if(t.allowRoots.length===0)return!1;let r=e.trim();if(fa(r))return!1;let o=n?r:qn(r,t.environment.home),i=t.resolvedCwd??t.anchoredCwd,s=Fo(o)?o:i?$t(i,o):null;if(!s)return!1;try{let a=he(L(s,t.environment.paths,t.budget));return t.allowRoots.some((l)=>a===l||a.startsWith(l.endsWith(ua)?l:`${l}${ua}`))}catch{return!1}}function KS(e){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(e)}function Bd(e,t=!1){return e.includes("$")||e.includes("`")||qS(e)||t&&YS(e)}function qS(e){let t=!1;for(let n of e){if(t){t=!1;continue}if(n==="\\"){t=!0;continue}if(n==="*"||n==="?"||n==="[")return!0}return!1}function YS(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(t){t=!1;continue}if(r==="\\"){t=!0;continue}if(r==="{"&&ZS(e,n)||(r==="+"||r==="@"||r==="!")&&e[n+1]==="(")return!0}return!1}function ZS(e,t){let n=e.indexOf("}",t+1);if(n===-1)return!1;let r=e.slice(t+1,n);return r.includes(",")||r.includes("..")}function XS(e,t,n,r){try{return he(L(e,n,r))===he(L(t,n,r))}catch{try{return he(e)===he(t)}catch{return!1}}}function JS(e,t,n,r,o=t){if(o===t&&(e==="."||e==="./"||e===".\\"))return!0;try{return he(L($t(t,e),n,r))===he(L(o,n,r))}catch{try{return he($t(t,e))===he(o)}catch{return!1}}}function QS(e,t,n,r,o,i,s){let a=n??t;if(!o&&(e.startsWith("~")||e.startsWith("$HOME")||e.startsWith("${HOME}")))return!1;if(r)return!1;if(e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e))try{return ca(e,t,i,s)}catch{return!1}if(e.startsWith("./")||e.startsWith(".\\")||!e.includes("/")&&!e.includes("\\"))try{return ca($t(a,e),t,i,s)}catch{return!1}if(e.startsWith("../"))return!1;try{return ca($t(a,e),t,i,s)}catch{return!1}}function ca(e,t,n,r){try{return Ud(L(e,n,r),L(t,n,r))}catch{return!1}}function $d(e,t,n,r){if(!t)return!1;try{return Ud(L(t,n,r),L(e,n,r))}catch{return!0}}function Ud(e,t){let n=he(e),r=he(t);return n.startsWith(`${r}${ua}`)||n===r}var ev=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),Hd="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",tv="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.",jd="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",Vd="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",nv="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",rv="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",ov={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:Vd},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:Ge},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:jd},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:nv},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:Hd},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:tv},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:Hd}};function Kd(e,t,n){return iv(e.words.map((r)=>({kind:"word",text:r.text,dynamic:r.provenance!=="literal"})),t,vt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths}),n.policy)}function iv(e,t,n,r){let o=e.filter((l)=>l.kind==="word"),i=av(o),s=o[i];if(!s||!ev.has(hv(s.text)))return null;let a=sv(o.slice(i+1));if(a.whatIfProtected)return null;if(ee(r,"powershell.remove-item-pipeline-dynamic-target",n.strict)&&t&&(a.targets.length===0||a.recursive))return v("powershell.remove-item-pipeline-dynamic-target",rv);for(let l of a.targets)if(!Je(l.text)&&da(pa(l.text)))return v(a.recursive&&a.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Vd);for(let l of a.targets)if(n.resolvedCwd&&zt(pa(l.text),n.resolvedCwd,n.protectedGitMetadata,a.recursive,n.environment,n.budget,!0))return v("powershell.remove-item-git-metadata",Ge);if(!a.recursive||!a.force)return null;if(ee(r,"powershell.remove-item-recursive-force-dynamic-target",n.strict)&&(a.hasDynamicTarget||a.targets.length===0))return v("powershell.remove-item-recursive-force-dynamic-target",jd);for(let l of a.targets){let c=mr(Fe(pa(l.text),n),n,r,ov);if(c)return c}return null}function sv(e){let t=[],n=!1,r=!1,o=!1,i=!1,s=!1;for(let a=0;a<e.length;a++){let l=e[a];if(!l||l.kind!=="word")continue;if(lv(l))continue;if(s){t.push(ma(l)),i=i||l.dynamic;continue}if(l.text==="--"){s=!0;continue}let c=uv(l.text);if(!c){t.push(ma(l)),i=i||l.dynamic;continue}if(dv(c.name)){let u=c.value?cv(c.value,l):e[++a];if(u?.kind==="word"){t.push(ma(u)),i=i||u.dynamic;continue}i=!0;continue}if(fv(c.name)){n=!0;continue}if(mv(c.name)){r=!0;continue}if(pv(c.name))o=gv(c.value)}return{targets:t,recursive:n,force:r,whatIfProtected:o,hasDynamicTarget:i}}function av(e){let t=e[0];if(t?.kind==="word"&&t.text==="&"||t?.text===".")return e.length>1?1:0;return 0}function ma(e){return{text:e.kind==="word"?e.text:"",dynamic:e.kind==="word"&&e.dynamic}}function lv(e){return e.kind==="word"&&e.text===","}function pa(e){let t=e.replace(/\\/g,"/"),n=/^(?:\$env:(?:userprofile|home)|\$home|\$\{home\})(?=$|\/)/i.exec(t);return n?`$HOME${t.slice(n[0].length)}`:t}function cv(e,t){return{kind:"word",text:e,dynamic:t.kind==="word"&&(t.dynamic||e.includes("$"))}}function uv(e){if(!e.startsWith("-")||e==="-")return null;let t=e.slice(1),n=t.indexOf(":");if(n===-1)return{name:t.toLowerCase()};return{name:t.slice(0,n).toLowerCase(),value:t.slice(n+1)}}function dv(e){return"path".startsWith(e)||"literalpath".startsWith(e)}function fv(e){return"recurse".startsWith(e)}function mv(e){return e.length>=2&&"force".startsWith(e)}function pv(e){return e==="wi"||"whatif".startsWith(e)}function gv(e){if(e===void 0||e==="")return!0;let t=e.toLowerCase();return t==="$true"||t==="true"}function hv(e){return e.toLowerCase()}var Sn="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",zo="Unsupported heredoc syntax",gr="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.",qd="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var yv=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),Cv=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),bv=new Set(["-o","--output","--query","--subscription"]),Sv=new Set;function Yd(e){if(e==="aws")return yv;if(e==="gcloud")return Cv;if(e==="az")return bv;return Sv}var vv=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),Ev=new Set;function Zd(e){if(e==="git")return ve;if(e==="docker")return vv;return Ev}function it(e,t){if(e.length===0||t.length===0)return null;let n=k(e[0]??""),r=fe(e);for(let o of t){if(!_v(n,o.command))continue;if(o.match){if(xv(n,e,o.match))return Xd(o);continue}if(!wv(n,e,o.subcommand))continue;if(Pv(e,new Set(o.block_args),r))return Xd(o)}return null}function Xd(e){return{id:`custom.${e.name}`,reason:`[${e.name}] ${e.reason}`,intent:e.intent??"manual_only"}}function xv(e,t,n){let r=t.slice(1);if(n.exclude_args?.some((o)=>r.includes(o)))return!1;if(n.any_args&&!n.any_args.some((o)=>r.includes(o)))return!1;return Rv(r,n.command_path,Yd(e))}function Rv(e,t,n){let r=0,o=!1;for(let i of e){if(r>=t.length)return!0;if(o){o=!1;continue}if(i.startsWith("-")){o=!i.includes("=")&&n.has(i);continue}if(i!==t[r])return!1;r++}return r>=t.length}function _v(e,t){return e===k(t)}function wv(e,t,n){if(!n)return!0;return Jd(t,1,n,Zd(e))}function Jd(e,t,n,r){let o=!1;for(let i=t;i<e.length;i++){let s=e[i];if(!s)continue;if(o){o=!1;continue}if(s==="--"){let a=e[i+1];if(a&&!a.startsWith("-"))return a===n;return!1}if(r.has(s)){o=!0;continue}if(s.startsWith("-")){if(!s.includes("=")&&Av(e,i,n,r))return!0;continue}return s===n}return!1}function Av(e,t,n,r){let o=e[t+1];if(!o||o.startsWith("-"))return!1;return Jd(e,t+2,n,r)}function Pv(e,t,n){return e.some((r)=>t.has(r))||[...n].some((r)=>t.has(r))}var Iv=new Set(["-e","--source"]),Tv=new Set(["-F","-v","--assign","--field-separator"]),Qd=new Set(["-f","--file"]),kv=new Set(["print","printf","return"]),ef=[{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"}],Ov="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 tf(e,t,n){let r=!1;for(let o of Mv(e)){let i=Dv(o,n);if(!i)continue;for(let s of i.commands){let a=t(s);if(a)return a;if(s.includes("{}")||/[$`]/.test(s))r=!0}r||=i.dynamic}return r?v("awk.system-dynamic",Ov):null}function ha(e){let t=[],n=!1,r=!1,o=!0,i=!0;for(let s=1;s<e.length;s++){let a=e[s];if(a===void 0)break;if(o&&a==="--"){o=!1;continue}if(o&&Iv.has(a)){n=!0;let l=e[s+1];if(i&&=l!==void 0,l!==void 0)t.push({tokenIndex:s+1,kind:"inline-code",value:l});s++;continue}if(o&&a.startsWith("--source=")){n=!0,t.push({tokenIndex:s,kind:"inline-code",value:a.slice(9)});continue}if(o&&a.startsWith("-e")&&a.length>2){n=!0,t.push({tokenIndex:s,kind:"inline-code",value:a.slice(2)});continue}if(o&&(Tv.has(a)||Qd.has(a))){let l=e[s+1];if(i&&=l!==void 0,Qd.has(a)){if(r=!0,l!==void 0)t.push({tokenIndex:s+1,kind:"program-file",value:l})}s++;continue}if(o&&(a.startsWith("-F")||a.startsWith("-v")&&a.slice(2).includes("=")))continue;if(o&&a.startsWith("-f")&&a.length>2){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(2)});continue}if(o&&(a.startsWith("--assign=")||a.startsWith("--field-separator=")))continue;if(o&&a.startsWith("--file=")){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(7)});continue}if(o&&a.startsWith("-")&&a!=="-")continue;if(!n&&!r)t.push({tokenIndex:s,kind:"main-program",value:a});return{sources:t,optionsOpen:!1}}return{sources:i?t:[],optionsOpen:o&&i}}function yr(e){return ha(e).sources}function Mv(e){return yr(e).filter((t)=>t.kind!=="program-file").map((t)=>t.value)}function Dv(e,t){Re(t,e);let n=e.includes("system")?ya(e,t):null,r=Nv(e,t);if(!n&&!r)return null;return{dynamic:!!n?.dynamic||!!r?.dynamic,commands:[...n?.commands??[],...r?.commands??[]]}}function ya(e,t){Re(t,e);let n=[],r=!1,o=!1,i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){i=$o(e,i,s)?.endIndex??i+1;continue}if(s==="#"){i=nf(e,i+1);continue}if(s==="/"&&rf(e,i)){i=of(e,i+1)??i+1;continue}if(!e.startsWith("system",i)){i++;continue}let a=i;if(i+=6,hr(e[a-1])||hr(e[i]))continue;let l=Bo(e,i);if(e[l]!=="(")continue;l=Bo(e,l+1);let c=e[l];if(c!=='"'&&c!=="'"){r=!0,o=!0;continue}let u=$o(e,l,c);if(!u){r=!0,o=!0;continue}if(l=Bo(e,u.endIndex),r=!0,e[l]!==")"){o=!0,i=u.endIndex;continue}n.push(u.value),i=l+1}if(!r)return null;return{dynamic:o,commands:n}}function Nv(e,t){Re(t,e);let n=[],r=!1,o=!1,i=0,s=0,a=null,l=null,c=0;while(i<e.length){let u=e[i];if(!u)break;if(u==='"'||u==="'"){let m=$o(e,i,u);if(m&&c===s)l={...m,startIndex:i};c=m?.endIndex??i+1,i=m?.endIndex??i+1;continue}if(u==="#"){i=nf(e,i+1),s=i,a=null,l=null,c=i;continue}if(u==="/"&&rf(e,i)){let m=of(e,i+1);c=m??i+1,i=m??i+1;continue}if(`;
32
- {}`.includes(u)){i++,s=i,a=null,l=null,c=i;continue}if(a===null&&(ga(e,i,"print")||ga(e,i,"printf")))a=i;if(u!=="|"||e[i-1]==="|"||e[i+1]==="|"){if(!/\s/.test(u))c=i+1;i++;continue}let f=e[i+1]==="&"?i+2:i+1,d=Bo(e,f);if(ga(e,d,"getline")){o=!0;let m=Gv(s,l,c);if(r||=m===null,m!==null)n.push(m);c=f,i=f;continue}if(zv(s,a)){o=!0;let m=Wv(e,d);if(!m){r=!0,c=f,i=f;continue}if(!Lv(e,m.endIndex)){r=!0,c=m.endIndex,i=m.endIndex;continue}n.push(m.value),c=m.endIndex,i=m.endIndex;continue}c=f,i++}if(!o)return null;return{dynamic:r,commands:n}}function hr(e){return!!e&&/[A-Za-z0-9_]/.test(e)}function Bo(e,t){let n=t;while(/\s/.test(e[n]??""))n++;return n}function Lv(e,t){let n=t;while(/[\t\f\v\r ]/.test(e[n]??""))n++;let r=e[n];return!r||`;
33
- }#`.includes(r)}function $o(e,t,n){let r="",o=!1;for(let i=t+1;i<e.length;i++){let s=e[i];if(!s)break;if(o){let a=Fv(e,i);if(!a)return null;r+=a.value,i=a.endIndex,o=!1;continue}if(s==="\\"){o=!0;continue}if(s===n)return{value:r,endIndex:i+1};r+=s}return null}function Wv(e,t){let n=e[t];if(n!=='"'&&n!=="'")return null;return $o(e,t,n)}function Gv(e,t,n){if(!t)return null;return t.startIndex>=e&&t.endIndex===n?t.value:null}function Fv(e,t){let n=e[t];if(!n)return null;if(n==="x"){let o=e.slice(t+1,t+3);if(!/^[0-9A-Fa-f]{2}$/.test(o))return null;return{value:String.fromCharCode(Number.parseInt(o,16)),endIndex:t+2}}if(/[0-7]/.test(n)){let o=/^[0-7]{1,3}/.exec(e.slice(t));if(!o)return null;return{value:String.fromCharCode(Number.parseInt(o[0],8)),endIndex:t+o[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
34
- `,r:"\r",t:"\t",v:"\v"}[n]??n,endIndex:t}}function ga(e,t,n){return e.startsWith(n,t)&&!hr(e[t-1])&&!hr(e[t+n.length])}function zv(e,t){return t!==null&&t>=e}function nf(e,t){let n=e.indexOf(`
35
- `,t);return n===-1?e.length:n+1}function rf(e,t){let n=Bv(e,t);if(n===-1)return!0;if("{([,;!~=".includes(e[n]??""))return!0;let r=n;while(hr(e[r-1]))r--;return kv.has(e.slice(r,n+1))}function Bv(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function of(e,t){let n=!1;for(let r=t;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="/")return r+1}return null}var $v="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",Uv="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",Hv="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function sf(e){return e==="dd"||e==="shred"||e==="mkfs"||e.startsWith("mkfs.")}function af(e,t){let n=t.slice(1);if(e==="dd"&&n.some((r)=>/^of=\/dev\/.+/.test(r)))return v("dd.device-write",$v);if((e==="mkfs"||e.startsWith("mkfs."))&&n.some((r)=>r.startsWith("/dev/")))return v("mkfs.device",Uv);if(e==="shred"&&n.length>0)return v("shred.target",Hv);return null}var jv=new Set(["sudo","env","command","builtin"]),Vv=new Set(["caffeinate","exec","nice","nohup","setsid","stdbuf","time","timeout"]);function Uo(e,t){let n=e[0];if(!n||!lf(A(n),t))return null;let r=A(n),o=e[1]==="--"?2:1,i=Kv(e,o,r,t),s=i[0];if(s===void 0)return null;return{wrapper:r,tokens:e.slice(s),childIndex:s,alternativeChildIndices:i.slice(1)}}function Kv(e,t,n,r){let o=e[1]==="--",i=[];for(let s=t;s<e.length;s++){let a=e[s];if(!a)continue;let l=A(a)!==n&&qv(a,r);if(l)i.push(s);if(!l&&Hr.has(k(a)))break;if(o)break}return i}function qv(e,t){let n=A(e),r=k(e);return r==="git"||n==="busybox"||Ut(e)||rs.has(n)||sf(r)||lf(n,t)||q.has(r)||e==="$SHELL"||Oe(r)||Ae.has(r)||t.rules.some((o)=>o.command===n)}function lf(e,t){return Vv.has(e)||t.transparentWrappers.includes(e)}function Ut(e){return jv.has(e.toLowerCase())}function Ht(e,t){return{embedded:!1,cwd:e.cwd,originalCwd:t.originalCwd,effectiveCwd:e.cwd,envAssignments:e.envAssignments,allowTmpdirVar:t.allowTmpdirVar,worktreeMode:t.worktreeMode,wrappedByTransparent:!1}}function ze(e,t){let n=t.policy??{rules:[],transparentWrappers:[]};return Ho([...e],t.environment,t.cwd,t.cwd,new Map,new Map(t.envAssignments??[]),n,{iterations:0},!1)}function*Ho(e,t,n,r,o,i,s,a,l){let c=Po(e,t,n,i);for(let[m,g]of c.envAssignments)i.set(m,g),o.set(m,g);let{tokens:u,cwd:f}=c;if(c.envSplitValues){let m=Ao(c.envSplitValues,u);if(!m)throw new N("derivedCommandShape");Ca(a),yield*Ho(m,t,f,r,o,i,s,a,l);return}if(Ut(u[0]??""))throw new N("wrapperPeelIterations");let d=Uo(u,s);if(d){for(let m of[d.childIndex,...d.alternativeChildIndices])Ca(a),yield*Ho(m===d.childIndex?d.tokens:u.slice(m),t,f,r,new Map(o),new Map(i),s,a,!0);return}if(Zv(u)){Ca(a),yield*Ho(u.slice(1),t,f,r,o,i,s,a,l);return}yield Yv(u,f,r,o,i,l)}function Yv(e,t,n,r,o,i){return{tokens:e,cwd:t===null?void 0:t??n,wrapperCwd:t,wrapperEnvAssignments:r,envAssignments:o,head:A(e[0]??"").toLowerCase(),wrappedByTransparent:i}}function Ca(e){if(e.iterations>=V.wrapperPeelIterations.cap)throw new N("wrapperPeelIterations");e.iterations++}function Zv(e){return A(e[0]??"").toLowerCase()==="busybox"&&e.length>1}function ba(e,t){let n=[],r=t;while(r<e.length){let o=e[r];if(o===void 0||o===":::")break;n.push(o),r++}return{markerIndex:r<e.length&&e[r]===":::"?r:-1,templateTokens:n}}function st(e){let t=!1,n=!1;for(let r of e){if(r==="--")break;if(r==="-r"||r==="-R"||Sa(r,"recursive")){t=!0;continue}if(r==="-f"||Sa(r,"force")){n=!0;continue}if(r.startsWith("-")&&!r.startsWith("--")){if(r.includes("r")||r.includes("R"))t=!0;if(r.includes("f"))n=!0}}return t&&n}function jo(e){let t=e.indexOf("--");return e.slice(1,t===-1?void 0:t).some((n)=>Sa(n,"recursive")||/^-[A-Za-z]+$/.test(n)&&/[rR]/.test(n.slice(1)))}function Sa(e,t){return e.length>2&&e.startsWith("--")&&t.startsWith(e.slice(2))}var Xv=["--init-file","--rcfile"],Jv=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function Be(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n)continue;if(n==="-c")return cf(e,t,!0);if(n.startsWith("-")&&n.includes("c")&&!n.startsWith("--")){let r=cf(e,t,!1);if(r!==null)return r}}return null}function at(e){let t=A(e[0]??"").toLowerCase();if(t==="zsh"||t==="ksh")return Ee(e).syntaxCheck;let n=!1;for(let r of e.slice(1)){if(r==="--")return n;if(r.startsWith("+")&&!r.startsWith("++")){if(r.slice(1).includes("n"))n=!1;continue}if(!r.startsWith("-")||r.startsWith("--"))return n;let o=r.slice(1);if(o.includes("n"))n=!0;if(o.includes("c"))return n}return n}function cf(e,t,n){if(e[t+1]==="--")return e[t+2]||null;let r=e[t+1];if(!r||!n&&r.startsWith("-"))return null;return r}function uf(e){let t=A(e[0]??"").toLowerCase(),n=Qv(e,t),r=Jv.get(t)??null,o=n.argvSource?.kind!=="absent";return{argvSource:t==="bash"?n.argvSource:null,argvSourceApplies:t==="bash"&&n.interactive&&n.argvSource?.kind==="literal",envName:r,envSourceApplies:o&&(r==="BASH_ENV"?!n.interactive:r==="ENV"&&n.interactive)}}function Qv(e,t){let n=Ee(e),r=n.commandIndex??n.scriptIndex??e.length,o=[],i=!1,s=!0;for(let a=1;a<r;a++){let l=e[a];if(l===void 0||l==="--"||l==="-"||l[0]!=="-"&&l[0]!=="+")break;if(l.startsWith("--")){if(t==="bash"&&s?Xv.find((d)=>l===d):void 0){let d=e[a+1];o.push(d===void 0?{kind:"absent"}:{kind:"literal",value:d}),a++;continue}let f=l.split("=",1)[0]??l;if(t==="bash"&&ts.has(f)&&!l.includes("="))a++;continue}if(t==="bash")s=!1;let c=ns(t,l,e[a+1],"startup");if(c.interactive)i=l[0]==="-";a+=c.followingValues}return{argvSource:o.at(-1)??null,interactive:i}}var eE="find -delete permanently removes files. Use -print first to preview.",tE="find -exec rm -rf is dangerous. Use explicit file list instead.",nE=new Set(["-exec","-execdir","-ok","-okdir"]),rE=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((e)=>[e,1]),["-fprintf",2]]);function df(e,t){let n=e.map(_),r=oE(e,n,t);if(r)return r;if(Vo(n,1)&&!uE(e,n,t)){let s=w(v("find.delete",eE),t.policy);if(s)return s}let o=t.budget??je(),i=0;while(i<n.length){let s=n[i],a=lt(s??"");if(a>0){i+=a+1;continue}if(!Ke(s)){i++;continue}o.charge("derivedTokens",n.length-i-1);let l=vn(n,i);i=l.nextIndex;let c=fE(l.tokens,t.environment);if(c){let m=w(c,t.policy);if(m)return m}let u=s==="-execdir"||s==="-okdir",f=t.analyzeTokens?.(l.tokens,u?null:t.cwd)??null,d=f?.id.startsWith("custom.")?f:w(f,t.policy);if(d)return d}return null}function oE(e,t,n){if(!Vo(t,1)&&!va(t,n.environment))return null;let o=Cr(e)??K(["."]),i=vt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let s of o){let a=pr(s);for(let l of a.expandedTargets??[_(s)]){let c=Fe(l,i,{targetIsLiteral:a.expandedTargets!==void 0||a.targetIsLiteral,tmpdirWordSplittingProtected:a.tmpdirWordSplittingProtected});if(c.kind==="root_or_home_target")return v("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(c.kind==="git_metadata_target"&&!iE(e,i.protectedGitMetadata,n.environment))return v("find.delete-git-metadata",Ge)}}if(cE(t)&&i.resolvedCwd&&Id(o.map(_),i.resolvedCwd,i.protectedGitMetadata,i.environment,i.budget))return v("find.delete-git-metadata",Ge);return null}function iE(e,t,n){if(!t)return!1;let r=e.map(_),o=[],i=!1,s=Cr(e)?.at(-1),a=s?e.indexOf(s)+1:1;while(a<r.length){let l=r[a]??"";if(Ke(l)){let c=vn(r,a),u=bt([...c.tokens],n),f=jo(u),d=q.has(A(u[0]??"").toLowerCase()),m=c.tokens.some((p)=>p!=="{}"&&p.includes("{}")),g=(l==="-execdir"||l==="-okdir")&&u.slice(1).some((p)=>p!=="{}"&&!p.startsWith("-"));if(f||d||m||g)return!1;i=!0,a=c.nextIndex;continue}if(l==="-delete"){i=!0,a++;continue}if(l==="-name"||l==="-iname"){let c=e[a+1];if(!(c?.provenance==="literal"&&!/[[\\]/.test(c.text)))return!1;if(!i)o.push(aE(c.text,l==="-iname"));a+=2;continue}if(!sE.has(l))return!1;a+=1+lt(l)}return o.length>0&&!kd(t,(l)=>o.every((c)=>c.test(l)))}var sE=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function aE(e,t){let n=e.replace(/[*?]|[.+^${}()|\]/]/g,(r)=>r==="*"?".*":r==="?"?".":`\\${r}`);return new RegExp(`^${n}$`,t?"isu":"su")}var lE=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function va(e,t){let n=0;while(n<e.length){if(!Ke(e[n])){n++;continue}let r=vn(e,n),o=bt([...r.tokens],t),i=A(o[0]??"").toLowerCase(),s=q.has(i)&&lE.test((Be(o)??"").replace(/["'\\]/g,""));if((i==="rm"||i==="rmdir"||s)&&o.some((l)=>l.includes("{}")))return!0;n=r.nextIndex}return!1}function cE(e){return e.some((t,n)=>{if(!["-name","-iname"].includes(t))return!1;return e[n+1]?.toLowerCase()==="hooks"})}function uE(e,t,n){if(t.includes("-L")||t.includes("-f")||t.includes("-follow"))return!1;let r=Cr(e);if(!r)return!1;let o=n.envAssignments??new Map,i=la(o,n.environment),s=n.trustedTmpdirValue??yn(o,n.environment),a=n.allowTmpdirVar??!fr(o,n.environment),l={environment:n.environment,protectedGitMetadata:n.protectedGitMetadata,cwd:n.cwd,originalCwd:n.originalCwd,strict:n.strict,allowTmpdirVar:a&&s&&Boolean(i),allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:n.tmpdirWordSplittingUnsafe??Bt(o,n.environment),trustedTmpdirValue:s,budget:n.budget},c=vt(l),u=vt({...l,cwd:n.originalCwd??n.cwd}),f=n.originalCwd&&n.environment.paths.realpath(n.originalCwd),d=n.cwd&&n.environment.paths.realpath(n.cwd),m=f&&d&&!bn(d,f)?n.cwd:void 0;return r.every((g)=>{let p=pr(g);if(p.unsafeBraceExpansion)return!1;return(p.expandedTargets??[_(g)]).every((h)=>{let C=/^\.\/*$/.test(h)?m:void 0,b=C??h,y={targetIsLiteral:p.expandedTargets!==void 0||p.targetIsLiteral,tmpdirWordSplittingProtected:p.tmpdirWordSplittingProtected};if(!ee(n.policy,"rm.recursive-force-paranoid",n.paranoid??!1)&&!C&&Fe(b,c,y).kind==="within_anchored_cwd")return!0;return zd(b,C?u:c,{...y,containmentTarget:dE(b,i)})})})}function dE(e,t){if(!t)return e;return e.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>t)}function Cr(e){let t=(o)=>{let i=e[o];return i?_(i):void 0},n=1;while(t(n)==="-H"||t(n)==="-P")n++;if(t(n)==="--")n++;let r=[];while(n<e.length){let o=t(n),i=e[n];if(!o||!i||o.startsWith("-")||["!","(",")"].includes(o))break;r.push(i),n++}return r.length>0?r:null}function fE(e,t){let n=Ct([...e],t);if(n.length===0)return null;let r=A(n[0]??"");if(r==="busybox"&&n.length>1)n=n.slice(1),r=A(n[0]??"");if(r==="rm"&&st(n))return v("find.exec-rm-recursive-force",tE);return null}function vn(e,t){let n=t+1;while(n<e.length&&e[n]!==";"&&!(e[n]==="+"&&e[n-1]==="{}"))n++;return{tokens:e.slice(t+1,n),nextIndex:Math.min(n+1,e.length)}}function Vo(e,t){let n=t;while(n<e.length){let r=e[n];if(!r){n++;continue}if(Ke(r)){n=vn(e,n).nextIndex;continue}let o=lt(r);if(o>0){n+=o+1;continue}if(r==="-delete")return!0;n++}return!1}function lt(e){return rE.get(e)??(/^-newer[A-Za-z]{2}$/.test(e)?1:0)}function Ke(e){return e!==void 0&&nE.has(e)}import{resolve as Fx}from"node:path";function br(e){let t=Me(e,"posix");if(t.status!=="complete"||t.nodes.length!==1)return null;let n=t.nodes[0];if(n?.kind!=="command")return null;if(n.redirections.length>0||n.nested.length>0)return null;if(n.words.some((r)=>r.provenance==="command-substitution"))return null;return n.words.map((r)=>r.text)}var mE=5,Ea="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 oe(e){let t=e.indexOf("--");if(t===-1)return{index:-1,before:e,after:[]};return{index:t,before:e.slice(0,t),after:e.slice(t+1)}}function mf(e,t,n){let r=Ko(e,t,n),o=pE(r.entries);if(o.size===0)return{blockedReason:r.blockedReason,expanded:!1,tokens:e};let i=e,s=!1;for(let a=0;a<mE;a++){let{subcommand:l,rest:c}=_e(i),u=l?.toLowerCase();if(!u||!o.has(u))return{blockedReason:r.blockedReason,expanded:s,tokens:i};let f=o.get(u),d=bE(f);if(d===null||d.length===0)return{blockedReason:Ea,expanded:!0,tokens:i};i=["git",...d,...c],s=!0}return{blockedReason:Ea,expanded:!0,tokens:i}}function pf(e,t,n){return Ko(e,t,n).entries.some((r)=>r.key.toLowerCase()==="core.sshcommand")}function _e(e){if(e.length===0)return{subcommand:null,rest:[]};let t=e[0];if((t?A(t).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let r=1;while(r<e.length){let o=e[r];if(!o)break;if(o==="--"){let i=e[r+1];if(i&&!i.startsWith("-"))return{subcommand:i,rest:e.slice(r+2)};return{subcommand:null,rest:e.slice(r+1)}}if(!o.startsWith("-"))return{subcommand:o,rest:e.slice(r+1)};r+=ve.has(o)?2:1}return{subcommand:null,rest:[]}}function pE(e){let t=new Map;for(let n of e){let r=n.key.toLowerCase();if(!r.startsWith("alias."))continue;let o=r.slice(6);if(o!=="")t.set(o,n.value)}return t}function Ko(e,t,n){if(e.length===0)return{blockedReason:null,entries:[]};let r=e[0];if((r?A(r).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let i=hE(t,n);return{blockedReason:i.blockedReason,entries:[...i.entries,...gE(e,t,n)]}}function gE(e,t,n){let r=[],o=1;while(o<e.length){let i=e[o];if(!i||i==="--"||!i.startsWith("-"))return r;if(i==="-c"){let s=xa(e[o+1]);if(s)r.push(s);o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=xa(i.slice(2));if(s)r.push(s);o++;continue}if(i==="--config-env"){let s=ff(e[o+1],t,n);if(s)r.push(s);o+=2;continue}if(i.startsWith("--config-env=")){let s=ff(i.slice(13),t,n);if(s)r.push(s);o++;continue}if(ve.has(i)){o+=2;continue}o++}return r}function hE(e,t){let n=yE(e,t),r=CE(e,t);return{blockedReason:n===null||r===null?Ea:null,entries:[...n??[],...r??[]]}}function yE(e,t){let n=rt("GIT_CONFIG_PARAMETERS",e,t);if(n===void 0)return[];let r=[],o=br(n);if(!o)return null;for(let i of o){let s=xa(i);if(!s)return null;r.push(s)}return r}function CE(e,t){let n=rd(e,t);if(n.state==="absent")return[];if(n.state==="invalid")return null;let r=[];for(let o=0;o<n.count;o++){let i=rt(`GIT_CONFIG_KEY_${o}`,e,t)?.trim(),s=rt(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i||s===void 0)return null;r.push({key:i,value:s})}return r}function xa(e){if(!e)return null;let t=e.indexOf("=");return{key:(t===-1?e:e.slice(0,t)).trim(),value:t===-1?void 0:e.slice(t+1)}}function ff(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;return{key:e.slice(0,r).trim(),value:rt(e.slice(r+1),t,n)}}function bE(e){let t=e?.trimStart();if(!t||t.startsWith("!"))return null;return br(t)}var SE="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",vE="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",EE="git checkout --force discards uncommitted changes. Use 'git stash' first.",xE="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",RE="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",_E="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",wE="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",AE="git switch --force discards uncommitted changes. Use 'git stash' first.",PE="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",IE="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",TE="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",kE="git reset --merge can lose uncommitted changes. Use 'git stash' first.",OE="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",ME="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.",DE="git push --force destroys remote history. Use --force-with-lease for safer force push.",NE="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",LE="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",WE="git branch -D force-deletes without merge check. Use -d for safe delete.",GE="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",FE="git merge --abort discards merge conflict resolutions. Use 'git status' first.",zE="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",BE="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",$E="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",UE="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",HE="git worktree remove --force can delete uncommitted changes. Remove --force flag.",jE=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),VE=new Set(["--recurse-submodules","--track","-t"]),Ra=new Set(["-b","-B","-U"]),_a=new Set(["-c","-C"]),KE=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function O(e,t){let n=e.split("=",1)[0]??e;return n.length>=4&&t.startsWith(n)&&n.startsWith("--")&&n.slice(2).length>=2}var En=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function hf(e,t){let{subcommand:n,rest:r}=_e(e);if(!n)return null;switch(n.toLowerCase()){case"checkout":return Et(qE(r,t));case"switch":return Et(ZE(r));case"restore":return Et(JE(r));case"reset":return ex(r);case"clean":return Et(nx(r));case"rm":return Et(rx(r));case"push":return jt(ox(r));case"branch":return jt(ax(r));case"stash":return jt(fx(r));case"worktree":return jt(mx(r));case"rebase":return Et(lx(r));case"merge":return Et(cx(r));case"tag":return jt(ux(r));case"reflog":return jt(dx(r));default:return null}}function Et(e){return e?{...e,localDiscard:!0}:null}function jt(e){return e?{...e,localDiscard:!1}:null}function qE(e,t){let{index:n,before:r}=oe(e),o=fe(r,{shortOptsWithValue:Ra});if(r.some((a)=>O(a,"--force"))||o.has("-f"))return v("git.checkout-force",EE);for(let a of e){if(a==="-b"||a==="-B"||a==="--orphan")return null;if(O(a,"--pathspec-from-file"))return v("git.checkout-pathspec-from-file",RE)}if(n!==-1){if(r.some((l)=>!l.startsWith("-")))return v("git.checkout-ref-path",xE);return v("git.checkout-double-dash",SE)}let i=XE(e);if(i.length>=2)return v("git.checkout-ambiguous",_E);let s=i[0];if(s===void 0||o.has("-d")||o.has("-t")||e.some((a)=>O(a,"--detach")||O(a,"--track")))return null;if(YE(s)||t(s))return v("git.checkout-double-dash",vE);return null}function YE(e){return e==="."||e===".."||/^\.\.?[/\\]/.test(e)||/^([/\\]|[A-Za-z]:[/\\])/.test(e)||e.endsWith("/")||e.startsWith(":")||/[*?[]/.test(e)}function ZE(e){let{before:t}=oe(e);if(t.some((r)=>O(r,"--discard-changes")))return v("git.switch-discard-changes",wE);let n=fe(t,{shortOptsWithValue:_a});if(t.some((r)=>O(r,"--force"))||n.has("-f"))return v("git.switch-force",AE);return null}function XE(e){let t=[],n=0;while(n<e.length){let r=e[n];if(!r)break;if(r==="--")break;if(!r.startsWith("-")){t.push(r),n++;continue}if(jE.has(r)){n+=2;continue}if(VE.has(r)){let o=e[n+1],i=r==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"];n+=o&&!o.startsWith("-")&&i.includes(o)?2:1;continue}n++}return t}function JE(e){let t=QE(e);if(t.isTerminal||!t.hasPathspec&&!t.hasPatch||!t.hasWorktree)return null;return t.hasExplicitLocation?v("git.restore-worktree",IE):v("git.restore-unstaged",PE)}function QE(e){let t=!1,n=!1,r=!0,o=!1,i=(s)=>{if(!o)r=!1,o=!0;if(s!==void 0)r=s};for(let s=0;s<e.length;s++){let a=e[s];if(a===void 0)break;if(a==="--"){t||=s+1<e.length;break}if(a==="--pathspec-from-file"){t=!0,s++;continue}if(a.startsWith("--pathspec-from-file=")){t=!0;continue}if(a==="-h"||a==="--help"||a==="--version")return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!0};if(a==="--staged"){i();continue}if(a==="--no-staged"){i();continue}if(a==="--worktree"){i(!0);continue}if(a==="--no-worktree"){i(!1);continue}if(a==="--patch"){n=!0;continue}if(a==="--no-patch"){n=!1;continue}if(KE.has(a)){s++;continue}if(a.startsWith("--"))continue;if(a==="-"){t=!0;continue}if(!a.startsWith("-")){t=!0;continue}for(let l=1;l<a.length;l++){let c=a.charAt(l);if(c==="h")return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!0};if(c==="S"){i();continue}if(c==="W"){i(!0);continue}if(c==="p"){n=!0;continue}if(c==="s"||c==="U"){if(l===a.length-1)s++;break}}}return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!1}}function ex(e){let t=null;for(let n of e){if(O(n,"--hard")){t=v("git.reset-hard",TE);break}if(O(n,"--merge")){t=v("git.reset-merge",kE);break}}if(!t)return null;return tx(e)?jt(t):Et(t)}function tx(e){for(let t of e){if(t==="--")return!1;if(!t.startsWith("-"))return!0}return!1}function nx(e){for(let n of e)if(n==="-n"||O(n,"--dry-run"))return null;let t=fe(e.filter((n)=>n!=="--"));if(e.some((n)=>O(n,"--force"))||t.has("-f"))return v("git.clean-force",OE);return null}function rx(e){let t=!1,n=!1,r=!1;for(let o of oe(e).before){if(O(o,"--no-force")){t=!1;continue}if(O(o,"--force")){t=!0;continue}if(O(o,"--no-cached")){n=!1;continue}if(O(o,"--cached")){n=!0;continue}if(O(o,"--no-dry-run")){r=!1;continue}if(O(o,"--dry-run")){r=!0;continue}let i=fe([o]);t||=i.has("-f"),r||=i.has("-n")}return t&&!n&&!r?v("git.rm-force",ME):null}function ox(e){let{before:t,after:n}=oe(e),r=fe(t);if(t.some((s)=>O(s,"--mirror")))return v("git.push-mirror",LE);if(t.some((s)=>O(s,"--force"))||r.has("-f")||gf(t,n).some(ix))return v("git.push-force",DE);if(t.some((s)=>O(s,"--delete"))||r.has("-d")||gf(t,n).some(sx))return v("git.push-delete",NE);return null}function gf(e,t){return[...e.filter((n)=>n!==""&&!n.startsWith("-")),...t]}function ix(e){return e.startsWith("+")||e.includes(":+")}function sx(e){return e.length>1&&e.startsWith(":")}function ax(e){let{before:t}=oe(e),n=fe(t),r=n.has("-D")||n.has("-d")||t.some((i)=>O(i,"--delete")),o=n.has("-D")||n.has("-f")||t.some((i)=>O(i,"--force"));if(r&&o)return v("git.branch-force-delete",WE);return null}function lx(e){let{before:t}=oe(e);return t.some((n)=>O(n,"--abort"))?v("git.rebase-abort",GE):null}function cx(e){let{before:t}=oe(e);return t.some((n)=>O(n,"--abort"))?v("git.merge-abort",FE):null}function ux(e){let{before:t}=oe(e);return fe(t).has("-d")||t.some((r)=>O(r,"--delete"))?v("git.tag-delete",zE):null}function dx(e){return e[0]==="delete"?v("git.reflog-delete",BE):null}function fx(e){for(let t of e){if(t==="drop")return v("git.stash-drop",$E);if(t==="clear")return v("git.stash-clear",UE)}return null}function mx(e){let{before:t}=oe(e);if(!t.includes("remove"))return null;let r=fe(t);if(t.some((o)=>O(o,"--force"))||r.has("-f"))return v("git.worktree-remove-force",HE);return null}import{dirname as Dx,isAbsolute as Nx,join as kf,resolve as Lx}from"node:path";var Aa="TMPDIR",Pa="IFS",Cf=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,bf=/^[A-Za-z_][A-Za-z0-9_]*$/,Sf=new Set(["export","typeset","declare","readonly"]),px=new Set(["builtin","command","time"]),gx=new Set(["do","then","else"]),hx=new Set(["do","then","case"]),yf=new Set(["done","fi","esac"]),yx=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function vf(e,t){return e.map((n)=>n.provenance==="variable"&&Pf(n.text)?Ef(n.text,t.shellAssignments):_(n))}function Ef(e,t){return e.replace(yx,(n,r,o)=>t.get(r??o??"")??n)}function qe(e,t){let n=e.parts.every((o)=>o.provenance!=="literal"||!/[$`]/.test(o.raw));if(e.provenance!=="variable"||!n)return null;let r=Ef(e.text,t);return/^[~-]/.test(r)||/[\s$`*?[]/.test(r)?null:r}function xf(e,t){return{env:e,effectiveEnvAssignments:vx(e,t),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function Rf(e){return{env:e.env,effectiveEnvAssignments:e.effectiveEnvAssignments?new Map(e.effectiveEnvAssignments):void 0,shellAssignments:new Map(e.shellAssignments),bodyDepth:e.bodyDepth,bodyAssignments:new Set(e.bodyAssignments)}}function Ia(e,t){let n=wf(e,t),r=e[0]??"";if(hx.has(r))t.bodyDepth+=1;if(r==="elif"||yf.has(r))t.bodyDepth=Math.max(0,t.bodyDepth-1);if(yf.has(r)&&t.bodyDepth===0)t.bodyAssignments.forEach((a)=>{t.shellAssignments.delete(a)}),t.bodyAssignments.clear();n.assignments.filter((a)=>a.persists).forEach((a)=>{if(t.shellAssignments.set(a.name,a.value),t.bodyDepth>0)t.bodyAssignments.add(a.name);Ta(t,a)});let o=n.commandIndex;if(o!==-1&&Sf.has(e[o]??""))e.filter((a)=>bf.test(a)&&wa(a)).forEach((a)=>{Ex(t,a)});let i=o===-1?-1:Af(e,o);if(i===-1||e[i]!=="unset")return;let s=Rx(e,i);if(s===null)return;e.slice(s).forEach((a)=>{if(t.bodyDepth>0){t.shellAssignments.set(a,"");return}xx(t,a)})}function _f(e,t){let n=wf(e,t).assignments;if(n.length===0)return t.effectiveEnvAssignments;let r=new Map(t.effectiveEnvAssignments??[]);return n.forEach((o)=>{r.set(o.name,o.value)}),r}function wf(e,t){let n=gx.has(e[0]??"")?1:0,r=e.findIndex((a,l)=>l>=n&&!Pf(a)),o=r!==-1&&Sf.has(e[Af(e,r)]??""),i=Sx(t);return{assignments:e.flatMap((a,l)=>{let c=Cx(a,i,t.env);if(!c)return[];if(r!==-1&&l>r&&!o&&!Ro(c.name))return[];return i.set(c.name,c.value),[{...c,persists:r===-1||o}]}),commandIndex:r}}function Af(e,t){let n=t;while(px.has(e[n]??"")){n+=1;while(e[n]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(e[n]??""))return t;n+=1}}return n}function Pf(e){return Ie(e)!==null||Cf.test(e)}function Cx(e,t,n){return Ie(e)??bx(e,t,n)}function bx(e,t,n){let r=_o(e,n,t);if(r)return r;let o=e.match(Cf)?.[1];if(!o)return null;let i=e.indexOf("=");return{name:o,value:`${t.has(o)?t.get(o):n.get(o)??""}${e.slice(i+1)}`}}function wa(e){return e===Aa||e===Pa||Qs(e)}function Sx(e){return new Map([...e.effectiveEnvAssignments??[],...e.shellAssignments])}function vx(e,t){let n=[Aa,Pa].map((r)=>{let o=e.get(r);return o===void 0?null:[r,o]}).filter((r)=>r!==null);if(n.length===0)return t;return new Map([...n,...t??[]])}function Ta(e,t){let n=new Map(e.effectiveEnvAssignments??[]);n.set(t.name,t.value),e.effectiveEnvAssignments=n}function Ex(e,t){Ta(e,{name:t,value:e.shellAssignments.get(t)??e.effectiveEnvAssignments?.get(t)??e.env.get(t)??""})}function xx(e,t){if(!wa(t)&&!bf.test(t))return;if(e.shellAssignments.set(t,""),Ro(t)&&e.env.has(t)){let r=new Map(e.env);r.delete(t),e.env=r}if(!wa(t)||t===Aa||t===Pa||Un(t)){Ta(e,{name:t,value:""});return}if(!e.effectiveEnvAssignments?.has(t))return;let n=new Map(e.effectiveEnvAssignments);n.delete(t),e.effectiveEnvAssignments=n.size===0?void 0:n}function Rx(e,t){let n=t+1;while(n<e.length){let r=e[n];if(!r)return null;if(r==="--")return n+1;if(r==="-v"){n++;continue}if(r.startsWith("-"))return null;return n}return n}import{resolve as _x}from"node:path";function qo(e,t){return Js.some((n)=>t?.has(n)||e.has(n))}function xn(e,t,n){if(!t)return{gitCwd:null,hasExplicitGitContext:!1};let r=n.realpath(_x(t));if(r===null||!n.isDirectory(r))return{gitCwd:null,hasExplicitGitContext:!1};let o=r,i=!1,s=1;while(s<e.length){let a=e[s];if(!a)break;if(a==="--")break;if(!a.startsWith("-"))break;if(a==="-C"){let l=e[s+1];if(!l)return{gitCwd:null,hasExplicitGitContext:i};let c=If(o,l,n);if(!c)return{gitCwd:null,hasExplicitGitContext:i};o=c,s+=2;continue}if(a.startsWith("-C")&&a.length>2){let l=If(o,a.slice(2),n);if(!l)return{gitCwd:null,hasExplicitGitContext:i};o=l,s++;continue}if(a==="--git-dir"||a==="--work-tree"){i=!0,s+=2;continue}if(a.startsWith("--git-dir=")||a.startsWith("--work-tree=")){i=!0,s++;continue}s+=ve.has(a)?2:1}return{gitCwd:o,hasExplicitGitContext:i}}function If(e,t,n){try{let r=yt(e,t,n);return n.isDirectory(r)?r:null}catch{return null}}function Tf(e,t,n){if(!t.localDiscard||!n.worktreeMode||qo(n.environment.env,n.envAssignments))return null;let r=xn(e,n.cwd,n.environment.paths);if(!r.gitCwd||r.hasExplicitGitContext)return null;let o=n.environment.worktreeFacts(r.gitCwd);if(!o)return null;if(ka(e,n,o))return null;return{kind:"worktree",originalReason:t.reason,gitCwd:r.gitCwd}}function ka(e,t,n){let{subcommand:r,rest:o}=_e(e),i=r?.toLowerCase();if(t.dynamicArguments||wx(o)||kx(e,t.environment.env,t.envAssignments,n)||Ix(o)||Ax(i,o))return!0;return i==="clean"&&Tx(o)>1}function wx(e){return e.some((t)=>/[$*?[]/.test(t))}function Ax(e,t){if(e==="checkout"){let{before:n}=oe(t),r=fe(n,{shortOptsWithValue:Ra}),o=n.some((s)=>O(s,"--force"))||r.has("-f"),i=r.has("-B")||n.some((s)=>s==="-B"||s.startsWith("-B"));return o&&i}if(e==="switch"){let{before:n}=oe(t),r=fe(n,{shortOptsWithValue:_a}),o=n.some((s)=>O(s,"--force"))||n.some((s)=>O(s,"--discard-changes"))||r.has("-f"),i=n.some((s)=>s==="-C"||s.startsWith("-C")||Px(s))||r.has("-C");return o&&i}return!1}function Px(e){let t=e.split("=",1)[0]??e;return t==="--force-create"||t.length>=9&&"--force-create".startsWith(t)}function Ix(e){return e.some((t)=>t.startsWith("--recurse-sub"))}function Tx(e){let t=0;for(let n of e){if(n==="--force"){t++;continue}if(n.startsWith("-")&&!n.startsWith("--")){for(let r of n.slice(1))if(r==="f")t++}}return t}function kx(e,t,n,r){if(rt("GIT_CONFIG_PARAMETERS",t,n)!==void 0)return!0;let o=Ko(e,t,n);if(o.blockedReason!==null)return!0;let i=o.entries.map((a)=>({key:a.key.toLowerCase(),value:a.value}));if(i.some((a)=>Mx(a.key)))return!0;let s=i.filter((a)=>a.key==="submodule.recurse").at(-1);if(s)return s.value===void 0||Ox(s.value);if(id(n))return!0;return r.recursiveSubmodules}function Ox(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function Mx(e){return e==="include.path"||e.startsWith("includeif.")&&e.endsWith(".path")}function Of(e,t,n){let r=e.map((l)=>qe(l,n.shellAssignments??new Map)??_(l)),o=n.environment.paths,i=xn(r,n.cwd,o),s=n.originalCwd?o.realpath(Lx(n.originalCwd)):null;if(t.id.startsWith("git.push-")||s===null||i.gitCwd===null||i.hasExplicitGitContext||qo(n.environment.env,n.envAssignments))return null;let a=t.id==="git.worktree-remove-force"?Gx(e,n.shellAssignments,o):Mf(i.gitCwd,o);if(a===null||t.id!=="git.worktree-remove-force"&&!Wx(a,r,t,n)||!Cn(a,n.environment)||Go(a,n.environment)||bn(s,a)||bn(a,s))return null;return{kind:"temp-root",originalReason:t.reason,gitCwd:i.gitCwd}}function Wx(e,t,n,r){let o=r.environment.paths,i=kf(e,".git");if(o.entryKind(i)!=="present")return!1;if(o.isDirectory(i))return!0;if(!n.localDiscard)return!1;let a=r.environment.worktreeFacts(e);return a!==null&&!ka(t,r,a)}function Gx(e,t,n){let r=_e(e.map(_)).rest,{before:o,after:i}=oe(r.slice(r.indexOf("remove")+1)),s=[...o.filter((u)=>!u.startsWith("-")),...i],a=s.length===1?s[0]??"":"",l=e.find((u)=>u.text===a),c=(l&&qe(l,t??new Map))??a;if(!Nx(c)||/[\s$`*?[]/.test(c)||n.entryKind(c)!=="present"||!n.isDirectory(c))return null;return n.realpath(c)}function Mf(e,t){if(t.entryKind(kf(e,".git"))!=="missing")return e;let n=Dx(e);return n===e?null:Mf(n,t)}var zx="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.",Bx=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function Yo(e,t){return Df(e,t)}function Df(e,t,n){let r=e.map(_),o=mf(r,t.environment.env,t.envAssignments),i=o.blockedReason?w(v("git.alias-config",o.blockedReason),t.policy):null;if(i)return i;let s=o.tokens;if((od(t.envAssignments)||pf(r,t.environment.env,t.envAssignments))&&$x(s))return v("git.ssh-env",zx);let a=hf(s,(c)=>{let u=xn(r,t.cwd,t.environment.paths).gitCwd;return u!==null&&t.environment.paths.entryKind(Fx(u,c))!=="missing"});if(!a)return null;if(o.expanded||o.blockedReason)return a;let l=Tf(r,a,t)??Of(e,a,t);if(!l)return a;return n?.(l),null}function Nf(e,t){let n=null;return{match:Df(e,t,(o)=>{n=o}),relaxation:n}}function $x(e){let{subcommand:t,rest:n}=_e(e),r=t?.toLowerCase();if(!r)return!1;if(Bx.has(r))return!0;if(r==="archive")return oe(n).before.some((o)=>O(o,"--remote"));return r==="remote"&&Ux(n)}function Ux(e){return e.find((t)=>!Hx(t))?.toLowerCase()==="update"}function Hx(e){return e==="-v"||O(e,"--verbose")||O(e,"--no-verbose")}import{isAbsolute as SR}from"node:path";function Lf(e,t,n,r){let o=e.slice(0,t),i=e.slice(t+n);return r.startsWith(o)&&r.endsWith(i)?r.slice(o.length,r.length-i.length):null}function Zo(e,t,n){let r=(i)=>`${i.tokenIndex}\x00${i.kind}\x00${i.value}`,o=new Set(e.map(r));return Array.from(t).some((i)=>n(i).some((s)=>!o.has(r(s))))}var Wf="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",jx="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.",Vx="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",Kx="rm -rf targeting root or home directory is extremely dangerous and always blocked.",qx="rm -rf in home directory is dangerous. Change to a project directory first.",Gf={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:Kx},git_metadata_target:{id:"rm.git-metadata",reason:Ge},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:Vx},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:qx},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:Wf},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:jx},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:Wf}};function Xo(e,t){let n=vt({...t,allowPaths:t.policy?.destructiveCommandAllowPaths,posixShell:!0}),r=e.map(_),o=jo(r),i=Zx(e);for(let s of i){let a=pr(s.word);if(o&&a.unsafeBraceExpansion){let l=w(mr({kind:"outside_anchored_cwd"},n,t.policy,Gf),t.policy);if(l)return l;continue}for(let l of a.expandedTargets??[s.text]){let c=Se(l),u={targetIsLiteral:a.expandedTargets!==void 0||a.targetIsLiteral,tmpdirWordSplittingProtected:a.tmpdirWordSplittingProtected};if(!o&&n.resolvedCwd&&zt(c,n.resolvedCwd,n.protectedGitMetadata,o,n.environment,n.budget))return v("rm.git-metadata",Ge);if(!o)continue;for(let f of Yx(c,n,u)){let d=mr(f,n,t.policy,Gf),m=w(d,t.policy);if(m)return m}}}return null}function Yx(e,t,n){let r=Fe(e,t,n);if(r.kind==="cwd_self_target")return[r,Fe(e,t,{...n,skipCwdSelf:!0})];if(r.kind!=="home_cwd_target")return[r];let o=Fe(e,t,{...n,skipHomeCwd:!0});if(o.kind!=="cwd_self_target")return[r,o];return[r,o,Fe(e,t,{...n,skipHomeCwd:!0,skipCwdSelf:!0})]}function Zx(e){let t=[],n=!1;for(let r of e.slice(1)){let o=_(r);if(!o)continue;if(o==="--"){n=!0;continue}if(n){t.push({text:o,word:r});continue}if(!o.startsWith("-"))t.push({text:o,word:r})}return t}var xt={kind:"none"},Vt={kind:"dynamic"},Xx=new Set(["<","<<","<<-","<<<","<&","<>"]),zf=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,Jx=/^(?:[0-9]+|[@*])$/,Qx=ht.maxWords,Bf=ht.maxInputLength;function $f(e){if(!e||A(k(e.words[0]?.text??""))!=="printf")return;if(e.words.some((o)=>o.provenance!=="literal"))return;let t=e.words.slice(e.words[1]?.text==="--"?2:1),n=t[0]?.text;if(n===void 0)return"";let r=t.slice(1).map((o)=>o.text);if(n==="%s")return r.join("");if(n==="%s\\n"||n===`%s
13
+ `?d+2:d+1,T=a.at(-1);if(T?.kind!=="connector"||!Au.has(T.operator))a.push(Object.freeze({kind:"connector",operator:e.slice(d,I),span:Object.freeze({start:d,end:I})}));if(u.length>0){let k=Ws(e,I,n,u.splice(0));l.push(...k.issues),d=k.next;continue}d=I;continue}d++;continue}if(m==="#"){while(d<n&&e[d]!==`
14
+ `&&e[d]!=="\r")d++;continue}let g=c.start===-1?Bb(e,d,n):void 0;if(g){if(Fs(a,l),i>=r.maxDepth)return pn(a,l,d,"depth-limit",r.maxDepth);if(!Gs(o))return pn(a,l,d,"word-limit",r.maxWords);let I=yo(e,g.braceIndex+1,n,r,o,i+1,"}"),T=I.next,k={start:g.braceIndex+1,end:I.closed?T-1:T},F=Ru(e,k,I);if(a.push({kind:"function",name:g.name,span:{start:d,end:T},body:F}),l.push(...I.issues),I.pendingHeredocs.length>0||or(I.nodes))l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(u.push(...I.pendingHeredocs),I.limited)return ho(a,l,I.next);if(!I.closed)l.push({code:"unclosed-function-body",message:"function body is not closed"});d=T;continue}let p=bo(e,d);if(p){if(f(),!Fu(a.at(-1)))l.push({code:"unexpected-connector",message:`connector ${p} has no preceding command`});a.push(Object.freeze({kind:"connector",operator:p,span:Object.freeze({start:d,end:d+p.length})})),d+=p.length;continue}if(m===")"){f(),l.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),a.push({kind:"unknown",source:m,span:{start:d,end:d+1}}),d++;continue}if((m==="("||m==="{"&&Ab(e,d,n))&&c.start===-1){if(Fs(a,l),i>=r.maxDepth)return pn(a,l,d,"depth-limit",r.maxDepth);let I=m==="("?")":"}",T=yo(e,d+1,n,r,o,i+1,I),k=T.next,F={start:d+1,end:T.closed?k-1:k},ue=Ru(e,F,T);if(a.push({kind:"group",style:m==="("?"subshell":"brace",span:{start:d,end:k},body:ue}),l.push(...T.issues),T.pendingHeredocs.length>0||or(T.nodes))l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(u.push(...T.pendingHeredocs),T.limited)return ho(a,l,T.next);if(!T.closed)l.push({code:m==="("?"unclosed-subshell":"unclosed-brace-group",message:`${m} group is not closed`});d=k;continue}let h=(m==="<"||m===">")&&e[d+1]!=="("?bb(e,d):null;if(h){let I=c.words.at(-1),T=I&&I.span.end===d&&/^[0-9]+$/.test(I.raw)?Number(I.raw):void 0;if(T!==void 0)c.words.pop();let k=T===void 0?d:I?.span.start??d;c.start=c.start===-1?d:c.start;let F=d+h.length;while(F<n&&/[ \t]/.test(e[F]??""))F++;let ue=e[F],Xe=F>d+h.length&&ue==="#",Ce=!ue||rr(ue)||!!bo(e,F)||ue===s||ue===")"||Xe||(ue==="<"||ue===">")&&e[F+1]!=="(",Tt=h==="<<"||h==="<<-",U=Tt?Ls(e,F,n):void 0,L=U?{word:mn(e,F,U.next,U.delimiter,"literal",U.quoted),nested:[],issues:[],next:U.next,limited:!1}:!Ce?zs(e,F,n,r,o,i):void 0;if(L){if(l.push(...L.issues),L.limited)return ho(a,l,L.next);if(!Gs(o))return pn(a,l,L.next,"word-limit",r.maxWords)}let ae=L?.next??d+h.length,J={kind:"redirection",operator:h,span:{start:k,end:ae},...T===void 0?{}:{fd:T},...L?{target:L.word}:{}};if(c.redirections.push(J),Tt&&!U)l.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if(U){if(U.ambiguous||U.delimiter.length===0)l.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let Q=c.nested;u.push({delimiter:U.delimiter,quotedDelimiter:U.quoted,stripTabs:h==="<<-",attach:(Se)=>{if(J.heredoc=Se,Se.quotedDelimiter)return;let ft=hb(e,Se.bodySpan.start,Se.bodySpan.end,r,o,i+1);Q.push(...ft.programs),l.push(...ft.issues)}})}if(!Tt&&!L)l.push({code:"missing-redirection-target",message:`redirection ${h} requires a target word`});if(L)c.nested.push(...L.nested);c.end=ae,d=ae;continue}let y=c.start===-1;if(y)Fs(a,l);let C=zs(e,d,n,r,o,i);if(l.push(...C.issues),C.limited)return ho(a,l,C.next);let b=kb(c.words)?Lb(e,C.word,o.maxWords-o.wordsUsed,r.maxDepth,r.maxInputLength):void 0;if(b?.limitCode)return pn(a,l,C.next,b.limitCode,b.limitCode==="word-limit"?r.maxWords:b.limitCode==="depth-limit"?r.maxDepth:r.maxInputLength);let E=b?.words??[C.word];for(let I of E){if(!Gs(o))return pn(a,l,C.next,"word-limit",r.maxWords);c.words.push(I)}if(c.start=c.start===-1?d:c.start,c.end=C.next,c.nested.push(...C.nested),y&&zu(C.word))f();d=C.next>d?C.next:d+1}return f(),Pu(a,l),l.push(...$b(u)),{nodes:a,issues:l,next:d,closed:s===void 0,limited:!1,pendingHeredocs:[]}}function Ru(e,t,n){return{kind:"program",dialect:"posix",source:e.slice(t.start,t.end),span:t,status:Co(n.issues,n.limited),issues:n.issues,nodes:n.nodes}}function zs(e,t,n,r,o,i){let s="",a=t,l=!1,c="literal",u=[],f=[],d=!1;while(a<n){let m=e[a],g=(m==="<"||m===">")&&e[a+1]==="(";if(!m||rr(m)||(m===";"||m==="|"||m==="&")&&bo(e,a)||(m==="<"||m===">")&&!g)break;if(m===")")break;if(m==="'"){l=!0;let y=e.indexOf("'",a+1);if(y===-1||y>=n){s+=e.slice(a+1,n),f.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),a=n;break}s+=e.slice(a+1,y),a=y+1;continue}if(m==='"'){l=!0;let y=gb(e,a,n,r,o,i);if(s+=y.text,u.push(...y.nested),f.push(...y.issues),d||=y.limited,c=nr(c,y.provenance),a=y.next,d)break;continue}if(e.startsWith("$'",a)){l=!0;let y=_b(e,a+2,n);if(s+=y.text,f.push(...y.issues),!y.closed)f.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});a=y.next;continue}if(m==="\\"){let y=e[a+1];if(!y){f.push({code:"trailing-escape",message:"escape has no following character"}),a++;break}if(y===`
15
+ `){a+=2;continue}s+=y,a+=2;continue}if(zt(e,a))f.push(Ft);let p=m==="$"||m==="<"||m===">"||m==="`"?ir(e,a,n,r,o,i):null,h=p?$s(p,u,f):Mu(e,a,n,r,o,i,u,f);if(h){if(h.provenance==="variable")s+=e.slice(a,h.next);if(d||=h.limited,c=nr(c,h.provenance),a=h.next,d)break;continue}if(m==="$"){let y=Nu(e,a,n,s,c);s=y.text,c=y.provenance,a=y.next;continue}if(m==="*"||m==="?"||m==="[")c=nr(c,"glob");s+=m,a++}return{word:mn(e,t,a,s,c,l,c==="literal"?void 0:Pb(e,t,a)),nested:u,issues:f,next:a,limited:d}}function gb(e,t,n,r,o,i){let s="",a="literal",l=[],c=[],u=!1,f=t+1;while(f<n){let d=e[f];if(d==='"')return{text:s,provenance:a,nested:l,issues:c,next:f+1,limited:u};if(d==="\\"&&e[f+1]){let p=e[f+1]??"";if(p===`
16
+ `){f+=2;continue}if(p==="\r"&&e[f+2]===`
17
+ `){f+=3;continue}s+=["$","`",'"',"\\"].includes(p)?p:`\\${p}`,f+=2;continue}if(zt(e,f))c.push(Ft);let m=ir(e,f,n,r,o,i),g=m?$s(m,l,c):Mu(e,f,n,r,o,i,l,c);if(g){if(g.provenance!=="command-substitution")s+=e.slice(f,g.next);if(f=g.next,u||=g.limited,a=nr(a,g.provenance),u)return{text:s,provenance:a,nested:l,issues:c,next:f,limited:u};continue}if(d==="$"){let p=Nu(e,f,n,s,a);s=p.text,a=p.provenance,f=p.next;continue}s+=d??"",f++}return c.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:s,provenance:a,nested:l,issues:c,next:n,limited:u}}function ir(e,t,n,r,o,i){let s=ku(e,t);if(!s)return null;let{length:a,closing:l}=s,c=l==="))",u=l==="`",f=e[t]==="<"||e[t]===">",d=Us(e,t+a,n,l),m=d===-1?n:d,g=d===-1?n:d+l.length;if(i>=r.maxDepth)return{program:zb(e,t+a,m,"depth-limit"),next:g,provenance:c?"arithmetic":"command-substitution"};if(c){let E=[],I=[],T=!1,k=t+a;while(k<m){let F=ir(e,k,m,r,o,i+1);if(!F){if(zt(e,k))I.push(Ft);k++;continue}if(E.push(...F.program.nodes),I.push(...F.program.issues),T||=F.program.status==="limited",k=F.next,T)break}if(d===-1)I.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:me({kind:"program",dialect:"posix",source:e.slice(t+a,m),span:{start:t+a,end:m},status:Co(I,T),issues:I,nodes:E}),next:g,provenance:"arithmetic"}}let p=yo(e,t+a,m,r,o,i+1),h=d===-1?[{code:"unclosed-command-substitution",message:`${e.slice(t,t+a)} substitution is not closed`}]:[],y=(u||f)&&or(p.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[],C=u&&/\\[\\$`\n]/.test(e.slice(t+a,m))?[Rb]:[],b=[...p.issues,...h,...y,...C];return{program:me({kind:"program",dialect:"posix",source:e.slice(t+a,m),span:{start:t+a,end:m},status:Co(b,p.limited),issues:b,nodes:p.nodes}),next:g,provenance:"command-substitution"}}function hb(e,t,n,r,o,i){let s=[],a=[],l=t;while(l<n){let c=e[l];if(c==="\\"){l+=2;continue}let u=c==="$"||c==="`"?ir(e,l,n,r,o,i):null;if(!u){if(zt(e,l))a.push(Ft);l++;continue}if(s.push(u.program),Cb(e,l,u.next)&&Sb(u.program))a.push(Ft);l=u.next}return{programs:s,issues:a}}function $s(e,t,n){return t.push(e.program),n.push(...e.program.issues),{provenance:e.provenance,next:e.next,limited:e.program.status==="limited"}}function Us(e,t,n,r){if(r==="`"){for(let a=t;a<n;a++){if(e[a]==="\\"){a++;continue}if(e[a]==="`")return a}return-1}let o={single:!1,double:!1},i=[],s=[];for(let a=t;a<n;a++){let l=e[a];if((l===`
18
+ `||l==="\r")&&s.length>0){let f=l==="\r"&&e[a+1]===`
19
+ `?a+2:a+1,d=Ws(e,f,n,s.splice(0));if(!d.terminated)return-1;a=d.next-1;continue}let c=Tu(e,a,t,n,o);if(c!==null){a=c;continue}if(!o.double&&e.startsWith("$((",a)){let f=yb(e,a+3,n);if(f===-1)return-1;a=f+1;continue}if(r===")"&&!o.double&&l==="<"&&e[a+1]==="<"&&e[a+2]!=="<"){let f=e[a+2]==="-",d=a+(f?3:2);while(d<n&&/[ \t]/.test(e[d]??""))d++;let m=Ls(e,d,n);if(m){s.push({delimiter:m.delimiter,quotedDelimiter:m.quoted,stripTabs:f,attach:()=>{return}}),a=m.next-1;continue}}if(e.startsWith("$(",a)&&!e.startsWith("$((",a)){i.push(o),o={single:!1,double:!1},a++;continue}if(l==="("&&!o.double){i.push(o),o={single:!1,double:!1};continue}if(l!==")"||o.double)continue;let u=i.pop();if(u){o=u;continue}return r==="))"&&e[a+1]!==")"?-1:a}return-1}function yb(e,t,n){let r=1,o={single:!1,double:!1};for(let i=t;i<n;i++){let s=e[i],a=Tu(e,i,t,n,o);if(a!==null){i=a;continue}if(e.startsWith("$(",i)&&!e.startsWith("$((",i)){r++,i++;continue}if(s==="("&&!o.double)r++;if(s!==")"||o.double)continue;if(r--,r===0)return e[i+1]===")"?i:-1}return-1}function Tu(e,t,n,r,o){let i=e[t];if(i==="\\"&&!o.single)return t+1;if(!o.double&&i==="'")o.single=!o.single;if(!o.single&&i==='"')o.double=!o.double;if(o.single)return t;if(o.double||i!=="#"||!Ub(e,t,n))return null;let s=t;while(s+1<r&&e[s+1]!==`
20
+ `&&e[s+1]!=="\r")s++;return s}function bo(e,t){let n=e[t];if(n===";")return";";if(n==="&")return e[t+1]==="&"?"&&":"&";if(n==="|")return e[t+1]==="|"?"||":e[t+1]==="&"?"|&":"|";return null}function bb(e,t){let n=e[t];if(n===">"){if(e[t+1]===">")return">>";if(e[t+1]==="&")return">&";return e[t+1]==="|"?">|":">"}if(n!=="<")return null;if(e.startsWith("<<<",t))return"<<<";if(e.startsWith("<<-",t))return"<<-";if(e[t+1]==="<")return"<<";if(e[t+1]==="&")return"<&";if(e[t+1]===">")return"<>";return"<"}function rr(e){let t=e.charCodeAt(0);if(t===32||t>=9&&t<=13)return!0;if(t<128)return!1;return/\s/u.test(e)}var Ft=Object.freeze({code:"unsupported-function-substitution",message:"${ list; } function substitutions run in the current shell and cannot be analyzed"});function zt(e,t){if(e[t]!=="$")return!1;let n=_u(e,t+1);if(e[n]!=="{")return!1;let r=e[_u(e,n+1)]??"";return r==="|"||rr(r)}function Cb(e,t,n){for(let r=e.indexOf("$",t);r!==-1&&r<n;r=e.indexOf("$",r+1))if(zt(e,r))return!0;return!1}function Sb(e){return e?.status==="limited"||(e?.issues??[]).some((t)=>t.code===Ft.code)}function _u(e,t){let n=t;while(e.startsWith("\\\n",n)||e.startsWith(`\\\r
21
+ `,n))n+=e[n+1]==="\r"?3:2;return n}function ku(e,t){if(e.startsWith("$((",t))return{length:3,closing:"))"};if(e.startsWith("$(",t)||e.startsWith("<(",t)||e.startsWith(">(",t))return{length:2,closing:")"};return e[t]==="`"?{length:1,closing:"`"}:null}var vb=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"}),Ou=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"}),Eb=/\$\(|`|[<>]\(/g;function xb(e,t,n){let r=Bs(n);return[...e.slice(t).matchAll(Eb)].some((o)=>{let i=t+o.index;return!r.some((s)=>i>=s.start&&i<s.end)})}function Bs(e){return e.flatMap((t)=>{if(t.kind==="command")return[...t.redirections.flatMap((n)=>n.heredoc?[n.heredoc.bodySpan]:[]),...t.nested.flatMap((n)=>Bs(n.nodes))];return t.kind==="group"||t.kind==="function"?Bs(t.body.nodes):[]})}var Rb=Object.freeze({code:"unsupported-backtick-escape",message:"a backslash escape inside backticks changes the command the shell runs and cannot be analyzed"});function Mu(e,t,n,r,o,i,s,a){if(e[t]!=="$"||e[t+1]!=="{")return null;let l=So(e,t+2,n),c=l.close===-1?n:l.close+1;if(l.close===-1)a.push(vb);if(l.quoted&&l.substitutions.length>0||l.continued)a.push(Ou);if(l.quoted)o.quotedExpansionEnd=Math.min(o.quotedExpansionEnd,c);let u=l.substitutions.some((f)=>{if(zt(e,f))return a.push(Ft),!1;let d=ir(e,f,c,r,o,i);return d!==null&&$s(d,s,a).limited});return{provenance:"variable",next:c,limited:u}}function So(e,t,n){let r=[],o=!1,i=!1,s=1,a=t;while(a<n){let l=e[a];if(l==="$"&&zt(e,a))r.push(a);if(l==="\\"||l==="'"||l==='"'){o=!0,i||=l==="\\"&&e[a+1]===`
22
+ `,a+=l==="\\"?2:1;continue}let c=ku(e,a);if(c){r.push(a);let u=Us(e,a+c.length,n,c.closing);if(u===-1)break;a=u+c.closing.length;continue}if(l==="$"&&e[a+1]==="{"){s++,a+=2;continue}if(l==="}"&&--s===0)return{close:a,substitutions:r,quoted:o,continued:i};a++}return{close:-1,substitutions:r,quoted:o,continued:i}}function Du(e,t,n){if(e[t+1]==="{"){let o=So(e,t+2,n).close;return o===-1?n:o+1}if(e[t+1]==="$")return t+2;let r=t+1;while(r<n&&/[A-Za-z0-9_?@#!*-]/.test(e[r]??""))r++;return r===t+1?t+1:r}function _b(e,t,n){let r="",o=[],i=t;while(i<n){let s=e[i];if(s==="'")return{text:r,next:i+1,closed:!0,issues:o};if(s!=="\\"){r+=s??"",i++;continue}let a=wb(e,i+1,n);if(r+=a.text,a.invalidCodePoint!==void 0)o.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${a.invalidCodePoint}`});i=a.next}return{text:r,next:n,closed:!1,issues:o}}function wb(e,t,n){let r=e[t];if(!r||t>=n)return{text:"\\",next:t};let o=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
23
+ `],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(o.has(r))return{text:o.get(r)??r,next:t+1};if(r==="x")return go(e,t+1,n,16,2,t+1);if(r==="u")return go(e,t+1,n,16,4,t+1);if(r==="U")return go(e,t+1,n,16,8,t+1);if(/[0-7]/.test(r))return go(e,t,n,8,3,t+1);return{text:r,next:t+1}}function go(e,t,n,r,o,i){let s=r===16?/[0-9a-fA-F]/:/[0-7]/,a="",l=t;while(l<n&&a.length<o&&s.test(e[l]??""))a+=e[l],l++;if(!a)return{text:e[i-1]??"",next:i};let c=Number.parseInt(a,r);return c>1114111||c>=55296&&c<=57343?{text:"�",next:l,invalidCodePoint:c}:{text:String.fromCodePoint(c),next:l}}function Co(e,t=!1){if(t)return"limited";if(e.some((n)=>n.code==="invalid-ansi-c-code-point"||n.code==="missing-heredoc-delimiter"||n.code==="ambiguous-heredoc-delimiter"||n.code==="unterminated-heredoc"||n.code==="unsupported-heredoc-context"||n.code==="unsupported-function-substitution"||n.code==="unsupported-backtick-escape"||n.code==="unclosed-parameter-expansion"||n.code==="unsupported-parameter-expansion"))return"invalid";return e.length>0?"partial":"complete"}function Nu(e,t,n,r,o){let i=Du(e,t,n);return{text:r+e.slice(t,i),provenance:nr(o,"variable"),next:i}}function Pb(e,t,n){let r=po(e),o=t,i=!1,s=!1,a=t;while(a<n){let l=e[a];if(l==="\\"&&!i){a+=2;continue}if(!s&&l==="'"){i=!i,a++;continue}if(!i&&l==='"'){s=!s,a++;continue}if(i){a++;continue}let c=e.startsWith("$((",a),u=e.startsWith("$(",a)&&!c,f=!s&&(e.startsWith("<(",a)||e.startsWith(">(",a)),d=l==="`";if(c||u||f||d){let m=c?3:d?1:2,g=c?"))":d?"`":")",p=Us(e,a+m,n,g),h=p===-1?n:p+g.length;r.push(o,a,"literal"),r.push(a,h,c?"arithmetic":"command-substitution"),a=h,o=h;continue}if(l==="$"){let m=Du(e,a,n);if(m>a+1){r.push(o,a,"literal"),r.push(a,m,"variable"),a=m,o=m;continue}}if(!s&&(l==="*"||l==="?"||l==="[")){r.push(o,a,"literal"),r.push(a,a+1,"glob"),a++,o=a;continue}a++}return r.push(o,n,"literal"),r.parts}function nr(e,t){if(t==="command-substitution"||e==="command-substitution")return"command-substitution";if(t==="arithmetic"||e==="arithmetic")return"arithmetic";if(t==="variable"||e==="variable")return"variable";if(t==="glob"||e==="glob")return"glob";return e}function Ab(e,t,n){return t+1>=n||rr(e[t+1]??"")||bo(e,t+1)!==null}var Ib=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),Tb=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function kb(e){let t=0;while(t<=e.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]?.text??""))t++;if(t===e.length)return!0;let n=Ob(e,t);if(n===void 0||n===null)return!1;t=n}return!1}function Ob(e,t){let n=e[t]?.text.toLowerCase();if(n==="command")return Mb(e,t);if(n==="env")return Db(e,t);if(n==="sudo")return Nb(e,t);return}function Mb(e,t){if(e[t+1]?.text==="-v")return null;for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(r==="-p"||r==="-v"||r==="-V"||/^-[pvV]+$/.test(r))continue;return n}return e.length}function Db(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(Ib.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-u=")||r.startsWith("--unset=")||r.startsWith("-C")&&r.length>2||r.startsWith("--chdir=")||r.startsWith("-S")&&r.length>2||r.startsWith("--split-string=")||r.startsWith("-P"))continue;if(r.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(r))continue;return n}return e.length}function Nb(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(Tb.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-"))continue;return n}return e.length}function Lu(e,t,n,r){if(e.provenance!=="literal"||!e.raw.includes("{"))return;let o=Wu(e.raw,t,n,r,!0);if(!o)return;if("limited"in o)return{limited:!0};let i=o.values.map((s)=>Gu(s,n));if(i.some((s)=>s===null))return{limited:!0};return{words:[...new Set(i.filter((s)=>s!==null&&s!==""))]}}function Lb(e,t,n,r,o){if(t.provenance!=="literal"||!t.raw.includes("{"))return;let i=Wu(t.raw,n,r,o,!1);if(!i)return;if("limited"in i){if(i.limited==="expansions")return{limitCode:"depth-limit"};return{limitCode:i.limited==="length"?"brace-expansion-limit":"word-limit"}}let s=i.values.map((a)=>Gu(a,r));if(s.some((a)=>a===null))return;return{words:s.filter((a)=>a!==null&&a!=="").map((a)=>mn(e,t.span.start,t.span.end,a,"literal",!1))}}function Wu(e,t,n,r,o){let i=[e],s=e.length,a=0;while(!0){let l=i.findIndex((m)=>wu(m,o));if(l===-1)break;if(++a>n)return{limited:"expansions"};let c=i[l]??"",u=wu(c,o);if(!u||u.kind==="range")return{limited:"expansions"};let f=u.start+c.length-u.end,d=u.alternatives.reduce((m,g)=>m+f+g.length,0);if(s-c.length+d>r)return{limited:"length"};if(i.length-1+u.alternatives.length>t)return{limited:"words"};i.splice(l,1,...Wb(c,u)),s+=d-c.length}return a===0?void 0:{values:i}}function wu(e,t){let n=[],r,o=null,i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(i){i=!1;continue}if(a==="\\"&&o!=="'"){i=!0;continue}if(a===o){o=null;continue}if(o===null&&(a==="'"||a==='"')){o=a;continue}if(o!==null)continue;if(a==="{"){n.push({start:s,commas:[]});continue}if(a===","&&n.length>0){n.at(-1)?.commas.push(s);continue}if(a!=="}"||n.length===0)continue;let l=n.pop();if(!l)continue;let c=l.commas.length>0?{kind:"alternatives",start:l.start,end:s+1,commas:l.commas}:t&&Fb(e.slice(l.start+1,s))?{kind:"range",start:l.start,end:s+1}:void 0;if(c&&(!r||c.start<r.start))r=c}if(!r||r.kind==="range")return r;return{kind:r.kind,start:r.start,end:r.end,alternatives:Gb(e,r)}}function Wb(e,t){return t.alternatives.map((n)=>`${e.slice(0,t.start)}${n}${e.slice(t.end)}`)}function Gb(e,t){let n=[t.start,...t.commas,t.end-1];return n.slice(0,-1).map((r,o)=>e.slice(r+1,n[o+1]))}function Fb(e){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(e)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(e)}function Gu(e,t){let n=`x${e}`,r=zs(n,0,n.length,{maxInputLength:n.length,maxWords:1,maxDepth:t},{wordsUsed:0,maxWords:1,quotedExpansionEnd:1/0},0);if(r.limited||r.issues.length>0||r.next!==n.length||r.word.provenance!=="literal")return null;return r.word.text.slice(1)}function zb(e,t,n,r){return me({kind:"program",dialect:"posix",source:e.slice(t,n),span:{start:t,end:n},status:"limited",issues:[{code:r,message:"command structure exceeds parser limit"}],nodes:[]})}function pn(e,t,n,r,o){return{nodes:e,issues:[...t,{code:r,message:`command structure exceeds parser limit ${o}`}],next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function ho(e,t,n){return{nodes:e,issues:t,next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function Gs(e){return e.wordsUsed++,e.wordsUsed<=e.maxWords}function Bb(e,t,n){let r=e.slice(t,n),o=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(r)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(r),i=o?.[1];if(!o||!i)return;return{name:i,braceIndex:t+o[0].lastIndexOf("{")}}function or(e){return e.some((t)=>{if(t.kind==="command")return t.redirections.some((n)=>n.heredoc)||t.nested.some((n)=>or(n.nodes));return(t.kind==="group"||t.kind==="function")&&or(t.body.nodes)})}function $b(e){return e.map((t)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${t.delimiter} was not found`}))}function Fu(e){return e?.kind==="command"||e?.kind==="group"||e?.kind==="function"}function Pu(e,t){let n=e.at(-1);if(n?.kind!=="connector"||!Au.has(n.operator))return;t.push({code:"missing-command-after-connector",message:`connector ${n.operator} requires a following command`})}function zu(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&pb.has(e.text)}function Fs(e,t){let n=e.at(-1);if(!Fu(n))return;if(n?.kind==="command"&&zu(n.words[0]))return;t.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function Ub(e,t,n){return t===n||/[\s;&|()]/u.test(e[t-1]??"")}var $u=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),Hb=new Set(["gc","cat","type","cp","mv","rm"]),Uu=["-rec","-for","-path","-literalpath","-whatif"],jb=/^\$env:\w/i,Vb=/^(?:\$\{?\w+\}?|~)\\./;function Hu(e,t){let n=e.toLowerCase().replaceAll("`","");if(![...$u].some((o)=>n.includes(o))&&!(n.includes("rm")&&Uu.some((o)=>n.includes(o)))&&!n.includes("<#")&&!Kb(n))return!1;let r=Ks(e,t);if(ju(r))return!1;return r.issues.some((o)=>o.code==="unclosed-block-comment"||o.code==="comment-depth-limit")||Vs(r).some(qb)}function ju(e){return e.nodes.some((t)=>{if(t.kind==="group")return ju(t.body);if(t.kind!=="command")return!1;return t.redirections.some((n)=>n.operator==="<<")})}function Kb(e){if(e.includes("$env:"))return!0;return e.includes("\\")&&(e.includes("$")||e.includes("~"))}function qb(e){let t=e[0]==="&"||e[0]==="."?1:0,n=e[t]?.toLowerCase();if(n&&$u.has(n))return!0;let r=e.slice(t+1);if(n&&Hb.has(n)&&r.some(Yb))return!0;if(n!=="rm")return!1;return r.some((o)=>{let i=o.toLowerCase().split(":",1)[0]??"";return Uu.some((s)=>i.startsWith(s))})}function Yb(e){return jb.test(e)||Vb.test(e)}function Ks(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return me({kind:"program",dialect:"powershell",source:e,span:n,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${t.maxInputLength} UTF-16 code units`}],nodes:[]});let r=qs(e,0,e.length,t,0);return me({kind:"program",dialect:"powershell",source:e,span:n,status:eC(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function qs(e,t,n,r,o,i=!1){let s=[],a=[],l=fo(),c=0,u=!1,f=()=>{if(l.words.length===0&&l.redirections.length===0)return;let m={start:l.start,end:l.end};mo(s,l,{kind:"command",dialect:"powershell",source:e.slice(m.start,m.end),span:m,words:l.words,redirections:l.redirections,nested:l.nested,displayText:l.words.map((g)=>g.text).join(" ")})},d=t;while(d<n){let m=e[d];if(!m)break;if(i&&m==="}")return f(),{nodes:s,issues:a,next:d+1,closed:!0,words:c,limited:u};let g=Qb(e,d,n,r.maxDepth);if(g){if(g.issue)a.push(g.issue);if(g.limited)return f(),{nodes:s,issues:a,next:g.next,closed:!1,words:c,limited:!0};d=g.next;continue}if(/\s/.test(m)){if(m==="\r"||m===`
24
+ `){f();let y=m==="\r"&&e[d+1]===`
25
+ `?d+2:d+1;s.push(Hs(e,d,y)),d=y;continue}d++;continue}let p=qu(e,d);if(p){f(),s.push(Hs(e,d,d+p.length)),d+=p.length;continue}if(m==="{"){if(f(),o>=r.maxDepth)return a.push(Ku(r.maxDepth)),{nodes:s,issues:a,next:n,closed:!1,words:c,limited:!0};let y=qs(e,d+1,n,r,o+1,!0),C=y.closed?y.next-1:y.next,b=me({kind:"program",dialect:"powershell",source:e.slice(d+1,C),span:{start:d+1,end:C},status:y.limited?"limited":y.issues.length>0?"partial":"complete",issues:y.issues,nodes:y.nodes});if(s.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:d,end:y.next}),body:b})),a.push(...y.issues),!y.closed)a.push({code:"unclosed-script-block",message:"PowerShell script block is not closed"});c+=y.words,u||=y.limited,d=y.next;continue}if(m==="}"){f(),s.push(Hs(e,d,d+1)),d++;continue}if(m===">"||m==="<"){l.start=l.start===-1?d:l.start;let y=e[d+1]===m?d+2:d+1,C=y;while(/[ \t]/.test(e[C]??""))C++;let b=C<n?Bu(e,C,n,r,o):void 0,E=b?.next??y;if(l.redirections.push(Object.freeze({kind:"redirection",operator:e.slice(d,y),span:Object.freeze({start:d,end:E}),...b?{target:b.word}:{}})),b)a.push(...b.issues),l.nested.push(...b.nested),c+=b.words,u||=b.limited;l.end=E,d=E;continue}if(m===","){l.start=l.start===-1?d:l.start,l.words.push(Ns({text:",",raw:",",span:{start:d,end:d+1},provenance:"literal",quoted:!1})),l.end=++d;continue}let h=Bu(e,d,n,r,o);if(l.start=l.start===-1?d:l.start,l.end=h.next,l.words.push(h.word),a.push(...h.issues),l.nested.push(...h.nested),c+=1+h.words,u||=h.limited,c>r.maxWords)return a.push({code:"word-limit",message:`command exceeds ${r.maxWords} words`}),f(),{nodes:s,issues:a,next:h.next,closed:!1,words:c,limited:!0};d=h.next>d?h.next:d+1}return f(),{nodes:s,issues:a,next:d,closed:!i,words:c,limited:u}}function Bu(e,t,n,r,o){let i="",s="literal",a=!1,l=[],c=[],u=0,f=!1,d=(g)=>{let p=Zb(e,g,n,r,o);return i+=e.slice(g,p.next),c.push(p.program),l.push(...p.program.issues),u+=js(p.program),f||=p.program.status==="limited",s="command-substitution",p.next},m=t;while(m<n){let g=e[m];if(!g||/\s/.test(g)||qu(e,m)||g===">"||g==="<"||g==="#")break;if(g===",")break;if(g==="`"){let p=e[m+1];if(!p){l.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),m++;break}i+=p,m+=2;continue}if(e.startsWith("$(",m)){m=d(m);continue}if(g==="'"){a=!0,m++;let p=!1;while(m<e.length){if(e[m]==="'"&&e[m+1]==="'"){i+="'",m+=2;continue}if(e[m]==="'"){p=!0,m++;break}i+=e[m]??"",m++}if(!p)l.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(g==='"'){a=!0,m++;let p=!1;while(m<n){let h=e[m];if(h==="`"&&e[m+1]){i+=e[m+1],m+=2;continue}if(h==='"'){p=!0,m++;break}if(e.startsWith("$(",m)){m=d(m);continue}if(h==="$")s=e[m+1]==="("?"command-substitution":"variable";i+=h??"",m++}if(!p)l.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(g==="$")s=e[m+1]==="("?"command-substitution":"variable";if(g==="@"&&m===t)s="variable";i+=g,m++}return{word:mn(e,t,m,i,s,a,s==="literal"?void 0:Xb(e,t,m)),next:m,issues:l,nested:c,words:u,limited:f}}function Zb(e,t,n,r,o){let i=Vu(e,t+2,n),s=i===-1?n:i,a=i===-1?n:i+1;if(o>=r.maxDepth)return{program:me({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:"limited",issues:[Ku(r.maxDepth)],nodes:[]}),next:a};let l=qs(e,t+2,s,r,o+1),c=i===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:me({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:l.limited?"limited":l.issues.length+c.length>0?"partial":"complete",issues:[...l.issues,...c],nodes:l.nodes}),next:a}}function Vu(e,t,n){let r=1,o=!1,i=!1;for(let s=t;s<n;s++){let a=e[s];if(a==="`"){s++;continue}if(!i&&a==="'"){if(o&&e[s+1]==="'"){s++;continue}o=!o;continue}if(!o&&a==='"'){i=!i;continue}if(o)continue;if(e.startsWith("$(",s)){r++,s++;continue}if(!i&&a==="(")r++;if(a!==")")continue;if(r--,r===0)return s}return-1}function js(e){let t=0;for(let n of e.nodes){if(n.kind==="group")t+=js(n.body);if(n.kind==="command"){t+=n.words.length;for(let r of n.nested)t+=js(r)}}return t}function Xb(e,t,n){let r=po(e),o=t,i=!1,s=t;while(s<n){let a=e[s];if(a==="`"){s+=2;continue}if(a==="'"){if(i&&e[s+1]==="'"){s+=2;continue}i=!i,s++;continue}if(i){s++;continue}if(e.startsWith("$(",s)){let l=Vu(e,s+2,n),c=l===-1?n:l+1;r.push(o,s,"literal"),r.push(s,c,"command-substitution"),s=c,o=c;continue}if(a==="$"||a==="@"&&s===t){let l=Jb(e,s+1,n);r.push(o,s,"literal"),r.push(s,l,"variable"),s=l,o=l;continue}s++}return r.push(o,n,"literal"),r.parts}function Jb(e,t,n){if(e[t]==="{"){let o=e.indexOf("}",t+1);return o===-1||o>=n?n:o+1}let r=t;while(r<n&&/[A-Za-z0-9_:?]/.test(e[r]??""))r++;return r}function Ku(e){return{code:"depth-limit",message:`command structure exceeds parser limit ${e}`}}function Vs(e){return e.nodes.flatMap((t)=>{if(t.kind==="group")return Vs(t.body);if(t.kind!=="command")return[];return[[...t.words,...t.redirections.flatMap((n)=>n.target?[n.target]:[])].sort((n,r)=>n.span.start-r.span.start).filter((n)=>n.text!==""&&n.raw!==",").map((n)=>n.text),...t.nested.flatMap(Vs)]})}function qu(e,t){for(let n of["&&","||",";","|"])if(e.startsWith(n,t))return n;return null}function Qb(e,t,n,r){if(e[t]==="#"&&e[t+1]!==">"){let s=t+1;while(s<n&&e[s]!=="\r"&&e[s]!==`
26
+ `)s++;return{next:s,limited:!1}}if(!e.startsWith("<#",t))return null;let o=1,i=t+2;while(i<n){if(e.startsWith("<#",i)){if(o++,o>r)return{next:n,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${r}`},limited:!0};i+=2;continue}if(e.startsWith("#>",i)){if(o--,i+=2,o===0)return{next:i,limited:!1};continue}i++}return{next:n,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function eC(e,t){if(t)return"limited";if(e.some((n)=>n.code==="unclosed-block-comment"))return"invalid";return e.length>0?"partial":"complete"}function Hs(e,t,n){return Object.freeze({kind:"connector",operator:e.slice(t,n),span:Object.freeze({start:t,end:n})})}function Ne(e,t="auto",n=bt){if(t==="powershell"||t==="auto"&&Hu(e.slice(0,n.maxInputLength),n))return Ks(e,n);return Iu(e,n)}function _(e){return e.provenance==="command-substitution"?e.raw:e.text}function gn(e,t){return e==="posix"?t:q(t.map((n)=>n.text))}function vo(e,t){return e&&e.provenance!=="unknown"?e.provenance==="literal":!/[$`*?[\]]/.test(t)}function q(e){return e.map((t)=>({kind:"word",text:t,raw:t,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function Ys(e,t){return{value:e,work:t}}function S(e,t){if(e.work)e.work.units=Math.min(Number.MAX_SAFE_INTEGER,e.work.units+1);return e.value[t]}function X(e){return e.value.length}function sr(e,t,n=1){if(e)e.units=Math.min(Number.MAX_SAFE_INTEGER,e.units+t.length*n)}function _e(e,t){sr(e,t)}function Bt(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t===95||t>=97&&t<=122}function j(e){if(!e)return!1;let t=e.charCodeAt(0);return t===9||t===10||t===11||t===12||t===13||t===32||t===160||t===65279||t===5760||t>=8192&&t<=8202||t===8232||t===8233||t===8239||t===8287||t===12288}function Zs(e){return e===`
27
+ `||e==="\r"||e==="\u2028"||e==="\u2029"}function V(e,t,n){if(t+n.length>X(e))return!1;for(let r=0;r<n.length;r++)if(S(e,t+r)!==n[r])return!1;return!0}function tt(e,t,n){return!Bt(S(e,t-1))&&V(e,t,n)&&!Bt(S(e,t+n.length))}function nt(e,t){return Bt(S(e,t-1))!==Bt(S(e,t))}function oe(e){return e===`
28
+ `||e===";"||e==="&"||e==="|"}function hn(e){return e==="|"||e===";"}function Eo(e,t,n){let r=Ys(e,n);if(t==="rm")return tC(r);if(t==="dd")return rC(r);return ed(r,!0)}function xo(e,t,n){let r=Ys(e,n);if(t==="rm")return oC(r);if(t==="reset-hard")return Ju(r,"--ha","rd");if(t==="reset-merge")return Ju(r,"--me","rge");if(t==="clean")return lC(r);if(t==="checkout")return uC(r);if(t==="push-force")return dC(r);if(t==="push-refspec")return fC(r);if(t==="push-delete")return mC(r);if(t==="branch")return pC(r);if(t==="tag")return yC(r);if(t==="restore")return bC(r);return ed(r,!1)}function tC(e){let t=!1,n=!1,r=!1,o=-1;for(let i=0;i<=X(e);i++){let s=S(e,i);if(!t){let l=S(e,i+2);if(tt(e,i,"rm")&&j(l)&&l!==`
29
+ `)t=!0,i++;continue}let a=nC(e,i);if(s===`
30
+ `||a!==-1){if(t=!1,n=!1,r=!1,o=-1,a!==-1)i=a-1;continue}if(s===";"||s==="&"||s==="|"||i===X(e)){if(o>=0){let l=Yu(e,o,i);n||=l.recursive,r||=l.force}if(n&&r)return!0;t=!1,n=!1,r=!1,o=-1;continue}if(j(s)){if(o<0)continue;if(V(e,o,"--")&&i-o===2){t=!1,n=!1,r=!1,o=-1;continue}let l=Yu(e,o,i);if(n||=l.recursive,r||=l.force,n&&r)return!0;o=-1;continue}if(o<0)o=i}return!1}function nC(e,t){if(S(e,t)!=="\\"||S(e,t-1)==="\\")return-1;if(V(e,t,String.raw`\n`))return t+2;if(V(e,t,String.raw`\x0a`)||V(e,t,String.raw`\x0A`))return t+5;if(V(e,t,String.raw`\u000a`)||V(e,t,String.raw`\u000A`))return t+7;return V(e,t,String.raw`\012`)?t+4:-1}function Yu(e,t,n){if(Zu(e,t,n,"recursive"))return{recursive:!0,force:!1};if(Zu(e,t,n,"force"))return{recursive:!1,force:!0};if(S(e,t)!=="-"||S(e,t+1)==="-")return{recursive:!1,force:!1};let r=!1,o=!1;for(let i=t+1;i<n;i++){let s=S(e,i);r||=s==="r"||s==="R",o||=s==="f"||s==="F"}return{recursive:r,force:o}}function Zu(e,t,n,r){let o=n-t-2;if(o<1||o>r.length||!V(e,t,"--"))return!1;for(let i=0;i<o;i++)if(S(e,t+i+2)!==r[i])return!1;return!0}function rC(e){let t=!1;for(let n=0;n<X(e);n++){if(oe(S(e,n))){t=!1;continue}if(tt(e,n,"dd")){t=!0,n++;continue}if(!t||!tt(e,n,"of")||!V(e,n,"of=/dev/"))continue;let r=n+8;if(r<X(e)&&!j(S(e,r))&&S(e,r)!=="'"&&S(e,r)!=='"')return!0}return!1}function oC(e){let t=!1,n=!1,r=!1;for(let o=0;o<=X(e);){let i=S(e,o);if(o===X(e)||oe(i)){t=!1,n=!1,r=!1,o++;continue}let s=sC(e,o);if(s>=0){if(iC(e,s))return!0;let a=s,l=!1;while(j(S(e,a)))l||=S(e,a)===`
31
+ `,a++;if(l)n=!1,r=!1;t=!0,o=a;continue}if(!t){o++;continue}if(V(e,o,"--")&&(o===0||j(S(e,o-1)))&&(!S(e,o+2)||j(S(e,o+2))||oe(S(e,o+2)))){t=!1,n=!1,r=!1,o+=2;continue}if(n||=V(e,o,"--recursive")&&nt(e,o+11)||Xs(e,o,"recursive"),r||=V(e,o,"--force")&&nt(e,o+7)||Xs(e,o,"force"),n&&r)return!0;o++}return!1}function Xs(e,t,n){if(!V(e,t,"--"))return!1;let r=0;while(r<=n.length){let o=S(e,t+r+2);if(!o||j(o)||oe(o))break;if(o!==n[r])return!1;r++}return r>0&&nt(e,t+r+2)}function iC(e,t){let n=t,r=!1,o=!1;while(n<X(e)){while(j(S(e,n)))n++;let i=n;while(n<X(e)&&!j(S(e,n)))n++;if(S(e,i)!=="-"||n-i===2&&V(e,i,"--"))return!1;let s=Xu(e,i,"recursive"),a=Xu(e,i,"force");if(r&&a||o&&s)return!0;if(r||=s,o||=a,S(e,i+1)==="-")continue;let l=aC(e,i,n);if(l.combined||r&&l.forceAtBoundary||o&&l.recursiveAtBoundary)return!0;r||=l.recursive,o||=l.force}return!1}function Xu(e,t,n){return V(e,t,`--${n}`)&&nt(e,t+n.length+2)||Xs(e,t,n)}function sC(e,t){if(t>0&&Bt(S(e,t-1)))return-1;let n=t;if(S(e,n)==="\\")n++;if(S(e,n)!=="r")return-1;if(n++,S(e,n)==="\\")n++;if(S(e,n)!=="m"||!j(S(e,n+1)))return-1;return n+1}function aC(e,t,n){let r=!1,o=!1,i=!1,s=!1,a=!1;if(S(e,t)!=="-")return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a};let l="";for(let c=t+1;c<n;c++){let u=S(e,c)??"",f=(u==="r"||u==="f")&&nt(e,c+1);r||=u==="r",o||=u==="f",i||=u==="r"&&f,s||=u==="f"&&f,a||=(l==="r"&&u==="f"||l==="f"&&u==="r")&&f,l=u}return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a}}function Ju(e,t,n){return lr(e,"reset",hn,!0,(r)=>S(e,r)==="-"&&yn(e,r,t,n)?!0:r)}function lC(e){return lr(e,"clean",hn,!0,(t)=>{if(S(e,t)!=="-")return t;if(yn(e,t,"--fo","rce"))return!0;let n=ar(e,t,hn);for(let r=t+1;r<n;r++)if(S(e,r)==="f")return!0;return n-1})}function Ro(e,t,n){if(!tt(e,t,"git"))return null;let r=t+3;if(!j(S(e,r)))return{commandEnd:-1,next:r};while(j(S(e,r)))r++;while(r<X(e)){if(oe(S(e,r)))return{commandEnd:-1,next:r};let o=ar(e,r,oe);if(tt(e,r,n))return{commandEnd:r+n.length,next:o};if(S(e,r)!=="-")return{commandEnd:-1,next:o};let i=o-r===2&&V(e,r,"--"),s=cC(e,r,o);r=o;while(j(S(e,r)))r++;if(i)return{commandEnd:tt(e,r,n)?r+n.length:-1,next:ar(e,r,oe)};if(!s)continue;if(r>=X(e)||oe(S(e,r)))return{commandEnd:-1,next:r};r=ar(e,r,oe);while(j(S(e,r)))r++}return{commandEnd:-1,next:r}}function cC(e,t,n){for(let r of Ee)if(n-t===r.length&&V(e,t,r))return!0;return!1}function uC(e){return Qu(e,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function dC(e){return lr(e,"push",hn,!0,(t)=>{if(S(e,t)!=="-")return t;if(S(e,t+1)==="f"&&!Bt(S(e,t+2))&&!V(e,t+2,"-with-lease"))return!0;let n=td(e,t,"--fo","rce");if(n>=0&&!V(e,n,"-with-lease"))return!0;return t})}function fC(e){return lr(e,"push",oe,!1,(t)=>{if(j(S(e,t))&&S(e,t+1)==="+"&&t+2<X(e)&&!oe(S(e,t+2))&&!j(S(e,t+2)))return!0;if(S(e,t)===":"&&S(e,t+1)==="+")return!0;return t})}function mC(e){return lr(e,"push",oe,!1,(t)=>{if(S(e,t)==="-"&&yn(e,t,"--de","lete"))return!0;if(j(S(e,t))&&S(e,t+1)===":"&&t+2<X(e)&&!j(S(e,t+2))&&!oe(S(e,t+2)))return!0;return t})}function pC(e){let t=!1,n=!1,r=!1;for(let o=0;o<=X(e);o++){if(o===X(e)||oe(S(e,o))){if(n&&r)return!0;t=!1,n=!1,r=!1;continue}if(!t){let a=Ro(e,o,"branch");if(a){t=a.commandEnd>=0,o=Math.max(o,(t?a.commandEnd:a.next)-1);continue}}if(!t||S(e,o)!=="-")continue;let i=ar(e,o,oe),s=gC(e,o,i);if(n||=s.deletion,r||=s.force,n&&r)return!0;o=i-1}return!1}function gC(e,t,n){let r=!1,o=!1;for(let i=t;i<n;i++){if(S(e,i)!=="-")continue;if(yn(e,i,"--de","lete"))r=!0;if(yn(e,i,"--fo","rce"))o=!0;if(S(e,i+1)==="-")continue;let s=i+1,a=!1,l=!1,c=!1;while(s<n&&hC(S(e,s))){let u=S(e,s);a||=u==="d"||u==="D",l||=u==="f",c||=u==="D",s++}if(!nt(e,s))continue;r||=a,o||=l||c}return{deletion:r,force:o}}function hC(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function yC(e){return Qu(e,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function Qu(e,t){let n=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let r=0;r<X(e);r++){let o=S(e,r),i=n[n.length-1];if(!i)return!1;let s=i.escaped;if(i.escaped=!s&&i.quote!=="'"&&o==="\\",!s&&o==="'"&&i.quote!=='"')i.quote=i.quote==="'"?"":"'";if(!s&&o==='"'&&i.quote!=="'")i.quote=i.quote==='"'?"":'"';if(o==="$"&&S(e,r+1)==="("&&(n.length===1||!s&&i.quote!=="'")){n.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),r++;continue}if(!s&&!i.quote&&n.length>1&&o==="("){i.depth++;continue}if(!s&&!i.quote&&n.length>1&&o===")"){if(i.depth--,i.depth===0)n.pop();continue}if(j(o))i.shortActive=!1,i.hasShortFlag=!1;if(!i.outerActive){let a=Ro(e,r,t.command);if(a){i.outerActive=a.commandEnd>=0&&j(S(e,a.commandEnd)),i.shortActive=!1,i.hasShortFlag=!1,r=Math.max(r,(i.outerActive?a.commandEnd:a.next)-1);continue}}if(i.outerActive&&o==="-"){if(yn(e,r,t.longPrefix,t.longOptional))return!0;i.shortActive||=!t.excludedShortStarts.includes(S(e,r+1)??"")}if(i.hasShortFlag||=i.shortActive&&o===t.shortFlag,i.hasShortFlag&&nt(e,r+1))return!0;if(hn(o))i.outerActive=!1}return!1}function lr(e,t,n,r,o){let i=!1;for(let s=0;s<X(e);s++){let a=S(e,s),l=n(a);if(!i&&!l){let c=Ro(e,s,t);if(c){i=c.commandEnd>=0&&(!r||j(S(e,c.commandEnd))),s=Math.max(s,(i?c.commandEnd:c.next)-1);continue}}if(i){let c=o(s);if(c===!0)return!0;for(let u=s;u<=c;u++)if(n(S(e,u)))i=!1;s=c}if(l)i=!1}return!1}function bC(e){let t=!1;for(let n=0;n<X(e);n++){if(Zs(S(e,n))){if(t)return!0;t=!1;continue}if(!t){let r=Ro(e,n,"restore");if(r){t=r.commandEnd>=0,n=Math.max(n,(t?r.commandEnd:r.next)-1);continue}}if(t&&S(e,n)==="-"&&S(e,n+1)==="-"&&(V(e,n+2,"staged")||V(e,n+2,"help")))t=!1}return t}function ed(e,t){let n=!1;for(let r=0;r<X(e);r++){let o=S(e,r),i=t?Zs(o):oe(o);if(n&&j(o)&&S(e,r+1)==="-"&&tt(e,r+2,"delete"))return!0;if(i){n=!1;continue}if(tt(e,r,"find"))n=!0,r+=3}return!1}function ar(e,t,n){let r=t;while(r<X(e)&&!j(S(e,r))&&!n(S(e,r)))r++;return r}function td(e,t,n,r){if(!V(e,t,n))return-1;let o=t+n.length;for(let i=0;i<r.length&&S(e,o)===r[i];i++)o++;return nt(e,o)?o:-1}function yn(e,t,n,r){return td(e,t,n,r)>=0}function Te(e,t){sr(t,e,2);let n=e.toLowerCase(),r=n.trimStart(),o=r.startsWith("echo ")||r.startsWith("rg "),i=[{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 s of i){if(s.skipForEchoRg&&o)continue;let a=s.caseSensitive?e:n;if(s.regex)_e(t,a);if((s.regex?.test(a)??!1)||s.scan&&xo(a,s.scan,t))return v("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${s.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var CC=/^[A-Za-z_][A-Za-z0-9_]*=/;function rd(e,t,n){let r=e.words[0];if(!t||!r||e.words.length!==1||e.dialect!=="posix")return!1;if(!r.quoted||r.provenance!=="literal")return!1;let o=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r.text)?.[1];if(!o)return!1;sr(n,t.source,2);let i={anchored:new RegExp(`^\\$\\{?${o}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${o}(?![A-Za-z0-9_])`)};return od(t.nodes,r,i)}function od(e,t,n){return e.every((r)=>{if(r.kind==="connector")return!0;if(r.kind==="group"||r.kind==="function")return od(r.body.nodes,t,n);if(r.kind==="unknown")return!n.loose.test(r.source);return SC(r,t,n)})}function SC(e,t,n){if(e.nested.some((o)=>n.loose.test(o.source)))return!1;let r=e.words.findIndex((o)=>!CC.test(o.text));return e.words.every((o,i)=>o===t||nd(o.raw,n.anchored,i!==r))&&e.redirections.every((o)=>(!o.heredoc||o.heredoc.quotedDelimiter||!n.loose.test(o.heredoc.body))&&(!o.target||nd(o.target.raw,n.anchored,!0)))}function nd(e,t,n){let r=!1,o=!1;for(let i=0;i<e.length;i++){let s=e[i];if(s==="\\"&&!r){i++;continue}if(!o&&s==="'"){r=!r;continue}if(!r&&s==='"'){o=!o;continue}if(r||s!=="$")continue;if(!t.test(e.slice(i)))continue;if(!o||!n)return!1}return!0}import{isAbsolute as vC,resolve as id}from"node:path";function cr(e,t,n,r){let o=vC(e)?id(e):t?id(t,e):void 0;if(!o)return;try{return D(o,n,r)}catch{return o}}function sd(e){return!["/dev","/proc","/sys"].some((t)=>e===t||e.startsWith(`${t}/`))}var bn="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",ur="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.",Qs=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),EC=new Set(["-p","--print"]),xC=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),RC=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"])]]),_C=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),wC=new Map([["python",new Set(["m"])]]),PC=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"])]]),AC=new Set(["always","default","never"]),IC=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),TC=/\\\r?\n/g,kC=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 ad(e){return wo(e).code}function _o(e){return wo(e).sources}function ld(e){return kC.get(ta(e))??[]}function wo(e){let t=ta(e[0]??"");if(!Qs.has(t))return{code:null,sources:[],optionsOpen:!1};let n=[],r=[],o=!0;for(let i=1;i<e.length;i++){let s=e[i];if(s===void 0)break;if(s==="--")return Le(t,n,r,o,e[i+1]===void 0?void 0:i+1,e[i+1]);if(s===""||s==="-"||!s.startsWith("-"))return Le(t,n,r,o,i,s);if(t==="node"&&EC.has(s)){let f=e[i+1];if(f===void 0)return Le(t,n,r,o);if(f.startsWith("-"))continue;n.push({tokenIndex:i+1,value:f}),r.push({tokenIndex:i+1,kind:"inline-code",value:f}),i++;continue}if(MC(t,s)){let f=e[i+1];if(f===void 0)return Le(t,n,r,o);if(n.push({tokenIndex:i+1,value:f}),r.push({tokenIndex:i+1,kind:"inline-code",value:f}),t==="python")return Le(t,n,r,o);i++;continue}let a=/^--eval=(.*)$/s.exec(s);if(DC(t)&&a){let f=a[1]??"";n.push({tokenIndex:i,value:f}),r.push({tokenIndex:i,kind:"inline-code",value:f});continue}if(t==="node"){let f=OC(s);if(f){if(f.attached){if(o&&=f.value!=="",f.value!=="")r.push({tokenIndex:i,kind:"module-file",value:f.value});continue}let d=e[i+1];if(d===void 0||d.startsWith("-"))return o=!1,Le(t,n,r,o);r.push({tokenIndex:i+1,kind:"module-file",value:d}),i++;continue}}if(t==="python"&&s.startsWith("--check-hash-based-pycs=")||t==="node"&&(s==="--conditions="||s==="--diagnostic-dir="||s==="--title=")||t==="ruby"&&(s==="--disable="||s==="--enable="))return Le(t,n,r,o);if(PC.get(t)?.has(s)){let f=e[i+1];if(f===void 0||f.startsWith("-")&&!(t==="ruby"&&IC.has(s))||t==="python"&&!AC.has(f))return Le(t,n,r,o);i++;continue}if(s.startsWith("--"))continue;let l,c=!1;for(let f=1;f<s.length;f++){let d=s[f];if(d===void 0)break;if(wC.get(t)?.has(d)){let m=s.slice(f+1),g=m||e[i+1];if(g!==void 0)r.push({tokenIndex:m?i:i+1,kind:"module-file",value:g});return Le(t,n,r,o)}if(xC.get(t)?.has(d)){l=s.slice(f+1)||e[i+1],c=f+1===s.length;break}if(t==="node"&&d==="r"){if(o&&=s==="-r",s==="-r"){let m=e[i+1];if(o&&=m!==void 0&&!m.startsWith("-"),o&&m!==void 0)r.push({tokenIndex:i+1,kind:"module-file",value:m});i++}break}if(t==="ruby"&&d==="r"){let m=s.slice(f+1),g=m||e[i+1];if(o&&=g!==void 0,g!==void 0)r.push({tokenIndex:m?i:i+1,kind:"module-file",value:g});if(!m)i++;break}if(t==="perl"&&(d==="M"||d==="m")){let m=s.slice(f+1);if(!m){if(o=!1,f+1===s.length)i++;break}r.push({tokenIndex:i,kind:"module-file",value:m});break}if(RC.get(t)?.has(d)){if(f+1===s.length)i++;break}if(_C.get(t)?.has(d)&&f+1<s.length)break}if(l===void 0)continue;let u=c?i+1:i;if(n.push({tokenIndex:u,value:l}),r.push({tokenIndex:u,kind:"inline-code",value:l}),t==="python")return Le(t,n,r,o);if(c)i++}return Le(t,n,r,o,void 0,void 0,!0)}function Le(e,t,n,r,o,i,s=!1){let a=e==="node"?t.slice(-1):t,l=new Set(a.map((u)=>u.tokenIndex)),c=n.filter((u)=>u.kind!=="inline-code"||l.has(u.tokenIndex));if(r&&t.length===0&&o!==void 0&&i!==void 0)c.push({tokenIndex:o,kind:"main-script",value:i});return{code:(e==="node"?a[0]?.value:a.map((u)=>u.value).join(`
32
+ `))||null,sources:r?c:[],optionsOpen:r&&s}}function OC(e){for(let t of["--import","--loader","--experimental-loader","--require"]){if(e===t)return{attached:!1,value:""};if(e.startsWith(`${t}=`))return{attached:!0,value:e.slice(t.length+1)}}return}function ea(e,t){return ta(e)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(t)}function ta(e){let t=P(e).toLowerCase();return qr.test(t)?"python":t}function MC(e,t){return Qs.get(e)?.has(t)??!1}function DC(e){return Qs.get(e)?.has("--eval")??!1}function dr(e,t,n=!1){let r=WC(e,t);if(!Js(r,t))return!1;_e(t,r);let o=LC(r);if(Js(o,t))return!0;if(_e(t,o),!cd.test(o))return!1;return!n||NC(r,t)}function NC(e,t){if(/`|%x|\bqx\b/.test(e))return!0;let r=e.split(""),o=[];for(let l=0;l<e.length;l++){let c=e[l];if(c!=="'"&&c!=='"')continue;let u=e.startsWith(c.repeat(3),l)?c.repeat(3):c,f=l+u.length,d=f;while(d<e.length&&!e.startsWith(u,d))d+=e[d]==="\\"?2:1;if(d>=e.length)return!0;o.push({start:f,text:e.slice(f,d)}),r.fill(" ",l,d+u.length),l=d+u.length-1}let i=r.join(""),s=Array.from(i.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((l)=>cd.test(l[1]??"")).map((l)=>{let c=l.index+l[0].length;return{start:c,end:na(i,c)}});if(s.some((l)=>ra(i,l.start)))return!0;return o.some((l)=>{let c=/\b(?:system|exec|spawn|popen)\s*$/.test(i.slice(0,l.start)),u=s.some((f)=>l.start>=f.start&&l.start<f.end);return(c||u)&&Js(l.text,t)})}function na(e,t){let n=1;for(let r=t;r<e.length;r++){if(e[r]==="(")n++;if(e[r]===")")n--;if(n===0)return r}return e.length}function ra(e,t){let n=0;for(let r=t;r<e.length;r++){let o=e[r]??"";if("([{".includes(o))n++;if(")]}".includes(o)&&n--===0)return!1;if(o===","&&n===0)return!1;if(/[A-Za-z_$]/.test(o))return!0}return!1}var cd=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function LC(e){let t=[],n=0,r=0;while(r<e.length){let o=e[r];if(o!=="'"&&o!=='"'){r++;continue}let i=e.startsWith(o.repeat(3),r)?o.repeat(3):o,s=r+i.length;while(s<e.length&&!e.startsWith(i,s))s+=e[s]==="\\"?2:1;if(s>=e.length)break;t.push(e.slice(n,r)," "),r=s+i.length,n=r}return t.push(e.slice(n)),t.join("")}function Js(e,t){if(Eo(e,"rm",t))return!0;for(let r of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(_e(t,e),r.test(e))return!0;if(Eo(e,"dd",t))return!0;for(let r of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(_e(t,e),r.test(e))return!0;if(Eo(e,"find",t))return!0;let n=e.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((r)=>(_e(t,e),n.some((o)=>xo(o,r))))}function WC(e,t){return _e(t,e),e.replace(TC,"")}import{lstatSync as DS,readdirSync as NS}from"node:fs";import{basename as LS,isAbsolute as Nd,join as WS,relative as Ld}from"node:path";import{isAbsolute as hd,parse as KC}from"node:path";import{dirname as GC,isAbsolute as FC,parse as zC,sep as BC}from"node:path";function Ct(e,t,n){if(Je(t))throw Error("Unsupported Windows namespace path");let r=FC(t)?zC(t).root:"",o=r||e;for(let i of UC(r?t.slice(r.length):t)){if(i===""||i===".")continue;if(i===".."){o=GC(o);continue}let s=$C(o,i),a=n.entryKind(s),l=a==="symlink"?n.realpath(s):s;if(a==="missing"||l===null)throw Error(`Cannot resolve path component: ${s}`);o=l}return o}function $C(e,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${t}`:`${e}${BC}${t}`}function UC(e){let t=process.platform==="win32"?/[\\/]+/:/\/+/;return e.split(t)}var oa=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],HC=new Set(oa),jC=1024,ud=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),dd=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),VC=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function Po(e){return HC.has(e)}function ia(e){return Po(e)||ud.has(e)||dd.has(e)||Kn(e)}function rt(e,t,n){return n?.has(e)?n.get(e):t.get(e)}function fd(e,t){let n=rt("GIT_CONFIG_COUNT",e,t);if(n===void 0)return{state:"absent"};if(n==="")return{state:"valid",count:0};if(!/^\d+$/.test(n))return{state:"invalid"};let r=Number(n);return Number.isSafeInteger(r)&&r<=jC?{state:"valid",count:r}:{state:"invalid"}}function Ao(e,t,n){let o=e.match(VC)?.[1];if(!o||!ia(o))return null;let i=e.indexOf("=");return{name:o,value:`${rt(o,t,n)??""}${e.slice(i+1)}`}}function md(e){return gd(e,dd)}function pd(e){return gd(e,ud)}function gd(e,t){if(!e)return!1;for(let n of e.keys())if(t.has(n))return!0;return!1}var bd=/^[A-Za-z_][A-Za-z0-9_]*=/;function ke(e){if(!bd.test(e))return null;let t=e.indexOf("=");return{name:e.slice(0,t),value:e.slice(t+1)}}function Io(e){let t=new Map,n=0;while(n<e.length){let r=e[n];if(!r)break;let o=ke(_(r));if(!o)break;t.set(o.name,o.value),n++}return{words:e.slice(n),envAssignments:t}}function Cd(e){let t=O(e);return e.includes("=")||t==="sudo"||t==="env"||t==="command"||t==="builtin"}function $t(e,t,n,r){if(!Cd(Cn(e)))return{words:e,envAssignments:new Map,cwd:n,rewritten:!1};let o=new Set(e),i=e,s=new Map,a=new Map(r??[]),l=[],c=n;for(let f=0;f<K.wrapperPeelIterations.cap;f++){let d=yd(i),m=Io(i);for(let[p,h]of m.envAssignments)s.set(p,h),a.set(p,h);if(i=m.words,i.length===0)break;while(i.length>0&&Cn(i).includes("=")&&!YC(i)){let p=ZC(Cn(i),a,t.env)??Ao(Cn(i),t.env,a);if(p)s.set(p.name,p.value),a.set(p.name,p.value);i=i.slice(1)}if(i.length===0)break;let g=O(Cn(i));if(g!=="sudo"&&g!=="env"&&g!=="command"&&g!=="builtin")break;if(g==="sudo"){let p=JC(i,t.paths,c);if(i=p.words,p.cwd!==void 0)c=p.cwd}if(g==="env"){let p=tS(i,c,a,t);if(l.push(...p.envSplitValues??[]),i=p.words,p.cwd!==void 0)c=p.cwd;for(let[h,y]of p.envAssignments)s.set(h,y),a.set(h,y)}if(g==="command")i=nS(i);if(g==="builtin")i=i.slice(We(i,1)==="--"?2:1);if(yd(i)===d)break}let u=Io(i);for(let[f,d]of u.envAssignments)s.set(f,d),a.set(f,d);return{words:u.words,envAssignments:s,cwd:c,envSplitValues:l.length>0?l:void 0,rewritten:qC(u.words,o)}}function qC(e,t){return e.some((n)=>!t.has(n))}function yd(e){return e.map(_).join(" ")}function Cn(e){let t=e[0];return t?_(t):""}function We(e,t){let n=e[t];return n?_(n):void 0}function YC(e){return bd.test(Cn(e))}function ZC(e,t,n){if(!e.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${t.get("TMPDIR")??n.get("TMPDIR")??""}${e.slice(8)}`}}var XC=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function JC(e,t,n){let r=1,o=n;while(r<e.length){let i=We(e,r);if(!i)break;if(i==="--")return{words:e.slice(r+1),cwd:o};if(!i.startsWith("-"))break;if(i==="-D"||i==="--chdir"){let s=We(e,r+1);o=s?fr(o,s,t):null,r+=2;continue}if(i.startsWith("--chdir=")){o=fr(o,i.slice(8),t),r++;continue}if(i.startsWith("-D")&&i.length>2){o=fr(o,i.slice(2),t),r++;continue}if(i==="-i"||i==="--login"){o=null,r++;continue}if(XC.has(i)){r+=2;continue}r++}return{words:e.slice(r),cwd:o}}var QC=new Set(["-i","-0","--null"]),eS=new Set(["-u","--unset","-C","--chdir","-P"]);function tS(e,t,n,r){let o=new Map,i=[],s=t,a=1,l=(c)=>({words:e.slice(c),envAssignments:o,cwd:s,envSplitValues:i.length>0?i:void 0});while(a<e.length){let c=We(e,a);if(!c)break;if(c==="--")return l(a+1);if(c==="-i"||c==="--ignore-environment"||c==="-"){o.clear();for(let f of n.keys())o.set(f,"");o.set("TMPDIR",""),a++;continue}if(QC.has(c)){a++;continue}if(c==="-u"||c==="--unset"){let f=We(e,a+1);if(f!==void 0)o.set(f,"");a+=2;continue}if(c.startsWith("-u")&&c.length>2&&!c.startsWith("-u=")){o.set(c.slice(2),""),a++;continue}if(c.startsWith("--unset=")){o.set(c.slice(8),""),a++;continue}let u=c==="-S"||c==="--split-string"?{value:We(e,a+1),consumed:2}:c.startsWith("-S")&&c.length>2?{value:c.slice(2),consumed:1}:c.startsWith("--split-string=")?{value:c.slice(15),consumed:1}:null;if(u){if(u.value!==void 0)i.push(u.value);return s=null,l(a+u.consumed)}if(eS.has(c)){if(c==="-C"||c==="--chdir"){let f=We(e,a+1);s=f?fr(s,f,r.paths):null}a+=2;continue}if(c.startsWith("-u=")){a++;continue}if(c.startsWith("-C")&&c.length>2||c.startsWith("--chdir=")){let f=c.startsWith("--chdir=")?c.slice(8):c.startsWith("-C=")?c.slice(3):c.slice(2);s=fr(s,f,r.paths),a++;continue}if(c.startsWith("-P")){a++;continue}if(c.startsWith("-")){a++;continue}if(!ke(c))break;while(a<e.length){let f=ke(We(e,a)??"");if(!f)break;o.set(f.name,f.value),a++}if(We(e,a)==="--")a++;return l(a)}return l(a)}function fr(e,t,n){if(t==="")return null;if(!e&&!hd(t))return null;let r=hd(t)?KC(t).root:n.realpath(e??"/");if(r===null)return null;try{return Ct(r,t,n)}catch{return null}}function nS(e){if(We(e,1)==="-v")return[...q(["type"]),...e.slice(2)];let t=1;while(t<e.length){let n=We(e,t);if(!n)break;if(n==="-p"||n==="-v"||n==="-V"){t++;continue}if(n==="--")return e.slice(t+1);if(n.startsWith("-")&&!n.startsWith("--")&&n.length>1){if(!/^[pvV]+$/.test(n.slice(1)))break;t++;continue}break}return e.slice(t)}var rS=/['"\\$`{}#]/;function To(e,t){if(e.some((r)=>rS.test(r)))return null;let n=[...e.flatMap((r)=>r.split(/\s+/).filter((o)=>o.length>0)),...t];return n.length<=64?n:null}function St(e,t,n){return ko(e,t,n).tokens}function oS(e){let t=[],n="",r=0;while(r<e.length){let o=e.charAt(r);if(o==='"'||o==="'"){let i=e.indexOf(o,r+1);if(i===-1)return e.split(/\s+/).map((s)=>s.replace(/["']/g,"")).filter((s)=>s.length>0);n+=e.slice(r+1,i),r=i+1;continue}if(/\s/.test(o)){if(n.length>0)t.push(n);n="",r++;continue}n+=o,r++}if(n.length>0)t.push(n);return t}function vt(e,t,n,r=0){let o=ko(e,t,n),i=(o.envSplitValues??[]).flatMap(oS);if(i.length===0)return o.tokens;let s=[...i,...o.tokens];if(r>=8)return s;return vt(s,t,n,r+1)}function ko(e,t,n,r){if(!Cd(e[0]??""))return{tokens:[...e],envAssignments:new Map,cwd:n};let o=$t(q(e),t,n,r);return{tokens:o.words.map(_),envAssignments:o.envAssignments,cwd:o.cwd,envSplitValues:o.envSplitValues}}var ca=Symbol("adopt-as-operand"),iS=new Set(["env","sudo","command","builtin"]),sS=new Set(["&&","||","|&","|","&",";"]),aS=new Set(["<<","<<<",">|"]),lS=new Set(["|","|&"]),cS=/[*@#?$!_-]/,uS=/^\w+(?::\w+)*/,dS=Object.freeze([]),mr=Object.freeze({kind:"scope",edge:"enter"}),pr=Object.freeze({kind:"scope",edge:"exit"}),fS=Object.freeze([]),mS=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),gr=new Set(["bash","sh","zsh","dash","ksh"]),pS=256,Rd=new WeakMap;function _d(e,t){let n=t.status==="complete"?new Set(la(t)):new Set,r=yS(e,n);if(Zr(r))return Oo("unclosed-quote",r,t);let o={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},i=Ut(t,{source:r,suppressed:n,flags:o,depth:0,functions:new Map,powershell:t.dialect==="powershell"});if(o.limited)return Oo("structural-limit",r,t);if(o.invalid)return Oo("invalid",r,t);let s=Oo("complete",r,t,o.assignmentFallbacks);return Rd.set(s,Object.freeze(i)),s}function Do(e,t,n,r,o){let i=o.word??((f)=>f),s={cwd:t,variables:new Map,previous:null},a=[],l=new Set,c=null,u=[];for(let f of wd(e)){if(f.kind==="scope"){if(f.edge==="enter"){u.push({state:s,segment:[...a],shellWords:new Set(l),pipeProducer:c});continue}let d=o.segment(a,s,c,null,l);if(d)return d;let m=u.pop();if(m===void 0)throw Error("scope exit without a matching enter");s=m.state,a=m.segment,l=m.shellWords,c=m.pipeProducer;continue}if(f.kind==="operator"){if(!f.boundary)continue;let d=o.segment(a,s,c,f.operator,l);if(d)return d;s=gS(a,s,n,r),c=a.length>0&&lS.has(f.operator)?a:null,a=[],l=new Set;continue}if(f.kind==="redirection"){if(f.fd!==void 0)l.add(a.length-1);if(f.target===void 0)continue;let d=o.redirection({operator:f.operator,role:f.role,targetOrder:f.targetOrder,target:f.target,...f.body===void 0?{}:{body:f.body,consumer:f.consumer}},s);if(d===ca){l.add(a.length),a.push(i(f.target));continue}if(d)return d;continue}a.push(i(f.text))}return o.segment(a,s,c,null,l)}function No(e){return wd(e).flatMap((t)=>{if(t.kind==="word")return[{kind:"word",text:t.text}];if(t.kind==="operator")return[{kind:"operator",boundary:t.boundary}];if(t.kind==="redirection")return[{kind:"redirection",target:t.target}];return[]})}function pe(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(n,r,o,i)=>{let s=t.get(r);if(s===void 0)return n;let a=o.startsWith(":")?s!=="":!0;if(o.endsWith("-"))return a?s:pe(i,t);return a?pe(i,t):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(n,r)=>t.get(r)??n).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(n,r)=>t.get(r)??n)}function hr(e){return e.length>0&&e.every((t)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t))}function gS(e,t,n,r){let o=hr(e)?new Map([...t.variables,...hS(e,t.variables)]):t.variables,i=St([...e],n),s=P(i[0]??"").toLowerCase()==="cd"?i[1]:void 0;if(!s)return{...t,variables:o};if(s==="-"){if(t.previous===null)return{...t,variables:o};return{cwd:t.previous,variables:o,previous:t.cwd}}return{cwd:le(pe(s,o),t.cwd,n,r),variables:o,previous:t.cwd}}function hS(e,t){return e.flatMap((n)=>{let r=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(n),o=r?.[2]?.startsWith("=")?r[2].slice(1):void 0;return r?.[1]!==void 0&&o!==void 0?[[r[1],pe(o,t)]]:[]})}function wd(e){return Rd.get(e)??dS}function yS(e,t){return[...t].reduce((n,r)=>n.slice(0,r.start)+" ".repeat(r.end-r.start)+n.slice(r.end),e)}function Oo(e,t,n,r=fS){return Object.freeze({status:e,source:t,program:n,assignmentFallbacks:Object.freeze(r)})}function Ut(e,t){return e.nodes.flatMap((n,r)=>bS(n,e,r,t)).sort((n,r)=>n.start-r.start).flatMap((n)=>[...n.events])}function bS(e,t,n,r){if(e.kind==="connector")return[{start:e.span.start,events:[Ge(xS(e.operator))]}];if(e.kind==="unknown")return[{start:e.span.start,events:[Ge(e.source)]}];if(e.kind==="function")return r.functions.set(e.name,e.body),[];if(e.kind==="group"){let i=e.style!=="subshell",s=r.source[e.span.end-1]===(i?"}":")"),a=i?r:{...r,functions:new Map(r.functions)};return[{start:e.span.start,events:i?[Mo("{"),...Ut(e.body,a),...s?[Mo("}")]:[]]:[mr,Ge("("),...Ut(e.body,a),...s?[Ge(")")]:[],pr]}]}let o=PS(e,r.functions);if(o){if(r.depth>=bt.maxDepth||++r.flags.expansions>pS)return r.flags.limited=!0,[];return[{start:e.span.start,events:[...Sd(e,r),Mo(";"),...Ut(o,{...r,depth:r.depth+1}),Mo(";")]},...vd(e,t,n,r)]}return[{start:e.span.start,events:Sd(e,r)},...vd(e,t,n,r)]}function Sd(e,t){return[...e.words.map((n)=>({start:n.span.start,events:Ad(n,e,t,!1)})),...e.redirections.map((n)=>({start:n.span.start,events:CS(n,e,t)}))].sort((n,r)=>n.start-r.start).flatMap((n)=>n.events)}function CS(e,t,n){let r=e.operator==="<<-"?"<<":e.operator,o=e.target?Ad(e.target,t,n,!0):[],i=o[0],s=i?.kind==="word"?i.text:void 0;return[...e.fd===void 0?[]:[ua(String(e.fd))],Object.freeze({kind:"redirection",operator:r,...e.fd===void 0?{}:{fd:e.fd},role:RS(r),targetOrder:aS.has(r)?"legacy-segment":"immediate",...s===void 0?{}:{target:s},...e.heredoc&&n.suppressed.has(e.heredoc.bodySpan)?{body:e.heredoc.body,consumer:Td(t)}:{}}),...s===void 0?o:o.slice(1)]}function vd(e,t,n,r){let o=e.redirections.filter((i)=>i.operator==="<<"||i.operator==="<<-");return[...o.flatMap((i)=>{let s=i.heredoc;if(!s)return[];let a=[ua(s.delimiter),.../[\r\n]/.test(r.source[s.terminatorSpan.end]??"")?[Ge(";")]:[]];if(r.suppressed.has(s.bodySpan))return[{start:s.bodySpan.start,events:a}];return[{start:s.bodySpan.start,events:[...Pd(r.source.slice(s.bodySpan.start,s.bodySpan.end),r),...a]}]}),...o.some((i)=>!i.heredoc&&i.target)?SS(t,n,r):[]]}function SS(e,t,n){let r=e.nodes.slice(t+1).find((o)=>o.kind==="connector");if(!r||r.span.end>=e.span.end)return[];return[{start:r.span.end,events:Pd(n.source.slice(r.span.end,e.span.end),n)}]}function Pd(e,t){if(t.depth>=bt.maxDepth)return t.flags.limited=!0,[];let n=Ne(e,"posix");if(n.status==="limited")return t.flags.limited=!0,[];let r={invalid:!1,limited:!1,expansions:t.flags.expansions,assignmentFallbacks:t.flags.assignmentFallbacks},o=Ut(n,{source:e,suppressed:new Set,flags:r,depth:t.depth+1,functions:new Map,powershell:!1});return t.flags.limited||=r.limited,t.flags.expansions=r.expansions,o}function Ad(e,t,n,r){let o=[],i={single:!1,double:!1},s="",a=!1,l=()=>{let c=a&&!r?Ge("glob"):s!==""||e.quoted&&o.length===0?ua(s):void 0;if(c)o.push(c);s="",a=!1};for(let c of e.parts){if(c.provenance!=="command-substitution"&&c.provenance!=="arithmetic"){for(let m of sa(c.raw,i,n.flags,n.powershell)){if(typeof m==="string"){l(),o.push(Ge(m));continue}s+=m.text,a||=m.glob}continue}let u=t.nested.find((m)=>m.span.start>=c.span.start&&m.span.end<=c.span.end);if(i.double){let m=n.source.slice(c.span.start,c.span.end);s+=sa(m,{single:!1,double:!0},n.flags,n.powershell).map((p)=>typeof p==="string"?p:p.text).join("");let g=u?Ut(u,n).filter((p)=>p.kind==="redirection"&&p.body!==void 0):[];if(g.length>0)o.push(mr,...g,pr);continue}let f=u?Ut(u,n):[];if(c.raw.startsWith("`")){s+="${}",l(),o.push(mr,...f,pr);continue}if(c.raw.startsWith("<(")||c.raw.startsWith(">(")){l(),o.push(c.raw.startsWith("<(")?Ge("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),mr,...f,...c.raw.endsWith(")")?[Ge(")")]:[],pr);continue}let d=c.raw.startsWith("$((")?2:1;s+="${}",l(),o.push(...Array.from({length:d},()=>Ge("(")),...d===1?[mr]:[],...f,...c.raw.endsWith(")".repeat(d))?Array.from({length:d},()=>Ge(")")):[],...d===1?[pr]:[])}return l(),o}function sa(e,t,n,r){let o=[],i="",s=!1,a=0;while(a<e.length){let l=e[a]??"";if(!t.single&&!t.double&&(l==="("||l===")")){o.push({text:i,glob:s},l),i="",s=!1,a++;continue}if(r&&l==="`"&&!t.single){i+=e[a+1]??"",a+=2;continue}if(t.single&&l==="'"){t.single=!1,a++;continue}if(t.single){i+=l,a++;continue}if(t.double){if(l==='"'){t.double=!1,a++;continue}if(!r&&l==="\\"){let c=e[a+1]??"";i+=['"',"\\","$"].includes(c)?c:`\\${c}`,a+=2;continue}if(l==="$"){let c=Ed(e,a,t,n,r);i+=c.text,a=c.next;continue}i+=l,a++;continue}if(l==="'"||l==='"'){t.single=l==="'",t.double=l==='"',a++;continue}if(!r&&l==="\\"){let c=e[a+1]??"";s||=c==="*"||c==="?",i+=c,a+=2;continue}if(l==="$"){let c=Ed(e,a,t,n,r);i+=c.text,a=c.next;continue}s||=l==="*"||l==="?",i+=l,a++}return[...o,{text:i,glob:s}]}function Ed(e,t,n,r,o){let i=e[t+1];if(i==="{"){let a=o?ES(e,t+2):So(e,t+2,e.length).close;if(a===-1)return r.invalid=!0,{text:"",next:e.length};let l=e.slice(t,a+1);return vS(l,n,r,o),{text:l,next:a+1}}if(i!==void 0&&cS.test(i))return{text:`\${${i}}`,next:t+2};let s=(o?uS:/^\w*/).exec(e.slice(t+1))?.[0]??"";return{text:`\${${s}}`,next:t+1+s.length}}function vS(e,t,n,r){let o=e.slice(2,-1),i=/^[A-Za-z_][A-Za-z0-9_]*/.exec(o)?.[0];if(!i)return;let s=o.slice(i.length),a=[":=","="].find((c)=>s.startsWith(c));if(!a)return;let l=sa(s.slice(a.length),{...t},n,r);n.assignmentFallbacks.push(...l.flatMap((c)=>typeof c==="string"||!c.text?[]:[c.text]))}function ES(e,t){let n=1,r=t;while(n>0&&r<e.length){if(e[r]==="{"&&e[r-1]==="$")n++;if(e[r]==="}")n--;r++}return n===0?r-1:-1}function xS(e){return/^[\r\n]+$/.test(e)?";":e}function Ge(e){return Object.freeze({kind:"operator",operator:e,boundary:sS.has(e)})}function Mo(e){return Object.freeze({kind:"operator",operator:e,boundary:!0})}function ua(e){return Object.freeze({kind:"word",text:e})}function RS(e){if(e==="<<"||e==="<<<")return"here-data";if(e==="<"||e==="<&")return"file-read";return"file-write"}function yr(e){return mS.has(e)||/^python\d/.test(e)}var _S=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 Id(e,t){let n=t[0];if(n===void 0||!n.startsWith("-"))return t;let r=_S.get(e)?.has(n)??!1;return Id(e,t.slice(r?2:1))}function aa(e){let t=e[0];if(t===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(t))return aa(e.slice(1));if(!iS.has(t))return[...e];return aa(Id(t,e.slice(1)))}function Td(e){let t=tr(e),n=e.words.findIndex((r)=>r.provenance==="literal"&&r.text===t);return aa(n<0?[]:e.words.slice(n).map((r)=>r.text))}function wS(e){let t=Td(e)[0];if(t===void 0)return!1;let n=P(t).toLowerCase();return yr(n)&&!gr.has(n)}function la(e){return e.nodes.flatMap((t,n)=>{if(t.kind==="group"||t.kind==="function")return la(t.body);if(t.kind!=="command")return[];let r=t.nested.flatMap((a)=>la(a)),o=t.redirections.flatMap((a)=>a.heredoc?.quotedDelimiter?[a.heredoc.bodySpan]:[]);if(wS(t))return[...r,...o];let i=e.nodes[n+1];if(i?.kind==="connector"&&(i.operator==="|"||i.operator==="|&")||!IS(t))return r;return[...r,...o]})}function PS(e,t){let n=tr(e);return n===void 0?void 0:t.get(n)}function Et(e,t){return e!==void 0&&e.provenance==="literal"&&!e.quoted&&e.raw===e.text&&e.text===t}function AS(e){if(Et(e.words[0],"git"))return Et(e.words[1],"commit");if(!Et(e.words[0],"gh")||!Et(e.words[2],"create"))return!1;return Et(e.words[1],"pr")||Et(e.words[1],"issue")}function IS(e){return(Et(e.words[0],"cat")||Et(e.words[0],"tee")||AS(e))&&!e.words.some(xd)&&!e.redirections.some((n)=>xd(n.target))}function xd(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}var kd=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Od=new Set([...kd,"glob"]),TS=new Set([...Od,"folder","pattern","patterns"]);class Fe extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Md(e){let t=kS(),n=Un(e.input),r=[];if((e.route.kind==="command"||e.route.kind==="unknown")&&n)r.push({usage:"input-candidate",source:n});if(e.route.kind==="command"&&"command"in e&&e.command)r.push({usage:"declared-command",source:e.command});let o=r.reduce((i,s)=>{let a=i.findIndex((u)=>u.source===s.source);if(a!==-1){let u=i[a];if(!u)return i;return i[a]={...u,usages:[...u.usages,s.usage]},i}let l=e.route.kind==="command"?e.route.shell:process.platform==="win32"?"powershell":"posix",c=t.getCommandProgram(s.source,l);return i.push({usages:[s.usage],source:s.source,program:c,shell:t.getShellSyntax(s.source,c)}),i},[]);return{invocation:{toolName:e.toolName,route:e.route,context:e.context},commands:o,paths:OS(e),store:t}}function ge(e,t){return e.commands.find((n)=>n.usages.includes(t))}function ot(e,t){if(!e.includes("$"))return e;return ki(e,t)}function kS(){let e=new Map,t=new Map,n=new WeakMap,r=(i,s)=>{let a=`${s}\x00${i}`,l=t.get(a);if(l)return l;let c=Ne(i,s);return t.set(a,c),c};return{getShellSyntax:(i,s)=>{if(s&&s.source!==i)throw TypeError("Shell syntax source does not match command program source.");let a=s??r(i,"posix");if(a.status==="limited"){let u=n.get(a);if(u)return u;let f={status:"structural-limit",source:i,program:a,assignmentFallbacks:[]};return n.set(a,f),f}let l=e.get(i);if(l)return l;let c=_d(i,a);return e.set(i,c),c},getCommandProgram:r}}function OS(e){let t=e.route.kind==="grep"?Od:e.route.kind==="glob"?TS:kd;return[...Ul(e.input,t),...e.route.kind==="patch"||typeof e.input==="string"?Vl(e.input):[]]}var MS=new Set(["-S","--suffix"]);function Sn(e,t,n,r,o){if(e.status==="structural-limit")throw new Fe;if(e.status!=="complete")return o.findMalformedTarget(e.source);return Do(e,t,n,r,{segment:(i,s)=>o.findSegmentTarget(i,s),redirection:(i,s)=>i.role==="file-write"&&o.isRedirectionTarget(pe(i.target,s.variables),s)?i.target:null})}function Lo(e){let t=[],n=null,r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i===void 0)break;if(!r&&i==="--"){r=!0;continue}if(!r&&(i==="-t"||i==="--target-directory")){n=e[++o]??null;continue}if(!r&&i.startsWith("--target-directory=")){n=i.slice(19);continue}if(!r&&i.startsWith("-t")&&i.length>2){n=i.slice(2);continue}if(!r&&MS.has(i)){o++;continue}if(!r&&(i.startsWith("--suffix=")||i.startsWith("--backup=")))continue;if(!r&&i.startsWith("-"))continue;t.push(i)}return n?{sources:t,destination:n}:{sources:t.slice(0,-1),destination:t.at(-1)??null}}var ze="Git metadata and hooks are protected. Ask the user before modifying them.";function Wd(e,t,n,r){let o=e.invocation.context.executionCwd;if(!t)return null;if(e.invocation.route.kind==="patch"||e.invocation.route.kind==="path"||e.invocation.route.kind==="unknown"){if(Fr(e.invocation.toolName))return null;let a=e.paths.find((l)=>Dd(l,o,t,n,r,t.entries));return a?{target:a}:null}if(e.invocation.route.kind!=="command")return null;let i=ge(e,"input-candidate");if(!i)return null;let s=Sn(i.shell,o,n,r,{findSegmentTarget:(a,l)=>US(a,l,t,n,r),isRedirectionTarget:(a,l)=>Dd(a,l.cwd,t,n,r,t.markerFiles),findMalformedTarget:()=>null});return s?{target:s}:null}function Ht(e,t,n,r,o,i,s=!1){if(!n)return!1;let a=Go(le(e,t,o,i)),l=a.replace(/(\/\.?\*+)+$/,"");if(l!==a&&l!==""){if(da(l,n))return!0;let c=s||a.slice(l.length).includes("/."),u=(f)=>c?Wo(f,l):GS(f,l);if(n.markerFiles.some(u))return!0;return r&&fa(n).some(u)}if(da(a,n))return!0;return r&&fa(n).some((c)=>Wo(c,a))}function GS(e,t){let n=Ld(t,e);if(n===""||n.startsWith("..")||Nd(n))return!1;return!n.split(/[\\/]/)[0]?.startsWith(".")}function FS(e,t,n,r,o){return Ht(e,t,n,!0,r,o)}function zS(e,t,n,r,o){if(!n)return!1;return da(Go(le(e,t,r,o)),n)}function Dd(e,t,n,r,o,i){let s=Go(le(e,t,r,o));return i.includes(s)||Fd(s,n)}function Gd(e,t,n,r,o){if(!n)return!1;return n.hooksDirectories.some((i)=>e.some((s)=>Wo(i,Go(le(s,t,r,o)))))}function da(e,t){return t.entries.includes(e)||t.directories.includes(e)||Fd(e,t)}function Fd(e,t){return t.hooksDirectories.some((n)=>Wo(e,n))}var BS=50000;function zd(e,t){let n=[...new Set(fa(e))];if(n.some((o)=>t(LS(o))))return!0;let r=0;while(n.length>0){let o=n.pop()??"",i=$S(o);if(!i)return!0;if(r+=i.length,r>BS)return!0;if(i.some((s)=>t(s.name)))return!0;n.push(...i.filter((s)=>s.isDirectory()).map((s)=>WS(o,s.name)))}return!1}function $S(e){try{let t=DS(e,{throwIfNoEntry:!1});if(!t)return[];if(!t.isDirectory())return t.isSymbolicLink()?null:[];return NS(e,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function fa(e){return[...e.entries,...e.directories,...e.hooksDirectories]}function Wo(e,t){let n=Ld(t,e);return n===""||!/^\.\.(?:[\\/]|$)/.test(n)&&!Nd(n)}function Go(e){return process.platform==="win32"?e.toLowerCase():e}function US(e,t,n,r,o){if(hr(e))return null;let i=vt([...e],r);if(P(i[0]??"").toLowerCase()!=="mv")return null;let s=Lo(i.slice(1)),a=s.sources.find((l)=>FS(pe(l,t.variables),t.cwd,n,r,o));if(a)return a;return s.destination&&zS(pe(s.destination,t.variables),t.cwd,n,r,o)?s.destination:null}import{isAbsolute as $o,normalize as XS,parse as JS,posix as qd,resolve as Vt,sep as ha}from"node:path";import{isAbsolute as HS,join as Bd,normalize as Hd,parse as jS,sep as $d}from"node:path";var VS=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],KS=`
33
+ `;function br(e,t){if(jt(e,t))return!0;if(!e.has("TMPDIR"))return!1;return!ma(e.get("TMPDIR")??"",t)}function vn(e,t){if(e.has("TMPDIR"))return ma(e.get("TMPDIR")??"",t);let n=pa(e,t);if(n===void 0)return!0;return ma(n,t)}function pa(e,t){return Vd(e,t,"TMPDIR")}function ma(e,t){if(!e)return!1;if(YS(e))return!1;return En(e,t)}function jt(e,t){let n=Vd(e,t,"IFS");return n!==void 0&&n!==""&&n!==KS}function En(e,t){let n=Fo(e,t.paths);if(n===null)return!1;return jd(t).some((r)=>xn(n,r))}function Bo(e,t){let n=Fo(e,t.paths);if(n===null)return!1;return jd(t).some((r)=>zo(r)===zo(n))}var Ud=new WeakMap;function jd(e){let t=Ud.get(e);if(t)return t;let n=qS(e);return Ud.set(e,n),n}function qS(e){let t=VS.map((r)=>Fo(r,e.paths)??Hd(r)),n=Fo(e.tmpdir,e.paths);if(!n)return t;if(process.platform==="win32")return[...t,n];if(process.platform==="darwin"&&ZS(n))return[...t,n];return t}function YS(e){return/[\s$`*?[]/.test(e)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(e)||/[+@!]\([^)]*\)/.test(e)}function Vd(e,t,n){return e.has(n)?e.get(n):t.env.get(n)}function ZS(e){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(e)}function Fo(e,t){try{let n=Hd(e);if(!HS(n))return n;let r=jS(n).root,o=n.slice(r.length).split(/[\\/]+/).filter(Boolean),i=r;for(let s=0;s<o.length;s++){let a=Bd(i,o[s]??"");if(t.entryKind(a)==="missing")return Bd(a,...o.slice(s+1));let l=t.realpath(a);if(l===null)return null;i=l}return i}catch{return null}}function xn(e,t){let n=zo(e),r=zo(t);if(n===r)return!0;let o=r.endsWith($d)?r:`${r}${$d}`;return n.startsWith(o)}function zo(e){return process.platform==="win32"?e.toLowerCase():e}var QS=process.platform==="win32",Kd=64,ev=16384;function Cr(e,t,n,r){if(e.kind==="temp_target")return null;let o=r[e.kind];if(e.kind==="dynamic_target"&&!ee(n,o.id,t.strict))return null;if(e.kind==="within_anchored_cwd"&&!ee(n,o.id,t.paranoid))return null;return v(o.id,o.reason)}function Sr(e){let t=Lu(e,Kd,Kd,ev);return{expandedTargets:t&&"words"in t?t.words:void 0,unsafeBraceExpansion:t!==void 0&&"limited"in t,targetIsLiteral:t===void 0&&e.provenance==="literal"&&(e.quoted||e.raw!==e.text),tmpdirWordSplittingProtected:tv(e)}}function tv(e){let t=e.parts.filter((n)=>n.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(n.raw));return t.length>0&&t.every((n)=>nv(e.raw,n.span.start-e.span.start))}function nv(e,t){let n=null,r=!1;for(let o=0;o<t;o++){let i=e[o];if(r){r=!1;continue}if(i==="\\"&&n!=="'"){r=!0;continue}if(n===i){n=null;continue}if(n===null&&(i==="'"||i==='"'))n=i}return n==='"'}function xt(e){let t=e.environment.home,n=e.environment.paths,r=e.budget??Ae();return{anchoredCwd:e.originalCwd??e.cwd??null,resolvedCwd:e.cwd??null,strict:e.strict??!1,paranoid:e.paranoid??!1,trustTmpdirVar:e.allowTmpdirVar??!0,posixShell:e.posixShell??!1,tmpdirWordSplittingUnsafe:e.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:e.trustedTmpdirValue??e.allowTmpdirVar??!0,environment:e.environment,allowRoots:lv(e.allowPaths,t,n,r),protectedGitMetadata:e.protectedGitMetadata,budget:r}}function Be(e,t,n={}){let r=n.targetIsLiteral??!1;if(!r&&t.tmpdirWordSplittingUnsafe&&!n.tmpdirWordSplittingProtected&&uv(e))return{kind:"outside_anchored_cwd"};let o=!r&&Zd(e,t.posixShell);if(Je(e))return{kind:"outside_anchored_cwd"};if(ya(e,r))return{kind:"root_or_home_target"};if(ov(e,t,r))return{kind:"root_or_home_target"};if(t.resolvedCwd&&Ht(e,t.resolvedCwd,t.protectedGitMetadata,!0,t.environment,t.budget,!t.posixShell))return{kind:"git_metadata_target"};if(iv(e,t.trustTmpdirVar,t.posixShell,o,r,n.tmpdirWordSplittingProtected??!1,t.trustedTmpdirValue,t.environment))return{kind:"temp_target"};if(o)return{kind:"dynamic_target"};if(cv(e,t,r))return{kind:"temp_target"};let i=t.anchoredCwd;if(i){if(!n.skipHomeCwd&&pv(i,t.environment.home,t.environment.paths,t.budget))return{kind:"home_cwd_target"};if(!n.skipCwdSelf&&[t.resolvedCwd??i,i].some((s)=>gv(e,t.resolvedCwd??i,t.environment.paths,t.budget,s)))return{kind:"cwd_self_target"};if(hv(e,i,t.resolvedCwd??i,o,r,t.environment.paths,t.budget))return{kind:"within_anchored_cwd"}}if(rv(e,t,o))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function rv(e,t,n){let r=e.trim();if(n||!t.resolvedCwd||!t.anchoredCwd||!r)return!1;if($o(r)||r.startsWith("~"))return!1;if(ba(r))return!1;if(Xd(t.resolvedCwd,t.anchoredCwd,t.environment.paths,t.budget))return!1;return En(Vt(t.resolvedCwd,r),t.environment)}function Yd(e,t,n={}){let{containmentTarget:r,...o}=n;if(Be(e,t,o).kind!=="temp_target")return!1;let i=e.trim();if(av(i))return!1;if(Bo(i,t.environment))return!1;return![t.anchoredCwd,t.resolvedCwd].some((s)=>Xd(r??i,s,t.environment.paths,t.budget))}function ya(e,t=!1){let n=e.trim(),r=qd.normalize(n),o=n.replace(/\\/g,"/"),i=r==="/"?r:r.replace(/\/+$/,"");if(i==="/"||i.startsWith("/")&&i.slice(1).split("/").every((s)=>/^\*+$/.test(s)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(o)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(o))return!0;if(!t&&(r==="~"||r==="~/"||r==="~/*"))return!0;if(!t&&(r==="$HOME"||r==="$HOME/"||r==="$HOME/*"))return!0;if(!t&&(r==="${HOME}"||r==="${HOME}/"||r==="${HOME}/*"))return!0;return!1}function ov(e,t,n){let r=e.trim(),o=n?r:r==="*"?".":r.endsWith("/*")?r.slice(0,-2):r;if(!o)return!1;try{let i=$o(o)?o:t.resolvedCwd?Vt(t.resolvedCwd,o):null;if(!i)return!1;let s=he(D(i,t.environment.paths,t.budget));if(s===JS(s).root)return!0;return s===he(D(t.environment.home,t.environment.paths,t.budget))}catch{return!1}}function he(e){let t=XS(e);if(QS){if(t=t.replace(/\//g,"\\").toLowerCase(),t.length>3&&t.endsWith("\\"))t=t.slice(0,-1);return t}if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);return t}function iv(e,t,n,r,o,i,s,a){let l=e.trim();if(ba(l))return!1;if(!r&&En(l,a))return!0;return(t||i&&s)&&n&&!o&&sv(l,n)}function sv(e,t){return["$TMPDIR","${TMPDIR}"].some((n)=>{if(e===n)return!0;if(!e.startsWith(`${n}/`))return!1;return!Zd(e.slice(n.length+1),t)})}function av(e){let t=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(e);if(!t)return!1;return qd.normalize(`/${t[1]??""}`)==="/"}function ba(e){return e.split(/[\\/]+/).includes("..")}function lv(e,t,n,r){if(!e?.length)return[];return e.flatMap((o)=>{let i=Xn(o.trim(),t);if(!$o(i))return[];try{let s=D(i,n,r);if(Jn(s,D(t,n,r)))return[];return[he(s)]}catch{return[]}})}function cv(e,t,n){if(t.allowRoots.length===0)return!1;let r=e.trim();if(ba(r))return!1;let o=n?r:Xn(r,t.environment.home),i=t.resolvedCwd??t.anchoredCwd,s=$o(o)?o:i?Vt(i,o):null;if(!s)return!1;try{let a=he(D(s,t.environment.paths,t.budget));return t.allowRoots.some((l)=>a===l||a.startsWith(l.endsWith(ha)?l:`${l}${ha}`))}catch{return!1}}function uv(e){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(e)}function Zd(e,t=!1){return e.includes("$")||e.includes("`")||dv(e)||t&&fv(e)}function dv(e){let t=!1;for(let n of e){if(t){t=!1;continue}if(n==="\\"){t=!0;continue}if(n==="*"||n==="?"||n==="[")return!0}return!1}function fv(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(t){t=!1;continue}if(r==="\\"){t=!0;continue}if(r==="{"&&mv(e,n)||(r==="+"||r==="@"||r==="!")&&e[n+1]==="(")return!0}return!1}function mv(e,t){let n=e.indexOf("}",t+1);if(n===-1)return!1;let r=e.slice(t+1,n);return r.includes(",")||r.includes("..")}function pv(e,t,n,r){try{return he(D(e,n,r))===he(D(t,n,r))}catch{try{return he(e)===he(t)}catch{return!1}}}function gv(e,t,n,r,o=t){if(o===t&&(e==="."||e==="./"||e===".\\"))return!0;try{return he(D(Vt(t,e),n,r))===he(D(o,n,r))}catch{try{return he(Vt(t,e))===he(o)}catch{return!1}}}function hv(e,t,n,r,o,i,s){let a=n??t;if(!o&&(e.startsWith("~")||e.startsWith("$HOME")||e.startsWith("${HOME}")))return!1;if(r)return!1;if(e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e))try{return ga(e,t,i,s)}catch{return!1}if(e.startsWith("./")||e.startsWith(".\\")||!e.includes("/")&&!e.includes("\\"))try{return ga(Vt(a,e),t,i,s)}catch{return!1}if(e.startsWith("../"))return!1;try{return ga(Vt(a,e),t,i,s)}catch{return!1}}function ga(e,t,n,r){try{return Jd(D(e,n,r),D(t,n,r))}catch{return!1}}function Xd(e,t,n,r){if(!t)return!1;try{return Jd(D(t,n,r),D(e,n,r))}catch{return!0}}function Jd(e,t){let n=he(e),r=he(t);return n.startsWith(`${r}${ha}`)||n===r}var yv=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),Qd="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",bv="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.",ef="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",tf="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",Cv="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",Sv="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",vv={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:tf},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:ze},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:ef},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:Cv},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:Qd},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:bv},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:Qd}};function nf(e,t,n){return Ev(e.words.map((r)=>({kind:"word",text:r.text,dynamic:r.provenance!=="literal"})),t,xt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths}),n.policy)}function Ev(e,t,n,r){let o=e.filter((l)=>l.kind==="word"),i=Rv(o),s=o[i];if(!s||!yv.has(Mv(s.text)))return null;let a=xv(o.slice(i+1));if(a.whatIfProtected)return null;if(ee(r,"powershell.remove-item-pipeline-dynamic-target",n.strict)&&t&&(a.targets.length===0||a.recursive))return v("powershell.remove-item-pipeline-dynamic-target",Sv);for(let l of a.targets)if(!Je(l.text)&&ya(Sa(l.text)))return v(a.recursive&&a.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",tf);for(let l of a.targets)if(n.resolvedCwd&&Ht(Sa(l.text),n.resolvedCwd,n.protectedGitMetadata,a.recursive,n.environment,n.budget,!0))return v("powershell.remove-item-git-metadata",ze);if(!a.recursive||!a.force)return null;if(ee(r,"powershell.remove-item-recursive-force-dynamic-target",n.strict)&&(a.hasDynamicTarget||a.targets.length===0))return v("powershell.remove-item-recursive-force-dynamic-target",ef);for(let l of a.targets){let c=Cr(Be(Sa(l.text),n),n,r,vv);if(c)return c}return null}function xv(e){let t=[],n=!1,r=!1,o=!1,i=!1,s=!1;for(let a=0;a<e.length;a++){let l=e[a];if(!l||l.kind!=="word")continue;if(_v(l))continue;if(s){t.push(Ca(l)),i=i||l.dynamic;continue}if(l.text==="--"){s=!0;continue}let c=Pv(l.text);if(!c){t.push(Ca(l)),i=i||l.dynamic;continue}if(Av(c.name)){let u=c.value?wv(c.value,l):e[++a];if(u?.kind==="word"){t.push(Ca(u)),i=i||u.dynamic;continue}i=!0;continue}if(Iv(c.name)){n=!0;continue}if(Tv(c.name)){r=!0;continue}if(kv(c.name))o=Ov(c.value)}return{targets:t,recursive:n,force:r,whatIfProtected:o,hasDynamicTarget:i}}function Rv(e){let t=e[0];if(t?.kind==="word"&&t.text==="&"||t?.text===".")return e.length>1?1:0;return 0}function Ca(e){return{text:e.kind==="word"?e.text:"",dynamic:e.kind==="word"&&e.dynamic}}function _v(e){return e.kind==="word"&&e.text===","}function Sa(e){let t=e.replace(/\\/g,"/"),n=/^(?:\$env:(?:userprofile|home)|\$home|\$\{home\})(?=$|\/)/i.exec(t);return n?`$HOME${t.slice(n[0].length)}`:t}function wv(e,t){return{kind:"word",text:e,dynamic:t.kind==="word"&&(t.dynamic||e.includes("$"))}}function Pv(e){if(!e.startsWith("-")||e==="-")return null;let t=e.slice(1),n=t.indexOf(":");if(n===-1)return{name:t.toLowerCase()};return{name:t.slice(0,n).toLowerCase(),value:t.slice(n+1)}}function Av(e){return"path".startsWith(e)||"literalpath".startsWith(e)}function Iv(e){return"recurse".startsWith(e)}function Tv(e){return e.length>=2&&"force".startsWith(e)}function kv(e){return e==="wi"||"whatif".startsWith(e)}function Ov(e){if(e===void 0||e==="")return!0;let t=e.toLowerCase();return t==="$true"||t==="true"}function Mv(e){return e.toLowerCase()}var Rn="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",Uo="Unsupported heredoc syntax",vr="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.",rf="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var Dv=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),Nv=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),Lv=new Set(["-o","--output","--query","--subscription"]),Wv=new Set;function of(e){if(e==="aws")return Dv;if(e==="gcloud")return Nv;if(e==="az")return Lv;return Wv}var Gv=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),Fv=new Set;function sf(e){if(e==="git")return Ee;if(e==="docker")return Gv;return Fv}function it(e,t){if(e.length===0||t.length===0)return null;let n=O(e[0]??""),r=fe(e);for(let o of t){if(!$v(n,o.command))continue;if(o.match){if(zv(n,e,o.match))return af(o);continue}if(!Uv(n,e,o.subcommand))continue;if(jv(e,new Set(o.block_args),r))return af(o)}return null}function af(e){return{id:`custom.${e.name}`,reason:`[${e.name}] ${e.reason}`,intent:e.intent??"manual_only"}}function zv(e,t,n){let r=t.slice(1);if(n.exclude_args?.some((o)=>r.includes(o)))return!1;if(n.any_args&&!n.any_args.some((o)=>r.includes(o)))return!1;return Bv(r,n.command_path,of(e))}function Bv(e,t,n){let r=0,o=!1;for(let i of e){if(r>=t.length)return!0;if(o){o=!1;continue}if(i.startsWith("-")){o=!i.includes("=")&&n.has(i);continue}if(i!==t[r])return!1;r++}return r>=t.length}function $v(e,t){return e===O(t)}function Uv(e,t,n){if(!n)return!0;return lf(t,1,n,sf(e))}function lf(e,t,n,r){let o=!1;for(let i=t;i<e.length;i++){let s=e[i];if(!s)continue;if(o){o=!1;continue}if(s==="--"){let a=e[i+1];if(a&&!a.startsWith("-"))return a===n;return!1}if(r.has(s)){o=!0;continue}if(s.startsWith("-")){if(!s.includes("=")&&Hv(e,i,n,r))return!0;continue}return s===n}return!1}function Hv(e,t,n,r){let o=e[t+1];if(!o||o.startsWith("-"))return!1;return lf(e,t+2,n,r)}function jv(e,t,n){return e.some((r)=>t.has(r))||[...n].some((r)=>t.has(r))}var Vv=new Set(["-e","--source"]),Kv=new Set(["-F","-v","--assign","--field-separator"]),cf=new Set(["-f","--file"]),qv=new Set(["print","printf","return"]),uf=[{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"}],Yv="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 df(e,t,n){let r=!1;for(let o of Zv(e)){let i=Xv(o,n);if(!i)continue;for(let s of i.commands){let a=t(s);if(a)return a;if(s.includes("{}")||/[$`]/.test(s))r=!0}r||=i.dynamic}return r?v("awk.system-dynamic",Yv):null}function Ea(e){let t=[],n=!1,r=!1,o=!0,i=!0;for(let s=1;s<e.length;s++){let a=e[s];if(a===void 0)break;if(o&&a==="--"){o=!1;continue}if(o&&Vv.has(a)){n=!0;let l=e[s+1];if(i&&=l!==void 0,l!==void 0)t.push({tokenIndex:s+1,kind:"inline-code",value:l});s++;continue}if(o&&a.startsWith("--source=")){n=!0,t.push({tokenIndex:s,kind:"inline-code",value:a.slice(9)});continue}if(o&&a.startsWith("-e")&&a.length>2){n=!0,t.push({tokenIndex:s,kind:"inline-code",value:a.slice(2)});continue}if(o&&(Kv.has(a)||cf.has(a))){let l=e[s+1];if(i&&=l!==void 0,cf.has(a)){if(r=!0,l!==void 0)t.push({tokenIndex:s+1,kind:"program-file",value:l})}s++;continue}if(o&&(a.startsWith("-F")||a.startsWith("-v")&&a.slice(2).includes("=")))continue;if(o&&a.startsWith("-f")&&a.length>2){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(2)});continue}if(o&&(a.startsWith("--assign=")||a.startsWith("--field-separator=")))continue;if(o&&a.startsWith("--file=")){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(7)});continue}if(o&&a.startsWith("-")&&a!=="-")continue;if(!n&&!r)t.push({tokenIndex:s,kind:"main-program",value:a});return{sources:t,optionsOpen:!1}}return{sources:i?t:[],optionsOpen:o&&i}}function xr(e){return Ea(e).sources}function Zv(e){return xr(e).filter((t)=>t.kind!=="program-file").map((t)=>t.value)}function Xv(e,t){_e(t,e);let n=e.includes("system")?xa(e,t):null,r=Jv(e,t);if(!n&&!r)return null;return{dynamic:!!n?.dynamic||!!r?.dynamic,commands:[...n?.commands??[],...r?.commands??[]]}}function xa(e,t){_e(t,e);let n=[],r=!1,o=!1,i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){i=jo(e,i,s)?.endIndex??i+1;continue}if(s==="#"){i=ff(e,i+1);continue}if(s==="/"&&mf(e,i)){i=pf(e,i+1)??i+1;continue}if(!e.startsWith("system",i)){i++;continue}let a=i;if(i+=6,Er(e[a-1])||Er(e[i]))continue;let l=Ho(e,i);if(e[l]!=="(")continue;l=Ho(e,l+1);let c=e[l];if(c!=='"'&&c!=="'"){r=!0,o=!0;continue}let u=jo(e,l,c);if(!u){r=!0,o=!0;continue}if(l=Ho(e,u.endIndex),r=!0,e[l]!==")"){o=!0,i=u.endIndex;continue}n.push(u.value),i=l+1}if(!r)return null;return{dynamic:o,commands:n}}function Jv(e,t){_e(t,e);let n=[],r=!1,o=!1,i=0,s=0,a=null,l=null,c=0;while(i<e.length){let u=e[i];if(!u)break;if(u==='"'||u==="'"){let m=jo(e,i,u);if(m&&c===s)l={...m,startIndex:i};c=m?.endIndex??i+1,i=m?.endIndex??i+1;continue}if(u==="#"){i=ff(e,i+1),s=i,a=null,l=null,c=i;continue}if(u==="/"&&mf(e,i)){let m=pf(e,i+1);c=m??i+1,i=m??i+1;continue}if(`;
34
+ {}`.includes(u)){i++,s=i,a=null,l=null,c=i;continue}if(a===null&&(va(e,i,"print")||va(e,i,"printf")))a=i;if(u!=="|"||e[i-1]==="|"||e[i+1]==="|"){if(!/\s/.test(u))c=i+1;i++;continue}let f=e[i+1]==="&"?i+2:i+1,d=Ho(e,f);if(va(e,d,"getline")){o=!0;let m=tE(s,l,c);if(r||=m===null,m!==null)n.push(m);c=f,i=f;continue}if(rE(s,a)){o=!0;let m=eE(e,d);if(!m){r=!0,c=f,i=f;continue}if(!Qv(e,m.endIndex)){r=!0,c=m.endIndex,i=m.endIndex;continue}n.push(m.value),c=m.endIndex,i=m.endIndex;continue}c=f,i++}if(!o)return null;return{dynamic:r,commands:n}}function Er(e){return!!e&&/[A-Za-z0-9_]/.test(e)}function Ho(e,t){let n=t;while(/\s/.test(e[n]??""))n++;return n}function Qv(e,t){let n=t;while(/[\t\f\v\r ]/.test(e[n]??""))n++;let r=e[n];return!r||`;
35
+ }#`.includes(r)}function jo(e,t,n){let r="",o=!1;for(let i=t+1;i<e.length;i++){let s=e[i];if(!s)break;if(o){let a=nE(e,i);if(!a)return null;r+=a.value,i=a.endIndex,o=!1;continue}if(s==="\\"){o=!0;continue}if(s===n)return{value:r,endIndex:i+1};r+=s}return null}function eE(e,t){let n=e[t];if(n!=='"'&&n!=="'")return null;return jo(e,t,n)}function tE(e,t,n){if(!t)return null;return t.startIndex>=e&&t.endIndex===n?t.value:null}function nE(e,t){let n=e[t];if(!n)return null;if(n==="x"){let o=e.slice(t+1,t+3);if(!/^[0-9A-Fa-f]{2}$/.test(o))return null;return{value:String.fromCharCode(Number.parseInt(o,16)),endIndex:t+2}}if(/[0-7]/.test(n)){let o=/^[0-7]{1,3}/.exec(e.slice(t));if(!o)return null;return{value:String.fromCharCode(Number.parseInt(o[0],8)),endIndex:t+o[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
36
+ `,r:"\r",t:"\t",v:"\v"}[n]??n,endIndex:t}}function va(e,t,n){return e.startsWith(n,t)&&!Er(e[t-1])&&!Er(e[t+n.length])}function rE(e,t){return t!==null&&t>=e}function ff(e,t){let n=e.indexOf(`
37
+ `,t);return n===-1?e.length:n+1}function mf(e,t){let n=oE(e,t);if(n===-1)return!0;if("{([,;!~=".includes(e[n]??""))return!0;let r=n;while(Er(e[r-1]))r--;return qv.has(e.slice(r,n+1))}function oE(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function pf(e,t){let n=!1;for(let r=t;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="/")return r+1}return null}var iE="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",sE="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",aE="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function gf(e){return e==="dd"||e==="shred"||e==="mkfs"||e.startsWith("mkfs.")}function hf(e,t){let n=t.slice(1);if(e==="dd"&&n.some((r)=>/^of=\/dev\/.+/.test(r)))return v("dd.device-write",iE);if((e==="mkfs"||e.startsWith("mkfs."))&&n.some((r)=>r.startsWith("/dev/")))return v("mkfs.device",sE);if(e==="shred"&&n.length>0)return v("shred.target",aE);return null}var lE=new Set(["sudo","env","command","builtin"]),cE=new Set(["caffeinate","exec","nice","nohup","setsid","stdbuf","time","timeout"]);function Vo(e,t){let n=e[0];if(!n||!yf(P(n),t))return null;let r=P(n),o=e[1]==="--"?2:1,i=uE(e,o,r,t),s=i[0];if(s===void 0)return null;return{wrapper:r,tokens:e.slice(s),childIndex:s,alternativeChildIndices:i.slice(1)}}function uE(e,t,n,r){let o=e[1]==="--",i=[];for(let s=t;s<e.length;s++){let a=e[s];if(!a)continue;let l=P(a)!==n&&dE(a,r);if(l)i.push(s);if(!l&&Yr.has(O(a)))break;if(o)break}return i}function dE(e,t){let n=P(e),r=O(e);return r==="git"||n==="busybox"||Kt(e)||as.has(n)||gf(r)||yf(n,t)||Y.has(r)||e==="$SHELL"||De(r)||Ie.has(r)||t.rules.some((o)=>o.command===n)}function yf(e,t){return cE.has(e)||t.transparentWrappers.includes(e)}function Kt(e){return lE.has(e.toLowerCase())}function qt(e,t){return{embedded:!1,cwd:e.cwd,originalCwd:t.originalCwd,effectiveCwd:e.cwd,envAssignments:e.envAssignments,allowTmpdirVar:t.allowTmpdirVar,worktreeMode:t.worktreeMode,wrappedByTransparent:!1}}function $e(e,t){let n=t.policy??{rules:[],transparentWrappers:[]};return Ko([...e],t.environment,t.cwd,t.cwd,new Map,new Map(t.envAssignments??[]),n,{iterations:0},!1)}function*Ko(e,t,n,r,o,i,s,a,l){let c=ko(e,t,n,i);for(let[m,g]of c.envAssignments)i.set(m,g),o.set(m,g);let{tokens:u,cwd:f}=c;if(c.envSplitValues){let m=To(c.envSplitValues,u);if(!m)throw new W("derivedCommandShape");Ra(a),yield*Ko(m,t,f,r,o,i,s,a,l);return}if(Kt(u[0]??""))throw new W("wrapperPeelIterations");let d=Vo(u,s);if(d){for(let m of[d.childIndex,...d.alternativeChildIndices])Ra(a),yield*Ko(m===d.childIndex?d.tokens:u.slice(m),t,f,r,new Map(o),new Map(i),s,a,!0);return}if(mE(u)){Ra(a),yield*Ko(u.slice(1),t,f,r,o,i,s,a,l);return}yield fE(u,f,r,o,i,l)}function fE(e,t,n,r,o,i){return{tokens:e,cwd:t===null?void 0:t??n,wrapperCwd:t,wrapperEnvAssignments:r,envAssignments:o,head:P(e[0]??"").toLowerCase(),wrappedByTransparent:i}}function Ra(e){if(e.iterations>=K.wrapperPeelIterations.cap)throw new W("wrapperPeelIterations");e.iterations++}function mE(e){return P(e[0]??"").toLowerCase()==="busybox"&&e.length>1}function _a(e,t){let n=[],r=t;while(r<e.length){let o=e[r];if(o===void 0||o===":::")break;n.push(o),r++}return{markerIndex:r<e.length&&e[r]===":::"?r:-1,templateTokens:n}}function st(e){let t=!1,n=!1;for(let r of e){if(r==="--")break;if(r==="-r"||r==="-R"||wa(r,"recursive")){t=!0;continue}if(r==="-f"||wa(r,"force")){n=!0;continue}if(r.startsWith("-")&&!r.startsWith("--")){if(r.includes("r")||r.includes("R"))t=!0;if(r.includes("f"))n=!0}}return t&&n}function qo(e){let t=e.indexOf("--");return e.slice(1,t===-1?void 0:t).some((n)=>wa(n,"recursive")||/^-[A-Za-z]+$/.test(n)&&/[rR]/.test(n.slice(1)))}function wa(e,t){return e.length>2&&e.startsWith("--")&&t.startsWith(e.slice(2))}var pE=["--init-file","--rcfile"],gE=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function Ue(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n)continue;if(n==="-c")return bf(e,t,!0);if(n.startsWith("-")&&n.includes("c")&&!n.startsWith("--")){let r=bf(e,t,!1);if(r!==null)return r}}return null}function at(e){let t=P(e[0]??"").toLowerCase();if(t==="zsh"||t==="ksh")return xe(e).syntaxCheck;let n=!1;for(let r of e.slice(1)){if(r==="--")return n;if(r.startsWith("+")&&!r.startsWith("++")){if(r.slice(1).includes("n"))n=!1;continue}if(!r.startsWith("-")||r.startsWith("--"))return n;let o=r.slice(1);if(o.includes("n"))n=!0;if(o.includes("c"))return n}return n}function bf(e,t,n){if(e[t+1]==="--")return e[t+2]||null;let r=e[t+1];if(!r||!n&&r.startsWith("-"))return null;return r}function Cf(e){let t=P(e[0]??"").toLowerCase(),n=hE(e,t),r=gE.get(t)??null,o=n.argvSource?.kind!=="absent";return{argvSource:t==="bash"?n.argvSource:null,argvSourceApplies:t==="bash"&&n.interactive&&n.argvSource?.kind==="literal",envName:r,envSourceApplies:o&&(r==="BASH_ENV"?!n.interactive:r==="ENV"&&n.interactive)}}function hE(e,t){let n=xe(e),r=n.commandIndex??n.scriptIndex??e.length,o=[],i=!1,s=!0;for(let a=1;a<r;a++){let l=e[a];if(l===void 0||l==="--"||l==="-"||l[0]!=="-"&&l[0]!=="+")break;if(l.startsWith("--")){if(t==="bash"&&s?pE.find((d)=>l===d):void 0){let d=e[a+1];o.push(d===void 0?{kind:"absent"}:{kind:"literal",value:d}),a++;continue}let f=l.split("=",1)[0]??l;if(t==="bash"&&is.has(f)&&!l.includes("="))a++;continue}if(t==="bash")s=!1;let c=ss(t,l,e[a+1],"startup");if(c.interactive)i=l[0]==="-";a+=c.followingValues}return{argvSource:o.at(-1)??null,interactive:i}}var yE="find -delete permanently removes files. Use -print first to preview.",bE="find -exec rm -rf is dangerous. Use explicit file list instead.",CE=new Set(["-exec","-execdir","-ok","-okdir"]),SE=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((e)=>[e,1]),["-fprintf",2]]);function Sf(e,t){let n=e.map(_),r=vE(e,n,t);if(r)return r;if(Yo(n,1)&&!PE(e,n,t)){let s=w(v("find.delete",yE),t.policy);if(s)return s}let o=t.budget??Ae(),i=0;while(i<n.length){let s=n[i],a=lt(s??"");if(a>0){i+=a+1;continue}if(!qe(s)){i++;continue}o.charge("derivedTokens",n.length-i-1);let l=_n(n,i);i=l.nextIndex;let c=IE(l.tokens,t.environment);if(c){let m=w(c,t.policy);if(m)return m}let u=s==="-execdir"||s==="-okdir",f=t.analyzeTokens?.(l.tokens,u?null:t.cwd)??null,d=f?.id.startsWith("custom.")?f:w(f,t.policy);if(d)return d}return null}function vE(e,t,n){if(!Yo(t,1)&&!Pa(t,n.environment))return null;let o=Rr(e)??q(["."]),i=xt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let s of o){let a=Sr(s);for(let l of a.expandedTargets??[_(s)]){let c=Be(l,i,{targetIsLiteral:a.expandedTargets!==void 0||a.targetIsLiteral,tmpdirWordSplittingProtected:a.tmpdirWordSplittingProtected});if(c.kind==="root_or_home_target")return v("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(c.kind==="git_metadata_target"&&!EE(e,i.protectedGitMetadata,n.environment))return v("find.delete-git-metadata",ze)}}if(wE(t)&&i.resolvedCwd&&Gd(o.map(_),i.resolvedCwd,i.protectedGitMetadata,i.environment,i.budget))return v("find.delete-git-metadata",ze);return null}function EE(e,t,n){if(!t)return!1;let r=e.map(_),o=[],i=!1,s=Rr(e)?.at(-1),a=s?e.indexOf(s)+1:1;while(a<r.length){let l=r[a]??"";if(qe(l)){let c=_n(r,a),u=vt([...c.tokens],n),f=qo(u),d=Y.has(P(u[0]??"").toLowerCase()),m=c.tokens.some((p)=>p!=="{}"&&p.includes("{}")),g=(l==="-execdir"||l==="-okdir")&&u.slice(1).some((p)=>p!=="{}"&&!p.startsWith("-"));if(f||d||m||g)return!1;i=!0,a=c.nextIndex;continue}if(l==="-delete"){i=!0,a++;continue}if(l==="-name"||l==="-iname"){let c=e[a+1];if(!(c?.provenance==="literal"&&!/[[\\]/.test(c.text)))return!1;if(!i)o.push(RE(c.text,l==="-iname"));a+=2;continue}if(!xE.has(l))return!1;a+=1+lt(l)}return o.length>0&&!zd(t,(l)=>o.every((c)=>c.test(l)))}var xE=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function RE(e,t){let n=e.replace(/[*?]|[.+^${}()|\]/]/g,(r)=>r==="*"?".*":r==="?"?".":`\\${r}`);return new RegExp(`^${n}$`,t?"isu":"su")}var _E=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function Pa(e,t){let n=0;while(n<e.length){if(!qe(e[n])){n++;continue}let r=_n(e,n),o=vt([...r.tokens],t),i=P(o[0]??"").toLowerCase(),s=Y.has(i)&&_E.test((Ue(o)??"").replace(/["'\\]/g,""));if((i==="rm"||i==="rmdir"||s)&&o.some((l)=>l.includes("{}")))return!0;n=r.nextIndex}return!1}function wE(e){return e.some((t,n)=>{if(!["-name","-iname"].includes(t))return!1;return e[n+1]?.toLowerCase()==="hooks"})}function PE(e,t,n){if(t.includes("-L")||t.includes("-f")||t.includes("-follow"))return!1;let r=Rr(e);if(!r)return!1;let o=n.envAssignments??new Map,i=pa(o,n.environment),s=n.trustedTmpdirValue??vn(o,n.environment),a=n.allowTmpdirVar??!br(o,n.environment),l={environment:n.environment,protectedGitMetadata:n.protectedGitMetadata,cwd:n.cwd,originalCwd:n.originalCwd,strict:n.strict,allowTmpdirVar:a&&s&&Boolean(i),allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:n.tmpdirWordSplittingUnsafe??jt(o,n.environment),trustedTmpdirValue:s,budget:n.budget},c=xt(l),u=xt({...l,cwd:n.originalCwd??n.cwd}),f=n.originalCwd&&n.environment.paths.realpath(n.originalCwd),d=n.cwd&&n.environment.paths.realpath(n.cwd),m=f&&d&&!xn(d,f)?n.cwd:void 0;return r.every((g)=>{let p=Sr(g);if(p.unsafeBraceExpansion)return!1;return(p.expandedTargets??[_(g)]).every((h)=>{let y=/^\.\/*$/.test(h)?m:void 0,C=y??h,b={targetIsLiteral:p.expandedTargets!==void 0||p.targetIsLiteral,tmpdirWordSplittingProtected:p.tmpdirWordSplittingProtected};if(!ee(n.policy,"rm.recursive-force-paranoid",n.paranoid??!1)&&!y&&Be(C,c,b).kind==="within_anchored_cwd")return!0;return Yd(C,y?u:c,{...b,containmentTarget:AE(C,i)})})})}function AE(e,t){if(!t)return e;return e.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>t)}function Rr(e){let t=(o)=>{let i=e[o];return i?_(i):void 0},n=1;while(t(n)==="-H"||t(n)==="-P")n++;if(t(n)==="--")n++;let r=[];while(n<e.length){let o=t(n),i=e[n];if(!o||!i||o.startsWith("-")||["!","(",")"].includes(o))break;r.push(i),n++}return r.length>0?r:null}function IE(e,t){let n=St([...e],t);if(n.length===0)return null;let r=P(n[0]??"");if(r==="busybox"&&n.length>1)n=n.slice(1),r=P(n[0]??"");if(r==="rm"&&st(n))return v("find.exec-rm-recursive-force",bE);return null}function _n(e,t){let n=t+1;while(n<e.length&&e[n]!==";"&&!(e[n]==="+"&&e[n-1]==="{}"))n++;return{tokens:e.slice(t+1,n),nextIndex:Math.min(n+1,e.length)}}function Yo(e,t){let n=t;while(n<e.length){let r=e[n];if(!r){n++;continue}if(qe(r)){n=_n(e,n).nextIndex;continue}let o=lt(r);if(o>0){n+=o+1;continue}if(r==="-delete")return!0;n++}return!1}function lt(e){return SE.get(e)??(/^-newer[A-Za-z]{2}$/.test(e)?1:0)}function qe(e){return e!==void 0&&CE.has(e)}import{resolve as nR}from"node:path";function _r(e){let t=Ne(e,"posix");if(t.status!=="complete"||t.nodes.length!==1)return null;let n=t.nodes[0];if(n?.kind!=="command")return null;if(n.redirections.length>0||n.nested.length>0)return null;if(n.words.some((r)=>r.provenance==="command-substitution"))return null;return n.words.map((r)=>r.text)}var TE=5,Aa="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 ie(e){let t=e.indexOf("--");if(t===-1)return{index:-1,before:e,after:[]};return{index:t,before:e.slice(0,t),after:e.slice(t+1)}}function Ef(e,t,n){let r=Zo(e,t,n),o=kE(r.entries);if(o.size===0)return{blockedReason:r.blockedReason,expanded:!1,tokens:e};let i=e,s=!1;for(let a=0;a<TE;a++){let{subcommand:l,rest:c}=we(i),u=l?.toLowerCase();if(!u||!o.has(u))return{blockedReason:r.blockedReason,expanded:s,tokens:i};let f=o.get(u),d=LE(f);if(d===null||d.length===0)return{blockedReason:Aa,expanded:!0,tokens:i};i=["git",...d,...c],s=!0}return{blockedReason:Aa,expanded:!0,tokens:i}}function xf(e,t,n){return Zo(e,t,n).entries.some((r)=>r.key.toLowerCase()==="core.sshcommand")}function we(e){if(e.length===0)return{subcommand:null,rest:[]};let t=e[0];if((t?P(t).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let r=1;while(r<e.length){let o=e[r];if(!o)break;if(o==="--"){let i=e[r+1];if(i&&!i.startsWith("-"))return{subcommand:i,rest:e.slice(r+2)};return{subcommand:null,rest:e.slice(r+1)}}if(!o.startsWith("-"))return{subcommand:o,rest:e.slice(r+1)};r+=Ee.has(o)?2:1}return{subcommand:null,rest:[]}}function kE(e){let t=new Map;for(let n of e){let r=n.key.toLowerCase();if(!r.startsWith("alias."))continue;let o=r.slice(6);if(o!=="")t.set(o,n.value)}return t}function Zo(e,t,n){if(e.length===0)return{blockedReason:null,entries:[]};let r=e[0];if((r?P(r).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let i=ME(t,n);return{blockedReason:i.blockedReason,entries:[...i.entries,...OE(e,t,n)]}}function OE(e,t,n){let r=[],o=1;while(o<e.length){let i=e[o];if(!i||i==="--"||!i.startsWith("-"))return r;if(i==="-c"){let s=Ia(e[o+1]);if(s)r.push(s);o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=Ia(i.slice(2));if(s)r.push(s);o++;continue}if(i==="--config-env"){let s=vf(e[o+1],t,n);if(s)r.push(s);o+=2;continue}if(i.startsWith("--config-env=")){let s=vf(i.slice(13),t,n);if(s)r.push(s);o++;continue}if(Ee.has(i)){o+=2;continue}o++}return r}function ME(e,t){let n=DE(e,t),r=NE(e,t);return{blockedReason:n===null||r===null?Aa:null,entries:[...n??[],...r??[]]}}function DE(e,t){let n=rt("GIT_CONFIG_PARAMETERS",e,t);if(n===void 0)return[];let r=[],o=_r(n);if(!o)return null;for(let i of o){let s=Ia(i);if(!s)return null;r.push(s)}return r}function NE(e,t){let n=fd(e,t);if(n.state==="absent")return[];if(n.state==="invalid")return null;let r=[];for(let o=0;o<n.count;o++){let i=rt(`GIT_CONFIG_KEY_${o}`,e,t)?.trim(),s=rt(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i||s===void 0)return null;r.push({key:i,value:s})}return r}function Ia(e){if(!e)return null;let t=e.indexOf("=");return{key:(t===-1?e:e.slice(0,t)).trim(),value:t===-1?void 0:e.slice(t+1)}}function vf(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;return{key:e.slice(0,r).trim(),value:rt(e.slice(r+1),t,n)}}function LE(e){let t=e?.trimStart();if(!t||t.startsWith("!"))return null;return _r(t)}var WE="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",GE="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",FE="git checkout --force discards uncommitted changes. Use 'git stash' first.",zE="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",BE="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",$E="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",UE="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",HE="git switch --force discards uncommitted changes. Use 'git stash' first.",jE="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",VE="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",KE="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",qE="git reset --merge can lose uncommitted changes. Use 'git stash' first.",YE="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",ZE="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.",XE="git push --force destroys remote history. Use --force-with-lease for safer force push.",JE="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",QE="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",ex="git branch -D force-deletes without merge check. Use -d for safe delete.",tx="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",nx="git merge --abort discards merge conflict resolutions. Use 'git status' first.",rx="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",ox="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",ix="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",sx="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",ax="git worktree remove --force can delete uncommitted changes. Remove --force flag.",lx=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),cx=new Set(["--recurse-submodules","--track","-t"]),Ta=new Set(["-b","-B","-U"]),ka=new Set(["-c","-C"]),ux=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function M(e,t){let n=e.split("=",1)[0]??e;return n.length>=4&&t.startsWith(n)&&n.startsWith("--")&&n.slice(2).length>=2}var wn=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function _f(e,t){let{subcommand:n,rest:r}=we(e);if(!n)return null;switch(n.toLowerCase()){case"checkout":return Rt(dx(r,t));case"switch":return Rt(mx(r));case"restore":return Rt(gx(r));case"reset":return yx(r);case"clean":return Rt(Cx(r));case"rm":return Rt(Sx(r));case"push":return Yt(vx(r));case"branch":return Yt(Rx(r));case"stash":return Yt(Ix(r));case"worktree":return Yt(Tx(r));case"rebase":return Rt(_x(r));case"merge":return Rt(wx(r));case"tag":return Yt(Px(r));case"reflog":return Yt(Ax(r));default:return null}}function Rt(e){return e?{...e,localDiscard:!0}:null}function Yt(e){return e?{...e,localDiscard:!1}:null}function dx(e,t){let{index:n,before:r}=ie(e),o=fe(r,{shortOptsWithValue:Ta});if(r.some((a)=>M(a,"--force"))||o.has("-f"))return v("git.checkout-force",FE);for(let a of e){if(a==="-b"||a==="-B"||a==="--orphan")return null;if(M(a,"--pathspec-from-file"))return v("git.checkout-pathspec-from-file",BE)}if(n!==-1){if(r.some((l)=>!l.startsWith("-")))return v("git.checkout-ref-path",zE);return v("git.checkout-double-dash",WE)}let i=px(e);if(i.length>=2)return v("git.checkout-ambiguous",$E);let s=i[0];if(s===void 0||o.has("-d")||o.has("-t")||e.some((a)=>M(a,"--detach")||M(a,"--track")))return null;if(fx(s)||t(s))return v("git.checkout-double-dash",GE);return null}function fx(e){return e==="."||e===".."||/^\.\.?[/\\]/.test(e)||/^([/\\]|[A-Za-z]:[/\\])/.test(e)||e.endsWith("/")||e.startsWith(":")||/[*?[]/.test(e)}function mx(e){let{before:t}=ie(e);if(t.some((r)=>M(r,"--discard-changes")))return v("git.switch-discard-changes",UE);let n=fe(t,{shortOptsWithValue:ka});if(t.some((r)=>M(r,"--force"))||n.has("-f"))return v("git.switch-force",HE);return null}function px(e){let t=[],n=0;while(n<e.length){let r=e[n];if(!r)break;if(r==="--")break;if(!r.startsWith("-")){t.push(r),n++;continue}if(lx.has(r)){n+=2;continue}if(cx.has(r)){let o=e[n+1],i=r==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"];n+=o&&!o.startsWith("-")&&i.includes(o)?2:1;continue}n++}return t}function gx(e){let t=hx(e);if(t.isTerminal||!t.hasPathspec&&!t.hasPatch||!t.hasWorktree)return null;return t.hasExplicitLocation?v("git.restore-worktree",VE):v("git.restore-unstaged",jE)}function hx(e){let t=!1,n=!1,r=!0,o=!1,i=(s)=>{if(!o)r=!1,o=!0;if(s!==void 0)r=s};for(let s=0;s<e.length;s++){let a=e[s];if(a===void 0)break;if(a==="--"){t||=s+1<e.length;break}if(a==="--pathspec-from-file"){t=!0,s++;continue}if(a.startsWith("--pathspec-from-file=")){t=!0;continue}if(a==="-h"||a==="--help"||a==="--version")return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!0};if(a==="--staged"){i();continue}if(a==="--no-staged"){i();continue}if(a==="--worktree"){i(!0);continue}if(a==="--no-worktree"){i(!1);continue}if(a==="--patch"){n=!0;continue}if(a==="--no-patch"){n=!1;continue}if(ux.has(a)){s++;continue}if(a.startsWith("--"))continue;if(a==="-"){t=!0;continue}if(!a.startsWith("-")){t=!0;continue}for(let l=1;l<a.length;l++){let c=a.charAt(l);if(c==="h")return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!0};if(c==="S"){i();continue}if(c==="W"){i(!0);continue}if(c==="p"){n=!0;continue}if(c==="s"||c==="U"){if(l===a.length-1)s++;break}}}return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!1}}function yx(e){let t=null;for(let n of e){if(M(n,"--hard")){t=v("git.reset-hard",KE);break}if(M(n,"--merge")){t=v("git.reset-merge",qE);break}}if(!t)return null;return bx(e)?Yt(t):Rt(t)}function bx(e){for(let t of e){if(t==="--")return!1;if(!t.startsWith("-"))return!0}return!1}function Cx(e){for(let n of e)if(n==="-n"||M(n,"--dry-run"))return null;let t=fe(e.filter((n)=>n!=="--"));if(e.some((n)=>M(n,"--force"))||t.has("-f"))return v("git.clean-force",YE);return null}function Sx(e){let t=!1,n=!1,r=!1;for(let o of ie(e).before){if(M(o,"--no-force")){t=!1;continue}if(M(o,"--force")){t=!0;continue}if(M(o,"--no-cached")){n=!1;continue}if(M(o,"--cached")){n=!0;continue}if(M(o,"--no-dry-run")){r=!1;continue}if(M(o,"--dry-run")){r=!0;continue}let i=fe([o]);t||=i.has("-f"),r||=i.has("-n")}return t&&!n&&!r?v("git.rm-force",ZE):null}function vx(e){let{before:t,after:n}=ie(e),r=fe(t);if(t.some((s)=>M(s,"--mirror")))return v("git.push-mirror",QE);if(t.some((s)=>M(s,"--force"))||r.has("-f")||Rf(t,n).some(Ex))return v("git.push-force",XE);if(t.some((s)=>M(s,"--delete"))||r.has("-d")||Rf(t,n).some(xx))return v("git.push-delete",JE);return null}function Rf(e,t){return[...e.filter((n)=>n!==""&&!n.startsWith("-")),...t]}function Ex(e){return e.startsWith("+")||e.includes(":+")}function xx(e){return e.length>1&&e.startsWith(":")}function Rx(e){let{before:t}=ie(e),n=fe(t),r=n.has("-D")||n.has("-d")||t.some((i)=>M(i,"--delete")),o=n.has("-D")||n.has("-f")||t.some((i)=>M(i,"--force"));if(r&&o)return v("git.branch-force-delete",ex);return null}function _x(e){let{before:t}=ie(e);return t.some((n)=>M(n,"--abort"))?v("git.rebase-abort",tx):null}function wx(e){let{before:t}=ie(e);return t.some((n)=>M(n,"--abort"))?v("git.merge-abort",nx):null}function Px(e){let{before:t}=ie(e);return fe(t).has("-d")||t.some((r)=>M(r,"--delete"))?v("git.tag-delete",rx):null}function Ax(e){return e[0]==="delete"?v("git.reflog-delete",ox):null}function Ix(e){for(let t of e){if(t==="drop")return v("git.stash-drop",ix);if(t==="clear")return v("git.stash-clear",sx)}return null}function Tx(e){let{before:t}=ie(e);if(!t.includes("remove"))return null;let r=fe(t);if(t.some((o)=>M(o,"--force"))||r.has("-f"))return v("git.worktree-remove-force",ax);return null}import{dirname as Xx,isAbsolute as Jx,join as zf,resolve as Qx}from"node:path";var Ma="TMPDIR",Da="IFS",Pf=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Af=/^[A-Za-z_][A-Za-z0-9_]*$/,If=new Set(["export","typeset","declare","readonly"]),kx=new Set(["builtin","command","time"]),Ox=new Set(["do","then","else"]),Mx=new Set(["do","then","case"]),wf=new Set(["done","fi","esac"]),Dx=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function Tf(e,t){return e.map((n)=>n.provenance==="variable"&&Wf(n.text)?kf(n.text,t.shellAssignments):_(n))}function kf(e,t){return e.replace(Dx,(n,r,o)=>t.get(r??o??"")??n)}function Ye(e,t){let n=e.parts.every((o)=>o.provenance!=="literal"||!/[$`]/.test(o.raw));if(e.provenance!=="variable"||!n)return null;let r=kf(e.text,t);return/^[~-]/.test(r)||/[\s$`*?[]/.test(r)?null:r}function Of(e,t){return{env:e,effectiveEnvAssignments:Gx(e,t),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function Mf(e){return{env:e.env,effectiveEnvAssignments:e.effectiveEnvAssignments?new Map(e.effectiveEnvAssignments):void 0,shellAssignments:new Map(e.shellAssignments),bodyDepth:e.bodyDepth,bodyAssignments:new Set(e.bodyAssignments)}}function Na(e,t){let n=Nf(e,t),r=e[0]??"";if(Mx.has(r))t.bodyDepth+=1;if(r==="elif"||wf.has(r))t.bodyDepth=Math.max(0,t.bodyDepth-1);if(wf.has(r)&&t.bodyDepth===0)t.bodyAssignments.forEach((a)=>{t.shellAssignments.delete(a)}),t.bodyAssignments.clear();n.assignments.filter((a)=>a.persists).forEach((a)=>{if(t.shellAssignments.set(a.name,a.value),t.bodyDepth>0)t.bodyAssignments.add(a.name);La(t,a)});let o=n.commandIndex;if(o!==-1&&If.has(e[o]??""))e.filter((a)=>Af.test(a)&&Oa(a)).forEach((a)=>{Fx(t,a)});let i=o===-1?-1:Lf(e,o);if(i===-1||e[i]!=="unset")return;let s=Bx(e,i);if(s===null)return;e.slice(s).forEach((a)=>{if(t.bodyDepth>0){t.shellAssignments.set(a,"");return}zx(t,a)})}function Df(e,t){let n=Nf(e,t).assignments;if(n.length===0)return t.effectiveEnvAssignments;let r=new Map(t.effectiveEnvAssignments??[]);return n.forEach((o)=>{r.set(o.name,o.value)}),r}function Nf(e,t){let n=Ox.has(e[0]??"")?1:0,r=e.findIndex((a,l)=>l>=n&&!Wf(a)),o=r!==-1&&If.has(e[Lf(e,r)]??""),i=Wx(t);return{assignments:e.flatMap((a,l)=>{let c=Nx(a,i,t.env);if(!c)return[];if(r!==-1&&l>r&&!o&&!Po(c.name))return[];return i.set(c.name,c.value),[{...c,persists:r===-1||o}]}),commandIndex:r}}function Lf(e,t){let n=t;while(kx.has(e[n]??"")){n+=1;while(e[n]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(e[n]??""))return t;n+=1}}return n}function Wf(e){return ke(e)!==null||Pf.test(e)}function Nx(e,t,n){return ke(e)??Lx(e,t,n)}function Lx(e,t,n){let r=Ao(e,n,t);if(r)return r;let o=e.match(Pf)?.[1];if(!o)return null;let i=e.indexOf("=");return{name:o,value:`${t.has(o)?t.get(o):n.get(o)??""}${e.slice(i+1)}`}}function Oa(e){return e===Ma||e===Da||ia(e)}function Wx(e){return new Map([...e.effectiveEnvAssignments??[],...e.shellAssignments])}function Gx(e,t){let n=[Ma,Da].map((r)=>{let o=e.get(r);return o===void 0?null:[r,o]}).filter((r)=>r!==null);if(n.length===0)return t;return new Map([...n,...t??[]])}function La(e,t){let n=new Map(e.effectiveEnvAssignments??[]);n.set(t.name,t.value),e.effectiveEnvAssignments=n}function Fx(e,t){La(e,{name:t,value:e.shellAssignments.get(t)??e.effectiveEnvAssignments?.get(t)??e.env.get(t)??""})}function zx(e,t){if(!Oa(t)&&!Af.test(t))return;if(e.shellAssignments.set(t,""),Po(t)&&e.env.has(t)){let r=new Map(e.env);r.delete(t),e.env=r}if(!Oa(t)||t===Ma||t===Da||Kn(t)){La(e,{name:t,value:""});return}if(!e.effectiveEnvAssignments?.has(t))return;let n=new Map(e.effectiveEnvAssignments);n.delete(t),e.effectiveEnvAssignments=n.size===0?void 0:n}function Bx(e,t){let n=t+1;while(n<e.length){let r=e[n];if(!r)return null;if(r==="--")return n+1;if(r==="-v"){n++;continue}if(r.startsWith("-"))return null;return n}return n}import{resolve as $x}from"node:path";function Xo(e,t){return oa.some((n)=>t?.has(n)||e.has(n))}function Pn(e,t,n){if(!t)return{gitCwd:null,hasExplicitGitContext:!1};let r=n.realpath($x(t));if(r===null||!n.isDirectory(r))return{gitCwd:null,hasExplicitGitContext:!1};let o=r,i=!1,s=1;while(s<e.length){let a=e[s];if(!a)break;if(a==="--")break;if(!a.startsWith("-"))break;if(a==="-C"){let l=e[s+1];if(!l)return{gitCwd:null,hasExplicitGitContext:i};let c=Gf(o,l,n);if(!c)return{gitCwd:null,hasExplicitGitContext:i};o=c,s+=2;continue}if(a.startsWith("-C")&&a.length>2){let l=Gf(o,a.slice(2),n);if(!l)return{gitCwd:null,hasExplicitGitContext:i};o=l,s++;continue}if(a==="--git-dir"||a==="--work-tree"){i=!0,s+=2;continue}if(a.startsWith("--git-dir=")||a.startsWith("--work-tree=")){i=!0,s++;continue}s+=Ee.has(a)?2:1}return{gitCwd:o,hasExplicitGitContext:i}}function Gf(e,t,n){try{let r=Ct(e,t,n);return n.isDirectory(r)?r:null}catch{return null}}function Ff(e,t,n){if(!t.localDiscard||!n.worktreeMode||Xo(n.environment.env,n.envAssignments))return null;let r=Pn(e,n.cwd,n.environment.paths);if(!r.gitCwd||r.hasExplicitGitContext)return null;let o=n.environment.worktreeFacts(r.gitCwd);if(!o)return null;if(Wa(e,n,o))return null;return{kind:"worktree",originalReason:t.reason,gitCwd:r.gitCwd}}function Wa(e,t,n){let{subcommand:r,rest:o}=we(e),i=r?.toLowerCase();if(t.dynamicArguments||Ux(o)||qx(e,t.environment.env,t.envAssignments,n)||Vx(o)||Hx(i,o))return!0;return i==="clean"&&Kx(o)>1}function Ux(e){return e.some((t)=>/[$*?[]/.test(t))}function Hx(e,t){if(e==="checkout"){let{before:n}=ie(t),r=fe(n,{shortOptsWithValue:Ta}),o=n.some((s)=>M(s,"--force"))||r.has("-f"),i=r.has("-B")||n.some((s)=>s==="-B"||s.startsWith("-B"));return o&&i}if(e==="switch"){let{before:n}=ie(t),r=fe(n,{shortOptsWithValue:ka}),o=n.some((s)=>M(s,"--force"))||n.some((s)=>M(s,"--discard-changes"))||r.has("-f"),i=n.some((s)=>s==="-C"||s.startsWith("-C")||jx(s))||r.has("-C");return o&&i}return!1}function jx(e){let t=e.split("=",1)[0]??e;return t==="--force-create"||t.length>=9&&"--force-create".startsWith(t)}function Vx(e){return e.some((t)=>t.startsWith("--recurse-sub"))}function Kx(e){let t=0;for(let n of e){if(n==="--force"){t++;continue}if(n.startsWith("-")&&!n.startsWith("--")){for(let r of n.slice(1))if(r==="f")t++}}return t}function qx(e,t,n,r){if(rt("GIT_CONFIG_PARAMETERS",t,n)!==void 0)return!0;let o=Zo(e,t,n);if(o.blockedReason!==null)return!0;let i=o.entries.map((a)=>({key:a.key.toLowerCase(),value:a.value}));if(i.some((a)=>Zx(a.key)))return!0;let s=i.filter((a)=>a.key==="submodule.recurse").at(-1);if(s)return s.value===void 0||Yx(s.value);if(pd(n))return!0;return r.recursiveSubmodules}function Yx(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function Zx(e){return e==="include.path"||e.startsWith("includeif.")&&e.endsWith(".path")}function Bf(e,t,n){let r=e.map((l)=>Ye(l,n.shellAssignments??new Map)??_(l)),o=n.environment.paths,i=Pn(r,n.cwd,o),s=n.originalCwd?o.realpath(Qx(n.originalCwd)):null;if(t.id.startsWith("git.push-")||s===null||i.gitCwd===null||i.hasExplicitGitContext||Xo(n.environment.env,n.envAssignments))return null;let a=t.id==="git.worktree-remove-force"?tR(e,n.shellAssignments,o):$f(i.gitCwd,o);if(a===null||t.id!=="git.worktree-remove-force"&&!eR(a,r,t,n)||!En(a,n.environment)||Bo(a,n.environment)||xn(s,a)||xn(a,s))return null;return{kind:"temp-root",originalReason:t.reason,gitCwd:i.gitCwd}}function eR(e,t,n,r){let o=r.environment.paths,i=zf(e,".git");if(o.entryKind(i)!=="present")return!1;if(o.isDirectory(i))return!0;if(!n.localDiscard)return!1;let a=r.environment.worktreeFacts(e);return a!==null&&!Wa(t,r,a)}function tR(e,t,n){let r=we(e.map(_)).rest,{before:o,after:i}=ie(r.slice(r.indexOf("remove")+1)),s=[...o.filter((u)=>!u.startsWith("-")),...i],a=s.length===1?s[0]??"":"",l=e.find((u)=>u.text===a),c=(l&&Ye(l,t??new Map))??a;if(!Jx(c)||/[\s$`*?[]/.test(c)||n.entryKind(c)!=="present"||!n.isDirectory(c))return null;return n.realpath(c)}function $f(e,t){if(t.entryKind(zf(e,".git"))!=="missing")return e;let n=Xx(e);return n===e?null:$f(n,t)}var rR="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.",oR=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function Jo(e,t){return Uf(e,t)}function Uf(e,t,n){let r=e.map(_),o=Ef(r,t.environment.env,t.envAssignments),i=o.blockedReason?w(v("git.alias-config",o.blockedReason),t.policy):null;if(i)return i;let s=o.tokens;if((md(t.envAssignments)||xf(r,t.environment.env,t.envAssignments))&&iR(s))return v("git.ssh-env",rR);let a=_f(s,(c)=>{let u=Pn(r,t.cwd,t.environment.paths).gitCwd;return u!==null&&t.environment.paths.entryKind(nR(u,c))!=="missing"});if(!a)return null;if(o.expanded||o.blockedReason)return a;let l=Ff(r,a,t)??Bf(e,a,t);if(!l)return a;return n?.(l),null}function Hf(e,t){let n=null;return{match:Uf(e,t,(o)=>{n=o}),relaxation:n}}function iR(e){let{subcommand:t,rest:n}=we(e),r=t?.toLowerCase();if(!r)return!1;if(oR.has(r))return!0;if(r==="archive")return ie(n).before.some((o)=>M(o,"--remote"));return r==="remote"&&sR(n)}function sR(e){return e.find((t)=>!aR(t))?.toLowerCase()==="update"}function aR(e){return e==="-v"||M(e,"--verbose")||M(e,"--no-verbose")}import{isAbsolute as WR}from"node:path";function jf(e,t,n,r){let o=e.slice(0,t),i=e.slice(t+n);return r.startsWith(o)&&r.endsWith(i)?r.slice(o.length,r.length-i.length):null}function Qo(e,t,n){let r=(i)=>`${i.tokenIndex}\x00${i.kind}\x00${i.value}`,o=new Set(e.map(r));return Array.from(t).some((i)=>n(i).some((s)=>!o.has(r(s))))}var Vf="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",lR="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.",cR="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",uR="rm -rf targeting root or home directory is extremely dangerous and always blocked.",dR="rm -rf in home directory is dangerous. Change to a project directory first.",Kf={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:uR},git_metadata_target:{id:"rm.git-metadata",reason:ze},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:cR},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:dR},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:Vf},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:lR},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:Vf}};function ei(e,t){let n=xt({...t,allowPaths:t.policy?.destructiveCommandAllowPaths,posixShell:!0}),r=e.map(_),o=qo(r),i=mR(e);for(let s of i){let a=Sr(s.word);if(o&&a.unsafeBraceExpansion){let l=w(Cr({kind:"outside_anchored_cwd"},n,t.policy,Kf),t.policy);if(l)return l;continue}for(let l of a.expandedTargets??[s.text]){let c=ve(l),u={targetIsLiteral:a.expandedTargets!==void 0||a.targetIsLiteral,tmpdirWordSplittingProtected:a.tmpdirWordSplittingProtected};if(!o&&n.resolvedCwd&&Ht(c,n.resolvedCwd,n.protectedGitMetadata,o,n.environment,n.budget))return v("rm.git-metadata",ze);if(!o)continue;for(let f of fR(c,n,u)){let d=Cr(f,n,t.policy,Kf),m=w(d,t.policy);if(m)return m}}}return null}function fR(e,t,n){let r=Be(e,t,n);if(r.kind==="cwd_self_target")return[r,Be(e,t,{...n,skipCwdSelf:!0})];if(r.kind!=="home_cwd_target")return[r];let o=Be(e,t,{...n,skipHomeCwd:!0});if(o.kind!=="cwd_self_target")return[r,o];return[r,o,Be(e,t,{...n,skipHomeCwd:!0,skipCwdSelf:!0})]}function mR(e){let t=[],n=!1;for(let r of e.slice(1)){let o=_(r);if(!o)continue;if(o==="--"){n=!0;continue}if(n){t.push({text:o,word:r});continue}if(!o.startsWith("-"))t.push({text:o,word:r})}return t}var _t={kind:"none"},Zt={kind:"dynamic"},pR=new Set(["<","<<","<<-","<<<","<&","<>"]),Yf=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,gR=/^(?:[0-9]+|[@*])$/,hR=bt.maxWords,Zf=bt.maxInputLength;function Xf(e){if(!e||P(O(e.words[0]?.text??""))!=="printf")return;if(e.words.some((o)=>o.provenance!=="literal"))return;let t=e.words.slice(e.words[1]?.text==="--"?2:1),n=t[0]?.text;if(n===void 0)return"";let r=t.slice(1).map((o)=>o.text);if(n==="%s")return r.join("");if(n==="%s\\n"||n===`%s
36
38
  `)return`${r.join(`
37
39
  `)}
38
40
  `;if(n.includes("%")||/\\(?![\\nrt])/.test(n))return;return n.replaceAll("\\n",`
39
- `).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function Jo(e){let t=Rn(e[1])==="--"?2:1;if(e.length<=t)return xt;let n=e.slice(t);if(!n.every(vr))return Vt;return{kind:"literal",source:n.map(_).join(" ")}}function Uf(e){let t=Rn(e[1])==="--"?2:1,n=e[t],r=Rn(n);if(n===void 0||e.length<=t+1||r==="-"||r===""||r==="-l"||r==="-p")return xt;if(!vr(n))return Vt;return{kind:"literal",source:r}}function Qo(e,t){let n=Vf(e);if(n===-1)return xt;let r=tR(t);if(!r)return xt;let o=[],i=r.command?.length??0;for(let s of r.references){let a=rR(s,e,n,r.ifs);if(!a)return Vt;if(i+=a.reduce((l,c)=>l+c.length+3,0),o.length+a.length>Qx||i>Bf)return Vt;o.push(...a)}if(r.command==="eval")return{kind:"literal",source:o.join(" ")};if(o.length===0||/\s/.test(o[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[r.command,r.command&&r.optionTerminator?"--":null,...o.map(ei)].filter((s)=>s!==null).join(" ")}}function Hf(e,t){let n=Vf(e),r=e.slice(n+1),o=/\bIFS\b/.test(t);if(n===-1||!r.every(vr)||o)return t;let i=r.map(Rn),s="",a=null,l=0;while(l<t.length){let c=t[l]??"",u=a==="'"?null:/^\$(?:\{([0-9]+|[@*])\}|([0-9@*]))/.exec(t.slice(l));if(u){let f=u[1]??u[2],d=f==="@"||f==="*"?i.slice(1):[i[Number(f)]??""];if(a!=='"'&&d.some((g)=>/[*?[]/.test(g)))return t;if(s+=a==='"'?d.map((g)=>g.replace(/["$`\\]/g,"\\$&")).join(f==="@"?'" "':" "):d.map((g)=>g.split(/[ \t\n]+/).map((p)=>p?ei(p):"").join(" ")).join(" "),s.length>Bf)return t;l+=u[0].length;continue}if(c==="\\"&&a!=="'"){s+=t.slice(l,l+2),l+=2;continue}if(c==="'"&&a!=='"'||c==='"'&&a!=="'")a=a?null:c;s+=c,l++}return s}function jf(e,t,n,r){if(!Ee(e.map(_)).readsStdinAsCommands)return xt;let o=t.filter((i)=>(i.fd===void 0||i.fd===0)&&Xx.has(i.operator)).at(-1);if(o){if(o.operator==="<<"||o.operator==="<<-")return xt;if(o.operator!=="<<<"||o.target?.provenance!=="literal")return Vt;return{kind:"literal",source:o.target.text}}if(!n)return xt;return r===void 0?Vt:{kind:"literal",source:r}}function ct(e,t=new Map){let n=Ee(e.map(_)).scriptIndex;if(n===null)return xt;let r=e[n],o=Rn(r);if(Co(r,o))return{kind:"literal",source:o};let i=r?qe(r,t):null;return i===null?Vt:{kind:"literal",source:i}}var eR=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function Na(e){if(e.words.length!==2||e.redirections.length!==0||e.nested.length!==1)return!1;let t=e.words[0],n=e.words[1];if(!t||t.provenance!=="literal"||t.quoted||t.raw!==t.text||!n)return!1;if(!(t.text==="eval"&&n.quoted&&n.parts.length===3&&n.parts[0]?.raw==='"'&&n.parts[1]?.provenance==="command-substitution"&&n.parts[1].raw.startsWith("$(")&&n.parts[2]?.raw==='"'||t.text==="eval"&&!n.quoted&&n.parts.length===1&&n.parts[0]?.provenance==="command-substitution"&&n.parts[0].raw.startsWith("$(")||(t.text==="source"||t.text===".")&&!n.quoted&&n.parts.length===1&&n.parts[0]?.provenance==="command-substitution"&&n.parts[0].raw.startsWith("<(")))return!1;let o=e.nested[0];if(o?.status!=="complete"||o.nodes.length!==1)return!1;let i=o.nodes[0];if(i?.kind!=="command"||i.redirections.length!==0||i.nested.length!==0||i.words.some((l)=>l.provenance!=="literal"||l.parts.some((c)=>c.provenance!=="literal")))return!1;let s=i.words[0]?.text;if(s===void 0||Ie(s)!==null)return!1;let a=A(k(s));return!eR.has(a)&&!q.has(a)&&!Ut(a)}function Vf(e){return Ee(e.map(_)).commandIndex??-1}function tR(e){let t=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(e.trim()),n=t?.[4]??e.trim(),r=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(n),o=(r?.[3]??n).split(/\s+/).map(nR);if(o.length===0||o.some((i)=>i===null))return null;return{command:r?.[1]??null,optionTerminator:r?.[2]!==void 0,references:o.filter((i)=>!!i),ifs:t?t[1]??t[2]??t[3]??"":`
40
- `}}function nR(e){let t=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(e),n=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(e),r=t??n;if(!r)return null;let o=r[1]??r[2];return{parameter:o==="@"||o==="*"?o:Number(o),quoted:t!==null}}function rR(e,t,n,r){let o=t.slice(n+2);if(e.parameter==="@")return e.quoted?Oa(o):oR(o,r);if(e.parameter==="*"){let a=Oa(o);if(!a)return;let l=a.join(r[0]??"");return e.quoted?[l]:Ma(l,r)}let i=t[n+1+e.parameter];if(i&&!vr(i))return;let s=Rn(i);return e.quoted?[s]:Ma(s,r)}function Oa(e){return e.every(vr)?e.map(_):void 0}function oR(e,t){let n=Oa(e);if(!n)return;let r=n.map((o)=>Ma(o,t));return r.some((o)=>o===void 0)?void 0:r.flatMap((o)=>o??[])}function Ma(e,t){if(["*","?","[","]"].some((n)=>e.includes(n)))return;if(t==="")return e===""?[]:[e];if(t===`
41
+ `).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function ti(e){let t=An(e[1])==="--"?2:1;if(e.length<=t)return _t;let n=e.slice(t);if(!n.every(Pr))return Zt;return{kind:"literal",source:n.map(_).join(" ")}}function Jf(e){let t=An(e[1])==="--"?2:1,n=e[t],r=An(n);if(n===void 0||e.length<=t+1||r==="-"||r===""||r==="-l"||r==="-p")return _t;if(!Pr(n))return Zt;return{kind:"literal",source:r}}function ni(e,t){let n=tm(e);if(n===-1)return _t;let r=bR(t);if(!r)return _t;let o=[],i=r.command?.length??0;for(let s of r.references){let a=SR(s,e,n,r.ifs);if(!a)return Zt;if(i+=a.reduce((l,c)=>l+c.length+3,0),o.length+a.length>hR||i>Zf)return Zt;o.push(...a)}if(r.command==="eval")return{kind:"literal",source:o.join(" ")};if(o.length===0||/\s/.test(o[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[r.command,r.command&&r.optionTerminator?"--":null,...o.map(ri)].filter((s)=>s!==null).join(" ")}}function Qf(e,t){let n=tm(e),r=e.slice(n+1),o=/\bIFS\b/.test(t);if(n===-1||!r.every(Pr)||o)return t;let i=r.map(An),s="",a=null,l=0;while(l<t.length){let c=t[l]??"",u=a==="'"?null:/^\$(?:\{([0-9]+|[@*])\}|([0-9@*]))/.exec(t.slice(l));if(u){let f=u[1]??u[2],d=f==="@"||f==="*"?i.slice(1):[i[Number(f)]??""];if(a!=='"'&&d.some((g)=>/[*?[]/.test(g)))return t;if(s+=a==='"'?d.map((g)=>g.replace(/["$`\\]/g,"\\$&")).join(f==="@"?'" "':" "):d.map((g)=>g.split(/[ \t\n]+/).map((p)=>p?ri(p):"").join(" ")).join(" "),s.length>Zf)return t;l+=u[0].length;continue}if(c==="\\"&&a!=="'"){s+=t.slice(l,l+2),l+=2;continue}if(c==="'"&&a!=='"'||c==='"'&&a!=="'")a=a?null:c;s+=c,l++}return s}function em(e,t,n,r){if(!xe(e.map(_)).readsStdinAsCommands)return _t;let o=t.filter((i)=>(i.fd===void 0||i.fd===0)&&pR.has(i.operator)).at(-1);if(o){if(o.operator==="<<"||o.operator==="<<-")return _t;if(o.operator!=="<<<"||o.target?.provenance!=="literal")return Zt;return{kind:"literal",source:o.target.text}}if(!n)return _t;return r===void 0?Zt:{kind:"literal",source:r}}function ct(e,t=new Map){let n=xe(e.map(_)).scriptIndex;if(n===null)return _t;let r=e[n],o=An(r);if(vo(r,o))return{kind:"literal",source:o};let i=r?Ye(r,t):null;return i===null?Zt:{kind:"literal",source:i}}var yR=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function Ba(e){if(e.words.length!==2||e.redirections.length!==0||e.nested.length!==1)return!1;let t=e.words[0],n=e.words[1];if(!t||t.provenance!=="literal"||t.quoted||t.raw!==t.text||!n)return!1;if(!(t.text==="eval"&&n.quoted&&n.parts.length===3&&n.parts[0]?.raw==='"'&&n.parts[1]?.provenance==="command-substitution"&&n.parts[1].raw.startsWith("$(")&&n.parts[2]?.raw==='"'||t.text==="eval"&&!n.quoted&&n.parts.length===1&&n.parts[0]?.provenance==="command-substitution"&&n.parts[0].raw.startsWith("$(")||(t.text==="source"||t.text===".")&&!n.quoted&&n.parts.length===1&&n.parts[0]?.provenance==="command-substitution"&&n.parts[0].raw.startsWith("<(")))return!1;let o=e.nested[0];if(o?.status!=="complete"||o.nodes.length!==1)return!1;let i=o.nodes[0];if(i?.kind!=="command"||i.redirections.length!==0||i.nested.length!==0||i.words.some((l)=>l.provenance!=="literal"||l.parts.some((c)=>c.provenance!=="literal")))return!1;let s=i.words[0]?.text;if(s===void 0||ke(s)!==null)return!1;let a=P(O(s));return!yR.has(a)&&!Y.has(a)&&!Kt(a)}function tm(e){return xe(e.map(_)).commandIndex??-1}function bR(e){let t=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(e.trim()),n=t?.[4]??e.trim(),r=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(n),o=(r?.[3]??n).split(/\s+/).map(CR);if(o.length===0||o.some((i)=>i===null))return null;return{command:r?.[1]??null,optionTerminator:r?.[2]!==void 0,references:o.filter((i)=>!!i),ifs:t?t[1]??t[2]??t[3]??"":`
42
+ `}}function CR(e){let t=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(e),n=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(e),r=t??n;if(!r)return null;let o=r[1]??r[2];return{parameter:o==="@"||o==="*"?o:Number(o),quoted:t!==null}}function SR(e,t,n,r){let o=t.slice(n+2);if(e.parameter==="@")return e.quoted?Ga(o):vR(o,r);if(e.parameter==="*"){let a=Ga(o);if(!a)return;let l=a.join(r[0]??"");return e.quoted?[l]:Fa(l,r)}let i=t[n+1+e.parameter];if(i&&!Pr(i))return;let s=An(i);return e.quoted?[s]:Fa(s,r)}function Ga(e){return e.every(Pr)?e.map(_):void 0}function vR(e,t){let n=Ga(e);if(!n)return;let r=n.map((o)=>Fa(o,t));return r.some((o)=>o===void 0)?void 0:r.flatMap((o)=>o??[])}function Fa(e,t){if(["*","?","[","]"].some((n)=>e.includes(n)))return;if(t==="")return e===""?[]:[e];if(t===`
41
43
  `)return e.trim().split(/\s+/).filter(Boolean);if(t.length!==1)return;return t===" "||t==="\t"||t===`
42
- `?e.trim().split(/\s+/).filter(Boolean):e.split(t).filter(Boolean)}function vr(e){if(!e)return!0;return e.provenance==="unknown"?!/[$`]/.test(_(e)):e.provenance==="literal"}function Rn(e){return e?_(e):""}function ei(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function La(e,t){return Da(Me(e,"posix"),t)}function Er(e){return La(e,new Set(Array.from(e.matchAll(zf)).flatMap((t)=>{let n=t[1]??t[2];return n===void 0?[]:[n]})))}function Da(e,t){if(e.status==="invalid"||e.status==="limited")return!1;let n=new Set(t);for(let r of e.nodes){if(r.kind==="group"){if(Da(r.body,n))return!0;continue}if(r.kind!=="command")continue;if(r.nested.some((o)=>Da(o,n))||Kf(r.words,n))return!0;cR(r,n)}return!1}function Kf(e,t){let n=e.findIndex((s)=>Ie(s.text)===null);if(n===-1)return!1;let r=e[n];if(!r)return!1;if(Sr(r,t))return!0;let o=k(r.text);if(o==="source"||o==="."){let s=e[n+1]?.text==="--"?n+2:n+1;return Ff(e[s],t)}if(q.has(o)){let s=e.slice(n),a=Ee(s.map((c)=>c.text)),l=a.commandIndex??a.scriptIndex;return!a.syntaxCheck&&l!==null&&Ff(s[l],t)}let i=iR(e,n,t);if(i===null)return!1;if(i===-1)return!0;return Kf(e.slice(i),t)}function iR(e,t,n){let r=k(e[t]?.text??"");if(r==="command")return sR(e,t+1);if(r==="exec")return aR(e,t+1);if(r==="env")return lR(e,t+1,n);return null}function sR(e,t){for(let n=t;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return e[n+1]?n+1:null;if(/^-[p]*[vV][pvV]*$/.test(r))return null;if(/^-p+$/.test(r))continue;return n}return null}function aR(e,t){for(let n=t;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return e[n+1]?n+1:null;if(r==="-a"){n++;continue}if(/^-a.+/.test(r)||/^-[cl]+$/.test(r))continue;return n}return null}function lR(e,t,n){for(let r=t;r<e.length;r++){let o=e[r],i=o?.text??"";if(i==="--")return e[r+1]?r+1:null;if(i==="-S"||i==="--split-string")return Sr(e[r+1],n)?-1:r+2;if(i.startsWith("-S")||i.startsWith("--split-string="))return Sr(o,n)?-1:r+1;if(i==="-u"||i==="--unset"||i==="-C"||i==="--chdir"||i==="-P"){r++;continue}if(i==="-i"||i==="-0"||i==="--null"||i.startsWith("-u=")||i.startsWith("--unset=")||i.startsWith("-C")||i.startsWith("--chdir=")||i.startsWith("-P"))continue;if(i.startsWith("-"))continue;if(Ie(i))continue;return r}return null}function cR(e,t){if(!e.words.every((n)=>Ie(n.text)!==null))return;for(let n of e.words){let r=Ie(n.text);if(!r)continue;if(Sr(n,t))t.add(r.name)}}function Sr(e,t){if(!e)return!1;return e.parts.filter((n)=>n.provenance==="variable").some((n)=>Array.from(n.raw.matchAll(zf)).some((r)=>{let o=r[1]??r[2];return o!==void 0&&(Jx.test(o)||t.has(o))}))}function Ff(e,t){return!!e&&(e.parts.some((n)=>n.provenance!=="literal"&&n.provenance!=="variable")||Sr(e,t))}var Wa="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",Ga="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",uR="__CC_SAFETY_NET_XARGS_INPUT__",ti="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",ni="rm",dR=/(?:^|[;&|]\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,fR=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,mR=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,pR=/^(?:[0-9]+|[@*])$/;function Zf(e,t){let n=e.map(_),{childStart:r,replacementToken:o}=Kt(n),i=n.slice(r),s=v("xargs.shell-dynamic",Ga);if(hR(i,o,t)&&w(s,t.policy))return w(s,t.policy);for(let a of ze(i,t)){let l=a.tokens,c=o!==null&&l[0]!==i[0]&&(l[0]?.includes(o)??!1)?w(s,t.policy):null;if(c)return c;let u=nm(l,o,a.wrapperEnvAssignments),f=a.head==="rm"&&o!==null&&em(l,o),d=t.analyzeChild(l,{...Ht(a,t),dynamicInput:u,dynamicSourceInput:f||Jf(l,a.head,o,a.wrapperEnvAssignments,u,t.environment,t.strict?void 0:t.analyzeNested),dynamicRmInput:f,shellDynamicMatch:s,dynamicSourceMatch:s,rmDynamicMatch:v("xargs.rm-recursive-force-dynamic",Wa)});if(d)return d;let m=gR(l,o,t.policy?.rules??[],w(s,t.policy));if(m)return m;if(a.head==="git"){let p=o===null?[...l,uR]:l,h=o!==null&&(l.some((b)=>b.includes(o))||Array.from(a.envAssignments.values()).some((b)=>b.includes(o))),C=t.analyzeChild(p,{...Ht(a,t),worktreeMode:o===null||h?!1:t.worktreeMode});if(C)return C}let g=it(l,t.policy?.rules??[]);if(g)return g}return null}function gR(e,t,n,r){if(n.length===0)return null;if(t===null){for(let i of n){let s=it([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],n);if(s)return s}return null}let o=k(e[0]??"");if(!n.some((i)=>k(i.command)===o))return null;return e.slice(1).some((i)=>i.includes(t))?r:null}function Xf(e,t,n){let r=e.indexOf(t);if(r===-1||e.indexOf(t,r+t.length)!==-1)return[];let o=Lf(e,r,t.length,n);return o===null?[]:[o]}function Jf(e,t,n,r,o,i,s){if(q.has(t)){if(at(e))return!1;if(n!==null&&yR(e,n,s))return!0;let a=Be(e);if(!a){let l=ct(K(e));if(l.kind==="literal")return n!==null&&l.source.includes(n);return l.kind==="none"&&o}if(n!==null&&a.includes(n)&&!Qf(a,n,s))return!0;if(Pe(a))return!0;return CR(a,n,r)}if(Oe(t))return qf(e,n,xo,Qu(t));if(Ae.has(t))return qf(e,n,ha,ef);if(t==="eval"){let a=Jo(K(e));if(a.kind==="dynamic")return!0;if(n!==null)return a.kind==="literal"&&a.source.includes(n);return o}if(t==="find")return bR(e,n,i);if(t==="git"){let a=_e(e);return n===null?a.subcommand===null:(a.subcommand?.includes(n)??!1)||a.subcommand!==null&&En.has(a.subcommand.toLowerCase())&&tm(a.rest,n).some((l)=>l.includes(n))}return!1}function Qf(e,t,n){if(n===void 0)return!1;let r=t.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+)*["']?${r}`).test(e)||/\bcase\b/.test(e))return!1;let i=e.replaceAll(t,"/");return Pe(i)===null&&n(i)===null}function qf(e,t,n,r){let o=n(e);if(t===null)return o.optionsOpen||n([...e,ti]).sources.some((a)=>a.value===ti);if(o.sources.some((a)=>a.value.includes(t)))return!0;let i=r.flatMap((a)=>[a.selector,...a.valueForm==="attached-only"||a.valueForm==="attached-or-separate"?[`${a.selector}${ti}`]:[],...a.valueForm==="equals-or-separate"?[`${a.selector}=${ti}`]:[]]),s=new Set(i.flatMap((a)=>e.flatMap((l)=>Xf(l,t,a))));return Zo(o.sources,s,(a)=>n(e.map((l)=>l.replaceAll(t,a))).sources)}function hR(e,t,n){if(e.length===0||(e[0]??"").toLowerCase()==="command")return!1;let r=new Set(Array.from(ze(e,n),(i)=>i.head)),o=t===null?[...e,ni]:e.map((i,s)=>s===0?i:i.replaceAll(t,ni));return Array.from(ze(o,n)).some((i)=>i.head===ni&&!r.has(ni))}function em(e,t){return tm(e.slice(1),t).some((n)=>n.includes(t)&&(n.startsWith("-")||n.startsWith(t)))}function tm(e,t){let n=e.findIndex((r)=>r==="--"&&!r.includes(t));return n===-1?e:e.slice(0,n)}function nm(e,t,n){if(t===null)return!0;return e.some((r)=>r.includes(t))||Array.from(n.values()).some((r)=>r.includes(t))}function yR(e,t,n){let r=Ee(e),o=r.commandIndex===null?"":e[r.commandIndex]??"";if(o.includes(t)&&!Qf(o,t,n)||r.scriptIndex!==null&&(e[r.scriptIndex]??"").includes(t))return!0;return["-c","-nc","-cn",`--${t}`,t].some((s)=>e.some((a,l)=>{if(l===0||!a.includes(t))return!1;return Xf(a,t,s).some((u)=>{let f=e.map((m,g)=>g===l?m.replaceAll(t,u):m),d=Ee(f);if(d.commandIndex===null&&d.scriptIndex===null)return!1;if(r.commandIndex===null&&d.commandIndex!==null)return!0;if(r.scriptIndex===null&&d.scriptIndex!==null)return!0;if(d.commandIndex!==null&&(f[d.commandIndex]??"").includes(u))return!0;return d.scriptIndex!==null&&(f[d.scriptIndex]??"").includes(u)})}))}function CR(e,t,n){let r=new Set(t===null?[]:Array.from(n).filter(([,o])=>o.includes(t)).map(([o])=>o));for(let o of e.matchAll(dR))if(Yf(o,r))return!0;for(let o of e.matchAll(fR))for(let i of(o[1]??"").matchAll(mR))if(Yf(i,r))return!0;return La(e,r)}function Yf(e,t){let n=e[1]??e[2];return n!==void 0&&(pR.test(n)||t.has(n))}function bR(e,t,n){if(t===null)return!0;let r=!1,o=0;for(let i=1;i<e.length;i++){let s=e[i]??"";if(!r&&!s.startsWith("-")&&s!=="!"&&s!=="("){if(s.indexOf(t)===0)return!0;continue}if(r=!0,o>0){o--;continue}if(Ke(s)){let l=vn(e,i);i=l.nextIndex-1;for(let c of ze(l.tokens,{environment:n,cwd:void 0})){let u=nm(c.tokens,t,c.wrapperEnvAssignments);if(c.head==="rm"&&em(c.tokens,t)||Jf(c.tokens,c.head,t,c.wrapperEnvAssignments,u,n))return!0}continue}let a=lt(s);if(a>0){if(o=a,s.includes(t))return!0;continue}if(s.includes(t))return!0}return!1}function Kt(e){let t=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"]),n=null,r=1;while(r<e.length){let o=e[r];if(!o)break;if(o==="--")return{childStart:r+1,replacementToken:n};if(!o.startsWith("-"))return{childStart:r,replacementToken:n};if(o==="-I"){n=e[r+1]??"{}",r+=2;continue}if(o.startsWith("-I")&&o.length>2){n=o.slice(2),r++;continue}if(o==="--replace"){n="{}",r++;continue}if(o.startsWith("--replace=")){let i=o.slice(10);n=i===""?"{}":i,r++;continue}if(o==="-J"){n=e[r+1]??"{}",r+=2;continue}r+=t.has(o)?2:1}return{childStart:e.length,replacementToken:n}}var xr="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",Rr="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",vR="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",ER="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",oi=/\{[^{}\s]*\}/g,rm=/\{\}|\{-?\d+\}/g,om=/[\s;&|<>()$`\\"']/,xR=["e","f","source","file","-e","-f","--source","--file"],RR=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],_R=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),wR=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),im=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),AR=new Set(["--workdir","--wd"]),sm="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Te(e,t){for(let n of e){let r=t(n);if(r)return r}return null}function cm(e){return Te([...e],(t)=>Pe(t))}function um(e,t){let n=e.map(_);if((t.envAssignments?.has("PARALLEL")?t.envAssignments.get("PARALLEL"):t.environment.env.get("PARALLEL"))?.trim()){let g=_n(t);if(g)return g}if(n.length===2&&(n[1]==="--version"||n[1]==="--help"))return null;let o=Em(n),{template:i,jobs:s,runsRemotely:a,readsCommandsFromInput:l,unsupported:c,workdir:u,dryRun:f}=o;if(c){let g=_n(t);if(g)return g;let p=cm(t.envAssignments?.values()??[]);if(p)return p}if(l){let g=DR(t);if(g)return g}if(u!==void 0&&a){let g=_n(t);if(g)return g}let d=NR(u,t.cwd,t.environment.paths);if(d===null){let g=_n(t);if(g)return g}let m=a?{...t,cwd:void 0,originalCwd:void 0}:d===null||d===void 0||d===t.cwd?t:{...t,cwd:d};if(f){if([...ze(i,m)].flatMap((p)=>[...p.envAssignments.values()]).some(Ba)){let p=_n(t);if(p)return p}return null}if(i.length===0){let g=s.map((h)=>h[0]??"");t.budget.charge("derivedTokens",g.length);let p=hm(m.envAssignments,m.cwd,a);return Te(g,(h)=>t.analyzeNested(h,p))}return Te(ze(i,m),(g)=>PR(g,o,t,m))}function PR(e,t,n,r){let{templateHasPlaceholder:o,runsRemotely:i,usesStdin:s}=t,a=e.tokens,l=[...e.envAssignments.values()];if(l.some(Sm)){let E=_n(n);if(E)return E}let c=cm(l);if(c)return c;let u=l.some(W),f=o||u,d=s&&f,m=hm(e.envAssignments,e.wrapperCwd,i||d),g=f?{...m,worktreeMode:!1}:m,p=a.join(" "),h=W(p.split(/[ \t\n=]/,1)[0]??""),C=!t.quotesCommand&&(h||a.some((E)=>om.test(E))),b=h||om.test(a[0]??""),y=C&&b&&t.jobs.length>0?null:IR(e,t,n,r,g,u);if(y||!C)return y;return dm(W(p)?p:`${p} {}`,!h,e,t,n,r,g)}function IR(e,t,n,r,o,i){let{jobs:s,templateHasPlaceholder:a,runsRemotely:l,usesStdin:c}=t,u=e.tokens,f=a||i;if(q.has(e.head)){let m=()=>{if(!a||s.length===0)return null;return Te(s,(h)=>n.analyzeChild(ri(u,h,n.budget),Ht(e,r)))};if(at(u))return m();let g=Be(u);if(g){if(vm(g)){let y=Rt(n);if(y)return y;if(s.length===0)return null;return Te(s,(E)=>n.analyzeNested(Cm(g,E,n.budget),o))}if(W(g))return dm(g,!1,e,t,n,r,o);let h=!i&&(!a||s.length>0)?(s.length>0?s:[void 0]).map((y)=>Qo(K(y===void 0?u:a?u.map((E)=>ym(E,y)):[...u,...y]),g)):[];if(h.some((y)=>y.kind==="dynamic")){let y=Rt(n);if(y)return y}let C=h.flatMap((y)=>y.kind==="literal"?[y.source]:[]);if(C.length>0)return n.budget.charge("derivedTokens",C.length),Te(C,(y)=>n.analyzeNested(y,o));if(Er(g)){let y=Rt(n);if(y)return y}let b=n.analyzeNested(g,o);if(b)return b;if(f)return Rt(n);return null}let p=ct(K(u));if(p.kind==="dynamic"||p.kind==="literal"&&W(p.source))return Rt(n)??m();if(p.kind==="literal")return m();if(s.length>0){let h=Rt(n);if(h)return h;let C=m();if(C)return C;if(a)return null;let b=s.flatMap((y)=>y[0]===void 0?[]:[y[0]]);return n.budget.charge("derivedTokens",b.length),Te(b,(y)=>n.analyzeNested(y,o))}if(f||c)return Rt(n)??m();return null}if(e.head==="rm"&&st(u)){if(a&&s.length>0)return Te(s,(g)=>Fa(ri(u,g,n.budget,rm),e.cwd,r));if(s.length>0)return Te(s,(g)=>Fa(lm(u,g,n.budget),e.cwd,r));let m=Fa(u.flatMap((g,p)=>{if(p===0||!W(g))return[g];return g.startsWith("-")?[g.replace(rm,"")]:[]}),e.cwd,r);if(m)return m;return gm(n)}let d=s.length>0?s:[void 0];return Te(d,(m)=>{let g=m===void 0?u:a?ri(u,m,n.budget):lm(u,m,n.budget),p=v("parallel.shell-dynamic",Rr),h=c&&e.head==="find"?MR(g,r):null,C=mm(g,c,n)??h?.customResult??null,b=k(e.head),y=c&&(b==="rm"&&za(g)||b==="xargs"&&pm(g)||h?.rmOptions===!0),E=c&&(y||h?.executedSource===!0||h===null&&fm(g,b)),I=n.analyzeChild(g,{...Ht(e,r),worktreeMode:l||c||f?!1:n.worktreeMode,dynamicInput:c||f,dynamicRmInput:y,dynamicSourceInput:C!==null||E,shellDynamicMatch:p,dynamicSourceMatch:p,rmDynamicMatch:v("parallel.rm-recursive-force-dynamic",xr)});if(E){let T=w(p,n.policy);if(T)return T}return I??C??it(g,n.policy?.rules??[])})}function dm(e,t,n,r,o,i,s){if(r.jobs.length>0)return Te(r.jobs,(c)=>o.analyzeNested(Cm(e,t?c.map(ei):c,o.budget),s));let a=br(e);if(a?.[0]&&k(a[0])==="rm"&&st(a)){let c=gm(o);if(c)return c}return(a?o.analyzeChild(a,{...Ht(n,i),dynamicInput:r.usesStdin,shellDynamicMatch:v("parallel.shell-dynamic",Rr),rmDynamicMatch:v("parallel.rm-recursive-force-dynamic",xr)}):null)??o.analyzeNested(e,s)}function fm(e,t){if(W(e[0]??""))return!0;if(t==="eval"||t==="source"||t===".")return!0;if(t==="parallel"||t==="xargs")return!0;if(q.has(t))return OR(e);if(t==="git")return TR(e);if(t==="find")return!0;if(Ae.has(t))return am(e,xR,yr);if(Oe(t))return am(e,RR,Eo);return!1}function za(e){let t=e.indexOf("--"),n=e.slice(1,t===-1?void 0:t);if(!e.some(W))return t===-1;return n.some((o)=>W(o)&&(o.startsWith("-")||vm(o)))}function TR(e){if(kR(e))return!0;let t=_e(e);if(t.subcommand===null||W(t.subcommand))return!0;if(!En.has(t.subcommand.toLowerCase()))return!1;let n=t.rest.indexOf("--"),r=t.rest.slice(0,n===-1?void 0:n);if(!e.some(W))return n===-1;return r.some(W)}function kR(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n||n==="--"||!n.startsWith("-"))return!1;if(n==="-c"||n==="--config-env"){if(W(e[t+1]??""))return!0;t++;continue}if(n.startsWith("-c")&&n.length>2||n.startsWith("--config-env=")){if(W(n))return!0;continue}if(W(n))return!0}return!1}function OR(e){if(at(e))return!1;let t=Be(e);if(t!==null)return W(t);let n=ct(K(e));if(n.kind==="literal")return W(n.source);if(n.kind==="dynamic")return!0;return!e.some(W)}function am(e,t,n){let r=n(e);if(r.some((o)=>W(o.value)))return!0;if(!e.some(W))return n([...e,sm]).some((o)=>o.value===sm);return Zo(r,t,(o)=>n(e.map((i)=>ym(i,[o]))))}function mm(e,t,n){let r=n.policy?.rules??[];if(!t||r.length===0)return null;let o=r.filter((i)=>k(i.command)===k(e[0]??""));if(o.length===0)return null;if(e.slice(1).some(W))return Rt(n);return Te(o,(i)=>it([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],[i]))}function MR(e,t){let n={customResult:null,executedSource:!e.some(W),rmOptions:!1},r=!1,o=0,i=null,s=()=>{if(!i?.some(W))return;for(let a of ze(i,t))n.executedSource||=fm(a.tokens,a.head),n.rmOptions||=a.head==="rm"&&za(a.tokens)||a.head==="xargs"&&pm(a.tokens),n.customResult??=mm(a.tokens,!0,t)};for(let a of e.slice(1)){if(!r&&!a.startsWith("-")&&a!=="!"&&a!=="("){n.executedSource||=W(a);continue}if(r=!0,i){if(a===";"||a==="+"){s(),i=null;continue}i.push(a);continue}if(o>0){o--;continue}if(Ke(a)){i=[],n.executedSource||=W(a);continue}let l=lt(a);if(l>0){o=l,n.executedSource||=W(a);continue}n.executedSource||=W(a)}return s(),n}function pm(e){let t=e.slice(Kt(e).childStart);return k(t[0]??"")==="rm"&&za(t)}function ii(e,t){return(n)=>w(v(e,t),n.policy)}var Rt=ii("parallel.shell-dynamic",Rr),DR=ii("parallel.command-stream-dynamic",vR),_n=ii("parallel.command-stream-dynamic",ER),gm=ii("parallel.rm-recursive-force-dynamic",xr);function Fa(e,t,n){return w(Xo(K(e),{environment:n.environment,cwd:t,budget:n.budget,originalCwd:n.originalCwd,strict:n.strict,paranoid:n.paranoidRm,allowTmpdirVar:n.allowTmpdirVar,tmpdirWordSplittingUnsafe:Bt(n.envAssignments??new Map,n.environment),trustedTmpdirValue:yn(n.envAssignments??new Map,n.environment),protectedGitMetadata:n.protectedGitMetadata,policy:n.policy}),n.policy)}function hm(e,t,n){let r={};if(e)r.envAssignments=e;if(n)return r.effectiveCwd=null,r.worktreeMode=!1,r;if(t!==void 0)r.effectiveCwd=t;return Object.keys(r).length>0?r:void 0}function ym(e,t){return e.replace(oi,(n)=>bm(n,t))}function ri(e,t,n,r=oi){return n.charge("derivedTokens",e.reduce((o,i)=>o+1+Math.floor(i.length/64),0)),e.map((o)=>o.replace(r,(i)=>{let s=bm(i,t);return n.charge("derivedTokens",Math.max(1,Math.ceil(s.length/64))),s}))}function Cm(e,t,n){return ri([e],t,n)[0]??""}function lm(e,t,n){return n.charge("derivedTokens",e.length+t.length),[...e,...t]}function bm(e,t){let n=/^\{(-?\d+)[^{}\s]*\}$/.exec(e)?.[1];if(n===void 0)return t[0]??"";let r=Number(n);return t[r>0?r-1:t.length+r]??""}function W(e){return e.search(oi)!==-1}function Sm(e){if(Ba(e))return!0;for(let t of e.matchAll(oi))if(!/^(?:\{\}|\{\d+\})$/.test(t[0]))return!0;return!1}function Ba(e){let t=e.indexOf("{=");return t!==-1&&e.indexOf("=}",t+2)!==-1}function vm(e){return/^\{[^{}\s]*\}$/.test(e)}function NR(e,t,n){if(e===void 0)return;if(e==="..."||/^~|[{}$`*?[]/.test(e))return null;if(!t&&!SR(e))return null;try{return yt(t??e,e,n)}catch{return null}}function Em(e){let t=1,n=[],r=e.length,o=-1,i=!1,s=!1,a=!1,l,c=!1,u=e.some((p)=>p==="::::"||p==="::::+"||p===":::+");while(t<e.length){let p=e[t];if(p===void 0)break;if(p===":::"){o=t;break}if(p==="--"){let E=ba(e,t+1);n.push(...E.templateTokens),r=t+1,o=E.markerIndex;break}if(!p.startsWith("-")){let E=ba(e,t);n.push(...E.templateTokens),r=t,o=E.markerIndex;break}let h=e[t+1],C=p.indexOf("="),b=C===-1?p:p.slice(0,C),y=C===-1?void 0:p.slice(C+1);if(p==="--dry-run"){c=!0,t++;continue}if(p==="-I"||p.startsWith("-I")&&p.length>2){u||=(p==="-I"?h:p.slice(2))!=="{}",t+=p==="-I"?2:1;continue}if(p==="--replace"||p==="-i"){u=!0,t+=2;continue}if(b==="--replace"||p.startsWith("-i")&&p.length>2){let E=b==="--replace"?y:p.slice(2);u||=E!==""&&E!=="{}",t++;continue}if(p==="-a"||wR.has(b)){u=!0,t+=y===void 0?2:1;continue}if(p==="-q"||p==="--quote"){s=!0,t++;continue}if(p==="--pipe"||p==="--pipepart"){a=!0,t++;continue}if(b==="--env"){u=!0,t+=y===void 0?2:1;continue}if(im.has(b)||p.startsWith("-S")&&p.length>2){i=!0,t+=im.has(p)?2:1;continue}if(AR.has(b)){u=!0;let E=y??h;if(E===void 0||E===":::"||E==="--"){t++;continue}l=E,t+=y===void 0?2:1;continue}if(p.startsWith("-j")&&p.length>2&&/^\d+$/.test(p.slice(2))){t++;continue}if(p.startsWith("--")&&y!==void 0){t++;continue}if(_R.has(p)){if(h===void 0||h===":::"||h==="--"){u=!0,t++;continue}t+=2;continue}t+=p==="-j"||p==="--jobs"?2:1}u||=n.some(c?Ba:Sm);let f=[];if(o!==-1){let p=[];for(let h=o+1;h<e.length;h++){let C=e[h];if(C===":::"){f.push(p),p=[];continue}if(C!==void 0)p.push(C)}f.push(p)}u||=f.length>1;let d=LR(f),m=n.some(W),g=n.length===0&&o===-1;return{template:n,jobs:d,childStart:r,templateHasPlaceholder:m,runsRemotely:i,quotesCommand:s,usesStdin:a||o===-1,readsCommandsFromInput:g,unsupported:u,workdir:l,dryRun:c}}function LR(e){if(e.length===0||e.some((n)=>n.length===0))return[];let t=[[]];for(let[n,r]of e.entries()){if(r.length===1){let i=r[0];if(i===void 0)return[];for(let s of t)s.push(i);if(t.length*(n+1)>V.derivedTokens.cap)throw new N("derivedTokens");continue}let o=[];for(let i of t)for(let s of r){if((o.length+1)*(n+1)>V.derivedTokens.cap)throw new N("derivedTokens");o.push([...i,s])}t=o}return t}function xm(e){return Em(e).childStart}var WR="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",si="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function Ua(e){return e?.parts.some((t)=>t.provenance==="command-substitution")??!1}function $a(e){return e?.parts.some((t)=>t.provenance==="literal"&&t.raw.replace(/^["']/,"").startsWith("-"))??!1}function _m(e,t,n,r,o=!1,i){let a=(Zn(e,t)||r&&e!=="powershell"&&t[0]?.provenance==="variable")&&ee(i,"shell.dynamic-executable",o)?v("shell.dynamic-executable",WR):null;return w(a,i)??wm(e,t,n,o,i)}function wm(e,t,n,r,o){if(t.length<2)return null;let i=t.flatMap((a,l)=>Ua(a)?[l]:[]);if(i.length===0)return null;let s=k(t[0]?.text??"");if(s==="git"){let a=dn(e,t),l=FR(a);if(ee(o,"shell.dynamic-structure",r)&&i.some((f)=>f<=l))return w(v("shell.dynamic-structure",si),o);if(w(Yo(a,{environment:n}),o))return null;let c=t[l]?.text.toLowerCase(),u=a.findIndex((f,d)=>d>l&&_(f)==="--");if(ee(o,"shell.dynamic-structure",r)&&c&&En.has(c)&&i.some((f)=>f>l&&(u===-1||f<u)))return w(v("shell.dynamic-structure",si),o);return null}if(s==="find")return ee(o,"shell.dynamic-structure",r)&&zR(t)?w(v("shell.dynamic-structure",si),o):null;if(s==="rm"){let a=t.findIndex((c,u)=>u>0&&_(c)==="--"),l=st(t.map(_));return ee(o,"shell.dynamic-structure",r)&&i.some((c)=>(a===-1||c<a)&&(c<t.length-1||!l))?w(v("shell.dynamic-structure",si),o):null}if(s==="xargs")return Rm(e,t.slice(Kt(t.map(_)).childStart),"xargs",n,r,o);if(s==="parallel")return Rm(e,t.slice(xm(t.map(_))),"parallel",n,r,o);return null}function Rm(e,t,n,r,o,i){if(t.length===0)return null;let s=GR(t,r);if(Zn(e,s)){let l=w(v(`${n}.shell-dynamic`,n==="xargs"?Ga:Rr),i);if(l)return l}let a=wm(e,s,r,o,i);if(a)return a;if(s[0]?.text==="rm"&&s.slice(1).some((l)=>Ua(l)&&$a(l)))return w(v(`${n}.rm-recursive-force-dynamic`,n==="xargs"?Wa:xr),i);return null}function GR(e,t){let n=Gt(e,t),r=n.rewritten?K(n.words.map(_)):n.words,o=r[0];return o&&_(o)==="busybox"?r.slice(1):r}function FR(e){let t=1;while(t<e.length){let n=e[t],r=n?_(n):"";if(ve.has(r)){t+=2;continue}if(r.startsWith("-")){t++;continue}return t}return t}function zR(e){let t=!1,n=0,r=!1,o=!1;for(let i=1;i<e.length;i++){let s=e[i];if(!s)continue;let a=Ua(s);if(n>0){n--;continue}if(o){if(s.text===";"||s.text==="+"){o=!1,t=!0,r=!1;continue}if(a&&(r||$a(s)))return!0;r=!1;continue}if(!t&&!s.text.startsWith("-")){if(a&&(i>1||$a(s)))return!0;continue}if(t=!0,a)return!0;let l=lt(s.text);if(l>0){n=l;continue}if(Ke(s.text))o=!0,r=!0}return!1}function Ha(e,t){return e.some((n)=>{if(n.value==="-"&&(n.kind==="main-script"||n.kind==="program-file"))return!0;return!Co(t[n.tokenIndex],n.value)})}var Im=[{heads:new Set(["rm","rmdir"]),analyze:(e)=>Xo(e.words,Pm(e))},{heads:new Set(["git"]),analyze:(e)=>Yo(e.words,ja(e))},{heads:new Set(["find"]),analyze:(e)=>df(e.words,{...Pm(e),envAssignments:e.envAssignments,analyzeTokens:e.analyzeChildTokens})},{heads:new Set(["xargs"]),analyze:(e)=>Zf(e.words,{...Am(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>wn(e.options.analyzeNested(t,n))})},{heads:new Set(["parallel"]),analyze:(e)=>um(e.words,{...Am(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>wn(e.options.analyzeNested(t,n))})}];function Am(e){return{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoidRm:e.options.paranoidRm,paranoidInterpreters:e.options.paranoidInterpreters,allowTmpdirVar:e.allowTmpdirVar,protectedGitMetadata:e.options.protectedGitMetadata,budget:e.options.budget,envAssignments:e.envAssignments,worktreeMode:e.options.worktreeMode,policy:e.options.policy}}function wn(e){return e?{id:e.ruleId,reason:e.reason,intent:e.intent??"manual_only"}:null}function Pm(e){return{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoid:e.options.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:Bt(e.envAssignments,e.options.environment),trustedTmpdirValue:yn(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,policy:e.options.policy,budget:e.options.budget}}function ja(e){return{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,dynamicArguments:e.dynamicArguments,envAssignments:e.envAssignments,shellAssignments:e.options.shellAssignments,policy:e.options.policy,worktreeMode:e.options.worktreeMode}}function Om(e){return Im.find((t)=>t.heads.has(e))?.analyze}function Pn(e,t,n){let r=n.trace;if(e.length===0)return null;let o=n.commandView?.dialect??"posix",i=(x)=>x.map((P)=>o==="posix"?_(P):P.text),s=n.child,a=s!==void 0&&!s.embedded,l=s?.embedded===!0,c=n.effectiveCwd===null,u=s?s.cwd:c?void 0:n.effectiveCwd??n.cwd,f=s?s.originalCwd:c?void 0:n.cwd,d=wo(e);if(d.envAssignments.size>0)r?.recordSegment({type:"env-strip",input:i(e),envVars:[...d.envAssignments.keys()],output:i(d.words)});let m=Gt(d.words,n.environment,u,new Map([...n.envAssignments??[],...d.envAssignments])),g=m.envSplitValues??[];if(g.length>0){let x=[...g,...i(m.words)].join(" "),P=Pe(x);if(P)return r?.recordSegment({type:"dangerous-text",token:x,matched:!0,reason:P.reason}),de(P);if(n.strict)return ye(r);let G=Ao(g,i(m.words));if(G){n.budget.charge("derivedTokens",G.length);let te=n.analyzeNested(G.join(" "),{effectiveCwd:m.cwd===void 0?n.effectiveCwd:m.cwd,envAssignments:new Map([...n.envAssignments??[],...d.envAssignments,...m.envAssignments])});if(te)return te}}let p=m.rewritten?K(i(m.words)):dn(o,m.words),h=i(p),C={...n,wrapperNormalizationBudget:n.wrapperNormalizationBudget??{iterations:0}};if(r&&d.words.length>p.length){let x=i(d.words);r.recordSegment({type:"leading-tokens-stripped",input:x,removed:x.slice(0,x.length-p.length),output:h})}let b=new Map([...n.envAssignments??[],...d.envAssignments,...m.envAssignments]),y=h[0];if(!y)return null;if(Ut(y))throw new N("wrapperPeelIterations");let E=k(y),I=m.cwd===null?void 0:m.cwd??u,T=m.cwd===null?void 0:f,M=m.cwd===void 0?n.effectiveCwd:m.cwd,Y=s?s.allowTmpdirVar:!fr(b,n.environment),ue=_m(o,m.words,n.environment,t===0,n.strict,n.policy);if(ue)return r?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:ue.reason}),de(ue);let Xe=Uo(h,n.policy);if(Xe){for(let x of[Xe.childIndex,...Xe.alternativeChildIndices]){Tm(C.wrapperNormalizationBudget);let P=p.slice(x);r?.recordSegment({type:"transparent-wrapper",wrapper:Xe.wrapper,output:i(P)});let G=Pn(P,t,{...C,effectiveCwd:M,envAssignments:b});if(G)return G}return null}let Ce=l?void 0:E==="eval"?Jo(p):E==="trap"&&!a?Uf(p):void 0;if(a&&s&&E==="eval"){if(Ce?.kind==="dynamic")return An(s,n.policy);if(Ce?.kind==="literal"){let x=n.analyzeNested(Ce.source,{effectiveCwd:M,envAssignments:b});if(x)return x}return In(s,n.policy)}if(Ce?.kind==="dynamic"&&(n.strict||!n.commandView||!Na(n.commandView)))return ye(r);if(Ce?.kind==="literal"){r?.recordSegment({type:"recurse",reason:E==="eval"?"shell-eval":"shell-trap",innerCommand:Ce.source,depth:t+1});let x=n.analyzeNested(Ce.source,{effectiveCwd:M,envAssignments:b,functionDefinitions:n.functionDefinitions});if(x)return x}if(a?q.has(E):Dm(y,E)){if(at(h))return null;if(a&&s){let x=Be(h);if(x){if(s.dynamicSourceInput??s.dynamicInput){let G=An(s,n.policy);if(G)return G}if(Er(x)){let G=An(s,n.policy);if(G)return G}return n.analyzeNested(x,{effectiveCwd:M,envAssignments:b})}let P=ct(p);if(P.kind==="dynamic")return An(s,n.policy);if(P.kind==="literal")return s.dynamicSourceInput?An(s,n.policy):null;return s.dynamicSourceInput??s.dynamicInput?An(s,n.policy):null}if(l){let x=Be(h),P=x?n.analyzeNested(x,{effectiveCwd:M,envAssignments:b}):ct(p).kind==="dynamic"?ye(r):null;if(P)return P}if(s===void 0){let x=HR(h,b,M,n,r,t);if(x)return x;let P=Be(h);if(P){let Qt=Qo(p,P);if(Qt.kind==="dynamic")return ye(r);let Si=Qt.kind==="literal"?Qt.source:Hf(p,P),vl=jR(Si);r?.recordSegment({type:"shell-wrapper",wrapper:E,innerCommand:vl}),r?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:vl,depth:t+1});let El=n.analyzeNested(Si,{effectiveCwd:M,envAssignments:b});if(El)return El;return Er(Si)?ye(r):null}let G=ct(p,n.strict?void 0:n.shellAssignments);if(G.kind==="dynamic")return ye(r);if(G.kind==="literal")return ai(G.source,M,b,n,r,t);let te=jf(p,n.commandView?.redirections??[],n.hasPipelineInput??!1,n.literalShellInput);if(te.kind==="dynamic")return ye(r);if(te.kind==="literal")return r?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:te.source,depth:t+1}),n.analyzeNested(te.source,{effectiveCwd:M,envAssignments:b})}}if(!s&&(E==="source"||E===".")){let x=h[1]==="-p"?2:null;if(x!==null){let Qt=n.commandView?p[x]:void 0;if(!Qt)return null;if(Qt.provenance!=="literal")return ye(r)}let P=x===null?1:3,G=h[P]==="--"?P+1:P,te=n.commandView?p[G]:void 0;if(!te)return null;if(te.provenance==="literal")return ai(te.text,M,b,n,r,t);if(n.strict||!n.commandView||!Na(n.commandView))return ye(r)}if(Ae.has(E)&&!l){if(!s&&n.strict&&Ha(yr(h),p))return ye(r);let x=tf(h,(G)=>wn(n.analyzeNested(G,{effectiveCwd:M,envAssignments:b}))),P=w(x,n.policy);if(P)return r?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:P.reason}),de(P)}if(Oe(E)&&!l){if(!s&&n.strict&&Ha(Eo(h),p))return ye(r);let x=Ju(h);if(a&&s)return $R(E,x,M,b,n,s);if(x){let P=ee(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(r?.recordSegment({type:"interpreter",interpreter:E,codeArg:x,paranoidBlocked:P}),P){let te=w(v("interpreter.one-liner-paranoid",or),n.policy);if(te)return de(te)}if(qs(E,x))return null;r?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:x,depth:t+1});let G=n.analyzeNested(x,{effectiveCwd:M,envAssignments:b});if(G&&!Mm(G,x))return G;if(ir(x,void 0,!n.strict)){let te=w(v("interpreter.dangerous-command",pn),n.policy);if(te)return r?.recordSegment({type:"dangerous-text",token:x,matched:!0,reason:pn}),de(te)}r=void 0}}if(E==="busybox"&&h.length>1)return Tm(C.wrapperNormalizationBudget),r?.recordSegment({type:"busybox",subcommand:h[1]??"unknown"}),r?.recordSegment({type:"recurse",reason:"busybox",innerCommand:h.slice(1).join(" "),depth:t+1}),Pn(p.slice(1),t,{...C,effectiveCwd:M,envAssignments:b});let z=s?null:w(af(E,h),n.policy);if(z)return r?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:z.reason}),de(z);let D=r===C.trace?C:{...C,trace:r},se={words:p,head:E,cwd:I,originalCwd:T,envAssignments:b,allowTmpdirVar:Y,dynamicArguments:m.words.some((x)=>x.provenance==="command-substitution"),depth:t,effectiveCwd:M,options:D,analyzeChildTokens:(x,P)=>a&&s?Ka(x,t,D,{...s,cwd:P??void 0,effectiveCwd:P??void 0}):wn(Pn(K(x),t+1,{...D,child:void 0,commandView:void 0,effectiveCwd:P,envAssignments:b}))??it(x,D.policy.rules),analyzeChild:(x,P)=>Ka(x,t,D,P)},J=s&&(E==="xargs"||E==="parallel")?void 0:Om(E);if(E==="rm"||E==="xargs"||E==="parallel")r?.recordSegment({type:"tmpdir-check",tmpdirValue:b.has("TMPDIR")||n.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:Y});let Q=r&&E==="git"?Nf(se.words,ja(se)):void 0,be=km(Q?Q.match:J?.(se)??null,n.policy);if(r)VR(se,be,Q?.relaxation??null);if(be)return de(be);if(a&&s&&(E==="rm"||E==="rmdir")){if(!(E==="rm"&&(st(h)||s.dynamicRmInput)))return null;return(s.dynamicRmInput?In(s,n.policy):null)??UR(s,n.policy)}let It=!s&&J===void 0&&!Hr.has(E),Mn=r&&It?[]:void 0;if(It)for(let x=1;x<h.length;x++){let P=h[x];if(!P)continue;Mn?.push(P);let G=km(BR(h,x,t,D,I,T,M,b),n.policy);if(G)return r?.recordSegment({type:"fallback-scan",tokensScanned:Mn??[],embeddedCommandFound:k(P)}),de(G)}if(r?.recordSegment({type:"fallback-scan",tokensScanned:Mn??[]}),l&&s&&!s.wrappedByTransparent)return null;let we=it(h,n.policy.rules);if(r?.recordSegment({type:"custom-rules-check",rulesChecked:n.policy.rules.length>0,matched:!!we,reason:we?.reason}),we)return de(we);return a&&s?In(s,n.policy):null}function Ka(e,t,n,r){return wn(Pn(K(e),t+1,{...n,trace:void 0,commandView:void 0,hasPipelineInput:void 0,literalShellInput:void 0,functionDefinitions:void 0,cwd:r.originalCwd,effectiveCwd:r.effectiveCwd,envAssignments:r.envAssignments,worktreeMode:r.dynamicInput?!1:r.worktreeMode,wrapperNormalizationBudget:{iterations:0},child:r}))}function BR(e,t,n,r,o,i,s,a){for(let l of ze(e.slice(t),{environment:r.environment,cwd:o,envAssignments:a,policy:r.policy})){let c=l.tokens[0];if(!c)continue;let u=k(c);if(Dm(c,u)||Om(u)!==void 0&&u!=="xargs"&&u!=="parallel"||l.wrappedByTransparent&&r.policy.rules.length>0)r.budget.charge("derivedTokens",e.length-t);let d=Ka(l.tokens,n,r,{embedded:!0,cwd:l.cwd,originalCwd:l.wrapperCwd===null?void 0:i,effectiveCwd:l.wrapperCwd===void 0?s:l.wrapperCwd,envAssignments:l.envAssignments,allowTmpdirVar:!fr(l.envAssignments,r.environment),worktreeMode:!1,wrappedByTransparent:l.wrappedByTransparent});if(d)return d}return null}function $R(e,t,n,r,o,i){if(!t)return In(i,o.policy);if(ee(o.policy,"interpreter.one-liner-paranoid",!!o.paranoidInterpreters)){let a=w(v("interpreter.one-liner-paranoid",or),o.policy);if(a)return de(a)}if(qs(e,t))return In(i,o.policy);let s=o.analyzeNested(t,{effectiveCwd:n,envAssignments:r});if(s&&!Mm(s,t))return s;if(ir(t,void 0,!o.strict)){let a=w(v("interpreter.dangerous-command",pn),o.policy);if(a)return de(a)}return In(i,o.policy)}function Mm(e,t){let n=e.ruleId==="raw-text.dangerous-command",r=(e.reason.startsWith(zo)||e.reason===Sn)&&!jr(t);return n||r}function An(e,t){let n=e.shellDynamicMatch?w(e.shellDynamicMatch,t):null;return n?de(n):null}function In(e,t){let n=e.dynamicSourceInput&&e.dynamicSourceMatch?w(e.dynamicSourceMatch,t):null;return n?de(n):null}function UR(e,t){let n=e.dynamicInput&&e.rmDynamicMatch?w(e.rmDynamicMatch,t):null;return n?de(n):null}function HR(e,t,n,r,o,i){let s=uf(e);if(s.argvSource?.kind==="absent")return ye(o);if(s.argvSourceApplies&&s.argvSource){let l=ai(s.argvSource.value,n,t,r,o,i,!0);if(l)return l}if(!s.envSourceApplies||!s.envName)return null;let a=t.get(s.envName);if(!a)return null;return ai(a,n,t,r,o,i,!0)}function ai(e,t,n,r,o,i,s=!1){if(s&&/[$`*?[\]]/.test(e))return ye(o);let a=rr(e,t,r.environment.paths,r.budget),l=a?r.literalHeredocFiles?.get(a):void 0;if(l===void 0)return s?ye(o):null;return r.budget.charge("derivedTokens",1),o?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:l,depth:i+1}),r.analyzeNested(l,{effectiveCwd:t,envAssignments:n})}function jR(e){let t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.at(-1)===t?e.slice(1,-1):e}function VR(e,t,n){let r={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[e.head];if(!r)return;if(e.options.trace?.recordSegment({type:"rule-check",rule:r,matched:!!t||!!n,reason:t?.reason??n?.originalReason}),n)e.options.trace?.recordSegment({type:n.kind==="worktree"?"worktree-relaxation":"temp-root-relaxation",originalReason:n.originalReason,gitCwd:n.gitCwd})}function Tm(e){if(e.iterations>=V.wrapperPeelIterations.cap)throw new N("wrapperPeelIterations");e.iterations++}function de(e){return{reason:e.reason,ruleId:e.id,intent:e.intent}}function ye(e){return e?.recordSegment({type:"error",message:gr}),de(KR())}function KR(){return{id:"analysis.dynamic-shell-source",reason:gr,intent:"stop_and_explain"}}function Dm(e,t){return q.has(t)||e==="$SHELL"||e==="${SHELL}"||q.has(A(t))}function km(e,t){return e?.id.startsWith("custom.")||e?.id==="raw-text.dangerous-command"?e:w(e,t)}var qR=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,YR=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function ZR(e,t){let n=Wm(e,t);if(n.length===0)return!1;let r=n[Lm(n)];if(r==="cd"||r==="pushd"||r==="popd")return!0;return qR.test(e.join(" "))}function Nm(e,t,n,r,o){if(e.dialect==="powershell"){let y=XR(e.words,o);if(y.kind==="none")return;if(!t||y.kind==="unknown")return null;return Va(t_(y.target),t,n.paths)}let i=e.words.map(_),s=i.some((y)=>/^CDPATH\+?=/.test(y));if(!ZR(i,n))return s?null:void 0;if(!t)return null;let a=Wm(i,n,t),l=Lm(a);if(l===-1||a[l]!=="cd")return null;let c=a.slice(l+1),u=c.findIndex((y)=>y.length<=1||!y.startsWith("-")||y==="--");if((u===-1?c:c.slice(0,u)).some((y)=>!/^-[LP]+$/.test(y)))return null;let d=u===-1?[]:c.slice(u),m=d[0]==="--"?d.slice(1):d;if(m.length>1)return null;let g=m[0],p=r.get("HOME")||n.home;if(g===void 0)return Va(p,t,n.paths);let h=e.words.find((y)=>y.provenance==="variable"&&y.text===g),C=e.words.find((y)=>y.text===g&&/^~(?:\/|$)/.test(y.raw)),b=h?qe(h,new Map([...r,["HOME",p]])):C?`${p}${g.slice(1)}`:g;if(b===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(b)&&(s||n.env.has("CDPATH")))return null;return Va(b,t,n.paths)}function Va(e,t,n){if(!e||e==="-"||e.startsWith("~")||e.includes("$")||e.includes("`"))return null;try{let r=yt(t,e,n);return n.isDirectory(r)?r:null}catch{return null}}function XR(e,t){let n=JR(e[0])?1:0,r=e[n];if(!QR(r,n===1))return{kind:"none"};let o=r.text.toLowerCase(),i=o.split(/[\\/]/).pop()??o;if(!YR.has(i))return{kind:"none"};if(o!==i||i==="pop-location"||i==="popd")return{kind:"unknown"};return e_(e.slice(n+1),t)}function JR(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&(e.text==="&"||e.text===".")}function QR(e,t){return e?.provenance==="literal"&&(t||!e.quoted&&e.raw===e.text)}function e_(e,t){let n;for(let r of e){if(r.provenance!=="literal"||n!==void 0)return{kind:"unknown"};n=r.text}if(n!==void 0)return{kind:"target",target:n};return t===void 0?{kind:"unknown"}:{kind:"target",target:t}}function t_(e){return e.includes("::")?void 0:e.replaceAll("\\","/")}function Lm(e){let t=0;if(e[0]==="builtin"&&e.length>1)t=1;if(e[t]!=="time")return t;let n=t+1;while(e[n]?.startsWith("-"))n++;return n}function Wm(e,t,n){let r=n_(e);return Ct([...r],t,n)}function n_(e){let t=0;while(t<e.length){let n=e[t];if(n!=="{"&&n!=="("&&n!=="$(")break;t++}return e.slice(t)}var c_="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",qt="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 Qa(e,t,n,r){if(t>=V.recursionDepth.cap)return n.trace?.recordSegment({type:"error",message:He}),{reason:He,segment:e,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};let o=r??n.factStore?.getCommandProgram(e,n.shell??"auto")??Me(e,n.shell);if(o.status==="limited")return n.trace?.recordSegment({type:"error",message:He}),{reason:He,segment:e,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};if(o.status==="invalid"){let c=o.issues.find((u)=>u.code.includes("heredoc"));if(c){if(!n.strict)return Ja(e,n);let u=`${zo}: ${c.message}`;return n.trace?.recordGlobal({type:"error",message:u}),{reason:u,segment:e,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"}}return Um(e,n),{reason:Sn,segment:e,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"}}if(n.strict&&o.status==="partial")return Um(e,n),{reason:Sn,segment:e,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"};if(o.issues.some((c)=>c.code.includes("quote")))return Ja(e,n);let s=n.cwd,a=n.effectiveCwd!==void 0?n.effectiveCwd:n.cwd,l=xf(n.environment.env,n.envAssignments);return ui(o,t,{...n,rootProgram:o},s,[{effectiveCwd:a,shellGitContextState:l,literalHeredocFiles:new Map(n.literalHeredocFiles),functionDefinitions:new Map(n.functionDefinitions),createdDirectories:new Set,compoundBodies:[]}]).result}function ui(e,t,n,r,o){let i=[...o],s,a,l;for(let[c,u]of e.nodes.entries()){if(u.kind==="connector"){a=u.operator;continue}let f=e.nodes[c+1],d=f?.kind==="connector"?f.operator:void 0,m=u_(e,c,u,a,d),p=a==="&&"||a==="||"?s:void 0,h=a==="&&"?p?.success??i:a==="||"?p?.failure??i:i,C=a==="||"?p?.success??[]:[],b=a==="&&"?p?.failure??[]:[],y={connector:a,skippedSuccessStates:C,skippedFailureStates:b};if(_t(d)&&!_t(a))l=y;let E=_t(d)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:_t(a)?l??y:y,I=Yt(E.connector)||Yt(d);if(u.kind==="function"){let z=h.flatMap((se)=>{let J=Zt(se);return J.functionDefinitions.set(u.name,u.body),qa(se,[J],m,d==="&",Yt(d))}),D=Ya(z,[],E.skippedSuccessStates,E.skippedFailureStates,E.connector,d);i=D.states,s=D.conditionalStates,a=void 0;continue}if(u.kind==="group"){let z=[],D=[];for(let J of h){let Q=ui(u.body,t,n,r,[Zt(J)]);if(Q.result)return Q;if(z.push(...qa(J,Q.states,m,d==="&",Yt(d))),I)D.push(J,...m?Q.states.map((be)=>li(J,be)):Q.states)}let se=Ya(z,D,E.skippedSuccessStates,E.skippedFailureStates,E.connector,d);i=se.states,s=se.conditionalStates,a=void 0;continue}if(u.kind!=="command")continue;let T=M_(e.nodes[c-1]),M=n.trace?.flattenNested?n.trace.currentSegmentIndex:n.trace?.allocateSegment(),Y=e.nodes[c-2],ue=_t(a)&&Y?.kind==="command"?$f(Y)??f_(Y):void 0,Xe=[],Ce=[];for(let z of h){let D=m_(u,t,n,r,[Zt(z)]);if(D.result)return{result:D.result,states:i};let se=e.dialect==="powershell"?D.states:D.states.map((J)=>li(z,J));for(let J of se){let Q=Zt(J),be=h_(u,t,n.trace?{...n,trace:Hm(n.trace,M)}:n,r,Q,_t(a),ue);if(be)return{result:be,states:i};let On=z_(u,Q.functionDefinitions);if(On)n.budget.charge("derivedTokens",di(On));let It=On?t+1>=V.recursionDepth.cap?Za(u.displayText,n,[Q]):ui(On,t+1,n,r,[Q]):{result:null,states:G_(u,Q).flatMap((we)=>D_(u,J,we,T))};if(It.result)return It;Xe.push(...qa(z,It.states,m,d==="&",Yt(d)));let Mn=typeof Q.effectiveCwd==="string"&&Q.effectiveCwd!==J.effectiveCwd&&u.redirections.every((we)=>["<",">",">>",">|"].includes(we.operator)&&we.target?.text==="/dev/null");if(I&&(T||!Mn))Ce.push(z),Ce.push(...It.states.map((we)=>m?li(z,we):we))}}let Pt=Ya(Xe,Ce,E.skippedSuccessStates,E.skippedFailureStates,E.connector,d);i=Pt.states,s=Pt.conditionalStates,a=void 0}return{result:null,states:i}}function u_(e,t,n,r,o){if(n.kind==="group"&&n.style==="subshell")return!0;if(e.dialect==="posix"&&(_t(r)||_t(o)))return!0;if(o==="&")return!0;return e.dialect==="powershell"&&n.kind==="group"&&n.style==="brace"&&d_(e,t)}function qa(e,t,n,r,o){let i=n?t.map((a)=>li(e,a)):[...t],s=o?i.flatMap((a)=>Tn(e.literalHeredocFiles,a.literalHeredocFiles)?[a]:[{...a,literalHeredocFiles:new Map(e.literalHeredocFiles)},a]):i;return r?[e,...s]:s}function li(e,t){return{...e,literalHeredocFiles:new Map(t.literalHeredocFiles),createdDirectories:new Set(t.createdDirectories)}}function d_(e,t){let n=e.nodes.slice(0,t).reverse().find((o)=>o.kind==="command"||o.kind==="connector");if(!n||n.kind!=="command")return!0;let r=n.words[0]?.text.toLowerCase();if(r==="&"||r===".")return!1;if(r==="write-output"||r==="function"||r==="start-job")return!0;if(p_(n))return!0;return n.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function _t(e){return e==="|"||e==="|&"}function f_(e){if(e?.dialect!=="powershell")return;if(e.words.length===1&&e.words[0]?.quoted&&e.words[0].provenance==="literal")return e.words[0].text;if(e.words[0]?.text.toLowerCase()==="write-output"&&e.words.length===2&&e.words[1]?.provenance==="literal")return e.words[1].text;return}function Yt(e){return e==="&&"||e==="||"}function Ya(e,t,n,r,o,i){let s={success:ci([...n,...e]),failure:ci([...r,...t])},a=Yt(i)?s:void 0;return{states:Yt(o)||a?ci([...s.success,...s.failure]):s.success,conditionalStates:a}}function Hm(e,t,n=e.flattenNested){return{currentSegmentIndex:t,flattenNested:n,allocateSegment:e.allocateSegment,getNextSegmentIndex:e.getNextSegmentIndex,recordGlobal:e.recordGlobal,recordSegment:(r,o=t)=>e.recordSegment(r,o)}}function m_(e,t,n,r,o){let i=e.nested.map((s)=>({program:s,depth:t}));if(e.dialect==="powershell"){let s=g_(e);if(s){if(t+1>=V.recursionDepth.cap)return Za(s,n,o);let a=Me(s,"powershell");if(a.status==="limited")return Za(s,n,o);if(a.status!=="complete")return Gm(i,n,r,o);n.budget.charge("derivedTokens",di(a)),i.push({program:a,depth:t+1})}}return Gm(i,n,r,o)}function p_(e){let t=e.words[0];return t?.provenance==="variable"&&e.words.at(-1)?.text==="="?t.text.toLowerCase():void 0}function Gm(e,t,n,r){let o=[...r];for(let i of e){let s=[];for(let a of o){let l=ui(i.program,i.depth,t,n,[Zt(a)]);if(l.result)return l;s.push(...l.states)}o=ci(s)}return{result:null,states:o}}function g_(e){let t=e.words[0]?.provenance==="literal"&&!e.words[0].quoted&&e.words[0].raw===e.words[0].text&&(e.words[0].text==="&"||e.words[0].text==="."),n=t?1:0,r=e.words[n];if(r?.provenance!=="literal"||!t&&(r.quoted||r.raw!==r.text)||!["iex","invoke-expression"].includes(r.text.toLowerCase()))return;let o=e.words.slice(n+1),i=o[0]&&!o[0].quoted&&o[0].raw===o[0].text&&["-c","-command"].includes(o[0].text.toLowerCase())?1:0,s=o[i];return o.length===i+1&&s?.quoted&&s.provenance==="literal"?s.text:void 0}function di(e){return e.nodes.reduce((t,n)=>t+(n.kind==="command"?n.words.length+n.nested.reduce((r,o)=>r+di(o),0):n.kind==="group"||n.kind==="function"?di(n.body):0),0)}function Za(e,t,n){return t.trace?.recordSegment({type:"error",message:He}),{result:{reason:He,segment:e,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"},states:[...n]}}function h_(e,t,n,r,o,i,s){let a={...n,environment:{...n.environment,env:o.shellGitContextState.env,paths:v_(n.environment.paths,o.createdDirectories,n.budget)}},l=A_(e,!a.strict);if(l&&a.strict)return a.trace?.recordSegment({type:"error",message:l}),{reason:l,segment:e.source,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"};jm(e,o,"before-consumer",a.environment.paths,a.budget);let c=dn(e.dialect,e.words),u=c.map(_),f=e.displayText,d=vf(c,o.shellGitContextState),m=_f(d,o.shellGitContextState);if(e.dialect==="powershell"){let h=w(Kd(e,i,$_(a,o.effectiveCwd)),a.policy);if(a.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!h,reason:h?.reason}),h)return B_(f,h)}if(u.length===1&&u[0]?.includes(" ")&&!Zn(e.dialect,e.words)){let h=w(Pe(u[0]),a.policy),C=h!==null&&!a.strict&&qu(e,a.rootProgram);if(h&&!C)return a.trace?.recordSegment({type:"dangerous-text",token:u[0],matched:!0,reason:h.reason}),{reason:h.reason,segment:f,ruleId:h.id,intent:h.intent};a.trace?.recordSegment({type:"dangerous-text",token:u[0],matched:!1});let b=Fm(e,l,o,m,s,a);if(b)return b;return Ia(d,o.shellGitContextState),null}let g=Pn(e.words,t,{...a,commandView:e,cwd:r,effectiveCwd:o.effectiveCwd,envAssignments:m,shellAssignments:o.shellGitContextState.shellAssignments,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:o.functionDefinitions,hasPipelineInput:i,literalShellInput:s,analyzeNested:(h,C)=>{let b=C&&Object.hasOwn(C,"effectiveCwd")?C.effectiveCwd:o.effectiveCwd,y=Qa(h,t+1,{...a,effectiveCwd:b,envAssignments:C?.envAssignments??m,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:C?.functionDefinitions,worktreeMode:C?.worktreeMode??a.worktreeMode,trace:a.trace?Hm(a.trace,a.trace.currentSegmentIndex,!0):void 0});return y?{reason:y.reason,ruleId:y.ruleId,intent:y.intent}:null}});if(g)return{...g,segment:f};let p=Fm(e,l,o,m,s,a);if(p)return p;return Ia(d,o.shellGitContextState),null}function Fm(e,t,n,r,o,i){let s=P_(e,t,n,r??new Map,i);if(s)return s;return jm(e,n,"after-consumer",i.environment.paths,i.budget),n.literalHeredocFiles.clear(),b_(e,t,n,i.environment.paths,i.budget),E_(e,n,i.environment.paths,i.budget),k_(e,n,o,i.environment,i.trace),null}var y_=new Set([">>","<>"]);function jm(e,t,n,r,o){for(let s of e.redirections){if(!(n==="before-consumer"?C_(s):y_.has(s.operator)))continue;zm(s.target,t,r,o)}if(n!=="before-consumer"||!ie(e.words[0],"tee"))return;let i=Km(e.words.slice(1));if(!i)return;for(let s of i.operands)zm(s,t,r,o)}function C_(e){if(e.operator===">"||e.operator===">|")return!0;return e.operator===">&"&&e.fd===void 0&&e.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(e.target.text)}function zm(e,t,n,r){let o=e?.provenance==="literal"?rr(e.text,t.effectiveCwd,n,r):void 0;if(!o)return;t.literalHeredocFiles.delete(o)}function b_(e,t,n,r,o){if(t)return;let i=e.redirections.find((s)=>s.operator==="<<"||s.operator==="<<-")?.heredoc;if(!i)return;for(let s of S_(e,n.shellGitContextState.shellAssignments)){let a=rr(s,n.effectiveCwd,r,o);if(!a||!Xu(a))continue;if(!n.literalHeredocFiles.has(a)&&n.literalHeredocFiles.size>=V.trackedHeredocFiles.cap)throw new N("trackedHeredocFiles");n.literalHeredocFiles.set(a,i.body)}}function S_(e,t){let n=Xa(__(e.redirections)?.target,t),r=n===void 0?[]:[n];if(ie(e.words[0],"cat"))return R_(e.words)?r:[];if(!ie(e.words[0],"tee"))return[];let o=Km(e.words.slice(1),t);if(!o||o.append||o.hasUnsupportedOptions)return[];let i=o.operands.map((s)=>Xa(s,t));if(!i.every((s)=>s!==void 0))return[];return[...i,...r]}function Xa(e,t){if(w_(e))return e.text;return(e&&qe(e,t))??void 0}function v_(e,t,n){if(t.size===0)return e;let r=(o)=>{let i=L(o,e,n);return[...t].some((s)=>s===i||s.startsWith(`${i}${l_}`))};return{realpath:(o)=>e.realpath(o)??(r(o)?L(o,e,n):null),entryKind:(o)=>{let i=e.entryKind(o);return i==="missing"&&r(o)?"present":i},isDirectory:(o)=>e.isDirectory(o)||r(o)}}function E_(e,t,n,r){if(t.shellGitContextState.bodyDepth>0||!ie(e.words[0],"mkdir"))return;let o=e.words.slice(1).map((c)=>Xa(c,t.shellGitContextState.shellAssignments));if(!o.every((c)=>c!==void 0))return;let i=o.findIndex((c)=>c==="--"||c==="-"||!c.startsWith("-")),s=o.slice(0,i);if(i===-1||!s.every((c)=>/^(?:-[pv]+|--parents|--verbose)$/.test(c)))return;let a=s.some((c)=>c==="--parents"||/^-v*p/.test(c)),l=t.effectiveCwd;for(let c of o.slice(o[i]==="--"?i+1:i)){if(c.split(/[\\/]/).includes("..")||!o_(c)&&!l)continue;let u=L(a_(l??"",c),n,r);if(a?x_(u,n):n.isDirectory(r_(u))&&Vm(u,n))t.createdDirectories.add(u)}}function x_(e,t){let n=s_(e).root,r=e.slice(n.length).split(/[\\/]+/).filter(Boolean),o=(s)=>i_(n,...r.slice(0,s+1)),i=r.findIndex((s,a)=>!t.isDirectory(o(a)));return i===-1||Vm(o(i),t)}function Vm(e,t){try{return t.entryKind(e)==="missing"}catch{return!1}}function R_(e){let t=!1;for(let n of e.slice(1)){if(t||n.provenance!=="literal")return!1;if(n.text==="--"){t=!0;continue}if(!/^-u+$/.test(n.text))return!1}return!0}function __(e){let t=e.findLast((n)=>(n.fd??([">",">|",">>",">&"].includes(n.operator)?1:0))===1);return t?.operator===">"||t?.operator===">|"?t:void 0}function Km(e,t=new Map){let n=[],r=!0,o=!1,i=!1;for(let s of e){if(s.provenance!=="literal"&&qe(s,t)===null)return;if(r&&ie(s,"--")){r=!1;continue}if(r&&!s.quoted&&s.raw===s.text&&/^-[^-]/.test(s.text)){o||=s.text.slice(1).includes("a"),i||=Array.from(s.text.slice(1)).some((a)=>a!=="a"&&a!=="i");continue}if(r&&!s.quoted&&s.raw===s.text&&s.text.startsWith("--")){o||=s.text==="--append",i||=s.text!=="--append"&&s.text!=="--ignore-interrupts";continue}n.push(s)}return{operands:n,append:o,hasUnsupportedOptions:i}}function w_(e){if(!e||e.provenance!=="literal"||e.text.length===0)return!1;if(e.quoted||e.raw!==e.text)return!0;return!e.raw.startsWith("~")&&!/[{}]/.test(e.raw)}function ie(e,t){return e?.text===t&&e.raw===t&&e.provenance==="literal"&&!e.quoted}function el(e){return e.quotedDelimiter||!/[$`\\]/.test(e.body)}function A_(e,t){let n=e.redirections.filter((l)=>l.operator==="<<"||l.operator==="<<-");if(n.length===0)return;if(n.length!==1)return qt;let r=n[0];if(!r?.heredoc)return qt;let o=/\$\(|`/.test(r.heredoc.body);if(!el(r.heredoc)&&(!t||o))return c_;if(r.fd!==void 0&&r.fd!==0)return qt;if(e.redirections.some((l)=>l!==r&&["<","<<","<<-","<<<","<&","<>"].includes(l.operator)))return qt;let i=e.redirections.some((l)=>l!==r&&Bm(l.target));if(ie(e.words[0],"cat"))return i?qt:void 0;if(ie(e.words[0],"tee"))return i||e.words.slice(1).some(Bm)?qt:void 0;let s=e.words[0],a=e.words[1];if(ie(s,"git")&&(ie(a,"apply")||ie(a,"commit")))return;if(ie(s,"gh")&&(ie(a,"pr")||ie(a,"issue"))&&ie(e.words[2],"create"))return;return qt}function Bm(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}function P_(e,t,n,r,o){if(!t)return null;let i=e.redirections.filter((c)=>c.operator==="<<"||c.operator==="<<-"),s=i.flatMap((c)=>c.heredoc?[c.heredoc.body]:[]);if(T_(e,i,n,r,o))return null;let a=I_(e,i,o);if(a!==void 0)return a?{reason:a.reason,segment:e.displayText,ruleId:a.id,intent:a.intent}:null;let l=Ja(s.length===i.length?s.join(`
43
- `):e.source,o);return l?{...l,segment:e.displayText}:null}function I_(e,t,n){let r=t.length===1?t[0]:void 0;if(!r?.heredoc||!el(r.heredoc)||r.fd!==void 0&&r.fd!==0)return;let o=ie(e.words[0],"uv")&&ie(e.words[1],"run")?e.words.slice(2):e.words,i=o[0];if(i?.provenance!=="literal"||!Oe(i.text))return;let s=o.findIndex((f)=>ie(f,"-"));if(!o.slice(1,s===-1?void 0:s).every((f)=>f.provenance==="literal"&&f.text.startsWith("-")))return;let l=r.heredoc.body,c=ee(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(n.trace?.recordSegment({type:"interpreter",interpreter:i.text,codeArg:l,paranoidBlocked:c}),c){let f=w(v("interpreter.one-liner-paranoid",or),n.policy);if(f)return f}if(!ir(l,void 0,!n.strict))return null;let u=w(v("interpreter.dangerous-command",pn),n.policy);if(!u)return null;return n.trace?.recordSegment({type:"dangerous-text",token:l,matched:!0,reason:u.reason}),u}function T_(e,t,n,r,o){let i=t.length===1?t[0]:void 0;if(!i?.heredoc||!el(i.heredoc)||i.fd!==void 0&&i.fd!==0)return!1;let s=Gt(e.words,o.environment,n.effectiveCwd,r),a=s.words.map(_),l=k(a[0]??"");if((s.envSplitValues?.length??0)>0||!q.has(l)&&!q.has(A(l)))return!1;return at(a)}function k_(e,t,n,r,o){let i=Nm(e,t.effectiveCwd,r,t.shellGitContextState.shellAssignments,n);if(i===null)o?.recordSegment({type:"cwd-change",segment:e.words.map(_).join(" "),effectiveCwdNowUnknown:!0});if(i!==void 0)t.effectiveCwd=i}var O_=new Set(["fi","done","esac"]);function M_(e){return e?.kind==="command"&&e.words.length===1&&e.words[0]?.raw==="!"}function D_(e,t,n,r){let o=e.words[0]?.text??"",i=t.shellGitContextState.bodyDepth,s=n.shellGitContextState.bodyDepth,a=n.compoundBodies;if(s>i)return n.compoundBodies=[...a.slice(0,i),{entryCwd:t.effectiveCwd,branchCwds:a[i]?.branchCwds??[],hasElse:!1}],[n];let l=i>0?a[i-1]:void 0;if(l&&(o==="else"||o==="elif"))return n.compoundBodies=[...a.slice(0,i-1),{entryCwd:l.entryCwd,branchCwds:[...l.branchCwds,n.effectiveCwd],hasElse:o==="else"}],n.effectiveCwd=l.entryCwd,[n];let c=l!==void 0&&O_.has(o);if(c)n.compoundBodies=a.slice(0,s);return[...new Set([n.effectiveCwd,...c?l.branchCwds:[],...c&&!l.hasElse?[l.entryCwd]:[],...r?[t.effectiveCwd]:[]])].map((f)=>{if(f===n.effectiveCwd)return n;let d=Zt(n);return d.effectiveCwd=f,d})}function N_(e,t){return e.length===t.length&&e.every((n,r)=>{let o=t[r];return o!==void 0&&n.entryCwd===o.entryCwd&&n.hasElse===o.hasElse&&n.branchCwds.length===o.branchCwds.length&&n.branchCwds.every((i,s)=>i===o.branchCwds[s])})}var L_=/^[A-Za-z_][A-Za-z0-9_]*$/,W_=8;function G_(e,t){let n=e.words[1]?.text;if(e.dialect!=="posix"||e.words[0]?.text!=="for"||n===void 0||!L_.test(n))return[t];let r=e.words.slice(3);if(!(e.words[2]?.text==="in"&&r.length>=1&&r.length<=W_&&r.every((i)=>i.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(i.text))))return t.shellGitContextState.shellAssignments.delete(n),[t];return r.map((i)=>{let s=Zt(t);return s.shellGitContextState.shellAssignments.set(n,i.text),s})}function Zt(e){return{effectiveCwd:e.effectiveCwd,shellGitContextState:Rf(e.shellGitContextState),literalHeredocFiles:new Map(e.literalHeredocFiles),functionDefinitions:new Map(e.functionDefinitions),createdDirectories:new Set(e.createdDirectories),compoundBodies:e.compoundBodies}}function ci(e){let t=[];for(let n of e){if(!t.some((r)=>F_(r,n)))t.push(n);if(t.length>V.controlFlowStates.cap)throw new N("controlFlowStates")}return t}function F_(e,t){return e.effectiveCwd===t.effectiveCwd&&N_(e.compoundBodies,t.compoundBodies)&&Tn(e.shellGitContextState.env,t.shellGitContextState.env)&&Tn(e.literalHeredocFiles,t.literalHeredocFiles)&&Tn(e.functionDefinitions,t.functionDefinitions)&&Tn(e.shellGitContextState.effectiveEnvAssignments,t.shellGitContextState.effectiveEnvAssignments)&&Tn(e.shellGitContextState.shellAssignments,t.shellGitContextState.shellAssignments)&&e.shellGitContextState.bodyDepth===t.shellGitContextState.bodyDepth&&$m(e.shellGitContextState.bodyAssignments,t.shellGitContextState.bodyAssignments)&&$m(e.createdDirectories,t.createdDirectories)}function $m(e,t){return e.size===t.size&&[...e].every((n)=>t.has(n))}function Tn(e,t){if(e===t)return!0;if(!e||!t||e.size!==t.size)return!1;return[...e].every(([n,r])=>t.get(n)===r&&t.has(n))}function z_(e,t){let n=Xn(e);return n===void 0?void 0:t.get(n)}function B_(e,t){if(!t)return null;return{reason:t.reason,segment:e,ruleId:t.id,intent:t.intent}}function $_(e,t=e.effectiveCwd){let n=t===null;return{environment:e.environment,cwd:n?void 0:t??e.cwd,originalCwd:n?void 0:e.cwd,strict:e.strict,paranoid:e.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,protectedGitMetadata:e.protectedGitMetadata,policy:e.policy,budget:e.budget}}function Ja(e,t){let n=w(Pe(e),t.policy),r=t.trace?.currentSegmentIndex??t.trace?.allocateSegment(),o={type:"dangerous-text",token:e,matched:!!n,reason:n?.reason};if(t.trace?.recordSegment(o,r),!n&&/^(?:cd|pushd)\s/.test(e))t.trace?.recordSegment({type:"cwd-change",segment:e,effectiveCwdNowUnknown:!0},r);return n?{reason:n.reason,segment:e,ruleId:n.id,intent:n.intent}:null}function Um(e,t){let n={type:"strict-unparseable",rawCommand:e,reason:Sn},r=t.trace?.currentSegmentIndex;if(r===void 0)t.trace?.recordGlobal(n);if(r!==void 0)t.trace?.recordSegment(n)}var U_=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function qm(e,t,n,r){let o=Qa(e,0,{...t,...gu(t),budget:t.budget??je(),factStore:r},n);if(!o)return null;return{kind:"deny",reason:o.reason,intent:o.intent??"manual_only",ruleId:o.ruleId,evidence:{command:e,segment:o.segment}}}function Ym(e,t,n){try{return{decision:e()}}catch(r){let o=H_(r,t,n);if(!o)throw r;return o}}function H_(e,t,n){if(!(e instanceof N)||!U_.has(e.kind))return null;let r=V[e.kind];if(n?.currentSegmentIndex!==void 0)n.recordSegment({type:"error",message:r.reason});if(n?.currentSegmentIndex===void 0)n?.recordGlobal({type:"error",message:r.reason});return{decision:{kind:"deny",reason:r.reason,ruleId:"analysis.derived-command-limit",intent:"stop_and_explain",evidence:{command:t,segment:t}},errorCode:r.errorCode}}var j_=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),nl=new Set(["cc-safety-net","ccsn"]),V_=new Set(["bunx","npx","pnpx"]),K_=new Set(["pnpm","yarn"]),q_=new Set(["npm","pnpm","yarn"]),Y_=new Set(["bun","node"]);function mi(e,t,n={}){if(nl.has(e))return 0;if(V_.has(e)){if(n.broad)return tl(t);let o=t[0]==="-y"||t[0]==="--yes"?1:0;return fi(t[o])?o+1:null}let r=n.broad?t.findIndex((o)=>!o.startsWith("-")):0;if(r!==-1&&q_.has(e)&&n.broad&&t[r]==="exec"){let o=tl(t.slice(r+1));return o===null?null:r+1+o}if(K_.has(e)){if(e==="yarn"&&!n.broad)return null;if(!n.broad)return t[0]==="dlx"&&fi(t[1])?2:null;if(r===-1||t[r]!=="dlx")return null;let o=tl(t.slice(r+1));return o===null?null:r+1+o}if(Y_.has(e)){let o=n.broad&&r!==-1?r:0;if(Zm(t[o]))return o+1;if(e==="bun"&&t[o]==="run"&&Zm(t[o+1]))return o+2}return null}function tl(e){let t=e.findIndex((r)=>fi(r));if(t===-1)return null;let n=t;while(n<e.length){let r=e[n]??"";if(!r.startsWith("-")&&!fi(r))break;n++}return n}function fi(e){if(!e)return!1;let t=e.indexOf("@");if(t===-1)return nl.has(e);if(t===0)return!1;let n=e.slice(t+1);if(n===""||n.includes("/")||n.includes(":"))return!1;return nl.has(e.slice(0,t))}function Zm(e){let t=e?.replaceAll("\\","/");return[...j_].some((n)=>t===n||t?.endsWith(`/${n}`))}var Xm="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 Jm(e,t,n){let r=ge(e,"input-candidate");if(!r)return null;let o=hn(r.shell,e.invocation.context.executionCwd,t,n,{findSegmentTarget:(i)=>Z_(i,t),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return o?{target:o}:null}function Z_(e,t){let n=Ct([...e],t),r=n.slice(1),o=mi(A(n[0]??"").toLowerCase(),r,{broad:!0});if(o===null)return null;let i=r.slice(o).filter((s)=>s!=="-g"&&s!=="--global");return i[0]==="policy"&&i[1]==="apply"?n.join(" "):null}import{dirname as pi}from"node:path";var np="This path contains the protected policy config and you must not modify or delete it.",X_=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function rp(e,t,n){let r=rw(e.invocation.context,t,n);if(e.invocation.route.kind==="patch")return Qm(e.paths,!1,e.invocation.context.executionCwd,r,t,n);let o=ge(e,"input-candidate");if(e.invocation.route.kind==="command")return o?ep(o.shell,e.invocation.context.executionCwd,r,t,n):null;if(e.invocation.route.kind==="unknown"&&o){let i=ep(o.shell,e.invocation.context.executionCwd,r,t,n);if(i)return i}return Qm(e.paths,e.invocation.route.kind==="grep"||e.invocation.route.kind==="glob"||Dr(e.invocation.toolName),e.invocation.context.executionCwd,r,t,n)}function Qm(e,t,n,r,o,i){if(t)return null;let s=e.find((a)=>_r(a,n,r,o,i));return s?{target:s}:null}function ep(e,t,n,r,o){let i=hn(e,t,r,o,{findSegmentTarget:(s,a)=>J_(s,a,n,r,o)?.target??null,isRedirectionTarget:(s,a)=>_r(s,a.cwd,n,r,o),findMalformedTarget:(s)=>nw(s,t,n,r,o)?.target??null});return i?{target:i}:null}function J_(e,t,n,r,o){if(ur(e))return null;let i=bt([...e],r),s=A(i[0]??"").toLowerCase(),a=i.slice(1);if(s==="rm"&&Q_(a)){let l=ew(a).find((c)=>tp(pe(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(s==="find"){if(Vo(i,1)||va(i,r)){let c=(Cr(K(i))??K(["."])).find((u)=>{let f=pe(u.text,t.variables);return _r(f,t.cwd,n,r,o)||tp(f,t.cwd,n,r,o)})?.text;if(c)return{target:c}}}if(s==="mv"){let l=Mo(a).sources.find((c)=>ow(pe(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(tw(i,s))return null;for(let l of[...e,...i])for(let c of op(l))if(_r(pe(c,t.variables),t.cwd,n,r,o))return{target:c};return null}function Q_(e){return e.some((t)=>t==="--recursive"||t.startsWith("-")&&!t.startsWith("--")&&/[rR]/.test(t.slice(1)))}function ew(e){let t=e.indexOf("--");if(t!==-1)return[...e.slice(0,t).filter((n)=>!n.startsWith("-")),...e.slice(t+1)];return e.filter((n)=>!n.startsWith("-"))}function tw(e,t){if(!X_.has(t))return!1;if(t!=="sed")return!0;return!e.slice(1).some((n)=>n.startsWith("-i")||n==="--in-place"||n.startsWith("--in-place="))}function nw(e,t,n,r,o){for(let i of e.split(/\s+/))for(let s of op(i))if(_r(s,t,n,r,o))return{target:s};return null}function op(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.indexOf("=");return n===-1||n===t.length-1?[t]:[t,t.slice(n+1)]}function rw(e,t,n){let r=(a)=>wr(ae(a,e.executionCwd,t,n)),o=r(on(t)),i=[r(jn(e.executionCwd)),r(jn(e.configCwd))],s=new Set(i.map((a)=>pi(a)));for(let a=pi(o);;a=pi(a))if(s.add(a),pi(a)===a)break;return{files:new Set([o,...i]),directoriesAndAncestors:s}}function _r(e,t,n,r,o){let i=kl(e,t,r,o,(s)=>wr(s)===$r);return i!==null&&n.files.has(wr(i))}function tp(e,t,n,r,o){return n.directoriesAndAncestors.has(wr(ae(e,t,r,o)))}function ow(e,t,n,r,o){let i=wr(ae(e,t,r,o));return n.files.has(i)||n.directoriesAndAncestors.has(i)}function wr(e){return process.platform==="win32"?e.toLowerCase():e}import{isAbsolute as gi,posix as hp,resolve as yi,win32 as iw}from"node:path";import{fileURLToPath as sw}from"node:url";var yp="Access to a sensitive path is not allowed.",Cp=new Set(["echo","printf"]),aw=new Set(["find"]),lw=new Set(["!","do","elif","else","if","then","until","while"]),cw=new Set(["-exec","-execdir"]),uw=new Set([";","+"]),dw=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),fw=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),bp=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),mw=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),pw=new Set(["append","awk","base64","cat","chmod","chown","connect","copy","cp","database","dd","eval","exec","fetch","file","function","grep","head","include","load","move","mv","open","fopen","popen","read","readfile","remove","rename","require","rg","rm","sed","shell","source","spawn","strings","system","tail","tar","truncate","unlink","write","xxd","zip"]),Sp=new Set(["-c","-e","-r","-E","--eval","--exec"]),gw=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"])]]),hw=new Set(["grep","rg"]),yw=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),Cw=new Set(["commit","merge","notes","stash","tag"]),bw=new Set(["-m","--message"]),Sw=new Set(["--grep"]),ip=new Set(["jq","gojq","jaq"]),sp="f",ap="file",vw="files",Ew=new Set(["e","f"]),xw=new Set(["regexp","file"]),Rw=new Set(["e","f","A","B","C","m"]),_w=new Set(["regexp","file","after-context","before-context","context","max-count"]),rl="__CC_SAFETY_NET_PIPE_INPUT__",il=/[\w./~@+-]*[./~][\w./~@+-]*/g,ww=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,Aw=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,Pw=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,lp=/\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,cp=/\b(?:system|exec|spawn|popen)\s*$/,Iw=/\b(?:eval|exec)\s*\(/g,Tw=/\b(?:eval|exec)\s*$/,kw=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 up(e,t,n,r,o,i){for(let s of e){let a=s.target;if(PA(a,s.cwd,t?.denyPaths??[],n,r,o))return{target:a,ruleId:"secret.deny-path"};if(i&&!i.has(a))continue;let l=wA(a,s.cwd,t,r,o);if(l){let c=i!==void 0&&!l.startsWith("secret.home.")&&!l.startsWith("secret.cli.");if(c&&r.paths.isDirectory(Ap(a,s.cwd,r,o)))continue;if(c&&s.isRedirectionWriteTarget===!0&&!a.includes("$")&&!al(a,s.cwd,r,o))continue;if(c&&/\s/.test(a)&&!a.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(a)&&!al(a,s.cwd,r,o))continue;if(!l.startsWith("secret.cli.")&&IA(a,s.cwd,t?.allowPaths??[],n,r,o))continue;return{target:a,ruleId:l}}}return null}function vp(e,t,n,r,o={}){let i=dp(e,n,r),s=up(i,t,e.invocation.context.configCwd,n,r);if(s===null||s.ruleId==="secret.deny-path"||o.strict!==!1)return s;let a=up(i,t,e.invocation.context.configCwd,n,r,new Set(dp(e,n,r,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}).map((l)=>l.target)));return a?.ruleId!=="secret.deny-path"&&Ow(e,n)?null:a}function Ow(e,t){let n=ge(e,"input-candidate")??ge(e,"declared-command");if(!n)return!1;if(n.program.nodes.some((s)=>s.kind==="command"&&s.nested.length>0))return!1;let r=[];for(let s of Oo(n.shell)){if(s.kind==="operator"&&s.boundary)return!1;if(s.kind==="redirection")return!1;if(s.kind==="operator")continue;r.push(ot(s.text,t))}let o=dt(r);if(o.length===0)return!1;let i=Ue(o[0]??"").toLowerCase();if(e.invocation.route.kind==="unknown")return n.program.dialect==="powershell"&&(i==="ls"||i==="stat");return ll(i,o.slice(1))}function ll(e,t){if(e==="ls"||e==="stat")return!0;if(e==="test")return t.length===2&&(t[0]==="-e"||t[0]==="-f");if(e==="[")return t.length===3&&(t[0]==="-e"||t[0]==="-f")&&t[2]==="]";if(e==="git")return t[0]==="check-ignore";if(e!=="find")return!1;return!t.some((n)=>dw.has(n))}function dp(e,t,n,r={}){let o=e.invocation.context.executionCwd,i=e.invocation.route.kind;if(i!=="command"&&i!=="unknown")return e.paths.map((a)=>({target:a,cwd:o}));let s=ge(e,"input-candidate");return[...s?kn(s.shell,e.store,r,t,o,n,Mw(s)):[],...i==="unknown"?e.paths.map((a)=>({target:a,cwd:o})):[]]}function Mw(e){return e.program.dialect==="powershell"}function kn(e,t,n,r,o,i,s=!1){if(e.status==="structural-limit")throw new We;if(e.status==="unclosed-quote")return[];if(e.status==="invalid")throw Error("Unable to parse command for secret protection");let a=[...e.assignmentFallbacks.map((c)=>({target:c,cwd:o})),...cA(ot(e.source,r),t,n,r,o,i)],l=(c)=>ot(Hw(c,s),r);return ko(e,o,r,i,{word:l,segment:(c,u,f,d,m)=>{if(c.length===0)return null;if(a.push(...Ci(c,t,n,r,u.cwd,i,m)),f!==null)a.push(...Nw(f,c,t,n,r,u.cwd,i));return null},redirection:(c,u)=>{if(c.body!==void 0&&c.consumer!==void 0)a.push(...Ep(c.consumer,[c.body],t,n,r,u.cwd,i,(f)=>Lw(c.consumer??[],f,t,n,r,u.cwd,i)));if(c.targetOrder==="legacy-segment")return ra;return a.push({target:l(c.target),cwd:u.cwd,...c.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}}),a}function cl(e,t,n,r,o,i){let s=t.getShellSyntax(e);if(s.status==="structural-limit")throw new We;return s.status==="complete"?kn(s,t,n,r,o,i):null}function Ci(e,t,n,r,o,i,s){let a=(p)=>({target:p,cwd:o});if(s?.size){let p=e.filter((h,C)=>!s.has(C));if(ip.has(Ue(dt(p)[0]??"").toLowerCase()))return[...e.filter((h,C)=>s.has(C)).map(a),...Ci(p,t,n,r,o,i)]}let l=Uw(e).map(a),c=dt(e);if(c.length===0)return l;let u=c[0]??"",f=Ue(u).toLowerCase(),d=c.slice(1),m=c.findIndex((p)=>!lw.has(p));if(n.skipMetadataOnlySegments===!0&&m!==-1&&ll(Ue(c[m]??"").toLowerCase(),c.slice(m+1)))return l;let g=Dw(u,f,d);if(g)return[...l,...g.map(a)];if(Cp.has(f))return n.displayOperandsAreCapturedOutput===!0?[...l,...xp(e).map(a)]:l;if(f==="eval")return[...l,...cl(d.join(" "),t,n,r,o,i)??d.map(a)];if(f==="export")return[...l,...d.flatMap((p)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(p)?[p.slice(p.indexOf("=")+1)]:Ze(f,p)).map(a)];if(f==="git")return[...l,...Vw(d).map(a)];if(f==="gh")return[...l,...sl(f,d,yw).map(a)];if(ip.has(f))return[...l,...jw(d).map(a)];if(hw.has(f))return[...l,...yA(d).map(a)];if(aw.has(f))return[...l,...Zw(d,t,n,r,o,i).map(a)];if(Ae.has(f))return[...l,...d.flatMap((p)=>Ze("awk",p)).map(a),...d.flatMap((p)=>Jw(p,t,n,r,o,i)),...d.flatMap(Qw).map(a)];if(f==="curl")return[...l,...d.flatMap((p)=>Ze(f,p)).map(a),...Kw(d).map(a)];if(dr(f)){let p=cr.has(f)?Ee([f,...d]):null;if(p!==null&&p.command!==null&&p.commandIndex!==null){let h=t.getShellSyntax(p.command);if(h.status==="structural-limit")throw new We;if(h.status==="complete")return[...l,...kn(h,t,n,r,o,i),...d.slice(p.commandIndex).filter((C)=>!C.startsWith("-")).map(a)]}return[...l,...Xw(f,d,t,n,r,o,i)]}return[...l,...d.flatMap((p)=>Ze(f,p)).map(a)]}function Dw(e,t,n){let r=mi(t,n);if(r===null||n[r]!=="explain")return null;let o=[e,...n.slice(0,r)],i=n.slice(r+1);for(let s=0;s<i.length;s++){let a=i[s];if(a==="--json"||a==="--help"||a==="-h")continue;if(a==="--cwd"){let l=i[s+1];if(l&&!l.startsWith("--"))o.push(l);s++;continue}return o}return o}function Nw(e,t,n,r,o,i,s){if(zw(t,n,r,o,i,s)){let a=dt(e),l=ll(Ue(a[0]??"").toLowerCase(),a.slice(1))?a.slice(1).filter((c)=>!c.startsWith("-")):[];return[...xp(e),...l].map((c)=>({target:c,cwd:i}))}return Ep(t,Ww(e),n,r,o,i,s,()=>[])}function Lw(e,t,n,r,o,i,s){let a=dt(e);if(!dr(Ue(a[0]??"").toLowerCase()))return[];return cl(t,n,r,o,i,s)??[{target:t,cwd:i}]}function Ep(e,t,n,r,o,i,s,a){let l=Bw(e);if(l===null)return t.flatMap(a);return t.flatMap((c)=>cr.has(l)?kn(n.getShellSyntax(c),n,r,o,i,s):hi(l,c,n,r,o,i,s))}function xp(e){let t=dt(e);if(t.length===0)return[];let n=Ue(t[0]??"").toLowerCase();if(!Cp.has(n))return[];let r=t[t[1]==="--"?2:1];if(n==="printf"&&r!==void 0&&!r.startsWith("-")&&!r.replaceAll("%%","").includes("%"))return[ul(r.replaceAll("%%","%"))];return t.slice(1)}function Ww(e){let t=dt(e);if(t.length===0)return[];let n=Ue(t[0]??"").toLowerCase(),r=t.slice(1);if(n==="echo"){let o=r.findIndex((i)=>!/^-[neE]+$/.test(i));return[(o===-1?[]:r.slice(o)).join(" ")]}if(n==="printf")return Gw(r);return[]}function Gw(e){let t=e[0];if(t===void 0)return[];let n=(t.match(/%%|%[bqs]/g)??[]).filter((o)=>o!=="%%").length;if(n===0||e.length===1)return[ul(t)];let r=e.slice(1);return Array.from({length:Math.ceil(r.length/n)},(o,i)=>Fw(t,r.slice(i*n,(i+1)*n)))}function Fw(e,t){let n=0;return ul(e.replace(/%%|%[bqs]/g,(r)=>{if(r==="%%")return"%";let o=t[n]??"";return n++,o}))}function ul(e){return e.replace(/\\n/g,`
44
- `).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function zw(e,t,n,r,o,i){let s=dt(e);if(s.length===0||Ue(s[0]??"").toLowerCase()!=="xargs")return!1;let a=Kt(s),l=s.slice(a.childStart);if(l.length===0)return!1;if(a.replacementToken==="")return!1;let c=a.replacementToken,u=c===null?[...l,rl]:l.map((f)=>f.split(c).join(rl));return Ci(u,t,n,r,o,i).some((f)=>f.target.includes(rl))}function Bw(e){let t=dt(e);if(t.length===0)return null;let n=Ue(t[0]??"").toLowerCase();if(!dr(n))return null;return $w(n,t.slice(1))?n:null}function $w(e,t){let n=dl(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(Sp.has(o)||Rp(e,o)||/^--(?:eval|exec)=/.test(o))return!1;if(o==="-")return!0;if(o.startsWith("-")){if(n==="python"&&o==="-m")return!1;if(kw.get(n)?.has(o))r++;continue}return!1}return!0}function dl(e){return/^python\d/.test(e)?"python":e}function Uw(e){let t=[];for(let n of e){if(wp(n))continue;let r=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(n);if(r===null)break;if(r[1]!==void 0&&r[1]!=="")t.push(r[1])}return t}var fp=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function Hw(e,t){if(!t||!fp.test(e))return e;return`~${e.replace(fp,"").replace(/\\/g,"/")}`}function Ze(e,t){if(t==="--")return[];let n=[],r=t.indexOf("=");if(r>0&&r<t.length-1)n.push(t.slice(r+1));if(t.startsWith("-"))return n;if(e==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(t))return n;if(e==="zip"&&/\.zip$/i.test(t))return n;return n.push(t),n}function jw(e){let t=-1,n=!1;for(let r=0;r<e.length;r++){let o=e[r]??"";if(!n&&o==="--"){n=!0;continue}if(n||!/^-(?:[A-Za-z]|-)/.test(o)){if(t===-1)t=r;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(o)){r+=2;continue}if(o==="--indent"||o==="-L"){r++;continue}if(o.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(o)||/^--(?: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(o))continue;return e.flatMap((i)=>Ze("jq",i))}return e.flatMap((r,o)=>o===t?[]:Ze("jq",r))}function Vw(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n]??"";if(r==="--"||!r.startsWith("-"))return[...t,...Cw.has(r)?sl("git",e.slice(n).map((i)=>/^-[aeinopqsv]+m$/.test(i)?"-m":i),bw):sl("git",e.slice(n),Sw)];if(t.push(...Ze("git",r)),!ve.has(r))continue;let o=e[n+1];if(o===void 0)break;t.push(...r==="-c"&&o.includes("=")?[o.slice(o.indexOf("=")+1)]:Ze("git",o)),n++}return t}function sl(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o]??"";if(i==="--")return[...r,...t.slice(o).flatMap((s)=>Ze(e,s))];if(n.has(i)){o++;continue}if(i.includes("=")&&n.has(i.slice(0,i.indexOf("="))))continue;r.push(...Ze(e,i))}return r}function Kw(e){return e.flatMap((t,n)=>{let r=Yw(t);if(r!==null)return mp(r.flag,r.value);let o=qw(e[n-1]);return o===null?[]:mp(o,t)})}function mp(e,t){if(e==="-F"||e==="--form"){let n=t.indexOf("="),r=n===-1?t:t.slice(n+1);if(!r.startsWith("@")&&!r.startsWith("<"))return[];return ol(r.slice(1).split(";")[0]??"")}if(e==="--data-urlencode"){let n=t.indexOf("@"),r=t.indexOf("=");if(n===-1||r!==-1&&r<n)return[];return ol(t.slice(n+1))}return t.startsWith("@")?ol(t.slice(1)):[]}function qw(e){if(e===void 0)return null;if(bp.has(e))return e;return/^-[A-Za-z]+[dF]$/.test(e)?`-${e.slice(-1)}`:null}function Yw(e){let t=e.slice(0,2);if(e.length>2&&(t==="-d"||t==="-F"))return{flag:t,value:e.slice(2)};let n=e.indexOf("=");if(n===-1)return null;let r=e.slice(0,n);return bp.has(r)?{flag:r,value:e.slice(n+1)}:null}function ol(e){return e===""||e==="-"?[]:[e]}function Zw(e,t,n,r,o,i){let s=e.findIndex((l)=>l.startsWith("-")||l==="("||l==="!"||l===";"),a=[...e.slice(0,s===-1?e.length:s),...e.flatMap((l,c)=>l==="-files0-from"&&e[c+1]!==void 0?[e[c+1]??""]:[])];for(let l=0;l<e.length;l++){if(!cw.has(e[l]??""))continue;let c=e.slice(l+1),u=c.findIndex((m)=>uw.has(m)),f=u===-1?c:c.slice(0,u),d=Ci(f,t,n,r,o,i).map((m)=>m.target);if(a.push(...d.filter((m)=>m!=="{}")),!d.includes("{}"))continue;a.push(...e.slice(0,l).flatMap((m,g,p)=>{if(!fw.has(m))return[];let h=p[g+1];return h===void 0?[]:[h,h.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return a}function Xw(e,t,n,r,o,i,s){let a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c===void 0)break;if(Sp.has(c)||Rp(e,c)){let f=t[l+1];if(f!==void 0)a.push(...hi(e,f,n,r,o,i,s)),l++;continue}let u=/^--(?:eval|exec)=(.*)$/.exec(c);if(u!==null&&u[1]!==void 0){a.push(...hi(e,u[1],n,r,o,i,s));continue}if(!c.startsWith("-"))a.push({target:c,cwd:i})}return a}function Rp(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<=2)return!1;return gw.get(t[t.length-1]??"")?.has(dl(e))??!1}function Jw(e,t,n,r,o,i){if(!e.includes("system"))return[];return ya(e)?.commands.flatMap((s)=>kn(t.getShellSyntax(s),t,n,r,o,i))??[]}function Qw(e){return Array.from(e.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((t)=>t[1]).filter((t)=>t!==void 0&&t!=="")}function eA(e){let t=Array.from(e.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((n)=>n[2]).filter((n)=>n!==void 0&&n!=="");return[...t,...t.flatMap(fl),...e.match(il)??[]]}function hi(e,t,n,r,o,i,s){let a=(p)=>({target:p,cwd:i}),l=nA(t,tA(e));if(l.kind==="unmaskable")return eA(t).map(a);let c=l.masked.match(lp)!==null||l.literals.some((p)=>cp.test(l.masked.slice(0,p.start))),u=l.masked.match(Iw)!==null||l.literals.some((p)=>Tw.test(l.masked.slice(0,p.start))),f=r.inlineLiteralsPresumedData===!0&&!cr.has(e),d=f&&!(sA(l.masked)||c||u)?[]:l.literals,m=f?Array.from(l.masked.matchAll(lp),(p)=>{let h=p.index+p[0].length;return{start:h,end:Zs(l.masked,h)}}):[],g=!f||m.some((p)=>Xs(l.masked,p.start))?l.literals:l.literals.filter((p)=>cp.test(l.masked.slice(0,p.start))||m.some((h)=>p.start>=h.start&&p.start<h.end));return[...d.map((p)=>p.text).filter((p)=>p!=="").map(a),...d.flatMap((p)=>fl(p.text)).map(a),...f?[]:l.literals.flatMap((p)=>p.text.match(il)??[]).map(a),...c?g.flatMap((p)=>cl(p.text,n,r,o,i,s)??[a(p.text)]):[],...u?l.literals.flatMap((p)=>hi(e,p.text.replace(/\\(.)/g,(h,C)=>C==="n"?`
45
- `:C),n,r,o,i,s)):[],...(l.masked.match(il)??[]).map(a)]}function tA(e){let t=dl(e);if(t==="python")return"python";if(t==="osascript")return"opaque";return t==="node"||t==="bun"||t==="deno"?"javascript":"simple"}function nA(e,t){if(t==="opaque")return{kind:"unmaskable"};let n=e.split(""),r=[];for(let o=0;o<e.length;o++){let i=e[o]??"";if(t==="simple"&&(i==="`"||i==="%"||i==="<")){if(Aw.test(e.slice(o)))return{kind:"unmaskable"}}let s=i==="'"||i==='"'||t==="javascript"&&i==="`"?i:null;if(s===null)continue;if(s==="`"&&iA(e,o))return{kind:"unmaskable"};let a=t==="python"?rA(e,o):"",l=t==="python"&&e.startsWith(s.repeat(3),o)?s.repeat(3):s,c=o+l.length,u=oA(e,c,l);if(u===null)return{kind:"unmaskable"};let f=e.slice(c,u);if(/[fF]/.test(a)&&f.includes("{"))return{kind:"unmaskable"};if(t==="simple"&&s==='"'&&Pw.test(f))return{kind:"unmaskable"};r.push({start:c,text:f});for(let d=o;d<u+l.length;d++)n[d]=" ";o=u+l.length-1}return{kind:"masked",masked:n.join(""),literals:r}}function rA(e,t){return ww.exec(e.slice(Math.max(0,t-3),t))?.[1]??""}function oA(e,t,n){let r=n==="`",o=r||n.length===3;for(let i=t;i<e.length;i++){let s=e[i];if(s==="\\"){i++;continue}if(r&&s==="$"&&e[i+1]==="{")return null;if(!o&&(s===`
46
- `||s==="\r"))return null;if(e.startsWith(n,i))return i}return null}function iA(e,t){for(let n=t-1;n>=0;n--){let r=e[n];if(!r||/\s/.test(r))continue;return/[\w$\])]/.test(r)}return!1}function sA(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(mw.has(n.toLowerCase()))return!0;let o=n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((i)=>i.toLowerCase());if(!o.some((i)=>pw.has(i)))continue;if(o.length>1)return!0;if(aA(e,r)===".")return!0;if(lA(e,r+n.length)==="(")return!0}return!1}function aA(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function lA(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function cA(e,t,n,r,o,i){return pA(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...kn(a,t,{...n,displayOperandsAreCapturedOutput:!0},r,o,i),...uA(a,r)?dA(a,r).map((l)=>({target:l,cwd:o})):[]]})}function uA(e,t){let n=Oo(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||Ue(ot(o.text,t)).toLowerCase()!=="base64")continue;for(let i=r+1;i<n.length;i++){let s=n[i];if(s?.kind==="operator")break;if(s?.kind!=="word")continue;let a=ot(s.text,t);if(a==="--decode"||!a.startsWith("--")&&a.startsWith("-")&&/[dD]/.test(a))return!0}}return!1}function dA(e,t){return Oo(e).flatMap((n)=>n.kind==="word"?[ot(n.text,t)]:n.kind==="redirection"&&n.target?[ot(n.target,t)]:[]).flatMap(fl)}function fl(e){let t=mA(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||fA(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function fA(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function mA(e){if(e.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(e))return null;if(/=/.test(e.replace(/=+$/g,"")))return null;let t=e.replace(/=+$/g,"");if(t.length%4===1)return null;return`${t.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-t.length%4)%4)}`}function pA(e){let t=[],n={inSingle:!1,inDouble:!1,escaped:!1};for(let r=0;r<e.length;r++){let o=e[r];if(!o)break;if(Vn(o,n))continue;if(_p(e,r,n)){let i=gA(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=hA(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function gA(e,t){let n={inSingle:!1,inDouble:!1,escaped:!1},r=1;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i)break;if(Vn(i,n))continue;if(_p(e,o,n)){r++,o++;continue}if(!n.inSingle&&!n.inDouble&&i===")"){if(r--,r===0)return{body:e.slice(t+1,o),endIndex:o}}}return null}function hA(e,t){let n=!1;for(let r=t+1;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="`")return{body:e.slice(t+1,r),endIndex:r}}return null}function _p(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function yA(e){let t=[],n=[],r=!1,o=!1,i=!1;for(let l=0;l<e.length;l++){let c=e[l];if(c===void 0)break;if(!i&&c==="--"){i=!0;continue}if(i){n.push(c);continue}let u=/^--([^=]+)(?:=(.*))?$/.exec(c);if(u!==null){let f=u[1]??"",d=u[2];if(f===vw)o=!0;if(xw.has(f))r=!0;if(d!==void 0){if(f===ap)t.push(d);continue}if(_w.has(f)){let m=e[l+1];if(f===ap&&m!==void 0)t.push(m);l++}continue}if(c.startsWith("-")&&c.length>1){let f=c.slice(1),d="",m="";for(let p=0;p<f.length;p++){let h=f[p]??"";if(Ew.has(h))r=!0;if(Rw.has(h)){d=h,m=f.slice(p+1);break}}if(d==="")continue;if(m.length>0){if(d===sp)t.push(m);continue}let g=e[l+1];if(d===sp&&g!==void 0)t.push(g);l++;continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function dt(e){let t=e.findIndex((n)=>!wp(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:e.slice(t)}function wp(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var CA=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),bA=".env.",SA=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),vA=[".env.example.",".env.sample."];function EA(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function xA(e){return e.length>0&&!/\s/.test(e)}function al(e,t,n,r){let o=Ap(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function Ap(e,t,n,r){try{return Ir(e,t,n,r)}catch(o){if(o instanceof N)throw o;return""}}var RA=new Set(["node_modules","__pycache__"]),_A=[["vendor","bundle"],["vendor","cache"]];function wA(e,t,n,r,o){if(EA(e))return null;let i=Ye(e,t,r,o);if(!i)return null;let s=B(i.split("/").pop()??""),a=B(i),l=()=>xA(s)||al(e,t,r,o);if(SA.has(s)||vA.some((d)=>s.startsWith(d)))return null;let c=B(OA(e,t,r,o));for(let d of ds){let m=`~/${d.suffixParts.join("/")}`;if((gp(a,m)||gp(c,m))&&ut(d.id,n))return d.id}let u=AA(i,t,n,r,o);if(u)return u;if(CA.has(s))return null;for(let d of us)if(s===d.basename&&ut(d.id,n))return d.id;if(s.startsWith(bA)&&ut(Yr.id,n)&&l())return Yr.id;for(let d of fs)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){let m=s.slice(d.prefix.length)[0];if((m==="-"||m==="_")&&ut(d.id,n)&&l())return d.id}for(let d of ms)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){if(s.slice(d.prefix.length)===d.suffix&&ut(d.id,n))return d.id}if(TA(a))return null;if(!s.includes(".")&&Kn.pattern.test(s)&&ut(Kn.id,n))return Kn.id;let f=kA(s,n);if(f)return f;return null}function AA(e,t,n,r,o){return Zr.find((i)=>{if(!ut(i.id,n))return!1;switch(i.id){case"secret.cli.claude-code":return F(e,j(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),[".credentials.json"]);case"secret.cli.claude-code.config":{let s=B(e).split("/");return F(e,j(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),["settings.json","settings.local.json"])||Pr(e,"~/.claude.json",t,r,o)||s.at(-1)==="settings.local.json"&&s.at(-2)===".claude"||s.at(-1)===".mcp.json"}case"secret.cli.antigravity":return F(e,Ye("~/.gemini/config",t,r,o),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let s=j(r.env.get("CODEX_HOME"),"~/.codex",t,r,o);return F(e,s,["auth.json",".credentials.json"])||Ar(e,s,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let s=j(r.env.get("CODEX_HOME"),"~/.codex",t,r,o),a=B(e).split("/").at(-1)??"";return F(e,s,["config.toml"])||a.endsWith(".config.toml")&&F(e,s,[a])}case"secret.cli.gemini":return F(e,ce(j(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let s=B(e).split("/"),a=r.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),l=r.env.get("ProgramData")?[ce(j(r.env.get("ProgramData"),"",t,r,o),"gemini-cli")]:[];return F(e,ce(j(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["settings.json","google_accounts.json"])||s.at(-1)==="settings.json"&&s.at(-2)===".gemini"||(a?.trim()?Pr(e,a,t,r,o):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...l].some((c)=>F(e,Ye(c,t,r,o),["settings.json"]))}case"secret.cli.copilot-cli":{let s=j(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o);return F(e,s,["config.json"])||Ar(e,s,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return F(e,j(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o),["mcp-config.json"]);case"secret.cli.kimi-code":{let s=j(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),a=j(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o);return F(e,s,["server.token"])||Ar(e,s,["credentials"])||Ar(e,a,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let s=["config.toml","mcp.json"],a=B(e).split("/");return a.at(-1)==="mcp.json"&&a.at(-2)===".kimi-code"||F(e,j(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),s)||F(e,j(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o),[...s,"config.json","config.json.bak"])}case"secret.cli.opencode":{let s=ce(j(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"opencode"),a=B(e).split("/").at(-1)??"",l=r.env.get("OPENCODE_DB")?.trim(),c=l&&l!==":memory:"?[l,`${l}-wal`,`${l}-shm`]:[];return F(e,s,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(a)&&F(e,s,[a])||c.some((u)=>Pr(e,u,t,r,o))}case"secret.cli.opencode.config":{let s=ce(j(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"opencode"),a=r.env.get("ProgramData")?[ce(j(r.env.get("ProgramData"),"",t,r,o),"opencode")]:[],l=["opencode.json","opencode.jsonc"],c=r.env.get("OPENCODE_CONFIG");return l.includes(B(e).split("/").at(-1)??"")||F(e,s,["config.json"])||(c?.trim()?Pr(e,c,t,r,o):!1)||["/Library/Application Support/opencode","/etc/opencode",...a].some((u)=>F(e,Ye(u,t,r,o),l))}case"secret.cli.pi":return F(e,j(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["auth.json"]);case"secret.cli.pi.config":return F(e,j(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["models.json"]);case"secret.cli.amp":{let s=Ye("~",t,r,o);return[ce(j(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"amp"),ce(s,".local","share","amp")].some((l)=>F(e,l,["secrets.json"]))||Ar(e,ce(s,".amp"),["oauth"])}case"secret.cli.amp.config":{let s=["settings.json","settings.jsonc"],a=[ce(j(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"amp"),ce(Ye("~",t,r,o),".config","amp")],l=B(e).split("/"),c=r.env.get("AMP_SETTINGS_FILE");return a.some((u)=>F(e,u,s))||l.at(-2)===".amp"&&s.includes(l.at(-1)??"")||(c?.trim()?Pr(e,c,t,r,o):!1)}case"secret.cli.cursor":{let s=ce(j(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"cursor"),a=ce(j(r.env.get("CURSOR_DATA_DIR"),"~/.cursor",t,r,o),"projects");return F(e,Ye("~/.cursor",t,r,o),["auth.json"])||F(e,s,["auth.json"])||B(e).split("/").at(-1)==="mcp-auth.json"&&Xt(B(e),B(a))}case"secret.cli.cursor.config":{let s=B(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".cursor"}case"secret.cli.grok-build":return F(e,j(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let s=B(e).split("/");return s.at(-1)==="config.toml"&&s.at(-2)===".grok"||F(e,j(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["config.toml","managed_config.toml","requirements.toml"])||F(e,Ye("/etc/grok",t,r,o),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var pp=new WeakMap;function j(e,t,n,r,o){let i=pp.get(o)??new Map;pp.set(o,i);let s=`${n}\x00${e??""}\x00${t}`,a=i.get(s);if(a!==void 0)return a;let l=Ye(e?.trim()?e:t,n,r,o);return i.set(s,l),l}function F(e,t,n){return n.some((r)=>Pp(e,ce(t,r)))}function Ar(e,t,n){return n.some((r)=>Xt(B(e),B(ce(t,r))))}function Pr(e,t,n,r,o){return Pp(e,Ye(t,n,r,o))}function Pp(e,t){return B(e)===B(t)}function ce(e,...t){return $e([e,...t].filter(Boolean).join("/"))}function PA(e,t,n,r,o,i){if(n.length===0)return!1;let s=B(Ir(e,t,o,i));return n.some((a)=>Xt(s,B(Ir(a,r,o,i))))}function IA(e,t,n,r,o,i){if(n.length===0)return!1;let s=B(Ir(e,t,o,i));if(!s)return!1;let a=o.env.get("HOME")??o.home,l=a?$e(L(Se(a),o.paths,i)):"",c=B(l),u=o.env.get("CC_SAFETY_NET_HOME"),f=B(u?$e(L(yi(Se(u)),o.paths,i)):l&&$e(L(`${l}/.cc-safety-net`,o.paths,i)));if(f&&Xt(s,f))return!1;return n.some((d)=>{let m=Cs(d);if(m&&hp.basename(s)!==B(m.name))return!1;let g=B(Ir(m?.root??d,r,o,i));if(!g)return!1;if(c&&(c===g||c.startsWith(g.endsWith("/")?g:`${g}/`)))return!1;return Xt(s,g)&&!(m&&s===g)})}function TA(e){let t=e.split("/");return t.some((n)=>RA.has(n))||_A.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function kA(e,t){let n=e.lastIndexOf("."),r=n>0&&n<e.length-1?e.slice(n+1):"";if(r==="")return null;for(let o of ps)if(r===o.extension&&ut(o.id,t))return o.id;for(let o of gs)if(o.pattern.test(r)&&ut(o.id,t))return o.id;return null}function B(e){return e.toLowerCase()}function ut(e,t){return!t?.disabledRules?.includes(e)}function Ye(e,t,n,r){let{home:o,normalized:i}=ml(e,n,r);if(!i)return"";if(!o)return i;let s=pl(i,o),a=gi(s)?s:$e(yi(t,s)),l=$e(L(a,n.paths,r));if(!Xt(l,o)){if(gi(s))return l;return l===a?i:l}let c=l.slice(o.length);return c?`~${c}`:"~"}function gp(e,t){return e===t||e.startsWith(`${t}/`)}function OA(e,t,n,r){let{home:o,normalized:i}=ml(e,n,r);if(!i||!o)return"";let s=pl(i,o),a=hp.normalize(gi(s)?s:$e(yi(t,s))),l=$e(Se(n.env.get("HOME")??n.home)),c=(d)=>process.platform==="win32"?d.toLowerCase():d,u=[o,l].find((d)=>d!==""&&Xt(c(a),c(d)));if(u===void 0)return"";let f=a.slice(u.length);return f?`~${f}`:"~"}function Ir(e,t,n,r){let{home:o,normalized:i}=ml(e,n,r);if(!i)return"";let s=o?pl(i,o):i;return $e(L(gi(s)?s:yi(t,s),n.paths,r))}function ml(e,t,n){let r=t.env.get("HOME")??t.home,o=r?$e(L(Se(r),t.paths,n)):"",i=$e(Se(MA(ot(e,t))));return{home:o,normalized:i}}function MA(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return sw(e)}catch{return e}}function pl(e,t){if(e==="~")return t;if(e.startsWith("~/"))return ce(t,e.slice(2));return e}function DA(e){if(process.platform==="win32")return!0;return iw.parse(e).root.length>1}function $e(e){let t=e.trim(),n=(t.includes("\\")&&DA(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function Xt(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function Ue(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class Jt extends Error{stage;evaluation;name="GuardEvaluationError";constructor(e,t,n){super(`CC Safety Net ${e} dependency failed`,{cause:n});this.stage=e;this.evaluation=t}}var NA={findPolicyMutation:rp,findGitMetadataMutation:Pd,resolveGitMetadata:WA,loadPolicySnapshot:pu,findSensitiveTarget:vp,analyzeCommand:qm,getModes:zi},LA=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function Ip(e,t){let n={...NA,...t.dependencies},r=zA(e),o=Tr(e)?e.command:r,i=wt("policy-protection",o,()=>Rd(e)),s=ge(i,"input-candidate"),a=ge(i,"declared-command");if(Tr(e)&&e.command?.trim()&&a?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:He,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:e.command,segment:e.command}}};if(s?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:qd,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let l=je(),c=wt("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd],t.environment)),u=wt("policy-protection",o,()=>n.findPolicyMutation(i,t.environment,l));if(u){let y=o??u.target;return{stage:"policy-protection",decision:{kind:"deny",reason:np,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:y,segment:u.target}}}}let f=wt("policy-protection",o,()=>Jm(i,t.environment,l));if(f){let y=o??f.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Xm,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:y,segment:f.target}}}}let d=wt("policy-protection",o,()=>n.findGitMetadataMutation(i,c,t.environment,l));if(d){let y=o??d.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Ge,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:y,segment:d.target}}}}let m=wt("config-load",o,()=>n.loadPolicySnapshot(t.environment,{...t.policyOptions,cwd:e.context.configCwd})),g=m.policy,p=n.getModes(g,t.environment.env),h={level:p.effectiveLevel,...GA(m)},C=g.secretProtection.enabled===!1?null:wt("secret-protection",o,()=>n.findSensitiveTarget(i,g.secretProtection,t.environment,l,{strict:Tr(e)||s?.program.dialect==="powershell"?p.strict:void 0}));if(C){let y=o??C.target;return{stage:"secret-protection",...h,decision:{kind:"deny",reason:yp,intent:"hard_stop",ruleId:C.ruleId,evidence:{command:y,segment:C.target}}}}if(!Tr(e))return{stage:"non-command",...h,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...gl("command-validation",o),...h};let b=wt("command-analysis",o,()=>Ym(()=>n.analyzeCommand(e.command,{cwd:e.context.executionCwd,shell:e.route.shell,policySnapshot:m,environment:t.environment,protectedGitMetadata:c,effectiveCapabilities:p.capabilities,strict:p.strict,paranoidRm:p.paranoidRm,paranoidInterpreters:p.paranoidInterpreters,worktreeMode:p.worktreeMode,budget:l,...t.trace?{trace:t.trace}:{}},FA(i),i.store),e.command,t.trace));if(b.decision){let y=!p.strict&&(b.decision.ruleId==="raw-text.dangerous-command"||b.decision.reason===gr&&!LA.test(b.decision.evidence?.segment??"")&&Pe(e.command)===null);return{stage:"command-analysis",...h,..."errorCode"in b?{errorCode:b.errorCode}:{},decision:y?{...b.decision,unverifiedByStandardMode:!0}:b.decision}}return{stage:"command-analysis",...h,decision:{kind:"allow"}}}function WA(e,t){let n=[...new Set(e.filter((r)=>typeof r==="string"&&r!==""))].flatMap((r)=>t.gitMetadata(r)??[]);if(n.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(n.flatMap((r)=>r.entries))]),markerFiles:Object.freeze([...new Set(n.flatMap((r)=>r.markerFiles))]),directories:Object.freeze([...new Set(n.flatMap((r)=>r.directories))]),hooksDirectories:Object.freeze([...new Set(n.flatMap((r)=>r.hooksDirectories))])})}function GA(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function FA(e){return ge(e,"declared-command")?.program}function zA(e){try{return Fn(e.input)}catch(t){let n=Tr(e)?e.command:void 0;throw new Jt("policy-protection",gl("policy-protection",t instanceof Qe?void 0:n,t),t)}}function wt(e,t,n){try{return n()}catch(r){throw new Jt(e,gl(e,r instanceof Qe?void 0:t,r),r)}}function gl(e,t,n){let r=n instanceof N||n instanceof We;return{stage:e,decision:{kind:"deny",reason:r?Ei:Nn,ruleId:r?"analysis.limit":"analysis.failed-closed",intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function Tr(e){return e.route.kind==="command"}import{appendFileSync as QA,mkdirSync as eP}from"node:fs";import{isAbsolute as tP,join as Cl}from"node:path";import{lstatSync as kp,readdirSync as BA,readFileSync as $A,rmdirSync as UA,statSync as Op,unlinkSync as HA,utimesSync as jA,writeFileSync as VA}from"node:fs";import{join as kr}from"node:path";function Tp(e,t={}){return io(on(e,t),e.home).policy.audit.retention_days}var yl=86400000,KA=".last-prune",qA=/^\d{4}-\d{2}$/,YA=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Mp=(e)=>Math.floor(e/yl);function Np(e,t,n=()=>new Date){try{let r=n().getTime();if(!Op(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=kr(t,KA),i=Op(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&Mp(i)===Mp(r))return;let s=r-Tp(e)*yl,a=new Date(r).toISOString().slice(0,7);for(let l of hl(t)){if(l.isDirectory()){ZA(kr(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))XA(kr(t,l.name),s)}VA(o,"",{mode:384}),jA(o,r/1000,r/1000)}catch{}}function ZA(e,t,n){for(let r of hl(e)){if(!r.isDirectory()||!qA.test(r.name))continue;let o=kr(e,r.name);for(let i of hl(o)){if(!i.isFile())continue;let s=YA.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+yl;if(!Number.isFinite(a)||a>=t)continue;Lp(kr(o,i.name))}if(r.name!==n)Dp(o)}Dp(e)}function XA(e,t){try{let n=kp(e);if(n.mtimeMs>=t)return;let r=$A(e,"utf-8").split(`
47
- `).filter((o)=>o.trim()).map(JA);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(kp(e).mtimeMs!==n.mtimeMs)return;Lp(e)}catch{}}function JA(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function hl(e){try{return BA(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Lp(e){try{HA(e)}catch{}}function Dp(e){try{UA(e)}catch{}}var nP="2.5.2",rP=1e4,oP=2000,iP=256,sP=32768;function aP(e){let t=e.trim();if(!t)return null;let n=t.replace(/[^A-Za-z0-9_.-]+/g,"_");if(n=n.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!n||n==="."||n==="..")return null;return n}function lP(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function bl(e,t,n,r,o,i,s={}){let a=aP(t);if(!a)return;let l=uP(e);if(!l)return;try{let c=(s.now??(()=>new Date))().toISOString(),u=bi(ft(n),s.failureStage?Number.POSITIVE_INFINITY:rP),f=bi(ft(r),oP),d=s.toolName?bi(ft(s.toolName),iP):void 0,m=i===null?void 0:bi(ft(i),sP),g=Cl(l,lP(m?.value??null),c.slice(0,7));eP(g,{recursive:!0,mode:448});let p=Cl(g,`${c.slice(0,10)}-${a}.jsonl`),h={ts:c,id:(s.createId??Bi)(),v:nP,sessionId:a,decision:s.decision??"deny",agent:s.agent,shape:s.shape,level:s.level,configFallback:s.configFallback,toolName:d?.value,command:u.value,segment:f.value,...u.truncated||f.truncated||d?.truncated||m?.truncated?{truncated:!0}:{},reason:o,ruleId:s.ruleId,intent:s.intent,failureStage:s.failureStage,errorCode:s.errorCode,cwd:m?.value??null};QA(p,`${JSON.stringify(h)}
48
- `,{encoding:"utf-8",mode:384}),Np(e,l,s.now)}catch{}}function bi(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function cP(e){let t=e.env.get("CC_SAFETY_NET_AUDIT_HOME");if(e.env.get("NODE_ENV")==="test"&&!t)return null;let n=t||e.home;return n&&tP(n)?n:null}function uP(e){let t=cP(e);return t?Cl(t,".cc-safety-net","logs"):null}function Gp(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=Wp(e);return{decision:"allow",command:a,segment:a,reason:"allowed",cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{}}}let i=t.decision.evidence,s=i?.command??(r?Wp(e):"");return{decision:"deny",command:s,segment:i?.segment??s,reason:t.decision.reason,cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{},ruleId:t.decision.ruleId,intent:t.decision.intent,failureStage:o?.stage,errorCode:o?.errorCode}}function Wp(e){return"command"in e?e.command??"":""}function Fp(e,t,n,r){if(!t)return;let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;bl(e,o,t.command,t.segment,t.reason,t.cwd,{decision:t.decision,agent:r.agent,shape:r.shape,level:t.level,configFallback:t.configFallback,toolName:t.toolName,ruleId:t.ruleId,intent:t.intent,failureStage:t.failureStage,errorCode:t.errorCode})}function zp(e,t,n,r){let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;bl(e,o,t.command??"",t.segment??t.command??"",t.reason,r.cwd??null,{decision:"deny",agent:r.agent,shape:r.shape,toolName:r.toolName??t.toolName,ruleId:t.ruleId,intent:t.intent})}function $p(e,t,n){try{let r=Ip(t,{environment:e,...n.guard});return Bp(e,t,r,n),r}catch(r){if(!(r instanceof Jt))throw r;throw Bp(e,t,r.evaluation,n,!(r.cause instanceof Qe),{stage:r.stage,errorCode:dP(r.cause)}),r}}function Bp(e,t,n,r,o=!0,i){Fp(e,Gp(t,n,r.guard?.auditAllowed??!1,o,i),r.audit.getSessionId,{agent:r.audit.agent,shape:r.audit.shape})}function dP(e){if(e instanceof N)return V[e.kind].errorCode;if(e instanceof Qe)return"tool-input-limit";if(e instanceof We)return"structural-shell-syntax-limit";return"unexpected-error"}function At(e,t={}){return{malformed:!0,denial:Ln(t),cwd:e}}function Sl(e,t){return{malformed:!0,denial:xi(e,t),cwd:e.cwd}}function Up(e,t={}){return(n,r)=>{try{return fP(n,r,e,t)}catch(o){return console.error("CC Safety Net error:",o),e.block(Ln())}}}function fP(e,t,n,r){let o=nc();if(n.cancelled?.(t))return n.block(Ln());let i=n.extract(e,t,o.paths);if(!i)return n.allow;let s=()=>n.getSessionId(e,t);if("malformed"in i)return zp(o,i.denial,s,{agent:n.agent,toolName:i.denial.toolName,cwd:i.cwd}),n.block(i.denial);let a=(l,c)=>{let u=Rl(l,{includeEvidence:c});return u?n.block(u):n.allow};try{let l=$p(o,i,{guard:{auditAllowed:sc(o.env),policyOptions:r.policyOptions,dependencies:r.guardDependencies},audit:{agent:n.agent,getSessionId:s}});return a(l,!0)}catch(l){if(!(l instanceof Jt))throw l;if(et(Z.debug,o.env))console.error(`CC Safety Net debug: ${n.debugLabel} analysis failed: ${wl(l.cause)}`);return a(l.evaluation,n.includeEvidenceOnError(i))}}var Hp="exec",mP=new Set(["auto","gateway"]);function jp(e){e.on("before_tool_call",pP(e),{matcher:[Hp],priority:50})}function pP(e,t={}){return Up({agent:"openclaw",debugLabel:"openclaw before_tool_call",extract:(r,o,i)=>gP(r,o,e,i),getSessionId:(r,o)=>o.sessionId??o.sessionKey,allow:void 0,block:(r)=>yP(r),includeEvidenceOnError:()=>!0,cancelled:(r)=>r.abortSignal?.aborted===!0},t)}function gP(e,t,n,r){if(!e||typeof e!=="object")return At(null);let o=e.toolName;if(typeof o!=="string"||o.trim()==="")return At(null);if(o!==Hp)return;if(e.toolKind!==void 0)return;let i=e.params;if(!i||typeof i!=="object"||Array.isArray(i))return At(null,{toolName:o});let s=i,a=s.command;if(typeof a!=="string"||a.trim()==="")return At(null,{toolName:o});if(s.host!==void 0&&!mP.has(s.host))return At(null,{command:a,toolName:o});let l=hP(n,t.agentId);if(!l)return At(null,{command:a,toolName:o});let c=Mi(".",[l],r);if(!c)return Sl({directory:"session",problem:"unusable",cwd:l},{command:a,toolName:o});let u=s.workdir;if(u!==void 0&&(typeof u!=="string"||u.trim()===""))return At(c,{command:a,toolName:o});let f=typeof u==="string"?u:".",d=Mi(f,[c],r);if(!d)return Sl({directory:"requested",problem:ql(f,c,r),cwd:f},{command:a,toolName:o});return Yl(o,s,{kind:"command",shell:"auto"},{configCwd:c,executionCwd:d},a)}function hP(e,t){if(typeof t!=="string"||t.trim()==="")return;try{let n=e.runtime.agent.resolveAgentWorkspaceDir(e.config,t);return typeof n==="string"&&n.trim()!==""?n:void 0}catch{return}}function yP(e){return{block:!0,blockReason:_l(e)}}var O1={...xl,register:jp};export{O1 as default};
44
+ `?e.trim().split(/\s+/).filter(Boolean):e.split(t).filter(Boolean)}function Pr(e){if(!e)return!0;return e.provenance==="unknown"?!/[$`]/.test(_(e)):e.provenance==="literal"}function An(e){return e?_(e):""}function ri(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function $a(e,t){return za(Ne(e,"posix"),t)}function Ar(e){return $a(e,new Set(Array.from(e.matchAll(Yf)).flatMap((t)=>{let n=t[1]??t[2];return n===void 0?[]:[n]})))}function za(e,t){if(e.status==="invalid"||e.status==="limited")return!1;let n=new Set(t);for(let r of e.nodes){if(r.kind==="group"){if(za(r.body,n))return!0;continue}if(r.kind!=="command")continue;if(r.nested.some((o)=>za(o,n))||nm(r.words,n))return!0;wR(r,n)}return!1}function nm(e,t){let n=e.findIndex((s)=>ke(s.text)===null);if(n===-1)return!1;let r=e[n];if(!r)return!1;if(wr(r,t))return!0;let o=O(r.text);if(o==="source"||o==="."){let s=e[n+1]?.text==="--"?n+2:n+1;return qf(e[s],t)}if(Y.has(o)){let s=e.slice(n),a=xe(s.map((c)=>c.text)),l=a.commandIndex??a.scriptIndex;return!a.syntaxCheck&&l!==null&&qf(s[l],t)}let i=ER(e,n,t);if(i===null)return!1;if(i===-1)return!0;return nm(e.slice(i),t)}function ER(e,t,n){let r=O(e[t]?.text??"");if(r==="command")return xR(e,t+1);if(r==="exec")return RR(e,t+1);if(r==="env")return _R(e,t+1,n);return null}function xR(e,t){for(let n=t;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return e[n+1]?n+1:null;if(/^-[p]*[vV][pvV]*$/.test(r))return null;if(/^-p+$/.test(r))continue;return n}return null}function RR(e,t){for(let n=t;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return e[n+1]?n+1:null;if(r==="-a"){n++;continue}if(/^-a.+/.test(r)||/^-[cl]+$/.test(r))continue;return n}return null}function _R(e,t,n){for(let r=t;r<e.length;r++){let o=e[r],i=o?.text??"";if(i==="--")return e[r+1]?r+1:null;if(i==="-S"||i==="--split-string")return wr(e[r+1],n)?-1:r+2;if(i.startsWith("-S")||i.startsWith("--split-string="))return wr(o,n)?-1:r+1;if(i==="-u"||i==="--unset"||i==="-C"||i==="--chdir"||i==="-P"){r++;continue}if(i==="-i"||i==="-0"||i==="--null"||i.startsWith("-u=")||i.startsWith("--unset=")||i.startsWith("-C")||i.startsWith("--chdir=")||i.startsWith("-P"))continue;if(i.startsWith("-"))continue;if(ke(i))continue;return r}return null}function wR(e,t){if(!e.words.every((n)=>ke(n.text)!==null))return;for(let n of e.words){let r=ke(n.text);if(!r)continue;if(wr(n,t))t.add(r.name)}}function wr(e,t){if(!e)return!1;return e.parts.filter((n)=>n.provenance==="variable").some((n)=>Array.from(n.raw.matchAll(Yf)).some((r)=>{let o=r[1]??r[2];return o!==void 0&&(gR.test(o)||t.has(o))}))}function qf(e,t){return!!e&&(e.parts.some((n)=>n.provenance!=="literal"&&n.provenance!=="variable")||wr(e,t))}var Ua="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",Ha="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",PR="__CC_SAFETY_NET_XARGS_INPUT__",oi="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",ii="rm",AR=/(?:^|[;&|]\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,IR=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,TR=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,kR=/^(?:[0-9]+|[@*])$/;function im(e,t){let n=e.map(_),{childStart:r,replacementToken:o}=Xt(n),i=n.slice(r),s=v("xargs.shell-dynamic",Ha);if(MR(i,o,t)&&w(s,t.policy))return w(s,t.policy);for(let a of $e(i,t)){let l=a.tokens,c=o!==null&&l[0]!==i[0]&&(l[0]?.includes(o)??!1)?w(s,t.policy):null;if(c)return c;let u=dm(l,o,a.wrapperEnvAssignments),f=a.head==="rm"&&o!==null&&cm(l,o),d=t.analyzeChild(l,{...qt(a,t),dynamicInput:u,dynamicSourceInput:f||am(l,a.head,o,a.wrapperEnvAssignments,u,t.environment,t.strict?void 0:t.analyzeNested),dynamicRmInput:f,shellDynamicMatch:s,dynamicSourceMatch:s,rmDynamicMatch:v("xargs.rm-recursive-force-dynamic",Ua)});if(d)return d;let m=OR(l,o,t.policy?.rules??[],w(s,t.policy));if(m)return m;if(a.head==="git"){let p=o===null?[...l,PR]:l,h=o!==null&&(l.some((C)=>C.includes(o))||Array.from(a.envAssignments.values()).some((C)=>C.includes(o))),y=t.analyzeChild(p,{...qt(a,t),worktreeMode:o===null||h?!1:t.worktreeMode});if(y)return y}let g=it(l,t.policy?.rules??[]);if(g)return g}return null}function OR(e,t,n,r){if(n.length===0)return null;if(t===null){for(let i of n){let s=it([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],n);if(s)return s}return null}let o=O(e[0]??"");if(!n.some((i)=>O(i.command)===o))return null;return e.slice(1).some((i)=>i.includes(t))?r:null}function sm(e,t,n){let r=e.indexOf(t);if(r===-1||e.indexOf(t,r+t.length)!==-1)return[];let o=jf(e,r,t.length,n);return o===null?[]:[o]}function am(e,t,n,r,o,i,s){if(Y.has(t)){if(at(e))return!1;if(n!==null&&DR(e,n,s))return!0;let a=Ue(e);if(!a){let l=ct(q(e));if(l.kind==="literal")return n!==null&&l.source.includes(n);return l.kind==="none"&&o}if(n!==null&&a.includes(n)&&!lm(a,n,s))return!0;if(Te(a))return!0;return NR(a,n,r)}if(De(t))return rm(e,n,wo,ld(t));if(Ie.has(t))return rm(e,n,Ea,uf);if(t==="eval"){let a=ti(q(e));if(a.kind==="dynamic")return!0;if(n!==null)return a.kind==="literal"&&a.source.includes(n);return o}if(t==="find")return LR(e,n,i);if(t==="git"){let a=we(e);return n===null?a.subcommand===null:(a.subcommand?.includes(n)??!1)||a.subcommand!==null&&wn.has(a.subcommand.toLowerCase())&&um(a.rest,n).some((l)=>l.includes(n))}return!1}function lm(e,t,n){if(n===void 0)return!1;let r=t.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+)*["']?${r}`).test(e)||/\bcase\b/.test(e))return!1;let i=e.replaceAll(t,"/");return Te(i)===null&&n(i)===null}function rm(e,t,n,r){let o=n(e);if(t===null)return o.optionsOpen||n([...e,oi]).sources.some((a)=>a.value===oi);if(o.sources.some((a)=>a.value.includes(t)))return!0;let i=r.flatMap((a)=>[a.selector,...a.valueForm==="attached-only"||a.valueForm==="attached-or-separate"?[`${a.selector}${oi}`]:[],...a.valueForm==="equals-or-separate"?[`${a.selector}=${oi}`]:[]]),s=new Set(i.flatMap((a)=>e.flatMap((l)=>sm(l,t,a))));return Qo(o.sources,s,(a)=>n(e.map((l)=>l.replaceAll(t,a))).sources)}function MR(e,t,n){if(e.length===0||(e[0]??"").toLowerCase()==="command")return!1;let r=new Set(Array.from($e(e,n),(i)=>i.head)),o=t===null?[...e,ii]:e.map((i,s)=>s===0?i:i.replaceAll(t,ii));return Array.from($e(o,n)).some((i)=>i.head===ii&&!r.has(ii))}function cm(e,t){return um(e.slice(1),t).some((n)=>n.includes(t)&&(n.startsWith("-")||n.startsWith(t)))}function um(e,t){let n=e.findIndex((r)=>r==="--"&&!r.includes(t));return n===-1?e:e.slice(0,n)}function dm(e,t,n){if(t===null)return!0;return e.some((r)=>r.includes(t))||Array.from(n.values()).some((r)=>r.includes(t))}function DR(e,t,n){let r=xe(e),o=r.commandIndex===null?"":e[r.commandIndex]??"";if(o.includes(t)&&!lm(o,t,n)||r.scriptIndex!==null&&(e[r.scriptIndex]??"").includes(t))return!0;return["-c","-nc","-cn",`--${t}`,t].some((s)=>e.some((a,l)=>{if(l===0||!a.includes(t))return!1;return sm(a,t,s).some((u)=>{let f=e.map((m,g)=>g===l?m.replaceAll(t,u):m),d=xe(f);if(d.commandIndex===null&&d.scriptIndex===null)return!1;if(r.commandIndex===null&&d.commandIndex!==null)return!0;if(r.scriptIndex===null&&d.scriptIndex!==null)return!0;if(d.commandIndex!==null&&(f[d.commandIndex]??"").includes(u))return!0;return d.scriptIndex!==null&&(f[d.scriptIndex]??"").includes(u)})}))}function NR(e,t,n){let r=new Set(t===null?[]:Array.from(n).filter(([,o])=>o.includes(t)).map(([o])=>o));for(let o of e.matchAll(AR))if(om(o,r))return!0;for(let o of e.matchAll(IR))for(let i of(o[1]??"").matchAll(TR))if(om(i,r))return!0;return $a(e,r)}function om(e,t){let n=e[1]??e[2];return n!==void 0&&(kR.test(n)||t.has(n))}function LR(e,t,n){if(t===null)return!0;let r=!1,o=0;for(let i=1;i<e.length;i++){let s=e[i]??"";if(!r&&!s.startsWith("-")&&s!=="!"&&s!=="("){if(s.indexOf(t)===0)return!0;continue}if(r=!0,o>0){o--;continue}if(qe(s)){let l=_n(e,i);i=l.nextIndex-1;for(let c of $e(l.tokens,{environment:n,cwd:void 0})){let u=dm(c.tokens,t,c.wrapperEnvAssignments);if(c.head==="rm"&&cm(c.tokens,t)||am(c.tokens,c.head,t,c.wrapperEnvAssignments,u,n))return!0}continue}let a=lt(s);if(a>0){if(o=a,s.includes(t))return!0;continue}if(s.includes(t))return!0}return!1}function Xt(e){let t=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"]),n=null,r=1;while(r<e.length){let o=e[r];if(!o)break;if(o==="--")return{childStart:r+1,replacementToken:n};if(!o.startsWith("-"))return{childStart:r,replacementToken:n};if(o==="-I"){n=e[r+1]??"{}",r+=2;continue}if(o.startsWith("-I")&&o.length>2){n=o.slice(2),r++;continue}if(o==="--replace"){n="{}",r++;continue}if(o.startsWith("--replace=")){let i=o.slice(10);n=i===""?"{}":i,r++;continue}if(o==="-J"){n=e[r+1]??"{}",r+=2;continue}r+=t.has(o)?2:1}return{childStart:e.length,replacementToken:n}}var Ir="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",Tr="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",GR="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",FR="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",ai=/\{[^{}\s]*\}/g,fm=/\{\}|\{-?\d+\}/g,mm=/[\s;&|<>()$`\\"']/,zR=["e","f","source","file","-e","-f","--source","--file"],BR=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],$R=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),UR=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),pm=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),HR=new Set(["--workdir","--wd"]),gm="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Oe(e,t){for(let n of e){let r=t(n);if(r)return r}return null}function bm(e){return Oe([...e],(t)=>Te(t))}function Cm(e,t){let n=e.map(_);if((t.envAssignments?.has("PARALLEL")?t.envAssignments.get("PARALLEL"):t.environment.env.get("PARALLEL"))?.trim()){let g=In(t);if(g)return g}if(n.length===2&&(n[1]==="--version"||n[1]==="--help"))return null;let o=km(n),{template:i,jobs:s,runsRemotely:a,readsCommandsFromInput:l,unsupported:c,workdir:u,dryRun:f}=o;if(c){let g=In(t);if(g)return g;let p=bm(t.envAssignments?.values()??[]);if(p)return p}if(l){let g=XR(t);if(g)return g}if(u!==void 0&&a){let g=In(t);if(g)return g}let d=JR(u,t.cwd,t.environment.paths);if(d===null){let g=In(t);if(g)return g}let m=a?{...t,cwd:void 0,originalCwd:void 0}:d===null||d===void 0||d===t.cwd?t:{...t,cwd:d};if(f){if([...$e(i,m)].flatMap((p)=>[...p.envAssignments.values()]).some(Ka)){let p=In(t);if(p)return p}return null}if(i.length===0){let g=s.map((h)=>h[0]??"");t.budget.charge("derivedTokens",g.length);let p=_m(m.envAssignments,m.cwd,a);return Oe(g,(h)=>t.analyzeNested(h,p))}return Oe($e(i,m),(g)=>jR(g,o,t,m))}function jR(e,t,n,r){let{templateHasPlaceholder:o,runsRemotely:i,usesStdin:s}=t,a=e.tokens,l=[...e.envAssignments.values()];if(l.some(Im)){let E=In(n);if(E)return E}let c=bm(l);if(c)return c;let u=l.some(G),f=o||u,d=s&&f,m=_m(e.envAssignments,e.wrapperCwd,i||d),g=f?{...m,worktreeMode:!1}:m,p=a.join(" "),h=G(p.split(/[ \t\n=]/,1)[0]??""),y=!t.quotesCommand&&(h||a.some((E)=>mm.test(E))),C=h||mm.test(a[0]??""),b=y&&C&&t.jobs.length>0?null:VR(e,t,n,r,g,u);if(b||!y)return b;return Sm(G(p)?p:`${p} {}`,!h,e,t,n,r,g)}function VR(e,t,n,r,o,i){let{jobs:s,templateHasPlaceholder:a,runsRemotely:l,usesStdin:c}=t,u=e.tokens,f=a||i;if(Y.has(e.head)){let m=()=>{if(!a||s.length===0)return null;return Oe(s,(h)=>n.analyzeChild(si(u,h,n.budget),qt(e,r)))};if(at(u))return m();let g=Ue(u);if(g){if(Tm(g)){let b=wt(n);if(b)return b;if(s.length===0)return null;return Oe(s,(E)=>n.analyzeNested(Pm(g,E,n.budget),o))}if(G(g))return Sm(g,!1,e,t,n,r,o);let h=!i&&(!a||s.length>0)?(s.length>0?s:[void 0]).map((b)=>ni(q(b===void 0?u:a?u.map((E)=>wm(E,b)):[...u,...b]),g)):[];if(h.some((b)=>b.kind==="dynamic")){let b=wt(n);if(b)return b}let y=h.flatMap((b)=>b.kind==="literal"?[b.source]:[]);if(y.length>0)return n.budget.charge("derivedTokens",y.length),Oe(y,(b)=>n.analyzeNested(b,o));if(Ar(g)){let b=wt(n);if(b)return b}let C=n.analyzeNested(g,o);if(C)return C;if(f)return wt(n);return null}let p=ct(q(u));if(p.kind==="dynamic"||p.kind==="literal"&&G(p.source))return wt(n)??m();if(p.kind==="literal")return m();if(s.length>0){let h=wt(n);if(h)return h;let y=m();if(y)return y;if(a)return null;let C=s.flatMap((b)=>b[0]===void 0?[]:[b[0]]);return n.budget.charge("derivedTokens",C.length),Oe(C,(b)=>n.analyzeNested(b,o))}if(f||c)return wt(n)??m();return null}if(e.head==="rm"&&st(u)){if(a&&s.length>0)return Oe(s,(g)=>ja(si(u,g,n.budget,fm),e.cwd,r));if(s.length>0)return Oe(s,(g)=>ja(ym(u,g,n.budget),e.cwd,r));let m=ja(u.flatMap((g,p)=>{if(p===0||!G(g))return[g];return g.startsWith("-")?[g.replace(fm,"")]:[]}),e.cwd,r);if(m)return m;return Rm(n)}let d=s.length>0?s:[void 0];return Oe(d,(m)=>{let g=m===void 0?u:a?si(u,m,n.budget):ym(u,m,n.budget),p=v("parallel.shell-dynamic",Tr),h=c&&e.head==="find"?ZR(g,r):null,y=Em(g,c,n)??h?.customResult??null,C=O(e.head),b=c&&(C==="rm"&&Va(g)||C==="xargs"&&xm(g)||h?.rmOptions===!0),E=c&&(b||h?.executedSource===!0||h===null&&vm(g,C)),I=n.analyzeChild(g,{...qt(e,r),worktreeMode:l||c||f?!1:n.worktreeMode,dynamicInput:c||f,dynamicRmInput:b,dynamicSourceInput:y!==null||E,shellDynamicMatch:p,dynamicSourceMatch:p,rmDynamicMatch:v("parallel.rm-recursive-force-dynamic",Ir)});if(E){let T=w(p,n.policy);if(T)return T}return I??y??it(g,n.policy?.rules??[])})}function Sm(e,t,n,r,o,i,s){if(r.jobs.length>0)return Oe(r.jobs,(c)=>o.analyzeNested(Pm(e,t?c.map(ri):c,o.budget),s));let a=_r(e);if(a?.[0]&&O(a[0])==="rm"&&st(a)){let c=Rm(o);if(c)return c}return(a?o.analyzeChild(a,{...qt(n,i),dynamicInput:r.usesStdin,shellDynamicMatch:v("parallel.shell-dynamic",Tr),rmDynamicMatch:v("parallel.rm-recursive-force-dynamic",Ir)}):null)??o.analyzeNested(e,s)}function vm(e,t){if(G(e[0]??""))return!0;if(t==="eval"||t==="source"||t===".")return!0;if(t==="parallel"||t==="xargs")return!0;if(Y.has(t))return YR(e);if(t==="git")return KR(e);if(t==="find")return!0;if(Ie.has(t))return hm(e,zR,xr);if(De(t))return hm(e,BR,_o);return!1}function Va(e){let t=e.indexOf("--"),n=e.slice(1,t===-1?void 0:t);if(!e.some(G))return t===-1;return n.some((o)=>G(o)&&(o.startsWith("-")||Tm(o)))}function KR(e){if(qR(e))return!0;let t=we(e);if(t.subcommand===null||G(t.subcommand))return!0;if(!wn.has(t.subcommand.toLowerCase()))return!1;let n=t.rest.indexOf("--"),r=t.rest.slice(0,n===-1?void 0:n);if(!e.some(G))return n===-1;return r.some(G)}function qR(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n||n==="--"||!n.startsWith("-"))return!1;if(n==="-c"||n==="--config-env"){if(G(e[t+1]??""))return!0;t++;continue}if(n.startsWith("-c")&&n.length>2||n.startsWith("--config-env=")){if(G(n))return!0;continue}if(G(n))return!0}return!1}function YR(e){if(at(e))return!1;let t=Ue(e);if(t!==null)return G(t);let n=ct(q(e));if(n.kind==="literal")return G(n.source);if(n.kind==="dynamic")return!0;return!e.some(G)}function hm(e,t,n){let r=n(e);if(r.some((o)=>G(o.value)))return!0;if(!e.some(G))return n([...e,gm]).some((o)=>o.value===gm);return Qo(r,t,(o)=>n(e.map((i)=>wm(i,[o]))))}function Em(e,t,n){let r=n.policy?.rules??[];if(!t||r.length===0)return null;let o=r.filter((i)=>O(i.command)===O(e[0]??""));if(o.length===0)return null;if(e.slice(1).some(G))return wt(n);return Oe(o,(i)=>it([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],[i]))}function ZR(e,t){let n={customResult:null,executedSource:!e.some(G),rmOptions:!1},r=!1,o=0,i=null,s=()=>{if(!i?.some(G))return;for(let a of $e(i,t))n.executedSource||=vm(a.tokens,a.head),n.rmOptions||=a.head==="rm"&&Va(a.tokens)||a.head==="xargs"&&xm(a.tokens),n.customResult??=Em(a.tokens,!0,t)};for(let a of e.slice(1)){if(!r&&!a.startsWith("-")&&a!=="!"&&a!=="("){n.executedSource||=G(a);continue}if(r=!0,i){if(a===";"||a==="+"){s(),i=null;continue}i.push(a);continue}if(o>0){o--;continue}if(qe(a)){i=[],n.executedSource||=G(a);continue}let l=lt(a);if(l>0){o=l,n.executedSource||=G(a);continue}n.executedSource||=G(a)}return s(),n}function xm(e){let t=e.slice(Xt(e).childStart);return O(t[0]??"")==="rm"&&Va(t)}function li(e,t){return(n)=>w(v(e,t),n.policy)}var wt=li("parallel.shell-dynamic",Tr),XR=li("parallel.command-stream-dynamic",GR),In=li("parallel.command-stream-dynamic",FR),Rm=li("parallel.rm-recursive-force-dynamic",Ir);function ja(e,t,n){return w(ei(q(e),{environment:n.environment,cwd:t,budget:n.budget,originalCwd:n.originalCwd,strict:n.strict,paranoid:n.paranoidRm,allowTmpdirVar:n.allowTmpdirVar,tmpdirWordSplittingUnsafe:jt(n.envAssignments??new Map,n.environment),trustedTmpdirValue:vn(n.envAssignments??new Map,n.environment),protectedGitMetadata:n.protectedGitMetadata,policy:n.policy}),n.policy)}function _m(e,t,n){let r={};if(e)r.envAssignments=e;if(n)return r.effectiveCwd=null,r.worktreeMode=!1,r;if(t!==void 0)r.effectiveCwd=t;return Object.keys(r).length>0?r:void 0}function wm(e,t){return e.replace(ai,(n)=>Am(n,t))}function si(e,t,n,r=ai){return n.charge("derivedTokens",e.reduce((o,i)=>o+1+Math.floor(i.length/64),0)),e.map((o)=>o.replace(r,(i)=>{let s=Am(i,t);return n.charge("derivedTokens",Math.max(1,Math.ceil(s.length/64))),s}))}function Pm(e,t,n){return si([e],t,n)[0]??""}function ym(e,t,n){return n.charge("derivedTokens",e.length+t.length),[...e,...t]}function Am(e,t){let n=/^\{(-?\d+)[^{}\s]*\}$/.exec(e)?.[1];if(n===void 0)return t[0]??"";let r=Number(n);return t[r>0?r-1:t.length+r]??""}function G(e){return e.search(ai)!==-1}function Im(e){if(Ka(e))return!0;for(let t of e.matchAll(ai))if(!/^(?:\{\}|\{\d+\})$/.test(t[0]))return!0;return!1}function Ka(e){let t=e.indexOf("{=");return t!==-1&&e.indexOf("=}",t+2)!==-1}function Tm(e){return/^\{[^{}\s]*\}$/.test(e)}function JR(e,t,n){if(e===void 0)return;if(e==="..."||/^~|[{}$`*?[]/.test(e))return null;if(!t&&!WR(e))return null;try{return Ct(t??e,e,n)}catch{return null}}function km(e){let t=1,n=[],r=e.length,o=-1,i=!1,s=!1,a=!1,l,c=!1,u=e.some((p)=>p==="::::"||p==="::::+"||p===":::+");while(t<e.length){let p=e[t];if(p===void 0)break;if(p===":::"){o=t;break}if(p==="--"){let E=_a(e,t+1);n.push(...E.templateTokens),r=t+1,o=E.markerIndex;break}if(!p.startsWith("-")){let E=_a(e,t);n.push(...E.templateTokens),r=t,o=E.markerIndex;break}let h=e[t+1],y=p.indexOf("="),C=y===-1?p:p.slice(0,y),b=y===-1?void 0:p.slice(y+1);if(p==="--dry-run"){c=!0,t++;continue}if(p==="-I"||p.startsWith("-I")&&p.length>2){u||=(p==="-I"?h:p.slice(2))!=="{}",t+=p==="-I"?2:1;continue}if(p==="--replace"||p==="-i"){u=!0,t+=2;continue}if(C==="--replace"||p.startsWith("-i")&&p.length>2){let E=C==="--replace"?b:p.slice(2);u||=E!==""&&E!=="{}",t++;continue}if(p==="-a"||UR.has(C)){u=!0,t+=b===void 0?2:1;continue}if(p==="-q"||p==="--quote"){s=!0,t++;continue}if(p==="--pipe"||p==="--pipepart"){a=!0,t++;continue}if(C==="--env"){u=!0,t+=b===void 0?2:1;continue}if(pm.has(C)||p.startsWith("-S")&&p.length>2){i=!0,t+=pm.has(p)?2:1;continue}if(HR.has(C)){u=!0;let E=b??h;if(E===void 0||E===":::"||E==="--"){t++;continue}l=E,t+=b===void 0?2:1;continue}if(p.startsWith("-j")&&p.length>2&&/^\d+$/.test(p.slice(2))){t++;continue}if(p.startsWith("--")&&b!==void 0){t++;continue}if($R.has(p)){if(h===void 0||h===":::"||h==="--"){u=!0,t++;continue}t+=2;continue}t+=p==="-j"||p==="--jobs"?2:1}u||=n.some(c?Ka:Im);let f=[];if(o!==-1){let p=[];for(let h=o+1;h<e.length;h++){let y=e[h];if(y===":::"){f.push(p),p=[];continue}if(y!==void 0)p.push(y)}f.push(p)}u||=f.length>1;let d=QR(f),m=n.some(G),g=n.length===0&&o===-1;return{template:n,jobs:d,childStart:r,templateHasPlaceholder:m,runsRemotely:i,quotesCommand:s,usesStdin:a||o===-1,readsCommandsFromInput:g,unsupported:u,workdir:l,dryRun:c}}function QR(e){if(e.length===0||e.some((n)=>n.length===0))return[];let t=[[]];for(let[n,r]of e.entries()){if(r.length===1){let i=r[0];if(i===void 0)return[];for(let s of t)s.push(i);if(t.length*(n+1)>K.derivedTokens.cap)throw new W("derivedTokens");continue}let o=[];for(let i of t)for(let s of r){if((o.length+1)*(n+1)>K.derivedTokens.cap)throw new W("derivedTokens");o.push([...i,s])}t=o}return t}function Om(e){return km(e).childStart}var e_="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",ci="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function Ya(e){return e?.parts.some((t)=>t.provenance==="command-substitution")??!1}function qa(e){return e?.parts.some((t)=>t.provenance==="literal"&&t.raw.replace(/^["']/,"").startsWith("-"))??!1}function Dm(e,t,n,r,o=!1,i){let a=(er(e,t)||r&&e!=="powershell"&&t[0]?.provenance==="variable")&&ee(i,"shell.dynamic-executable",o)?v("shell.dynamic-executable",e_):null;return w(a,i)??Nm(e,t,n,o,i)}function Nm(e,t,n,r,o){if(t.length<2)return null;let i=t.flatMap((a,l)=>Ya(a)?[l]:[]);if(i.length===0)return null;let s=O(t[0]?.text??"");if(s==="git"){let a=gn(e,t),l=n_(a);if(ee(o,"shell.dynamic-structure",r)&&i.some((f)=>f<=l))return w(v("shell.dynamic-structure",ci),o);if(w(Jo(a,{environment:n}),o))return null;let c=t[l]?.text.toLowerCase(),u=a.findIndex((f,d)=>d>l&&_(f)==="--");if(ee(o,"shell.dynamic-structure",r)&&c&&wn.has(c)&&i.some((f)=>f>l&&(u===-1||f<u)))return w(v("shell.dynamic-structure",ci),o);return null}if(s==="find")return ee(o,"shell.dynamic-structure",r)&&r_(t)?w(v("shell.dynamic-structure",ci),o):null;if(s==="rm"){let a=t.findIndex((c,u)=>u>0&&_(c)==="--"),l=st(t.map(_));return ee(o,"shell.dynamic-structure",r)&&i.some((c)=>(a===-1||c<a)&&(c<t.length-1||!l))?w(v("shell.dynamic-structure",ci),o):null}if(s==="xargs")return Mm(e,t.slice(Xt(t.map(_)).childStart),"xargs",n,r,o);if(s==="parallel")return Mm(e,t.slice(Om(t.map(_))),"parallel",n,r,o);return null}function Mm(e,t,n,r,o,i){if(t.length===0)return null;let s=t_(t,r);if(er(e,s)){let l=w(v(`${n}.shell-dynamic`,n==="xargs"?Ha:Tr),i);if(l)return l}let a=Nm(e,s,r,o,i);if(a)return a;if(s[0]?.text==="rm"&&s.slice(1).some((l)=>Ya(l)&&qa(l)))return w(v(`${n}.rm-recursive-force-dynamic`,n==="xargs"?Ua:Ir),i);return null}function t_(e,t){let n=$t(e,t),r=n.rewritten?q(n.words.map(_)):n.words,o=r[0];return o&&_(o)==="busybox"?r.slice(1):r}function n_(e){let t=1;while(t<e.length){let n=e[t],r=n?_(n):"";if(Ee.has(r)){t+=2;continue}if(r.startsWith("-")){t++;continue}return t}return t}function r_(e){let t=!1,n=0,r=!1,o=!1;for(let i=1;i<e.length;i++){let s=e[i];if(!s)continue;let a=Ya(s);if(n>0){n--;continue}if(o){if(s.text===";"||s.text==="+"){o=!1,t=!0,r=!1;continue}if(a&&(r||qa(s)))return!0;r=!1;continue}if(!t&&!s.text.startsWith("-")){if(a&&(i>1||qa(s)))return!0;continue}if(t=!0,a)return!0;let l=lt(s.text);if(l>0){n=l;continue}if(qe(s.text))o=!0,r=!0}return!1}function Za(e,t){return e.some((n)=>{if(n.value==="-"&&(n.kind==="main-script"||n.kind==="program-file"))return!0;return!vo(t[n.tokenIndex],n.value)})}var Gm=[{heads:new Set(["rm","rmdir"]),analyze:(e)=>ei(e.words,Wm(e))},{heads:new Set(["git"]),analyze:(e)=>Jo(e.words,Xa(e))},{heads:new Set(["find"]),analyze:(e)=>Sf(e.words,{...Wm(e),envAssignments:e.envAssignments,analyzeTokens:e.analyzeChildTokens})},{heads:new Set(["xargs"]),analyze:(e)=>im(e.words,{...Lm(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>Tn(e.options.analyzeNested(t,n))})},{heads:new Set(["parallel"]),analyze:(e)=>Cm(e.words,{...Lm(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>Tn(e.options.analyzeNested(t,n))})}];function Lm(e){return{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoidRm:e.options.paranoidRm,paranoidInterpreters:e.options.paranoidInterpreters,allowTmpdirVar:e.allowTmpdirVar,protectedGitMetadata:e.options.protectedGitMetadata,budget:e.options.budget,envAssignments:e.envAssignments,worktreeMode:e.options.worktreeMode,policy:e.options.policy}}function Tn(e){return e?{id:e.ruleId,reason:e.reason,intent:e.intent??"manual_only"}:null}function Wm(e){return{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoid:e.options.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:jt(e.envAssignments,e.options.environment),trustedTmpdirValue:vn(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,policy:e.options.policy,budget:e.options.budget}}function Xa(e){return{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,dynamicArguments:e.dynamicArguments,envAssignments:e.envAssignments,shellAssignments:e.options.shellAssignments,policy:e.options.policy,worktreeMode:e.options.worktreeMode}}function Bm(e){return Gm.find((t)=>t.heads.has(e))?.analyze}function On(e,t,n){let r=n.trace;if(e.length===0)return null;let o=n.commandView?.dialect??"posix",i=(x)=>x.map((A)=>o==="posix"?_(A):A.text),s=n.child,a=s!==void 0&&!s.embedded,l=s?.embedded===!0,c=n.effectiveCwd===null,u=s?s.cwd:c?void 0:n.effectiveCwd??n.cwd,f=s?s.originalCwd:c?void 0:n.cwd,d=Io(e);if(d.envAssignments.size>0)r?.recordSegment({type:"env-strip",input:i(e),envVars:[...d.envAssignments.keys()],output:i(d.words)});let m=$t(d.words,n.environment,u,new Map([...n.envAssignments??[],...d.envAssignments])),g=m.envSplitValues??[];if(g.length>0){let x=[...g,...i(m.words)].join(" "),A=Te(x);if(A)return r?.recordSegment({type:"dangerous-text",token:x,matched:!0,reason:A.reason}),de(A);if(n.strict)return ye(r);let z=To(g,i(m.words));if(z){n.budget.charge("derivedTokens",z.length);let ne=n.analyzeNested(z.join(" "),{effectiveCwd:m.cwd===void 0?n.effectiveCwd:m.cwd,envAssignments:new Map([...n.envAssignments??[],...d.envAssignments,...m.envAssignments])});if(ne)return ne}}let p=m.rewritten?q(i(m.words)):gn(o,m.words),h=i(p),y={...n,wrapperNormalizationBudget:n.wrapperNormalizationBudget??{iterations:0}};if(r&&d.words.length>p.length){let x=i(d.words);r.recordSegment({type:"leading-tokens-stripped",input:x,removed:x.slice(0,x.length-p.length),output:h})}let C=new Map([...n.envAssignments??[],...d.envAssignments,...m.envAssignments]),b=h[0];if(!b)return null;if(Kt(b))throw new W("wrapperPeelIterations");let E=O(b),I=m.cwd===null?void 0:m.cwd??u,T=m.cwd===null?void 0:f,k=m.cwd===void 0?n.effectiveCwd:m.cwd,F=s?s.allowTmpdirVar:!br(C,n.environment),ue=Dm(o,m.words,n.environment,t===0,n.strict,n.policy);if(ue)return r?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:ue.reason}),de(ue);let Xe=Vo(h,n.policy);if(Xe){for(let x of[Xe.childIndex,...Xe.alternativeChildIndices]){Fm(y.wrapperNormalizationBudget);let A=p.slice(x);r?.recordSegment({type:"transparent-wrapper",wrapper:Xe.wrapper,output:i(A)});let z=On(A,t,{...y,effectiveCwd:k,envAssignments:C});if(z)return z}return null}let Ce=l?void 0:E==="eval"?ti(p):E==="trap"&&!a?Jf(p):void 0;if(a&&s&&E==="eval"){if(Ce?.kind==="dynamic")return kn(s,n.policy);if(Ce?.kind==="literal"){let x=n.analyzeNested(Ce.source,{effectiveCwd:k,envAssignments:C});if(x)return x}return Mn(s,n.policy)}if(Ce?.kind==="dynamic"&&(n.strict||!n.commandView||!Ba(n.commandView)))return ye(r);if(Ce?.kind==="literal"){r?.recordSegment({type:"recurse",reason:E==="eval"?"shell-eval":"shell-trap",innerCommand:Ce.source,depth:t+1});let x=n.analyzeNested(Ce.source,{effectiveCwd:k,envAssignments:C,functionDefinitions:n.functionDefinitions});if(x)return x}if(a?Y.has(E):Um(b,E)){if(at(h))return null;if(a&&s){let x=Ue(h);if(x){if(s.dynamicSourceInput??s.dynamicInput){let z=kn(s,n.policy);if(z)return z}if(Ar(x)){let z=kn(s,n.policy);if(z)return z}return n.analyzeNested(x,{effectiveCwd:k,envAssignments:C})}let A=ct(p);if(A.kind==="dynamic")return kn(s,n.policy);if(A.kind==="literal")return s.dynamicSourceInput?kn(s,n.policy):null;return s.dynamicSourceInput??s.dynamicInput?kn(s,n.policy):null}if(l){let x=Ue(h),A=x?n.analyzeNested(x,{effectiveCwd:k,envAssignments:C}):ct(p).kind==="dynamic"?ye(r):null;if(A)return A}if(s===void 0){let x=a_(h,C,k,n,r,t);if(x)return x;let A=Ue(h);if(A){let rn=ni(p,A);if(rn.kind==="dynamic")return ye(r);let Ri=rn.kind==="literal"?rn.source:Qf(p,A),wl=l_(Ri);r?.recordSegment({type:"shell-wrapper",wrapper:E,innerCommand:wl}),r?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:wl,depth:t+1});let Pl=n.analyzeNested(Ri,{effectiveCwd:k,envAssignments:C});if(Pl)return Pl;return Ar(Ri)?ye(r):null}let z=ct(p,n.strict?void 0:n.shellAssignments);if(z.kind==="dynamic")return ye(r);if(z.kind==="literal")return ui(z.source,k,C,n,r,t);let ne=em(p,n.commandView?.redirections??[],n.hasPipelineInput??!1,n.literalShellInput);if(ne.kind==="dynamic")return ye(r);if(ne.kind==="literal")return r?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:ne.source,depth:t+1}),n.analyzeNested(ne.source,{effectiveCwd:k,envAssignments:C})}}if(!s&&(E==="source"||E===".")){let x=h[1]==="-p"?2:null;if(x!==null){let rn=n.commandView?p[x]:void 0;if(!rn)return null;if(rn.provenance!=="literal")return ye(r)}let A=x===null?1:3,z=h[A]==="--"?A+1:A,ne=n.commandView?p[z]:void 0;if(!ne)return null;if(ne.provenance==="literal")return ui(ne.text,k,C,n,r,t);if(n.strict||!n.commandView||!Ba(n.commandView))return ye(r)}if(Ie.has(E)&&!l){if(!s&&n.strict&&Za(xr(h),p))return ye(r);let x=df(h,(z)=>Tn(n.analyzeNested(z,{effectiveCwd:k,envAssignments:C}))),A=w(x,n.policy);if(A)return r?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:A.reason}),de(A)}if(De(E)&&!l){if(!s&&n.strict&&Za(_o(h),p))return ye(r);let x=ad(h);if(a&&s)return i_(E,x,k,C,n,s);if(x){let A=ee(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(r?.recordSegment({type:"interpreter",interpreter:E,codeArg:x,paranoidBlocked:A}),A){let ne=w(v("interpreter.one-liner-paranoid",ur),n.policy);if(ne)return de(ne)}if(ea(E,x))return null;r?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:x,depth:t+1});let z=n.analyzeNested(x,{effectiveCwd:k,envAssignments:C});if(z&&!$m(z,x))return z;if(dr(x,void 0,!n.strict)){let ne=w(v("interpreter.dangerous-command",bn),n.policy);if(ne)return r?.recordSegment({type:"dangerous-text",token:x,matched:!0,reason:bn}),de(ne)}r=void 0}}if(E==="busybox"&&h.length>1)return Fm(y.wrapperNormalizationBudget),r?.recordSegment({type:"busybox",subcommand:h[1]??"unknown"}),r?.recordSegment({type:"recurse",reason:"busybox",innerCommand:h.slice(1).join(" "),depth:t+1}),On(p.slice(1),t,{...y,effectiveCwd:k,envAssignments:C});let U=s?null:w(hf(E,h),n.policy);if(U)return r?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:U.reason}),de(U);let L=r===y.trace?y:{...y,trace:r},ae={words:p,head:E,cwd:I,originalCwd:T,envAssignments:C,allowTmpdirVar:F,dynamicArguments:m.words.some((x)=>x.provenance==="command-substitution"),depth:t,effectiveCwd:k,options:L,analyzeChildTokens:(x,A)=>a&&s?Qa(x,t,L,{...s,cwd:A??void 0,effectiveCwd:A??void 0}):Tn(On(q(x),t+1,{...L,child:void 0,commandView:void 0,effectiveCwd:A,envAssignments:C}))??it(x,L.policy.rules),analyzeChild:(x,A)=>Qa(x,t,L,A)},J=s&&(E==="xargs"||E==="parallel")?void 0:Bm(E);if(E==="rm"||E==="xargs"||E==="parallel")r?.recordSegment({type:"tmpdir-check",tmpdirValue:C.has("TMPDIR")||n.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:F});let Q=r&&E==="git"?Hf(ae.words,Xa(ae)):void 0,Se=zm(Q?Q.match:J?.(ae)??null,n.policy);if(r)c_(ae,Se,Q?.relaxation??null);if(Se)return de(Se);if(a&&s&&(E==="rm"||E==="rmdir")){if(!(E==="rm"&&(st(h)||s.dynamicRmInput)))return null;return(s.dynamicRmInput?Mn(s,n.policy):null)??s_(s,n.policy)}let kt=!s&&J===void 0&&!Yr.has(E),Wn=r&&kt?[]:void 0;if(kt)for(let x=1;x<h.length;x++){let A=h[x];if(!A)continue;Wn?.push(A);let z=zm(o_(h,x,t,L,I,T,k,C),n.policy);if(z)return r?.recordSegment({type:"fallback-scan",tokensScanned:Wn??[],embeddedCommandFound:O(A)}),de(z)}if(r?.recordSegment({type:"fallback-scan",tokensScanned:Wn??[]}),l&&s&&!s.wrappedByTransparent)return null;let Pe=it(h,n.policy.rules);if(r?.recordSegment({type:"custom-rules-check",rulesChecked:n.policy.rules.length>0,matched:!!Pe,reason:Pe?.reason}),Pe)return de(Pe);return a&&s?Mn(s,n.policy):null}function Qa(e,t,n,r){return Tn(On(q(e),t+1,{...n,trace:void 0,commandView:void 0,hasPipelineInput:void 0,literalShellInput:void 0,functionDefinitions:void 0,cwd:r.originalCwd,effectiveCwd:r.effectiveCwd,envAssignments:r.envAssignments,worktreeMode:r.dynamicInput?!1:r.worktreeMode,wrapperNormalizationBudget:{iterations:0},child:r}))}function o_(e,t,n,r,o,i,s,a){for(let l of $e(e.slice(t),{environment:r.environment,cwd:o,envAssignments:a,policy:r.policy})){let c=l.tokens[0];if(!c)continue;let u=O(c);if(Um(c,u)||Bm(u)!==void 0&&u!=="xargs"&&u!=="parallel"||l.wrappedByTransparent&&r.policy.rules.length>0)r.budget.charge("derivedTokens",e.length-t);let d=Qa(l.tokens,n,r,{embedded:!0,cwd:l.cwd,originalCwd:l.wrapperCwd===null?void 0:i,effectiveCwd:l.wrapperCwd===void 0?s:l.wrapperCwd,envAssignments:l.envAssignments,allowTmpdirVar:!br(l.envAssignments,r.environment),worktreeMode:!1,wrappedByTransparent:l.wrappedByTransparent});if(d)return d}return null}function i_(e,t,n,r,o,i){if(!t)return Mn(i,o.policy);if(ee(o.policy,"interpreter.one-liner-paranoid",!!o.paranoidInterpreters)){let a=w(v("interpreter.one-liner-paranoid",ur),o.policy);if(a)return de(a)}if(ea(e,t))return Mn(i,o.policy);let s=o.analyzeNested(t,{effectiveCwd:n,envAssignments:r});if(s&&!$m(s,t))return s;if(dr(t,void 0,!o.strict)){let a=w(v("interpreter.dangerous-command",bn),o.policy);if(a)return de(a)}return Mn(i,o.policy)}function $m(e,t){let n=e.ruleId==="raw-text.dangerous-command",r=(e.reason.startsWith(Uo)||e.reason===Rn)&&!Zr(t);return n||r}function kn(e,t){let n=e.shellDynamicMatch?w(e.shellDynamicMatch,t):null;return n?de(n):null}function Mn(e,t){let n=e.dynamicSourceInput&&e.dynamicSourceMatch?w(e.dynamicSourceMatch,t):null;return n?de(n):null}function s_(e,t){let n=e.dynamicInput&&e.rmDynamicMatch?w(e.rmDynamicMatch,t):null;return n?de(n):null}function a_(e,t,n,r,o,i){let s=Cf(e);if(s.argvSource?.kind==="absent")return ye(o);if(s.argvSourceApplies&&s.argvSource){let l=ui(s.argvSource.value,n,t,r,o,i,!0);if(l)return l}if(!s.envSourceApplies||!s.envName)return null;let a=t.get(s.envName);if(!a)return null;return ui(a,n,t,r,o,i,!0)}function ui(e,t,n,r,o,i,s=!1){if(s&&/[$`*?[\]]/.test(e))return ye(o);let a=cr(e,t,r.environment.paths,r.budget),l=a?r.literalHeredocFiles?.get(a):void 0;if(l===void 0)return s?ye(o):null;return r.budget.charge("derivedTokens",1),o?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:l,depth:i+1}),r.analyzeNested(l,{effectiveCwd:t,envAssignments:n})}function l_(e){let t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.at(-1)===t?e.slice(1,-1):e}function c_(e,t,n){let r={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[e.head];if(!r)return;if(e.options.trace?.recordSegment({type:"rule-check",rule:r,matched:!!t||!!n,reason:t?.reason??n?.originalReason}),n)e.options.trace?.recordSegment({type:n.kind==="worktree"?"worktree-relaxation":"temp-root-relaxation",originalReason:n.originalReason,gitCwd:n.gitCwd})}function Fm(e){if(e.iterations>=K.wrapperPeelIterations.cap)throw new W("wrapperPeelIterations");e.iterations++}function de(e){return{reason:e.reason,ruleId:e.id,intent:e.intent}}function ye(e){return e?.recordSegment({type:"error",message:vr}),de(u_())}function u_(){return{id:"analysis.dynamic-shell-source",reason:vr,intent:"stop_and_explain"}}function Um(e,t){return Y.has(t)||e==="$SHELL"||e==="${SHELL}"||Y.has(P(t))}function zm(e,t){return e?.id.startsWith("custom.")||e?.id==="raw-text.dangerous-command"?e:w(e,t)}var d_=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,f_=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function m_(e,t){let n=Vm(e,t);if(n.length===0)return!1;let r=n[jm(n)];if(r==="cd"||r==="pushd"||r==="popd")return!0;return d_.test(e.join(" "))}function Hm(e,t,n,r,o){if(e.dialect==="powershell"){let b=p_(e.words,o);if(b.kind==="none")return;if(!t||b.kind==="unknown")return null;return Ja(b_(b.target),t,n.paths)}let i=e.words.map(_),s=i.some((b)=>/^CDPATH\+?=/.test(b));if(!m_(i,n))return s?null:void 0;if(!t)return null;let a=Vm(i,n,t),l=jm(a);if(l===-1||a[l]!=="cd")return null;let c=a.slice(l+1),u=c.findIndex((b)=>b.length<=1||!b.startsWith("-")||b==="--");if((u===-1?c:c.slice(0,u)).some((b)=>!/^-[LP]+$/.test(b)))return null;let d=u===-1?[]:c.slice(u),m=d[0]==="--"?d.slice(1):d;if(m.length>1)return null;let g=m[0],p=r.get("HOME")||n.home;if(g===void 0)return Ja(p,t,n.paths);let h=e.words.find((b)=>b.provenance==="variable"&&b.text===g),y=e.words.find((b)=>b.text===g&&/^~(?:\/|$)/.test(b.raw)),C=h?Ye(h,new Map([...r,["HOME",p]])):y?`${p}${g.slice(1)}`:g;if(C===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(C)&&(s||n.env.has("CDPATH")))return null;return Ja(C,t,n.paths)}function Ja(e,t,n){if(!e||e==="-"||e.startsWith("~")||e.includes("$")||e.includes("`"))return null;try{let r=Ct(t,e,n);return n.isDirectory(r)?r:null}catch{return null}}function p_(e,t){let n=g_(e[0])?1:0,r=e[n];if(!h_(r,n===1))return{kind:"none"};let o=r.text.toLowerCase(),i=o.split(/[\\/]/).pop()??o;if(!f_.has(i))return{kind:"none"};if(o!==i||i==="pop-location"||i==="popd")return{kind:"unknown"};return y_(e.slice(n+1),t)}function g_(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&(e.text==="&"||e.text===".")}function h_(e,t){return e?.provenance==="literal"&&(t||!e.quoted&&e.raw===e.text)}function y_(e,t){let n;for(let r of e){if(r.provenance!=="literal"||n!==void 0)return{kind:"unknown"};n=r.text}if(n!==void 0)return{kind:"target",target:n};return t===void 0?{kind:"unknown"}:{kind:"target",target:t}}function b_(e){return e.includes("::")?void 0:e.replaceAll("\\","/")}function jm(e){let t=0;if(e[0]==="builtin"&&e.length>1)t=1;if(e[t]!=="time")return t;let n=t+1;while(e[n]?.startsWith("-"))n++;return n}function Vm(e,t,n){let r=C_(e);return St([...r],t,n)}function C_(e){let t=0;while(t<e.length){let n=e[t];if(n!=="{"&&n!=="("&&n!=="$(")break;t++}return e.slice(t)}var w_="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",Jt="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 il(e,t,n,r){if(t>=K.recursionDepth.cap)return n.trace?.recordSegment({type:"error",message:Ve}),{reason:Ve,segment:e,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};let o=r??n.factStore?.getCommandProgram(e,n.shell??"auto")??Ne(e,n.shell);if(o.status==="limited")return n.trace?.recordSegment({type:"error",message:Ve}),{reason:Ve,segment:e,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"};if(o.status==="invalid"){let c=o.issues.find((u)=>u.code.includes("heredoc"));if(c){if(!n.strict)return ol(e,n);let u=`${Uo}: ${c.message}`;return n.trace?.recordGlobal({type:"error",message:u}),{reason:u,segment:e,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"}}return Jm(e,n),{reason:Rn,segment:e,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"}}if(n.strict&&o.status==="partial")return Jm(e,n),{reason:Rn,segment:e,ruleId:"analysis.strict-unparseable",intent:"stop_and_explain"};if(o.issues.some((c)=>c.code.includes("quote")))return ol(e,n);let s=n.cwd,a=n.effectiveCwd!==void 0?n.effectiveCwd:n.cwd,l=Of(n.environment.env,n.envAssignments);return mi(o,t,{...n,rootProgram:o},s,[{effectiveCwd:a,shellGitContextState:l,literalHeredocFiles:new Map(n.literalHeredocFiles),functionDefinitions:new Map(n.functionDefinitions),createdDirectories:new Set,compoundBodies:[]}]).result}function mi(e,t,n,r,o){let i=[...o],s,a,l;for(let[c,u]of e.nodes.entries()){if(u.kind==="connector"){a=u.operator;continue}let f=e.nodes[c+1],d=f?.kind==="connector"?f.operator:void 0,m=P_(e,c,u,a,d),p=a==="&&"||a==="||"?s:void 0,h=a==="&&"?p?.success??i:a==="||"?p?.failure??i:i,y=a==="||"?p?.success??[]:[],C=a==="&&"?p?.failure??[]:[],b={connector:a,skippedSuccessStates:y,skippedFailureStates:C};if(Pt(d)&&!Pt(a))l=b;let E=Pt(d)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:Pt(a)?l??b:b,I=Qt(E.connector)||Qt(d);if(u.kind==="function"){let U=h.flatMap((ae)=>{let J=en(ae);return J.functionDefinitions.set(u.name,u.body),el(ae,[J],m,d==="&",Qt(d))}),L=tl(U,[],E.skippedSuccessStates,E.skippedFailureStates,E.connector,d);i=L.states,s=L.conditionalStates,a=void 0;continue}if(u.kind==="group"){let U=[],L=[];for(let J of h){let Q=mi(u.body,t,n,r,[en(J)]);if(Q.result)return Q;if(U.push(...el(J,Q.states,m,d==="&",Qt(d))),I)L.push(J,...m?Q.states.map((Se)=>di(J,Se)):Q.states)}let ae=tl(U,L,E.skippedSuccessStates,E.skippedFailureStates,E.connector,d);i=ae.states,s=ae.conditionalStates,a=void 0;continue}if(u.kind!=="command")continue;let T=Z_(e.nodes[c-1]),k=n.trace?.flattenNested?n.trace.currentSegmentIndex:n.trace?.allocateSegment(),F=e.nodes[c-2],ue=Pt(a)&&F?.kind==="command"?Xf(F)??I_(F):void 0,Xe=[],Ce=[];for(let U of h){let L=T_(u,t,n,r,[en(U)]);if(L.result)return{result:L.result,states:i};let ae=e.dialect==="powershell"?L.states:L.states.map((J)=>di(U,J));for(let J of ae){let Q=en(J),Se=M_(u,t,n.trace?{...n,trace:Qm(n.trace,k)}:n,r,Q,Pt(a),ue);if(Se)return{result:Se,states:i};let ft=rw(u,Q.functionDefinitions);if(ft)n.budget.charge("derivedTokens",pi(ft));let kt=ft?t+1>=K.recursionDepth.cap?nl(u.displayText,n,[Q]):mi(ft,t+1,n,r,[Q]):{result:null,states:tw(u,Q).flatMap((Pe)=>X_(u,J,Pe,T))};if(kt.result)return kt;Xe.push(...el(U,kt.states,m,d==="&",Qt(d)));let Wn=typeof Q.effectiveCwd==="string"&&Q.effectiveCwd!==J.effectiveCwd&&u.redirections.every((Pe)=>["<",">",">>",">|"].includes(Pe.operator)&&Pe.target?.text==="/dev/null");if(I&&(T||!Wn))Ce.push(U),Ce.push(...kt.states.map((Pe)=>m?di(U,Pe):Pe))}}let Tt=tl(Xe,Ce,E.skippedSuccessStates,E.skippedFailureStates,E.connector,d);i=Tt.states,s=Tt.conditionalStates,a=void 0}return{result:null,states:i}}function P_(e,t,n,r,o){if(n.kind==="group"&&n.style==="subshell")return!0;if(e.dialect==="posix"&&(Pt(r)||Pt(o)))return!0;if(o==="&")return!0;return e.dialect==="powershell"&&n.kind==="group"&&n.style==="brace"&&A_(e,t)}function el(e,t,n,r,o){let i=n?t.map((a)=>di(e,a)):[...t],s=o?i.flatMap((a)=>Dn(e.literalHeredocFiles,a.literalHeredocFiles)?[a]:[{...a,literalHeredocFiles:new Map(e.literalHeredocFiles)},a]):i;return r?[e,...s]:s}function di(e,t){return{...e,literalHeredocFiles:new Map(t.literalHeredocFiles),createdDirectories:new Set(t.createdDirectories)}}function A_(e,t){let n=e.nodes.slice(0,t).reverse().find((o)=>o.kind==="command"||o.kind==="connector");if(!n||n.kind!=="command")return!0;let r=n.words[0]?.text.toLowerCase();if(r==="&"||r===".")return!1;if(r==="write-output"||r==="function"||r==="start-job")return!0;if(k_(n))return!0;return n.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function Pt(e){return e==="|"||e==="|&"}function I_(e){if(e?.dialect!=="powershell")return;if(e.words.length===1&&e.words[0]?.quoted&&e.words[0].provenance==="literal")return e.words[0].text;if(e.words[0]?.text.toLowerCase()==="write-output"&&e.words.length===2&&e.words[1]?.provenance==="literal")return e.words[1].text;return}function Qt(e){return e==="&&"||e==="||"}function tl(e,t,n,r,o,i){let s={success:fi([...n,...e]),failure:fi([...r,...t])},a=Qt(i)?s:void 0;return{states:Qt(o)||a?fi([...s.success,...s.failure]):s.success,conditionalStates:a}}function Qm(e,t,n=e.flattenNested){return{currentSegmentIndex:t,flattenNested:n,allocateSegment:e.allocateSegment,getNextSegmentIndex:e.getNextSegmentIndex,recordGlobal:e.recordGlobal,recordSegment:(r,o=t)=>e.recordSegment(r,o)}}function T_(e,t,n,r,o){let i=e.nested.map((s)=>({program:s,depth:t}));if(e.dialect==="powershell"){let s=O_(e);if(s){if(t+1>=K.recursionDepth.cap)return nl(s,n,o);let a=Ne(s,"powershell");if(a.status==="limited")return nl(s,n,o);if(a.status!=="complete")return Km(i,n,r,o);n.budget.charge("derivedTokens",pi(a)),i.push({program:a,depth:t+1})}}return Km(i,n,r,o)}function k_(e){let t=e.words[0];return t?.provenance==="variable"&&e.words.at(-1)?.text==="="?t.text.toLowerCase():void 0}function Km(e,t,n,r){let o=[...r];for(let i of e){let s=[];for(let a of o){let l=mi(i.program,i.depth,t,n,[en(a)]);if(l.result)return l;s.push(...l.states)}o=fi(s)}return{result:null,states:o}}function O_(e){let t=e.words[0]?.provenance==="literal"&&!e.words[0].quoted&&e.words[0].raw===e.words[0].text&&(e.words[0].text==="&"||e.words[0].text==="."),n=t?1:0,r=e.words[n];if(r?.provenance!=="literal"||!t&&(r.quoted||r.raw!==r.text)||!["iex","invoke-expression"].includes(r.text.toLowerCase()))return;let o=e.words.slice(n+1),i=o[0]&&!o[0].quoted&&o[0].raw===o[0].text&&["-c","-command"].includes(o[0].text.toLowerCase())?1:0,s=o[i];return o.length===i+1&&s?.quoted&&s.provenance==="literal"?s.text:void 0}function pi(e){return e.nodes.reduce((t,n)=>t+(n.kind==="command"?n.words.length+n.nested.reduce((r,o)=>r+pi(o),0):n.kind==="group"||n.kind==="function"?pi(n.body):0),0)}function nl(e,t,n){return t.trace?.recordSegment({type:"error",message:Ve}),{result:{reason:Ve,segment:e,ruleId:"analysis.recursion-limit",intent:"stop_and_explain"},states:[...n]}}function M_(e,t,n,r,o,i,s){let a={...n,environment:{...n.environment,env:o.shellGitContextState.env,paths:G_(n.environment.paths,o.createdDirectories,n.budget)}},l=H_(e,!a.strict);if(l&&a.strict)return a.trace?.recordSegment({type:"error",message:l}),{reason:l,segment:e.source,ruleId:"analysis.unsupported-heredoc",intent:"stop_and_explain"};ep(e,o,"before-consumer",a.environment.paths,a.budget);let c=gn(e.dialect,e.words),u=c.map(_),f=e.displayText,d=Tf(c,o.shellGitContextState),m=Df(d,o.shellGitContextState);if(e.dialect==="powershell"){let h=w(nf(e,i,iw(a,o.effectiveCwd)),a.policy);if(a.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!h,reason:h?.reason}),h)return ow(f,h)}if(u.length===1&&u[0]?.includes(" ")&&!er(e.dialect,e.words)){let h=w(Te(u[0]),a.policy),y=h!==null&&!a.strict&&rd(e,a.rootProgram);if(h&&!y)return a.trace?.recordSegment({type:"dangerous-text",token:u[0],matched:!0,reason:h.reason}),{reason:h.reason,segment:f,ruleId:h.id,intent:h.intent};a.trace?.recordSegment({type:"dangerous-text",token:u[0],matched:!1});let C=qm(e,l,o,m,s,a);if(C)return C;return Na(d,o.shellGitContextState),null}let g=On(e.words,t,{...a,commandView:e,cwd:r,effectiveCwd:o.effectiveCwd,envAssignments:m,shellAssignments:o.shellGitContextState.shellAssignments,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:o.functionDefinitions,hasPipelineInput:i,literalShellInput:s,analyzeNested:(h,y)=>{let C=y&&Object.hasOwn(y,"effectiveCwd")?y.effectiveCwd:o.effectiveCwd,b=il(h,t+1,{...a,effectiveCwd:C,envAssignments:y?.envAssignments??m,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:y?.functionDefinitions,worktreeMode:y?.worktreeMode??a.worktreeMode,trace:a.trace?Qm(a.trace,a.trace.currentSegmentIndex,!0):void 0});return b?{reason:b.reason,ruleId:b.ruleId,intent:b.intent}:null}});if(g)return{...g,segment:f};let p=qm(e,l,o,m,s,a);if(p)return p;return Na(d,o.shellGitContextState),null}function qm(e,t,n,r,o,i){let s=j_(e,t,n,r??new Map,i);if(s)return s;return ep(e,n,"after-consumer",i.environment.paths,i.budget),n.literalHeredocFiles.clear(),L_(e,t,n,i.environment.paths,i.budget),F_(e,n,i.environment.paths,i.budget),q_(e,n,o,i.environment,i.trace),null}var D_=new Set([">>","<>"]);function ep(e,t,n,r,o){for(let s of e.redirections){if(!(n==="before-consumer"?N_(s):D_.has(s.operator)))continue;Ym(s.target,t,r,o)}if(n!=="before-consumer"||!se(e.words[0],"tee"))return;let i=np(e.words.slice(1));if(!i)return;for(let s of i.operands)Ym(s,t,r,o)}function N_(e){if(e.operator===">"||e.operator===">|")return!0;return e.operator===">&"&&e.fd===void 0&&e.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(e.target.text)}function Ym(e,t,n,r){let o=e?.provenance==="literal"?cr(e.text,t.effectiveCwd,n,r):void 0;if(!o)return;t.literalHeredocFiles.delete(o)}function L_(e,t,n,r,o){if(t)return;let i=e.redirections.find((s)=>s.operator==="<<"||s.operator==="<<-")?.heredoc;if(!i)return;for(let s of W_(e,n.shellGitContextState.shellAssignments)){let a=cr(s,n.effectiveCwd,r,o);if(!a||!sd(a))continue;if(!n.literalHeredocFiles.has(a)&&n.literalHeredocFiles.size>=K.trackedHeredocFiles.cap)throw new W("trackedHeredocFiles");n.literalHeredocFiles.set(a,i.body)}}function W_(e,t){let n=rl($_(e.redirections)?.target,t),r=n===void 0?[]:[n];if(se(e.words[0],"cat"))return B_(e.words)?r:[];if(!se(e.words[0],"tee"))return[];let o=np(e.words.slice(1),t);if(!o||o.append||o.hasUnsupportedOptions)return[];let i=o.operands.map((s)=>rl(s,t));if(!i.every((s)=>s!==void 0))return[];return[...i,...r]}function rl(e,t){if(U_(e))return e.text;return(e&&Ye(e,t))??void 0}function G_(e,t,n){if(t.size===0)return e;let r=(o)=>{let i=D(o,e,n);return[...t].some((s)=>s===i||s.startsWith(`${i}${__}`))};return{realpath:(o)=>e.realpath(o)??(r(o)?D(o,e,n):null),entryKind:(o)=>{let i=e.entryKind(o);return i==="missing"&&r(o)?"present":i},isDirectory:(o)=>e.isDirectory(o)||r(o)}}function F_(e,t,n,r){if(t.shellGitContextState.bodyDepth>0||!se(e.words[0],"mkdir"))return;let o=e.words.slice(1).map((c)=>rl(c,t.shellGitContextState.shellAssignments));if(!o.every((c)=>c!==void 0))return;let i=o.findIndex((c)=>c==="--"||c==="-"||!c.startsWith("-")),s=o.slice(0,i);if(i===-1||!s.every((c)=>/^(?:-[pv]+|--parents|--verbose)$/.test(c)))return;let a=s.some((c)=>c==="--parents"||/^-v*p/.test(c)),l=t.effectiveCwd;for(let c of o.slice(o[i]==="--"?i+1:i)){if(c.split(/[\\/]/).includes("..")||!v_(c)&&!l)continue;let u=D(R_(l??"",c),n,r);if(a?z_(u,n):n.isDirectory(S_(u))&&tp(u,n))t.createdDirectories.add(u)}}function z_(e,t){let n=x_(e).root,r=e.slice(n.length).split(/[\\/]+/).filter(Boolean),o=(s)=>E_(n,...r.slice(0,s+1)),i=r.findIndex((s,a)=>!t.isDirectory(o(a)));return i===-1||tp(o(i),t)}function tp(e,t){try{return t.entryKind(e)==="missing"}catch{return!1}}function B_(e){let t=!1;for(let n of e.slice(1)){if(t||n.provenance!=="literal")return!1;if(n.text==="--"){t=!0;continue}if(!/^-u+$/.test(n.text))return!1}return!0}function $_(e){let t=e.findLast((n)=>(n.fd??([">",">|",">>",">&"].includes(n.operator)?1:0))===1);return t?.operator===">"||t?.operator===">|"?t:void 0}function np(e,t=new Map){let n=[],r=!0,o=!1,i=!1;for(let s of e){if(s.provenance!=="literal"&&Ye(s,t)===null)return;if(r&&se(s,"--")){r=!1;continue}if(r&&!s.quoted&&s.raw===s.text&&/^-[^-]/.test(s.text)){o||=s.text.slice(1).includes("a"),i||=Array.from(s.text.slice(1)).some((a)=>a!=="a"&&a!=="i");continue}if(r&&!s.quoted&&s.raw===s.text&&s.text.startsWith("--")){o||=s.text==="--append",i||=s.text!=="--append"&&s.text!=="--ignore-interrupts";continue}n.push(s)}return{operands:n,append:o,hasUnsupportedOptions:i}}function U_(e){if(!e||e.provenance!=="literal"||e.text.length===0)return!1;if(e.quoted||e.raw!==e.text)return!0;return!e.raw.startsWith("~")&&!/[{}]/.test(e.raw)}function se(e,t){return e?.text===t&&e.raw===t&&e.provenance==="literal"&&!e.quoted}function sl(e){return e.quotedDelimiter||!/[$`\\]/.test(e.body)}function H_(e,t){let n=e.redirections.filter((l)=>l.operator==="<<"||l.operator==="<<-");if(n.length===0)return;if(n.length!==1)return Jt;let r=n[0];if(!r?.heredoc)return Jt;let o=/\$\(|`/.test(r.heredoc.body);if(!sl(r.heredoc)&&(!t||o))return w_;if(r.fd!==void 0&&r.fd!==0)return Jt;if(e.redirections.some((l)=>l!==r&&["<","<<","<<-","<<<","<&","<>"].includes(l.operator)))return Jt;let i=e.redirections.some((l)=>l!==r&&Zm(l.target));if(se(e.words[0],"cat"))return i?Jt:void 0;if(se(e.words[0],"tee"))return i||e.words.slice(1).some(Zm)?Jt:void 0;let s=e.words[0],a=e.words[1];if(se(s,"git")&&(se(a,"apply")||se(a,"commit")))return;if(se(s,"gh")&&(se(a,"pr")||se(a,"issue"))&&se(e.words[2],"create"))return;return Jt}function Zm(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}function j_(e,t,n,r,o){if(!t)return null;let i=e.redirections.filter((c)=>c.operator==="<<"||c.operator==="<<-"),s=i.flatMap((c)=>c.heredoc?[c.heredoc.body]:[]);if(K_(e,i,n,r,o))return null;let a=V_(e,i,o);if(a!==void 0)return a?{reason:a.reason,segment:e.displayText,ruleId:a.id,intent:a.intent}:null;let l=ol(s.length===i.length?s.join(`
45
+ `):e.source,o);return l?{...l,segment:e.displayText}:null}function V_(e,t,n){let r=t.length===1?t[0]:void 0;if(!r?.heredoc||!sl(r.heredoc)||r.fd!==void 0&&r.fd!==0)return;let o=se(e.words[0],"uv")&&se(e.words[1],"run")?e.words.slice(2):e.words,i=o[0];if(i?.provenance!=="literal"||!De(i.text))return;let s=o.findIndex((f)=>se(f,"-"));if(!o.slice(1,s===-1?void 0:s).every((f)=>f.provenance==="literal"&&f.text.startsWith("-")))return;let l=r.heredoc.body,c=ee(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(n.trace?.recordSegment({type:"interpreter",interpreter:i.text,codeArg:l,paranoidBlocked:c}),c){let f=w(v("interpreter.one-liner-paranoid",ur),n.policy);if(f)return f}if(!dr(l,void 0,!n.strict))return null;let u=w(v("interpreter.dangerous-command",bn),n.policy);if(!u)return null;return n.trace?.recordSegment({type:"dangerous-text",token:l,matched:!0,reason:u.reason}),u}function K_(e,t,n,r,o){let i=t.length===1?t[0]:void 0;if(!i?.heredoc||!sl(i.heredoc)||i.fd!==void 0&&i.fd!==0)return!1;let s=$t(e.words,o.environment,n.effectiveCwd,r),a=s.words.map(_),l=O(a[0]??"");if((s.envSplitValues?.length??0)>0||!Y.has(l)&&!Y.has(P(l)))return!1;return at(a)}function q_(e,t,n,r,o){let i=Hm(e,t.effectiveCwd,r,t.shellGitContextState.shellAssignments,n);if(i===null)o?.recordSegment({type:"cwd-change",segment:e.words.map(_).join(" "),effectiveCwdNowUnknown:!0});if(i!==void 0)t.effectiveCwd=i}var Y_=new Set(["fi","done","esac"]);function Z_(e){return e?.kind==="command"&&e.words.length===1&&e.words[0]?.raw==="!"}function X_(e,t,n,r){let o=e.words[0]?.text??"",i=t.shellGitContextState.bodyDepth,s=n.shellGitContextState.bodyDepth,a=n.compoundBodies;if(s>i)return n.compoundBodies=[...a.slice(0,i),{entryCwd:t.effectiveCwd,branchCwds:a[i]?.branchCwds??[],hasElse:!1}],[n];let l=i>0?a[i-1]:void 0;if(l&&(o==="else"||o==="elif"))return n.compoundBodies=[...a.slice(0,i-1),{entryCwd:l.entryCwd,branchCwds:[...l.branchCwds,n.effectiveCwd],hasElse:o==="else"}],n.effectiveCwd=l.entryCwd,[n];let c=l!==void 0&&Y_.has(o);if(c)n.compoundBodies=a.slice(0,s);return[...new Set([n.effectiveCwd,...c?l.branchCwds:[],...c&&!l.hasElse?[l.entryCwd]:[],...r?[t.effectiveCwd]:[]])].map((f)=>{if(f===n.effectiveCwd)return n;let d=en(n);return d.effectiveCwd=f,d})}function J_(e,t){return e.length===t.length&&e.every((n,r)=>{let o=t[r];return o!==void 0&&n.entryCwd===o.entryCwd&&n.hasElse===o.hasElse&&n.branchCwds.length===o.branchCwds.length&&n.branchCwds.every((i,s)=>i===o.branchCwds[s])})}var Q_=/^[A-Za-z_][A-Za-z0-9_]*$/,ew=8;function tw(e,t){let n=e.words[1]?.text;if(e.dialect!=="posix"||e.words[0]?.text!=="for"||n===void 0||!Q_.test(n))return[t];let r=e.words.slice(3);if(!(e.words[2]?.text==="in"&&r.length>=1&&r.length<=ew&&r.every((i)=>i.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(i.text))))return t.shellGitContextState.shellAssignments.delete(n),[t];return r.map((i)=>{let s=en(t);return s.shellGitContextState.shellAssignments.set(n,i.text),s})}function en(e){return{effectiveCwd:e.effectiveCwd,shellGitContextState:Mf(e.shellGitContextState),literalHeredocFiles:new Map(e.literalHeredocFiles),functionDefinitions:new Map(e.functionDefinitions),createdDirectories:new Set(e.createdDirectories),compoundBodies:e.compoundBodies}}function fi(e){let t=[];for(let n of e){if(!t.some((r)=>nw(r,n)))t.push(n);if(t.length>K.controlFlowStates.cap)throw new W("controlFlowStates")}return t}function nw(e,t){return e.effectiveCwd===t.effectiveCwd&&J_(e.compoundBodies,t.compoundBodies)&&Dn(e.shellGitContextState.env,t.shellGitContextState.env)&&Dn(e.literalHeredocFiles,t.literalHeredocFiles)&&Dn(e.functionDefinitions,t.functionDefinitions)&&Dn(e.shellGitContextState.effectiveEnvAssignments,t.shellGitContextState.effectiveEnvAssignments)&&Dn(e.shellGitContextState.shellAssignments,t.shellGitContextState.shellAssignments)&&e.shellGitContextState.bodyDepth===t.shellGitContextState.bodyDepth&&Xm(e.shellGitContextState.bodyAssignments,t.shellGitContextState.bodyAssignments)&&Xm(e.createdDirectories,t.createdDirectories)}function Xm(e,t){return e.size===t.size&&[...e].every((n)=>t.has(n))}function Dn(e,t){if(e===t)return!0;if(!e||!t||e.size!==t.size)return!1;return[...e].every(([n,r])=>t.get(n)===r&&t.has(n))}function rw(e,t){let n=tr(e);return n===void 0?void 0:t.get(n)}function ow(e,t){if(!t)return null;return{reason:t.reason,segment:e,ruleId:t.id,intent:t.intent}}function iw(e,t=e.effectiveCwd){let n=t===null;return{environment:e.environment,cwd:n?void 0:t??e.cwd,originalCwd:n?void 0:e.cwd,strict:e.strict,paranoid:e.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,protectedGitMetadata:e.protectedGitMetadata,policy:e.policy,budget:e.budget}}function ol(e,t){let n=w(Te(e),t.policy),r=t.trace?.currentSegmentIndex??t.trace?.allocateSegment(),o={type:"dangerous-text",token:e,matched:!!n,reason:n?.reason};if(t.trace?.recordSegment(o,r),!n&&/^(?:cd|pushd)\s/.test(e))t.trace?.recordSegment({type:"cwd-change",segment:e,effectiveCwdNowUnknown:!0},r);return n?{reason:n.reason,segment:e,ruleId:n.id,intent:n.intent}:null}function Jm(e,t){let n={type:"strict-unparseable",rawCommand:e,reason:Rn},r=t.trace?.currentSegmentIndex;if(r===void 0)t.trace?.recordGlobal(n);if(r!==void 0)t.trace?.recordSegment(n)}var sw=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function rp(e,t,n,r){let o=il(e,0,{...t,...vu(t),budget:t.budget??Ae(),factStore:r},n);if(!o)return null;return{kind:"deny",reason:o.reason,intent:o.intent??"manual_only",ruleId:o.ruleId,evidence:{command:e,segment:o.segment}}}function op(e,t,n){try{return{decision:e()}}catch(r){let o=aw(r,t,n);if(!o)throw r;return o}}function aw(e,t,n){if(!(e instanceof W)||!sw.has(e.kind))return null;let r=K[e.kind];if(n?.currentSegmentIndex!==void 0)n.recordSegment({type:"error",message:r.reason});if(n?.currentSegmentIndex===void 0)n?.recordGlobal({type:"error",message:r.reason});return{decision:{kind:"deny",reason:r.reason,ruleId:"analysis.derived-command-limit",intent:"stop_and_explain",evidence:{command:t,segment:t}},errorCode:r.errorCode}}var lw=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),ll=new Set(["cc-safety-net","ccsn"]),cw=new Set(["bunx","npx","pnpx"]),uw=new Set(["pnpm","yarn"]),dw=new Set(["npm","pnpm","yarn"]),fw=new Set(["bun","node"]);function hi(e,t,n={}){if(ll.has(e))return 0;if(cw.has(e)){if(n.broad)return al(t);let o=t[0]==="-y"||t[0]==="--yes"?1:0;return gi(t[o])?o+1:null}let r=n.broad?t.findIndex((o)=>!o.startsWith("-")):0;if(r!==-1&&dw.has(e)&&n.broad&&t[r]==="exec"){let o=al(t.slice(r+1));return o===null?null:r+1+o}if(uw.has(e)){if(e==="yarn"&&!n.broad)return null;if(!n.broad)return t[0]==="dlx"&&gi(t[1])?2:null;if(r===-1||t[r]!=="dlx")return null;let o=al(t.slice(r+1));return o===null?null:r+1+o}if(fw.has(e)){let o=n.broad&&r!==-1?r:0;if(ip(t[o]))return o+1;if(e==="bun"&&t[o]==="run"&&ip(t[o+1]))return o+2}return null}function al(e){let t=e.findIndex((r)=>gi(r));if(t===-1)return null;let n=t;while(n<e.length){let r=e[n]??"";if(!r.startsWith("-")&&!gi(r))break;n++}return n}function gi(e){if(!e)return!1;let t=e.indexOf("@");if(t===-1)return ll.has(e);if(t===0)return!1;let n=e.slice(t+1);if(n===""||n.includes("/")||n.includes(":"))return!1;return ll.has(e.slice(0,t))}function ip(e){let t=e?.replaceAll("\\","/");return[...lw].some((n)=>t===n||t?.endsWith(`/${n}`))}var sp="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 ap(e,t,n){let r=ge(e,"input-candidate");if(!r)return null;let o=Sn(r.shell,e.invocation.context.executionCwd,t,n,{findSegmentTarget:(i)=>mw(i,t),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return o?{target:o}:null}function mw(e,t){let n=St([...e],t),r=n.slice(1),o=hi(P(n[0]??"").toLowerCase(),r,{broad:!0});if(o===null)return null;let i=r.slice(o).filter((s)=>s!=="-g"&&s!=="--global");return i[0]==="policy"&&i[1]==="apply"?n.join(" "):null}import{dirname as yi}from"node:path";var dp="This path contains the protected policy config and you must not modify or delete it.",pw=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function fp(e,t,n){let r=Sw(e.invocation.context,t,n);if(e.invocation.route.kind==="patch")return lp(e.paths,!1,e.invocation.context.executionCwd,r,t,n);let o=ge(e,"input-candidate");if(e.invocation.route.kind==="command")return o?cp(o.shell,e.invocation.context.executionCwd,r,t,n):null;if(e.invocation.route.kind==="unknown"&&o){let i=cp(o.shell,e.invocation.context.executionCwd,r,t,n);if(i)return i}return lp(e.paths,e.invocation.route.kind==="grep"||e.invocation.route.kind==="glob"||Fr(e.invocation.toolName),e.invocation.context.executionCwd,r,t,n)}function lp(e,t,n,r,o,i){if(t)return null;let s=e.find((a)=>kr(a,n,r,o,i));return s?{target:s}:null}function cp(e,t,n,r,o){let i=Sn(e,t,r,o,{findSegmentTarget:(s,a)=>gw(s,a,n,r,o)?.target??null,isRedirectionTarget:(s,a)=>kr(s,a.cwd,n,r,o),findMalformedTarget:(s)=>Cw(s,t,n,r,o)?.target??null});return i?{target:i}:null}function gw(e,t,n,r,o){if(hr(e))return null;let i=vt([...e],r),s=P(i[0]??"").toLowerCase(),a=i.slice(1);if(s==="rm"&&hw(a)){let l=yw(a).find((c)=>up(pe(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(s==="find"){if(Yo(i,1)||Pa(i,r)){let c=(Rr(q(i))??q(["."])).find((u)=>{let f=pe(u.text,t.variables);return kr(f,t.cwd,n,r,o)||up(f,t.cwd,n,r,o)})?.text;if(c)return{target:c}}}if(s==="mv"){let l=Lo(a).sources.find((c)=>vw(pe(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(bw(i,s))return null;for(let l of[...e,...i])for(let c of mp(l))if(kr(pe(c,t.variables),t.cwd,n,r,o))return{target:c};return null}function hw(e){return e.some((t)=>t==="--recursive"||t.startsWith("-")&&!t.startsWith("--")&&/[rR]/.test(t.slice(1)))}function yw(e){let t=e.indexOf("--");if(t!==-1)return[...e.slice(0,t).filter((n)=>!n.startsWith("-")),...e.slice(t+1)];return e.filter((n)=>!n.startsWith("-"))}function bw(e,t){if(!pw.has(t))return!1;if(t!=="sed")return!0;return!e.slice(1).some((n)=>n.startsWith("-i")||n==="--in-place"||n.startsWith("--in-place="))}function Cw(e,t,n,r,o){for(let i of e.split(/\s+/))for(let s of mp(i))if(kr(s,t,n,r,o))return{target:s};return null}function mp(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.indexOf("=");return n===-1||n===t.length-1?[t]:[t,t.slice(n+1)]}function Sw(e,t,n){let r=(a)=>Or(le(a,e.executionCwd,t,n)),o=r(Wt(t)),i=[r(cn(e.executionCwd)),r(cn(e.configCwd))],s=new Set(i.map((a)=>yi(a)));for(let a=yi(o);;a=yi(a))if(s.add(a),yi(a)===a)break;return{files:new Set([o,...i]),directoriesAndAncestors:s}}function kr(e,t,n,r,o){let i=Ll(e,t,r,o,(s)=>Or(s)===Kr);return i!==null&&n.files.has(Or(i))}function up(e,t,n,r,o){return n.directoriesAndAncestors.has(Or(le(e,t,r,o)))}function vw(e,t,n,r,o){let i=Or(le(e,t,r,o));return n.files.has(i)||n.directoriesAndAncestors.has(i)}function Or(e){return process.platform==="win32"?e.toLowerCase():e}import{isAbsolute as bi,posix as _p,resolve as vi,win32 as Ew}from"node:path";import{fileURLToPath as xw}from"node:url";var wp="Access to a sensitive path is not allowed.",Pp=new Set(["echo","printf"]),Rw=new Set(["find"]),_w=new Set(["!","do","elif","else","if","then","until","while"]),ww=new Set(["-exec","-execdir"]),Pw=new Set([";","+"]),Aw=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),Iw=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Ap=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),Tw=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),kw=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"]),Ip=new Set(["-c","-e","-r","-E","--eval","--exec"]),Ow=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"])]]),Mw=new Set(["grep","rg"]),Dw=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),Nw=new Set(["commit","merge","notes","stash","tag"]),Lw=new Set(["-m","--message"]),Ww=new Set(["--grep"]),pp=new Set(["jq","gojq","jaq"]),gp="f",hp="file",Gw="files",Fw=new Set(["e","f"]),zw=new Set(["regexp","file"]),Bw=new Set(["e","f","A","B","C","m"]),$w=new Set(["regexp","file","after-context","before-context","context","max-count"]),cl="__CC_SAFETY_NET_PIPE_INPUT__",dl=/[\w./~@+-]*[./~][\w./~@+-]*/g,Uw=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,Hw=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,jw=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,yp=/\b(?:subprocess\s*\.\s*(?:run|call|Popen|check_output|check_call|getoutput|getstatusoutput)|(?:[\w$]+\s*\.\s*)*(?:exec(?:File)?(?:Sync)?|spawn(?:File)?(?:Sync)?|system|popen|shell_exec|passthru|child_process|eval))\s*\(/g,bp=/\b(?:system|exec|spawn|popen)\s*$/,Vw=/\b(?:eval|exec)\s*\(/g,Kw=/\b(?:eval|exec)\s*$/,qw=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 Cp(e,t,n,r,o,i){for(let s of e){let a=s.target;if(HP(a,s.cwd,t?.denyPaths??[],n,r,o))return{target:a,ruleId:"secret.deny-path"};if(i&&!i.has(a))continue;let l=$P(a,s.cwd,t,r,o);if(l){let c=i!==void 0&&!l.startsWith("secret.home.")&&!l.startsWith("secret.cli.");if(c&&r.paths.isDirectory(Gp(a,s.cwd,r,o)))continue;if(c&&s.isRedirectionWriteTarget===!0&&!a.includes("$")&&!Si(a,s.cwd,r,o))continue;if(c&&/\s/.test(a)&&!a.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(a)&&!Si(a,s.cwd,r,o))continue;if(!l.startsWith("secret.cli.")&&jP(a,s.cwd,t?.allowPaths??[],n,r,o))continue;return{target:a,ruleId:l}}}return null}function Tp(e,t,n,r,o={}){let i=Sp(e,n,r),s=Cp(i,t,e.invocation.context.configCwd,n,r);if(s===null||s.ruleId==="secret.deny-path"||o.strict!==!1)return s;let a=Cp(i,t,e.invocation.context.configCwd,n,r,new Set(Sp(e,n,r,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}).map((l)=>l.target)));return a?.ruleId!=="secret.deny-path"&&Yw(e,n)?null:a}function Yw(e,t){let n=ge(e,"input-candidate")??ge(e,"declared-command");if(!n)return!1;if(n.program.nodes.some((s)=>s.kind==="command"&&s.nested.length>0))return!1;let r=[];for(let s of No(n.shell)){if(s.kind==="operator"&&s.boundary)return!1;if(s.kind==="redirection")return!1;if(s.kind==="operator")continue;r.push(ot(s.text,t))}let o=dt(r);if(o.length===0)return!1;let i=je(o[0]??"").toLowerCase();if(e.invocation.route.kind==="unknown")return n.program.dialect==="powershell"&&(i==="ls"||i==="stat");return ml(i,o.slice(1))}function ml(e,t){if(e==="ls"||e==="stat")return!0;if(e==="test")return t.length===2&&(t[0]==="-e"||t[0]==="-f");if(e==="[")return t.length===3&&(t[0]==="-e"||t[0]==="-f")&&t[2]==="]";if(e==="git")return t[0]==="check-ignore";if(e!=="find")return!1;return!t.some((n)=>Aw.has(n))}function Sp(e,t,n,r={}){let o=e.invocation.context.executionCwd,i=e.invocation.route.kind;if(i!=="command"&&i!=="unknown")return e.paths.map((a)=>({target:a,cwd:o}));let s=ge(e,"input-candidate");return[...s?Ln(s.shell,e.store,r,t,o,n,Zw(s)):[],...i==="unknown"?e.paths.map((a)=>({target:a,cwd:o})):[]]}function Zw(e){return e.program.dialect==="powershell"}function Ln(e,t,n,r,o,i,s=!1){if(e.status==="structural-limit")throw new Fe;if(e.status==="unclosed-quote")return[];if(e.status==="invalid")throw Error("Unable to parse command for secret protection");let a=[...e.assignmentFallbacks.map((c)=>({target:c,cwd:o})),...RP(ot(e.source,r),t,n,r,o,i)],l=(c)=>ot(aP(c,s),r);return Do(e,o,r,i,{word:l,segment:(c,u,f,d,m)=>{if(c.length===0)return null;if(a.push(...Ei(c,t,n,r,u.cwd,i,m)),f!==null)a.push(...Jw(f,c,t,n,r,u.cwd,i));return null},redirection:(c,u)=>{if(c.body!==void 0&&c.consumer!==void 0)a.push(...kp(c.consumer,[c.body],t,n,r,u.cwd,i,(f)=>Qw(c.consumer??[],f,t,n,r,u.cwd,i)));if(c.targetOrder==="legacy-segment")return ca;return a.push({target:l(c.target),cwd:u.cwd,...c.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}}),a}function pl(e,t,n,r,o,i){let s=t.getShellSyntax(e);if(s.status==="structural-limit")throw new Fe;return s.status==="complete"?Ln(s,t,n,r,o,i):null}function Ei(e,t,n,r,o,i,s){let a=(p)=>({target:p,cwd:o});if(s?.size){let p=e.filter((h,y)=>!s.has(y));if(pp.has(je(dt(p)[0]??"").toLowerCase()))return[...e.filter((h,y)=>s.has(y)).map(a),...Ei(p,t,n,r,o,i)]}let l=sP(e).map(a),c=dt(e);if(c.length===0)return l;let u=c[0]??"",f=je(u).toLowerCase(),d=c.slice(1),m=c.findIndex((p)=>!_w.has(p));if(n.skipMetadataOnlySegments===!0&&m!==-1&&ml(je(c[m]??"").toLowerCase(),c.slice(m+1)))return l;let g=Xw(u,f,d);if(g)return[...l,...g.map(a)];if(Pp.has(f))return n.displayOperandsAreCapturedOutput===!0?[...l,...Op(e).map(a)]:l;if(f==="eval")return[...l,...pl(d.join(" "),t,n,r,o,i)??d.map(a)];if(f==="export")return[...l,...d.flatMap((p)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(p)?[p.slice(p.indexOf("=")+1)]:Ze(f,p)).map(a)];if(f==="git")return[...l,...cP(d).map(a)];if(f==="gh")return[...l,...fl(f,d,Dw).map(a)];if(pp.has(f))return[...l,...lP(d).map(a)];if(Mw.has(f))return[...l,...OP(d).map(a)];if(Rw.has(f))return[...l,...dP(d,t,n,r,o,i).map(a)];if(Ie.has(f))return[...l,...d.flatMap((p)=>Ze("awk",p)).map(a),...d.flatMap((p)=>mP(p,t,n,r,o,i)),...d.flatMap(pP).map(a)];if(f==="curl")return[...l,...d.filter((p,h)=>Dp(p)===null&&Mp(d[h-1])===null).flatMap((p)=>Ze(f,p)).map(a),...uP(d).map(a)];if(yr(f)){let p=gr.has(f)?xe([f,...d]):null;if(p!==null&&p.command!==null&&p.commandIndex!==null){let h=t.getShellSyntax(p.command);if(h.status==="structural-limit")throw new Fe;if(h.status==="complete")return[...l,...Ln(h,t,n,r,o,i),...d.slice(p.commandIndex).filter((y)=>!y.startsWith("-")).map(a)]}return[...l,...fP(f,d,t,n,r,o,i)]}return[...l,...d.flatMap((p)=>Ze(f,p)).map(a)]}function Xw(e,t,n){let r=hi(t,n);if(r===null||n[r]!=="explain")return null;let o=[e,...n.slice(0,r)],i=n.slice(r+1);for(let s=0;s<i.length;s++){let a=i[s];if(a==="--json"||a==="--help"||a==="-h")continue;if(a==="--cwd"){let l=i[s+1];if(l&&!l.startsWith("--"))o.push(l);s++;continue}return o}return o}function Jw(e,t,n,r,o,i,s){if(rP(t,n,r,o,i,s)){let a=dt(e),l=ml(je(a[0]??"").toLowerCase(),a.slice(1))?a.slice(1).filter((c)=>!c.startsWith("-")):[];return[...Op(e),...l].map((c)=>({target:c,cwd:i}))}return kp(t,eP(e),n,r,o,i,s,()=>[])}function Qw(e,t,n,r,o,i,s){let a=dt(e);if(!yr(je(a[0]??"").toLowerCase()))return[];return pl(t,n,r,o,i,s)??[{target:t,cwd:i}]}function kp(e,t,n,r,o,i,s,a){let l=oP(e);if(l===null)return t.flatMap(a);return t.flatMap((c)=>gr.has(l)?Ln(n.getShellSyntax(c),n,r,o,i,s):Ci(l,c,n,r,o,i,s))}function Op(e){let t=dt(e);if(t.length===0)return[];let n=je(t[0]??"").toLowerCase();if(!Pp.has(n))return[];let r=t[t[1]==="--"?2:1];if(n==="printf"&&r!==void 0&&!r.startsWith("-")&&!r.replaceAll("%%","").includes("%"))return[gl(r.replaceAll("%%","%"))];return t.slice(1)}function eP(e){let t=dt(e);if(t.length===0)return[];let n=je(t[0]??"").toLowerCase(),r=t.slice(1);if(n==="echo"){let o=r.findIndex((i)=>!/^-[neE]+$/.test(i));return[(o===-1?[]:r.slice(o)).join(" ")]}if(n==="printf")return tP(r);return[]}function tP(e){let t=e[0];if(t===void 0)return[];let n=(t.match(/%%|%[bqs]/g)??[]).filter((o)=>o!=="%%").length;if(n===0||e.length===1)return[gl(t)];let r=e.slice(1);return Array.from({length:Math.ceil(r.length/n)},(o,i)=>nP(t,r.slice(i*n,(i+1)*n)))}function nP(e,t){let n=0;return gl(e.replace(/%%|%[bqs]/g,(r)=>{if(r==="%%")return"%";let o=t[n]??"";return n++,o}))}function gl(e){return e.replace(/\\n/g,`
46
+ `).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function rP(e,t,n,r,o,i){let s=dt(e);if(s.length===0||je(s[0]??"").toLowerCase()!=="xargs")return!1;let a=Xt(s),l=s.slice(a.childStart);if(l.length===0)return!1;if(a.replacementToken==="")return!1;let c=a.replacementToken,u=c===null?[...l,cl]:l.map((f)=>f.split(c).join(cl));return Ei(u,t,n,r,o,i).some((f)=>f.target.includes(cl))}function oP(e){let t=dt(e);if(t.length===0)return null;let n=je(t[0]??"").toLowerCase();if(!yr(n))return null;return iP(n,t.slice(1))?n:null}function iP(e,t){let n=hl(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(Ip.has(o)||Np(e,o)||/^--(?:eval|exec)=/.test(o))return!1;if(o==="-")return!0;if(o.startsWith("-")){if(n==="python"&&o==="-m")return!1;if(qw.get(n)?.has(o))r++;continue}return!1}return!0}function hl(e){return/^python\d/.test(e)?"python":e}function sP(e){let t=[];for(let n of e){if(Wp(n))continue;let r=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(n);if(r===null)break;if(r[1]!==void 0&&r[1]!=="")t.push(r[1])}return t}var vp=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function aP(e,t){if(!t||!vp.test(e))return e;return`~${e.replace(vp,"").replace(/\\/g,"/")}`}function Ze(e,t){if(t==="--")return[];let n=[],r=t.indexOf("=");if(r>0&&r<t.length-1&&!t.slice(0,r).includes("?"))n.push(t.slice(r+1));if(t.startsWith("-"))return n;if(e==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(t))return n;if(e==="zip"&&/\.zip$/i.test(t))return n;return n.push(t),n}function lP(e){let t=-1,n=!1;for(let r=0;r<e.length;r++){let o=e[r]??"";if(!n&&o==="--"){n=!0;continue}if(n||!/^-(?:[A-Za-z]|-)/.test(o)){if(t===-1)t=r;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(o)){r+=2;continue}if(o==="--indent"||o==="-L"){r++;continue}if(o.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(o)||/^--(?: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(o))continue;return e.flatMap((i)=>Ze("jq",i))}return e.flatMap((r,o)=>o===t?[]:Ze("jq",r))}function cP(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n]??"";if(r==="--"||!r.startsWith("-"))return[...t,...Nw.has(r)?fl("git",e.slice(n).map((i)=>/^-[aeinopqsv]+m$/.test(i)?"-m":i),Lw):fl("git",e.slice(n),Ww)];if(t.push(...Ze("git",r)),!Ee.has(r))continue;let o=e[n+1];if(o===void 0)break;t.push(...r==="-c"&&o.includes("=")?[o.slice(o.indexOf("=")+1)]:Ze("git",o)),n++}return t}function fl(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o]??"";if(i==="--")return[...r,...t.slice(o).flatMap((s)=>Ze(e,s))];if(n.has(i)){o++;continue}if(i.includes("=")&&n.has(i.slice(0,i.indexOf("="))))continue;r.push(...Ze(e,i))}return r}function uP(e){return e.flatMap((t,n)=>{let r=Dp(t);if(r!==null)return Ep(r.flag,r.value);let o=Mp(e[n-1]);return o===null?[]:Ep(o,t)})}function Ep(e,t){if(e==="-F"||e==="--form"){let n=t.indexOf("="),r=n===-1?t:t.slice(n+1);if(!r.startsWith("@")&&!r.startsWith("<"))return[];return ul(r.slice(1).split(";")[0]??"")}if(e==="--data-urlencode"){let n=t.indexOf("@"),r=t.indexOf("=");if(n===-1||r!==-1&&r<n)return[];return ul(t.slice(n+1))}return t.startsWith("@")?ul(t.slice(1)):[]}function Mp(e){if(e===void 0)return null;if(Ap.has(e))return e;return/^-[A-Za-z]+[dF]$/.test(e)?`-${e.slice(-1)}`:null}function Dp(e){let t=e.slice(0,2);if(e.length>2&&(t==="-d"||t==="-F"))return{flag:t,value:e.slice(2)};let n=e.indexOf("=");if(n===-1)return null;let r=e.slice(0,n);return Ap.has(r)?{flag:r,value:e.slice(n+1)}:null}function ul(e){return e===""||e==="-"?[]:[e]}function dP(e,t,n,r,o,i){let s=e.findIndex((l)=>l.startsWith("-")||l==="("||l==="!"||l===";"),a=[...e.slice(0,s===-1?e.length:s),...e.flatMap((l,c)=>l==="-files0-from"&&e[c+1]!==void 0?[e[c+1]??""]:[])];for(let l=0;l<e.length;l++){if(!ww.has(e[l]??""))continue;let c=e.slice(l+1),u=c.findIndex((m)=>Pw.has(m)),f=u===-1?c:c.slice(0,u),d=Ei(f,t,n,r,o,i).map((m)=>m.target);if(a.push(...d.filter((m)=>m!=="{}")),!d.includes("{}"))continue;a.push(...e.slice(0,l).flatMap((m,g,p)=>{if(!Iw.has(m))return[];let h=p[g+1];return h===void 0?[]:[h,h.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return a}function fP(e,t,n,r,o,i,s){let a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c===void 0)break;if(Ip.has(c)||Np(e,c)){let f=t[l+1];if(f!==void 0)a.push(...Ci(e,f,n,r,o,i,s)),l++;continue}let u=/^--(?:eval|exec)=(.*)$/.exec(c);if(u!==null&&u[1]!==void 0){a.push(...Ci(e,u[1],n,r,o,i,s));continue}if(!c.startsWith("-"))a.push({target:c,cwd:i})}return a}function Np(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<=2)return!1;return Ow.get(t[t.length-1]??"")?.has(hl(e))??!1}function mP(e,t,n,r,o,i){if(!e.includes("system"))return[];return xa(e)?.commands.flatMap((s)=>Ln(t.getShellSyntax(s),t,n,r,o,i))??[]}function pP(e){return Array.from(e.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((t)=>t[1]).filter((t)=>t!==void 0&&t!=="")}function gP(e){let t=Array.from(e.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((n)=>n[2]).filter((n)=>n!==void 0&&n!=="");return[...t,...t.flatMap(yl),...e.match(dl)??[]]}function Ci(e,t,n,r,o,i,s){let a=(p)=>({target:p,cwd:i}),l=yP(t,hP(e));if(l.kind==="unmaskable")return gP(t).map(a);let c=l.masked.match(yp)!==null||l.literals.some((p)=>bp.test(l.masked.slice(0,p.start))),u=l.masked.match(Vw)!==null||l.literals.some((p)=>Kw.test(l.masked.slice(0,p.start))),f=r.inlineLiteralsPresumedData===!0&&!gr.has(e),d=f&&!(vP(l.masked)||c||u)?[]:l.literals,m=f?Array.from(l.masked.matchAll(yp),(p)=>{let h=p.index+p[0].length;return{start:h,end:na(l.masked,h)}}):[],g=!f||m.some((p)=>ra(l.masked,p.start))?l.literals:l.literals.filter((p)=>bp.test(l.masked.slice(0,p.start))||m.some((h)=>p.start>=h.start&&p.start<h.end));return[...d.map((p)=>p.text).filter((p)=>p!=="").map(a),...d.flatMap((p)=>yl(p.text)).map(a),...f?[]:l.literals.flatMap((p)=>p.text.match(dl)??[]).map(a),...c?g.flatMap((p)=>pl(p.text,n,r,o,i,s)??[a(p.text)]):[],...u?l.literals.flatMap((p)=>Ci(e,p.text.replace(/\\(.)/g,(h,y)=>y==="n"?`
47
+ `:y),n,r,o,i,s)):[],...(l.masked.match(dl)??[]).map(a)]}function hP(e){let t=hl(e);if(t==="python")return"python";if(t==="osascript")return"opaque";return t==="node"||t==="bun"||t==="deno"?"javascript":"simple"}function yP(e,t){if(t==="opaque")return{kind:"unmaskable"};let n=e.split(""),r=[];for(let o=0;o<e.length;o++){let i=e[o]??"";if(t==="simple"&&(i==="`"||i==="%"||i==="<")){if(Hw.test(e.slice(o)))return{kind:"unmaskable"}}let s=i==="'"||i==='"'||t==="javascript"&&i==="`"?i:null;if(s===null)continue;if(s==="`"&&SP(e,o))return{kind:"unmaskable"};let a=t==="python"?bP(e,o):"",l=t==="python"&&e.startsWith(s.repeat(3),o)?s.repeat(3):s,c=o+l.length,u=CP(e,c,l);if(u===null)return{kind:"unmaskable"};let f=e.slice(c,u);if(/[fF]/.test(a)&&f.includes("{"))return{kind:"unmaskable"};if(t==="simple"&&s==='"'&&jw.test(f))return{kind:"unmaskable"};r.push({start:c,text:f});for(let d=o;d<u+l.length;d++)n[d]=" ";o=u+l.length-1}return{kind:"masked",masked:n.join(""),literals:r}}function bP(e,t){return Uw.exec(e.slice(Math.max(0,t-3),t))?.[1]??""}function CP(e,t,n){let r=n==="`",o=r||n.length===3;for(let i=t;i<e.length;i++){let s=e[i];if(s==="\\"){i++;continue}if(r&&s==="$"&&e[i+1]==="{")return null;if(!o&&(s===`
48
+ `||s==="\r"))return null;if(e.startsWith(n,i))return i}return null}function SP(e,t){for(let n=t-1;n>=0;n--){let r=e[n];if(!r||/\s/.test(r))continue;return/[\w$\])]/.test(r)}return!1}function vP(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(Tw.has(n.toLowerCase()))return!0;let o=n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((i)=>i.toLowerCase());if(!o.some((i)=>kw.has(i)))continue;if(o.length>1)return!0;if(EP(e,r)===".")return!0;if(xP(e,r+n.length)==="(")return!0}return!1}function EP(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function xP(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function RP(e,t,n,r,o,i){return IP(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...Ln(a,t,{...n,displayOperandsAreCapturedOutput:!0},r,o,i),..._P(a,r)?wP(a,r).map((l)=>({target:l,cwd:o})):[]]})}function _P(e,t){let n=No(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||je(ot(o.text,t)).toLowerCase()!=="base64")continue;for(let i=r+1;i<n.length;i++){let s=n[i];if(s?.kind==="operator")break;if(s?.kind!=="word")continue;let a=ot(s.text,t);if(a==="--decode"||!a.startsWith("--")&&a.startsWith("-")&&/[dD]/.test(a))return!0}}return!1}function wP(e,t){return No(e).flatMap((n)=>n.kind==="word"?[ot(n.text,t)]:n.kind==="redirection"&&n.target?[ot(n.target,t)]:[]).flatMap(yl)}function yl(e){let t=AP(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||PP(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function PP(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function AP(e){if(e.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(e))return null;if(/=/.test(e.replace(/=+$/g,"")))return null;let t=e.replace(/=+$/g,"");if(t.length%4===1)return null;return`${t.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-t.length%4)%4)}`}function IP(e){let t=[],n={inSingle:!1,inDouble:!1,escaped:!1};for(let r=0;r<e.length;r++){let o=e[r];if(!o)break;if(Yn(o,n))continue;if(Lp(e,r,n)){let i=TP(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=kP(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function TP(e,t){let n={inSingle:!1,inDouble:!1,escaped:!1},r=1;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i)break;if(Yn(i,n))continue;if(Lp(e,o,n)){r++,o++;continue}if(!n.inSingle&&!n.inDouble&&i===")"){if(r--,r===0)return{body:e.slice(t+1,o),endIndex:o}}}return null}function kP(e,t){let n=!1;for(let r=t+1;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="`")return{body:e.slice(t+1,r),endIndex:r}}return null}function Lp(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function OP(e){let t=[],n=[],r=!1,o=!1,i=!1;for(let l=0;l<e.length;l++){let c=e[l];if(c===void 0)break;if(!i&&c==="--"){i=!0;continue}if(i){n.push(c);continue}let u=/^--([^=]+)(?:=(.*))?$/.exec(c);if(u!==null){let f=u[1]??"",d=u[2];if(f===Gw)o=!0;if(zw.has(f))r=!0;if(d!==void 0){if(f===hp)t.push(d);continue}if($w.has(f)){let m=e[l+1];if(f===hp&&m!==void 0)t.push(m);l++}continue}if(c.startsWith("-")&&c.length>1){let f=c.slice(1),d="",m="";for(let p=0;p<f.length;p++){let h=f[p]??"";if(Fw.has(h))r=!0;if(Bw.has(h)){d=h,m=f.slice(p+1);break}}if(d==="")continue;if(m.length>0){if(d===gp)t.push(m);continue}let g=e[l+1];if(d===gp&&g!==void 0)t.push(g);l++;continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function dt(e){let t=e.findIndex((n)=>!Wp(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:e.slice(t)}function Wp(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var MP=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),DP=".env.",NP=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),LP=[".env.example.",".env.sample."];function WP(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function GP(e){return e.length>0&&!/\s/.test(e)}function Si(e,t,n,r){let o=Gp(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function Gp(e,t,n,r){try{return Dr(e,t,n,r)}catch(o){if(o instanceof W)throw o;return""}}var FP=/[?&][^?&=/]+=/,zP=new Set(["node_modules","__pycache__"]),BP=[["vendor","bundle"],["vendor","cache"]];function $P(e,t,n,r,o){if(WP(e))return null;let i=be(e,t,r,o);if(!i)return null;let s=B(i.split("/").pop()??""),a=B(i),l=()=>GP(s)||Si(e,t,r,o);if(NP.has(s)||LP.some((d)=>s.startsWith(d)))return null;let c=B(qP(e,t,r,o));for(let d of gs){let m=`~/${d.suffixParts.join("/")}`;if((Rp(a,m)||Rp(c,m))&&ut(d.id,n))return d.id}let u=UP(i,t,n,r,o);if(u)return u;if(MP.has(s))return null;for(let d of ps)if(s===d.basename&&ut(d.id,n))return d.id;if(s.startsWith(DP)&&ut(eo.id,n)&&l())return eo.id;for(let d of hs)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){let m=s.slice(d.prefix.length)[0];if((m==="-"||m==="_")&&ut(d.id,n)&&l())return d.id}for(let d of ys)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){if(s.slice(d.prefix.length)===d.suffix&&ut(d.id,n))return d.id}if(VP(a))return null;if(!s.includes(".")&&Zn.pattern.test(s)&&ut(Zn.id,n))return Zn.id;if(FP.test(e)&&!Si(e,t,r,o))return null;let f=KP(s,n);if(f)return f;return null}function UP(e,t,n,r,o){return to.find((i)=>{if(!ut(i.id,n))return!1;switch(i.id){case"secret.cli.claude-code":return N(e,H(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),[".credentials.json"]);case"secret.cli.claude-code.config":{let s=B(e).split("/");return N(e,H(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),["settings.json","settings.local.json"])||Mr(e,"~/.claude.json",t,r,o)||s.at(-1)==="settings.local.json"&&s.at(-2)===".claude"||s.at(-1)===".mcp.json"}case"secret.cli.antigravity":return N(e,be("~/.gemini/config",t,r,o),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let s=H(r.env.get("CODEX_HOME"),"~/.codex",t,r,o);return N(e,s,["auth.json",".credentials.json"])||Nn(e,s,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let s=H(r.env.get("CODEX_HOME"),"~/.codex",t,r,o),a=B(e).split("/").at(-1)??"";return N(e,s,["config.toml"])||a.endsWith(".config.toml")&&N(e,s,[a])}case"secret.cli.gemini":return N(e,te(H(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let s=B(e).split("/"),a=r.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),l=r.env.get("ProgramData")?[te(H(r.env.get("ProgramData"),"",t,r,o),"gemini-cli")]:[];return N(e,te(H(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["settings.json","google_accounts.json"])||s.at(-1)==="settings.json"&&s.at(-2)===".gemini"||(a?.trim()?Mr(e,a,t,r,o):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...l].some((c)=>N(e,be(c,t,r,o),["settings.json"]))}case"secret.cli.copilot-cli":{let s=H(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o);return N(e,s,["config.json"])||Nn(e,s,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return N(e,H(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o),["mcp-config.json"]);case"secret.cli.kimi-code":{let s=H(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),a=H(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o);return N(e,s,["server.token"])||Nn(e,s,["credentials"])||Nn(e,a,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let s=["config.toml","mcp.json"],a=B(e).split("/");return a.at(-1)==="mcp.json"&&a.at(-2)===".kimi-code"||N(e,H(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),s)||N(e,H(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o),[...s,"config.json","config.json.bak"])}case"secret.cli.opencode":{let s=te(H(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"opencode"),a=B(e).split("/").at(-1)??"",l=r.env.get("OPENCODE_DB")?.trim(),c=l&&l!==":memory:"?[l,`${l}-wal`,`${l}-shm`]:[];return N(e,s,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(a)&&N(e,s,[a])||c.some((u)=>Mr(e,u,t,r,o))}case"secret.cli.opencode.config":{let s=te(H(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"opencode"),a=r.env.get("ProgramData")?[te(H(r.env.get("ProgramData"),"",t,r,o),"opencode")]:[],l=["opencode.json","opencode.jsonc"],c=r.env.get("OPENCODE_CONFIG");return l.includes(B(e).split("/").at(-1)??"")||N(e,s,["config.json"])||(c?.trim()?Mr(e,c,t,r,o):!1)||["/Library/Application Support/opencode","/etc/opencode",...a].some((u)=>N(e,be(u,t,r,o),l))}case"secret.cli.pi":return N(e,H(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["auth.json"]);case"secret.cli.pi.config":return N(e,H(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["models.json"]);case"secret.cli.amp":{let s=be("~",t,r,o);return[te(H(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"amp"),te(s,".local","share","amp")].some((l)=>N(e,l,["secrets.json"]))||Nn(e,te(s,".amp"),["oauth"])}case"secret.cli.amp.config":{let s=["settings.json","settings.jsonc"],a=[te(H(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"amp"),te(be("~",t,r,o),".config","amp")],l=B(e).split("/"),c=r.env.get("AMP_SETTINGS_FILE");return a.some((u)=>N(e,u,s))||l.at(-2)===".amp"&&s.includes(l.at(-1)??"")||(c?.trim()?Mr(e,c,t,r,o):!1)}case"secret.cli.cursor":{let s=te(H(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"cursor"),a=te(H(r.env.get("CURSOR_DATA_DIR"),"~/.cursor",t,r,o),"projects");return N(e,be("~/.cursor",t,r,o),["auth.json"])||N(e,s,["auth.json"])||B(e).split("/").at(-1)==="mcp-auth.json"&&tn(B(e),B(a))}case"secret.cli.cursor.config":{let s=B(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".cursor"}case"secret.cli.grok-build":return N(e,H(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let s=B(e).split("/");return s.at(-1)==="config.toml"&&s.at(-2)===".grok"||N(e,H(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["config.toml","managed_config.toml","requirements.toml"])||N(e,be("/etc/grok",t,r,o),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return N(e,be("~/.factory",t,r,o),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let s=B(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".factory"||N(e,be("~/.factory",t,r,o),["settings.json","hooks.json"])}case"secret.cli.devin":return[H(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),be("~/.local/share",t,r,o)].some((s)=>N(e,te(s,"devin"),["credentials.toml"])||Nn(e,te(s,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[H(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),be("~/.config",t,r,o)].some((s)=>N(e,te(s,"devin"),["config.json"]));default:return!1}})?.id??null}var xp=new WeakMap;function H(e,t,n,r,o){let i=xp.get(o)??new Map;xp.set(o,i);let s=`${n}\x00${e??""}\x00${t}`,a=i.get(s);if(a!==void 0)return a;let l=be(e?.trim()?e:t,n,r,o);return i.set(s,l),l}function N(e,t,n){return n.some((r)=>Fp(e,te(t,r)))}function Nn(e,t,n){return n.some((r)=>tn(B(e),B(te(t,r))))}function Mr(e,t,n,r,o){return Fp(e,be(t,n,r,o))}function Fp(e,t){return B(e)===B(t)}function te(e,...t){return He([e,...t].filter(Boolean).join("/"))}function HP(e,t,n,r,o,i){if(n.length===0)return!1;let s=B(Dr(e,t,o,i));return n.some((a)=>tn(s,B(Dr(a,r,o,i))))}function jP(e,t,n,r,o,i){if(n.length===0)return!1;let s=B(Dr(e,t,o,i));if(!s)return!1;let a=o.env.get("HOME")??o.home,l=a?He(D(ve(a),o.paths,i)):"",c=B(l),u=o.env.get("CC_SAFETY_NET_HOME"),f=B(u?He(D(vi(ve(u)),o.paths,i)):l&&He(D(`${l}/.cc-safety-net`,o.paths,i)));if(f&&tn(s,f))return!1;return n.some((d)=>{let m=Es(d);if(m&&_p.basename(s)!==B(m.name))return!1;let g=B(Dr(m?.root??d,r,o,i));if(!g)return!1;if(c&&(c===g||c.startsWith(g.endsWith("/")?g:`${g}/`)))return!1;return tn(s,g)&&!(m&&s===g)})}function VP(e){let t=e.split("/");return t.some((n)=>zP.has(n))||BP.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function KP(e,t){let n=e.lastIndexOf("."),r=n>0&&n<e.length-1?e.slice(n+1):"";if(r==="")return null;for(let o of bs)if(r===o.extension&&ut(o.id,t))return o.id;for(let o of Cs)if(o.pattern.test(r)&&ut(o.id,t))return o.id;return null}function B(e){return e.toLowerCase()}function ut(e,t){return!t?.disabledRules?.includes(e)}function be(e,t,n,r){let{home:o,normalized:i}=bl(e,n,r);if(!i)return"";if(!o)return i;let s=Cl(i,o),a=bi(s)?s:He(vi(t,s)),l=He(D(a,n.paths,r));if(!tn(l,o)){if(bi(s))return l;return l===a?i:l}let c=l.slice(o.length);return c?`~${c}`:"~"}function Rp(e,t){return e===t||e.startsWith(`${t}/`)}function qP(e,t,n,r){let{home:o,normalized:i}=bl(e,n,r);if(!i||!o)return"";let s=Cl(i,o),a=_p.normalize(bi(s)?s:He(vi(t,s))),l=He(ve(n.env.get("HOME")??n.home)),c=(d)=>process.platform==="win32"?d.toLowerCase():d,u=[o,l].find((d)=>d!==""&&tn(c(a),c(d)));if(u===void 0)return"";let f=a.slice(u.length);return f?`~${f}`:"~"}function Dr(e,t,n,r){let{home:o,normalized:i}=bl(e,n,r);if(!i)return"";let s=o?Cl(i,o):i;return He(D(bi(s)?s:vi(t,s),n.paths,r))}function bl(e,t,n){let r=t.env.get("HOME")??t.home,o=r?He(D(ve(r),t.paths,n)):"",i=He(ve(YP(ot(e,t))));return{home:o,normalized:i}}function YP(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return xw(e)}catch{return e}}function Cl(e,t){if(e==="~")return t;if(e.startsWith("~/"))return te(t,e.slice(2));return e}function ZP(e){if(process.platform==="win32")return!0;return Ew.parse(e).root.length>1}function He(e){let t=e.trim(),n=(t.includes("\\")&&ZP(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function tn(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function je(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class nn extends Error{stage;evaluation;name="GuardEvaluationError";constructor(e,t,n){super(`CC Safety Net ${e} dependency failed`,{cause:n});this.stage=e;this.evaluation=t}}var XP={findPolicyMutation:fp,findGitMetadataMutation:Wd,resolveGitMetadata:QP,loadPolicySnapshot:Su,findSensitiveTarget:Tp,analyzeCommand:rp,getModes:Hi},JP=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function zp(e,t){let n={...XP,...t.dependencies},r=nA(e),o=Nr(e)?e.command:r,i=At("policy-protection",o,()=>Md(e)),s=ge(i,"input-candidate"),a=ge(i,"declared-command");if(Nr(e)&&e.command?.trim()&&a?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Ve,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:e.command,segment:e.command}}};if(s?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:rf,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let l=Ae(),c=At("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd],t.environment)),u=At("policy-protection",o,()=>n.findPolicyMutation(i,t.environment,l));if(u){let b=o??u.target;return{stage:"policy-protection",decision:{kind:"deny",reason:dp,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:b,segment:u.target}}}}let f=At("policy-protection",o,()=>ap(i,t.environment,l));if(f){let b=o??f.target;return{stage:"policy-protection",decision:{kind:"deny",reason:sp,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:b,segment:f.target}}}}let d=At("policy-protection",o,()=>n.findGitMetadataMutation(i,c,t.environment,l));if(d){let b=o??d.target;return{stage:"policy-protection",decision:{kind:"deny",reason:ze,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:b,segment:d.target}}}}let m=At("config-load",o,()=>n.loadPolicySnapshot(t.environment,{...t.policyOptions,cwd:e.context.configCwd})),g=m.policy,p=n.getModes(g,t.environment.env),h={level:p.effectiveLevel,...eA(m)},y=g.secretProtection.enabled===!1?null:At("secret-protection",o,()=>n.findSensitiveTarget(i,g.secretProtection,t.environment,l,{strict:Nr(e)||s?.program.dialect==="powershell"?p.strict:void 0}));if(y){let b=o??y.target;return{stage:"secret-protection",...h,decision:{kind:"deny",reason:wp,intent:"hard_stop",ruleId:y.ruleId,evidence:{command:b,segment:y.target}}}}if(!Nr(e))return{stage:"non-command",...h,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...Sl("command-validation",o),...h};let C=At("command-analysis",o,()=>op(()=>n.analyzeCommand(e.command,{cwd:e.context.executionCwd,shell:e.route.shell,policySnapshot:m,environment:t.environment,protectedGitMetadata:c,effectiveCapabilities:p.capabilities,strict:p.strict,paranoidRm:p.paranoidRm,paranoidInterpreters:p.paranoidInterpreters,worktreeMode:p.worktreeMode,budget:l,...t.trace?{trace:t.trace}:{}},tA(i),i.store),e.command,t.trace));if(C.decision){let b=!p.strict&&(C.decision.ruleId==="raw-text.dangerous-command"||C.decision.reason===vr&&!JP.test(C.decision.evidence?.segment??"")&&Te(e.command)===null);return{stage:"command-analysis",...h,..."errorCode"in C?{errorCode:C.errorCode}:{},decision:b?{...C.decision,unverifiedByStandardMode:!0}:C.decision}}return{stage:"command-analysis",...h,decision:{kind:"allow"}}}function QP(e,t){let n=[...new Set(e.filter((r)=>typeof r==="string"&&r!==""))].flatMap((r)=>t.gitMetadata(r)??[]);if(n.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(n.flatMap((r)=>r.entries))]),markerFiles:Object.freeze([...new Set(n.flatMap((r)=>r.markerFiles))]),directories:Object.freeze([...new Set(n.flatMap((r)=>r.directories))]),hooksDirectories:Object.freeze([...new Set(n.flatMap((r)=>r.hooksDirectories))])})}function eA(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function tA(e){return ge(e,"declared-command")?.program}function nA(e){try{return Un(e.input)}catch(t){let n=Nr(e)?e.command:void 0;throw new nn("policy-protection",Sl("policy-protection",t instanceof Qe?void 0:n,t),t)}}function At(e,t,n){try{return n()}catch(r){throw new nn(e,Sl(e,r instanceof Qe?void 0:t,r),r)}}function Sl(e,t,n){let r=n instanceof W||n instanceof Fe;return{stage:e,decision:{kind:"deny",reason:r?wi:Fn,ruleId:r?"analysis.limit":"analysis.failed-closed",intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function Nr(e){return e.route.kind==="command"}import{appendFileSync as gA,mkdirSync as hA}from"node:fs";import{isAbsolute as yA,join as xl}from"node:path";import{lstatSync as $p,readdirSync as rA,readFileSync as oA,rmdirSync as iA,statSync as Up,unlinkSync as sA,utimesSync as aA,writeFileSync as lA}from"node:fs";import{join as Lr}from"node:path";function Bp(e,t={}){return co(Wt(e,t),e.home).policy.audit.retention_days}var El=86400000,cA=".last-prune",uA=/^\d{4}-\d{2}$/,dA=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Hp=(e)=>Math.floor(e/El);function Vp(e,t,n=()=>new Date){try{let r=n().getTime();if(!Up(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=Lr(t,cA),i=Up(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&Hp(i)===Hp(r))return;let s=r-Bp(e)*El,a=new Date(r).toISOString().slice(0,7);for(let l of vl(t)){if(l.isDirectory()){fA(Lr(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))mA(Lr(t,l.name),s)}lA(o,"",{mode:384}),aA(o,r/1000,r/1000)}catch{}}function fA(e,t,n){for(let r of vl(e)){if(!r.isDirectory()||!uA.test(r.name))continue;let o=Lr(e,r.name);for(let i of vl(o)){if(!i.isFile())continue;let s=dA.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+El;if(!Number.isFinite(a)||a>=t)continue;Kp(Lr(o,i.name))}if(r.name!==n)jp(o)}jp(e)}function mA(e,t){try{let n=$p(e);if(n.mtimeMs>=t)return;let r=oA(e,"utf-8").split(`
49
+ `).filter((o)=>o.trim()).map(pA);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if($p(e).mtimeMs!==n.mtimeMs)return;Kp(e)}catch{}}function pA(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function vl(e){try{return rA(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Kp(e){try{sA(e)}catch{}}function jp(e){try{iA(e)}catch{}}var bA="2.6.0",CA=1e4,SA=2000,vA=256,EA=32768;function xA(e){let t=e.trim();if(!t)return null;let n=t.replace(/[^A-Za-z0-9_.-]+/g,"_");if(n=n.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!n||n==="."||n==="..")return null;return n}function RA(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function Rl(e,t,n,r,o,i,s={}){let a=xA(t);if(!a)return;let l=wA(e);if(!l)return;try{let c=(s.now??(()=>new Date))().toISOString(),u=xi(mt(n),s.failureStage?Number.POSITIVE_INFINITY:CA),f=xi(mt(r),SA),d=s.toolName?xi(mt(s.toolName),vA):void 0,m=i===null?void 0:xi(mt(i),EA),g=xl(l,RA(m?.value??null),c.slice(0,7));hA(g,{recursive:!0,mode:448});let p=xl(g,`${c.slice(0,10)}-${a}.jsonl`),h={ts:c,id:(s.createId??ji)(),v:bA,sessionId:a,decision:s.decision??"deny",agent:s.agent,shape:s.shape,level:s.level,configFallback:s.configFallback,toolName:d?.value,command:u.value,segment:f.value,...u.truncated||f.truncated||d?.truncated||m?.truncated?{truncated:!0}:{},reason:o,ruleId:s.ruleId,intent:s.intent,failureStage:s.failureStage,errorCode:s.errorCode,cwd:m?.value??null};gA(p,`${JSON.stringify(h)}
50
+ `,{encoding:"utf-8",mode:384}),Vp(e,l,s.now)}catch{}}function xi(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function _A(e){let t=e.env.get("CC_SAFETY_NET_AUDIT_HOME");if(e.env.get("NODE_ENV")==="test"&&!t)return null;let n=t||e.home;return n&&yA(n)?n:null}function wA(e){let t=_A(e);return t?xl(t,".cc-safety-net","logs"):null}function Yp(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=qp(e);return{decision:"allow",command:a,segment:a,reason:"allowed",cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{}}}let i=t.decision.evidence,s=i?.command??(r?qp(e):"");return{decision:"deny",command:s,segment:i?.segment??s,reason:t.decision.reason,cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{},ruleId:t.decision.ruleId,intent:t.decision.intent,failureStage:o?.stage,errorCode:o?.errorCode}}function qp(e){return"command"in e?e.command??"":""}function Zp(e,t,n,r){if(!t)return;let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Rl(e,o,t.command,t.segment,t.reason,t.cwd,{decision:t.decision,agent:r.agent,shape:r.shape,level:t.level,configFallback:t.configFallback,toolName:t.toolName,ruleId:t.ruleId,intent:t.intent,failureStage:t.failureStage,errorCode:t.errorCode})}function Xp(e,t,n,r){let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Rl(e,o,t.command??"",t.segment??t.command??"",t.reason,r.cwd??null,{decision:"deny",agent:r.agent,shape:r.shape,toolName:r.toolName??t.toolName,ruleId:t.ruleId,intent:t.intent})}function Qp(e,t,n){try{let r=zp(t,{environment:e,...n.guard});return Jp(e,t,r,n),r}catch(r){if(!(r instanceof nn))throw r;throw Jp(e,t,r.evaluation,n,!(r.cause instanceof Qe),{stage:r.stage,errorCode:PA(r.cause)}),r}}function Jp(e,t,n,r,o=!0,i){Zp(e,Yp(t,n,r.guard?.auditAllowed??!1,o,i),r.audit.getSessionId,{agent:r.audit.agent,shape:r.audit.shape})}function PA(e){if(e instanceof W)return K[e.kind].errorCode;if(e instanceof Qe)return"tool-input-limit";if(e instanceof Fe)return"structural-shell-syntax-limit";return"unexpected-error"}function It(e,t={}){return{malformed:!0,denial:zn(t),cwd:e}}function _l(e,t){return{malformed:!0,denial:Pi(e,t),cwd:e.cwd}}function eg(e,t={}){return(n,r)=>{try{return AA(n,r,e,t)}catch(o){return console.error("CC Safety Net error:",o),e.block(zn())}}}function AA(e,t,n,r){let o=ac();if(n.cancelled?.(t))return n.block(zn());let i=n.extract(e,t,o.paths);if(!i)return n.allow;let s=()=>n.getSessionId(e,t);if("malformed"in i)return Xp(o,i.denial,s,{agent:n.agent,toolName:i.denial.toolName,cwd:i.cwd}),n.block(i.denial);let a=(l,c)=>{let u=Il(l,{includeEvidence:c});return u?n.block(u):n.allow};try{let l=Qp(o,i,{guard:{auditAllowed:dc(o.env),policyOptions:r.policyOptions,dependencies:r.guardDependencies},audit:{agent:n.agent,getSessionId:s}});return a(l,!0)}catch(l){if(!(l instanceof nn))throw l;if(et(Z.debug,o.env))console.error(`CC Safety Net debug: ${n.debugLabel} analysis failed: ${kl(l.cause)}`);return a(l.evaluation,n.includeEvidenceOnError(i))}}var tg="exec",IA=new Set(["auto","gateway"]);function ng(e){e.on("before_tool_call",TA(e),{matcher:[tg],priority:50})}function TA(e,t={}){return eg({agent:"openclaw",debugLabel:"openclaw before_tool_call",extract:(r,o,i)=>kA(r,o,e,i),getSessionId:(r,o)=>o.sessionId??o.sessionKey,allow:void 0,block:(r)=>MA(r),includeEvidenceOnError:()=>!0,cancelled:(r)=>r.abortSignal?.aborted===!0},t)}function kA(e,t,n,r){if(!e||typeof e!=="object")return It(null);let o=e.toolName;if(typeof o!=="string"||o.trim()==="")return It(null);if(o!==tg)return;if(e.toolKind!==void 0)return;let i=e.params;if(!i||typeof i!=="object"||Array.isArray(i))return It(null,{toolName:o});let s=i,a=s.command;if(typeof a!=="string"||a.trim()==="")return It(null,{toolName:o});if(s.host!==void 0&&!IA.has(s.host))return It(null,{command:a,toolName:o});let l=OA(n,t.agentId);if(!l)return It(null,{command:a,toolName:o});let c=Wi(".",[l],r);if(!c)return _l({directory:"session",problem:"unusable",cwd:l},{command:a,toolName:o});let u=s.workdir;if(u!==void 0&&(typeof u!=="string"||u.trim()===""))return It(c,{command:a,toolName:o});let f=typeof u==="string"?u:".",d=Wi(f,[c],r);if(!d)return _l({directory:"requested",problem:Ql(f,c,r),cwd:f},{command:a,toolName:o});return ec(o,s,{kind:"command",shell:"auto"},{configCwd:c,executionCwd:d},a)}function OA(e,t){if(typeof t!=="string"||t.trim()==="")return;try{let n=e.runtime.agent.resolveAgentWorkspaceDir(e.config,t);return typeof n==="string"&&n.trim()!==""?n:void 0}catch{return}}function MA(e){return{block:!0,blockReason:Tl(e)}}var Z1={...Al,register:ng};export{Z1 as default};