cc-safety-net 2.4.12 → 2.4.14
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-q47ejf84.js → index-jb96wweh.js} +2 -2
- package/dist/chunks/{index-kwg376ge.js → index-qbhpx1zs.js} +9 -9
- 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 fg=["-h","--help"];function io(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(fg.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 Wl=require("node:path");var Qi="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 Ji={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,...Ji},processedCandidateBytes:{cap:4194304,...Ji},pathEnvironmentExpansion:{cap:64,...Ji},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 pg=[/\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 gg(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 gg(e){return pg.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 hg={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 Hl(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.":hg[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==="`"?
|
|
4
|
+
`)}function es(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 yg={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 so(e,t={}){return{...yg[e.directory][e.problem],command:t.command,toolName:t.toolName,cwd:e.cwd}}function Bl(e){return Hl({...e,redact:Ct})}function $l(e){return Hl({...e,redact:Ct,askUser:!0})}function Ul(e){return Ct(e instanceof Error?e.message:String(e))}var Re=require("node:path");var Cg=256,ao=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 ir(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 os(e,t){return ts(e,0,t)}function ts(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=ns(e,o+2),a=bg(e,o,t);if(a===null){if(ao.has(s))throw new N("pathEnvironmentExpansion");r+=e.slice(o);break}let l=e.slice(o,a+1);r+=Sg(l,t,n),o=a+1;continue}let i=ns(e,o+1);if(!i){r+="$",o++;continue}r+=rs(i,n)??`$${i}`,o+=i.length+1}return r}function bg(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 Sg(e,t,n){let r=e.slice(2,-1),o=ns(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return rs(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(ao.has(o))throw new N("pathEnvironmentExpansion");return e}if(!ao.has(o))return e;if(s.endsWith("="))throw new N("pathEnvironmentExpansion");let a=rs(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??"":ts(i.slice(s.length),t+1,n);return l?ts(i.slice(s.length),t+1,n):""}function ns(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 rs(e,t){if(!ao.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){Vl(n,i);let s=t.realpath(i);if(s!==null)return jl(n,e,s,o);let a=Re.dirname(i);if(a===i||o.length>=Cg)return jl(n,e,i,o);o.push(Re.basename(i)),i=a}}function jl(e,t,n,r){let o=r.length===0?n:Re.join(n,...r.reverse());return e.resolvedPaths.set(t,o),o}function vg(e,t,n){let r=n.resolvedPaths.get(e);if(r!==void 0)return r;Vl(n,e);let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function Vl(e,t){e.charge("realpathAttempts"),e.charge("processedCandidateBytes",Buffer.byteLength(t))}function he(e,t,n,r){let o=ql(e,t,n);if(!o)return"";return O(o,n.paths,r).replace(/\\/g,"/")}function Kl(e,t,n,r,o){let i=ql(e,t,n);if(!i)return null;if(o(Re.basename(i)))return O(i,n.paths,r).replace(/\\/g,"/");let s=vg(i,n.paths,r);return s===null?null:s.replace(/\\/g,"/")}function ql(e,t,n){let r=n.home,o=os(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 ec=require("node:util"),Eg=new Set(["applypatch","patch"]),xg=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),Rg=new Set(["grep","grepsearch","rg"]),wg=new Set(["find","findbyname","glob"]),_g=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),Ag=new Set(["command","diff","input","patch","patchtext"]),Yl=new TextEncoder,Pg=new TextDecoder,Tg=/\s/,kg=64;class be extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var sr=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function tc(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function co(e){return _g.has(tc(e))}function nc(e){let t=tc(e);if(Eg.has(t))return"patch";if(Rg.has(t))return"grep";if(wg.has(t))return"glob";if(xg.has(t))return"path";return"unknown"}function Nt(e){if(!e||typeof e!=="object")return;ac(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 uo(e,t){return rc(e,t,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function rc(e,t,n,r,o){let i=sc(e,r,o);if(typeof e==="string")return n?[e]:[];if(!i)return[];let s=i.entries.flatMap(([a,l])=>rc(l,t,i.array?n:t.has(oc(a)),r,o+1));return r.ancestors.delete(i.object),s}function oc(e){return e.replace(/-/g,"_").toLowerCase()}function mo(e){return ic(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Og)}function ic(e,t,n,r){let o=sc(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>ic(a,o.array?t:Ag.has(oc(s)),n,r+1));return n.ancestors.delete(o.object),i}function Ig(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>sr.maxDepth||t.nodes>sr.maxNodes)dt();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>sr.maxStringBytes||t.stringBytes>sr.maxAggregateStringBytes)dt()}function sc(e,t,n){if(Ig(e,t,n),!e||typeof e!=="object")return null;let r=ac(e);if(t.ancestors.has(e))dt();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>sr.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 ac(e){if(ec.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 Og(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=Mg(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(...is(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...is(c));continue}if(c.startsWith("--- ")){let u=n[l+1]??"";if(!u.startsWith("+++ "))continue;t.push(...as(lo(c.slice(4),!0),lo(u.slice(4),!0))),l++;continue}if(!r)t.push(...is(c))}return t}function Mg(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 is(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return Ql(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return Ql(n[1]);if(e.startsWith("diff --git "))return Dg(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return Jl(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return Jl(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return Hg(i[1]);return[]}function Dg(e){let t=Ng(e);if(t.length===2&&t[0]&&t[1])return as(t[0],t[1]);let n=Lg(e);return n?as(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function Ng(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=lc(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(Qt(e[n]))n++;return n===e.length?t:[]}function Lg(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>kg)dt();if(Wg(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function Wg(e,t,n,r,o){if(ss(e,t,n,r,o))return!0;let i=Zl(e,"/",t,n),s=Zl(e,"/",r,o);if(i<=t||s<=r)return!1;if(ss(e,t,i,r,s))return!1;return ss(e,i+1,n,s+1,o)}function ss(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 Zl(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&&Tg.test(e)}function lc(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:Pg.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...Yl.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(...Yl.encode(Gg(s[0]??""))),o+=2}return null}function Gg(e){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
5
|
+
`,r:"\r",t:"\t",v:"\v"}[e]??e}function Fg(e){return ar(Bg(e))}function as(e,t){if(e==="/dev/null")return Xl(t);if(t==="/dev/null")return Xl(e);if(e.startsWith("a/")&&t.startsWith("b/"))return[e.slice(2),t.slice(2)].flatMap(ar);let n=zg(e,t)??(e===t?cc(e):null);return[e,t,...n?[n]:[]].flatMap(ar)}function Xl(e){let t=cc(e);return[e,...t?[t]:[]].flatMap(ar)}function cc(e){let t=e.indexOf("/");return t>0&&t<e.length-1?e.slice(t+1):null}function zg(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 Jl(e){return Fg(lo(e,!0))}function Hg(e){return ar(lo(e,!1))}function lo(e,t){let n=e.trim(),r=n[0]==='"'||n[0]==="'"?n[0]:void 0;if(r){let o=lc(n,0,r);if(o&&(t||n.slice(o.end).trim()===""))return o.value}return t?n.split("\t",1)[0]?.trim()??"":n}function Bg(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function ar(e){return e===""||e==="/dev/null"?[]:[e]}function Ql(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)=>fo(i,n));if(!r[0])return;let o=fo(Ye.isAbsolute(e)?e:Ye.resolve(r[0],e),n)[0];if(!o)return;return r.some((i)=>lr(o,i))?o:void 0}function ls(e,t,n){if(bt(e))return;return fo(Ye.isAbsolute(e)?e:Ye.resolve(t,e),n)[0]}function vt(e,t){return e.flatMap((n)=>fo(n,t))[0]}function Et(e,t,n){return ls(e,t,n)?"outside-workspace":"unusable"}function fo(e,t){let n=t.realpath(e);if(n===null)return[];return t.isDirectory(n)?[n]:[]}function lr(e,t){let n=Ye.relative(t,e);return n===""||n!==".."&&!n.startsWith(`..${Ye.sep}`)&&!Ye.isAbsolute(n)}var $g=8388608;async function uc(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>$g)throw Ug(e),Error("hook input byte limit exceeded");t.push(o)}return Buffer.concat(t,n).toString("utf-8")}function Ug(e){let t=e.destroy??e.cancel;if(!t)return;try{Promise.resolve(t.call(e)).catch(()=>{})}catch{}}function po(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:nc(e)}}function dc(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:mc(t),toolName:n}))}function He(e,t,n,r){e(so(r,{command:mc(t),toolName:n}))}function mc(e){try{return Nt(e)}catch(t){if(!(t instanceof be))throw t;return}}var wn=require("node:fs"),go=require("node:os");var Cc=require("node:fs"),bc=require("node:path");var pc=require("node:child_process"),F=require("node:fs"),re=require("node:path"),jg=["/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"],Vg=5000;function gc(e,t=ch(),n=Vg){let r=Kg(e),o=r===null?null:qg(r);if(r===null||o===null)return null;let i=ah(r,o,t,n);return i===null?null:{recursiveSubmodules:i}}function Kg(e){try{let t=F.realpathSync(re.resolve(e));return F.statSync(t).isDirectory()?t:null}catch{return null}}function qg(e){let t=sh(e);if(!t)return null;try{let n=F.lstatSync(t);if(n.isSymbolicLink()||!n.isFile())return null;let r=cs(t);if(!r?.commonDir)return null;if(!Xg(r.gitDir,t))return null;return Jg(r.gitDir,re.dirname(t))?{gitDir:r.gitDir,commonDir:r.commonDir}:null}catch{return null}}function cs(e){try{let t=Yg(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:Zg(n)}}catch{return null}}function Yg(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 Zg(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 Xg(e,t){let n=Qg(e);return n===null?!1:hc(e,n,t)}function Jg(e,t){let n=eh(e);return n===null?!0:hc(e,n,t)}function Qg(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 eh(e){let t=re.join(e,"config.worktree");return F.existsSync(t)?nh(t):null}function hc(e,t,n){try{return th(re.isAbsolute(t)?t:re.resolve(e,t),n)}catch{return!1}}function th(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 fc(F.realpathSync.native(e))===fc(F.realpathSync.native(t))}function fc(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 nh(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=rh(s[1]??"")}return r}function rh(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;return ih(t.slice(1,-1))}var oh={"\\":"\\",'"':'"',n:`
|
|
6
|
+
`,t:"\t",b:"\b"};function ih(e){return e.replace(/\\(.?)/gs,(t,n)=>n===""?t:oh[n]??t)}function sh(e){try{return us(F.realpathSync(e))}catch{return null}}function us(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 ah(e,t,n,r){if(lh(t))return!0;if(n===null)return!0;let o=pc.spawnSync(n,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:uh(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&&yc(o.stdout.trim())}function lh(e){return[re.join(e.commonDir,"config"),re.join(e.gitDir,"config.worktree")].filter((t)=>F.existsSync(t)).some((t)=>dh(t))}function ch(){return jg.find((e)=>F.existsSync(e))??null}function cr(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function uh(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!cr(t)))}function dh(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(mh(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=yc(c)}return r}function mh(e){return e==="include"||e.startsWith("includeif ")}function yc(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function Sc(e,t){if(e==="")return null;let n=ue(),r=us(he(e,e,t,n)),o=r?fh(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 fh(e,t,n,r){try{let o=he(e,t,n,r),i=Cc.statSync(e),s=i.isFile()?o:null,a=i.isFile()?cs(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(bc.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 ph={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 Ec(){return gh({env:new Map(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),home:Me(process.env.HOME||go.homedir()),tmpdir:go.tmpdir(),paths:ph})}function gh(e,t={}){let n=new Map,r=new Map,o={...e,gitMetadata:(i)=>vc(n,i,()=>Sc(i,o)),worktreeFacts:(i)=>vc(r,i,()=>gc(i)),...t};return o}function vc(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"],ho={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"}},yo=["standard","strict","paranoid"];function hh(e,t){if(!t)return e;return yo.indexOf(t)>yo.indexOf(e)?t:e}function yh(e){let t=ps(ae.level,e);if(t===void 0||t==="")return;if(yo.includes(t))return t;console.error(`CC Safety Net: ignored invalid ${ae.level.name}=${JSON.stringify(t.slice(0,40))}. Use ${yo.join(", ")}.`);return}function Ch(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function xc(e){return Ch(ps(ae.auditScope,e))==="all"}function ms(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 fs(e={},t){let n=e.safety?.level??"standard",r=yh(t),o=hh(n,r),i=ho[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:ms(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"?ds(e,t):ps(e,t);return n==="1"||n?.toLowerCase()==="true"}function ds(e,t){return t.get(e)}function ps(e,t){let n=ds(e.name,t);if(n!==void 0)return n;if(e.legacyName)return ds(e.legacyName,t);return}function ur(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 pr=require("node:path");var W=require("node:fs"),j=require("node:path");function gs(){let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${e()}${e()}`}var bh=Symbol("PolicyFilesystemScope"),Sh=Symbol("PolicyFilesystemTarget"),vh=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{[bh]:!0,root:j.resolve(e),label:t}}function Rc(e,t){let n=j.normalize(t);if(t===""||j.isAbsolute(t)||n===".."||n.startsWith(`..${j.sep}`))throw new ye(e.label);return{[Sh]:!0,scope:e,relativePath:n,path:j.join(e.root,n)}}function dr(e,t){return Rc(e,j.relative(e.root,j.resolve(t)))}function wc(e,t="rules policy"){let n=j.resolve(e),r=j.parse(n).dir;return Rc(tn(r,t),j.relative(r,n))}function bo(e){return Ac(e.scope.label,()=>{if(!Co(e))return null;let t=W.openSync(e.path,W.constants.O_RDONLY|vh);return Eh(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 Co(e),r})})}function _c(e,t){if(e.path===t.path)return!0;return Ac(e.scope.label,()=>{if(!Co(e)||!Co(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 Ac(e,t,n){try{return t()}catch(r){if(n?.(),r instanceof ye)throw r;throw new ye(e)}}function Eh(e,t){try{return t()}finally{W.closeSync(e)}}function Co(e,t="file"){let n=xh(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);Rh(n,W.realpathSync(i),e.scope.label)}return!0}function xh(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 Rh(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}$/,Pc="rulebook.json",Tc=".cc-safety-net/rules";var kc=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/;var wh=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,_h=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ah="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),wP=new RegExp(`^${_h}/(${nn.source.slice(1,-1)})/${Ah}$`);function Ph(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function Ic(e){if(So(e))try{return hs(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 hs(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(kc);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||!wh.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:Ph(o),name:o}}function So(e){return kc.test(e)}var Oc="rule.json",vo="policy.json",Mc=".cc-safety-net",Th="rules",kh="CC_SAFETY_NET_HOME",Dc="`cc-safety-net rule update`";function Ih(e){return L.resolve(e,Tc)}function Oh(e){return L.join(Ih(e),Oc)}function mr(e){return L.join(L.resolve(e),Mc,vo)}function ys(e,t={}){return t.userConfigDir??(t.userConfigPath?L.dirname(t.userConfigPath):L.join(Mh(e),Th))}function Mh(e){let t=e.env.get(kh);return t?L.resolve(Me(t)):L.join(e.home,Mc)}function Dh(e,t={}){return L.join(ys(e,t),Oc)}function An(e,t={}){return L.join(L.dirname(ys(e,t)),vo)}function Nc(e,t){let n=t.userConfigPath??Dh(e,t),r=t.projectConfigPath??Oh(t.cwd),o=Nh(e,t),i=Lh(r,t.cwd);return{userConfigPath:n,projectConfigPath:r,userScope:o,projectScope:i,userConfigTarget:dr(o,n),projectConfigTarget:dr(i,r)}}function Nh(e,t){let n=t.userConfigPath?L.dirname(L.dirname(L.resolve(t.userConfigPath))):L.dirname(L.resolve(t.userConfigDir??ys(e,t)));return tn(n,"user policy")}function Lh(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 Lc(e,t){return L.join(e,t,Pc)}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"]),Wc=new Set(["python","python3","python2","node","ruby","perl"]),Eo=/^python(?:[23](?:\.\d+)*)?$/,Be=new Set(["awk","gawk","nawk","mawk"]),xo=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 Gc="Rulebook exceeds CC Safety Net's safe validation limits.",Fc="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 zc(e){if(Cs(e.allowed_commands,Ze.maxAllowedCommands)||Cs(e.rules,Ze.maxRules)||Cs(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 Cs(e,t){return Array.isArray(e)&&e.length>t}var bs=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var Ss=64,vs="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 Wh={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},Es=new Set(["--init-file","--rcfile"]);function xs(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(!Wh[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"&&Es.has(l)&&!s.includes("="))i++;continue}let a=xs(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 fr(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 Ro(e){let t={inSingle:!1,inDouble:!1,escaped:!1};for(let n of Gh(e))fr(n,t);return t.inSingle||t.inDouble}function Gh(e){let t="",n={inSingle:!1,inDouble:!1,escaped:!1},r=!1,o=!0;for(let i=0;i<e.length;i++){let s=e[i];if(!s)break;if(r){if(s===`
|
|
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);fr(s,n)}return t}var Rs=new Set(["rm","find","xargs","parallel"]),Fh=new Set(["git","busybox",...Rs,...Q,...Wc,...Be]),zh=new Set(["python","node","ruby","perl"]);function Hc(e){let t=M(e);return Fh.has(t)||Xe(t)}function Xe(e){return zh.has(Hh(e))}function Hh(e){let t=k(e).toLowerCase();return Eo.test(t)?"python":t}function ws(e){try{let t=bo(Bh(e));if(t===null)return{config:null,errors:[]};if(!t.trim())return{config:null,errors:["Config file is empty"]};let n=JSON.parse(t),r=jh(n);if(r.errors.length>0)return{config:null,errors:r.errors};return{config:{version:1,rules:n.rules??[],overrides:n.overrides??{},transparent_wrappers:n.transparent_wrappers??[]},errors:[]}}catch(t){if(t instanceof 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 Bh(e){return typeof e==="string"?wc(e):e}var w=(e,t)=>({path:e,message:t,kind:"typed"}),de=(e,t)=>({path:e,message:t,kind:"custom"});function Bc(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 _s=`must be one of ${bs.join(", ")}`,$h=/^[^/]+\/[^/]+$/,Uh=["version","rules","overrides","transparent_wrappers"];function jh(e){let t=Vh(e);return{errors:As(ty(t,Uh,(n)=>n.kind==="custom"),": "," "),sources:ey(e,t)}}function Vh(e){if(!Pn(e))return[w([],"Config must be an object")];let t=Array.isArray(e.rules)&&e.rules.length>Ss;return[...e.version===1?[]:[w(["version"],"must be 1")],...Kh(e.rules,t),...Zh(e.overrides),...Jh(e.transparent_wrappers),...t?[]:Yh(e.rules),...Pn(e.overrides)?Object.keys(e.overrides).filter((n)=>!$h.test(n)).map((n)=>de(["overrides",n],"must use <rulebook-name>/<rule-name>")):[],...Qh(e.transparent_wrappers)]}function Kh(e,t){if(e===void 0)return[];if(!Array.isArray(e))return[w(["rules"],"must be an array of rulebook source strings"),...$c(e,Ss)?[w(["rules"],vs)]:[]];if(t)return[{path:["rules"],message:vs,kind:"limit"}];return e.flatMap((n,r)=>{if(typeof n!=="string")return[w(["rules",r],"must be a rulebook source string"),...qh(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 $c(e,t){let n=Uc(e);return n!==void 0&&!(n<=t)}function qh(e,t){let n=Uc(e);return n!==void 0&&!(n>=t)}function Uc(e){if(e===null||e===void 0)return;let t=e.length;return t===void 0?void 0:Number(t)}function Yh(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||n==="")return[];if(n.trim()==="")return[de(["rules",r],"must be a non-empty rulebook source string")];let o=Ic(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 Zh(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[...Xh(n.reason,["overrides",t,"reason"]),...n.intent===void 0||Ts(n.intent)?[]:[w(["overrides",t,"intent"],_s)]]})}function Xh(e,t){if(typeof e!=="string")return[w(t,"required non-empty string"),...$c(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 Jh(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 Qh(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(Hc(n))return[de(["transparent_wrappers",r],`reserved command "${n}" cannot be a wrapper`)];return t.add(n),[]})}function ey(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 ty(e,t,n){let r=e.map((s)=>s.path[1]),o=[...new Set(r.filter((s)=>typeof s==="string"))],i=(s,a)=>[s.path.length===0?-1:t.indexOf(String(s.path[0])),typeof a==="number"?a:o.indexOf(String(a)),n(s)?0:1];return e.map((s,a)=>({issue:s,rank:i(s,r[a])})).sort((s,a)=>s.rank[0]-a.rank[0]||s.rank[1]-a.rank[1]||s.rank[2]-a.rank[2]).map((s)=>s.issue)}function As(e,t,n){return[...new Set(e.map((r)=>{let o=Ps(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 Ps(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function Ts(e){return bs.includes(e)}function Pn(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Vc(e){let t=oy(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}var ny=`required non-empty string up to ${Wt} characters`,jc="must be a non-empty array of unique non-empty strings",ry="required non-empty array of non-empty strings";function oy(e){if(!Gt(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!zc(e))return{errors:[Gc],ruleNames:new Set};let t=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...As(iy(e,e.rulebook_version===2),": ",": ")];return{errors:t.length>Ze.maxValidationErrors?[...t.slice(0,Ze.maxValidationErrors),Fc]:t,ruleNames:new Set(Kc(e).map((n)=>n.toLowerCase()))}}function Kc(e){let t=Gt(e)?e.rules:void 0;return(Array.isArray(t)?t:[]).flatMap((n)=>{let r=Gt(n)?n.name:void 0;return typeof r==="string"?[r]:[]})}function iy(e,t){return[...typeof e.name==="string"&&nn.test(e.name)?[]:[w(["name"],"required string matching rule name pattern")],...typeof e.version==="string"&&e.version!==""?[]:[w(["version"],"required non-empty string")],...sy(e.allowed_commands),...ay(e.rules,t),...dy(e.tests),...my(e),...fy(e)]}function sy(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 ay(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?cy(n,["rules",r]):ly(n,["rules",r])}),...Bc(e)]}function ly(e,t){return[...qc(e.name,t),...Yc(e.command,t),...e.subcommand===void 0||typeof e.subcommand==="string"&&Lt.test(e.subcommand)?[]:[w([...t,"subcommand"],"must match command pattern")],...wo(e.block_args,[...t,"block_args"],"required non-empty array",!1),...Zc(e.reason,t),...Xc(e.intent,t)]}function cy(e,t){return[...qc(e.name,t),...Yc(e.command,t),...Zc(e.reason,t),...Xc(e.intent,t),...uy(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 qc(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 Yc(e,t){return typeof e==="string"&&Lt.test(e)?[]:[w([...t,"command"],"required string matching command pattern")]}function Zc(e,t){return typeof e==="string"&&e!==""&&e.length<=Wt?[]:[w([...t,"reason"],ny)]}function Xc(e,t){return e===void 0||Ts(e)?[]:[w([...t,"intent"],_s)]}function uy(e,t){if(!Gt(e))return[w(t,"required object")];return[...wo(e.command_path,[...t,"command_path"],ry,!1),...e.any_args===void 0?[]:wo(e.any_args,[...t,"any_args"],jc,!0),...e.exclude_args===void 0?[]:wo(e.exclude_args,[...t,"exclude_args"],jc,!0)]}function wo(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 dy(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 my(e){if(!Array.isArray(e.tests))return[];let t=new Set(Kc(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 fy(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 ru(e,t){let n=Nc(e,t),r;try{r=_c(n.userConfigTarget,n.projectConfigTarget)}catch(f){if(f instanceof ye)return Ey(n,f.message);throw f}let o=ws(n.userConfigTarget),i=r?{config:null,errors:[]}:ws(n.projectConfigTarget),s=tu(n.userConfigPath,o.errors),a=tu(n.projectConfigPath,i.errors),l=new Set,c=o.config?Jc(o.config,pr.dirname(n.userConfigPath),"user",n.userScope,l):nu(),u=i.config?Jc(i.config,pr.dirname(n.projectConfigPath),"project",n.projectScope,l):nu(),m=o.config?.overrides??{},d=i.config?.overrides??{};return{rules:[...Qc(c.rules,m),...Qc(u.rules,d)],transparent_wrappers:Sy(o.config,i.config),rulebooks:[...c.rulebooks,...u.rulebooks],errors:[...s,...a,...c.errors,...u.errors],warnings:[...c.warnings,...u.warnings,...c.canValidateOverrides?eu(m,c.knownRuleIds,n.userConfigPath):[],...c.canValidateOverrides?vy(d,c.knownRuleIds,n.projectConfigPath):[],...u.canValidateOverrides?eu(d,u.knownRuleIds,n.projectConfigPath):[]],userConfig:o.config??void 0,projectConfig:i.config??void 0,...n}}function Jc(e,t,n,r=tn(pr.dirname(pr.dirname(t)),n==="user"?"user policy":"project policy"),o=new Set){let i=[],s=[],a=e.rules.flatMap((c)=>{let u=gy(c,t,r);if(u.errors.length>0||!u.rulebook)return i.push(...u.errors),[];let 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:py(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 py(e){if(e.rulebook_version===2)return e.rules.map((t)=>({name:`${e.name}/${t.name}`,command:t.command,block_args:[],match:t.match,reason:t.reason,intent:t.intent}));return e.rules.map((t)=>({...t,name:`${e.name}/${t.name}`,match:void 0}))}function gy(e,t,n){let r=hy(e),o=Lc(t,r),i=Cy(o,n);if("error"in i)return{rulebook:null,errors:[i.error]};if(i.content===null)return{rulebook:null,errors:[`missing rulebook file ${o} for ${e}; ${yy(e)}`]};let s=by(i.content);if("problem"in s)return{rulebook:null,errors:[`invalid rulebook ${o}: ${s.problem}; fix that file`]};if(s.rulebook.name!==r)return{rulebook:null,errors:[`rulebook name "${s.rulebook.name}" in ${o} must match source "${e}"; fix that file`]};return{rulebook:s.rulebook,errors:[]}}function hy(e){return So(e)?hs(e).name:e}function yy(e){return So(e)?`run ${Dc} to vendor ${e}`:"create that file or remove that source from the rules config"}function Cy(e,t){try{return{content:bo(dr(t,e))}}catch(n){if(n instanceof ye)return{error:n.message};throw n}}function by(e){let t;try{t=JSON.parse(e)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:Vc(t)}}catch(n){return{problem:n instanceof Error?n.message:"invalid rulebook"}}}function Sy(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function Qc(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 eu(e,t,n){return Object.keys(e).filter((r)=>!t.has(r)).map((r)=>`unknown override key "${r}" in ${n}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function vy(e,t,n){return Object.keys(e).filter((r)=>t.has(r)).map((r)=>`project override cannot target user-scoped rule "${r}" in ${n}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function tu(e,t){return t.map((n)=>n.startsWith("Unable to access ")?n:`${e}: ${n}`)}function Ey(e,t){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath}}function nu(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}var Lo=require("node:fs");var ou=[{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"}],ks=new Set(ou.map((e)=>e.id)),_o=ou,xy=new Map(_o.map((e)=>[e.id,e.intent]));function v(e,t){return{id:e,reason:t,intent:xy.get(e)??"manual_only"}}var Is=[{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"}],Ao={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},Ry=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],wy=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Os=[{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"]},...wy.flatMap((e)=>Ry.map((t)=>({id:["secret.home",e.idSlug,t.slice(1)].join("."),category:"Home path",label:[e.label,t].join(""),description:["Blocks home ",e.label,t," credential backup files."].join(""),suffixParts:[...e.directoryParts,[e.basename,t].join("")]}))),{id:"secret.home.gh-hosts",category:"Home path",label:"~/.config/gh/hosts.yml",description:"Blocks GitHub CLI host credential files.",suffixParts:[".config","gh","hosts.yml"]}];var Po=[{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"]}],iu=[{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"}],_y=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Ms=iu.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})),Ds=iu.flatMap((e)=>_y.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}))),gr={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)$/},Ns=["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})),Ls=[{id:"secret.ext-pattern.key",category:"Extension pattern",label:".key / .keypair",description:"Blocks key and keypair extension patterns.",pattern:/^key(pair)?$/},{id:"secret.ext-pattern.keystore",category:"Extension pattern",label:".keystore / .keyring",description:"Blocks keystore and keyring extension patterns.",pattern:/^key(store|ring)$/},{id:"secret.ext-pattern.kdbx",category:"Extension pattern",label:".kdb / .kdbx",description:"Blocks KeePass database extension patterns.",pattern:/^kdbx?$/}],Ay=[...Is,Ao,...Os,...Ms,...Ds,gr,...Ns,...Ls,...Po].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}})),To=new Set(Po.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),Ws=new Set(Ay.map((e)=>e.id));var Le=require("node:path"),ko=process.platform==="win32",su=/[*?]/;function Gs(e){let t=e.trim(),n=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(ko?t.replaceAll("\\","/"):t);if(!n)return null;let r=n[1]??"",o=n[2]??"";if(su.test(r)||o==="."||o==="..")return null;return{root:r||"/",name:o}}function hr(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function Fs(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=hr(e.trim(),t);if(!Le.isAbsolute(n))return"must be an absolute path or start with ~/";return yr(n,t)}function zs(e,t){let n=au(e,t);if(n===null)return"must be a non-empty path string";if(!Le.isAbsolute(n))return null;if(yr(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 Py="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Ty="cannot cover the guard's own configuration";function au(e,t){if(typeof e!=="string"||e.trim()==="")return null;let n=e.trim(),r=ko?n.replaceAll("\\","/"):n;return hr(r.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function Hs(e,t){let n=au(e,t);if(n===null)return"must be a non-empty path string";let r=Gs(n)?.root??n;if(su.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(yr(r,t)!==null)return Py;return ky(r,t)?Ty:null}function ky(e,t){let n=Io(e),r=Io(Le.join(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${Le.sep}`)}function yr(e,t){let n=Io(e),r=Io(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 Io(e){let t=Le.normalize(e);if(ko)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(ko?3:1)&&t.endsWith(Le.sep))t=t.slice(0,-1);return t}var lu=30,Oo=1,Mo=365;function cu(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var uu=new Set(_o.filter((e)=>e.catastrophic).map((e)=>e.id));function T(e,t){if(!e)return null;if(uu.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(uu.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function du(e,t){return Object.freeze(Object.fromEntries(_o.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 mu(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:du(e,t)})}var fu={standard:0,strict:1,paranoid:2};function hu(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:Bs(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:Bs(e.secret_protection.deny_paths,t.secret_protection?.deny_paths),allow_paths:Bs(e.secret_protection.allow_paths,t.secret_protection?.allow_paths)},audit:e.audit},weakenings:Iy(e,t)}}function Bs(e,t){return[...new Set([...e,...t??[]])]}function Iy(e,t){let n=t.safety?.level,r=ho[e.safety.level];return[...n&&fu[n]<fu[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"]:[],...pu(t.destructive_command_protection?.overrides,(o)=>e.destructive_command_protection.enabled&&e.destructive_command_protection.overrides[o]!=="off"),...pu(t.secret_protection?.overrides,(o)=>e.secret_protection.enabled&&(e.secret_protection.overrides[o]==="on"?!0:e.secret_protection.overrides[o]!=="off"&&!To.has(o))),...e.destructive_command_protection.enabled?gu(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?gu(e.secret_protection.allow_paths,t.secret_protection?.allow_paths).map((o)=>`project policy adds secret allow path: ${o}`):[]]}function pu(e,t){return Object.entries(e??{}).flatMap(([n,r])=>r==="off"&&t(n)?[`project policy disables rule ${n}`]:[])}function gu(e,t){return(t??[]).filter((n)=>!e.includes(n))}var js=new Set(["standard","strict","paranoid"]),Su={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:lu}};function vu(e,t){let n=Hy(An(e,t),e.home),r=Wo(mr(t.cwd),e.home),o=My(r.parsed,e.home),i=Object.keys(o.policy).length>0?hu(n.gui??Su,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?Us(i.policy):n.policy,errors:s,...a?{fallback:a}:{},...r.exists?{policyScopes:{levelScope:l,weakenings:i?.weakenings??[]}}:{}}}var Oy="project policy audit settings are ignored; audit is user scope only";function My(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={...js.has(n.level)?{level:n.level}:{},...We(n.overrides)?yu({overrides:Eu(n.overrides,_n,["safety","overrides"],rn)}):{}},a={...typeof o.enabled==="boolean"?{enabled:o.enabled}:{},...o.overrides!==void 0?{overrides:No(o.overrides,ks,Ru,rn)}:{},...o.allow_paths!==void 0?{allow_paths:kn(o.allow_paths,Fs,t,["destructive_command_protection","allow_paths"],rn)}:{}},l={...typeof i.enabled==="boolean"?{enabled:i.enabled}:{},...i.overrides!==void 0?{overrides:No(i.overrides,Ws,wu,rn)}:{},...i.deny_paths!==void 0?{deny_paths:kn(i.deny_paths,zs,t,["secret_protection","deny_paths"],rn)}:{},...i.allow_paths!==void 0?{allow_paths:kn(i.allow_paths,Hs,t,["secret_protection","allow_paths"],rn)}:{}};return{policy:yu({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?[]:[Oy]}}function Eu(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],Vs));return[]}))}function yu(e){return Object.fromEntries(Object.entries(e).flatMap((t)=>Object.keys(t[1]).length>0?[t]:[]))}var rn=()=>{return},Vs="must be a boolean",Ks="must be an object if provided",xu=`must be an integer between ${Oo} and ${Mo}`,Ru={path:["destructive_command_protection","overrides"],label:"destructive command"},wu={path:["secret_protection","overrides"],label:"secret protection"},Dy=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Ny(e,t){let n=[];return{policy:_u(e,t,(o)=>{n.push(o)}),issues:n}}function Ly(e,t){return _u(e,t,rn)}function _u(e,t,n){if(!We(e))return n(w([],"Config must be an object")),Do();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 Au(e,Dy,[],n),{version:1,safety:{level:Wy(r.level,n),overrides:Eu(o,_n,["safety","overrides"],n)},workflow:{worktree_mode:$s(i.worktree_mode,["workflow","worktree_mode"],!1,n)},destructive_command_protection:{enabled:$s(s.enabled,["destructive_command_protection","enabled"],!0,n),overrides:No(s.overrides,ks,Ru,n),allow_paths:kn(s.allow_paths,Fs,t,["destructive_command_protection","allow_paths"],n)},secret_protection:{enabled:$s(a.enabled,["secret_protection","enabled"],!0,n),overrides:No(a.overrides,Ws,wu,n),deny_paths:kn(a.deny_paths,zs,t,["secret_protection","deny_paths"],n),allow_paths:kn(a.allow_paths,Hs,t,["secret_protection","allow_paths"],n)},audit:{retention_days:Gy(l.retention_days,n)}}}function Tn(e,t,n,r){if(e===void 0)return{};if(!We(e))return r(w(t,Ks)),{};return Au(e,n,t,r),e}function Au(e,t,n,r){for(let o of Object.keys(e).filter((i)=>!t.includes(i)))r({path:n,message:o,kind:"unknownKeys"})}function Wy(e,t){if(e===void 0)return"standard";if(js.has(e))return e;return t(w(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function $s(e,t,n,r){if(typeof e==="boolean")return e;if(e!==void 0)r(w(t,Vs));return n}function Gy(e,t){if(!(e===void 0||typeof e==="number"&&Number.isInteger(e)&&e>=Oo&&e<=Mo))t(w(["audit","retention_days"],xu));return cu(e)}function No(e,t,n,r){if(e===void 0)return{};if(!We(e))return r(w(n.path,Ks)),{};return Object.fromEntries(Object.entries(e).flatMap(([o,i])=>{if(!t.has(o))return r({path:[...n.path,o],message:`unknown ${n.label} rule id "${o}"`,kind:"key"}),[];if(i==="on"||i==="off")return[[o,i]];return r(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 Do(){return structuredClone(Su)}function Wo(e,t){if(!Lo.existsSync(e))return{exists:!1,policy:Do(),errors:[]};try{let n=Lo.readFileSync(e,"utf-8");if(!n.trim())return{exists:!0,policy:Do(),errors:[`${e}: Config file is empty`],fallback:"defaults"};let r=JSON.parse(n),o=Ny(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}: ${zy(i)}`),fallback:We(r)?"salvaged":"defaults"}}catch(n){let r=n instanceof Error?n.message:String(n);return{exists:!0,policy:Do(),errors:[`${e}: ${n instanceof SyntaxError?"Invalid JSON":r}`],fallback:"defaults"}}}var Fy=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[Ks,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[Vs,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[xu,`not an integer between ${Oo} and ${Mo}`]]);function zy(e){let t=Ps(e.path);if(e.kind==="unknownKeys")return`${t===""?"":`${t}.`}${e.message}: unknown field`;if(e.kind==="key")return`${t}: unknown rule id`;let n=Fy.get(e.message)??e.message;return t===""?n:`${t}: ${n}`}function Hy(e,t){let n=Wo(e,t);if(!n.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!We(r))return{policy:bu(),errors:[]};let o=Ly(r,t);return{policy:Us(o),gui:o,errors:[],levelPresent:Cu(r)}}if(n.parsed===void 0)return{policy:bu(),errors:n.errors,...n.fallback?{fallback:n.fallback}:{}};return{policy:Us(n.policy),gui:n.policy,errors:n.errors,...n.fallback?{fallback:n.fallback}:{},levelPresent:Cu(n.parsed)}}function Cu(e){let t=We(e)&&We(e.safety)?e.safety:{};return js.has(t.level)}function Pu(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...To].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function bu(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Pu({}),denyPaths:[],allowPaths:[]}}}function Us(e){return{safety:By(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:Pu(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function By(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 Tu(e,t){let n=ru(e,t),r=vu(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}),...Vy(l.spec)?{source:l.spec}:{}}:{},...c&&typeof c==="object"?{override:Object.freeze({type:"reason",reason:c.reason})}:{}})]})));return Ky(o,$y(n,r),s,r.policyScopes)}function $y(e,t){let n=jy(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:qy(e.errors.length>0?Uy(e.errors):void 0,e.warnings.length>0?Ys(e.warnings.join("; ")):void 0,n)}}function Uy(e){return`${Ys(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function jy(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 Vy(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function Ky(e,t,n=Object.freeze({}),r){let o=qs(structuredClone(e)),i=r?{policyScopes:qs(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 qs(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))qs(t);return Object.freeze(e)}function qy(...e){return Ys(e.filter((t)=>!!t).join("; "))}function Ys(e){return/[.!?]$/.test(e)?e:`${e}.`}function ku(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:Zs(t.fail_closed,e.strict,"strict"),paranoid_rm:Zs(t.paranoid_rm,e.paranoidRm,"paranoidRm"),paranoid_interpreters:Zs(t.paranoid_interpreters,e.paranoidInterpreters,"paranoidInterpreters")};return{policy:mu(e.policySnapshot.policy,i),effectiveCapabilities:i,effectiveLevel:ms({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}function Zs(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 Cr(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 Yy=/^[A-Za-z_][A-Za-z0-9_]*=/;function Go(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function br(e){let t=Go(e.words[0],"time")?1:0,n=t===1&&Go(e.words[t],"-p")?t+1:t,r=t===1&&Go(e.words[n],"--")?n+1:n,o=Go(e.words[r],"!")?r+1:r,i=e.words.slice(o).find((s)=>!Yy.test(s.text));return i?.provenance==="literal"?i.text:void 0}var Ft=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Fo(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Zy(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 zo(e,t,n){e.push(n),t.reset()}function Ho(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 Xs(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 Xs({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 Zy(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 Js(e,t,n){if(t>=n||Ou(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!Ou(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=Iu(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=Iu(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 Qs(e,t,n,r){let o=[],i=t;for(let s of r){let a=i,l=!1;while(i<n){let c=Xy(e,i,n);if((s.stripTabs?c.text.replace(/^\t+/,""):c.text)===s.delimiter){s.attach({body:s.stripTabs?Jy(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 Iu(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 Ou(e){return e!=="\r"&&(/[\s;&|<>)]/u.test(e)||e==="`")}function Xy(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 Jy(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Lu=new Set(["&&","||","|","|&"]);function Wu(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=Uo(e,0,e.length,t,{used:0,max:t.maxWords},0);return _e({kind:"program",dialect:"posix",source:e,span:n,status:Ko(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function Uo(e,t,n,r,o,i,s){let a=[],l=[],c=Fo(),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);zo(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(),Nu(a,l),{nodes:a,issues:l,next:d+1,closed:!0,limited:!1,pendingHeredocs:u};if(Vo(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"||!Lu.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=Qs(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?bC(e,d,n):void 0;if(p){if(ta(a,l),i>=r.maxDepth)return On(a,l,d,"depth-limit",r.maxDepth);if(!ea(o))return On(a,l,d,"word-limit",r.maxWords);let C=Uo(e,p.braceIndex+1,n,r,o,i+1,"}"),P=C.next,x={start:p.braceIndex+1,end:C.closed?P-1:P},A=Mu(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||vr(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 $o(a,l,C.next);if(!C.closed)l.push({code:"unclosed-function-body",message:"function body is not closed"});d=P;continue}let g=jo(e,d);if(g){if(m(),!ju(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==="{"&&sC(e,d,n))&&c.start===-1){if(ta(a,l),i>=r.maxDepth)return On(a,l,d,"depth-limit",r.maxDepth);let C=f==="("?")":"}",P=Uo(e,d+1,n,r,o,i+1,C),x=P.next,A={start:d+1,end:P.closed?x-1:x},ee=Mu(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||vr(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 $o(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]!=="("?nC(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||Vo(ee)||!!jo(e,A)||ee===s||ee===")"||qe||(ee==="<"||ee===">")&&e[A+1]!=="(",xe=h==="<<"||h==="<<-",Z=xe?Js(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?na(e,A,n,r,o,i):void 0;if(H){if(l.push(...H.issues),H.limited)return $o(a,l,H.next);if(!ea(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(...eC(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)ta(a,l);let y=na(e,d,n,r,o,i);if(l.push(...y.issues),y.limited)return $o(a,l,y.next);let S=cC(c.words)?pC(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(!ea(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(),Nu(a,l),l.push(...SC(u)),{nodes:a,issues:l,next:d,closed:s===void 0,limited:!1,pendingHeredocs:[]}}function Mu(e,t,n){return{kind:"program",dialect:"posix",source:e.slice(t.start,t.end),span:t,status:Ko(n.issues,n.limited),issues:n.issues,nodes:n.nodes}}function na(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||Vo(f)||(f===";"||f==="|"||f==="&")&&jo(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=Qy(e,a,n,r,o,i);if(s+=h.text,u.push(...h.nested),m.push(...h.issues),d||=h.limited,c=Sr(c,h.provenance),a=h.next,d)break;continue}if(e.startsWith("$'",a)){l=!0;let h=rC(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==="`"?qo(e,a,n,r,o,i):null;if(g){let h=Gu(g,u,m);if(d||=h.limited,c=Sr(c,h.provenance),a=h.next,d)break;continue}if(f==="$"){let h=Hu(e,a,n,s,c);s=h.text,c=h.provenance,a=h.next;continue}if(f==="*"||f==="?"||f==="[")c=Sr(c,"glob");s+=f,a++}return{word:In(e,t,a,s,c,l,c==="literal"?void 0:iC(e,t,a)),nested:u,issues:m,next:a,limited:d}}function Qy(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
|
|
20
|
-
`],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(o.has(r))return{text:o.get(r)??r,next:t+1};if(r==="x")return
|
|
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
|
|
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
|
|
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=ra(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=qo(e,m,n,r,o,i);if(f){let p=Gu(f,l,c);if(m=p.next,u||=p.limited,a=Sr(a,p.provenance),u)return{text:s,provenance:a,nested:l,issues:c,next:m,limited:u};continue}if(d==="$"){let p=Hu(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 qo(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=ra(e,t+u,n,m),f=d===-1?n:d,p=d===-1?n:d+m.length;if(i>=r.maxDepth)return{program:CC(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=qo(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:Ko(E,C),issues:E,nodes:S}),next:p,provenance:"arithmetic"}}let g=Uo(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)&&vr(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:Ko([...g.issues,...h,...y],g.limited),issues:[...g.issues,...h,...y],nodes:g.nodes}),next:p,provenance:"command-substitution"}}function eC(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==="`"?qo(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 Gu(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 ra(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=Qs(e,u,n,s.splice(0));if(!m.terminated)return-1;a=m.next-1;continue}let c=Fu(e,a,t,n,i);if(c!==null){a=c;continue}if(!i.double&&e.startsWith("$((",a)){let u=tC(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=Js(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 tC(e,t,n){let r=1,o={single:!1,double:!1};for(let i=t;i<n;i++){let s=e[i],a=Fu(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 Fu(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!=="#"||!vC(e,t,n))return null;let s=t;while(s+1<r&&e[s+1]!==`
|
|
19
|
+
`&&e[s+1]!=="\r")s++;return s}function jo(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 nC(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 Vo(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 zu(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 rC(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=oC(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 oC(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 Bo(e,t+1,n,16,2,t+1);if(r==="u")return Bo(e,t+1,n,16,4,t+1);if(r==="U")return Bo(e,t+1,n,16,8,t+1);if(/[0-7]/.test(r))return Bo(e,t,n,8,3,t+1);return{text:r,next:t+1}}function Bo(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 Ko(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 Hu(e,t,n,r,o){let i=zu(e,t,n);return{text:r+e.slice(t,i),provenance:Sr(o,"variable"),next:i}}function iC(e,t,n){let r=Ho(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=ra(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=zu(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 Sr(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 sC(e,t,n){return t+1>=n||Vo(e[t+1]??"")||jo(e,t+1)!==null}var aC=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),lC=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function cC(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=uC(e,t);if(n===void 0||n===null)return!1;t=n}return!1}function uC(e,t){let n=e[t]?.text.toLowerCase();if(n==="command")return dC(e,t);if(n==="env")return mC(e,t);if(n==="sudo")return fC(e,t);return}function dC(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 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("-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 fC(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(lC.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-"))continue;return n}return e.length}function Bu(e,t,n,r){if(e.provenance!=="literal"||!e.raw.includes("{"))return;let o=$u(e.raw,t,n,r,!0);if(!o)return;if("limited"in o)return{limited:!0};let i=o.values.map((s)=>Uu(s,n));if(i.some((s)=>s===null))return{limited:!0};return{words:[...new Set(i.filter((s)=>s!==null&&s!==""))]}}function pC(e,t,n,r,o){if(t.provenance!=="literal"||!t.raw.includes("{"))return;let i=$u(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)=>Uu(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 $u(e,t,n,r,o){let i=[e],s=e.length,a=0;while(!0){let l=i.findIndex((f)=>Du(f,o));if(l===-1)break;if(++a>n)return{limited:"expansions"};let c=i[l]??"",u=Du(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,...gC(c,u)),s+=d-c.length}return a===0?void 0:{values:i}}function Du(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&&yC(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:hC(e,r)}}function gC(e,t){return t.alternatives.map((n)=>`${e.slice(0,t.start)}${n}${e.slice(t.end)}`)}function hC(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 yC(e){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(e)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(e)}function Uu(e,t){let n=`x${e}`,r=na(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 CC(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 $o(e,t,n){return{nodes:e,issues:t,next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function ea(e){return e.used++,e.used<=e.max}function bC(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 vr(e){return e.some((t)=>{if(t.kind==="command")return t.redirections.some((n)=>n.heredoc)||t.nested.some((n)=>vr(n.nodes));return(t.kind==="group"||t.kind==="function")&&vr(t.body.nodes)})}function SC(e){return e.map((t)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${t.delimiter} was not found`}))}function ju(e){return e?.kind==="command"||e?.kind==="group"||e?.kind==="function"}function Nu(e,t){let n=e.at(-1);if(n?.kind!=="connector"||!Lu.has(n.operator))return;t.push({code:"missing-command-after-connector",message:`connector ${n.operator} requires a following command`})}function ta(e,t){if(!ju(e.at(-1)))return;t.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function vC(e,t,n){return t===n||/[\s;&|()]/u.test(e[t-1]??"")}var Ku=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),EC=new Set(["gc","cat","type","cp","mv","rm"]),qu=["-rec","-for","-path","-literalpath","-whatif"],xC=/^\$env:\w/i,RC=/^(?:\$\{?\w+\}?|~)\\./;function Yu(e,t){let n=e.toLowerCase().replaceAll("`","");if(![...Ku].some((o)=>n.includes(o))&&!(n.includes("rm")&&qu.some((o)=>n.includes(o)))&&!n.includes("<#")&&!wC(n))return!1;let r=aa(e,t);if(Zu(r))return!1;return r.issues.some((o)=>o.code==="unclosed-block-comment"||o.code==="comment-depth-limit")||sa(r).some(_C)}function Zu(e){return e.nodes.some((t)=>{if(t.kind==="group")return Zu(t.body);if(t.kind!=="command")return!1;return t.redirections.some((n)=>n.operator==="<<")})}function wC(e){if(e.includes("$env:"))return!0;return e.includes("\\")&&(e.includes("$")||e.includes("~"))}function _C(e){let t=e[0]==="&"||e[0]==="."?1:0,n=e[t]?.toLowerCase();if(n&&Ku.has(n))return!0;let r=e.slice(t+1);if(n&&EC.has(n)&&r.some(AC))return!0;if(n!=="rm")return!1;return r.some((o)=>{let i=o.toLowerCase().split(":",1)[0]??"";return qu.some((s)=>i.startsWith(s))})}function AC(e){return xC.test(e)||RC.test(e)}function aa(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=la(e,0,e.length,t,0);return _e({kind:"program",dialect:"powershell",source:e,span:n,status:OC(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function la(e,t,n,r,o,i=!1){let s=[],a=[],l=Fo(),c=0,u=!1,m=()=>{if(l.words.length===0&&l.redirections.length===0)return;let f={start:l.start,end:l.end};zo(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=IC(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(oa(e,d,y)),d=y;continue}d++;continue}let g=Qu(e,d);if(g){m(),s.push(oa(e,d,d+g.length)),d+=g.length;continue}if(f==="{"){if(m(),o>=r.maxDepth)return a.push(Ju(r.maxDepth)),{nodes:s,issues:a,next:n,closed:!1,words:c,limited:!0};let y=la(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(oa(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?Vu(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(Xs({text:",",raw:",",span:{start:d,end:d+1},provenance:"literal",quoted:!1})),l.end=++d;continue}let h=Vu(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 Vu(e,t,n,r,o){let i="",s="literal",a=!1,l=[],c=[],u=0,m=!1,d=(p)=>{let g=PC(e,p,n,r,o);return i+=e.slice(p,g.next),c.push(g.program),l.push(...g.program.issues),u+=ia(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)||Qu(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:TC(e,t,f)),next:f,issues:l,nested:c,words:u,limited:m}}function PC(e,t,n,r,o){let i=Xu(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:[Ju(r.maxDepth)],nodes:[]}),next:a};let l=la(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 Xu(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 ia(e){let t=0;for(let n of e.nodes){if(n.kind==="group")t+=ia(n.body);if(n.kind==="command"){t+=n.words.length;for(let r of n.nested)t+=ia(r)}}return t}function TC(e,t,n){let r=Ho(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=Xu(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=kC(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 kC(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 Ju(e){return{code:"depth-limit",message:`command structure exceeds parser limit ${e}`}}function sa(e){return e.nodes.flatMap((t)=>{if(t.kind==="group")return sa(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(sa)]})}function Qu(e,t){for(let n of["&&","||",";","|"])if(e.startsWith(n,t))return n;return null}function IC(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 OC(e,t){if(t)return"limited";if(e.some((n)=>n.code==="unclosed-block-comment"))return"invalid";return e.length>0?"partial":"complete"}function oa(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"&&Yu(e.slice(0,n.maxInputLength),n))return aa(e,n);return Wu(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 Yo(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 ca(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 Er(e,t,n=1){if(e)e.units=Math.min(Number.MAX_SAFE_INTEGER,e.units+t.length*n)}function Ge(e,t){Er(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 ua(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 Zo(e,t,n){let r=ca(e,n);if(t==="rm")return MC(r);if(t==="dd")return NC(r);return id(r,!0)}function Xo(e,t,n){let r=ca(e,n);if(t==="rm")return LC(r);if(t==="reset-hard")return rd(r,"--ha","rd");if(t==="reset-merge")return rd(r,"--me","rge");if(t==="clean")return zC(r);if(t==="checkout")return BC(r);if(t==="push-force")return $C(r);if(t==="push-refspec")return UC(r);if(t==="push-delete")return jC(r);if(t==="branch")return VC(r);if(t==="tag")return YC(r);if(t==="restore")return ZC(r);return id(r,!1)}function MC(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=DC(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=ed(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=ed(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 DC(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 ed(e,t,n){if(td(e,t,n,"recursive"))return{recursive:!0,force:!1};if(td(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 td(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 NC(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 LC(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=GC(e,o);if(s>=0){if(WC(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)||da(e,o,"recursive"),r||=K(e,o,"--force")&&Rt(e,o+7)||da(e,o,"force"),n&&r)return!0;o++}return!1}function da(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 WC(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=nd(e,i,"recursive"),a=nd(e,i,"force");if(r&&a||o&&s)return!0;if(r||=s,o||=a,b(e,i+1)==="-")continue;let l=FC(e,i,n);if(l.combined||r&&l.forceAtBoundary||o&&l.recursiveAtBoundary)return!0;r||=l.recursive,o||=l.force}return!1}function nd(e,t,n){return K(e,t,`--${n}`)&&Rt(e,t+n.length+2)||da(e,t,n)}function GC(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 FC(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 rd(e,t,n){return Rr(e,"reset",Dn,!0,(r)=>b(e,r)==="-"&&Nn(e,r,t,n)?!0:r)}function zC(e){return Rr(e,"clean",Dn,!0,(t)=>{if(b(e,t)!=="-")return t;if(Nn(e,t,"--fo","rce"))return!0;let n=xr(e,t,Dn);for(let r=t+1;r<n;r++)if(b(e,r)==="f")return!0;return n-1})}function Jo(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=xr(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=HC(e,r,o);r=o;while(V(b(e,r)))r++;if(i)return{commandEnd:xt(e,r,n)?r+n.length:-1,next:xr(e,r,fe)};if(!s)continue;if(r>=te(e)||fe(b(e,r)))return{commandEnd:-1,next:r};r=xr(e,r,fe);while(V(b(e,r)))r++}return{commandEnd:-1,next:r}}function HC(e,t,n){for(let r of De)if(n-t===r.length&&K(e,t,r))return!0;return!1}function BC(e){return od(e,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function $C(e){return Rr(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=sd(e,t,"--fo","rce");if(n>=0&&!K(e,n,"-with-lease"))return!0;return t})}function UC(e){return Rr(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 jC(e){return Rr(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 VC(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=Jo(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=xr(e,o,fe),s=KC(e,o,i);if(n||=s.deletion,r||=s.force,n&&r)return!0;o=i-1}return!1}function KC(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&&qC(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 qC(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function YC(e){return od(e,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function od(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=Jo(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 Rr(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=Jo(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 ZC(e){let t=!1;for(let n=0;n<te(e);n++){if(ua(b(e,n))){if(t)return!0;t=!1;continue}if(!t){let r=Jo(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 id(e,t){let n=!1;for(let r=0;r<te(e);r++){let o=b(e,r),i=t?ua(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 xr(e,t,n){let r=t;while(r<te(e)&&!V(b(e,r))&&!n(b(e,r)))r++;return r}function sd(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 sd(e,t,n,r)>=0}function $e(e,t){Er(t,e,2);let n=e.toLowerCase(),r=n.trimStart(),o=r.startsWith("echo ")||r.startsWith("rg "),i=[{scan:"rm",label:"rm -rf"},{scan:"reset-hard",label:"git reset --hard"},{scan:"reset-merge",label:"git reset --merge"},{scan:"clean",label:"git clean -f"},{scan:"checkout",label:"git checkout --force"},{scan:"push-force",label:"git push --force"},{scan:"push-refspec",label:"git push --force"},{scan:"push-delete",label:"git push delete"},{scan:"branch",label:"git branch -D",caseSensitive:!0},{scan:"tag",label:"git tag -d"},{regex:/\bgit\s+stash\s+(drop|clear)\b/,label:"git stash drop/clear"},{regex:/\bgit\s+checkout\s+--\s/,label:"git checkout --"},{scan:"restore",label:"git restore without --staged"},{scan:"find",label:"find -delete",skipForEchoRg:!0},{regex:/\bdd\b[^\n|;&]*\bof=\/dev\/\S/,label:"dd of=/dev/",skipForEchoRg:!0},{regex:/\bmkfs(?:\.[a-z0-9_-]+)?\s+\/dev\/\S/,label:"mkfs /dev/",skipForEchoRg:!0},{regex:/\bshred\b\s+\S/,label:"shred",skipForEchoRg:!0},{regex:/\b(?:curl|wget|fetch|aria2c|https?|xhs?|ncat|netcat|nc)\b(?:[^\n|;&]|\\\n)*\|(?:\s|\\\n)*(?:(?:sudo|env|command|builtin)(?:\s+(?:-\S+|\w+=\S*))*\s+)?(?:[^\s|;&]*\/)?(?:ba|da|z|k)?sh(?![^\s;&|])/,label:"download piped to shell",skipForEchoRg:!0}];for(let s of i){if(s.skipForEchoRg&&o)continue;let a=s.caseSensitive?e:n;if(s.regex)Ge(t,a);if((s.regex?.test(a)??!1)||s.scan&&Xo(a,s.scan,t))return v("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${s.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var XC=/^[A-Za-z_][A-Za-z0-9_]*=/;function ld(e,t,n){let r=e.words[0];if(!t||!r||e.words.length!==1||e.dialect!=="posix")return!1;if(!r.quoted||r.provenance!=="literal")return!1;let o=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r.text)?.[1];if(!o)return!1;Er(n,t.source,2);let i={anchored:new RegExp(`^\\$\\{?${o}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${o}(?![A-Za-z0-9_])`)};return cd(t.nodes,r,i)}function cd(e,t,n){return e.every((r)=>{if(r.kind==="connector")return!0;if(r.kind==="group"||r.kind==="function")return cd(r.body.nodes,t,n);if(r.kind==="unknown")return!n.loose.test(r.source);return JC(r,t,n)})}function JC(e,t,n){if(e.nested.some((o)=>n.loose.test(o.source)))return!1;let r=e.words.findIndex((o)=>!XC.test(o.text));return e.words.every((o,i)=>o===t||ad(o.raw,n.anchored,i!==r))&&e.redirections.every((o)=>(!o.heredoc||o.heredoc.quotedDelimiter||!n.loose.test(o.heredoc.body))&&(!o.target||ad(o.target.raw,n.anchored,!0)))}function ad(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 wr=require("node:path");function _r(e,t,n,r){let o=wr.isAbsolute(e)?wr.resolve(e):t?wr.resolve(t,e):void 0;if(!o)return;try{return O(o,n,r)}catch{return o}}function ud(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.",Ar="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.",fa=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),QC=new Set(["-p","--print"]),eb=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),tb=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"])]]),nb=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),rb=new Map([["python",new Set(["m"])]]),ob=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"])]]),ib=new Set(["always","default","never"]),sb=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),ab=/\\\r?\n/g,lb=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 dd(e){return ei(e).code}function Qo(e){return ei(e).sources}function md(e){return lb.get(ga(e))??[]}function ei(e){let t=ga(e[0]??"");if(!fa.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"&&QC.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(ub(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(db(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=cb(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(ob.get(t)?.has(s)){let m=e[i+1];if(m===void 0||m.startsWith("-")&&!(t==="ruby"&&sb.has(s))||t==="python"&&!ib.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(rb.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(eb.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(tb.get(t)?.has(d)){if(m+1===s.length)i++;break}if(nb.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 cb(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 pa(e,t){return ga(e)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(t)}function ga(e){let t=k(e).toLowerCase();return Eo.test(t)?"python":t}function ub(e,t){return fa.get(e)?.has(t)??!1}function db(e){return fa.get(e)?.has("--eval")??!1}function Pr(e,t,n=!1){let r=pb(e,t);if(!ma(r,t))return!1;Ge(t,r);let o=fb(r);if(ma(o,t))return!0;if(Ge(t,o),!fd.test(o))return!1;return!n||mb(r,t)}function mb(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)=>fd.test(l[1]??"")).map((l)=>{let c=l.index+l[0].length;return{start:c,end:ha(i,c)}});if(s.some((l)=>ya(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)&&ma(l.text,t)})}function ha(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 ya(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 fd=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function fb(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 ma(e,t){if(Zo(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(Zo(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(Zo(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)=>Xo(o,r))))}function pb(e,t){return Ge(t,e),e.replace(ab,"")}var mi=require("node:fs"),mt=require("node:path");var kr=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 hb(r?t.slice(r.length):t)){if(i===""||i===".")continue;if(i===".."){o=zt.dirname(o);continue}let s=gb(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 gb(e,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${t}`:`${e}${zt.sep}${t}`}function hb(e){let t=process.platform==="win32"?/[\\/]+/:/\/+/;return e.split(t)}var Ca=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],yb=new Set(Ca),Cb=1024,pd=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),gd=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),bb=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ti(e){return yb.has(e)}function ba(e){return ti(e)||pd.has(e)||gd.has(e)||cr(e)}function wt(e,t,n){return n?.has(e)?n.get(e):t.get(e)}function hd(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<=Cb?{state:"valid",count:r}:{state:"invalid"}}function ni(e,t,n){let o=e.match(bb)?.[1];if(!o||!ba(o))return null;let i=e.indexOf("=");return{name:o,value:`${wt(o,t,n)??""}${e.slice(i+1)}`}}function yd(e){return bd(e,gd)}function Cd(e){return bd(e,pd)}function bd(e,t){if(!e)return!1;for(let n of e.keys())if(t.has(n))return!0;return!1}var vd=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ue(e){if(!vd.test(e))return null;let t=e.indexOf("=");return{name:e.slice(0,t),value:e.slice(t+1)}}function ri(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 Ed(e){let t=M(e);return e.includes("=")||t==="sudo"||t==="env"||t==="command"||t==="builtin"}function sn(e,t,n,r){if(!Ed(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=Sd(i),f=ri(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("=")&&!vb(i)){let g=Eb(Wn(i),a,t.env)??ni(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=Rb(i,t.paths,c);if(i=g.words,g.cwd!==void 0)c=g.cwd}if(p==="env"){let g=Ab(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=Pb(i);if(p==="builtin")i=i.slice(et(i,1)==="--"?2:1);if(Sd(i)===d)break}let u=ri(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:Sb(u.words,o)}}function Sb(e,t){return e.some((n)=>!t.has(n))}function Sd(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 vb(e){return vd.test(Wn(e))}function Eb(e,t,n){if(!e.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${t.get("TMPDIR")??n.get("TMPDIR")??""}${e.slice(8)}`}}var xb=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function Rb(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?Tr(o,s,t):null,r+=2;continue}if(i.startsWith("--chdir=")){o=Tr(o,i.slice(8),t),r++;continue}if(i.startsWith("-D")&&i.length>2){o=Tr(o,i.slice(2),t),r++;continue}if(i==="-i"||i==="--login"){o=null,r++;continue}if(xb.has(i)){r+=2;continue}r++}return{words:e.slice(r),cwd:o}}var wb=new Set(["-i","-0","--null"]),_b=new Set(["-u","--unset","-C","--chdir","-P"]);function Ab(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(wb.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(_b.has(c)){if(c==="-C"||c==="--chdir"){let m=et(e,a+1);s=m?Tr(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=Tr(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 Tr(e,t,n){if(t==="")return null;if(!e&&!kr.isAbsolute(t))return null;let r=kr.isAbsolute(t)?kr.parse(t).root:n.realpath(e??"/");if(r===null)return null;try{return Ht(r,t,n)}catch{return null}}function Pb(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 Tb=/['"\\$`{}#]/;function oi(e,t){if(e.some((r)=>Tb.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 ii(e,t,n).tokens}function kb(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=ii(e,t,n),i=(o.envSplitValues??[]).flatMap(kb);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 ii(e,t,n,r){if(!Ed(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 xa=Symbol("adopt-as-operand"),Ib=new Set(["env","sudo","command","builtin"]),Ob=new Set(["&&","||","|&","|","&",";"]),Mb=new Set(["<<","<<<",">|"]),Db=new Set(["|","|&"]),Nb=/[*@#?$!_-]/,Lb=/^\w+(?::\w+)*/,Wb=Object.freeze([]),Ir=Object.freeze({kind:"scope",edge:"enter"}),Or=Object.freeze({kind:"scope",edge:"exit"}),Gb=Object.freeze([]),Fb=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),Mr=new Set(["bash","sh","zsh","dash","ksh"]),zb=256,Ad=new WeakMap;function Pd(e,t){let n=t.status==="complete"?new Set(Ea(t)):new Set,r=$b(e,n);if(Ro(r))return si("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 si("structural-limit",r,t);if(o.invalid)return si("invalid",r,t);let s=si("complete",r,t,o.assignmentFallbacks);return Ad.set(s,Object.freeze(i)),s}function li(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 Td(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=Hb(a,s,n,r),c=a.length>0&&Db.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===xa){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 ci(e){return Td(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 Dr(e){return e.length>0&&e.every((t)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t))}function Hb(e,t,n,r){let o=Dr(e)?new Map([...t.variables,...Bb(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 Bb(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 Td(e){return Ad.get(e)??Wb}function $b(e,t){return[...t].reduce((n,r)=>n.slice(0,r.start)+" ".repeat(r.end-r.start)+n.slice(r.end),e)}function si(e,t,n,r=Gb){return Object.freeze({status:e,source:t,program:n,assignmentFallbacks:Object.freeze(r)})}function an(e,t){return e.nodes.flatMap((n,r)=>Ub(n,e,r,t)).sort((n,r)=>n.start-r.start).flatMap((n)=>[...n.events])}function Ub(e,t,n,r){if(e.kind==="connector")return[{start:e.span.start,events:[tt(Yb(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?[ai("{"),...an(e.body,a),...s?[ai("}")]:[]]:[Ir,tt("("),...an(e.body,a),...s?[tt(")")]:[],Or]}]}let o=Qb(e,r.functions);if(o){if(r.depth>=Ft.maxDepth||++r.flags.expansions>zb)return r.flags.limited=!0,[];return[{start:e.span.start,events:[...xd(e,r),ai(";"),...an(o,{...r,depth:r.depth+1}),ai(";")]},...Rd(e,t,n,r)]}return[{start:e.span.start,events:xd(e,r)},...Rd(e,t,n,r)]}function xd(e,t){return[...e.words.map((n)=>({start:n.span.start,events:Id(n,e,t,!1)})),...e.redirections.map((n)=>({start:n.span.start,events:jb(n,e,t)}))].sort((n,r)=>n.start-r.start).flatMap((n)=>n.events)}function jb(e,t,n){let r=e.operator==="<<-"?"<<":e.operator,o=e.target?Id(e.target,t,n,!0):[],i=o[0],s=i?.kind==="word"?i.text:void 0;return[...e.fd===void 0?[]:[Ra(String(e.fd))],Object.freeze({kind:"redirection",operator:r,...e.fd===void 0?{}:{fd:e.fd},role:Zb(r),targetOrder:Mb.has(r)?"legacy-segment":"immediate",...s===void 0?{}:{target:s},...e.heredoc&&n.suppressed.has(e.heredoc.bodySpan)?{body:e.heredoc.body,consumer:Md(t)}:{}}),...s===void 0?o:o.slice(1)]}function Rd(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=[Ra(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:[...kd(r.source.slice(s.bodySpan.start,s.bodySpan.end),r),...a]}]}),...o.some((i)=>!i.heredoc&&i.target)?Vb(t,n,r):[]]}function Vb(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:kd(n.source.slice(r.span.end,e.span.end),n)}]}function kd(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 Id(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?Ra(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 Sa(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+=Sa(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(Ir,...p,Or);continue}let m=u?an(u,n):[];if(c.raw.startsWith("`")){s+="${}",l(),o.push(Ir,...m,Or);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"}),Ir,...m,...c.raw.endsWith(")")?[tt(")")]:[],Or);continue}let d=c.raw.startsWith("$((")?2:1;s+="${}",l(),o.push(...Array.from({length:d},()=>tt("(")),...d===1?[Ir]:[],...m,...c.raw.endsWith(")".repeat(d))?Array.from({length:d},()=>tt(")")):[],...d===1?[Or]:[])}return l(),o}function Sa(e,t,n,r){let o=[],i="",s=!1,a=0;while(a<e.length){let l=e[a]??"";if(!t.single&&!t.double&&(l==="("||l===")")){o.push({text:i,glob:s},l),i="",s=!1,a++;continue}if(r&&l==="`"&&!t.single){i+=e[a+1]??"",a+=2;continue}if(t.single&&l==="'"){t.single=!1,a++;continue}if(t.single){i+=l,a++;continue}if(t.double){if(l==='"'){t.double=!1,a++;continue}if(!r&&l==="\\"){let c=e[a+1]??"";i+=['"',"\\","$"].includes(c)?c:`\\${c}`,a+=2;continue}if(l==="$"){let c=wd(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=wd(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 wd(e,t,n,r,o){let i=e[t+1];if(i==="{"){let a=qb(e,t+2);if(a===-1)return r.invalid=!0,{text:"",next:e.length};let l=e.slice(t,a+1);return Kb(l,n,r,o),{text:l,next:a+1}}if(i!==void 0&&Nb.test(i))return{text:`\${${i}}`,next:t+2};let s=(o?Lb:/^\w*/).exec(e.slice(t+1))?.[0]??"";return{text:`\${${s}}`,next:t+1+s.length}}function Kb(e,t,n,r){let o=e.slice(2,-1),i=/^[A-Za-z_][A-Za-z0-9_]*/.exec(o)?.[0];if(!i)return;let s=o.slice(i.length),a=[":=","="].find((c)=>s.startsWith(c));if(!a)return;let l=Sa(s.slice(a.length),{...t},n,r);n.assignmentFallbacks.push(...l.flatMap((c)=>typeof c==="string"||!c.text?[]:[c.text]))}function qb(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 Yb(e){return/^[\r\n]+$/.test(e)?";":e}function tt(e){return Object.freeze({kind:"operator",operator:e,boundary:Ob.has(e)})}function ai(e){return Object.freeze({kind:"operator",operator:e,boundary:!0})}function Ra(e){return Object.freeze({kind:"word",text:e})}function Zb(e){if(e==="<<"||e==="<<<")return"here-data";if(e==="<"||e==="<&")return"file-read";return"file-write"}function Nr(e){return Fb.has(e)||/^python\d/.test(e)}var Xb=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 Od(e,t){let n=t[0];if(n===void 0||!n.startsWith("-"))return t;let r=Xb.get(e)?.has(n)??!1;return Od(e,t.slice(r?2:1))}function va(e){let t=e[0];if(t===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(t))return va(e.slice(1));if(!Ib.has(t))return[...e];return va(Od(t,e.slice(1)))}function Md(e){let t=br(e),n=e.words.findIndex((r)=>r.provenance==="literal"&&r.text===t);return va(n<0?[]:e.words.slice(n).map((r)=>r.text))}function Jb(e){let t=Md(e)[0];if(t===void 0)return!1;let n=k(t).toLowerCase();return Nr(n)&&!Mr.has(n)}function Ea(e){return e.nodes.flatMap((t,n)=>{if(t.kind==="group"||t.kind==="function")return Ea(t.body);if(t.kind!=="command")return[];let r=t.nested.flatMap((a)=>Ea(a)),o=t.redirections.flatMap((a)=>a.heredoc?.quotedDelimiter?[a.heredoc.bodySpan]:[]);if(Jb(t))return[...r,...o];let i=e.nodes[n+1];if(i?.kind==="connector"&&(i.operator==="|"||i.operator==="|&")||!tS(t))return r;return[...r,...o]})}function Qb(e,t){let n=br(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 eS(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 tS(e){return(Ut(e.words[0],"cat")||Ut(e.words[0],"tee")||eS(e))&&!e.words.some(_d)&&!e.redirections.some((n)=>_d(n.target))}function _d(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}var Dd=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Nd=new Set([...Dd,"glob"]),nS=new Set([...Nd,"pattern"]);class nt extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Lr(e){let t=rS(),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:oS(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 os(e,t)}function rS(){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=Pd(i,a);return e.set(i,c),c},getCommandProgram:r}}function oS(e){let t=e.route.kind==="grep"?Nd:e.route.kind==="glob"?nS:Dd;return[...uo(e.input,t),...e.route.kind==="patch"||typeof e.input==="string"?mo(e.input):[]]}var iS=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 li(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 ui(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&&iS.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 Wd(e,t,n,r){let o=e.invocation.context.executionCwd;if(!t)return null;if(e.invocation.route.kind==="patch"||e.invocation.route.kind==="path"||e.invocation.route.kind==="unknown"){if(co(e.invocation.toolName))return null;let a=e.paths.find((l)=>Ld(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)=>dS(a,l,t,n,r),isRedirectionTarget:(a,l)=>Ld(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=fi(he(e,t,o,i)),l=a.replace(/(\/\.?\*+)+$/,"");if(l!==a&&l!==""){if(wa(l,n))return!0;let c=s||a.slice(l.length).includes("/."),u=(m)=>c?di(m,l):sS(m,l);if(n.markerFiles.some(u))return!0;return r&&_a(n).some(u)}if(wa(a,n))return!0;return r&&_a(n).some((c)=>di(c,a))}function sS(e,t){let n=mt.relative(t,e);if(n===""||n.startsWith("..")||mt.isAbsolute(n))return!1;return!n.split(/[\\/]/)[0]?.startsWith(".")}function aS(e,t,n,r,o){return ln(e,t,n,!0,r,o)}function lS(e,t,n,r,o){if(!n)return!1;return wa(fi(he(e,t,r,o)),n)}function Ld(e,t,n,r,o,i){let s=fi(he(e,t,r,o));return i.includes(s)||Fd(s,n)}function Gd(e,t,n,r,o){if(!n)return!1;return n.hooksDirectories.some((i)=>e.some((s)=>di(i,fi(he(s,t,r,o)))))}function wa(e,t){return t.entries.includes(e)||t.directories.includes(e)||Fd(e,t)}function Fd(e,t){return t.hooksDirectories.some((n)=>di(e,n))}var cS=50000;function zd(e,t){let n=[...new Set(_a(e))];if(n.some((o)=>t(mt.basename(o))))return!0;let r=0;while(n.length>0){let o=n.pop()??"",i=uS(o);if(!i)return!0;if(r+=i.length,r>cS)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 uS(e){try{let t=mi.lstatSync(e,{throwIfNoEntry:!1});if(!t)return[];if(!t.isDirectory())return t.isSymbolicLink()?null:[];return mi.readdirSync(e,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function _a(e){return[...e.entries,...e.directories,...e.hooksDirectories]}function di(e,t){let n=mt.relative(t,e);return n===""||!/^\.\.(?:[\\/]|$)/.test(n)&&!mt.isAbsolute(n)}function fi(e){return process.platform==="win32"?e.toLowerCase():e}function dS(e,t,n,r,o){if(Dr(e))return null;let i=$t([...e],r);if(k(i[0]??"").toLowerCase()!=="mv")return null;let s=ui(i.slice(1)),a=s.sources.find((l)=>aS(Ae(l,t.variables),t.cwd,n,r,o));if(a)return a;return s.destination&&lS(Ae(s.destination,t.variables),t.cwd,n,r,o)?s.destination:null}var q=require("node:path");var Fe=require("node:path"),mS=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],fS=`
|
|
30
|
+
`;function Wr(e,t){if(jt(e,t))return!0;if(!e.has("TMPDIR"))return!1;return!Aa(e.get("TMPDIR")??"",t)}function cn(e,t){if(e.has("TMPDIR"))return Aa(e.get("TMPDIR")??"",t);let n=Pa(e,t);if(n===void 0)return!0;return Aa(n,t)}function Pa(e,t){return $d(e,t,"TMPDIR")}function Aa(e,t){if(!e)return!1;if(gS(e))return!1;return Fn(e,t)}function jt(e,t){let n=$d(e,t,"IFS");return n!==void 0&&n!==""&&n!==fS}function Fn(e,t){let n=pi(e,t.paths);if(n===null)return!1;return Bd(t).some((r)=>zn(n,r))}function hi(e,t){let n=pi(e,t.paths);if(n===null)return!1;return Bd(t).some((r)=>gi(r)===gi(n))}var Hd=new WeakMap;function Bd(e){let t=Hd.get(e);if(t)return t;let n=pS(e);return Hd.set(e,n),n}function pS(e){let t=mS.map((r)=>pi(r,e.paths)??Fe.normalize(r)),n=pi(e.tmpdir,e.paths);if(!n)return t;if(process.platform==="win32")return[...t,n];if(process.platform==="darwin"&&hS(n))return[...t,n];return t}function gS(e){return/[\s$`*?[]/.test(e)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(e)||/[+@!]\([^)]*\)/.test(e)}function $d(e,t,n){return e.has(n)?e.get(n):t.env.get(n)}function hS(e){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(e)}function pi(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=gi(e),r=gi(t);if(n===r)return!0;let o=r.endsWith(Fe.sep)?r:`${r}${Fe.sep}`;return n.startsWith(o)}function gi(e){return process.platform==="win32"?e.toLowerCase():e}var yS=process.platform==="win32",Ud=64,CS=16384;function Gr(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 Fr(e){let t=Bu(e,Ud,Ud,CS);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:bS(e)}}function bS(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)=>SS(e.raw,n.span.start-e.span.start))}function SS(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:_S(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&&PS(e))return{kind:"outside_anchored_cwd"};let o=!r&&Vd(e,t.posixShell);if(bt(e))return{kind:"outside_anchored_cwd"};if(ka(e,r))return{kind:"root_or_home_target"};if(ES(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(xS(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(AS(e,t,r))return{kind:"temp_target"};let i=t.anchoredCwd;if(i){if(!n.skipHomeCwd&&OS(i,t.environment.home,t.environment.paths,t.budget))return{kind:"home_cwd_target"};if(!n.skipCwdSelf&&[t.resolvedCwd??i,i].some((s)=>MS(e,t.resolvedCwd??i,t.environment.paths,t.budget,s)))return{kind:"cwd_self_target"};if(DS(e,i,t.resolvedCwd??i,o,r,t.environment.paths,t.budget))return{kind:"within_anchored_cwd"}}if(vS(e,t,o))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function vS(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(Ia(r))return!1;if(Kd(t.resolvedCwd,t.anchoredCwd,t.environment.paths,t.budget))return!1;return Fn(q.resolve(t.resolvedCwd,r),t.environment)}function jd(e,t,n={}){let{containmentTarget:r,...o}=n;if(rt(e,t,o).kind!=="temp_target")return!1;let i=e.trim();if(wS(i))return!1;if(hi(i,t.environment))return!1;return![t.anchoredCwd,t.resolvedCwd].some((s)=>Kd(r??i,s,t.environment.paths,t.budget))}function ka(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 ES(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(yS){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 xS(e,t,n,r,o,i,s,a){let l=e.trim();if(Ia(l))return!1;if(!r&&Fn(l,a))return!0;return(t||i&&s)&&n&&!o&&RS(l,n)}function RS(e,t){return["$TMPDIR","${TMPDIR}"].some((n)=>{if(e===n)return!0;if(!e.startsWith(`${n}/`))return!1;return!Vd(e.slice(n.length+1),t)})}function wS(e){let t=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(e);if(!t)return!1;return q.posix.normalize(`/${t[1]??""}`)==="/"}function Ia(e){return e.split(/[\\/]+/).includes("..")}function _S(e,t,n,r){if(!e?.length)return[];return e.flatMap((o)=>{let i=hr(o.trim(),t);if(!q.isAbsolute(i))return[];try{let s=O(i,n,r);if(yr(s,O(t,n,r)))return[];return[Te(s)]}catch{return[]}})}function AS(e,t,n){if(t.allowRoots.length===0)return!1;let r=e.trim();if(Ia(r))return!1;let o=n?r:hr(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 PS(e){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(e)}function Vd(e,t=!1){return e.includes("$")||e.includes("`")||TS(e)||t&&kS(e)}function TS(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 kS(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==="{"&&IS(e,n)||(r==="+"||r==="@"||r==="!")&&e[n+1]==="(")return!0}return!1}function IS(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 OS(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 MS(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 DS(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 Ta(e,t,i,s)}catch{return!1}if(e.startsWith("./")||e.startsWith(".\\")||!e.includes("/")&&!e.includes("\\"))try{return Ta(q.resolve(a,e),t,i,s)}catch{return!1}if(e.startsWith("../"))return!1;try{return Ta(q.resolve(a,e),t,i,s)}catch{return!1}}function Ta(e,t,n,r){try{return qd(O(e,n,r),O(t,n,r))}catch{return!1}}function Kd(e,t,n,r){if(!t)return!1;try{return qd(O(t,n,r),O(e,n,r))}catch{return!0}}function qd(e,t){let n=Te(e),r=Te(t);return n.startsWith(`${r}${q.sep}`)||n===r}var NS=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),Yd="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",LS="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.",Zd="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",Xd="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",WS="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",GS="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",FS={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:Xd},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:je},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:Zd},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:WS},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:Yd},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:LS},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:Yd}};function Jd(e,t,n,r=Vt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths})){return zS(e.words.map((o)=>({kind:"word",text:o.text,dynamic:o.provenance!=="literal"})),t,r,n.policy)}function zS(e,t,n,r){let o=e.filter((l)=>l.kind==="word"),i=BS(o),s=o[i];if(!s||!NS.has(XS(s.text)))return null;let a=HS(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",GS);for(let l of a.targets)if(!bt(l.text)&&ka(Ma(l.text)))return v(a.recursive&&a.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Xd);for(let l of a.targets)if(n.resolvedCwd&&ln(Ma(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",Zd);for(let l of a.targets){let c=Gr(rt(Ma(l.text),n),n,r,FS);if(c)return c}return null}function HS(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($S(l))continue;if(s){t.push(Oa(l)),i=i||l.dynamic;continue}if(l.text==="--"){s=!0;continue}let c=jS(l.text);if(!c){t.push(Oa(l)),i=i||l.dynamic;continue}if(VS(c.name)){let u=c.value?US(c.value,l):e[++a];if(u?.kind==="word"){t.push(Oa(u)),i=i||u.dynamic;continue}i=!0;continue}if(KS(c.name)){n=!0;continue}if(qS(c.name)){r=!0;continue}if(YS(c.name))o=ZS(c.value)}return{targets:t,recursive:n,force:r,whatIfProtected:o,hasDynamicTarget:i}}function BS(e){let t=e[0];if(t?.kind==="word"&&t.text==="&"||t?.text===".")return e.length>1?1:0;return 0}function Oa(e){return{text:e.kind==="word"?e.text:"",dynamic:e.kind==="word"&&e.dynamic}}function $S(e){return e.kind==="word"&&e.text===","}function Ma(e){let t=e.replace(/\\/g,"/"),n=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(t);return n?`$HOME${t.slice(n[0].length)}`:t}function US(e,t){return{kind:"word",text:e,dynamic:t.kind==="word"&&(t.dynamic||e.includes("$"))}}function jS(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 VS(e){return"path".startsWith(e)||"literalpath".startsWith(e)}function KS(e){return"recurse".startsWith(e)}function qS(e){return e.length>=2&&"force".startsWith(e)}function YS(e){return e==="wi"||"whatif".startsWith(e)}function ZS(e){if(e===void 0||e==="")return!0;let t=e.toLowerCase();return t==="$true"||t==="true"}function XS(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.",yi="Unsupported heredoc syntax",zr="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.",Qd="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var JS=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),QS=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),ev=new Set(["-o","--output","--query","--subscription"]),tv=new Set;function em(e){if(e==="aws")return JS;if(e==="gcloud")return QS;if(e==="az")return ev;return tv}var nv=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),rv=new Set;function tm(e){if(e==="git")return De;if(e==="docker")return nv;return rv}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(!sv(n,o.command))continue;if(o.match){if(ov(n,e,o.match))return nm(o);continue}if(!av(n,e,o.subcommand))continue;if(cv(e,new Set(o.block_args),r))return nm(o)}return null}function nm(e){return{id:`custom.${e.name}`,reason:`[${e.name}] ${e.reason}`,intent:e.intent??"manual_only"}}function ov(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 iv(r,n.command_path,em(e))}function iv(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 sv(e,t){return e===M(t)}function av(e,t,n){if(!n)return!0;return rm(t,1,n,tm(e))}function rm(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("=")&&lv(e,i,n,r))return!0;continue}return s===n}return!1}function lv(e,t,n,r){let o=e[t+1];if(!o||o.startsWith("-"))return!1;return rm(e,t+2,n,r)}function cv(e,t,n){return e.some((r)=>t.has(r))||[...n].some((r)=>t.has(r))}var uv=new Set(["-e","--source"]),dv=new Set(["-F","-v","--assign","--field-separator"]),om=new Set(["-f","--file"]),mv=new Set(["print","printf","return"]),im=[{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"}],fv="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 sm(e,t,n){let r=!1;for(let o of pv(e)){let i=gv(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",fv):null}function Na(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&&uv.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&&(dv.has(a)||om.has(a))){let l=e[s+1];if(i&&=l!==void 0,om.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 Br(e){return Na(e).sources}function pv(e){return Br(e).filter((t)=>t.kind!=="program-file").map((t)=>t.value)}function gv(e,t){Ge(t,e);let n=e.includes("system")?La(e,t):null,r=hv(e,t);if(!n&&!r)return null;return{dynamic:!!n?.dynamic||!!r?.dynamic,commands:[...n?.commands??[],...r?.commands??[]]}}function La(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=bi(e,i,s)?.endIndex??i+1;continue}if(s==="#"){i=am(e,i+1);continue}if(s==="/"&&lm(e,i)){i=cm(e,i+1)??i+1;continue}if(!e.startsWith("system",i)){i++;continue}let a=i;if(i+=6,Hr(e[a-1])||Hr(e[i]))continue;let l=Ci(e,i);if(e[l]!=="(")continue;l=Ci(e,l+1);let c=e[l];if(c!=='"'&&c!=="'"){r=!0,o=!0;continue}let u=bi(e,l,c);if(!u){r=!0,o=!0;continue}if(l=Ci(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 hv(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=bi(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=am(e,i+1),s=i,a=null,l=null,c=i;continue}if(u==="/"&&lm(e,i)){let f=cm(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&&(Da(e,i,"print")||Da(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=Ci(e,m);if(Da(e,d,"getline")){o=!0;let f=bv(s,l,c);if(r||=f===null,f!==null)n.push(f);c=m,i=m;continue}if(vv(s,a)){o=!0;let f=Cv(e,d);if(!f){r=!0,c=m,i=m;continue}if(!yv(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 Hr(e){return!!e&&/[A-Za-z0-9_]/.test(e)}function Ci(e,t){let n=t;while(/\s/.test(e[n]??""))n++;return n}function yv(e,t){let n=t;while(/[\t\f\v\r ]/.test(e[n]??""))n++;let r=e[n];return!r||`;
|
|
32
|
+
}#`.includes(r)}function bi(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=Sv(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 Cv(e,t){let n=e[t];if(n!=='"'&&n!=="'")return null;return bi(e,t,n)}function bv(e,t,n){if(!t)return null;return t.startIndex>=e&&t.endIndex===n?t.value:null}function Sv(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 Da(e,t,n){return e.startsWith(n,t)&&!Hr(e[t-1])&&!Hr(e[t+n.length])}function vv(e,t){return t!==null&&t>=e}function am(e,t){let n=e.indexOf(`
|
|
34
|
+
`,t);return n===-1?e.length:n+1}function lm(e,t){let n=Ev(e,t);if(n===-1)return!0;if("{([,;!~=".includes(e[n]??""))return!0;let r=n;while(Hr(e[r-1]))r--;return mv.has(e.slice(r,n+1))}function Ev(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function cm(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 xv=new Set(["sudo","env","command","builtin"]);function Si(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=Rv(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 Rv(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&&wv(a,r);if(l)i.push(s);if(!l&&xo.has(M(a)))break;if(o)break}return i}function wv(e,t){let n=k(e),r=M(e);return r==="git"||n==="busybox"||un(e)||Rs.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 xv.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 vi([...e],t.environment,t.cwd,t.cwd,new Map,new Map(t.envAssignments??[]),n,{iterations:0},!1)}function*vi(e,t,n,r,o,i,s,a,l){let c=ii(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=oi(c.envSplitValues,u);if(!f)throw new N("derivedCommandShape");Wa(a),yield*vi(f,t,m,r,o,i,s,a,l);return}if(un(u[0]??""))throw new N("wrapperPeelIterations");let d=Si(u,s);if(d){for(let f of[d.childIndex,...d.alternativeChildIndices])Wa(a),yield*vi(f===d.childIndex?d.tokens:u.slice(f),t,m,r,new Map(o),new Map(i),s,a,!0);return}if(Av(u)){Wa(a),yield*vi(u.slice(1),t,m,r,o,i,s,a,l);return}yield _v(u,m,r,o,i,l)}function _v(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 Wa(e){if(e.iterations>=X.wrapperPeelIterations.cap)throw new N("wrapperPeelIterations");e.iterations++}function Av(e){return k(e[0]??"").toLowerCase()==="busybox"&&e.length>1}function Ga(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"||Fa(r,"recursive")){t=!0;continue}if(r==="-f"||Fa(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 Ei(e){let t=e.indexOf("--");return e.slice(1,t===-1?void 0:t).some((n)=>Fa(n,"recursive")||/^-[A-Za-z]+$/.test(n)&&/[rR]/.test(n.slice(1)))}function Fa(e,t){return e.length>2&&e.startsWith("--")&&t.startsWith(e.slice(2))}var Pv=["--init-file","--rcfile"],Tv=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 um(e,t,!0);if(n.startsWith("-")&&n.includes("c")&&!n.startsWith("--")){let r=um(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 um(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 dm(e){let t=k(e[0]??"").toLowerCase(),n=kv(e,t),r=Tv.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 kv(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?Pv.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"&&Es.has(m)&&!l.includes("="))a++;continue}if(t==="bash")s=!1;let c=xs(t,l,e[a+1],"startup");if(c.interactive)i=l[0]==="-";a+=c.followingValues}return{argvSource:o.at(-1)??null,interactive:i}}var Iv="find -delete permanently removes files. Use -print first to preview.",Ov="find -exec rm -rf is dangerous. Use explicit file list instead.",Mv=new Set(["-exec","-execdir","-ok","-okdir"]),Dv=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 mm(e,t){let n=e.map(_),r=Nv(e,n,t);if(r)return r;if(xi(n,1)&&!Hv(e,n,t)){let s=T(v("find.delete",Iv),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=$v(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 Nv(e,t,n){if(!xi(t,1)&&!za(t,n.environment))return null;let o=$r(e)??J(["."]),i=Vt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let s of o){let a=Fr(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"&&!Lv(e,i.protectedGitMetadata,n.environment))return v("find.delete-git-metadata",je)}}if(zv(t)&&i.resolvedCwd&&Gd(o.map(_),i.resolvedCwd,i.protectedGitMetadata,i.environment,i.budget))return v("find.delete-git-metadata",je);return null}function Lv(e,t,n){if(!t)return!1;let r=e.map(_),o=[],i=!1,s=$r(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=Ei(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(Gv(c.text,l==="-iname"));a+=2;continue}if(!Wv.has(l))return!1;a+=1+Tt(l)}return o.length>0&&!zd(t,(l)=>o.every((c)=>c.test(l)))}var Wv=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function Gv(e,t){let n=e.replace(/[*?]|[.+^${}()|\]/]/g,(r)=>r==="*"?".*":r==="?"?".":`\\${r}`);return new RegExp(`^${n}$`,t?"isu":"su")}var Fv=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function za(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)&&Fv.test((st(o)??"").replace(/["'\\]/g,""));if((i==="rm"||i==="rmdir"||s)&&o.some((l)=>l.includes("{}")))return!0;n=r.nextIndex}return!1}function zv(e){return e.some((t,n)=>{if(!["-name","-iname"].includes(t))return!1;return e[n+1]?.toLowerCase()==="hooks"})}function Hv(e,t,n){if(t.includes("-L")||t.includes("-f")||t.includes("-follow"))return!1;let r=$r(e);if(!r)return!1;let o=n.envAssignments??new Map,i=Pa(o,n.environment),s=n.trustedTmpdirValue??cn(o,n.environment),a=n.allowTmpdirVar??!Wr(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=Fr(p);if(g.unsafeBraceExpansion)return!1;return(g.expandedTargets??[_(p)]).every((h)=>{let y=/^\.\/*$/.test(h)?f:void 0,S=y??h;return jd(S,y?u:c,{containmentTarget:Bv(S,i),targetIsLiteral:g.expandedTargets!==void 0||g.targetIsLiteral,tmpdirWordSplittingProtected:g.tmpdirWordSplittingProtected})})})}function Bv(e,t){if(!t)return e;return e.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>t)}function $r(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 $v(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",Ov);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 xi(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 Dv.get(e)??(/^-newer[A-Za-z]{2}$/.test(e)?1:0)}function ft(e){return e!==void 0&&Mv.has(e)}var Lm=require("node:path");function Ur(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 Uv=5,Ha="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 pm(e,t,n){let r=Ri(e,t,n),o=jv(r.entries);if(o.size===0)return{blockedReason:r.blockedReason,expanded:!1,tokens:e};let i=e,s=!1;for(let a=0;a<Uv;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=Zv(m);if(d===null||d.length===0)return{blockedReason:Ha,expanded:!0,tokens:i};i=["git",...d,...c],s=!0}return{blockedReason:Ha,expanded:!0,tokens:i}}function gm(e,t,n){return Ri(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 jv(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 Ri(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=Kv(t,n);return{blockedReason:i.blockedReason,entries:[...i.entries,...Vv(e,t,n)]}}function Vv(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=Ba(e[o+1]);if(s)r.push(s);o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=Ba(i.slice(2));if(s)r.push(s);o++;continue}if(i==="--config-env"){let s=fm(e[o+1],t,n);if(s)r.push(s);o+=2;continue}if(i.startsWith("--config-env=")){let s=fm(i.slice(13),t,n);if(s)r.push(s);o++;continue}if(De.has(i)){o+=2;continue}o++}return r}function Kv(e,t){let n=qv(e,t),r=Yv(e,t);return{blockedReason:n===null||r===null?Ha:null,entries:[...n??[],...r??[]]}}function qv(e,t){let n=wt("GIT_CONFIG_PARAMETERS",e,t);if(n===void 0)return[];let r=[],o=Ur(n);if(!o)return null;for(let i of o){let s=Ba(i);if(!s)return null;r.push(s)}return r}function Yv(e,t){let n=hd(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 Ba(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 fm(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 Zv(e){let t=e?.trimStart();if(!t||t.startsWith("!"))return null;return Ur(t)}var Xv="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",Jv="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",Qv="git checkout --force discards uncommitted changes. Use 'git stash' first.",eE="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",tE="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",nE="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",rE="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",oE="git switch --force discards uncommitted changes. Use 'git stash' first.",iE="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",sE="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",aE="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",lE="git reset --merge can lose uncommitted changes. Use 'git stash' first.",cE="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",uE="git rm --force removes tracked files from the working tree. Use 'git rm --cached' to keep the files, or 'git rm --dry-run' to preview first.",dE="git push --force destroys remote history. Use --force-with-lease for safer force push.",mE="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",fE="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",pE="git branch -D force-deletes without merge check. Use -d for safe delete.",gE="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",hE="git merge --abort discards merge conflict resolutions. Use 'git status' first.",yE="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",CE="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",bE="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",SE="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",vE="git worktree remove --force can delete uncommitted changes. Remove --force flag.",EE=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),xE=new Set(["--recurse-submodules","--track","-t"]),$a=new Set(["-b","-B","-U"]),Ua=new Set(["-c","-C"]),RE=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 ym(e,t){let{subcommand:n,rest:r}=ze(e);if(!n)return null;switch(n.toLowerCase()){case"checkout":return Kt(wE(r,t));case"switch":return Kt(AE(r));case"restore":return Kt(TE(r));case"reset":return IE(r);case"clean":return Kt(ME(r));case"rm":return Kt(DE(r));case"push":return mn(NE(r));case"branch":return mn(GE(r));case"stash":return mn($E(r));case"worktree":return mn(UE(r));case"rebase":return Kt(FE(r));case"merge":return Kt(zE(r));case"tag":return mn(HE(r));case"reflog":return mn(BE(r));default:return null}}function Kt(e){return e?{...e,localDiscard:!0}:null}function mn(e){return e?{...e,localDiscard:!1}:null}function wE(e,t){let{index:n,before:r}=pe(e),o=we(r,{shortOptsWithValue:$a});if(r.some((a)=>D(a,"--force"))||o.has("-f"))return v("git.checkout-force",Qv);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",tE)}if(n!==-1){if(r.some((l)=>!l.startsWith("-")))return v("git.checkout-ref-path",eE);return v("git.checkout-double-dash",Xv)}let i=PE(e);if(i.length>=2)return v("git.checkout-ambiguous",nE);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(_E(s)||t(s))return v("git.checkout-double-dash",Jv);return null}function _E(e){return e==="."||e===".."||/^\.\.?[/\\]/.test(e)||/^([/\\]|[A-Za-z]:[/\\])/.test(e)||e.endsWith("/")||e.startsWith(":")||/[*?[]/.test(e)}function AE(e){let{before:t}=pe(e);if(t.some((r)=>D(r,"--discard-changes")))return v("git.switch-discard-changes",rE);let n=we(t,{shortOptsWithValue:Ua});if(t.some((r)=>D(r,"--force"))||n.has("-f"))return v("git.switch-force",oE);return null}function PE(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(EE.has(r)){n+=2;continue}if(xE.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 TE(e){let t=kE(e);if(t.isTerminal||!t.hasPathspec&&!t.hasPatch||!t.hasWorktree)return null;return t.hasExplicitLocation?v("git.restore-worktree",sE):v("git.restore-unstaged",iE)}function kE(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(RE.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 IE(e){let t=null;for(let n of e){if(D(n,"--hard")){t=v("git.reset-hard",aE);break}if(D(n,"--merge")){t=v("git.reset-merge",lE);break}}if(!t)return null;return OE(e)?mn(t):Kt(t)}function OE(e){for(let t of e){if(t==="--")return!1;if(!t.startsWith("-"))return!0}return!1}function ME(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",cE);return null}function DE(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",uE):null}function NE(e){let{before:t,after:n}=pe(e),r=we(t);if(t.some((s)=>D(s,"--mirror")))return v("git.push-mirror",fE);if(t.some((s)=>D(s,"--force"))||r.has("-f")||hm(t,n).some(LE))return v("git.push-force",dE);if(t.some((s)=>D(s,"--delete"))||r.has("-d")||hm(t,n).some(WE))return v("git.push-delete",mE);return null}function hm(e,t){return[...e.filter((n)=>n!==""&&!n.startsWith("-")),...t]}function LE(e){return e.startsWith("+")||e.includes(":+")}function WE(e){return e.length>1&&e.startsWith(":")}function GE(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",pE);return null}function FE(e){let{before:t}=pe(e);return t.some((n)=>D(n,"--abort"))?v("git.rebase-abort",gE):null}function zE(e){let{before:t}=pe(e);return t.some((n)=>D(n,"--abort"))?v("git.merge-abort",hE):null}function HE(e){let{before:t}=pe(e);return we(t).has("-d")||t.some((r)=>D(r,"--delete"))?v("git.tag-delete",yE):null}function BE(e){return e[0]==="delete"?v("git.reflog-delete",CE):null}function $E(e){for(let t of e){if(t==="drop")return v("git.stash-drop",bE);if(t==="clear")return v("git.stash-clear",SE)}return null}function UE(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",vE);return null}var kt=require("node:path");var Va="TMPDIR",Ka="IFS",bm=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,Sm=/^[A-Za-z_][A-Za-z0-9_]*$/,vm=new Set(["export","typeset","declare","readonly"]),jE=new Set(["builtin","command","time"]),Em=new Set(["do","then","else"]),VE=new Set(["do","then","case"]),Cm=new Set(["done","fi","esac"]),KE=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function xm(e,t){return e.map((n)=>n.provenance==="variable"&&km(n.text)?Rm(n.text,t.shellAssignments):_(n))}function Rm(e,t){return e.replace(KE,(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=Rm(e.text,t);return/^[~-]/.test(r)||/[\s$`*?[]/.test(r)?null:r}function wm(e,t){return{env:e,effectiveEnvAssignments:XE(e,t),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function _m(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 qa(e,t){let n=Pm(e,t),r=e[0]??"";if(VE.has(r))t.bodyDepth+=1;if(r==="elif"||Cm.has(r))t.bodyDepth=Math.max(0,t.bodyDepth-1);if(Cm.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);Ya(t,a)});let o=n.commandIndex;if(o!==-1&&vm.has(e[o]??""))e.filter((a)=>Sm.test(a)&&ja(a)).forEach((a)=>{JE(t,a)});let i=o===-1?-1:Tm(e,o);if(i===-1||e[i]!=="unset")return;let s=ex(e,i);if(s===null)return;e.slice(s).forEach((a)=>{if(Em.has(r)){t.shellAssignments.set(a,"");return}QE(t,a)})}function Am(e,t){let n=Pm(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 Pm(e,t){let n=Em.has(e[0]??"")?1:0,r=e.findIndex((a,l)=>l>=n&&!km(a)),o=r!==-1&&vm.has(e[Tm(e,r)]??""),i=ZE(t);return{assignments:e.flatMap((a,l)=>{let c=qE(a,i,t.env);if(!c)return[];if(r!==-1&&l>r&&!o&&!ti(c.name))return[];return i.set(c.name,c.value),[{...c,persists:r===-1||o}]}),commandIndex:r}}function Tm(e,t){let n=t;while(jE.has(e[n]??"")){n+=1;while(e[n]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(e[n]??""))return t;n+=1}}return n}function km(e){return Ue(e)!==null||bm.test(e)}function qE(e,t,n){return Ue(e)??YE(e,t,n)}function YE(e,t,n){let r=ni(e,n,t);if(r)return r;let o=e.match(bm)?.[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 ja(e){return e===Va||e===Ka||ba(e)}function ZE(e){return new Map([...e.effectiveEnvAssignments??[],...e.shellAssignments])}function XE(e,t){let n=[Va,Ka].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 Ya(e,t){let n=new Map(e.effectiveEnvAssignments??[]);n.set(t.name,t.value),e.effectiveEnvAssignments=n}function JE(e,t){Ya(e,{name:t,value:e.shellAssignments.get(t)??e.effectiveEnvAssignments?.get(t)??e.env.get(t)??""})}function QE(e,t){if(!ja(t)&&!Sm.test(t))return;if(e.shellAssignments.set(t,""),ti(t)&&e.env.has(t)){let r=new Map(e.env);r.delete(t),e.env=r}if(!ja(t)||t===Va||t===Ka||cr(t)){Ya(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 ex(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 Om=require("node:path");function wi(e,t){return Ca.some((n)=>t?.has(n)||e.has(n))}function Un(e,t,n){if(!t)return{gitCwd:null,hasExplicitGitContext:!1};let r=n.realpath(Om.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=Im(o,l,n);if(!c)return{gitCwd:null,hasExplicitGitContext:i};o=c,s+=2;continue}if(a.startsWith("-C")&&a.length>2){let l=Im(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 Im(e,t,n){try{let r=Ht(e,t,n);return n.isDirectory(r)?r:null}catch{return null}}function Mm(e,t,n){if(!t.localDiscard||!n.worktreeMode||wi(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(Za(e,n,o))return null;return{kind:"worktree",originalReason:t.reason,gitCwd:r.gitCwd}}function Za(e,t,n){let{subcommand:r,rest:o}=ze(e),i=r?.toLowerCase();if(t.dynamicArguments||tx(o)||sx(e,t.environment.env,t.envAssignments,n)||ox(o)||nx(i,o))return!0;return i==="clean"&&ix(o)>1}function tx(e){return e.some((t)=>/[$*?[]/.test(t))}function nx(e,t){if(e==="checkout"){let{before:n}=pe(t),r=we(n,{shortOptsWithValue:$a}),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:Ua}),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")||rx(s))||r.has("-C");return o&&i}return!1}function rx(e){let t=e.split("=",1)[0]??e;return t==="--force-create"||t.length>=9&&"--force-create".startsWith(t)}function ox(e){return e.some((t)=>t.startsWith("--recurse-sub"))}function ix(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 sx(e,t,n,r){if(wt("GIT_CONFIG_PARAMETERS",t,n)!==void 0)return!0;let o=Ri(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)=>lx(a.key)))return!0;let s=i.filter((a)=>a.key==="submodule.recurse").at(-1);if(s)return s.value===void 0||ax(s.value);if(Cd(n))return!0;return r.recursiveSubmodules}function ax(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function lx(e){return e==="include.path"||e.startsWith("includeif.")&&e.endsWith(".path")}function Dm(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||wi(n.environment.env,n.envAssignments))return null;let a=t.id==="git.worktree-remove-force"?ux(e,n.shellAssignments,o):Nm(i.gitCwd,o);if(a===null||t.id!=="git.worktree-remove-force"&&!cx(a,r,t,n)||!Fn(a,n.environment)||hi(a,n.environment)||zn(s,a)||zn(a,s))return null;return{kind:"temp-root",originalReason:t.reason,gitCwd:i.gitCwd}}function cx(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&&!Za(t,r,a)}function ux(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 Nm(e,t){if(t.entryKind(kt.join(e,".git"))!=="missing")return e;let n=kt.dirname(e);return n===e?null:Nm(n,t)}var dx="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.",mx=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function _i(e,t){return Wm(e,t)}function Wm(e,t,n){let r=e.map(_),o=pm(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((yd(t.envAssignments)||gm(r,t.environment.env,t.envAssignments))&&fx(s))return v("git.ssh-env",dx);let a=ym(s,(c)=>{let u=Un(r,t.cwd,t.environment.paths).gitCwd;return u!==null&&t.environment.paths.entryKind(Lm.resolve(u,c))!=="missing"});if(!a)return null;if(o.expanded||o.blockedReason)return a;let l=Mm(r,a,t)??Dm(e,a,t);if(!l)return a;return n?.(l),null}function Gm(e,t){let n=null;return{match:Wm(e,t,(o)=>{n=o}),relaxation:n}}function fx(e){let{subcommand:t,rest:n}=ze(e),r=t?.toLowerCase();if(!r)return!1;if(mx.has(r))return!0;if(r==="archive")return pe(n).before.some((o)=>D(o,"--remote"));return r==="remote"&&px(n)}function px(e){return e.find((t)=>!gx(t))?.toLowerCase()==="update"}function gx(e){return e==="-v"||D(e,"--verbose")||D(e,"--no-verbose")}var hf=require("node:path");function Fm(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 Ai(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 zm="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",hx="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.",yx="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",Bm="rm -rf targeting root or home directory is extremely dangerous and always blocked.",Cx="rm -rf in home directory is dangerous. Change to a project directory first.",Hm={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:Bm},git_metadata_target:{id:"rm.git-metadata",reason:je},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:yx},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:Cx},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:zm},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:hx},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:zm}};function Pi(e,t){let n=Vt({...t,allowPaths:t.policy?.destructiveCommandAllowPaths,posixShell:!0}),r=e.map(_),o=it(r),i=Ei(r),s=Sx(e);for(let a of s){let l=Fr(a.word);if(o&&l.unsafeBraceExpansion){let c=T(Gr({kind:"outside_anchored_cwd"},n,t.policy,Hm),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",Bm);if(d.kind==="git_metadata_target")return v("rm.git-metadata",je);continue}if(!o)continue;for(let d of bx(u,n,m)){let f=Gr(d,n,t.policy,Hm),p=T(f,t.policy);if(p)return p}}}return null}function bx(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 Sx(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"},vx=new Set(["<","<<","<<-","<<<","<&","<>"]),Um=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,Ex=/^(?:[0-9]+|[@*])$/,xx=Ft.maxWords,jm=Ft.maxInputLength;function Vm(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
|
|
39
|
-
`}}function
|
|
38
|
+
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function Ti(e){let t=jn(e[1])==="--"?2:1;if(e.length<=t)return qt;let n=e.slice(t);if(!n.every(Vr))return fn;return{kind:"literal",source:n.map(_).join(" ")}}function Km(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(!Vr(n))return fn;return{kind:"literal",source:r}}function ki(e,t){let n=Zm(e);if(n===-1)return qt;let r=wx(t);if(!r)return qt;let o=[],i=r.command?.length??0;for(let s of r.references){let a=Ax(s,e,n,r.ifs);if(!a)return fn;if(i+=a.reduce((l,c)=>l+c.length+3,0),o.length+a.length>xx||i>jm)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(Xm)].filter((s)=>s!==null).join(" ")}}function qm(e,t){let n=Zm(e),r=e.slice(n+1),o=/\bIFS\b/.test(t);if(n===-1||!r.every(Vr)||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?Xm(g):"").join(" ")).join(" "),s.length>jm)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 Ym(e,t,n,r){if(!Ne(e.map(_)).readsStdinAsCommands)return qt;let o=t.filter((i)=>(i.fd===void 0||i.fd===0)&&vx.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(Yo(r,o))return{kind:"literal",source:o};let i=r?pt(r,t):null;return i===null?fn:{kind:"literal",source:i}}var Rx=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function el(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!Rx.has(a)&&!Q.has(a)&&!un(a)}function Zm(e){return Ne(e.map(_)).commandIndex??-1}function wx(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(_x);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 _x(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 Ax(e,t,n,r){let o=t.slice(n+2);if(e.parameter==="@")return e.quoted?Xa(o):Px(o,r);if(e.parameter==="*"){let a=Xa(o);if(!a)return;let l=a.join(r[0]??"");return e.quoted?[l]:Ja(l,r)}let i=t[n+1+e.parameter];if(i&&!Vr(i))return;let s=jn(i);return e.quoted?[s]:Ja(s,r)}function Xa(e){return e.every(Vr)?e.map(_):void 0}function Px(e,t){let n=Xa(e);if(!n)return;let r=n.map((o)=>Ja(o,t));return r.some((o)=>o===void 0)?void 0:r.flatMap((o)=>o??[])}function Ja(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 Vr(e){if(!e)return!0;return e.provenance==="unknown"?!/[$`]/.test(_(e)):e.provenance==="literal"}function jn(e){return e?_(e):""}function Xm(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function tl(e,t){return Qa(Je(e,"posix"),t)}function Kr(e){return tl(e,new Set(Array.from(e.matchAll(Um)).flatMap((t)=>{let n=t[1]??t[2];return n===void 0?[]:[n]})))}function Qa(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(Qa(r.body,n))return!0;continue}if(r.kind!=="command")continue;if(r.nested.some((o)=>Qa(o,n))||Jm(r.words,n))return!0;Mx(r,n)}return!1}function Jm(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(jr(r,t))return!0;let o=M(r.text);if(o==="source"||o==="."){let s=e[n+1]?.text==="--"?n+2:n+1;return $m(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&&$m(s[l],t)}let i=Tx(e,n,t);if(i===null)return!1;if(i===-1)return!0;return Jm(e.slice(i),t)}function Tx(e,t,n){let r=M(e[t]?.text??"");if(r==="command")return kx(e,t+1);if(r==="exec")return Ix(e,t+1);if(r==="env")return Ox(e,t+1,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(/^-[p]*[vV][pvV]*$/.test(r))return null;if(/^-p+$/.test(r))continue;return n}return null}function Ix(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 Ox(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 jr(e[r+1],n)?-1:r+2;if(i.startsWith("-S")||i.startsWith("--split-string="))return jr(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 Mx(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(jr(n,t))t.add(r.name)}}function jr(e,t){if(!e)return!1;return e.parts.filter((n)=>n.provenance==="variable").some((n)=>Array.from(n.raw.matchAll(Um)).some((r)=>{let o=r[1]??r[2];return o!==void 0&&(Ex.test(o)||t.has(o))}))}function $m(e,t){return!!e&&(e.parts.some((n)=>n.provenance!=="literal"&&n.provenance!=="variable")||jr(e,t))}var nl="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",rl="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",Dx="__CC_SAFETY_NET_XARGS_INPUT__",Ii="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",Oi="rm",Nx=/(?:^|[;&|]\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,Lx=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,Wx=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,Gx=/^(?:[0-9]+|[@*])$/;function tf(e,t){let n=e.map(_),{childStart:r,replacementToken:o}=pn(n),i=n.slice(r),s=v("xargs.shell-dynamic",rl);if(zx(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=lf(l,o,a.wrapperEnvAssignments),m=a.head==="rm"&&o!==null&&sf(l,o),d=t.analyzeChild(l,{...dn(a,t),dynamicInput:u,dynamicSourceInput:m||rf(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",nl)});if(d)return d;let f=Fx(l,o,t.policy?.rules??[],T(s,t.policy));if(f)return f;if(a.head==="git"){let g=o===null?[...l,Dx]: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 Fx(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 nf(e,t,n){let r=e.indexOf(t);if(r===-1||e.indexOf(t,r+t.length)!==-1)return[];let o=Fm(e,r,t.length,n);return o===null?[]:[o]}function rf(e,t,n,r,o,i,s){if(Q.has(t)){if(Pt(e))return!1;if(n!==null&&Hx(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)&&!of(a,n,s))return!0;if($e(a))return!0;return Bx(a,n,r)}if(Xe(t))return Qm(e,n,ei,md(t));if(Be.has(t))return Qm(e,n,Na,im);if(t==="eval"){let a=Ti(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 $x(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())&&af(a.rest,n).some((l)=>l.includes(n))}return!1}function of(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 Qm(e,t,n,r){let o=n(e);if(t===null)return o.optionsOpen||n([...e,Ii]).sources.some((a)=>a.value===Ii);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}${Ii}`]:[],...a.valueForm==="equals-or-separate"?[`${a.selector}=${Ii}`]:[]]),s=new Set(i.flatMap((a)=>e.flatMap((l)=>nf(l,t,a))));return Ai(o.sources,s,(a)=>n(e.map((l)=>l.replaceAll(t,a))).sources)}function zx(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,Oi]:e.map((i,s)=>s===0?i:i.replaceAll(t,Oi));return Array.from(ot(o,n)).some((i)=>i.head===Oi&&!r.has(Oi))}function sf(e,t){return af(e.slice(1),t).some((n)=>n.includes(t)&&(n.startsWith("-")||n.startsWith(t)))}function af(e,t){let n=e.findIndex((r)=>r==="--"&&!r.includes(t));return n===-1?e:e.slice(0,n)}function lf(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 Hx(e,t,n){let r=Ne(e),o=r.commandIndex===null?"":e[r.commandIndex]??"";if(o.includes(t)&&!of(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 nf(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 Bx(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(Nx))if(ef(o,r))return!0;for(let o of e.matchAll(Lx))for(let i of(o[1]??"").matchAll(Wx))if(ef(i,r))return!0;return tl(e,r)}function ef(e,t){let n=e[1]??e[2];return n!==void 0&&(Gx.test(n)||t.has(n))}function $x(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=lf(c.tokens,t,c.wrapperEnvAssignments);if(c.head==="rm"&&sf(c.tokens,t)||rf(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 qr="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",Yr="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",Ux="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",jx="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Di=/\{[^{}\s]*\}/g,cf=/\{\}|\{-?\d+\}/g,Vx=["e","f","source","file","-e","-f","--source","--file"],Kx=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],qx=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),Yx=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),uf=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),Zx=new Set(["--workdir","--wd"]),df="__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 yf(e){return Ve([...e],(t)=>$e(t))}function Cf(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=Af(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=yf(t.envAssignments?.values()??[]);if(g)return g}if(l){let p=nR(t);if(p)return p}if(u!==void 0&&a){let p=Vn(t);if(p)return p}let d=rR(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(sl)){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=Ef(f.envAssignments,f.cwd,a);return Ve(p,(h)=>t.analyzeNested(h,g))}return Ve(ot(i,f),(p)=>Xx(p,o,t,f))}function Xx(e,t,n,r){let{jobs:o,templateHasPlaceholder:i,runsRemotely:s,usesStdin:a}=t,l=e.tokens,c=[...e.envAssignments.values()];if(c.some(wf)){let h=Vn(n);if(h)return h}let u=yf(c);if(u)return u;let m=c.some(B),d=i||m,f=a&&d,p=Ef(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(Mi(l,E,n.budget),dn(e,r)))};if(Pt(l))return h();let y=st(l);if(y){if(_f(y)){let x=Yt(n);if(x)return x;if(o.length===0)return null;return Ve(o,(A)=>n.analyzeNested(pf(y,A,n.budget),p))}if(B(y)){if(o.length>0)return Ve(o,(ee)=>n.analyzeNested(pf(y,ee,n.budget),p));let x=Ur(y);if(x?.[0]&&M(x[0])==="rm"&&it(x)){let ee=ff(n);if(ee)return ee}let A=x?n.analyzeChild(x,{...dn(e,r),dynamicInput:a,shellDynamicMatch:v("parallel.shell-dynamic",Yr),rmDynamicMatch:v("parallel.rm-recursive-force-dynamic",qr)}):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)=>ki(J(x===void 0?l:i?l.map((A)=>xf(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(Kr(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)=>ol(Mi(l,y,n.budget,cf),e.cwd,r));if(o.length>0)return Ve(o,(y)=>ol(gf(l,y,n.budget),e.cwd,r));let h=ol(l.flatMap((y,S)=>{if(S===0||!B(y))return[y];return y.startsWith("-")?[y.replace(cf,"")]:[]}),e.cwd,r);if(h)return h;return ff(n)}let g=o.length>0?o:[void 0];return Ve(g,(h)=>{let y=h===void 0?l:i?Mi(l,h,n.budget):gf(l,h,n.budget),S=v("parallel.shell-dynamic",Yr),E=a&&e.head==="find"?tR(y,r):null,C=Sf(y,a,n)??E?.customResult??null,P=M(e.head),x=a&&(P==="rm"&&il(y)||P==="xargs"&&vf(y)||E?.rmOptions===!0),A=a&&(x||E?.executedSource===!0||E===null&&bf(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",qr)});if(A){let qe=T(S,n.policy);if(qe)return qe}return ee??C??At(y,n.policy?.rules??[])})}function bf(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 eR(e);if(t==="git")return Jx(e);if(t==="find")return!0;if(Be.has(t))return mf(e,Vx,Br);if(Xe(t))return mf(e,Kx,Qo);return!1}function il(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("-")||_f(o)))}function Jx(e){if(Qx(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 Qx(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 eR(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 mf(e,t,n){let r=n(e);if(r.some((o)=>B(o.value)))return!0;if(!e.some(B))return n([...e,df]).some((o)=>o.value===df);return Ai(r,t,(o)=>n(e.map((i)=>xf(i,[o]))))}function Sf(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 tR(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||=bf(a.tokens,a.head),n.rmOptions||=a.head==="rm"&&il(a.tokens)||a.head==="xargs"&&vf(a.tokens),n.customResult??=Sf(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 vf(e){let t=e.slice(pn(e).childStart);return M(t[0]??"")==="rm"&&il(t)}function Ni(e,t){return(n)=>T(v(e,t),n.policy)}var Yt=Ni("parallel.shell-dynamic",Yr),nR=Ni("parallel.command-stream-dynamic",Ux),Vn=Ni("parallel.command-stream-dynamic",jx),ff=Ni("parallel.rm-recursive-force-dynamic",qr);function ol(e,t,n){return T(Pi(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 Ef(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 xf(e,t){return e.replace(Di,(n)=>Rf(n,t))}function Mi(e,t,n,r=Di){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=Rf(i,t);return n.charge("derivedTokens",Math.max(1,Math.ceil(s.length/64))),s}))}function pf(e,t,n){return Mi([e],t,n)[0]??""}function gf(e,t,n){return n.charge("derivedTokens",e.length+t.length),[...e,...t]}function Rf(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(Di)!==-1}function wf(e){if(sl(e))return!0;for(let t of e.matchAll(Di))if(!/^(?:\{\}|\{\d+\})$/.test(t[0]))return!0;return!1}function sl(e){let t=e.indexOf("{=");return t!==-1&&e.indexOf("=}",t+2)!==-1}function _f(e){return/^\{[^{}\s]*\}$/.test(e)}function rR(e,t,n){if(e===void 0)return;if(e==="..."||/^~|[{}$`*?[]/.test(e))return null;if(!t&&!hf.isAbsolute(e))return null;try{return Ht(t??e,e,n)}catch{return null}}function Af(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=Ga(e,t+1);n.push(...E.templateTokens),r=t+1,o=E.markerIndex;break}if(!p.startsWith("-")){let E=Ga(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"||Yx.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(uf.has(y)||p.startsWith("-S")&&p.length>2){i=!0,t+=uf.has(p)?2:1;continue}if(Zx.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(qx.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?sl:wf);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=oR(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 oR(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 Pf(e){return Af(e).childStart}var iR="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",Li="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function ll(e){return e?.parts.some((t)=>t.provenance==="command-substitution")??!1}function al(e){return e?.parts.some((t)=>t.provenance==="literal"&&t.raw.replace(/^["']/,"").startsWith("-"))??!1}function kf(e,t,n,r,o=!1,i){let a=(Cr(e,t)||r&&e!=="powershell"&&t[0]?.provenance==="variable")&&me(i,"shell.dynamic-executable",o)?v("shell.dynamic-executable",iR):null;return T(a,i)??If(e,t,n,o,i)}function If(e,t,n,r,o){if(t.length<2)return null;let i=t.flatMap((a,l)=>ll(a)?[l]:[]);if(i.length===0)return null;let s=M(t[0]?.text??"");if(s==="git"){let a=Mn(e,t),l=aR(a);if(me(o,"shell.dynamic-structure",r)&&i.some((m)=>m<=l))return T(v("shell.dynamic-structure",Li),o);if(T(_i(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",Li),o);return null}if(s==="find")return me(o,"shell.dynamic-structure",r)&&lR(t)?T(v("shell.dynamic-structure",Li),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",Li),o):null}if(s==="xargs")return Tf(e,t.slice(pn(t.map(_)).childStart),"xargs",n,r,o);if(s==="parallel")return Tf(e,t.slice(Pf(t.map(_))),"parallel",n,r,o);return null}function Tf(e,t,n,r,o,i){if(t.length===0)return null;let s=sR(t,r);if(Cr(e,s)){let l=T(v(`${n}.shell-dynamic`,n==="xargs"?rl:Yr),i);if(l)return l}let a=If(e,s,r,o,i);if(a)return a;if(s[0]?.text==="rm"&&s.slice(1).some((l)=>ll(l)&&al(l)))return T(v(`${n}.rm-recursive-force-dynamic`,n==="xargs"?nl:qr),i);return null}function sR(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 aR(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 lR(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=ll(s);if(n>0){n--;continue}if(o){if(s.text===";"||s.text==="+"){o=!1,t=!0,r=!1;continue}if(a&&(r||al(s)))return!0;r=!1;continue}if(!t&&!s.text.startsWith("-")){if(a&&(i>1||al(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 cl(e,t){return e.some((n)=>{if(n.value==="-"&&(n.kind==="main-script"||n.kind==="program-file"))return!0;return!Yo(t[n.tokenIndex],n.value)})}var cR="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",uR="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",dR="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function Of(e,t){let n=t.slice(1);if(e==="dd"&&n.some((r)=>/^of=\/dev\/.+/.test(r)))return v("dd.device-write",cR);if((e==="mkfs"||e.startsWith("mkfs."))&&n.some((r)=>r.startsWith("/dev/")))return v("mkfs.device",uR);if(e==="shred"&&n.length>0)return v("shred.target",dR);return null}var Df=[{heads:new Set(["rm","rmdir"]),analyze:(e)=>Pi(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)=>_i(e.words,ul(e))},{heads:new Set(["find"]),analyze:(e)=>mm(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)=>tf(e.words,{...Mf(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>gn(e.options.analyzeNested(t,n))})},{heads:new Set(["parallel"]),analyze:(e)=>Cf(e.words,{...Mf(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>gn(e.options.analyzeNested(t,n))})}];function Mf(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 ul(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 Gf(e){return Df.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=ri(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=oi(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:!Wr(S,n.environment),qe=kf(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=Si(h,n.policy);if(ct){for(let R of[ct.childIndex,...ct.alternativeChildIndices]){Nf(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"?Ti(g):C==="trap"&&!a?Km(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||!el(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):zf(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(Kr(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=gR(h,S,A,n,r,t);if(R)return R;let I=st(h);if(I){let En=ki(g,I);if(En.kind==="dynamic")return ke(r);let Xi=En.kind==="literal"?En.source:qm(g,I),Fl=hR(Xi);r?.recordSegment({type:"shell-wrapper",wrapper:C,innerCommand:Fl}),r?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:Fl,depth:t+1});let zl=n.analyzeNested(Xi,{effectiveCwd:A,envAssignments:S});if(zl)return zl;return Kr(Xi)?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 Wi(G.source,A,S,n,r,t);let ce=Ym(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 Wi(ce.text,A,S,n,r,t);if(n.strict||!n.commandView||!el(n.commandView))return ke(r)}if(Be.has(C)&&!l){if(!s&&n.strict&&cl(Br(h),g))return ke(r);let R=sm(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&&cl(Qo(h),g))return ke(r);let R=dd(h);if(a&&s)return fR(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",Ar),n.policy);if(ce)return ve(ce)}if(pa(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&&!Ff(G,R))return G;if(Pr(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 Nf(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(Of(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?dl(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)=>dl(R,t,ie,I)},se=s&&(C==="xargs"||C==="parallel")?void 0:Gf(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"?Gm(ne.words,ul(ne)):void 0,Dt=Lf(Oe?Oe.match:se?.(ne)??null,n.policy);if(r)yR(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)??pR(s,n.policy)}let ro=!s&&se===void 0&&!xo.has(C),yt=r&&ro?[]:void 0;if(ro)for(let R=1;R<h.length;R++){let I=h[R];if(!I)continue;yt?.push(I);let G=Lf(mR(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 oo=At(h,n.policy.rules);if(r?.recordSegment({type:"custom-rules-check",rulesChecked:n.policy.rules.length>0,matched:!!oo,reason:oo?.reason}),oo)return ve(oo);return a&&s?Yn(s,n.policy):null}function dl(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 mR(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(zf(c,u)||Gf(u)!==void 0&&u!=="xargs"&&u!=="parallel"||l.wrappedByTransparent&&r.policy.rules.length>0)r.budget.charge("derivedTokens",e.length-t);let d=dl(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:!Wr(l.envAssignments,r.environment),worktreeMode:!1,wrappedByTransparent:l.wrappedByTransparent});if(d)return d}return null}function fR(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",Ar),o.policy);if(a)return ve(a)}if(pa(e,t))return Yn(i,o.policy);let s=o.analyzeNested(t,{effectiveCwd:n,envAssignments:r});if(s&&!Ff(s,t))return s;if(Pr(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 Ff(e,t){let n=e.ruleId==="raw-text.dangerous-command",r=(e.reason.startsWith(yi)||e.reason===Hn)&&!Ro(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 pR(e,t){let n=e.dynamicInput&&e.rmDynamicMatch?T(e.rmDynamicMatch,t):null;return n?ve(n):null}function gR(e,t,n,r,o,i){let s=dm(e);if(s.argvSource?.kind==="absent")return ke(o);if(s.argvSourceApplies&&s.argvSource){let l=Wi(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 Wi(a,n,t,r,o,i,!0)}function Wi(e,t,n,r,o,i,s=!1){if(s&&/[$`*?[\]]/.test(e))return ke(o);let a=_r(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 hR(e){let t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.at(-1)===t?e.slice(1,-1):e}function yR(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 Nf(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:zr}),ve(CR())}function CR(){return{id:"",reason:zr,intent:"stop_and_explain"}}function zf(e,t){return Q.has(t)||e==="$SHELL"||e==="${SHELL}"||Q.has(k(t))}function Lf(e,t){return e?.id.startsWith("custom.")||e?.id==="raw-text.dangerous-command"?e:T(e,t)}var bR=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,SR=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function vR(e,t){let n=$f(e,t);if(n.length===0)return!1;let r=n[Bf(n)];if(r==="cd"||r==="pushd"||r==="popd")return!0;return bR.test(e.join(" "))}function Hf(e,t,n,r,o){if(e.dialect==="powershell"){let y=ER(e.words,o);if(y.kind==="none")return;if(!t||y.kind==="unknown")return null;return Wf(_R(y.target),t,n.paths)}let i=e.words.map(_),s=i.some((y)=>/^CDPATH\+?=/.test(y));if(!vR(i,n))return s?null:void 0;if(!t)return null;let a=$f(i,n,t),l=Bf(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 Wf(h,t,n.paths)}function Wf(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 ER(e,t){let n=xR(e[0])?1:0,r=e[n];if(!RR(r,n===1))return{kind:"none"};let o=r.text.toLowerCase(),i=o.split(/[\\/]/).pop()??o;if(!SR.has(i))return{kind:"none"};if(o!==i||i==="pop-location"||i==="popd")return{kind:"unknown"};return wR(e.slice(n+1),t)}function xR(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&(e.text==="&"||e.text===".")}function RR(e,t){return e?.provenance==="literal"&&(t||!e.quoted&&e.raw===e.text)}function wR(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 _R(e){return e.includes("::")?void 0:e.replaceAll("\\","/")}function Bf(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 $f(e,t,n){let r=AR(e);return Bt([...r],t,n)}function AR(e){let t=0;while(t<e.length){let n=e[t];if(n!=="{"&&n!=="("&&n!=="$(")break;t++}return e.slice(t)}var PR="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 yl(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 hl(e,n);let u=`${yi}: ${c.message}`;return n.trace?.recordGlobal({type:"error",message:u}),{reason:u,segment:e,intent:"stop_and_explain"}}return Yf(e,n),{reason:Hn,segment:e,intent:"stop_and_explain"}}if(n.strict&&o.status==="partial")return Yf(e,n),{reason:Hn,segment:e,intent:"stop_and_explain"};if(o.issues.some((c)=>c.code.includes("quote")))return hl(e,n);let s=n.cwd,a=n.effectiveCwd!==void 0?n.effectiveCwd:n.cwd,l=wm(n.environment.env,n.envAssignments);return zi(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 zi(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=TR(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),ml(ie,[ne],f,d==="&",yn(d))}),H=fl(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=zi(u.body,t,n,r,[Xn(ne)]);if(se.result)return se;if(Z.push(...ml(ne,se.states,f,d==="&",yn(d))),P)H.push(ne,...f?se.states.map((Oe)=>Gi(ne,Oe)):se.states)}let ie=fl(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"?Vm(A)??IR(A):void 0,qe=[],ct=[];for(let Z of h){let H=OR(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)=>Gi(Z,ne));for(let ne of ie){let se=Xn(ne),Oe=NR(u,t,n.trace?{...n,trace:Zf(n.trace,x)}:n,r,se,Zt(a),ee);if(Oe)return{result:Oe,states:i};let Dt=tw(u,se.functionDefinitions);if(Dt)n.budget.charge("derivedTokens",Hi(Dt));let nr=Dt?t+1>=X.recursionDepth.cap?pl(u.displayText,n,[se]):zi(Dt,t+1,n,r,[se]):{result:null,states:QR(u,se)};if(nr.result)return nr;qe.push(...ml(Z,nr.states,f,d==="&",yn(d)));let ro=typeof se.effectiveCwd==="string"&&se.effectiveCwd!==ne.effectiveCwd&&u.redirections.every((yt)=>["<",">",">>",">|"].includes(yt.operator)&&yt.target?.text==="/dev/null");if(P&&!ro)ct.push(Z),ct.push(...nr.states.map((yt)=>f?Gi(Z,yt):yt))}}let xe=fl(qe,ct,C.skippedSuccessStates,C.skippedFailureStates,C.connector,d);i=xe.states,s=xe.conditionalStates,a=void 0}return{result:null,states:i}}function TR(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"&&kR(e,t)}function ml(e,t,n,r,o){let i=n?t.map((a)=>Gi(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 Gi(e,t){return{...e,literalHeredocFiles:new Map(t.literalHeredocFiles),createdDirectories:new Set(t.createdDirectories)}}function kR(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(MR(n))return!0;return n.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function Zt(e){return e==="|"||e==="|&"}function IR(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 fl(e,t,n,r,o,i){let s={success:Fi([...n,...e]),failure:Fi([...r,...t])},a=yn(i)?s:void 0;return{states:yn(o)||a?Fi([...s.success,...s.failure]):s.success,conditionalStates:a}}function Zf(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 OR(e,t,n,r,o){let i=e.nested.map((s)=>({program:s,depth:t}));if(e.dialect==="powershell"){let s=DR(e);if(s){if(t+1>=X.recursionDepth.cap)return pl(s,n,o);let a=Je(s,"powershell");if(a.status==="limited")return pl(s,n,o);if(a.status!=="complete")return Uf(i,n,r,o);n.budget.charge("derivedTokens",Hi(a)),i.push({program:a,depth:t+1})}}return Uf(i,n,r,o)}function MR(e){let t=e.words[0];return t?.provenance==="variable"&&e.words.at(-1)?.text==="="?t.text.toLowerCase():void 0}function Uf(e,t,n,r){let o=[...r];for(let i of e){let s=[];for(let a of o){let l=zi(i.program,i.depth,t,n,[Xn(a)]);if(l.result)return l;s.push(...l.states)}o=Fi(s)}return{result:null,states:o}}function DR(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 Hi(e){return e.nodes.reduce((t,n)=>t+(n.kind==="command"?n.words.length+n.nested.reduce((r,o)=>r+Hi(o),0):n.kind==="group"||n.kind==="function"?Hi(n.body):0),0)}function pl(e,t,n){return t.trace?.recordSegment({type:"error",message:ut}),{result:{reason:ut,segment:e,intent:"stop_and_explain"},states:[...n]}}function NR(e,t,n,r,o,i,s){let a={...n,environment:{...n.environment,env:o.shellGitContextState.env,paths:zR(n.environment.paths,o.createdDirectories,n.budget)}},l=VR(e,!a.strict);if(l&&a.strict)return a.trace?.recordSegment({type:"error",message:l}),{reason:l,segment:e.source,intent:"stop_and_explain"};Xf(e,o,"before-consumer",a.environment.paths,a.budget);let c=Mn(e.dialect,e.words),u=c.map(_),m=e.displayText,d=xm(c,o.shellGitContextState),f=Am(d,o.shellGitContextState);if(e.dialect==="powershell"){let h=T(Jd(e,i,rw(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 nw(m,h)}if(u.length===1&&u[0]?.includes(" ")&&!Cr(e.dialect,e.words)){let h=T($e(u[0]),a.policy),y=h!==null&&!a.strict&&ld(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=jf(e,l,o,f,s,a);if(S)return S;return qa(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=yl(h,t+1,{...a,effectiveCwd:S,envAssignments:y?.envAssignments??f,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:y?.functionDefinitions,worktreeMode:y?.worktreeMode??a.worktreeMode,trace:a.trace?Zf(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=jf(e,l,o,f,s,a);if(g)return g;return qa(d,o.shellGitContextState),null}function jf(e,t,n,r,o,i){let s=KR(e,t,n,r??new Map,i);if(s)return s;return Xf(e,n,"after-consumer",i.environment.paths,i.budget),n.literalHeredocFiles.clear(),GR(e,t,n,i.environment.paths,i.budget),HR(e,n,i.environment.paths,i.budget),ZR(e,n,o,i.environment,i.trace),null}var LR=new Set([">>","<>"]);function Xf(e,t,n,r,o){for(let s of e.redirections){if(!(n==="before-consumer"?WR(s):LR.has(s.operator)))continue;Vf(s.target,t,r,o)}if(n!=="before-consumer"||!ge(e.words[0],"tee"))return;let i=Qf(e.words.slice(1));if(!i)return;for(let s of i.operands)Vf(s,t,r,o)}function WR(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 Vf(e,t,n,r){let o=e?.provenance==="literal"?_r(e.text,t.effectiveCwd,n,r):void 0;if(!o)return;t.literalHeredocFiles.delete(o)}function GR(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 FR(e,n.shellGitContextState.shellAssignments)){let a=_r(s,n.effectiveCwd,r,o);if(!a||!ud(a))continue;if(!n.literalHeredocFiles.has(a)&&n.literalHeredocFiles.size>=X.trackedHeredocFiles.cap)throw new N("trackedHeredocFiles");n.literalHeredocFiles.set(a,i.body)}}function FR(e,t){let n=gl(UR(e.redirections)?.target,t),r=n===void 0?[]:[n];if(ge(e.words[0],"cat"))return $R(e.words)?r:[];if(!ge(e.words[0],"tee"))return[];let o=Qf(e.words.slice(1),t);if(!o||o.append||o.hasUnsupportedOptions)return[];let i=o.operands.map((s)=>gl(s,t));if(!i.every((s)=>s!==void 0))return[];return[...i,...r]}function gl(e,t){if(jR(e))return e.text;return(e&&pt(e,t))??void 0}function zR(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 HR(e,t,n,r){if(t.shellGitContextState.bodyDepth>0||!ge(e.words[0],"mkdir"))return;let o=e.words.slice(1).map((c)=>gl(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?BR(u,n):n.isDirectory(Ke.dirname(u))&&Jf(u,n))t.createdDirectories.add(u)}}function BR(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||Jf(o(i),t)}function Jf(e,t){try{return t.entryKind(e)==="missing"}catch{return!1}}function $R(e){let t=!1;for(let n of e.slice(1)){if(t||n.provenance!=="literal")return!1;if(n.text==="--"){t=!0;continue}if(!/^-u+$/.test(n.text))return!1}return!0}function UR(e){let t=e.findLast((n)=>(n.fd??([">",">|",">>",">&"].includes(n.operator)?1:0))===1);return t?.operator===">"||t?.operator===">|"?t:void 0}function Qf(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 jR(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 Cl(e){return e.quotedDelimiter||!/[$`\\]/.test(e.body)}function VR(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(!Cl(r.heredoc)&&(!t||o))return PR;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&&Kf(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(Kf)?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 Kf(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}function KR(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(YR(e,i,n,r,o))return null;let a=qR(e,i,o);if(a!==void 0)return a?{reason:a.reason,segment:e.displayText,ruleId:a.id,intent:a.intent}:null;let l=hl(s.length===i.length?s.join(`
|
|
42
|
+
`):e.source,o);return l?{...l,segment:e.displayText}:null}function qR(e,t,n){let r=t.length===1?t[0]:void 0;if(!r?.heredoc||!Cl(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",Ar),n.policy);if(m)return m}if(!Pr(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 YR(e,t,n,r,o){let i=t.length===1?t[0]:void 0;if(!i?.heredoc||!Cl(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 ZR(e,t,n,r,o){let i=Hf(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 XR=/^[A-Za-z_][A-Za-z0-9_]*$/,JR=8;function QR(e,t){let n=e.words[1]?.text;if(e.dialect!=="posix"||e.words[0]?.text!=="for"||n===void 0||!XR.test(n))return[t];let r=e.words.slice(3);if(!(e.words[2]?.text==="in"&&r.length>=1&&r.length<=JR&&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:_m(e.shellGitContextState),literalHeredocFiles:new Map(e.literalHeredocFiles),functionDefinitions:new Map(e.functionDefinitions),createdDirectories:new Set(e.createdDirectories)}}function Fi(e){let t=[];for(let n of e){if(!t.some((r)=>ew(r,n)))t.push(n);if(t.length>X.controlFlowStates.cap)throw new N("controlFlowStates")}return t}function ew(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&&qf(e.shellGitContextState.bodyAssignments,t.shellGitContextState.bodyAssignments)&&qf(e.createdDirectories,t.createdDirectories)}function qf(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 tw(e,t){let n=br(e);return n===void 0?void 0:t.get(n)}function nw(e,t){if(!t)return null;return{reason:t.reason,segment:e,ruleId:t.id,intent:t.intent}}function rw(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 hl(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 Yf(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 ow=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function ep(e,t,n,r){let o=yl(e,0,{...t,...ku(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 tp(e,t,n){try{return{decision:e()}}catch(r){let o=iw(r,t,n);if(!o)throw r;return o}}function iw(e,t,n){if(!(e instanceof N)||!ow.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 sw=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),Sl=new Set(["cc-safety-net","ccsn"]),aw=new Set(["bunx","npx","pnpx"]),lw=new Set(["pnpm","yarn"]),cw=new Set(["npm","pnpm","yarn"]),uw=new Set(["bun","node"]);function $i(e,t,n={}){if(Sl.has(e))return 0;if(aw.has(e)){if(n.broad)return bl(t);let o=t[0]==="-y"||t[0]==="--yes"?1:0;return Bi(t[o])?o+1:null}let r=n.broad?t.findIndex((o)=>!o.startsWith("-")):0;if(r!==-1&&cw.has(e)&&n.broad&&t[r]==="exec"){let o=bl(t.slice(r+1));return o===null?null:r+1+o}if(lw.has(e)){if(e==="yarn"&&!n.broad)return null;if(!n.broad)return t[0]==="dlx"&&Bi(t[1])?2:null;if(r===-1||t[r]!=="dlx")return null;let o=bl(t.slice(r+1));return o===null?null:r+1+o}if(uw.has(e)){let o=n.broad&&r!==-1?r:0;if(np(t[o]))return o+1;if(e==="bun"&&t[o]==="run"&&np(t[o+1]))return o+2}return null}function bl(e){let t=e.findIndex((r)=>Bi(r));if(t===-1)return null;let n=t;while(n<e.length){let r=e[n]??"";if(!r.startsWith("-")&&!Bi(r))break;n++}return n}function Bi(e){if(!e)return!1;let t=e.indexOf("@");if(t===-1)return Sl.has(e);if(t===0)return!1;let n=e.slice(t+1);if(n===""||n.includes("/")||n.includes(":"))return!1;return Sl.has(e.slice(0,t))}function np(e){let t=e?.replaceAll("\\","/");return[...sw].some((n)=>t===n||t?.endsWith(`/${n}`))}var rp="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 op(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)=>dw(i,t),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return o?{target:o}:null}function dw(e,t){let n=Bt([...e],t),r=n.slice(1),o=$i(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 Zr=require("node:path");var lp="This path contains the protected policy config and you must not modify or delete it.",mw=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function cp(e,t,n){let r=Cw(e.invocation.context,t,n);if(e.invocation.route.kind==="patch")return ip(e.paths,!1,e.invocation.context.executionCwd,r,t,n);let o=Pe(e,"input-candidate");if(e.invocation.route.kind==="command")return o?sp(o.shell,e.invocation.context.executionCwd,r,t,n):null;if(e.invocation.route.kind==="unknown"&&o){let i=sp(o.shell,e.invocation.context.executionCwd,r,t,n);if(i)return i}return ip(e.paths,e.invocation.route.kind==="grep"||e.invocation.route.kind==="glob"||co(e.invocation.toolName),e.invocation.context.executionCwd,r,t,n)}function ip(e,t,n,r,o,i){if(t)return null;let s=e.find((a)=>Xr(a,n,r,o,i));return s?{target:s}:null}function sp(e,t,n,r,o){let i=Gn(e,t,r,o,{findSegmentTarget:(s,a)=>fw(s,a,n,r,o)?.target??null,isRedirectionTarget:(s,a)=>Xr(s,a.cwd,n,r,o),findMalformedTarget:(s)=>yw(s,t,n,r,o)?.target??null});return i?{target:i}:null}function fw(e,t,n,r,o){if(Dr(e))return null;let i=$t([...e],r),s=k(i[0]??"").toLowerCase(),a=i.slice(1);if(s==="rm"&&pw(a)){let l=gw(a).find((c)=>ap(Ae(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(s==="find"){if(xi(i,1)||za(i,r)){let c=($r(J(i))??J(["."])).find((u)=>{let m=Ae(u.text,t.variables);return Xr(m,t.cwd,n,r,o)||ap(m,t.cwd,n,r,o)})?.text;if(c)return{target:c}}}if(s==="mv"){let l=ui(a).sources.find((c)=>bw(Ae(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(hw(i,s))return null;for(let l of[...e,...i])for(let c of up(l))if(Xr(Ae(c,t.variables),t.cwd,n,r,o))return{target:c};return null}function pw(e){return e.some((t)=>t==="--recursive"||t.startsWith("-")&&!t.startsWith("--")&&/[rR]/.test(t.slice(1)))}function gw(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 hw(e,t){if(!mw.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 yw(e,t,n,r,o){for(let i of e.split(/\s+/))for(let s of up(i))if(Xr(s,t,n,r,o))return{target:s};return null}function up(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.indexOf("=");return n===-1||n===t.length-1?[t]:[t,t.slice(n+1)]}function Cw(e,t,n){let r=(a)=>Jr(he(a,e.executionCwd,t,n)),o=r(An(t)),i=[r(mr(e.executionCwd)),r(mr(e.configCwd))],s=new Set(i.map((a)=>Zr.dirname(a)));for(let a=Zr.dirname(o);;a=Zr.dirname(a))if(s.add(a),Zr.dirname(a)===a)break;return{files:new Set([o,...i]),directoriesAndAncestors:s}}function Xr(e,t,n,r,o){let i=Kl(e,t,r,o,(s)=>Jr(s)===vo);return i!==null&&n.files.has(Jr(i))}function ap(e,t,n,r,o){return n.directoriesAndAncestors.has(Jr(he(e,t,r,o)))}function bw(e,t,n,r,o){let i=Jr(he(e,t,r,o));return n.files.has(i)||n.directoriesAndAncestors.has(i)}function Jr(e){return process.platform==="win32"?e.toLowerCase():e}var Ee=require("node:path"),Ep=require("node:url");var xp="Access to a sensitive path is not allowed.",Rp=new Set(["echo","printf"]),Sw=new Set(["find"]),vw=new Set(["!","do","elif","else","if","then","until","while"]),Ew=new Set(["-exec","-execdir"]),xw=new Set([";","+"]),Rw=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),ww=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),wp=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),_w=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),Aw=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"]),_p=new Set(["-c","-e","-r","-E","--eval","--exec"]),Pw=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"])]]),Tw=new Set(["grep","rg"]),kw=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),Iw=new Set(["commit","merge","notes","stash","tag"]),Ow=new Set(["-m","--message"]),Mw=new Set(["--grep"]),dp=new Set(["jq","gojq","jaq"]),mp="f",fp="file",Dw="files",Nw=new Set(["e","f"]),Lw=new Set(["regexp","file"]),Ww=new Set(["e","f","A","B","C","m"]),Gw=new Set(["regexp","file","after-context","before-context","context","max-count"]),vl="__CC_SAFETY_NET_PIPE_INPUT__",xl=/[\w./~@+-]*[./~][\w./~@+-]*/g,Fw=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,zw=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,Hw=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,pp=/\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,gp=/\b(?:system|exec|spawn|popen)\s*$/,Bw=/\b(?:eval|exec)\s*\(/g,$w=/\b(?:eval|exec)\s*$/,Uw=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 hp(e,t,n,r,o,i){for(let s of e){let a=s.target;if(H_(a,s.cwd,t?.denyPaths??[],n,r,o))return{target:a,ruleId:"secret.deny-path"};if(i&&!i.has(a))continue;let l=F_(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(Mp(a,s.cwd,r,o)))continue;if(c&&s.isRedirectionWriteTarget===!0&&!a.includes("$")&&!wl(a,s.cwd,r,o))continue;if(c&&/\s/.test(a)&&!a.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(a)&&!wl(a,s.cwd,r,o))continue;if(!l.startsWith("secret.cli.")&&B_(a,s.cwd,t?.allowPaths??[],n,r,o))continue;return{target:a,ruleId:l}}}return null}function Ap(e,t,n,r,o={}){let i=yp(e,n,r),s=hp(i,t,e.invocation.context.configCwd,n,r);if(s===null||s.ruleId==="secret.deny-path"||o.strict!==!1)return s;let a=hp(i,t,e.invocation.context.configCwd,n,r,new Set(yp(e,n,r,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}).map((l)=>l.target)));return a?.ruleId!=="secret.deny-path"&&jw(e,n)?null:a}function jw(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 ci(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 _l(i,o.slice(1))}function _l(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)=>Rw.has(n))}function yp(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,Vw(s)):[],...i==="unknown"?e.paths.map((a)=>({target:a,cwd:o})):[]]}function Vw(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})),...E_(_t(e.source,r),t,n,r,o,i)],l=(c)=>_t(r_(c,s),r);return li(e,o,r,i,{word:l,segment:(c,u,m,d,f)=>{if(c.length===0)return null;if(a.push(...ji(c,t,n,r,u.cwd,i,f)),m!==null)a.push(...qw(m,c,t,n,r,u.cwd,i));return null},redirection:(c,u)=>{if(c.body!==void 0&&c.consumer!==void 0)a.push(...Pp(c.consumer,[c.body],t,n,r,u.cwd,i,(m)=>Yw(c.consumer??[],m,t,n,r,u.cwd,i)));if(c.targetOrder==="legacy-segment")return xa;return a.push({target:l(c.target),cwd:u.cwd,...c.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}}),a}function Al(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 ji(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(dp.has(lt(Mt(g)[0]??"").toLowerCase()))return[...e.filter((h,y)=>s.has(y)).map(a),...ji(g,t,n,r,o,i)]}let l=n_(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)=>!vw.has(g));if(n.skipMetadataOnlySegments===!0&&f!==-1&&_l(lt(c[f]??"").toLowerCase(),c.slice(f+1)))return l;let p=Kw(u,m,d);if(p)return[...l,...p.map(a)];if(Rp.has(m))return n.displayOperandsAreCapturedOutput===!0?[...l,...Tp(e).map(a)]:l;if(m==="eval")return[...l,...Al(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,...i_(d).map(a)];if(m==="gh")return[...l,...Rl(m,d,kw).map(a)];if(dp.has(m))return[...l,...o_(d).map(a)];if(Tw.has(m))return[...l,...k_(d).map(a)];if(Sw.has(m))return[...l,...c_(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)=>d_(g,t,n,r,o,i)),...d.flatMap(m_).map(a)];if(m==="curl")return[...l,...d.flatMap((g)=>ht(m,g)).map(a),...s_(d).map(a)];if(Nr(m)){let g=Mr.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,...u_(m,d,t,n,r,o,i)]}return[...l,...d.flatMap((g)=>ht(m,g)).map(a)]}function Kw(e,t,n){let r=$i(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 qw(e,t,n,r,o,i,s){if(Qw(t,n,r,o,i,s)){let a=Mt(e),l=_l(lt(a[0]??"").toLowerCase(),a.slice(1))?a.slice(1).filter((c)=>!c.startsWith("-")):[];return[...Tp(e),...l].map((c)=>({target:c,cwd:i}))}return Pp(t,Zw(e),n,r,o,i,s,()=>[])}function Yw(e,t,n,r,o,i,s){let a=Mt(e);if(!Nr(lt(a[0]??"").toLowerCase()))return[];return Al(t,n,r,o,i,s)??[{target:t,cwd:i}]}function Pp(e,t,n,r,o,i,s,a){let l=e_(e);if(l===null)return t.flatMap(a);return t.flatMap((c)=>Mr.has(l)?Jn(n.getShellSyntax(c),n,r,o,i,s):Ui(l,c,n,r,o,i,s))}function Tp(e){let t=Mt(e);if(t.length===0)return[];let n=lt(t[0]??"").toLowerCase();if(!Rp.has(n))return[];let r=t[t[1]==="--"?2:1];if(n==="printf"&&r!==void 0&&!r.startsWith("-")&&!r.replaceAll("%%","").includes("%"))return[Pl(r.replaceAll("%%","%"))];return t.slice(1)}function Zw(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 Xw(r);return[]}function Xw(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[Pl(t)];let r=e.slice(1);return Array.from({length:Math.ceil(r.length/n)},(o,i)=>Jw(t,r.slice(i*n,(i+1)*n)))}function Jw(e,t){let n=0;return Pl(e.replace(/%%|%[bqs]/g,(r)=>{if(r==="%%")return"%";let o=t[n]??"";return n++,o}))}function Pl(e){return e.replace(/\\n/g,`
|
|
43
|
+
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function Qw(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,vl]:l.map((m)=>m.split(c).join(vl));return ji(u,t,n,r,o,i).some((m)=>m.target.includes(vl))}function e_(e){let t=Mt(e);if(t.length===0)return null;let n=lt(t[0]??"").toLowerCase();if(!Nr(n))return null;return t_(n,t.slice(1))?n:null}function t_(e,t){let n=Tl(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(_p.has(o)||kp(e,o)||/^--(?:eval|exec)=/.test(o))return!1;if(o==="-")return!0;if(o.startsWith("-")){if(n==="python"&&o==="-m")return!1;if(Uw.get(n)?.has(o))r++;continue}return!1}return!0}function Tl(e){return/^python\d/.test(e)?"python":e}function n_(e){let t=[];for(let n of e){if(Op(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 Cp=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function r_(e,t){if(!t||!Cp.test(e))return e;return`~${e.replace(Cp,"").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 o_(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 i_(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n]??"";if(r==="--"||!r.startsWith("-"))return[...t,...Iw.has(r)?Rl("git",e.slice(n).map((i)=>/^-[aeinopqsv]+m$/.test(i)?"-m":i),Ow):Rl("git",e.slice(n),Mw)];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 Rl(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 s_(e){return e.flatMap((t,n)=>{let r=l_(t);if(r!==null)return bp(r.flag,r.value);let o=a_(e[n-1]);return o===null?[]:bp(o,t)})}function bp(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 El(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 El(t.slice(n+1))}return t.startsWith("@")?El(t.slice(1)):[]}function a_(e){if(e===void 0)return null;if(wp.has(e))return e;return/^-[A-Za-z]+[dF]$/.test(e)?`-${e.slice(-1)}`:null}function l_(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 wp.has(r)?{flag:r,value:e.slice(n+1)}:null}function El(e){return e===""||e==="-"?[]:[e]}function c_(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(!Ew.has(e[l]??""))continue;let c=e.slice(l+1),u=c.findIndex((f)=>xw.has(f)),m=u===-1?c:c.slice(0,u),d=ji(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(!ww.has(f))return[];let h=g[p+1];return h===void 0?[]:[h,h.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return a}function u_(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(_p.has(c)||kp(e,c)){let m=t[l+1];if(m!==void 0)a.push(...Ui(e,m,n,r,o,i,s)),l++;continue}let u=/^--(?:eval|exec)=(.*)$/.exec(c);if(u!==null&&u[1]!==void 0){a.push(...Ui(e,u[1],n,r,o,i,s));continue}if(!c.startsWith("-"))a.push({target:c,cwd:i})}return a}function kp(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<=2)return!1;return Pw.get(t[t.length-1]??"")?.has(Tl(e))??!1}function d_(e,t,n,r,o,i){if(!e.includes("system"))return[];return La(e)?.commands.flatMap((s)=>Jn(t.getShellSyntax(s),t,n,r,o,i))??[]}function m_(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 f_(e){let t=Array.from(e.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((n)=>n[2]).filter((n)=>n!==void 0&&n!=="");return[...t,...t.flatMap(kl),...e.match(xl)??[]]}function Ui(e,t,n,r,o,i,s){let a=(g)=>({target:g,cwd:i}),l=g_(t,p_(e));if(l.kind==="unmaskable")return f_(t).map(a);let c=l.masked.match(pp)!==null||l.literals.some((g)=>gp.test(l.masked.slice(0,g.start))),u=l.masked.match(Bw)!==null||l.literals.some((g)=>$w.test(l.masked.slice(0,g.start))),m=r.inlineLiteralsPresumedData===!0&&!Mr.has(e),d=m&&!(b_(l.masked)||c||u)?[]:l.literals,f=m?Array.from(l.masked.matchAll(pp),(g)=>{let h=g.index+g[0].length;return{start:h,end:ha(l.masked,h)}}):[],p=!m||f.some((g)=>ya(l.masked,g.start))?l.literals:l.literals.filter((g)=>gp.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)=>kl(g.text)).map(a),...m?[]:l.literals.flatMap((g)=>g.text.match(xl)??[]).map(a),...c?p.flatMap((g)=>Al(g.text,n,r,o,i,s)??[a(g.text)]):[],...u?l.literals.flatMap((g)=>Ui(e,g.text.replace(/\\(.)/g,(h,y)=>y==="n"?`
|
|
44
|
+
`:y),n,r,o,i,s)):[],...(l.masked.match(xl)??[]).map(a)]}function p_(e){let t=Tl(e);if(t==="python")return"python";if(t==="osascript")return"opaque";return t==="node"||t==="bun"||t==="deno"?"javascript":"simple"}function g_(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(zw.test(e.slice(o)))return{kind:"unmaskable"}}let s=i==="'"||i==='"'||t==="javascript"&&i==="`"?i:null;if(s===null)continue;if(s==="`"&&C_(e,o))return{kind:"unmaskable"};let a=t==="python"?h_(e,o):"",l=t==="python"&&e.startsWith(s.repeat(3),o)?s.repeat(3):s,c=o+l.length,u=y_(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==='"'&&Hw.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 h_(e,t){return Fw.exec(e.slice(Math.max(0,t-3),t))?.[1]??""}function y_(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 C_(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 b_(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(_w.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)=>Aw.has(i)))continue;if(o.length>1)return!0;if(S_(e,r)===".")return!0;if(v_(e,r+n.length)==="(")return!0}return!1}function S_(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function v_(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function E_(e,t,n,r,o,i){return A_(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...Jn(a,t,{...n,displayOperandsAreCapturedOutput:!0},r,o,i),...x_(a,r)?R_(a,r).map((l)=>({target:l,cwd:o})):[]]})}function x_(e,t){let n=ci(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 R_(e,t){return ci(e).flatMap((n)=>n.kind==="word"?[_t(n.text,t)]:n.kind==="redirection"&&n.target?[_t(n.target,t)]:[]).flatMap(kl)}function kl(e){let t=__(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||w_(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function w_(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function __(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 A_(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(fr(o,n))continue;if(Ip(e,r,n)){let i=P_(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=T_(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function P_(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(fr(i,n))continue;if(Ip(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 T_(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 Ip(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function k_(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===Dw)o=!0;if(Lw.has(m))r=!0;if(d!==void 0){if(m===fp)t.push(d);continue}if(Gw.has(m)){let f=e[l+1];if(m===fp&&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(Nw.has(h))r=!0;if(Ww.has(h)){d=h,f=m.slice(g+1);break}}if(d==="")continue;if(f.length>0){if(d===mp)t.push(f);continue}let p=e[l+1];if(d===mp&&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)=>!Op(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:e.slice(t)}function Op(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var I_=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),O_=".env.",M_=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),D_=[".env.example.",".env.sample."];function N_(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function L_(e){return e.length>0&&!/\s/.test(e)}function wl(e,t,n,r){let o=Mp(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function Mp(e,t,n,r){try{return to(e,t,n,r)}catch(o){if(o instanceof N)throw o;return""}}var W_=new Set(["node_modules","__pycache__"]),G_=[["vendor","bundle"],["vendor","cache"]];function F_(e,t,n,r,o){if(N_(e))return null;let i=gt(e,t,r,o);if(!i)return null;let s=U(i.split("/").pop()??""),a=U(i),l=()=>L_(s)||wl(e,t,r,o);if(M_.has(s)||D_.some((d)=>s.startsWith(d)))return null;let c=U(j_(e,t,r,o));for(let d of Os){let f=`~/${d.suffixParts.join("/")}`;if((vp(a,f)||vp(c,f))&&Ot(d.id,n))return d.id}let u=z_(i,t,n,r,o);if(u)return u;if(I_.has(s))return null;for(let d of Is)if(s===d.basename&&Ot(d.id,n))return d.id;if(s.startsWith(O_)&&Ot(Ao.id,n)&&l())return Ao.id;for(let d of Ms)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 Ds)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($_(a))return null;if(!s.includes(".")&&gr.pattern.test(s)&&Ot(gr.id,n))return gr.id;let m=U_(s,n);if(m)return m;return null}function z_(e,t,n,r,o){return Po.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"])||eo(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"])||Qr(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()?eo(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"])||Qr(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"])||Qr(e,s,["credentials"])||Qr(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)=>eo(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()?eo(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"]))||Qr(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()?eo(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 Sp=new WeakMap;function Y(e,t,n,r,o){let i=Sp.get(o)??new Map;Sp.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)=>Dp(e,Ce(t,r)))}function Qr(e,t,n){return n.some((r)=>Cn(U(e),U(Ce(t,r))))}function eo(e,t,n,r,o){return Dp(e,gt(t,n,r,o))}function Dp(e,t){return U(e)===U(t)}function Ce(e,...t){return at([e,...t].filter(Boolean).join("/"))}function H_(e,t,n,r,o,i){if(n.length===0)return!1;let s=U(to(e,t,o,i));return n.some((a)=>Cn(s,U(to(a,r,o,i))))}function B_(e,t,n,r,o,i){if(n.length===0)return!1;let s=U(to(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=Gs(d);if(f&&Ee.posix.basename(s)!==U(f.name))return!1;let p=U(to(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 $_(e){let t=e.split("/");return t.some((n)=>W_.has(n))||G_.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function U_(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 Ns)if(r===o.extension&&Ot(o.id,t))return o.id;for(let o of Ls)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}=Il(e,n,r);if(!i)return"";if(!o)return i;let s=Ol(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 vp(e,t){return e===t||e.startsWith(`${t}/`)}function j_(e,t,n,r){let{home:o,normalized:i}=Il(e,n,r);if(!i||!o)return"";let s=Ol(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 to(e,t,n,r){let{home:o,normalized:i}=Il(e,n,r);if(!i)return"";let s=o?Ol(i,o):i;return at(O(Ee.isAbsolute(s)?s:Ee.resolve(t,s),n.paths,r))}function Il(e,t,n){let r=t.env.get("HOME")??t.home,o=r?at(O(Me(r),t.paths,n)):"",i=at(Me(V_(_t(e,t))));return{home:o,normalized:i}}function V_(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return Ep.fileURLToPath(e)}catch{return e}}function Ol(e,t){if(e==="~")return t;if(e.startsWith("~/"))return Ce(t,e.slice(2));return e}function K_(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("\\")&&K_(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 q_={findPolicyMutation:cp,findGitMetadataMutation:Wd,resolveGitMetadata:Z_,loadPolicySnapshot:Tu,findSensitiveTarget:Ap,analyzeCommand:ep,getModes:fs},Y_=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function Np(e,t){let n={...q_,...t.dependencies},r=Q_(e),o=no(e)?e.command:r,i=Xt("policy-protection",o,()=>Lr(e)),s=Pe(i,"input-candidate"),a=Pe(i,"declared-command");if(no(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:Qd,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:lp,intent:"hard_stop",evidence:{command:E,segment:u.target}}}}let m=Xt("policy-protection",o,()=>op(i,t.environment,l));if(m){let E=o??m.target;return{stage:"policy-protection",decision:{kind:"deny",reason:rp,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,...X_(f)},y=p.secretProtection.enabled===!1?null:Xt("secret-protection",o,()=>n.findSensitiveTarget(i,p.secretProtection,t.environment,l,{strict:no(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:xp,intent:"hard_stop",ruleId:y.ruleId,evidence:{command:E,segment:y.target}}}}if(!no(e))return{stage:"non-command",...h,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...Ml("command-validation",o),...h};let S=Xt("command-analysis",o,()=>tp(()=>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}:{}},J_(i),i.store),e.command,t.trace));if(S.decision){let E=!g.strict&&(S.decision.ruleId==="raw-text.dangerous-command"||S.decision.reason===zr&&!Y_.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 Z_(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 X_(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function J_(e){return Pe(e,"declared-command")?.program}function Q_(e){try{return Nt(e.input)}catch(t){let n=no(e)?e.command:void 0;throw new bn("policy-protection",Ml("policy-protection",t instanceof be?void 0:n,t),t)}}function Xt(e,t,n){try{return n()}catch(r){throw new bn(e,Ml(e,r instanceof be?void 0:t,r),r)}}function Ml(e,t,n){let r=n instanceof N||n instanceof nt;return{stage:e,decision:{kind:"deny",reason:r?Qi:or,intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function no(e){return e.route.kind==="command"}var Ki=require("node:fs"),er=require("node:path");var le=require("node:fs"),Qn=require("node:path");function Lp(e,t={}){return Wo(An(e,t),e.home).policy.audit.retention_days}var Nl=86400000,eA=".last-prune",tA=/^\d{4}-\d{2}$/,nA=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Wp=(e)=>Math.floor(e/Nl);function Fp(e,t,n=()=>new Date){try{let r=n().getTime();if(!le.statSync(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=Qn.join(t,eA),i=le.statSync(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&Wp(i)===Wp(r))return;let s=r-Lp(e)*Nl,a=new Date(r).toISOString().slice(0,7);for(let l of Dl(t)){if(l.isDirectory()){rA(Qn.join(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))oA(Qn.join(t,l.name),s)}le.writeFileSync(o,"",{mode:384}),le.utimesSync(o,r/1000,r/1000)}catch{}}function rA(e,t,n){for(let r of Dl(e)){if(!r.isDirectory()||!tA.test(r.name))continue;let o=Qn.join(e,r.name);for(let i of Dl(o)){if(!i.isFile())continue;let s=nA.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+Nl;if(!Number.isFinite(a)||a>=t)continue;zp(Qn.join(o,i.name))}if(r.name!==n)Gp(o)}Gp(e)}function oA(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(iA);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(le.lstatSync(e).mtimeMs!==n.mtimeMs)return;zp(e)}catch{}}function iA(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 Dl(e){try{return le.readdirSync(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function zp(e){try{le.unlinkSync(e)}catch{}}function Gp(e){try{le.rmdirSync(e)}catch{}}var sA="2.4.14",aA=1e4,lA=2000,cA=256,uA=32768;function dA(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 mA(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function Ll(e,t,n,r,o,i,s={}){let a=dA(t);if(!a)return;let l=pA(e);if(!l)return;try{let c=(s.now??(()=>new Date))().toISOString(),u=Vi(Ct(n),s.failureStage?Number.POSITIVE_INFINITY:aA),m=Vi(Ct(r),lA),d=s.toolName?Vi(Ct(s.toolName),cA):void 0,f=i===null?void 0:Vi(Ct(i),uA),p=er.join(l,mA(f?.value??null),c.slice(0,7));Ki.mkdirSync(p,{recursive:!0,mode:448});let g=er.join(p,`${c.slice(0,10)}-${a}.jsonl`),h={ts:c,id:(s.createId??gs)(),v:sA,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};Ki.appendFileSync(g,`${JSON.stringify(h)}
|
|
47
|
+
`,{encoding:"utf-8",mode:384}),Fp(e,l,s.now)}catch{}}function Vi(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function fA(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 pA(e){let t=fA(e);return t?er.join(t,".cc-safety-net","logs"):null}function Bp(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=Hp(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?Hp(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 Hp(e){return"command"in e?e.command??"":""}function $p(e,t,n,r){if(!t)return;let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Ll(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 Up(e,t,n,r){let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Ll(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 Vp(e,t,n){try{let r=Np(t,{environment:e,...n.guard});return jp(e,t,r,n),r}catch(r){if(!(r instanceof bn))throw r;throw jp(e,t,r.evaluation,n,!(r.cause instanceof be),{stage:r.stage,errorCode:gA(r.cause)}),r}}function jp(e,t,n,r,o=!0,i){$p(e,Bp(t,n,r.guard?.auditAllowed??!1,o,i),r.audit.getSessionId,{agent:r.audit.agent,shape:r.audit.shape})}function gA(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)=>dc(e.cwd,t,n,r,o.paths,process.cwd()),qi=(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?ls(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 hA(e,t){console.log(JSON.stringify(e(Bl(t))))}async function yA(e){let t;try{t=(await uc(process.stdin)).trim()}catch{e({reason:"Failed to parse hook input JSON."});return}if(!t){e({reason:"Missing hook input JSON."});return}return po(t,e,"Failed to parse hook input JSON.")}async function CA(e){let t=Ec(),n=await yA(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=EA(n),s=(p,g)=>{Up(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),vA(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=ur(l,u.input,u.route,m,d??null);try{let p=Vp(t,f,{guard:{auditAllowed:xc(t.env),dependencies:e.guardDependencies},audit:{agent:r,shape:o,getSessionId:()=>e.getSessionId(n)}}),g=es(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;bA(p,t.env);let g=es(p.evaluation,{includeEvidence:!0,toolName:p.evaluation.stage==="command-analysis"?void 0:l});if(g)e.outputDeny(g);return}}function bA(e,t){if(!en(ae.debug,t))return;console.error(`CC Safety Net debug: ${SA(e.stage)}: ${Ul(e.cause)}`)}function SA(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 vA(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 EA(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)=>hA(e.createDenyOutput,s),n=e.createAskOutput,r=n?(s)=>console.log(JSON.stringify(n($l(s)))):void 0,o=e.createAllowOutput,i=o?()=>console.log(JSON.stringify(o())):void 0;try{await CA({...e,outputDeny:t,outputAsk:r,outputAllow:i})}catch(s){console.error("CC Safety Net error:",s),t(xn())}}var xA=new Map([["run_command","auto"]]),RA=new Set(["absolutepath","directorypath","file_path","filepath","path","searchdirectory","searchpath","target_file","targetfile"]);function Kp(e){return oe(e,xA)}async function qp(){await Ie({agent:"antigravity-cli",createDenyOutput:(e)=>({decision:"deny",reason:e}),isSupported:()=>!0,getToolName:(e)=>e.toolCall?.name,getToolInput:(e,t)=>({ok:!0,input:PA(e.toolCall?.args,t),route:Kp(t)}),getContext:wA,getSessionId:(e)=>e.conversationId})}function wA(e,t,n,r,o){let i=AA(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=_A(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=Yp(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 _A(e,t,n,r){let o=Kp(t),i=[...uo(e,RA),...o.kind==="patch"?mo(e):[]].filter(Wl.isAbsolute),s=ue(),a=new Set(i.flatMap((l)=>{let c=Yp(O(l,r,s),n);return c?[c]:[]}));if(a.size>1)return null;return[...a][0]??n[0]??null}function Yp(e,t){return t.filter((n)=>lr(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?so(r,i):xn(i))}function AA(e){if(e.workspacePaths===void 0)return[process.cwd()];return Array.isArray(e.workspacePaths)?e.workspacePaths.filter((t)=>typeof t==="string"&&t.trim()!==""):[]}function PA(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 Yi=[{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"]}}],PL=Yi.slice().sort((e,t)=>e.doctorOrder-t.doctorOrder).map((e)=>e.id),Zp=Yi.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})),TL=Yi.slice().sort((e,t)=>e.install.order-t.install.order).map((e)=>({id:e.id,...e.install})).map(({order:e,...t})=>t),kL=Object.fromEntries(Yi.map((e)=>[e.id,e.displayName]));var vn=require("node:path");function Xp(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 lr(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 Zi="PreToolUse",Jp="BeforeTool",Qp="pre_tool_call";async function tr(e){await Ie({agent:e.agent,...e.getAgent?{getAgent:e.getAgent}:{},createDenyOutput:(t)=>({hookSpecificOutput:{hookEventName:Zi,permissionDecision:"deny",permissionDecisionReason:t}}),...e.canPromptPerson?{canPromptPerson:e.canPromptPerson,createAskOutput:(t)=>({hookSpecificOutput:{hookEventName:Zi,permissionDecision:"ask",permissionDecisionReason:t}})}:{},isSupported:(t)=>t.hook_event_name===Zi,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 TA=new Map([["Bash","posix"],["PowerShell","powershell"],["Monitor","posix"]]);function kA(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,TA)}async function eg(){await tr({agent:"claude-code",getAgent:(e,t)=>Xp(e.transcript_path,t),canPromptPerson:(e)=>["default","acceptEdits","plan"].includes(e.permission_mode??""),getToolRoute:kA})}var IA=new Map([["Bash","auto"]]);async function tg(){await tr({agent:"codex",getToolRoute:(e)=>oe(e,IA)})}var OA=new Map([["bash","auto"],["Bash","auto"],["powershell","powershell"],["PowerShell","powershell"]]);function MA(e){return oe(e,OA)}async function ng(){await Ie({agent:"copilot-cli",createDenyOutput:(e)=>({permissionDecision:"deny",permissionDecisionReason:e}),isSupported:()=>!0,getToolName:(e)=>e.toolName,getToolInput:(e,t,n)=>{let r=MA(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=po(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 DA=new Map([["Shell","auto"]]);function NA(e){return oe(e,DA)}async function rg(){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:NA(t)}),getContext:LA,getSessionId:(e)=>e.conversation_id})}function LA(e,t,n,r,o){let i=WA(e);if(!i[0])return Se(r,t,n),null;let s=i.flatMap((d)=>{let f=vt([d],o.paths);return f?[f]:[]});if(!s[0])return He(r,t,n,{directory:"session",problem:"unusable",cwd:i[0]}),null;let a=GA(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=ir(c),m=St(u,s,o.paths);if(!m)return He(r,t,n,{directory:"requested",problem:Et(u,s[0],o.paths),cwd:u}),null;return{configCwd:l,executionCwd:m}}function WA(e){if(e.workspace_roots===void 0)return typeof e.cwd==="string"&&e.cwd.trim()!==""?[ir(e.cwd)]:[];if(!Array.isArray(e.workspace_roots))return[];return e.workspace_roots.filter((t)=>typeof t==="string"&&t.trim()!=="").map((t)=>ir(t))}function GA(e){return typeof e==="string"&&e.trim()!==""?ir(e):"."}var og=new Map([["run_shell_command","auto"]]);function FA(e){return oe(e,og)}async function ig(){await Ie({agent:"gemini-cli",createDenyOutput:(e)=>({decision:"deny",reason:e,systemMessage:e}),isSupported:(e)=>e.hook_event_name===Jp,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:FA(t)}),getContext:qi("dir_path",og,{emptyMeansSessionCwd:!0,allowOutsideSessionCwd:!0}),getSessionId:(e)=>e.session_id})}var zA=new Map([["run_terminal_command","auto"],["monitor","auto"]]);function HA(e){return oe(e,zA)}async function sg(){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:HA(t)}},getContext:BA,getSessionId:(e)=>e.sessionId})}function BA(e,t,n,r,o){let i=$A(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=UA(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 $A(e){let t=e.workspaceRoot===void 0?e.cwd:e.workspaceRoot;return typeof t==="string"&&t.trim()!==""?t:void 0}function UA(e){return typeof e==="string"&&e.trim()!==""?e:"."}var ag=require("node:path");var jA=new Map([["terminal","posix"]]);async function lg(){await Ie({agent:"hermes-agent",createDenyOutput:(e)=>({action:"block",message:e}),isSupported:(e)=>e.hook_event_name===Qp,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:oe(t,jA)}),getContext:VA,getSessionId:(e)=>e.session_id})}function VA(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([ag.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 cg=new Map([["Bash","posix"]]);function KA(e){return oe(e,cg)}async function ug(){await tr({agent:"kimi-code",getToolRoute:KA,getContext:qi("cwd",cg)})}var qA={"antigravity-cli":qp,"claude-code":eg,codex:tg,"copilot-cli":ng,cursor:rg,"gemini-cli":ig,"grok-build":sg,"hermes-agent":lg,"kimi-code":ug},Gl=Zp.map((e)=>({...e,run:qA[e.id]}));function dg(e){let t=io({label:"hook",booleans:Object.fromEntries(Gl.map((r)=>[r.id,[...r.flags,...r.legacyFlags]]))},e);if(t.errors.length>0)return;let n=Gl.filter((r)=>t.flags[r.id]);return n.length===1?n[0]:void 0}function mg(e){return Gl.find((t)=>t.legacyTopLevelFlags.some((n)=>n===e))}async function YA(){let e=process.argv.slice(2),t=e[0],n=io({label:"cc-safety-net",booleans:{version:["-V","--version"]},positionals:"list"},e);if(!n.help&&!n.flags.version){if(t?.toLowerCase()==="hook"){let i=dg(e.slice(1));if(i){await i.run();return}}let o=mg(t);if(o){await o.run();return}}let r=await import("../cli.js");await r.runCli(e)}YA().catch((e)=>{console.error("CC Safety Net error:",e),process.exit(1)});
|