cc-safety-net 2.4.12 → 2.4.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/amp/cc-safety-net/index.ts +11 -11
- package/dist/api.js +1 -1
- package/dist/bin/hook.js +40 -40
- package/dist/chunks/{index-kwg376ge.js → index-av9c301x.js} +9 -9
- package/dist/chunks/{index-q47ejf84.js → index-fjkkpma1.js} +2 -2
- package/dist/cli.js +126 -117
- package/dist/index.js +7 -7
- package/dist/openclaw/cc-safety-net/index.js +36 -36
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +2 -2
- package/package.json +2 -2
package/dist/bin/hook.js
CHANGED
|
@@ -1,47 +1,47 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var mg=["-h","--help"];function oo(e,t){let n=Object.entries(e.booleans??{}),r=Object.entries(e.values??{}),o=Object.entries(e.lists??{}),i=Object.fromEntries(n.map(([d])=>[d,!1])),s={},a=Object.fromEntries(o.map(([d])=>[d,[]])),l=[],c=[],u=!1,m=-1;for(let[d,f]of t.entries()){if(d<=m)continue;if(f==="--"){l.push(...t.slice(d+1));break}if(mg.includes(f)){u=!0;continue}let p=n.find(([,y])=>y.includes(f));if(p){i[p[0]]=!0;continue}let g=r.find(([,y])=>y.includes(f));if(g){let y=t[d+1];if(y===void 0||y.startsWith("-")){c.push(`${f} requires a value`);continue}s[g[0]]=y,m=d+1;continue}let h=o.find(([,y])=>y.includes(f));if(h){let y=t.slice(d+1),S=y.findIndex((C)=>C.startsWith("-")),E=y.slice(0,S===-1?y.length:S);if(E.length===0){c.push(`${f} requires at least one value`);continue}a[h[0]]=[...a[h[0]]??[],...E],m=d+E.length;continue}if(f.startsWith("-")){c.push(`Unknown option for ${e.label}: ${f}`);continue}if(e.positionals==="tail"){l.push(...t.slice(d));break}l.push(f)}if(e.positionals!=="list"&&e.positionals!=="tail")c.push(...l.map((d)=>`Unexpected argument for ${e.label}: ${d}`));return{flags:i,values:s,lists:a,positionals:l,help:u,errors:c}}var Ll=require("node:path");var Ji="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",ut="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",or="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var Xi={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."},rr={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."},X=Object.freeze({realpathAttempts:{cap:16384,...Xi},processedCandidateBytes:{cap:4194304,...Xi},pathEnvironmentExpansion:{cap:64,...Xi},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,...rr},trackedHeredocFiles:{cap:64,...rr},controlFlowStates:{cap:64,...rr},wrapperPeelIterations:{cap:20,...rr},derivedCommandShape:rr});class N extends Error{kind;name="AnalysisLimit";constructor(e){super(X[e].reason);this.kind=e}}function ue(){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>X[t].cap)throw new N(t)}}}var fg=[/\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 Ct(e){return pg(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 pg(e){return fg.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 gg={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 zl(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.":gg[e.intent??"manual_only"]].filter((o)=>o!==void 0).join(`
|
|
3
3
|
|
|
4
|
-
`)}function Ji(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 xn(e={}){return{reason:or,intent:"stop_and_explain",command:e.command,segment:e.segment??e.command,toolName:e.toolName}}var fg={session:{unusable:{reason:"CC Safety Net cannot check tool calls because the session's working directory or workspace root no longer exists, is inaccessible, is not a directory, or uses an unsupported path form. Ask the user to restart the session from an existing directory.",intent:"hard_stop"},"outside-workspace":{reason:"CC Safety Net cannot check tool calls because the session's working directory is outside its workspace roots. Ask the user to restart the session from a directory inside the workspace.",intent:"hard_stop"}},requested:{unusable:{reason:"CC Safety Net could not use the requested working directory because it does not exist, is inaccessible, is not a directory, or uses an unsupported path form. Use an existing accessible working directory. If the requested directory is missing, create it from an accessible location before retrying the command.",intent:"use_alternative"},"outside-workspace":{reason:"CC Safety Net could not use the requested working directory because it is outside the session's workspace. Use a working directory inside the workspace.",intent:"use_alternative"}}};function io(e,t={}){return{...fg[e.directory][e.problem],command:t.command,toolName:t.toolName,cwd:e.cwd}}function Fl(e){return Gl({...e,redact:bt})}function zl(e){return Gl({...e,redact:bt,askUser:!0})}function Hl(e){return bt(e instanceof Error?e.message:String(e))}var Re=require("node:path");var pg=256,so=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 Me(e,t=process.platform){if(t!=="win32")return e;return e.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function St(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function ns(e,t){return Qi(e,0,t)}function Qi(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=es(e,o+2),a=gg(e,o,t);if(a===null){if(so.has(s))throw new N("pathEnvironmentExpansion");r+=e.slice(o);break}let l=e.slice(o,a+1);r+=hg(l,t,n),o=a+1;continue}let i=es(e,o+1);if(!i){r+="$",o++;continue}r+=ts(i,n)??`$${i}`,o+=i.length+1}return r}function gg(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>X.pathEnvironmentExpansion.cap)throw new N("pathEnvironmentExpansion");o++;continue}if(e[o]!=="}")continue;if(r--,r===0)return o}return null}function hg(e,t,n){let r=e.slice(2,-1),o=es(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return ts(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(so.has(o))throw new N("pathEnvironmentExpansion");return e}if(!so.has(o))return e;if(s.endsWith("="))throw new N("pathEnvironmentExpansion");let a=ts(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??"":Qi(i.slice(s.length),t+1,n);return l?Qi(i.slice(s.length),t+1,n):""}function es(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 ts(e,t){if(!so.has(e))return null;if(e==="HOME")return t.env.get("HOME")??t.home;return t.env.get(e)??null}function O(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){$l(n,i);let s=t.realpath(i);if(s!==null)return Bl(n,e,s,o);let a=Re.dirname(i);if(a===i||o.length>=pg)return Bl(n,e,i,o);o.push(Re.basename(i)),i=a}}function Bl(e,t,n,r){let o=r.length===0?n:Re.join(n,...r.reverse());return e.resolvedPaths.set(t,o),o}function yg(e,t,n){let r=n.resolvedPaths.get(e);if(r!==void 0)return r;$l(n,e);let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function $l(e,t){e.charge("realpathAttempts"),e.charge("processedCandidateBytes",Buffer.byteLength(t))}function he(e,t,n,r){let o=jl(e,t,n);if(!o)return"";return O(o,n.paths,r).replace(/\\/g,"/")}function Ul(e,t,n,r,o){let i=jl(e,t,n);if(!i)return null;if(o(Re.basename(i)))return O(i,n.paths,r).replace(/\\/g,"/");let s=yg(i,n.paths,r);return s===null?null:s.replace(/\\/g,"/")}function jl(e,t,n){let r=n.home,o=ns(e.trim(),n).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?Re.resolve(r,o.slice(2)):o,s=Me(i);return Re.normalize(Re.isAbsolute(s)?s:Re.resolve(t,s))}var Xl=require("node:util"),Cg=new Set(["applypatch","patch"]),bg=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),Sg=new Set(["grep","grepsearch","rg"]),vg=new Set(["find","findbyname","glob"]),Eg=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),xg=new Set(["command","diff","input","patch","patchtext"]),Vl=new TextEncoder,Rg=new TextDecoder,wg=/\s/,_g=64;class Se extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var ir=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Jl(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function lo(e){return Eg.has(Jl(e))}function Ql(e){let t=Jl(e);if(Cg.has(t))return"patch";if(Sg.has(t))return"grep";if(vg.has(t))return"glob";if(bg.has(t))return"path";return"unknown"}function Lt(e){if(!e||typeof e!=="object")return;oc(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)dt();return}if(t.get||t.set)dt();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function co(e,t){return ec(e,t,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function ec(e,t,n,r){let o=rc(e,n,r);if(!o)return[];let i=o.entries.flatMap(([s,a])=>{let l=ec(a,t,n,r+1);return typeof a==="string"&&t.has(tc(s))?[a]:l});return n.ancestors.delete(o.object),i}function tc(e){return e.replace(/-/g,"_").toLowerCase()}function uo(e){return nc(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Pg)}function nc(e,t,n,r){let o=rc(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>nc(a,o.array?t:xg.has(tc(s)),n,r+1));return n.ancestors.delete(o.object),i}function Ag(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>ir.maxDepth||t.nodes>ir.maxNodes)dt();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>ir.maxStringBytes||t.stringBytes>ir.maxAggregateStringBytes)dt()}function rc(e,t,n){if(Ag(e,t,n),!e||typeof e!=="object")return null;let r=oc(e);if(t.ancestors.has(e))dt();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>ir.maxKeys)dt();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)dt();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function oc(e){if(Xl.types.isProxy(e))dt();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)dt();return t}function dt(){throw new Se}function Pg(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 d=Tg(c);if(o=!0,i=d?.oldLines??null,s=d?.newLines??null,i===0&&s===0)a();continue}if(o&&i!==null&&s!==null){let d=c.startsWith(" ")||c.startsWith("-")?1:0,m=c.startsWith(" ")||c.startsWith("+")?1:0;if(i=Math.max(0,i-d),s=Math.max(0,s-m),i===0&&s===0)a();continue}if(c.startsWith("*** ")){a(),t.push(...rs(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...rs(c));continue}if(c.startsWith("--- ")){let d=n[l+1]??"";if(!d.startsWith("+++ "))continue;t.push(...is(ao(c.slice(4),!0),ao(d.slice(4),!0))),l++;continue}if(!r)t.push(...rs(c))}return t}function Tg(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 rs(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return Zl(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return Zl(n[1]);if(e.startsWith("diff --git "))return kg(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return Yl(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return Yl(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return Wg(i[1]);return[]}function kg(e){let t=Ig(e);if(t.length===2&&t[0]&&t[1])return is(t[0],t[1]);let n=Og(e);return n?is(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function Ig(e){let t=[],n=0;while(n<e.length&&t.length<2){while(en(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&&!en(e[n]))n++;t.push(e.slice(i,n));continue}let o=ic(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(en(e[n]))n++;return n===e.length?t:[]}function Og(e){let t=0;while(t<e.length&&en(e[t]))t++;let n=e.length;while(n>t&&en(e[n-1]))n--;let r=0,o=t;while(o<n){if(!en(e[o])){o++;continue}let i=o;while(o<n&&en(e[o]))o++;if(i===t||o===n)continue;if(r++,r>_g)dt();if(Mg(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function Mg(e,t,n,r,o){if(os(e,t,n,r,o))return!0;let i=Kl(e,"/",t,n),s=Kl(e,"/",r,o);if(i<=t||s<=r)return!1;if(os(e,t,i,r,s))return!1;return os(e,i+1,n,s+1,o)}function os(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 Kl(e,t,n,r){for(let o=n;o<r;o++)if(e[o]===t)return o;return-1}function en(e){return e!==void 0&&wg.test(e)}function ic(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:Rg.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...Vl.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(...Vl.encode(Dg(s[0]??""))),o+=2}return null}function Dg(e){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
5
|
-
`,r:"\r",t:"\t",v:"\v"}[e]??e}function
|
|
6
|
-
`,t:"\t",b:"\b"};function nh(e){return e.replace(/\\(.?)/gs,(t,n)=>n===""?t:th[n]??t)}function rh(e){try{return as(F.realpathSync(e))}catch{return null}}function as(e){let t=e;while(!0){let n=re.join(t,".git");if(F.existsSync(n))return n;let r=re.dirname(t);if(r===t)return null;t=r}}function oh(e,t,n,r){if(ih(t))return!0;if(n===null)return!0;let o=dc.spawnSync(n,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:ah(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&&pc(o.stdout.trim())}function ih(e){return[re.join(e.commonDir,"config"),re.join(e.gitDir,"config.worktree")].filter((t)=>F.existsSync(t)).some((t)=>lh(t))}function sh(){return Bg.find((e)=>F.existsSync(e))??null}function lr(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function ah(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!lr(t)))}function lh(e){let t;try{t=F.readFileSync(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(ch(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=pc(c)}return r}function ch(e){return e==="include"||e.startsWith("includeif ")}function pc(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function yc(e,t){if(e==="")return null;let n=ue(),r=as(he(e,e,t,n)),o=r?uh(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 uh(e,t,n,r){try{let o=he(e,t,n,r),i=gc.statSync(e),s=i.isFile()?o:null,a=i.isFile()?ss(e):null,l=(i.isDirectory()?[o]:[a?.gitDir,a?.commonDir]).flatMap((d)=>d?[Rn(he(d,t,n,r))]:[]),c=[...new Set(i.isDirectory()?[Rn(e.replace(/\\/g,"/")),...l]:l)];return{entry:Rn(o),markerFile:s?Rn(s):null,directories:c,hooksDirectories:[...new Set(c.flatMap((d)=>{let m=Rn(hc.join(d,"hooks").replace(/\\/g,"/"));return[m,Rn(he(m,t,n,r))]}))]}}catch{return null}}function Rn(e){return process.platform==="win32"?e.toLowerCase():e}var dh={realpath:(e)=>{try{return wn.realpathSync(e)}catch{return null}},entryKind:(e)=>{let t=wn.lstatSync(e,{throwIfNoEntry:!1});if(!t)return"missing";return t.isSymbolicLink()?"symlink":"present"},isDirectory:(e)=>{try{return wn.statSync(e).isDirectory()}catch{return!1}}};function bc(){return mh({env:new Map(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),home:Me(process.env.HOME||po.homedir()),tmpdir:po.tmpdir(),paths:dh})}function mh(e,t={}){let n=new Map,r=new Map,o={...e,gitMetadata:(i)=>Cc(n,i,()=>yc(i,o)),worktreeFacts:(i)=>Cc(r,i,()=>mc(i)),...t};return o}function Cc(e,t,n){let r=e.get(t);if(r!==void 0)return r;let o=n();return e.set(t,o),o}var _n=["fail_closed","paranoid_rm","paranoid_interpreters"],go={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 ae={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"}},ho=["standard","strict","paranoid"];function fh(e,t){if(!t)return e;return ho.indexOf(t)>ho.indexOf(e)?t:e}function ph(e){let t=ds(ae.level,e);if(t===void 0||t==="")return;if(ho.includes(t))return t;console.error(`CC Safety Net: ignored invalid ${ae.level.name}=${JSON.stringify(t.slice(0,40))}. Use ${ho.join(", ")}.`);return}function gh(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function Sc(e){return gh(ds(ae.auditScope,e))==="all"}function cs(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 us(e={},t){let n=e.safety?.level??"standard",r=ph(t),o=fh(n,r),i=go[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 ${ae.level.name}=${r}`),l.paranoidRm.push(`env ${ae.level.name}=${r}`),l.paranoidInterpreters.push(`env ${ae.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(tn(ae.strict,t))s.failClosed=!0,a.failClosed="environment",l.failClosed.push(`env ${ae.strict.name}`);if(tn(ae.paranoid,t))s.paranoidRm=!0,s.paranoidInterpreters=!0,a.paranoidRm="environment",a.paranoidInterpreters="environment",l.paranoidRm.push(`env ${ae.paranoid.name}`),l.paranoidInterpreters.push(`env ${ae.paranoid.name}`);if(tn(ae.paranoidRm,t))s.paranoidRm=!0,a.paranoidRm="environment",l.paranoidRm.push(`env ${ae.paranoidRm.name}`);if(tn(ae.paranoidInterpreters,t))s.paranoidInterpreters=!0,a.paranoidInterpreters="environment",l.paranoidInterpreters.push(`env ${ae.paranoidInterpreters.name}`);let c=!!e.worktreeMode||tn(ae.worktree,t);return{strict:s.failClosed,paranoidRm:s.paranoidRm,paranoidInterpreters:s.paranoidInterpreters,worktreeMode:c,effectiveLevel:cs(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 tn(e,t){let n=typeof e==="string"?ls(e,t):ds(e,t);return n==="1"||n?.toLowerCase()==="true"}function ls(e,t){return t.get(e)}function ds(e,t){let n=ls(e.name,t);if(n!==void 0)return n;if(e.legacyName)return ls(e.legacyName,t);return}function cr(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}}var fr=require("node:path");var W=require("node:fs"),j=require("node:path");function ms(){let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${e()}${e()}`}var hh=Symbol("PolicyFilesystemScope"),yh=Symbol("PolicyFilesystemTarget"),Ch=W.constants.O_NOFOLLOW??0;class Ce extends Error{name="PolicyFilesystemError";constructor(e){super(`Unable to access ${e} filesystem safely.`)}}function nn(e,t){return{[hh]:!0,root:j.resolve(e),label:t}}function vc(e,t){let n=j.normalize(t);if(t===""||j.isAbsolute(t)||n===".."||n.startsWith(`..${j.sep}`))throw new Ce(e.label);return{[yh]:!0,scope:e,relativePath:n,path:j.join(e.root,n)}}function ur(e,t){return vc(e,j.relative(e.root,j.resolve(t)))}function Ec(e,t="rules policy"){let n=j.resolve(e),r=j.parse(n).dir;return vc(nn(r,t),j.relative(r,n))}function Co(e){return Rc(e.scope.label,()=>{if(!yo(e))return null;let t=W.openSync(e.path,W.constants.O_RDONLY|Ch);return bh(t,()=>{let n=W.fstatSync(t);if(!n.isFile())throw new Ce(e.scope.label);let r=W.readFileSync(t,"utf-8"),o=W.lstatSync(e.path);if(!o.isFile()||o.isSymbolicLink()||n.dev!==o.dev||n.ino!==o.ino)throw new Ce(e.scope.label);return yo(e),r})})}function xc(e,t){if(e.path===t.path)return!0;return Rc(e.scope.label,()=>{if(!yo(e)||!yo(t))return!1;let n=(r)=>j.join(W.realpathSync(j.parse(r).dir),j.parse(r).base);return n(e.path)===n(t.path)})}function Rc(e,t,n){try{return t()}catch(r){if(n?.(),r instanceof Ce)throw r;throw new Ce(e)}}function bh(e,t){try{return t()}finally{W.closeSync(e)}}function yo(e,t="file"){let n=Sh(e.scope);if(!n)return!1;let r=e.relativePath.split(j.sep);for(let o of r.keys()){let i=j.join(e.scope.root,...r.slice(0,o+1)),s=W.lstatSync(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);vh(n,W.realpathSync(i),e.scope.label)}return!0}function Sh(e){if(!W.lstatSync(e.root,{throwIfNoEntry:!1}))return null;if(!W.statSync(e.root).isDirectory())throw new Ce(e.label);return W.realpathSync(e.root)}function vh(e,t,n){let r=j.relative(e,t);if(r===".."||r.startsWith(`..${j.sep}`)||j.isAbsolute(r))throw new Ce(n)}var L=require("node:path");var rn=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,wc="rulebook.json",_c=".cc-safety-net/rules";var Ac=/^([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,"\\$&"),xP=new RegExp(`^${xh}/(${rn.source.slice(1,-1)})/${Rh}$`);function wh(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function Pc(e){if(bo(e))try{return fs(e),null}catch(t){return t instanceof Error?t.message:String(t)}return rn.test(e)?null:`Local rulebook sources must be bare names matching ${rn}: ${e}`}function fs(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(Ac);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||!rn.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:wh(o),name:o}}function bo(e){return Ac.test(e)}var Tc="rule.json",So="policy.json",kc=".cc-safety-net",_h="rules",Ah="CC_SAFETY_NET_HOME",Ic="`cc-safety-net rule update`";function Ph(e){return L.resolve(e,_c)}function Th(e){return L.join(Ph(e),Tc)}function dr(e){return L.join(L.resolve(e),kc,So)}function ps(e,t={}){return t.userConfigDir??(t.userConfigPath?L.dirname(t.userConfigPath):L.join(kh(e),_h))}function kh(e){let t=e.env.get(Ah);return t?L.resolve(Me(t)):L.join(e.home,kc)}function Ih(e,t={}){return L.join(ps(e,t),Tc)}function An(e,t={}){return L.join(L.dirname(ps(e,t)),So)}function Oc(e,t){let n=t.userConfigPath??Ih(e,t),r=t.projectConfigPath??Th(t.cwd),o=Oh(e,t),i=Mh(r,t.cwd);return{userConfigPath:n,projectConfigPath:r,userScope:o,projectScope:i,userConfigTarget:ur(o,n),projectConfigTarget:ur(i,r)}}function Oh(e,t){let n=t.userConfigPath?L.dirname(L.dirname(L.resolve(t.userConfigPath))):L.dirname(L.resolve(t.userConfigDir??ps(e,t)));return nn(n,"user policy")}function Mh(e,t){let n=L.resolve(t),r=L.resolve(e),o=L.relative(n,r);if(o!==".."&&!o.startsWith(`..${L.sep}`)&&!L.isAbsolute(o))return nn(n,"project policy");return nn(L.dirname(L.dirname(r)),"project policy")}function Mc(e,t){return L.join(e,t,wc)}var De=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),Wt=/^[a-zA-Z][a-zA-Z0-9_-]*$/,Gt=256,Q=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Dc=new Set(["python","python3","python2","node","ruby","perl"]),vo=/^python(?:[23](?:\.\d+)*)?$/,Be=new Set(["awk","gawk","nawk","mawk"]),Eo=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 Nc="Rulebook exceeds CC Safety Net's safe validation limits.",Lc="Additional rulebook validation errors were omitted.",Ze=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Wc(e){if(gs(e.allowed_commands,Ze.maxAllowedCommands)||gs(e.rules,Ze.maxRules)||gs(e.tests,Ze.maxTests))return!1;let{maxAggregateStringCodeUnits:t,maxTotalBlockArgs:n}=Ze,r=(o,i=!1)=>{if(typeof o!=="string")return!0;if(o.length>Ze.maxStringCodeUnits||i&&o.length>Ze.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>Ze.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 gs(e,t){return Array.isArray(e)&&e.length>t}var hs=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var ys=64,Cs="Rule config exceeds CC Safety Net's safe source limit.";function M(e){return k(e).toLowerCase()}function k(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}function we(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 Dh={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},bs=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 d=t[c];if(d===void 0)break;if(e==="ksh"&&d==="o"&&c+1<t.length){if(r==="argv"){let m=t.slice(c+1);if(t[0]==="-"&&(m==="c"||m[0]==="-"&&m.endsWith("c")))s=!0}break}if(e==="ksh"&&d==="o"&&c+1===t.length&&(n?.startsWith("-")||n?.startsWith("+")))break;if(e==="zsh"&&d==="o"&&c+1<t.length)break;if(r==="startup"&&d==="i")o=t[0]==="-";if(r==="argv"&&t[0]==="-"&&d==="c")s=!0;if(r==="argv"&&d==="n")l=t[0]==="-";if(r==="argv"&&d==="s")a=t[0]==="-";if(!Dh[e]?.includes(d))continue;if(c+1===t.length)i++;break}return{interactive:o,followingValues:i,commandSelected:s,stdinMode:a,syntaxCheck:l}}function Ne(e){let t=k(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"&&bs.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 mr(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 xo(e){let t={inSingle:!1,inDouble:!1,escaped:!1};for(let n of Nh(e))mr(n,t);return t.inSingle||t.inDouble}function Nh(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===`
|
|
7
|
-
`||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);mr(s,n)}return t}var vs=new Set(["rm","find","xargs","parallel"]),Lh=new Set(["git","busybox",...vs,...Q,...Dc,...Be]),Wh=new Set(["python","node","ruby","perl"]);function Gc(e){let t=M(e);return Lh.has(t)||Xe(t)}function Xe(e){return Wh.has(Gh(e))}function Gh(e){let t=k(e).toLowerCase();return vo.test(t)?"python":t}function Es(e){try{let t=Co(Fh(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=Bh(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 Fh(e){return typeof e==="string"?Ec(e):e}var w=(e,t)=>({path:e,message:t,kind:"typed"}),de=(e,t)=>({path:e,message:t,kind:"custom"});function Fc(e){let t=new Set;return e.flatMap((n,r)=>{let o=Pn(n)?n.name:void 0;if(typeof o!=="string")return[];if(t.has(o.toLowerCase()))return[de(["rules",r,"name"],`duplicate rule name "${o}"`)];return t.add(o.toLowerCase()),[]})}var xs=`must be one of ${hs.join(", ")}`,zh=/^[^/]+\/[^/]+$/,Hh=["version","rules","overrides","transparent_wrappers"];function Bh(e){let t=$h(e);return{errors:Rs(Jh(t,Hh,(n)=>n.kind==="custom"),": "," "),sources:Xh(e,t)}}function $h(e){if(!Pn(e))return[w([],"Config must be an object")];let t=Array.isArray(e.rules)&&e.rules.length>ys;return[...e.version===1?[]:[w(["version"],"must be 1")],...Uh(e.rules,t),...Kh(e.overrides),...Yh(e.transparent_wrappers),...t?[]:Vh(e.rules),...Pn(e.overrides)?Object.keys(e.overrides).filter((n)=>!zh.test(n)).map((n)=>de(["overrides",n],"must use <rulebook-name>/<rule-name>")):[],...Zh(e.transparent_wrappers)]}function Uh(e,t){if(e===void 0)return[];if(!Array.isArray(e))return[w(["rules"],"must be an array of rulebook source strings"),...zc(e,ys)?[w(["rules"],Cs)]:[]];if(t)return[{path:["rules"],message:Cs,kind:"limit"}];return e.flatMap((n,r)=>{if(typeof n!=="string")return[w(["rules",r],"must be a rulebook source string"),...jh(n,1)?[w(["rules",r],"must be a non-empty rulebook source string")]:[]];return n===""?[w(["rules",r],"must be a non-empty rulebook source string")]:[]})}function zc(e,t){let n=Hc(e);return n!==void 0&&!(n<=t)}function jh(e,t){let n=Hc(e);return n!==void 0&&!(n>=t)}function Hc(e){if(e===null||e===void 0)return;let t=e.length;return t===void 0?void 0:Number(t)}function Vh(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[de(["rules",r],"must be a non-empty rulebook source string")];let o=Pc(n);if(o)return[de(["rules",r],o)];if(t.has(n))return[de(["rules",r],`duplicate rulebook source "${n}"`)];return t.add(n),[]})}function Kh(e){if(e===void 0)return[];if(!Pn(e))return[w(["overrides"],"must be an object if provided")];return Object.keys(e).flatMap((t)=>{let n=e[t];if(n==="off")return[];if(!Pn(n))return[w(["overrides",t],'must be "off" or an object')];return[...qh(n.reason,["overrides",t,"reason"]),...n.intent===void 0||_s(n.intent)?[]:[w(["overrides",t,"intent"],xs)]]})}function qh(e,t){if(typeof e!=="string")return[w(t,"required non-empty string"),...zc(e,Gt)?[w(t,`must be at most ${Gt} characters`)]:[]];if(e==="")return[w(t,"required non-empty string")];return e.length>Gt?[w(t,`must be at most ${Gt} characters`)]:[]}function Yh(e){if(e===void 0)return[];if(!Array.isArray(e))return[w(["transparent_wrappers"],"must be an array of command strings")];return e.flatMap((t,n)=>{if(typeof t!=="string")return[w(["transparent_wrappers",n],"must be a command string")];return Wt.test(t)?[]:[w(["transparent_wrappers",n],"must match command pattern")]})}function Zh(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||!Wt.test(n))return[];if(t.has(n))return[de(["transparent_wrappers",r],`duplicate command "${n}"`)];if(Gc(n))return[de(["transparent_wrappers",r],`reserved command "${n}" cannot be a wrapper`)];return t.add(n),[]})}function Xh(e,t){let n=Pn(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 Jh(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 Rs(e,t,n){return[...new Set(e.map((r)=>{let o=ws(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 ws(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function _s(e){return hs.includes(e)}function Pn(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function $c(e){let t=ty(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}var Qh=`required non-empty string up to ${Gt} characters`,Bc="must be a non-empty array of unique non-empty strings",ey="required non-empty array of non-empty strings";function ty(e){if(!Ft(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Wc(e))return{errors:[Nc],ruleNames:new Set};let t=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...Rs(ny(e,e.rulebook_version===2),": ",": ")];return{errors:t.length>Ze.maxValidationErrors?[...t.slice(0,Ze.maxValidationErrors),Lc]:t,ruleNames:new Set(Uc(e).map((n)=>n.toLowerCase()))}}function Uc(e){let t=Ft(e)?e.rules:void 0;return(Array.isArray(t)?t:[]).flatMap((n)=>{let r=Ft(n)?n.name:void 0;return typeof r==="string"?[r]:[]})}function ny(e,t){return[...typeof e.name==="string"&&rn.test(e.name)?[]:[w(["name"],"required string matching rule name pattern")],...typeof e.version==="string"&&e.version!==""?[]:[w(["version"],"required non-empty string")],...ry(e.allowed_commands),...oy(e.rules,t),...ly(e.tests),...cy(e),...uy(e)]}function ry(e){if(!Array.isArray(e))return[w(["allowed_commands"],"required array")];let t=new Set;return[...e.flatMap((n,r)=>typeof n==="string"&&Wt.test(n)?[]:[w(["allowed_commands",r],"must match command pattern")]),...e.flatMap((n,r)=>{if(typeof n!=="string"||!Wt.test(n))return[];if(t.has(n))return[de(["allowed_commands",r],`duplicate command "${n}"`)];return t.add(n),[]})]}function oy(e,t){if(!Array.isArray(e))return[w(["rules"],"required array")];return[...e.flatMap((n,r)=>{if(!Ft(n))return[w(["rules",r],"must be an object")];return t?sy(n,["rules",r]):iy(n,["rules",r])}),...Fc(e)]}function iy(e,t){return[...jc(e.name,t),...Vc(e.command,t),...e.subcommand===void 0||typeof e.subcommand==="string"&&Wt.test(e.subcommand)?[]:[w([...t,"subcommand"],"must match command pattern")],...Ro(e.block_args,[...t,"block_args"],"required non-empty array",!1),...Kc(e.reason,t),...qc(e.intent,t)]}function sy(e,t){return[...jc(e.name,t),...Vc(e.command,t),...Kc(e.reason,t),...qc(e.intent,t),...ay(e.match,[...t,"match"]),...e.subcommand===void 0?[]:[w([...t,"subcommand"],"not supported in rulebook_version 2")],...e.block_args===void 0?[]:[w([...t,"block_args"],"not supported in rulebook_version 2")]]}function jc(e,t){if(typeof e!=="string")return[w([...t,"name"],"required string")];return rn.test(e)?[]:[w([...t,"name"],"must match rule name pattern")]}function Vc(e,t){return typeof e==="string"&&Wt.test(e)?[]:[w([...t,"command"],"required string matching command pattern")]}function Kc(e,t){return typeof e==="string"&&e!==""&&e.length<=Gt?[]:[w([...t,"reason"],Qh)]}function qc(e,t){return e===void 0||_s(e)?[]:[w([...t,"intent"],xs)]}function ay(e,t){if(!Ft(e))return[w(t,"required object")];return[...Ro(e.command_path,[...t,"command_path"],ey,!1),...e.any_args===void 0?[]:Ro(e.any_args,[...t,"any_args"],Bc,!0),...e.exclude_args===void 0?[]:Ro(e.exclude_args,[...t,"exclude_args"],Bc,!0)]}function Ro(e,t,n,r){if(!Array.isArray(e))return[w(t,n)];let o=e.flatMap((i,s)=>{if(typeof i!=="string")return[w([...t,s],"must be a non-empty string")];return i===""?[de([...t,s],"must be a non-empty string")]:[]});if(e.some((i)=>typeof i!=="string"))return o;return[...o,...e.length===0?[de(t,n)]:[],...r&&new Set(e).size!==e.length?[de(t,"must not contain duplicate values")]:[]]}function ly(e){if(e===void 0)return[];if(!Array.isArray(e))return[w(["tests"],"must be an array if provided")];return e.flatMap((t,n)=>{if(!Ft(t))return[w(["tests",n],"must be an object")];return[...typeof t.command==="string"&&t.command.trim()!==""?[]:[w(["tests",n,"command"],"required non-empty string")],...t.expect==="blocked"||t.expect==="allowed"?[]:[w(["tests",n,"expect"],'must be "blocked" or "allowed"')],...t.rule===void 0||typeof t.rule==="string"?[]:[w(["tests",n,"rule"],"must be a string if provided")],...t.expect==="blocked"&&typeof t.rule!=="string"?[de(["tests",n,"rule"],"required string for blocked fixtures")]:[]]})}function cy(e){if(!Array.isArray(e.tests))return[];let t=new Set(Uc(e));return[...new Set(e.tests.flatMap((n)=>Ft(n)&&n.expect==="blocked"&&typeof n.rule==="string"?[n.rule]:[]))].filter((n)=>!t.has(n)).map((n)=>de(["tests"],`blocked fixture references unknown rule "${n}"`))}function uy(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=Ft(n)?n.command:void 0;if(typeof o!=="string"||t.has(o))return[];return[de(["rules",r,"command"],`"${o}" must be listed in allowed_commands`)]})}function Ft(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function eu(e,t){let n=Oc(e,t),r;try{r=xc(n.userConfigTarget,n.projectConfigTarget)}catch(f){if(f instanceof Ce)return by(n,f.message);throw f}let o=Es(n.userConfigTarget),i=r?{config:null,errors:[]}:Es(n.projectConfigTarget),s=Jc(n.userConfigPath,o.errors),a=Jc(n.projectConfigPath,i.errors),l=new Set,c=o.config?Yc(o.config,fr.dirname(n.userConfigPath),"user",n.userScope,l):Qc(),d=i.config?Yc(i.config,fr.dirname(n.projectConfigPath),"project",n.projectScope,l):Qc(),m=o.config?.overrides??{},u=i.config?.overrides??{};return{rules:[...Zc(c.rules,m),...Zc(d.rules,u)],transparent_wrappers:yy(o.config,i.config),rulebooks:[...c.rulebooks,...d.rulebooks],errors:[...s,...a,...c.errors,...d.errors],warnings:[...c.warnings,...d.warnings,...c.canValidateOverrides?Xc(m,c.knownRuleIds,n.userConfigPath):[],...c.canValidateOverrides?Cy(u,c.knownRuleIds,n.projectConfigPath):[],...d.canValidateOverrides?Xc(u,d.knownRuleIds,n.projectConfigPath):[]],userConfig:o.config??void 0,projectConfig:i.config??void 0,...n}}function Yc(e,t,n,r=nn(fr.dirname(fr.dirname(t)),n==="user"?"user policy":"project policy"),o=new Set){let i=[],s=[],a=e.rules.flatMap((c)=>{let d=my(c,t,r);if(d.errors.length>0||!d.rulebook)return i.push(...d.errors),[];let m=d.rulebook;if(o.has(m.name))return s.push(`duplicate active rulebook name "${m.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(m.name),[{rules:dy(m),rulebook:{source:n,spec:c,name:m.name,version:m.version,rules:m.rules.map((u)=>`${m.name}/${u.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 dy(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 my(e,t,n){let r=fy(e),o=Mc(t,r),i=gy(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}; ${py(e)}`]};let s=hy(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 fy(e){return bo(e)?fs(e).name:e}function py(e){return bo(e)?`run ${Ic} to vendor ${e}`:"create that file or remove that source from the rules config"}function gy(e,t){try{return{content:Co(ur(t,e))}}catch(n){if(n instanceof Ce)return{error:n.message};throw n}}function hy(e){let t;try{t=JSON.parse(e)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:$c(t)}}catch(n){return{problem:n instanceof Error?n.message:"invalid rulebook"}}}function yy(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function Zc(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 Xc(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 Cy(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 Jc(e,t){return t.map((n)=>n.startsWith("Unable to access ")?n:`${e}: ${n}`)}function by(e,t){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath}}function Qc(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}var No=require("node:fs");var tu=[{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"}],As=new Set(tu.map((e)=>e.id)),wo=tu,Sy=new Map(wo.map((e)=>[e.id,e.intent]));function v(e,t){return{id:e,reason:t,intent:Sy.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"}],_o={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},vy=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Ey=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Ts=[{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"]},...Ey.flatMap((e)=>vy.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 Ao=[{id:"secret.cli.claude-code",category:"Coding CLI credential",label:"Claude Code credentials",paths:["~/.claude/.credentials.json"]},{id:"secret.cli.claude-code.config",category:"Coding CLI config",label:"Claude Code config",paths:["~/.claude/settings.json","~/.claude/settings.local.json","~/.claude.json","<project>/.claude/settings.local.json","<project>/.mcp.json"]},{id:"secret.cli.antigravity",category:"Coding CLI config",label:"Antigravity CLI hook config",paths:["~/.gemini/config/hooks.json","~/.gemini/config/mcp_config.json"]},{id:"secret.cli.codex",category:"Coding CLI credential",label:"Codex credentials",paths:["~/.codex/auth.json","~/.codex/.credentials.json","~/.codex/secrets","~/.codex/.sandbox-secrets"]},{id:"secret.cli.codex.config",category:"Coding CLI config",label:"Codex config",paths:["~/.codex/config.toml","~/.codex/<name>.config.toml"]},{id:"secret.cli.gemini",category:"Coding CLI credential",label:"Gemini CLI credentials",paths:["~/.gemini/oauth_creds.json","~/.gemini/mcp-oauth-tokens.json","~/.gemini/a2a-oauth-tokens.json","~/.gemini/gemini-credentials.json"]},{id:"secret.cli.gemini.config",category:"Coding CLI config",label:"Gemini CLI config",paths:["~/.gemini/settings.json","~/.gemini/google_accounts.json","<project>/.gemini/settings.json","/Library/Application Support/GeminiCli/settings.json","/etc/gemini-cli/settings.json"]},{id:"secret.cli.copilot-cli",category:"Coding CLI credential",label:"GitHub Copilot CLI credentials",paths:["~/.copilot/config.json","~/.copilot/mcp-oauth-config","~/.copilot/mcp-secrets"]},{id:"secret.cli.copilot-cli.config",category:"Coding CLI config",label:"GitHub Copilot CLI config",paths:["~/.copilot/mcp-config.json"]},{id:"secret.cli.kimi-code",category:"Coding CLI credential",label:"Kimi Code credentials",paths:["~/.kimi-code/server.token","~/.kimi-code/credentials","~/.kimi/credentials","~/.kimi/mcp-oauth"]},{id:"secret.cli.kimi-code.config",category:"Coding CLI config",label:"Kimi Code config",paths:["~/.kimi-code/config.toml","~/.kimi-code/mcp.json","~/.kimi/config.toml","~/.kimi/config.json","~/.kimi/config.json.bak","~/.kimi/mcp.json","<project>/.kimi-code/mcp.json"]},{id:"secret.cli.opencode",category:"Coding CLI credential",label:"OpenCode credentials",paths:["~/.local/share/opencode/auth.json","~/.local/share/opencode/mcp-auth.json","~/.local/share/opencode/opencode.db"]},{id:"secret.cli.opencode.config",category:"Coding CLI config",label:"OpenCode config",paths:["~/.config/opencode/opencode.json","~/.config/opencode/opencode.jsonc","/Library/Application Support/opencode/opencode.json","/etc/opencode/opencode.json","<project>/opencode.json","<project>/opencode.jsonc"]},{id:"secret.cli.pi",category:"Coding CLI credential",label:"Pi credentials",paths:["~/.pi/agent/auth.json"]},{id:"secret.cli.pi.config",category:"Coding CLI config",label:"Pi config",paths:["~/.pi/agent/models.json"]},{id:"secret.cli.amp",category:"Coding CLI credential",label:"Amp Code credentials",paths:["~/.local/share/amp/secrets.json","~/.amp/oauth"]},{id:"secret.cli.amp.config",category:"Coding CLI config",label:"Amp Code config",paths:["~/.config/amp/settings.json","~/.config/amp/settings.jsonc","<project>/.amp/settings.json","<project>/.amp/settings.jsonc"]},{id:"secret.cli.cursor",category:"Coding CLI credential",label:"Cursor CLI credentials",paths:["~/.cursor/auth.json","~/.config/cursor/auth.json","~/.cursor/projects/<name>/mcp-auth.json"]},{id:"secret.cli.cursor.config",category:"Coding CLI config",label:"Cursor CLI config",paths:["~/.cursor/mcp.json","<project>/.cursor/mcp.json"]},{id:"secret.cli.grok-build",category:"Coding CLI credential",label:"Grok Build credentials",paths:["~/.grok/auth.json","~/.grok/mcp_credentials.json"]},{id:"secret.cli.grok-build.config",category:"Coding CLI config",label:"Grok Build config",paths:["~/.grok/config.toml","~/.grok/managed_config.toml","~/.grok/requirements.toml","<project>/.grok/config.toml","/etc/grok/managed_config.toml","/etc/grok/requirements.toml"]}],nu=[{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"}],xy=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],ks=nu.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})),Is=nu.flatMap((e)=>xy.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}))),pr={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)$/},Os=["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})),Ms=[{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?$/}],Ry=[...Ps,_o,...Ts,...ks,...Is,pr,...Os,...Ms,...Ao].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}})),Po=new Set(Ao.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),Ds=new Set(Ry.map((e)=>e.id));var Le=require("node:path"),To=process.platform==="win32",ru=/[*?]/;function Ns(e){let t=e.trim(),n=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(To?t.replaceAll("\\","/"):t);if(!n)return null;let r=n[1]??"",o=n[2]??"";if(ru.test(r)||o==="."||o==="..")return null;return{root:r||"/",name:o}}function gr(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function Ls(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=gr(e.trim(),t);if(!Le.isAbsolute(n))return"must be an absolute path or start with ~/";return hr(n,t)}function Ws(e,t){let n=ou(e,t);if(n===null)return"must be a non-empty path string";if(!Le.isAbsolute(n))return null;if(hr(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 wy="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 ou(e,t){if(typeof e!=="string"||e.trim()==="")return null;let n=e.trim(),r=To?n.replaceAll("\\","/"):n;return gr(r.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function Gs(e,t){let n=ou(e,t);if(n===null)return"must be a non-empty path string";let r=Ns(n)?.root??n;if(ru.test(r))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Le.isAbsolute(r))return null;if(hr(r,t)!==null)return wy;return Ay(r,t)?_y:null}function Ay(e,t){let n=ko(e),r=ko(Le.join(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${Le.sep}`)}function hr(e,t){let n=ko(e),r=ko(t);if(n===r)return"cannot be the home directory";let o=n.endsWith(Le.sep)?n:`${n}${Le.sep}`;if(r.startsWith(o))return"cannot contain the home directory";return null}function ko(e){let t=Le.normalize(e);if(To)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(To?3:1)&&t.endsWith(Le.sep))t=t.slice(0,-1);return t}var iu=30,Io=1,Oo=365;function su(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var au=new Set(wo.filter((e)=>e.catastrophic).map((e)=>e.id));function T(e,t){if(!e)return null;if(au.has(e.id))return e;if(t?.destructiveCommandProtectionEnabled===!1)return null;let n=t?.effectiveDestructiveCommandRules[e.id];return n&&!n.enabled?null:e}function me(e,t,n){if(au.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function lu(e,t){return Object.freeze(Object.fromEntries(wo.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 cu(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:lu(e,t)})}var uu={standard:0,strict:1,paranoid:2};function fu(e,t){return{policy:{version:1,safety:{level:t.safety?.level??e.safety.level,overrides:{...e.safety.overrides,...t.safety?.overrides}},workflow:{worktree_mode:t.workflow?.worktree_mode??e.workflow.worktree_mode},destructive_command_protection:{enabled:t.destructive_command_protection?.enabled??e.destructive_command_protection.enabled,overrides:{...e.destructive_command_protection.overrides,...t.destructive_command_protection?.overrides},allow_paths:Fs(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths)},secret_protection:{enabled:t.secret_protection?.enabled??e.secret_protection.enabled,overrides:{...e.secret_protection.overrides,...t.secret_protection?.overrides},deny_paths:Fs(e.secret_protection.deny_paths,t.secret_protection?.deny_paths),allow_paths:Fs(e.secret_protection.allow_paths,t.secret_protection?.allow_paths)},audit:e.audit},weakenings:Py(e,t)}}function Fs(e,t){return[...new Set([...e,...t??[]])]}function Py(e,t){let n=t.safety?.level,r=go[e.safety.level];return[...n&&uu[n]<uu[e.safety.level]?[`project policy lowers level: ${e.safety.level} -> ${n}`]:[],..._n.flatMap((o)=>t.safety?.overrides?.[o]===!1&&(e.safety.overrides[o]??r[o])?[`project policy disables ${o}`]:[]),...t.workflow?.worktree_mode===!0&&!e.workflow.worktree_mode?["project policy enables worktree mode relaxations"]:[],...t.destructive_command_protection?.enabled===!1&&e.destructive_command_protection.enabled?["project policy disables destructive command protection"]:[],...t.secret_protection?.enabled===!1&&e.secret_protection.enabled?["project policy disables secret protection"]:[],...du(t.destructive_command_protection?.overrides,(o)=>e.destructive_command_protection.enabled&&e.destructive_command_protection.overrides[o]!=="off"),...du(t.secret_protection?.overrides,(o)=>e.secret_protection.enabled&&(e.secret_protection.overrides[o]==="on"?!0:e.secret_protection.overrides[o]!=="off"&&!Po.has(o))),...e.destructive_command_protection.enabled?mu(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths).map((o)=>`project policy adds destructive allow path: ${o}`):[],...e.secret_protection.enabled?mu(e.secret_protection.allow_paths,t.secret_protection?.allow_paths).map((o)=>`project policy adds secret allow path: ${o}`):[]]}function du(e,t){return Object.entries(e??{}).flatMap(([n,r])=>r==="off"&&t(n)?[`project policy disables rule ${n}`]:[])}function mu(e,t){return(t??[]).filter((n)=>!e.includes(n))}var Bs=new Set(["standard","strict","paranoid"]),yu={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:iu}};function Cu(e,t){let n=Gy(An(e,t),e.home),r=Lo(dr(t.cwd),e.home),o=ky(r.parsed,e.home),i=Object.keys(o.policy).length>0?fu(n.gui??yu,o.policy):void 0,s=[...n.errors,...r.errors,...o.diagnostics],a=(n.fallback==="defaults"&&i?"salvaged":n.fallback)??(n.gui?void 0:r.fallback)??(s.length>0?"salvaged":void 0),l=o.policy.safety?.level?"project":n.levelPresent?"user":"default";return{...i?Hs(i.policy):n.policy,errors:s,...a?{fallback:a}:{},...r.exists?{policyScopes:{levelScope:l,weakenings:i?.weakenings??[]}}:{}}}var Ty="project policy audit settings are ignored; audit is user scope only";function ky(e,t){if(!We(e))return{policy:{},diagnostics:[]};let n=We(e.safety)?e.safety:{},r=We(e.workflow)?e.workflow:{},o=We(e.destructive_command_protection)?e.destructive_command_protection:{},i=We(e.secret_protection)?e.secret_protection:{},s={...Bs.has(n.level)?{level:n.level}:{},...We(n.overrides)?pu({overrides:bu(n.overrides,_n,["safety","overrides"],on)}):{}},a={...typeof o.enabled==="boolean"?{enabled:o.enabled}:{},...o.overrides!==void 0?{overrides:Do(o.overrides,As,vu,on)}:{},...o.allow_paths!==void 0?{allow_paths:kn(o.allow_paths,Ls,t,["destructive_command_protection","allow_paths"],on)}:{}},l={...typeof i.enabled==="boolean"?{enabled:i.enabled}:{},...i.overrides!==void 0?{overrides:Do(i.overrides,Ds,Eu,on)}:{},...i.deny_paths!==void 0?{deny_paths:kn(i.deny_paths,Ws,t,["secret_protection","deny_paths"],on)}:{},...i.allow_paths!==void 0?{allow_paths:kn(i.allow_paths,Gs,t,["secret_protection","allow_paths"],on)}:{}};return{policy:pu({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?[]:[Ty]}}function bu(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(w([...n,o],$s));return[]}))}function pu(e){return Object.fromEntries(Object.entries(e).flatMap((t)=>Object.keys(t[1]).length>0?[t]:[]))}var on=()=>{return},$s="must be a boolean",Us="must be an object if provided",Su=`must be an integer between ${Io} and ${Oo}`,vu={path:["destructive_command_protection","overrides"],label:"destructive command"},Eu={path:["secret_protection","overrides"],label:"secret protection"},Iy=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Oy(e,t){let n=[];return{policy:xu(e,t,(o)=>{n.push(o)}),issues:n}}function My(e,t){return xu(e,t,on)}function xu(e,t,n){if(!We(e))return n(w([],"Config must be an object")),Mo();if(e.version!==1)n(w(["version"],"must be 1"));let r=Tn(e.safety,["safety"],["level","overrides"],n),o=Tn(r.overrides,["safety","overrides"],_n,n),i=Tn(e.workflow,["workflow"],["worktree_mode"],n),s=Tn(e.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],n),a=Tn(e.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],n),l=Tn(e.audit,["audit"],["retention_days"],n);return Ru(e,Iy,[],n),{version:1,safety:{level:Dy(r.level,n),overrides:bu(o,_n,["safety","overrides"],n)},workflow:{worktree_mode:zs(i.worktree_mode,["workflow","worktree_mode"],!1,n)},destructive_command_protection:{enabled:zs(s.enabled,["destructive_command_protection","enabled"],!0,n),overrides:Do(s.overrides,As,vu,n),allow_paths:kn(s.allow_paths,Ls,t,["destructive_command_protection","allow_paths"],n)},secret_protection:{enabled:zs(a.enabled,["secret_protection","enabled"],!0,n),overrides:Do(a.overrides,Ds,Eu,n),deny_paths:kn(a.deny_paths,Ws,t,["secret_protection","deny_paths"],n),allow_paths:kn(a.allow_paths,Gs,t,["secret_protection","allow_paths"],n)},audit:{retention_days:Ny(l.retention_days,n)}}}function Tn(e,t,n,r){if(e===void 0)return{};if(!We(e))return r(w(t,Us)),{};return Ru(e,n,t,r),e}function Ru(e,t,n,r){for(let o of Object.keys(e).filter((i)=>!t.includes(i)))r({path:n,message:o,kind:"unknownKeys"})}function Dy(e,t){if(e===void 0)return"standard";if(Bs.has(e))return e;return t(w(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function zs(e,t,n,r){if(typeof e==="boolean")return e;if(e!==void 0)r(w(t,$s));return n}function Ny(e,t){if(!(e===void 0||typeof e==="number"&&Number.isInteger(e)&&e>=Io&&e<=Oo))t(w(["audit","retention_days"],Su));return su(e)}function Do(e,t,n,r){if(e===void 0)return{};if(!We(e))return r(w(n.path,Us)),{};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(w([...n.path,o],'must be "on" or "off"')),[]}))}function kn(e,t,n,r,o){if(e===void 0)return[];if(!Array.isArray(e))return o(w(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"?de([...r,s],a):w([...r,s],a)),[]})}function We(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Mo(){return structuredClone(yu)}function Lo(e,t){if(!No.existsSync(e))return{exists:!1,policy:Mo(),errors:[]};try{let n=No.readFileSync(e,"utf-8");if(!n.trim())return{exists:!0,policy:Mo(),errors:[`${e}: Config file is empty`],fallback:"defaults"};let r=JSON.parse(n),o=Oy(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}: ${Wy(i)}`),fallback:We(r)?"salvaged":"defaults"}}catch(n){let r=n instanceof Error?n.message:String(n);return{exists:!0,policy:Mo(),errors:[`${e}: ${n instanceof SyntaxError?"Invalid JSON":r}`],fallback:"defaults"}}}var Ly=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[Us,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[$s,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Su,`not an integer between ${Io} and ${Oo}`]]);function Wy(e){let t=ws(e.path);if(e.kind==="unknownKeys")return`${t===""?"":`${t}.`}${e.message}: unknown field`;if(e.kind==="key")return`${t}: unknown rule id`;let n=Ly.get(e.message)??e.message;return t===""?n:`${t}: ${n}`}function Gy(e,t){let n=Lo(e,t);if(!n.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!We(r))return{policy:hu(),errors:[]};let o=My(r,t);return{policy:Hs(o),gui:o,errors:[],levelPresent:gu(r)}}if(n.parsed===void 0)return{policy:hu(),errors:n.errors,...n.fallback?{fallback:n.fallback}:{}};return{policy:Hs(n.policy),gui:n.policy,errors:n.errors,...n.fallback?{fallback:n.fallback}:{},levelPresent:gu(n.parsed)}}function gu(e){let t=We(e)&&We(e.safety)?e.safety:{};return Bs.has(t.level)}function wu(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...Po].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function hu(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:wu({}),denyPaths:[],allowPaths:[]}}}function Hs(e){return{safety:Fy(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:wu(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function Fy(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 _u(e,t){let n=eu(e,t),r=Cu(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((d)=>d.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}),...$y(l.spec)?{source:l.spec}:{}}:{},...c&&typeof c==="object"?{override:Object.freeze({type:"reason",reason:c.reason})}:{}})]})));return Uy(o,zy(n,r),s,r.policyScopes)}function zy(e,t){let n=By(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?Hy(e.errors):void 0,e.warnings.length>0?Vs(e.warnings.join("; ")):void 0,n)}}function Hy(e){return`${Vs(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function By(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 $y(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function Uy(e,t,n=Object.freeze({}),r){let o=js(structuredClone(e)),i=r?{policyScopes:js(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 js(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))js(t);return Object.freeze(e)}function jy(...e){return Vs(e.filter((t)=>!!t).join("; "))}function Vs(e){return/[.!?]$/.test(e)?e:`${e}.`}function Au(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:Ks(t.fail_closed,e.strict,"strict"),paranoid_rm:Ks(t.paranoid_rm,e.paranoidRm,"paranoidRm"),paranoid_interpreters:Ks(t.paranoid_interpreters,e.paranoidInterpreters,"paranoidInterpreters")};return{policy:cu(e.policySnapshot.policy,i),effectiveCapabilities:i,effectiveLevel:cs({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}function Ks(e,t,n){if(t===void 0||t===e.enabled)return e;return{enabled:t,source:"capability_override",sources:[...e.sources,`analysis options.${n}`]}}var Ke=require("node:path");function yr(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 Vy=/^[A-Za-z_][A-Za-z0-9_]*=/;function Wo(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function Cr(e){let t=Wo(e.words[0],"time")?1:0,n=t===1&&Wo(e.words[t],"-p")?t+1:t,r=t===1&&Wo(e.words[n],"--")?n+1:n,o=Wo(e.words[r],"!")?r+1:r,i=e.words.slice(o).find((s)=>!Vy.test(s.text));return i?.provenance==="literal"?i.text:void 0}var zt=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Go(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Ky(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)=>_e(t)))})}function Fo(e,t,n){e.push(n),t.reset()}function zo(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 qs(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 In(e,t,n,r,o,i,s){return qs({text:r,raw:e.slice(t,n),span:{start:t,end:n},provenance:o,quoted:i,...s?{parts:s}:{}})}function _e(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 Ky(t);if(t.kind==="group"||t.kind==="function")return Object.freeze({...t,span:Object.freeze(t.span),body:_e(t.body)});return Object.freeze({...t,span:Object.freeze(t.span)})}))})}function Ys(e,t,n){if(t>=n||Tu(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!Tu(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=Pu(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=Pu(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===`
|
|
8
|
-
`||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
|
|
9
|
-
`&&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
|
|
10
|
-
`)r++;let o=r>=n?n:r+1;return{text:e.slice(t,r),contentEnd:r,next:o}}function
|
|
11
|
-
`||f==="\r"){m();let C=f==="\r"&&e[
|
|
12
|
-
`?
|
|
13
|
-
`&&e[
|
|
14
|
-
`){a+=2;continue}s+=h,a+=2;continue}let g=f==="$"||f==="<"||f===">"||f==="`"?Ko(e,a,n,r,o,i):null;if(g){let h=
|
|
4
|
+
`)}function Qi(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 xn(e={}){return{reason:or,intent:"stop_and_explain",command:e.command,segment:e.segment??e.command,toolName:e.toolName}}var hg={session:{unusable:{reason:"CC Safety Net cannot check tool calls because the session's working directory or workspace root no longer exists, is inaccessible, is not a directory, or uses an unsupported path form. Ask the user to restart the session from an existing directory.",intent:"hard_stop"},"outside-workspace":{reason:"CC Safety Net cannot check tool calls because the session's working directory is outside its workspace roots. Ask the user to restart the session from a directory inside the workspace.",intent:"hard_stop"}},requested:{unusable:{reason:"CC Safety Net could not use the requested working directory because it does not exist, is inaccessible, is not a directory, or uses an unsupported path form. Use an existing accessible working directory. If the requested directory is missing, create it from an accessible location before retrying the command.",intent:"use_alternative"},"outside-workspace":{reason:"CC Safety Net could not use the requested working directory because it is outside the session's workspace. Use a working directory inside the workspace.",intent:"use_alternative"}}};function io(e,t={}){return{...hg[e.directory][e.problem],command:t.command,toolName:t.toolName,cwd:e.cwd}}function Hl(e){return zl({...e,redact:Ct})}function Bl(e){return zl({...e,redact:Ct,askUser:!0})}function $l(e){return Ct(e instanceof Error?e.message:String(e))}var Re=require("node:path");var yg=256,so=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 Me(e,t=process.platform){if(t!=="win32")return e;return e.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function bt(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function rs(e,t){return es(e,0,t)}function es(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=ts(e,o+2),a=Cg(e,o,t);if(a===null){if(so.has(s))throw new N("pathEnvironmentExpansion");r+=e.slice(o);break}let l=e.slice(o,a+1);r+=bg(l,t,n),o=a+1;continue}let i=ts(e,o+1);if(!i){r+="$",o++;continue}r+=ns(i,n)??`$${i}`,o+=i.length+1}return r}function Cg(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>X.pathEnvironmentExpansion.cap)throw new N("pathEnvironmentExpansion");o++;continue}if(e[o]!=="}")continue;if(r--,r===0)return o}return null}function bg(e,t,n){let r=e.slice(2,-1),o=ts(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return ns(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(so.has(o))throw new N("pathEnvironmentExpansion");return e}if(!so.has(o))return e;if(s.endsWith("="))throw new N("pathEnvironmentExpansion");let a=ns(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??"":es(i.slice(s.length),t+1,n);return l?es(i.slice(s.length),t+1,n):""}function ts(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 ns(e,t){if(!so.has(e))return null;if(e==="HOME")return t.env.get("HOME")??t.home;return t.env.get(e)??null}function O(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){jl(n,i);let s=t.realpath(i);if(s!==null)return Ul(n,e,s,o);let a=Re.dirname(i);if(a===i||o.length>=yg)return Ul(n,e,i,o);o.push(Re.basename(i)),i=a}}function Ul(e,t,n,r){let o=r.length===0?n:Re.join(n,...r.reverse());return e.resolvedPaths.set(t,o),o}function Sg(e,t,n){let r=n.resolvedPaths.get(e);if(r!==void 0)return r;jl(n,e);let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function jl(e,t){e.charge("realpathAttempts"),e.charge("processedCandidateBytes",Buffer.byteLength(t))}function he(e,t,n,r){let o=Kl(e,t,n);if(!o)return"";return O(o,n.paths,r).replace(/\\/g,"/")}function Vl(e,t,n,r,o){let i=Kl(e,t,n);if(!i)return null;if(o(Re.basename(i)))return O(i,n.paths,r).replace(/\\/g,"/");let s=Sg(i,n.paths,r);return s===null?null:s.replace(/\\/g,"/")}function Kl(e,t,n){let r=n.home,o=rs(e.trim(),n).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?Re.resolve(r,o.slice(2)):o,s=Me(i);return Re.normalize(Re.isAbsolute(s)?s:Re.resolve(t,s))}var Ql=require("node:util"),vg=new Set(["applypatch","patch"]),Eg=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),xg=new Set(["grep","grepsearch","rg"]),Rg=new Set(["find","findbyname","glob"]),wg=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),_g=new Set(["command","diff","input","patch","patchtext"]),ql=new TextEncoder,Ag=new TextDecoder,Pg=/\s/,Tg=64;class be extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var ir=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function ec(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function lo(e){return wg.has(ec(e))}function tc(e){let t=ec(e);if(vg.has(t))return"patch";if(xg.has(t))return"grep";if(Rg.has(t))return"glob";if(Eg.has(t))return"path";return"unknown"}function Nt(e){if(!e||typeof e!=="object")return;sc(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)dt();return}if(t.get||t.set)dt();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function co(e,t){return nc(e,t,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function nc(e,t,n,r,o){let i=ic(e,r,o);if(typeof e==="string")return n?[e]:[];if(!i)return[];let s=i.entries.flatMap(([a,l])=>nc(l,t,i.array?n:t.has(rc(a)),r,o+1));return r.ancestors.delete(i.object),s}function rc(e){return e.replace(/-/g,"_").toLowerCase()}function uo(e){return oc(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Ig)}function oc(e,t,n,r){let o=ic(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>oc(a,o.array?t:_g.has(rc(s)),n,r+1));return n.ancestors.delete(o.object),i}function kg(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>ir.maxDepth||t.nodes>ir.maxNodes)dt();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>ir.maxStringBytes||t.stringBytes>ir.maxAggregateStringBytes)dt()}function ic(e,t,n){if(kg(e,t,n),!e||typeof e!=="object")return null;let r=sc(e);if(t.ancestors.has(e))dt();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>ir.maxKeys)dt();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)dt();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function sc(e){if(Ql.types.isProxy(e))dt();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)dt();return t}function dt(){throw new be}function Ig(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=Og(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,m=c.startsWith(" ")||c.startsWith("+")?1:0;if(i=Math.max(0,i-u),s=Math.max(0,s-m),i===0&&s===0)a();continue}if(c.startsWith("*** ")){a(),t.push(...os(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...os(c));continue}if(c.startsWith("--- ")){let u=n[l+1]??"";if(!u.startsWith("+++ "))continue;t.push(...ss(ao(c.slice(4),!0),ao(u.slice(4),!0))),l++;continue}if(!r)t.push(...os(c))}return t}function Og(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 os(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return Jl(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return Jl(n[1]);if(e.startsWith("diff --git "))return Mg(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return Xl(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return Xl(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return zg(i[1]);return[]}function Mg(e){let t=Dg(e);if(t.length===2&&t[0]&&t[1])return ss(t[0],t[1]);let n=Ng(e);return n?ss(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function Dg(e){let t=[],n=0;while(n<e.length&&t.length<2){while(Qt(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&&!Qt(e[n]))n++;t.push(e.slice(i,n));continue}let o=ac(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(Qt(e[n]))n++;return n===e.length?t:[]}function Ng(e){let t=0;while(t<e.length&&Qt(e[t]))t++;let n=e.length;while(n>t&&Qt(e[n-1]))n--;let r=0,o=t;while(o<n){if(!Qt(e[o])){o++;continue}let i=o;while(o<n&&Qt(e[o]))o++;if(i===t||o===n)continue;if(r++,r>Tg)dt();if(Lg(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function Lg(e,t,n,r,o){if(is(e,t,n,r,o))return!0;let i=Yl(e,"/",t,n),s=Yl(e,"/",r,o);if(i<=t||s<=r)return!1;if(is(e,t,i,r,s))return!1;return is(e,i+1,n,s+1,o)}function is(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 Yl(e,t,n,r){for(let o=n;o<r;o++)if(e[o]===t)return o;return-1}function Qt(e){return e!==void 0&&Pg.test(e)}function ac(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:Ag.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...ql.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(...ql.encode(Wg(s[0]??""))),o+=2}return null}function Wg(e){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
5
|
+
`,r:"\r",t:"\t",v:"\v"}[e]??e}function Gg(e){return sr(Hg(e))}function ss(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(sr);let n=Fg(e,t)??(e===t?lc(e):null);return[e,t,...n?[n]:[]].flatMap(sr)}function Zl(e){let t=lc(e);return[e,...t?[t]:[]].flatMap(sr)}function lc(e){let t=e.indexOf("/");return t>0&&t<e.length-1?e.slice(t+1):null}function Fg(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 Xl(e){return Gg(ao(e,!0))}function zg(e){return sr(ao(e,!1))}function ao(e,t){let n=e.trim(),r=n[0]==='"'||n[0]==="'"?n[0]:void 0;if(r){let o=ac(n,0,r);if(o&&(t||n.slice(o.end).trim()===""))return o.value}return t?n.split("\t",1)[0]?.trim()??"":n}function Hg(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function sr(e){return e===""||e==="/dev/null"?[]:[e]}function Jl(e){let t=e.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return t===""||t==="/dev/null"?[]:[t]}var Ye=require("node:path");function St(e,t,n){if(bt(e))return;let r=t.flatMap((i)=>mo(i,n));if(!r[0])return;let o=mo(Ye.isAbsolute(e)?e:Ye.resolve(r[0],e),n)[0];if(!o)return;return r.some((i)=>ar(o,i))?o:void 0}function as(e,t,n){if(bt(e))return;return mo(Ye.isAbsolute(e)?e:Ye.resolve(t,e),n)[0]}function vt(e,t){return e.flatMap((n)=>mo(n,t))[0]}function Et(e,t,n){return as(e,t,n)?"outside-workspace":"unusable"}function mo(e,t){let n=t.realpath(e);if(n===null)return[];return t.isDirectory(n)?[n]:[]}function ar(e,t){let n=Ye.relative(t,e);return n===""||n!==".."&&!n.startsWith(`..${Ye.sep}`)&&!Ye.isAbsolute(n)}var Bg=8388608;async function cc(e){let t=[],n=0;for await(let r of e){let o=typeof r==="string"?Buffer.from(r,"utf-8"):Buffer.from(r.buffer,r.byteOffset,r.byteLength);if(n+=o.byteLength,n>Bg)throw $g(e),Error("hook input byte limit exceeded");t.push(o)}return Buffer.concat(t,n).toString("utf-8")}function $g(e){let t=e.destroy??e.cancel;if(!t)return;try{Promise.resolve(t.call(e)).catch(()=>{})}catch{}}function fo(e,t,n){try{return JSON.parse(e)}catch{t({reason:n});return}}function oe(e,t){let n=t.get(e);return n?{kind:"command",shell:n}:{kind:tc(e)}}function uc(e,t,n,r,o,i){let s=e===void 0?i:e;if(typeof s!=="string"||s.trim()==="")return Se(r,t,n),null;let a=vt([s],o);if(a)return{configCwd:a,executionCwd:a};return He(r,t,n,{directory:"session",problem:"unusable",cwd:s}),null}function Se(e,t,n){e(xn({command:dc(t),toolName:n}))}function He(e,t,n,r){e(io(r,{command:dc(t),toolName:n}))}function dc(e){try{return Nt(e)}catch(t){if(!(t instanceof be))throw t;return}}var wn=require("node:fs"),po=require("node:os");var yc=require("node:fs"),Cc=require("node:path");var fc=require("node:child_process"),F=require("node:fs"),re=require("node:path"),Ug=["/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"],jg=5000;function pc(e,t=lh(),n=jg){let r=Vg(e),o=r===null?null:Kg(r);if(r===null||o===null)return null;let i=sh(r,o,t,n);return i===null?null:{recursiveSubmodules:i}}function Vg(e){try{let t=F.realpathSync(re.resolve(e));return F.statSync(t).isDirectory()?t:null}catch{return null}}function Kg(e){let t=ih(e);if(!t)return null;try{let n=F.lstatSync(t);if(n.isSymbolicLink()||!n.isFile())return null;let r=ls(t);if(!r?.commonDir)return null;if(!Zg(r.gitDir,t))return null;return Xg(r.gitDir,re.dirname(t))?{gitDir:r.gitDir,commonDir:r.commonDir}:null}catch{return null}}function ls(e){try{let t=qg(e);if(!t)return null;let n=F.realpathSync(re.isAbsolute(t)?t:re.resolve(re.dirname(e),t));if(!F.statSync(n).isDirectory())return null;return{gitDir:n,commonDir:Yg(n)}}catch{return null}}function qg(e){let t=F.readFileSync(e,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!t.startsWith("gitdir:"))return null;return t.slice(7).trim()||null}function Yg(e){try{let t=F.readFileSync(re.join(e,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!t)return null;let n=F.realpathSync(re.isAbsolute(t)?t:re.resolve(e,t));return F.statSync(n).isDirectory()?n:null}catch{return null}}function Zg(e,t){let n=Jg(e);return n===null?!1:gc(e,n,t)}function Xg(e,t){let n=Qg(e);return n===null?!0:gc(e,n,t)}function Jg(e){let t=re.join(e,"gitdir");if(!F.existsSync(t))return null;let n=F.readFileSync(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return n===""?null:n}function Qg(e){let t=re.join(e,"config.worktree");return F.existsSync(t)?th(t):null}function gc(e,t,n){try{return eh(re.isAbsolute(t)?t:re.resolve(e,t),n)}catch{return!1}}function eh(e,t){try{let n=F.statSync(e),r=F.statSync(t);if(n.ino!==0&&r.ino!==0&&n.dev===r.dev&&n.ino===r.ino)return!0}catch{}return mc(F.realpathSync.native(e))===mc(F.realpathSync.native(t))}function mc(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 th(e){let t=F.readFileSync(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=nh(s[1]??"")}return r}function nh(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;return oh(t.slice(1,-1))}var rh={"\\":"\\",'"':'"',n:`
|
|
6
|
+
`,t:"\t",b:"\b"};function oh(e){return e.replace(/\\(.?)/gs,(t,n)=>n===""?t:rh[n]??t)}function ih(e){try{return cs(F.realpathSync(e))}catch{return null}}function cs(e){let t=e;while(!0){let n=re.join(t,".git");if(F.existsSync(n))return n;let r=re.dirname(t);if(r===t)return null;t=r}}function sh(e,t,n,r){if(ah(t))return!0;if(n===null)return!0;let o=fc.spawnSync(n,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:ch(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&&hc(o.stdout.trim())}function ah(e){return[re.join(e.commonDir,"config"),re.join(e.gitDir,"config.worktree")].filter((t)=>F.existsSync(t)).some((t)=>uh(t))}function lh(){return Ug.find((e)=>F.existsSync(e))??null}function lr(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function ch(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!lr(t)))}function uh(e){let t;try{t=F.readFileSync(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(dh(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=hc(c)}return r}function dh(e){return e==="include"||e.startsWith("includeif ")}function hc(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function bc(e,t){if(e==="")return null;let n=ue(),r=cs(he(e,e,t,n)),o=r?mh(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 mh(e,t,n,r){try{let o=he(e,t,n,r),i=yc.statSync(e),s=i.isFile()?o:null,a=i.isFile()?ls(e):null,l=(i.isDirectory()?[o]:[a?.gitDir,a?.commonDir]).flatMap((u)=>u?[Rn(he(u,t,n,r))]:[]),c=[...new Set(i.isDirectory()?[Rn(e.replace(/\\/g,"/")),...l]:l)];return{entry:Rn(o),markerFile:s?Rn(s):null,directories:c,hooksDirectories:[...new Set(c.flatMap((u)=>{let m=Rn(Cc.join(u,"hooks").replace(/\\/g,"/"));return[m,Rn(he(m,t,n,r))]}))]}}catch{return null}}function Rn(e){return process.platform==="win32"?e.toLowerCase():e}var fh={realpath:(e)=>{try{return wn.realpathSync(e)}catch{return null}},entryKind:(e)=>{let t=wn.lstatSync(e,{throwIfNoEntry:!1});if(!t)return"missing";return t.isSymbolicLink()?"symlink":"present"},isDirectory:(e)=>{try{return wn.statSync(e).isDirectory()}catch{return!1}}};function vc(){return ph({env:new Map(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),home:Me(process.env.HOME||po.homedir()),tmpdir:po.tmpdir(),paths:fh})}function ph(e,t={}){let n=new Map,r=new Map,o={...e,gitMetadata:(i)=>Sc(n,i,()=>bc(i,o)),worktreeFacts:(i)=>Sc(r,i,()=>pc(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 _n=["fail_closed","paranoid_rm","paranoid_interpreters"],go={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 ae={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"}},ho=["standard","strict","paranoid"];function gh(e,t){if(!t)return e;return ho.indexOf(t)>ho.indexOf(e)?t:e}function hh(e){let t=fs(ae.level,e);if(t===void 0||t==="")return;if(ho.includes(t))return t;console.error(`CC Safety Net: ignored invalid ${ae.level.name}=${JSON.stringify(t.slice(0,40))}. Use ${ho.join(", ")}.`);return}function yh(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function Ec(e){return yh(fs(ae.auditScope,e))==="all"}function ds(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 ms(e={},t){let n=e.safety?.level??"standard",r=hh(t),o=gh(n,r),i=go[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 ${ae.level.name}=${r}`),l.paranoidRm.push(`env ${ae.level.name}=${r}`),l.paranoidInterpreters.push(`env ${ae.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(en(ae.strict,t))s.failClosed=!0,a.failClosed="environment",l.failClosed.push(`env ${ae.strict.name}`);if(en(ae.paranoid,t))s.paranoidRm=!0,s.paranoidInterpreters=!0,a.paranoidRm="environment",a.paranoidInterpreters="environment",l.paranoidRm.push(`env ${ae.paranoid.name}`),l.paranoidInterpreters.push(`env ${ae.paranoid.name}`);if(en(ae.paranoidRm,t))s.paranoidRm=!0,a.paranoidRm="environment",l.paranoidRm.push(`env ${ae.paranoidRm.name}`);if(en(ae.paranoidInterpreters,t))s.paranoidInterpreters=!0,a.paranoidInterpreters="environment",l.paranoidInterpreters.push(`env ${ae.paranoidInterpreters.name}`);let c=!!e.worktreeMode||en(ae.worktree,t);return{strict:s.failClosed,paranoidRm:s.paranoidRm,paranoidInterpreters:s.paranoidInterpreters,worktreeMode:c,effectiveLevel:ds(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 en(e,t){let n=typeof e==="string"?us(e,t):fs(e,t);return n==="1"||n?.toLowerCase()==="true"}function us(e,t){return t.get(e)}function fs(e,t){let n=us(e.name,t);if(n!==void 0)return n;if(e.legacyName)return us(e.legacyName,t);return}function cr(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}}var fr=require("node:path");var W=require("node:fs"),j=require("node:path");function ps(){let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${e()}${e()}`}var Ch=Symbol("PolicyFilesystemScope"),bh=Symbol("PolicyFilesystemTarget"),Sh=W.constants.O_NOFOLLOW??0;class ye extends Error{name="PolicyFilesystemError";constructor(e){super(`Unable to access ${e} filesystem safely.`)}}function tn(e,t){return{[Ch]:!0,root:j.resolve(e),label:t}}function xc(e,t){let n=j.normalize(t);if(t===""||j.isAbsolute(t)||n===".."||n.startsWith(`..${j.sep}`))throw new ye(e.label);return{[bh]:!0,scope:e,relativePath:n,path:j.join(e.root,n)}}function ur(e,t){return xc(e,j.relative(e.root,j.resolve(t)))}function Rc(e,t="rules policy"){let n=j.resolve(e),r=j.parse(n).dir;return xc(tn(r,t),j.relative(r,n))}function Co(e){return _c(e.scope.label,()=>{if(!yo(e))return null;let t=W.openSync(e.path,W.constants.O_RDONLY|Sh);return vh(t,()=>{let n=W.fstatSync(t);if(!n.isFile())throw new ye(e.scope.label);let r=W.readFileSync(t,"utf-8"),o=W.lstatSync(e.path);if(!o.isFile()||o.isSymbolicLink()||n.dev!==o.dev||n.ino!==o.ino)throw new ye(e.scope.label);return yo(e),r})})}function wc(e,t){if(e.path===t.path)return!0;return _c(e.scope.label,()=>{if(!yo(e)||!yo(t))return!1;let n=(r)=>j.join(W.realpathSync(j.parse(r).dir),j.parse(r).base);return n(e.path)===n(t.path)})}function _c(e,t,n){try{return t()}catch(r){if(n?.(),r instanceof ye)throw r;throw new ye(e)}}function vh(e,t){try{return t()}finally{W.closeSync(e)}}function yo(e,t="file"){let n=Eh(e.scope);if(!n)return!1;let r=e.relativePath.split(j.sep);for(let o of r.keys()){let i=j.join(e.scope.root,...r.slice(0,o+1)),s=W.lstatSync(i,{throwIfNoEntry:!1});if(!s)return!1;if(s.isSymbolicLink())throw new ye(e.scope.label);if(o<r.length-1&&!s.isDirectory())throw new ye(e.scope.label);if(o===r.length-1&&(t==="file"?!s.isFile():!s.isDirectory()))throw new ye(e.scope.label);xh(n,W.realpathSync(i),e.scope.label)}return!0}function Eh(e){if(!W.lstatSync(e.root,{throwIfNoEntry:!1}))return null;if(!W.statSync(e.root).isDirectory())throw new ye(e.label);return W.realpathSync(e.root)}function xh(e,t,n){let r=j.relative(e,t);if(r===".."||r.startsWith(`..${j.sep}`)||j.isAbsolute(r))throw new ye(n)}var L=require("node:path");var nn=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,Ac="rulebook.json",Pc=".cc-safety-net/rules";var Tc=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/;var Rh=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,wh=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),_h="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),RP=new RegExp(`^${wh}/(${nn.source.slice(1,-1)})/${_h}$`);function Ah(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function kc(e){if(bo(e))try{return gs(e),null}catch(t){return t instanceof Error?t.message:String(t)}return nn.test(e)?null:`Local rulebook sources must be bare names matching ${nn}: ${e}`}function gs(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(Tc);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||!Rh.test(r))throw Error(`GitHub rulebook refs must use valid path segments: ${e}`);if(!o||!nn.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:Ah(o),name:o}}function bo(e){return Tc.test(e)}var Ic="rule.json",So="policy.json",Oc=".cc-safety-net",Ph="rules",Th="CC_SAFETY_NET_HOME",Mc="`cc-safety-net rule update`";function kh(e){return L.resolve(e,Pc)}function Ih(e){return L.join(kh(e),Ic)}function dr(e){return L.join(L.resolve(e),Oc,So)}function hs(e,t={}){return t.userConfigDir??(t.userConfigPath?L.dirname(t.userConfigPath):L.join(Oh(e),Ph))}function Oh(e){let t=e.env.get(Th);return t?L.resolve(Me(t)):L.join(e.home,Oc)}function Mh(e,t={}){return L.join(hs(e,t),Ic)}function An(e,t={}){return L.join(L.dirname(hs(e,t)),So)}function Dc(e,t){let n=t.userConfigPath??Mh(e,t),r=t.projectConfigPath??Ih(t.cwd),o=Dh(e,t),i=Nh(r,t.cwd);return{userConfigPath:n,projectConfigPath:r,userScope:o,projectScope:i,userConfigTarget:ur(o,n),projectConfigTarget:ur(i,r)}}function Dh(e,t){let n=t.userConfigPath?L.dirname(L.dirname(L.resolve(t.userConfigPath))):L.dirname(L.resolve(t.userConfigDir??hs(e,t)));return tn(n,"user policy")}function Nh(e,t){let n=L.resolve(t),r=L.resolve(e),o=L.relative(n,r);if(o!==".."&&!o.startsWith(`..${L.sep}`)&&!L.isAbsolute(o))return tn(n,"project policy");return tn(L.dirname(L.dirname(r)),"project policy")}function Nc(e,t){return L.join(e,t,Ac)}var De=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),Lt=/^[a-zA-Z][a-zA-Z0-9_-]*$/,Wt=256,Q=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Lc=new Set(["python","python3","python2","node","ruby","perl"]),vo=/^python(?:[23](?:\.\d+)*)?$/,Be=new Set(["awk","gawk","nawk","mawk"]),Eo=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 Wc="Rulebook exceeds CC Safety Net's safe validation limits.",Gc="Additional rulebook validation errors were omitted.",Ze=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Fc(e){if(ys(e.allowed_commands,Ze.maxAllowedCommands)||ys(e.rules,Ze.maxRules)||ys(e.tests,Ze.maxTests))return!1;let{maxAggregateStringCodeUnits:t,maxTotalBlockArgs:n}=Ze,r=(o,i=!1)=>{if(typeof o!=="string")return!0;if(o.length>Ze.maxStringCodeUnits||i&&o.length>Ze.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>Ze.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 ys(e,t){return Array.isArray(e)&&e.length>t}var Cs=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var bs=64,Ss="Rule config exceeds CC Safety Net's safe source limit.";function M(e){return k(e).toLowerCase()}function k(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}function we(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 Lh={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},vs=new Set(["--init-file","--rcfile"]);function Es(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 m=t.slice(c+1);if(t[0]==="-"&&(m==="c"||m[0]==="-"&&m.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(!Lh[e]?.includes(u))continue;if(c+1===t.length)i++;break}return{interactive:o,followingValues:i,commandSelected:s,stdinMode:a,syntaxCheck:l}}function Ne(e){let t=k(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"&&vs.has(l)&&!s.includes("="))i++;continue}let a=Es(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 mr(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 xo(e){let t={inSingle:!1,inDouble:!1,escaped:!1};for(let n of Wh(e))mr(n,t);return t.inSingle||t.inDouble}function Wh(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===`
|
|
7
|
+
`||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);mr(s,n)}return t}var xs=new Set(["rm","find","xargs","parallel"]),Gh=new Set(["git","busybox",...xs,...Q,...Lc,...Be]),Fh=new Set(["python","node","ruby","perl"]);function zc(e){let t=M(e);return Gh.has(t)||Xe(t)}function Xe(e){return Fh.has(zh(e))}function zh(e){let t=k(e).toLowerCase();return vo.test(t)?"python":t}function Rs(e){try{let t=Co(Hh(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=Uh(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 ye)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 Hh(e){return typeof e==="string"?Rc(e):e}var w=(e,t)=>({path:e,message:t,kind:"typed"}),de=(e,t)=>({path:e,message:t,kind:"custom"});function Hc(e){let t=new Set;return e.flatMap((n,r)=>{let o=Pn(n)?n.name:void 0;if(typeof o!=="string")return[];if(t.has(o.toLowerCase()))return[de(["rules",r,"name"],`duplicate rule name "${o}"`)];return t.add(o.toLowerCase()),[]})}var ws=`must be one of ${Cs.join(", ")}`,Bh=/^[^/]+\/[^/]+$/,$h=["version","rules","overrides","transparent_wrappers"];function Uh(e){let t=jh(e);return{errors:_s(ey(t,$h,(n)=>n.kind==="custom"),": "," "),sources:Qh(e,t)}}function jh(e){if(!Pn(e))return[w([],"Config must be an object")];let t=Array.isArray(e.rules)&&e.rules.length>bs;return[...e.version===1?[]:[w(["version"],"must be 1")],...Vh(e.rules,t),...Yh(e.overrides),...Xh(e.transparent_wrappers),...t?[]:qh(e.rules),...Pn(e.overrides)?Object.keys(e.overrides).filter((n)=>!Bh.test(n)).map((n)=>de(["overrides",n],"must use <rulebook-name>/<rule-name>")):[],...Jh(e.transparent_wrappers)]}function Vh(e,t){if(e===void 0)return[];if(!Array.isArray(e))return[w(["rules"],"must be an array of rulebook source strings"),...Bc(e,bs)?[w(["rules"],Ss)]:[]];if(t)return[{path:["rules"],message:Ss,kind:"limit"}];return e.flatMap((n,r)=>{if(typeof n!=="string")return[w(["rules",r],"must be a rulebook source string"),...Kh(n,1)?[w(["rules",r],"must be a non-empty rulebook source string")]:[]];return n===""?[w(["rules",r],"must be a non-empty rulebook source string")]:[]})}function Bc(e,t){let n=$c(e);return n!==void 0&&!(n<=t)}function Kh(e,t){let n=$c(e);return n!==void 0&&!(n>=t)}function $c(e){if(e===null||e===void 0)return;let t=e.length;return t===void 0?void 0:Number(t)}function qh(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[de(["rules",r],"must be a non-empty rulebook source string")];let o=kc(n);if(o)return[de(["rules",r],o)];if(t.has(n))return[de(["rules",r],`duplicate rulebook source "${n}"`)];return t.add(n),[]})}function Yh(e){if(e===void 0)return[];if(!Pn(e))return[w(["overrides"],"must be an object if provided")];return Object.keys(e).flatMap((t)=>{let n=e[t];if(n==="off")return[];if(!Pn(n))return[w(["overrides",t],'must be "off" or an object')];return[...Zh(n.reason,["overrides",t,"reason"]),...n.intent===void 0||Ps(n.intent)?[]:[w(["overrides",t,"intent"],ws)]]})}function Zh(e,t){if(typeof e!=="string")return[w(t,"required non-empty string"),...Bc(e,Wt)?[w(t,`must be at most ${Wt} characters`)]:[]];if(e==="")return[w(t,"required non-empty string")];return e.length>Wt?[w(t,`must be at most ${Wt} characters`)]:[]}function Xh(e){if(e===void 0)return[];if(!Array.isArray(e))return[w(["transparent_wrappers"],"must be an array of command strings")];return e.flatMap((t,n)=>{if(typeof t!=="string")return[w(["transparent_wrappers",n],"must be a command string")];return Lt.test(t)?[]:[w(["transparent_wrappers",n],"must match command pattern")]})}function Jh(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||!Lt.test(n))return[];if(t.has(n))return[de(["transparent_wrappers",r],`duplicate command "${n}"`)];if(zc(n))return[de(["transparent_wrappers",r],`reserved command "${n}" cannot be a wrapper`)];return t.add(n),[]})}function Qh(e,t){let n=Pn(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 ey(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 _s(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 Ps(e){return Cs.includes(e)}function Pn(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function jc(e){let t=ry(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}var ty=`required non-empty string up to ${Wt} characters`,Uc="must be a non-empty array of unique non-empty strings",ny="required non-empty array of non-empty strings";function ry(e){if(!Gt(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Fc(e))return{errors:[Wc],ruleNames:new Set};let t=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],..._s(oy(e,e.rulebook_version===2),": ",": ")];return{errors:t.length>Ze.maxValidationErrors?[...t.slice(0,Ze.maxValidationErrors),Gc]:t,ruleNames:new Set(Vc(e).map((n)=>n.toLowerCase()))}}function Vc(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 oy(e,t){return[...typeof e.name==="string"&&nn.test(e.name)?[]:[w(["name"],"required string matching rule name pattern")],...typeof e.version==="string"&&e.version!==""?[]:[w(["version"],"required non-empty string")],...iy(e.allowed_commands),...sy(e.rules,t),...uy(e.tests),...dy(e),...my(e)]}function iy(e){if(!Array.isArray(e))return[w(["allowed_commands"],"required array")];let t=new Set;return[...e.flatMap((n,r)=>typeof n==="string"&&Lt.test(n)?[]:[w(["allowed_commands",r],"must match command pattern")]),...e.flatMap((n,r)=>{if(typeof n!=="string"||!Lt.test(n))return[];if(t.has(n))return[de(["allowed_commands",r],`duplicate command "${n}"`)];return t.add(n),[]})]}function sy(e,t){if(!Array.isArray(e))return[w(["rules"],"required array")];return[...e.flatMap((n,r)=>{if(!Gt(n))return[w(["rules",r],"must be an object")];return t?ly(n,["rules",r]):ay(n,["rules",r])}),...Hc(e)]}function ay(e,t){return[...Kc(e.name,t),...qc(e.command,t),...e.subcommand===void 0||typeof e.subcommand==="string"&&Lt.test(e.subcommand)?[]:[w([...t,"subcommand"],"must match command pattern")],...Ro(e.block_args,[...t,"block_args"],"required non-empty array",!1),...Yc(e.reason,t),...Zc(e.intent,t)]}function ly(e,t){return[...Kc(e.name,t),...qc(e.command,t),...Yc(e.reason,t),...Zc(e.intent,t),...cy(e.match,[...t,"match"]),...e.subcommand===void 0?[]:[w([...t,"subcommand"],"not supported in rulebook_version 2")],...e.block_args===void 0?[]:[w([...t,"block_args"],"not supported in rulebook_version 2")]]}function Kc(e,t){if(typeof e!=="string")return[w([...t,"name"],"required string")];return nn.test(e)?[]:[w([...t,"name"],"must match rule name pattern")]}function qc(e,t){return typeof e==="string"&&Lt.test(e)?[]:[w([...t,"command"],"required string matching command pattern")]}function Yc(e,t){return typeof e==="string"&&e!==""&&e.length<=Wt?[]:[w([...t,"reason"],ty)]}function Zc(e,t){return e===void 0||Ps(e)?[]:[w([...t,"intent"],ws)]}function cy(e,t){if(!Gt(e))return[w(t,"required object")];return[...Ro(e.command_path,[...t,"command_path"],ny,!1),...e.any_args===void 0?[]:Ro(e.any_args,[...t,"any_args"],Uc,!0),...e.exclude_args===void 0?[]:Ro(e.exclude_args,[...t,"exclude_args"],Uc,!0)]}function Ro(e,t,n,r){if(!Array.isArray(e))return[w(t,n)];let o=e.flatMap((i,s)=>{if(typeof i!=="string")return[w([...t,s],"must be a non-empty string")];return i===""?[de([...t,s],"must be a non-empty string")]:[]});if(e.some((i)=>typeof i!=="string"))return o;return[...o,...e.length===0?[de(t,n)]:[],...r&&new Set(e).size!==e.length?[de(t,"must not contain duplicate values")]:[]]}function uy(e){if(e===void 0)return[];if(!Array.isArray(e))return[w(["tests"],"must be an array if provided")];return e.flatMap((t,n)=>{if(!Gt(t))return[w(["tests",n],"must be an object")];return[...typeof t.command==="string"&&t.command.trim()!==""?[]:[w(["tests",n,"command"],"required non-empty string")],...t.expect==="blocked"||t.expect==="allowed"?[]:[w(["tests",n,"expect"],'must be "blocked" or "allowed"')],...t.rule===void 0||typeof t.rule==="string"?[]:[w(["tests",n,"rule"],"must be a string if provided")],...t.expect==="blocked"&&typeof t.rule!=="string"?[de(["tests",n,"rule"],"required string for blocked fixtures")]:[]]})}function dy(e){if(!Array.isArray(e.tests))return[];let t=new Set(Vc(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)=>de(["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[de(["rules",r,"command"],`"${o}" must be listed in allowed_commands`)]})}function Gt(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function nu(e,t){let n=Dc(e,t),r;try{r=wc(n.userConfigTarget,n.projectConfigTarget)}catch(f){if(f instanceof ye)return vy(n,f.message);throw f}let o=Rs(n.userConfigTarget),i=r?{config:null,errors:[]}:Rs(n.projectConfigTarget),s=eu(n.userConfigPath,o.errors),a=eu(n.projectConfigPath,i.errors),l=new Set,c=o.config?Xc(o.config,fr.dirname(n.userConfigPath),"user",n.userScope,l):tu(),u=i.config?Xc(i.config,fr.dirname(n.projectConfigPath),"project",n.projectScope,l):tu(),m=o.config?.overrides??{},d=i.config?.overrides??{};return{rules:[...Jc(c.rules,m),...Jc(u.rules,d)],transparent_wrappers:by(o.config,i.config),rulebooks:[...c.rulebooks,...u.rulebooks],errors:[...s,...a,...c.errors,...u.errors],warnings:[...c.warnings,...u.warnings,...c.canValidateOverrides?Qc(m,c.knownRuleIds,n.userConfigPath):[],...c.canValidateOverrides?Sy(d,c.knownRuleIds,n.projectConfigPath):[],...u.canValidateOverrides?Qc(d,u.knownRuleIds,n.projectConfigPath):[]],userConfig:o.config??void 0,projectConfig:i.config??void 0,...n}}function Xc(e,t,n,r=tn(fr.dirname(fr.dirname(t)),n==="user"?"user policy":"project policy"),o=new Set){let i=[],s=[],a=e.rules.flatMap((c)=>{let u=py(c,t,r);if(u.errors.length>0||!u.rulebook)return i.push(...u.errors),[];let m=u.rulebook;if(o.has(m.name))return s.push(`duplicate active rulebook name "${m.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(m.name),[{rules:fy(m),rulebook:{source:n,spec:c,name:m.name,version:m.version,rules:m.rules.map((d)=>`${m.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 fy(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 py(e,t,n){let r=gy(e),o=Nc(t,r),i=yy(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}; ${hy(e)}`]};let s=Cy(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 gy(e){return bo(e)?gs(e).name:e}function hy(e){return bo(e)?`run ${Mc} to vendor ${e}`:"create that file or remove that source from the rules config"}function yy(e,t){try{return{content:Co(ur(t,e))}}catch(n){if(n instanceof ye)return{error:n.message};throw n}}function Cy(e){let t;try{t=JSON.parse(e)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:jc(t)}}catch(n){return{problem:n instanceof Error?n.message:"invalid rulebook"}}}function by(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function Jc(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 Qc(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 Sy(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 eu(e,t){return t.map((n)=>n.startsWith("Unable to access ")?n:`${e}: ${n}`)}function vy(e,t){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath}}function tu(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}var No=require("node:fs");var ru=[{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"}],Ts=new Set(ru.map((e)=>e.id)),wo=ru,Ey=new Map(wo.map((e)=>[e.id,e.intent]));function v(e,t){return{id:e,reason:t,intent:Ey.get(e)??"manual_only"}}var ks=[{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"}],_o={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},xy=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Ry=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Is=[{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"]},...Ry.flatMap((e)=>xy.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 Ao=[{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"]}],ou=[{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"],Os=ou.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=ou.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}))),pr={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)$/},Ds=["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})),Ns=[{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?$/}],_y=[...ks,_o,...Is,...Os,...Ms,pr,...Ds,...Ns,...Ao].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}})),Po=new Set(Ao.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),Ls=new Set(_y.map((e)=>e.id));var Le=require("node:path"),To=process.platform==="win32",iu=/[*?]/;function Ws(e){let t=e.trim(),n=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(To?t.replaceAll("\\","/"):t);if(!n)return null;let r=n[1]??"",o=n[2]??"";if(iu.test(r)||o==="."||o==="..")return null;return{root:r||"/",name:o}}function gr(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function Gs(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=gr(e.trim(),t);if(!Le.isAbsolute(n))return"must be an absolute path or start with ~/";return hr(n,t)}function Fs(e,t){let n=su(e,t);if(n===null)return"must be a non-empty path string";if(!Le.isAbsolute(n))return null;if(hr(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 Ay="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Py="cannot cover the guard's own configuration";function su(e,t){if(typeof e!=="string"||e.trim()==="")return null;let n=e.trim(),r=To?n.replaceAll("\\","/"):n;return gr(r.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function zs(e,t){let n=su(e,t);if(n===null)return"must be a non-empty path string";let r=Ws(n)?.root??n;if(iu.test(r))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Le.isAbsolute(r))return null;if(hr(r,t)!==null)return Ay;return Ty(r,t)?Py:null}function Ty(e,t){let n=ko(e),r=ko(Le.join(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${Le.sep}`)}function hr(e,t){let n=ko(e),r=ko(t);if(n===r)return"cannot be the home directory";let o=n.endsWith(Le.sep)?n:`${n}${Le.sep}`;if(r.startsWith(o))return"cannot contain the home directory";return null}function ko(e){let t=Le.normalize(e);if(To)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(To?3:1)&&t.endsWith(Le.sep))t=t.slice(0,-1);return t}var au=30,Io=1,Oo=365;function lu(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var cu=new Set(wo.filter((e)=>e.catastrophic).map((e)=>e.id));function T(e,t){if(!e)return null;if(cu.has(e.id))return e;if(t?.destructiveCommandProtectionEnabled===!1)return null;let n=t?.effectiveDestructiveCommandRules[e.id];return n&&!n.enabled?null:e}function me(e,t,n){if(cu.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function uu(e,t){return Object.freeze(Object.fromEntries(wo.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 du(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:uu(e,t)})}var mu={standard:0,strict:1,paranoid:2};function gu(e,t){return{policy:{version:1,safety:{level:t.safety?.level??e.safety.level,overrides:{...e.safety.overrides,...t.safety?.overrides}},workflow:{worktree_mode:t.workflow?.worktree_mode??e.workflow.worktree_mode},destructive_command_protection:{enabled:t.destructive_command_protection?.enabled??e.destructive_command_protection.enabled,overrides:{...e.destructive_command_protection.overrides,...t.destructive_command_protection?.overrides},allow_paths:Hs(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths)},secret_protection:{enabled:t.secret_protection?.enabled??e.secret_protection.enabled,overrides:{...e.secret_protection.overrides,...t.secret_protection?.overrides},deny_paths:Hs(e.secret_protection.deny_paths,t.secret_protection?.deny_paths),allow_paths:Hs(e.secret_protection.allow_paths,t.secret_protection?.allow_paths)},audit:e.audit},weakenings:ky(e,t)}}function Hs(e,t){return[...new Set([...e,...t??[]])]}function ky(e,t){let n=t.safety?.level,r=go[e.safety.level];return[...n&&mu[n]<mu[e.safety.level]?[`project policy lowers level: ${e.safety.level} -> ${n}`]:[],..._n.flatMap((o)=>t.safety?.overrides?.[o]===!1&&(e.safety.overrides[o]??r[o])?[`project policy disables ${o}`]:[]),...t.workflow?.worktree_mode===!0&&!e.workflow.worktree_mode?["project policy enables worktree mode relaxations"]:[],...t.destructive_command_protection?.enabled===!1&&e.destructive_command_protection.enabled?["project policy disables destructive command protection"]:[],...t.secret_protection?.enabled===!1&&e.secret_protection.enabled?["project policy disables secret protection"]:[],...fu(t.destructive_command_protection?.overrides,(o)=>e.destructive_command_protection.enabled&&e.destructive_command_protection.overrides[o]!=="off"),...fu(t.secret_protection?.overrides,(o)=>e.secret_protection.enabled&&(e.secret_protection.overrides[o]==="on"?!0:e.secret_protection.overrides[o]!=="off"&&!Po.has(o))),...e.destructive_command_protection.enabled?pu(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths).map((o)=>`project policy adds destructive allow path: ${o}`):[],...e.secret_protection.enabled?pu(e.secret_protection.allow_paths,t.secret_protection?.allow_paths).map((o)=>`project policy adds secret allow path: ${o}`):[]]}function fu(e,t){return Object.entries(e??{}).flatMap(([n,r])=>r==="off"&&t(n)?[`project policy disables rule ${n}`]:[])}function pu(e,t){return(t??[]).filter((n)=>!e.includes(n))}var Us=new Set(["standard","strict","paranoid"]),bu={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:au}};function Su(e,t){let n=zy(An(e,t),e.home),r=Lo(dr(t.cwd),e.home),o=Oy(r.parsed,e.home),i=Object.keys(o.policy).length>0?gu(n.gui??bu,o.policy):void 0,s=[...n.errors,...r.errors,...o.diagnostics],a=(n.fallback==="defaults"&&i?"salvaged":n.fallback)??(n.gui?void 0:r.fallback)??(s.length>0?"salvaged":void 0),l=o.policy.safety?.level?"project":n.levelPresent?"user":"default";return{...i?$s(i.policy):n.policy,errors:s,...a?{fallback:a}:{},...r.exists?{policyScopes:{levelScope:l,weakenings:i?.weakenings??[]}}:{}}}var Iy="project policy audit settings are ignored; audit is user scope only";function Oy(e,t){if(!We(e))return{policy:{},diagnostics:[]};let n=We(e.safety)?e.safety:{},r=We(e.workflow)?e.workflow:{},o=We(e.destructive_command_protection)?e.destructive_command_protection:{},i=We(e.secret_protection)?e.secret_protection:{},s={...Us.has(n.level)?{level:n.level}:{},...We(n.overrides)?hu({overrides:vu(n.overrides,_n,["safety","overrides"],rn)}):{}},a={...typeof o.enabled==="boolean"?{enabled:o.enabled}:{},...o.overrides!==void 0?{overrides:Do(o.overrides,Ts,xu,rn)}:{},...o.allow_paths!==void 0?{allow_paths:kn(o.allow_paths,Gs,t,["destructive_command_protection","allow_paths"],rn)}:{}},l={...typeof i.enabled==="boolean"?{enabled:i.enabled}:{},...i.overrides!==void 0?{overrides:Do(i.overrides,Ls,Ru,rn)}:{},...i.deny_paths!==void 0?{deny_paths:kn(i.deny_paths,Fs,t,["secret_protection","deny_paths"],rn)}:{},...i.allow_paths!==void 0?{allow_paths:kn(i.allow_paths,zs,t,["secret_protection","allow_paths"],rn)}:{}};return{policy:hu({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?[]:[Iy]}}function vu(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(w([...n,o],js));return[]}))}function hu(e){return Object.fromEntries(Object.entries(e).flatMap((t)=>Object.keys(t[1]).length>0?[t]:[]))}var rn=()=>{return},js="must be a boolean",Vs="must be an object if provided",Eu=`must be an integer between ${Io} and ${Oo}`,xu={path:["destructive_command_protection","overrides"],label:"destructive command"},Ru={path:["secret_protection","overrides"],label:"secret protection"},My=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Dy(e,t){let n=[];return{policy:wu(e,t,(o)=>{n.push(o)}),issues:n}}function Ny(e,t){return wu(e,t,rn)}function wu(e,t,n){if(!We(e))return n(w([],"Config must be an object")),Mo();if(e.version!==1)n(w(["version"],"must be 1"));let r=Tn(e.safety,["safety"],["level","overrides"],n),o=Tn(r.overrides,["safety","overrides"],_n,n),i=Tn(e.workflow,["workflow"],["worktree_mode"],n),s=Tn(e.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],n),a=Tn(e.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],n),l=Tn(e.audit,["audit"],["retention_days"],n);return _u(e,My,[],n),{version:1,safety:{level:Ly(r.level,n),overrides:vu(o,_n,["safety","overrides"],n)},workflow:{worktree_mode:Bs(i.worktree_mode,["workflow","worktree_mode"],!1,n)},destructive_command_protection:{enabled:Bs(s.enabled,["destructive_command_protection","enabled"],!0,n),overrides:Do(s.overrides,Ts,xu,n),allow_paths:kn(s.allow_paths,Gs,t,["destructive_command_protection","allow_paths"],n)},secret_protection:{enabled:Bs(a.enabled,["secret_protection","enabled"],!0,n),overrides:Do(a.overrides,Ls,Ru,n),deny_paths:kn(a.deny_paths,Fs,t,["secret_protection","deny_paths"],n),allow_paths:kn(a.allow_paths,zs,t,["secret_protection","allow_paths"],n)},audit:{retention_days:Wy(l.retention_days,n)}}}function Tn(e,t,n,r){if(e===void 0)return{};if(!We(e))return r(w(t,Vs)),{};return _u(e,n,t,r),e}function _u(e,t,n,r){for(let o of Object.keys(e).filter((i)=>!t.includes(i)))r({path:n,message:o,kind:"unknownKeys"})}function Ly(e,t){if(e===void 0)return"standard";if(Us.has(e))return e;return t(w(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Bs(e,t,n,r){if(typeof e==="boolean")return e;if(e!==void 0)r(w(t,js));return n}function Wy(e,t){if(!(e===void 0||typeof e==="number"&&Number.isInteger(e)&&e>=Io&&e<=Oo))t(w(["audit","retention_days"],Eu));return lu(e)}function Do(e,t,n,r){if(e===void 0)return{};if(!We(e))return r(w(n.path,Vs)),{};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(w([...n.path,o],'must be "on" or "off"')),[]}))}function kn(e,t,n,r,o){if(e===void 0)return[];if(!Array.isArray(e))return o(w(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"?de([...r,s],a):w([...r,s],a)),[]})}function We(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Mo(){return structuredClone(bu)}function Lo(e,t){if(!No.existsSync(e))return{exists:!1,policy:Mo(),errors:[]};try{let n=No.readFileSync(e,"utf-8");if(!n.trim())return{exists:!0,policy:Mo(),errors:[`${e}: Config file is empty`],fallback:"defaults"};let r=JSON.parse(n),o=Dy(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}: ${Fy(i)}`),fallback:We(r)?"salvaged":"defaults"}}catch(n){let r=n instanceof Error?n.message:String(n);return{exists:!0,policy:Mo(),errors:[`${e}: ${n instanceof SyntaxError?"Invalid JSON":r}`],fallback:"defaults"}}}var Gy=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[Vs,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[js,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Eu,`not an integer between ${Io} and ${Oo}`]]);function Fy(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=Gy.get(e.message)??e.message;return t===""?n:`${t}: ${n}`}function zy(e,t){let n=Lo(e,t);if(!n.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!We(r))return{policy:Cu(),errors:[]};let o=Ny(r,t);return{policy:$s(o),gui:o,errors:[],levelPresent:yu(r)}}if(n.parsed===void 0)return{policy:Cu(),errors:n.errors,...n.fallback?{fallback:n.fallback}:{}};return{policy:$s(n.policy),gui:n.policy,errors:n.errors,...n.fallback?{fallback:n.fallback}:{},levelPresent:yu(n.parsed)}}function yu(e){let t=We(e)&&We(e.safety)?e.safety:{};return Us.has(t.level)}function Au(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...Po].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function Cu(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Au({}),denyPaths:[],allowPaths:[]}}}function $s(e){return{safety:Hy(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:Au(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function Hy(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=nu(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}),...jy(l.spec)?{source:l.spec}:{}}:{},...c&&typeof c==="object"?{override:Object.freeze({type:"reason",reason:c.reason})}:{}})]})));return Vy(o,By(n,r),s,r.policyScopes)}function By(e,t){let n=Uy(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:Ky(e.errors.length>0?$y(e.errors):void 0,e.warnings.length>0?qs(e.warnings.join("; ")):void 0,n)}}function $y(e){return`${qs(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Uy(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 jy(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function Vy(e,t,n=Object.freeze({}),r){let o=Ks(structuredClone(e)),i=r?{policyScopes:Ks(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 Ks(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))Ks(t);return Object.freeze(e)}function Ky(...e){return qs(e.filter((t)=>!!t).join("; "))}function qs(e){return/[.!?]$/.test(e)?e:`${e}.`}function Tu(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:Ys(t.fail_closed,e.strict,"strict"),paranoid_rm:Ys(t.paranoid_rm,e.paranoidRm,"paranoidRm"),paranoid_interpreters:Ys(t.paranoid_interpreters,e.paranoidInterpreters,"paranoidInterpreters")};return{policy:du(e.policySnapshot.policy,i),effectiveCapabilities:i,effectiveLevel:ds({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}function Ys(e,t,n){if(t===void 0||t===e.enabled)return e;return{enabled:t,source:"capability_override",sources:[...e.sources,`analysis options.${n}`]}}var Ke=require("node:path");function yr(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 Wo(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function Cr(e){let t=Wo(e.words[0],"time")?1:0,n=t===1&&Wo(e.words[t],"-p")?t+1:t,r=t===1&&Wo(e.words[n],"--")?n+1:n,o=Wo(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 Ft=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Go(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Yy(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)=>_e(t)))})}function Fo(e,t,n){e.push(n),t.reset()}function zo(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 Zs(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 In(e,t,n,r,o,i,s){return Zs({text:r,raw:e.slice(t,n),span:{start:t,end:n},provenance:o,quoted:i,...s?{parts:s}:{}})}function _e(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 Yy(t);if(t.kind==="group"||t.kind==="function")return Object.freeze({...t,span:Object.freeze(t.span),body:_e(t.body)});return Object.freeze({...t,span:Object.freeze(t.span)})}))})}function Xs(e,t,n){if(t>=n||Iu(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!Iu(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=ku(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=ku(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===`
|
|
8
|
+
`||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 Js(e,t,n,r){let o=[],i=t;for(let s of r){let a=i,l=!1;while(i<n){let c=Zy(e,i,n);if((s.stripTabs?c.text.replace(/^\t+/,""):c.text)===s.delimiter){s.attach({body:s.stripTabs?Xy(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 ku(e,t,n,r){let o="",i=t;while(i<n&&e[i]!==`
|
|
9
|
+
`&&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 Iu(e){return e!=="\r"&&(/[\s;&|<>)]/u.test(e)||e==="`")}function Zy(e,t,n){let r=t;while(r<n&&e[r]!==`
|
|
10
|
+
`)r++;let o=r>=n?n:r+1;return{text:e.slice(t,r),contentEnd:r,next:o}}function Xy(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Nu=new Set(["&&","||","|","|&"]);function Lu(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return _e({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=$o(e,0,e.length,t,{used:0,max:t.maxWords},0);return _e({kind:"program",dialect:"posix",source:e,span:n,status:Vo(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function $o(e,t,n,r,o,i,s){let a=[],l=[],c=Go(),u=[],m=()=>{if(c.words.length===0&&c.redirections.length===0)return;let f={start:c.start,end:c.end},p=c.words.map((g)=>g.text);Fo(a,c,{kind:"command",dialect:"posix",source:e.slice(f.start,f.end),span:f,words:c.words,redirections:c.redirections,nested:c.nested,displayText:l.length>0&&a.length===0?e.slice(t,n):p.join(" ")})},d=t;while(d<n){let f=e[d];if(!f)break;if(s&&f===s)return m(),Du(a,l),{nodes:a,issues:l,next:d+1,closed:!0,limited:!1,pendingHeredocs:u};if(jo(f)){if(f===`
|
|
11
|
+
`||f==="\r"){m();let C=f==="\r"&&e[d+1]===`
|
|
12
|
+
`?d+2:d+1,P=a.at(-1);if(P?.kind!=="connector"||!Nu.has(P.operator))a.push(Object.freeze({kind:"connector",operator:e.slice(d,C),span:Object.freeze({start:d,end:C})}));if(u.length>0){let x=Js(e,C,n,u.splice(0));l.push(...x.issues),d=x.next;continue}d=C;continue}d++;continue}if(f==="#"){while(d<n&&e[d]!==`
|
|
13
|
+
`&&e[d]!=="\r")d++;continue}let p=c.start===-1?CC(e,d,n):void 0;if(p){if(ea(a,l),i>=r.maxDepth)return On(a,l,d,"depth-limit",r.maxDepth);if(!Qs(o))return On(a,l,d,"word-limit",r.maxWords);let C=$o(e,p.braceIndex+1,n,r,o,i+1,"}"),P=C.next,x={start:p.braceIndex+1,end:C.closed?P-1:P},A=Ou(e,x,C);if(a.push({kind:"function",name:p.name,span:{start:d,end:P},body:A}),l.push(...C.issues),C.pendingHeredocs.length>0||Sr(C.nodes))l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(u.push(...C.pendingHeredocs),C.limited)return Bo(a,l,C.next);if(!C.closed)l.push({code:"unclosed-function-body",message:"function body is not closed"});d=P;continue}let g=Uo(e,d);if(g){if(m(),!Uu(a.at(-1)))l.push({code:"unexpected-connector",message:`connector ${g} has no preceding command`});a.push(Object.freeze({kind:"connector",operator:g,span:Object.freeze({start:d,end:d+g.length})})),d+=g.length;continue}if(f===")"){m(),l.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),a.push({kind:"unknown",source:f,span:{start:d,end:d+1}}),d++;continue}if((f==="("||f==="{"&&iC(e,d,n))&&c.start===-1){if(ea(a,l),i>=r.maxDepth)return On(a,l,d,"depth-limit",r.maxDepth);let C=f==="("?")":"}",P=$o(e,d+1,n,r,o,i+1,C),x=P.next,A={start:d+1,end:P.closed?x-1:x},ee=Ou(e,A,P);if(a.push({kind:"group",style:f==="("?"subshell":"brace",span:{start:d,end:x},body:ee}),l.push(...P.issues),P.pendingHeredocs.length>0||Sr(P.nodes))l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(u.push(...P.pendingHeredocs),P.limited)return Bo(a,l,P.next);if(!P.closed)l.push({code:f==="("?"unclosed-subshell":"unclosed-brace-group",message:`${f} group is not closed`});d=x;continue}let h=(f==="<"||f===">")&&e[d+1]!=="("?tC(e,d):null;if(h){let C=c.words.at(-1),P=C&&C.span.end===d&&/^[0-9]+$/.test(C.raw)?Number(C.raw):void 0;if(P!==void 0)c.words.pop();let x=P===void 0?d:C?.span.start??d;c.start=c.start===-1?d:c.start;let A=d+h.length;while(A<n&&/[ \t]/.test(e[A]??""))A++;let ee=e[A],qe=A>d+h.length&&ee==="#",ct=!ee||jo(ee)||!!Uo(e,A)||ee===s||ee===")"||qe||(ee==="<"||ee===">")&&e[A+1]!=="(",xe=h==="<<"||h==="<<-",Z=xe?Xs(e,A,n):void 0,H=Z?{word:In(e,A,Z.next,Z.delimiter,"literal",Z.quoted),nested:[],issues:[],next:Z.next,limited:!1}:!ct?ta(e,A,n,r,o,i):void 0;if(H){if(l.push(...H.issues),H.limited)return Bo(a,l,H.next);if(!Qs(o))return On(a,l,H.next,"word-limit",r.maxWords)}let ie=H?.next??d+h.length,ne={kind:"redirection",operator:h,span:{start:x,end:ie},...P===void 0?{}:{fd:P},...H?{target:H.word}:{}};if(c.redirections.push(ne),xe&&!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 se=c.nested;u.push({delimiter:Z.delimiter,quotedDelimiter:Z.quoted,stripTabs:h==="<<-",attach:(Oe)=>{if(ne.heredoc=Oe,Oe.quotedDelimiter)return;se.push(...Qy(e,Oe.bodySpan.start,Oe.bodySpan.end,r,o,i+1))}})}if(!xe&&!H)l.push({code:"missing-redirection-target",message:`redirection ${h} requires a target word`});if(H)c.nested.push(...H.nested);c.end=ie,d=ie;continue}if(c.start===-1)ea(a,l);let y=ta(e,d,n,r,o,i);if(l.push(...y.issues),y.limited)return Bo(a,l,y.next);let S=lC(c.words)?fC(e,y.word,o.max-o.used,r.maxDepth,r.maxInputLength):void 0;if(S?.limitCode)return On(a,l,y.next,S.limitCode,S.limitCode==="word-limit"?r.maxWords:S.limitCode==="depth-limit"?r.maxDepth:r.maxInputLength);let E=S?.words??[y.word];for(let C of E){if(!Qs(o))return On(a,l,y.next,"word-limit",r.maxWords);c.words.push(C)}c.start=c.start===-1?d:c.start,c.end=y.next,c.nested.push(...y.nested),d=y.next>d?y.next:d+1}return m(),Du(a,l),l.push(...bC(u)),{nodes:a,issues:l,next:d,closed:s===void 0,limited:!1,pendingHeredocs:[]}}function Ou(e,t,n){return{kind:"program",dialect:"posix",source:e.slice(t.start,t.end),span:t,status:Vo(n.issues,n.limited),issues:n.issues,nodes:n.nodes}}function ta(e,t,n,r,o,i){let s="",a=t,l=!1,c="literal",u=[],m=[],d=!1;while(a<n){let f=e[a],p=(f==="<"||f===">")&&e[a+1]==="(";if(!f||jo(f)||(f===";"||f==="|"||f==="&")&&Uo(e,a)||(f==="<"||f===">")&&!p)break;if(f===")")break;if(f==="'"){l=!0;let h=e.indexOf("'",a+1);if(h===-1||h>=n){s+=e.slice(a+1,n),m.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(f==='"'){l=!0;let h=Jy(e,a,n,r,o,i);if(s+=h.text,u.push(...h.nested),m.push(...h.issues),d||=h.limited,c=br(c,h.provenance),a=h.next,d)break;continue}if(e.startsWith("$'",a)){l=!0;let h=nC(e,a+2,n);if(s+=h.text,m.push(...h.issues),!h.closed)m.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});a=h.next;continue}if(f==="\\"){let h=e[a+1];if(!h){m.push({code:"trailing-escape",message:"escape has no following character"}),a++;break}if(h===`
|
|
14
|
+
`){a+=2;continue}s+=h,a+=2;continue}let g=f==="$"||f==="<"||f===">"||f==="`"?Ko(e,a,n,r,o,i):null;if(g){let h=Wu(g,u,m);if(d||=h.limited,c=br(c,h.provenance),a=h.next,d)break;continue}if(f==="$"){let h=zu(e,a,n,s,c);s=h.text,c=h.provenance,a=h.next;continue}if(f==="*"||f==="?"||f==="[")c=br(c,"glob");s+=f,a++}return{word:In(e,t,a,s,c,l,c==="literal"?void 0:oC(e,t,a)),nested:u,issues:m,next:a,limited:d}}function Jy(e,t,n,r,o,i){let s="",a="literal",l=[],c=[],u=!1,m=t+1;while(m<n){let d=e[m];if(d==='"')return{text:s,provenance:a,nested:l,issues:c,next:m+1,limited:u};if(d==="\\"&&e[m+1]){let p=e[m+1]??"";if(p===`
|
|
15
15
|
`){m+=2;continue}if(p==="\r"&&e[m+2]===`
|
|
16
|
-
`){m+=3;continue}s+=["$","`",'"',"\\"].includes(p)?p:`\\${p}`,m+=2;continue}if(e.startsWith("$((",m)){let p=
|
|
17
|
-
`||l==="\r")&&s.length>0){let
|
|
18
|
-
`?a+2:a+1,m=
|
|
19
|
-
`&&e[s+1]!=="\r")s++;return s}function Uo(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
|
|
20
|
-
`],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(o.has(r))return{text:o.get(r)??r,next:t+1};if(r==="x")return Ho(e,t+1,n,16,2,t+1);if(r==="u")return Ho(e,t+1,n,16,4,t+1);if(r==="U")return Ho(e,t+1,n,16,8,t+1);if(/[0-7]/.test(r))return Ho(e,t,n,8,3,t+1);return{text:r,next:t+1}}function Ho(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 Vo(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
|
|
21
|
-
`){m();let y=f==="\r"&&e[
|
|
22
|
-
`?
|
|
23
|
-
`)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
|
|
24
|
-
`||e==="\r"||e==="\u2028"||e==="\u2029"}function
|
|
25
|
-
`||e===";"||e==="&"||e==="|"}function Dn(e){return e==="|"||e===";"}function Yo(e,t,n){let r=
|
|
26
|
-
`)t=!0,i++;continue}let a=
|
|
27
|
-
`||a!==-1){if(t=!1,n=!1,r=!1,o=-1,a!==-1)i=a-1;continue}if(s===";"||s==="&"||s==="|"||i===te(e)){if(o>=0){let l=
|
|
28
|
-
`,a++;if(l)n=!1,r=!1;t=!0,o=a;continue}if(!t){o++;continue}if(q(e,o,"--")&&(o===0||K(b(e,o-1)))&&(!b(e,o+2)||K(b(e,o+2))||fe(b(e,o+2)))){t=!1,n=!1,r=!1,o+=2;continue}if(n||=q(e,o,"--recursive")&&wt(e,o+11)||la(e,o,"recursive"),r||=q(e,o,"--force")&&wt(e,o+7)||la(e,o,"force"),n&&r)return!0;o++}return!1}function la(e,t,n){if(!q(e,t,"--"))return!1;let r=0;while(r<=n.length){let o=b(e,t+r+2);if(!o||K(o)||fe(o))break;if(o!==n[r])return!1;r++}return r>0&&wt(e,t+r+2)}function DC(e,t){let n=t,r=!1,o=!1;while(n<te(e)){while(K(b(e,n)))n++;let i=n;while(n<te(e)&&!K(b(e,n)))n++;if(b(e,i)!=="-"||n-i===2&&q(e,i,"--"))return!1;let s=Qu(e,i,"recursive"),a=Qu(e,i,"force");if(r&&a||o&&s)return!0;if(r||=s,o||=a,b(e,i+1)==="-")continue;let l=LC(e,i,n);if(l.combined||r&&l.forceAtBoundary||o&&l.recursiveAtBoundary)return!0;r||=l.recursive,o||=l.force}return!1}function Qu(e,t,n){return q(e,t,`--${n}`)&&wt(e,t+n.length+2)||la(e,t,n)}function NC(e,t){if(t>0&&sn(b(e,t-1)))return-1;let n=t;if(b(e,n)==="\\")n++;if(b(e,n)!=="r")return-1;if(n++,b(e,n)==="\\")n++;if(b(e,n)!=="m"||!K(b(e,n+1)))return-1;return n+1}function LC(e,t,n){let r=!1,o=!1,i=!1,s=!1,a=!1;if(b(e,t)!=="-")return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a};let l="";for(let c=t+1;c<n;c++){let d=b(e,c)??"",m=(d==="r"||d==="f")&&wt(e,c+1);r||=d==="r",o||=d==="f",i||=d==="r"&&m,s||=d==="f"&&m,a||=(l==="r"&&d==="f"||l==="f"&&d==="r")&&m,l=d}return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a}}function ed(e,t,n){return xr(e,"reset",Dn,!0,(r)=>b(e,r)==="-"&&Nn(e,r,t,n)?!0:r)}function WC(e){return xr(e,"clean",Dn,!0,(t)=>{if(b(e,t)!=="-")return t;if(Nn(e,t,"--fo","rce"))return!0;let n=Er(e,t,Dn);for(let r=t+1;r<n;r++)if(b(e,r)==="f")return!0;return n-1})}function Xo(e,t,n){if(!Rt(e,t,"git"))return null;let r=t+3;if(!K(b(e,r)))return{commandEnd:-1,next:r};while(K(b(e,r)))r++;while(r<te(e)){if(fe(b(e,r)))return{commandEnd:-1,next:r};let o=Er(e,r,fe);if(Rt(e,r,n))return{commandEnd:r+n.length,next:o};if(b(e,r)!=="-")return{commandEnd:-1,next:o};let i=o-r===2&&q(e,r,"--"),s=GC(e,r,o);r=o;while(K(b(e,r)))r++;if(i)return{commandEnd:Rt(e,r,n)?r+n.length:-1,next:Er(e,r,fe)};if(!s)continue;if(r>=te(e)||fe(b(e,r)))return{commandEnd:-1,next:r};r=Er(e,r,fe);while(K(b(e,r)))r++}return{commandEnd:-1,next:r}}function GC(e,t,n){for(let r of De)if(n-t===r.length&&q(e,t,r))return!0;return!1}function FC(e){return td(e,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function zC(e){return xr(e,"push",Dn,!0,(t)=>{if(b(e,t)!=="-")return t;if(b(e,t+1)==="f"&&!sn(b(e,t+2))&&!q(e,t+2,"-with-lease"))return!0;let n=rd(e,t,"--fo","rce");if(n>=0&&!q(e,n,"-with-lease"))return!0;return t})}function HC(e){return xr(e,"push",fe,!1,(t)=>{if(K(b(e,t))&&b(e,t+1)==="+"&&t+2<te(e)&&!fe(b(e,t+2))&&!K(b(e,t+2)))return!0;if(b(e,t)===":"&&b(e,t+1)==="+")return!0;return t})}function BC(e){return xr(e,"push",fe,!1,(t)=>{if(b(e,t)==="-"&&Nn(e,t,"--de","lete"))return!0;if(K(b(e,t))&&b(e,t+1)===":"&&t+2<te(e)&&!K(b(e,t+2))&&!fe(b(e,t+2)))return!0;return t})}function $C(e){let t=!1,n=!1,r=!1;for(let o=0;o<=te(e);o++){if(o===te(e)||fe(b(e,o))){if(n&&r)return!0;t=!1,n=!1,r=!1;continue}if(!t){let a=Xo(e,o,"branch");if(a){t=a.commandEnd>=0,o=Math.max(o,(t?a.commandEnd:a.next)-1);continue}}if(!t||b(e,o)!=="-")continue;let i=Er(e,o,fe),s=UC(e,o,i);if(n||=s.deletion,r||=s.force,n&&r)return!0;o=i-1}return!1}function UC(e,t,n){let r=!1,o=!1;for(let i=t;i<n;i++){if(b(e,i)!=="-")continue;if(Nn(e,i,"--de","lete"))r=!0;if(Nn(e,i,"--fo","rce"))o=!0;if(b(e,i+1)==="-")continue;let s=i+1,a=!1,l=!1,c=!1;while(s<n&&jC(b(e,s))){let d=b(e,s);a||=d==="d"||d==="D",l||=d==="f",c||=d==="D",s++}if(!wt(e,s))continue;r||=a,o||=l||c}return{deletion:r,force:o}}function jC(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function VC(e){return td(e,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function td(e,t){let n=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let r=0;r<te(e);r++){let o=b(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==="$"&&b(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(K(o))i.shortActive=!1,i.hasShortFlag=!1;if(!i.outerActive){let a=Xo(e,r,t.command);if(a){i.outerActive=a.commandEnd>=0&&K(b(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(Nn(e,r,t.longPrefix,t.longOptional))return!0;i.shortActive||=!t.excludedShortStarts.includes(b(e,r+1)??"")}if(i.hasShortFlag||=i.shortActive&&o===t.shortFlag,i.hasShortFlag&&wt(e,r+1))return!0;if(Dn(o))i.outerActive=!1}return!1}function xr(e,t,n,r,o){let i=!1;for(let s=0;s<te(e);s++){let a=b(e,s),l=n(a);if(!i&&!l){let c=Xo(e,s,t);if(c){i=c.commandEnd>=0&&(!r||K(b(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 d=s;d<=c;d++)if(n(b(e,d)))i=!1;s=c}if(l)i=!1}return!1}function KC(e){let t=!1;for(let n=0;n<te(e);n++){if(aa(b(e,n))){if(t)return!0;t=!1;continue}if(!t){let r=Xo(e,n,"restore");if(r){t=r.commandEnd>=0,n=Math.max(n,(t?r.commandEnd:r.next)-1);continue}}if(t&&b(e,n)==="-"&&b(e,n+1)==="-"&&(q(e,n+2,"staged")||q(e,n+2,"help")))t=!1}return t}function nd(e,t){let n=!1;for(let r=0;r<te(e);r++){let o=b(e,r),i=t?aa(o):fe(o);if(n&&K(o)&&b(e,r+1)==="-"&&Rt(e,r+2,"delete"))return!0;if(i){n=!1;continue}if(Rt(e,r,"find"))n=!0,r+=3}return!1}function Er(e,t,n){let r=t;while(r<te(e)&&!K(b(e,r))&&!n(b(e,r)))r++;return r}function rd(e,t,n,r){if(!q(e,t,n))return-1;let o=t+n.length;for(let i=0;i<r.length&&b(e,o)===r[i];i++)o++;return wt(e,o)?o:-1}function Nn(e,t,n,r){return rd(e,t,n,r)>=0}function $e(e,t){vr(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)Ge(t,a);if((s.regex?.test(a)??!1)||s.scan&&Zo(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 qC=/^[A-Za-z_][A-Za-z0-9_]*=/;function id(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;vr(n,t.source,2);let i={anchored:new RegExp(`^\\$\\{?${o}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${o}(?![A-Za-z0-9_])`)};return sd(t.nodes,r,i)}function sd(e,t,n){return e.every((r)=>{if(r.kind==="connector")return!0;if(r.kind==="group"||r.kind==="function")return sd(r.body.nodes,t,n);if(r.kind==="unknown")return!n.loose.test(r.source);return YC(r,t,n)})}function YC(e,t,n){if(e.nested.some((o)=>n.loose.test(o.source)))return!1;let r=e.words.findIndex((o)=>!qC.test(o.text));return e.words.every((o,i)=>o===t||od(o.raw,n.anchored,i!==r))&&e.redirections.every((o)=>(!o.heredoc||o.heredoc.quotedDelimiter||!n.loose.test(o.heredoc.body))&&(!o.target||od(o.target.raw,n.anchored,!0)))}function od(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}var Rr=require("node:path");function wr(e,t,n,r){let o=Rr.isAbsolute(e)?Rr.resolve(e):t?Rr.resolve(t,e):void 0;if(!o)return;try{return O(o,n,r)}catch{return o}}function ad(e){return!["/dev","/proc","/sys"].some((t)=>e===t||e.startsWith(`${t}/`))}var Ln="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",_r="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.",ua=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),ZC=new Set(["-p","--print"]),XC=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),JC=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"])]]),QC=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),eb=new Map([["python",new Set(["m"])]]),tb=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"])]]),nb=new Set(["always","default","never"]),rb=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),ob=/\\\r?\n/g,ib=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 ld(e){return Qo(e).code}function Jo(e){return Qo(e).sources}function cd(e){return ib.get(ma(e))??[]}function Qo(e){let t=ma(e[0]??"");if(!ua.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 Qe(t,n,r,o,e[i+1]===void 0?void 0:i+1,e[i+1]);if(s===""||s==="-"||!s.startsWith("-"))return Qe(t,n,r,o,i,s);if(t==="node"&&ZC.has(s)){let m=e[i+1];if(m===void 0)return Qe(t,n,r,o);if(m.startsWith("-"))continue;n.push({tokenIndex:i+1,value:m}),r.push({tokenIndex:i+1,kind:"inline-code",value:m}),i++;continue}if(ab(t,s)){let m=e[i+1];if(m===void 0)return Qe(t,n,r,o);if(n.push({tokenIndex:i+1,value:m}),r.push({tokenIndex:i+1,kind:"inline-code",value:m}),t==="python")return Qe(t,n,r,o);i++;continue}let a=/^--eval=(.*)$/s.exec(s);if(lb(t)&&a){let m=a[1]??"";n.push({tokenIndex:i,value:m}),r.push({tokenIndex:i,kind:"inline-code",value:m});continue}if(t==="node"){let m=sb(s);if(m){if(m.attached){if(o&&=m.value!=="",m.value!=="")r.push({tokenIndex:i,kind:"module-file",value:m.value});continue}let u=e[i+1];if(u===void 0||u.startsWith("-"))return o=!1,Qe(t,n,r,o);r.push({tokenIndex:i+1,kind:"module-file",value:u}),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 Qe(t,n,r,o);if(tb.get(t)?.has(s)){let m=e[i+1];if(m===void 0||m.startsWith("-")&&!(t==="ruby"&&rb.has(s))||t==="python"&&!nb.has(m))return Qe(t,n,r,o);i++;continue}if(s.startsWith("--"))continue;let l,c=!1;for(let m=1;m<s.length;m++){let u=s[m];if(u===void 0)break;if(eb.get(t)?.has(u)){let f=s.slice(m+1),p=f||e[i+1];if(p!==void 0)r.push({tokenIndex:f?i:i+1,kind:"module-file",value:p});return Qe(t,n,r,o)}if(XC.get(t)?.has(u)){l=s.slice(m+1)||e[i+1],c=m+1===s.length;break}if(t==="node"&&u==="r"){if(o&&=s==="-r",s==="-r"){let f=e[i+1];if(o&&=f!==void 0&&!f.startsWith("-"),o&&f!==void 0)r.push({tokenIndex:i+1,kind:"module-file",value:f});i++}break}if(t==="ruby"&&u==="r"){let f=s.slice(m+1),p=f||e[i+1];if(o&&=p!==void 0,p!==void 0)r.push({tokenIndex:f?i:i+1,kind:"module-file",value:p});if(!f)i++;break}if(t==="perl"&&(u==="M"||u==="m")){let f=s.slice(m+1);if(!f){if(o=!1,m+1===s.length)i++;break}r.push({tokenIndex:i,kind:"module-file",value:f});break}if(JC.get(t)?.has(u)){if(m+1===s.length)i++;break}if(QC.get(t)?.has(u)&&m+1<s.length)break}if(l===void 0)continue;let d=c?i+1:i;if(n.push({tokenIndex:d,value:l}),r.push({tokenIndex:d,kind:"inline-code",value:l}),t==="python")return Qe(t,n,r,o);if(c)i++}return Qe(t,n,r,o,void 0,void 0,!0)}function Qe(e,t,n,r,o,i,s=!1){let a=e==="node"?t.slice(-1):t,l=new Set(a.map((d)=>d.tokenIndex)),c=n.filter((d)=>d.kind!=="inline-code"||l.has(d.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((d)=>d.value).join(`
|
|
29
|
-
`))||null,sources:r?c:[],optionsOpen:r&&s}}function sb(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 da(e,t){return ma(e)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(t)}function ma(e){let t=k(e).toLowerCase();return vo.test(t)?"python":t}function ab(e,t){return ua.get(e)?.has(t)??!1}function lb(e){return ua.get(e)?.has("--eval")??!1}function Ar(e,t,n=!1){let r=db(e,t);if(!ca(r,t))return!1;Ge(t,r);let o=ub(r);if(ca(o,t))return!0;if(Ge(t,o),!ud.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 d=e.startsWith(c.repeat(3),l)?c.repeat(3):c,m=l+d.length,u=m;while(u<e.length&&!e.startsWith(d,u))u+=e[u]==="\\"?2:1;if(u>=e.length)return!0;o.push({start:m,text:e.slice(m,u)}),r.fill(" ",l,u+d.length),l=u+d.length-1}let i=r.join(""),s=Array.from(i.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((l)=>ud.test(l[1]??"")).map((l)=>{let c=l.index+l[0].length;return{start:c,end:fa(i,c)}});if(s.some((l)=>pa(i,l.start)))return!0;return o.some((l)=>{let c=/\b(?:system|exec|spawn|popen)\s*$/.test(i.slice(0,l.start)),d=s.some((m)=>l.start>=m.start&&l.start<m.end);return(c||d)&&ca(l.text,t)})}function fa(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 pa(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 ud=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function ub(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 ca(e,t){if(Yo(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(Ge(t,e),r.test(e))return!0;if(Yo(e,"dd",t))return!0;for(let r of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(Ge(t,e),r.test(e))return!0;if(Yo(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)=>(Ge(t,e),n.some((o)=>Zo(o,r))))}function db(e,t){return Ge(t,e),e.replace(ob,"")}var di=require("node:fs"),mt=require("node:path");var Tr=require("node:path");var Ht=require("node:path");function Bt(e,t,n){if(St(t))throw Error("Unsupported Windows namespace path");let r=Ht.isAbsolute(t)?Ht.parse(t).root:"",o=r||e;for(let i of fb(r?t.slice(r.length):t)){if(i===""||i===".")continue;if(i===".."){o=Ht.dirname(o);continue}let s=mb(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 mb(e,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${t}`:`${e}${Ht.sep}${t}`}function fb(e){let t=process.platform==="win32"?/[\\/]+/:/\/+/;return e.split(t)}var ga=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],pb=new Set(ga),gb=1024,dd=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),md=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),hb=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ei(e){return pb.has(e)}function ha(e){return ei(e)||dd.has(e)||md.has(e)||lr(e)}function _t(e,t,n){return n?.has(e)?n.get(e):t.get(e)}function fd(e,t){let n=_t("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<=gb?{state:"valid",count:r}:{state:"invalid"}}function ti(e,t,n){let o=e.match(hb)?.[1];if(!o||!ha(o))return null;let i=e.indexOf("=");return{name:o,value:`${_t(o,t,n)??""}${e.slice(i+1)}`}}function pd(e){return hd(e,md)}function gd(e){return hd(e,dd)}function hd(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 Ue(e){if(!Cd.test(e))return null;let t=e.indexOf("=");return{name:e.slice(0,t),value:e.slice(t+1)}}function ni(e){let t=new Map,n=0;while(n<e.length){let r=e[n];if(!r)break;let o=Ue(_(r));if(!o)break;t.set(o.name,o.value),n++}return{words:e.slice(n),envAssignments:t}}function bd(e){let t=M(e);return e.includes("=")||t==="sudo"||t==="env"||t==="command"||t==="builtin"}function an(e,t,n,r){if(!bd(Wn(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 m=0;m<X.wrapperPeelIterations.cap;m++){let u=yd(i),f=ni(i);for(let[g,h]of f.envAssignments)s.set(g,h),a.set(g,h);if(i=f.words,i.length===0)break;while(i.length>0&&Wn(i).includes("=")&&!Cb(i)){let g=bb(Wn(i),a,t.env)??ti(Wn(i),t.env,a);if(g)s.set(g.name,g.value),a.set(g.name,g.value);i=i.slice(1)}if(i.length===0)break;let p=M(Wn(i));if(p!=="sudo"&&p!=="env"&&p!=="command"&&p!=="builtin")break;if(p==="sudo"){let g=vb(i,t.paths,c);if(i=g.words,g.cwd!==void 0)c=g.cwd}if(p==="env"){let g=Rb(i,c,a,t);if(l.push(...g.envSplitValues??[]),i=g.words,g.cwd!==void 0)c=g.cwd;for(let[h,y]of g.envAssignments)s.set(h,y),a.set(h,y)}if(p==="command")i=wb(i);if(p==="builtin")i=i.slice(et(i,1)==="--"?2:1);if(yd(i)===u)break}let d=ni(i);for(let[m,u]of d.envAssignments)s.set(m,u),a.set(m,u);return{words:d.words,envAssignments:s,cwd:c,envSplitValues:l.length>0?l:void 0,rewritten:yb(d.words,o)}}function yb(e,t){return e.some((n)=>!t.has(n))}function yd(e){return e.map(_).join(" ")}function Wn(e){let t=e[0];return t?_(t):""}function et(e,t){let n=e[t];return n?_(n):void 0}function Cb(e){return Cd.test(Wn(e))}function bb(e,t,n){if(!e.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${t.get("TMPDIR")??n.get("TMPDIR")??""}${e.slice(8)}`}}var Sb=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function vb(e,t,n){let r=1,o=n;while(r<e.length){let i=et(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=et(e,r+1);o=s?Pr(o,s,t):null,r+=2;continue}if(i.startsWith("--chdir=")){o=Pr(o,i.slice(8),t),r++;continue}if(i.startsWith("-D")&&i.length>2){o=Pr(o,i.slice(2),t),r++;continue}if(i==="-i"||i==="--login"){o=null,r++;continue}if(Sb.has(i)){r+=2;continue}r++}return{words:e.slice(r),cwd:o}}var Eb=new Set(["-i","-0","--null"]),xb=new Set(["-u","--unset","-C","--chdir","-P"]);function Rb(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=et(e,a);if(!c)break;if(c==="--")return l(a+1);if(c==="-i"||c==="--ignore-environment"||c==="-"){o.clear();for(let m of n.keys())o.set(m,"");o.set("TMPDIR",""),a++;continue}if(Eb.has(c)){a++;continue}if(c==="-u"||c==="--unset"){let m=et(e,a+1);if(m!==void 0)o.set(m,"");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 d=c==="-S"||c==="--split-string"?{value:et(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(d){if(d.value!==void 0)i.push(d.value);return s=null,l(a+d.consumed)}if(xb.has(c)){if(c==="-C"||c==="--chdir"){let m=et(e,a+1);s=m?Pr(s,m,r.paths):null}a+=2;continue}if(c.startsWith("-u=")){a++;continue}if(c.startsWith("-C")&&c.length>2||c.startsWith("--chdir=")){let m=c.startsWith("--chdir=")?c.slice(8):c.startsWith("-C=")?c.slice(3):c.slice(2);s=Pr(s,m,r.paths),a++;continue}if(c.startsWith("-P")){a++;continue}if(c.startsWith("-")){a++;continue}if(!Ue(c))break;while(a<e.length){let m=Ue(et(e,a)??"");if(!m)break;o.set(m.name,m.value),a++}if(et(e,a)==="--")a++;return l(a)}return l(a)}function Pr(e,t,n){if(t==="")return null;if(!e&&!Tr.isAbsolute(t))return null;let r=Tr.isAbsolute(t)?Tr.parse(t).root:n.realpath(e??"/");if(r===null)return null;try{return Bt(r,t,n)}catch{return null}}function wb(e){if(et(e,1)==="-v")return[...J(["type"]),...e.slice(2)];let t=1;while(t<e.length){let n=et(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 _b=/['"\\$`{}#]/;function ri(e,t){if(e.some((r)=>_b.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 $t(e,t,n){return oi(e,t,n).tokens}function Ab(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 Ut(e,t,n,r=0){let o=oi(e,t,n),i=(o.envSplitValues??[]).flatMap(Ab);if(i.length===0)return o.tokens;let s=[...i,...o.tokens];if(r>=8)return s;return Ut(s,t,n,r+1)}function oi(e,t,n,r){if(!bd(e[0]??""))return{tokens:[...e],envAssignments:new Map,cwd:n};let o=an(J(e),t,n,r);return{tokens:o.words.map(_),envAssignments:o.envAssignments,cwd:o.cwd,envSplitValues:o.envSplitValues}}var Sa=Symbol("adopt-as-operand"),Pb=new Set(["env","sudo","command","builtin"]),Tb=new Set(["&&","||","|&","|","&",";"]),kb=new Set(["<<","<<<",">|"]),Ib=new Set(["|","|&"]),Ob=/[*@#?$!_-]/,Mb=/^\w+(?::\w+)*/,Db=Object.freeze([]),kr=Object.freeze({kind:"scope",edge:"enter"}),Ir=Object.freeze({kind:"scope",edge:"exit"}),Nb=Object.freeze([]),Lb=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),Or=new Set(["bash","sh","zsh","dash","ksh"]),Wb=256,Rd=new WeakMap;function wd(e,t){let n=t.status==="complete"?new Set(ba(t)):new Set,r=zb(e,n);if(xo(r))return ii("unclosed-quote",r,t);let o={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},i=ln(t,{source:r,suppressed:n,flags:o,depth:0,functions:new Map,powershell:t.dialect==="powershell"});if(o.limited)return ii("structural-limit",r,t);if(o.invalid)return ii("invalid",r,t);let s=ii("complete",r,t,o.assignmentFallbacks);return Rd.set(s,Object.freeze(i)),s}function ai(e,t,n,r,o){let i=o.word??((m)=>m),s={cwd:t,variables:new Map,previous:null},a=[],l=new Set,c=null,d=[];for(let m of _d(e)){if(m.kind==="scope"){if(m.edge==="enter"){d.push({state:s,segment:[...a],shellWords:new Set(l),pipeProducer:c});continue}let u=o.segment(a,s,c,null,l);if(u)return u;let f=d.pop();if(f===void 0)throw Error("scope exit without a matching enter");s=f.state,a=f.segment,l=f.shellWords,c=f.pipeProducer;continue}if(m.kind==="operator"){if(!m.boundary)continue;let u=o.segment(a,s,c,m.operator,l);if(u)return u;s=Gb(a,s,n,r),c=a.length>0&&Ib.has(m.operator)?a:null,a=[],l=new Set;continue}if(m.kind==="redirection"){if(m.fd!==void 0)l.add(a.length-1);if(m.target===void 0)continue;let u=o.redirection({operator:m.operator,role:m.role,targetOrder:m.targetOrder,target:m.target,...m.body===void 0?{}:{body:m.body,consumer:m.consumer}},s);if(u===Sa){l.add(a.length),a.push(i(m.target));continue}if(u)return u;continue}a.push(i(m.text))}return o.segment(a,s,c,null,l)}function li(e){return _d(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 Ae(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:Ae(i,t);return a?Ae(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 Mr(e){return e.length>0&&e.every((t)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t))}function Gb(e,t,n,r){let o=Mr(e)?new Map([...t.variables,...Fb(e,t.variables)]):t.variables,i=$t([...e],n),s=k(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:he(Ae(s,o),t.cwd,n,r),variables:o,previous:t.cwd}}function Fb(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],Ae(o,t)]]:[]})}function _d(e){return Rd.get(e)??Db}function zb(e,t){return[...t].reduce((n,r)=>n.slice(0,r.start)+" ".repeat(r.end-r.start)+n.slice(r.end),e)}function ii(e,t,n,r=Nb){return Object.freeze({status:e,source:t,program:n,assignmentFallbacks:Object.freeze(r)})}function ln(e,t){return e.nodes.flatMap((n,r)=>Hb(n,e,r,t)).sort((n,r)=>n.start-r.start).flatMap((n)=>[...n.events])}function Hb(e,t,n,r){if(e.kind==="connector")return[{start:e.span.start,events:[tt(Vb(e.operator))]}];if(e.kind==="unknown")return[{start:e.span.start,events:[tt(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?[si("{"),...ln(e.body,a),...s?[si("}")]:[]]:[kr,tt("("),...ln(e.body,a),...s?[tt(")")]:[],Ir]}]}let o=Zb(e,r.functions);if(o){if(r.depth>=zt.maxDepth||++r.flags.expansions>Wb)return r.flags.limited=!0,[];return[{start:e.span.start,events:[...Sd(e,r),si(";"),...ln(o,{...r,depth:r.depth+1}),si(";")]},...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:Pd(n,e,t,!1)})),...e.redirections.map((n)=>({start:n.span.start,events:Bb(n,e,t)}))].sort((n,r)=>n.start-r.start).flatMap((n)=>n.events)}function Bb(e,t,n){let r=e.operator==="<<-"?"<<":e.operator,o=e.target?Pd(e.target,t,n,!0):[],i=o[0],s=i?.kind==="word"?i.text:void 0;return[...e.fd===void 0?[]:[va(String(e.fd))],Object.freeze({kind:"redirection",operator:r,...e.fd===void 0?{}:{fd:e.fd},role:Kb(r),targetOrder:kb.has(r)?"legacy-segment":"immediate",...s===void 0?{}:{target:s},...e.heredoc&&n.suppressed.has(e.heredoc.bodySpan)?{body:e.heredoc.body,consumer:kd(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=[va(s.delimiter),.../[\r\n]/.test(r.source[s.terminatorSpan.end]??"")?[tt(";")]:[]];if(r.suppressed.has(s.bodySpan))return[{start:s.bodySpan.start,events:a}];return[{start:s.bodySpan.start,events:[...Ad(r.source.slice(s.bodySpan.start,s.bodySpan.end),r),...a]}]}),...o.some((i)=>!i.heredoc&&i.target)?$b(t,n,r):[]]}function $b(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:Ad(n.source.slice(r.span.end,e.span.end),n)}]}function Ad(e,t){if(t.depth>=zt.maxDepth)return t.flags.limited=!0,[];let n=Je(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=ln(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 Pd(e,t,n,r){let o=[],i={single:!1,double:!1},s="",a=!1,l=()=>{let c=a&&!r?tt("glob"):s!==""||e.quoted&&o.length===0?va(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 f of ya(c.raw,i,n.flags,n.powershell)){if(typeof f==="string"){l(),o.push(tt(f));continue}s+=f.text,a||=f.glob}continue}let d=t.nested.find((f)=>f.span.start>=c.span.start&&f.span.end<=c.span.end);if(i.double){let f=n.source.slice(c.span.start,c.span.end);s+=ya(f,{single:!1,double:!0},n.flags,n.powershell).map((g)=>typeof g==="string"?g:g.text).join("");let p=d?ln(d,n).filter((g)=>g.kind==="redirection"&&g.body!==void 0):[];if(p.length>0)o.push(kr,...p,Ir);continue}let m=d?ln(d,n):[];if(c.raw.startsWith("`")){s+="${}",l(),o.push(kr,...m,Ir);continue}if(c.raw.startsWith("<(")||c.raw.startsWith(">(")){l(),o.push(c.raw.startsWith("<(")?tt("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),kr,...m,...c.raw.endsWith(")")?[tt(")")]:[],Ir);continue}let u=c.raw.startsWith("$((")?2:1;s+="${}",l(),o.push(...Array.from({length:u},()=>tt("(")),...u===1?[kr]:[],...m,...c.raw.endsWith(")".repeat(u))?Array.from({length:u},()=>tt(")")):[],...u===1?[Ir]:[])}return l(),o}function ya(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=jb(e,t+2);if(a===-1)return r.invalid=!0,{text:"",next:e.length};let l=e.slice(t,a+1);return Ub(l,n,r,o),{text:l,next:a+1}}if(i!==void 0&&Ob.test(i))return{text:`\${${i}}`,next:t+2};let s=(o?Mb:/^\w*/).exec(e.slice(t+1))?.[0]??"";return{text:`\${${s}}`,next:t+1+s.length}}function Ub(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=ya(s.slice(a.length),{...t},n,r);n.assignmentFallbacks.push(...l.flatMap((c)=>typeof c==="string"||!c.text?[]:[c.text]))}function jb(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 Vb(e){return/^[\r\n]+$/.test(e)?";":e}function tt(e){return Object.freeze({kind:"operator",operator:e,boundary:Tb.has(e)})}function si(e){return Object.freeze({kind:"operator",operator:e,boundary:!0})}function va(e){return Object.freeze({kind:"word",text:e})}function Kb(e){if(e==="<<"||e==="<<<")return"here-data";if(e==="<"||e==="<&")return"file-read";return"file-write"}function Dr(e){return Lb.has(e)||/^python\d/.test(e)}var qb=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 Td(e,t){let n=t[0];if(n===void 0||!n.startsWith("-"))return t;let r=qb.get(e)?.has(n)??!1;return Td(e,t.slice(r?2:1))}function Ca(e){let t=e[0];if(t===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(t))return Ca(e.slice(1));if(!Pb.has(t))return[...e];return Ca(Td(t,e.slice(1)))}function kd(e){let t=Cr(e),n=e.words.findIndex((r)=>r.provenance==="literal"&&r.text===t);return Ca(n<0?[]:e.words.slice(n).map((r)=>r.text))}function Yb(e){let t=kd(e)[0];if(t===void 0)return!1;let n=k(t).toLowerCase();return Dr(n)&&!Or.has(n)}function ba(e){return e.nodes.flatMap((t,n)=>{if(t.kind==="group"||t.kind==="function")return ba(t.body);if(t.kind!=="command")return[];let r=t.nested.flatMap((a)=>ba(a)),o=t.redirections.flatMap((a)=>a.heredoc?.quotedDelimiter?[a.heredoc.bodySpan]:[]);if(Yb(t))return[...r,...o];let i=e.nodes[n+1];if(i?.kind==="connector"&&(i.operator==="|"||i.operator==="|&")||!Jb(t))return r;return[...r,...o]})}function Zb(e,t){let n=Cr(e);return n===void 0?void 0:t.get(n)}function jt(e,t){return e!==void 0&&e.provenance==="literal"&&!e.quoted&&e.raw===e.text&&e.text===t}function Xb(e){if(jt(e.words[0],"git"))return jt(e.words[1],"commit");if(!jt(e.words[0],"gh")||!jt(e.words[2],"create"))return!1;return jt(e.words[1],"pr")||jt(e.words[1],"issue")}function Jb(e){return(jt(e.words[0],"cat")||jt(e.words[0],"tee")||Xb(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 Id=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Od=new Set([...Id,"glob"]),Qb=new Set([...Od,"pattern"]);class nt extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Nr(e){let t=eS(),n=Lt(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((d)=>d.source===s.source);if(a!==-1){let d=i[a];if(!d)return i;return i[a]={...d,usages:[...d.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:tS(e),store:t}}function Pe(e,t){return e.commands.find((n)=>n.usages.includes(t))}function At(e,t){if(!e.includes("$"))return e;return ns(e,t)}function eS(){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=Je(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 d=n.get(a);if(d)return d;let m={status:"structural-limit",source:i,program:a,assignmentFallbacks:[]};return n.set(a,m),m}let l=e.get(i);if(l)return l;let c=wd(i,a);return e.set(i,c),c},getCommandProgram:r}}function tS(e){let t=e.route.kind==="grep"?Od:e.route.kind==="glob"?Qb:Id;return[...co(e.input,t),...e.route.kind==="patch"?uo(e.input):[]]}var nS=new Set(["-S","--suffix"]);function Gn(e,t,n,r,o){if(e.status==="structural-limit")throw new nt;if(e.status!=="complete")return o.findMalformedTarget(e.source);return ai(e,t,n,r,{segment:(i,s)=>o.findSegmentTarget(i,s),redirection:(i,s)=>i.role==="file-write"&&o.isRedirectionTarget(Ae(i.target,s.variables),s)?i.target:null})}function ci(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&&nS.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 je="Git metadata and hooks are protected. Ask the user before modifying them.";function Dd(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(lo(e.invocation.toolName))return null;let a=e.paths.find((l)=>Md(l,o,t,n,r,t.entries));return a?{target:a}:null}if(e.invocation.route.kind!=="command")return null;let i=Pe(e,"input-candidate");if(!i)return null;let s=Gn(i.shell,o,n,r,{findSegmentTarget:(a,l)=>lS(a,l,t,n,r),isRedirectionTarget:(a,l)=>Md(a,l.cwd,t,n,r,t.markerFiles),findMalformedTarget:()=>null});return s?{target:s}:null}function cn(e,t,n,r,o,i,s=!1){if(!n)return!1;let a=mi(he(e,t,o,i)),l=a.replace(/(\/\.?\*+)+$/,"");if(l!==a&&l!==""){if(Ea(l,n))return!0;let c=s||a.slice(l.length).includes("/."),d=(m)=>c?ui(m,l):rS(m,l);if(n.markerFiles.some(d))return!0;return r&&xa(n).some(d)}if(Ea(a,n))return!0;return r&&xa(n).some((c)=>ui(c,a))}function rS(e,t){let n=mt.relative(t,e);if(n===""||n.startsWith("..")||mt.isAbsolute(n))return!1;return!n.split(/[\\/]/)[0]?.startsWith(".")}function oS(e,t,n,r,o){return cn(e,t,n,!0,r,o)}function iS(e,t,n,r,o){if(!n)return!1;return Ea(mi(he(e,t,r,o)),n)}function Md(e,t,n,r,o,i){let s=mi(he(e,t,r,o));return i.includes(s)||Ld(s,n)}function Nd(e,t,n,r,o){if(!n)return!1;return n.hooksDirectories.some((i)=>e.some((s)=>ui(i,mi(he(s,t,r,o)))))}function Ea(e,t){return t.entries.includes(e)||t.directories.includes(e)||Ld(e,t)}function Ld(e,t){return t.hooksDirectories.some((n)=>ui(e,n))}var sS=50000;function Wd(e,t){let n=[...new Set(xa(e))];if(n.some((o)=>t(mt.basename(o))))return!0;let r=0;while(n.length>0){let o=n.pop()??"",i=aS(o);if(!i)return!0;if(r+=i.length,r>sS)return!0;if(i.some((s)=>t(s.name)))return!0;n.push(...i.filter((s)=>s.isDirectory()).map((s)=>mt.join(o,s.name)))}return!1}function aS(e){try{let t=di.lstatSync(e,{throwIfNoEntry:!1});if(!t)return[];if(!t.isDirectory())return t.isSymbolicLink()?null:[];return di.readdirSync(e,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function xa(e){return[...e.entries,...e.directories,...e.hooksDirectories]}function ui(e,t){let n=mt.relative(t,e);return n===""||!/^\.\.(?:[\\/]|$)/.test(n)&&!mt.isAbsolute(n)}function mi(e){return process.platform==="win32"?e.toLowerCase():e}function lS(e,t,n,r,o){if(Mr(e))return null;let i=Ut([...e],r);if(k(i[0]??"").toLowerCase()!=="mv")return null;let s=ci(i.slice(1)),a=s.sources.find((l)=>oS(Ae(l,t.variables),t.cwd,n,r,o));if(a)return a;return s.destination&&iS(Ae(s.destination,t.variables),t.cwd,n,r,o)?s.destination:null}var Y=require("node:path");var Fe=require("node:path"),cS=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],uS=`
|
|
30
|
-
`;function Lr(e,t){if(Vt(e,t))return!0;if(!e.has("TMPDIR"))return!1;return!Ra(e.get("TMPDIR")??"",t)}function un(e,t){if(e.has("TMPDIR"))return Ra(e.get("TMPDIR")??"",t);let n=wa(e,t);if(n===void 0)return!0;return Ra(n,t)}function wa(e,t){return zd(e,t,"TMPDIR")}function Ra(e,t){if(!e)return!1;if(mS(e))return!1;return Fn(e,t)}function Vt(e,t){let n=zd(e,t,"IFS");return n!==void 0&&n!==""&&n!==uS}function Fn(e,t){let n=fi(e,t.paths);if(n===null)return!1;return Fd(t).some((r)=>zn(n,r))}function gi(e,t){let n=fi(e,t.paths);if(n===null)return!1;return Fd(t).some((r)=>pi(r)===pi(n))}var Gd=new WeakMap;function Fd(e){let t=Gd.get(e);if(t)return t;let n=dS(e);return Gd.set(e,n),n}function dS(e){let t=cS.map((r)=>fi(r,e.paths)??Fe.normalize(r)),n=fi(e.tmpdir,e.paths);if(!n)return t;if(process.platform==="win32")return[...t,n];if(process.platform==="darwin"&&fS(n))return[...t,n];return t}function mS(e){return/[\s$`*?[]/.test(e)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(e)||/[+@!]\([^)]*\)/.test(e)}function zd(e,t,n){return e.has(n)?e.get(n):t.env.get(n)}function fS(e){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(e)}function fi(e,t){try{let n=Fe.normalize(e);if(!Fe.isAbsolute(n))return n;let r=Fe.parse(n).root,o=n.slice(r.length).split(/[\\/]+/).filter(Boolean),i=r;for(let s=0;s<o.length;s++){let a=Fe.join(i,o[s]??"");if(t.entryKind(a)==="missing")return Fe.join(a,...o.slice(s+1));let l=t.realpath(a);if(l===null)return null;i=l}return i}catch{return null}}function zn(e,t){let n=pi(e),r=pi(t);if(n===r)return!0;let o=r.endsWith(Fe.sep)?r:`${r}${Fe.sep}`;return n.startsWith(o)}function pi(e){return process.platform==="win32"?e.toLowerCase():e}var pS=process.platform==="win32",Hd=64,gS=16384;function Wr(e,t,n,r){if(e.kind==="temp_target")return null;let o=r[e.kind];if(e.kind==="dynamic_target"&&!me(n,o.id,t.strict))return null;if(e.kind==="within_anchored_cwd"&&!me(n,o.id,t.paranoid))return null;return v(o.id,o.reason)}function Gr(e){let t=Fu(e,Hd,Hd,gS);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:hS(e)}}function hS(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)=>yS(e.raw,n.span.start-e.span.start))}function yS(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 Kt(e){let t=e.environment.home,n=e.environment.paths,r=e.budget??ue();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:xS(e.allowPaths,t,n,r),protectedGitMetadata:e.protectedGitMetadata,budget:r}}function rt(e,t,n={}){let r=n.targetIsLiteral??!1;if(!r&&t.tmpdirWordSplittingUnsafe&&!n.tmpdirWordSplittingProtected&&wS(e))return{kind:"outside_anchored_cwd"};let o=!r&&$d(e,t.posixShell);if(St(e))return{kind:"outside_anchored_cwd"};if(Aa(e,r))return{kind:"root_or_home_target"};if(bS(e,t,r))return{kind:"root_or_home_target"};if(t.resolvedCwd&&cn(e,t.resolvedCwd,t.protectedGitMetadata,!0,t.environment,t.budget,!t.posixShell))return{kind:"git_metadata_target"};if(SS(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(RS(e,t,r))return{kind:"temp_target"};let i=t.anchoredCwd;if(i){if(!n.skipHomeCwd&&TS(i,t.environment.home,t.environment.paths,t.budget))return{kind:"home_cwd_target"};if(!n.skipCwdSelf&&[t.resolvedCwd??i,i].some((s)=>kS(e,t.resolvedCwd??i,t.environment.paths,t.budget,s)))return{kind:"cwd_self_target"};if(IS(e,i,t.resolvedCwd??i,o,r,t.environment.paths,t.budget))return{kind:"within_anchored_cwd"}}if(CS(e,t,o))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function CS(e,t,n){let r=e.trim();if(n||!t.resolvedCwd||!t.anchoredCwd||!r)return!1;if(Y.isAbsolute(r)||r.startsWith("~"))return!1;if(Pa(r))return!1;if(Ud(t.resolvedCwd,t.anchoredCwd,t.environment.paths,t.budget))return!1;return Fn(Y.resolve(t.resolvedCwd,r),t.environment)}function Bd(e,t,n={}){let{containmentTarget:r,...o}=n;if(rt(e,t,o).kind!=="temp_target")return!1;let i=e.trim();if(ES(i))return!1;if(gi(i,t.environment))return!1;return![t.anchoredCwd,t.resolvedCwd].some((s)=>Ud(r??i,s,t.environment.paths,t.budget))}function Aa(e,t=!1){let n=e.trim(),r=Y.posix.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=Y.isAbsolute(o)?o:t.resolvedCwd?Y.resolve(t.resolvedCwd,o):null;if(!i)return!1;let s=Te(O(i,t.environment.paths,t.budget));if(s===Y.parse(s).root)return!0;return s===Te(O(t.environment.home,t.environment.paths,t.budget))}catch{return!1}}function Te(e){let t=Y.normalize(e);if(pS){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 SS(e,t,n,r,o,i,s,a){let l=e.trim();if(Pa(l))return!1;if(!r&&Fn(l,a))return!0;return(t||i&&s)&&n&&!o&&vS(l,n)}function vS(e,t){return["$TMPDIR","${TMPDIR}"].some((n)=>{if(e===n)return!0;if(!e.startsWith(`${n}/`))return!1;return!$d(e.slice(n.length+1),t)})}function ES(e){let t=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(e);if(!t)return!1;return Y.posix.normalize(`/${t[1]??""}`)==="/"}function Pa(e){return e.split(/[\\/]+/).includes("..")}function xS(e,t,n,r){if(!e?.length)return[];return e.flatMap((o)=>{let i=gr(o.trim(),t);if(!Y.isAbsolute(i))return[];try{let s=O(i,n,r);if(hr(s,O(t,n,r)))return[];return[Te(s)]}catch{return[]}})}function RS(e,t,n){if(t.allowRoots.length===0)return!1;let r=e.trim();if(Pa(r))return!1;let o=n?r:gr(r,t.environment.home),i=t.resolvedCwd??t.anchoredCwd,s=Y.isAbsolute(o)?o:i?Y.resolve(i,o):null;if(!s)return!1;try{let a=Te(O(s,t.environment.paths,t.budget));return t.allowRoots.some((l)=>a===l||a.startsWith(l.endsWith(Y.sep)?l:`${l}${Y.sep}`))}catch{return!1}}function wS(e){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(e)}function $d(e,t=!1){return e.includes("$")||e.includes("`")||_S(e)||t&&AS(e)}function _S(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 AS(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==="{"&&PS(e,n)||(r==="+"||r==="@"||r==="!")&&e[n+1]==="(")return!0}return!1}function PS(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 TS(e,t,n,r){try{return Te(O(e,n,r))===Te(O(t,n,r))}catch{try{return Te(e)===Te(t)}catch{return!1}}}function kS(e,t,n,r,o=t){if(o===t&&(e==="."||e==="./"||e===".\\"))return!0;try{return Te(O(Y.resolve(t,e),n,r))===Te(O(o,n,r))}catch{try{return Te(Y.resolve(t,e))===Te(o)}catch{return!1}}}function IS(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 _a(e,t,i,s)}catch{return!1}if(e.startsWith("./")||e.startsWith(".\\")||!e.includes("/")&&!e.includes("\\"))try{return _a(Y.resolve(a,e),t,i,s)}catch{return!1}if(e.startsWith("../"))return!1;try{return _a(Y.resolve(a,e),t,i,s)}catch{return!1}}function _a(e,t,n,r){try{return jd(O(e,n,r),O(t,n,r))}catch{return!1}}function Ud(e,t,n,r){if(!t)return!1;try{return jd(O(t,n,r),O(e,n,r))}catch{return!0}}function jd(e,t){let n=Te(e),r=Te(t);return n.startsWith(`${r}${Y.sep}`)||n===r}var OS=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),Vd="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",MS="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.",Kd="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",qd="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",DS="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",NS="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",LS={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:qd},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:je},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:Kd},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:DS},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:Vd},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:MS},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:Vd}};function Yd(e,t,n,r=Kt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths})){return WS(e.words.map((o)=>({kind:"word",text:o.text,dynamic:o.provenance!=="literal"})),t,r,n.policy)}function WS(e,t,n,r){let o=e.filter((l)=>l.kind==="word"),i=FS(o),s=o[i];if(!s||!OS.has(qS(s.text)))return null;let a=GS(o.slice(i+1));if(a.whatIfProtected)return null;if(me(r,"powershell.remove-item-pipeline-dynamic-target",n.strict)&&t&&(a.targets.length===0||a.recursive))return v("powershell.remove-item-pipeline-dynamic-target",NS);for(let l of a.targets)if(!St(l.text)&&Aa(ka(l.text)))return v(a.recursive&&a.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",qd);for(let l of a.targets)if(n.resolvedCwd&&cn(ka(l.text),n.resolvedCwd,n.protectedGitMetadata,a.recursive,n.environment,n.budget,!0))return v("powershell.remove-item-git-metadata",je);if(!a.recursive||!a.force)return null;if(me(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",Kd);for(let l of a.targets){let c=Wr(rt(ka(l.text),n),n,r,LS);if(c)return c}return null}function GS(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(zS(l))continue;if(s){t.push(Ta(l)),i=i||l.dynamic;continue}if(l.text==="--"){s=!0;continue}let c=BS(l.text);if(!c){t.push(Ta(l)),i=i||l.dynamic;continue}if($S(c.name)){let d=c.value?HS(c.value,l):e[++a];if(d?.kind==="word"){t.push(Ta(d)),i=i||d.dynamic;continue}i=!0;continue}if(US(c.name)){n=!0;continue}if(jS(c.name)){r=!0;continue}if(VS(c.name))o=KS(c.value)}return{targets:t,recursive:n,force:r,whatIfProtected:o,hasDynamicTarget:i}}function FS(e){let t=e[0];if(t?.kind==="word"&&t.text==="&"||t?.text===".")return e.length>1?1:0;return 0}function Ta(e){return{text:e.kind==="word"?e.text:"",dynamic:e.kind==="word"&&e.dynamic}}function zS(e){return e.kind==="word"&&e.text===","}function ka(e){let t=e.replace(/\\/g,"/"),n=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(t);return n?`$HOME${t.slice(n[0].length)}`:t}function HS(e,t){return{kind:"word",text:e,dynamic:t.kind==="word"&&(t.dynamic||e.includes("$"))}}function BS(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 $S(e){return"path".startsWith(e)||"literalpath".startsWith(e)}function US(e){return"recurse".startsWith(e)}function jS(e){return e.length>=2&&"force".startsWith(e)}function VS(e){return e==="wi"||"whatif".startsWith(e)}function KS(e){if(e===void 0||e==="")return!0;let t=e.toLowerCase();return t==="$true"||t==="true"}function qS(e){return e.toLowerCase()}var Hn="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",hi="Unsupported heredoc syntax",Fr="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.",Zd="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var YS=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),ZS=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),XS=new Set(["-o","--output","--query","--subscription"]),JS=new Set;function Xd(e){if(e==="aws")return YS;if(e==="gcloud")return ZS;if(e==="az")return XS;return JS}var QS=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),ev=new Set;function Jd(e){if(e==="git")return De;if(e==="docker")return QS;return ev}function Pt(e,t){if(e.length===0||t.length===0)return null;let n=M(e[0]??""),r=we(e);for(let o of t){if(!rv(n,o.command))continue;if(o.match){if(tv(n,e,o.match))return Qd(o);continue}if(!ov(n,e,o.subcommand))continue;if(sv(e,new Set(o.block_args),r))return Qd(o)}return null}function Qd(e){return{id:`custom.${e.name}`,reason:`[${e.name}] ${e.reason}`,intent:e.intent??"manual_only"}}function tv(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 nv(r,n.command_path,Xd(e))}function nv(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 rv(e,t){return e===M(t)}function ov(e,t,n){if(!n)return!0;return em(t,1,n,Jd(e))}function em(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("=")&&iv(e,i,n,r))return!0;continue}return s===n}return!1}function iv(e,t,n,r){let o=e[t+1];if(!o||o.startsWith("-"))return!1;return em(e,t+2,n,r)}function sv(e,t,n){return e.some((r)=>t.has(r))||[...n].some((r)=>t.has(r))}var av=new Set(["-e","--source"]),lv=new Set(["-F","-v","--assign","--field-separator"]),tm=new Set(["-f","--file"]),cv=new Set(["print","printf","return"]),nm=[{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"}],uv="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 rm(e,t,n){let r=!1;for(let o of dv(e)){let i=mv(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",uv):null}function Oa(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&&av.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&&(lv.has(a)||tm.has(a))){let l=e[s+1];if(i&&=l!==void 0,tm.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 Hr(e){return Oa(e).sources}function dv(e){return Hr(e).filter((t)=>t.kind!=="program-file").map((t)=>t.value)}function mv(e,t){Ge(t,e);let n=e.includes("system")?Ma(e,t):null,r=fv(e,t);if(!n&&!r)return null;return{dynamic:!!n?.dynamic||!!r?.dynamic,commands:[...n?.commands??[],...r?.commands??[]]}}function Ma(e,t){Ge(t,e);let n=[],r=!1,o=!1,i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){i=Ci(e,i,s)?.endIndex??i+1;continue}if(s==="#"){i=om(e,i+1);continue}if(s==="/"&&im(e,i)){i=sm(e,i+1)??i+1;continue}if(!e.startsWith("system",i)){i++;continue}let a=i;if(i+=6,zr(e[a-1])||zr(e[i]))continue;let l=yi(e,i);if(e[l]!=="(")continue;l=yi(e,l+1);let c=e[l];if(c!=='"'&&c!=="'"){r=!0,o=!0;continue}let d=Ci(e,l,c);if(!d){r=!0,o=!0;continue}if(l=yi(e,d.endIndex),r=!0,e[l]!==")"){o=!0,i=d.endIndex;continue}n.push(d.value),i=l+1}if(!r)return null;return{dynamic:o,commands:n}}function fv(e,t){Ge(t,e);let n=[],r=!1,o=!1,i=0,s=0,a=null,l=null,c=0;while(i<e.length){let d=e[i];if(!d)break;if(d==='"'||d==="'"){let f=Ci(e,i,d);if(f&&c===s)l={...f,startIndex:i};c=f?.endIndex??i+1,i=f?.endIndex??i+1;continue}if(d==="#"){i=om(e,i+1),s=i,a=null,l=null,c=i;continue}if(d==="/"&&im(e,i)){let f=sm(e,i+1);c=f??i+1,i=f??i+1;continue}if(`;
|
|
31
|
-
{}`.includes(
|
|
32
|
-
}#`.includes(r)}function Ci(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=
|
|
33
|
-
`,r:"\r",t:"\t",v:"\v"}[n]??n,endIndex:t}}function
|
|
34
|
-
`,t);return n===-1?e.length:n+1}function im(e,t){let n=bv(e,t);if(n===-1)return!0;if("{([,;!~=".includes(e[n]??""))return!0;let r=n;while(zr(e[r-1]))r--;return cv.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 sm(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 Sv=new Set(["sudo","env","command","builtin"]);function bi(e,t){let n=e[0];if(!n||!t.transparentWrappers.includes(k(n)))return null;let r=k(n),o=e[1]==="--"?2:1,i=vv(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 vv(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=k(a)!==n&&Ev(a,r);if(l)i.push(s);if(!l&&Eo.has(M(a)))break;if(o)break}return i}function Ev(e,t){let n=k(e),r=M(e);return r==="git"||n==="busybox"||dn(e)||vs.has(n)||t.transparentWrappers.includes(n)||Q.has(r)||e==="$SHELL"||Xe(r)||Be.has(r)||t.rules.some((o)=>o.command===n)}function dn(e){return Sv.has(e.toLowerCase())}function mn(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 ot(e,t){let n=t.policy??{rules:[],transparentWrappers:[]};return Si([...e],t.environment,t.cwd,t.cwd,new Map,new Map(t.envAssignments??[]),n,{iterations:0},!1)}function*Si(e,t,n,r,o,i,s,a,l){let c=oi(e,t,n,i);for(let[f,p]of c.envAssignments)i.set(f,p),o.set(f,p);let{tokens:d,cwd:m}=c;if(c.envSplitValues){let f=ri(c.envSplitValues,d);if(!f)throw new N("derivedCommandShape");Da(a),yield*Si(f,t,m,r,o,i,s,a,l);return}if(dn(d[0]??""))throw new N("wrapperPeelIterations");let u=bi(d,s);if(u){for(let f of[u.childIndex,...u.alternativeChildIndices])Da(a),yield*Si(f===u.childIndex?u.tokens:d.slice(f),t,m,r,new Map(o),new Map(i),s,a,!0);return}if(Rv(d)){Da(a),yield*Si(d.slice(1),t,m,r,o,i,s,a,l);return}yield xv(d,m,r,o,i,l)}function xv(e,t,n,r,o,i){return{tokens:e,cwd:t===null?void 0:t??n,wrapperCwd:t,wrapperEnvAssignments:r,envAssignments:o,head:k(e[0]??"").toLowerCase(),wrappedByTransparent:i}}function Da(e){if(e.iterations>=X.wrapperPeelIterations.cap)throw new N("wrapperPeelIterations");e.iterations++}function Rv(e){return k(e[0]??"").toLowerCase()==="busybox"&&e.length>1}function Na(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 it(e){let t=!1,n=!1;for(let r of e){if(r==="--")break;if(r==="-r"||r==="-R"||La(r,"recursive")){t=!0;continue}if(r==="-f"||La(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 vi(e){let t=e.indexOf("--");return e.slice(1,t===-1?void 0:t).some((n)=>La(n,"recursive")||/^-[A-Za-z]+$/.test(n)&&/[rR]/.test(n.slice(1)))}function La(e,t){return e.length>2&&e.startsWith("--")&&t.startsWith(e.slice(2))}var wv=["--init-file","--rcfile"],_v=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function st(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n)continue;if(n==="-c")return am(e,t,!0);if(n.startsWith("-")&&n.includes("c")&&!n.startsWith("--")){let r=am(e,t,!1);if(r!==null)return r}}return null}function Tt(e){let t=k(e[0]??"").toLowerCase();if(t==="zsh"||t==="ksh")return Ne(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 am(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 lm(e){let t=k(e[0]??"").toLowerCase(),n=Av(e,t),r=_v.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 Av(e,t){let n=Ne(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?wv.find((u)=>l===u):void 0){let u=e[a+1];o.push(u===void 0?{kind:"absent"}:{kind:"literal",value:u}),a++;continue}let m=l.split("=",1)[0]??l;if(t==="bash"&&bs.has(m)&&!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 Pv="find -delete permanently removes files. Use -print first to preview.",Tv="find -exec rm -rf is dangerous. Use explicit file list instead.",kv=new Set(["-exec","-execdir","-ok","-okdir"]),Iv=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 cm(e,t){let n=e.map(_),r=Ov(e,n,t);if(r)return r;if(Ei(n,1)&&!Gv(e,n,t)){let s=T(v("find.delete",Pv),t.policy);if(s)return s}let o=t.budget??ue(),i=0;while(i<n.length){let s=n[i],a=kt(s??"");if(a>0){i+=a+1;continue}if(!ft(s)){i++;continue}o.charge("derivedTokens",n.length-i-1);let l=Bn(n,i);i=l.nextIndex;let c=zv(l.tokens,t.environment);if(c){let f=T(c,t.policy);if(f)return f}let d=s==="-execdir"||s==="-okdir",m=t.analyzeTokens?t.analyzeTokens(l.tokens,d?null:t.cwd):t.analyzeNested?t.analyzeNested(l.tokens.join(" "),{effectiveCwd:d?void 0:t.cwd,envAssignments:t.envAssignments}):null,u=m?.id.startsWith("custom.")?m:T(m,t.policy);if(u)return u}return null}function Ov(e,t,n){if(!Ei(t,1)&&!Wa(t,n.environment))return null;let o=Br(e)??J(["."]),i=Kt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let s of o){let a=Gr(s);for(let l of a.expandedTargets??[_(s)]){let c=rt(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"&&!Mv(e,i.protectedGitMetadata,n.environment))return v("find.delete-git-metadata",je)}}if(Wv(t)&&i.resolvedCwd&&Nd(o.map(_),i.resolvedCwd,i.protectedGitMetadata,i.environment,i.budget))return v("find.delete-git-metadata",je);return null}function Mv(e,t,n){if(!t)return!1;let r=e.map(_),o=[],i=!1,s=Br(e)?.at(-1),a=s?e.indexOf(s)+1:1;while(a<r.length){let l=r[a]??"";if(ft(l)){let c=Bn(r,a),d=Ut([...c.tokens],n),m=vi(d),u=Q.has(k(d[0]??"").toLowerCase()),f=c.tokens.some((g)=>g!=="{}"&&g.includes("{}")),p=(l==="-execdir"||l==="-okdir")&&d.slice(1).some((g)=>g!=="{}"&&!g.startsWith("-"));if(m||u||f||p)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(Nv(c.text,l==="-iname"));a+=2;continue}if(!Dv.has(l))return!1;a+=1+kt(l)}return o.length>0&&!Wd(t,(l)=>o.every((c)=>c.test(l)))}var Dv=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function Nv(e,t){let n=e.replace(/[*?]|[.+^${}()|\]/]/g,(r)=>r==="*"?".*":r==="?"?".":`\\${r}`);return new RegExp(`^${n}$`,t?"isu":"su")}var Lv=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function Wa(e,t){let n=0;while(n<e.length){if(!ft(e[n])){n++;continue}let r=Bn(e,n),o=Ut([...r.tokens],t),i=k(o[0]??"").toLowerCase(),s=Q.has(i)&&Lv.test((st(o)??"").replace(/["'\\]/g,""));if((i==="rm"||i==="rmdir"||s)&&o.some((l)=>l.includes("{}")))return!0;n=r.nextIndex}return!1}function Wv(e){return e.some((t,n)=>{if(!["-name","-iname"].includes(t))return!1;return e[n+1]?.toLowerCase()==="hooks"})}function Gv(e,t,n){if(t.includes("-L")||t.includes("-f")||t.includes("-follow"))return!1;let r=Br(e);if(!r)return!1;let o=n.envAssignments??new Map,i=wa(o,n.environment),s=n.trustedTmpdirValue??un(o,n.environment),a=n.allowTmpdirVar??!Lr(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??Vt(o,n.environment),trustedTmpdirValue:s,budget:n.budget},c=Kt(l),d=Kt({...l,cwd:n.originalCwd??n.cwd}),m=n.originalCwd&&n.environment.paths.realpath(n.originalCwd),u=n.cwd&&n.environment.paths.realpath(n.cwd),f=m&&u&&!zn(u,m)?n.cwd:void 0;return r.every((p)=>{let g=Gr(p);if(g.unsafeBraceExpansion)return!1;return(g.expandedTargets??[_(p)]).every((h)=>{let y=/^\.\/*$/.test(h)?f:void 0,S=y??h;return Bd(S,y?d:c,{containmentTarget:Fv(S,i),targetIsLiteral:g.expandedTargets!==void 0||g.targetIsLiteral,tmpdirWordSplittingProtected:g.tmpdirWordSplittingProtected})})})}function Fv(e,t){if(!t)return e;return e.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>t)}function Br(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 zv(e,t){let n=$t([...e],t);if(n.length===0)return null;let r=k(n[0]??"");if(r==="busybox"&&n.length>1)n=n.slice(1),r=k(n[0]??"");if(r==="rm"&&it(n))return v("find.exec-rm-recursive-force",Tv);return null}function Bn(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 Ei(e,t){let n=t;while(n<e.length){let r=e[n];if(!r){n++;continue}if(ft(r)){n=Bn(e,n).nextIndex;continue}let o=kt(r);if(o>0){n+=o+1;continue}if(r==="-delete")return!0;n++}return!1}function kt(e){return Iv.get(e)??(/^-newer[A-Za-z]{2}$/.test(e)?1:0)}function ft(e){return e!==void 0&&kv.has(e)}var Mm=require("node:path");function $r(e){let t=Je(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 Hv=5,Ga="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 pe(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 dm(e,t,n){let r=xi(e,t,n),o=Bv(r.entries);if(o.size===0)return{blockedReason:r.blockedReason,expanded:!1,tokens:e};let i=e,s=!1;for(let a=0;a<Hv;a++){let{subcommand:l,rest:c}=ze(i),d=l?.toLowerCase();if(!d||!o.has(d))return{blockedReason:r.blockedReason,expanded:s,tokens:i};let m=o.get(d),u=Kv(m);if(u===null||u.length===0)return{blockedReason:Ga,expanded:!0,tokens:i};i=["git",...u,...c],s=!0}return{blockedReason:Ga,expanded:!0,tokens:i}}function mm(e,t,n){return xi(e,t,n).entries.some((r)=>r.key.toLowerCase()==="core.sshcommand")}function ze(e){if(e.length===0)return{subcommand:null,rest:[]};let t=e[0];if((t?k(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+=De.has(o)?2:1}return{subcommand:null,rest:[]}}function Bv(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 xi(e,t,n){if(e.length===0)return{blockedReason:null,entries:[]};let r=e[0];if((r?k(r).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let i=Uv(t,n);return{blockedReason:i.blockedReason,entries:[...i.entries,...$v(e,t,n)]}}function $v(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=Fa(e[o+1]);if(s)r.push(s);o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=Fa(i.slice(2));if(s)r.push(s);o++;continue}if(i==="--config-env"){let s=um(e[o+1],t,n);if(s)r.push(s);o+=2;continue}if(i.startsWith("--config-env=")){let s=um(i.slice(13),t,n);if(s)r.push(s);o++;continue}if(De.has(i)){o+=2;continue}o++}return r}function Uv(e,t){let n=jv(e,t),r=Vv(e,t);return{blockedReason:n===null||r===null?Ga:null,entries:[...n??[],...r??[]]}}function jv(e,t){let n=_t("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=Fa(i);if(!s)return null;r.push(s)}return r}function Vv(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=_t(`GIT_CONFIG_KEY_${o}`,e,t)?.trim(),s=_t(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i||s===void 0)return null;r.push({key:i,value:s})}return r}function Fa(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 um(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;return{key:e.slice(0,r).trim(),value:_t(e.slice(r+1),t,n)}}function Kv(e){let t=e?.trimStart();if(!t||t.startsWith("!"))return null;return $r(t)}var qv="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",Yv="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",Zv="git checkout --force discards uncommitted changes. Use 'git stash' first.",Xv="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",Jv="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",Qv="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",eE="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",tE="git switch --force discards uncommitted changes. Use 'git stash' first.",nE="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",rE="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",oE="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",iE="git reset --merge can lose uncommitted changes. Use 'git stash' first.",sE="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",aE="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.",lE="git push --force destroys remote history. Use --force-with-lease for safer force push.",cE="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",uE="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",dE="git branch -D force-deletes without merge check. Use -d for safe delete.",mE="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",fE="git merge --abort discards merge conflict resolutions. Use 'git status' first.",pE="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",gE="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",hE="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",yE="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",CE="git worktree remove --force can delete uncommitted changes. Remove --force flag.",bE=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),SE=new Set(["--recurse-submodules","--track","-t"]),za=new Set(["-b","-B","-U"]),Ha=new Set(["-c","-C"]),vE=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function D(e,t){let n=e.split("=",1)[0]??e;return n.length>=4&&t.startsWith(n)&&n.startsWith("--")&&n.slice(2).length>=2}var $n=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function pm(e,t){let{subcommand:n,rest:r}=ze(e);if(!n)return null;switch(n.toLowerCase()){case"checkout":return qt(EE(r,t));case"switch":return qt(RE(r));case"restore":return qt(_E(r));case"reset":return PE(r);case"clean":return qt(kE(r));case"rm":return qt(IE(r));case"push":return fn(OE(r));case"branch":return fn(NE(r));case"stash":return fn(zE(r));case"worktree":return fn(HE(r));case"rebase":return qt(LE(r));case"merge":return qt(WE(r));case"tag":return fn(GE(r));case"reflog":return fn(FE(r));default:return null}}function qt(e){return e?{...e,localDiscard:!0}:null}function fn(e){return e?{...e,localDiscard:!1}:null}function EE(e,t){let{index:n,before:r}=pe(e),o=we(r,{shortOptsWithValue:za});if(r.some((a)=>D(a,"--force"))||o.has("-f"))return v("git.checkout-force",Zv);for(let a of e){if(a==="-b"||a==="-B"||a==="--orphan")return null;if(D(a,"--pathspec-from-file"))return v("git.checkout-pathspec-from-file",Jv)}if(n!==-1){if(r.some((l)=>!l.startsWith("-")))return v("git.checkout-ref-path",Xv);return v("git.checkout-double-dash",qv)}let i=wE(e);if(i.length>=2)return v("git.checkout-ambiguous",Qv);let s=i[0];if(s===void 0||o.has("-d")||o.has("-t")||e.some((a)=>D(a,"--detach")||D(a,"--track")))return null;if(xE(s)||t(s))return v("git.checkout-double-dash",Yv);return null}function xE(e){return e==="."||e===".."||/^\.\.?[/\\]/.test(e)||/^([/\\]|[A-Za-z]:[/\\])/.test(e)||e.endsWith("/")||e.startsWith(":")||/[*?[]/.test(e)}function RE(e){let{before:t}=pe(e);if(t.some((r)=>D(r,"--discard-changes")))return v("git.switch-discard-changes",eE);let n=we(t,{shortOptsWithValue:Ha});if(t.some((r)=>D(r,"--force"))||n.has("-f"))return v("git.switch-force",tE);return null}function wE(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(bE.has(r)){n+=2;continue}if(SE.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 _E(e){let t=AE(e);if(t.isTerminal||!t.hasPathspec&&!t.hasPatch||!t.hasWorktree)return null;return t.hasExplicitLocation?v("git.restore-worktree",rE):v("git.restore-unstaged",nE)}function AE(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(vE.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 PE(e){let t=null;for(let n of e){if(D(n,"--hard")){t=v("git.reset-hard",oE);break}if(D(n,"--merge")){t=v("git.reset-merge",iE);break}}if(!t)return null;return TE(e)?fn(t):qt(t)}function TE(e){for(let t of e){if(t==="--")return!1;if(!t.startsWith("-"))return!0}return!1}function kE(e){for(let n of e)if(n==="-n"||D(n,"--dry-run"))return null;let t=we(e.filter((n)=>n!=="--"));if(e.some((n)=>D(n,"--force"))||t.has("-f"))return v("git.clean-force",sE);return null}function IE(e){let t=!1,n=!1,r=!1;for(let o of pe(e).before){if(D(o,"--no-force")){t=!1;continue}if(D(o,"--force")){t=!0;continue}if(D(o,"--no-cached")){n=!1;continue}if(D(o,"--cached")){n=!0;continue}if(D(o,"--no-dry-run")){r=!1;continue}if(D(o,"--dry-run")){r=!0;continue}let i=we([o]);t||=i.has("-f"),r||=i.has("-n")}return t&&!n&&!r?v("git.rm-force",aE):null}function OE(e){let{before:t,after:n}=pe(e),r=we(t);if(t.some((s)=>D(s,"--mirror")))return v("git.push-mirror",uE);if(t.some((s)=>D(s,"--force"))||r.has("-f")||fm(t,n).some(ME))return v("git.push-force",lE);if(t.some((s)=>D(s,"--delete"))||r.has("-d")||fm(t,n).some(DE))return v("git.push-delete",cE);return null}function fm(e,t){return[...e.filter((n)=>n!==""&&!n.startsWith("-")),...t]}function ME(e){return e.startsWith("+")||e.includes(":+")}function DE(e){return e.length>1&&e.startsWith(":")}function NE(e){let{before:t}=pe(e),n=we(t),r=n.has("-D")||n.has("-d")||t.some((i)=>D(i,"--delete")),o=n.has("-D")||n.has("-f")||t.some((i)=>D(i,"--force"));if(r&&o)return v("git.branch-force-delete",dE);return null}function LE(e){let{before:t}=pe(e);return t.some((n)=>D(n,"--abort"))?v("git.rebase-abort",mE):null}function WE(e){let{before:t}=pe(e);return t.some((n)=>D(n,"--abort"))?v("git.merge-abort",fE):null}function GE(e){let{before:t}=pe(e);return we(t).has("-d")||t.some((r)=>D(r,"--delete"))?v("git.tag-delete",pE):null}function FE(e){return e[0]==="delete"?v("git.reflog-delete",gE):null}function zE(e){for(let t of e){if(t==="drop")return v("git.stash-drop",hE);if(t==="clear")return v("git.stash-clear",yE)}return null}function HE(e){let{before:t}=pe(e);if(!t.includes("remove"))return null;let r=we(t);if(t.some((o)=>D(o,"--force"))||r.has("-f"))return v("git.worktree-remove-force",CE);return null}var It=require("node:path");var $a="TMPDIR",Ua="IFS",hm=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,ym=/^[A-Za-z_][A-Za-z0-9_]*$/,Cm=new Set(["export","typeset","declare","readonly"]),BE=new Set(["builtin","command","time"]),bm=new Set(["do","then","else"]),$E=new Set(["do","then","case"]),gm=new Set(["done","fi","esac"]),UE=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function Sm(e,t){return e.map((n)=>n.provenance==="variable"&&Am(n.text)?vm(n.text,t.shellAssignments):_(n))}function vm(e,t){return e.replace(UE,(n,r,o)=>t.get(r??o??"")??n)}function pt(e,t){let n=e.parts.every((o)=>o.provenance!=="literal"||!/[$`]/.test(o.raw));if(e.provenance!=="variable"||!n)return null;let r=vm(e.text,t);return/^[~-]/.test(r)||/[\s$`*?[]/.test(r)?null:r}function Em(e,t){return{env:e,effectiveEnvAssignments:qE(e,t),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function xm(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 ja(e,t){let n=wm(e,t),r=e[0]??"";if($E.has(r))t.bodyDepth+=1;if(r==="elif"||gm.has(r))t.bodyDepth=Math.max(0,t.bodyDepth-1);if(gm.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);Va(t,a)});let o=n.commandIndex;if(o!==-1&&Cm.has(e[o]??""))e.filter((a)=>ym.test(a)&&Ba(a)).forEach((a)=>{YE(t,a)});let i=o===-1?-1:_m(e,o);if(i===-1||e[i]!=="unset")return;let s=XE(e,i);if(s===null)return;e.slice(s).forEach((a)=>{if(bm.has(r)){t.shellAssignments.set(a,"");return}ZE(t,a)})}function Rm(e,t){let n=wm(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 wm(e,t){let n=bm.has(e[0]??"")?1:0,r=e.findIndex((a,l)=>l>=n&&!Am(a)),o=r!==-1&&Cm.has(e[_m(e,r)]??""),i=KE(t);return{assignments:e.flatMap((a,l)=>{let c=jE(a,i,t.env);if(!c)return[];if(r!==-1&&l>r&&!o&&!ei(c.name))return[];return i.set(c.name,c.value),[{...c,persists:r===-1||o}]}),commandIndex:r}}function _m(e,t){let n=t;while(BE.has(e[n]??"")){n+=1;while(e[n]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(e[n]??""))return t;n+=1}}return n}function Am(e){return Ue(e)!==null||hm.test(e)}function jE(e,t,n){return Ue(e)??VE(e,t,n)}function VE(e,t,n){let r=ti(e,n,t);if(r)return r;let o=e.match(hm)?.[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 Ba(e){return e===$a||e===Ua||ha(e)}function KE(e){return new Map([...e.effectiveEnvAssignments??[],...e.shellAssignments])}function qE(e,t){let n=[$a,Ua].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 Va(e,t){let n=new Map(e.effectiveEnvAssignments??[]);n.set(t.name,t.value),e.effectiveEnvAssignments=n}function YE(e,t){Va(e,{name:t,value:e.shellAssignments.get(t)??e.effectiveEnvAssignments?.get(t)??e.env.get(t)??""})}function ZE(e,t){if(!Ba(t)&&!ym.test(t))return;if(e.shellAssignments.set(t,""),ei(t)&&e.env.has(t)){let r=new Map(e.env);r.delete(t),e.env=r}if(!Ba(t)||t===$a||t===Ua||lr(t)){Va(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 XE(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}var Tm=require("node:path");function Ri(e,t){return ga.some((n)=>t?.has(n)||e.has(n))}function Un(e,t,n){if(!t)return{gitCwd:null,hasExplicitGitContext:!1};let r=n.realpath(Tm.resolve(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=Pm(o,l,n);if(!c)return{gitCwd:null,hasExplicitGitContext:i};o=c,s+=2;continue}if(a.startsWith("-C")&&a.length>2){let l=Pm(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+=De.has(a)?2:1}return{gitCwd:o,hasExplicitGitContext:i}}function Pm(e,t,n){try{let r=Bt(e,t,n);return n.isDirectory(r)?r:null}catch{return null}}function km(e,t,n){if(!t.localDiscard||!n.worktreeMode||Ri(n.environment.env,n.envAssignments))return null;let r=Un(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}=ze(e),i=r?.toLowerCase();if(t.dynamicArguments||JE(o)||rx(e,t.environment.env,t.envAssignments,n)||tx(o)||QE(i,o))return!0;return i==="clean"&&nx(o)>1}function JE(e){return e.some((t)=>/[$*?[]/.test(t))}function QE(e,t){if(e==="checkout"){let{before:n}=pe(t),r=we(n,{shortOptsWithValue:za}),o=n.some((s)=>D(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}=pe(t),r=we(n,{shortOptsWithValue:Ha}),o=n.some((s)=>D(s,"--force"))||n.some((s)=>D(s,"--discard-changes"))||r.has("-f"),i=n.some((s)=>s==="-C"||s.startsWith("-C")||ex(s))||r.has("-C");return o&&i}return!1}function ex(e){let t=e.split("=",1)[0]??e;return t==="--force-create"||t.length>=9&&"--force-create".startsWith(t)}function tx(e){return e.some((t)=>t.startsWith("--recurse-sub"))}function nx(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 rx(e,t,n,r){if(_t("GIT_CONFIG_PARAMETERS",t,n)!==void 0)return!0;let o=xi(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)=>ix(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(gd(n))return!0;return r.recursiveSubmodules}function ox(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function ix(e){return e==="include.path"||e.startsWith("includeif.")&&e.endsWith(".path")}function Im(e,t,n){let r=e.map((l)=>pt(l,n.shellAssignments??new Map)??_(l)),o=n.environment.paths,i=Un(r,n.cwd,o),s=n.originalCwd?o.realpath(It.resolve(n.originalCwd)):null;if(t.id.startsWith("git.push-")||s===null||i.gitCwd===null||i.hasExplicitGitContext||Ri(n.environment.env,n.envAssignments))return null;let a=t.id==="git.worktree-remove-force"?ax(e,n.shellAssignments,o):Om(i.gitCwd,o);if(a===null||t.id!=="git.worktree-remove-force"&&!sx(a,r,t,n)||!Fn(a,n.environment)||gi(a,n.environment)||zn(s,a)||zn(a,s))return null;return{kind:"temp-root",originalReason:t.reason,gitCwd:i.gitCwd}}function sx(e,t,n,r){let o=r.environment.paths,i=It.join(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 ax(e,t,n){let r=ze(e.map(_)).rest,{before:o,after:i}=pe(r.slice(r.indexOf("remove")+1)),s=[...o.filter((d)=>!d.startsWith("-")),...i],a=s.length===1?s[0]??"":"",l=e.find((d)=>d.text===a),c=(l&&pt(l,t??new Map))??a;if(!It.isAbsolute(c)||/[\s$`*?[]/.test(c)||n.entryKind(c)!=="present"||!n.isDirectory(c))return null;return n.realpath(c)}function Om(e,t){if(t.entryKind(It.join(e,".git"))!=="missing")return e;let n=It.dirname(e);return n===e?null:Om(n,t)}var lx="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.",cx=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function wi(e,t){return Dm(e,t)}function Dm(e,t,n){let r=e.map(_),o=dm(r,t.environment.env,t.envAssignments),i=o.blockedReason?T(v("git.alias-config",o.blockedReason),t.policy):null;if(i)return i;let s=o.tokens;if((pd(t.envAssignments)||mm(r,t.environment.env,t.envAssignments))&&ux(s))return v("git.ssh-env",lx);let a=pm(s,(c)=>{let d=Un(r,t.cwd,t.environment.paths).gitCwd;return d!==null&&t.environment.paths.entryKind(Mm.resolve(d,c))!=="missing"});if(!a)return null;if(o.expanded||o.blockedReason)return a;let l=km(r,a,t)??Im(e,a,t);if(!l)return a;return n?.(l),null}function Nm(e,t){let n=null;return{match:Dm(e,t,(o)=>{n=o}),relaxation:n}}function ux(e){let{subcommand:t,rest:n}=ze(e),r=t?.toLowerCase();if(!r)return!1;if(cx.has(r))return!0;if(r==="archive")return pe(n).before.some((o)=>D(o,"--remote"));return r==="remote"&&dx(n)}function dx(e){return e.find((t)=>!mx(t))?.toLowerCase()==="update"}function mx(e){return e==="-v"||D(e,"--verbose")||D(e,"--no-verbose")}var ff=require("node:path");function Lm(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 _i(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 Wm="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",fx="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.",px="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",Fm="rm -rf targeting root or home directory is extremely dangerous and always blocked.",gx="rm -rf in home directory is dangerous. Change to a project directory first.",Gm={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:Fm},git_metadata_target:{id:"rm.git-metadata",reason:je},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:px},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:gx},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:Wm},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:fx},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:Wm}};function Ai(e,t){let n=Kt({...t,allowPaths:t.policy?.destructiveCommandAllowPaths,posixShell:!0}),r=e.map(_),o=it(r),i=vi(r),s=yx(e);for(let a of s){let l=Gr(a.word);if(o&&l.unsafeBraceExpansion){let c=T(Wr({kind:"outside_anchored_cwd"},n,t.policy,Gm),t.policy);if(c)return c;continue}for(let c of l.expandedTargets??[a.text]){let d=Me(c),m={targetIsLiteral:l.expandedTargets!==void 0||l.targetIsLiteral,tmpdirWordSplittingProtected:l.tmpdirWordSplittingProtected};if(!i&&n.resolvedCwd&&cn(d,n.resolvedCwd,n.protectedGitMetadata,i,n.environment,n.budget))return v("rm.git-metadata",je);if(i&&!o){let u=rt(d,n,m);if(u.kind==="root_or_home_target")return v("rm.recursive-force-root-or-home",Fm);if(u.kind==="git_metadata_target")return v("rm.git-metadata",je);continue}if(!o)continue;for(let u of hx(d,n,m)){let f=Wr(u,n,t.policy,Gm),p=T(f,t.policy);if(p)return p}}}return null}function hx(e,t,n){let r=rt(e,t,n);if(r.kind==="cwd_self_target")return[r,rt(e,t,{...n,skipCwdSelf:!0})];if(r.kind!=="home_cwd_target")return[r];let o=rt(e,t,{...n,skipHomeCwd:!0});if(o.kind!=="cwd_self_target")return[r,o];return[r,o,rt(e,t,{...n,skipHomeCwd:!0,skipCwdSelf:!0})]}function yx(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 Yt={kind:"none"},pn={kind:"dynamic"},Cx=new Set(["<","<<","<<-","<<<","<&","<>"]),Hm=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,bx=/^(?:[0-9]+|[@*])$/,Sx=zt.maxWords,Bm=zt.maxInputLength;function $m(e){if(!e||k(M(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
|
|
16
|
+
`){m+=3;continue}s+=["$","`",'"',"\\"].includes(p)?p:`\\${p}`,m+=2;continue}if(e.startsWith("$((",m)){let p=na(e,m+3,n,"))"),g=p===-1?n:p+2;if(s+=e.slice(m,g),p===-1)c.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});m=g;continue}let f=Ko(e,m,n,r,o,i);if(f){let p=Wu(f,l,c);if(m=p.next,u||=p.limited,a=br(a,p.provenance),u)return{text:s,provenance:a,nested:l,issues:c,next:m,limited:u};continue}if(d==="$"){let p=zu(e,m,n,s,a);s=p.text,a=p.provenance,m=p.next;continue}s+=d??"",m++}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 Ko(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,m=s?"))":c?"`":")",d=na(e,t+u,n,m),f=d===-1?n:d,p=d===-1?n:d+m.length;if(i>=r.maxDepth)return{program:yC(e,t+u,f,"depth-limit"),next:p,provenance:s?"arithmetic":"command-substitution"};if(s){let S=[],E=[],C=!1,P=t+u;while(P<f){let x=Ko(e,P,f,r,o,i+1);if(!x){P++;continue}if(S.push(...x.program.nodes),E.push(...x.program.issues),C||=x.program.status==="limited",P=x.next,C)break}if(d===-1)E.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:_e({kind:"program",dialect:"posix",source:e.slice(t+u,f),span:{start:t+u,end:f},status:Vo(E,C),issues:E,nodes:S}),next:p,provenance:"arithmetic"}}let g=$o(e,t+u,f,r,o,i+1),h=d===-1?[{code:"unclosed-command-substitution",message:`${e.slice(t,t+u)} substitution is not closed`}]:[],y=(c||l)&&Sr(g.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[];return{program:_e({kind:"program",dialect:"posix",source:e.slice(t+u,f),span:{start:t+u,end:f},status:Vo([...g.issues,...h,...y],g.limited),issues:[...g.issues,...h,...y],nodes:g.nodes}),next:p,provenance:"command-substitution"}}function Qy(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==="`"?Ko(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 Wu(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 na(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===`
|
|
17
|
+
`||l==="\r")&&s.length>0){let u=l==="\r"&&e[a+1]===`
|
|
18
|
+
`?a+2:a+1,m=Js(e,u,n,s.splice(0));if(!m.terminated)return-1;a=m.next-1;continue}let c=Gu(e,a,t,n,i);if(c!==null){a=c;continue}if(!i.double&&e.startsWith("$((",a)){let u=eC(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]==="-",m=a+(u?3:2);while(m<n&&/[ \t]/.test(e[m]??""))m++;let d=Xs(e,m,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 eC(e,t,n){let r=1,o={single:!1,double:!1};for(let i=t;i<n;i++){let s=e[i],a=Gu(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 Gu(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!=="#"||!SC(e,t,n))return null;let s=t;while(s+1<r&&e[s+1]!==`
|
|
19
|
+
`&&e[s+1]!=="\r")s++;return s}function Uo(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 tC(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 jo(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 Fu(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 nC(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=rC(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 rC(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",`
|
|
20
|
+
`],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(o.has(r))return{text:o.get(r)??r,next:t+1};if(r==="x")return Ho(e,t+1,n,16,2,t+1);if(r==="u")return Ho(e,t+1,n,16,4,t+1);if(r==="U")return Ho(e,t+1,n,16,8,t+1);if(/[0-7]/.test(r))return Ho(e,t,n,8,3,t+1);return{text:r,next:t+1}}function Ho(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 Vo(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 zu(e,t,n,r,o){let i=Fu(e,t,n);return{text:r+e.slice(t,i),provenance:br(o,"variable"),next:i}}function oC(e,t,n){let r=zo(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,m=!s&&(e.startsWith("<(",a)||e.startsWith(">(",a)),d=l==="`";if(c||u||m||d){let f=c?3:d?1:2,p=c?"))":d?"`":")",g=na(e,a+f,n,p),h=g===-1?n:g+p.length;r.push(o,a,"literal"),r.push(a,h,c?"arithmetic":"command-substitution"),a=h,o=h;continue}if(l==="$"){let f=Fu(e,a,n);if(f>a+1){r.push(o,a,"literal"),r.push(a,f,"variable"),a=f,o=f;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 br(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 iC(e,t,n){return t+1>=n||jo(e[t+1]??"")||Uo(e,t+1)!==null}var sC=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),aC=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function lC(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=cC(e,t);if(n===void 0||n===null)return!1;t=n}return!1}function cC(e,t){let n=e[t]?.text.toLowerCase();if(n==="command")return uC(e,t);if(n==="env")return dC(e,t);if(n==="sudo")return mC(e,t);return}function uC(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 dC(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(sC.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 mC(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(aC.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-"))continue;return n}return e.length}function Hu(e,t,n,r){if(e.provenance!=="literal"||!e.raw.includes("{"))return;let o=Bu(e.raw,t,n,r,!0);if(!o)return;if("limited"in o)return{limited:!0};let i=o.values.map((s)=>$u(s,n));if(i.some((s)=>s===null))return{limited:!0};return{words:[...new Set(i.filter((s)=>s!==null&&s!==""))]}}function fC(e,t,n,r,o){if(t.provenance!=="literal"||!t.raw.includes("{"))return;let i=Bu(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)=>$u(a,r));if(s.some((a)=>a===null))return;return{words:s.filter((a)=>a!==null&&a!=="").map((a)=>In(e,t.span.start,t.span.end,a,"literal",!1))}}function Bu(e,t,n,r,o){let i=[e],s=e.length,a=0;while(!0){let l=i.findIndex((f)=>Mu(f,o));if(l===-1)break;if(++a>n)return{limited:"expansions"};let c=i[l]??"",u=Mu(c,o);if(!u||u.kind==="range")return{limited:"expansions"};let m=u.start+c.length-u.end,d=u.alternatives.reduce((f,p)=>f+m+p.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,...pC(c,u)),s+=d-c.length}return a===0?void 0:{values:i}}function Mu(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&&hC(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:gC(e,r)}}function pC(e,t){return t.alternatives.map((n)=>`${e.slice(0,t.start)}${n}${e.slice(t.end)}`)}function gC(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 hC(e){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(e)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(e)}function $u(e,t){let n=`x${e}`,r=ta(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 yC(e,t,n,r){return _e({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 On(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 Bo(e,t,n){return{nodes:e,issues:t,next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function Qs(e){return e.used++,e.used<=e.max}function CC(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 Sr(e){return e.some((t)=>{if(t.kind==="command")return t.redirections.some((n)=>n.heredoc)||t.nested.some((n)=>Sr(n.nodes));return(t.kind==="group"||t.kind==="function")&&Sr(t.body.nodes)})}function bC(e){return e.map((t)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${t.delimiter} was not found`}))}function Uu(e){return e?.kind==="command"||e?.kind==="group"||e?.kind==="function"}function Du(e,t){let n=e.at(-1);if(n?.kind!=="connector"||!Nu.has(n.operator))return;t.push({code:"missing-command-after-connector",message:`connector ${n.operator} requires a following command`})}function ea(e,t){if(!Uu(e.at(-1)))return;t.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function SC(e,t,n){return t===n||/[\s;&|()]/u.test(e[t-1]??"")}var Vu=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),vC=new Set(["gc","cat","type","cp","mv","rm"]),Ku=["-rec","-for","-path","-literalpath","-whatif"],EC=/^\$env:\w/i,xC=/^(?:\$\{?\w+\}?|~)\\./;function qu(e,t){let n=e.toLowerCase().replaceAll("`","");if(![...Vu].some((o)=>n.includes(o))&&!(n.includes("rm")&&Ku.some((o)=>n.includes(o)))&&!n.includes("<#")&&!RC(n))return!1;let r=sa(e,t);if(Yu(r))return!1;return r.issues.some((o)=>o.code==="unclosed-block-comment"||o.code==="comment-depth-limit")||ia(r).some(wC)}function Yu(e){return e.nodes.some((t)=>{if(t.kind==="group")return Yu(t.body);if(t.kind!=="command")return!1;return t.redirections.some((n)=>n.operator==="<<")})}function RC(e){if(e.includes("$env:"))return!0;return e.includes("\\")&&(e.includes("$")||e.includes("~"))}function wC(e){let t=e[0]==="&"||e[0]==="."?1:0,n=e[t]?.toLowerCase();if(n&&Vu.has(n))return!0;let r=e.slice(t+1);if(n&&vC.has(n)&&r.some(_C))return!0;if(n!=="rm")return!1;return r.some((o)=>{let i=o.toLowerCase().split(":",1)[0]??"";return Ku.some((s)=>i.startsWith(s))})}function _C(e){return EC.test(e)||xC.test(e)}function sa(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return _e({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=aa(e,0,e.length,t,0);return _e({kind:"program",dialect:"powershell",source:e,span:n,status:IC(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function aa(e,t,n,r,o,i=!1){let s=[],a=[],l=Go(),c=0,u=!1,m=()=>{if(l.words.length===0&&l.redirections.length===0)return;let f={start:l.start,end:l.end};Fo(s,l,{kind:"command",dialect:"powershell",source:e.slice(f.start,f.end),span:f,words:l.words,redirections:l.redirections,nested:l.nested,displayText:l.words.map((p)=>p.text).join(" ")})},d=t;while(d<n){let f=e[d];if(!f)break;if(i&&f==="}")return m(),{nodes:s,issues:a,next:d+1,closed:!0,words:c,limited:u};let p=kC(e,d,n,r.maxDepth);if(p){if(p.issue)a.push(p.issue);if(p.limited)return m(),{nodes:s,issues:a,next:p.next,closed:!1,words:c,limited:!0};d=p.next;continue}if(/\s/.test(f)){if(f==="\r"||f===`
|
|
21
|
+
`){m();let y=f==="\r"&&e[d+1]===`
|
|
22
|
+
`?d+2:d+1;s.push(ra(e,d,y)),d=y;continue}d++;continue}let g=Ju(e,d);if(g){m(),s.push(ra(e,d,d+g.length)),d+=g.length;continue}if(f==="{"){if(m(),o>=r.maxDepth)return a.push(Xu(r.maxDepth)),{nodes:s,issues:a,next:n,closed:!1,words:c,limited:!0};let y=aa(e,d+1,n,r,o+1,!0),S=y.closed?y.next-1:y.next,E=_e({kind:"program",dialect:"powershell",source:e.slice(d+1,S),span:{start:d+1,end:S},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:E})),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(f==="}"){m(),s.push(ra(e,d,d+1)),d++;continue}if(f===">"||f==="<"){l.start=l.start===-1?d:l.start;let y=e[d+1]===f?d+2:d+1,S=y;while(/[ \t]/.test(e[S]??""))S++;let E=S<n?ju(e,S,n,r,o):void 0,C=E?.next??y;if(l.redirections.push(Object.freeze({kind:"redirection",operator:e.slice(d,y),span:Object.freeze({start:d,end:C}),...E?{target:E.word}:{}})),E)a.push(...E.issues),l.nested.push(...E.nested),c+=E.words,u||=E.limited;l.end=C,d=C;continue}if(f===","){l.start=l.start===-1?d:l.start,l.words.push(Zs({text:",",raw:",",span:{start:d,end:d+1},provenance:"literal",quoted:!1})),l.end=++d;continue}let h=ju(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`}),m(),{nodes:s,issues:a,next:h.next,closed:!1,words:c,limited:!0};d=h.next>d?h.next:d+1}return m(),{nodes:s,issues:a,next:d,closed:!i,words:c,limited:u}}function ju(e,t,n,r,o){let i="",s="literal",a=!1,l=[],c=[],u=0,m=!1,d=(p)=>{let g=AC(e,p,n,r,o);return i+=e.slice(p,g.next),c.push(g.program),l.push(...g.program.issues),u+=oa(g.program),m||=g.program.status==="limited",s="command-substitution",g.next},f=t;while(f<n){let p=e[f];if(!p||/\s/.test(p)||Ju(e,f)||p===">"||p==="<"||p==="#")break;if(p===",")break;if(p==="`"){let g=e[f+1];if(!g){l.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),f++;break}i+=g,f+=2;continue}if(e.startsWith("$(",f)){f=d(f);continue}if(p==="'"){a=!0,f++;let g=!1;while(f<e.length){if(e[f]==="'"&&e[f+1]==="'"){i+="'",f+=2;continue}if(e[f]==="'"){g=!0,f++;break}i+=e[f]??"",f++}if(!g)l.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(p==='"'){a=!0,f++;let g=!1;while(f<n){let h=e[f];if(h==="`"&&e[f+1]){i+=e[f+1],f+=2;continue}if(h==='"'){g=!0,f++;break}if(e.startsWith("$(",f)){f=d(f);continue}if(h==="$")s=e[f+1]==="("?"command-substitution":"variable";i+=h??"",f++}if(!g)l.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(p==="$")s=e[f+1]==="("?"command-substitution":"variable";if(p==="@"&&f===t)s="variable";i+=p,f++}return{word:In(e,t,f,i,s,a,s==="literal"?void 0:PC(e,t,f)),next:f,issues:l,nested:c,words:u,limited:m}}function AC(e,t,n,r,o){let i=Zu(e,t+2,n),s=i===-1?n:i,a=i===-1?n:i+1;if(o>=r.maxDepth)return{program:_e({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:"limited",issues:[Xu(r.maxDepth)],nodes:[]}),next:a};let l=aa(e,t+2,s,r,o+1),c=i===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:_e({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 Zu(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 oa(e){let t=0;for(let n of e.nodes){if(n.kind==="group")t+=oa(n.body);if(n.kind==="command"){t+=n.words.length;for(let r of n.nested)t+=oa(r)}}return t}function PC(e,t,n){let r=zo(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=Zu(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=TC(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 TC(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 Xu(e){return{code:"depth-limit",message:`command structure exceeds parser limit ${e}`}}function ia(e){return e.nodes.flatMap((t)=>{if(t.kind==="group")return ia(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(ia)]})}function Ju(e,t){for(let n of["&&","||",";","|"])if(e.startsWith(n,t))return n;return null}function kC(e,t,n,r){if(e[t]==="#"&&e[t+1]!==">"){let s=t+1;while(s<n&&e[s]!=="\r"&&e[s]!==`
|
|
23
|
+
`)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 IC(e,t){if(t)return"limited";if(e.some((n)=>n.code==="unclosed-block-comment"))return"invalid";return e.length>0?"partial":"complete"}function ra(e,t,n){return Object.freeze({kind:"connector",operator:e.slice(t,n),span:Object.freeze({start:t,end:n})})}function Je(e,t="auto",n=Ft){if(t==="powershell"||t==="auto"&&qu(e.slice(0,n.maxInputLength),n))return sa(e,n);return Lu(e,n)}function _(e){return e.provenance==="command-substitution"?e.raw:e.text}function Mn(e,t){return e==="posix"?t:J(t.map((n)=>n.text))}function qo(e,t){return e&&e.provenance!=="unknown"?e.provenance==="literal":!/[$`*?[\]]/.test(t)}function J(e){return e.map((t)=>({kind:"word",text:t,raw:t,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function la(e,t){return{value:e,work:t}}function b(e,t){if(e.work)e.work.units=Math.min(Number.MAX_SAFE_INTEGER,e.work.units+1);return e.value[t]}function te(e){return e.value.length}function vr(e,t,n=1){if(e)e.units=Math.min(Number.MAX_SAFE_INTEGER,e.units+t.length*n)}function Ge(e,t){vr(e,t)}function on(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 V(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 ca(e){return e===`
|
|
24
|
+
`||e==="\r"||e==="\u2028"||e==="\u2029"}function K(e,t,n){if(t+n.length>te(e))return!1;for(let r=0;r<n.length;r++)if(b(e,t+r)!==n[r])return!1;return!0}function xt(e,t,n){return!on(b(e,t-1))&&K(e,t,n)&&!on(b(e,t+n.length))}function Rt(e,t){return on(b(e,t-1))!==on(b(e,t))}function fe(e){return e===`
|
|
25
|
+
`||e===";"||e==="&"||e==="|"}function Dn(e){return e==="|"||e===";"}function Yo(e,t,n){let r=la(e,n);if(t==="rm")return OC(r);if(t==="dd")return DC(r);return od(r,!0)}function Zo(e,t,n){let r=la(e,n);if(t==="rm")return NC(r);if(t==="reset-hard")return nd(r,"--ha","rd");if(t==="reset-merge")return nd(r,"--me","rge");if(t==="clean")return FC(r);if(t==="checkout")return HC(r);if(t==="push-force")return BC(r);if(t==="push-refspec")return $C(r);if(t==="push-delete")return UC(r);if(t==="branch")return jC(r);if(t==="tag")return qC(r);if(t==="restore")return YC(r);return od(r,!1)}function OC(e){let t=!1,n=!1,r=!1,o=-1;for(let i=0;i<=te(e);i++){let s=b(e,i);if(!t){let l=b(e,i+2);if(xt(e,i,"rm")&&V(l)&&l!==`
|
|
26
|
+
`)t=!0,i++;continue}let a=MC(e,i);if(s===`
|
|
27
|
+
`||a!==-1){if(t=!1,n=!1,r=!1,o=-1,a!==-1)i=a-1;continue}if(s===";"||s==="&"||s==="|"||i===te(e)){if(o>=0){let l=Qu(e,o,i);n||=l.recursive,r||=l.force}if(n&&r)return!0;t=!1,n=!1,r=!1,o=-1;continue}if(V(s)){if(o<0)continue;if(K(e,o,"--")&&i-o===2){t=!1,n=!1,r=!1,o=-1;continue}let l=Qu(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 MC(e,t){if(b(e,t)!=="\\"||b(e,t-1)==="\\")return-1;if(K(e,t,String.raw`\n`))return t+2;if(K(e,t,String.raw`\x0a`)||K(e,t,String.raw`\x0A`))return t+5;if(K(e,t,String.raw`\u000a`)||K(e,t,String.raw`\u000A`))return t+7;return K(e,t,String.raw`\012`)?t+4:-1}function Qu(e,t,n){if(ed(e,t,n,"recursive"))return{recursive:!0,force:!1};if(ed(e,t,n,"force"))return{recursive:!1,force:!0};if(b(e,t)!=="-"||b(e,t+1)==="-")return{recursive:!1,force:!1};let r=!1,o=!1;for(let i=t+1;i<n;i++){let s=b(e,i);r||=s==="r"||s==="R",o||=s==="f"||s==="F"}return{recursive:r,force:o}}function ed(e,t,n,r){let o=n-t-2;if(o<1||o>r.length||!K(e,t,"--"))return!1;for(let i=0;i<o;i++)if(b(e,t+i+2)!==r[i])return!1;return!0}function DC(e){let t=!1;for(let n=0;n<te(e);n++){if(fe(b(e,n))){t=!1;continue}if(xt(e,n,"dd")){t=!0,n++;continue}if(!t||!xt(e,n,"of")||!K(e,n,"of=/dev/"))continue;let r=n+8;if(r<te(e)&&!V(b(e,r))&&b(e,r)!=="'"&&b(e,r)!=='"')return!0}return!1}function NC(e){let t=!1,n=!1,r=!1;for(let o=0;o<=te(e);){let i=b(e,o);if(o===te(e)||fe(i)){t=!1,n=!1,r=!1,o++;continue}let s=WC(e,o);if(s>=0){if(LC(e,s))return!0;let a=s,l=!1;while(V(b(e,a)))l||=b(e,a)===`
|
|
28
|
+
`,a++;if(l)n=!1,r=!1;t=!0,o=a;continue}if(!t){o++;continue}if(K(e,o,"--")&&(o===0||V(b(e,o-1)))&&(!b(e,o+2)||V(b(e,o+2))||fe(b(e,o+2)))){t=!1,n=!1,r=!1,o+=2;continue}if(n||=K(e,o,"--recursive")&&Rt(e,o+11)||ua(e,o,"recursive"),r||=K(e,o,"--force")&&Rt(e,o+7)||ua(e,o,"force"),n&&r)return!0;o++}return!1}function ua(e,t,n){if(!K(e,t,"--"))return!1;let r=0;while(r<=n.length){let o=b(e,t+r+2);if(!o||V(o)||fe(o))break;if(o!==n[r])return!1;r++}return r>0&&Rt(e,t+r+2)}function LC(e,t){let n=t,r=!1,o=!1;while(n<te(e)){while(V(b(e,n)))n++;let i=n;while(n<te(e)&&!V(b(e,n)))n++;if(b(e,i)!=="-"||n-i===2&&K(e,i,"--"))return!1;let s=td(e,i,"recursive"),a=td(e,i,"force");if(r&&a||o&&s)return!0;if(r||=s,o||=a,b(e,i+1)==="-")continue;let l=GC(e,i,n);if(l.combined||r&&l.forceAtBoundary||o&&l.recursiveAtBoundary)return!0;r||=l.recursive,o||=l.force}return!1}function td(e,t,n){return K(e,t,`--${n}`)&&Rt(e,t+n.length+2)||ua(e,t,n)}function WC(e,t){if(t>0&&on(b(e,t-1)))return-1;let n=t;if(b(e,n)==="\\")n++;if(b(e,n)!=="r")return-1;if(n++,b(e,n)==="\\")n++;if(b(e,n)!=="m"||!V(b(e,n+1)))return-1;return n+1}function GC(e,t,n){let r=!1,o=!1,i=!1,s=!1,a=!1;if(b(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=b(e,c)??"",m=(u==="r"||u==="f")&&Rt(e,c+1);r||=u==="r",o||=u==="f",i||=u==="r"&&m,s||=u==="f"&&m,a||=(l==="r"&&u==="f"||l==="f"&&u==="r")&&m,l=u}return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a}}function nd(e,t,n){return xr(e,"reset",Dn,!0,(r)=>b(e,r)==="-"&&Nn(e,r,t,n)?!0:r)}function FC(e){return xr(e,"clean",Dn,!0,(t)=>{if(b(e,t)!=="-")return t;if(Nn(e,t,"--fo","rce"))return!0;let n=Er(e,t,Dn);for(let r=t+1;r<n;r++)if(b(e,r)==="f")return!0;return n-1})}function Xo(e,t,n){if(!xt(e,t,"git"))return null;let r=t+3;if(!V(b(e,r)))return{commandEnd:-1,next:r};while(V(b(e,r)))r++;while(r<te(e)){if(fe(b(e,r)))return{commandEnd:-1,next:r};let o=Er(e,r,fe);if(xt(e,r,n))return{commandEnd:r+n.length,next:o};if(b(e,r)!=="-")return{commandEnd:-1,next:o};let i=o-r===2&&K(e,r,"--"),s=zC(e,r,o);r=o;while(V(b(e,r)))r++;if(i)return{commandEnd:xt(e,r,n)?r+n.length:-1,next:Er(e,r,fe)};if(!s)continue;if(r>=te(e)||fe(b(e,r)))return{commandEnd:-1,next:r};r=Er(e,r,fe);while(V(b(e,r)))r++}return{commandEnd:-1,next:r}}function zC(e,t,n){for(let r of De)if(n-t===r.length&&K(e,t,r))return!0;return!1}function HC(e){return rd(e,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function BC(e){return xr(e,"push",Dn,!0,(t)=>{if(b(e,t)!=="-")return t;if(b(e,t+1)==="f"&&!on(b(e,t+2))&&!K(e,t+2,"-with-lease"))return!0;let n=id(e,t,"--fo","rce");if(n>=0&&!K(e,n,"-with-lease"))return!0;return t})}function $C(e){return xr(e,"push",fe,!1,(t)=>{if(V(b(e,t))&&b(e,t+1)==="+"&&t+2<te(e)&&!fe(b(e,t+2))&&!V(b(e,t+2)))return!0;if(b(e,t)===":"&&b(e,t+1)==="+")return!0;return t})}function UC(e){return xr(e,"push",fe,!1,(t)=>{if(b(e,t)==="-"&&Nn(e,t,"--de","lete"))return!0;if(V(b(e,t))&&b(e,t+1)===":"&&t+2<te(e)&&!V(b(e,t+2))&&!fe(b(e,t+2)))return!0;return t})}function jC(e){let t=!1,n=!1,r=!1;for(let o=0;o<=te(e);o++){if(o===te(e)||fe(b(e,o))){if(n&&r)return!0;t=!1,n=!1,r=!1;continue}if(!t){let a=Xo(e,o,"branch");if(a){t=a.commandEnd>=0,o=Math.max(o,(t?a.commandEnd:a.next)-1);continue}}if(!t||b(e,o)!=="-")continue;let i=Er(e,o,fe),s=VC(e,o,i);if(n||=s.deletion,r||=s.force,n&&r)return!0;o=i-1}return!1}function VC(e,t,n){let r=!1,o=!1;for(let i=t;i<n;i++){if(b(e,i)!=="-")continue;if(Nn(e,i,"--de","lete"))r=!0;if(Nn(e,i,"--fo","rce"))o=!0;if(b(e,i+1)==="-")continue;let s=i+1,a=!1,l=!1,c=!1;while(s<n&&KC(b(e,s))){let u=b(e,s);a||=u==="d"||u==="D",l||=u==="f",c||=u==="D",s++}if(!Rt(e,s))continue;r||=a,o||=l||c}return{deletion:r,force:o}}function KC(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function qC(e){return rd(e,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function rd(e,t){let n=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let r=0;r<te(e);r++){let o=b(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==="$"&&b(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(V(o))i.shortActive=!1,i.hasShortFlag=!1;if(!i.outerActive){let a=Xo(e,r,t.command);if(a){i.outerActive=a.commandEnd>=0&&V(b(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(Nn(e,r,t.longPrefix,t.longOptional))return!0;i.shortActive||=!t.excludedShortStarts.includes(b(e,r+1)??"")}if(i.hasShortFlag||=i.shortActive&&o===t.shortFlag,i.hasShortFlag&&Rt(e,r+1))return!0;if(Dn(o))i.outerActive=!1}return!1}function xr(e,t,n,r,o){let i=!1;for(let s=0;s<te(e);s++){let a=b(e,s),l=n(a);if(!i&&!l){let c=Xo(e,s,t);if(c){i=c.commandEnd>=0&&(!r||V(b(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(b(e,u)))i=!1;s=c}if(l)i=!1}return!1}function YC(e){let t=!1;for(let n=0;n<te(e);n++){if(ca(b(e,n))){if(t)return!0;t=!1;continue}if(!t){let r=Xo(e,n,"restore");if(r){t=r.commandEnd>=0,n=Math.max(n,(t?r.commandEnd:r.next)-1);continue}}if(t&&b(e,n)==="-"&&b(e,n+1)==="-"&&(K(e,n+2,"staged")||K(e,n+2,"help")))t=!1}return t}function od(e,t){let n=!1;for(let r=0;r<te(e);r++){let o=b(e,r),i=t?ca(o):fe(o);if(n&&V(o)&&b(e,r+1)==="-"&&xt(e,r+2,"delete"))return!0;if(i){n=!1;continue}if(xt(e,r,"find"))n=!0,r+=3}return!1}function Er(e,t,n){let r=t;while(r<te(e)&&!V(b(e,r))&&!n(b(e,r)))r++;return r}function id(e,t,n,r){if(!K(e,t,n))return-1;let o=t+n.length;for(let i=0;i<r.length&&b(e,o)===r[i];i++)o++;return Rt(e,o)?o:-1}function Nn(e,t,n,r){return id(e,t,n,r)>=0}function $e(e,t){vr(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)Ge(t,a);if((s.regex?.test(a)??!1)||s.scan&&Zo(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 ZC=/^[A-Za-z_][A-Za-z0-9_]*=/;function ad(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;vr(n,t.source,2);let i={anchored:new RegExp(`^\\$\\{?${o}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${o}(?![A-Za-z0-9_])`)};return ld(t.nodes,r,i)}function ld(e,t,n){return e.every((r)=>{if(r.kind==="connector")return!0;if(r.kind==="group"||r.kind==="function")return ld(r.body.nodes,t,n);if(r.kind==="unknown")return!n.loose.test(r.source);return XC(r,t,n)})}function XC(e,t,n){if(e.nested.some((o)=>n.loose.test(o.source)))return!1;let r=e.words.findIndex((o)=>!ZC.test(o.text));return e.words.every((o,i)=>o===t||sd(o.raw,n.anchored,i!==r))&&e.redirections.every((o)=>(!o.heredoc||o.heredoc.quotedDelimiter||!n.loose.test(o.heredoc.body))&&(!o.target||sd(o.target.raw,n.anchored,!0)))}function sd(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}var Rr=require("node:path");function wr(e,t,n,r){let o=Rr.isAbsolute(e)?Rr.resolve(e):t?Rr.resolve(t,e):void 0;if(!o)return;try{return O(o,n,r)}catch{return o}}function cd(e){return!["/dev","/proc","/sys"].some((t)=>e===t||e.startsWith(`${t}/`))}var Ln="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",_r="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.",ma=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),JC=new Set(["-p","--print"]),QC=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),eb=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"])]]),tb=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),nb=new Map([["python",new Set(["m"])]]),rb=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"])]]),ob=new Set(["always","default","never"]),ib=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),sb=/\\\r?\n/g,ab=new Map([["python",[{selector:"-c",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-m",kind:"module-file",valueForm:"attached-or-separate"}]],["node",[{selector:"-e",kind:"inline-code",valueForm:"separate-only"},{selector:"--eval",kind:"inline-code",valueForm:"equals-or-separate"},{selector:"-p",kind:"inline-code",valueForm:"separate-only"},{selector:"--print",kind:"inline-code",valueForm:"separate-only"},{selector:"-r",kind:"module-file",valueForm:"separate-only"},{selector:"--require",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--import",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--loader",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--experimental-loader",kind:"module-file",valueForm:"equals-or-separate"}]],["ruby",[{selector:"-e",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-r",kind:"module-file",valueForm:"attached-or-separate"}]],["perl",[{selector:"-e",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-E",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-M",kind:"module-file",valueForm:"attached-only"},{selector:"-m",kind:"module-file",valueForm:"attached-only"}]]]);function ud(e){return Qo(e).code}function Jo(e){return Qo(e).sources}function dd(e){return ab.get(pa(e))??[]}function Qo(e){let t=pa(e[0]??"");if(!ma.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 Qe(t,n,r,o,e[i+1]===void 0?void 0:i+1,e[i+1]);if(s===""||s==="-"||!s.startsWith("-"))return Qe(t,n,r,o,i,s);if(t==="node"&&JC.has(s)){let m=e[i+1];if(m===void 0)return Qe(t,n,r,o);if(m.startsWith("-"))continue;n.push({tokenIndex:i+1,value:m}),r.push({tokenIndex:i+1,kind:"inline-code",value:m}),i++;continue}if(cb(t,s)){let m=e[i+1];if(m===void 0)return Qe(t,n,r,o);if(n.push({tokenIndex:i+1,value:m}),r.push({tokenIndex:i+1,kind:"inline-code",value:m}),t==="python")return Qe(t,n,r,o);i++;continue}let a=/^--eval=(.*)$/s.exec(s);if(ub(t)&&a){let m=a[1]??"";n.push({tokenIndex:i,value:m}),r.push({tokenIndex:i,kind:"inline-code",value:m});continue}if(t==="node"){let m=lb(s);if(m){if(m.attached){if(o&&=m.value!=="",m.value!=="")r.push({tokenIndex:i,kind:"module-file",value:m.value});continue}let d=e[i+1];if(d===void 0||d.startsWith("-"))return o=!1,Qe(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 Qe(t,n,r,o);if(rb.get(t)?.has(s)){let m=e[i+1];if(m===void 0||m.startsWith("-")&&!(t==="ruby"&&ib.has(s))||t==="python"&&!ob.has(m))return Qe(t,n,r,o);i++;continue}if(s.startsWith("--"))continue;let l,c=!1;for(let m=1;m<s.length;m++){let d=s[m];if(d===void 0)break;if(nb.get(t)?.has(d)){let f=s.slice(m+1),p=f||e[i+1];if(p!==void 0)r.push({tokenIndex:f?i:i+1,kind:"module-file",value:p});return Qe(t,n,r,o)}if(QC.get(t)?.has(d)){l=s.slice(m+1)||e[i+1],c=m+1===s.length;break}if(t==="node"&&d==="r"){if(o&&=s==="-r",s==="-r"){let f=e[i+1];if(o&&=f!==void 0&&!f.startsWith("-"),o&&f!==void 0)r.push({tokenIndex:i+1,kind:"module-file",value:f});i++}break}if(t==="ruby"&&d==="r"){let f=s.slice(m+1),p=f||e[i+1];if(o&&=p!==void 0,p!==void 0)r.push({tokenIndex:f?i:i+1,kind:"module-file",value:p});if(!f)i++;break}if(t==="perl"&&(d==="M"||d==="m")){let f=s.slice(m+1);if(!f){if(o=!1,m+1===s.length)i++;break}r.push({tokenIndex:i,kind:"module-file",value:f});break}if(eb.get(t)?.has(d)){if(m+1===s.length)i++;break}if(tb.get(t)?.has(d)&&m+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 Qe(t,n,r,o);if(c)i++}return Qe(t,n,r,o,void 0,void 0,!0)}function Qe(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(`
|
|
29
|
+
`))||null,sources:r?c:[],optionsOpen:r&&s}}function lb(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 fa(e,t){return pa(e)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(t)}function pa(e){let t=k(e).toLowerCase();return vo.test(t)?"python":t}function cb(e,t){return ma.get(e)?.has(t)??!1}function ub(e){return ma.get(e)?.has("--eval")??!1}function Ar(e,t,n=!1){let r=fb(e,t);if(!da(r,t))return!1;Ge(t,r);let o=mb(r);if(da(o,t))return!0;if(Ge(t,o),!md.test(o))return!1;return!n||db(r,t)}function db(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,m=l+u.length,d=m;while(d<e.length&&!e.startsWith(u,d))d+=e[d]==="\\"?2:1;if(d>=e.length)return!0;o.push({start:m,text:e.slice(m,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)=>md.test(l[1]??"")).map((l)=>{let c=l.index+l[0].length;return{start:c,end:ga(i,c)}});if(s.some((l)=>ha(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((m)=>l.start>=m.start&&l.start<m.end);return(c||u)&&da(l.text,t)})}function ga(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 ha(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 md=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function mb(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 da(e,t){if(Yo(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(Ge(t,e),r.test(e))return!0;if(Yo(e,"dd",t))return!0;for(let r of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(Ge(t,e),r.test(e))return!0;if(Yo(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)=>(Ge(t,e),n.some((o)=>Zo(o,r))))}function fb(e,t){return Ge(t,e),e.replace(sb,"")}var di=require("node:fs"),mt=require("node:path");var Tr=require("node:path");var zt=require("node:path");function Ht(e,t,n){if(bt(t))throw Error("Unsupported Windows namespace path");let r=zt.isAbsolute(t)?zt.parse(t).root:"",o=r||e;for(let i of gb(r?t.slice(r.length):t)){if(i===""||i===".")continue;if(i===".."){o=zt.dirname(o);continue}let s=pb(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 pb(e,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${t}`:`${e}${zt.sep}${t}`}function gb(e){let t=process.platform==="win32"?/[\\/]+/:/\/+/;return e.split(t)}var ya=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],hb=new Set(ya),yb=1024,fd=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),pd=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),Cb=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ei(e){return hb.has(e)}function Ca(e){return ei(e)||fd.has(e)||pd.has(e)||lr(e)}function wt(e,t,n){return n?.has(e)?n.get(e):t.get(e)}function gd(e,t){let n=wt("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<=yb?{state:"valid",count:r}:{state:"invalid"}}function ti(e,t,n){let o=e.match(Cb)?.[1];if(!o||!Ca(o))return null;let i=e.indexOf("=");return{name:o,value:`${wt(o,t,n)??""}${e.slice(i+1)}`}}function hd(e){return Cd(e,pd)}function yd(e){return Cd(e,fd)}function Cd(e,t){if(!e)return!1;for(let n of e.keys())if(t.has(n))return!0;return!1}var Sd=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ue(e){if(!Sd.test(e))return null;let t=e.indexOf("=");return{name:e.slice(0,t),value:e.slice(t+1)}}function ni(e){let t=new Map,n=0;while(n<e.length){let r=e[n];if(!r)break;let o=Ue(_(r));if(!o)break;t.set(o.name,o.value),n++}return{words:e.slice(n),envAssignments:t}}function vd(e){let t=M(e);return e.includes("=")||t==="sudo"||t==="env"||t==="command"||t==="builtin"}function sn(e,t,n,r){if(!vd(Wn(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 m=0;m<X.wrapperPeelIterations.cap;m++){let d=bd(i),f=ni(i);for(let[g,h]of f.envAssignments)s.set(g,h),a.set(g,h);if(i=f.words,i.length===0)break;while(i.length>0&&Wn(i).includes("=")&&!Sb(i)){let g=vb(Wn(i),a,t.env)??ti(Wn(i),t.env,a);if(g)s.set(g.name,g.value),a.set(g.name,g.value);i=i.slice(1)}if(i.length===0)break;let p=M(Wn(i));if(p!=="sudo"&&p!=="env"&&p!=="command"&&p!=="builtin")break;if(p==="sudo"){let g=xb(i,t.paths,c);if(i=g.words,g.cwd!==void 0)c=g.cwd}if(p==="env"){let g=_b(i,c,a,t);if(l.push(...g.envSplitValues??[]),i=g.words,g.cwd!==void 0)c=g.cwd;for(let[h,y]of g.envAssignments)s.set(h,y),a.set(h,y)}if(p==="command")i=Ab(i);if(p==="builtin")i=i.slice(et(i,1)==="--"?2:1);if(bd(i)===d)break}let u=ni(i);for(let[m,d]of u.envAssignments)s.set(m,d),a.set(m,d);return{words:u.words,envAssignments:s,cwd:c,envSplitValues:l.length>0?l:void 0,rewritten:bb(u.words,o)}}function bb(e,t){return e.some((n)=>!t.has(n))}function bd(e){return e.map(_).join(" ")}function Wn(e){let t=e[0];return t?_(t):""}function et(e,t){let n=e[t];return n?_(n):void 0}function Sb(e){return Sd.test(Wn(e))}function vb(e,t,n){if(!e.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${t.get("TMPDIR")??n.get("TMPDIR")??""}${e.slice(8)}`}}var Eb=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function xb(e,t,n){let r=1,o=n;while(r<e.length){let i=et(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=et(e,r+1);o=s?Pr(o,s,t):null,r+=2;continue}if(i.startsWith("--chdir=")){o=Pr(o,i.slice(8),t),r++;continue}if(i.startsWith("-D")&&i.length>2){o=Pr(o,i.slice(2),t),r++;continue}if(i==="-i"||i==="--login"){o=null,r++;continue}if(Eb.has(i)){r+=2;continue}r++}return{words:e.slice(r),cwd:o}}var Rb=new Set(["-i","-0","--null"]),wb=new Set(["-u","--unset","-C","--chdir","-P"]);function _b(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=et(e,a);if(!c)break;if(c==="--")return l(a+1);if(c==="-i"||c==="--ignore-environment"||c==="-"){o.clear();for(let m of n.keys())o.set(m,"");o.set("TMPDIR",""),a++;continue}if(Rb.has(c)){a++;continue}if(c==="-u"||c==="--unset"){let m=et(e,a+1);if(m!==void 0)o.set(m,"");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:et(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 m=et(e,a+1);s=m?Pr(s,m,r.paths):null}a+=2;continue}if(c.startsWith("-u=")){a++;continue}if(c.startsWith("-C")&&c.length>2||c.startsWith("--chdir=")){let m=c.startsWith("--chdir=")?c.slice(8):c.startsWith("-C=")?c.slice(3):c.slice(2);s=Pr(s,m,r.paths),a++;continue}if(c.startsWith("-P")){a++;continue}if(c.startsWith("-")){a++;continue}if(!Ue(c))break;while(a<e.length){let m=Ue(et(e,a)??"");if(!m)break;o.set(m.name,m.value),a++}if(et(e,a)==="--")a++;return l(a)}return l(a)}function Pr(e,t,n){if(t==="")return null;if(!e&&!Tr.isAbsolute(t))return null;let r=Tr.isAbsolute(t)?Tr.parse(t).root:n.realpath(e??"/");if(r===null)return null;try{return Ht(r,t,n)}catch{return null}}function Ab(e){if(et(e,1)==="-v")return[...J(["type"]),...e.slice(2)];let t=1;while(t<e.length){let n=et(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 Pb=/['"\\$`{}#]/;function ri(e,t){if(e.some((r)=>Pb.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 Bt(e,t,n){return oi(e,t,n).tokens}function Tb(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 $t(e,t,n,r=0){let o=oi(e,t,n),i=(o.envSplitValues??[]).flatMap(Tb);if(i.length===0)return o.tokens;let s=[...i,...o.tokens];if(r>=8)return s;return $t(s,t,n,r+1)}function oi(e,t,n,r){if(!vd(e[0]??""))return{tokens:[...e],envAssignments:new Map,cwd:n};let o=sn(J(e),t,n,r);return{tokens:o.words.map(_),envAssignments:o.envAssignments,cwd:o.cwd,envSplitValues:o.envSplitValues}}var Ea=Symbol("adopt-as-operand"),kb=new Set(["env","sudo","command","builtin"]),Ib=new Set(["&&","||","|&","|","&",";"]),Ob=new Set(["<<","<<<",">|"]),Mb=new Set(["|","|&"]),Db=/[*@#?$!_-]/,Nb=/^\w+(?::\w+)*/,Lb=Object.freeze([]),kr=Object.freeze({kind:"scope",edge:"enter"}),Ir=Object.freeze({kind:"scope",edge:"exit"}),Wb=Object.freeze([]),Gb=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),Or=new Set(["bash","sh","zsh","dash","ksh"]),Fb=256,_d=new WeakMap;function Ad(e,t){let n=t.status==="complete"?new Set(va(t)):new Set,r=Bb(e,n);if(xo(r))return ii("unclosed-quote",r,t);let o={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},i=an(t,{source:r,suppressed:n,flags:o,depth:0,functions:new Map,powershell:t.dialect==="powershell"});if(o.limited)return ii("structural-limit",r,t);if(o.invalid)return ii("invalid",r,t);let s=ii("complete",r,t,o.assignmentFallbacks);return _d.set(s,Object.freeze(i)),s}function ai(e,t,n,r,o){let i=o.word??((m)=>m),s={cwd:t,variables:new Map,previous:null},a=[],l=new Set,c=null,u=[];for(let m of Pd(e)){if(m.kind==="scope"){if(m.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 f=u.pop();if(f===void 0)throw Error("scope exit without a matching enter");s=f.state,a=f.segment,l=f.shellWords,c=f.pipeProducer;continue}if(m.kind==="operator"){if(!m.boundary)continue;let d=o.segment(a,s,c,m.operator,l);if(d)return d;s=zb(a,s,n,r),c=a.length>0&&Mb.has(m.operator)?a:null,a=[],l=new Set;continue}if(m.kind==="redirection"){if(m.fd!==void 0)l.add(a.length-1);if(m.target===void 0)continue;let d=o.redirection({operator:m.operator,role:m.role,targetOrder:m.targetOrder,target:m.target,...m.body===void 0?{}:{body:m.body,consumer:m.consumer}},s);if(d===Ea){l.add(a.length),a.push(i(m.target));continue}if(d)return d;continue}a.push(i(m.text))}return o.segment(a,s,c,null,l)}function li(e){return Pd(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 Ae(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:Ae(i,t);return a?Ae(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 Mr(e){return e.length>0&&e.every((t)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t))}function zb(e,t,n,r){let o=Mr(e)?new Map([...t.variables,...Hb(e,t.variables)]):t.variables,i=Bt([...e],n),s=k(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:he(Ae(s,o),t.cwd,n,r),variables:o,previous:t.cwd}}function Hb(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],Ae(o,t)]]:[]})}function Pd(e){return _d.get(e)??Lb}function Bb(e,t){return[...t].reduce((n,r)=>n.slice(0,r.start)+" ".repeat(r.end-r.start)+n.slice(r.end),e)}function ii(e,t,n,r=Wb){return Object.freeze({status:e,source:t,program:n,assignmentFallbacks:Object.freeze(r)})}function an(e,t){return e.nodes.flatMap((n,r)=>$b(n,e,r,t)).sort((n,r)=>n.start-r.start).flatMap((n)=>[...n.events])}function $b(e,t,n,r){if(e.kind==="connector")return[{start:e.span.start,events:[tt(qb(e.operator))]}];if(e.kind==="unknown")return[{start:e.span.start,events:[tt(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?[si("{"),...an(e.body,a),...s?[si("}")]:[]]:[kr,tt("("),...an(e.body,a),...s?[tt(")")]:[],Ir]}]}let o=Jb(e,r.functions);if(o){if(r.depth>=Ft.maxDepth||++r.flags.expansions>Fb)return r.flags.limited=!0,[];return[{start:e.span.start,events:[...Ed(e,r),si(";"),...an(o,{...r,depth:r.depth+1}),si(";")]},...xd(e,t,n,r)]}return[{start:e.span.start,events:Ed(e,r)},...xd(e,t,n,r)]}function Ed(e,t){return[...e.words.map((n)=>({start:n.span.start,events:kd(n,e,t,!1)})),...e.redirections.map((n)=>({start:n.span.start,events:Ub(n,e,t)}))].sort((n,r)=>n.start-r.start).flatMap((n)=>n.events)}function Ub(e,t,n){let r=e.operator==="<<-"?"<<":e.operator,o=e.target?kd(e.target,t,n,!0):[],i=o[0],s=i?.kind==="word"?i.text:void 0;return[...e.fd===void 0?[]:[xa(String(e.fd))],Object.freeze({kind:"redirection",operator:r,...e.fd===void 0?{}:{fd:e.fd},role:Yb(r),targetOrder:Ob.has(r)?"legacy-segment":"immediate",...s===void 0?{}:{target:s},...e.heredoc&&n.suppressed.has(e.heredoc.bodySpan)?{body:e.heredoc.body,consumer:Od(t)}:{}}),...s===void 0?o:o.slice(1)]}function xd(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=[xa(s.delimiter),.../[\r\n]/.test(r.source[s.terminatorSpan.end]??"")?[tt(";")]:[]];if(r.suppressed.has(s.bodySpan))return[{start:s.bodySpan.start,events:a}];return[{start:s.bodySpan.start,events:[...Td(r.source.slice(s.bodySpan.start,s.bodySpan.end),r),...a]}]}),...o.some((i)=>!i.heredoc&&i.target)?jb(t,n,r):[]]}function jb(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:Td(n.source.slice(r.span.end,e.span.end),n)}]}function Td(e,t){if(t.depth>=Ft.maxDepth)return t.flags.limited=!0,[];let n=Je(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=an(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 kd(e,t,n,r){let o=[],i={single:!1,double:!1},s="",a=!1,l=()=>{let c=a&&!r?tt("glob"):s!==""||e.quoted&&o.length===0?xa(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 f of ba(c.raw,i,n.flags,n.powershell)){if(typeof f==="string"){l(),o.push(tt(f));continue}s+=f.text,a||=f.glob}continue}let u=t.nested.find((f)=>f.span.start>=c.span.start&&f.span.end<=c.span.end);if(i.double){let f=n.source.slice(c.span.start,c.span.end);s+=ba(f,{single:!1,double:!0},n.flags,n.powershell).map((g)=>typeof g==="string"?g:g.text).join("");let p=u?an(u,n).filter((g)=>g.kind==="redirection"&&g.body!==void 0):[];if(p.length>0)o.push(kr,...p,Ir);continue}let m=u?an(u,n):[];if(c.raw.startsWith("`")){s+="${}",l(),o.push(kr,...m,Ir);continue}if(c.raw.startsWith("<(")||c.raw.startsWith(">(")){l(),o.push(c.raw.startsWith("<(")?tt("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),kr,...m,...c.raw.endsWith(")")?[tt(")")]:[],Ir);continue}let d=c.raw.startsWith("$((")?2:1;s+="${}",l(),o.push(...Array.from({length:d},()=>tt("(")),...d===1?[kr]:[],...m,...c.raw.endsWith(")".repeat(d))?Array.from({length:d},()=>tt(")")):[],...d===1?[Ir]:[])}return l(),o}function ba(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=Rd(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=Rd(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 Rd(e,t,n,r,o){let i=e[t+1];if(i==="{"){let a=Kb(e,t+2);if(a===-1)return r.invalid=!0,{text:"",next:e.length};let l=e.slice(t,a+1);return Vb(l,n,r,o),{text:l,next:a+1}}if(i!==void 0&&Db.test(i))return{text:`\${${i}}`,next:t+2};let s=(o?Nb:/^\w*/).exec(e.slice(t+1))?.[0]??"";return{text:`\${${s}}`,next:t+1+s.length}}function Vb(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=ba(s.slice(a.length),{...t},n,r);n.assignmentFallbacks.push(...l.flatMap((c)=>typeof c==="string"||!c.text?[]:[c.text]))}function Kb(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 qb(e){return/^[\r\n]+$/.test(e)?";":e}function tt(e){return Object.freeze({kind:"operator",operator:e,boundary:Ib.has(e)})}function si(e){return Object.freeze({kind:"operator",operator:e,boundary:!0})}function xa(e){return Object.freeze({kind:"word",text:e})}function Yb(e){if(e==="<<"||e==="<<<")return"here-data";if(e==="<"||e==="<&")return"file-read";return"file-write"}function Dr(e){return Gb.has(e)||/^python\d/.test(e)}var Zb=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=Zb.get(e)?.has(n)??!1;return Id(e,t.slice(r?2:1))}function Sa(e){let t=e[0];if(t===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(t))return Sa(e.slice(1));if(!kb.has(t))return[...e];return Sa(Id(t,e.slice(1)))}function Od(e){let t=Cr(e),n=e.words.findIndex((r)=>r.provenance==="literal"&&r.text===t);return Sa(n<0?[]:e.words.slice(n).map((r)=>r.text))}function Xb(e){let t=Od(e)[0];if(t===void 0)return!1;let n=k(t).toLowerCase();return Dr(n)&&!Or.has(n)}function va(e){return e.nodes.flatMap((t,n)=>{if(t.kind==="group"||t.kind==="function")return va(t.body);if(t.kind!=="command")return[];let r=t.nested.flatMap((a)=>va(a)),o=t.redirections.flatMap((a)=>a.heredoc?.quotedDelimiter?[a.heredoc.bodySpan]:[]);if(Xb(t))return[...r,...o];let i=e.nodes[n+1];if(i?.kind==="connector"&&(i.operator==="|"||i.operator==="|&")||!eS(t))return r;return[...r,...o]})}function Jb(e,t){let n=Cr(e);return n===void 0?void 0:t.get(n)}function Ut(e,t){return e!==void 0&&e.provenance==="literal"&&!e.quoted&&e.raw===e.text&&e.text===t}function Qb(e){if(Ut(e.words[0],"git"))return Ut(e.words[1],"commit");if(!Ut(e.words[0],"gh")||!Ut(e.words[2],"create"))return!1;return Ut(e.words[1],"pr")||Ut(e.words[1],"issue")}function eS(e){return(Ut(e.words[0],"cat")||Ut(e.words[0],"tee")||Qb(e))&&!e.words.some(wd)&&!e.redirections.some((n)=>wd(n.target))}function wd(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}var Md=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Dd=new Set([...Md,"glob"]),tS=new Set([...Dd,"pattern"]);class nt extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Nr(e){let t=nS(),n=Nt(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:rS(e),store:t}}function Pe(e,t){return e.commands.find((n)=>n.usages.includes(t))}function _t(e,t){if(!e.includes("$"))return e;return rs(e,t)}function nS(){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=Je(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 m={status:"structural-limit",source:i,program:a,assignmentFallbacks:[]};return n.set(a,m),m}let l=e.get(i);if(l)return l;let c=Ad(i,a);return e.set(i,c),c},getCommandProgram:r}}function rS(e){let t=e.route.kind==="grep"?Dd:e.route.kind==="glob"?tS:Md;return[...co(e.input,t),...e.route.kind==="patch"||typeof e.input==="string"?uo(e.input):[]]}var oS=new Set(["-S","--suffix"]);function Gn(e,t,n,r,o){if(e.status==="structural-limit")throw new nt;if(e.status!=="complete")return o.findMalformedTarget(e.source);return ai(e,t,n,r,{segment:(i,s)=>o.findSegmentTarget(i,s),redirection:(i,s)=>i.role==="file-write"&&o.isRedirectionTarget(Ae(i.target,s.variables),s)?i.target:null})}function ci(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&&oS.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 je="Git metadata and hooks are protected. Ask the user before modifying them.";function Ld(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(lo(e.invocation.toolName))return null;let a=e.paths.find((l)=>Nd(l,o,t,n,r,t.entries));return a?{target:a}:null}if(e.invocation.route.kind!=="command")return null;let i=Pe(e,"input-candidate");if(!i)return null;let s=Gn(i.shell,o,n,r,{findSegmentTarget:(a,l)=>uS(a,l,t,n,r),isRedirectionTarget:(a,l)=>Nd(a,l.cwd,t,n,r,t.markerFiles),findMalformedTarget:()=>null});return s?{target:s}:null}function ln(e,t,n,r,o,i,s=!1){if(!n)return!1;let a=mi(he(e,t,o,i)),l=a.replace(/(\/\.?\*+)+$/,"");if(l!==a&&l!==""){if(Ra(l,n))return!0;let c=s||a.slice(l.length).includes("/."),u=(m)=>c?ui(m,l):iS(m,l);if(n.markerFiles.some(u))return!0;return r&&wa(n).some(u)}if(Ra(a,n))return!0;return r&&wa(n).some((c)=>ui(c,a))}function iS(e,t){let n=mt.relative(t,e);if(n===""||n.startsWith("..")||mt.isAbsolute(n))return!1;return!n.split(/[\\/]/)[0]?.startsWith(".")}function sS(e,t,n,r,o){return ln(e,t,n,!0,r,o)}function aS(e,t,n,r,o){if(!n)return!1;return Ra(mi(he(e,t,r,o)),n)}function Nd(e,t,n,r,o,i){let s=mi(he(e,t,r,o));return i.includes(s)||Gd(s,n)}function Wd(e,t,n,r,o){if(!n)return!1;return n.hooksDirectories.some((i)=>e.some((s)=>ui(i,mi(he(s,t,r,o)))))}function Ra(e,t){return t.entries.includes(e)||t.directories.includes(e)||Gd(e,t)}function Gd(e,t){return t.hooksDirectories.some((n)=>ui(e,n))}var lS=50000;function Fd(e,t){let n=[...new Set(wa(e))];if(n.some((o)=>t(mt.basename(o))))return!0;let r=0;while(n.length>0){let o=n.pop()??"",i=cS(o);if(!i)return!0;if(r+=i.length,r>lS)return!0;if(i.some((s)=>t(s.name)))return!0;n.push(...i.filter((s)=>s.isDirectory()).map((s)=>mt.join(o,s.name)))}return!1}function cS(e){try{let t=di.lstatSync(e,{throwIfNoEntry:!1});if(!t)return[];if(!t.isDirectory())return t.isSymbolicLink()?null:[];return di.readdirSync(e,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function wa(e){return[...e.entries,...e.directories,...e.hooksDirectories]}function ui(e,t){let n=mt.relative(t,e);return n===""||!/^\.\.(?:[\\/]|$)/.test(n)&&!mt.isAbsolute(n)}function mi(e){return process.platform==="win32"?e.toLowerCase():e}function uS(e,t,n,r,o){if(Mr(e))return null;let i=$t([...e],r);if(k(i[0]??"").toLowerCase()!=="mv")return null;let s=ci(i.slice(1)),a=s.sources.find((l)=>sS(Ae(l,t.variables),t.cwd,n,r,o));if(a)return a;return s.destination&&aS(Ae(s.destination,t.variables),t.cwd,n,r,o)?s.destination:null}var q=require("node:path");var Fe=require("node:path"),dS=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],mS=`
|
|
30
|
+
`;function Lr(e,t){if(jt(e,t))return!0;if(!e.has("TMPDIR"))return!1;return!_a(e.get("TMPDIR")??"",t)}function cn(e,t){if(e.has("TMPDIR"))return _a(e.get("TMPDIR")??"",t);let n=Aa(e,t);if(n===void 0)return!0;return _a(n,t)}function Aa(e,t){return Bd(e,t,"TMPDIR")}function _a(e,t){if(!e)return!1;if(pS(e))return!1;return Fn(e,t)}function jt(e,t){let n=Bd(e,t,"IFS");return n!==void 0&&n!==""&&n!==mS}function Fn(e,t){let n=fi(e,t.paths);if(n===null)return!1;return Hd(t).some((r)=>zn(n,r))}function gi(e,t){let n=fi(e,t.paths);if(n===null)return!1;return Hd(t).some((r)=>pi(r)===pi(n))}var zd=new WeakMap;function Hd(e){let t=zd.get(e);if(t)return t;let n=fS(e);return zd.set(e,n),n}function fS(e){let t=dS.map((r)=>fi(r,e.paths)??Fe.normalize(r)),n=fi(e.tmpdir,e.paths);if(!n)return t;if(process.platform==="win32")return[...t,n];if(process.platform==="darwin"&&gS(n))return[...t,n];return t}function pS(e){return/[\s$`*?[]/.test(e)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(e)||/[+@!]\([^)]*\)/.test(e)}function Bd(e,t,n){return e.has(n)?e.get(n):t.env.get(n)}function gS(e){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(e)}function fi(e,t){try{let n=Fe.normalize(e);if(!Fe.isAbsolute(n))return n;let r=Fe.parse(n).root,o=n.slice(r.length).split(/[\\/]+/).filter(Boolean),i=r;for(let s=0;s<o.length;s++){let a=Fe.join(i,o[s]??"");if(t.entryKind(a)==="missing")return Fe.join(a,...o.slice(s+1));let l=t.realpath(a);if(l===null)return null;i=l}return i}catch{return null}}function zn(e,t){let n=pi(e),r=pi(t);if(n===r)return!0;let o=r.endsWith(Fe.sep)?r:`${r}${Fe.sep}`;return n.startsWith(o)}function pi(e){return process.platform==="win32"?e.toLowerCase():e}var hS=process.platform==="win32",$d=64,yS=16384;function Wr(e,t,n,r){if(e.kind==="temp_target")return null;let o=r[e.kind];if(e.kind==="dynamic_target"&&!me(n,o.id,t.strict))return null;if(e.kind==="within_anchored_cwd"&&!me(n,o.id,t.paranoid))return null;return v(o.id,o.reason)}function Gr(e){let t=Hu(e,$d,$d,yS);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:CS(e)}}function CS(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)=>bS(e.raw,n.span.start-e.span.start))}function bS(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??ue();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:wS(e.allowPaths,t,n,r),protectedGitMetadata:e.protectedGitMetadata,budget:r}}function rt(e,t,n={}){let r=n.targetIsLiteral??!1;if(!r&&t.tmpdirWordSplittingUnsafe&&!n.tmpdirWordSplittingProtected&&AS(e))return{kind:"outside_anchored_cwd"};let o=!r&&jd(e,t.posixShell);if(bt(e))return{kind:"outside_anchored_cwd"};if(Ta(e,r))return{kind:"root_or_home_target"};if(vS(e,t,r))return{kind:"root_or_home_target"};if(t.resolvedCwd&&ln(e,t.resolvedCwd,t.protectedGitMetadata,!0,t.environment,t.budget,!t.posixShell))return{kind:"git_metadata_target"};if(ES(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(_S(e,t,r))return{kind:"temp_target"};let i=t.anchoredCwd;if(i){if(!n.skipHomeCwd&&IS(i,t.environment.home,t.environment.paths,t.budget))return{kind:"home_cwd_target"};if(!n.skipCwdSelf&&[t.resolvedCwd??i,i].some((s)=>OS(e,t.resolvedCwd??i,t.environment.paths,t.budget,s)))return{kind:"cwd_self_target"};if(MS(e,i,t.resolvedCwd??i,o,r,t.environment.paths,t.budget))return{kind:"within_anchored_cwd"}}if(SS(e,t,o))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function SS(e,t,n){let r=e.trim();if(n||!t.resolvedCwd||!t.anchoredCwd||!r)return!1;if(q.isAbsolute(r)||r.startsWith("~"))return!1;if(ka(r))return!1;if(Vd(t.resolvedCwd,t.anchoredCwd,t.environment.paths,t.budget))return!1;return Fn(q.resolve(t.resolvedCwd,r),t.environment)}function Ud(e,t,n={}){let{containmentTarget:r,...o}=n;if(rt(e,t,o).kind!=="temp_target")return!1;let i=e.trim();if(RS(i))return!1;if(gi(i,t.environment))return!1;return![t.anchoredCwd,t.resolvedCwd].some((s)=>Vd(r??i,s,t.environment.paths,t.budget))}function Ta(e,t=!1){let n=e.trim(),r=q.posix.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 vS(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=q.isAbsolute(o)?o:t.resolvedCwd?q.resolve(t.resolvedCwd,o):null;if(!i)return!1;let s=Te(O(i,t.environment.paths,t.budget));if(s===q.parse(s).root)return!0;return s===Te(O(t.environment.home,t.environment.paths,t.budget))}catch{return!1}}function Te(e){let t=q.normalize(e);if(hS){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 ES(e,t,n,r,o,i,s,a){let l=e.trim();if(ka(l))return!1;if(!r&&Fn(l,a))return!0;return(t||i&&s)&&n&&!o&&xS(l,n)}function xS(e,t){return["$TMPDIR","${TMPDIR}"].some((n)=>{if(e===n)return!0;if(!e.startsWith(`${n}/`))return!1;return!jd(e.slice(n.length+1),t)})}function RS(e){let t=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(e);if(!t)return!1;return q.posix.normalize(`/${t[1]??""}`)==="/"}function ka(e){return e.split(/[\\/]+/).includes("..")}function wS(e,t,n,r){if(!e?.length)return[];return e.flatMap((o)=>{let i=gr(o.trim(),t);if(!q.isAbsolute(i))return[];try{let s=O(i,n,r);if(hr(s,O(t,n,r)))return[];return[Te(s)]}catch{return[]}})}function _S(e,t,n){if(t.allowRoots.length===0)return!1;let r=e.trim();if(ka(r))return!1;let o=n?r:gr(r,t.environment.home),i=t.resolvedCwd??t.anchoredCwd,s=q.isAbsolute(o)?o:i?q.resolve(i,o):null;if(!s)return!1;try{let a=Te(O(s,t.environment.paths,t.budget));return t.allowRoots.some((l)=>a===l||a.startsWith(l.endsWith(q.sep)?l:`${l}${q.sep}`))}catch{return!1}}function AS(e){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(e)}function jd(e,t=!1){return e.includes("$")||e.includes("`")||PS(e)||t&&TS(e)}function PS(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 TS(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==="{"&&kS(e,n)||(r==="+"||r==="@"||r==="!")&&e[n+1]==="(")return!0}return!1}function kS(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 IS(e,t,n,r){try{return Te(O(e,n,r))===Te(O(t,n,r))}catch{try{return Te(e)===Te(t)}catch{return!1}}}function OS(e,t,n,r,o=t){if(o===t&&(e==="."||e==="./"||e===".\\"))return!0;try{return Te(O(q.resolve(t,e),n,r))===Te(O(o,n,r))}catch{try{return Te(q.resolve(t,e))===Te(o)}catch{return!1}}}function MS(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 Pa(e,t,i,s)}catch{return!1}if(e.startsWith("./")||e.startsWith(".\\")||!e.includes("/")&&!e.includes("\\"))try{return Pa(q.resolve(a,e),t,i,s)}catch{return!1}if(e.startsWith("../"))return!1;try{return Pa(q.resolve(a,e),t,i,s)}catch{return!1}}function Pa(e,t,n,r){try{return Kd(O(e,n,r),O(t,n,r))}catch{return!1}}function Vd(e,t,n,r){if(!t)return!1;try{return Kd(O(t,n,r),O(e,n,r))}catch{return!0}}function Kd(e,t){let n=Te(e),r=Te(t);return n.startsWith(`${r}${q.sep}`)||n===r}var DS=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.",NS="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.",Yd="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",Zd="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",LS="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",WS="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",GS={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:Zd},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:je},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:Yd},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:LS},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:qd},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:NS},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:qd}};function Xd(e,t,n,r=Vt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths})){return FS(e.words.map((o)=>({kind:"word",text:o.text,dynamic:o.provenance!=="literal"})),t,r,n.policy)}function FS(e,t,n,r){let o=e.filter((l)=>l.kind==="word"),i=HS(o),s=o[i];if(!s||!DS.has(ZS(s.text)))return null;let a=zS(o.slice(i+1));if(a.whatIfProtected)return null;if(me(r,"powershell.remove-item-pipeline-dynamic-target",n.strict)&&t&&(a.targets.length===0||a.recursive))return v("powershell.remove-item-pipeline-dynamic-target",WS);for(let l of a.targets)if(!bt(l.text)&&Ta(Oa(l.text)))return v(a.recursive&&a.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Zd);for(let l of a.targets)if(n.resolvedCwd&&ln(Oa(l.text),n.resolvedCwd,n.protectedGitMetadata,a.recursive,n.environment,n.budget,!0))return v("powershell.remove-item-git-metadata",je);if(!a.recursive||!a.force)return null;if(me(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",Yd);for(let l of a.targets){let c=Wr(rt(Oa(l.text),n),n,r,GS);if(c)return c}return null}function zS(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(BS(l))continue;if(s){t.push(Ia(l)),i=i||l.dynamic;continue}if(l.text==="--"){s=!0;continue}let c=US(l.text);if(!c){t.push(Ia(l)),i=i||l.dynamic;continue}if(jS(c.name)){let u=c.value?$S(c.value,l):e[++a];if(u?.kind==="word"){t.push(Ia(u)),i=i||u.dynamic;continue}i=!0;continue}if(VS(c.name)){n=!0;continue}if(KS(c.name)){r=!0;continue}if(qS(c.name))o=YS(c.value)}return{targets:t,recursive:n,force:r,whatIfProtected:o,hasDynamicTarget:i}}function HS(e){let t=e[0];if(t?.kind==="word"&&t.text==="&"||t?.text===".")return e.length>1?1:0;return 0}function Ia(e){return{text:e.kind==="word"?e.text:"",dynamic:e.kind==="word"&&e.dynamic}}function BS(e){return e.kind==="word"&&e.text===","}function Oa(e){let t=e.replace(/\\/g,"/"),n=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(t);return n?`$HOME${t.slice(n[0].length)}`:t}function $S(e,t){return{kind:"word",text:e,dynamic:t.kind==="word"&&(t.dynamic||e.includes("$"))}}function US(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 jS(e){return"path".startsWith(e)||"literalpath".startsWith(e)}function VS(e){return"recurse".startsWith(e)}function KS(e){return e.length>=2&&"force".startsWith(e)}function qS(e){return e==="wi"||"whatif".startsWith(e)}function YS(e){if(e===void 0||e==="")return!0;let t=e.toLowerCase();return t==="$true"||t==="true"}function ZS(e){return e.toLowerCase()}var Hn="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",hi="Unsupported heredoc syntax",Fr="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.",Jd="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var XS=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),JS=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),QS=new Set(["-o","--output","--query","--subscription"]),ev=new Set;function Qd(e){if(e==="aws")return XS;if(e==="gcloud")return JS;if(e==="az")return QS;return ev}var tv=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),nv=new Set;function em(e){if(e==="git")return De;if(e==="docker")return tv;return nv}function At(e,t){if(e.length===0||t.length===0)return null;let n=M(e[0]??""),r=we(e);for(let o of t){if(!iv(n,o.command))continue;if(o.match){if(rv(n,e,o.match))return tm(o);continue}if(!sv(n,e,o.subcommand))continue;if(lv(e,new Set(o.block_args),r))return tm(o)}return null}function tm(e){return{id:`custom.${e.name}`,reason:`[${e.name}] ${e.reason}`,intent:e.intent??"manual_only"}}function rv(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 ov(r,n.command_path,Qd(e))}function ov(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 iv(e,t){return e===M(t)}function sv(e,t,n){if(!n)return!0;return nm(t,1,n,em(e))}function nm(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 nm(e,t+2,n,r)}function lv(e,t,n){return e.some((r)=>t.has(r))||[...n].some((r)=>t.has(r))}var cv=new Set(["-e","--source"]),uv=new Set(["-F","-v","--assign","--field-separator"]),rm=new Set(["-f","--file"]),dv=new Set(["print","printf","return"]),om=[{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"}],mv="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 im(e,t,n){let r=!1;for(let o of fv(e)){let i=pv(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",mv):null}function Da(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&&cv.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&&(uv.has(a)||rm.has(a))){let l=e[s+1];if(i&&=l!==void 0,rm.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 Hr(e){return Da(e).sources}function fv(e){return Hr(e).filter((t)=>t.kind!=="program-file").map((t)=>t.value)}function pv(e,t){Ge(t,e);let n=e.includes("system")?Na(e,t):null,r=gv(e,t);if(!n&&!r)return null;return{dynamic:!!n?.dynamic||!!r?.dynamic,commands:[...n?.commands??[],...r?.commands??[]]}}function Na(e,t){Ge(t,e);let n=[],r=!1,o=!1,i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){i=Ci(e,i,s)?.endIndex??i+1;continue}if(s==="#"){i=sm(e,i+1);continue}if(s==="/"&&am(e,i)){i=lm(e,i+1)??i+1;continue}if(!e.startsWith("system",i)){i++;continue}let a=i;if(i+=6,zr(e[a-1])||zr(e[i]))continue;let l=yi(e,i);if(e[l]!=="(")continue;l=yi(e,l+1);let c=e[l];if(c!=='"'&&c!=="'"){r=!0,o=!0;continue}let u=Ci(e,l,c);if(!u){r=!0,o=!0;continue}if(l=yi(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 gv(e,t){Ge(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 f=Ci(e,i,u);if(f&&c===s)l={...f,startIndex:i};c=f?.endIndex??i+1,i=f?.endIndex??i+1;continue}if(u==="#"){i=sm(e,i+1),s=i,a=null,l=null,c=i;continue}if(u==="/"&&am(e,i)){let f=lm(e,i+1);c=f??i+1,i=f??i+1;continue}if(`;
|
|
31
|
+
{}`.includes(u)){i++,s=i,a=null,l=null,c=i;continue}if(a===null&&(Ma(e,i,"print")||Ma(e,i,"printf")))a=i;if(u!=="|"||e[i-1]==="|"||e[i+1]==="|"){if(!/\s/.test(u))c=i+1;i++;continue}let m=e[i+1]==="&"?i+2:i+1,d=yi(e,m);if(Ma(e,d,"getline")){o=!0;let f=Cv(s,l,c);if(r||=f===null,f!==null)n.push(f);c=m,i=m;continue}if(Sv(s,a)){o=!0;let f=yv(e,d);if(!f){r=!0,c=m,i=m;continue}if(!hv(e,f.endIndex)){r=!0,c=f.endIndex,i=f.endIndex;continue}n.push(f.value),c=f.endIndex,i=f.endIndex;continue}c=m,i++}if(!o)return null;return{dynamic:r,commands:n}}function zr(e){return!!e&&/[A-Za-z0-9_]/.test(e)}function yi(e,t){let n=t;while(/\s/.test(e[n]??""))n++;return n}function hv(e,t){let n=t;while(/[\t\f\v\r ]/.test(e[n]??""))n++;let r=e[n];return!r||`;
|
|
32
|
+
}#`.includes(r)}function Ci(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=bv(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 yv(e,t){let n=e[t];if(n!=='"'&&n!=="'")return null;return Ci(e,t,n)}function Cv(e,t,n){if(!t)return null;return t.startIndex>=e&&t.endIndex===n?t.value:null}function bv(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:`
|
|
33
|
+
`,r:"\r",t:"\t",v:"\v"}[n]??n,endIndex:t}}function Ma(e,t,n){return e.startsWith(n,t)&&!zr(e[t-1])&&!zr(e[t+n.length])}function Sv(e,t){return t!==null&&t>=e}function sm(e,t){let n=e.indexOf(`
|
|
34
|
+
`,t);return n===-1?e.length:n+1}function am(e,t){let n=vv(e,t);if(n===-1)return!0;if("{([,;!~=".includes(e[n]??""))return!0;let r=n;while(zr(e[r-1]))r--;return dv.has(e.slice(r,n+1))}function vv(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function lm(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 Ev=new Set(["sudo","env","command","builtin"]);function bi(e,t){let n=e[0];if(!n||!t.transparentWrappers.includes(k(n)))return null;let r=k(n),o=e[1]==="--"?2:1,i=xv(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 xv(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=k(a)!==n&&Rv(a,r);if(l)i.push(s);if(!l&&Eo.has(M(a)))break;if(o)break}return i}function Rv(e,t){let n=k(e),r=M(e);return r==="git"||n==="busybox"||un(e)||xs.has(n)||t.transparentWrappers.includes(n)||Q.has(r)||e==="$SHELL"||Xe(r)||Be.has(r)||t.rules.some((o)=>o.command===n)}function un(e){return Ev.has(e.toLowerCase())}function dn(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 ot(e,t){let n=t.policy??{rules:[],transparentWrappers:[]};return Si([...e],t.environment,t.cwd,t.cwd,new Map,new Map(t.envAssignments??[]),n,{iterations:0},!1)}function*Si(e,t,n,r,o,i,s,a,l){let c=oi(e,t,n,i);for(let[f,p]of c.envAssignments)i.set(f,p),o.set(f,p);let{tokens:u,cwd:m}=c;if(c.envSplitValues){let f=ri(c.envSplitValues,u);if(!f)throw new N("derivedCommandShape");La(a),yield*Si(f,t,m,r,o,i,s,a,l);return}if(un(u[0]??""))throw new N("wrapperPeelIterations");let d=bi(u,s);if(d){for(let f of[d.childIndex,...d.alternativeChildIndices])La(a),yield*Si(f===d.childIndex?d.tokens:u.slice(f),t,m,r,new Map(o),new Map(i),s,a,!0);return}if(_v(u)){La(a),yield*Si(u.slice(1),t,m,r,o,i,s,a,l);return}yield wv(u,m,r,o,i,l)}function wv(e,t,n,r,o,i){return{tokens:e,cwd:t===null?void 0:t??n,wrapperCwd:t,wrapperEnvAssignments:r,envAssignments:o,head:k(e[0]??"").toLowerCase(),wrappedByTransparent:i}}function La(e){if(e.iterations>=X.wrapperPeelIterations.cap)throw new N("wrapperPeelIterations");e.iterations++}function _v(e){return k(e[0]??"").toLowerCase()==="busybox"&&e.length>1}function Wa(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 it(e){let t=!1,n=!1;for(let r of e){if(r==="--")break;if(r==="-r"||r==="-R"||Ga(r,"recursive")){t=!0;continue}if(r==="-f"||Ga(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 vi(e){let t=e.indexOf("--");return e.slice(1,t===-1?void 0:t).some((n)=>Ga(n,"recursive")||/^-[A-Za-z]+$/.test(n)&&/[rR]/.test(n.slice(1)))}function Ga(e,t){return e.length>2&&e.startsWith("--")&&t.startsWith(e.slice(2))}var Av=["--init-file","--rcfile"],Pv=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function st(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n)continue;if(n==="-c")return cm(e,t,!0);if(n.startsWith("-")&&n.includes("c")&&!n.startsWith("--")){let r=cm(e,t,!1);if(r!==null)return r}}return null}function Pt(e){let t=k(e[0]??"").toLowerCase();if(t==="zsh"||t==="ksh")return Ne(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 cm(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 um(e){let t=k(e[0]??"").toLowerCase(),n=Tv(e,t),r=Pv.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 Tv(e,t){let n=Ne(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?Av.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 m=l.split("=",1)[0]??l;if(t==="bash"&&vs.has(m)&&!l.includes("="))a++;continue}if(t==="bash")s=!1;let c=Es(t,l,e[a+1],"startup");if(c.interactive)i=l[0]==="-";a+=c.followingValues}return{argvSource:o.at(-1)??null,interactive:i}}var kv="find -delete permanently removes files. Use -print first to preview.",Iv="find -exec rm -rf is dangerous. Use explicit file list instead.",Ov=new Set(["-exec","-execdir","-ok","-okdir"]),Mv=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 dm(e,t){let n=e.map(_),r=Dv(e,n,t);if(r)return r;if(Ei(n,1)&&!zv(e,n,t)){let s=T(v("find.delete",kv),t.policy);if(s)return s}let o=t.budget??ue(),i=0;while(i<n.length){let s=n[i],a=Tt(s??"");if(a>0){i+=a+1;continue}if(!ft(s)){i++;continue}o.charge("derivedTokens",n.length-i-1);let l=Bn(n,i);i=l.nextIndex;let c=Bv(l.tokens,t.environment);if(c){let f=T(c,t.policy);if(f)return f}let u=s==="-execdir"||s==="-okdir",m=t.analyzeTokens?t.analyzeTokens(l.tokens,u?null:t.cwd):t.analyzeNested?t.analyzeNested(l.tokens.join(" "),{effectiveCwd:u?void 0:t.cwd,envAssignments:t.envAssignments}):null,d=m?.id.startsWith("custom.")?m:T(m,t.policy);if(d)return d}return null}function Dv(e,t,n){if(!Ei(t,1)&&!Fa(t,n.environment))return null;let o=Br(e)??J(["."]),i=Vt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let s of o){let a=Gr(s);for(let l of a.expandedTargets??[_(s)]){let c=rt(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"&&!Nv(e,i.protectedGitMetadata,n.environment))return v("find.delete-git-metadata",je)}}if(Fv(t)&&i.resolvedCwd&&Wd(o.map(_),i.resolvedCwd,i.protectedGitMetadata,i.environment,i.budget))return v("find.delete-git-metadata",je);return null}function Nv(e,t,n){if(!t)return!1;let r=e.map(_),o=[],i=!1,s=Br(e)?.at(-1),a=s?e.indexOf(s)+1:1;while(a<r.length){let l=r[a]??"";if(ft(l)){let c=Bn(r,a),u=$t([...c.tokens],n),m=vi(u),d=Q.has(k(u[0]??"").toLowerCase()),f=c.tokens.some((g)=>g!=="{}"&&g.includes("{}")),p=(l==="-execdir"||l==="-okdir")&&u.slice(1).some((g)=>g!=="{}"&&!g.startsWith("-"));if(m||d||f||p)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(Wv(c.text,l==="-iname"));a+=2;continue}if(!Lv.has(l))return!1;a+=1+Tt(l)}return o.length>0&&!Fd(t,(l)=>o.every((c)=>c.test(l)))}var Lv=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function Wv(e,t){let n=e.replace(/[*?]|[.+^${}()|\]/]/g,(r)=>r==="*"?".*":r==="?"?".":`\\${r}`);return new RegExp(`^${n}$`,t?"isu":"su")}var Gv=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function Fa(e,t){let n=0;while(n<e.length){if(!ft(e[n])){n++;continue}let r=Bn(e,n),o=$t([...r.tokens],t),i=k(o[0]??"").toLowerCase(),s=Q.has(i)&&Gv.test((st(o)??"").replace(/["'\\]/g,""));if((i==="rm"||i==="rmdir"||s)&&o.some((l)=>l.includes("{}")))return!0;n=r.nextIndex}return!1}function Fv(e){return e.some((t,n)=>{if(!["-name","-iname"].includes(t))return!1;return e[n+1]?.toLowerCase()==="hooks"})}function zv(e,t,n){if(t.includes("-L")||t.includes("-f")||t.includes("-follow"))return!1;let r=Br(e);if(!r)return!1;let o=n.envAssignments??new Map,i=Aa(o,n.environment),s=n.trustedTmpdirValue??cn(o,n.environment),a=n.allowTmpdirVar??!Lr(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=Vt(l),u=Vt({...l,cwd:n.originalCwd??n.cwd}),m=n.originalCwd&&n.environment.paths.realpath(n.originalCwd),d=n.cwd&&n.environment.paths.realpath(n.cwd),f=m&&d&&!zn(d,m)?n.cwd:void 0;return r.every((p)=>{let g=Gr(p);if(g.unsafeBraceExpansion)return!1;return(g.expandedTargets??[_(p)]).every((h)=>{let y=/^\.\/*$/.test(h)?f:void 0,S=y??h;return Ud(S,y?u:c,{containmentTarget:Hv(S,i),targetIsLiteral:g.expandedTargets!==void 0||g.targetIsLiteral,tmpdirWordSplittingProtected:g.tmpdirWordSplittingProtected})})})}function Hv(e,t){if(!t)return e;return e.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>t)}function Br(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 Bv(e,t){let n=Bt([...e],t);if(n.length===0)return null;let r=k(n[0]??"");if(r==="busybox"&&n.length>1)n=n.slice(1),r=k(n[0]??"");if(r==="rm"&&it(n))return v("find.exec-rm-recursive-force",Iv);return null}function Bn(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 Ei(e,t){let n=t;while(n<e.length){let r=e[n];if(!r){n++;continue}if(ft(r)){n=Bn(e,n).nextIndex;continue}let o=Tt(r);if(o>0){n+=o+1;continue}if(r==="-delete")return!0;n++}return!1}function Tt(e){return Mv.get(e)??(/^-newer[A-Za-z]{2}$/.test(e)?1:0)}function ft(e){return e!==void 0&&Ov.has(e)}var Nm=require("node:path");function $r(e){let t=Je(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 $v=5,za="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 pe(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 fm(e,t,n){let r=xi(e,t,n),o=Uv(r.entries);if(o.size===0)return{blockedReason:r.blockedReason,expanded:!1,tokens:e};let i=e,s=!1;for(let a=0;a<$v;a++){let{subcommand:l,rest:c}=ze(i),u=l?.toLowerCase();if(!u||!o.has(u))return{blockedReason:r.blockedReason,expanded:s,tokens:i};let m=o.get(u),d=Yv(m);if(d===null||d.length===0)return{blockedReason:za,expanded:!0,tokens:i};i=["git",...d,...c],s=!0}return{blockedReason:za,expanded:!0,tokens:i}}function pm(e,t,n){return xi(e,t,n).entries.some((r)=>r.key.toLowerCase()==="core.sshcommand")}function ze(e){if(e.length===0)return{subcommand:null,rest:[]};let t=e[0];if((t?k(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+=De.has(o)?2:1}return{subcommand:null,rest:[]}}function Uv(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 xi(e,t,n){if(e.length===0)return{blockedReason:null,entries:[]};let r=e[0];if((r?k(r).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let i=Vv(t,n);return{blockedReason:i.blockedReason,entries:[...i.entries,...jv(e,t,n)]}}function jv(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=Ha(e[o+1]);if(s)r.push(s);o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=Ha(i.slice(2));if(s)r.push(s);o++;continue}if(i==="--config-env"){let s=mm(e[o+1],t,n);if(s)r.push(s);o+=2;continue}if(i.startsWith("--config-env=")){let s=mm(i.slice(13),t,n);if(s)r.push(s);o++;continue}if(De.has(i)){o+=2;continue}o++}return r}function Vv(e,t){let n=Kv(e,t),r=qv(e,t);return{blockedReason:n===null||r===null?za:null,entries:[...n??[],...r??[]]}}function Kv(e,t){let n=wt("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=Ha(i);if(!s)return null;r.push(s)}return r}function qv(e,t){let n=gd(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=wt(`GIT_CONFIG_KEY_${o}`,e,t)?.trim(),s=wt(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i||s===void 0)return null;r.push({key:i,value:s})}return r}function Ha(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 mm(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;return{key:e.slice(0,r).trim(),value:wt(e.slice(r+1),t,n)}}function Yv(e){let t=e?.trimStart();if(!t||t.startsWith("!"))return null;return $r(t)}var Zv="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",Xv="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",Jv="git checkout --force discards uncommitted changes. Use 'git stash' first.",Qv="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",eE="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",tE="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",nE="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",rE="git switch --force discards uncommitted changes. Use 'git stash' first.",oE="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.",sE="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",aE="git reset --merge can lose uncommitted changes. Use 'git stash' first.",lE="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",cE="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.",uE="git push --force destroys remote history. Use --force-with-lease for safer force push.",dE="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",mE="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",fE="git branch -D force-deletes without merge check. Use -d for safe delete.",pE="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",gE="git merge --abort discards merge conflict resolutions. Use 'git status' first.",hE="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",yE="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",CE="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",bE="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",SE="git worktree remove --force can delete uncommitted changes. Remove --force flag.",vE=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),EE=new Set(["--recurse-submodules","--track","-t"]),Ba=new Set(["-b","-B","-U"]),$a=new Set(["-c","-C"]),xE=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function D(e,t){let n=e.split("=",1)[0]??e;return n.length>=4&&t.startsWith(n)&&n.startsWith("--")&&n.slice(2).length>=2}var $n=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function hm(e,t){let{subcommand:n,rest:r}=ze(e);if(!n)return null;switch(n.toLowerCase()){case"checkout":return Kt(RE(r,t));case"switch":return Kt(_E(r));case"restore":return Kt(PE(r));case"reset":return kE(r);case"clean":return Kt(OE(r));case"rm":return Kt(ME(r));case"push":return mn(DE(r));case"branch":return mn(WE(r));case"stash":return mn(BE(r));case"worktree":return mn($E(r));case"rebase":return Kt(GE(r));case"merge":return Kt(FE(r));case"tag":return mn(zE(r));case"reflog":return mn(HE(r));default:return null}}function Kt(e){return e?{...e,localDiscard:!0}:null}function mn(e){return e?{...e,localDiscard:!1}:null}function RE(e,t){let{index:n,before:r}=pe(e),o=we(r,{shortOptsWithValue:Ba});if(r.some((a)=>D(a,"--force"))||o.has("-f"))return v("git.checkout-force",Jv);for(let a of e){if(a==="-b"||a==="-B"||a==="--orphan")return null;if(D(a,"--pathspec-from-file"))return v("git.checkout-pathspec-from-file",eE)}if(n!==-1){if(r.some((l)=>!l.startsWith("-")))return v("git.checkout-ref-path",Qv);return v("git.checkout-double-dash",Zv)}let i=AE(e);if(i.length>=2)return v("git.checkout-ambiguous",tE);let s=i[0];if(s===void 0||o.has("-d")||o.has("-t")||e.some((a)=>D(a,"--detach")||D(a,"--track")))return null;if(wE(s)||t(s))return v("git.checkout-double-dash",Xv);return null}function wE(e){return e==="."||e===".."||/^\.\.?[/\\]/.test(e)||/^([/\\]|[A-Za-z]:[/\\])/.test(e)||e.endsWith("/")||e.startsWith(":")||/[*?[]/.test(e)}function _E(e){let{before:t}=pe(e);if(t.some((r)=>D(r,"--discard-changes")))return v("git.switch-discard-changes",nE);let n=we(t,{shortOptsWithValue:$a});if(t.some((r)=>D(r,"--force"))||n.has("-f"))return v("git.switch-force",rE);return null}function AE(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(vE.has(r)){n+=2;continue}if(EE.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 PE(e){let t=TE(e);if(t.isTerminal||!t.hasPathspec&&!t.hasPatch||!t.hasWorktree)return null;return t.hasExplicitLocation?v("git.restore-worktree",iE):v("git.restore-unstaged",oE)}function TE(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(xE.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 kE(e){let t=null;for(let n of e){if(D(n,"--hard")){t=v("git.reset-hard",sE);break}if(D(n,"--merge")){t=v("git.reset-merge",aE);break}}if(!t)return null;return IE(e)?mn(t):Kt(t)}function IE(e){for(let t of e){if(t==="--")return!1;if(!t.startsWith("-"))return!0}return!1}function OE(e){for(let n of e)if(n==="-n"||D(n,"--dry-run"))return null;let t=we(e.filter((n)=>n!=="--"));if(e.some((n)=>D(n,"--force"))||t.has("-f"))return v("git.clean-force",lE);return null}function ME(e){let t=!1,n=!1,r=!1;for(let o of pe(e).before){if(D(o,"--no-force")){t=!1;continue}if(D(o,"--force")){t=!0;continue}if(D(o,"--no-cached")){n=!1;continue}if(D(o,"--cached")){n=!0;continue}if(D(o,"--no-dry-run")){r=!1;continue}if(D(o,"--dry-run")){r=!0;continue}let i=we([o]);t||=i.has("-f"),r||=i.has("-n")}return t&&!n&&!r?v("git.rm-force",cE):null}function DE(e){let{before:t,after:n}=pe(e),r=we(t);if(t.some((s)=>D(s,"--mirror")))return v("git.push-mirror",mE);if(t.some((s)=>D(s,"--force"))||r.has("-f")||gm(t,n).some(NE))return v("git.push-force",uE);if(t.some((s)=>D(s,"--delete"))||r.has("-d")||gm(t,n).some(LE))return v("git.push-delete",dE);return null}function gm(e,t){return[...e.filter((n)=>n!==""&&!n.startsWith("-")),...t]}function NE(e){return e.startsWith("+")||e.includes(":+")}function LE(e){return e.length>1&&e.startsWith(":")}function WE(e){let{before:t}=pe(e),n=we(t),r=n.has("-D")||n.has("-d")||t.some((i)=>D(i,"--delete")),o=n.has("-D")||n.has("-f")||t.some((i)=>D(i,"--force"));if(r&&o)return v("git.branch-force-delete",fE);return null}function GE(e){let{before:t}=pe(e);return t.some((n)=>D(n,"--abort"))?v("git.rebase-abort",pE):null}function FE(e){let{before:t}=pe(e);return t.some((n)=>D(n,"--abort"))?v("git.merge-abort",gE):null}function zE(e){let{before:t}=pe(e);return we(t).has("-d")||t.some((r)=>D(r,"--delete"))?v("git.tag-delete",hE):null}function HE(e){return e[0]==="delete"?v("git.reflog-delete",yE):null}function BE(e){for(let t of e){if(t==="drop")return v("git.stash-drop",CE);if(t==="clear")return v("git.stash-clear",bE)}return null}function $E(e){let{before:t}=pe(e);if(!t.includes("remove"))return null;let r=we(t);if(t.some((o)=>D(o,"--force"))||r.has("-f"))return v("git.worktree-remove-force",SE);return null}var kt=require("node:path");var ja="TMPDIR",Va="IFS",Cm=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,bm=/^[A-Za-z_][A-Za-z0-9_]*$/,Sm=new Set(["export","typeset","declare","readonly"]),UE=new Set(["builtin","command","time"]),vm=new Set(["do","then","else"]),jE=new Set(["do","then","case"]),ym=new Set(["done","fi","esac"]),VE=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function Em(e,t){return e.map((n)=>n.provenance==="variable"&&Tm(n.text)?xm(n.text,t.shellAssignments):_(n))}function xm(e,t){return e.replace(VE,(n,r,o)=>t.get(r??o??"")??n)}function pt(e,t){let n=e.parts.every((o)=>o.provenance!=="literal"||!/[$`]/.test(o.raw));if(e.provenance!=="variable"||!n)return null;let r=xm(e.text,t);return/^[~-]/.test(r)||/[\s$`*?[]/.test(r)?null:r}function Rm(e,t){return{env:e,effectiveEnvAssignments:ZE(e,t),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function wm(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 Ka(e,t){let n=Am(e,t),r=e[0]??"";if(jE.has(r))t.bodyDepth+=1;if(r==="elif"||ym.has(r))t.bodyDepth=Math.max(0,t.bodyDepth-1);if(ym.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);qa(t,a)});let o=n.commandIndex;if(o!==-1&&Sm.has(e[o]??""))e.filter((a)=>bm.test(a)&&Ua(a)).forEach((a)=>{XE(t,a)});let i=o===-1?-1:Pm(e,o);if(i===-1||e[i]!=="unset")return;let s=QE(e,i);if(s===null)return;e.slice(s).forEach((a)=>{if(vm.has(r)){t.shellAssignments.set(a,"");return}JE(t,a)})}function _m(e,t){let n=Am(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 Am(e,t){let n=vm.has(e[0]??"")?1:0,r=e.findIndex((a,l)=>l>=n&&!Tm(a)),o=r!==-1&&Sm.has(e[Pm(e,r)]??""),i=YE(t);return{assignments:e.flatMap((a,l)=>{let c=KE(a,i,t.env);if(!c)return[];if(r!==-1&&l>r&&!o&&!ei(c.name))return[];return i.set(c.name,c.value),[{...c,persists:r===-1||o}]}),commandIndex:r}}function Pm(e,t){let n=t;while(UE.has(e[n]??"")){n+=1;while(e[n]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(e[n]??""))return t;n+=1}}return n}function Tm(e){return Ue(e)!==null||Cm.test(e)}function KE(e,t,n){return Ue(e)??qE(e,t,n)}function qE(e,t,n){let r=ti(e,n,t);if(r)return r;let o=e.match(Cm)?.[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 Ua(e){return e===ja||e===Va||Ca(e)}function YE(e){return new Map([...e.effectiveEnvAssignments??[],...e.shellAssignments])}function ZE(e,t){let n=[ja,Va].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 qa(e,t){let n=new Map(e.effectiveEnvAssignments??[]);n.set(t.name,t.value),e.effectiveEnvAssignments=n}function XE(e,t){qa(e,{name:t,value:e.shellAssignments.get(t)??e.effectiveEnvAssignments?.get(t)??e.env.get(t)??""})}function JE(e,t){if(!Ua(t)&&!bm.test(t))return;if(e.shellAssignments.set(t,""),ei(t)&&e.env.has(t)){let r=new Map(e.env);r.delete(t),e.env=r}if(!Ua(t)||t===ja||t===Va||lr(t)){qa(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 QE(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}var Im=require("node:path");function Ri(e,t){return ya.some((n)=>t?.has(n)||e.has(n))}function Un(e,t,n){if(!t)return{gitCwd:null,hasExplicitGitContext:!1};let r=n.realpath(Im.resolve(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=km(o,l,n);if(!c)return{gitCwd:null,hasExplicitGitContext:i};o=c,s+=2;continue}if(a.startsWith("-C")&&a.length>2){let l=km(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+=De.has(a)?2:1}return{gitCwd:o,hasExplicitGitContext:i}}function km(e,t,n){try{let r=Ht(e,t,n);return n.isDirectory(r)?r:null}catch{return null}}function Om(e,t,n){if(!t.localDiscard||!n.worktreeMode||Ri(n.environment.env,n.envAssignments))return null;let r=Un(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(Ya(e,n,o))return null;return{kind:"worktree",originalReason:t.reason,gitCwd:r.gitCwd}}function Ya(e,t,n){let{subcommand:r,rest:o}=ze(e),i=r?.toLowerCase();if(t.dynamicArguments||ex(o)||ix(e,t.environment.env,t.envAssignments,n)||rx(o)||tx(i,o))return!0;return i==="clean"&&ox(o)>1}function ex(e){return e.some((t)=>/[$*?[]/.test(t))}function tx(e,t){if(e==="checkout"){let{before:n}=pe(t),r=we(n,{shortOptsWithValue:Ba}),o=n.some((s)=>D(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}=pe(t),r=we(n,{shortOptsWithValue:$a}),o=n.some((s)=>D(s,"--force"))||n.some((s)=>D(s,"--discard-changes"))||r.has("-f"),i=n.some((s)=>s==="-C"||s.startsWith("-C")||nx(s))||r.has("-C");return o&&i}return!1}function nx(e){let t=e.split("=",1)[0]??e;return t==="--force-create"||t.length>=9&&"--force-create".startsWith(t)}function rx(e){return e.some((t)=>t.startsWith("--recurse-sub"))}function ox(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 ix(e,t,n,r){if(wt("GIT_CONFIG_PARAMETERS",t,n)!==void 0)return!0;let o=xi(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)=>ax(a.key)))return!0;let s=i.filter((a)=>a.key==="submodule.recurse").at(-1);if(s)return s.value===void 0||sx(s.value);if(yd(n))return!0;return r.recursiveSubmodules}function sx(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function ax(e){return e==="include.path"||e.startsWith("includeif.")&&e.endsWith(".path")}function Mm(e,t,n){let r=e.map((l)=>pt(l,n.shellAssignments??new Map)??_(l)),o=n.environment.paths,i=Un(r,n.cwd,o),s=n.originalCwd?o.realpath(kt.resolve(n.originalCwd)):null;if(t.id.startsWith("git.push-")||s===null||i.gitCwd===null||i.hasExplicitGitContext||Ri(n.environment.env,n.envAssignments))return null;let a=t.id==="git.worktree-remove-force"?cx(e,n.shellAssignments,o):Dm(i.gitCwd,o);if(a===null||t.id!=="git.worktree-remove-force"&&!lx(a,r,t,n)||!Fn(a,n.environment)||gi(a,n.environment)||zn(s,a)||zn(a,s))return null;return{kind:"temp-root",originalReason:t.reason,gitCwd:i.gitCwd}}function lx(e,t,n,r){let o=r.environment.paths,i=kt.join(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&&!Ya(t,r,a)}function cx(e,t,n){let r=ze(e.map(_)).rest,{before:o,after:i}=pe(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&&pt(l,t??new Map))??a;if(!kt.isAbsolute(c)||/[\s$`*?[]/.test(c)||n.entryKind(c)!=="present"||!n.isDirectory(c))return null;return n.realpath(c)}function Dm(e,t){if(t.entryKind(kt.join(e,".git"))!=="missing")return e;let n=kt.dirname(e);return n===e?null:Dm(n,t)}var ux="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.",dx=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function wi(e,t){return Lm(e,t)}function Lm(e,t,n){let r=e.map(_),o=fm(r,t.environment.env,t.envAssignments),i=o.blockedReason?T(v("git.alias-config",o.blockedReason),t.policy):null;if(i)return i;let s=o.tokens;if((hd(t.envAssignments)||pm(r,t.environment.env,t.envAssignments))&&mx(s))return v("git.ssh-env",ux);let a=hm(s,(c)=>{let u=Un(r,t.cwd,t.environment.paths).gitCwd;return u!==null&&t.environment.paths.entryKind(Nm.resolve(u,c))!=="missing"});if(!a)return null;if(o.expanded||o.blockedReason)return a;let l=Om(r,a,t)??Mm(e,a,t);if(!l)return a;return n?.(l),null}function Wm(e,t){let n=null;return{match:Lm(e,t,(o)=>{n=o}),relaxation:n}}function mx(e){let{subcommand:t,rest:n}=ze(e),r=t?.toLowerCase();if(!r)return!1;if(dx.has(r))return!0;if(r==="archive")return pe(n).before.some((o)=>D(o,"--remote"));return r==="remote"&&fx(n)}function fx(e){return e.find((t)=>!px(t))?.toLowerCase()==="update"}function px(e){return e==="-v"||D(e,"--verbose")||D(e,"--no-verbose")}var gf=require("node:path");function Gm(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 _i(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 Fm="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",gx="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.",hx="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",Hm="rm -rf targeting root or home directory is extremely dangerous and always blocked.",yx="rm -rf in home directory is dangerous. Change to a project directory first.",zm={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:Hm},git_metadata_target:{id:"rm.git-metadata",reason:je},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:hx},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:yx},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:Fm},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:gx},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:Fm}};function Ai(e,t){let n=Vt({...t,allowPaths:t.policy?.destructiveCommandAllowPaths,posixShell:!0}),r=e.map(_),o=it(r),i=vi(r),s=bx(e);for(let a of s){let l=Gr(a.word);if(o&&l.unsafeBraceExpansion){let c=T(Wr({kind:"outside_anchored_cwd"},n,t.policy,zm),t.policy);if(c)return c;continue}for(let c of l.expandedTargets??[a.text]){let u=Me(c),m={targetIsLiteral:l.expandedTargets!==void 0||l.targetIsLiteral,tmpdirWordSplittingProtected:l.tmpdirWordSplittingProtected};if(!i&&n.resolvedCwd&&ln(u,n.resolvedCwd,n.protectedGitMetadata,i,n.environment,n.budget))return v("rm.git-metadata",je);if(i&&!o){let d=rt(u,n,m);if(d.kind==="root_or_home_target")return v("rm.recursive-force-root-or-home",Hm);if(d.kind==="git_metadata_target")return v("rm.git-metadata",je);continue}if(!o)continue;for(let d of Cx(u,n,m)){let f=Wr(d,n,t.policy,zm),p=T(f,t.policy);if(p)return p}}}return null}function Cx(e,t,n){let r=rt(e,t,n);if(r.kind==="cwd_self_target")return[r,rt(e,t,{...n,skipCwdSelf:!0})];if(r.kind!=="home_cwd_target")return[r];let o=rt(e,t,{...n,skipHomeCwd:!0});if(o.kind!=="cwd_self_target")return[r,o];return[r,o,rt(e,t,{...n,skipHomeCwd:!0,skipCwdSelf:!0})]}function bx(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 qt={kind:"none"},fn={kind:"dynamic"},Sx=new Set(["<","<<","<<-","<<<","<&","<>"]),$m=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,vx=/^(?:[0-9]+|[@*])$/,Ex=Ft.maxWords,Um=Ft.maxInputLength;function jm(e){if(!e||k(M(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
|
|
35
35
|
`)return`${r.join(`
|
|
36
36
|
`)}
|
|
37
37
|
`;if(n.includes("%")||/\\(?![\\nrt])/.test(n))return;return n.replaceAll("\\n",`
|
|
38
|
-
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function Pi(e){let t=jn(e[1])==="--"?2:1;if(e.length<=t)return
|
|
39
|
-
`}}function
|
|
38
|
+
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function Pi(e){let t=jn(e[1])==="--"?2:1;if(e.length<=t)return qt;let n=e.slice(t);if(!n.every(jr))return fn;return{kind:"literal",source:n.map(_).join(" ")}}function Vm(e){let t=jn(e[1])==="--"?2:1,n=e[t],r=jn(n);if(n===void 0||e.length<=t+1||r==="-"||r===""||r==="-l"||r==="-p")return qt;if(!jr(n))return fn;return{kind:"literal",source:r}}function Ti(e,t){let n=Ym(e);if(n===-1)return qt;let r=Rx(t);if(!r)return qt;let o=[],i=r.command?.length??0;for(let s of r.references){let a=_x(s,e,n,r.ifs);if(!a)return fn;if(i+=a.reduce((l,c)=>l+c.length+3,0),o.length+a.length>Ex||i>Um)return fn;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(Zm)].filter((s)=>s!==null).join(" ")}}function Km(e,t){let n=Ym(e),r=e.slice(n+1),o=/\bIFS\b/.test(t);if(n===-1||!r.every(jr)||o)return t;let i=r.map(jn),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 m=u[1]??u[2],d=m==="@"||m==="*"?i.slice(1):[i[Number(m)]??""];if(a!=='"'&&d.some((p)=>/[*?[]/.test(p)))return t;if(s+=a==='"'?d.map((p)=>p.replace(/["$`\\]/g,"\\$&")).join(m==="@"?'" "':" "):d.map((p)=>p.split(/[ \t\n]+/).map((g)=>g?Zm(g):"").join(" ")).join(" "),s.length>Um)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 qm(e,t,n,r){if(!Ne(e.map(_)).readsStdinAsCommands)return qt;let o=t.filter((i)=>(i.fd===void 0||i.fd===0)&&Sx.has(i.operator)).at(-1);if(o){if(o.operator==="<<"||o.operator==="<<-")return qt;if(o.operator!=="<<<"||o.target?.provenance!=="literal")return fn;return{kind:"literal",source:o.target.text}}if(!n)return qt;return r===void 0?fn:{kind:"literal",source:r}}function It(e,t=new Map){let n=Ne(e.map(_)).scriptIndex;if(n===null)return qt;let r=e[n],o=jn(r);if(qo(r,o))return{kind:"literal",source:o};let i=r?pt(r,t):null;return i===null?fn:{kind:"literal",source:i}}var xx=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function Qa(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||Ue(s)!==null)return!1;let a=k(M(s));return!xx.has(a)&&!Q.has(a)&&!un(a)}function Ym(e){return Ne(e.map(_)).commandIndex??-1}function Rx(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(wx);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]??"":`
|
|
39
|
+
`}}function wx(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 _x(e,t,n,r){let o=t.slice(n+2);if(e.parameter==="@")return e.quoted?Za(o):Ax(o,r);if(e.parameter==="*"){let a=Za(o);if(!a)return;let l=a.join(r[0]??"");return e.quoted?[l]:Xa(l,r)}let i=t[n+1+e.parameter];if(i&&!jr(i))return;let s=jn(i);return e.quoted?[s]:Xa(s,r)}function Za(e){return e.every(jr)?e.map(_):void 0}function Ax(e,t){let n=Za(e);if(!n)return;let r=n.map((o)=>Xa(o,t));return r.some((o)=>o===void 0)?void 0:r.flatMap((o)=>o??[])}function Xa(e,t){if(["*","?","[","]"].some((n)=>e.includes(n)))return;if(t==="")return e===""?[]:[e];if(t===`
|
|
40
40
|
`)return e.trim().split(/\s+/).filter(Boolean);if(t.length!==1)return;return t===" "||t==="\t"||t===`
|
|
41
|
-
`?e.trim().split(/\s+/).filter(Boolean):e.split(t).filter(Boolean)}function jr(e){if(!e)return!0;return e.provenance==="unknown"?!/[$`]/.test(_(e)):e.provenance==="literal"}function jn(e){return e?_(e):""}function qm(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Ja(e,t){return Za(Je(e,"posix"),t)}function Vr(e){return Ja(e,new Set(Array.from(e.matchAll(Hm)).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))||Ym(r.words,n))return!0;kx(r,n)}return!1}function Ym(e,t){let n=e.findIndex((s)=>Ue(s.text)===null);if(n===-1)return!1;let r=e[n];if(!r)return!1;if(Ur(r,t))return!0;let o=M(r.text);if(o==="source"||o==="."){let s=e[n+1]?.text==="--"?n+2:n+1;return zm(e[s],t)}if(Q.has(o)){let s=e.slice(n),a=Ne(s.map((c)=>c.text)),l=a.commandIndex??a.scriptIndex;return!a.syntaxCheck&&l!==null&&zm(s[l],t)}let i=_x(e,n,t);if(i===null)return!1;if(i===-1)return!0;return Ym(e.slice(i),t)}function _x(e,t,n){let r=M(e[t]?.text??"");if(r==="command")return Ax(e,t+1);if(r==="exec")return Px(e,t+1);if(r==="env")return Tx(e,t+1,n);return null}function Ax(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 Px(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 Tx(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 Ur(e[r+1],n)?-1:r+2;if(i.startsWith("-S")||i.startsWith("--split-string="))return Ur(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(Ue(i))continue;return r}return null}function kx(e,t){if(!e.words.every((n)=>Ue(n.text)!==null))return;for(let n of e.words){let r=Ue(n.text);if(!r)continue;if(Ur(n,t))t.add(r.name)}}function Ur(e,t){if(!e)return!1;return e.parts.filter((n)=>n.provenance==="variable").some((n)=>Array.from(n.raw.matchAll(Hm)).some((r)=>{let o=r[1]??r[2];return o!==void 0&&(bx.test(o)||t.has(o))}))}function zm(e,t){return!!e&&(e.parts.some((n)=>n.provenance!=="literal"&&n.provenance!=="variable")||Ur(e,t))}var Qa="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",el="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",Ix="__CC_SAFETY_NET_XARGS_INPUT__",ki="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",Ii="rm",Ox=/(?:^|[;&|]\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,Mx=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,Dx=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,Nx=/^(?:[0-9]+|[@*])$/;function Jm(e,t){let n=e.map(_),{childStart:r,replacementToken:o}=gn(n),i=n.slice(r),s=v("xargs.shell-dynamic",el);if(Wx(i,o,t)&&T(s,t.policy))return T(s,t.policy);for(let a of ot(i,t)){let l=a.tokens,c=o!==null&&l[0]!==i[0]&&(l[0]?.includes(o)??!1)?T(s,t.policy):null;if(c)return c;let d=of(l,o,a.wrapperEnvAssignments),m=a.head==="rm"&&o!==null&&nf(l,o),u=t.analyzeChild(l,{...mn(a,t),dynamicInput:d,dynamicSourceInput:m||ef(l,a.head,o,a.wrapperEnvAssignments,d,t.environment,t.strict?void 0:t.analyzeNested),dynamicRmInput:m,shellDynamicMatch:s,dynamicSourceMatch:s,rmDynamicMatch:v("xargs.rm-recursive-force-dynamic",Qa)});if(u)return u;let f=Lx(l,o,t.policy?.rules??[],T(s,t.policy));if(f)return f;if(a.head==="git"){let g=o===null?[...l,Ix]:l,h=o!==null&&(l.some((S)=>S.includes(o))||Array.from(a.envAssignments.values()).some((S)=>S.includes(o))),y=t.analyzeChild(g,{...mn(a,t),worktreeMode:o===null||h?!1:t.worktreeMode});if(y)return y}let p=Pt(l,t.policy?.rules??[]);if(p)return p}return null}function Lx(e,t,n,r){if(n.length===0)return null;if(t===null){for(let i of n){let s=Pt([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],n);if(s)return s}return null}let o=M(e[0]??"");if(!n.some((i)=>M(i.command)===o))return null;return e.slice(1).some((i)=>i.includes(t))?r:null}function Qm(e,t,n){let r=e.indexOf(t);if(r===-1||e.indexOf(t,r+t.length)!==-1)return[];let o=Lm(e,r,t.length,n);return o===null?[]:[o]}function ef(e,t,n,r,o,i,s){if(Q.has(t)){if(Tt(e))return!1;if(n!==null&&Gx(e,n,s))return!0;let a=st(e);if(!a){let l=Ot(J(e));if(l.kind==="literal")return n!==null&&l.source.includes(n);return l.kind==="none"&&o}if(n!==null&&a.includes(n)&&!tf(a,n,s))return!0;if($e(a))return!0;return Fx(a,n,r)}if(Xe(t))return Zm(e,n,Qo,cd(t));if(Be.has(t))return Zm(e,n,Oa,nm);if(t==="eval"){let a=Pi(J(e));if(a.kind==="dynamic")return!0;if(n!==null)return a.kind==="literal"&&a.source.includes(n);return o}if(t==="find")return zx(e,n,i);if(t==="git"){let a=ze(e);return n===null?a.subcommand===null:(a.subcommand?.includes(n)??!1)||a.subcommand!==null&&$n.has(a.subcommand.toLowerCase())&&rf(a.rest,n).some((l)=>l.includes(n))}return!1}function tf(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 $e(i)===null&&n(i)===null}function Zm(e,t,n,r){let o=n(e);if(t===null)return o.optionsOpen||n([...e,ki]).sources.some((a)=>a.value===ki);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}${ki}`]:[],...a.valueForm==="equals-or-separate"?[`${a.selector}=${ki}`]:[]]),s=new Set(i.flatMap((a)=>e.flatMap((l)=>Qm(l,t,a))));return _i(o.sources,s,(a)=>n(e.map((l)=>l.replaceAll(t,a))).sources)}function Wx(e,t,n){if(e.length===0||(e[0]??"").toLowerCase()==="command")return!1;let r=new Set(Array.from(ot(e,n),(i)=>i.head)),o=t===null?[...e,Ii]:e.map((i,s)=>s===0?i:i.replaceAll(t,Ii));return Array.from(ot(o,n)).some((i)=>i.head===Ii&&!r.has(Ii))}function nf(e,t){return rf(e.slice(1),t).some((n)=>n.includes(t)&&(n.startsWith("-")||n.startsWith(t)))}function rf(e,t){let n=e.findIndex((r)=>r==="--"&&!r.includes(t));return n===-1?e:e.slice(0,n)}function of(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 Gx(e,t,n){let r=Ne(e),o=r.commandIndex===null?"":e[r.commandIndex]??"";if(o.includes(t)&&!tf(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 Qm(a,t,s).some((d)=>{let m=e.map((f,p)=>p===l?f.replaceAll(t,d):f),u=Ne(m);if(u.commandIndex===null&&u.scriptIndex===null)return!1;if(r.commandIndex===null&&u.commandIndex!==null)return!0;if(r.scriptIndex===null&&u.scriptIndex!==null)return!0;if(u.commandIndex!==null&&(m[u.commandIndex]??"").includes(d))return!0;return u.scriptIndex!==null&&(m[u.scriptIndex]??"").includes(d)})}))}function Fx(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(Ox))if(Xm(o,r))return!0;for(let o of e.matchAll(Mx))for(let i of(o[1]??"").matchAll(Dx))if(Xm(i,r))return!0;return Ja(e,r)}function Xm(e,t){let n=e[1]??e[2];return n!==void 0&&(Nx.test(n)||t.has(n))}function zx(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(ft(s)){let l=Bn(e,i);i=l.nextIndex-1;for(let c of ot(l.tokens,{environment:n,cwd:void 0})){let d=of(c.tokens,t,c.wrapperEnvAssignments);if(c.head==="rm"&&nf(c.tokens,t)||ef(c.tokens,c.head,t,c.wrapperEnvAssignments,d,n))return!0}continue}let a=kt(s);if(a>0){if(o=a,s.includes(t))return!0;continue}if(s.includes(t))return!0}return!1}function gn(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 Kr="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",qr="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",Hx="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",Bx="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Mi=/\{[^{}\s]*\}/g,sf=/\{\}|\{-?\d+\}/g,$x=["e","f","source","file","-e","-f","--source","--file"],Ux=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],jx=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),Vx=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),af=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),Kx=new Set(["--workdir","--wd"]),lf="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Ve(e,t){for(let n of e){let r=t(n);if(r)return r}return null}function pf(e){return Ve([...e],(t)=>$e(t))}function gf(e,t){let n=e.map(_);if((t.envAssignments?.has("PARALLEL")?t.envAssignments.get("PARALLEL"):t.environment.env.get("PARALLEL"))?.trim()){let p=Vn(t);if(p)return p}if(n.length===2&&(n[1]==="--version"||n[1]==="--help"))return null;let o=Rf(n),{template:i,jobs:s,runsRemotely:a,readsCommandsFromInput:l,unsupported:c,workdir:d,dryRun:m}=o;if(c){let p=Vn(t);if(p)return p;let g=pf(t.envAssignments?.values()??[]);if(g)return g}if(l){let p=Qx(t);if(p)return p}if(d!==void 0&&a){let p=Vn(t);if(p)return p}let u=eR(d,t.cwd,t.environment.paths);if(u===null){let p=Vn(t);if(p)return p}let f=a?{...t,cwd:void 0,originalCwd:void 0}:u===null||u===void 0||u===t.cwd?t:{...t,cwd:u};if(m){if([...ot(i,f)].flatMap((g)=>[...g.envAssignments.values()]).some(rl)){let g=Vn(t);if(g)return g}return null}if(i.length===0){let p=s.map((h)=>h[0]??"");t.budget.charge("derivedTokens",p.length);let g=bf(f.envAssignments,f.cwd,a);return Ve(p,(h)=>t.analyzeNested(h,g))}return Ve(ot(i,f),(p)=>qx(p,o,t,f))}function qx(e,t,n,r){let{jobs:o,templateHasPlaceholder:i,runsRemotely:s,usesStdin:a}=t,l=e.tokens,c=[...e.envAssignments.values()];if(c.some(Ef)){let h=Vn(n);if(h)return h}let d=pf(c);if(d)return d;let m=c.some(B),u=i||m,f=a&&u,p=bf(e.envAssignments,e.wrapperCwd,s||f);if(Q.has(e.head)){let h=()=>{if(!i||o.length===0)return null;return Ve(o,(E)=>n.analyzeChild(Oi(l,E,n.budget),mn(e,r)))};if(Tt(l))return h();let y=st(l);if(y){if(xf(y)){let x=Zt(n);if(x)return x;if(o.length===0)return null;return Ve(o,(A)=>n.analyzeNested(df(y,A,n.budget),p))}if(B(y)){if(o.length>0)return Ve(o,(ee)=>n.analyzeNested(df(y,ee,n.budget),p));let x=$r(y);if(x?.[0]&&M(x[0])==="rm"&&it(x)){let ee=uf(n);if(ee)return ee}let A=x?n.analyzeChild(x,{...mn(e,r),dynamicInput:a,shellDynamicMatch:v("parallel.shell-dynamic",qr),rmDynamicMatch:v("parallel.rm-recursive-force-dynamic",Kr)}):null;if(A)return A;return n.analyzeNested(y,p)}let E=!m&&(!i||o.length>0)?(o.length>0?o:[void 0]).map((x)=>Ti(J(x===void 0?l:i?l.map((A)=>Sf(A,x)):[...l,...x]),y)):[];if(E.some((x)=>x.kind==="dynamic")){let x=Zt(n);if(x)return x}let C=E.flatMap((x)=>x.kind==="literal"?[x.source]:[]);if(C.length>0)return n.budget.charge("derivedTokens",C.length),Ve(C,(x)=>n.analyzeNested(x,p));if(Vr(y)){let x=Zt(n);if(x)return x}let P=n.analyzeNested(y,p);if(P)return P;if(u)return Zt(n);return null}let S=Ot(J(l));if(S.kind==="dynamic"||S.kind==="literal"&&B(S.source))return Zt(n)??h();if(S.kind==="literal")return h();if(o.length>0){let E=Zt(n);if(E)return E;let C=h();if(C)return C;if(i)return null;let P=o.flatMap((x)=>x[0]===void 0?[]:[x[0]]);return n.budget.charge("derivedTokens",P.length),Ve(P,(x)=>n.analyzeNested(x,p))}if(u||a)return Zt(n)??h();return null}if(e.head==="rm"&&it(l)){if(i&&o.length>0)return Ve(o,(y)=>tl(Oi(l,y,n.budget,sf),e.cwd,r));if(o.length>0)return Ve(o,(y)=>tl(mf(l,y,n.budget),e.cwd,r));let h=tl(l.flatMap((y,S)=>{if(S===0||!B(y))return[y];return y.startsWith("-")?[y.replace(sf,"")]:[]}),e.cwd,r);if(h)return h;return uf(n)}let g=o.length>0?o:[void 0];return Ve(g,(h)=>{let y=h===void 0?l:i?Oi(l,h,n.budget):mf(l,h,n.budget),S=v("parallel.shell-dynamic",qr),E=a&&e.head==="find"?Jx(y,r):null,C=yf(y,a,n)??E?.customResult??null,P=M(e.head),x=a&&(P==="rm"&&nl(y)||P==="xargs"&&Cf(y)||E?.rmOptions===!0),A=a&&(x||E?.executedSource===!0||E===null&&hf(y,P)),ee=n.analyzeChild(y,{...mn(e,r),worktreeMode:s||a||u?!1:n.worktreeMode,dynamicInput:a||u,dynamicRmInput:x,dynamicSourceInput:C!==null||A,shellDynamicMatch:S,dynamicSourceMatch:S,rmDynamicMatch:v("parallel.rm-recursive-force-dynamic",Kr)});if(A){let qe=T(S,n.policy);if(qe)return qe}return ee??C??Pt(y,n.policy?.rules??[])})}function hf(e,t){if(B(e[0]??""))return!0;if(t==="eval"||t==="source"||t===".")return!0;if(t==="parallel"||t==="xargs")return!0;if(Q.has(t))return Xx(e);if(t==="git")return Yx(e);if(t==="find")return!0;if(Be.has(t))return cf(e,$x,Hr);if(Xe(t))return cf(e,Ux,Jo);return!1}function nl(e){let t=e.indexOf("--"),n=e.slice(1,t===-1?void 0:t);if(!e.some(B))return t===-1;return n.some((o)=>B(o)&&(o.startsWith("-")||xf(o)))}function Yx(e){if(Zx(e))return!0;let t=ze(e);if(t.subcommand===null||B(t.subcommand))return!0;if(!$n.has(t.subcommand.toLowerCase()))return!1;let n=t.rest.indexOf("--"),r=t.rest.slice(0,n===-1?void 0:n);if(!e.some(B))return n===-1;return r.some(B)}function Zx(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(B(e[t+1]??""))return!0;t++;continue}if(n.startsWith("-c")&&n.length>2||n.startsWith("--config-env=")){if(B(n))return!0;continue}if(B(n))return!0}return!1}function Xx(e){if(Tt(e))return!1;let t=st(e);if(t!==null)return B(t);let n=Ot(J(e));if(n.kind==="literal")return B(n.source);if(n.kind==="dynamic")return!0;return!e.some(B)}function cf(e,t,n){let r=n(e);if(r.some((o)=>B(o.value)))return!0;if(!e.some(B))return n([...e,lf]).some((o)=>o.value===lf);return _i(r,t,(o)=>n(e.map((i)=>Sf(i,[o]))))}function yf(e,t,n){let r=n.policy?.rules??[];if(!t||r.length===0)return null;let o=r.filter((i)=>M(i.command)===M(e[0]??""));if(o.length===0)return null;if(e.slice(1).some(B))return Zt(n);return Ve(o,(i)=>Pt([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],[i]))}function Jx(e,t){let n={customResult:null,executedSource:!e.some(B),rmOptions:!1},r=!1,o=0,i=null,s=()=>{if(!i?.some(B))return;for(let a of ot(i,t))n.executedSource||=hf(a.tokens,a.head),n.rmOptions||=a.head==="rm"&&nl(a.tokens)||a.head==="xargs"&&Cf(a.tokens),n.customResult??=yf(a.tokens,!0,t)};for(let a of e.slice(1)){if(!r&&!a.startsWith("-")&&a!=="!"&&a!=="("){n.executedSource||=B(a);continue}if(r=!0,i){if(a===";"||a==="+"){s(),i=null;continue}i.push(a);continue}if(o>0){o--;continue}if(ft(a)){i=[],n.executedSource||=B(a);continue}let l=kt(a);if(l>0){o=l,n.executedSource||=B(a);continue}n.executedSource||=B(a)}return s(),n}function Cf(e){let t=e.slice(gn(e).childStart);return M(t[0]??"")==="rm"&&nl(t)}function Di(e,t){return(n)=>T(v(e,t),n.policy)}var Zt=Di("parallel.shell-dynamic",qr),Qx=Di("parallel.command-stream-dynamic",Hx),Vn=Di("parallel.command-stream-dynamic",Bx),uf=Di("parallel.rm-recursive-force-dynamic",Kr);function tl(e,t,n){return T(Ai(J(e),{environment:n.environment,cwd:t,budget:n.budget,originalCwd:n.originalCwd,strict:n.strict,paranoid:n.paranoidRm,allowTmpdirVar:n.allowTmpdirVar,tmpdirWordSplittingUnsafe:Vt(n.envAssignments??new Map,n.environment),trustedTmpdirValue:un(n.envAssignments??new Map,n.environment),protectedGitMetadata:n.protectedGitMetadata,policy:n.policy}),n.policy)}function bf(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 Sf(e,t){return e.replace(Mi,(n)=>vf(n,t))}function Oi(e,t,n,r=Mi){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=vf(i,t);return n.charge("derivedTokens",Math.max(1,Math.ceil(s.length/64))),s}))}function df(e,t,n){return Oi([e],t,n)[0]??""}function mf(e,t,n){return n.charge("derivedTokens",e.length+t.length),[...e,...t]}function vf(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 B(e){return e.search(Mi)!==-1}function Ef(e){if(rl(e))return!0;for(let t of e.matchAll(Mi))if(!/^(?:\{\}|\{\d+\})$/.test(t[0]))return!0;return!1}function rl(e){let t=e.indexOf("{=");return t!==-1&&e.indexOf("=}",t+2)!==-1}function xf(e){return/^\{[^{}\s]*\}$/.test(e)}function eR(e,t,n){if(e===void 0)return;if(e==="..."||/^~|[{}$`*?[]/.test(e))return null;if(!t&&!ff.isAbsolute(e))return null;try{return Bt(t??e,e,n)}catch{return null}}function Rf(e){let t=1,n=[],r=e.length,o=-1,i=!1,s=!1,a,l=!1,c=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=Na(e,t+1);n.push(...E.templateTokens),r=t+1,o=E.markerIndex;break}if(!p.startsWith("-")){let E=Na(e,t);n.push(...E.templateTokens),r=t,o=E.markerIndex;break}let g=e[t+1],h=p.indexOf("="),y=h===-1?p:p.slice(0,h),S=h===-1?void 0:p.slice(h+1);if(p==="--dry-run"){l=!0,t++;continue}if(p==="-I"||p.startsWith("-I")&&p.length>2){c||=(p==="-I"?g:p.slice(2))!=="{}",t+=p==="-I"?2:1;continue}if(p==="--replace"||p==="-i"){c=!0,t+=2;continue}if(y==="--replace"||p.startsWith("-i")&&p.length>2){let E=y==="--replace"?S:p.slice(2);c||=E!==""&&E!=="{}",t++;continue}if(p==="-a"||Vx.has(y)){c=!0,t+=S===void 0?2:1;continue}if(p==="--pipe"||p==="--pipepart"){s=!0,t++;continue}if(y==="--env"){c=!0,t+=S===void 0?2:1;continue}if(af.has(y)||p.startsWith("-S")&&p.length>2){i=!0,t+=af.has(p)?2:1;continue}if(Kx.has(y)){c=!0;let E=S??g;if(E===void 0||E===":::"||E==="--"){t++;continue}a=E,t+=S===void 0?2:1;continue}if(p.startsWith("-j")&&p.length>2&&/^\d+$/.test(p.slice(2))){t++;continue}if(p.startsWith("--")&&S!==void 0){t++;continue}if(jx.has(p)){if(g===void 0||g===":::"||g==="--"){c=!0,t++;continue}t+=2;continue}t+=p==="-j"||p==="--jobs"?2:1}c||=n.some(l?rl:Ef);let d=[];if(o!==-1){let p=[];for(let g=o+1;g<e.length;g++){let h=e[g];if(h===":::"){d.push(p),p=[];continue}if(h!==void 0)p.push(h)}d.push(p)}c||=d.length>1;let m=tR(d),u=n.some(B),f=n.length===0&&o===-1;return{template:n,jobs:m,childStart:r,templateHasPlaceholder:u,runsRemotely:i,usesStdin:s||o===-1,readsCommandsFromInput:f,unsupported:c,workdir:a,dryRun:l}}function tR(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)>X.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)>X.derivedTokens.cap)throw new N("derivedTokens");o.push([...i,s])}t=o}return t}function wf(e){return Rf(e).childStart}var nR="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",Ni="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function il(e){return e?.parts.some((t)=>t.provenance==="command-substitution")??!1}function ol(e){return e?.parts.some((t)=>t.provenance==="literal"&&t.raw.replace(/^["']/,"").startsWith("-"))??!1}function Af(e,t,n,r,o=!1,i){let a=(yr(e,t)||r&&e!=="powershell"&&t[0]?.provenance==="variable")&&me(i,"shell.dynamic-executable",o)?v("shell.dynamic-executable",nR):null;return T(a,i)??Pf(e,t,n,o,i)}function Pf(e,t,n,r,o){if(t.length<2)return null;let i=t.flatMap((a,l)=>il(a)?[l]:[]);if(i.length===0)return null;let s=M(t[0]?.text??"");if(s==="git"){let a=Mn(e,t),l=oR(a);if(me(o,"shell.dynamic-structure",r)&&i.some((m)=>m<=l))return T(v("shell.dynamic-structure",Ni),o);if(T(wi(a,{environment:n}),o))return null;let c=t[l]?.text.toLowerCase(),d=a.findIndex((m,u)=>u>l&&_(m)==="--");if(me(o,"shell.dynamic-structure",r)&&c&&$n.has(c)&&i.some((m)=>m>l&&(d===-1||m<d)))return T(v("shell.dynamic-structure",Ni),o);return null}if(s==="find")return me(o,"shell.dynamic-structure",r)&&iR(t)?T(v("shell.dynamic-structure",Ni),o):null;if(s==="rm"){let a=t.findIndex((c,d)=>d>0&&_(c)==="--"),l=it(t.map(_));return me(o,"shell.dynamic-structure",r)&&i.some((c)=>(a===-1||c<a)&&(c<t.length-1||!l))?T(v("shell.dynamic-structure",Ni),o):null}if(s==="xargs")return _f(e,t.slice(gn(t.map(_)).childStart),"xargs",n,r,o);if(s==="parallel")return _f(e,t.slice(wf(t.map(_))),"parallel",n,r,o);return null}function _f(e,t,n,r,o,i){if(t.length===0)return null;let s=rR(t,r);if(yr(e,s)){let l=T(v(`${n}.shell-dynamic`,n==="xargs"?el:qr),i);if(l)return l}let a=Pf(e,s,r,o,i);if(a)return a;if(s[0]?.text==="rm"&&s.slice(1).some((l)=>il(l)&&ol(l)))return T(v(`${n}.rm-recursive-force-dynamic`,n==="xargs"?Qa:Kr),i);return null}function rR(e,t){let n=an(e,t),r=n.rewritten?J(n.words.map(_)):n.words,o=r[0];return o&&_(o)==="busybox"?r.slice(1):r}function oR(e){let t=1;while(t<e.length){let n=e[t],r=n?_(n):"";if(De.has(r)){t+=2;continue}if(r.startsWith("-")){t++;continue}return t}return t}function iR(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=il(s);if(n>0){n--;continue}if(o){if(s.text===";"||s.text==="+"){o=!1,t=!0,r=!1;continue}if(a&&(r||ol(s)))return!0;r=!1;continue}if(!t&&!s.text.startsWith("-")){if(a&&(i>1||ol(s)))return!0;continue}if(t=!0,a)return!0;let l=kt(s.text);if(l>0){n=l;continue}if(ft(s.text))o=!0,r=!0}return!1}function sl(e,t){return e.some((n)=>{if(n.value==="-"&&(n.kind==="main-script"||n.kind==="program-file"))return!0;return!qo(t[n.tokenIndex],n.value)})}var sR="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",aR="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",lR="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function Tf(e,t){let n=t.slice(1);if(e==="dd"&&n.some((r)=>/^of=\/dev\/.+/.test(r)))return v("dd.device-write",sR);if((e==="mkfs"||e.startsWith("mkfs."))&&n.some((r)=>r.startsWith("/dev/")))return v("mkfs.device",aR);if(e==="shred"&&n.length>0)return v("shred.target",lR);return null}var If=[{heads:new Set(["rm","rmdir"]),analyze:(e)=>Ai(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoid:e.options.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:Vt(e.envAssignments,e.options.environment),trustedTmpdirValue:un(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,policy:e.options.policy,budget:e.options.budget})},{heads:new Set(["git"]),analyze:(e)=>wi(e.words,al(e))},{heads:new Set(["find"]),analyze:(e)=>cm(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:Vt(e.envAssignments,e.options.environment),trustedTmpdirValue:un(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,budget:e.options.budget,envAssignments:e.envAssignments,policy:e.options.policy,analyzeTokens:e.analyzeChildTokens,analyzeNested:(t,n)=>hn(e.options.analyzeNested(t,n))})},{heads:new Set(["xargs"]),analyze:(e)=>Jm(e.words,{...kf(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>hn(e.options.analyzeNested(t,n))})},{heads:new Set(["parallel"]),analyze:(e)=>gf(e.words,{...kf(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>hn(e.options.analyzeNested(t,n))})}];function kf(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 hn(e){return e?{id:e.ruleId??"",reason:e.reason,intent:e.intent??"manual_only"}:null}function al(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 Nf(e){return If.find((t)=>t.heads.has(e))?.analyze}function qn(e,t,n){let r=n.trace;if(e.length===0)return null;let o=n.commandView?.dialect??"posix",i=(R)=>R.map((I)=>o==="posix"?_(I):I.text),s=n.child,a=s!==void 0&&!s.embedded,l=s?.embedded===!0,c=n.effectiveCwd===null,d=s?s.cwd:c?void 0:n.effectiveCwd??n.cwd,m=s?s.originalCwd:c?void 0:n.cwd,u=ni(e);if(u.envAssignments.size>0)r?.recordSegment({type:"env-strip",input:i(e),envVars:[...u.envAssignments.keys()],output:i(u.words)});let f=an(u.words,n.environment,d,new Map([...n.envAssignments??[],...u.envAssignments])),p=f.envSplitValues??[];if(p.length>0){let R=[...p,...i(f.words)].join(" "),I=$e(R);if(I)return r?.recordSegment({type:"dangerous-text",token:R,matched:!0,reason:I.reason}),ve(I);if(n.strict)return ke(r);let G=ri(p,i(f.words));if(G){n.budget.charge("derivedTokens",G.length);let ce=n.analyzeNested(G.join(" "),{effectiveCwd:f.cwd===void 0?n.effectiveCwd:f.cwd,envAssignments:new Map([...n.envAssignments??[],...u.envAssignments,...f.envAssignments])});if(ce)return ce}}let g=f.rewritten?J(i(f.words)):Mn(o,f.words),h=i(g),y={...n,wrapperNormalizationBudget:n.wrapperNormalizationBudget??{iterations:0}};if(r&&u.words.length>g.length){let R=i(u.words);r.recordSegment({type:"leading-tokens-stripped",input:R,removed:R.slice(0,R.length-g.length),output:h})}let S=new Map([...n.envAssignments??[],...u.envAssignments,...f.envAssignments]),E=h[0];if(!E)return null;if(dn(E))throw new N("wrapperPeelIterations");let C=M(E),P=f.cwd===null?void 0:f.cwd??d,x=f.cwd===null?void 0:m,A=f.cwd===void 0?n.effectiveCwd:f.cwd,ee=s?s.allowTmpdirVar:!Lr(S,n.environment),qe=Af(o,f.words,n.environment,t===0,n.strict,n.policy);if(qe)return r?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:qe.reason}),ve(qe);let ct=bi(h,n.policy);if(ct){for(let R of[ct.childIndex,...ct.alternativeChildIndices]){Of(y.wrapperNormalizationBudget);let I=g.slice(R);r?.recordSegment({type:"transparent-wrapper",wrapper:ct.wrapper,output:i(I)});let G=qn(I,t,{...y,effectiveCwd:A,envAssignments:S});if(G)return G}return null}let xe=l?void 0:C==="eval"?Pi(g):C==="trap"&&!a?Um(g):void 0;if(a&&s&&C==="eval"){if(xe?.kind==="dynamic")return Kn(s,n.policy);if(xe?.kind==="literal"){let R=n.analyzeNested(xe.source,{effectiveCwd:A,envAssignments:S});if(R)return R}return Yn(s,n.policy)}if(xe?.kind==="dynamic"&&(n.strict||!n.commandView||!Xa(n.commandView)))return ke(r);if(xe?.kind==="literal"){r?.recordSegment({type:"recurse",reason:C==="eval"?"shell-eval":"shell-trap",innerCommand:xe.source,depth:t+1});let R=n.analyzeNested(xe.source,{effectiveCwd:A,envAssignments:S,functionDefinitions:n.functionDefinitions});if(R)return R}if(a?Q.has(C):Wf(E,C)){if(Tt(h))return null;if(a&&s){let R=st(h);if(R){if(s.dynamicSourceInput??s.dynamicInput){let G=Kn(s,n.policy);if(G)return G}if(Vr(R)){let G=Kn(s,n.policy);if(G)return G}return n.analyzeNested(R,{effectiveCwd:A,envAssignments:S})}let I=Ot(g);if(I.kind==="dynamic")return Kn(s,n.policy);if(I.kind==="literal")return s.dynamicSourceInput?Kn(s,n.policy):null;return s.dynamicSourceInput??s.dynamicInput?Kn(s,n.policy):null}if(l){let R=st(h),I=R?n.analyzeNested(R,{effectiveCwd:A,envAssignments:S}):Ot(g).kind==="dynamic"?ke(r):null;if(I)return I}if(s===void 0){let R=mR(h,S,A,n,r,t);if(R)return R;let I=st(h);if(I){let En=Ti(g,I);if(En.kind==="dynamic")return ke(r);let Yi=En.kind==="literal"?En.source:jm(g,I),Ll=fR(Yi);r?.recordSegment({type:"shell-wrapper",wrapper:C,innerCommand:Ll}),r?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:Ll,depth:t+1});let Wl=n.analyzeNested(Yi,{effectiveCwd:A,envAssignments:S});if(Wl)return Wl;return Vr(Yi)?ke(r):null}let G=Ot(g,n.strict?void 0:n.shellAssignments);if(G.kind==="dynamic")return ke(r);if(G.kind==="literal")return Li(G.source,A,S,n,r,t);let ce=Vm(g,n.commandView?.redirections??[],n.hasPipelineInput??!1,n.literalShellInput);if(ce.kind==="dynamic")return ke(r);if(ce.kind==="literal")return r?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:ce.source,depth:t+1}),n.analyzeNested(ce.source,{effectiveCwd:A,envAssignments:S})}}if(!s&&(C==="source"||C===".")){let R=h[1]==="-p"?2:null;if(R!==null){let En=n.commandView?g[R]:void 0;if(!En)return null;if(En.provenance!=="literal")return ke(r)}let I=R===null?1:3,G=h[I]==="--"?I+1:I,ce=n.commandView?g[G]:void 0;if(!ce)return null;if(ce.provenance==="literal")return Li(ce.text,A,S,n,r,t);if(n.strict||!n.commandView||!Xa(n.commandView))return ke(r)}if(Be.has(C)&&!l){if(!s&&n.strict&&sl(Hr(h),g))return ke(r);let R=rm(h,(G)=>hn(n.analyzeNested(G,{effectiveCwd:A,envAssignments:S}))),I=T(R,n.policy);if(I)return r?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:I.reason}),ve(I)}if(Xe(C)&&!l){if(!s&&n.strict&&sl(Jo(h),g))return ke(r);let R=ld(h);if(a&&s)return uR(C,R,A,S,n,s);if(R){let I=me(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(r?.recordSegment({type:"interpreter",interpreter:C,codeArg:R,paranoidBlocked:I}),I){let ce=T(v("interpreter.one-liner-paranoid",_r),n.policy);if(ce)return ve(ce)}if(da(C,R))return null;r?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:R,depth:t+1});let G=n.analyzeNested(R,{effectiveCwd:A,envAssignments:S});if(G&&!Lf(G,R))return G;if(Ar(R,void 0,!n.strict)){let ce=T(v("interpreter.dangerous-command",Ln),n.policy);if(ce)return r?.recordSegment({type:"dangerous-text",token:R,matched:!0,reason:Ln}),ve(ce)}r=void 0}}if(C==="busybox"&&h.length>1)return Of(y.wrapperNormalizationBudget),r?.recordSegment({type:"busybox",subcommand:h[1]??"unknown"}),r?.recordSegment({type:"recurse",reason:"busybox",innerCommand:h.slice(1).join(" "),depth:t+1}),qn(g.slice(1),t,{...y,effectiveCwd:A,envAssignments:S});let H=s?null:T(Tf(C,h),n.policy);if(H)return r?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:H.reason}),ve(H);let oe=r===y.trace?y:{...y,trace:r},ne={words:g,head:C,cwd:P,originalCwd:x,envAssignments:S,allowTmpdirVar:ee,dynamicArguments:f.words.some((R)=>R.provenance==="command-substitution"),depth:t,effectiveCwd:A,options:oe,analyzeChildTokens:(R,I)=>a&&s?ll(R,t,oe,{...s,cwd:I??void 0,effectiveCwd:I??void 0}):hn(qn(J(R),t+1,{...oe,child:void 0,commandView:void 0,effectiveCwd:I,envAssignments:S}))??Pt(R,oe.policy.rules),analyzeChild:(R,I)=>ll(R,t,oe,I)},ie=s&&(C==="xargs"||C==="parallel")?void 0:Nf(C);if(C==="rm"||C==="xargs"||C==="parallel")r?.recordSegment({type:"tmpdir-check",tmpdirValue:S.has("TMPDIR")||n.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:ee});let Oe=r&&C==="git"?Nm(ne.words,al(ne)):void 0,Nt=Mf(Oe?Oe.match:ie?.(ne)??null,n.policy);if(r)pR(ne,Nt,Oe?.relaxation??null);if(Nt)return ve(Nt);if(a&&s&&(C==="rm"||C==="rmdir")){if(!(C==="rm"&&(it(h)||s.dynamicRmInput)))return null;return(s.dynamicRmInput?Yn(s,n.policy):null)??dR(s,n.policy)}let no=!s&&ie===void 0&&!Eo.has(C),Ct=r&&no?[]:void 0;if(no)for(let R=1;R<h.length;R++){let I=h[R];if(!I)continue;Ct?.push(I);let G=Mf(cR(h,R,t,oe,P,x,A,S),n.policy);if(G)return r?.recordSegment({type:"fallback-scan",tokensScanned:Ct??[],embeddedCommandFound:M(I)}),ve(G)}if(r?.recordSegment({type:"fallback-scan",tokensScanned:Ct??[]}),l&&s&&!s.wrappedByTransparent)return null;let ro=Pt(h,n.policy.rules);if(r?.recordSegment({type:"custom-rules-check",rulesChecked:n.policy.rules.length>0,matched:!!ro,reason:ro?.reason}),ro)return ve(ro);return a&&s?Yn(s,n.policy):null}function ll(e,t,n,r){return hn(qn(J(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 cR(e,t,n,r,o,i,s,a){for(let l of ot(e.slice(t),{environment:r.environment,cwd:o,envAssignments:a,policy:r.policy})){let c=l.tokens[0];if(!c)continue;let d=M(c);if(Wf(c,d)||Nf(d)!==void 0&&d!=="xargs"&&d!=="parallel"||l.wrappedByTransparent&&r.policy.rules.length>0)r.budget.charge("derivedTokens",e.length-t);let u=ll(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:!Lr(l.envAssignments,r.environment),worktreeMode:!1,wrappedByTransparent:l.wrappedByTransparent});if(u)return u}return null}function uR(e,t,n,r,o,i){if(!t)return Yn(i,o.policy);if(me(o.policy,"interpreter.one-liner-paranoid",!!o.paranoidInterpreters)){let a=T(v("interpreter.one-liner-paranoid",_r),o.policy);if(a)return ve(a)}if(da(e,t))return Yn(i,o.policy);let s=o.analyzeNested(t,{effectiveCwd:n,envAssignments:r});if(s&&!Lf(s,t))return s;if(Ar(t,void 0,!o.strict)){let a=T(v("interpreter.dangerous-command",Ln),o.policy);if(a)return ve(a)}return Yn(i,o.policy)}function Lf(e,t){let n=e.ruleId==="raw-text.dangerous-command",r=(e.reason.startsWith(hi)||e.reason===Hn)&&!xo(t);return n||r}function Kn(e,t){let n=e.shellDynamicMatch?T(e.shellDynamicMatch,t):null;return n?ve(n):null}function Yn(e,t){let n=e.dynamicSourceInput&&e.dynamicSourceMatch?T(e.dynamicSourceMatch,t):null;return n?ve(n):null}function dR(e,t){let n=e.dynamicInput&&e.rmDynamicMatch?T(e.rmDynamicMatch,t):null;return n?ve(n):null}function mR(e,t,n,r,o,i){let s=lm(e);if(s.argvSource?.kind==="absent")return ke(o);if(s.argvSourceApplies&&s.argvSource){let l=Li(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 Li(a,n,t,r,o,i,!0)}function Li(e,t,n,r,o,i,s=!1){if(s&&/[$`*?[\]]/.test(e))return ke(o);let a=wr(e,t,r.environment.paths,r.budget),l=a?r.literalHeredocFiles?.get(a):void 0;if(l===void 0)return s?ke(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 fR(e){let t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.at(-1)===t?e.slice(1,-1):e}function pR(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 Of(e){if(e.iterations>=X.wrapperPeelIterations.cap)throw new N("wrapperPeelIterations");e.iterations++}function ve(e){return{reason:e.reason,ruleId:e.id||void 0,intent:e.intent}}function ke(e){return e?.recordSegment({type:"error",message:Fr}),ve(gR())}function gR(){return{id:"",reason:Fr,intent:"stop_and_explain"}}function Wf(e,t){return Q.has(t)||e==="$SHELL"||e==="${SHELL}"||Q.has(k(t))}function Mf(e,t){return e?.id.startsWith("custom.")||e?.id==="raw-text.dangerous-command"?e:T(e,t)}var hR=/^\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 CR(e,t){let n=zf(e,t);if(n.length===0)return!1;let r=n[Ff(n)];if(r==="cd"||r==="pushd"||r==="popd")return!0;return hR.test(e.join(" "))}function Gf(e,t,n,r,o){if(e.dialect==="powershell"){let y=bR(e.words,o);if(y.kind==="none")return;if(!t||y.kind==="unknown")return null;return Df(xR(y.target),t,n.paths)}let i=e.words.map(_),s=i.some((y)=>/^CDPATH\+?=/.test(y));if(!CR(i,n))return s?null:void 0;if(!t)return null;let a=zf(i,n,t),l=Ff(a);if(l===-1||a[l]!=="cd")return null;let c=a.slice(l+1),d=c.findIndex((y)=>y.length<=1||!y.startsWith("-")||y==="--");if((d===-1?c:c.slice(0,d)).some((y)=>!/^-[LP]+$/.test(y)))return null;let u=d===-1?[]:c.slice(d),f=u[0]==="--"?u.slice(1):u;if(f.length!==1)return null;let p=f[0]??"",g=e.words.find((y)=>y.provenance==="variable"&&y.text===p),h=g?pt(g,r):p;if(h===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(h)&&(s||n.env.has("CDPATH")))return null;return Df(h,t,n.paths)}function Df(e,t,n){if(!e||e==="-"||e.startsWith("~")||e.includes("$")||e.includes("`"))return null;try{let r=Bt(t,e,n);return n.isDirectory(r)?r:null}catch{return null}}function bR(e,t){let n=SR(e[0])?1:0,r=e[n];if(!vR(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 ER(e.slice(n+1),t)}function SR(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&(e.text==="&"||e.text===".")}function vR(e,t){return e?.provenance==="literal"&&(t||!e.quoted&&e.raw===e.text)}function ER(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 xR(e){return e.includes("::")?void 0:e.replaceAll("\\","/")}function Ff(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 zf(e,t,n){let r=RR(e);return $t([...r],t,n)}function RR(e){let t=0;while(t<e.length){let n=e[t];if(n!=="{"&&n!=="("&&n!=="$(")break;t++}return e.slice(t)}var wR="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",yn="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 pl(e,t,n,r){if(t>=X.recursionDepth.cap)return n.trace?.recordSegment({type:"error",message:ut}),{reason:ut,segment:e,intent:"stop_and_explain"};let o=r??n.factStore?.getCommandProgram(e,n.shell??"auto")??Je(e,n.shell);if(o.status==="limited")return n.trace?.recordSegment({type:"error",message:ut}),{reason:ut,segment:e,intent:"stop_and_explain"};if(o.status==="invalid"){let c=o.issues.find((d)=>d.code.includes("heredoc"));if(c){if(!n.strict)return fl(e,n);let d=`${hi}: ${c.message}`;return n.trace?.recordGlobal({type:"error",message:d}),{reason:d,segment:e,intent:"stop_and_explain"}}return Vf(e,n),{reason:Hn,segment:e,intent:"stop_and_explain"}}if(n.strict&&o.status==="partial")return Vf(e,n),{reason:Hn,segment:e,intent:"stop_and_explain"};if(o.issues.some((c)=>c.code.includes("quote")))return fl(e,n);let s=n.cwd,a=n.effectiveCwd!==void 0?n.effectiveCwd:n.cwd,l=Em(n.environment.env,n.envAssignments);return Fi(o,t,{...n,rootProgram:o},s,[{effectiveCwd:a,shellGitContextState:l,literalHeredocFiles:new Map(n.literalHeredocFiles),functionDefinitions:new Map(n.functionDefinitions),createdDirectories:new Set}]).result}function Fi(e,t,n,r,o){let i=[...o],s,a,l;for(let[c,d]of e.nodes.entries()){if(d.kind==="connector"){a=d.operator;continue}let m=e.nodes[c+1],u=m?.kind==="connector"?m.operator:void 0,f=_R(e,c,d,a,u),g=a==="&&"||a==="||"?s:void 0,h=a==="&&"?g?.success??i:a==="||"?g?.failure??i:i,y=a==="||"?g?.success??[]:[],S=a==="&&"?g?.failure??[]:[],E={connector:a,skippedSuccessStates:y,skippedFailureStates:S};if(Xt(u)&&!Xt(a))l=E;let C=Xt(u)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:Xt(a)?l??E:E,P=Cn(C.connector)||Cn(u);if(d.kind==="function"){let Z=h.flatMap((oe)=>{let ne=Xn(oe);return ne.functionDefinitions.set(d.name,d.body),cl(oe,[ne],f,u==="&",Cn(u))}),H=ul(Z,[],C.skippedSuccessStates,C.skippedFailureStates,C.connector,u);i=H.states,s=H.conditionalStates,a=void 0;continue}if(d.kind==="group"){let Z=[],H=[];for(let ne of h){let ie=Fi(d.body,t,n,r,[Xn(ne)]);if(ie.result)return ie;if(Z.push(...cl(ne,ie.states,f,u==="&",Cn(u))),P)H.push(ne,...f?ie.states.map((Oe)=>Wi(ne,Oe)):ie.states)}let oe=ul(Z,H,C.skippedSuccessStates,C.skippedFailureStates,C.connector,u);i=oe.states,s=oe.conditionalStates,a=void 0;continue}if(d.kind!=="command")continue;let x=n.trace?.flattenNested?n.trace.currentSegmentIndex:n.trace?.allocateSegment(),A=e.nodes[c-2],ee=Xt(a)&&A?.kind==="command"?$m(A)??PR(A):void 0,qe=[],ct=[];for(let Z of h){let H=TR(d,t,n,r,[Xn(Z)]);if(H.result)return{result:H.result,states:i};let oe=e.dialect==="powershell"?H.states:H.states.map((ne)=>Wi(Z,ne));for(let ne of oe){let ie=Xn(ne),Oe=OR(d,t,n.trace?{...n,trace:Kf(n.trace,x)}:n,r,ie,Xt(a),ee);if(Oe)return{result:Oe,states:i};let Nt=JR(d,ie.functionDefinitions);if(Nt)n.budget.charge("derivedTokens",zi(Nt));let nr=Nt?t+1>=X.recursionDepth.cap?dl(d.displayText,n,[ie]):Fi(Nt,t+1,n,r,[ie]):{result:null,states:ZR(d,ie)};if(nr.result)return nr;qe.push(...cl(Z,nr.states,f,u==="&",Cn(u)));let no=typeof ie.effectiveCwd==="string"&&ie.effectiveCwd!==ne.effectiveCwd&&d.redirections.every((Ct)=>["<",">",">>",">|"].includes(Ct.operator)&&Ct.target?.text==="/dev/null");if(P&&!no)ct.push(Z),ct.push(...nr.states.map((Ct)=>f?Wi(Z,Ct):Ct))}}let xe=ul(qe,ct,C.skippedSuccessStates,C.skippedFailureStates,C.connector,u);i=xe.states,s=xe.conditionalStates,a=void 0}return{result:null,states:i}}function _R(e,t,n,r,o){if(n.kind==="group"&&n.style==="subshell")return!0;if(e.dialect==="posix"&&(Xt(r)||Xt(o)))return!0;if(o==="&")return!0;return e.dialect==="powershell"&&n.kind==="group"&&n.style==="brace"&&AR(e,t)}function cl(e,t,n,r,o){let i=n?t.map((a)=>Wi(e,a)):[...t],s=o?i.flatMap((a)=>Zn(e.literalHeredocFiles,a.literalHeredocFiles)?[a]:[{...a,literalHeredocFiles:new Map(e.literalHeredocFiles)},a]):i;return r?[e,...s]:s}function Wi(e,t){return{...e,literalHeredocFiles:new Map(t.literalHeredocFiles),createdDirectories:new Set(t.createdDirectories)}}function AR(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(kR(n))return!0;return n.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function Xt(e){return e==="|"||e==="|&"}function PR(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 Cn(e){return e==="&&"||e==="||"}function ul(e,t,n,r,o,i){let s={success:Gi([...n,...e]),failure:Gi([...r,...t])},a=Cn(i)?s:void 0;return{states:Cn(o)||a?Gi([...s.success,...s.failure]):s.success,conditionalStates:a}}function Kf(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 TR(e,t,n,r,o){let i=e.nested.map((s)=>({program:s,depth:t}));if(e.dialect==="powershell"){let s=IR(e);if(s){if(t+1>=X.recursionDepth.cap)return dl(s,n,o);let a=Je(s,"powershell");if(a.status==="limited")return dl(s,n,o);if(a.status!=="complete")return Hf(i,n,r,o);n.budget.charge("derivedTokens",zi(a)),i.push({program:a,depth:t+1})}}return Hf(i,n,r,o)}function kR(e){let t=e.words[0];return t?.provenance==="variable"&&e.words.at(-1)?.text==="="?t.text.toLowerCase():void 0}function Hf(e,t,n,r){let o=[...r];for(let i of e){let s=[];for(let a of o){let l=Fi(i.program,i.depth,t,n,[Xn(a)]);if(l.result)return l;s.push(...l.states)}o=Gi(s)}return{result:null,states:o}}function IR(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 zi(e){return e.nodes.reduce((t,n)=>t+(n.kind==="command"?n.words.length+n.nested.reduce((r,o)=>r+zi(o),0):n.kind==="group"||n.kind==="function"?zi(n.body):0),0)}function dl(e,t,n){return t.trace?.recordSegment({type:"error",message:ut}),{result:{reason:ut,segment:e,intent:"stop_and_explain"},states:[...n]}}function OR(e,t,n,r,o,i,s){let a={...n,environment:{...n.environment,env:o.shellGitContextState.env,paths:WR(n.environment.paths,o.createdDirectories,n.budget)}},l=$R(e,!a.strict);if(l&&a.strict)return a.trace?.recordSegment({type:"error",message:l}),{reason:l,segment:e.source,intent:"stop_and_explain"};qf(e,o,"before-consumer",a.environment.paths,a.budget);let c=Mn(e.dialect,e.words),d=c.map(_),m=e.displayText,u=Sm(c,o.shellGitContextState),f=Rm(u,o.shellGitContextState);if(e.dialect==="powershell"){let h=T(Yd(e,i,ew(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 QR(m,h)}if(d.length===1&&d[0]?.includes(" ")&&!yr(e.dialect,e.words)){let h=T($e(d[0]),a.policy),y=h!==null&&!a.strict&&id(e,a.rootProgram);if(h&&!y)return a.trace?.recordSegment({type:"dangerous-text",token:d[0],matched:!0,reason:h.reason}),{reason:h.reason,segment:m,ruleId:h.id,intent:h.intent};a.trace?.recordSegment({type:"dangerous-text",token:d[0],matched:!1});let S=Bf(e,l,o,f,s,a);if(S)return S;return ja(u,o.shellGitContextState),null}let p=qn(e.words,t,{...a,commandView:e,cwd:r,effectiveCwd:o.effectiveCwd,envAssignments:f,shellAssignments:o.shellGitContextState.shellAssignments,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:o.functionDefinitions,hasPipelineInput:i,literalShellInput:s,analyzeNested:(h,y)=>{let S=y&&Object.hasOwn(y,"effectiveCwd")?y.effectiveCwd:o.effectiveCwd,E=pl(h,t+1,{...a,effectiveCwd:S,envAssignments:y?.envAssignments??f,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:y?.functionDefinitions,worktreeMode:y?.worktreeMode??a.worktreeMode,trace:a.trace?Kf(a.trace,a.trace.currentSegmentIndex,!0):void 0});return E?{reason:E.reason,ruleId:E.ruleId,intent:E.intent}:null}});if(p)return{...p,segment:m};let g=Bf(e,l,o,f,s,a);if(g)return g;return ja(u,o.shellGitContextState),null}function Bf(e,t,n,r,o,i){let s=UR(e,t,n,r??new Map,i);if(s)return s;return qf(e,n,"after-consumer",i.environment.paths,i.budget),n.literalHeredocFiles.clear(),NR(e,t,n,i.environment.paths,i.budget),GR(e,n,i.environment.paths,i.budget),KR(e,n,o,i.environment,i.trace),null}var MR=new Set([">>","<>"]);function qf(e,t,n,r,o){for(let s of e.redirections){if(!(n==="before-consumer"?DR(s):MR.has(s.operator)))continue;$f(s.target,t,r,o)}if(n!=="before-consumer"||!ge(e.words[0],"tee"))return;let i=Zf(e.words.slice(1));if(!i)return;for(let s of i.operands)$f(s,t,r,o)}function DR(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 $f(e,t,n,r){let o=e?.provenance==="literal"?wr(e.text,t.effectiveCwd,n,r):void 0;if(!o)return;t.literalHeredocFiles.delete(o)}function NR(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 LR(e,n.shellGitContextState.shellAssignments)){let a=wr(s,n.effectiveCwd,r,o);if(!a||!ad(a))continue;if(!n.literalHeredocFiles.has(a)&&n.literalHeredocFiles.size>=X.trackedHeredocFiles.cap)throw new N("trackedHeredocFiles");n.literalHeredocFiles.set(a,i.body)}}function LR(e,t){let n=ml(HR(e.redirections)?.target,t),r=n===void 0?[]:[n];if(ge(e.words[0],"cat"))return zR(e.words)?r:[];if(!ge(e.words[0],"tee"))return[];let o=Zf(e.words.slice(1),t);if(!o||o.append||o.hasUnsupportedOptions)return[];let i=o.operands.map((s)=>ml(s,t));if(!i.every((s)=>s!==void 0))return[];return[...i,...r]}function ml(e,t){if(BR(e))return e.text;return(e&&pt(e,t))??void 0}function WR(e,t,n){if(t.size===0)return e;let r=(o)=>{let i=O(o,e,n);return[...t].some((s)=>s===i||s.startsWith(`${i}${Ke.sep}`))};return{realpath:(o)=>e.realpath(o)??(r(o)?O(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 GR(e,t,n,r){if(t.shellGitContextState.bodyDepth>0||!ge(e.words[0],"mkdir"))return;let o=e.words.slice(1).map((c)=>ml(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("..")||!Ke.isAbsolute(c)&&!l)continue;let d=O(Ke.resolve(l??"",c),n,r);if(a?FR(d,n):n.isDirectory(Ke.dirname(d))&&Yf(d,n))t.createdDirectories.add(d)}}function FR(e,t){let n=Ke.parse(e).root,r=e.slice(n.length).split(/[\\/]+/).filter(Boolean),o=(s)=>Ke.join(n,...r.slice(0,s+1)),i=r.findIndex((s,a)=>!t.isDirectory(o(a)));return i===-1||Yf(o(i),t)}function Yf(e,t){try{return t.entryKind(e)==="missing"}catch{return!1}}function zR(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 HR(e){let t=e.findLast((n)=>(n.fd??([">",">|",">>",">&"].includes(n.operator)?1:0))===1);return t?.operator===">"||t?.operator===">|"?t:void 0}function Zf(e,t=new Map){let n=[],r=!0,o=!1,i=!1;for(let s of e){if(s.provenance!=="literal"&&pt(s,t)===null)return;if(r&&ge(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 BR(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 ge(e,t){return e?.text===t&&e.raw===t&&e.provenance==="literal"&&!e.quoted}function gl(e){return e.quotedDelimiter||!/[$`\\]/.test(e.body)}function $R(e,t){let n=e.redirections.filter((l)=>l.operator==="<<"||l.operator==="<<-");if(n.length===0)return;if(n.length!==1)return yn;let r=n[0];if(!r?.heredoc)return yn;let o=/\$\(|`/.test(r.heredoc.body);if(!gl(r.heredoc)&&(!t||o))return wR;if(r.fd!==void 0&&r.fd!==0)return yn;if(e.redirections.some((l)=>l!==r&&["<","<<","<<-","<<<","<&","<>"].includes(l.operator)))return yn;let i=e.redirections.some((l)=>l!==r&&Uf(l.target));if(ge(e.words[0],"cat"))return i?yn:void 0;if(ge(e.words[0],"tee"))return i||e.words.slice(1).some(Uf)?yn:void 0;let s=e.words[0],a=e.words[1];if(ge(s,"git")&&(ge(a,"apply")||ge(a,"commit")))return;if(ge(s,"gh")&&(ge(a,"pr")||ge(a,"issue"))&&ge(e.words[2],"create"))return;return yn}function Uf(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}function UR(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(VR(e,i,n,r,o))return null;let a=jR(e,i,o);if(a!==void 0)return a?{reason:a.reason,segment:e.displayText,ruleId:a.id,intent:a.intent}:null;let l=fl(s.length===i.length?s.join(`
|
|
42
|
-
`):e.source,o);return l?{...l,segment:e.displayText}:null}function jR(e,t,n){let r=t.length===1?t[0]:void 0;if(!r?.heredoc||!gl(r.heredoc)||r.fd!==void 0&&r.fd!==0)return;let o=ge(e.words[0],"uv")&&ge(e.words[1],"run")?e.words.slice(2):e.words,i=o[0];if(i?.provenance!=="literal"||!Xe(i.text))return;let s=o.findIndex((m)=>ge(m,"-"));if(!o.slice(1,s===-1?void 0:s).every((m)=>m.provenance==="literal"&&m.text.startsWith("-")))return;let l=r.heredoc.body,c=me(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(n.trace?.recordSegment({type:"interpreter",interpreter:i.text,codeArg:l,paranoidBlocked:c}),c){let m=T(v("interpreter.one-liner-paranoid",_r),n.policy);if(m)return m}if(!Ar(l,void 0,!n.strict))return null;let d=T(v("interpreter.dangerous-command",Ln),n.policy);if(!d)return null;return n.trace?.recordSegment({type:"dangerous-text",token:l,matched:!0,reason:d.reason}),d}function VR(e,t,n,r,o){let i=t.length===1?t[0]:void 0;if(!i?.heredoc||!gl(i.heredoc)||i.fd!==void 0&&i.fd!==0)return!1;let s=an(e.words,o.environment,n.effectiveCwd,r),a=s.words.map(_),l=M(a[0]??"");if((s.envSplitValues?.length??0)>0||!Q.has(l)&&!Q.has(k(l)))return!1;return Tt(a)}function KR(e,t,n,r,o){let i=Gf(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 qR=/^[A-Za-z_][A-Za-z0-9_]*$/,YR=8;function ZR(e,t){let n=e.words[1]?.text;if(e.dialect!=="posix"||e.words[0]?.text!=="for"||n===void 0||!qR.test(n))return[t];let r=e.words.slice(3);if(!(e.words[2]?.text==="in"&&r.length>=1&&r.length<=YR&&r.every((i)=>i.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(i.text))))return t.shellGitContextState.shellAssignments.delete(n),[t];return r.map((i)=>{let s=Xn(t);return s.shellGitContextState.shellAssignments.set(n,i.text),s})}function Xn(e){return{effectiveCwd:e.effectiveCwd,shellGitContextState:xm(e.shellGitContextState),literalHeredocFiles:new Map(e.literalHeredocFiles),functionDefinitions:new Map(e.functionDefinitions),createdDirectories:new Set(e.createdDirectories)}}function Gi(e){let t=[];for(let n of e){if(!t.some((r)=>XR(r,n)))t.push(n);if(t.length>X.controlFlowStates.cap)throw new N("controlFlowStates")}return t}function XR(e,t){return e.effectiveCwd===t.effectiveCwd&&Zn(e.shellGitContextState.env,t.shellGitContextState.env)&&Zn(e.literalHeredocFiles,t.literalHeredocFiles)&&Zn(e.functionDefinitions,t.functionDefinitions)&&Zn(e.shellGitContextState.effectiveEnvAssignments,t.shellGitContextState.effectiveEnvAssignments)&&Zn(e.shellGitContextState.shellAssignments,t.shellGitContextState.shellAssignments)&&e.shellGitContextState.bodyDepth===t.shellGitContextState.bodyDepth&&jf(e.shellGitContextState.bodyAssignments,t.shellGitContextState.bodyAssignments)&&jf(e.createdDirectories,t.createdDirectories)}function jf(e,t){return e.size===t.size&&[...e].every((n)=>t.has(n))}function Zn(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 JR(e,t){let n=Cr(e);return n===void 0?void 0:t.get(n)}function QR(e,t){if(!t)return null;return{reason:t.reason,segment:e,ruleId:t.id,intent:t.intent}}function ew(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 fl(e,t){let n=T($e(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 Vf(e,t){let n={type:"strict-unparseable",rawCommand:e,reason:Hn},r=t.trace?.currentSegmentIndex;if(r===void 0)t.trace?.recordGlobal(n);if(r!==void 0)t.trace?.recordSegment(n)}var tw=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function Xf(e,t,n,r){let o=pl(e,0,{...t,...Au(t),budget:t.budget??ue(),factStore:r},n);if(!o)return null;return{kind:"deny",reason:o.reason,intent:o.intent??"manual_only",...o.ruleId?{ruleId:o.ruleId}:{},evidence:{command:e,segment:o.segment}}}function Jf(e,t,n){try{return{decision:e()}}catch(r){let o=nw(r,t,n);if(!o)throw r;return o}}function nw(e,t,n){if(!(e instanceof N)||!tw.has(e.kind))return null;let r=X[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,intent:"stop_and_explain",evidence:{command:t,segment:t}},errorCode:r.errorCode}}var rw=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),yl=new Set(["cc-safety-net","ccsn"]),ow=new Set(["bunx","npx","pnpx"]),iw=new Set(["pnpm","yarn"]),sw=new Set(["npm","pnpm","yarn"]),aw=new Set(["bun","node"]);function Bi(e,t,n={}){if(yl.has(e))return 0;if(ow.has(e)){if(n.broad)return hl(t);let o=t[0]==="-y"||t[0]==="--yes"?1:0;return Hi(t[o])?o+1:null}let r=n.broad?t.findIndex((o)=>!o.startsWith("-")):0;if(r!==-1&&sw.has(e)&&n.broad&&t[r]==="exec"){let o=hl(t.slice(r+1));return o===null?null:r+1+o}if(iw.has(e)){if(e==="yarn"&&!n.broad)return null;if(!n.broad)return t[0]==="dlx"&&Hi(t[1])?2:null;if(r===-1||t[r]!=="dlx")return null;let o=hl(t.slice(r+1));return o===null?null:r+1+o}if(aw.has(e)){let o=n.broad&&r!==-1?r:0;if(Qf(t[o]))return o+1;if(e==="bun"&&t[o]==="run"&&Qf(t[o+1]))return o+2}return null}function hl(e){let t=e.findIndex((r)=>Hi(r));if(t===-1)return null;let n=t;while(n<e.length){let r=e[n]??"";if(!r.startsWith("-")&&!Hi(r))break;n++}return n}function Hi(e){if(!e)return!1;let t=e.indexOf("@");if(t===-1)return yl.has(e);if(t===0)return!1;let n=e.slice(t+1);if(n===""||n.includes("/")||n.includes(":"))return!1;return yl.has(e.slice(0,t))}function Qf(e){let t=e?.replaceAll("\\","/");return[...rw].some((n)=>t===n||t?.endsWith(`/${n}`))}var ep="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 tp(e,t,n){let r=Pe(e,"input-candidate");if(!r)return null;let o=Gn(r.shell,e.invocation.context.executionCwd,t,n,{findSegmentTarget:(i)=>lw(i,t),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return o?{target:o}:null}function lw(e,t){let n=$t([...e],t),r=n.slice(1),o=Bi(k(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}var Yr=require("node:path");var ip="This path contains the protected policy config and you must not modify or delete it.",cw=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function sp(e,t,n){let r=gw(e.invocation.context,t,n);if(e.invocation.route.kind==="patch")return np(e.paths,!1,e.invocation.context.executionCwd,r,t,n);let o=Pe(e,"input-candidate");if(e.invocation.route.kind==="command")return o?rp(o.shell,e.invocation.context.executionCwd,r,t,n):null;if(e.invocation.route.kind==="unknown"&&o){let i=rp(o.shell,e.invocation.context.executionCwd,r,t,n);if(i)return i}return np(e.paths,e.invocation.route.kind==="grep"||e.invocation.route.kind==="glob"||lo(e.invocation.toolName),e.invocation.context.executionCwd,r,t,n)}function np(e,t,n,r,o,i){if(t)return null;let s=e.find((a)=>Zr(a,n,r,o,i));return s?{target:s}:null}function rp(e,t,n,r,o){let i=Gn(e,t,r,o,{findSegmentTarget:(s,a)=>uw(s,a,n,r,o)?.target??null,isRedirectionTarget:(s,a)=>Zr(s,a.cwd,n,r,o),findMalformedTarget:(s)=>pw(s,t,n,r,o)?.target??null});return i?{target:i}:null}function uw(e,t,n,r,o){if(Mr(e))return null;let i=Ut([...e],r),s=k(i[0]??"").toLowerCase(),a=i.slice(1);if(s==="rm"&&dw(a)){let l=mw(a).find((c)=>op(Ae(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(s==="find"){if(Ei(i,1)||Wa(i,r)){let c=(Br(J(i))??J(["."])).find((d)=>{let m=Ae(d.text,t.variables);return Zr(m,t.cwd,n,r,o)||op(m,t.cwd,n,r,o)})?.text;if(c)return{target:c}}}if(s==="mv"){let l=ci(a).sources.find((c)=>hw(Ae(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(fw(i,s))return null;for(let l of[...e,...i])for(let c of ap(l))if(Zr(Ae(c,t.variables),t.cwd,n,r,o))return{target:c};return null}function dw(e){return e.some((t)=>t==="--recursive"||t.startsWith("-")&&!t.startsWith("--")&&/[rR]/.test(t.slice(1)))}function mw(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 fw(e,t){if(!cw.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 pw(e,t,n,r,o){for(let i of e.split(/\s+/))for(let s of ap(i))if(Zr(s,t,n,r,o))return{target:s};return null}function ap(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.indexOf("=");return n===-1||n===t.length-1?[t]:[t,t.slice(n+1)]}function gw(e,t,n){let r=(a)=>Xr(he(a,e.executionCwd,t,n)),o=r(An(t)),i=[r(dr(e.executionCwd)),r(dr(e.configCwd))],s=new Set(i.map((a)=>Yr.dirname(a)));for(let a=Yr.dirname(o);;a=Yr.dirname(a))if(s.add(a),Yr.dirname(a)===a)break;return{files:new Set([o,...i]),directoriesAndAncestors:s}}function Zr(e,t,n,r,o){let i=Ul(e,t,r,o,(s)=>Xr(s)===So);return i!==null&&n.files.has(Xr(i))}function op(e,t,n,r,o){return n.directoriesAndAncestors.has(Xr(he(e,t,r,o)))}function hw(e,t,n,r,o){let i=Xr(he(e,t,r,o));return n.files.has(i)||n.directoriesAndAncestors.has(i)}function Xr(e){return process.platform==="win32"?e.toLowerCase():e}var Ee=require("node:path"),bp=require("node:url");var Sp="Access to a sensitive path is not allowed.",vp=new Set(["echo","printf"]),yw=new Set(["find"]),Cw=new Set(["!","do","elif","else","if","then","until","while"]),bw=new Set(["-exec","-execdir"]),Sw=new Set([";","+"]),vw=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),Ew=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Ep=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),xw=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),Rw=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"]),xp=new Set(["-c","-e","-r","-E","--eval","--exec"]),ww=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"])]]),_w=new Set(["grep","rg"]),Aw=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),Pw=new Set(["commit","merge","notes","stash","tag"]),Tw=new Set(["-m","--message"]),kw=new Set(["--grep"]),lp=new Set(["jq","gojq","jaq"]),cp="f",up="file",Iw="files",Ow=new Set(["e","f"]),Mw=new Set(["regexp","file"]),Dw=new Set(["e","f","A","B","C","m"]),Nw=new Set(["regexp","file","after-context","before-context","context","max-count"]),Cl="__CC_SAFETY_NET_PIPE_INPUT__",Sl=/[\w./~@+-]*[./~][\w./~@+-]*/g,Lw=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,Ww=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,Gw=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,dp=/\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,mp=/\b(?:system|exec|spawn|popen)\s*$/,Fw=/\b(?:eval|exec)\s*\(/g,zw=/\b(?:eval|exec)\s*$/,Hw=new Map([["bash",new Set(["-O"])],["sh",new Set(["-O"])],["zsh",new Set(["-o"])],["dash",new Set(["-o"])],["ksh",new Set(["-o"])],["python",new Set(["-W","-X"])],["node",new Set(["-r","--require","--loader","--import","--input-type"])]]);function fp(e,t,n,r,o,i){for(let s of e){let a=s.target;if(G_(a,s.cwd,t?.denyPaths??[],n,r,o))return{target:a,ruleId:"secret.deny-path"};if(i&&!i.has(a))continue;let l=L_(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(kp(a,s.cwd,r,o)))continue;if(c&&s.isRedirectionWriteTarget===!0&&!a.includes("$")&&!El(a,s.cwd,r,o))continue;if(c&&/\s/.test(a)&&!a.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(a)&&!El(a,s.cwd,r,o))continue;if(!l.startsWith("secret.cli.")&&F_(a,s.cwd,t?.allowPaths??[],n,r,o))continue;return{target:a,ruleId:l}}}return null}function Rp(e,t,n,r,o={}){let i=pp(e,n,r),s=fp(i,t,e.invocation.context.configCwd,n,r);if(s===null||s.ruleId==="secret.deny-path"||o.strict!==!1)return s;let a=fp(i,t,e.invocation.context.configCwd,n,r,new Set(pp(e,n,r,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}).map((l)=>l.target)));return a?.ruleId!=="secret.deny-path"&&Bw(e,n)?null:a}function Bw(e,t){let n=Pe(e,"input-candidate")??Pe(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 li(n.shell)){if(s.kind==="operator"&&s.boundary)return!1;if(s.kind==="redirection")return!1;if(s.kind==="operator")continue;r.push(At(s.text,t))}let o=Dt(r);if(o.length===0)return!1;let i=lt(o[0]??"").toLowerCase();if(e.invocation.route.kind==="unknown")return n.program.dialect==="powershell"&&(i==="ls"||i==="stat");return xl(i,o.slice(1))}function xl(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)=>vw.has(n))}function pp(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=Pe(e,"input-candidate");return[...s?Jn(s.shell,e.store,r,t,o,n,$w(s)):[],...i==="unknown"?e.paths.map((a)=>({target:a,cwd:o})):[]]}function $w(e){return e.program.dialect==="powershell"}function Jn(e,t,n,r,o,i,s=!1){if(e.status==="structural-limit")throw new nt;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})),...b_(At(e.source,r),t,n,r,o,i)],l=(c)=>At(e_(c,s),r);return ai(e,o,r,i,{word:l,segment:(c,d,m,u,f)=>{if(c.length===0)return null;if(a.push(...Ui(c,t,n,r,d.cwd,i,f)),m!==null)a.push(...jw(m,c,t,n,r,d.cwd,i));return null},redirection:(c,d)=>{if(c.body!==void 0&&c.consumer!==void 0)a.push(...wp(c.consumer,[c.body],t,n,r,d.cwd,i,(m)=>Vw(c.consumer??[],m,t,n,r,d.cwd,i)));if(c.targetOrder==="legacy-segment")return Sa;return a.push({target:l(c.target),cwd:d.cwd,...c.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}}),a}function Rl(e,t,n,r,o,i){let s=t.getShellSyntax(e);if(s.status==="structural-limit")throw new nt;return s.status==="complete"?Jn(s,t,n,r,o,i):null}function Ui(e,t,n,r,o,i,s){let a=(g)=>({target:g,cwd:o});if(s?.size){let g=e.filter((h,y)=>!s.has(y));if(lp.has(lt(Dt(g)[0]??"").toLowerCase()))return[...e.filter((h,y)=>s.has(y)).map(a),...Ui(g,t,n,r,o,i)]}let l=Qw(e).map(a),c=Dt(e);if(c.length===0)return l;let d=c[0]??"",m=lt(d).toLowerCase(),u=c.slice(1),f=c.findIndex((g)=>!Cw.has(g));if(n.skipMetadataOnlySegments===!0&&f!==-1&&xl(lt(c[f]??"").toLowerCase(),c.slice(f+1)))return l;let p=Uw(d,m,u);if(p)return[...l,...p.map(a)];if(vp.has(m))return n.displayOperandsAreCapturedOutput===!0?[...l,..._p(e).map(a)]:l;if(m==="eval")return[...l,...Rl(u.join(" "),t,n,r,o,i)??u.map(a)];if(m==="export")return[...l,...u.flatMap((g)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(g)?[g.slice(g.indexOf("=")+1)]:ht(m,g)).map(a)];if(m==="git")return[...l,...n_(u).map(a)];if(m==="gh")return[...l,...vl(m,u,Aw).map(a)];if(lp.has(m))return[...l,...t_(u).map(a)];if(_w.has(m))return[...l,...A_(u).map(a)];if(yw.has(m))return[...l,...s_(u,t,n,r,o,i).map(a)];if(Be.has(m))return[...l,...u.flatMap((g)=>ht("awk",g)).map(a),...u.flatMap((g)=>l_(g,t,n,r,o,i)),...u.flatMap(c_).map(a)];if(m==="curl")return[...l,...u.flatMap((g)=>ht(m,g)).map(a),...r_(u).map(a)];if(Dr(m)){let g=Or.has(m)?Ne([m,...u]):null;if(g!==null&&g.command!==null&&g.commandIndex!==null){let h=t.getShellSyntax(g.command);if(h.status==="structural-limit")throw new nt;if(h.status==="complete")return[...l,...Jn(h,t,n,r,o,i),...u.slice(g.commandIndex).filter((y)=>!y.startsWith("-")).map(a)]}return[...l,...a_(m,u,t,n,r,o,i)]}return[...l,...u.flatMap((g)=>ht(m,g)).map(a)]}function Uw(e,t,n){let r=Bi(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(Zw(t,n,r,o,i,s)){let a=Dt(e),l=xl(lt(a[0]??"").toLowerCase(),a.slice(1))?a.slice(1).filter((c)=>!c.startsWith("-")):[];return[..._p(e),...l].map((c)=>({target:c,cwd:i}))}return wp(t,Kw(e),n,r,o,i,s,()=>[])}function Vw(e,t,n,r,o,i,s){let a=Dt(e);if(!Dr(lt(a[0]??"").toLowerCase()))return[];return Rl(t,n,r,o,i,s)??[{target:t,cwd:i}]}function wp(e,t,n,r,o,i,s,a){let l=Xw(e);if(l===null)return t.flatMap(a);return t.flatMap((c)=>Or.has(l)?Jn(n.getShellSyntax(c),n,r,o,i,s):$i(l,c,n,r,o,i,s))}function _p(e){let t=Dt(e);if(t.length===0)return[];let n=lt(t[0]??"").toLowerCase();if(!vp.has(n))return[];let r=t[t[1]==="--"?2:1];if(n==="printf"&&r!==void 0&&!r.startsWith("-")&&!r.replaceAll("%%","").includes("%"))return[wl(r.replaceAll("%%","%"))];return t.slice(1)}function Kw(e){let t=Dt(e);if(t.length===0)return[];let n=lt(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 qw(r);return[]}function qw(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[wl(t)];let r=e.slice(1);return Array.from({length:Math.ceil(r.length/n)},(o,i)=>Yw(t,r.slice(i*n,(i+1)*n)))}function Yw(e,t){let n=0;return wl(e.replace(/%%|%[bqs]/g,(r)=>{if(r==="%%")return"%";let o=t[n]??"";return n++,o}))}function wl(e){return e.replace(/\\n/g,`
|
|
43
|
-
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function
|
|
44
|
-
`:y),n,r,o,i,s)):[],...(l.masked.match(
|
|
45
|
-
`||s==="\r"))return null;if(e.startsWith(n,i))return i}return null}function g_(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 h_(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(xw.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)=>Rw.has(i)))continue;if(o.length>1)return!0;if(y_(e,r)===".")return!0;if(C_(e,r+n.length)==="(")return!0}return!1}function y_(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function C_(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function b_(e,t,n,r,o,i){return R_(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...Jn(a,t,{...n,displayOperandsAreCapturedOutput:!0},r,o,i),...S_(a,r)?v_(a,r).map((l)=>({target:l,cwd:o})):[]]})}function S_(e,t){let n=li(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||lt(At(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=At(s.text,t);if(a==="--decode"||!a.startsWith("--")&&a.startsWith("-")&&/[dD]/.test(a))return!0}}return!1}function v_(e,t){return li(e).flatMap((n)=>n.kind==="word"?[At(n.text,t)]:n.kind==="redirection"&&n.target?[At(n.target,t)]:[]).flatMap(Al)}function Al(e){let t=x_(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||E_(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function E_(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function x_(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 R_(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(mr(o,n))continue;if(Pp(e,r,n)){let i=w_(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=__(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function w_(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(mr(i,n))continue;if(Pp(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 __(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 Pp(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function A_(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 d=/^--([^=]+)(?:=(.*))?$/.exec(c);if(d!==null){let m=d[1]??"",u=d[2];if(m===Iw)o=!0;if(Mw.has(m))r=!0;if(u!==void 0){if(m===up)t.push(u);continue}if(Nw.has(m)){let f=e[l+1];if(m===up&&f!==void 0)t.push(f);l++}continue}if(c.startsWith("-")&&c.length>1){let m=c.slice(1),u="",f="";for(let g=0;g<m.length;g++){let h=m[g]??"";if(Ow.has(h))r=!0;if(Dw.has(h)){u=h,f=m.slice(g+1);break}}if(u==="")continue;if(f.length>0){if(u===cp)t.push(f);continue}let p=e[l+1];if(u===cp&&p!==void 0)t.push(p);l++;continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function Dt(e){let t=e.findIndex((n)=>!Tp(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:e.slice(t)}function Tp(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var P_=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),T_=".env.",k_=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),I_=[".env.example.",".env.sample."];function O_(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function M_(e){return e.length>0&&!/\s/.test(e)}function El(e,t,n,r){let o=kp(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function kp(e,t,n,r){try{return eo(e,t,n,r)}catch(o){if(o instanceof N)throw o;return""}}var D_=new Set(["node_modules","__pycache__"]),N_=[["vendor","bundle"],["vendor","cache"]];function L_(e,t,n,r,o){if(O_(e))return null;let i=gt(e,t,r,o);if(!i)return null;let s=U(i.split("/").pop()??""),a=U(i),l=()=>M_(s)||El(e,t,r,o);if(k_.has(s)||I_.some((u)=>s.startsWith(u)))return null;let c=U(B_(e,t,r,o));for(let u of Ts){let f=`~/${u.suffixParts.join("/")}`;if((Cp(a,f)||Cp(c,f))&&Mt(u.id,n))return u.id}let d=W_(i,t,n,r,o);if(d)return d;if(P_.has(s))return null;for(let u of Ps)if(s===u.basename&&Mt(u.id,n))return u.id;if(s.startsWith(T_)&&Mt(_o.id,n)&&l())return _o.id;for(let u of ks)if(s.length>u.prefix.length&&s.startsWith(u.prefix)){let f=s.slice(u.prefix.length)[0];if((f==="-"||f==="_")&&Mt(u.id,n)&&l())return u.id}for(let u of Is)if(s.length>u.prefix.length&&s.startsWith(u.prefix)){if(s.slice(u.prefix.length)===u.suffix&&Mt(u.id,n))return u.id}if(z_(a))return null;if(!s.includes(".")&&pr.pattern.test(s)&&Mt(pr.id,n))return pr.id;let m=H_(s,n);if(m)return m;return null}function W_(e,t,n,r,o){return Ao.find((i)=>{if(!Mt(i.id,n))return!1;switch(i.id){case"secret.cli.claude-code":return z(e,V(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),[".credentials.json"]);case"secret.cli.claude-code.config":{let s=U(e).split("/");return z(e,V(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),["settings.json","settings.local.json"])||Qr(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 z(e,gt("~/.gemini/config",t,r,o),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let s=V(r.env.get("CODEX_HOME"),"~/.codex",t,r,o);return z(e,s,["auth.json",".credentials.json"])||Jr(e,s,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let s=V(r.env.get("CODEX_HOME"),"~/.codex",t,r,o),a=U(e).split("/").at(-1)??"";return z(e,s,["config.toml"])||a.endsWith(".config.toml")&&z(e,s,[a])}case"secret.cli.gemini":return z(e,be(V(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=U(e).split("/"),a=r.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),l=r.env.get("ProgramData")?[be(V(r.env.get("ProgramData"),"",t,r,o),"gemini-cli")]:[];return z(e,be(V(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()?Qr(e,a,t,r,o):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...l].some((c)=>z(e,gt(c,t,r,o),["settings.json"]))}case"secret.cli.copilot-cli":{let s=V(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o);return z(e,s,["config.json"])||Jr(e,s,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return z(e,V(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o),["mcp-config.json"]);case"secret.cli.kimi-code":{let s=V(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),a=V(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o);return z(e,s,["server.token"])||Jr(e,s,["credentials"])||Jr(e,a,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let s=["config.toml","mcp.json"],a=U(e).split("/");return a.at(-1)==="mcp.json"&&a.at(-2)===".kimi-code"||z(e,V(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),s)||z(e,V(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o),[...s,"config.json","config.json.bak"])}case"secret.cli.opencode":{let s=be(V(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"opencode"),a=U(e).split("/").at(-1)??"",l=r.env.get("OPENCODE_DB")?.trim(),c=l&&l!==":memory:"?[l,`${l}-wal`,`${l}-shm`]:[];return z(e,s,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(a)&&z(e,s,[a])||c.some((d)=>Qr(e,d,t,r,o))}case"secret.cli.opencode.config":{let s=r.env.get("OPENCODE_CONFIG_DIR")?V(r.env.get("OPENCODE_CONFIG_DIR"),"~/.config/opencode",t,r,o):be(V(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"opencode"),a=r.env.get("ProgramData")?[be(V(r.env.get("ProgramData"),"",t,r,o),"opencode")]:[],l=["opencode.json","opencode.jsonc"],c=r.env.get("OPENCODE_CONFIG");return l.includes(U(e).split("/").at(-1)??"")||z(e,s,l)||(c?.trim()?Qr(e,c,t,r,o):!1)||["/Library/Application Support/opencode","/etc/opencode",...a].some((d)=>z(e,gt(d,t,r,o),l))}case"secret.cli.pi":return z(e,V(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["auth.json"]);case"secret.cli.pi.config":return z(e,V(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["models.json"]);case"secret.cli.amp":{let s=gt("~",t,r,o);return[be(V(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"amp"),be(s,".local","share","amp")].some((l)=>z(e,l,["secrets.json"]))||Jr(e,be(s,".amp"),["oauth"])}case"secret.cli.amp.config":{let s=["settings.json","settings.jsonc"],a=[be(V(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"amp"),be(gt("~",t,r,o),".config","amp")],l=U(e).split("/"),c=r.env.get("AMP_SETTINGS_FILE");return a.some((d)=>z(e,d,s))||l.at(-2)===".amp"&&s.includes(l.at(-1)??"")||(c?.trim()?Qr(e,c,t,r,o):!1)}case"secret.cli.cursor":{let s=be(V(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"cursor"),a=be(V(r.env.get("CURSOR_DATA_DIR"),"~/.cursor",t,r,o),"projects");return z(e,gt("~/.cursor",t,r,o),["auth.json"])||z(e,s,["auth.json"])||U(e).split("/").at(-1)==="mcp-auth.json"&&bn(U(e),U(a))}case"secret.cli.cursor.config":{let s=U(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".cursor"}case"secret.cli.grok-build":return z(e,V(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let s=U(e).split("/");return s.at(-1)==="config.toml"&&s.at(-2)===".grok"||z(e,V(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["config.toml","managed_config.toml","requirements.toml"])||z(e,gt("/etc/grok",t,r,o),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var yp=new WeakMap;function V(e,t,n,r,o){let i=yp.get(o)??new Map;yp.set(o,i);let s=`${n}\x00${e??""}\x00${t}`,a=i.get(s);if(a!==void 0)return a;let l=gt(e?.trim()?e:t,n,r,o);return i.set(s,l),l}function z(e,t,n){return n.some((r)=>Ip(e,be(t,r)))}function Jr(e,t,n){return n.some((r)=>bn(U(e),U(be(t,r))))}function Qr(e,t,n,r,o){return Ip(e,gt(t,n,r,o))}function Ip(e,t){return U(e)===U(t)}function be(e,...t){return at([e,...t].filter(Boolean).join("/"))}function G_(e,t,n,r,o,i){if(n.length===0)return!1;let s=U(eo(e,t,o,i));return n.some((a)=>bn(s,U(eo(a,r,o,i))))}function F_(e,t,n,r,o,i){if(n.length===0)return!1;let s=U(eo(e,t,o,i));if(!s)return!1;let a=o.env.get("HOME")??o.home,l=a?at(O(Me(a),o.paths,i)):"",c=U(l),d=o.env.get("CC_SAFETY_NET_HOME"),m=U(d?at(O(Ee.resolve(Me(d)),o.paths,i)):l&&at(O(`${l}/.cc-safety-net`,o.paths,i)));if(m&&bn(s,m))return!1;return n.some((u)=>{let f=Ns(u);if(f&&Ee.posix.basename(s)!==U(f.name))return!1;let p=U(eo(f?.root??u,r,o,i));if(!p)return!1;if(c&&(c===p||c.startsWith(p.endsWith("/")?p:`${p}/`)))return!1;return bn(s,p)&&!(f&&s===p)})}function z_(e){let t=e.split("/");return t.some((n)=>D_.has(n))||N_.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function H_(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 Os)if(r===o.extension&&Mt(o.id,t))return o.id;for(let o of Ms)if(o.pattern.test(r)&&Mt(o.id,t))return o.id;return null}function U(e){return e.toLowerCase()}function Mt(e,t){return!t?.disabledRules?.includes(e)}function gt(e,t,n,r){let{home:o,normalized:i}=Pl(e,n,r);if(!i)return"";if(!o)return i;let s=Tl(i,o),a=Ee.isAbsolute(s)?s:at(Ee.resolve(t,s)),l=at(O(a,n.paths,r));if(!bn(l,o)){if(Ee.isAbsolute(s))return l;return l===a?i:l}let c=l.slice(o.length);return c?`~${c}`:"~"}function Cp(e,t){return e===t||e.startsWith(`${t}/`)}function B_(e,t,n,r){let{home:o,normalized:i}=Pl(e,n,r);if(!i||!o)return"";let s=Tl(i,o),a=Ee.posix.normalize(Ee.isAbsolute(s)?s:at(Ee.resolve(t,s))),l=at(Me(n.env.get("HOME")??n.home)),c=(u)=>process.platform==="win32"?u.toLowerCase():u,d=[o,l].find((u)=>u!==""&&bn(c(a),c(u)));if(d===void 0)return"";let m=a.slice(d.length);return m?`~${m}`:"~"}function eo(e,t,n,r){let{home:o,normalized:i}=Pl(e,n,r);if(!i)return"";let s=o?Tl(i,o):i;return at(O(Ee.isAbsolute(s)?s:Ee.resolve(t,s),n.paths,r))}function Pl(e,t,n){let r=t.env.get("HOME")??t.home,o=r?at(O(Me(r),t.paths,n)):"",i=at(Me($_(At(e,t))));return{home:o,normalized:i}}function $_(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return bp.fileURLToPath(e)}catch{return e}}function Tl(e,t){if(e==="~")return t;if(e.startsWith("~/"))return be(t,e.slice(2));return e}function U_(e){if(process.platform==="win32")return!0;return Ee.win32.parse(e).root.length>1}function at(e){let t=e.trim(),n=(t.includes("\\")&&U_(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function bn(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function lt(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class Sn 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 j_={findPolicyMutation:sp,findGitMetadataMutation:Dd,resolveGitMetadata:K_,loadPolicySnapshot:_u,findSensitiveTarget:Rp,analyzeCommand:Xf,getModes:us},V_=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function Op(e,t){let n={...j_,...t.dependencies},r=Z_(e),o=to(e)?e.command:r,i=Jt("policy-protection",o,()=>Nr(e)),s=Pe(i,"input-candidate"),a=Pe(i,"declared-command");if(to(e)&&e.command?.trim()&&a?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:ut,intent:"stop_and_explain",evidence:{command:e.command,segment:e.command}}};if(s?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:Zd,intent:"stop_and_explain"}};let l=ue(),c=Jt("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd],t.environment)),d=Jt("policy-protection",o,()=>n.findPolicyMutation(i,t.environment,l));if(d){let E=o??d.target;return{stage:"policy-protection",decision:{kind:"deny",reason:ip,intent:"hard_stop",evidence:{command:E,segment:d.target}}}}let m=Jt("policy-protection",o,()=>tp(i,t.environment,l));if(m){let E=o??m.target;return{stage:"policy-protection",decision:{kind:"deny",reason:ep,intent:"hard_stop",evidence:{command:E,segment:m.target}}}}let u=Jt("policy-protection",o,()=>n.findGitMetadataMutation(i,c,t.environment,l));if(u){let E=o??u.target;return{stage:"policy-protection",decision:{kind:"deny",reason:je,intent:"hard_stop",evidence:{command:E,segment:u.target}}}}let f=Jt("config-load",o,()=>n.loadPolicySnapshot(t.environment,{...t.policyOptions,cwd:e.context.configCwd})),p=f.policy,g=n.getModes(p,t.environment.env),h={level:g.effectiveLevel,...q_(f)},y=p.secretProtection.enabled===!1?null:Jt("secret-protection",o,()=>n.findSensitiveTarget(i,p.secretProtection,t.environment,l,{strict:to(e)||s?.program.dialect==="powershell"?g.strict:void 0}));if(y){let E=o??y.target;return{stage:"secret-protection",...h,decision:{kind:"deny",reason:Sp,intent:"hard_stop",ruleId:y.ruleId,evidence:{command:E,segment:y.target}}}}if(!to(e))return{stage:"non-command",...h,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...kl("command-validation",o),...h};let S=Jt("command-analysis",o,()=>Jf(()=>n.analyzeCommand(e.command,{cwd:e.context.executionCwd,shell:e.route.shell,policySnapshot:f,environment:t.environment,protectedGitMetadata:c,effectiveCapabilities:g.capabilities,strict:g.strict,paranoidRm:g.paranoidRm,paranoidInterpreters:g.paranoidInterpreters,worktreeMode:g.worktreeMode,budget:l,...t.trace?{trace:t.trace}:{}},Y_(i),i.store),e.command,t.trace));if(S.decision){let E=!g.strict&&(S.decision.ruleId==="raw-text.dangerous-command"||S.decision.reason===Fr&&!V_.test(S.decision.evidence?.segment??"")&&$e(e.command)===null);return{stage:"command-analysis",...h,..."errorCode"in S?{errorCode:S.errorCode}:{},decision:E?{...S.decision,unverifiedByStandardMode:!0}:S.decision}}return{stage:"command-analysis",...h,decision:{kind:"allow"}}}function K_(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 q_(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function Y_(e){return Pe(e,"declared-command")?.program}function Z_(e){try{return Lt(e.input)}catch(t){let n=to(e)?e.command:void 0;throw new Sn("policy-protection",kl("policy-protection",t instanceof Se?void 0:n,t),t)}}function Jt(e,t,n){try{return n()}catch(r){throw new Sn(e,kl(e,r instanceof Se?void 0:t,r),r)}}function kl(e,t,n){let r=n instanceof N||n instanceof nt;return{stage:e,decision:{kind:"deny",reason:r?Xi:or,intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function to(e){return e.route.kind==="command"}var Vi=require("node:fs"),er=require("node:path");var le=require("node:fs"),Qn=require("node:path");function Mp(e,t={}){return Lo(An(e,t),e.home).policy.audit.retention_days}var Ol=86400000,X_=".last-prune",J_=/^\d{4}-\d{2}$/,Q_=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Dp=(e)=>Math.floor(e/Ol);function Lp(e,t,n=()=>new Date){try{let r=n().getTime();if(!le.statSync(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=Qn.join(t,X_),i=le.statSync(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&Dp(i)===Dp(r))return;let s=r-Mp(e)*Ol,a=new Date(r).toISOString().slice(0,7);for(let l of Il(t)){if(l.isDirectory()){eA(Qn.join(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))tA(Qn.join(t,l.name),s)}le.writeFileSync(o,"",{mode:384}),le.utimesSync(o,r/1000,r/1000)}catch{}}function eA(e,t,n){for(let r of Il(e)){if(!r.isDirectory()||!J_.test(r.name))continue;let o=Qn.join(e,r.name);for(let i of Il(o)){if(!i.isFile())continue;let s=Q_.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+Ol;if(!Number.isFinite(a)||a>=t)continue;Wp(Qn.join(o,i.name))}if(r.name!==n)Np(o)}Np(e)}function tA(e,t){try{let n=le.lstatSync(e);if(n.mtimeMs>=t)return;let r=le.readFileSync(e,"utf-8").split(`
|
|
46
|
-
`).filter((o)=>o.trim()).map(
|
|
47
|
-
`,{encoding:"utf-8",mode:384}),Lp(e,l,s.now)}catch{}}function ji(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function uA(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&&er.isAbsolute(n)?n:null}function dA(e){let t=uA(e);return t?er.join(t,".cc-safety-net","logs"):null}function Fp(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=Gp(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?Gp(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 Gp(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;Ml(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 Hp(e,t,n,r){let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Ml(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=Op(t,{environment:e,...n.guard});return Bp(e,t,r,n),r}catch(r){if(!(r instanceof Sn))throw r;throw Bp(e,t,r.evaluation,n,!(r.cause instanceof Se),{stage:r.stage,errorCode:mA(r.cause)}),r}}function Bp(e,t,n,r,o=!0,i){zp(e,Fp(t,n,r.guard?.auditAllowed??!1,o,i),r.audit.getSessionId,{agent:r.audit.agent,shape:r.audit.shape})}function mA(e){if(e instanceof N)return X[e.kind].errorCode;if(e instanceof Se)return"tool-input-limit";if(e instanceof nt)return"structural-shell-syntax-limit";return"unexpected-error"}var yt=(e,t,n,r,o)=>lc(e.cwd,t,n,r,o.paths,process.cwd());function fA(e,t){console.log(JSON.stringify(e(Fl(t))))}async function pA(e){let t;try{t=(await ac(process.stdin)).trim()}catch{e({reason:"Failed to parse hook input JSON."});return}if(!t){e({reason:"Missing hook input JSON."});return}return fo(t,e,"Failed to parse hook input JSON.")}async function gA(e){let t=bc(),n=await pA(e.outputDeny);if(n===void 0)return;if(!n||typeof n!=="object"||Array.isArray(n)){ye(e.outputDeny);return}if(!e.isSupported(n))return;let r=e.getAgent?.(n,t)??e.agent,o=e.agent===r?void 0:e.agent,i=bA(n),s=(p,g)=>{Hp(t,p,()=>e.getSessionId(n),{agent:r,shape:o,toolName:g,cwd:p.cwd??i}),e.outputDeny(p)},a=e.getToolName(n);if(typeof a!=="string"||a.trim()===""){ye((p)=>s(p),CA(n));return}let l=a,c=(p)=>s(p,l),d;try{d=e.getToolInput(n,l,c,t)}catch(p){if(!(p instanceof Se))throw p;ye(c,void 0,l);return}if(!d.ok)return;let m=e.getContext(n,d.input,l,c,t);if(!m)return;let u;try{u=Lt(d.input)}catch(p){if(!(p instanceof Se))throw p;ye(c,void 0,l);return}let f=cr(l,d.input,d.route,m,u??null);try{let p=$p(t,f,{guard:{auditAllowed:Sc(t.env),dependencies:e.guardDependencies},audit:{agent:r,shape:o,getSessionId:()=>e.getSessionId(n)}}),g=Ji(p,{includeEvidence:!0,toolName:p.stage==="command-analysis"?void 0:l});if(g){if(g.unverifiedByStandardMode&&e.outputAsk&&e.canPromptPerson?.(n)){e.outputAsk(g);return}e.outputDeny(g);return}e.outputAllow?.()}catch(p){if(!(p instanceof Sn))throw p;hA(p,t.env);let g=Ji(p.evaluation,{includeEvidence:!0,toolName:p.evaluation.stage==="command-analysis"?void 0:l});if(g)e.outputDeny(g);return}}function hA(e,t){if(!tn(ae.debug,t))return;console.error(`CC Safety Net debug: ${yA(e.stage)}: ${Hl(e.cause)}`)}function yA(e){if(e==="policy-protection")return"hook policy protection failed";if(e==="config-load")return"hook config loading failed";if(e==="secret-protection")return"hook secret protection failed";return"hook analysis failed"}function CA(e){if(!e||typeof e!=="object"||Array.isArray(e))return;if(Object.hasOwn(e,"tool_input"))return e.tool_input;let t=e.toolCall;if(t&&typeof t==="object"&&!Array.isArray(t))return t.args;return}function bA(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let t=e.cwd;if(typeof t==="string")return t;let n=e.toolCall;if(!n||typeof n!=="object"||Array.isArray(n))return null;let r=n.args;if(!r||typeof r!=="object"||Array.isArray(r))return null;let o=r.Cwd;return typeof o==="string"?o:null}async function Ie(e){let t=(s)=>fA(e.createDenyOutput,s),n=e.createAskOutput,r=n?(s)=>console.log(JSON.stringify(n(zl(s)))):void 0,o=e.createAllowOutput,i=o?()=>console.log(JSON.stringify(o())):void 0;try{await gA({...e,outputDeny:t,outputAsk:r,outputAllow:i})}catch(s){console.error("CC Safety Net error:",s),t(xn())}}var SA=new Map([["run_command","auto"]]),vA=new Set(["absolutepath","directorypath","file_path","filepath","path","searchdirectory","searchpath","target_file","targetfile"]);function Up(e){return se(e,SA)}async function jp(){await Ie({agent:"antigravity-cli",createDenyOutput:(e)=>({decision:"deny",reason:e}),isSupported:()=>!0,getToolName:(e)=>e.toolCall?.name,getToolInput:(e,t)=>({ok:!0,input:wA(e.toolCall?.args,t),route:Up(t)}),getContext:EA,getSessionId:(e)=>e.conversationId})}function EA(e,t,n,r,o){let i=RA(e);if(!i[0])return Qt(r,t,n),null;let s=i.flatMap((d)=>{let m=Et([d],o.paths);return m?[m]:[]});if(!s[0])return Qt(r,t,n,{directory:"session",problem:"unusable",cwd:i[0]}),null;if(n!=="run_command"){let d;try{d=xA(t,n,s,o.paths)}catch(m){if(m instanceof Se)return Qt(r,void 0,n),null;if(!(m instanceof N))throw m;return Qt(r,t,n),null}if(!d)return Qt(r,t,n),null;return{configCwd:d,executionCwd:d}}let a=e.toolCall?.args;if(!a||!Object.hasOwn(a,"Cwd"))return{configCwd:s[0],executionCwd:s[0]};let l=a.Cwd;if(typeof l!=="string"||l.trim()==="")return Qt(r,t,n),null;let c=vt(l,s,o.paths);if(c){let d=Vp(c,s);if(!d)return Qt(r,t,n),null;return{configCwd:d,executionCwd:c}}return Qt(r,t,n,{directory:"requested",problem:xt(l,s[0],o.paths),cwd:l}),null}function xA(e,t,n,r){let o=Up(t),i=[...co(e,vA),...o.kind==="patch"?uo(e):[]].filter(Dl.isAbsolute),s=ue(),a=new Set(i.flatMap((l)=>{let c=Vp(O(l,r,s),n);return c?[c]:[]}));if(a.size>1)return null;return[...a][0]??n[0]??null}function Vp(e,t){return t.filter((n)=>ar(e,n)).reduce((n,r)=>r.length>n.length?r:n,"")||null}function Qt(e,t,n,r){let o=t&&typeof t==="object"?t.command:void 0,i={command:typeof o==="string"?o:void 0,toolName:n};e(r?io(r,i):xn(i))}function RA(e){if(e.workspacePaths===void 0)return[process.cwd()];return Array.isArray(e.workspacePaths)?e.workspacePaths.filter((t)=>typeof t==="string"&&t.trim()!==""):[]}function wA(e,t){if(!e)return;if(t!=="run_command")return e;return{...e,command:typeof e.CommandLine==="string"&&e.CommandLine!==""?e.CommandLine:void 0}}var Ki=[{id:"antigravity-cli",displayName:"Antigravity CLI",doctorOrder:3,runtime:{order:1,flags:["-ac","--agy-cli"],description:"Run as Antigravity CLI PreToolUse hook",legacyTopLevelFlags:[]},install:{order:2,flag:"--agy-cli",artifactKind:"hook config",probeCommand:["agy","--version"]}},{id:"claude-code",displayName:"Claude Code",doctorOrder:1,runtime:{order:2,displayName:"Coding CLI",flags:["-cc","--coding-cli"],legacyFlags:["--claude-code"],description:"Run as Coding CLI PreToolUse hook",legacyTopLevelFlags:["-cc","--claude-code"]},install:{order:3,flag:"--claude-code",artifactKind:"plugin",probeCommand:["claude","--version"]}},{id:"codex",displayName:"Codex",doctorOrder:4,runtime:{order:3,flags:["-cx","--codex"],description:"Run as a Codex PreToolUse hook",legacyTopLevelFlags:[]},install:{order:4,flag:"--codex",artifactKind:"plugin",probeCommand:["codex","--version"]}},{id:"copilot-cli",displayName:"GitHub Copilot CLI",doctorOrder:7,runtime:{order:6,flags:["-cp","--copilot-cli"],description:"Run as GitHub Copilot CLI PreToolUse hook",legacyTopLevelFlags:["-cp","--copilot-cli"]},install:{order:7,flag:"--copilot-cli",artifactKind:"plugin",probeCommand:["copilot","--binary-version"]}},{id:"gemini-cli",displayName:"Gemini CLI",doctorOrder:6,runtime:{order:5,flags:["-gc","--gemini-cli"],description:"Run as Gemini CLI BeforeTool hook",legacyTopLevelFlags:["-gc","--gemini-cli"]},install:{order:6,flag:"--gemini-cli",artifactKind:"extension",probeCommand:["gemini","--version"]}},{id:"grok-build",displayName:"Grok Build",doctorOrder:8,runtime:{order:7,flags:["-gb","--grok-build"],description:"Run as Grok Build PreToolUse hook",legacyTopLevelFlags:[]},install:{order:8,flag:"--grok-build",artifactKind:"hook config",probeCommand:["grok","--version"]}},{id:"hermes-agent",displayName:"Hermes Agent",doctorOrder:9,runtime:{order:8,flags:["-ha","--hermes-agent"],description:"Run as Hermes Agent pre_tool_call hook",legacyTopLevelFlags:[]},install:{order:9,flag:"--hermes-agent",artifactKind:"plugin",probeCommand:["hermes","--version"]}},{id:"kimi-code",displayName:"Kimi Code",doctorOrder:10,runtime:{order:9,flags:["-kc","--kimi-code"],description:"Run as Kimi Code PreToolUse hook",legacyTopLevelFlags:[]},install:{order:10,flag:"--kimi-code",artifactKind:"hook config",probeCommand:["kimi","--version"]}},{id:"openclaw",displayName:"OpenClaw",doctorOrder:11,install:{order:11,flag:"--openclaw",artifactKind:"plugin",probeCommand:["openclaw","--version"]}},{id:"opencode",displayName:"OpenCode",doctorOrder:12,install:{order:12,flag:"--opencode",artifactKind:"plugin",probeCommand:["opencode","--version"]}},{id:"pi",displayName:"Pi",doctorOrder:13,install:{order:13,flag:"--pi",artifactKind:"package",probeCommand:["pi","--version"]}},{id:"cursor",displayName:"Cursor",doctorOrder:5,runtime:{order:4,flags:["-cu","--cursor"],description:"Run as Cursor preToolUse hook",legacyTopLevelFlags:[]},install:{order:5,flag:"--cursor",artifactKind:"hook config",probeCommand:["cursor","--version"]}},{id:"amp",displayName:"Amp Code",doctorOrder:2,install:{order:1,flag:"--amp",artifactKind:"plugin",probeCommand:["amp","--version"]}}],_L=Ki.slice().sort((e,t)=>e.doctorOrder-t.doctorOrder).map((e)=>e.id),Kp=Ki.filter((e)=>("runtime"in e)).slice().sort((e,t)=>e.runtime.order-t.runtime.order).map((e)=>({id:e.id,displayName:"displayName"in e.runtime?e.runtime.displayName:e.displayName,flags:e.runtime.flags,legacyFlags:"legacyFlags"in e.runtime?e.runtime.legacyFlags:[],description:e.runtime.description,legacyTopLevelFlags:e.runtime.legacyTopLevelFlags})),AL=Ki.slice().sort((e,t)=>e.install.order-t.install.order).map((e)=>({id:e.id,...e.install})).map(({order:e,...t})=>t),PL=Object.fromEntries(Ki.map((e)=>[e.id,e.displayName]));var vn=require("node:path");function qp(e,t){if(e!==void 0&&e!==null&&typeof e!=="string")return"unknown";if(typeof e==="string"&&!vn.isAbsolute(e))return"unknown";try{let n=ue(),r=typeof e==="string"&&e?O(e,t.paths,n):void 0,o=t.home,i=[["codex",t.env.get("CODEX_HOME")||vn.join(o,".codex")],["copilot-cli",t.env.get("COPILOT_HOME")||vn.join(o,".copilot")],["claude-code",t.env.get("CLAUDE_CONFIG_DIR")||vn.join(o,".claude")]],s=r?i.flatMap(([a,l])=>{if(!vn.isAbsolute(l))return[];return ar(r,O(l,t.paths,n))?[a]:[]}):[];if(s.length===1)return s[0]??"unknown";if(s.length>1)return"unknown"}catch{return"unknown"}if(t.env.get("CLAUDECODE")==="1"||Boolean(t.env.get("CLAUDE_CODE_ENTRYPOINT")))return"claude-code";return"unknown"}var qi="PreToolUse",Yp="BeforeTool",Zp="pre_tool_call";async function tr(e){await Ie({agent:e.agent,...e.getAgent?{getAgent:e.getAgent}:{},createDenyOutput:(t)=>({hookSpecificOutput:{hookEventName:qi,permissionDecision:"deny",permissionDecisionReason:t}}),...e.canPromptPerson?{canPromptPerson:e.canPromptPerson,createAskOutput:(t)=>({hookSpecificOutput:{hookEventName:qi,permissionDecision:"ask",permissionDecisionReason:t}})}:{},isSupported:(t)=>t.hook_event_name===qi,getToolName:(t)=>t.tool_name,getToolInput:(t,n)=>({ok:!0,input:t.tool_input,route:e.getToolRoute(n)}),getContext:e.getContext??yt,getSessionId:(t)=>t.session_id})}var _A=new Map([["Bash","posix"],["PowerShell","powershell"]]);function AA(e){return se(e,_A)}async function Xp(){await tr({agent:"claude-code",getAgent:(e,t)=>qp(e.transcript_path,t),canPromptPerson:(e)=>["default","acceptEdits","plan"].includes(e.permission_mode??""),getToolRoute:AA})}var PA=new Map([["Bash","auto"]]);async function Jp(){await tr({agent:"codex",getToolRoute:(e)=>se(e,PA)})}var TA=new Map([["bash","auto"],["Bash","auto"],["powershell","powershell"],["PowerShell","powershell"]]);function kA(e){return se(e,TA)}async function Qp(){await Ie({agent:"copilot-cli",createDenyOutput:(e)=>({permissionDecision:"deny",permissionDecisionReason:e}),isSupported:()=>!0,getToolName:(e)=>e.toolName,getToolInput:(e,t,n)=>{if(typeof e.toolArgs!=="string")return n({reason:"Failed to parse toolArgs JSON."}),{ok:!1};let r=fo(e.toolArgs,n,"Failed to parse toolArgs JSON.");if(r===void 0)return{ok:!1};return{ok:!0,input:r,route:kA(t)}},getContext:yt,getSessionId:(e)=>typeof e.sessionId==="string"&&e.sessionId.trim()?e.sessionId:void 0})}var IA=new Map([["Shell","auto"]]);function OA(e){return se(e,IA)}async function eg(){await Ie({agent:"cursor",createDenyOutput:(e)=>({permission:"deny",user_message:e,agent_message:e}),createAllowOutput:()=>({permission:"allow"}),isSupported:()=>!0,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:OA(t)}),getContext:MA,getSessionId:(e)=>e.conversation_id})}function MA(e,t,n,r,o){let i=DA(e);if(!i[0])return ye(r,t,n),null;let s=i.flatMap((m)=>{let u=Et([m],o.paths);return u?[u]:[]});if(!s[0])return He(r,t,n,{directory:"session",problem:"unusable",cwd:i[0]}),null;let a=NA(e.cwd),l=vt(a,s,o.paths);if(!l)return He(r,t,n,{directory:"session",problem:xt(a,s[0],o.paths),cwd:a}),null;if(t===null||typeof t!=="object"||Array.isArray(t))return{configCwd:l,executionCwd:l};if(!Object.hasOwn(t,"working_directory"))return{configCwd:l,executionCwd:l};let c=t.working_directory;if(typeof c!=="string"||c.trim()==="")return ye(r,t,n),null;let d=vt(c,s,o.paths);if(!d)return He(r,t,n,{directory:"requested",problem:xt(c,s[0],o.paths),cwd:c}),null;return{configCwd:l,executionCwd:d}}function DA(e){if(e.workspace_roots===void 0)return typeof e.cwd==="string"&&e.cwd.trim()!==""?[e.cwd]:[];if(!Array.isArray(e.workspace_roots))return[];return e.workspace_roots.filter((t)=>typeof t==="string"&&t.trim()!=="")}function NA(e){return typeof e==="string"&&e.trim()!==""?e:"."}var LA=new Map([["run_shell_command","auto"]]);function WA(e){return se(e,LA)}async function tg(){await Ie({agent:"gemini-cli",createDenyOutput:(e)=>({decision:"deny",reason:e,systemMessage:e}),isSupported:(e)=>e.hook_event_name===Yp,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:WA(t)}),getContext:yt,getSessionId:(e)=>e.session_id})}var GA=new Map([["run_terminal_command","auto"]]);function FA(e){return se(e,GA)}async function ng(){await Ie({agent:"grok-build",createDenyOutput:(e)=>({decision:"deny",reason:e}),createAllowOutput:()=>({decision:"allow"}),isSupported:()=>!0,getToolName:(e)=>e.toolName,getToolInput:(e,t,n)=>{if(e.toolInputTruncated===!0)return ye(n,e.toolInput,t),{ok:!1};return{ok:!0,input:e.toolInput,route:FA(t)}},getContext:zA,getSessionId:(e)=>e.sessionId})}function zA(e,t,n,r,o){let i=HA(e);if(!i)return ye(r,t,n),null;let s=Et([i],o.paths);if(!s)return He(r,t,n,{directory:"session",problem:"unusable",cwd:i}),null;let a=BA(e.cwd),l=vt(a,[s],o.paths);if(!l)return He(r,t,n,{directory:"session",problem:xt(a,s,o.paths),cwd:a}),null;return{configCwd:l,executionCwd:l}}function HA(e){let t=e.workspaceRoot===void 0?e.cwd:e.workspaceRoot;return typeof t==="string"&&t.trim()!==""?t:void 0}function BA(e){return typeof e==="string"&&e.trim()!==""?e:"."}var rg=require("node:path");var $A=new Map([["terminal","posix"]]);async function og(){await Ie({agent:"hermes-agent",createDenyOutput:(e)=>({action:"block",message:e}),isSupported:(e)=>e.hook_event_name===Zp,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:se(t,$A)}),getContext:UA,getSessionId:(e)=>e.session_id})}function UA(e,t,n,r,o){let i=yt(e,t,n,r,o);if(!i)return null;if(!t||typeof t!=="object"||Array.isArray(t))return i;if(!Object.hasOwn(t,"workdir"))return i;let s=t.workdir;if(typeof s!=="string"||s.trim()==="")return ye(r,t,n),null;let a=Et([rg.resolve(i.configCwd,s)],o.paths);if(!a)return He(r,t,n,{directory:"requested",problem:"unusable",cwd:s}),null;return{...i,executionCwd:a}}var ig=new Map([["Bash","posix"]]);function jA(e){return se(e,ig)}async function sg(){await tr({agent:"kimi-code",getToolRoute:jA,getContext:(e,t,n,r,o)=>{let i=yt(e,t,n,r,o);if(!i)return null;let s=e.tool_input;if(!ig.has(n)||!s||!Object.hasOwn(s,"cwd"))return i;let a=s.cwd;if(typeof a!=="string"||a.trim()==="")return ye(r,t,n),null;let l=vt(a,[i.configCwd],o.paths);if(!l)return He(r,t,n,{directory:"requested",problem:xt(a,i.configCwd,o.paths),cwd:a}),null;return{configCwd:i.configCwd,executionCwd:l}}})}var VA={"antigravity-cli":jp,"claude-code":Xp,codex:Jp,"copilot-cli":Qp,cursor:eg,"gemini-cli":tg,"grok-build":ng,"hermes-agent":og,"kimi-code":sg},Nl=Kp.map((e)=>({...e,run:VA[e.id]}));function ag(e){let t=oo({label:"hook",booleans:Object.fromEntries(Nl.map((r)=>[r.id,[...r.flags,...r.legacyFlags]]))},e);if(t.errors.length>0)return;let n=Nl.filter((r)=>t.flags[r.id]);return n.length===1?n[0]:void 0}function lg(e){return Nl.find((t)=>t.legacyTopLevelFlags.some((n)=>n===e))}async function KA(){let e=process.argv.slice(2),t=e[0],n=oo({label:"cc-safety-net",booleans:{version:["-V","--version"]},positionals:"list"},e);if(!n.help&&!n.flags.version){if(t?.toLowerCase()==="hook"){let i=ag(e.slice(1));if(i){await i.run();return}}let o=lg(t);if(o){await o.run();return}}let r=await import("../cli.js");await r.runCli(e)}KA().catch((e)=>{console.error("CC Safety Net error:",e),process.exit(1)});
|
|
41
|
+
`?e.trim().split(/\s+/).filter(Boolean):e.split(t).filter(Boolean)}function jr(e){if(!e)return!0;return e.provenance==="unknown"?!/[$`]/.test(_(e)):e.provenance==="literal"}function jn(e){return e?_(e):""}function Zm(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function el(e,t){return Ja(Je(e,"posix"),t)}function Vr(e){return el(e,new Set(Array.from(e.matchAll($m)).flatMap((t)=>{let n=t[1]??t[2];return n===void 0?[]:[n]})))}function Ja(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(Ja(r.body,n))return!0;continue}if(r.kind!=="command")continue;if(r.nested.some((o)=>Ja(o,n))||Xm(r.words,n))return!0;Ox(r,n)}return!1}function Xm(e,t){let n=e.findIndex((s)=>Ue(s.text)===null);if(n===-1)return!1;let r=e[n];if(!r)return!1;if(Ur(r,t))return!0;let o=M(r.text);if(o==="source"||o==="."){let s=e[n+1]?.text==="--"?n+2:n+1;return Bm(e[s],t)}if(Q.has(o)){let s=e.slice(n),a=Ne(s.map((c)=>c.text)),l=a.commandIndex??a.scriptIndex;return!a.syntaxCheck&&l!==null&&Bm(s[l],t)}let i=Px(e,n,t);if(i===null)return!1;if(i===-1)return!0;return Xm(e.slice(i),t)}function Px(e,t,n){let r=M(e[t]?.text??"");if(r==="command")return Tx(e,t+1);if(r==="exec")return kx(e,t+1);if(r==="env")return Ix(e,t+1,n);return null}function Tx(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 kx(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 Ix(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 Ur(e[r+1],n)?-1:r+2;if(i.startsWith("-S")||i.startsWith("--split-string="))return Ur(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(Ue(i))continue;return r}return null}function Ox(e,t){if(!e.words.every((n)=>Ue(n.text)!==null))return;for(let n of e.words){let r=Ue(n.text);if(!r)continue;if(Ur(n,t))t.add(r.name)}}function Ur(e,t){if(!e)return!1;return e.parts.filter((n)=>n.provenance==="variable").some((n)=>Array.from(n.raw.matchAll($m)).some((r)=>{let o=r[1]??r[2];return o!==void 0&&(vx.test(o)||t.has(o))}))}function Bm(e,t){return!!e&&(e.parts.some((n)=>n.provenance!=="literal"&&n.provenance!=="variable")||Ur(e,t))}var tl="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",nl="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",Mx="__CC_SAFETY_NET_XARGS_INPUT__",ki="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",Ii="rm",Dx=/(?:^|[;&|]\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,Nx=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,Lx=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,Wx=/^(?:[0-9]+|[@*])$/;function ef(e,t){let n=e.map(_),{childStart:r,replacementToken:o}=pn(n),i=n.slice(r),s=v("xargs.shell-dynamic",nl);if(Fx(i,o,t)&&T(s,t.policy))return T(s,t.policy);for(let a of ot(i,t)){let l=a.tokens,c=o!==null&&l[0]!==i[0]&&(l[0]?.includes(o)??!1)?T(s,t.policy):null;if(c)return c;let u=af(l,o,a.wrapperEnvAssignments),m=a.head==="rm"&&o!==null&&of(l,o),d=t.analyzeChild(l,{...dn(a,t),dynamicInput:u,dynamicSourceInput:m||nf(l,a.head,o,a.wrapperEnvAssignments,u,t.environment,t.strict?void 0:t.analyzeNested),dynamicRmInput:m,shellDynamicMatch:s,dynamicSourceMatch:s,rmDynamicMatch:v("xargs.rm-recursive-force-dynamic",tl)});if(d)return d;let f=Gx(l,o,t.policy?.rules??[],T(s,t.policy));if(f)return f;if(a.head==="git"){let g=o===null?[...l,Mx]:l,h=o!==null&&(l.some((S)=>S.includes(o))||Array.from(a.envAssignments.values()).some((S)=>S.includes(o))),y=t.analyzeChild(g,{...dn(a,t),worktreeMode:o===null||h?!1:t.worktreeMode});if(y)return y}let p=At(l,t.policy?.rules??[]);if(p)return p}return null}function Gx(e,t,n,r){if(n.length===0)return null;if(t===null){for(let i of n){let s=At([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],n);if(s)return s}return null}let o=M(e[0]??"");if(!n.some((i)=>M(i.command)===o))return null;return e.slice(1).some((i)=>i.includes(t))?r:null}function tf(e,t,n){let r=e.indexOf(t);if(r===-1||e.indexOf(t,r+t.length)!==-1)return[];let o=Gm(e,r,t.length,n);return o===null?[]:[o]}function nf(e,t,n,r,o,i,s){if(Q.has(t)){if(Pt(e))return!1;if(n!==null&&zx(e,n,s))return!0;let a=st(e);if(!a){let l=It(J(e));if(l.kind==="literal")return n!==null&&l.source.includes(n);return l.kind==="none"&&o}if(n!==null&&a.includes(n)&&!rf(a,n,s))return!0;if($e(a))return!0;return Hx(a,n,r)}if(Xe(t))return Jm(e,n,Qo,dd(t));if(Be.has(t))return Jm(e,n,Da,om);if(t==="eval"){let a=Pi(J(e));if(a.kind==="dynamic")return!0;if(n!==null)return a.kind==="literal"&&a.source.includes(n);return o}if(t==="find")return Bx(e,n,i);if(t==="git"){let a=ze(e);return n===null?a.subcommand===null:(a.subcommand?.includes(n)??!1)||a.subcommand!==null&&$n.has(a.subcommand.toLowerCase())&&sf(a.rest,n).some((l)=>l.includes(n))}return!1}function rf(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 $e(i)===null&&n(i)===null}function Jm(e,t,n,r){let o=n(e);if(t===null)return o.optionsOpen||n([...e,ki]).sources.some((a)=>a.value===ki);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}${ki}`]:[],...a.valueForm==="equals-or-separate"?[`${a.selector}=${ki}`]:[]]),s=new Set(i.flatMap((a)=>e.flatMap((l)=>tf(l,t,a))));return _i(o.sources,s,(a)=>n(e.map((l)=>l.replaceAll(t,a))).sources)}function Fx(e,t,n){if(e.length===0||(e[0]??"").toLowerCase()==="command")return!1;let r=new Set(Array.from(ot(e,n),(i)=>i.head)),o=t===null?[...e,Ii]:e.map((i,s)=>s===0?i:i.replaceAll(t,Ii));return Array.from(ot(o,n)).some((i)=>i.head===Ii&&!r.has(Ii))}function of(e,t){return sf(e.slice(1),t).some((n)=>n.includes(t)&&(n.startsWith("-")||n.startsWith(t)))}function sf(e,t){let n=e.findIndex((r)=>r==="--"&&!r.includes(t));return n===-1?e:e.slice(0,n)}function af(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 zx(e,t,n){let r=Ne(e),o=r.commandIndex===null?"":e[r.commandIndex]??"";if(o.includes(t)&&!rf(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 tf(a,t,s).some((u)=>{let m=e.map((f,p)=>p===l?f.replaceAll(t,u):f),d=Ne(m);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&&(m[d.commandIndex]??"").includes(u))return!0;return d.scriptIndex!==null&&(m[d.scriptIndex]??"").includes(u)})}))}function Hx(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(Dx))if(Qm(o,r))return!0;for(let o of e.matchAll(Nx))for(let i of(o[1]??"").matchAll(Lx))if(Qm(i,r))return!0;return el(e,r)}function Qm(e,t){let n=e[1]??e[2];return n!==void 0&&(Wx.test(n)||t.has(n))}function Bx(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(ft(s)){let l=Bn(e,i);i=l.nextIndex-1;for(let c of ot(l.tokens,{environment:n,cwd:void 0})){let u=af(c.tokens,t,c.wrapperEnvAssignments);if(c.head==="rm"&&of(c.tokens,t)||nf(c.tokens,c.head,t,c.wrapperEnvAssignments,u,n))return!0}continue}let a=Tt(s);if(a>0){if(o=a,s.includes(t))return!0;continue}if(s.includes(t))return!0}return!1}function pn(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 Kr="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",qr="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",$x="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",Ux="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Mi=/\{[^{}\s]*\}/g,lf=/\{\}|\{-?\d+\}/g,jx=["e","f","source","file","-e","-f","--source","--file"],Vx=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],Kx=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),qx=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),cf=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),Yx=new Set(["--workdir","--wd"]),uf="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Ve(e,t){for(let n of e){let r=t(n);if(r)return r}return null}function hf(e){return Ve([...e],(t)=>$e(t))}function yf(e,t){let n=e.map(_);if((t.envAssignments?.has("PARALLEL")?t.envAssignments.get("PARALLEL"):t.environment.env.get("PARALLEL"))?.trim()){let p=Vn(t);if(p)return p}if(n.length===2&&(n[1]==="--version"||n[1]==="--help"))return null;let o=_f(n),{template:i,jobs:s,runsRemotely:a,readsCommandsFromInput:l,unsupported:c,workdir:u,dryRun:m}=o;if(c){let p=Vn(t);if(p)return p;let g=hf(t.envAssignments?.values()??[]);if(g)return g}if(l){let p=tR(t);if(p)return p}if(u!==void 0&&a){let p=Vn(t);if(p)return p}let d=nR(u,t.cwd,t.environment.paths);if(d===null){let p=Vn(t);if(p)return p}let f=a?{...t,cwd:void 0,originalCwd:void 0}:d===null||d===void 0||d===t.cwd?t:{...t,cwd:d};if(m){if([...ot(i,f)].flatMap((g)=>[...g.envAssignments.values()]).some(il)){let g=Vn(t);if(g)return g}return null}if(i.length===0){let p=s.map((h)=>h[0]??"");t.budget.charge("derivedTokens",p.length);let g=vf(f.envAssignments,f.cwd,a);return Ve(p,(h)=>t.analyzeNested(h,g))}return Ve(ot(i,f),(p)=>Zx(p,o,t,f))}function Zx(e,t,n,r){let{jobs:o,templateHasPlaceholder:i,runsRemotely:s,usesStdin:a}=t,l=e.tokens,c=[...e.envAssignments.values()];if(c.some(Rf)){let h=Vn(n);if(h)return h}let u=hf(c);if(u)return u;let m=c.some(B),d=i||m,f=a&&d,p=vf(e.envAssignments,e.wrapperCwd,s||f);if(Q.has(e.head)){let h=()=>{if(!i||o.length===0)return null;return Ve(o,(E)=>n.analyzeChild(Oi(l,E,n.budget),dn(e,r)))};if(Pt(l))return h();let y=st(l);if(y){if(wf(y)){let x=Yt(n);if(x)return x;if(o.length===0)return null;return Ve(o,(A)=>n.analyzeNested(ff(y,A,n.budget),p))}if(B(y)){if(o.length>0)return Ve(o,(ee)=>n.analyzeNested(ff(y,ee,n.budget),p));let x=$r(y);if(x?.[0]&&M(x[0])==="rm"&&it(x)){let ee=mf(n);if(ee)return ee}let A=x?n.analyzeChild(x,{...dn(e,r),dynamicInput:a,shellDynamicMatch:v("parallel.shell-dynamic",qr),rmDynamicMatch:v("parallel.rm-recursive-force-dynamic",Kr)}):null;if(A)return A;return n.analyzeNested(y,p)}let E=!m&&(!i||o.length>0)?(o.length>0?o:[void 0]).map((x)=>Ti(J(x===void 0?l:i?l.map((A)=>Ef(A,x)):[...l,...x]),y)):[];if(E.some((x)=>x.kind==="dynamic")){let x=Yt(n);if(x)return x}let C=E.flatMap((x)=>x.kind==="literal"?[x.source]:[]);if(C.length>0)return n.budget.charge("derivedTokens",C.length),Ve(C,(x)=>n.analyzeNested(x,p));if(Vr(y)){let x=Yt(n);if(x)return x}let P=n.analyzeNested(y,p);if(P)return P;if(d)return Yt(n);return null}let S=It(J(l));if(S.kind==="dynamic"||S.kind==="literal"&&B(S.source))return Yt(n)??h();if(S.kind==="literal")return h();if(o.length>0){let E=Yt(n);if(E)return E;let C=h();if(C)return C;if(i)return null;let P=o.flatMap((x)=>x[0]===void 0?[]:[x[0]]);return n.budget.charge("derivedTokens",P.length),Ve(P,(x)=>n.analyzeNested(x,p))}if(d||a)return Yt(n)??h();return null}if(e.head==="rm"&&it(l)){if(i&&o.length>0)return Ve(o,(y)=>rl(Oi(l,y,n.budget,lf),e.cwd,r));if(o.length>0)return Ve(o,(y)=>rl(pf(l,y,n.budget),e.cwd,r));let h=rl(l.flatMap((y,S)=>{if(S===0||!B(y))return[y];return y.startsWith("-")?[y.replace(lf,"")]:[]}),e.cwd,r);if(h)return h;return mf(n)}let g=o.length>0?o:[void 0];return Ve(g,(h)=>{let y=h===void 0?l:i?Oi(l,h,n.budget):pf(l,h,n.budget),S=v("parallel.shell-dynamic",qr),E=a&&e.head==="find"?eR(y,r):null,C=bf(y,a,n)??E?.customResult??null,P=M(e.head),x=a&&(P==="rm"&&ol(y)||P==="xargs"&&Sf(y)||E?.rmOptions===!0),A=a&&(x||E?.executedSource===!0||E===null&&Cf(y,P)),ee=n.analyzeChild(y,{...dn(e,r),worktreeMode:s||a||d?!1:n.worktreeMode,dynamicInput:a||d,dynamicRmInput:x,dynamicSourceInput:C!==null||A,shellDynamicMatch:S,dynamicSourceMatch:S,rmDynamicMatch:v("parallel.rm-recursive-force-dynamic",Kr)});if(A){let qe=T(S,n.policy);if(qe)return qe}return ee??C??At(y,n.policy?.rules??[])})}function Cf(e,t){if(B(e[0]??""))return!0;if(t==="eval"||t==="source"||t===".")return!0;if(t==="parallel"||t==="xargs")return!0;if(Q.has(t))return Qx(e);if(t==="git")return Xx(e);if(t==="find")return!0;if(Be.has(t))return df(e,jx,Hr);if(Xe(t))return df(e,Vx,Jo);return!1}function ol(e){let t=e.indexOf("--"),n=e.slice(1,t===-1?void 0:t);if(!e.some(B))return t===-1;return n.some((o)=>B(o)&&(o.startsWith("-")||wf(o)))}function Xx(e){if(Jx(e))return!0;let t=ze(e);if(t.subcommand===null||B(t.subcommand))return!0;if(!$n.has(t.subcommand.toLowerCase()))return!1;let n=t.rest.indexOf("--"),r=t.rest.slice(0,n===-1?void 0:n);if(!e.some(B))return n===-1;return r.some(B)}function Jx(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(B(e[t+1]??""))return!0;t++;continue}if(n.startsWith("-c")&&n.length>2||n.startsWith("--config-env=")){if(B(n))return!0;continue}if(B(n))return!0}return!1}function Qx(e){if(Pt(e))return!1;let t=st(e);if(t!==null)return B(t);let n=It(J(e));if(n.kind==="literal")return B(n.source);if(n.kind==="dynamic")return!0;return!e.some(B)}function df(e,t,n){let r=n(e);if(r.some((o)=>B(o.value)))return!0;if(!e.some(B))return n([...e,uf]).some((o)=>o.value===uf);return _i(r,t,(o)=>n(e.map((i)=>Ef(i,[o]))))}function bf(e,t,n){let r=n.policy?.rules??[];if(!t||r.length===0)return null;let o=r.filter((i)=>M(i.command)===M(e[0]??""));if(o.length===0)return null;if(e.slice(1).some(B))return Yt(n);return Ve(o,(i)=>At([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],[i]))}function eR(e,t){let n={customResult:null,executedSource:!e.some(B),rmOptions:!1},r=!1,o=0,i=null,s=()=>{if(!i?.some(B))return;for(let a of ot(i,t))n.executedSource||=Cf(a.tokens,a.head),n.rmOptions||=a.head==="rm"&&ol(a.tokens)||a.head==="xargs"&&Sf(a.tokens),n.customResult??=bf(a.tokens,!0,t)};for(let a of e.slice(1)){if(!r&&!a.startsWith("-")&&a!=="!"&&a!=="("){n.executedSource||=B(a);continue}if(r=!0,i){if(a===";"||a==="+"){s(),i=null;continue}i.push(a);continue}if(o>0){o--;continue}if(ft(a)){i=[],n.executedSource||=B(a);continue}let l=Tt(a);if(l>0){o=l,n.executedSource||=B(a);continue}n.executedSource||=B(a)}return s(),n}function Sf(e){let t=e.slice(pn(e).childStart);return M(t[0]??"")==="rm"&&ol(t)}function Di(e,t){return(n)=>T(v(e,t),n.policy)}var Yt=Di("parallel.shell-dynamic",qr),tR=Di("parallel.command-stream-dynamic",$x),Vn=Di("parallel.command-stream-dynamic",Ux),mf=Di("parallel.rm-recursive-force-dynamic",Kr);function rl(e,t,n){return T(Ai(J(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:cn(n.envAssignments??new Map,n.environment),protectedGitMetadata:n.protectedGitMetadata,policy:n.policy}),n.policy)}function vf(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 Ef(e,t){return e.replace(Mi,(n)=>xf(n,t))}function Oi(e,t,n,r=Mi){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=xf(i,t);return n.charge("derivedTokens",Math.max(1,Math.ceil(s.length/64))),s}))}function ff(e,t,n){return Oi([e],t,n)[0]??""}function pf(e,t,n){return n.charge("derivedTokens",e.length+t.length),[...e,...t]}function xf(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 B(e){return e.search(Mi)!==-1}function Rf(e){if(il(e))return!0;for(let t of e.matchAll(Mi))if(!/^(?:\{\}|\{\d+\})$/.test(t[0]))return!0;return!1}function il(e){let t=e.indexOf("{=");return t!==-1&&e.indexOf("=}",t+2)!==-1}function wf(e){return/^\{[^{}\s]*\}$/.test(e)}function nR(e,t,n){if(e===void 0)return;if(e==="..."||/^~|[{}$`*?[]/.test(e))return null;if(!t&&!gf.isAbsolute(e))return null;try{return Ht(t??e,e,n)}catch{return null}}function _f(e){let t=1,n=[],r=e.length,o=-1,i=!1,s=!1,a,l=!1,c=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=Wa(e,t+1);n.push(...E.templateTokens),r=t+1,o=E.markerIndex;break}if(!p.startsWith("-")){let E=Wa(e,t);n.push(...E.templateTokens),r=t,o=E.markerIndex;break}let g=e[t+1],h=p.indexOf("="),y=h===-1?p:p.slice(0,h),S=h===-1?void 0:p.slice(h+1);if(p==="--dry-run"){l=!0,t++;continue}if(p==="-I"||p.startsWith("-I")&&p.length>2){c||=(p==="-I"?g:p.slice(2))!=="{}",t+=p==="-I"?2:1;continue}if(p==="--replace"||p==="-i"){c=!0,t+=2;continue}if(y==="--replace"||p.startsWith("-i")&&p.length>2){let E=y==="--replace"?S:p.slice(2);c||=E!==""&&E!=="{}",t++;continue}if(p==="-a"||qx.has(y)){c=!0,t+=S===void 0?2:1;continue}if(p==="--pipe"||p==="--pipepart"){s=!0,t++;continue}if(y==="--env"){c=!0,t+=S===void 0?2:1;continue}if(cf.has(y)||p.startsWith("-S")&&p.length>2){i=!0,t+=cf.has(p)?2:1;continue}if(Yx.has(y)){c=!0;let E=S??g;if(E===void 0||E===":::"||E==="--"){t++;continue}a=E,t+=S===void 0?2:1;continue}if(p.startsWith("-j")&&p.length>2&&/^\d+$/.test(p.slice(2))){t++;continue}if(p.startsWith("--")&&S!==void 0){t++;continue}if(Kx.has(p)){if(g===void 0||g===":::"||g==="--"){c=!0,t++;continue}t+=2;continue}t+=p==="-j"||p==="--jobs"?2:1}c||=n.some(l?il:Rf);let u=[];if(o!==-1){let p=[];for(let g=o+1;g<e.length;g++){let h=e[g];if(h===":::"){u.push(p),p=[];continue}if(h!==void 0)p.push(h)}u.push(p)}c||=u.length>1;let m=rR(u),d=n.some(B),f=n.length===0&&o===-1;return{template:n,jobs:m,childStart:r,templateHasPlaceholder:d,runsRemotely:i,usesStdin:s||o===-1,readsCommandsFromInput:f,unsupported:c,workdir:a,dryRun:l}}function rR(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)>X.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)>X.derivedTokens.cap)throw new N("derivedTokens");o.push([...i,s])}t=o}return t}function Af(e){return _f(e).childStart}var oR="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",Ni="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function al(e){return e?.parts.some((t)=>t.provenance==="command-substitution")??!1}function sl(e){return e?.parts.some((t)=>t.provenance==="literal"&&t.raw.replace(/^["']/,"").startsWith("-"))??!1}function Tf(e,t,n,r,o=!1,i){let a=(yr(e,t)||r&&e!=="powershell"&&t[0]?.provenance==="variable")&&me(i,"shell.dynamic-executable",o)?v("shell.dynamic-executable",oR):null;return T(a,i)??kf(e,t,n,o,i)}function kf(e,t,n,r,o){if(t.length<2)return null;let i=t.flatMap((a,l)=>al(a)?[l]:[]);if(i.length===0)return null;let s=M(t[0]?.text??"");if(s==="git"){let a=Mn(e,t),l=sR(a);if(me(o,"shell.dynamic-structure",r)&&i.some((m)=>m<=l))return T(v("shell.dynamic-structure",Ni),o);if(T(wi(a,{environment:n}),o))return null;let c=t[l]?.text.toLowerCase(),u=a.findIndex((m,d)=>d>l&&_(m)==="--");if(me(o,"shell.dynamic-structure",r)&&c&&$n.has(c)&&i.some((m)=>m>l&&(u===-1||m<u)))return T(v("shell.dynamic-structure",Ni),o);return null}if(s==="find")return me(o,"shell.dynamic-structure",r)&&aR(t)?T(v("shell.dynamic-structure",Ni),o):null;if(s==="rm"){let a=t.findIndex((c,u)=>u>0&&_(c)==="--"),l=it(t.map(_));return me(o,"shell.dynamic-structure",r)&&i.some((c)=>(a===-1||c<a)&&(c<t.length-1||!l))?T(v("shell.dynamic-structure",Ni),o):null}if(s==="xargs")return Pf(e,t.slice(pn(t.map(_)).childStart),"xargs",n,r,o);if(s==="parallel")return Pf(e,t.slice(Af(t.map(_))),"parallel",n,r,o);return null}function Pf(e,t,n,r,o,i){if(t.length===0)return null;let s=iR(t,r);if(yr(e,s)){let l=T(v(`${n}.shell-dynamic`,n==="xargs"?nl:qr),i);if(l)return l}let a=kf(e,s,r,o,i);if(a)return a;if(s[0]?.text==="rm"&&s.slice(1).some((l)=>al(l)&&sl(l)))return T(v(`${n}.rm-recursive-force-dynamic`,n==="xargs"?tl:Kr),i);return null}function iR(e,t){let n=sn(e,t),r=n.rewritten?J(n.words.map(_)):n.words,o=r[0];return o&&_(o)==="busybox"?r.slice(1):r}function sR(e){let t=1;while(t<e.length){let n=e[t],r=n?_(n):"";if(De.has(r)){t+=2;continue}if(r.startsWith("-")){t++;continue}return t}return t}function aR(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=al(s);if(n>0){n--;continue}if(o){if(s.text===";"||s.text==="+"){o=!1,t=!0,r=!1;continue}if(a&&(r||sl(s)))return!0;r=!1;continue}if(!t&&!s.text.startsWith("-")){if(a&&(i>1||sl(s)))return!0;continue}if(t=!0,a)return!0;let l=Tt(s.text);if(l>0){n=l;continue}if(ft(s.text))o=!0,r=!0}return!1}function ll(e,t){return e.some((n)=>{if(n.value==="-"&&(n.kind==="main-script"||n.kind==="program-file"))return!0;return!qo(t[n.tokenIndex],n.value)})}var lR="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",cR="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",uR="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function If(e,t){let n=t.slice(1);if(e==="dd"&&n.some((r)=>/^of=\/dev\/.+/.test(r)))return v("dd.device-write",lR);if((e==="mkfs"||e.startsWith("mkfs."))&&n.some((r)=>r.startsWith("/dev/")))return v("mkfs.device",cR);if(e==="shred"&&n.length>0)return v("shred.target",uR);return null}var Mf=[{heads:new Set(["rm","rmdir"]),analyze:(e)=>Ai(e.words,{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:cn(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,policy:e.options.policy,budget:e.options.budget})},{heads:new Set(["git"]),analyze:(e)=>wi(e.words,cl(e))},{heads:new Set(["find"]),analyze:(e)=>dm(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:jt(e.envAssignments,e.options.environment),trustedTmpdirValue:cn(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,budget:e.options.budget,envAssignments:e.envAssignments,policy:e.options.policy,analyzeTokens:e.analyzeChildTokens,analyzeNested:(t,n)=>gn(e.options.analyzeNested(t,n))})},{heads:new Set(["xargs"]),analyze:(e)=>ef(e.words,{...Of(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>gn(e.options.analyzeNested(t,n))})},{heads:new Set(["parallel"]),analyze:(e)=>yf(e.words,{...Of(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>gn(e.options.analyzeNested(t,n))})}];function Of(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 gn(e){return e?{id:e.ruleId??"",reason:e.reason,intent:e.intent??"manual_only"}:null}function cl(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 Wf(e){return Mf.find((t)=>t.heads.has(e))?.analyze}function qn(e,t,n){let r=n.trace;if(e.length===0)return null;let o=n.commandView?.dialect??"posix",i=(R)=>R.map((I)=>o==="posix"?_(I):I.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,m=s?s.originalCwd:c?void 0:n.cwd,d=ni(e);if(d.envAssignments.size>0)r?.recordSegment({type:"env-strip",input:i(e),envVars:[...d.envAssignments.keys()],output:i(d.words)});let f=sn(d.words,n.environment,u,new Map([...n.envAssignments??[],...d.envAssignments])),p=f.envSplitValues??[];if(p.length>0){let R=[...p,...i(f.words)].join(" "),I=$e(R);if(I)return r?.recordSegment({type:"dangerous-text",token:R,matched:!0,reason:I.reason}),ve(I);if(n.strict)return ke(r);let G=ri(p,i(f.words));if(G){n.budget.charge("derivedTokens",G.length);let ce=n.analyzeNested(G.join(" "),{effectiveCwd:f.cwd===void 0?n.effectiveCwd:f.cwd,envAssignments:new Map([...n.envAssignments??[],...d.envAssignments,...f.envAssignments])});if(ce)return ce}}let g=f.rewritten?J(i(f.words)):Mn(o,f.words),h=i(g),y={...n,wrapperNormalizationBudget:n.wrapperNormalizationBudget??{iterations:0}};if(r&&d.words.length>g.length){let R=i(d.words);r.recordSegment({type:"leading-tokens-stripped",input:R,removed:R.slice(0,R.length-g.length),output:h})}let S=new Map([...n.envAssignments??[],...d.envAssignments,...f.envAssignments]),E=h[0];if(!E)return null;if(un(E))throw new N("wrapperPeelIterations");let C=M(E),P=f.cwd===null?void 0:f.cwd??u,x=f.cwd===null?void 0:m,A=f.cwd===void 0?n.effectiveCwd:f.cwd,ee=s?s.allowTmpdirVar:!Lr(S,n.environment),qe=Tf(o,f.words,n.environment,t===0,n.strict,n.policy);if(qe)return r?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:qe.reason}),ve(qe);let ct=bi(h,n.policy);if(ct){for(let R of[ct.childIndex,...ct.alternativeChildIndices]){Df(y.wrapperNormalizationBudget);let I=g.slice(R);r?.recordSegment({type:"transparent-wrapper",wrapper:ct.wrapper,output:i(I)});let G=qn(I,t,{...y,effectiveCwd:A,envAssignments:S});if(G)return G}return null}let xe=l?void 0:C==="eval"?Pi(g):C==="trap"&&!a?Vm(g):void 0;if(a&&s&&C==="eval"){if(xe?.kind==="dynamic")return Kn(s,n.policy);if(xe?.kind==="literal"){let R=n.analyzeNested(xe.source,{effectiveCwd:A,envAssignments:S});if(R)return R}return Yn(s,n.policy)}if(xe?.kind==="dynamic"&&(n.strict||!n.commandView||!Qa(n.commandView)))return ke(r);if(xe?.kind==="literal"){r?.recordSegment({type:"recurse",reason:C==="eval"?"shell-eval":"shell-trap",innerCommand:xe.source,depth:t+1});let R=n.analyzeNested(xe.source,{effectiveCwd:A,envAssignments:S,functionDefinitions:n.functionDefinitions});if(R)return R}if(a?Q.has(C):Ff(E,C)){if(Pt(h))return null;if(a&&s){let R=st(h);if(R){if(s.dynamicSourceInput??s.dynamicInput){let G=Kn(s,n.policy);if(G)return G}if(Vr(R)){let G=Kn(s,n.policy);if(G)return G}return n.analyzeNested(R,{effectiveCwd:A,envAssignments:S})}let I=It(g);if(I.kind==="dynamic")return Kn(s,n.policy);if(I.kind==="literal")return s.dynamicSourceInput?Kn(s,n.policy):null;return s.dynamicSourceInput??s.dynamicInput?Kn(s,n.policy):null}if(l){let R=st(h),I=R?n.analyzeNested(R,{effectiveCwd:A,envAssignments:S}):It(g).kind==="dynamic"?ke(r):null;if(I)return I}if(s===void 0){let R=pR(h,S,A,n,r,t);if(R)return R;let I=st(h);if(I){let En=Ti(g,I);if(En.kind==="dynamic")return ke(r);let Zi=En.kind==="literal"?En.source:Km(g,I),Gl=gR(Zi);r?.recordSegment({type:"shell-wrapper",wrapper:C,innerCommand:Gl}),r?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:Gl,depth:t+1});let Fl=n.analyzeNested(Zi,{effectiveCwd:A,envAssignments:S});if(Fl)return Fl;return Vr(Zi)?ke(r):null}let G=It(g,n.strict?void 0:n.shellAssignments);if(G.kind==="dynamic")return ke(r);if(G.kind==="literal")return Li(G.source,A,S,n,r,t);let ce=qm(g,n.commandView?.redirections??[],n.hasPipelineInput??!1,n.literalShellInput);if(ce.kind==="dynamic")return ke(r);if(ce.kind==="literal")return r?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:ce.source,depth:t+1}),n.analyzeNested(ce.source,{effectiveCwd:A,envAssignments:S})}}if(!s&&(C==="source"||C===".")){let R=h[1]==="-p"?2:null;if(R!==null){let En=n.commandView?g[R]:void 0;if(!En)return null;if(En.provenance!=="literal")return ke(r)}let I=R===null?1:3,G=h[I]==="--"?I+1:I,ce=n.commandView?g[G]:void 0;if(!ce)return null;if(ce.provenance==="literal")return Li(ce.text,A,S,n,r,t);if(n.strict||!n.commandView||!Qa(n.commandView))return ke(r)}if(Be.has(C)&&!l){if(!s&&n.strict&&ll(Hr(h),g))return ke(r);let R=im(h,(G)=>gn(n.analyzeNested(G,{effectiveCwd:A,envAssignments:S}))),I=T(R,n.policy);if(I)return r?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:I.reason}),ve(I)}if(Xe(C)&&!l){if(!s&&n.strict&&ll(Jo(h),g))return ke(r);let R=ud(h);if(a&&s)return mR(C,R,A,S,n,s);if(R){let I=me(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(r?.recordSegment({type:"interpreter",interpreter:C,codeArg:R,paranoidBlocked:I}),I){let ce=T(v("interpreter.one-liner-paranoid",_r),n.policy);if(ce)return ve(ce)}if(fa(C,R))return null;r?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:R,depth:t+1});let G=n.analyzeNested(R,{effectiveCwd:A,envAssignments:S});if(G&&!Gf(G,R))return G;if(Ar(R,void 0,!n.strict)){let ce=T(v("interpreter.dangerous-command",Ln),n.policy);if(ce)return r?.recordSegment({type:"dangerous-text",token:R,matched:!0,reason:Ln}),ve(ce)}r=void 0}}if(C==="busybox"&&h.length>1)return Df(y.wrapperNormalizationBudget),r?.recordSegment({type:"busybox",subcommand:h[1]??"unknown"}),r?.recordSegment({type:"recurse",reason:"busybox",innerCommand:h.slice(1).join(" "),depth:t+1}),qn(g.slice(1),t,{...y,effectiveCwd:A,envAssignments:S});let H=s?null:T(If(C,h),n.policy);if(H)return r?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:H.reason}),ve(H);let ie=r===y.trace?y:{...y,trace:r},ne={words:g,head:C,cwd:P,originalCwd:x,envAssignments:S,allowTmpdirVar:ee,dynamicArguments:f.words.some((R)=>R.provenance==="command-substitution"),depth:t,effectiveCwd:A,options:ie,analyzeChildTokens:(R,I)=>a&&s?ul(R,t,ie,{...s,cwd:I??void 0,effectiveCwd:I??void 0}):gn(qn(J(R),t+1,{...ie,child:void 0,commandView:void 0,effectiveCwd:I,envAssignments:S}))??At(R,ie.policy.rules),analyzeChild:(R,I)=>ul(R,t,ie,I)},se=s&&(C==="xargs"||C==="parallel")?void 0:Wf(C);if(C==="rm"||C==="xargs"||C==="parallel")r?.recordSegment({type:"tmpdir-check",tmpdirValue:S.has("TMPDIR")||n.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:ee});let Oe=r&&C==="git"?Wm(ne.words,cl(ne)):void 0,Dt=Nf(Oe?Oe.match:se?.(ne)??null,n.policy);if(r)hR(ne,Dt,Oe?.relaxation??null);if(Dt)return ve(Dt);if(a&&s&&(C==="rm"||C==="rmdir")){if(!(C==="rm"&&(it(h)||s.dynamicRmInput)))return null;return(s.dynamicRmInput?Yn(s,n.policy):null)??fR(s,n.policy)}let no=!s&&se===void 0&&!Eo.has(C),yt=r&&no?[]:void 0;if(no)for(let R=1;R<h.length;R++){let I=h[R];if(!I)continue;yt?.push(I);let G=Nf(dR(h,R,t,ie,P,x,A,S),n.policy);if(G)return r?.recordSegment({type:"fallback-scan",tokensScanned:yt??[],embeddedCommandFound:M(I)}),ve(G)}if(r?.recordSegment({type:"fallback-scan",tokensScanned:yt??[]}),l&&s&&!s.wrappedByTransparent)return null;let ro=At(h,n.policy.rules);if(r?.recordSegment({type:"custom-rules-check",rulesChecked:n.policy.rules.length>0,matched:!!ro,reason:ro?.reason}),ro)return ve(ro);return a&&s?Yn(s,n.policy):null}function ul(e,t,n,r){return gn(qn(J(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 dR(e,t,n,r,o,i,s,a){for(let l of ot(e.slice(t),{environment:r.environment,cwd:o,envAssignments:a,policy:r.policy})){let c=l.tokens[0];if(!c)continue;let u=M(c);if(Ff(c,u)||Wf(u)!==void 0&&u!=="xargs"&&u!=="parallel"||l.wrappedByTransparent&&r.policy.rules.length>0)r.budget.charge("derivedTokens",e.length-t);let d=ul(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:!Lr(l.envAssignments,r.environment),worktreeMode:!1,wrappedByTransparent:l.wrappedByTransparent});if(d)return d}return null}function mR(e,t,n,r,o,i){if(!t)return Yn(i,o.policy);if(me(o.policy,"interpreter.one-liner-paranoid",!!o.paranoidInterpreters)){let a=T(v("interpreter.one-liner-paranoid",_r),o.policy);if(a)return ve(a)}if(fa(e,t))return Yn(i,o.policy);let s=o.analyzeNested(t,{effectiveCwd:n,envAssignments:r});if(s&&!Gf(s,t))return s;if(Ar(t,void 0,!o.strict)){let a=T(v("interpreter.dangerous-command",Ln),o.policy);if(a)return ve(a)}return Yn(i,o.policy)}function Gf(e,t){let n=e.ruleId==="raw-text.dangerous-command",r=(e.reason.startsWith(hi)||e.reason===Hn)&&!xo(t);return n||r}function Kn(e,t){let n=e.shellDynamicMatch?T(e.shellDynamicMatch,t):null;return n?ve(n):null}function Yn(e,t){let n=e.dynamicSourceInput&&e.dynamicSourceMatch?T(e.dynamicSourceMatch,t):null;return n?ve(n):null}function fR(e,t){let n=e.dynamicInput&&e.rmDynamicMatch?T(e.rmDynamicMatch,t):null;return n?ve(n):null}function pR(e,t,n,r,o,i){let s=um(e);if(s.argvSource?.kind==="absent")return ke(o);if(s.argvSourceApplies&&s.argvSource){let l=Li(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 Li(a,n,t,r,o,i,!0)}function Li(e,t,n,r,o,i,s=!1){if(s&&/[$`*?[\]]/.test(e))return ke(o);let a=wr(e,t,r.environment.paths,r.budget),l=a?r.literalHeredocFiles?.get(a):void 0;if(l===void 0)return s?ke(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 gR(e){let t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.at(-1)===t?e.slice(1,-1):e}function hR(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 Df(e){if(e.iterations>=X.wrapperPeelIterations.cap)throw new N("wrapperPeelIterations");e.iterations++}function ve(e){return{reason:e.reason,ruleId:e.id||void 0,intent:e.intent}}function ke(e){return e?.recordSegment({type:"error",message:Fr}),ve(yR())}function yR(){return{id:"",reason:Fr,intent:"stop_and_explain"}}function Ff(e,t){return Q.has(t)||e==="$SHELL"||e==="${SHELL}"||Q.has(k(t))}function Nf(e,t){return e?.id.startsWith("custom.")||e?.id==="raw-text.dangerous-command"?e:T(e,t)}var CR=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,bR=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function SR(e,t){let n=Bf(e,t);if(n.length===0)return!1;let r=n[Hf(n)];if(r==="cd"||r==="pushd"||r==="popd")return!0;return CR.test(e.join(" "))}function zf(e,t,n,r,o){if(e.dialect==="powershell"){let y=vR(e.words,o);if(y.kind==="none")return;if(!t||y.kind==="unknown")return null;return Lf(wR(y.target),t,n.paths)}let i=e.words.map(_),s=i.some((y)=>/^CDPATH\+?=/.test(y));if(!SR(i,n))return s?null:void 0;if(!t)return null;let a=Bf(i,n,t),l=Hf(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),f=d[0]==="--"?d.slice(1):d;if(f.length!==1)return null;let p=f[0]??"",g=e.words.find((y)=>y.provenance==="variable"&&y.text===p),h=g?pt(g,r):p;if(h===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(h)&&(s||n.env.has("CDPATH")))return null;return Lf(h,t,n.paths)}function Lf(e,t,n){if(!e||e==="-"||e.startsWith("~")||e.includes("$")||e.includes("`"))return null;try{let r=Ht(t,e,n);return n.isDirectory(r)?r:null}catch{return null}}function vR(e,t){let n=ER(e[0])?1:0,r=e[n];if(!xR(r,n===1))return{kind:"none"};let o=r.text.toLowerCase(),i=o.split(/[\\/]/).pop()??o;if(!bR.has(i))return{kind:"none"};if(o!==i||i==="pop-location"||i==="popd")return{kind:"unknown"};return RR(e.slice(n+1),t)}function ER(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&(e.text==="&"||e.text===".")}function xR(e,t){return e?.provenance==="literal"&&(t||!e.quoted&&e.raw===e.text)}function RR(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 wR(e){return e.includes("::")?void 0:e.replaceAll("\\","/")}function Hf(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 Bf(e,t,n){let r=_R(e);return Bt([...r],t,n)}function _R(e){let t=0;while(t<e.length){let n=e[t];if(n!=="{"&&n!=="("&&n!=="$(")break;t++}return e.slice(t)}var AR="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",hn="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 hl(e,t,n,r){if(t>=X.recursionDepth.cap)return n.trace?.recordSegment({type:"error",message:ut}),{reason:ut,segment:e,intent:"stop_and_explain"};let o=r??n.factStore?.getCommandProgram(e,n.shell??"auto")??Je(e,n.shell);if(o.status==="limited")return n.trace?.recordSegment({type:"error",message:ut}),{reason:ut,segment:e,intent:"stop_and_explain"};if(o.status==="invalid"){let c=o.issues.find((u)=>u.code.includes("heredoc"));if(c){if(!n.strict)return gl(e,n);let u=`${hi}: ${c.message}`;return n.trace?.recordGlobal({type:"error",message:u}),{reason:u,segment:e,intent:"stop_and_explain"}}return qf(e,n),{reason:Hn,segment:e,intent:"stop_and_explain"}}if(n.strict&&o.status==="partial")return qf(e,n),{reason:Hn,segment:e,intent:"stop_and_explain"};if(o.issues.some((c)=>c.code.includes("quote")))return gl(e,n);let s=n.cwd,a=n.effectiveCwd!==void 0?n.effectiveCwd:n.cwd,l=Rm(n.environment.env,n.envAssignments);return Fi(o,t,{...n,rootProgram:o},s,[{effectiveCwd:a,shellGitContextState:l,literalHeredocFiles:new Map(n.literalHeredocFiles),functionDefinitions:new Map(n.functionDefinitions),createdDirectories:new Set}]).result}function Fi(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 m=e.nodes[c+1],d=m?.kind==="connector"?m.operator:void 0,f=PR(e,c,u,a,d),g=a==="&&"||a==="||"?s:void 0,h=a==="&&"?g?.success??i:a==="||"?g?.failure??i:i,y=a==="||"?g?.success??[]:[],S=a==="&&"?g?.failure??[]:[],E={connector:a,skippedSuccessStates:y,skippedFailureStates:S};if(Zt(d)&&!Zt(a))l=E;let C=Zt(d)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:Zt(a)?l??E:E,P=yn(C.connector)||yn(d);if(u.kind==="function"){let Z=h.flatMap((ie)=>{let ne=Xn(ie);return ne.functionDefinitions.set(u.name,u.body),dl(ie,[ne],f,d==="&",yn(d))}),H=ml(Z,[],C.skippedSuccessStates,C.skippedFailureStates,C.connector,d);i=H.states,s=H.conditionalStates,a=void 0;continue}if(u.kind==="group"){let Z=[],H=[];for(let ne of h){let se=Fi(u.body,t,n,r,[Xn(ne)]);if(se.result)return se;if(Z.push(...dl(ne,se.states,f,d==="&",yn(d))),P)H.push(ne,...f?se.states.map((Oe)=>Wi(ne,Oe)):se.states)}let ie=ml(Z,H,C.skippedSuccessStates,C.skippedFailureStates,C.connector,d);i=ie.states,s=ie.conditionalStates,a=void 0;continue}if(u.kind!=="command")continue;let x=n.trace?.flattenNested?n.trace.currentSegmentIndex:n.trace?.allocateSegment(),A=e.nodes[c-2],ee=Zt(a)&&A?.kind==="command"?jm(A)??kR(A):void 0,qe=[],ct=[];for(let Z of h){let H=IR(u,t,n,r,[Xn(Z)]);if(H.result)return{result:H.result,states:i};let ie=e.dialect==="powershell"?H.states:H.states.map((ne)=>Wi(Z,ne));for(let ne of ie){let se=Xn(ne),Oe=DR(u,t,n.trace?{...n,trace:Yf(n.trace,x)}:n,r,se,Zt(a),ee);if(Oe)return{result:Oe,states:i};let Dt=ew(u,se.functionDefinitions);if(Dt)n.budget.charge("derivedTokens",zi(Dt));let nr=Dt?t+1>=X.recursionDepth.cap?fl(u.displayText,n,[se]):Fi(Dt,t+1,n,r,[se]):{result:null,states:JR(u,se)};if(nr.result)return nr;qe.push(...dl(Z,nr.states,f,d==="&",yn(d)));let no=typeof se.effectiveCwd==="string"&&se.effectiveCwd!==ne.effectiveCwd&&u.redirections.every((yt)=>["<",">",">>",">|"].includes(yt.operator)&&yt.target?.text==="/dev/null");if(P&&!no)ct.push(Z),ct.push(...nr.states.map((yt)=>f?Wi(Z,yt):yt))}}let xe=ml(qe,ct,C.skippedSuccessStates,C.skippedFailureStates,C.connector,d);i=xe.states,s=xe.conditionalStates,a=void 0}return{result:null,states:i}}function PR(e,t,n,r,o){if(n.kind==="group"&&n.style==="subshell")return!0;if(e.dialect==="posix"&&(Zt(r)||Zt(o)))return!0;if(o==="&")return!0;return e.dialect==="powershell"&&n.kind==="group"&&n.style==="brace"&&TR(e,t)}function dl(e,t,n,r,o){let i=n?t.map((a)=>Wi(e,a)):[...t],s=o?i.flatMap((a)=>Zn(e.literalHeredocFiles,a.literalHeredocFiles)?[a]:[{...a,literalHeredocFiles:new Map(e.literalHeredocFiles)},a]):i;return r?[e,...s]:s}function Wi(e,t){return{...e,literalHeredocFiles:new Map(t.literalHeredocFiles),createdDirectories:new Set(t.createdDirectories)}}function TR(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(OR(n))return!0;return n.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function Zt(e){return e==="|"||e==="|&"}function kR(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 yn(e){return e==="&&"||e==="||"}function ml(e,t,n,r,o,i){let s={success:Gi([...n,...e]),failure:Gi([...r,...t])},a=yn(i)?s:void 0;return{states:yn(o)||a?Gi([...s.success,...s.failure]):s.success,conditionalStates:a}}function Yf(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 IR(e,t,n,r,o){let i=e.nested.map((s)=>({program:s,depth:t}));if(e.dialect==="powershell"){let s=MR(e);if(s){if(t+1>=X.recursionDepth.cap)return fl(s,n,o);let a=Je(s,"powershell");if(a.status==="limited")return fl(s,n,o);if(a.status!=="complete")return $f(i,n,r,o);n.budget.charge("derivedTokens",zi(a)),i.push({program:a,depth:t+1})}}return $f(i,n,r,o)}function OR(e){let t=e.words[0];return t?.provenance==="variable"&&e.words.at(-1)?.text==="="?t.text.toLowerCase():void 0}function $f(e,t,n,r){let o=[...r];for(let i of e){let s=[];for(let a of o){let l=Fi(i.program,i.depth,t,n,[Xn(a)]);if(l.result)return l;s.push(...l.states)}o=Gi(s)}return{result:null,states:o}}function MR(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 zi(e){return e.nodes.reduce((t,n)=>t+(n.kind==="command"?n.words.length+n.nested.reduce((r,o)=>r+zi(o),0):n.kind==="group"||n.kind==="function"?zi(n.body):0),0)}function fl(e,t,n){return t.trace?.recordSegment({type:"error",message:ut}),{result:{reason:ut,segment:e,intent:"stop_and_explain"},states:[...n]}}function DR(e,t,n,r,o,i,s){let a={...n,environment:{...n.environment,env:o.shellGitContextState.env,paths:FR(n.environment.paths,o.createdDirectories,n.budget)}},l=jR(e,!a.strict);if(l&&a.strict)return a.trace?.recordSegment({type:"error",message:l}),{reason:l,segment:e.source,intent:"stop_and_explain"};Zf(e,o,"before-consumer",a.environment.paths,a.budget);let c=Mn(e.dialect,e.words),u=c.map(_),m=e.displayText,d=Em(c,o.shellGitContextState),f=_m(d,o.shellGitContextState);if(e.dialect==="powershell"){let h=T(Xd(e,i,nw(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 tw(m,h)}if(u.length===1&&u[0]?.includes(" ")&&!yr(e.dialect,e.words)){let h=T($e(u[0]),a.policy),y=h!==null&&!a.strict&&ad(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:m,ruleId:h.id,intent:h.intent};a.trace?.recordSegment({type:"dangerous-text",token:u[0],matched:!1});let S=Uf(e,l,o,f,s,a);if(S)return S;return Ka(d,o.shellGitContextState),null}let p=qn(e.words,t,{...a,commandView:e,cwd:r,effectiveCwd:o.effectiveCwd,envAssignments:f,shellAssignments:o.shellGitContextState.shellAssignments,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:o.functionDefinitions,hasPipelineInput:i,literalShellInput:s,analyzeNested:(h,y)=>{let S=y&&Object.hasOwn(y,"effectiveCwd")?y.effectiveCwd:o.effectiveCwd,E=hl(h,t+1,{...a,effectiveCwd:S,envAssignments:y?.envAssignments??f,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:y?.functionDefinitions,worktreeMode:y?.worktreeMode??a.worktreeMode,trace:a.trace?Yf(a.trace,a.trace.currentSegmentIndex,!0):void 0});return E?{reason:E.reason,ruleId:E.ruleId,intent:E.intent}:null}});if(p)return{...p,segment:m};let g=Uf(e,l,o,f,s,a);if(g)return g;return Ka(d,o.shellGitContextState),null}function Uf(e,t,n,r,o,i){let s=VR(e,t,n,r??new Map,i);if(s)return s;return Zf(e,n,"after-consumer",i.environment.paths,i.budget),n.literalHeredocFiles.clear(),WR(e,t,n,i.environment.paths,i.budget),zR(e,n,i.environment.paths,i.budget),YR(e,n,o,i.environment,i.trace),null}var NR=new Set([">>","<>"]);function Zf(e,t,n,r,o){for(let s of e.redirections){if(!(n==="before-consumer"?LR(s):NR.has(s.operator)))continue;jf(s.target,t,r,o)}if(n!=="before-consumer"||!ge(e.words[0],"tee"))return;let i=Jf(e.words.slice(1));if(!i)return;for(let s of i.operands)jf(s,t,r,o)}function LR(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 jf(e,t,n,r){let o=e?.provenance==="literal"?wr(e.text,t.effectiveCwd,n,r):void 0;if(!o)return;t.literalHeredocFiles.delete(o)}function WR(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 GR(e,n.shellGitContextState.shellAssignments)){let a=wr(s,n.effectiveCwd,r,o);if(!a||!cd(a))continue;if(!n.literalHeredocFiles.has(a)&&n.literalHeredocFiles.size>=X.trackedHeredocFiles.cap)throw new N("trackedHeredocFiles");n.literalHeredocFiles.set(a,i.body)}}function GR(e,t){let n=pl($R(e.redirections)?.target,t),r=n===void 0?[]:[n];if(ge(e.words[0],"cat"))return BR(e.words)?r:[];if(!ge(e.words[0],"tee"))return[];let o=Jf(e.words.slice(1),t);if(!o||o.append||o.hasUnsupportedOptions)return[];let i=o.operands.map((s)=>pl(s,t));if(!i.every((s)=>s!==void 0))return[];return[...i,...r]}function pl(e,t){if(UR(e))return e.text;return(e&&pt(e,t))??void 0}function FR(e,t,n){if(t.size===0)return e;let r=(o)=>{let i=O(o,e,n);return[...t].some((s)=>s===i||s.startsWith(`${i}${Ke.sep}`))};return{realpath:(o)=>e.realpath(o)??(r(o)?O(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 zR(e,t,n,r){if(t.shellGitContextState.bodyDepth>0||!ge(e.words[0],"mkdir"))return;let o=e.words.slice(1).map((c)=>pl(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("..")||!Ke.isAbsolute(c)&&!l)continue;let u=O(Ke.resolve(l??"",c),n,r);if(a?HR(u,n):n.isDirectory(Ke.dirname(u))&&Xf(u,n))t.createdDirectories.add(u)}}function HR(e,t){let n=Ke.parse(e).root,r=e.slice(n.length).split(/[\\/]+/).filter(Boolean),o=(s)=>Ke.join(n,...r.slice(0,s+1)),i=r.findIndex((s,a)=>!t.isDirectory(o(a)));return i===-1||Xf(o(i),t)}function Xf(e,t){try{return t.entryKind(e)==="missing"}catch{return!1}}function BR(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 $R(e){let t=e.findLast((n)=>(n.fd??([">",">|",">>",">&"].includes(n.operator)?1:0))===1);return t?.operator===">"||t?.operator===">|"?t:void 0}function Jf(e,t=new Map){let n=[],r=!0,o=!1,i=!1;for(let s of e){if(s.provenance!=="literal"&&pt(s,t)===null)return;if(r&&ge(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 UR(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 ge(e,t){return e?.text===t&&e.raw===t&&e.provenance==="literal"&&!e.quoted}function yl(e){return e.quotedDelimiter||!/[$`\\]/.test(e.body)}function jR(e,t){let n=e.redirections.filter((l)=>l.operator==="<<"||l.operator==="<<-");if(n.length===0)return;if(n.length!==1)return hn;let r=n[0];if(!r?.heredoc)return hn;let o=/\$\(|`/.test(r.heredoc.body);if(!yl(r.heredoc)&&(!t||o))return AR;if(r.fd!==void 0&&r.fd!==0)return hn;if(e.redirections.some((l)=>l!==r&&["<","<<","<<-","<<<","<&","<>"].includes(l.operator)))return hn;let i=e.redirections.some((l)=>l!==r&&Vf(l.target));if(ge(e.words[0],"cat"))return i?hn:void 0;if(ge(e.words[0],"tee"))return i||e.words.slice(1).some(Vf)?hn:void 0;let s=e.words[0],a=e.words[1];if(ge(s,"git")&&(ge(a,"apply")||ge(a,"commit")))return;if(ge(s,"gh")&&(ge(a,"pr")||ge(a,"issue"))&&ge(e.words[2],"create"))return;return hn}function Vf(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}function VR(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(qR(e,i,n,r,o))return null;let a=KR(e,i,o);if(a!==void 0)return a?{reason:a.reason,segment:e.displayText,ruleId:a.id,intent:a.intent}:null;let l=gl(s.length===i.length?s.join(`
|
|
42
|
+
`):e.source,o);return l?{...l,segment:e.displayText}:null}function KR(e,t,n){let r=t.length===1?t[0]:void 0;if(!r?.heredoc||!yl(r.heredoc)||r.fd!==void 0&&r.fd!==0)return;let o=ge(e.words[0],"uv")&&ge(e.words[1],"run")?e.words.slice(2):e.words,i=o[0];if(i?.provenance!=="literal"||!Xe(i.text))return;let s=o.findIndex((m)=>ge(m,"-"));if(!o.slice(1,s===-1?void 0:s).every((m)=>m.provenance==="literal"&&m.text.startsWith("-")))return;let l=r.heredoc.body,c=me(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(n.trace?.recordSegment({type:"interpreter",interpreter:i.text,codeArg:l,paranoidBlocked:c}),c){let m=T(v("interpreter.one-liner-paranoid",_r),n.policy);if(m)return m}if(!Ar(l,void 0,!n.strict))return null;let u=T(v("interpreter.dangerous-command",Ln),n.policy);if(!u)return null;return n.trace?.recordSegment({type:"dangerous-text",token:l,matched:!0,reason:u.reason}),u}function qR(e,t,n,r,o){let i=t.length===1?t[0]:void 0;if(!i?.heredoc||!yl(i.heredoc)||i.fd!==void 0&&i.fd!==0)return!1;let s=sn(e.words,o.environment,n.effectiveCwd,r),a=s.words.map(_),l=M(a[0]??"");if((s.envSplitValues?.length??0)>0||!Q.has(l)&&!Q.has(k(l)))return!1;return Pt(a)}function YR(e,t,n,r,o){let i=zf(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 ZR=/^[A-Za-z_][A-Za-z0-9_]*$/,XR=8;function JR(e,t){let n=e.words[1]?.text;if(e.dialect!=="posix"||e.words[0]?.text!=="for"||n===void 0||!ZR.test(n))return[t];let r=e.words.slice(3);if(!(e.words[2]?.text==="in"&&r.length>=1&&r.length<=XR&&r.every((i)=>i.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(i.text))))return t.shellGitContextState.shellAssignments.delete(n),[t];return r.map((i)=>{let s=Xn(t);return s.shellGitContextState.shellAssignments.set(n,i.text),s})}function Xn(e){return{effectiveCwd:e.effectiveCwd,shellGitContextState:wm(e.shellGitContextState),literalHeredocFiles:new Map(e.literalHeredocFiles),functionDefinitions:new Map(e.functionDefinitions),createdDirectories:new Set(e.createdDirectories)}}function Gi(e){let t=[];for(let n of e){if(!t.some((r)=>QR(r,n)))t.push(n);if(t.length>X.controlFlowStates.cap)throw new N("controlFlowStates")}return t}function QR(e,t){return e.effectiveCwd===t.effectiveCwd&&Zn(e.shellGitContextState.env,t.shellGitContextState.env)&&Zn(e.literalHeredocFiles,t.literalHeredocFiles)&&Zn(e.functionDefinitions,t.functionDefinitions)&&Zn(e.shellGitContextState.effectiveEnvAssignments,t.shellGitContextState.effectiveEnvAssignments)&&Zn(e.shellGitContextState.shellAssignments,t.shellGitContextState.shellAssignments)&&e.shellGitContextState.bodyDepth===t.shellGitContextState.bodyDepth&&Kf(e.shellGitContextState.bodyAssignments,t.shellGitContextState.bodyAssignments)&&Kf(e.createdDirectories,t.createdDirectories)}function Kf(e,t){return e.size===t.size&&[...e].every((n)=>t.has(n))}function Zn(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 ew(e,t){let n=Cr(e);return n===void 0?void 0:t.get(n)}function tw(e,t){if(!t)return null;return{reason:t.reason,segment:e,ruleId:t.id,intent:t.intent}}function nw(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 gl(e,t){let n=T($e(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 qf(e,t){let n={type:"strict-unparseable",rawCommand:e,reason:Hn},r=t.trace?.currentSegmentIndex;if(r===void 0)t.trace?.recordGlobal(n);if(r!==void 0)t.trace?.recordSegment(n)}var rw=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function Qf(e,t,n,r){let o=hl(e,0,{...t,...Tu(t),budget:t.budget??ue(),factStore:r},n);if(!o)return null;return{kind:"deny",reason:o.reason,intent:o.intent??"manual_only",...o.ruleId?{ruleId:o.ruleId}:{},evidence:{command:e,segment:o.segment}}}function ep(e,t,n){try{return{decision:e()}}catch(r){let o=ow(r,t,n);if(!o)throw r;return o}}function ow(e,t,n){if(!(e instanceof N)||!rw.has(e.kind))return null;let r=X[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,intent:"stop_and_explain",evidence:{command:t,segment:t}},errorCode:r.errorCode}}var iw=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),bl=new Set(["cc-safety-net","ccsn"]),sw=new Set(["bunx","npx","pnpx"]),aw=new Set(["pnpm","yarn"]),lw=new Set(["npm","pnpm","yarn"]),cw=new Set(["bun","node"]);function Bi(e,t,n={}){if(bl.has(e))return 0;if(sw.has(e)){if(n.broad)return Cl(t);let o=t[0]==="-y"||t[0]==="--yes"?1:0;return Hi(t[o])?o+1:null}let r=n.broad?t.findIndex((o)=>!o.startsWith("-")):0;if(r!==-1&&lw.has(e)&&n.broad&&t[r]==="exec"){let o=Cl(t.slice(r+1));return o===null?null:r+1+o}if(aw.has(e)){if(e==="yarn"&&!n.broad)return null;if(!n.broad)return t[0]==="dlx"&&Hi(t[1])?2:null;if(r===-1||t[r]!=="dlx")return null;let o=Cl(t.slice(r+1));return o===null?null:r+1+o}if(cw.has(e)){let o=n.broad&&r!==-1?r:0;if(tp(t[o]))return o+1;if(e==="bun"&&t[o]==="run"&&tp(t[o+1]))return o+2}return null}function Cl(e){let t=e.findIndex((r)=>Hi(r));if(t===-1)return null;let n=t;while(n<e.length){let r=e[n]??"";if(!r.startsWith("-")&&!Hi(r))break;n++}return n}function Hi(e){if(!e)return!1;let t=e.indexOf("@");if(t===-1)return bl.has(e);if(t===0)return!1;let n=e.slice(t+1);if(n===""||n.includes("/")||n.includes(":"))return!1;return bl.has(e.slice(0,t))}function tp(e){let t=e?.replaceAll("\\","/");return[...iw].some((n)=>t===n||t?.endsWith(`/${n}`))}var np="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 rp(e,t,n){let r=Pe(e,"input-candidate");if(!r)return null;let o=Gn(r.shell,e.invocation.context.executionCwd,t,n,{findSegmentTarget:(i)=>uw(i,t),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return o?{target:o}:null}function uw(e,t){let n=Bt([...e],t),r=n.slice(1),o=Bi(k(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}var Yr=require("node:path");var ap="This path contains the protected policy config and you must not modify or delete it.",dw=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function lp(e,t,n){let r=yw(e.invocation.context,t,n);if(e.invocation.route.kind==="patch")return op(e.paths,!1,e.invocation.context.executionCwd,r,t,n);let o=Pe(e,"input-candidate");if(e.invocation.route.kind==="command")return o?ip(o.shell,e.invocation.context.executionCwd,r,t,n):null;if(e.invocation.route.kind==="unknown"&&o){let i=ip(o.shell,e.invocation.context.executionCwd,r,t,n);if(i)return i}return op(e.paths,e.invocation.route.kind==="grep"||e.invocation.route.kind==="glob"||lo(e.invocation.toolName),e.invocation.context.executionCwd,r,t,n)}function op(e,t,n,r,o,i){if(t)return null;let s=e.find((a)=>Zr(a,n,r,o,i));return s?{target:s}:null}function ip(e,t,n,r,o){let i=Gn(e,t,r,o,{findSegmentTarget:(s,a)=>mw(s,a,n,r,o)?.target??null,isRedirectionTarget:(s,a)=>Zr(s,a.cwd,n,r,o),findMalformedTarget:(s)=>hw(s,t,n,r,o)?.target??null});return i?{target:i}:null}function mw(e,t,n,r,o){if(Mr(e))return null;let i=$t([...e],r),s=k(i[0]??"").toLowerCase(),a=i.slice(1);if(s==="rm"&&fw(a)){let l=pw(a).find((c)=>sp(Ae(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(s==="find"){if(Ei(i,1)||Fa(i,r)){let c=(Br(J(i))??J(["."])).find((u)=>{let m=Ae(u.text,t.variables);return Zr(m,t.cwd,n,r,o)||sp(m,t.cwd,n,r,o)})?.text;if(c)return{target:c}}}if(s==="mv"){let l=ci(a).sources.find((c)=>Cw(Ae(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(gw(i,s))return null;for(let l of[...e,...i])for(let c of cp(l))if(Zr(Ae(c,t.variables),t.cwd,n,r,o))return{target:c};return null}function fw(e){return e.some((t)=>t==="--recursive"||t.startsWith("-")&&!t.startsWith("--")&&/[rR]/.test(t.slice(1)))}function pw(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 gw(e,t){if(!dw.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 hw(e,t,n,r,o){for(let i of e.split(/\s+/))for(let s of cp(i))if(Zr(s,t,n,r,o))return{target:s};return null}function cp(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.indexOf("=");return n===-1||n===t.length-1?[t]:[t,t.slice(n+1)]}function yw(e,t,n){let r=(a)=>Xr(he(a,e.executionCwd,t,n)),o=r(An(t)),i=[r(dr(e.executionCwd)),r(dr(e.configCwd))],s=new Set(i.map((a)=>Yr.dirname(a)));for(let a=Yr.dirname(o);;a=Yr.dirname(a))if(s.add(a),Yr.dirname(a)===a)break;return{files:new Set([o,...i]),directoriesAndAncestors:s}}function Zr(e,t,n,r,o){let i=Vl(e,t,r,o,(s)=>Xr(s)===So);return i!==null&&n.files.has(Xr(i))}function sp(e,t,n,r,o){return n.directoriesAndAncestors.has(Xr(he(e,t,r,o)))}function Cw(e,t,n,r,o){let i=Xr(he(e,t,r,o));return n.files.has(i)||n.directoriesAndAncestors.has(i)}function Xr(e){return process.platform==="win32"?e.toLowerCase():e}var Ee=require("node:path"),vp=require("node:url");var Ep="Access to a sensitive path is not allowed.",xp=new Set(["echo","printf"]),bw=new Set(["find"]),Sw=new Set(["!","do","elif","else","if","then","until","while"]),vw=new Set(["-exec","-execdir"]),Ew=new Set([";","+"]),xw=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),Rw=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Rp=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),ww=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),_w=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"]),wp=new Set(["-c","-e","-r","-E","--eval","--exec"]),Aw=new Map([["c",new Set(["bash","sh","zsh","dash","ksh","python"])],["e",new Set(["node","deno","bun","ruby","perl","rscript","osascript"])],["E",new Set(["perl"])],["r",new Set(["php"])]]),Pw=new Set(["grep","rg"]),Tw=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),kw=new Set(["commit","merge","notes","stash","tag"]),Iw=new Set(["-m","--message"]),Ow=new Set(["--grep"]),up=new Set(["jq","gojq","jaq"]),dp="f",mp="file",Mw="files",Dw=new Set(["e","f"]),Nw=new Set(["regexp","file"]),Lw=new Set(["e","f","A","B","C","m"]),Ww=new Set(["regexp","file","after-context","before-context","context","max-count"]),Sl="__CC_SAFETY_NET_PIPE_INPUT__",El=/[\w./~@+-]*[./~][\w./~@+-]*/g,Gw=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,Fw=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,zw=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,fp=/\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,pp=/\b(?:system|exec|spawn|popen)\s*$/,Hw=/\b(?:eval|exec)\s*\(/g,Bw=/\b(?:eval|exec)\s*$/,$w=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 gp(e,t,n,r,o,i){for(let s of e){let a=s.target;if(z_(a,s.cwd,t?.denyPaths??[],n,r,o))return{target:a,ruleId:"secret.deny-path"};if(i&&!i.has(a))continue;let l=G_(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(Op(a,s.cwd,r,o)))continue;if(c&&s.isRedirectionWriteTarget===!0&&!a.includes("$")&&!Rl(a,s.cwd,r,o))continue;if(c&&/\s/.test(a)&&!a.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(a)&&!Rl(a,s.cwd,r,o))continue;if(!l.startsWith("secret.cli.")&&H_(a,s.cwd,t?.allowPaths??[],n,r,o))continue;return{target:a,ruleId:l}}}return null}function _p(e,t,n,r,o={}){let i=hp(e,n,r),s=gp(i,t,e.invocation.context.configCwd,n,r);if(s===null||s.ruleId==="secret.deny-path"||o.strict!==!1)return s;let a=gp(i,t,e.invocation.context.configCwd,n,r,new Set(hp(e,n,r,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}).map((l)=>l.target)));return a?.ruleId!=="secret.deny-path"&&Uw(e,n)?null:a}function Uw(e,t){let n=Pe(e,"input-candidate")??Pe(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 li(n.shell)){if(s.kind==="operator"&&s.boundary)return!1;if(s.kind==="redirection")return!1;if(s.kind==="operator")continue;r.push(_t(s.text,t))}let o=Mt(r);if(o.length===0)return!1;let i=lt(o[0]??"").toLowerCase();if(e.invocation.route.kind==="unknown")return n.program.dialect==="powershell"&&(i==="ls"||i==="stat");return wl(i,o.slice(1))}function wl(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)=>xw.has(n))}function hp(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=Pe(e,"input-candidate");return[...s?Jn(s.shell,e.store,r,t,o,n,jw(s)):[],...i==="unknown"?e.paths.map((a)=>({target:a,cwd:o})):[]]}function jw(e){return e.program.dialect==="powershell"}function Jn(e,t,n,r,o,i,s=!1){if(e.status==="structural-limit")throw new nt;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})),...v_(_t(e.source,r),t,n,r,o,i)],l=(c)=>_t(n_(c,s),r);return ai(e,o,r,i,{word:l,segment:(c,u,m,d,f)=>{if(c.length===0)return null;if(a.push(...Ui(c,t,n,r,u.cwd,i,f)),m!==null)a.push(...Kw(m,c,t,n,r,u.cwd,i));return null},redirection:(c,u)=>{if(c.body!==void 0&&c.consumer!==void 0)a.push(...Ap(c.consumer,[c.body],t,n,r,u.cwd,i,(m)=>qw(c.consumer??[],m,t,n,r,u.cwd,i)));if(c.targetOrder==="legacy-segment")return Ea;return a.push({target:l(c.target),cwd:u.cwd,...c.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}}),a}function _l(e,t,n,r,o,i){let s=t.getShellSyntax(e);if(s.status==="structural-limit")throw new nt;return s.status==="complete"?Jn(s,t,n,r,o,i):null}function Ui(e,t,n,r,o,i,s){let a=(g)=>({target:g,cwd:o});if(s?.size){let g=e.filter((h,y)=>!s.has(y));if(up.has(lt(Mt(g)[0]??"").toLowerCase()))return[...e.filter((h,y)=>s.has(y)).map(a),...Ui(g,t,n,r,o,i)]}let l=t_(e).map(a),c=Mt(e);if(c.length===0)return l;let u=c[0]??"",m=lt(u).toLowerCase(),d=c.slice(1),f=c.findIndex((g)=>!Sw.has(g));if(n.skipMetadataOnlySegments===!0&&f!==-1&&wl(lt(c[f]??"").toLowerCase(),c.slice(f+1)))return l;let p=Vw(u,m,d);if(p)return[...l,...p.map(a)];if(xp.has(m))return n.displayOperandsAreCapturedOutput===!0?[...l,...Pp(e).map(a)]:l;if(m==="eval")return[...l,..._l(d.join(" "),t,n,r,o,i)??d.map(a)];if(m==="export")return[...l,...d.flatMap((g)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(g)?[g.slice(g.indexOf("=")+1)]:ht(m,g)).map(a)];if(m==="git")return[...l,...o_(d).map(a)];if(m==="gh")return[...l,...xl(m,d,Tw).map(a)];if(up.has(m))return[...l,...r_(d).map(a)];if(Pw.has(m))return[...l,...T_(d).map(a)];if(bw.has(m))return[...l,...l_(d,t,n,r,o,i).map(a)];if(Be.has(m))return[...l,...d.flatMap((g)=>ht("awk",g)).map(a),...d.flatMap((g)=>u_(g,t,n,r,o,i)),...d.flatMap(d_).map(a)];if(m==="curl")return[...l,...d.flatMap((g)=>ht(m,g)).map(a),...i_(d).map(a)];if(Dr(m)){let g=Or.has(m)?Ne([m,...d]):null;if(g!==null&&g.command!==null&&g.commandIndex!==null){let h=t.getShellSyntax(g.command);if(h.status==="structural-limit")throw new nt;if(h.status==="complete")return[...l,...Jn(h,t,n,r,o,i),...d.slice(g.commandIndex).filter((y)=>!y.startsWith("-")).map(a)]}return[...l,...c_(m,d,t,n,r,o,i)]}return[...l,...d.flatMap((g)=>ht(m,g)).map(a)]}function Vw(e,t,n){let r=Bi(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 Kw(e,t,n,r,o,i,s){if(Jw(t,n,r,o,i,s)){let a=Mt(e),l=wl(lt(a[0]??"").toLowerCase(),a.slice(1))?a.slice(1).filter((c)=>!c.startsWith("-")):[];return[...Pp(e),...l].map((c)=>({target:c,cwd:i}))}return Ap(t,Yw(e),n,r,o,i,s,()=>[])}function qw(e,t,n,r,o,i,s){let a=Mt(e);if(!Dr(lt(a[0]??"").toLowerCase()))return[];return _l(t,n,r,o,i,s)??[{target:t,cwd:i}]}function Ap(e,t,n,r,o,i,s,a){let l=Qw(e);if(l===null)return t.flatMap(a);return t.flatMap((c)=>Or.has(l)?Jn(n.getShellSyntax(c),n,r,o,i,s):$i(l,c,n,r,o,i,s))}function Pp(e){let t=Mt(e);if(t.length===0)return[];let n=lt(t[0]??"").toLowerCase();if(!xp.has(n))return[];let r=t[t[1]==="--"?2:1];if(n==="printf"&&r!==void 0&&!r.startsWith("-")&&!r.replaceAll("%%","").includes("%"))return[Al(r.replaceAll("%%","%"))];return t.slice(1)}function Yw(e){let t=Mt(e);if(t.length===0)return[];let n=lt(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 Zw(r);return[]}function Zw(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[Al(t)];let r=e.slice(1);return Array.from({length:Math.ceil(r.length/n)},(o,i)=>Xw(t,r.slice(i*n,(i+1)*n)))}function Xw(e,t){let n=0;return Al(e.replace(/%%|%[bqs]/g,(r)=>{if(r==="%%")return"%";let o=t[n]??"";return n++,o}))}function Al(e){return e.replace(/\\n/g,`
|
|
43
|
+
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function Jw(e,t,n,r,o,i){let s=Mt(e);if(s.length===0||lt(s[0]??"").toLowerCase()!=="xargs")return!1;let a=pn(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,Sl]:l.map((m)=>m.split(c).join(Sl));return Ui(u,t,n,r,o,i).some((m)=>m.target.includes(Sl))}function Qw(e){let t=Mt(e);if(t.length===0)return null;let n=lt(t[0]??"").toLowerCase();if(!Dr(n))return null;return e_(n,t.slice(1))?n:null}function e_(e,t){let n=Pl(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(wp.has(o)||Tp(e,o)||/^--(?:eval|exec)=/.test(o))return!1;if(o==="-")return!0;if(o.startsWith("-")){if(n==="python"&&o==="-m")return!1;if($w.get(n)?.has(o))r++;continue}return!1}return!0}function Pl(e){return/^python\d/.test(e)?"python":e}function t_(e){let t=[];for(let n of e){if(Ip(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 yp=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function n_(e,t){if(!t||!yp.test(e))return e;return`~${e.replace(yp,"").replace(/\\/g,"/")}`}function ht(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 r_(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)=>ht("jq",i))}return e.flatMap((r,o)=>o===t?[]:ht("jq",r))}function o_(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n]??"";if(r==="--"||!r.startsWith("-"))return[...t,...kw.has(r)?xl("git",e.slice(n).map((i)=>/^-[aeinopqsv]+m$/.test(i)?"-m":i),Iw):xl("git",e.slice(n),Ow)];if(t.push(...ht("git",r)),!De.has(r))continue;let o=e[n+1];if(o===void 0)break;t.push(...r==="-c"&&o.includes("=")?[o.slice(o.indexOf("=")+1)]:ht("git",o)),n++}return t}function xl(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)=>ht(e,s))];if(n.has(i)){o++;continue}if(i.includes("=")&&n.has(i.slice(0,i.indexOf("="))))continue;r.push(...ht(e,i))}return r}function i_(e){return e.flatMap((t,n)=>{let r=a_(t);if(r!==null)return Cp(r.flag,r.value);let o=s_(e[n-1]);return o===null?[]:Cp(o,t)})}function Cp(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 vl(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 vl(t.slice(n+1))}return t.startsWith("@")?vl(t.slice(1)):[]}function s_(e){if(e===void 0)return null;if(Rp.has(e))return e;return/^-[A-Za-z]+[dF]$/.test(e)?`-${e.slice(-1)}`:null}function a_(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 Rp.has(r)?{flag:r,value:e.slice(n+1)}:null}function vl(e){return e===""||e==="-"?[]:[e]}function l_(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(!vw.has(e[l]??""))continue;let c=e.slice(l+1),u=c.findIndex((f)=>Ew.has(f)),m=u===-1?c:c.slice(0,u),d=Ui(m,t,n,r,o,i).map((f)=>f.target);if(a.push(...d.filter((f)=>f!=="{}")),!d.includes("{}"))continue;a.push(...e.slice(0,l).flatMap((f,p,g)=>{if(!Rw.has(f))return[];let h=g[p+1];return h===void 0?[]:[h,h.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return a}function c_(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(wp.has(c)||Tp(e,c)){let m=t[l+1];if(m!==void 0)a.push(...$i(e,m,n,r,o,i,s)),l++;continue}let u=/^--(?:eval|exec)=(.*)$/.exec(c);if(u!==null&&u[1]!==void 0){a.push(...$i(e,u[1],n,r,o,i,s));continue}if(!c.startsWith("-"))a.push({target:c,cwd:i})}return a}function Tp(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<=2)return!1;return Aw.get(t[t.length-1]??"")?.has(Pl(e))??!1}function u_(e,t,n,r,o,i){if(!e.includes("system"))return[];return Na(e)?.commands.flatMap((s)=>Jn(t.getShellSyntax(s),t,n,r,o,i))??[]}function d_(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 m_(e){let t=Array.from(e.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((n)=>n[2]).filter((n)=>n!==void 0&&n!=="");return[...t,...t.flatMap(Tl),...e.match(El)??[]]}function $i(e,t,n,r,o,i,s){let a=(g)=>({target:g,cwd:i}),l=p_(t,f_(e));if(l.kind==="unmaskable")return m_(t).map(a);let c=l.masked.match(fp)!==null||l.literals.some((g)=>pp.test(l.masked.slice(0,g.start))),u=l.masked.match(Hw)!==null||l.literals.some((g)=>Bw.test(l.masked.slice(0,g.start))),m=r.inlineLiteralsPresumedData===!0&&!Or.has(e),d=m&&!(C_(l.masked)||c||u)?[]:l.literals,f=m?Array.from(l.masked.matchAll(fp),(g)=>{let h=g.index+g[0].length;return{start:h,end:ga(l.masked,h)}}):[],p=!m||f.some((g)=>ha(l.masked,g.start))?l.literals:l.literals.filter((g)=>pp.test(l.masked.slice(0,g.start))||f.some((h)=>g.start>=h.start&&g.start<h.end));return[...d.map((g)=>g.text).filter((g)=>g!=="").map(a),...d.flatMap((g)=>Tl(g.text)).map(a),...m?[]:l.literals.flatMap((g)=>g.text.match(El)??[]).map(a),...c?p.flatMap((g)=>_l(g.text,n,r,o,i,s)??[a(g.text)]):[],...u?l.literals.flatMap((g)=>$i(e,g.text.replace(/\\(.)/g,(h,y)=>y==="n"?`
|
|
44
|
+
`:y),n,r,o,i,s)):[],...(l.masked.match(El)??[]).map(a)]}function f_(e){let t=Pl(e);if(t==="python")return"python";if(t==="osascript")return"opaque";return t==="node"||t==="bun"||t==="deno"?"javascript":"simple"}function p_(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(Fw.test(e.slice(o)))return{kind:"unmaskable"}}let s=i==="'"||i==='"'||t==="javascript"&&i==="`"?i:null;if(s===null)continue;if(s==="`"&&y_(e,o))return{kind:"unmaskable"};let a=t==="python"?g_(e,o):"",l=t==="python"&&e.startsWith(s.repeat(3),o)?s.repeat(3):s,c=o+l.length,u=h_(e,c,l);if(u===null)return{kind:"unmaskable"};let m=e.slice(c,u);if(/[fF]/.test(a)&&m.includes("{"))return{kind:"unmaskable"};if(t==="simple"&&s==='"'&&zw.test(m))return{kind:"unmaskable"};r.push({start:c,text:m});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 g_(e,t){return Gw.exec(e.slice(Math.max(0,t-3),t))?.[1]??""}function h_(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===`
|
|
45
|
+
`||s==="\r"))return null;if(e.startsWith(n,i))return i}return null}function y_(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 C_(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(ww.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)=>_w.has(i)))continue;if(o.length>1)return!0;if(b_(e,r)===".")return!0;if(S_(e,r+n.length)==="(")return!0}return!1}function b_(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function S_(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function v_(e,t,n,r,o,i){return __(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...Jn(a,t,{...n,displayOperandsAreCapturedOutput:!0},r,o,i),...E_(a,r)?x_(a,r).map((l)=>({target:l,cwd:o})):[]]})}function E_(e,t){let n=li(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||lt(_t(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=_t(s.text,t);if(a==="--decode"||!a.startsWith("--")&&a.startsWith("-")&&/[dD]/.test(a))return!0}}return!1}function x_(e,t){return li(e).flatMap((n)=>n.kind==="word"?[_t(n.text,t)]:n.kind==="redirection"&&n.target?[_t(n.target,t)]:[]).flatMap(Tl)}function Tl(e){let t=w_(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||R_(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function R_(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function w_(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 __(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(mr(o,n))continue;if(kp(e,r,n)){let i=A_(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=P_(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function A_(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(mr(i,n))continue;if(kp(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 P_(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 kp(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function T_(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 m=u[1]??"",d=u[2];if(m===Mw)o=!0;if(Nw.has(m))r=!0;if(d!==void 0){if(m===mp)t.push(d);continue}if(Ww.has(m)){let f=e[l+1];if(m===mp&&f!==void 0)t.push(f);l++}continue}if(c.startsWith("-")&&c.length>1){let m=c.slice(1),d="",f="";for(let g=0;g<m.length;g++){let h=m[g]??"";if(Dw.has(h))r=!0;if(Lw.has(h)){d=h,f=m.slice(g+1);break}}if(d==="")continue;if(f.length>0){if(d===dp)t.push(f);continue}let p=e[l+1];if(d===dp&&p!==void 0)t.push(p);l++;continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function Mt(e){let t=e.findIndex((n)=>!Ip(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:e.slice(t)}function Ip(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var k_=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),I_=".env.",O_=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),M_=[".env.example.",".env.sample."];function D_(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function N_(e){return e.length>0&&!/\s/.test(e)}function Rl(e,t,n,r){let o=Op(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function Op(e,t,n,r){try{return eo(e,t,n,r)}catch(o){if(o instanceof N)throw o;return""}}var L_=new Set(["node_modules","__pycache__"]),W_=[["vendor","bundle"],["vendor","cache"]];function G_(e,t,n,r,o){if(D_(e))return null;let i=gt(e,t,r,o);if(!i)return null;let s=U(i.split("/").pop()??""),a=U(i),l=()=>N_(s)||Rl(e,t,r,o);if(O_.has(s)||M_.some((d)=>s.startsWith(d)))return null;let c=U(U_(e,t,r,o));for(let d of Is){let f=`~/${d.suffixParts.join("/")}`;if((Sp(a,f)||Sp(c,f))&&Ot(d.id,n))return d.id}let u=F_(i,t,n,r,o);if(u)return u;if(k_.has(s))return null;for(let d of ks)if(s===d.basename&&Ot(d.id,n))return d.id;if(s.startsWith(I_)&&Ot(_o.id,n)&&l())return _o.id;for(let d of Os)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){let f=s.slice(d.prefix.length)[0];if((f==="-"||f==="_")&&Ot(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&&Ot(d.id,n))return d.id}if(B_(a))return null;if(!s.includes(".")&&pr.pattern.test(s)&&Ot(pr.id,n))return pr.id;let m=$_(s,n);if(m)return m;return null}function F_(e,t,n,r,o){return Ao.find((i)=>{if(!Ot(i.id,n))return!1;switch(i.id){case"secret.cli.claude-code":return z(e,Y(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),[".credentials.json"]);case"secret.cli.claude-code.config":{let s=U(e).split("/");return z(e,Y(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),["settings.json","settings.local.json"])||Qr(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 z(e,gt("~/.gemini/config",t,r,o),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let s=Y(r.env.get("CODEX_HOME"),"~/.codex",t,r,o);return z(e,s,["auth.json",".credentials.json"])||Jr(e,s,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let s=Y(r.env.get("CODEX_HOME"),"~/.codex",t,r,o),a=U(e).split("/").at(-1)??"";return z(e,s,["config.toml"])||a.endsWith(".config.toml")&&z(e,s,[a])}case"secret.cli.gemini":return z(e,Ce(Y(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=U(e).split("/"),a=r.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),l=r.env.get("ProgramData")?[Ce(Y(r.env.get("ProgramData"),"",t,r,o),"gemini-cli")]:[];return z(e,Ce(Y(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()?Qr(e,a,t,r,o):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...l].some((c)=>z(e,gt(c,t,r,o),["settings.json"]))}case"secret.cli.copilot-cli":{let s=Y(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o);return z(e,s,["config.json"])||Jr(e,s,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return z(e,Y(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o),["mcp-config.json"]);case"secret.cli.kimi-code":{let s=Y(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),a=Y(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o);return z(e,s,["server.token"])||Jr(e,s,["credentials"])||Jr(e,a,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let s=["config.toml","mcp.json"],a=U(e).split("/");return a.at(-1)==="mcp.json"&&a.at(-2)===".kimi-code"||z(e,Y(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),s)||z(e,Y(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o),[...s,"config.json","config.json.bak"])}case"secret.cli.opencode":{let s=Ce(Y(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"opencode"),a=U(e).split("/").at(-1)??"",l=r.env.get("OPENCODE_DB")?.trim(),c=l&&l!==":memory:"?[l,`${l}-wal`,`${l}-shm`]:[];return z(e,s,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(a)&&z(e,s,[a])||c.some((u)=>Qr(e,u,t,r,o))}case"secret.cli.opencode.config":{let s=Ce(Y(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"opencode"),a=r.env.get("ProgramData")?[Ce(Y(r.env.get("ProgramData"),"",t,r,o),"opencode")]:[],l=["opencode.json","opencode.jsonc"],c=r.env.get("OPENCODE_CONFIG");return l.includes(U(e).split("/").at(-1)??"")||z(e,s,["config.json"])||(c?.trim()?Qr(e,c,t,r,o):!1)||["/Library/Application Support/opencode","/etc/opencode",...a].some((u)=>z(e,gt(u,t,r,o),l))}case"secret.cli.pi":return z(e,Y(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["auth.json"]);case"secret.cli.pi.config":return z(e,Y(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["models.json"]);case"secret.cli.amp":{let s=gt("~",t,r,o);return[Ce(Y(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"amp"),Ce(s,".local","share","amp")].some((l)=>z(e,l,["secrets.json"]))||Jr(e,Ce(s,".amp"),["oauth"])}case"secret.cli.amp.config":{let s=["settings.json","settings.jsonc"],a=[Ce(Y(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"amp"),Ce(gt("~",t,r,o),".config","amp")],l=U(e).split("/"),c=r.env.get("AMP_SETTINGS_FILE");return a.some((u)=>z(e,u,s))||l.at(-2)===".amp"&&s.includes(l.at(-1)??"")||(c?.trim()?Qr(e,c,t,r,o):!1)}case"secret.cli.cursor":{let s=Ce(Y(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"cursor"),a=Ce(Y(r.env.get("CURSOR_DATA_DIR"),"~/.cursor",t,r,o),"projects");return z(e,gt("~/.cursor",t,r,o),["auth.json"])||z(e,s,["auth.json"])||U(e).split("/").at(-1)==="mcp-auth.json"&&Cn(U(e),U(a))}case"secret.cli.cursor.config":{let s=U(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".cursor"}case"secret.cli.grok-build":return z(e,Y(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let s=U(e).split("/");return s.at(-1)==="config.toml"&&s.at(-2)===".grok"||z(e,Y(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["config.toml","managed_config.toml","requirements.toml"])||z(e,gt("/etc/grok",t,r,o),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var bp=new WeakMap;function Y(e,t,n,r,o){let i=bp.get(o)??new Map;bp.set(o,i);let s=`${n}\x00${e??""}\x00${t}`,a=i.get(s);if(a!==void 0)return a;let l=gt(e?.trim()?e:t,n,r,o);return i.set(s,l),l}function z(e,t,n){return n.some((r)=>Mp(e,Ce(t,r)))}function Jr(e,t,n){return n.some((r)=>Cn(U(e),U(Ce(t,r))))}function Qr(e,t,n,r,o){return Mp(e,gt(t,n,r,o))}function Mp(e,t){return U(e)===U(t)}function Ce(e,...t){return at([e,...t].filter(Boolean).join("/"))}function z_(e,t,n,r,o,i){if(n.length===0)return!1;let s=U(eo(e,t,o,i));return n.some((a)=>Cn(s,U(eo(a,r,o,i))))}function H_(e,t,n,r,o,i){if(n.length===0)return!1;let s=U(eo(e,t,o,i));if(!s)return!1;let a=o.env.get("HOME")??o.home,l=a?at(O(Me(a),o.paths,i)):"",c=U(l),u=o.env.get("CC_SAFETY_NET_HOME"),m=U(u?at(O(Ee.resolve(Me(u)),o.paths,i)):l&&at(O(`${l}/.cc-safety-net`,o.paths,i)));if(m&&Cn(s,m))return!1;return n.some((d)=>{let f=Ws(d);if(f&&Ee.posix.basename(s)!==U(f.name))return!1;let p=U(eo(f?.root??d,r,o,i));if(!p)return!1;if(c&&(c===p||c.startsWith(p.endsWith("/")?p:`${p}/`)))return!1;return Cn(s,p)&&!(f&&s===p)})}function B_(e){let t=e.split("/");return t.some((n)=>L_.has(n))||W_.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function $_(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 Ds)if(r===o.extension&&Ot(o.id,t))return o.id;for(let o of Ns)if(o.pattern.test(r)&&Ot(o.id,t))return o.id;return null}function U(e){return e.toLowerCase()}function Ot(e,t){return!t?.disabledRules?.includes(e)}function gt(e,t,n,r){let{home:o,normalized:i}=kl(e,n,r);if(!i)return"";if(!o)return i;let s=Il(i,o),a=Ee.isAbsolute(s)?s:at(Ee.resolve(t,s)),l=at(O(a,n.paths,r));if(!Cn(l,o)){if(Ee.isAbsolute(s))return l;return l===a?i:l}let c=l.slice(o.length);return c?`~${c}`:"~"}function Sp(e,t){return e===t||e.startsWith(`${t}/`)}function U_(e,t,n,r){let{home:o,normalized:i}=kl(e,n,r);if(!i||!o)return"";let s=Il(i,o),a=Ee.posix.normalize(Ee.isAbsolute(s)?s:at(Ee.resolve(t,s))),l=at(Me(n.env.get("HOME")??n.home)),c=(d)=>process.platform==="win32"?d.toLowerCase():d,u=[o,l].find((d)=>d!==""&&Cn(c(a),c(d)));if(u===void 0)return"";let m=a.slice(u.length);return m?`~${m}`:"~"}function eo(e,t,n,r){let{home:o,normalized:i}=kl(e,n,r);if(!i)return"";let s=o?Il(i,o):i;return at(O(Ee.isAbsolute(s)?s:Ee.resolve(t,s),n.paths,r))}function kl(e,t,n){let r=t.env.get("HOME")??t.home,o=r?at(O(Me(r),t.paths,n)):"",i=at(Me(j_(_t(e,t))));return{home:o,normalized:i}}function j_(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return vp.fileURLToPath(e)}catch{return e}}function Il(e,t){if(e==="~")return t;if(e.startsWith("~/"))return Ce(t,e.slice(2));return e}function V_(e){if(process.platform==="win32")return!0;return Ee.win32.parse(e).root.length>1}function at(e){let t=e.trim(),n=(t.includes("\\")&&V_(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function Cn(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function lt(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class bn 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 K_={findPolicyMutation:lp,findGitMetadataMutation:Ld,resolveGitMetadata:Y_,loadPolicySnapshot:Pu,findSensitiveTarget:_p,analyzeCommand:Qf,getModes:ms},q_=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function Dp(e,t){let n={...K_,...t.dependencies},r=J_(e),o=to(e)?e.command:r,i=Xt("policy-protection",o,()=>Nr(e)),s=Pe(i,"input-candidate"),a=Pe(i,"declared-command");if(to(e)&&e.command?.trim()&&a?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:ut,intent:"stop_and_explain",evidence:{command:e.command,segment:e.command}}};if(s?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:Jd,intent:"stop_and_explain"}};let l=ue(),c=Xt("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd],t.environment)),u=Xt("policy-protection",o,()=>n.findPolicyMutation(i,t.environment,l));if(u){let E=o??u.target;return{stage:"policy-protection",decision:{kind:"deny",reason:ap,intent:"hard_stop",evidence:{command:E,segment:u.target}}}}let m=Xt("policy-protection",o,()=>rp(i,t.environment,l));if(m){let E=o??m.target;return{stage:"policy-protection",decision:{kind:"deny",reason:np,intent:"hard_stop",evidence:{command:E,segment:m.target}}}}let d=Xt("policy-protection",o,()=>n.findGitMetadataMutation(i,c,t.environment,l));if(d){let E=o??d.target;return{stage:"policy-protection",decision:{kind:"deny",reason:je,intent:"hard_stop",evidence:{command:E,segment:d.target}}}}let f=Xt("config-load",o,()=>n.loadPolicySnapshot(t.environment,{...t.policyOptions,cwd:e.context.configCwd})),p=f.policy,g=n.getModes(p,t.environment.env),h={level:g.effectiveLevel,...Z_(f)},y=p.secretProtection.enabled===!1?null:Xt("secret-protection",o,()=>n.findSensitiveTarget(i,p.secretProtection,t.environment,l,{strict:to(e)||s?.program.dialect==="powershell"?g.strict:void 0}));if(y){let E=o??y.target;return{stage:"secret-protection",...h,decision:{kind:"deny",reason:Ep,intent:"hard_stop",ruleId:y.ruleId,evidence:{command:E,segment:y.target}}}}if(!to(e))return{stage:"non-command",...h,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...Ol("command-validation",o),...h};let S=Xt("command-analysis",o,()=>ep(()=>n.analyzeCommand(e.command,{cwd:e.context.executionCwd,shell:e.route.shell,policySnapshot:f,environment:t.environment,protectedGitMetadata:c,effectiveCapabilities:g.capabilities,strict:g.strict,paranoidRm:g.paranoidRm,paranoidInterpreters:g.paranoidInterpreters,worktreeMode:g.worktreeMode,budget:l,...t.trace?{trace:t.trace}:{}},X_(i),i.store),e.command,t.trace));if(S.decision){let E=!g.strict&&(S.decision.ruleId==="raw-text.dangerous-command"||S.decision.reason===Fr&&!q_.test(S.decision.evidence?.segment??"")&&$e(e.command)===null);return{stage:"command-analysis",...h,..."errorCode"in S?{errorCode:S.errorCode}:{},decision:E?{...S.decision,unverifiedByStandardMode:!0}:S.decision}}return{stage:"command-analysis",...h,decision:{kind:"allow"}}}function Y_(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 Z_(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function X_(e){return Pe(e,"declared-command")?.program}function J_(e){try{return Nt(e.input)}catch(t){let n=to(e)?e.command:void 0;throw new bn("policy-protection",Ol("policy-protection",t instanceof be?void 0:n,t),t)}}function Xt(e,t,n){try{return n()}catch(r){throw new bn(e,Ol(e,r instanceof be?void 0:t,r),r)}}function Ol(e,t,n){let r=n instanceof N||n instanceof nt;return{stage:e,decision:{kind:"deny",reason:r?Ji:or,intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function to(e){return e.route.kind==="command"}var Vi=require("node:fs"),er=require("node:path");var le=require("node:fs"),Qn=require("node:path");function Np(e,t={}){return Lo(An(e,t),e.home).policy.audit.retention_days}var Dl=86400000,Q_=".last-prune",eA=/^\d{4}-\d{2}$/,tA=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Lp=(e)=>Math.floor(e/Dl);function Gp(e,t,n=()=>new Date){try{let r=n().getTime();if(!le.statSync(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=Qn.join(t,Q_),i=le.statSync(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&Lp(i)===Lp(r))return;let s=r-Np(e)*Dl,a=new Date(r).toISOString().slice(0,7);for(let l of Ml(t)){if(l.isDirectory()){nA(Qn.join(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))rA(Qn.join(t,l.name),s)}le.writeFileSync(o,"",{mode:384}),le.utimesSync(o,r/1000,r/1000)}catch{}}function nA(e,t,n){for(let r of Ml(e)){if(!r.isDirectory()||!eA.test(r.name))continue;let o=Qn.join(e,r.name);for(let i of Ml(o)){if(!i.isFile())continue;let s=tA.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+Dl;if(!Number.isFinite(a)||a>=t)continue;Fp(Qn.join(o,i.name))}if(r.name!==n)Wp(o)}Wp(e)}function rA(e,t){try{let n=le.lstatSync(e);if(n.mtimeMs>=t)return;let r=le.readFileSync(e,"utf-8").split(`
|
|
46
|
+
`).filter((o)=>o.trim()).map(oA);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(le.lstatSync(e).mtimeMs!==n.mtimeMs)return;Fp(e)}catch{}}function oA(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 Ml(e){try{return le.readdirSync(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Fp(e){try{le.unlinkSync(e)}catch{}}function Wp(e){try{le.rmdirSync(e)}catch{}}var iA="2.4.13",sA=1e4,aA=2000,lA=256,cA=32768;function uA(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 dA(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function Nl(e,t,n,r,o,i,s={}){let a=uA(t);if(!a)return;let l=fA(e);if(!l)return;try{let c=(s.now??(()=>new Date))().toISOString(),u=ji(Ct(n),s.failureStage?Number.POSITIVE_INFINITY:sA),m=ji(Ct(r),aA),d=s.toolName?ji(Ct(s.toolName),lA):void 0,f=i===null?void 0:ji(Ct(i),cA),p=er.join(l,dA(f?.value??null),c.slice(0,7));Vi.mkdirSync(p,{recursive:!0,mode:448});let g=er.join(p,`${c.slice(0,10)}-${a}.jsonl`),h={ts:c,id:(s.createId??ps)(),v:iA,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:m.value,...u.truncated||m.truncated||d?.truncated||f?.truncated?{truncated:!0}:{},reason:o,ruleId:s.ruleId,intent:s.intent,failureStage:s.failureStage,errorCode:s.errorCode,cwd:f?.value??null};Vi.appendFileSync(g,`${JSON.stringify(h)}
|
|
47
|
+
`,{encoding:"utf-8",mode:384}),Gp(e,l,s.now)}catch{}}function ji(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function mA(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&&er.isAbsolute(n)?n:null}function fA(e){let t=mA(e);return t?er.join(t,".cc-safety-net","logs"):null}function Hp(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=zp(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?zp(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 zp(e){return"command"in e?e.command??"":""}function Bp(e,t,n,r){if(!t)return;let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Nl(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 $p(e,t,n,r){let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Nl(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 jp(e,t,n){try{let r=Dp(t,{environment:e,...n.guard});return Up(e,t,r,n),r}catch(r){if(!(r instanceof bn))throw r;throw Up(e,t,r.evaluation,n,!(r.cause instanceof be),{stage:r.stage,errorCode:pA(r.cause)}),r}}function Up(e,t,n,r,o=!0,i){Bp(e,Hp(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 N)return X[e.kind].errorCode;if(e instanceof be)return"tool-input-limit";if(e instanceof nt)return"structural-shell-syntax-limit";return"unexpected-error"}var Sn=(e,t,n,r,o)=>uc(e.cwd,t,n,r,o.paths,process.cwd()),Ki=(e,t,n)=>(r,o,i,s,a)=>{let l=Sn(r,o,i,s,a);if(!l)return null;let c=r.tool_input;if(!t.has(i)||!c||!Object.hasOwn(c,e))return l;let u=c[e];if(n?.emptyMeansSessionCwd&&u==="")return l;if(typeof u!=="string"||u.trim()==="")return Se(s,o,i),null;let m=n?.allowOutsideSessionCwd?as(u,l.configCwd,a.paths):St(u,[l.configCwd],a.paths);if(m)return{configCwd:l.configCwd,executionCwd:m};return He(s,o,i,{directory:"requested",problem:Et(u,l.configCwd,a.paths),cwd:u}),null};function gA(e,t){console.log(JSON.stringify(e(Hl(t))))}async function hA(e){let t;try{t=(await cc(process.stdin)).trim()}catch{e({reason:"Failed to parse hook input JSON."});return}if(!t){e({reason:"Missing hook input JSON."});return}return fo(t,e,"Failed to parse hook input JSON.")}async function yA(e){let t=vc(),n=await hA(e.outputDeny);if(n===void 0)return;if(!n||typeof n!=="object"||Array.isArray(n)){Se(e.outputDeny);return}if(!e.isSupported(n))return;let r=e.getAgent?.(n,t)??e.agent,o=e.agent===r?void 0:e.agent,i=vA(n),s=(p,g)=>{$p(t,p,()=>e.getSessionId(n),{agent:r,shape:o,toolName:g,cwd:p.cwd??i}),e.outputDeny(p)},a=e.getToolName(n);if(typeof a!=="string"||a.trim()===""){Se((p)=>s(p),SA(n));return}let l=a,c=(p)=>s(p,l),u;try{u=e.getToolInput(n,l,c,t)}catch(p){if(!(p instanceof be))throw p;Se(c,void 0,l);return}if(!u.ok)return;let m=e.getContext(n,u.input,l,c,t);if(!m)return;let d;try{d=Nt(u.input)}catch(p){if(!(p instanceof be))throw p;Se(c,void 0,l);return}let f=cr(l,u.input,u.route,m,d??null);try{let p=jp(t,f,{guard:{auditAllowed:Ec(t.env),dependencies:e.guardDependencies},audit:{agent:r,shape:o,getSessionId:()=>e.getSessionId(n)}}),g=Qi(p,{includeEvidence:!0,toolName:p.stage==="command-analysis"?void 0:l});if(g){if(g.unverifiedByStandardMode&&e.outputAsk&&e.canPromptPerson?.(n)){e.outputAsk(g);return}e.outputDeny(g);return}e.outputAllow?.()}catch(p){if(!(p instanceof bn))throw p;CA(p,t.env);let g=Qi(p.evaluation,{includeEvidence:!0,toolName:p.evaluation.stage==="command-analysis"?void 0:l});if(g)e.outputDeny(g);return}}function CA(e,t){if(!en(ae.debug,t))return;console.error(`CC Safety Net debug: ${bA(e.stage)}: ${$l(e.cause)}`)}function bA(e){if(e==="policy-protection")return"hook policy protection failed";if(e==="config-load")return"hook config loading failed";if(e==="secret-protection")return"hook secret protection failed";return"hook analysis failed"}function SA(e){if(!e||typeof e!=="object"||Array.isArray(e))return;if(Object.hasOwn(e,"tool_input"))return e.tool_input;let t=e.toolCall;if(t&&typeof t==="object"&&!Array.isArray(t))return t.args;return}function vA(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let t=e.cwd;if(typeof t==="string")return t;let n=e.toolCall;if(!n||typeof n!=="object"||Array.isArray(n))return null;let r=n.args;if(!r||typeof r!=="object"||Array.isArray(r))return null;let o=r.Cwd;return typeof o==="string"?o:null}async function Ie(e){let t=(s)=>gA(e.createDenyOutput,s),n=e.createAskOutput,r=n?(s)=>console.log(JSON.stringify(n(Bl(s)))):void 0,o=e.createAllowOutput,i=o?()=>console.log(JSON.stringify(o())):void 0;try{await yA({...e,outputDeny:t,outputAsk:r,outputAllow:i})}catch(s){console.error("CC Safety Net error:",s),t(xn())}}var EA=new Map([["run_command","auto"]]),xA=new Set(["absolutepath","directorypath","file_path","filepath","path","searchdirectory","searchpath","target_file","targetfile"]);function Vp(e){return oe(e,EA)}async function Kp(){await Ie({agent:"antigravity-cli",createDenyOutput:(e)=>({decision:"deny",reason:e}),isSupported:()=>!0,getToolName:(e)=>e.toolCall?.name,getToolInput:(e,t)=>({ok:!0,input:AA(e.toolCall?.args,t),route:Vp(t)}),getContext:RA,getSessionId:(e)=>e.conversationId})}function RA(e,t,n,r,o){let i=_A(e);if(!i[0])return Jt(r,t,n),null;let s=i.flatMap((u)=>{let m=vt([u],o.paths);return m?[m]:[]});if(!s[0])return Jt(r,t,n,{directory:"session",problem:"unusable",cwd:i[0]}),null;if(n!=="run_command"){let u;try{u=wA(t,n,s,o.paths)}catch(m){if(m instanceof be)return Jt(r,void 0,n),null;if(!(m instanceof N))throw m;return Jt(r,t,n),null}if(!u)return Jt(r,t,n),null;return{configCwd:u,executionCwd:u}}let a=e.toolCall?.args;if(!a||!Object.hasOwn(a,"Cwd"))return{configCwd:s[0],executionCwd:s[0]};let l=a.Cwd;if(typeof l!=="string"||l.trim()==="")return Jt(r,t,n),null;let c=St(l,s,o.paths);if(c){let u=qp(c,s);if(!u)return Jt(r,t,n),null;return{configCwd:u,executionCwd:c}}return Jt(r,t,n,{directory:"requested",problem:Et(l,s[0],o.paths),cwd:l}),null}function wA(e,t,n,r){let o=Vp(t),i=[...co(e,xA),...o.kind==="patch"?uo(e):[]].filter(Ll.isAbsolute),s=ue(),a=new Set(i.flatMap((l)=>{let c=qp(O(l,r,s),n);return c?[c]:[]}));if(a.size>1)return null;return[...a][0]??n[0]??null}function qp(e,t){return t.filter((n)=>ar(e,n)).reduce((n,r)=>r.length>n.length?r:n,"")||null}function Jt(e,t,n,r){let o=t&&typeof t==="object"?t.command:void 0,i={command:typeof o==="string"?o:void 0,toolName:n};e(r?io(r,i):xn(i))}function _A(e){if(e.workspacePaths===void 0)return[process.cwd()];return Array.isArray(e.workspacePaths)?e.workspacePaths.filter((t)=>typeof t==="string"&&t.trim()!==""):[]}function AA(e,t){if(!e)return;if(t!=="run_command")return e;return{...e,command:typeof e.CommandLine==="string"&&e.CommandLine!==""?e.CommandLine:void 0}}var qi=[{id:"antigravity-cli",displayName:"Antigravity CLI",doctorOrder:3,runtime:{order:1,flags:["-ac","--agy-cli"],description:"Run as Antigravity CLI PreToolUse hook",legacyTopLevelFlags:[]},install:{order:2,flag:"--agy-cli",artifactKind:"hook config",probeCommand:["agy","--version"]}},{id:"claude-code",displayName:"Claude Code",doctorOrder:1,runtime:{order:2,displayName:"Coding CLI",flags:["-cc","--coding-cli"],legacyFlags:["--claude-code"],description:"Run as Coding CLI PreToolUse hook",legacyTopLevelFlags:["-cc","--claude-code"]},install:{order:3,flag:"--claude-code",artifactKind:"plugin",probeCommand:["claude","--version"]}},{id:"codex",displayName:"Codex",doctorOrder:4,runtime:{order:3,flags:["-cx","--codex"],description:"Run as a Codex PreToolUse hook",legacyTopLevelFlags:[]},install:{order:4,flag:"--codex",artifactKind:"plugin",probeCommand:["codex","--version"]}},{id:"copilot-cli",displayName:"GitHub Copilot CLI",doctorOrder:7,runtime:{order:6,flags:["-cp","--copilot-cli"],description:"Run as GitHub Copilot CLI PreToolUse hook",legacyTopLevelFlags:["-cp","--copilot-cli"]},install:{order:7,flag:"--copilot-cli",artifactKind:"plugin",probeCommand:["copilot","--binary-version"]}},{id:"gemini-cli",displayName:"Gemini CLI",doctorOrder:6,runtime:{order:5,flags:["-gc","--gemini-cli"],description:"Run as Gemini CLI BeforeTool hook",legacyTopLevelFlags:["-gc","--gemini-cli"]},install:{order:6,flag:"--gemini-cli",artifactKind:"extension",probeCommand:["gemini","--version"]}},{id:"grok-build",displayName:"Grok Build",doctorOrder:8,runtime:{order:7,flags:["-gb","--grok-build"],description:"Run as Grok Build PreToolUse hook",legacyTopLevelFlags:[]},install:{order:8,flag:"--grok-build",artifactKind:"hook config",probeCommand:["grok","--version"]}},{id:"hermes-agent",displayName:"Hermes Agent",doctorOrder:9,runtime:{order:8,flags:["-ha","--hermes-agent"],description:"Run as Hermes Agent pre_tool_call hook",legacyTopLevelFlags:[]},install:{order:9,flag:"--hermes-agent",artifactKind:"plugin",probeCommand:["hermes","--version"]}},{id:"kimi-code",displayName:"Kimi Code",doctorOrder:10,runtime:{order:9,flags:["-kc","--kimi-code"],description:"Run as Kimi Code PreToolUse hook",legacyTopLevelFlags:[]},install:{order:10,flag:"--kimi-code",artifactKind:"hook config",probeCommand:["kimi","--version"]}},{id:"openclaw",displayName:"OpenClaw",doctorOrder:11,install:{order:11,flag:"--openclaw",artifactKind:"plugin",probeCommand:["openclaw","--version"]}},{id:"opencode",displayName:"OpenCode",doctorOrder:12,install:{order:12,flag:"--opencode",artifactKind:"plugin",probeCommand:["opencode","--version"]}},{id:"pi",displayName:"Pi",doctorOrder:13,install:{order:13,flag:"--pi",artifactKind:"package",probeCommand:["pi","--version"]}},{id:"cursor",displayName:"Cursor",doctorOrder:5,runtime:{order:4,flags:["-cu","--cursor"],description:"Run as Cursor preToolUse hook",legacyTopLevelFlags:[]},install:{order:5,flag:"--cursor",artifactKind:"hook config",probeCommand:["cursor","--version"]}},{id:"amp",displayName:"Amp Code",doctorOrder:2,install:{order:1,flag:"--amp",artifactKind:"plugin",probeCommand:["amp","--version"]}}],AL=qi.slice().sort((e,t)=>e.doctorOrder-t.doctorOrder).map((e)=>e.id),Yp=qi.filter((e)=>("runtime"in e)).slice().sort((e,t)=>e.runtime.order-t.runtime.order).map((e)=>({id:e.id,displayName:"displayName"in e.runtime?e.runtime.displayName:e.displayName,flags:e.runtime.flags,legacyFlags:"legacyFlags"in e.runtime?e.runtime.legacyFlags:[],description:e.runtime.description,legacyTopLevelFlags:e.runtime.legacyTopLevelFlags})),PL=qi.slice().sort((e,t)=>e.install.order-t.install.order).map((e)=>({id:e.id,...e.install})).map(({order:e,...t})=>t),TL=Object.fromEntries(qi.map((e)=>[e.id,e.displayName]));var vn=require("node:path");function Zp(e,t){if(e!==void 0&&e!==null&&typeof e!=="string")return"unknown";if(typeof e==="string"&&!vn.isAbsolute(e))return"unknown";try{let n=ue(),r=typeof e==="string"&&e?O(e,t.paths,n):void 0,o=t.home,i=[["codex",t.env.get("CODEX_HOME")||vn.join(o,".codex")],["copilot-cli",t.env.get("COPILOT_HOME")||vn.join(o,".copilot")],["claude-code",t.env.get("CLAUDE_CONFIG_DIR")||vn.join(o,".claude")]],s=r?i.flatMap(([a,l])=>{if(!vn.isAbsolute(l))return[];return ar(r,O(l,t.paths,n))?[a]:[]}):[];if(s.length===1)return s[0]??"unknown";if(s.length>1)return"unknown"}catch{return"unknown"}if(t.env.get("COPILOT_CLI")==="1")return"copilot-cli";if(t.env.get("CLAUDECODE")==="1"||Boolean(t.env.get("CLAUDE_CODE_ENTRYPOINT")))return"claude-code";return"unknown"}var Yi="PreToolUse",Xp="BeforeTool",Jp="pre_tool_call";async function tr(e){await Ie({agent:e.agent,...e.getAgent?{getAgent:e.getAgent}:{},createDenyOutput:(t)=>({hookSpecificOutput:{hookEventName:Yi,permissionDecision:"deny",permissionDecisionReason:t}}),...e.canPromptPerson?{canPromptPerson:e.canPromptPerson,createAskOutput:(t)=>({hookSpecificOutput:{hookEventName:Yi,permissionDecision:"ask",permissionDecisionReason:t}})}:{},isSupported:(t)=>t.hook_event_name===Yi,getToolName:(t)=>t.tool_name,getToolInput:(t,n,r,o)=>({ok:!0,input:t.tool_input,route:e.getToolRoute(n,t.tool_input,o)}),getContext:e.getContext??Sn,getSessionId:(t)=>t.session_id})}var PA=new Map([["Bash","posix"],["PowerShell","powershell"],["Monitor","posix"]]);function TA(e,t,n){if(e==="Bash"&&n.env.get("COPILOT_CLI")==="1")return{kind:"command",shell:"auto"};return e==="Monitor"&&t?.command===void 0?oe(e,new Map):oe(e,PA)}async function Qp(){await tr({agent:"claude-code",getAgent:(e,t)=>Zp(e.transcript_path,t),canPromptPerson:(e)=>["default","acceptEdits","plan"].includes(e.permission_mode??""),getToolRoute:TA})}var kA=new Map([["Bash","auto"]]);async function eg(){await tr({agent:"codex",getToolRoute:(e)=>oe(e,kA)})}var IA=new Map([["bash","auto"],["Bash","auto"],["powershell","powershell"],["PowerShell","powershell"]]);function OA(e){return oe(e,IA)}async function tg(){await Ie({agent:"copilot-cli",createDenyOutput:(e)=>({permissionDecision:"deny",permissionDecisionReason:e}),isSupported:()=>!0,getToolName:(e)=>e.toolName,getToolInput:(e,t,n)=>{let r=OA(t);if(typeof e.toolArgs==="object"&&e.toolArgs!==null)return{ok:!0,input:e.toolArgs,route:r};if(typeof e.toolArgs!=="string")return n({reason:"Failed to parse toolArgs JSON."}),{ok:!1};if(r.kind==="patch"&&e.toolArgs.trimStart().startsWith("*** Begin Patch"))return{ok:!0,input:e.toolArgs,route:r};let i=fo(e.toolArgs,n,"Failed to parse toolArgs JSON.");if(i===void 0)return{ok:!1};return{ok:!0,input:i,route:r}},getContext:Sn,getSessionId:(e)=>typeof e.sessionId==="string"&&e.sessionId.trim()?e.sessionId:void 0})}var MA=new Map([["Shell","auto"]]);function DA(e){return oe(e,MA)}async function ng(){await Ie({agent:"cursor",createDenyOutput:(e)=>({permission:"deny",user_message:e,agent_message:e}),createAllowOutput:()=>({permission:"allow"}),isSupported:()=>!0,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:DA(t)}),getContext:NA,getSessionId:(e)=>e.conversation_id})}function NA(e,t,n,r,o){let i=LA(e);if(!i[0])return Se(r,t,n),null;let s=i.flatMap((m)=>{let d=vt([m],o.paths);return d?[d]:[]});if(!s[0])return He(r,t,n,{directory:"session",problem:"unusable",cwd:i[0]}),null;let a=WA(e.cwd),l=St(a,s,o.paths);if(!l)return He(r,t,n,{directory:"session",problem:Et(a,s[0],o.paths),cwd:a}),null;if(t===null||typeof t!=="object"||Array.isArray(t))return{configCwd:l,executionCwd:l};if(!Object.hasOwn(t,"working_directory"))return{configCwd:l,executionCwd:l};let c=t.working_directory;if(typeof c!=="string"||c.trim()==="")return Se(r,t,n),null;let u=St(c,s,o.paths);if(!u)return He(r,t,n,{directory:"requested",problem:Et(c,s[0],o.paths),cwd:c}),null;return{configCwd:l,executionCwd:u}}function LA(e){if(e.workspace_roots===void 0)return typeof e.cwd==="string"&&e.cwd.trim()!==""?[e.cwd]:[];if(!Array.isArray(e.workspace_roots))return[];return e.workspace_roots.filter((t)=>typeof t==="string"&&t.trim()!=="")}function WA(e){return typeof e==="string"&&e.trim()!==""?e:"."}var rg=new Map([["run_shell_command","auto"]]);function GA(e){return oe(e,rg)}async function og(){await Ie({agent:"gemini-cli",createDenyOutput:(e)=>({decision:"deny",reason:e,systemMessage:e}),isSupported:(e)=>e.hook_event_name===Xp,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:GA(t)}),getContext:Ki("dir_path",rg,{emptyMeansSessionCwd:!0,allowOutsideSessionCwd:!0}),getSessionId:(e)=>e.session_id})}var FA=new Map([["run_terminal_command","auto"],["monitor","auto"]]);function zA(e){return oe(e,FA)}async function ig(){await Ie({agent:"grok-build",createDenyOutput:(e)=>({decision:"deny",reason:e}),createAllowOutput:()=>({decision:"allow"}),isSupported:()=>!0,getToolName:(e)=>e.toolName,getToolInput:(e,t,n)=>{if(e.toolInputTruncated===!0)return Se(n,e.toolInput,t),{ok:!1};return{ok:!0,input:e.toolInput,route:zA(t)}},getContext:HA,getSessionId:(e)=>e.sessionId})}function HA(e,t,n,r,o){let i=BA(e);if(!i)return Se(r,t,n),null;let s=vt([i],o.paths);if(!s)return He(r,t,n,{directory:"session",problem:"unusable",cwd:i}),null;let a=$A(e.cwd),l=St(a,[s],o.paths);if(!l)return He(r,t,n,{directory:"session",problem:Et(a,s,o.paths),cwd:a}),null;return{configCwd:l,executionCwd:l}}function BA(e){let t=e.workspaceRoot===void 0?e.cwd:e.workspaceRoot;return typeof t==="string"&&t.trim()!==""?t:void 0}function $A(e){return typeof e==="string"&&e.trim()!==""?e:"."}var sg=require("node:path");var UA=new Map([["terminal","posix"]]);async function ag(){await Ie({agent:"hermes-agent",createDenyOutput:(e)=>({action:"block",message:e}),isSupported:(e)=>e.hook_event_name===Jp,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:oe(t,UA)}),getContext:jA,getSessionId:(e)=>e.session_id})}function jA(e,t,n,r,o){let i=Sn(e,t,n,r,o);if(!i)return null;if(!t||typeof t!=="object"||Array.isArray(t))return i;if(!Object.hasOwn(t,"workdir"))return i;let s=t.workdir;if(typeof s!=="string"||s.trim()==="")return Se(r,t,n),null;let a=vt([sg.resolve(i.configCwd,s)],o.paths);if(!a)return He(r,t,n,{directory:"requested",problem:"unusable",cwd:s}),null;return{...i,executionCwd:a}}var lg=new Map([["Bash","posix"]]);function VA(e){return oe(e,lg)}async function cg(){await tr({agent:"kimi-code",getToolRoute:VA,getContext:Ki("cwd",lg)})}var KA={"antigravity-cli":Kp,"claude-code":Qp,codex:eg,"copilot-cli":tg,cursor:ng,"gemini-cli":og,"grok-build":ig,"hermes-agent":ag,"kimi-code":cg},Wl=Yp.map((e)=>({...e,run:KA[e.id]}));function ug(e){let t=oo({label:"hook",booleans:Object.fromEntries(Wl.map((r)=>[r.id,[...r.flags,...r.legacyFlags]]))},e);if(t.errors.length>0)return;let n=Wl.filter((r)=>t.flags[r.id]);return n.length===1?n[0]:void 0}function dg(e){return Wl.find((t)=>t.legacyTopLevelFlags.some((n)=>n===e))}async function qA(){let e=process.argv.slice(2),t=e[0],n=oo({label:"cc-safety-net",booleans:{version:["-V","--version"]},positionals:"list"},e);if(!n.help&&!n.flags.version){if(t?.toLowerCase()==="hook"){let i=ug(e.slice(1));if(i){await i.run();return}}let o=dg(t);if(o){await o.run();return}}let r=await import("../cli.js");await r.runCli(e)}qA().catch((e)=>{console.error("CC Safety Net error:",e),process.exit(1)});
|