cc-safety-net 2.4.11 → 2.4.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/amp/cc-safety-net/index.ts +42 -42
- package/dist/api.js +1 -1
- package/dist/bin/hook.js +38 -38
- package/dist/chunks/index-av9c301x.js +45 -0
- package/dist/chunks/{index-jtfqeraz.js → index-fjkkpma1.js} +4 -4
- package/dist/chunks/index-pm924a1e.js +2 -0
- package/dist/cli.js +266 -246
- package/dist/index.js +7 -7
- package/dist/openclaw/cc-safety-net/index.js +40 -40
- 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 +5 -3
- package/dist/chunks/index-mzkasrgh.js +0 -45
- package/dist/chunks/index-rr4ytenf.js +0 -2
package/dist/bin/hook.js
CHANGED
|
@@ -1,47 +1,47 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var mg=["-h","--help"];function oo(e,t){let n=Object.entries(e.booleans??{}),r=Object.entries(e.values??{}),o=Object.entries(e.lists??{}),i=Object.fromEntries(n.map(([d])=>[d,!1])),s={},a=Object.fromEntries(o.map(([d])=>[d,[]])),l=[],c=[],u=!1,m=-1;for(let[d,f]of t.entries()){if(d<=m)continue;if(f==="--"){l.push(...t.slice(d+1));break}if(mg.includes(f)){u=!0;continue}let p=n.find(([,y])=>y.includes(f));if(p){i[p[0]]=!0;continue}let g=r.find(([,y])=>y.includes(f));if(g){let y=t[d+1];if(y===void 0||y.startsWith("-")){c.push(`${f} requires a value`);continue}s[g[0]]=y,m=d+1;continue}let h=o.find(([,y])=>y.includes(f));if(h){let y=t.slice(d+1),S=y.findIndex((C)=>C.startsWith("-")),E=y.slice(0,S===-1?y.length:S);if(E.length===0){c.push(`${f} requires at least one value`);continue}a[h[0]]=[...a[h[0]]??[],...E],m=d+E.length;continue}if(f.startsWith("-")){c.push(`Unknown option for ${e.label}: ${f}`);continue}if(e.positionals==="tail"){l.push(...t.slice(d));break}l.push(f)}if(e.positionals!=="list"&&e.positionals!=="tail")c.push(...l.map((d)=>`Unexpected argument for ${e.label}: ${d}`));return{flags:i,values:s,lists:a,positionals:l,help:u,errors:c}}var Ll=require("node:path");var Ji="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",ut="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",or="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var Xi={errorCode:"path-canonicalization-limit",reason:"CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry."},rr={errorCode:"structural-shell-syntax-limit",reason:"Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry."},X=Object.freeze({realpathAttempts:{cap:16384,...Xi},processedCandidateBytes:{cap:4194304,...Xi},pathEnvironmentExpansion:{cap:64,...Xi},recursionDepth:{cap:10,errorCode:"structural-shell-syntax-limit",reason:"Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry."},derivedTokens:{cap:16384,...rr},trackedHeredocFiles:{cap:64,...rr},controlFlowStates:{cap:64,...rr},wrapperPeelIterations:{cap:20,...rr},derivedCommandShape:rr});class N extends Error{kind;name="AnalysisLimit";constructor(e){super(X[e].reason);this.kind=e}}function ue(){let e=new Map;return{counters:e,resolvedPaths:new Map,charge(t,n=1){let r=(e.get(t)??0)+n;if(e.set(t,r),r>X[t].cap)throw new N(t)}}}var fg=[/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bglpat-[A-Za-z0-9_-]{20,}\b/g,/\bxox[abeprs]-[A-Za-z0-9-]{20,}\b/g,/\bnpm_[A-Za-z0-9_]{20,}\b/g,/\bpypi-[A-Za-z0-9_-]{20,}\b/g,/\b[rs]k_(?:live|test)_[A-Za-z0-9_]{20,}\b/g,/\bsk-[A-Za-z0-9_-]{20,}\b/g,/\bsk_[A-Za-z0-9]{20,}\b/g,/\bgsk_[A-Za-z0-9]{52,}\b/g,/\bxai-[A-Za-z0-9_-]{80,}\b/g,/\bpplx-[A-Za-z0-9_-]{20,}\b/g,/\bbastn_[A-Za-z0-9]{16,}\b/g,/\btgp_v1_[A-Za-z0-9_-]{43,}\b/g,/\bflp_[A-Za-z0-9]{10,}\b/g,/\bwfr_[A-Za-z0-9]{20,}\b/g,/\bfwp?_[A-Za-z0-9_-]{20,}\b/g,/\btp-[A-Za-z0-9_-]{20,}\b/g,/\bpsk-[A-Za-z0-9_-]{8,}-[A-Za-z0-9_-]{8,}\b/g,/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/g];function Ct(e){return pg(e.replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_DSN|CONNECTION_STRING)=("[^"]*"|'[^']*'|[^\s]+(?:\s+[A-Z_][A-Z0-9_]*=[^\s]+)*)/gi,"$1=<redacted>").replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_(?:URL|URI|CONNECTION_STRING))=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIALS)[A-Z0-9_]*)=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>"))}function pg(e){return fg.reduce((t,n)=>t.replace(n,"<redacted>"),e.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi,"<redacted>").replace(/((?:(['"])(?:authorization|cookie|x-api-key|api-key)\2|(?:authorization|cookie|x-api-key|api-key))\s*:\s*)(['"])(?:\\[^\r\n]|(?!\3)[^\\\r\n])*\3/gi,"$1$3<redacted>$3").replace(/(['"]?\s*(?:authorization|cookie|x-api-key|api-key)\s*:(?!\s*(?:"<redacted>"|'<redacted>'))\s*)([^'"\r\n]+)(['"]?)/gi,"$1<redacted>$3").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s@/]+)@/gi,"$1<redacted>:<redacted>@").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+)@/gi,"$1<redacted>@").replace(/(^|[\s?&;|])((?:x-amz-signature|x-goog-signature|sig|signature)=)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^&#\s'"`;|<>()]*)/gi,"$1$2<redacted>").replace(/(^|\s)((?:-u|--user)(?:\s+|=))([^\s:]+):([^\s]+)/g,"$1$2<redacted>:<redacted>")).replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"<redacted>").replace(/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,"<redacted>")}var gg={hard_stop:"Do not retry this operation or attempt any workaround (other tools, flags, or paths). Report the block to the user and continue with the rest of the task.",use_alternative:"Do not retry the blocked form. Continue the task using the safer alternative described above.",scope_down:"Retry with a narrower, explicit target as described above. Escalate to the user if the broad operation is truly required.",manual_only:"If this operation is truly needed, ask the user for explicit permission and have them run the command manually.",stop_and_explain:"Do not brute-force variants. Simplify or restructure the command so it can be analyzed, or report the block to the user."};function zl(e){let t=e.maxLen??200,n=e.redact??((o)=>o),r=(o)=>o.length>t?`${o.slice(0,t)}...`:o;return[e.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${n(e.reason)}`,e.ruleId?`Rule: ${e.ruleId}`:void 0,e.toolName?`Tool: ${e.toolName}`:void 0,e.command?`Command: ${r(n(e.command))}`:void 0,e.segment&&e.segment!==e.command?`Segment: ${r(n(e.segment))}`:void 0,e.cwd?`Working directory: ${r(n(e.cwd))}`:void 0,e.configWarning?`Config warning: ${n(e.configWarning)}`:void 0,e.askUser?"Approve only if you expected this command.":gg[e.intent??"manual_only"]].filter((o)=>o!==void 0).join(`
|
|
3
3
|
|
|
4
|
-
`)}function ji(e,t){if(e.decision.kind!=="deny")return;let n=t.includeEvidence?e.decision.evidence:void 0;return{reason:e.decision.reason,ruleId:e.decision.ruleId,intent:e.decision.intent,command:n?.command,segment:n?.segment,toolName:t.toolName,...e.configFallback?{configWarning:e.configFallback.reason}:{},...e.decision.ask?{ask:!0}:{}}}function gn(e={}){return{reason:Zn,intent:"stop_and_explain",command:e.command,segment:e.segment??e.command,toolName:e.toolName}}function Ml(e){return Ol({...e,redact:gt})}function Dl(e){return Ol({...e,redact:gt,askUser:!0})}function Nl(e){return gt(e instanceof Error?e.message:String(e))}var Re=require("node:path");var og=256,Zr=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 Oe(e,t=process.platform){if(t!=="win32")return e;return e.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function Tt(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function Yi(e,t){return Vi(e,0,t)}function Vi(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=Ki(e,o+2),a=ig(e,o,t);if(a===null){if(Zr.has(s))throw new D("pathEnvironmentExpansion");r+=e.slice(o);break}let l=e.slice(o,a+1);r+=sg(l,t,n),o=a+1;continue}let i=Ki(e,o+1);if(!i){r+="$",o++;continue}r+=qi(i,n)??`$${i}`,o+=i.length+1}return r}function ig(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 D("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=Ki(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return qi(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(Zr.has(o))throw new D("pathEnvironmentExpansion");return e}if(!Zr.has(o))return e;if(s.endsWith("="))throw new D("pathEnvironmentExpansion");let a=qi(o,n),l=s.startsWith(":")?a!==null&&a!=="":a!==null;if(s.endsWith("?")&&!l)throw new D("pathEnvironmentExpansion");if(s.endsWith("-")||s.endsWith("?"))return l?a??"":Vi(i.slice(s.length),t+1,n);return l?Vi(i.slice(s.length),t+1,n):""}function Ki(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 qi(e,t){if(!Zr.has(e))return null;if(e==="HOME")return t.env.get("HOME")??t.home;return t.env.get(e)??null}function N(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){Wl(n,i);let s=t.realpath(i);if(s!==null)return Ll(n,e,s,o);let a=Re.dirname(i);if(a===i||o.length>=og)return Ll(n,e,i,o);o.push(Re.basename(i)),i=a}}function Ll(e,t,n,r){let o=r.length===0?n:Re.join(n,...r.reverse());return e.resolvedPaths.set(t,o),o}function ag(e,t,n){let r=n.resolvedPaths.get(e);if(r!==void 0)return r;Wl(n,e);let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function Wl(e,t){e.charge("realpathAttempts"),e.charge("processedCandidateBytes",Buffer.byteLength(t))}function he(e,t,n,r){let o=Fl(e,t,n);if(!o)return"";return N(o,n.paths,r).replace(/\\/g,"/")}function Gl(e,t,n,r,o){let i=Fl(e,t,n);if(!i)return null;if(o(Re.basename(i)))return N(i,n.paths,r).replace(/\\/g,"/");let s=ag(i,n.paths,r);return s===null?null:s.replace(/\\/g,"/")}function Fl(e,t,n){let r=n.home,o=Yi(e.trim(),n).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?Re.resolve(r,o.slice(2)):o,s=Oe(i);return Re.normalize(Re.isAbsolute(s)?s:Re.resolve(t,s))}var jl=require("node:util"),lg=new Set(["applypatch","patch"]),cg=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),ug=new Set(["grep","grepsearch","rg"]),dg=new Set(["find","findbyname","glob"]),mg=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),fg=new Set(["command","diff","input","patch","patchtext"]),zl=new TextEncoder,pg=new TextDecoder,gg=/\s/,hg=64;class ve extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var Xn=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function Vl(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function Jr(e){return mg.has(Vl(e))}function Kl(e){let t=Vl(e);if(lg.has(t))return"patch";if(ug.has(t))return"grep";if(dg.has(t))return"glob";if(cg.has(t))return"path";return"unknown"}function It(e){if(!e||typeof e!=="object")return;Jl(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)at();return}if(t.get||t.set)at();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function Qr(e,t){return ql(e,t,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function ql(e,t,n,r){let o=Xl(e,n,r);if(!o)return[];let i=o.entries.flatMap(([s,a])=>{let l=ql(a,t,n,r+1);return typeof a==="string"&&t.has(Yl(s))?[a]:l});return n.ancestors.delete(o.object),i}function Yl(e){return e.replace(/-/g,"_").toLowerCase()}function eo(e){return Zl(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Cg)}function Zl(e,t,n,r){let o=Xl(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>Zl(a,o.array?t:fg.has(Yl(s)),n,r+1));return n.ancestors.delete(o.object),i}function yg(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>Xn.maxDepth||t.nodes>Xn.maxNodes)at();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>Xn.maxStringBytes||t.stringBytes>Xn.maxAggregateStringBytes)at()}function Xl(e,t,n){if(yg(e,t,n),!e||typeof e!=="object")return null;let r=Jl(e);if(t.ancestors.has(e))at();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>Xn.maxKeys)at();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)at();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function Jl(e){if(jl.types.isProxy(e))at();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)at();return t}function at(){throw new ve}function Cg(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=bg(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(...Zi(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...Zi(c));continue}if(c.startsWith("--- ")){let u=n[l+1]??"";if(!u.startsWith("+++ "))continue;t.push(...Ji(Xr(c.slice(4),!0),Xr(u.slice(4),!0))),l++;continue}if(!r)t.push(...Zi(c))}return t}function bg(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 Zi(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return Ul(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return Ul(n[1]);if(e.startsWith("diff --git "))return Sg(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return $l(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return $l(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return Ag(i[1]);return[]}function Sg(e){let t=vg(e);if(t.length===2&&t[0]&&t[1])return Ji(t[0],t[1]);let n=Eg(e);return n?Ji(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function vg(e){let t=[],n=0;while(n<e.length&&t.length<2){while(jt(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&&!jt(e[n]))n++;t.push(e.slice(i,n));continue}let o=Ql(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(jt(e[n]))n++;return n===e.length?t:[]}function Eg(e){let t=0;while(t<e.length&&jt(e[t]))t++;let n=e.length;while(n>t&&jt(e[n-1]))n--;let r=0,o=t;while(o<n){if(!jt(e[o])){o++;continue}let i=o;while(o<n&&jt(e[o]))o++;if(i===t||o===n)continue;if(r++,r>hg)at();if(xg(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function xg(e,t,n,r,o){if(Xi(e,t,n,r,o))return!0;let i=Hl(e,"/",t,n),s=Hl(e,"/",r,o);if(i<=t||s<=r)return!1;if(Xi(e,t,i,r,s))return!1;return Xi(e,i+1,n,s+1,o)}function Xi(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 Hl(e,t,n,r){for(let o=n;o<r;o++)if(e[o]===t)return o;return-1}function jt(e){return e!==void 0&&gg.test(e)}function Ql(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(...zl.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(...zl.encode(Rg(s[0]??""))),o+=2}return null}function Rg(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 Vg(e){return e.replace(/\\(.?)/gs,(t,n)=>n===""?t:jg[n]??t)}function Kg(e){try{return ns(z.realpathSync(e))}catch{return null}}function ns(e){let t=e;while(!0){let n=re.join(t,".git");if(z.existsSync(n))return n;let r=re.dirname(t);if(r===t)return null;t=r}}function qg(e,t,n,r){if(Yg(t))return!0;if(n===null)return!0;let o=oc.spawnSync(n,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:Xg(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&&ac(o.stdout.trim())}function Yg(e){return[re.join(e.commonDir,"config"),re.join(e.gitDir,"config.worktree")].filter((t)=>z.existsSync(t)).some((t)=>Jg(t))}function Zg(){return Og.find((e)=>z.existsSync(e))??null}function Qn(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function Xg(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Qn(t)))}function Jg(e){let t;try{t=z.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(Qg(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=ac(c)}return r}function Qg(e){return e==="include"||e.startsWith("includeif ")}function ac(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function uc(e,t){if(e==="")return null;let n=de(),r=ns(he(e,e,t,n)),o=r?eh(r,e,t,n):null;if(!o)return null;return Object.freeze({entries:Object.freeze([o.entry]),markerFiles:Object.freeze(o.markerFile?[o.markerFile]:[]),directories:Object.freeze(o.directories),hooksDirectories:Object.freeze(o.hooksDirectories)})}function eh(e,t,n,r){try{let o=he(e,t,n,r),i=lc.statSync(e),s=i.isFile()?o:null,a=i.isFile()?ts(e):null,l=(i.isDirectory()?[o]:[a?.gitDir,a?.commonDir]).flatMap((u)=>u?[hn(he(u,t,n,r))]:[]),c=[...new Set(i.isDirectory()?[hn(e.replace(/\\/g,"/")),...l]:l)];return{entry:hn(o),markerFile:s?hn(s):null,directories:c,hooksDirectories:[...new Set(c.flatMap((u)=>{let m=hn(cc.join(u,"hooks").replace(/\\/g,"/"));return[m,hn(he(m,t,n,r))]}))]}}catch{return null}}function hn(e){return process.platform==="win32"?e.toLowerCase():e}var th={realpath:(e)=>{try{return yn.realpathSync(e)}catch{return null}},entryKind:(e)=>{let t=yn.lstatSync(e,{throwIfNoEntry:!1});if(!t)return"missing";return t.isSymbolicLink()?"symlink":"present"},isDirectory:(e)=>{try{return yn.statSync(e).isDirectory()}catch{return!1}}};function mc(){return nh({env:new Map(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),home:Oe(process.env.HOME||no.homedir()),tmpdir:no.tmpdir(),paths:th})}function nh(e,t={}){let n=new Map,r=new Map,o={...e,gitMetadata:(i)=>dc(n,i,()=>uc(i,o)),worktreeFacts:(i)=>dc(r,i,()=>ic(i)),...t};return o}function dc(e,t,n){let r=e.get(t);if(r!==void 0)return r;let o=n();return e.set(t,o),o}var Cn=["fail_closed","paranoid_rm","paranoid_interpreters"],ro={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"}},oo=["standard","strict","paranoid"];function rh(e,t){if(!t)return e;return oo.indexOf(t)>oo.indexOf(e)?t:e}function oh(e){let t=ss(ae.level,e);if(t===void 0||t==="")return;if(oo.includes(t))return t;console.error(`CC Safety Net: ignored invalid ${ae.level.name}=${JSON.stringify(t.slice(0,40))}. Use ${oo.join(", ")}.`);return}function ih(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function fc(e){return ih(ss(ae.auditScope,e))==="all"}function os(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 is(e={},t){let n=e.safety?.level??"standard",r=oh(t),o=rh(n,r),i=ro[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(Vt(ae.strict,t))s.failClosed=!0,a.failClosed="environment",l.failClosed.push(`env ${ae.strict.name}`);if(Vt(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(Vt(ae.paranoidRm,t))s.paranoidRm=!0,a.paranoidRm="environment",l.paranoidRm.push(`env ${ae.paranoidRm.name}`);if(Vt(ae.paranoidInterpreters,t))s.paranoidInterpreters=!0,a.paranoidInterpreters="environment",l.paranoidInterpreters.push(`env ${ae.paranoidInterpreters.name}`);let c=!!e.worktreeMode||Vt(ae.worktree,t);return{strict:s.failClosed,paranoidRm:s.paranoidRm,paranoidInterpreters:s.paranoidInterpreters,worktreeMode:c,effectiveLevel:os(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 Vt(e,t){let n=typeof e==="string"?rs(e,t):ss(e,t);return n==="1"||n?.toLowerCase()==="true"}function rs(e,t){return t.get(e)}function ss(e,t){let n=rs(e.name,t);if(n!==void 0)return n;if(e.legacyName)return rs(e.legacyName,t);return}function er(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 or=require("node:path");var W=require("node:fs"),j=require("node:path");function as(){let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${e()}${e()}`}var sh=Symbol("PolicyFilesystemScope"),ah=Symbol("PolicyFilesystemTarget"),lh=W.constants.O_NOFOLLOW??0;class ye extends Error{name="PolicyFilesystemError";constructor(e){super(`Unable to access ${e} filesystem safely.`)}}function Kt(e,t){return{[sh]:!0,root:j.resolve(e),label:t}}function pc(e,t){let n=j.normalize(t);if(t===""||j.isAbsolute(t)||n===".."||n.startsWith(`..${j.sep}`))throw new ye(e.label);return{[ah]:!0,scope:e,relativePath:n,path:j.join(e.root,n)}}function tr(e,t){return pc(e,j.relative(e.root,j.resolve(t)))}function gc(e,t="rules policy"){let n=j.resolve(e),r=j.parse(n).dir;return pc(Kt(r,t),j.relative(r,n))}function so(e){return yc(e.scope.label,()=>{if(!io(e))return null;let t=W.openSync(e.path,W.constants.O_RDONLY|lh);return ch(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 io(e),r})})}function hc(e,t){if(e.path===t.path)return!0;return yc(e.scope.label,()=>{if(!io(e)||!io(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 yc(e,t,n){try{return t()}catch(r){if(n?.(),r instanceof ye)throw r;throw new ye(e)}}function ch(e,t){try{return t()}finally{W.closeSync(e)}}function io(e,t="file"){let n=uh(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);dh(n,W.realpathSync(i),e.scope.label)}return!0}function uh(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 dh(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 qt=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,Cc="rulebook.json",bc=".cc-safety-net/rules";var Sc=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/;var mh=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,fh=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ph="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),mP=new RegExp(`^${fh}/(${qt.source.slice(1,-1)})/${ph}$`);function gh(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function vc(e){if(ao(e))try{return ls(e),null}catch(t){return t instanceof Error?t.message:String(t)}return qt.test(e)?null:`Local rulebook sources must be bare names matching ${qt}: ${e}`}function ls(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(Sc);if(!t?.[1]||!t[2]||!t[3])throw Error(`Invalid GitHub rulebook source: ${e}`);let n=t[3].lastIndexOf("/");if(n<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);let r=t[3].slice(0,n),o=t[3].slice(n+1);if(!r||!mh.test(r))throw Error(`GitHub rulebook refs must use valid path segments: ${e}`);if(!o||!qt.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:gh(o),name:o}}function ao(e){return Sc.test(e)}var Ec="rule.json",lo="policy.json",xc=".cc-safety-net",hh="rules",yh="CC_SAFETY_NET_HOME",Rc="`cc-safety-net rule update`";function Ch(e){return L.resolve(e,bc)}function bh(e){return L.join(Ch(e),Ec)}function nr(e){return L.join(L.resolve(e),xc,lo)}function cs(e,t={}){return t.userConfigDir??(t.userConfigPath?L.dirname(t.userConfigPath):L.join(Sh(e),hh))}function Sh(e){let t=e.env.get(yh);return t?L.resolve(Oe(t)):L.join(e.home,xc)}function vh(e,t={}){return L.join(cs(e,t),Ec)}function bn(e,t={}){return L.join(L.dirname(cs(e,t)),lo)}function _c(e,t){let n=t.userConfigPath??vh(e,t),r=t.projectConfigPath??bh(t.cwd),o=Eh(e,t),i=xh(r,t.cwd);return{userConfigPath:n,projectConfigPath:r,userScope:o,projectScope:i,userConfigTarget:tr(o,n),projectConfigTarget:tr(i,r)}}function Eh(e,t){let n=t.userConfigPath?L.dirname(L.dirname(L.resolve(t.userConfigPath))):L.dirname(L.resolve(t.userConfigDir??cs(e,t)));return Kt(n,"user policy")}function xh(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 Kt(n,"project policy");return Kt(L.dirname(L.dirname(r)),"project policy")}function wc(e,t){return L.join(e,t,Cc)}var Me=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),kt=/^[a-zA-Z][a-zA-Z0-9_-]*$/,Ot=256,ee=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Ac=new Set(["python","python3","python2","node","ruby","perl"]),co=/^python(?:[23](?:\.\d+)*)?$/,He=new Set(["awk","gawk","nawk","mawk"]),uo=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 Pc="Rulebook exceeds CC Safety Net's safe validation limits.",Tc="Additional rulebook validation errors were omitted.",Ke=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Ic(e){if(us(e.allowed_commands,Ke.maxAllowedCommands)||us(e.rules,Ke.maxRules)||us(e.tests,Ke.maxTests))return!1;let{maxAggregateStringCodeUnits:t,maxTotalBlockArgs:n}=Ke,r=(o,i=!1)=>{if(typeof o!=="string")return!0;if(o.length>Ke.maxStringCodeUnits||i&&o.length>Ke.maxFixtureCommandCodeUnits||o.length>t)return!1;return t-=o.length,!0};if(!r(e.name)||!r(e.version)||!r(e.description)||!r(e.author)||!r(e.migrated_from))return!1;if(Array.isArray(e.allowed_commands)){for(let o of e.allowed_commands)if(!r(o))return!1}if(Array.isArray(e.rules))for(let o of e.rules){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.name)||!r(i.command)||!r(i.subcommand)||!r(i.reason)||!r(i.intent))return!1;let s=i.match&&typeof i.match==="object"?i.match:{};for(let a of[i.block_args,s.command_path,s.any_args,s.exclude_args]){if(!Array.isArray(a))continue;if(a.length>Ke.maxBlockArgsPerRule||a.length>n)return!1;n-=a.length;for(let l of a)if(!r(l))return!1}}if(Array.isArray(e.tests))for(let o of e.tests){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.command,!0)||!r(i.expect)||!r(i.rule))return!1}return!0}function us(e,t){return Array.isArray(e)&&e.length>t}var ds=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var ms=64,fs="Rule config exceeds CC Safety Net's safe source limit.";function O(e){return I(e).toLowerCase()}function I(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}function _e(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 Rh={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},ps=new Set(["--init-file","--rcfile"]);function gs(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(!Rh[e]?.includes(u))continue;if(c+1===t.length)i++;break}return{interactive:o,followingValues:i,commandSelected:s,stdinMode:a,syntaxCheck:l}}function De(e){let t=I(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"&&ps.has(l)&&!s.includes("="))i++;continue}let a=gs(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 rr(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 mo(e){let t={inSingle:!1,inDouble:!1,escaped:!1};for(let n of _h(e))rr(n,t);return t.inSingle||t.inDouble}function _h(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);rr(s,n)}return t}var hs=new Set(["rm","find","xargs","parallel"]),wh=new Set(["git","busybox",...hs,...ee,...Ac,...He]),Ah=new Set(["python","node","ruby","perl"]);function kc(e){let t=O(e);return wh.has(t)||qe(t)}function qe(e){return Ah.has(Ph(e))}function Ph(e){let t=I(e).toLowerCase();return co.test(t)?"python":t}function ys(e){try{let t=so(Th(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=Oh(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 Th(e){return typeof e==="string"?gc(e):e}var _=(e,t)=>({path:e,message:t,kind:"typed"}),me=(e,t)=>({path:e,message:t,kind:"custom"});function Oc(e){let t=new Set;return e.flatMap((n,r)=>{let o=Sn(n)?n.name:void 0;if(typeof o!=="string")return[];if(t.has(o.toLowerCase()))return[me(["rules",r,"name"],`duplicate rule name "${o}"`)];return t.add(o.toLowerCase()),[]})}var Cs=`must be one of ${ds.join(", ")}`,Ih=/^[^/]+\/[^/]+$/,kh=["version","rules","overrides","transparent_wrappers"];function Oh(e){let t=Mh(e);return{errors:bs(Bh(t,kh,(n)=>n.kind==="custom"),": "," "),sources:Hh(e,t)}}function Mh(e){if(!Sn(e))return[_([],"Config must be an object")];let t=Array.isArray(e.rules)&&e.rules.length>ms;return[...e.version===1?[]:[_(["version"],"must be 1")],...Dh(e.rules,t),...Wh(e.overrides),...Fh(e.transparent_wrappers),...t?[]:Lh(e.rules),...Sn(e.overrides)?Object.keys(e.overrides).filter((n)=>!Ih.test(n)).map((n)=>me(["overrides",n],"must use <rulebook-name>/<rule-name>")):[],...zh(e.transparent_wrappers)]}function Dh(e,t){if(e===void 0)return[];if(!Array.isArray(e))return[_(["rules"],"must be an array of rulebook source strings"),...Mc(e,ms)?[_(["rules"],fs)]:[]];if(t)return[{path:["rules"],message:fs,kind:"limit"}];return e.flatMap((n,r)=>{if(typeof n!=="string")return[_(["rules",r],"must be a rulebook source string"),...Nh(n,1)?[_(["rules",r],"must be a non-empty rulebook source string")]:[]];return n===""?[_(["rules",r],"must be a non-empty rulebook source string")]:[]})}function Mc(e,t){let n=Dc(e);return n!==void 0&&!(n<=t)}function Nh(e,t){let n=Dc(e);return n!==void 0&&!(n>=t)}function Dc(e){if(e===null||e===void 0)return;let t=e.length;return t===void 0?void 0:Number(t)}function Lh(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[me(["rules",r],"must be a non-empty rulebook source string")];let o=vc(n);if(o)return[me(["rules",r],o)];if(t.has(n))return[me(["rules",r],`duplicate rulebook source "${n}"`)];return t.add(n),[]})}function Wh(e){if(e===void 0)return[];if(!Sn(e))return[_(["overrides"],"must be an object if provided")];return Object.keys(e).flatMap((t)=>{let n=e[t];if(n==="off")return[];if(!Sn(n))return[_(["overrides",t],'must be "off" or an object')];return[...Gh(n.reason,["overrides",t,"reason"]),...n.intent===void 0||vs(n.intent)?[]:[_(["overrides",t,"intent"],Cs)]]})}function Gh(e,t){if(typeof e!=="string")return[_(t,"required non-empty string"),...Mc(e,Ot)?[_(t,`must be at most ${Ot} characters`)]:[]];if(e==="")return[_(t,"required non-empty string")];return e.length>Ot?[_(t,`must be at most ${Ot} characters`)]:[]}function Fh(e){if(e===void 0)return[];if(!Array.isArray(e))return[_(["transparent_wrappers"],"must be an array of command strings")];return e.flatMap((t,n)=>{if(typeof t!=="string")return[_(["transparent_wrappers",n],"must be a command string")];return kt.test(t)?[]:[_(["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"||!kt.test(n))return[];if(t.has(n))return[me(["transparent_wrappers",r],`duplicate command "${n}"`)];if(kc(n))return[me(["transparent_wrappers",r],`reserved command "${n}" cannot be a wrapper`)];return t.add(n),[]})}function Hh(e,t){let n=Sn(e)?e.rules:void 0;if(!Array.isArray(n))return new Set;if(t.some((o)=>o.path.length===1&&o.path[0]==="rules"))return new Set;let r=new Set(t.filter((o)=>o.path[0]==="rules"&&typeof o.path[1]==="number").map((o)=>o.path[1]));return new Set(n.filter((o,i)=>typeof o==="string"&&!r.has(i)))}function Bh(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 bs(e,t,n){return[...new Set(e.map((r)=>{let o=Ss(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 Ss(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function vs(e){return ds.includes(e)}function Sn(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Lc(e){let t=jh(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}var $h=`required non-empty string up to ${Ot} characters`,Nc="must be a non-empty array of unique non-empty strings",Uh="required non-empty array of non-empty strings";function jh(e){if(!Mt(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Ic(e))return{errors:[Pc],ruleNames:new Set};let t=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...bs(Vh(e,e.rulebook_version===2),": ",": ")];return{errors:t.length>Ke.maxValidationErrors?[...t.slice(0,Ke.maxValidationErrors),Tc]:t,ruleNames:new Set(Wc(e).map((n)=>n.toLowerCase()))}}function Wc(e){let t=Mt(e)?e.rules:void 0;return(Array.isArray(t)?t:[]).flatMap((n)=>{let r=Mt(n)?n.name:void 0;return typeof r==="string"?[r]:[]})}function Vh(e,t){return[...typeof e.name==="string"&&qt.test(e.name)?[]:[_(["name"],"required string matching rule name pattern")],...typeof e.version==="string"&&e.version!==""?[]:[_(["version"],"required non-empty string")],...Kh(e.allowed_commands),...qh(e.rules,t),...Jh(e.tests),...Qh(e),...ey(e)]}function Kh(e){if(!Array.isArray(e))return[_(["allowed_commands"],"required array")];let t=new Set;return[...e.flatMap((n,r)=>typeof n==="string"&&kt.test(n)?[]:[_(["allowed_commands",r],"must match command pattern")]),...e.flatMap((n,r)=>{if(typeof n!=="string"||!kt.test(n))return[];if(t.has(n))return[me(["allowed_commands",r],`duplicate command "${n}"`)];return t.add(n),[]})]}function qh(e,t){if(!Array.isArray(e))return[_(["rules"],"required array")];return[...e.flatMap((n,r)=>{if(!Mt(n))return[_(["rules",r],"must be an object")];return t?Zh(n,["rules",r]):Yh(n,["rules",r])}),...Oc(e)]}function Yh(e,t){return[...Gc(e.name,t),...Fc(e.command,t),...e.subcommand===void 0||typeof e.subcommand==="string"&&kt.test(e.subcommand)?[]:[_([...t,"subcommand"],"must match command pattern")],...fo(e.block_args,[...t,"block_args"],"required non-empty array",!1),...zc(e.reason,t),...Hc(e.intent,t)]}function Zh(e,t){return[...Gc(e.name,t),...Fc(e.command,t),...zc(e.reason,t),...Hc(e.intent,t),...Xh(e.match,[...t,"match"]),...e.subcommand===void 0?[]:[_([...t,"subcommand"],"not supported in rulebook_version 2")],...e.block_args===void 0?[]:[_([...t,"block_args"],"not supported in rulebook_version 2")]]}function Gc(e,t){if(typeof e!=="string")return[_([...t,"name"],"required string")];return qt.test(e)?[]:[_([...t,"name"],"must match rule name pattern")]}function Fc(e,t){return typeof e==="string"&&kt.test(e)?[]:[_([...t,"command"],"required string matching command pattern")]}function zc(e,t){return typeof e==="string"&&e!==""&&e.length<=Ot?[]:[_([...t,"reason"],$h)]}function Hc(e,t){return e===void 0||vs(e)?[]:[_([...t,"intent"],Cs)]}function Xh(e,t){if(!Mt(e))return[_(t,"required object")];return[...fo(e.command_path,[...t,"command_path"],Uh,!1),...e.any_args===void 0?[]:fo(e.any_args,[...t,"any_args"],Nc,!0),...e.exclude_args===void 0?[]:fo(e.exclude_args,[...t,"exclude_args"],Nc,!0)]}function fo(e,t,n,r){if(!Array.isArray(e))return[_(t,n)];let o=e.flatMap((i,s)=>{if(typeof i!=="string")return[_([...t,s],"must be a non-empty string")];return i===""?[me([...t,s],"must be a non-empty string")]:[]});if(e.some((i)=>typeof i!=="string"))return o;return[...o,...e.length===0?[me(t,n)]:[],...r&&new Set(e).size!==e.length?[me(t,"must not contain duplicate values")]:[]]}function Jh(e){if(e===void 0)return[];if(!Array.isArray(e))return[_(["tests"],"must be an array if provided")];return e.flatMap((t,n)=>{if(!Mt(t))return[_(["tests",n],"must be an object")];return[...typeof t.command==="string"&&t.command.trim()!==""?[]:[_(["tests",n,"command"],"required non-empty string")],...t.expect==="blocked"||t.expect==="allowed"?[]:[_(["tests",n,"expect"],'must be "blocked" or "allowed"')],...t.rule===void 0||typeof t.rule==="string"?[]:[_(["tests",n,"rule"],"must be a string if provided")],...t.expect==="blocked"&&typeof t.rule!=="string"?[me(["tests",n,"rule"],"required string for blocked fixtures")]:[]]})}function Qh(e){if(!Array.isArray(e.tests))return[];let t=new Set(Wc(e));return[...new Set(e.tests.flatMap((n)=>Mt(n)&&n.expect==="blocked"&&typeof n.rule==="string"?[n.rule]:[]))].filter((n)=>!t.has(n)).map((n)=>me(["tests"],`blocked fixture references unknown rule "${n}"`))}function ey(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=Mt(n)?n.command:void 0;if(typeof o!=="string"||t.has(o))return[];return[me(["rules",r,"command"],`"${o}" must be listed in allowed_commands`)]})}function Mt(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Kc(e,t){let n=_c(e,t),r;try{r=hc(n.userConfigTarget,n.projectConfigTarget)}catch(f){if(f instanceof ye)return cy(n,f.message);throw f}let o=ys(n.userConfigTarget),i=r?{config:null,errors:[]}:ys(n.projectConfigTarget),s=jc(n.userConfigPath,o.errors),a=jc(n.projectConfigPath,i.errors),l=new Set,c=o.config?Bc(o.config,or.dirname(n.userConfigPath),"user",n.userScope,l):Vc(),u=i.config?Bc(i.config,or.dirname(n.projectConfigPath),"project",n.projectScope,l):Vc(),m=o.config?.overrides??{},d=i.config?.overrides??{};return{rules:[...$c(c.rules,m),...$c(u.rules,d)],transparent_wrappers:ay(o.config,i.config),rulebooks:[...c.rulebooks,...u.rulebooks],errors:[...s,...a,...c.errors,...u.errors],warnings:[...c.warnings,...u.warnings,...c.canValidateOverrides?Uc(m,c.knownRuleIds,n.userConfigPath):[],...c.canValidateOverrides?ly(d,c.knownRuleIds,n.projectConfigPath):[],...u.canValidateOverrides?Uc(d,u.knownRuleIds,n.projectConfigPath):[]],userConfig:o.config??void 0,projectConfig:i.config??void 0,...n}}function Bc(e,t,n,r=Kt(or.dirname(or.dirname(t)),n==="user"?"user policy":"project policy"),o=new Set){let i=[],s=[],a=e.rules.flatMap((c)=>{let u=ny(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:ty(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 ty(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 ny(e,t,n){let r=ry(e),o=wc(t,r),i=iy(o,n);if("error"in i)return{rulebook:null,errors:[i.error]};if(i.content===null)return{rulebook:null,errors:[`missing rulebook file ${o} for ${e}; ${oy(e)}`]};let s=sy(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 ry(e){return ao(e)?ls(e).name:e}function oy(e){return ao(e)?`run ${Rc} to vendor ${e}`:"create that file or remove that source from the rules config"}function iy(e,t){try{return{content:so(tr(t,e))}}catch(n){if(n instanceof ye)return{error:n.message};throw n}}function sy(e){let t;try{t=JSON.parse(e)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:Lc(t)}}catch(n){return{problem:n instanceof Error?n.message:"invalid rulebook"}}}function ay(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function $c(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 Uc(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 ly(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 cy(e,t){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath}}function Vc(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}var Ro=require("node:fs");var qc=[{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"}],Es=new Set(qc.map((e)=>e.id)),po=qc,uy=new Map(po.map((e)=>[e.id,e.intent]));function S(e,t){return{id:e,reason:t,intent:uy.get(e)??"manual_only"}}var xs=[{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"}],go={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},dy=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],my=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Rs=[{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"]},...my.flatMap((e)=>dy.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 ho=[{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"]}],Yc=[{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"}],fy=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],_s=Yc.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})),ws=Yc.flatMap((e)=>fy.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}))),ir={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)$/},As=["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})),Ps=[{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?$/}],py=[...xs,go,...Rs,..._s,...ws,ir,...As,...Ps,...ho].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}})),yo=new Set(ho.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),Ts=new Set(py.map((e)=>e.id));var Ne=require("node:path"),Co=process.platform==="win32",Zc=/[*?]/;function Is(e){let t=e.trim(),n=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(Co?t.replaceAll("\\","/"):t);if(!n)return null;let r=n[1]??"",o=n[2]??"";if(Zc.test(r)||o==="."||o==="..")return null;return{root:r||"/",name:o}}function sr(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function ks(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=sr(e.trim(),t);if(!Ne.isAbsolute(n))return"must be an absolute path or start with ~/";return ar(n,t)}function Os(e,t){let n=Xc(e,t);if(n===null)return"must be a non-empty path string";if(!Ne.isAbsolute(n))return null;if(ar(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 gy="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",hy="cannot cover the guard's own configuration";function Xc(e,t){if(typeof e!=="string"||e.trim()==="")return null;let n=e.trim(),r=Co?n.replaceAll("\\","/"):n;return sr(r.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function Ms(e,t){let n=Xc(e,t);if(n===null)return"must be a non-empty path string";let r=Is(n)?.root??n;if(Zc.test(r))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Ne.isAbsolute(r))return null;if(ar(r,t)!==null)return gy;return yy(r,t)?hy:null}function yy(e,t){let n=bo(e),r=bo(Ne.join(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${Ne.sep}`)}function ar(e,t){let n=bo(e),r=bo(t);if(n===r)return"cannot be the home directory";let o=n.endsWith(Ne.sep)?n:`${n}${Ne.sep}`;if(r.startsWith(o))return"cannot contain the home directory";return null}function bo(e){let t=Ne.normalize(e);if(Co)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(Co?3:1)&&t.endsWith(Ne.sep))t=t.slice(0,-1);return t}var Jc=30,So=1,vo=365;function Qc(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var eu=new Set(po.filter((e)=>e.catastrophic).map((e)=>e.id));function P(e,t){if(!e)return null;if(eu.has(e.id))return e;if(t?.destructiveCommandProtectionEnabled===!1)return null;let n=t?.effectiveDestructiveCommandRules[e.id];return n&&!n.enabled?null:e}function fe(e,t,n){if(eu.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function tu(e,t){return Object.freeze(Object.fromEntries(po.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 nu(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:tu(e,t)})}var ru={standard:0,strict:1,paranoid:2};function su(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:Ds(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:Ds(e.secret_protection.deny_paths,t.secret_protection?.deny_paths),allow_paths:Ds(e.secret_protection.allow_paths,t.secret_protection?.allow_paths)},audit:e.audit},weakenings:Cy(e,t)}}function Ds(e,t){return[...new Set([...e,...t??[]])]}function Cy(e,t){let n=t.safety?.level,r=ro[e.safety.level];return[...n&&ru[n]<ru[e.safety.level]?[`project policy lowers level: ${e.safety.level} -> ${n}`]:[],...Cn.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"]:[],...ou(t.destructive_command_protection?.overrides,(o)=>e.destructive_command_protection.enabled&&e.destructive_command_protection.overrides[o]!=="off"),...ou(t.secret_protection?.overrides,(o)=>e.secret_protection.enabled&&(e.secret_protection.overrides[o]==="on"?!0:e.secret_protection.overrides[o]!=="off"&&!yo.has(o))),...e.destructive_command_protection.enabled?iu(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?iu(e.secret_protection.allow_paths,t.secret_protection?.allow_paths).map((o)=>`project policy adds secret allow path: ${o}`):[]]}function ou(e,t){return Object.entries(e??{}).flatMap(([n,r])=>r==="off"&&t(n)?[`project policy disables rule ${n}`]:[])}function iu(e,t){return(t??[]).filter((n)=>!e.includes(n))}var Ws=new Set(["standard","strict","paranoid"]),uu={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:Jc}};function du(e,t){let n=Py(bn(e,t),e.home),r=_o(nr(t.cwd),e.home),o=Sy(r.parsed,e.home),i=Object.keys(o.policy).length>0?su(n.gui??uu,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?Ls(i.policy):n.policy,errors:s,...a?{fallback:a}:{},...r.exists?{policyScopes:{levelScope:l,weakenings:i?.weakenings??[]}}:{}}}var by="project policy audit settings are ignored; audit is user scope only";function Sy(e,t){if(!Le(e))return{policy:{},diagnostics:[]};let n=Le(e.safety)?e.safety:{},r=Le(e.workflow)?e.workflow:{},o=Le(e.destructive_command_protection)?e.destructive_command_protection:{},i=Le(e.secret_protection)?e.secret_protection:{},s={...Ws.has(n.level)?{level:n.level}:{},...Le(n.overrides)?au({overrides:mu(n.overrides,Cn,["safety","overrides"],Yt)}):{}},a={...typeof o.enabled==="boolean"?{enabled:o.enabled}:{},...o.overrides!==void 0?{overrides:xo(o.overrides,Es,pu,Yt)}:{},...o.allow_paths!==void 0?{allow_paths:En(o.allow_paths,ks,t,["destructive_command_protection","allow_paths"],Yt)}:{}},l={...typeof i.enabled==="boolean"?{enabled:i.enabled}:{},...i.overrides!==void 0?{overrides:xo(i.overrides,Ts,gu,Yt)}:{},...i.deny_paths!==void 0?{deny_paths:En(i.deny_paths,Os,t,["secret_protection","deny_paths"],Yt)}:{},...i.allow_paths!==void 0?{allow_paths:En(i.allow_paths,Ms,t,["secret_protection","allow_paths"],Yt)}:{}};return{policy:au({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?[]:[by]}}function mu(e,t,n,r){return Object.fromEntries(t.flatMap((o)=>{let i=e[o];if(typeof i==="boolean")return[[o,i]];if(i!==void 0)r(_([...n,o],Gs));return[]}))}function au(e){return Object.fromEntries(Object.entries(e).flatMap((t)=>Object.keys(t[1]).length>0?[t]:[]))}var Yt=()=>{return},Gs="must be a boolean",Fs="must be an object if provided",fu=`must be an integer between ${So} and ${vo}`,pu={path:["destructive_command_protection","overrides"],label:"destructive command"},gu={path:["secret_protection","overrides"],label:"secret protection"},vy=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Ey(e,t){let n=[];return{policy:hu(e,t,(o)=>{n.push(o)}),issues:n}}function xy(e,t){return hu(e,t,Yt)}function hu(e,t,n){if(!Le(e))return n(_([],"Config must be an object")),Eo();if(e.version!==1)n(_(["version"],"must be 1"));let r=vn(e.safety,["safety"],["level","overrides"],n),o=vn(r.overrides,["safety","overrides"],Cn,n),i=vn(e.workflow,["workflow"],["worktree_mode"],n),s=vn(e.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],n),a=vn(e.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],n),l=vn(e.audit,["audit"],["retention_days"],n);return yu(e,vy,[],n),{version:1,safety:{level:Ry(r.level,n),overrides:mu(o,Cn,["safety","overrides"],n)},workflow:{worktree_mode:Ns(i.worktree_mode,["workflow","worktree_mode"],!1,n)},destructive_command_protection:{enabled:Ns(s.enabled,["destructive_command_protection","enabled"],!0,n),overrides:xo(s.overrides,Es,pu,n),allow_paths:En(s.allow_paths,ks,t,["destructive_command_protection","allow_paths"],n)},secret_protection:{enabled:Ns(a.enabled,["secret_protection","enabled"],!0,n),overrides:xo(a.overrides,Ts,gu,n),deny_paths:En(a.deny_paths,Os,t,["secret_protection","deny_paths"],n),allow_paths:En(a.allow_paths,Ms,t,["secret_protection","allow_paths"],n)},audit:{retention_days:_y(l.retention_days,n)}}}function vn(e,t,n,r){if(e===void 0)return{};if(!Le(e))return r(_(t,Fs)),{};return yu(e,n,t,r),e}function yu(e,t,n,r){for(let o of Object.keys(e).filter((i)=>!t.includes(i)))r({path:n,message:o,kind:"unknownKeys"})}function Ry(e,t){if(e===void 0)return"standard";if(Ws.has(e))return e;return t(_(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Ns(e,t,n,r){if(typeof e==="boolean")return e;if(e!==void 0)r(_(t,Gs));return n}function _y(e,t){if(!(e===void 0||typeof e==="number"&&Number.isInteger(e)&&e>=So&&e<=vo))t(_(["audit","retention_days"],fu));return Qc(e)}function xo(e,t,n,r){if(e===void 0)return{};if(!Le(e))return r(_(n.path,Fs)),{};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(_([...n.path,o],'must be "on" or "off"')),[]}))}function En(e,t,n,r,o){if(e===void 0)return[];if(!Array.isArray(e))return o(_(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"?me([...r,s],a):_([...r,s],a)),[]})}function Le(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Eo(){return structuredClone(uu)}function _o(e,t){if(!Ro.existsSync(e))return{exists:!1,policy:Eo(),errors:[]};try{let n=Ro.readFileSync(e,"utf-8");if(!n.trim())return{exists:!0,policy:Eo(),errors:[`${e}: Config file is empty`],fallback:"defaults"};let r=JSON.parse(n),o=Ey(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}: ${Ay(i)}`),fallback:Le(r)?"salvaged":"defaults"}}catch(n){let r=n instanceof Error?n.message:String(n);return{exists:!0,policy:Eo(),errors:[`${e}: ${n instanceof SyntaxError?"Invalid JSON":r}`],fallback:"defaults"}}}var wy=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[Fs,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[Gs,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[fu,`not an integer between ${So} and ${vo}`]]);function Ay(e){let t=Ss(e.path);if(e.kind==="unknownKeys")return`${t===""?"":`${t}.`}${e.message}: unknown field`;if(e.kind==="key")return`${t}: unknown rule id`;let n=wy.get(e.message)??e.message;return t===""?n:`${t}: ${n}`}function Py(e,t){let n=_o(e,t);if(!n.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!Le(r))return{policy:cu(),errors:[]};let o=xy(r,t);return{policy:Ls(o),gui:o,errors:[],levelPresent:lu(r)}}if(n.parsed===void 0)return{policy:cu(),errors:n.errors,...n.fallback?{fallback:n.fallback}:{}};return{policy:Ls(n.policy),gui:n.policy,errors:n.errors,...n.fallback?{fallback:n.fallback}:{},levelPresent:lu(n.parsed)}}function lu(e){let t=Le(e)&&Le(e.safety)?e.safety:{};return Ws.has(t.level)}function Cu(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...yo].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function cu(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Cu({}),denyPaths:[],allowPaths:[]}}}function Ls(e){return{safety:Ty(e.safety),worktreeMode:e.workflow.worktree_mode,destructiveCommandProtectionEnabled:e.destructive_command_protection.enabled,destructiveCommandRuleOverrides:e.destructive_command_protection.overrides,destructiveCommandAllowPaths:e.destructive_command_protection.allow_paths,secretProtection:{enabled:e.secret_protection.enabled,disabledRules:Cu(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function Ty(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 bu(e,t){let n=Kc(e,t),r=du(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}),...My(l.spec)?{source:l.spec}:{}}:{},...c&&typeof c==="object"?{override:Object.freeze({type:"reason",reason:c.reason})}:{}})]})));return Dy(o,Iy(n,r),s,r.policyScopes)}function Iy(e,t){let n=Oy(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:Ny(e.errors.length>0?ky(e.errors):void 0,e.warnings.length>0?Hs(e.warnings.join("; ")):void 0,n)}}function ky(e){return`${Hs(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Oy(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 My(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function Dy(e,t,n=Object.freeze({}),r){let o=zs(structuredClone(e)),i=r?{policyScopes:zs(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 zs(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))zs(t);return Object.freeze(e)}function Ny(...e){return Hs(e.filter((t)=>!!t).join("; "))}function Hs(e){return/[.!?]$/.test(e)?e:`${e}.`}function Su(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:Bs(t.fail_closed,e.strict,"strict"),paranoid_rm:Bs(t.paranoid_rm,e.paranoidRm,"paranoidRm"),paranoid_interpreters:Bs(t.paranoid_interpreters,e.paranoidInterpreters,"paranoidInterpreters")};return{policy:nu(e.policySnapshot.policy,i),effectiveCapabilities:i,effectiveLevel:os({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}function Bs(e,t,n){if(t===void 0||t===e.enabled)return e;return{enabled:t,source:"capability_override",sources:[...e.sources,`analysis options.${n}`]}}function lr(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 Ly=/^[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)=>!Ly.test(s.text));return i?.provenance==="literal"?i.text:void 0}var Dt=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Ao(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Wy(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)=>we(t)))})}function Po(e,t,n){e.push(n),t.reset()}function To(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 $s(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 xn(e,t,n,r,o,i,s){return $s({text:r,raw:e.slice(t,n),span:{start:t,end:n},provenance:o,quoted:i,...s?{parts:s}:{}})}function we(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 Wy(t);if(t.kind==="group"||t.kind==="function")return Object.freeze({...t,span:Object.freeze(t.span),body:we(t.body)});return Object.freeze({...t,span:Object.freeze(t.span)})}))})}function Us(e,t,n){if(t>=n||Eu(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!Eu(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=vu(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=vu(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
|
|
12
|
-
`?d+2:d+1,
|
|
13
|
-
`&&e[d]!=="\r")d++;continue}let p=c.start===-1?
|
|
14
|
-
`){a+=2;continue}s+=h,a+=2;continue}let g=f==="$"||f==="<"||f===">"||f==="`"?
|
|
4
|
+
`)}function Qi(e,t){if(e.decision.kind!=="deny")return;let n=t.includeEvidence?e.decision.evidence:void 0;return{reason:e.decision.reason,ruleId:e.decision.ruleId,intent:e.decision.intent,command:n?.command,segment:n?.segment,toolName:t.toolName,...e.configFallback?{configWarning:e.configFallback.reason}:{},...e.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function xn(e={}){return{reason:or,intent:"stop_and_explain",command:e.command,segment:e.segment??e.command,toolName:e.toolName}}var hg={session:{unusable:{reason:"CC Safety Net cannot check tool calls because the session's working directory or workspace root no longer exists, is inaccessible, is not a directory, or uses an unsupported path form. Ask the user to restart the session from an existing directory.",intent:"hard_stop"},"outside-workspace":{reason:"CC Safety Net cannot check tool calls because the session's working directory is outside its workspace roots. Ask the user to restart the session from a directory inside the workspace.",intent:"hard_stop"}},requested:{unusable:{reason:"CC Safety Net could not use the requested working directory because it does not exist, is inaccessible, is not a directory, or uses an unsupported path form. Use an existing accessible working directory. If the requested directory is missing, create it from an accessible location before retrying the command.",intent:"use_alternative"},"outside-workspace":{reason:"CC Safety Net could not use the requested working directory because it is outside the session's workspace. Use a working directory inside the workspace.",intent:"use_alternative"}}};function io(e,t={}){return{...hg[e.directory][e.problem],command:t.command,toolName:t.toolName,cwd:e.cwd}}function Hl(e){return zl({...e,redact:Ct})}function Bl(e){return zl({...e,redact:Ct,askUser:!0})}function $l(e){return Ct(e instanceof Error?e.message:String(e))}var Re=require("node:path");var yg=256,so=new Set(["CC_SAFETY_NET_HOME","CLAUDE_CONFIG_DIR","CODEX_HOME","COPILOT_HOME","GEMINI_CLI_HOME","GROK_HOME","HOME","KIMI_CODE_HOME","KIMI_SHARE_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","ProgramData","TMPDIR","XDG_CONFIG_HOME","XDG_DATA_HOME"]);function Me(e,t=process.platform){if(t!=="win32")return e;return e.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function bt(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function rs(e,t){return es(e,0,t)}function es(e,t,n){let r="",o=0;while(o<e.length){if(e[o]!=="$"){r+=e[o],o++;continue}if(e[o+1]==="{"){let s=ts(e,o+2),a=Cg(e,o,t);if(a===null){if(so.has(s))throw new N("pathEnvironmentExpansion");r+=e.slice(o);break}let l=e.slice(o,a+1);r+=bg(l,t,n),o=a+1;continue}let i=ts(e,o+1);if(!i){r+="$",o++;continue}r+=ns(i,n)??`$${i}`,o+=i.length+1}return r}function Cg(e,t,n){let r=1;for(let o=t+2;o<e.length;o++){if(e[o]==="\\"){o++;continue}if(e[o]==="$"&&e[o+1]==="{"){if(r++,n+r>X.pathEnvironmentExpansion.cap)throw new N("pathEnvironmentExpansion");o++;continue}if(e[o]!=="}")continue;if(r--,r===0)return o}return null}function bg(e,t,n){let r=e.slice(2,-1),o=ts(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return ns(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(so.has(o))throw new N("pathEnvironmentExpansion");return e}if(!so.has(o))return e;if(s.endsWith("="))throw new N("pathEnvironmentExpansion");let a=ns(o,n),l=s.startsWith(":")?a!==null&&a!=="":a!==null;if(s.endsWith("?")&&!l)throw new N("pathEnvironmentExpansion");if(s.endsWith("-")||s.endsWith("?"))return l?a??"":es(i.slice(s.length),t+1,n);return l?es(i.slice(s.length),t+1,n):""}function ts(e,t){if(!/[A-Za-z_]/.test(e[t]??""))return"";let n=t+1;while(/[A-Za-z0-9_]/.test(e[n]??""))n++;return e.slice(t,n)}function ns(e,t){if(!so.has(e))return null;if(e==="HOME")return t.env.get("HOME")??t.home;return t.env.get(e)??null}function O(e,t,n){if(!e)return e;let r=n.resolvedPaths.get(e);if(r!==void 0)return r;let o=[],i=e;while(!0){jl(n,i);let s=t.realpath(i);if(s!==null)return Ul(n,e,s,o);let a=Re.dirname(i);if(a===i||o.length>=yg)return Ul(n,e,i,o);o.push(Re.basename(i)),i=a}}function Ul(e,t,n,r){let o=r.length===0?n:Re.join(n,...r.reverse());return e.resolvedPaths.set(t,o),o}function Sg(e,t,n){let r=n.resolvedPaths.get(e);if(r!==void 0)return r;jl(n,e);let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function jl(e,t){e.charge("realpathAttempts"),e.charge("processedCandidateBytes",Buffer.byteLength(t))}function he(e,t,n,r){let o=Kl(e,t,n);if(!o)return"";return O(o,n.paths,r).replace(/\\/g,"/")}function Vl(e,t,n,r,o){let i=Kl(e,t,n);if(!i)return null;if(o(Re.basename(i)))return O(i,n.paths,r).replace(/\\/g,"/");let s=Sg(i,n.paths,r);return s===null?null:s.replace(/\\/g,"/")}function Kl(e,t,n){let r=n.home,o=rs(e.trim(),n).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?Re.resolve(r,o.slice(2)):o,s=Me(i);return Re.normalize(Re.isAbsolute(s)?s:Re.resolve(t,s))}var Ql=require("node:util"),vg=new Set(["applypatch","patch"]),Eg=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),xg=new Set(["grep","grepsearch","rg"]),Rg=new Set(["find","findbyname","glob"]),wg=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),_g=new Set(["command","diff","input","patch","patchtext"]),ql=new TextEncoder,Ag=new TextDecoder,Pg=/\s/,Tg=64;class be extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var ir=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function ec(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function lo(e){return wg.has(ec(e))}function tc(e){let t=ec(e);if(vg.has(t))return"patch";if(xg.has(t))return"grep";if(Rg.has(t))return"glob";if(Eg.has(t))return"path";return"unknown"}function Nt(e){if(!e||typeof e!=="object")return;sc(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)dt();return}if(t.get||t.set)dt();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function co(e,t){return nc(e,t,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function nc(e,t,n,r,o){let i=ic(e,r,o);if(typeof e==="string")return n?[e]:[];if(!i)return[];let s=i.entries.flatMap(([a,l])=>nc(l,t,i.array?n:t.has(rc(a)),r,o+1));return r.ancestors.delete(i.object),s}function rc(e){return e.replace(/-/g,"_").toLowerCase()}function uo(e){return oc(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Ig)}function oc(e,t,n,r){let o=ic(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>oc(a,o.array?t:_g.has(rc(s)),n,r+1));return n.ancestors.delete(o.object),i}function kg(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>ir.maxDepth||t.nodes>ir.maxNodes)dt();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>ir.maxStringBytes||t.stringBytes>ir.maxAggregateStringBytes)dt()}function ic(e,t,n){if(kg(e,t,n),!e||typeof e!=="object")return null;let r=sc(e);if(t.ancestors.has(e))dt();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>ir.maxKeys)dt();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)dt();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function sc(e){if(Ql.types.isProxy(e))dt();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)dt();return t}function dt(){throw new be}function Ig(e){let t=[],n=e.split(/\r?\n/),r=!1,o=!1,i=null,s=null,a=()=>{o=!1,i=null,s=null};for(let l=0;l<n.length;l++){let c=n[l]??"";if(c==="*** Begin Patch"){r=!0,a();continue}if(c==="*** End Patch"){r=!1,a();continue}if(c.startsWith("@@")){let u=Og(c);if(o=!0,i=u?.oldLines??null,s=u?.newLines??null,i===0&&s===0)a();continue}if(o&&i!==null&&s!==null){let u=c.startsWith(" ")||c.startsWith("-")?1:0,m=c.startsWith(" ")||c.startsWith("+")?1:0;if(i=Math.max(0,i-u),s=Math.max(0,s-m),i===0&&s===0)a();continue}if(c.startsWith("*** ")){a(),t.push(...os(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...os(c));continue}if(c.startsWith("--- ")){let u=n[l+1]??"";if(!u.startsWith("+++ "))continue;t.push(...ss(ao(c.slice(4),!0),ao(u.slice(4),!0))),l++;continue}if(!r)t.push(...os(c))}return t}function Og(e){let t=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(e);if(!t)return null;return{oldLines:Number(t[1]??1),newLines:Number(t[2]??1)}}function os(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return Jl(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return Jl(n[1]);if(e.startsWith("diff --git "))return Mg(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return Xl(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return Xl(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return zg(i[1]);return[]}function Mg(e){let t=Dg(e);if(t.length===2&&t[0]&&t[1])return ss(t[0],t[1]);let n=Ng(e);return n?ss(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function Dg(e){let t=[],n=0;while(n<e.length&&t.length<2){while(Qt(e[n]))n++;if(n>=e.length)break;let r=e[n]==='"'||e[n]==="'"?e[n]:void 0;if(!r){let i=n;while(n<e.length&&!Qt(e[n]))n++;t.push(e.slice(i,n));continue}let o=ac(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while(Qt(e[n]))n++;return n===e.length?t:[]}function Ng(e){let t=0;while(t<e.length&&Qt(e[t]))t++;let n=e.length;while(n>t&&Qt(e[n-1]))n--;let r=0,o=t;while(o<n){if(!Qt(e[o])){o++;continue}let i=o;while(o<n&&Qt(e[o]))o++;if(i===t||o===n)continue;if(r++,r>Tg)dt();if(Lg(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function Lg(e,t,n,r,o){if(is(e,t,n,r,o))return!0;let i=Yl(e,"/",t,n),s=Yl(e,"/",r,o);if(i<=t||s<=r)return!1;if(is(e,t,i,r,s))return!1;return is(e,i+1,n,s+1,o)}function is(e,t,n,r,o){if(n-t!==o-r)return!1;for(let i=0;i<n-t;i++)if(e[t+i]!==e[r+i])return!1;return!0}function Yl(e,t,n,r){for(let o=n;o<r;o++)if(e[o]===t)return o;return-1}function Qt(e){return e!==void 0&&Pg.test(e)}function ac(e,t,n){let r=[],o=t+1;while(o<e.length){let i=String.fromCodePoint(e.codePointAt(o)??0);if(i===n)return{value:Ag.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...ql.encode(i)),o+=i.length;continue}let s=e.slice(o+1),a=/^[0-7]{1,3}/.exec(s)?.[0];if(a){r.push(Number.parseInt(a,8)),o+=a.length+1;continue}r.push(...ql.encode(Wg(s[0]??""))),o+=2}return null}function Wg(e){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
5
|
+
`,r:"\r",t:"\t",v:"\v"}[e]??e}function Gg(e){return sr(Hg(e))}function ss(e,t){if(e==="/dev/null")return Zl(t);if(t==="/dev/null")return Zl(e);if(e.startsWith("a/")&&t.startsWith("b/"))return[e.slice(2),t.slice(2)].flatMap(sr);let n=Fg(e,t)??(e===t?lc(e):null);return[e,t,...n?[n]:[]].flatMap(sr)}function Zl(e){let t=lc(e);return[e,...t?[t]:[]].flatMap(sr)}function lc(e){let t=e.indexOf("/");return t>0&&t<e.length-1?e.slice(t+1):null}function Fg(e,t){let n=e.indexOf("/"),r=t.indexOf("/");if(n<1||r<1)return null;if(e.slice(0,n)===t.slice(0,r))return null;let o=e.slice(n+1);return o===t.slice(r+1)?o:null}function Xl(e){return Gg(ao(e,!0))}function zg(e){return sr(ao(e,!1))}function ao(e,t){let n=e.trim(),r=n[0]==='"'||n[0]==="'"?n[0]:void 0;if(r){let o=ac(n,0,r);if(o&&(t||n.slice(o.end).trim()===""))return o.value}return t?n.split("\t",1)[0]?.trim()??"":n}function Hg(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function sr(e){return e===""||e==="/dev/null"?[]:[e]}function Jl(e){let t=e.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return t===""||t==="/dev/null"?[]:[t]}var Ye=require("node:path");function St(e,t,n){if(bt(e))return;let r=t.flatMap((i)=>mo(i,n));if(!r[0])return;let o=mo(Ye.isAbsolute(e)?e:Ye.resolve(r[0],e),n)[0];if(!o)return;return r.some((i)=>ar(o,i))?o:void 0}function as(e,t,n){if(bt(e))return;return mo(Ye.isAbsolute(e)?e:Ye.resolve(t,e),n)[0]}function vt(e,t){return e.flatMap((n)=>mo(n,t))[0]}function Et(e,t,n){return as(e,t,n)?"outside-workspace":"unusable"}function mo(e,t){let n=t.realpath(e);if(n===null)return[];return t.isDirectory(n)?[n]:[]}function ar(e,t){let n=Ye.relative(t,e);return n===""||n!==".."&&!n.startsWith(`..${Ye.sep}`)&&!Ye.isAbsolute(n)}var Bg=8388608;async function cc(e){let t=[],n=0;for await(let r of e){let o=typeof r==="string"?Buffer.from(r,"utf-8"):Buffer.from(r.buffer,r.byteOffset,r.byteLength);if(n+=o.byteLength,n>Bg)throw $g(e),Error("hook input byte limit exceeded");t.push(o)}return Buffer.concat(t,n).toString("utf-8")}function $g(e){let t=e.destroy??e.cancel;if(!t)return;try{Promise.resolve(t.call(e)).catch(()=>{})}catch{}}function fo(e,t,n){try{return JSON.parse(e)}catch{t({reason:n});return}}function oe(e,t){let n=t.get(e);return n?{kind:"command",shell:n}:{kind:tc(e)}}function uc(e,t,n,r,o,i){let s=e===void 0?i:e;if(typeof s!=="string"||s.trim()==="")return Se(r,t,n),null;let a=vt([s],o);if(a)return{configCwd:a,executionCwd:a};return He(r,t,n,{directory:"session",problem:"unusable",cwd:s}),null}function Se(e,t,n){e(xn({command:dc(t),toolName:n}))}function He(e,t,n,r){e(io(r,{command:dc(t),toolName:n}))}function dc(e){try{return Nt(e)}catch(t){if(!(t instanceof be))throw t;return}}var wn=require("node:fs"),po=require("node:os");var yc=require("node:fs"),Cc=require("node:path");var fc=require("node:child_process"),F=require("node:fs"),re=require("node:path"),Ug=["/usr/bin/git","/usr/local/bin/git","/opt/homebrew/bin/git","C:\\Program Files\\Git\\cmd\\git.exe","C:\\Program Files\\Git\\bin\\git.exe"],jg=5000;function pc(e,t=lh(),n=jg){let r=Vg(e),o=r===null?null:Kg(r);if(r===null||o===null)return null;let i=sh(r,o,t,n);return i===null?null:{recursiveSubmodules:i}}function Vg(e){try{let t=F.realpathSync(re.resolve(e));return F.statSync(t).isDirectory()?t:null}catch{return null}}function Kg(e){let t=ih(e);if(!t)return null;try{let n=F.lstatSync(t);if(n.isSymbolicLink()||!n.isFile())return null;let r=ls(t);if(!r?.commonDir)return null;if(!Zg(r.gitDir,t))return null;return Xg(r.gitDir,re.dirname(t))?{gitDir:r.gitDir,commonDir:r.commonDir}:null}catch{return null}}function ls(e){try{let t=qg(e);if(!t)return null;let n=F.realpathSync(re.isAbsolute(t)?t:re.resolve(re.dirname(e),t));if(!F.statSync(n).isDirectory())return null;return{gitDir:n,commonDir:Yg(n)}}catch{return null}}function qg(e){let t=F.readFileSync(e,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!t.startsWith("gitdir:"))return null;return t.slice(7).trim()||null}function Yg(e){try{let t=F.readFileSync(re.join(e,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!t)return null;let n=F.realpathSync(re.isAbsolute(t)?t:re.resolve(e,t));return F.statSync(n).isDirectory()?n:null}catch{return null}}function Zg(e,t){let n=Jg(e);return n===null?!1:gc(e,n,t)}function Xg(e,t){let n=Qg(e);return n===null?!0:gc(e,n,t)}function Jg(e){let t=re.join(e,"gitdir");if(!F.existsSync(t))return null;let n=F.readFileSync(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return n===""?null:n}function Qg(e){let t=re.join(e,"config.worktree");return F.existsSync(t)?th(t):null}function gc(e,t,n){try{return eh(re.isAbsolute(t)?t:re.resolve(e,t),n)}catch{return!1}}function eh(e,t){try{let n=F.statSync(e),r=F.statSync(t);if(n.ino!==0&&r.ino!==0&&n.dev===r.dev&&n.ino===r.ino)return!0}catch{}return mc(F.realpathSync.native(e))===mc(F.realpathSync.native(t))}function mc(e){let t=e.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),n=t.length>1&&t.endsWith("/")?t.slice(0,-1):t;return process.platform==="win32"?n.toLowerCase():n}function th(e){let t=F.readFileSync(e,"utf-8"),n=!1,r=null;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i===""||i.startsWith("#")||i.startsWith(";"))continue;if(i.startsWith("[")){n=/^\[core\]$/i.test(i);continue}if(!n)continue;let s=i.match(/^worktree\s*=\s*(.*)$/i);if(s)r=nh(s[1]??"")}return r}function nh(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;return oh(t.slice(1,-1))}var rh={"\\":"\\",'"':'"',n:`
|
|
6
|
+
`,t:"\t",b:"\b"};function oh(e){return e.replace(/\\(.?)/gs,(t,n)=>n===""?t:rh[n]??t)}function ih(e){try{return cs(F.realpathSync(e))}catch{return null}}function cs(e){let t=e;while(!0){let n=re.join(t,".git");if(F.existsSync(n))return n;let r=re.dirname(t);if(r===t)return null;t=r}}function sh(e,t,n,r){if(ah(t))return!0;if(n===null)return!0;let o=fc.spawnSync(n,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:ch(process.env),stdio:["ignore","pipe","ignore"],timeout:r});if(o.error!==void 0||o.status!==0&&o.status!==1)return null;return o.status===0&&hc(o.stdout.trim())}function ah(e){return[re.join(e.commonDir,"config"),re.join(e.gitDir,"config.worktree")].filter((t)=>F.existsSync(t)).some((t)=>uh(t))}function lh(){return Ug.find((e)=>F.existsSync(e))??null}function lr(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function ch(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!lr(t)))}function uh(e){let t;try{t=F.readFileSync(e,"utf-8")}catch{return!0}let n="",r=!1;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i===""||i.startsWith("#")||i.startsWith(";"))continue;let s=i.match(/^\[([^\]]+)\]$/);if(s){n=s[1]?.trim().toLowerCase()??"";continue}let a=i.indexOf("="),l=(a===-1?i:i.slice(0,a)).trim().toLowerCase(),c=a===-1?"true":i.slice(a+1).trim();if(dh(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=hc(c)}return r}function dh(e){return e==="include"||e.startsWith("includeif ")}function hc(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function bc(e,t){if(e==="")return null;let n=ue(),r=cs(he(e,e,t,n)),o=r?mh(r,e,t,n):null;if(!o)return null;return Object.freeze({entries:Object.freeze([o.entry]),markerFiles:Object.freeze(o.markerFile?[o.markerFile]:[]),directories:Object.freeze(o.directories),hooksDirectories:Object.freeze(o.hooksDirectories)})}function mh(e,t,n,r){try{let o=he(e,t,n,r),i=yc.statSync(e),s=i.isFile()?o:null,a=i.isFile()?ls(e):null,l=(i.isDirectory()?[o]:[a?.gitDir,a?.commonDir]).flatMap((u)=>u?[Rn(he(u,t,n,r))]:[]),c=[...new Set(i.isDirectory()?[Rn(e.replace(/\\/g,"/")),...l]:l)];return{entry:Rn(o),markerFile:s?Rn(s):null,directories:c,hooksDirectories:[...new Set(c.flatMap((u)=>{let m=Rn(Cc.join(u,"hooks").replace(/\\/g,"/"));return[m,Rn(he(m,t,n,r))]}))]}}catch{return null}}function Rn(e){return process.platform==="win32"?e.toLowerCase():e}var fh={realpath:(e)=>{try{return wn.realpathSync(e)}catch{return null}},entryKind:(e)=>{let t=wn.lstatSync(e,{throwIfNoEntry:!1});if(!t)return"missing";return t.isSymbolicLink()?"symlink":"present"},isDirectory:(e)=>{try{return wn.statSync(e).isDirectory()}catch{return!1}}};function vc(){return ph({env:new Map(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),home:Me(process.env.HOME||po.homedir()),tmpdir:po.tmpdir(),paths:fh})}function ph(e,t={}){let n=new Map,r=new Map,o={...e,gitMetadata:(i)=>Sc(n,i,()=>bc(i,o)),worktreeFacts:(i)=>Sc(r,i,()=>pc(i)),...t};return o}function Sc(e,t,n){let r=e.get(t);if(r!==void 0)return r;let o=n();return e.set(t,o),o}var _n=["fail_closed","paranoid_rm","paranoid_interpreters"],go={standard:{fail_closed:!1,paranoid_rm:!1,paranoid_interpreters:!1},strict:{fail_closed:!0,paranoid_rm:!1,paranoid_interpreters:!1},paranoid:{fail_closed:!0,paranoid_rm:!0,paranoid_interpreters:!0}};var ae={level:{name:"CC_SAFETY_NET_LEVEL"},strict:{name:"CC_SAFETY_NET_STRICT",legacyName:"SAFETY_NET_STRICT"},paranoid:{name:"CC_SAFETY_NET_PARANOID",legacyName:"SAFETY_NET_PARANOID"},paranoidRm:{name:"CC_SAFETY_NET_PARANOID_RM",legacyName:"SAFETY_NET_PARANOID_RM"},paranoidInterpreters:{name:"CC_SAFETY_NET_PARANOID_INTERPRETERS",legacyName:"SAFETY_NET_PARANOID_INTERPRETERS"},worktree:{name:"CC_SAFETY_NET_WORKTREE",legacyName:"SAFETY_NET_WORKTREE"},debug:{name:"CC_SAFETY_NET_DEBUG"},auditScope:{name:"CC_SAFETY_NET_AUDIT_SCOPE"}},ho=["standard","strict","paranoid"];function gh(e,t){if(!t)return e;return ho.indexOf(t)>ho.indexOf(e)?t:e}function hh(e){let t=fs(ae.level,e);if(t===void 0||t==="")return;if(ho.includes(t))return t;console.error(`CC Safety Net: ignored invalid ${ae.level.name}=${JSON.stringify(t.slice(0,40))}. Use ${ho.join(", ")}.`);return}function yh(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function Ec(e){return yh(fs(ae.auditScope,e))==="all"}function ds(e){if(e.failClosed&&e.paranoidRm&&e.paranoidInterpreters)return"paranoid";if(e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"strict";if(!e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"standard";return"custom"}function ms(e={},t){let n=e.safety?.level??"standard",r=hh(t),o=gh(n,r),i=go[o],s={failClosed:i.fail_closed,paranoidRm:i.paranoid_rm,paranoidInterpreters:i.paranoid_interpreters},a={failClosed:o===n?"preset":"environment",paranoidRm:o===n?"preset":"environment",paranoidInterpreters:o===n?"preset":"environment"},l={failClosed:[`policy safety.level=${n}`],paranoidRm:[`policy safety.level=${n}`],paranoidInterpreters:[`policy safety.level=${n}`]};if(o!==n)l.failClosed.push(`env ${ae.level.name}=${r}`),l.paranoidRm.push(`env ${ae.level.name}=${r}`),l.paranoidInterpreters.push(`env ${ae.level.name}=${r}`);if(e.safety?.overrides?.failClosed!==void 0)s.failClosed=e.safety.overrides.failClosed,a.failClosed="capability_override",l.failClosed.push("policy safety.overrides.fail_closed");if(e.safety?.overrides?.paranoidRm!==void 0)s.paranoidRm=e.safety.overrides.paranoidRm,a.paranoidRm="capability_override",l.paranoidRm.push("policy safety.overrides.paranoid_rm");if(e.safety?.overrides?.paranoidInterpreters!==void 0)s.paranoidInterpreters=e.safety.overrides.paranoidInterpreters,a.paranoidInterpreters="capability_override",l.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(en(ae.strict,t))s.failClosed=!0,a.failClosed="environment",l.failClosed.push(`env ${ae.strict.name}`);if(en(ae.paranoid,t))s.paranoidRm=!0,s.paranoidInterpreters=!0,a.paranoidRm="environment",a.paranoidInterpreters="environment",l.paranoidRm.push(`env ${ae.paranoid.name}`),l.paranoidInterpreters.push(`env ${ae.paranoid.name}`);if(en(ae.paranoidRm,t))s.paranoidRm=!0,a.paranoidRm="environment",l.paranoidRm.push(`env ${ae.paranoidRm.name}`);if(en(ae.paranoidInterpreters,t))s.paranoidInterpreters=!0,a.paranoidInterpreters="environment",l.paranoidInterpreters.push(`env ${ae.paranoidInterpreters.name}`);let c=!!e.worktreeMode||en(ae.worktree,t);return{strict:s.failClosed,paranoidRm:s.paranoidRm,paranoidInterpreters:s.paranoidInterpreters,worktreeMode:c,effectiveLevel:ds(s),capabilities:{fail_closed:{enabled:s.failClosed,source:a.failClosed,sources:l.failClosed},paranoid_rm:{enabled:s.paranoidRm,source:a.paranoidRm,sources:l.paranoidRm},paranoid_interpreters:{enabled:s.paranoidInterpreters,source:a.paranoidInterpreters,sources:l.paranoidInterpreters}}}}function en(e,t){let n=typeof e==="string"?us(e,t):fs(e,t);return n==="1"||n?.toLowerCase()==="true"}function us(e,t){return t.get(e)}function fs(e,t){let n=us(e.name,t);if(n!==void 0)return n;if(e.legacyName)return us(e.legacyName,t);return}function cr(e,t,n,r,o){if(n.kind!=="command")return{toolName:e,input:t,route:n,context:r};return{toolName:e,input:t,route:n,context:r,command:o}}var fr=require("node:path");var W=require("node:fs"),j=require("node:path");function ps(){let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${e()}${e()}`}var Ch=Symbol("PolicyFilesystemScope"),bh=Symbol("PolicyFilesystemTarget"),Sh=W.constants.O_NOFOLLOW??0;class ye extends Error{name="PolicyFilesystemError";constructor(e){super(`Unable to access ${e} filesystem safely.`)}}function tn(e,t){return{[Ch]:!0,root:j.resolve(e),label:t}}function xc(e,t){let n=j.normalize(t);if(t===""||j.isAbsolute(t)||n===".."||n.startsWith(`..${j.sep}`))throw new ye(e.label);return{[bh]:!0,scope:e,relativePath:n,path:j.join(e.root,n)}}function ur(e,t){return xc(e,j.relative(e.root,j.resolve(t)))}function Rc(e,t="rules policy"){let n=j.resolve(e),r=j.parse(n).dir;return xc(tn(r,t),j.relative(r,n))}function Co(e){return _c(e.scope.label,()=>{if(!yo(e))return null;let t=W.openSync(e.path,W.constants.O_RDONLY|Sh);return vh(t,()=>{let n=W.fstatSync(t);if(!n.isFile())throw new ye(e.scope.label);let r=W.readFileSync(t,"utf-8"),o=W.lstatSync(e.path);if(!o.isFile()||o.isSymbolicLink()||n.dev!==o.dev||n.ino!==o.ino)throw new ye(e.scope.label);return yo(e),r})})}function wc(e,t){if(e.path===t.path)return!0;return _c(e.scope.label,()=>{if(!yo(e)||!yo(t))return!1;let n=(r)=>j.join(W.realpathSync(j.parse(r).dir),j.parse(r).base);return n(e.path)===n(t.path)})}function _c(e,t,n){try{return t()}catch(r){if(n?.(),r instanceof ye)throw r;throw new ye(e)}}function vh(e,t){try{return t()}finally{W.closeSync(e)}}function yo(e,t="file"){let n=Eh(e.scope);if(!n)return!1;let r=e.relativePath.split(j.sep);for(let o of r.keys()){let i=j.join(e.scope.root,...r.slice(0,o+1)),s=W.lstatSync(i,{throwIfNoEntry:!1});if(!s)return!1;if(s.isSymbolicLink())throw new ye(e.scope.label);if(o<r.length-1&&!s.isDirectory())throw new ye(e.scope.label);if(o===r.length-1&&(t==="file"?!s.isFile():!s.isDirectory()))throw new ye(e.scope.label);xh(n,W.realpathSync(i),e.scope.label)}return!0}function Eh(e){if(!W.lstatSync(e.root,{throwIfNoEntry:!1}))return null;if(!W.statSync(e.root).isDirectory())throw new ye(e.label);return W.realpathSync(e.root)}function xh(e,t,n){let r=j.relative(e,t);if(r===".."||r.startsWith(`..${j.sep}`)||j.isAbsolute(r))throw new ye(n)}var L=require("node:path");var nn=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,Ac="rulebook.json",Pc=".cc-safety-net/rules";var Tc=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/;var Rh=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,wh=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),_h="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),RP=new RegExp(`^${wh}/(${nn.source.slice(1,-1)})/${_h}$`);function Ah(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function kc(e){if(bo(e))try{return gs(e),null}catch(t){return t instanceof Error?t.message:String(t)}return nn.test(e)?null:`Local rulebook sources must be bare names matching ${nn}: ${e}`}function gs(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(Tc);if(!t?.[1]||!t[2]||!t[3])throw Error(`Invalid GitHub rulebook source: ${e}`);let n=t[3].lastIndexOf("/");if(n<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);let r=t[3].slice(0,n),o=t[3].slice(n+1);if(!r||!Rh.test(r))throw Error(`GitHub rulebook refs must use valid path segments: ${e}`);if(!o||!nn.test(o))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);return{owner:t[1],repo:t[2],ref:r,path:Ah(o),name:o}}function bo(e){return Tc.test(e)}var Ic="rule.json",So="policy.json",Oc=".cc-safety-net",Ph="rules",Th="CC_SAFETY_NET_HOME",Mc="`cc-safety-net rule update`";function kh(e){return L.resolve(e,Pc)}function Ih(e){return L.join(kh(e),Ic)}function dr(e){return L.join(L.resolve(e),Oc,So)}function hs(e,t={}){return t.userConfigDir??(t.userConfigPath?L.dirname(t.userConfigPath):L.join(Oh(e),Ph))}function Oh(e){let t=e.env.get(Th);return t?L.resolve(Me(t)):L.join(e.home,Oc)}function Mh(e,t={}){return L.join(hs(e,t),Ic)}function An(e,t={}){return L.join(L.dirname(hs(e,t)),So)}function Dc(e,t){let n=t.userConfigPath??Mh(e,t),r=t.projectConfigPath??Ih(t.cwd),o=Dh(e,t),i=Nh(r,t.cwd);return{userConfigPath:n,projectConfigPath:r,userScope:o,projectScope:i,userConfigTarget:ur(o,n),projectConfigTarget:ur(i,r)}}function Dh(e,t){let n=t.userConfigPath?L.dirname(L.dirname(L.resolve(t.userConfigPath))):L.dirname(L.resolve(t.userConfigDir??hs(e,t)));return tn(n,"user policy")}function Nh(e,t){let n=L.resolve(t),r=L.resolve(e),o=L.relative(n,r);if(o!==".."&&!o.startsWith(`..${L.sep}`)&&!L.isAbsolute(o))return tn(n,"project policy");return tn(L.dirname(L.dirname(r)),"project policy")}function Nc(e,t){return L.join(e,t,Ac)}var De=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),Lt=/^[a-zA-Z][a-zA-Z0-9_-]*$/,Wt=256,Q=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),Lc=new Set(["python","python3","python2","node","ruby","perl"]),vo=/^python(?:[23](?:\.\d+)*)?$/,Be=new Set(["awk","gawk","nawk","mawk"]),Eo=new Set(["echo","printf","cat","head","tail","less","more","grep","rg","ag","ack","sed","awk","cut","tr","sort","uniq","wc","tee","man","help","info","type","which","whereis","whatis","apropos","file","stat","ls","ll","dir","tree","pwd","date","cal","uptime","whoami","id","groups","hostname","uname","env","printenv","set","export","alias","history","jobs","fg","bg","test","true","false","read","return","exit","break","continue","shift","wait","trap","basename","dirname","realpath","readlink","md5sum","sha256sum","base64","xxd","od","hexdump","strings","diff","cmp","comm","join","paste","column","fmt","fold","nl","pr","expand","unexpand","rev","tac","shuf","seq","yes","sleep","logger","write","wall","mesg","notify-send"]);var Wc="Rulebook exceeds CC Safety Net's safe validation limits.",Gc="Additional rulebook validation errors were omitted.",Ze=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function Fc(e){if(ys(e.allowed_commands,Ze.maxAllowedCommands)||ys(e.rules,Ze.maxRules)||ys(e.tests,Ze.maxTests))return!1;let{maxAggregateStringCodeUnits:t,maxTotalBlockArgs:n}=Ze,r=(o,i=!1)=>{if(typeof o!=="string")return!0;if(o.length>Ze.maxStringCodeUnits||i&&o.length>Ze.maxFixtureCommandCodeUnits||o.length>t)return!1;return t-=o.length,!0};if(!r(e.name)||!r(e.version)||!r(e.description)||!r(e.author)||!r(e.migrated_from))return!1;if(Array.isArray(e.allowed_commands)){for(let o of e.allowed_commands)if(!r(o))return!1}if(Array.isArray(e.rules))for(let o of e.rules){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.name)||!r(i.command)||!r(i.subcommand)||!r(i.reason)||!r(i.intent))return!1;let s=i.match&&typeof i.match==="object"?i.match:{};for(let a of[i.block_args,s.command_path,s.any_args,s.exclude_args]){if(!Array.isArray(a))continue;if(a.length>Ze.maxBlockArgsPerRule||a.length>n)return!1;n-=a.length;for(let l of a)if(!r(l))return!1}}if(Array.isArray(e.tests))for(let o of e.tests){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.command,!0)||!r(i.expect)||!r(i.rule))return!1}return!0}function ys(e,t){return Array.isArray(e)&&e.length>t}var Cs=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var bs=64,Ss="Rule config exceeds CC Safety Net's safe source limit.";function M(e){return k(e).toLowerCase()}function k(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}function we(e,t){let n=new Set,r=!1;for(let o of e){if(o==="--"){r=!0;continue}if(r)continue;if(o.startsWith("-")&&!o.startsWith("--")&&o.length>1)for(let i=1;i<o.length;i++){let s=o[i];if(!s||!/[a-zA-Z]/.test(s))break;let a=`-${s}`;if(n.add(a),t?.shortOptsWithValue?.has(a))break}}return n}var Lh={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},vs=new Set(["--init-file","--rcfile"]);function Es(e,t,n,r){let o=!1,i=0,s=!1,a=!1,l=!1;for(let c=1;c<t.length;c++){let u=t[c];if(u===void 0)break;if(e==="ksh"&&u==="o"&&c+1<t.length){if(r==="argv"){let m=t.slice(c+1);if(t[0]==="-"&&(m==="c"||m[0]==="-"&&m.endsWith("c")))s=!0}break}if(e==="ksh"&&u==="o"&&c+1===t.length&&(n?.startsWith("-")||n?.startsWith("+")))break;if(e==="zsh"&&u==="o"&&c+1<t.length)break;if(r==="startup"&&u==="i")o=t[0]==="-";if(r==="argv"&&t[0]==="-"&&u==="c")s=!0;if(r==="argv"&&u==="n")l=t[0]==="-";if(r==="argv"&&u==="s")a=t[0]==="-";if(!Lh[e]?.includes(u))continue;if(c+1===t.length)i++;break}return{interactive:o,followingValues:i,commandSelected:s,stdinMode:a,syntaxCheck:l}}function Ne(e){let t=k(e[0]??"").toLowerCase(),n=!1,r=!1,o=!1;for(let i=1;i<e.length;i++){let s=e[i];if(s===void 0)break;if(s==="--"){let l=n&&e[i+1]!==void 0?i+1:null;return{command:l===null?null:e[l]??null,commandIndex:l,scriptIndex:!n&&!r&&e[i+1]!==void 0?i+1:null,readsStdinAsCommands:!n&&(r||e[i+1]===void 0),syntaxCheck:o}}if(s==="-"||s[0]!=="-"&&s[0]!=="+")return{command:n?s:null,commandIndex:n?i:null,scriptIndex:!n&&!r&&s!=="-"?i:null,readsStdinAsCommands:!n&&(r||s==="-"),syntaxCheck:o};if(s.startsWith("--")){let l=s.split("=",1)[0]??s;if(t==="bash"&&vs.has(l)&&!s.includes("="))i++;continue}let a=Es(t,s,e[i+1],"argv");if(a.commandSelected)n=!0;if(a.syntaxCheck)o=!0;if(a.stdinMode)r=!0;i+=a.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!n,syntaxCheck:o}}function mr(e,t){if(t.escaped)return t.escaped=!1,!0;if(e==="\\"&&!t.inSingle)return t.escaped=!0,!0;if(e==="'"&&!t.inDouble)return t.inSingle=!t.inSingle,!0;if(e==='"'&&!t.inSingle)return t.inDouble=!t.inDouble,!0;return!1}function xo(e){let t={inSingle:!1,inDouble:!1,escaped:!1};for(let n of Wh(e))mr(n,t);return t.inSingle||t.inDouble}function Wh(e){let t="",n={inSingle:!1,inDouble:!1,escaped:!1},r=!1,o=!0;for(let i=0;i<e.length;i++){let s=e[i];if(!s)break;if(r){if(s===`
|
|
7
|
+
`||s==="\r")t+=s,r=!1,n.escaped=!1;continue}if(s==="#"&&!n.inSingle&&!n.inDouble&&o){r=!0;continue}if(t+=s,!n.inSingle&&!n.inDouble&&!n.escaped)o=/[\s;&|()<>]/.test(s);mr(s,n)}return t}var xs=new Set(["rm","find","xargs","parallel"]),Gh=new Set(["git","busybox",...xs,...Q,...Lc,...Be]),Fh=new Set(["python","node","ruby","perl"]);function zc(e){let t=M(e);return Gh.has(t)||Xe(t)}function Xe(e){return Fh.has(zh(e))}function zh(e){let t=k(e).toLowerCase();return vo.test(t)?"python":t}function Rs(e){try{let t=Co(Hh(e));if(t===null)return{config:null,errors:[]};if(!t.trim())return{config:null,errors:["Config file is empty"]};let n=JSON.parse(t),r=Uh(n);if(r.errors.length>0)return{config:null,errors:r.errors};return{config:{version:1,rules:n.rules??[],overrides:n.overrides??{},transparent_wrappers:n.transparent_wrappers??[]},errors:[]}}catch(t){if(t instanceof ye)return{config:null,errors:[t.message]};let n=t instanceof Error?t.message:String(t);return{config:null,errors:[t instanceof SyntaxError?"Invalid JSON":n]}}}function Hh(e){return typeof e==="string"?Rc(e):e}var w=(e,t)=>({path:e,message:t,kind:"typed"}),de=(e,t)=>({path:e,message:t,kind:"custom"});function Hc(e){let t=new Set;return e.flatMap((n,r)=>{let o=Pn(n)?n.name:void 0;if(typeof o!=="string")return[];if(t.has(o.toLowerCase()))return[de(["rules",r,"name"],`duplicate rule name "${o}"`)];return t.add(o.toLowerCase()),[]})}var ws=`must be one of ${Cs.join(", ")}`,Bh=/^[^/]+\/[^/]+$/,$h=["version","rules","overrides","transparent_wrappers"];function Uh(e){let t=jh(e);return{errors:_s(ey(t,$h,(n)=>n.kind==="custom"),": "," "),sources:Qh(e,t)}}function jh(e){if(!Pn(e))return[w([],"Config must be an object")];let t=Array.isArray(e.rules)&&e.rules.length>bs;return[...e.version===1?[]:[w(["version"],"must be 1")],...Vh(e.rules,t),...Yh(e.overrides),...Xh(e.transparent_wrappers),...t?[]:qh(e.rules),...Pn(e.overrides)?Object.keys(e.overrides).filter((n)=>!Bh.test(n)).map((n)=>de(["overrides",n],"must use <rulebook-name>/<rule-name>")):[],...Jh(e.transparent_wrappers)]}function Vh(e,t){if(e===void 0)return[];if(!Array.isArray(e))return[w(["rules"],"must be an array of rulebook source strings"),...Bc(e,bs)?[w(["rules"],Ss)]:[]];if(t)return[{path:["rules"],message:Ss,kind:"limit"}];return e.flatMap((n,r)=>{if(typeof n!=="string")return[w(["rules",r],"must be a rulebook source string"),...Kh(n,1)?[w(["rules",r],"must be a non-empty rulebook source string")]:[]];return n===""?[w(["rules",r],"must be a non-empty rulebook source string")]:[]})}function Bc(e,t){let n=$c(e);return n!==void 0&&!(n<=t)}function Kh(e,t){let n=$c(e);return n!==void 0&&!(n>=t)}function $c(e){if(e===null||e===void 0)return;let t=e.length;return t===void 0?void 0:Number(t)}function qh(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||n==="")return[];if(n.trim()==="")return[de(["rules",r],"must be a non-empty rulebook source string")];let o=kc(n);if(o)return[de(["rules",r],o)];if(t.has(n))return[de(["rules",r],`duplicate rulebook source "${n}"`)];return t.add(n),[]})}function Yh(e){if(e===void 0)return[];if(!Pn(e))return[w(["overrides"],"must be an object if provided")];return Object.keys(e).flatMap((t)=>{let n=e[t];if(n==="off")return[];if(!Pn(n))return[w(["overrides",t],'must be "off" or an object')];return[...Zh(n.reason,["overrides",t,"reason"]),...n.intent===void 0||Ps(n.intent)?[]:[w(["overrides",t,"intent"],ws)]]})}function Zh(e,t){if(typeof e!=="string")return[w(t,"required non-empty string"),...Bc(e,Wt)?[w(t,`must be at most ${Wt} characters`)]:[]];if(e==="")return[w(t,"required non-empty string")];return e.length>Wt?[w(t,`must be at most ${Wt} characters`)]:[]}function Xh(e){if(e===void 0)return[];if(!Array.isArray(e))return[w(["transparent_wrappers"],"must be an array of command strings")];return e.flatMap((t,n)=>{if(typeof t!=="string")return[w(["transparent_wrappers",n],"must be a command string")];return Lt.test(t)?[]:[w(["transparent_wrappers",n],"must match command pattern")]})}function Jh(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||!Lt.test(n))return[];if(t.has(n))return[de(["transparent_wrappers",r],`duplicate command "${n}"`)];if(zc(n))return[de(["transparent_wrappers",r],`reserved command "${n}" cannot be a wrapper`)];return t.add(n),[]})}function Qh(e,t){let n=Pn(e)?e.rules:void 0;if(!Array.isArray(n))return new Set;if(t.some((o)=>o.path.length===1&&o.path[0]==="rules"))return new Set;let r=new Set(t.filter((o)=>o.path[0]==="rules"&&typeof o.path[1]==="number").map((o)=>o.path[1]));return new Set(n.filter((o,i)=>typeof o==="string"&&!r.has(i)))}function ey(e,t,n){let r=e.map((s)=>s.path[1]),o=[...new Set(r.filter((s)=>typeof s==="string"))],i=(s,a)=>[s.path.length===0?-1:t.indexOf(String(s.path[0])),typeof a==="number"?a:o.indexOf(String(a)),n(s)?0:1];return e.map((s,a)=>({issue:s,rank:i(s,r[a])})).sort((s,a)=>s.rank[0]-a.rank[0]||s.rank[1]-a.rank[1]||s.rank[2]-a.rank[2]).map((s)=>s.issue)}function _s(e,t,n){return[...new Set(e.map((r)=>{let o=As(r.path);if(r.kind==="unknownKeys")return`${o?`${o}.`:""}unknown field "${r.message}"`;if(r.kind==="key"||r.kind==="limit"||r.path.length===0)return r.message;return`${o}${r.path.length===1?n:t}${r.message}`}))]}function As(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function Ps(e){return Cs.includes(e)}function Pn(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function jc(e){let t=ry(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}var ty=`required non-empty string up to ${Wt} characters`,Uc="must be a non-empty array of unique non-empty strings",ny="required non-empty array of non-empty strings";function ry(e){if(!Gt(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Fc(e))return{errors:[Wc],ruleNames:new Set};let t=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],..._s(oy(e,e.rulebook_version===2),": ",": ")];return{errors:t.length>Ze.maxValidationErrors?[...t.slice(0,Ze.maxValidationErrors),Gc]:t,ruleNames:new Set(Vc(e).map((n)=>n.toLowerCase()))}}function Vc(e){let t=Gt(e)?e.rules:void 0;return(Array.isArray(t)?t:[]).flatMap((n)=>{let r=Gt(n)?n.name:void 0;return typeof r==="string"?[r]:[]})}function oy(e,t){return[...typeof e.name==="string"&&nn.test(e.name)?[]:[w(["name"],"required string matching rule name pattern")],...typeof e.version==="string"&&e.version!==""?[]:[w(["version"],"required non-empty string")],...iy(e.allowed_commands),...sy(e.rules,t),...uy(e.tests),...dy(e),...my(e)]}function iy(e){if(!Array.isArray(e))return[w(["allowed_commands"],"required array")];let t=new Set;return[...e.flatMap((n,r)=>typeof n==="string"&&Lt.test(n)?[]:[w(["allowed_commands",r],"must match command pattern")]),...e.flatMap((n,r)=>{if(typeof n!=="string"||!Lt.test(n))return[];if(t.has(n))return[de(["allowed_commands",r],`duplicate command "${n}"`)];return t.add(n),[]})]}function sy(e,t){if(!Array.isArray(e))return[w(["rules"],"required array")];return[...e.flatMap((n,r)=>{if(!Gt(n))return[w(["rules",r],"must be an object")];return t?ly(n,["rules",r]):ay(n,["rules",r])}),...Hc(e)]}function ay(e,t){return[...Kc(e.name,t),...qc(e.command,t),...e.subcommand===void 0||typeof e.subcommand==="string"&&Lt.test(e.subcommand)?[]:[w([...t,"subcommand"],"must match command pattern")],...Ro(e.block_args,[...t,"block_args"],"required non-empty array",!1),...Yc(e.reason,t),...Zc(e.intent,t)]}function ly(e,t){return[...Kc(e.name,t),...qc(e.command,t),...Yc(e.reason,t),...Zc(e.intent,t),...cy(e.match,[...t,"match"]),...e.subcommand===void 0?[]:[w([...t,"subcommand"],"not supported in rulebook_version 2")],...e.block_args===void 0?[]:[w([...t,"block_args"],"not supported in rulebook_version 2")]]}function Kc(e,t){if(typeof e!=="string")return[w([...t,"name"],"required string")];return nn.test(e)?[]:[w([...t,"name"],"must match rule name pattern")]}function qc(e,t){return typeof e==="string"&&Lt.test(e)?[]:[w([...t,"command"],"required string matching command pattern")]}function Yc(e,t){return typeof e==="string"&&e!==""&&e.length<=Wt?[]:[w([...t,"reason"],ty)]}function Zc(e,t){return e===void 0||Ps(e)?[]:[w([...t,"intent"],ws)]}function cy(e,t){if(!Gt(e))return[w(t,"required object")];return[...Ro(e.command_path,[...t,"command_path"],ny,!1),...e.any_args===void 0?[]:Ro(e.any_args,[...t,"any_args"],Uc,!0),...e.exclude_args===void 0?[]:Ro(e.exclude_args,[...t,"exclude_args"],Uc,!0)]}function Ro(e,t,n,r){if(!Array.isArray(e))return[w(t,n)];let o=e.flatMap((i,s)=>{if(typeof i!=="string")return[w([...t,s],"must be a non-empty string")];return i===""?[de([...t,s],"must be a non-empty string")]:[]});if(e.some((i)=>typeof i!=="string"))return o;return[...o,...e.length===0?[de(t,n)]:[],...r&&new Set(e).size!==e.length?[de(t,"must not contain duplicate values")]:[]]}function uy(e){if(e===void 0)return[];if(!Array.isArray(e))return[w(["tests"],"must be an array if provided")];return e.flatMap((t,n)=>{if(!Gt(t))return[w(["tests",n],"must be an object")];return[...typeof t.command==="string"&&t.command.trim()!==""?[]:[w(["tests",n,"command"],"required non-empty string")],...t.expect==="blocked"||t.expect==="allowed"?[]:[w(["tests",n,"expect"],'must be "blocked" or "allowed"')],...t.rule===void 0||typeof t.rule==="string"?[]:[w(["tests",n,"rule"],"must be a string if provided")],...t.expect==="blocked"&&typeof t.rule!=="string"?[de(["tests",n,"rule"],"required string for blocked fixtures")]:[]]})}function dy(e){if(!Array.isArray(e.tests))return[];let t=new Set(Vc(e));return[...new Set(e.tests.flatMap((n)=>Gt(n)&&n.expect==="blocked"&&typeof n.rule==="string"?[n.rule]:[]))].filter((n)=>!t.has(n)).map((n)=>de(["tests"],`blocked fixture references unknown rule "${n}"`))}function my(e){if(!Array.isArray(e.allowed_commands)||!Array.isArray(e.rules))return[];let t=new Set(e.allowed_commands.filter((n)=>typeof n==="string"));return e.rules.flatMap((n,r)=>{let o=Gt(n)?n.command:void 0;if(typeof o!=="string"||t.has(o))return[];return[de(["rules",r,"command"],`"${o}" must be listed in allowed_commands`)]})}function Gt(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function nu(e,t){let n=Dc(e,t),r;try{r=wc(n.userConfigTarget,n.projectConfigTarget)}catch(f){if(f instanceof ye)return vy(n,f.message);throw f}let o=Rs(n.userConfigTarget),i=r?{config:null,errors:[]}:Rs(n.projectConfigTarget),s=eu(n.userConfigPath,o.errors),a=eu(n.projectConfigPath,i.errors),l=new Set,c=o.config?Xc(o.config,fr.dirname(n.userConfigPath),"user",n.userScope,l):tu(),u=i.config?Xc(i.config,fr.dirname(n.projectConfigPath),"project",n.projectScope,l):tu(),m=o.config?.overrides??{},d=i.config?.overrides??{};return{rules:[...Jc(c.rules,m),...Jc(u.rules,d)],transparent_wrappers:by(o.config,i.config),rulebooks:[...c.rulebooks,...u.rulebooks],errors:[...s,...a,...c.errors,...u.errors],warnings:[...c.warnings,...u.warnings,...c.canValidateOverrides?Qc(m,c.knownRuleIds,n.userConfigPath):[],...c.canValidateOverrides?Sy(d,c.knownRuleIds,n.projectConfigPath):[],...u.canValidateOverrides?Qc(d,u.knownRuleIds,n.projectConfigPath):[]],userConfig:o.config??void 0,projectConfig:i.config??void 0,...n}}function Xc(e,t,n,r=tn(fr.dirname(fr.dirname(t)),n==="user"?"user policy":"project policy"),o=new Set){let i=[],s=[],a=e.rules.flatMap((c)=>{let u=py(c,t,r);if(u.errors.length>0||!u.rulebook)return i.push(...u.errors),[];let m=u.rulebook;if(o.has(m.name))return s.push(`duplicate active rulebook name "${m.name}" for ${c}; keeping the first and ignoring this one, so its rules are not active; rename one of them in its rulebook file and in the rules config that lists it`),[];return o.add(m.name),[{rules:fy(m),rulebook:{source:n,spec:c,name:m.name,version:m.version,rules:m.rules.map((d)=>`${m.name}/${d.name}`)}}]}),l=a.flatMap((c)=>c.rules);return{rules:l,rulebooks:a.map((c)=>c.rulebook),knownRuleIds:new Set(l.map((c)=>c.name)),errors:i,warnings:s,canValidateOverrides:i.length===0}}function fy(e){if(e.rulebook_version===2)return e.rules.map((t)=>({name:`${e.name}/${t.name}`,command:t.command,block_args:[],match:t.match,reason:t.reason,intent:t.intent}));return e.rules.map((t)=>({...t,name:`${e.name}/${t.name}`,match:void 0}))}function py(e,t,n){let r=gy(e),o=Nc(t,r),i=yy(o,n);if("error"in i)return{rulebook:null,errors:[i.error]};if(i.content===null)return{rulebook:null,errors:[`missing rulebook file ${o} for ${e}; ${hy(e)}`]};let s=Cy(i.content);if("problem"in s)return{rulebook:null,errors:[`invalid rulebook ${o}: ${s.problem}; fix that file`]};if(s.rulebook.name!==r)return{rulebook:null,errors:[`rulebook name "${s.rulebook.name}" in ${o} must match source "${e}"; fix that file`]};return{rulebook:s.rulebook,errors:[]}}function gy(e){return bo(e)?gs(e).name:e}function hy(e){return bo(e)?`run ${Mc} to vendor ${e}`:"create that file or remove that source from the rules config"}function yy(e,t){try{return{content:Co(ur(t,e))}}catch(n){if(n instanceof ye)return{error:n.message};throw n}}function Cy(e){let t;try{t=JSON.parse(e)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:jc(t)}}catch(n){return{problem:n instanceof Error?n.message:"invalid rulebook"}}}function by(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function Jc(e,t){return e.flatMap((n)=>{let r=t[n.name];if(r==="off")return[];if(r&&typeof r==="object")return[{...n,intent:r.intent??n.intent,reason:r.reason}];return[n]})}function Qc(e,t,n){return Object.keys(e).filter((r)=>!t.has(r)).map((r)=>`unknown override key "${r}" in ${n}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function Sy(e,t,n){return Object.keys(e).filter((r)=>t.has(r)).map((r)=>`project override cannot target user-scoped rule "${r}" in ${n}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function eu(e,t){return t.map((n)=>n.startsWith("Unable to access ")?n:`${e}: ${n}`)}function vy(e,t){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath}}function tu(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}var No=require("node:fs");var ru=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores, with or without --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"find.delete",category:"Filesystem",label:"find delete",description:"Blocks unsafe find -delete operations.",example:"find . -delete",intent:"scope_down"},{id:"find.delete-git-metadata",category:"Filesystem",label:"find delete Git metadata",description:"Blocks find -delete operations selecting protected Git metadata and hooks.",example:"find .git -delete",intent:"hard_stop",catastrophic:!0},{id:"find.exec-rm-recursive-force",category:"Filesystem",label:"find exec rm -rf",description:"Blocks find -exec rm -rf operations.",example:"find . -exec rm -rf {} +",intent:"scope_down"},{id:"dd.device-write",category:"Filesystem",label:"dd device write",description:"Blocks dd writing to a /dev device.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"mkfs device format",description:"Blocks mkfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],Ts=new Set(ru.map((e)=>e.id)),wo=ru,Ey=new Map(wo.map((e)=>[e.id,e.intent]));function v(e,t){return{id:e,reason:t,intent:Ey.get(e)??"manual_only"}}var ks=[{id:"secret.basename.env",category:"Basename",label:".env",description:"Blocks exact .env files.",basename:".env"},{id:"secret.basename.npmrc",category:"Basename",label:".npmrc",description:"Blocks npm credential config files.",basename:".npmrc"},{id:"secret.basename.pypirc",category:"Basename",label:".pypirc",description:"Blocks Python package index credential files.",basename:".pypirc"},{id:"secret.basename.netrc",category:"Basename",label:".netrc",description:"Blocks machine login credential files.",basename:".netrc"},{id:"secret.basename.git-credentials",category:"Basename",label:".git-credentials",description:"Blocks Git credential storage files.",basename:".git-credentials"},{id:"secret.basename.id-rsa",category:"Basename",label:"id_rsa",description:"Blocks RSA private key basenames.",basename:"id_rsa"},{id:"secret.basename.id-ed25519",category:"Basename",label:"id_ed25519",description:"Blocks Ed25519 private key basenames.",basename:"id_ed25519"},{id:"secret.basename.id-ecdsa",category:"Basename",label:"id_ecdsa",description:"Blocks ECDSA private key basenames.",basename:"id_ecdsa"},{id:"secret.basename.credentials",category:"Basename",label:"credentials",description:"Blocks generic credentials file basenames.",basename:"credentials"}],_o={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},xy=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],Ry=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Is=[{id:"secret.home.ssh",category:"Home path",label:"~/.ssh",description:"Blocks home SSH configuration and key paths.",suffixParts:[".ssh"]},{id:"secret.home.aws",category:"Home path",label:"~/.aws",description:"Blocks home AWS credential and config paths.",suffixParts:[".aws"]},{id:"secret.home.gcp",category:"Home path",label:"~/.gcp",description:"Blocks home GCP credential paths.",suffixParts:[".gcp"]},{id:"secret.home.gcloud-config",category:"Home path",label:"~/.config/gcloud",description:"Blocks home Google Cloud SDK credential paths.",suffixParts:[".config","gcloud"]},{id:"secret.home.kube-config",category:"Home path",label:"~/.kube/config",description:"Blocks home Kubernetes config files.",suffixParts:[".kube","config"]},{id:"secret.home.docker-config",category:"Home path",label:"~/.docker/config.json",description:"Blocks home Docker credential config files.",suffixParts:[".docker","config.json"]},...Ry.flatMap((e)=>xy.map((t)=>({id:["secret.home",e.idSlug,t.slice(1)].join("."),category:"Home path",label:[e.label,t].join(""),description:["Blocks home ",e.label,t," credential backup files."].join(""),suffixParts:[...e.directoryParts,[e.basename,t].join("")]}))),{id:"secret.home.gh-hosts",category:"Home path",label:"~/.config/gh/hosts.yml",description:"Blocks GitHub CLI host credential files.",suffixParts:[".config","gh","hosts.yml"]}];var Ao=[{id:"secret.cli.claude-code",category:"Coding CLI credential",label:"Claude Code credentials",paths:["~/.claude/.credentials.json"]},{id:"secret.cli.claude-code.config",category:"Coding CLI config",label:"Claude Code config",paths:["~/.claude/settings.json","~/.claude/settings.local.json","~/.claude.json","<project>/.claude/settings.local.json","<project>/.mcp.json"]},{id:"secret.cli.antigravity",category:"Coding CLI config",label:"Antigravity CLI hook config",paths:["~/.gemini/config/hooks.json","~/.gemini/config/mcp_config.json"]},{id:"secret.cli.codex",category:"Coding CLI credential",label:"Codex credentials",paths:["~/.codex/auth.json","~/.codex/.credentials.json","~/.codex/secrets","~/.codex/.sandbox-secrets"]},{id:"secret.cli.codex.config",category:"Coding CLI config",label:"Codex config",paths:["~/.codex/config.toml","~/.codex/<name>.config.toml"]},{id:"secret.cli.gemini",category:"Coding CLI credential",label:"Gemini CLI credentials",paths:["~/.gemini/oauth_creds.json","~/.gemini/mcp-oauth-tokens.json","~/.gemini/a2a-oauth-tokens.json","~/.gemini/gemini-credentials.json"]},{id:"secret.cli.gemini.config",category:"Coding CLI config",label:"Gemini CLI config",paths:["~/.gemini/settings.json","~/.gemini/google_accounts.json","<project>/.gemini/settings.json","/Library/Application Support/GeminiCli/settings.json","/etc/gemini-cli/settings.json"]},{id:"secret.cli.copilot-cli",category:"Coding CLI credential",label:"GitHub Copilot CLI credentials",paths:["~/.copilot/config.json","~/.copilot/mcp-oauth-config","~/.copilot/mcp-secrets"]},{id:"secret.cli.copilot-cli.config",category:"Coding CLI config",label:"GitHub Copilot CLI config",paths:["~/.copilot/mcp-config.json"]},{id:"secret.cli.kimi-code",category:"Coding CLI credential",label:"Kimi Code credentials",paths:["~/.kimi-code/server.token","~/.kimi-code/credentials","~/.kimi/credentials","~/.kimi/mcp-oauth"]},{id:"secret.cli.kimi-code.config",category:"Coding CLI config",label:"Kimi Code config",paths:["~/.kimi-code/config.toml","~/.kimi-code/mcp.json","~/.kimi/config.toml","~/.kimi/config.json","~/.kimi/config.json.bak","~/.kimi/mcp.json","<project>/.kimi-code/mcp.json"]},{id:"secret.cli.opencode",category:"Coding CLI credential",label:"OpenCode credentials",paths:["~/.local/share/opencode/auth.json","~/.local/share/opencode/mcp-auth.json","~/.local/share/opencode/opencode.db"]},{id:"secret.cli.opencode.config",category:"Coding CLI config",label:"OpenCode config",paths:["~/.config/opencode/opencode.json","~/.config/opencode/opencode.jsonc","~/.config/opencode/config.json","/Library/Application Support/opencode/opencode.json","/etc/opencode/opencode.json","<project>/opencode.json","<project>/opencode.jsonc"]},{id:"secret.cli.pi",category:"Coding CLI credential",label:"Pi credentials",paths:["~/.pi/agent/auth.json"]},{id:"secret.cli.pi.config",category:"Coding CLI config",label:"Pi config",paths:["~/.pi/agent/models.json"]},{id:"secret.cli.amp",category:"Coding CLI credential",label:"Amp Code credentials",paths:["~/.local/share/amp/secrets.json","~/.amp/oauth"]},{id:"secret.cli.amp.config",category:"Coding CLI config",label:"Amp Code config",paths:["~/.config/amp/settings.json","~/.config/amp/settings.jsonc","<project>/.amp/settings.json","<project>/.amp/settings.jsonc"]},{id:"secret.cli.cursor",category:"Coding CLI credential",label:"Cursor CLI credentials",paths:["~/.cursor/auth.json","~/.config/cursor/auth.json","~/.cursor/projects/<name>/mcp-auth.json"]},{id:"secret.cli.cursor.config",category:"Coding CLI config",label:"Cursor CLI config",paths:["~/.cursor/mcp.json","<project>/.cursor/mcp.json"]},{id:"secret.cli.grok-build",category:"Coding CLI credential",label:"Grok Build credentials",paths:["~/.grok/auth.json","~/.grok/mcp_credentials.json"]},{id:"secret.cli.grok-build.config",category:"Coding CLI config",label:"Grok Build config",paths:["~/.grok/config.toml","~/.grok/managed_config.toml","~/.grok/requirements.toml","<project>/.grok/config.toml","/etc/grok/managed_config.toml","/etc/grok/requirements.toml"]}],ou=[{prefix:"id_rsa",slug:"id-rsa",label:"id_rsa"},{prefix:"id_dsa",slug:"id-dsa",label:"id_dsa"},{prefix:"id_ed25519",slug:"id-ed25519",label:"id_ed25519"},{prefix:"id_ecdsa",slug:"id-ecdsa",label:"id_ecdsa"},{prefix:"credentials",slug:"credentials",label:"credentials"}],wy=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Os=ou.map((e)=>({id:`secret.variant.${e.slug}.separator`,category:"Variant",label:`${e.label}-* / ${e.label}_*`,description:`Blocks ${e.label} variants with dash or underscore suffixes.`,prefix:e.prefix})),Ms=ou.flatMap((e)=>wy.map((t)=>({id:`secret.variant.${e.slug}.${t.slice(1)}`,category:"Variant",label:`${e.label}${t}`,description:`Blocks ${e.label}${t} private credential variants.`,prefix:e.prefix,suffix:t}))),pr={id:"secret.pattern.ssh-key-basename",category:"Pattern",label:"*_(rsa|dsa|ed25519|ecdsa)",description:"Blocks extensionless SSH private key-like basenames.",pattern:/^.*_(rsa|dsa|ed25519|ecdsa)$/},Ds=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((e)=>({id:`secret.ext.${e}`,category:"Extension",label:`.${e}`,description:`Blocks files with the .${e} extension.`,extension:e})),Ns=[{id:"secret.ext-pattern.key",category:"Extension pattern",label:".key / .keypair",description:"Blocks key and keypair extension patterns.",pattern:/^key(pair)?$/},{id:"secret.ext-pattern.keystore",category:"Extension pattern",label:".keystore / .keyring",description:"Blocks keystore and keyring extension patterns.",pattern:/^key(store|ring)$/},{id:"secret.ext-pattern.kdbx",category:"Extension pattern",label:".kdb / .kdbx",description:"Blocks KeePass database extension patterns.",pattern:/^kdbx?$/}],_y=[...ks,_o,...Is,...Os,...Ms,pr,...Ds,...Ns,...Ao].map((e)=>({id:e.id,category:e.category,label:e.label,...e.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in e?{paths:e.paths}:{description:e.description}})),Po=new Set(Ao.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),Ls=new Set(_y.map((e)=>e.id));var Le=require("node:path"),To=process.platform==="win32",iu=/[*?]/;function Ws(e){let t=e.trim(),n=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(To?t.replaceAll("\\","/"):t);if(!n)return null;let r=n[1]??"",o=n[2]??"";if(iu.test(r)||o==="."||o==="..")return null;return{root:r||"/",name:o}}function gr(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function Gs(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=gr(e.trim(),t);if(!Le.isAbsolute(n))return"must be an absolute path or start with ~/";return hr(n,t)}function Fs(e,t){let n=su(e,t);if(n===null)return"must be a non-empty path string";if(!Le.isAbsolute(n))return null;if(hr(n,t)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var Ay="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",Py="cannot cover the guard's own configuration";function su(e,t){if(typeof e!=="string"||e.trim()==="")return null;let n=e.trim(),r=To?n.replaceAll("\\","/"):n;return gr(r.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function zs(e,t){let n=su(e,t);if(n===null)return"must be a non-empty path string";let r=Ws(n)?.root??n;if(iu.test(r))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!Le.isAbsolute(r))return null;if(hr(r,t)!==null)return Ay;return Ty(r,t)?Py:null}function Ty(e,t){let n=ko(e),r=ko(Le.join(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${Le.sep}`)}function hr(e,t){let n=ko(e),r=ko(t);if(n===r)return"cannot be the home directory";let o=n.endsWith(Le.sep)?n:`${n}${Le.sep}`;if(r.startsWith(o))return"cannot contain the home directory";return null}function ko(e){let t=Le.normalize(e);if(To)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(To?3:1)&&t.endsWith(Le.sep))t=t.slice(0,-1);return t}var au=30,Io=1,Oo=365;function lu(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var cu=new Set(wo.filter((e)=>e.catastrophic).map((e)=>e.id));function T(e,t){if(!e)return null;if(cu.has(e.id))return e;if(t?.destructiveCommandProtectionEnabled===!1)return null;let n=t?.effectiveDestructiveCommandRules[e.id];return n&&!n.enabled?null:e}function me(e,t,n){if(cu.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function uu(e,t){return Object.freeze(Object.fromEntries(wo.map((n)=>{let r=n.activationCapability?t[n.activationCapability]:void 0,o=r?.enabled??!0,i=e.destructiveCommandRuleOverrides[n.id],s=n.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...i?{override:i}:{}}:e.destructiveCommandProtectionEnabled?i?{enabled:i==="on",inheritedEnabled:o,changesInherited:i==="on"!==o,source:"rule_override",...n.activationCapability?{activationCapability:n.activationCapability}:{},override:i}:{enabled:o,inheritedEnabled:o,changesInherited:!1,source:r?.source??"built_in_default",...n.activationCapability?{activationCapability:n.activationCapability}:{}}:{enabled:!1,inheritedEnabled:o,changesInherited:!1,source:"master_disabled",...n.activationCapability?{activationCapability:n.activationCapability}:{},...i?{override:i}:{}};return[n.id,Object.freeze(s)]})))}function du(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:uu(e,t)})}var mu={standard:0,strict:1,paranoid:2};function gu(e,t){return{policy:{version:1,safety:{level:t.safety?.level??e.safety.level,overrides:{...e.safety.overrides,...t.safety?.overrides}},workflow:{worktree_mode:t.workflow?.worktree_mode??e.workflow.worktree_mode},destructive_command_protection:{enabled:t.destructive_command_protection?.enabled??e.destructive_command_protection.enabled,overrides:{...e.destructive_command_protection.overrides,...t.destructive_command_protection?.overrides},allow_paths:Hs(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths)},secret_protection:{enabled:t.secret_protection?.enabled??e.secret_protection.enabled,overrides:{...e.secret_protection.overrides,...t.secret_protection?.overrides},deny_paths:Hs(e.secret_protection.deny_paths,t.secret_protection?.deny_paths),allow_paths:Hs(e.secret_protection.allow_paths,t.secret_protection?.allow_paths)},audit:e.audit},weakenings:ky(e,t)}}function Hs(e,t){return[...new Set([...e,...t??[]])]}function ky(e,t){let n=t.safety?.level,r=go[e.safety.level];return[...n&&mu[n]<mu[e.safety.level]?[`project policy lowers level: ${e.safety.level} -> ${n}`]:[],..._n.flatMap((o)=>t.safety?.overrides?.[o]===!1&&(e.safety.overrides[o]??r[o])?[`project policy disables ${o}`]:[]),...t.workflow?.worktree_mode===!0&&!e.workflow.worktree_mode?["project policy enables worktree mode relaxations"]:[],...t.destructive_command_protection?.enabled===!1&&e.destructive_command_protection.enabled?["project policy disables destructive command protection"]:[],...t.secret_protection?.enabled===!1&&e.secret_protection.enabled?["project policy disables secret protection"]:[],...fu(t.destructive_command_protection?.overrides,(o)=>e.destructive_command_protection.enabled&&e.destructive_command_protection.overrides[o]!=="off"),...fu(t.secret_protection?.overrides,(o)=>e.secret_protection.enabled&&(e.secret_protection.overrides[o]==="on"?!0:e.secret_protection.overrides[o]!=="off"&&!Po.has(o))),...e.destructive_command_protection.enabled?pu(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths).map((o)=>`project policy adds destructive allow path: ${o}`):[],...e.secret_protection.enabled?pu(e.secret_protection.allow_paths,t.secret_protection?.allow_paths).map((o)=>`project policy adds secret allow path: ${o}`):[]]}function fu(e,t){return Object.entries(e??{}).flatMap(([n,r])=>r==="off"&&t(n)?[`project policy disables rule ${n}`]:[])}function pu(e,t){return(t??[]).filter((n)=>!e.includes(n))}var Us=new Set(["standard","strict","paranoid"]),bu={version:1,safety:{level:"standard",overrides:{}},workflow:{worktree_mode:!1},destructive_command_protection:{enabled:!0,overrides:{},allow_paths:[]},secret_protection:{enabled:!0,overrides:{},deny_paths:[],allow_paths:[]},audit:{retention_days:au}};function Su(e,t){let n=zy(An(e,t),e.home),r=Lo(dr(t.cwd),e.home),o=Oy(r.parsed,e.home),i=Object.keys(o.policy).length>0?gu(n.gui??bu,o.policy):void 0,s=[...n.errors,...r.errors,...o.diagnostics],a=(n.fallback==="defaults"&&i?"salvaged":n.fallback)??(n.gui?void 0:r.fallback)??(s.length>0?"salvaged":void 0),l=o.policy.safety?.level?"project":n.levelPresent?"user":"default";return{...i?$s(i.policy):n.policy,errors:s,...a?{fallback:a}:{},...r.exists?{policyScopes:{levelScope:l,weakenings:i?.weakenings??[]}}:{}}}var Iy="project policy audit settings are ignored; audit is user scope only";function Oy(e,t){if(!We(e))return{policy:{},diagnostics:[]};let n=We(e.safety)?e.safety:{},r=We(e.workflow)?e.workflow:{},o=We(e.destructive_command_protection)?e.destructive_command_protection:{},i=We(e.secret_protection)?e.secret_protection:{},s={...Us.has(n.level)?{level:n.level}:{},...We(n.overrides)?hu({overrides:vu(n.overrides,_n,["safety","overrides"],rn)}):{}},a={...typeof o.enabled==="boolean"?{enabled:o.enabled}:{},...o.overrides!==void 0?{overrides:Do(o.overrides,Ts,xu,rn)}:{},...o.allow_paths!==void 0?{allow_paths:kn(o.allow_paths,Gs,t,["destructive_command_protection","allow_paths"],rn)}:{}},l={...typeof i.enabled==="boolean"?{enabled:i.enabled}:{},...i.overrides!==void 0?{overrides:Do(i.overrides,Ls,Ru,rn)}:{},...i.deny_paths!==void 0?{deny_paths:kn(i.deny_paths,Fs,t,["secret_protection","deny_paths"],rn)}:{},...i.allow_paths!==void 0?{allow_paths:kn(i.allow_paths,zs,t,["secret_protection","allow_paths"],rn)}:{}};return{policy:hu({safety:s,workflow:typeof r.worktree_mode==="boolean"?{worktree_mode:r.worktree_mode}:{},destructive_command_protection:a,secret_protection:l}),diagnostics:e.audit===void 0?[]:[Iy]}}function vu(e,t,n,r){return Object.fromEntries(t.flatMap((o)=>{let i=e[o];if(typeof i==="boolean")return[[o,i]];if(i!==void 0)r(w([...n,o],js));return[]}))}function hu(e){return Object.fromEntries(Object.entries(e).flatMap((t)=>Object.keys(t[1]).length>0?[t]:[]))}var rn=()=>{return},js="must be a boolean",Vs="must be an object if provided",Eu=`must be an integer between ${Io} and ${Oo}`,xu={path:["destructive_command_protection","overrides"],label:"destructive command"},Ru={path:["secret_protection","overrides"],label:"secret protection"},My=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function Dy(e,t){let n=[];return{policy:wu(e,t,(o)=>{n.push(o)}),issues:n}}function Ny(e,t){return wu(e,t,rn)}function wu(e,t,n){if(!We(e))return n(w([],"Config must be an object")),Mo();if(e.version!==1)n(w(["version"],"must be 1"));let r=Tn(e.safety,["safety"],["level","overrides"],n),o=Tn(r.overrides,["safety","overrides"],_n,n),i=Tn(e.workflow,["workflow"],["worktree_mode"],n),s=Tn(e.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],n),a=Tn(e.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],n),l=Tn(e.audit,["audit"],["retention_days"],n);return _u(e,My,[],n),{version:1,safety:{level:Ly(r.level,n),overrides:vu(o,_n,["safety","overrides"],n)},workflow:{worktree_mode:Bs(i.worktree_mode,["workflow","worktree_mode"],!1,n)},destructive_command_protection:{enabled:Bs(s.enabled,["destructive_command_protection","enabled"],!0,n),overrides:Do(s.overrides,Ts,xu,n),allow_paths:kn(s.allow_paths,Gs,t,["destructive_command_protection","allow_paths"],n)},secret_protection:{enabled:Bs(a.enabled,["secret_protection","enabled"],!0,n),overrides:Do(a.overrides,Ls,Ru,n),deny_paths:kn(a.deny_paths,Fs,t,["secret_protection","deny_paths"],n),allow_paths:kn(a.allow_paths,zs,t,["secret_protection","allow_paths"],n)},audit:{retention_days:Wy(l.retention_days,n)}}}function Tn(e,t,n,r){if(e===void 0)return{};if(!We(e))return r(w(t,Vs)),{};return _u(e,n,t,r),e}function _u(e,t,n,r){for(let o of Object.keys(e).filter((i)=>!t.includes(i)))r({path:n,message:o,kind:"unknownKeys"})}function Ly(e,t){if(e===void 0)return"standard";if(Us.has(e))return e;return t(w(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function Bs(e,t,n,r){if(typeof e==="boolean")return e;if(e!==void 0)r(w(t,js));return n}function Wy(e,t){if(!(e===void 0||typeof e==="number"&&Number.isInteger(e)&&e>=Io&&e<=Oo))t(w(["audit","retention_days"],Eu));return lu(e)}function Do(e,t,n,r){if(e===void 0)return{};if(!We(e))return r(w(n.path,Vs)),{};return Object.fromEntries(Object.entries(e).flatMap(([o,i])=>{if(!t.has(o))return r({path:[...n.path,o],message:`unknown ${n.label} rule id "${o}"`,kind:"key"}),[];if(i==="on"||i==="off")return[[o,i]];return r(w([...n.path,o],'must be "on" or "off"')),[]}))}function kn(e,t,n,r,o){if(e===void 0)return[];if(!Array.isArray(e))return o(w(r,"must be an array of paths")),[];return e.flatMap((i,s)=>{let a=t(i,n);if(a===null)return[i];return o(typeof i==="string"?de([...r,s],a):w([...r,s],a)),[]})}function We(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Mo(){return structuredClone(bu)}function Lo(e,t){if(!No.existsSync(e))return{exists:!1,policy:Mo(),errors:[]};try{let n=No.readFileSync(e,"utf-8");if(!n.trim())return{exists:!0,policy:Mo(),errors:[`${e}: Config file is empty`],fallback:"defaults"};let r=JSON.parse(n),o=Dy(r,t);if(o.issues.length===0)return{exists:!0,parsed:r,policy:o.policy,errors:[]};return{exists:!0,parsed:r,policy:o.policy,errors:o.issues.map((i)=>`${e}: ${Fy(i)}`),fallback:We(r)?"salvaged":"defaults"}}catch(n){let r=n instanceof Error?n.message:String(n);return{exists:!0,policy:Mo(),errors:[`${e}: ${n instanceof SyntaxError?"Invalid JSON":r}`],fallback:"defaults"}}}var Gy=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[Vs,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[js,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[Eu,`not an integer between ${Io} and ${Oo}`]]);function Fy(e){let t=As(e.path);if(e.kind==="unknownKeys")return`${t===""?"":`${t}.`}${e.message}: unknown field`;if(e.kind==="key")return`${t}: unknown rule id`;let n=Gy.get(e.message)??e.message;return t===""?n:`${t}: ${n}`}function zy(e,t){let n=Lo(e,t);if(!n.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!We(r))return{policy:Cu(),errors:[]};let o=Ny(r,t);return{policy:$s(o),gui:o,errors:[],levelPresent:yu(r)}}if(n.parsed===void 0)return{policy:Cu(),errors:n.errors,...n.fallback?{fallback:n.fallback}:{}};return{policy:$s(n.policy),gui:n.policy,errors:n.errors,...n.fallback?{fallback:n.fallback}:{},levelPresent:yu(n.parsed)}}function yu(e){let t=We(e)&&We(e.safety)?e.safety:{};return Us.has(t.level)}function Au(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...Po].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function Cu(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:Au({}),denyPaths:[],allowPaths:[]}}}function $s(e){return{safety:Hy(e.safety),worktreeMode:e.workflow.worktree_mode,destructiveCommandProtectionEnabled:e.destructive_command_protection.enabled,destructiveCommandRuleOverrides:e.destructive_command_protection.overrides,destructiveCommandAllowPaths:e.destructive_command_protection.allow_paths,secretProtection:{enabled:e.secret_protection.enabled,disabledRules:Au(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function Hy(e){let t={...e.overrides.fail_closed!==void 0?{failClosed:e.overrides.fail_closed}:{},...e.overrides.paranoid_rm!==void 0?{paranoidRm:e.overrides.paranoid_rm}:{},...e.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:e.overrides.paranoid_interpreters}:{}};return{level:e.level,...Object.keys(t).length>0?{overrides:t}:{}}}function Pu(e,t){let n=nu(e,t),r=Su(e,t),o={rules:n.rules,transparentWrappers:n.transparent_wrappers,safety:r.safety,worktreeMode:r.worktreeMode,destructiveCommandProtectionEnabled:r.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:r.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:r.destructiveCommandAllowPaths,secretProtection:{enabled:r.secretProtection.enabled??!0,disabledRules:r.secretProtection.disabledRules??[],denyPaths:r.secretProtection.denyPaths,allowPaths:r.secretProtection.allowPaths??[]}},i={...n.userConfig?.overrides,...n.projectConfig?.overrides},s=Object.freeze(Object.fromEntries(o.rules.map((a)=>{let l=n.rulebooks.find((u)=>u.rules.includes(a.name)),c=i[a.name];return[a.name,Object.freeze({id:a.name,...l?{rulebook:Object.freeze({name:l.name,version:l.version}),...jy(l.spec)?{source:l.spec}:{}}:{},...c&&typeof c==="object"?{override:Object.freeze({type:"reason",reason:c.reason})}:{}})]})));return Vy(o,By(n,r),s,r.policyScopes)}function By(e,t){let n=Uy(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:Ky(e.errors.length>0?$y(e.errors):void 0,e.warnings.length>0?qs(e.warnings.join("; ")):void 0,n)}}function $y(e){return`${qs(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function Uy(e){if(e.errors.length===0)return;let t=e.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${e.errors.join("; ")}. Enforcing ${t}; the invalid values are not active. Fix the policy file manually`}function jy(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function Vy(e,t,n=Object.freeze({}),r){let o=Ks(structuredClone(e)),i=r?{policyScopes:Ks(structuredClone(r))}:{};if(!t)return Object.freeze({state:"ready",policy:o,diagnostics:Object.freeze([]),ruleMetadata:n,...i});return Object.freeze({state:"degraded",policy:o,diagnostics:Object.freeze([...t.diagnostics]),reason:t.reason,ruleMetadata:n,...i})}function Ks(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))Ks(t);return Object.freeze(e)}function Ky(...e){return qs(e.filter((t)=>!!t).join("; "))}function qs(e){return/[.!?]$/.test(e)?e:`${e}.`}function Tu(e){let t=e.effectiveCapabilities,n=e.strict??t.fail_closed.enabled,r=e.paranoidRm??t.paranoid_rm.enabled,o=e.paranoidInterpreters??t.paranoid_interpreters.enabled,i={fail_closed:Ys(t.fail_closed,e.strict,"strict"),paranoid_rm:Ys(t.paranoid_rm,e.paranoidRm,"paranoidRm"),paranoid_interpreters:Ys(t.paranoid_interpreters,e.paranoidInterpreters,"paranoidInterpreters")};return{policy:du(e.policySnapshot.policy,i),effectiveCapabilities:i,effectiveLevel:ds({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}function Ys(e,t,n){if(t===void 0||t===e.enabled)return e;return{enabled:t,source:"capability_override",sources:[...e.sources,`analysis options.${n}`]}}var Ke=require("node:path");function yr(e,t){if(e!=="powershell")return t[0]?.provenance==="command-substitution";let n=t[0]?.text==="&"||t[0]?.text==="."?1:0,r=t[n]?.provenance;return r!==void 0&&r!=="literal"}var qy=/^[A-Za-z_][A-Za-z0-9_]*=/;function Wo(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function Cr(e){let t=Wo(e.words[0],"time")?1:0,n=t===1&&Wo(e.words[t],"-p")?t+1:t,r=t===1&&Wo(e.words[n],"--")?n+1:n,o=Wo(e.words[r],"!")?r+1:r,i=e.words.slice(o).find((s)=>!qy.test(s.text));return i?.provenance==="literal"?i.text:void 0}var Ft=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Go(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Yy(e){return Object.freeze({...e,span:Object.freeze(e.span),words:Object.freeze(e.words),redirections:Object.freeze(e.redirections.map((t)=>Object.freeze({...t,span:Object.freeze(t.span),...t.heredoc?{heredoc:Object.freeze({...t.heredoc,bodySpan:Object.freeze(t.heredoc.bodySpan),terminatorSpan:Object.freeze(t.heredoc.terminatorSpan)})}:{}}))),nested:Object.freeze(e.nested.map((t)=>_e(t)))})}function Fo(e,t,n){e.push(n),t.reset()}function zo(e){let t=[];return{parts:t,push:(n,r,o)=>{if(r<=n)return;t.push({raw:e.slice(n,r),span:{start:n,end:r},provenance:o})}}}function Zs(e){let t=e.parts??[{raw:e.raw,span:e.span,provenance:e.provenance}];return Object.freeze({kind:"word",...e,span:Object.freeze(e.span),parts:Object.freeze(t.map((n)=>Object.freeze({...n,span:Object.freeze(n.span)})))})}function In(e,t,n,r,o,i,s){return Zs({text:r,raw:e.slice(t,n),span:{start:t,end:n},provenance:o,quoted:i,...s?{parts:s}:{}})}function _e(e){return Object.freeze({...e,span:Object.freeze(e.span),issues:Object.freeze(e.issues.map((t)=>Object.freeze({...t}))),nodes:Object.freeze(e.nodes.map((t)=>{if(t.kind==="command")return Yy(t);if(t.kind==="group"||t.kind==="function")return Object.freeze({...t,span:Object.freeze(t.span),body:_e(t.body)});return Object.freeze({...t,span:Object.freeze(t.span)})}))})}function Xs(e,t,n){if(t>=n||Iu(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!Iu(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=ku(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=ku(e,s+1,n,'"');r+=l.text,i||=!l.closed,s=l.next;continue}if(a==="\\"){o=!0;let l=e[s+1];if(!l||l===`
|
|
8
|
+
`||l==="\r"){i=!0;break}r+=l,s+=2;continue}if(a==="`"||e.startsWith("$(",s)||e.startsWith("${",s)||e.startsWith("<(",s)||e.startsWith(">(",s))i=!0;r+=a,s++}return{delimiter:r,quoted:o,next:s,ambiguous:i}}function Js(e,t,n,r){let o=[],i=t;for(let s of r){let a=i,l=!1;while(i<n){let c=Zy(e,i,n);if((s.stripTabs?c.text.replace(/^\t+/,""):c.text)===s.delimiter){s.attach({body:s.stripTabs?Xy(e.slice(a,i)):e.slice(a,i),delimiter:s.delimiter,quotedDelimiter:s.quotedDelimiter,bodySpan:{start:a,end:i},terminatorSpan:{start:i,end:c.contentEnd}}),i=c.next,l=!0;break}if(c.next<=i)break;i=c.next}if(l)continue;return o.push({code:"unterminated-heredoc",message:`heredoc delimiter ${s.delimiter} was not found`}),{next:n,issues:o,terminated:!1}}return{next:i,issues:o,terminated:!0}}function ku(e,t,n,r){let o="",i=t;while(i<n&&e[i]!==`
|
|
9
|
+
`&&e[i]!=="\r"){let s=e[i]??"";if(s===r)return{text:o,next:i+1,closed:!0};if(r==='"'&&s==="\\"&&e[i+1]){let a=e[i+1]??"";o+=["$","`",'"',"\\"].includes(a)?a:`\\${a}`,i+=2;continue}o+=s,i++}return{text:o,next:i,closed:!1}}function Iu(e){return e!=="\r"&&(/[\s;&|<>)]/u.test(e)||e==="`")}function Zy(e,t,n){let r=t;while(r<n&&e[r]!==`
|
|
10
|
+
`)r++;let o=r>=n?n:r+1;return{text:e.slice(t,r),contentEnd:r,next:o}}function Xy(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Nu=new Set(["&&","||","|","|&"]);function Lu(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return _e({kind:"program",dialect:"posix",source:e,span:n,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${t.maxInputLength} UTF-16 code units`}],nodes:[]});let r=$o(e,0,e.length,t,{used:0,max:t.maxWords},0);return _e({kind:"program",dialect:"posix",source:e,span:n,status:Vo(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function $o(e,t,n,r,o,i,s){let a=[],l=[],c=Go(),u=[],m=()=>{if(c.words.length===0&&c.redirections.length===0)return;let f={start:c.start,end:c.end},p=c.words.map((g)=>g.text);Fo(a,c,{kind:"command",dialect:"posix",source:e.slice(f.start,f.end),span:f,words:c.words,redirections:c.redirections,nested:c.nested,displayText:l.length>0&&a.length===0?e.slice(t,n):p.join(" ")})},d=t;while(d<n){let f=e[d];if(!f)break;if(s&&f===s)return m(),Du(a,l),{nodes:a,issues:l,next:d+1,closed:!0,limited:!1,pendingHeredocs:u};if(jo(f)){if(f===`
|
|
11
|
+
`||f==="\r"){m();let C=f==="\r"&&e[d+1]===`
|
|
12
|
+
`?d+2:d+1,P=a.at(-1);if(P?.kind!=="connector"||!Nu.has(P.operator))a.push(Object.freeze({kind:"connector",operator:e.slice(d,C),span:Object.freeze({start:d,end:C})}));if(u.length>0){let x=Js(e,C,n,u.splice(0));l.push(...x.issues),d=x.next;continue}d=C;continue}d++;continue}if(f==="#"){while(d<n&&e[d]!==`
|
|
13
|
+
`&&e[d]!=="\r")d++;continue}let p=c.start===-1?CC(e,d,n):void 0;if(p){if(ea(a,l),i>=r.maxDepth)return On(a,l,d,"depth-limit",r.maxDepth);if(!Qs(o))return On(a,l,d,"word-limit",r.maxWords);let C=$o(e,p.braceIndex+1,n,r,o,i+1,"}"),P=C.next,x={start:p.braceIndex+1,end:C.closed?P-1:P},A=Ou(e,x,C);if(a.push({kind:"function",name:p.name,span:{start:d,end:P},body:A}),l.push(...C.issues),C.pendingHeredocs.length>0||Sr(C.nodes))l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"});if(u.push(...C.pendingHeredocs),C.limited)return Bo(a,l,C.next);if(!C.closed)l.push({code:"unclosed-function-body",message:"function body is not closed"});d=P;continue}let g=Uo(e,d);if(g){if(m(),!Uu(a.at(-1)))l.push({code:"unexpected-connector",message:`connector ${g} has no preceding command`});a.push(Object.freeze({kind:"connector",operator:g,span:Object.freeze({start:d,end:d+g.length})})),d+=g.length;continue}if(f===")"){m(),l.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),a.push({kind:"unknown",source:f,span:{start:d,end:d+1}}),d++;continue}if((f==="("||f==="{"&&iC(e,d,n))&&c.start===-1){if(ea(a,l),i>=r.maxDepth)return On(a,l,d,"depth-limit",r.maxDepth);let C=f==="("?")":"}",P=$o(e,d+1,n,r,o,i+1,C),x=P.next,A={start:d+1,end:P.closed?x-1:x},ee=Ou(e,A,P);if(a.push({kind:"group",style:f==="("?"subshell":"brace",span:{start:d,end:x},body:ee}),l.push(...P.issues),P.pendingHeredocs.length>0||Sr(P.nodes))l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"});if(u.push(...P.pendingHeredocs),P.limited)return Bo(a,l,P.next);if(!P.closed)l.push({code:f==="("?"unclosed-subshell":"unclosed-brace-group",message:`${f} group is not closed`});d=x;continue}let h=(f==="<"||f===">")&&e[d+1]!=="("?tC(e,d):null;if(h){let C=c.words.at(-1),P=C&&C.span.end===d&&/^[0-9]+$/.test(C.raw)?Number(C.raw):void 0;if(P!==void 0)c.words.pop();let x=P===void 0?d:C?.span.start??d;c.start=c.start===-1?d:c.start;let A=d+h.length;while(A<n&&/[ \t]/.test(e[A]??""))A++;let ee=e[A],qe=A>d+h.length&&ee==="#",ct=!ee||jo(ee)||!!Uo(e,A)||ee===s||ee===")"||qe||(ee==="<"||ee===">")&&e[A+1]!=="(",xe=h==="<<"||h==="<<-",Z=xe?Xs(e,A,n):void 0,H=Z?{word:In(e,A,Z.next,Z.delimiter,"literal",Z.quoted),nested:[],issues:[],next:Z.next,limited:!1}:!ct?ta(e,A,n,r,o,i):void 0;if(H){if(l.push(...H.issues),H.limited)return Bo(a,l,H.next);if(!Qs(o))return On(a,l,H.next,"word-limit",r.maxWords)}let ie=H?.next??d+h.length,ne={kind:"redirection",operator:h,span:{start:x,end:ie},...P===void 0?{}:{fd:P},...H?{target:H.word}:{}};if(c.redirections.push(ne),xe&&!Z)l.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"});if(Z){if(Z.ambiguous||Z.delimiter.length===0)l.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let se=c.nested;u.push({delimiter:Z.delimiter,quotedDelimiter:Z.quoted,stripTabs:h==="<<-",attach:(Oe)=>{if(ne.heredoc=Oe,Oe.quotedDelimiter)return;se.push(...Qy(e,Oe.bodySpan.start,Oe.bodySpan.end,r,o,i+1))}})}if(!xe&&!H)l.push({code:"missing-redirection-target",message:`redirection ${h} requires a target word`});if(H)c.nested.push(...H.nested);c.end=ie,d=ie;continue}if(c.start===-1)ea(a,l);let y=ta(e,d,n,r,o,i);if(l.push(...y.issues),y.limited)return Bo(a,l,y.next);let S=lC(c.words)?fC(e,y.word,o.max-o.used,r.maxDepth,r.maxInputLength):void 0;if(S?.limitCode)return On(a,l,y.next,S.limitCode,S.limitCode==="word-limit"?r.maxWords:S.limitCode==="depth-limit"?r.maxDepth:r.maxInputLength);let E=S?.words??[y.word];for(let C of E){if(!Qs(o))return On(a,l,y.next,"word-limit",r.maxWords);c.words.push(C)}c.start=c.start===-1?d:c.start,c.end=y.next,c.nested.push(...y.nested),d=y.next>d?y.next:d+1}return m(),Du(a,l),l.push(...bC(u)),{nodes:a,issues:l,next:d,closed:s===void 0,limited:!1,pendingHeredocs:[]}}function Ou(e,t,n){return{kind:"program",dialect:"posix",source:e.slice(t.start,t.end),span:t,status:Vo(n.issues,n.limited),issues:n.issues,nodes:n.nodes}}function ta(e,t,n,r,o,i){let s="",a=t,l=!1,c="literal",u=[],m=[],d=!1;while(a<n){let f=e[a],p=(f==="<"||f===">")&&e[a+1]==="(";if(!f||jo(f)||(f===";"||f==="|"||f==="&")&&Uo(e,a)||(f==="<"||f===">")&&!p)break;if(f===")")break;if(f==="'"){l=!0;let h=e.indexOf("'",a+1);if(h===-1||h>=n){s+=e.slice(a+1,n),m.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),a=n;break}s+=e.slice(a+1,h),a=h+1;continue}if(f==='"'){l=!0;let h=Jy(e,a,n,r,o,i);if(s+=h.text,u.push(...h.nested),m.push(...h.issues),d||=h.limited,c=br(c,h.provenance),a=h.next,d)break;continue}if(e.startsWith("$'",a)){l=!0;let h=nC(e,a+2,n);if(s+=h.text,m.push(...h.issues),!h.closed)m.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"});a=h.next;continue}if(f==="\\"){let h=e[a+1];if(!h){m.push({code:"trailing-escape",message:"escape has no following character"}),a++;break}if(h===`
|
|
14
|
+
`){a+=2;continue}s+=h,a+=2;continue}let g=f==="$"||f==="<"||f===">"||f==="`"?Ko(e,a,n,r,o,i):null;if(g){let h=Wu(g,u,m);if(d||=h.limited,c=br(c,h.provenance),a=h.next,d)break;continue}if(f==="$"){let h=zu(e,a,n,s,c);s=h.text,c=h.provenance,a=h.next;continue}if(f==="*"||f==="?"||f==="[")c=br(c,"glob");s+=f,a++}return{word:In(e,t,a,s,c,l,c==="literal"?void 0:oC(e,t,a)),nested:u,issues:m,next:a,limited:d}}function Jy(e,t,n,r,o,i){let s="",a="literal",l=[],c=[],u=!1,m=t+1;while(m<n){let d=e[m];if(d==='"')return{text:s,provenance:a,nested:l,issues:c,next:m+1,limited:u};if(d==="\\"&&e[m+1]){let p=e[m+1]??"";if(p===`
|
|
15
15
|
`){m+=2;continue}if(p==="\r"&&e[m+2]===`
|
|
16
|
-
`){m+=3;continue}s+=["$","`",'"',"\\"].includes(p)?p:`\\${p}`,m+=2;continue}if(e.startsWith("$((",m)){let p=
|
|
16
|
+
`){m+=3;continue}s+=["$","`",'"',"\\"].includes(p)?p:`\\${p}`,m+=2;continue}if(e.startsWith("$((",m)){let p=na(e,m+3,n,"))"),g=p===-1?n:p+2;if(s+=e.slice(m,g),p===-1)c.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});m=g;continue}let f=Ko(e,m,n,r,o,i);if(f){let p=Wu(f,l,c);if(m=p.next,u||=p.limited,a=br(a,p.provenance),u)return{text:s,provenance:a,nested:l,issues:c,next:m,limited:u};continue}if(d==="$"){let p=zu(e,m,n,s,a);s=p.text,a=p.provenance,m=p.next;continue}s+=d??"",m++}return c.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:s,provenance:a,nested:l,issues:c,next:n,limited:u}}function Ko(e,t,n,r,o,i){let s=e.startsWith("$((",t),a=e.startsWith("$(",t)&&!s,l=e.startsWith("<(",t)||e.startsWith(">(",t),c=e[t]==="`";if(!s&&!a&&!l&&!c)return null;let u=s?3:c?1:2,m=s?"))":c?"`":")",d=na(e,t+u,n,m),f=d===-1?n:d,p=d===-1?n:d+m.length;if(i>=r.maxDepth)return{program:yC(e,t+u,f,"depth-limit"),next:p,provenance:s?"arithmetic":"command-substitution"};if(s){let S=[],E=[],C=!1,P=t+u;while(P<f){let x=Ko(e,P,f,r,o,i+1);if(!x){P++;continue}if(S.push(...x.program.nodes),E.push(...x.program.issues),C||=x.program.status==="limited",P=x.next,C)break}if(d===-1)E.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"});return{program:_e({kind:"program",dialect:"posix",source:e.slice(t+u,f),span:{start:t+u,end:f},status:Vo(E,C),issues:E,nodes:S}),next:p,provenance:"arithmetic"}}let g=$o(e,t+u,f,r,o,i+1),h=d===-1?[{code:"unclosed-command-substitution",message:`${e.slice(t,t+u)} substitution is not closed`}]:[],y=(c||l)&&Sr(g.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[];return{program:_e({kind:"program",dialect:"posix",source:e.slice(t+u,f),span:{start:t+u,end:f},status:Vo([...g.issues,...h,...y],g.limited),issues:[...g.issues,...h,...y],nodes:g.nodes}),next:p,provenance:"command-substitution"}}function Qy(e,t,n,r,o,i){let s=[],a=t;while(a<n){let l=e[a];if(l==="\\"){a+=2;continue}let c=l==="$"||l==="`"?Ko(e,a,n,r,o,i):null;if(!c){a++;continue}if(s.push(c.program),a=c.next,c.program.status==="limited")break}return s}function Wu(e,t,n){return t.push(e.program),n.push(...e.program.issues),{provenance:e.provenance,next:e.next,limited:e.program.status==="limited"}}function na(e,t,n,r){if(r==="`"){for(let a=t;a<n;a++){if(e[a]==="\\"){a++;continue}if(e[a]==="`")return a}return-1}let o=1,i={single:!1,double:!1},s=[];for(let a=t;a<n;a++){let l=e[a];if((l===`
|
|
17
17
|
`||l==="\r")&&s.length>0){let u=l==="\r"&&e[a+1]===`
|
|
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
|
|
18
|
+
`?a+2:a+1,m=Js(e,u,n,s.splice(0));if(!m.terminated)return-1;a=m.next-1;continue}let c=Gu(e,a,t,n,i);if(c!==null){a=c;continue}if(!i.double&&e.startsWith("$((",a)){let u=eC(e,a+3,n);if(u===-1)return-1;a=u+1;continue}if(r===")"&&!i.double&&l==="<"&&e[a+1]==="<"&&e[a+2]!=="<"){let u=e[a+2]==="-",m=a+(u?3:2);while(m<n&&/[ \t]/.test(e[m]??""))m++;let d=Xs(e,m,n);if(d){s.push({delimiter:d.delimiter,quotedDelimiter:d.quoted,stripTabs:u,attach:()=>{return}}),a=d.next-1;continue}}if(e.startsWith("$(",a)&&!e.startsWith("$((",a)){o++,a++;continue}if(l==="("&&!i.double)o++;if(l===")"&&!i.double){if(o--,o===0)return r==="))"&&e[a+1]!==")"?-1:a}}return-1}function eC(e,t,n){let r=1,o={single:!1,double:!1};for(let i=t;i<n;i++){let s=e[i],a=Gu(e,i,t,n,o);if(a!==null){i=a;continue}if(e.startsWith("$(",i)&&!e.startsWith("$((",i)){r++,i++;continue}if(s==="("&&!o.double)r++;if(s!==")"||o.double)continue;if(r--,r===0)return e[i+1]===")"?i:-1}return-1}function Gu(e,t,n,r,o){let i=e[t];if(i==="\\"&&!o.single)return t+1;if(!o.double&&i==="'")o.single=!o.single;if(!o.single&&i==='"')o.double=!o.double;if(o.single)return t;if(o.double||i!=="#"||!SC(e,t,n))return null;let s=t;while(s+1<r&&e[s+1]!==`
|
|
19
|
+
`&&e[s+1]!=="\r")s++;return s}function Uo(e,t){let n=e[t];if(n===";")return";";if(n==="&")return e[t+1]==="&"?"&&":"&";if(n==="|")return e[t+1]==="|"?"||":e[t+1]==="&"?"|&":"|";return null}function tC(e,t){let n=e[t];if(n===">"){if(e[t+1]===">")return">>";if(e[t+1]==="&")return">&";return e[t+1]==="|"?">|":">"}if(n!=="<")return null;if(e.startsWith("<<<",t))return"<<<";if(e.startsWith("<<-",t))return"<<-";if(e[t+1]==="<")return"<<";if(e[t+1]==="&")return"<&";if(e[t+1]===">")return"<>";return"<"}function jo(e){let t=e.charCodeAt(0);if(t===32||t>=9&&t<=13)return!0;if(t<128)return!1;return/\s/u.test(e)}function Fu(e,t,n){if(e[t+1]==="{"){let o=e.indexOf("}",t+2);return o===-1||o>=n?n:o+1}let r=t+1;while(r<n&&/[A-Za-z0-9_?@#$!*-]/.test(e[r]??""))r++;return r===t+1?t+1:r}function nC(e,t,n){let r="",o=[],i=t;while(i<n){let s=e[i];if(s==="'")return{text:r,next:i+1,closed:!0,issues:o};if(s!=="\\"){r+=s??"",i++;continue}let a=rC(e,i+1,n);if(r+=a.text,a.invalidCodePoint!==void 0)o.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${a.invalidCodePoint}`});i=a.next}return{text:r,next:n,closed:!1,issues:o}}function rC(e,t,n){let r=e[t];if(!r||t>=n)return{text:"\\",next:t};let o=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
|
|
20
|
+
`],["r","\r"],["t","\t"],["v","\v"],["\\","\\"],["'","'"],['"','"']]);if(o.has(r))return{text:o.get(r)??r,next:t+1};if(r==="x")return Ho(e,t+1,n,16,2,t+1);if(r==="u")return Ho(e,t+1,n,16,4,t+1);if(r==="U")return Ho(e,t+1,n,16,8,t+1);if(/[0-7]/.test(r))return Ho(e,t,n,8,3,t+1);return{text:r,next:t+1}}function Ho(e,t,n,r,o,i){let s=r===16?/[0-9a-fA-F]/:/[0-7]/,a="",l=t;while(l<n&&a.length<o&&s.test(e[l]??""))a+=e[l],l++;if(!a)return{text:e[i-1]??"",next:i};let c=Number.parseInt(a,r);return c>1114111||c>=55296&&c<=57343?{text:"�",next:l,invalidCodePoint:c}:{text:String.fromCodePoint(c),next:l}}function Vo(e,t=!1){if(t)return"limited";if(e.some((n)=>n.code==="invalid-ansi-c-code-point"||n.code==="missing-heredoc-delimiter"||n.code==="ambiguous-heredoc-delimiter"||n.code==="unterminated-heredoc"||n.code==="unsupported-heredoc-context"))return"invalid";return e.length>0?"partial":"complete"}function zu(e,t,n,r,o){let i=Fu(e,t,n);return{text:r+e.slice(t,i),provenance:br(o,"variable"),next:i}}function oC(e,t,n){let r=zo(e),o=t,i=!1,s=!1,a=t;while(a<n){let l=e[a];if(l==="\\"&&!i){a+=2;continue}if(!s&&l==="'"){i=!i,a++;continue}if(!i&&l==='"'){s=!s,a++;continue}if(i){a++;continue}let c=e.startsWith("$((",a),u=e.startsWith("$(",a)&&!c,m=!s&&(e.startsWith("<(",a)||e.startsWith(">(",a)),d=l==="`";if(c||u||m||d){let f=c?3:d?1:2,p=c?"))":d?"`":")",g=na(e,a+f,n,p),h=g===-1?n:g+p.length;r.push(o,a,"literal"),r.push(a,h,c?"arithmetic":"command-substitution"),a=h,o=h;continue}if(l==="$"){let f=Fu(e,a,n);if(f>a+1){r.push(o,a,"literal"),r.push(a,f,"variable"),a=f,o=f;continue}}if(!s&&(l==="*"||l==="?"||l==="[")){r.push(o,a,"literal"),r.push(a,a+1,"glob"),a++,o=a;continue}a++}return r.push(o,n,"literal"),r.parts}function br(e,t){if(t==="command-substitution"||e==="command-substitution")return"command-substitution";if(t==="arithmetic"||e==="arithmetic")return"arithmetic";if(t==="variable"||e==="variable")return"variable";if(t==="glob"||e==="glob")return"glob";return e}function iC(e,t,n){return t+1>=n||jo(e[t+1]??"")||Uo(e,t+1)!==null}var sC=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),aC=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function lC(e){let t=0;while(t<=e.length){while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]?.text??""))t++;if(t===e.length)return!0;let n=cC(e,t);if(n===void 0||n===null)return!1;t=n}return!1}function cC(e,t){let n=e[t]?.text.toLowerCase();if(n==="command")return uC(e,t);if(n==="env")return dC(e,t);if(n==="sudo")return mC(e,t);return}function uC(e,t){if(e[t+1]?.text==="-v")return null;for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(r==="-p"||r==="-v"||r==="-V"||/^-[pvV]+$/.test(r))continue;return n}return e.length}function dC(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(sC.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-u=")||r.startsWith("--unset=")||r.startsWith("-C")&&r.length>2||r.startsWith("--chdir=")||r.startsWith("-S")&&r.length>2||r.startsWith("--split-string=")||r.startsWith("-P"))continue;if(r.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(r))continue;return n}return e.length}function mC(e,t){for(let n=t+1;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return n+1;if(aC.has(r)){if(e[n+1]===void 0)return null;n++;continue}if(r.startsWith("-"))continue;return n}return e.length}function Hu(e,t,n,r){if(e.provenance!=="literal"||!e.raw.includes("{"))return;let o=Bu(e.raw,t,n,r,!0);if(!o)return;if("limited"in o)return{limited:!0};let i=o.values.map((s)=>$u(s,n));if(i.some((s)=>s===null))return{limited:!0};return{words:[...new Set(i.filter((s)=>s!==null&&s!==""))]}}function fC(e,t,n,r,o){if(t.provenance!=="literal"||!t.raw.includes("{"))return;let i=Bu(t.raw,n,r,o,!1);if(!i)return;if("limited"in i){if(i.limited==="expansions")return{limitCode:"depth-limit"};return{limitCode:i.limited==="length"?"brace-expansion-limit":"word-limit"}}let s=i.values.map((a)=>$u(a,r));if(s.some((a)=>a===null))return;return{words:s.filter((a)=>a!==null&&a!=="").map((a)=>In(e,t.span.start,t.span.end,a,"literal",!1))}}function Bu(e,t,n,r,o){let i=[e],s=e.length,a=0;while(!0){let l=i.findIndex((f)=>Mu(f,o));if(l===-1)break;if(++a>n)return{limited:"expansions"};let c=i[l]??"",u=Mu(c,o);if(!u||u.kind==="range")return{limited:"expansions"};let m=u.start+c.length-u.end,d=u.alternatives.reduce((f,p)=>f+m+p.length,0);if(s-c.length+d>r)return{limited:"length"};if(i.length-1+u.alternatives.length>t)return{limited:"words"};i.splice(l,1,...pC(c,u)),s+=d-c.length}return a===0?void 0:{values:i}}function Mu(e,t){let n=[],r,o=null,i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(i){i=!1;continue}if(a==="\\"&&o!=="'"){i=!0;continue}if(a===o){o=null;continue}if(o===null&&(a==="'"||a==='"')){o=a;continue}if(o!==null)continue;if(a==="{"){n.push({start:s,commas:[]});continue}if(a===","&&n.length>0){n.at(-1)?.commas.push(s);continue}if(a!=="}"||n.length===0)continue;let l=n.pop();if(!l)continue;let c=l.commas.length>0?{kind:"alternatives",start:l.start,end:s+1,commas:l.commas}:t&&hC(e.slice(l.start+1,s))?{kind:"range",start:l.start,end:s+1}:void 0;if(c&&(!r||c.start<r.start))r=c}if(!r||r.kind==="range")return r;return{kind:r.kind,start:r.start,end:r.end,alternatives:gC(e,r)}}function pC(e,t){return t.alternatives.map((n)=>`${e.slice(0,t.start)}${n}${e.slice(t.end)}`)}function gC(e,t){let n=[t.start,...t.commas,t.end-1];return n.slice(0,-1).map((r,o)=>e.slice(r+1,n[o+1]))}function hC(e){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(e)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(e)}function $u(e,t){let n=`x${e}`,r=ta(n,0,n.length,{maxInputLength:n.length,maxWords:1,maxDepth:t},{used:0,max:1},0);if(r.limited||r.issues.length>0||r.next!==n.length||r.word.provenance!=="literal")return null;return r.word.text.slice(1)}function yC(e,t,n,r){return _e({kind:"program",dialect:"posix",source:e.slice(t,n),span:{start:t,end:n},status:"limited",issues:[{code:r,message:"command structure exceeds parser limit"}],nodes:[]})}function On(e,t,n,r,o){return{nodes:e,issues:[...t,{code:r,message:`command structure exceeds parser limit ${o}`}],next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function Bo(e,t,n){return{nodes:e,issues:t,next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function Qs(e){return e.used++,e.used<=e.max}function CC(e,t,n){let r=e.slice(t,n),o=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(r)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(r),i=o?.[1];if(!o||!i)return;return{name:i,braceIndex:t+o[0].lastIndexOf("{")}}function Sr(e){return e.some((t)=>{if(t.kind==="command")return t.redirections.some((n)=>n.heredoc)||t.nested.some((n)=>Sr(n.nodes));return(t.kind==="group"||t.kind==="function")&&Sr(t.body.nodes)})}function bC(e){return e.map((t)=>({code:"unterminated-heredoc",message:`heredoc delimiter ${t.delimiter} was not found`}))}function Uu(e){return e?.kind==="command"||e?.kind==="group"||e?.kind==="function"}function Du(e,t){let n=e.at(-1);if(n?.kind!=="connector"||!Nu.has(n.operator))return;t.push({code:"missing-command-after-connector",message:`connector ${n.operator} requires a following command`})}function ea(e,t){if(!Uu(e.at(-1)))return;t.push({code:"missing-command-connector",message:"adjacent commands require a connector"})}function SC(e,t,n){return t===n||/[\s;&|()]/u.test(e[t-1]??"")}var Vu=new Set(["remove-item","ri","del","erase","rd","rmdir","get-content","set-content","add-content","copy-item","move-item"]),vC=new Set(["gc","cat","type","cp","mv","rm"]),Ku=["-rec","-for","-path","-literalpath","-whatif"],EC=/^\$env:\w/i,xC=/^(?:\$\{?\w+\}?|~)\\./;function qu(e,t){let n=e.toLowerCase().replaceAll("`","");if(![...Vu].some((o)=>n.includes(o))&&!(n.includes("rm")&&Ku.some((o)=>n.includes(o)))&&!n.includes("<#")&&!RC(n))return!1;let r=sa(e,t);if(Yu(r))return!1;return r.issues.some((o)=>o.code==="unclosed-block-comment"||o.code==="comment-depth-limit")||ia(r).some(wC)}function Yu(e){return e.nodes.some((t)=>{if(t.kind==="group")return Yu(t.body);if(t.kind!=="command")return!1;return t.redirections.some((n)=>n.operator==="<<")})}function RC(e){if(e.includes("$env:"))return!0;return e.includes("\\")&&(e.includes("$")||e.includes("~"))}function wC(e){let t=e[0]==="&"||e[0]==="."?1:0,n=e[t]?.toLowerCase();if(n&&Vu.has(n))return!0;let r=e.slice(t+1);if(n&&vC.has(n)&&r.some(_C))return!0;if(n!=="rm")return!1;return r.some((o)=>{let i=o.toLowerCase().split(":",1)[0]??"";return Ku.some((s)=>i.startsWith(s))})}function _C(e){return EC.test(e)||xC.test(e)}function sa(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return _e({kind:"program",dialect:"powershell",source:e,span:n,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${t.maxInputLength} UTF-16 code units`}],nodes:[]});let r=aa(e,0,e.length,t,0);return _e({kind:"program",dialect:"powershell",source:e,span:n,status:IC(r.issues,r.limited),issues:r.issues,nodes:r.nodes})}function aa(e,t,n,r,o,i=!1){let s=[],a=[],l=Go(),c=0,u=!1,m=()=>{if(l.words.length===0&&l.redirections.length===0)return;let f={start:l.start,end:l.end};Fo(s,l,{kind:"command",dialect:"powershell",source:e.slice(f.start,f.end),span:f,words:l.words,redirections:l.redirections,nested:l.nested,displayText:l.words.map((p)=>p.text).join(" ")})},d=t;while(d<n){let f=e[d];if(!f)break;if(i&&f==="}")return m(),{nodes:s,issues:a,next:d+1,closed:!0,words:c,limited:u};let p=kC(e,d,n,r.maxDepth);if(p){if(p.issue)a.push(p.issue);if(p.limited)return m(),{nodes:s,issues:a,next:p.next,closed:!1,words:c,limited:!0};d=p.next;continue}if(/\s/.test(f)){if(f==="\r"||f===`
|
|
21
21
|
`){m();let y=f==="\r"&&e[d+1]===`
|
|
22
|
-
`?d+2:d+1;s.push(
|
|
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
|
|
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===
|
|
28
|
-
`,a++;if(l)n=!1,r=!1;t=!0,o=a;continue}if(!t){o++;continue}if(Y(e,o,"--")&&(o===0||q(C(e,o-1)))&&(!C(e,o+2)||q(C(e,o+2))||pe(C(e,o+2)))){t=!1,n=!1,r=!1,o+=2;continue}if(n||=Y(e,o,"--recursive")&&bt(e,o+11)||ra(e,o,"recursive"),r||=Y(e,o,"--force")&&bt(e,o+7)||ra(e,o,"force"),n&&r)return!0;o++}return!1}function ra(e,t,n){if(!Y(e,t,"--"))return!1;let r=0;while(r<=n.length){let o=C(e,t+r+2);if(!o||q(o)||pe(o))break;if(o!==n[r])return!1;r++}return r>0&&bt(e,t+r+2)}function RC(e,t){let n=t,r=!1,o=!1;while(n<ne(e)){while(q(C(e,n)))n++;let i=n;while(n<ne(e)&&!q(C(e,n)))n++;if(C(e,i)!=="-"||n-i===2&&Y(e,i,"--"))return!1;let s=Vu(e,i,"recursive"),a=Vu(e,i,"force");if(r&&a||o&&s)return!0;if(r||=s,o||=a,C(e,i+1)==="-")continue;let l=wC(e,i,n);if(l.combined||r&&l.forceAtBoundary||o&&l.recursiveAtBoundary)return!0;r||=l.recursive,o||=l.force}return!1}function Vu(e,t,n){return Y(e,t,`--${n}`)&&bt(e,t+n.length+2)||ra(e,t,n)}function _C(e,t){if(t>0&&Zt(C(e,t-1)))return-1;let n=t;if(C(e,n)==="\\")n++;if(C(e,n)!=="r")return-1;if(n++,C(e,n)==="\\")n++;if(C(e,n)!=="m"||!q(C(e,n+1)))return-1;return n+1}function wC(e,t,n){let r=!1,o=!1,i=!1,s=!1,a=!1;if(C(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=C(e,c)??"",m=(u==="r"||u==="f")&&bt(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 Ku(e,t,n){return pr(e,"reset",wn,!0,(r)=>C(e,r)==="-"&&An(e,r,t,n)?!0:r)}function AC(e){return pr(e,"clean",wn,!0,(t)=>{if(C(e,t)!=="-")return t;if(An(e,t,"--fo","rce"))return!0;let n=fr(e,t,wn);for(let r=t+1;r<n;r++)if(C(e,r)==="f")return!0;return n-1})}function zo(e,t,n){if(!Ct(e,t,"git"))return null;let r=t+3;if(!q(C(e,r)))return{commandEnd:-1,next:r};while(q(C(e,r)))r++;while(r<ne(e)){if(pe(C(e,r)))return{commandEnd:-1,next:r};let o=fr(e,r,pe);if(Ct(e,r,n))return{commandEnd:r+n.length,next:o};if(C(e,r)!=="-")return{commandEnd:-1,next:o};let i=o-r===2&&Y(e,r,"--"),s=PC(e,r,o);r=o;while(q(C(e,r)))r++;if(i)return{commandEnd:Ct(e,r,n)?r+n.length:-1,next:fr(e,r,pe)};if(!s)continue;if(r>=ne(e)||pe(C(e,r)))return{commandEnd:-1,next:r};r=fr(e,r,pe);while(q(C(e,r)))r++}return{commandEnd:-1,next:r}}function PC(e,t,n){for(let r of Me)if(n-t===r.length&&Y(e,t,r))return!0;return!1}function TC(e){return qu(e,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function IC(e){return pr(e,"push",wn,!0,(t)=>{if(C(e,t)!=="-")return t;if(C(e,t+1)==="f"&&!Zt(C(e,t+2))&&!Y(e,t+2,"-with-lease"))return!0;let n=Zu(e,t,"--fo","rce");if(n>=0&&!Y(e,n,"-with-lease"))return!0;return t})}function kC(e){return pr(e,"push",pe,!1,(t)=>{if(q(C(e,t))&&C(e,t+1)==="+"&&t+2<ne(e)&&!pe(C(e,t+2))&&!q(C(e,t+2)))return!0;if(C(e,t)===":"&&C(e,t+1)==="+")return!0;return t})}function OC(e){return pr(e,"push",pe,!1,(t)=>{if(C(e,t)==="-"&&An(e,t,"--de","lete"))return!0;if(q(C(e,t))&&C(e,t+1)===":"&&t+2<ne(e)&&!q(C(e,t+2))&&!pe(C(e,t+2)))return!0;return t})}function MC(e){let t=!1,n=!1,r=!1;for(let o=0;o<=ne(e);o++){if(o===ne(e)||pe(C(e,o))){if(n&&r)return!0;t=!1,n=!1,r=!1;continue}if(!t){let a=zo(e,o,"branch");if(a){t=a.commandEnd>=0,o=Math.max(o,(t?a.commandEnd:a.next)-1);continue}}if(!t||C(e,o)!=="-")continue;let i=fr(e,o,pe),s=DC(e,o,i);if(n||=s.deletion,r||=s.force,n&&r)return!0;o=i-1}return!1}function DC(e,t,n){let r=!1,o=!1;for(let i=t;i<n;i++){if(C(e,i)!=="-")continue;if(An(e,i,"--de","lete"))r=!0;if(An(e,i,"--fo","rce"))o=!0;if(C(e,i+1)==="-")continue;let s=i+1,a=!1,l=!1,c=!1;while(s<n&&NC(C(e,s))){let u=C(e,s);a||=u==="d"||u==="D",l||=u==="f",c||=u==="D",s++}if(!bt(e,s))continue;r||=a,o||=l||c}return{deletion:r,force:o}}function NC(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function LC(e){return qu(e,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function qu(e,t){let n=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let r=0;r<ne(e);r++){let o=C(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==="$"&&C(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(q(o))i.shortActive=!1,i.hasShortFlag=!1;if(!i.outerActive){let a=zo(e,r,t.command);if(a){i.outerActive=a.commandEnd>=0&&q(C(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(An(e,r,t.longPrefix,t.longOptional))return!0;i.shortActive||=!t.excludedShortStarts.includes(C(e,r+1)??"")}if(i.hasShortFlag||=i.shortActive&&o===t.shortFlag,i.hasShortFlag&&bt(e,r+1))return!0;if(wn(o))i.outerActive=!1}return!1}function pr(e,t,n,r,o){let i=!1;for(let s=0;s<ne(e);s++){let a=C(e,s),l=n(a);if(!i&&!l){let c=zo(e,s,t);if(c){i=c.commandEnd>=0&&(!r||q(C(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(C(e,u)))i=!1;s=c}if(l)i=!1}return!1}function WC(e){let t=!1;for(let n=0;n<ne(e);n++){if(na(C(e,n))){if(t)return!0;t=!1;continue}if(!t){let r=zo(e,n,"restore");if(r){t=r.commandEnd>=0,n=Math.max(n,(t?r.commandEnd:r.next)-1);continue}}if(t&&C(e,n)==="-"&&C(e,n+1)==="-"&&(Y(e,n+2,"staged")||Y(e,n+2,"help")))t=!1}return t}function Yu(e,t){let n=!1;for(let r=0;r<ne(e);r++){let o=C(e,r),i=t?na(o):pe(o);if(n&&q(o)&&C(e,r+1)==="-"&&Ct(e,r+2,"delete"))return!0;if(i){n=!1;continue}if(Ct(e,r,"find"))n=!0,r+=3}return!1}function fr(e,t,n){let r=t;while(r<ne(e)&&!q(C(e,r))&&!n(C(e,r)))r++;return r}function Zu(e,t,n,r){if(!Y(e,t,n))return-1;let o=t+n.length;for(let i=0;i<r.length&&C(e,o)===r[i];i++)o++;return bt(e,o)?o:-1}function An(e,t,n,r){return Zu(e,t,n,r)>=0}function Be(e,t){mr(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)We(t,a);if((s.regex?.test(a)??!1)||s.scan&&Fo(a,s.scan,t))return S("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 GC=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ju(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;mr(n,t.source,2);let i={anchored:new RegExp(`^\\$\\{?${o}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${o}(?![A-Za-z0-9_])`)};return Qu(t.nodes,r,i)}function Qu(e,t,n){return e.every((r)=>{if(r.kind==="connector")return!0;if(r.kind==="group"||r.kind==="function")return Qu(r.body.nodes,t,n);if(r.kind==="unknown")return!n.loose.test(r.source);return FC(r,t,n)})}function FC(e,t,n){if(e.nested.some((o)=>n.loose.test(o.source)))return!1;let r=e.words.findIndex((o)=>!GC.test(o.text));return e.words.every((o,i)=>o===t||Xu(o.raw,n.anchored,i!==r))&&e.redirections.every((o)=>(!o.heredoc||o.heredoc.quotedDelimiter||!n.loose.test(o.heredoc.body))&&(!o.target||Xu(o.target.raw,n.anchored,!0)))}function Xu(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 gr=require("node:path");function hr(e,t,n,r){let o=gr.isAbsolute(e)?gr.resolve(e):t?gr.resolve(t,e):void 0;if(!o)return;try{return N(o,n,r)}catch{return o}}function ed(e){return!["/dev","/proc","/sys"].some((t)=>e===t||e.startsWith(`${t}/`))}var Pn="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",yr="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.",ia=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"]),HC=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),BC=new Map([["python",new Set(["W","X"])],["node",new Set(["C","r"])],["ruby",new Set(["C","E","F","I","r"])],["perl",new Set(["F","I","M","m"])]]),$C=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),UC=new Map([["python",new Set(["m"])]]),jC=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"])]]),VC=new Set(["always","default","never"]),KC=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),qC=/\\\r?\n/g,YC=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 td(e){return Bo(e).code}function Ho(e){return Bo(e).sources}function nd(e){return YC.get(aa(e))??[]}function Bo(e){let t=aa(e[0]??"");if(!ia.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 Ze(t,n,r,o,e[i+1]===void 0?void 0:i+1,e[i+1]);if(s===""||s==="-"||!s.startsWith("-"))return Ze(t,n,r,o,i,s);if(t==="node"&&zC.has(s)){let m=e[i+1];if(m===void 0)return Ze(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(XC(t,s)){let m=e[i+1];if(m===void 0)return Ze(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 Ze(t,n,r,o);i++;continue}let a=/^--eval=(.*)$/s.exec(s);if(JC(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=ZC(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,Ze(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 Ze(t,n,r,o);if(jC.get(t)?.has(s)){let m=e[i+1];if(m===void 0||m.startsWith("-")&&!(t==="ruby"&&KC.has(s))||t==="python"&&!VC.has(m))return Ze(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(UC.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 Ze(t,n,r,o)}if(HC.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(BC.get(t)?.has(d)){if(m+1===s.length)i++;break}if($C.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 Ze(t,n,r,o);if(c)i++}return Ze(t,n,r,o,void 0,void 0,!0)}function Ze(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 ZC(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 sa(e,t){return aa(e)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(t)}function aa(e){let t=I(e).toLowerCase();return co.test(t)?"python":t}function XC(e,t){return ia.get(e)?.has(t)??!1}function JC(e){return ia.get(e)?.has("--eval")??!1}function Cr(e,t,n=!1){let r=tb(e,t);if(!oa(r,t))return!1;We(t,r);let o=eb(r);if(oa(o,t))return!0;if(We(t,o),!rd.test(o))return!1;return!n||QC(r,t)}function QC(e,t){if(/`|%x|\bqx\b/.test(e))return!0;let n=e.split(""),r=[];for(let s=0;s<e.length;s++){let a=e[s];if(a!=="'"&&a!=='"')continue;let l=e.startsWith(a.repeat(3),s)?a.repeat(3):a,c=s+l.length,u=c;while(u<e.length&&!e.startsWith(l,u))u+=e[u]==="\\"?2:1;if(u>=e.length)return!0;r.push({start:c,text:e.slice(c,u)}),n.fill(" ",s,u+l.length),s=u+l.length-1}let o=n.join(""),i=Array.from(o.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((s)=>rd.test(s[1]??"")).map((s)=>{let a=s.index+s[0].length;return{start:a,end:la(o,a)}});if(i.some((s)=>ca(o,s.start)))return!0;return r.some((s)=>(/\b(?:system|exec|spawn|popen)\s*$/.test(o.slice(0,s.start))||i.some((a)=>s.start>=a.start&&s.start<a.end))&&oa(s.text,t))}function la(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 ca(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 rd=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function eb(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 oa(e,t){if(Go(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(We(t,e),r.test(e))return!0;if(Go(e,"dd",t))return!0;for(let r of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(We(t,e),r.test(e))return!0;if(Go(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)=>(We(t,e),n.some((o)=>Fo(o,r))))}function tb(e,t){return We(t,e),e.replace(qC,"")}var ei=require("node:fs"),ct=require("node:path");var Sr=require("node:path");var Nt=require("node:path");function Lt(e,t,n){if(Tt(t))throw Error("Unsupported Windows namespace path");let r=Nt.isAbsolute(t)?Nt.parse(t).root:"",o=r||e;for(let i of rb(r?t.slice(r.length):t)){if(i===""||i===".")continue;if(i===".."){o=Nt.dirname(o);continue}let s=nb(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 nb(e,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${t}`:`${e}${Nt.sep}${t}`}function rb(e){let t=process.platform==="win32"?/[\\/]+/:/\/+/;return e.split(t)}var ua=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],ob=new Set(ua),ib=1024,od=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),id=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),sb=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function $o(e){return ob.has(e)}function da(e){return $o(e)||od.has(e)||id.has(e)||Qn(e)}function St(e,t,n){return n?.has(e)?n.get(e):t.get(e)}function sd(e,t){let n=St("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<=ib?{state:"valid",count:r}:{state:"invalid"}}function Uo(e,t,n){let o=e.match(sb)?.[1];if(!o||!da(o))return null;let i=e.indexOf("=");return{name:o,value:`${St(o,t,n)??""}${e.slice(i+1)}`}}function ad(e){return cd(e,id)}function ld(e){return cd(e,od)}function cd(e,t){if(!e)return!1;for(let n of e.keys())if(t.has(n))return!0;return!1}var dd=/^[A-Za-z_][A-Za-z0-9_]*=/;function $e(e){if(!dd.test(e))return null;let t=e.indexOf("=");return{name:e.slice(0,t),value:e.slice(t+1)}}function jo(e){let t=new Map,n=0;while(n<e.length){let r=e[n];if(!r)break;let o=$e(w(r));if(!o)break;t.set(o.name,o.value),n++}return{words:e.slice(n),envAssignments:t}}function md(e){let t=O(e);return e.includes("=")||t==="sudo"||t==="env"||t==="command"||t==="builtin"}function Xt(e,t,n,r){if(!md(Tn(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=ud(i),f=jo(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&&Tn(i).includes("=")&&!lb(i)){let g=cb(Tn(i),a,t.env)??Uo(Tn(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=O(Tn(i));if(p!=="sudo"&&p!=="env"&&p!=="command"&&p!=="builtin")break;if(p==="sudo"){let g=db(i,t.paths,c);if(i=g.words,g.cwd!==void 0)c=g.cwd}if(p==="env"){let g=pb(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=gb(i);if(p==="builtin")i=i.slice(Xe(i,1)==="--"?2:1);if(ud(i)===d)break}let u=jo(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:ab(u.words,o)}}function ab(e,t){return e.some((n)=>!t.has(n))}function ud(e){return e.map(w).join(" ")}function Tn(e){let t=e[0];return t?w(t):""}function Xe(e,t){let n=e[t];return n?w(n):void 0}function lb(e){return dd.test(Tn(e))}function cb(e,t,n){if(!e.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${t.get("TMPDIR")??n.get("TMPDIR")??""}${e.slice(8)}`}}var ub=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function db(e,t,n){let r=1,o=n;while(r<e.length){let i=Xe(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=Xe(e,r+1);o=s?br(o,s,t):null,r+=2;continue}if(i.startsWith("--chdir=")){o=br(o,i.slice(8),t),r++;continue}if(i.startsWith("-D")&&i.length>2){o=br(o,i.slice(2),t),r++;continue}if(i==="-i"||i==="--login"){o=null,r++;continue}if(ub.has(i)){r+=2;continue}r++}return{words:e.slice(r),cwd:o}}var mb=new Set(["-i","-0","--null"]),fb=new Set(["-u","--unset","-C","--chdir","-P"]);function pb(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=Xe(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(mb.has(c)){a++;continue}if(c==="-u"||c==="--unset"){let m=Xe(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:Xe(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(fb.has(c)){if(c==="-C"||c==="--chdir"){let m=Xe(e,a+1);s=m?br(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=br(s,m,r.paths),a++;continue}if(c.startsWith("-P")){a++;continue}if(c.startsWith("-")){a++;continue}if(!$e(c))break;while(a<e.length){let m=$e(Xe(e,a)??"");if(!m)break;o.set(m.name,m.value),a++}if(Xe(e,a)==="--")a++;return l(a)}return l(a)}function br(e,t,n){if(t==="")return null;if(!e&&!Sr.isAbsolute(t))return null;let r=Sr.isAbsolute(t)?Sr.parse(t).root:n.realpath(e??"/");if(r===null)return null;try{return Lt(r,t,n)}catch{return null}}function gb(e){if(Xe(e,1)==="-v")return[...J(["type"]),...e.slice(2)];let t=1;while(t<e.length){let n=Xe(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 hb=/['"\\$`{}#]/;function Vo(e,t){if(e.some((r)=>hb.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 Wt(e,t,n){return Ko(e,t,n).tokens}function yb(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 Gt(e,t,n,r=0){let o=Ko(e,t,n),i=(o.envSplitValues??[]).flatMap(yb);if(i.length===0)return o.tokens;let s=[...i,...o.tokens];if(r>=8)return s;return Gt(s,t,n,r+1)}function Ko(e,t,n,r){if(!md(e[0]??""))return{tokens:[...e],envAssignments:new Map,cwd:n};let o=Xt(J(e),t,n,r);return{tokens:o.words.map(w),envAssignments:o.envAssignments,cwd:o.cwd,envSplitValues:o.envSplitValues}}var ga=Symbol("adopt-as-operand"),Cb=new Set(["env","sudo","command","builtin"]),bb=new Set(["&&","||","|&","|","&",";"]),Sb=new Set(["<<","<<<",">|"]),vb=new Set(["|","|&"]),Eb=/[*@#?$!_-]/,xb=/^\w+(?::\w+)*/,Rb=Object.freeze([]),vr=Object.freeze({kind:"scope",edge:"enter"}),Er=Object.freeze({kind:"scope",edge:"exit"}),_b=Object.freeze([]),wb=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),xr=new Set(["bash","sh","zsh","dash","ksh"]),Ab=256,yd=new WeakMap;function Cd(e,t){let n=t.status==="complete"?new Set(pa(t)):new Set,r=Ib(e,n);if(mo(r))return qo("unclosed-quote",r,t);let o={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},i=Jt(t,{source:r,suppressed:n,flags:o,depth:0,functions:new Map,powershell:t.dialect==="powershell"});if(o.limited)return qo("structural-limit",r,t);if(o.invalid)return qo("invalid",r,t);let s=qo("complete",r,t,o.assignmentFallbacks);return yd.set(s,Object.freeze(i)),s}function Zo(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 bd(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=Pb(a,s,n,r),c=a.length>0&&vb.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===ga){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 Xo(e){return bd(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 Rr(e){return e.length>0&&e.every((t)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t))}function Pb(e,t,n,r){let o=Rr(e)?new Map([...t.variables,...Tb(e,t.variables)]):t.variables,i=Wt([...e],n),s=I(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 Tb(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 bd(e){return yd.get(e)??Rb}function Ib(e,t){return[...t].reduce((n,r)=>n.slice(0,r.start)+" ".repeat(r.end-r.start)+n.slice(r.end),e)}function qo(e,t,n,r=_b){return Object.freeze({status:e,source:t,program:n,assignmentFallbacks:Object.freeze(r)})}function Jt(e,t){return e.nodes.flatMap((n,r)=>kb(n,e,r,t)).sort((n,r)=>n.start-r.start).flatMap((n)=>[...n.events])}function kb(e,t,n,r){if(e.kind==="connector")return[{start:e.span.start,events:[Je(Lb(e.operator))]}];if(e.kind==="unknown")return[{start:e.span.start,events:[Je(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?[Yo("{"),...Jt(e.body,a),...s?[Yo("}")]:[]]:[vr,Je("("),...Jt(e.body,a),...s?[Je(")")]:[],Er]}]}let o=zb(e,r.functions);if(o){if(r.depth>=Dt.maxDepth||++r.flags.expansions>Ab)return r.flags.limited=!0,[];return[{start:e.span.start,events:[...fd(e,r),Yo(";"),...Jt(o,{...r,depth:r.depth+1}),Yo(";")]},...pd(e,t,n,r)]}return[{start:e.span.start,events:fd(e,r)},...pd(e,t,n,r)]}function fd(e,t){return[...e.words.map((n)=>({start:n.span.start,events:vd(n,e,t,!1)})),...e.redirections.map((n)=>({start:n.span.start,events:Ob(n,e,t)}))].sort((n,r)=>n.start-r.start).flatMap((n)=>n.events)}function Ob(e,t,n){let r=e.operator==="<<-"?"<<":e.operator,o=e.target?vd(e.target,t,n,!0):[],i=o[0],s=i?.kind==="word"?i.text:void 0;return[...e.fd===void 0?[]:[ha(String(e.fd))],Object.freeze({kind:"redirection",operator:r,...e.fd===void 0?{}:{fd:e.fd},role:Wb(r),targetOrder:Sb.has(r)?"legacy-segment":"immediate",...s===void 0?{}:{target:s},...e.heredoc&&n.suppressed.has(e.heredoc.bodySpan)?{body:e.heredoc.body,consumer:xd(t)}:{}}),...s===void 0?o:o.slice(1)]}function pd(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=[ha(s.delimiter),.../[\r\n]/.test(r.source[s.terminatorSpan.end]??"")?[Je(";")]:[]];if(r.suppressed.has(s.bodySpan))return[{start:s.bodySpan.start,events:a}];return[{start:s.bodySpan.start,events:[...Sd(r.source.slice(s.bodySpan.start,s.bodySpan.end),r),...a]}]}),...o.some((i)=>!i.heredoc&&i.target)?Mb(t,n,r):[]]}function Mb(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:Sd(n.source.slice(r.span.end,e.span.end),n)}]}function Sd(e,t){if(t.depth>=Dt.maxDepth)return t.flags.limited=!0,[];let n=Ye(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=Jt(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 vd(e,t,n,r){let o=[],i={single:!1,double:!1},s="",a=!1,l=()=>{let c=a&&!r?Je("glob"):s!==""||e.quoted&&o.length===0?ha(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 ma(c.raw,i,n.flags,n.powershell)){if(typeof f==="string"){l(),o.push(Je(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+=ma(f,{single:!1,double:!0},n.flags,n.powershell).map((g)=>typeof g==="string"?g:g.text).join("");let p=u?Jt(u,n).filter((g)=>g.kind==="redirection"&&g.body!==void 0):[];if(p.length>0)o.push(vr,...p,Er);continue}let m=u?Jt(u,n):[];if(c.raw.startsWith("`")){s+="${}",l(),o.push(vr,...m,Er);continue}if(c.raw.startsWith("<(")||c.raw.startsWith(">(")){l(),o.push(c.raw.startsWith("<(")?Je("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),vr,...m,...c.raw.endsWith(")")?[Je(")")]:[],Er);continue}let d=c.raw.startsWith("$((")?2:1;s+="${}",l(),o.push(...Array.from({length:d},()=>Je("(")),...d===1?[vr]:[],...m,...c.raw.endsWith(")".repeat(d))?Array.from({length:d},()=>Je(")")):[],...d===1?[Er]:[])}return l(),o}function ma(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=gd(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=gd(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 gd(e,t,n,r,o){let i=e[t+1];if(i==="{"){let a=Nb(e,t+2);if(a===-1)return r.invalid=!0,{text:"",next:e.length};let l=e.slice(t,a+1);return Db(l,n,r,o),{text:l,next:a+1}}if(i!==void 0&&Eb.test(i))return{text:`\${${i}}`,next:t+2};let s=(o?xb:/^\w*/).exec(e.slice(t+1))?.[0]??"";return{text:`\${${s}}`,next:t+1+s.length}}function Db(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=ma(s.slice(a.length),{...t},n,r);n.assignmentFallbacks.push(...l.flatMap((c)=>typeof c==="string"||!c.text?[]:[c.text]))}function Nb(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 Lb(e){return/^[\r\n]+$/.test(e)?";":e}function Je(e){return Object.freeze({kind:"operator",operator:e,boundary:bb.has(e)})}function Yo(e){return Object.freeze({kind:"operator",operator:e,boundary:!0})}function ha(e){return Object.freeze({kind:"word",text:e})}function Wb(e){if(e==="<<"||e==="<<<")return"here-data";if(e==="<"||e==="<&")return"file-read";return"file-write"}function _r(e){return wb.has(e)||/^python\d/.test(e)}var Gb=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 Ed(e,t){let n=t[0];if(n===void 0||!n.startsWith("-"))return t;let r=Gb.get(e)?.has(n)??!1;return Ed(e,t.slice(r?2:1))}function fa(e){let t=e[0];if(t===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(t))return fa(e.slice(1));if(!Cb.has(t))return[...e];return fa(Ed(t,e.slice(1)))}function xd(e){let t=cr(e),n=e.words.findIndex((r)=>r.provenance==="literal"&&r.text===t);return fa(n<0?[]:e.words.slice(n).map((r)=>r.text))}function Fb(e){let t=xd(e)[0];if(t===void 0)return!1;let n=I(t).toLowerCase();return _r(n)&&!xr.has(n)}function pa(e){return e.nodes.flatMap((t,n)=>{if(t.kind==="group"||t.kind==="function")return pa(t.body);if(t.kind!=="command")return[];let r=t.nested.flatMap((a)=>pa(a)),o=t.redirections.flatMap((a)=>a.heredoc?.quotedDelimiter?[a.heredoc.bodySpan]:[]);if(Fb(t))return[...r,...o];let i=e.nodes[n+1];if(i?.kind==="connector"&&(i.operator==="|"||i.operator==="|&")||!Bb(t))return r;return[...r,...o]})}function zb(e,t){let n=cr(e);return n===void 0?void 0:t.get(n)}function Ft(e,t){return e!==void 0&&e.provenance==="literal"&&!e.quoted&&e.raw===e.text&&e.text===t}function Hb(e){if(Ft(e.words[0],"git"))return Ft(e.words[1],"commit");if(!Ft(e.words[0],"gh")||!Ft(e.words[2],"create"))return!1;return Ft(e.words[1],"pr")||Ft(e.words[1],"issue")}function Bb(e){return(Ft(e.words[0],"cat")||Ft(e.words[0],"tee")||Hb(e))&&!e.words.some(hd)&&!e.redirections.some((n)=>hd(n.target))}function hd(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}var Rd=new Set(["absolutepath","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","searchdirectory","search_directory","searchpath","targetfile","target_file"]),_d=new Set([...Rd,"glob"]),$b=new Set([..._d,"pattern"]);class Qe extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function wr(e){let t=Ub(),n=It(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:jb(e),store:t}}function Pe(e,t){return e.commands.find((n)=>n.usages.includes(t))}function vt(e,t){if(!e.includes("$"))return e;return Yi(e,t)}function Ub(){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=Ye(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=Cd(i,a);return e.set(i,c),c},getCommandProgram:r}}function jb(e){let t=e.route.kind==="grep"?_d:e.route.kind==="glob"?$b:Rd;return[...Qr(e.input,t),...e.route.kind==="patch"?eo(e.input):[]]}var Vb=new Set(["-S","--suffix"]);function In(e,t,n,r,o){if(e.status==="structural-limit")throw new Qe;if(e.status!=="complete")return o.findMalformedTarget(e.source);return Zo(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 Jo(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&&Vb.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 Ue="Git metadata and hooks are protected. Ask the user before modifying them.";function Ad(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(Jr(e.invocation.toolName))return null;let a=e.paths.find((l)=>wd(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=In(i.shell,o,n,r,{findSegmentTarget:(a,l)=>Jb(a,l,t,n,r),isRedirectionTarget:(a,l)=>wd(a,l.cwd,t,n,r,t.markerFiles),findMalformedTarget:()=>null});return s?{target:s}:null}function Qt(e,t,n,r,o,i,s=!1){if(!n)return!1;let a=ti(he(e,t,o,i)),l=a.replace(/(\/\.?\*+)+$/,"");if(l!==a&&l!==""){if(ya(l,n))return!0;let c=s||a.slice(l.length).includes("/."),u=(m)=>c?Qo(m,l):Kb(m,l);if(n.markerFiles.some(u))return!0;return r&&Ca(n).some(u)}if(ya(a,n))return!0;return r&&Ca(n).some((c)=>Qo(c,a))}function Kb(e,t){let n=ct.relative(t,e);if(n===""||n.startsWith("..")||ct.isAbsolute(n))return!1;return!n.split(/[\\/]/)[0]?.startsWith(".")}function qb(e,t,n,r,o){return Qt(e,t,n,!0,r,o)}function Yb(e,t,n,r,o){if(!n)return!1;return ya(ti(he(e,t,r,o)),n)}function wd(e,t,n,r,o,i){let s=ti(he(e,t,r,o));return i.includes(s)||Td(s,n)}function Pd(e,t,n,r,o){if(!n)return!1;return n.hooksDirectories.some((i)=>e.some((s)=>Qo(i,ti(he(s,t,r,o)))))}function ya(e,t){return t.entries.includes(e)||t.directories.includes(e)||Td(e,t)}function Td(e,t){return t.hooksDirectories.some((n)=>Qo(e,n))}var Zb=50000;function Id(e,t){let n=[...new Set(Ca(e))];if(n.some((o)=>t(ct.basename(o))))return!0;let r=0;while(n.length>0){let o=n.pop()??"",i=Xb(o);if(!i)return!0;if(r+=i.length,r>Zb)return!0;if(i.some((s)=>t(s.name)))return!0;n.push(...i.filter((s)=>s.isDirectory()).map((s)=>ct.join(o,s.name)))}return!1}function Xb(e){try{let t=ei.lstatSync(e,{throwIfNoEntry:!1});if(!t)return[];if(!t.isDirectory())return t.isSymbolicLink()?null:[];return ei.readdirSync(e,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function Ca(e){return[...e.entries,...e.directories,...e.hooksDirectories]}function Qo(e,t){let n=ct.relative(t,e);return n===""||!/^\.\.(?:[\\/]|$)/.test(n)&&!ct.isAbsolute(n)}function ti(e){return process.platform==="win32"?e.toLowerCase():e}function Jb(e,t,n,r,o){if(Rr(e))return null;let i=Gt([...e],r);if(I(i[0]??"").toLowerCase()!=="mv")return null;let s=Jo(i.slice(1)),a=s.sources.find((l)=>qb(Ae(l,t.variables),t.cwd,n,r,o));if(a)return a;return s.destination&&Yb(Ae(s.destination,t.variables),t.cwd,n,r,o)?s.destination:null}var Z=require("node:path");var Ge=require("node:path"),Qb=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],eS=`
|
|
30
|
-
`;function Ar(e,t){if(zt(e,t))return!0;if(!e.has("TMPDIR"))return!1;return!ba(e.get("TMPDIR")??"",t)}function en(e,t){if(e.has("TMPDIR"))return ba(e.get("TMPDIR")??"",t);let n=Sa(e,t);if(n===void 0)return!0;return ba(n,t)}function Sa(e,t){return Md(e,t,"TMPDIR")}function ba(e,t){if(!e)return!1;if(nS(e))return!1;return kn(e,t)}function zt(e,t){let n=Md(e,t,"IFS");return n!==void 0&&n!==""&&n!==eS}function kn(e,t){let n=ni(e,t.paths);if(n===null)return!1;return Od(t).some((r)=>ii(n,r))}function oi(e,t){let n=ni(e,t.paths);if(n===null)return!1;return Od(t).some((r)=>ri(r)===ri(n))}var kd=new WeakMap;function Od(e){let t=kd.get(e);if(t)return t;let n=tS(e);return kd.set(e,n),n}function tS(e){let t=Qb.map((r)=>ni(r,e.paths)??Ge.normalize(r)),n=ni(e.tmpdir,e.paths);if(!n)return t;if(process.platform==="win32")return[...t,n];if(process.platform==="darwin"&&rS(n))return[...t,n];return t}function nS(e){return/[\s$`*?[]/.test(e)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(e)||/[+@!]\([^)]*\)/.test(e)}function Md(e,t,n){return e.has(n)?e.get(n):t.env.get(n)}function rS(e){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(e)}function ni(e,t){try{let n=Ge.normalize(e);if(!Ge.isAbsolute(n))return n;let r=Ge.parse(n).root,o=n.slice(r.length).split(/[\\/]+/).filter(Boolean),i=r;for(let s=0;s<o.length;s++){let a=Ge.join(i,o[s]??"");if(t.entryKind(a)==="missing")return Ge.join(a,...o.slice(s+1));let l=t.realpath(a);if(l===null)return null;i=l}return i}catch{return null}}function ii(e,t){let n=ri(e),r=ri(t);if(n===r)return!0;let o=r.endsWith(Ge.sep)?r:`${r}${Ge.sep}`;return n.startsWith(o)}function ri(e){return process.platform==="win32"?e.toLowerCase():e}var oS=process.platform==="win32",Dd=64,iS=16384;function Pr(e,t,n,r){if(e.kind==="temp_target")return null;let o=r[e.kind];if(e.kind==="dynamic_target"&&!fe(n,o.id,t.strict))return null;if(e.kind==="within_anchored_cwd"&&!fe(n,o.id,t.paranoid))return null;return S(o.id,o.reason)}function Tr(e){let t=Ou(e,Dd,Dd,iS);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:sS(e)}}function sS(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)=>aS(e.raw,n.span.start-e.span.start))}function aS(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 tn(e){let t=e.environment.home,n=e.environment.paths,r=e.budget??de();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:fS(e.allowPaths,t,n,r),protectedGitMetadata:e.protectedGitMetadata,budget:r}}function et(e,t,n={}){let r=n.targetIsLiteral??!1;if(!r&&t.tmpdirWordSplittingUnsafe&&!n.tmpdirWordSplittingProtected&&gS(e))return{kind:"outside_anchored_cwd"};let o=!r&&Ld(e,t.posixShell);if(Tt(e))return{kind:"outside_anchored_cwd"};if(Ea(e,r))return{kind:"root_or_home_target"};if(cS(e,t,r))return{kind:"root_or_home_target"};if(t.resolvedCwd&&Qt(e,t.resolvedCwd,t.protectedGitMetadata,!0,t.environment,t.budget,!t.posixShell))return{kind:"git_metadata_target"};if(uS(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(pS(e,t,r))return{kind:"temp_target"};let i=t.anchoredCwd;if(i){if(!n.skipHomeCwd&&bS(i,t.environment.home,t.environment.paths,t.budget))return{kind:"home_cwd_target"};if(!n.skipCwdSelf&&[t.resolvedCwd??i,i].some((s)=>SS(e,t.resolvedCwd??i,t.environment.paths,t.budget,s)))return{kind:"cwd_self_target"};if(vS(e,i,t.resolvedCwd??i,o,r,t.environment.paths,t.budget))return{kind:"within_anchored_cwd"}}if(lS(e,t,o))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function lS(e,t,n){let r=e.trim();if(n||!t.resolvedCwd||!t.anchoredCwd||!r)return!1;if(Z.isAbsolute(r)||r.startsWith("~"))return!1;if(xa(r))return!1;if(Wd(t.resolvedCwd,t.anchoredCwd,t.environment.paths,t.budget))return!1;return kn(Z.resolve(t.resolvedCwd,r),t.environment)}function Nd(e,t,n={}){let{containmentTarget:r,...o}=n;if(et(e,t,o).kind!=="temp_target")return!1;let i=e.trim();if(mS(i))return!1;if(oi(i,t.environment))return!1;return![t.anchoredCwd,t.resolvedCwd].some((s)=>Wd(r??i,s,t.environment.paths,t.budget))}function Ea(e,t=!1){let n=e.trim(),r=Z.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 cS(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=Z.isAbsolute(o)?o:t.resolvedCwd?Z.resolve(t.resolvedCwd,o):null;if(!i)return!1;let s=Te(N(i,t.environment.paths,t.budget));if(s===Z.parse(s).root)return!0;return s===Te(N(t.environment.home,t.environment.paths,t.budget))}catch{return!1}}function Te(e){let t=Z.normalize(e);if(oS){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 uS(e,t,n,r,o,i,s,a){let l=e.trim();if(xa(l))return!1;if(!r&&kn(l,a))return!0;return(t||i&&s)&&n&&!o&&dS(l,n)}function dS(e,t){return["$TMPDIR","${TMPDIR}"].some((n)=>{if(e===n)return!0;if(!e.startsWith(`${n}/`))return!1;return!Ld(e.slice(n.length+1),t)})}function mS(e){let t=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(e);if(!t)return!1;return Z.posix.normalize(`/${t[1]??""}`)==="/"}function xa(e){return e.split(/[\\/]+/).includes("..")}function fS(e,t,n,r){if(!e?.length)return[];return e.flatMap((o)=>{let i=sr(o.trim(),t);if(!Z.isAbsolute(i))return[];try{let s=N(i,n,r);if(ar(s,N(t,n,r)))return[];return[Te(s)]}catch{return[]}})}function pS(e,t,n){if(t.allowRoots.length===0)return!1;let r=e.trim();if(xa(r))return!1;let o=n?r:sr(r,t.environment.home),i=t.resolvedCwd??t.anchoredCwd,s=Z.isAbsolute(o)?o:i?Z.resolve(i,o):null;if(!s)return!1;try{let a=Te(N(s,t.environment.paths,t.budget));return t.allowRoots.some((l)=>a===l||a.startsWith(l.endsWith(Z.sep)?l:`${l}${Z.sep}`))}catch{return!1}}function gS(e){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(e)}function Ld(e,t=!1){return e.includes("$")||e.includes("`")||hS(e)||t&&yS(e)}function hS(e){let t=!1;for(let n of e){if(t){t=!1;continue}if(n==="\\"){t=!0;continue}if(n==="*"||n==="?"||n==="[")return!0}return!1}function yS(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(t){t=!1;continue}if(r==="\\"){t=!0;continue}if(r==="{"&&CS(e,n)||(r==="+"||r==="@"||r==="!")&&e[n+1]==="(")return!0}return!1}function CS(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 bS(e,t,n,r){try{return Te(N(e,n,r))===Te(N(t,n,r))}catch{try{return Te(e)===Te(t)}catch{return!1}}}function SS(e,t,n,r,o=t){if(o===t&&(e==="."||e==="./"||e===".\\"))return!0;try{return Te(N(Z.resolve(t,e),n,r))===Te(N(o,n,r))}catch{try{return Te(Z.resolve(t,e))===Te(o)}catch{return!1}}}function vS(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 va(e,t,i,s)}catch{return!1}if(e.startsWith("./")||e.startsWith(".\\")||!e.includes("/")&&!e.includes("\\"))try{return va(Z.resolve(a,e),t,i,s)}catch{return!1}if(e.startsWith("../"))return!1;try{return va(Z.resolve(a,e),t,i,s)}catch{return!1}}function va(e,t,n,r){try{return Gd(N(e,n,r),N(t,n,r))}catch{return!1}}function Wd(e,t,n,r){if(!t)return!1;try{return Gd(N(t,n,r),N(e,n,r))}catch{return!0}}function Gd(e,t){let n=Te(e),r=Te(t);return n.startsWith(`${r}${Z.sep}`)||n===r}var ES=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),Fd="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",xS="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.",Hd="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",RS="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",_S="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",wS={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:Hd},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:Ue},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:zd},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:RS},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:Fd},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:xS},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:Fd}};function Bd(e,t,n,r=tn({...n,allowPaths:n.policy?.destructiveCommandAllowPaths})){return AS(e.words.map((o)=>({kind:"word",text:o.text,dynamic:o.provenance!=="literal"})),t,r,n.policy)}function AS(e,t,n,r){let o=e.filter((l)=>l.kind==="word"),i=TS(o),s=o[i];if(!s||!ES.has(GS(s.text)))return null;let a=PS(o.slice(i+1));if(a.whatIfProtected)return null;if(fe(r,"powershell.remove-item-pipeline-dynamic-target",n.strict)&&t&&(a.targets.length===0||a.recursive))return S("powershell.remove-item-pipeline-dynamic-target",_S);for(let l of a.targets)if(!Tt(l.text)&&Ea(_a(l.text)))return S(a.recursive&&a.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Hd);for(let l of a.targets)if(n.resolvedCwd&&Qt(_a(l.text),n.resolvedCwd,n.protectedGitMetadata,a.recursive,n.environment,n.budget,!0))return S("powershell.remove-item-git-metadata",Ue);if(!a.recursive||!a.force)return null;if(fe(r,"powershell.remove-item-recursive-force-dynamic-target",n.strict)&&(a.hasDynamicTarget||a.targets.length===0))return S("powershell.remove-item-recursive-force-dynamic-target",zd);for(let l of a.targets){let c=Pr(et(_a(l.text),n),n,r,wS);if(c)return c}return null}function PS(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(IS(l))continue;if(s){t.push(Ra(l)),i=i||l.dynamic;continue}if(l.text==="--"){s=!0;continue}let c=OS(l.text);if(!c){t.push(Ra(l)),i=i||l.dynamic;continue}if(MS(c.name)){let u=c.value?kS(c.value,l):e[++a];if(u?.kind==="word"){t.push(Ra(u)),i=i||u.dynamic;continue}i=!0;continue}if(DS(c.name)){n=!0;continue}if(NS(c.name)){r=!0;continue}if(LS(c.name))o=WS(c.value)}return{targets:t,recursive:n,force:r,whatIfProtected:o,hasDynamicTarget:i}}function TS(e){let t=e[0];if(t?.kind==="word"&&t.text==="&"||t?.text===".")return e.length>1?1:0;return 0}function Ra(e){return{text:e.kind==="word"?e.text:"",dynamic:e.kind==="word"&&e.dynamic}}function IS(e){return e.kind==="word"&&e.text===","}function _a(e){let t=e.replace(/\\/g,"/"),n=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(t);return n?`$HOME${t.slice(n[0].length)}`:t}function kS(e,t){return{kind:"word",text:e,dynamic:t.kind==="word"&&(t.dynamic||e.includes("$"))}}function OS(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 MS(e){return"path".startsWith(e)||"literalpath".startsWith(e)}function DS(e){return"recurse".startsWith(e)}function NS(e){return e.length>=2&&"force".startsWith(e)}function LS(e){return e==="wi"||"whatif".startsWith(e)}function WS(e){if(e===void 0||e==="")return!0;let t=e.toLowerCase();return t==="$true"||t==="true"}function GS(e){return e.toLowerCase()}var On="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",si="Unsupported heredoc syntax",Ir="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.",$d="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var FS=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"]),HS=new Set(["-o","--output","--query","--subscription"]),BS=new Set;function Ud(e){if(e==="aws")return FS;if(e==="gcloud")return zS;if(e==="az")return HS;return BS}var $S=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),US=new Set;function jd(e){if(e==="git")return Me;if(e==="docker")return $S;return US}function Et(e,t){if(e.length===0||t.length===0)return null;let n=O(e[0]??""),r=_e(e);for(let o of t){if(!KS(n,o.command))continue;if(o.match){if(jS(n,e,o.match))return Vd(o);continue}if(!qS(n,e,o.subcommand))continue;if(ZS(e,new Set(o.block_args),r))return Vd(o)}return null}function Vd(e){return{id:`custom.${e.name}`,reason:`[${e.name}] ${e.reason}`,intent:e.intent??"manual_only"}}function jS(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 VS(r,n.command_path,Ud(e))}function VS(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 KS(e,t){return e===O(t)}function qS(e,t,n){if(!n)return!0;return Kd(t,1,n,jd(e))}function Kd(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("=")&&YS(e,i,n,r))return!0;continue}return s===n}return!1}function YS(e,t,n,r){let o=e[t+1];if(!o||o.startsWith("-"))return!1;return Kd(e,t+2,n,r)}function ZS(e,t,n){return e.some((r)=>t.has(r))||[...n].some((r)=>t.has(r))}var XS=new Set(["-e","--source"]),JS=new Set(["-F","-v","--assign","--field-separator"]),qd=new Set(["-f","--file"]),QS=new Set(["print","printf","return"]),Yd=[{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"}],ev="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 Zd(e,t,n){let r=!1;for(let o of tv(e)){let i=nv(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?S("awk.system-dynamic",ev):null}function Aa(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&&XS.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&&(JS.has(a)||qd.has(a))){let l=e[s+1];if(i&&=l!==void 0,qd.has(a)){if(r=!0,l!==void 0)t.push({tokenIndex:s+1,kind:"program-file",value:l})}s++;continue}if(o&&(a.startsWith("-F")||a.startsWith("-v")&&a.slice(2).includes("=")))continue;if(o&&a.startsWith("-f")&&a.length>2){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(2)});continue}if(o&&(a.startsWith("--assign=")||a.startsWith("--field-separator=")))continue;if(o&&a.startsWith("--file=")){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(7)});continue}if(o&&a.startsWith("-")&&a!=="-")continue;if(!n&&!r)t.push({tokenIndex:s,kind:"main-program",value:a});return{sources:t,optionsOpen:!1}}return{sources:i?t:[],optionsOpen:o&&i}}function Or(e){return Aa(e).sources}function tv(e){return Or(e).filter((t)=>t.kind!=="program-file").map((t)=>t.value)}function nv(e,t){We(t,e);let n=e.includes("system")?Pa(e,t):null,r=rv(e,t);if(!n&&!r)return null;return{dynamic:!!n?.dynamic||!!r?.dynamic,commands:[...n?.commands??[],...r?.commands??[]]}}function Pa(e,t){We(t,e);let n=[],r=!1,o=!1,i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){i=li(e,i,s)?.endIndex??i+1;continue}if(s==="#"){i=Xd(e,i+1);continue}if(s==="/"&&Jd(e,i)){i=Qd(e,i+1)??i+1;continue}if(!e.startsWith("system",i)){i++;continue}let a=i;if(i+=6,kr(e[a-1])||kr(e[i]))continue;let l=ai(e,i);if(e[l]!=="(")continue;l=ai(e,l+1);let c=e[l];if(c!=='"'&&c!=="'"){r=!0,o=!0;continue}let u=li(e,l,c);if(!u){r=!0,o=!0;continue}if(l=ai(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 rv(e,t){We(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=li(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=Xd(e,i+1),s=i,a=null,l=null,c=i;continue}if(u==="/"&&Jd(e,i)){let f=Qd(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&&(
|
|
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 Jd(e,t){let n=cv(e,t);if(n===-1)return!0;if("{([,;!~=".includes(e[n]??""))return!0;let r=n;while(kr(e[r-1]))r--;return QS.has(e.slice(r,n+1))}function cv(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function Qd(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 uv=new Set(["sudo","env","command","builtin"]);function ci(e,t){let n=e[0];if(!n||!t.transparentWrappers.includes(I(n)))return null;let r=I(n),o=e[1]==="--"?2:1,i=dv(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 dv(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=I(a)!==n&&mv(a,r);if(l)i.push(s);if(!l&&uo.has(O(a)))break;if(o)break}return i}function mv(e,t){let n=I(e),r=O(e);return r==="git"||n==="busybox"||nn(e)||hs.has(n)||t.transparentWrappers.includes(n)||ee.has(r)||e==="$SHELL"||qe(r)||He.has(r)||t.rules.some((o)=>o.command===n)}function nn(e){return uv.has(e.toLowerCase())}function rn(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 tt(e,t){let n=t.policy??{rules:[],transparentWrappers:[]};return ui([...e],t.environment,t.cwd,t.cwd,new Map,new Map(t.envAssignments??[]),n,{iterations:0},!1)}function*ui(e,t,n,r,o,i,s,a,l){let c=Ko(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=Vo(c.envSplitValues,u);if(!f)throw new D("derivedCommandShape");Ta(a),yield*ui(f,t,m,r,o,i,s,a,l);return}if(nn(u[0]??""))throw new D("wrapperPeelIterations");let d=ci(u,s);if(d){for(let f of[d.childIndex,...d.alternativeChildIndices])Ta(a),yield*ui(f===d.childIndex?d.tokens:u.slice(f),t,m,r,new Map(o),new Map(i),s,a,!0);return}if(pv(u)){Ta(a),yield*ui(u.slice(1),t,m,r,o,i,s,a,l);return}yield fv(u,m,r,o,i,l)}function fv(e,t,n,r,o,i){return{tokens:e,cwd:t===null?void 0:t??n,wrapperCwd:t,wrapperEnvAssignments:r,envAssignments:o,head:I(e[0]??"").toLowerCase(),wrappedByTransparent:i}}function Ta(e){if(e.iterations>=X.wrapperPeelIterations.cap)throw new D("wrapperPeelIterations");e.iterations++}function pv(e){return I(e[0]??"").toLowerCase()==="busybox"&&e.length>1}function Ia(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 nt(e){let t=!1,n=!1;for(let r of e){if(r==="--")break;if(r==="-r"||r==="-R"||ka(r,"recursive")){t=!0;continue}if(r==="-f"||ka(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 di(e){let t=e.indexOf("--");return e.slice(1,t===-1?void 0:t).some((n)=>ka(n,"recursive")||/^-[A-Za-z]+$/.test(n)&&/[rR]/.test(n.slice(1)))}function ka(e,t){return e.length>2&&e.startsWith("--")&&t.startsWith(e.slice(2))}var gv=["--init-file","--rcfile"],hv=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function rt(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n)continue;if(n==="-c")return em(e,t,!0);if(n.startsWith("-")&&n.includes("c")&&!n.startsWith("--")){let r=em(e,t,!1);if(r!==null)return r}}return null}function xt(e){let t=I(e[0]??"").toLowerCase();if(t==="zsh"||t==="ksh")return De(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 em(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 tm(e){let t=I(e[0]??"").toLowerCase(),n=yv(e,t),r=hv.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 yv(e,t){let n=De(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?gv.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"&&ps.has(m)&&!l.includes("="))a++;continue}if(t==="bash")s=!1;let c=gs(t,l,e[a+1],"startup");if(c.interactive)i=l[0]==="-";a+=c.followingValues}return{argvSource:o.at(-1)??null,interactive:i}}var Cv="find -delete permanently removes files. Use -print first to preview.",bv="find -exec rm -rf is dangerous. Use explicit file list instead.",Sv=new Set(["-exec","-execdir","-ok","-okdir"]),vv=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 nm(e,t){let n=e.map(w),r=Ev(e,n,t);if(r)return r;if(mi(n,1)&&!Pv(e,n,t)){let s=P(S("find.delete",Cv),t.policy);if(s)return s}let o=t.budget??de(),i=0;while(i<n.length){let s=n[i],a=Rt(s??"");if(a>0){i+=a+1;continue}if(!ut(s)){i++;continue}o.charge("derivedTokens",n.length-i-1);let l=Mn(n,i);i=l.nextIndex;let c=Iv(l.tokens,t.environment);if(c){let f=P(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:P(m,t.policy);if(d)return d}return null}function Ev(e,t,n){if(!mi(t,1)&&!Oa(t,n.environment))return null;let o=Mr(e)??J(["."]),i=tn({...n,allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let s of o){let a=Tr(s);for(let l of a.expandedTargets??[w(s)]){let c=et(l,i,{targetIsLiteral:a.expandedTargets!==void 0||a.targetIsLiteral,tmpdirWordSplittingProtected:a.tmpdirWordSplittingProtected});if(c.kind==="root_or_home_target")return S("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"&&!xv(e,i.protectedGitMetadata,n.environment))return S("find.delete-git-metadata",Ue)}}if(Av(t)&&i.resolvedCwd&&Pd(o.map(w),i.resolvedCwd,i.protectedGitMetadata,i.environment,i.budget))return S("find.delete-git-metadata",Ue);return null}function xv(e,t,n){if(!t)return!1;let r=e.map(w),o=[],i=!1,s=Mr(e)?.at(-1),a=s?e.indexOf(s)+1:1;while(a<r.length){let l=r[a]??"";if(ut(l)){let c=Mn(r,a),u=Gt([...c.tokens],n);if(di(u))return!1;if(ee.has(I(u[0]??"").toLowerCase()))return!1;if(c.tokens.some((d)=>d!=="{}"&&d.includes("{}")))return!1;if((l==="-execdir"||l==="-okdir")&&u.slice(1).some((d)=>d!=="{}"&&!d.startsWith("-")))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(_v(c.text,l==="-iname"));a+=2;continue}if(!Rv.has(l))return!1;a+=1+Rt(l)}return o.length>0&&!Id(t,(l)=>o.every((c)=>c.test(l)))}var Rv=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function _v(e,t){let n=e.replace(/[*?]|[.+^${}()|\]/]/g,(r)=>r==="*"?".*":r==="?"?".":`\\${r}`);return new RegExp(`^${n}$`,t?"isu":"su")}var wv=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function Oa(e,t){let n=0;while(n<e.length){if(!ut(e[n])){n++;continue}let r=Mn(e,n),o=Gt([...r.tokens],t),i=I(o[0]??"").toLowerCase();if((i==="rm"||i==="rmdir"||ee.has(i)&&wv.test((rt(o)??"").replace(/["'\\]/g,"")))&&o.some((a)=>a.includes("{}")))return!0;n=r.nextIndex}return!1}function Av(e){return e.some((t,n)=>{if(!["-name","-iname"].includes(t))return!1;return e[n+1]?.toLowerCase()==="hooks"})}function Pv(e,t,n){if(t.includes("-L")||t.includes("-f")||t.includes("-follow"))return!1;let r=Mr(e);if(!r)return!1;let o=n.envAssignments??new Map,i=Sa(o,n.environment),s=n.trustedTmpdirValue??en(o,n.environment),a=n.allowTmpdirVar??!Ar(o,n.environment),l=tn({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??zt(o,n.environment),trustedTmpdirValue:s,budget:n.budget});return r.every((c)=>{let u=Tr(c);if(u.unsafeBraceExpansion)return!1;return(u.expandedTargets??[w(c)]).every((m)=>Nd(m,l,{containmentTarget:Tv(m,i),targetIsLiteral:u.expandedTargets!==void 0||u.targetIsLiteral,tmpdirWordSplittingProtected:u.tmpdirWordSplittingProtected}))})}function Tv(e,t){if(!t)return e;return e.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>t)}function Mr(e){let t=(o)=>{let i=e[o];return i?w(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 Iv(e,t){let n=Wt([...e],t);if(n.length===0)return null;let r=I(n[0]??"");if(r==="busybox"&&n.length>1)n=n.slice(1),r=I(n[0]??"");if(r==="rm"&&nt(n))return S("find.exec-rm-recursive-force",bv);return null}function Mn(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 mi(e,t){let n=t;while(n<e.length){let r=e[n];if(!r){n++;continue}if(ut(r)){n=Mn(e,n).nextIndex;continue}let o=Rt(r);if(o>0){n+=o+1;continue}if(r==="-delete")return!0;n++}return!1}function Rt(e){return vv.get(e)??(/^-newer[A-Za-z]{2}$/.test(e)?1:0)}function ut(e){return e!==void 0&&Sv.has(e)}var _m=require("node:path");function Dr(e){let t=Ye(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 kv=5,Ma="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 ge(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 om(e,t,n){let r=fi(e,t,n),o=Ov(r.entries);if(o.size===0)return{blockedReason:r.blockedReason,expanded:!1,tokens:e};let i=e,s=!1;for(let a=0;a<kv;a++){let{subcommand:l,rest:c}=Fe(i),u=l?.toLowerCase();if(!u||!o.has(u))return{blockedReason:r.blockedReason,expanded:s,tokens:i};let m=o.get(u),d=Wv(m);if(d===null||d.length===0)return{blockedReason:Ma,expanded:!0,tokens:i};i=["git",...d,...c],s=!0}return{blockedReason:Ma,expanded:!0,tokens:i}}function im(e,t,n){return fi(e,t,n).entries.some((r)=>r.key.toLowerCase()==="core.sshcommand")}function Fe(e){if(e.length===0)return{subcommand:null,rest:[]};let t=e[0];if((t?I(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+=Me.has(o)?2:1}return{subcommand:null,rest:[]}}function Ov(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 fi(e,t,n){if(e.length===0)return{blockedReason:null,entries:[]};let r=e[0];if((r?I(r).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let i=Dv(t,n);return{blockedReason:i.blockedReason,entries:[...i.entries,...Mv(e,t,n)]}}function Mv(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=Da(e[o+1]);if(s)r.push(s);o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=Da(i.slice(2));if(s)r.push(s);o++;continue}if(i==="--config-env"){let s=rm(e[o+1],t,n);if(s)r.push(s);o+=2;continue}if(i.startsWith("--config-env=")){let s=rm(i.slice(13),t,n);if(s)r.push(s);o++;continue}if(Me.has(i)){o+=2;continue}o++}return r}function Dv(e,t){let n=Nv(e,t),r=Lv(e,t);return{blockedReason:n===null||r===null?Ma:null,entries:[...n??[],...r??[]]}}function Nv(e,t){let n=St("GIT_CONFIG_PARAMETERS",e,t);if(n===void 0)return[];let r=[],o=Dr(n);if(!o)return null;for(let i of o){let s=Da(i);if(!s)return null;r.push(s)}return r}function Lv(e,t){let n=sd(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=St(`GIT_CONFIG_KEY_${o}`,e,t)?.trim(),s=St(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i||s===void 0)return null;r.push({key:i,value:s})}return r}function Da(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 rm(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;return{key:e.slice(0,r).trim(),value:St(e.slice(r+1),t,n)}}function Wv(e){let t=e?.trimStart();if(!t||t.startsWith("!"))return null;return Dr(t)}var Gv="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",Fv="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.",Hv="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",Bv="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",$v="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",Uv="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",jv="git switch --force discards uncommitted changes. Use 'git stash' first.",Vv="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",Kv="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",qv="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",Yv="git reset --merge can lose uncommitted changes. Use 'git stash' first.",Zv="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",Xv="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.",Jv="git push --force destroys remote history. Use --force-with-lease for safer force push.",Qv="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",eE="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",tE="git branch -D force-deletes without merge check. Use -d for safe delete.",nE="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",rE="git merge --abort discards merge conflict resolutions. Use 'git status' first.",oE="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",iE="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",sE="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",aE="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",lE="git worktree remove --force can delete uncommitted changes. Remove --force flag.",cE=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),uE=new Set(["--recurse-submodules","--track","-t"]),Na=new Set(["-b","-B","-U"]),La=new Set(["-c","-C"]),dE=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function M(e,t){let n=e.split("=",1)[0]??e;return n.length>=4&&t.startsWith(n)&&n.startsWith("--")&&n.slice(2).length>=2}var Dn=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function am(e,t){let{subcommand:n,rest:r}=Fe(e);if(!n)return null;switch(n.toLowerCase()){case"checkout":return Ht(mE(r,t));case"switch":return Ht(pE(r));case"restore":return Ht(hE(r));case"reset":return CE(r);case"clean":return Ht(SE(r));case"rm":return Ht(vE(r));case"push":return on(EE(r));case"branch":return on(_E(r));case"stash":return on(IE(r));case"worktree":return on(kE(r));case"rebase":return Ht(wE(r));case"merge":return Ht(AE(r));case"tag":return on(PE(r));case"reflog":return on(TE(r));default:return null}}function Ht(e){return e?{...e,localDiscard:!0}:null}function on(e){return e?{...e,localDiscard:!1}:null}function mE(e,t){let{index:n,before:r}=ge(e),o=_e(r,{shortOptsWithValue:Na});if(r.some((a)=>M(a,"--force"))||o.has("-f"))return S("git.checkout-force",zv);for(let a of e){if(a==="-b"||a==="-B"||a==="--orphan")return null;if(M(a,"--pathspec-from-file"))return S("git.checkout-pathspec-from-file",Bv)}if(n!==-1){if(r.some((l)=>!l.startsWith("-")))return S("git.checkout-ref-path",Hv);return S("git.checkout-double-dash",Gv)}let i=gE(e);if(i.length>=2)return S("git.checkout-ambiguous",$v);let s=i[0];if(s===void 0||o.has("-d")||o.has("-t")||e.some((a)=>M(a,"--detach")||M(a,"--track")))return null;if(fE(s)||t(s))return S("git.checkout-double-dash",Fv);return null}function fE(e){return e==="."||e===".."||/^\.\.?[/\\]/.test(e)||/^([/\\]|[A-Za-z]:[/\\])/.test(e)||e.endsWith("/")||e.startsWith(":")||/[*?[]/.test(e)}function pE(e){let{before:t}=ge(e);if(t.some((r)=>M(r,"--discard-changes")))return S("git.switch-discard-changes",Uv);let n=_e(t,{shortOptsWithValue:La});if(t.some((r)=>M(r,"--force"))||n.has("-f"))return S("git.switch-force",jv);return null}function gE(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(cE.has(r)){n+=2;continue}if(uE.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 hE(e){let t=yE(e);if(t.isTerminal||!t.hasPathspec&&!t.hasPatch||!t.hasWorktree)return null;return t.hasExplicitLocation?S("git.restore-worktree",Kv):S("git.restore-unstaged",Vv)}function yE(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(dE.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 CE(e){let t=null;for(let n of e){if(M(n,"--hard")){t=S("git.reset-hard",qv);break}if(M(n,"--merge")){t=S("git.reset-merge",Yv);break}}if(!t)return null;return bE(e)?on(t):Ht(t)}function bE(e){for(let t of e){if(t==="--")return!1;if(!t.startsWith("-"))return!0}return!1}function SE(e){for(let n of e)if(n==="-n"||M(n,"--dry-run"))return null;let t=_e(e.filter((n)=>n!=="--"));if(e.some((n)=>M(n,"--force"))||t.has("-f"))return S("git.clean-force",Zv);return null}function vE(e){let t=!1,n=!1,r=!1;for(let o of ge(e).before){if(M(o,"--no-force")){t=!1;continue}if(M(o,"--force")){t=!0;continue}if(M(o,"--no-cached")){n=!1;continue}if(M(o,"--cached")){n=!0;continue}if(M(o,"--no-dry-run")){r=!1;continue}if(M(o,"--dry-run")){r=!0;continue}let i=_e([o]);t||=i.has("-f"),r||=i.has("-n")}return t&&!n&&!r?S("git.rm-force",Xv):null}function EE(e){let{before:t,after:n}=ge(e),r=_e(t);if(t.some((s)=>M(s,"--mirror")))return S("git.push-mirror",eE);if(t.some((s)=>M(s,"--force"))||r.has("-f")||sm(t,n).some(xE))return S("git.push-force",Jv);if(t.some((s)=>M(s,"--delete"))||r.has("-d")||sm(t,n).some(RE))return S("git.push-delete",Qv);return null}function sm(e,t){return[...e.filter((n)=>n!==""&&!n.startsWith("-")),...t]}function xE(e){return e.startsWith("+")||e.includes(":+")}function RE(e){return e.length>1&&e.startsWith(":")}function _E(e){let{before:t}=ge(e),n=_e(t),r=n.has("-D")||n.has("-d")||t.some((i)=>M(i,"--delete")),o=n.has("-D")||n.has("-f")||t.some((i)=>M(i,"--force"));if(r&&o)return S("git.branch-force-delete",tE);return null}function wE(e){let{before:t}=ge(e);return t.some((n)=>M(n,"--abort"))?S("git.rebase-abort",nE):null}function AE(e){let{before:t}=ge(e);return t.some((n)=>M(n,"--abort"))?S("git.merge-abort",rE):null}function PE(e){let{before:t}=ge(e);return _e(t).has("-d")||t.some((r)=>M(r,"--delete"))?S("git.tag-delete",oE):null}function TE(e){return e[0]==="delete"?S("git.reflog-delete",iE):null}function IE(e){for(let t of e){if(t==="drop")return S("git.stash-drop",sE);if(t==="clear")return S("git.stash-clear",aE)}return null}function kE(e){let{before:t}=ge(e);if(!t.includes("remove"))return null;let r=_e(t);if(t.some((o)=>M(o,"--force"))||r.has("-f"))return S("git.worktree-remove-force",lE);return null}var _t=require("node:path");var Ga="TMPDIR",Fa="IFS",cm=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,um=/^[A-Za-z_][A-Za-z0-9_]*$/,dm=new Set(["export","typeset","declare","readonly"]),OE=new Set(["builtin","command","time"]),mm=new Set(["do","then","else"]),ME=new Set(["do","then","case"]),lm=new Set(["done","fi","esac"]),DE=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function fm(e,t){return e.map((n)=>n.provenance==="variable"&&bm(n.text)?Nr(n.text,t.shellAssignments):w(n))}function Nr(e,t){return e.replace(DE,(n,r,o)=>t.get(r??o??"")??n)}function pm(e,t){return{env:e,effectiveEnvAssignments:GE(e,t),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function gm(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 za(e,t){let n=ym(e,t),r=e[0]??"";if(ME.has(r))t.bodyDepth+=1;if(r==="elif"||lm.has(r))t.bodyDepth=Math.max(0,t.bodyDepth-1);if(lm.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);Ha(t,a)});let o=n.commandIndex;if(o!==-1&&dm.has(e[o]??""))e.filter((a)=>um.test(a)&&Wa(a)).forEach((a)=>{FE(t,a)});let i=o===-1?-1:Cm(e,o);if(i===-1||e[i]!=="unset")return;let s=HE(e,i);if(s===null)return;e.slice(s).forEach((a)=>{if(mm.has(r)){t.shellAssignments.set(a,"");return}zE(t,a)})}function hm(e,t){let n=ym(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 ym(e,t){let n=mm.has(e[0]??"")?1:0,r=e.findIndex((a,l)=>l>=n&&!bm(a)),o=r!==-1&&dm.has(e[Cm(e,r)]??""),i=WE(t);return{assignments:e.flatMap((a,l)=>{let c=NE(a,i,t.env);if(!c)return[];if(r!==-1&&l>r&&!o&&!$o(c.name))return[];return i.set(c.name,c.value),[{...c,persists:r===-1||o}]}),commandIndex:r}}function Cm(e,t){let n=t;while(OE.has(e[n]??"")){n+=1;while(e[n]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(e[n]??""))return t;n+=1}}return n}function bm(e){return $e(e)!==null||cm.test(e)}function NE(e,t,n){return $e(e)??LE(e,t,n)}function LE(e,t,n){let r=Uo(e,n,t);if(r)return r;let o=e.match(cm)?.[1];if(!o)return null;let i=e.indexOf("=");return{name:o,value:`${t.has(o)?t.get(o):n.get(o)??""}${e.slice(i+1)}`}}function Wa(e){return e===Ga||e===Fa||da(e)}function WE(e){return new Map([...e.effectiveEnvAssignments??[],...e.shellAssignments])}function GE(e,t){let n=[Ga,Fa].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 Ha(e,t){let n=new Map(e.effectiveEnvAssignments??[]);n.set(t.name,t.value),e.effectiveEnvAssignments=n}function FE(e,t){Ha(e,{name:t,value:e.shellAssignments.get(t)??e.effectiveEnvAssignments?.get(t)??e.env.get(t)??""})}function zE(e,t){if(!Wa(t)&&!um.test(t))return;if(e.shellAssignments.set(t,""),$o(t)&&e.env.has(t)){let r=new Map(e.env);r.delete(t),e.env=r}if(!Wa(t)||t===Ga||t===Fa||Qn(t)){Ha(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 HE(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 vm=require("node:path");function pi(e,t){return ua.some((n)=>t?.has(n)||e.has(n))}function Nn(e,t,n){if(!t)return{gitCwd:null,hasExplicitGitContext:!1};let r=n.realpath(vm.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=Sm(o,l,n);if(!c)return{gitCwd:null,hasExplicitGitContext:i};o=c,s+=2;continue}if(a.startsWith("-C")&&a.length>2){let l=Sm(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+=Me.has(a)?2:1}return{gitCwd:o,hasExplicitGitContext:i}}function Sm(e,t,n){try{let r=Lt(e,t,n);return n.isDirectory(r)?r:null}catch{return null}}function Em(e,t,n){if(!t.localDiscard||!n.worktreeMode||pi(n.environment.env,n.envAssignments))return null;let r=Nn(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(Ba(e,n,o))return null;return{kind:"worktree",originalReason:t.reason,gitCwd:r.gitCwd}}function Ba(e,t,n){let{subcommand:r,rest:o}=Fe(e),i=r?.toLowerCase();if(t.dynamicArguments||BE(o)||KE(e,t.environment.env,t.envAssignments,n)||jE(o)||$E(i,o))return!0;return i==="clean"&&VE(o)>1}function BE(e){return e.some((t)=>/[$*?[]/.test(t))}function $E(e,t){if(e==="checkout"){let{before:n}=ge(t),r=_e(n,{shortOptsWithValue:Na}),o=n.some((s)=>M(s,"--force"))||r.has("-f"),i=r.has("-B")||n.some((s)=>s==="-B"||s.startsWith("-B"));return o&&i}if(e==="switch"){let{before:n}=ge(t),r=_e(n,{shortOptsWithValue:La}),o=n.some((s)=>M(s,"--force"))||n.some((s)=>M(s,"--discard-changes"))||r.has("-f"),i=n.some((s)=>s==="-C"||s.startsWith("-C")||UE(s))||r.has("-C");return o&&i}return!1}function UE(e){let t=e.split("=",1)[0]??e;return t==="--force-create"||t.length>=9&&"--force-create".startsWith(t)}function jE(e){return e.some((t)=>t.startsWith("--recurse-sub"))}function VE(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 KE(e,t,n,r){if(St("GIT_CONFIG_PARAMETERS",t,n)!==void 0)return!0;let o=fi(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)=>YE(a.key)))return!0;let s=i.filter((a)=>a.key==="submodule.recurse").at(-1);if(s)return s.value===void 0||qE(s.value);if(ld(n))return!0;return r.recursiveSubmodules}function qE(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function YE(e){return e==="include.path"||e.startsWith("includeif.")&&e.endsWith(".path")}function xm(e,t,n){let r=e.map(w),o=n.environment.paths,i=Nn(r,n.cwd,o),s=n.originalCwd?o.realpath(_t.resolve(n.originalCwd)):null;if(t.id.startsWith("git.push-")||s===null||i.gitCwd===null||i.hasExplicitGitContext||pi(n.environment.env,n.envAssignments))return null;let a=t.id==="git.worktree-remove-force"?XE(e,n.shellAssignments,o):Rm(i.gitCwd,o);if(a===null||t.id!=="git.worktree-remove-force"&&!ZE(a,r,t,n)||!kn(a,n.environment)||oi(a,n.environment)||ii(s,a)||ii(a,s))return null;return{kind:"temp-root",originalReason:t.reason,gitCwd:i.gitCwd}}function ZE(e,t,n,r){let o=r.environment.paths,i=_t.join(e,".git");if(o.entryKind(i)!=="present")return!1;if(o.isDirectory(i))return!0;let s=n.localDiscard?r.environment.worktreeFacts(e):null;return s!==null&&!Ba(t,r,s)}function XE(e,t,n){let r=Fe(e.map(w)).rest,{before:o,after:i}=ge(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?.provenance==="variable"&&l.parts.every((u)=>u.provenance!=="literal"||!/[$`]/.test(u.raw))?Nr(a,t??new Map):a;if(!_t.isAbsolute(c)||/[\s$`*?[]/.test(c)||n.entryKind(c)!=="present"||!n.isDirectory(c))return null;return n.realpath(c)}function Rm(e,t){if(t.entryKind(_t.join(e,".git"))!=="missing")return e;let n=_t.dirname(e);return n===e?null:Rm(n,t)}var JE="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.",QE=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function gi(e,t){return wm(e,t)}function wm(e,t,n){let r=e.map(w),o=om(r,t.environment.env,t.envAssignments),i=o.blockedReason?P(S("git.alias-config",o.blockedReason),t.policy):null;if(i)return i;let s=o.tokens;if((ad(t.envAssignments)||im(r,t.environment.env,t.envAssignments))&&ex(s))return S("git.ssh-env",JE);let a=am(s,(c)=>{let u=Nn(r,t.cwd,t.environment.paths).gitCwd;return u!==null&&t.environment.paths.entryKind(_m.resolve(u,c))!=="missing"});if(!a)return null;if(o.expanded||o.blockedReason)return a;let l=Em(r,a,t)??xm(e,a,t);if(!l)return a;return n?.(l),null}function Am(e,t){let n=null;return{match:wm(e,t,(o)=>{n=o}),relaxation:n}}function ex(e){let{subcommand:t,rest:n}=Fe(e),r=t?.toLowerCase();if(!r)return!1;if(QE.has(r))return!0;if(r==="archive")return ge(n).before.some((o)=>M(o,"--remote"));return r==="remote"&&tx(n)}function tx(e){return e.find((t)=>!nx(t))?.toLowerCase()==="update"}function nx(e){return e==="-v"||M(e,"--verbose")||M(e,"--no-verbose")}var of=require("node:path");function Pm(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 hi(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 Tm="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",rx="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.",ox="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",km="rm -rf targeting root or home directory is extremely dangerous and always blocked.",ix="rm -rf in home directory is dangerous. Change to a project directory first.",Im={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:km},git_metadata_target:{id:"rm.git-metadata",reason:Ue},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:ox},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:ix},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:Tm},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:rx},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:Tm}};function yi(e,t){let n=tn({...t,allowPaths:t.policy?.destructiveCommandAllowPaths,posixShell:!0}),r=e.map(w),o=nt(r),i=di(r),s=ax(e);for(let a of s){let l=Tr(a.word);if(o&&l.unsafeBraceExpansion){let c=P(Pr({kind:"outside_anchored_cwd"},n,t.policy,Im),t.policy);if(c)return c;continue}for(let c of l.expandedTargets??[a.text]){let u=Oe(c),m={targetIsLiteral:l.expandedTargets!==void 0||l.targetIsLiteral,tmpdirWordSplittingProtected:l.tmpdirWordSplittingProtected};if(!i&&n.resolvedCwd&&Qt(u,n.resolvedCwd,n.protectedGitMetadata,i,n.environment,n.budget))return S("rm.git-metadata",Ue);if(i&&!o){let d=et(u,n,m);if(d.kind==="root_or_home_target")return S("rm.recursive-force-root-or-home",km);if(d.kind==="git_metadata_target")return S("rm.git-metadata",Ue);continue}if(!o)continue;for(let d of sx(u,n,m)){let f=Pr(d,n,t.policy,Im),p=P(f,t.policy);if(p)return p}}}return null}function sx(e,t,n){let r=et(e,t,n);if(r.kind==="cwd_self_target")return[r,et(e,t,{...n,skipCwdSelf:!0})];if(r.kind!=="home_cwd_target")return[r];let o=et(e,t,{...n,skipHomeCwd:!0});if(o.kind!=="cwd_self_target")return[r,o];return[r,o,et(e,t,{...n,skipHomeCwd:!0,skipCwdSelf:!0})]}function ax(e){let t=[],n=!1;for(let r of e.slice(1)){let o=w(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 Bt={kind:"none"},sn={kind:"dynamic"},lx=new Set(["<","<<","<<-","<<<","<&","<>"]),Mm=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,cx=/^(?:[0-9]+|[@*])$/,ux=Dt.maxWords,Dm=Dt.maxInputLength;function Nm(e){if(!e||I(O(e.words[0]?.text??""))!=="printf")return;if(e.words.some((o)=>o.provenance!=="literal"))return;let t=e.words.slice(e.words[1]?.text==="--"?2:1),n=t[0]?.text;if(n===void 0)return"";let r=t.slice(1).map((o)=>o.text);if(n==="%s")return r.join("");if(n==="%s\\n"||n===`%s
|
|
22
|
+
`?d+2:d+1;s.push(ra(e,d,y)),d=y;continue}d++;continue}let g=Ju(e,d);if(g){m(),s.push(ra(e,d,d+g.length)),d+=g.length;continue}if(f==="{"){if(m(),o>=r.maxDepth)return a.push(Xu(r.maxDepth)),{nodes:s,issues:a,next:n,closed:!1,words:c,limited:!0};let y=aa(e,d+1,n,r,o+1,!0),S=y.closed?y.next-1:y.next,E=_e({kind:"program",dialect:"powershell",source:e.slice(d+1,S),span:{start:d+1,end:S},status:y.limited?"limited":y.issues.length>0?"partial":"complete",issues:y.issues,nodes:y.nodes});if(s.push(Object.freeze({kind:"group",style:"brace",span:Object.freeze({start:d,end:y.next}),body:E})),a.push(...y.issues),!y.closed)a.push({code:"unclosed-script-block",message:"PowerShell script block is not closed"});c+=y.words,u||=y.limited,d=y.next;continue}if(f==="}"){m(),s.push(ra(e,d,d+1)),d++;continue}if(f===">"||f==="<"){l.start=l.start===-1?d:l.start;let y=e[d+1]===f?d+2:d+1,S=y;while(/[ \t]/.test(e[S]??""))S++;let E=S<n?ju(e,S,n,r,o):void 0,C=E?.next??y;if(l.redirections.push(Object.freeze({kind:"redirection",operator:e.slice(d,y),span:Object.freeze({start:d,end:C}),...E?{target:E.word}:{}})),E)a.push(...E.issues),l.nested.push(...E.nested),c+=E.words,u||=E.limited;l.end=C,d=C;continue}if(f===","){l.start=l.start===-1?d:l.start,l.words.push(Zs({text:",",raw:",",span:{start:d,end:d+1},provenance:"literal",quoted:!1})),l.end=++d;continue}let h=ju(e,d,n,r,o);if(l.start=l.start===-1?d:l.start,l.end=h.next,l.words.push(h.word),a.push(...h.issues),l.nested.push(...h.nested),c+=1+h.words,u||=h.limited,c>r.maxWords)return a.push({code:"word-limit",message:`command exceeds ${r.maxWords} words`}),m(),{nodes:s,issues:a,next:h.next,closed:!1,words:c,limited:!0};d=h.next>d?h.next:d+1}return m(),{nodes:s,issues:a,next:d,closed:!i,words:c,limited:u}}function ju(e,t,n,r,o){let i="",s="literal",a=!1,l=[],c=[],u=0,m=!1,d=(p)=>{let g=AC(e,p,n,r,o);return i+=e.slice(p,g.next),c.push(g.program),l.push(...g.program.issues),u+=oa(g.program),m||=g.program.status==="limited",s="command-substitution",g.next},f=t;while(f<n){let p=e[f];if(!p||/\s/.test(p)||Ju(e,f)||p===">"||p==="<"||p==="#")break;if(p===",")break;if(p==="`"){let g=e[f+1];if(!g){l.push({code:"trailing-escape",message:"PowerShell escape has no following character"}),f++;break}i+=g,f+=2;continue}if(e.startsWith("$(",f)){f=d(f);continue}if(p==="'"){a=!0,f++;let g=!1;while(f<e.length){if(e[f]==="'"&&e[f+1]==="'"){i+="'",f+=2;continue}if(e[f]==="'"){g=!0,f++;break}i+=e[f]??"",f++}if(!g)l.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"});continue}if(p==='"'){a=!0,f++;let g=!1;while(f<n){let h=e[f];if(h==="`"&&e[f+1]){i+=e[f+1],f+=2;continue}if(h==='"'){g=!0,f++;break}if(e.startsWith("$(",f)){f=d(f);continue}if(h==="$")s=e[f+1]==="("?"command-substitution":"variable";i+=h??"",f++}if(!g)l.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"});continue}if(p==="$")s=e[f+1]==="("?"command-substitution":"variable";if(p==="@"&&f===t)s="variable";i+=p,f++}return{word:In(e,t,f,i,s,a,s==="literal"?void 0:PC(e,t,f)),next:f,issues:l,nested:c,words:u,limited:m}}function AC(e,t,n,r,o){let i=Zu(e,t+2,n),s=i===-1?n:i,a=i===-1?n:i+1;if(o>=r.maxDepth)return{program:_e({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:"limited",issues:[Xu(r.maxDepth)],nodes:[]}),next:a};let l=aa(e,t+2,s,r,o+1),c=i===-1?[{code:"unclosed-command-subexpression",message:"PowerShell command subexpression is not closed"}]:[];return{program:_e({kind:"program",dialect:"powershell",source:e.slice(t+2,s),span:{start:t+2,end:s},status:l.limited?"limited":l.issues.length+c.length>0?"partial":"complete",issues:[...l.issues,...c],nodes:l.nodes}),next:a}}function Zu(e,t,n){let r=1,o=!1,i=!1;for(let s=t;s<n;s++){let a=e[s];if(a==="`"){s++;continue}if(!i&&a==="'"){if(o&&e[s+1]==="'"){s++;continue}o=!o;continue}if(!o&&a==='"'){i=!i;continue}if(o)continue;if(e.startsWith("$(",s)){r++,s++;continue}if(!i&&a==="(")r++;if(a!==")")continue;if(r--,r===0)return s}return-1}function oa(e){let t=0;for(let n of e.nodes){if(n.kind==="group")t+=oa(n.body);if(n.kind==="command"){t+=n.words.length;for(let r of n.nested)t+=oa(r)}}return t}function PC(e,t,n){let r=zo(e),o=t,i=!1,s=t;while(s<n){let a=e[s];if(a==="`"){s+=2;continue}if(a==="'"){if(i&&e[s+1]==="'"){s+=2;continue}i=!i,s++;continue}if(i){s++;continue}if(e.startsWith("$(",s)){let l=Zu(e,s+2,n),c=l===-1?n:l+1;r.push(o,s,"literal"),r.push(s,c,"command-substitution"),s=c,o=c;continue}if(a==="$"||a==="@"&&s===t){let l=TC(e,s+1,n);r.push(o,s,"literal"),r.push(s,l,"variable"),s=l,o=l;continue}s++}return r.push(o,n,"literal"),r.parts}function TC(e,t,n){if(e[t]==="{"){let o=e.indexOf("}",t+1);return o===-1||o>=n?n:o+1}let r=t;while(r<n&&/[A-Za-z0-9_:?]/.test(e[r]??""))r++;return r}function Xu(e){return{code:"depth-limit",message:`command structure exceeds parser limit ${e}`}}function ia(e){return e.nodes.flatMap((t)=>{if(t.kind==="group")return ia(t.body);if(t.kind!=="command")return[];return[[...t.words,...t.redirections.flatMap((n)=>n.target?[n.target]:[])].sort((n,r)=>n.span.start-r.span.start).filter((n)=>n.text!==""&&n.raw!==",").map((n)=>n.text),...t.nested.flatMap(ia)]})}function Ju(e,t){for(let n of["&&","||",";","|"])if(e.startsWith(n,t))return n;return null}function kC(e,t,n,r){if(e[t]==="#"&&e[t+1]!==">"){let s=t+1;while(s<n&&e[s]!=="\r"&&e[s]!==`
|
|
23
|
+
`)s++;return{next:s,limited:!1}}if(!e.startsWith("<#",t))return null;let o=1,i=t+2;while(i<n){if(e.startsWith("<#",i)){if(o++,o>r)return{next:n,issue:{code:"comment-depth-limit",message:`PowerShell block comment exceeds nesting limit ${r}`},limited:!0};i+=2;continue}if(e.startsWith("#>",i)){if(o--,i+=2,o===0)return{next:i,limited:!1};continue}i++}return{next:n,issue:{code:"unclosed-block-comment",message:"PowerShell block comment is not closed"},limited:!1}}function IC(e,t){if(t)return"limited";if(e.some((n)=>n.code==="unclosed-block-comment"))return"invalid";return e.length>0?"partial":"complete"}function ra(e,t,n){return Object.freeze({kind:"connector",operator:e.slice(t,n),span:Object.freeze({start:t,end:n})})}function Je(e,t="auto",n=Ft){if(t==="powershell"||t==="auto"&&qu(e.slice(0,n.maxInputLength),n))return sa(e,n);return Lu(e,n)}function _(e){return e.provenance==="command-substitution"?e.raw:e.text}function Mn(e,t){return e==="posix"?t:J(t.map((n)=>n.text))}function qo(e,t){return e&&e.provenance!=="unknown"?e.provenance==="literal":!/[$`*?[\]]/.test(t)}function J(e){return e.map((t)=>({kind:"word",text:t,raw:t,span:{start:0,end:0},provenance:"unknown",quoted:!1,parts:[]}))}function la(e,t){return{value:e,work:t}}function b(e,t){if(e.work)e.work.units=Math.min(Number.MAX_SAFE_INTEGER,e.work.units+1);return e.value[t]}function te(e){return e.value.length}function vr(e,t,n=1){if(e)e.units=Math.min(Number.MAX_SAFE_INTEGER,e.units+t.length*n)}function Ge(e,t){vr(e,t)}function on(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t===95||t>=97&&t<=122}function V(e){if(!e)return!1;let t=e.charCodeAt(0);return t===9||t===10||t===11||t===12||t===13||t===32||t===160||t===65279||t===5760||t>=8192&&t<=8202||t===8232||t===8233||t===8239||t===8287||t===12288}function ca(e){return e===`
|
|
24
|
+
`||e==="\r"||e==="\u2028"||e==="\u2029"}function K(e,t,n){if(t+n.length>te(e))return!1;for(let r=0;r<n.length;r++)if(b(e,t+r)!==n[r])return!1;return!0}function xt(e,t,n){return!on(b(e,t-1))&&K(e,t,n)&&!on(b(e,t+n.length))}function Rt(e,t){return on(b(e,t-1))!==on(b(e,t))}function fe(e){return e===`
|
|
25
|
+
`||e===";"||e==="&"||e==="|"}function Dn(e){return e==="|"||e===";"}function Yo(e,t,n){let r=la(e,n);if(t==="rm")return OC(r);if(t==="dd")return DC(r);return od(r,!0)}function Zo(e,t,n){let r=la(e,n);if(t==="rm")return NC(r);if(t==="reset-hard")return nd(r,"--ha","rd");if(t==="reset-merge")return nd(r,"--me","rge");if(t==="clean")return FC(r);if(t==="checkout")return HC(r);if(t==="push-force")return BC(r);if(t==="push-refspec")return $C(r);if(t==="push-delete")return UC(r);if(t==="branch")return jC(r);if(t==="tag")return qC(r);if(t==="restore")return YC(r);return od(r,!1)}function OC(e){let t=!1,n=!1,r=!1,o=-1;for(let i=0;i<=te(e);i++){let s=b(e,i);if(!t){let l=b(e,i+2);if(xt(e,i,"rm")&&V(l)&&l!==`
|
|
26
|
+
`)t=!0,i++;continue}let a=MC(e,i);if(s===`
|
|
27
|
+
`||a!==-1){if(t=!1,n=!1,r=!1,o=-1,a!==-1)i=a-1;continue}if(s===";"||s==="&"||s==="|"||i===te(e)){if(o>=0){let l=Qu(e,o,i);n||=l.recursive,r||=l.force}if(n&&r)return!0;t=!1,n=!1,r=!1,o=-1;continue}if(V(s)){if(o<0)continue;if(K(e,o,"--")&&i-o===2){t=!1,n=!1,r=!1,o=-1;continue}let l=Qu(e,o,i);if(n||=l.recursive,r||=l.force,n&&r)return!0;o=-1;continue}if(o<0)o=i}return!1}function MC(e,t){if(b(e,t)!=="\\"||b(e,t-1)==="\\")return-1;if(K(e,t,String.raw`\n`))return t+2;if(K(e,t,String.raw`\x0a`)||K(e,t,String.raw`\x0A`))return t+5;if(K(e,t,String.raw`\u000a`)||K(e,t,String.raw`\u000A`))return t+7;return K(e,t,String.raw`\012`)?t+4:-1}function Qu(e,t,n){if(ed(e,t,n,"recursive"))return{recursive:!0,force:!1};if(ed(e,t,n,"force"))return{recursive:!1,force:!0};if(b(e,t)!=="-"||b(e,t+1)==="-")return{recursive:!1,force:!1};let r=!1,o=!1;for(let i=t+1;i<n;i++){let s=b(e,i);r||=s==="r"||s==="R",o||=s==="f"||s==="F"}return{recursive:r,force:o}}function ed(e,t,n,r){let o=n-t-2;if(o<1||o>r.length||!K(e,t,"--"))return!1;for(let i=0;i<o;i++)if(b(e,t+i+2)!==r[i])return!1;return!0}function DC(e){let t=!1;for(let n=0;n<te(e);n++){if(fe(b(e,n))){t=!1;continue}if(xt(e,n,"dd")){t=!0,n++;continue}if(!t||!xt(e,n,"of")||!K(e,n,"of=/dev/"))continue;let r=n+8;if(r<te(e)&&!V(b(e,r))&&b(e,r)!=="'"&&b(e,r)!=='"')return!0}return!1}function NC(e){let t=!1,n=!1,r=!1;for(let o=0;o<=te(e);){let i=b(e,o);if(o===te(e)||fe(i)){t=!1,n=!1,r=!1,o++;continue}let s=WC(e,o);if(s>=0){if(LC(e,s))return!0;let a=s,l=!1;while(V(b(e,a)))l||=b(e,a)===`
|
|
28
|
+
`,a++;if(l)n=!1,r=!1;t=!0,o=a;continue}if(!t){o++;continue}if(K(e,o,"--")&&(o===0||V(b(e,o-1)))&&(!b(e,o+2)||V(b(e,o+2))||fe(b(e,o+2)))){t=!1,n=!1,r=!1,o+=2;continue}if(n||=K(e,o,"--recursive")&&Rt(e,o+11)||ua(e,o,"recursive"),r||=K(e,o,"--force")&&Rt(e,o+7)||ua(e,o,"force"),n&&r)return!0;o++}return!1}function ua(e,t,n){if(!K(e,t,"--"))return!1;let r=0;while(r<=n.length){let o=b(e,t+r+2);if(!o||V(o)||fe(o))break;if(o!==n[r])return!1;r++}return r>0&&Rt(e,t+r+2)}function LC(e,t){let n=t,r=!1,o=!1;while(n<te(e)){while(V(b(e,n)))n++;let i=n;while(n<te(e)&&!V(b(e,n)))n++;if(b(e,i)!=="-"||n-i===2&&K(e,i,"--"))return!1;let s=td(e,i,"recursive"),a=td(e,i,"force");if(r&&a||o&&s)return!0;if(r||=s,o||=a,b(e,i+1)==="-")continue;let l=GC(e,i,n);if(l.combined||r&&l.forceAtBoundary||o&&l.recursiveAtBoundary)return!0;r||=l.recursive,o||=l.force}return!1}function td(e,t,n){return K(e,t,`--${n}`)&&Rt(e,t+n.length+2)||ua(e,t,n)}function WC(e,t){if(t>0&&on(b(e,t-1)))return-1;let n=t;if(b(e,n)==="\\")n++;if(b(e,n)!=="r")return-1;if(n++,b(e,n)==="\\")n++;if(b(e,n)!=="m"||!V(b(e,n+1)))return-1;return n+1}function GC(e,t,n){let r=!1,o=!1,i=!1,s=!1,a=!1;if(b(e,t)!=="-")return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a};let l="";for(let c=t+1;c<n;c++){let u=b(e,c)??"",m=(u==="r"||u==="f")&&Rt(e,c+1);r||=u==="r",o||=u==="f",i||=u==="r"&&m,s||=u==="f"&&m,a||=(l==="r"&&u==="f"||l==="f"&&u==="r")&&m,l=u}return{recursive:r,force:o,recursiveAtBoundary:i,forceAtBoundary:s,combined:a}}function nd(e,t,n){return xr(e,"reset",Dn,!0,(r)=>b(e,r)==="-"&&Nn(e,r,t,n)?!0:r)}function FC(e){return xr(e,"clean",Dn,!0,(t)=>{if(b(e,t)!=="-")return t;if(Nn(e,t,"--fo","rce"))return!0;let n=Er(e,t,Dn);for(let r=t+1;r<n;r++)if(b(e,r)==="f")return!0;return n-1})}function Xo(e,t,n){if(!xt(e,t,"git"))return null;let r=t+3;if(!V(b(e,r)))return{commandEnd:-1,next:r};while(V(b(e,r)))r++;while(r<te(e)){if(fe(b(e,r)))return{commandEnd:-1,next:r};let o=Er(e,r,fe);if(xt(e,r,n))return{commandEnd:r+n.length,next:o};if(b(e,r)!=="-")return{commandEnd:-1,next:o};let i=o-r===2&&K(e,r,"--"),s=zC(e,r,o);r=o;while(V(b(e,r)))r++;if(i)return{commandEnd:xt(e,r,n)?r+n.length:-1,next:Er(e,r,fe)};if(!s)continue;if(r>=te(e)||fe(b(e,r)))return{commandEnd:-1,next:r};r=Er(e,r,fe);while(V(b(e,r)))r++}return{commandEnd:-1,next:r}}function zC(e,t,n){for(let r of De)if(n-t===r.length&&K(e,t,r))return!0;return!1}function HC(e){return rd(e,{command:"checkout",longPrefix:"--fo",longOptional:"rce",shortFlag:"f",excludedShortStarts:"bBU"})}function BC(e){return xr(e,"push",Dn,!0,(t)=>{if(b(e,t)!=="-")return t;if(b(e,t+1)==="f"&&!on(b(e,t+2))&&!K(e,t+2,"-with-lease"))return!0;let n=id(e,t,"--fo","rce");if(n>=0&&!K(e,n,"-with-lease"))return!0;return t})}function $C(e){return xr(e,"push",fe,!1,(t)=>{if(V(b(e,t))&&b(e,t+1)==="+"&&t+2<te(e)&&!fe(b(e,t+2))&&!V(b(e,t+2)))return!0;if(b(e,t)===":"&&b(e,t+1)==="+")return!0;return t})}function UC(e){return xr(e,"push",fe,!1,(t)=>{if(b(e,t)==="-"&&Nn(e,t,"--de","lete"))return!0;if(V(b(e,t))&&b(e,t+1)===":"&&t+2<te(e)&&!V(b(e,t+2))&&!fe(b(e,t+2)))return!0;return t})}function jC(e){let t=!1,n=!1,r=!1;for(let o=0;o<=te(e);o++){if(o===te(e)||fe(b(e,o))){if(n&&r)return!0;t=!1,n=!1,r=!1;continue}if(!t){let a=Xo(e,o,"branch");if(a){t=a.commandEnd>=0,o=Math.max(o,(t?a.commandEnd:a.next)-1);continue}}if(!t||b(e,o)!=="-")continue;let i=Er(e,o,fe),s=VC(e,o,i);if(n||=s.deletion,r||=s.force,n&&r)return!0;o=i-1}return!1}function VC(e,t,n){let r=!1,o=!1;for(let i=t;i<n;i++){if(b(e,i)!=="-")continue;if(Nn(e,i,"--de","lete"))r=!0;if(Nn(e,i,"--fo","rce"))o=!0;if(b(e,i+1)==="-")continue;let s=i+1,a=!1,l=!1,c=!1;while(s<n&&KC(b(e,s))){let u=b(e,s);a||=u==="d"||u==="D",l||=u==="f",c||=u==="D",s++}if(!Rt(e,s))continue;r||=a,o||=l||c}return{deletion:r,force:o}}function KC(e){if(!e)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function qC(e){return rd(e,{command:"tag",longPrefix:"--de",longOptional:"lete",shortFlag:"d",excludedShortStarts:""})}function rd(e,t){let n=[{outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:0,quote:"",escaped:!1}];for(let r=0;r<te(e);r++){let o=b(e,r),i=n[n.length-1];if(!i)return!1;let s=i.escaped;if(i.escaped=!s&&i.quote!=="'"&&o==="\\",!s&&o==="'"&&i.quote!=='"')i.quote=i.quote==="'"?"":"'";if(!s&&o==='"'&&i.quote!=="'")i.quote=i.quote==='"'?"":'"';if(o==="$"&&b(e,r+1)==="("&&(n.length===1||!s&&i.quote!=="'")){n.push({outerActive:!1,shortActive:!1,hasShortFlag:!1,depth:1,quote:"",escaped:!1}),r++;continue}if(!s&&!i.quote&&n.length>1&&o==="("){i.depth++;continue}if(!s&&!i.quote&&n.length>1&&o===")"){if(i.depth--,i.depth===0)n.pop();continue}if(V(o))i.shortActive=!1,i.hasShortFlag=!1;if(!i.outerActive){let a=Xo(e,r,t.command);if(a){i.outerActive=a.commandEnd>=0&&V(b(e,a.commandEnd)),i.shortActive=!1,i.hasShortFlag=!1,r=Math.max(r,(i.outerActive?a.commandEnd:a.next)-1);continue}}if(i.outerActive&&o==="-"){if(Nn(e,r,t.longPrefix,t.longOptional))return!0;i.shortActive||=!t.excludedShortStarts.includes(b(e,r+1)??"")}if(i.hasShortFlag||=i.shortActive&&o===t.shortFlag,i.hasShortFlag&&Rt(e,r+1))return!0;if(Dn(o))i.outerActive=!1}return!1}function xr(e,t,n,r,o){let i=!1;for(let s=0;s<te(e);s++){let a=b(e,s),l=n(a);if(!i&&!l){let c=Xo(e,s,t);if(c){i=c.commandEnd>=0&&(!r||V(b(e,c.commandEnd))),s=Math.max(s,(i?c.commandEnd:c.next)-1);continue}}if(i){let c=o(s);if(c===!0)return!0;for(let u=s;u<=c;u++)if(n(b(e,u)))i=!1;s=c}if(l)i=!1}return!1}function YC(e){let t=!1;for(let n=0;n<te(e);n++){if(ca(b(e,n))){if(t)return!0;t=!1;continue}if(!t){let r=Xo(e,n,"restore");if(r){t=r.commandEnd>=0,n=Math.max(n,(t?r.commandEnd:r.next)-1);continue}}if(t&&b(e,n)==="-"&&b(e,n+1)==="-"&&(K(e,n+2,"staged")||K(e,n+2,"help")))t=!1}return t}function od(e,t){let n=!1;for(let r=0;r<te(e);r++){let o=b(e,r),i=t?ca(o):fe(o);if(n&&V(o)&&b(e,r+1)==="-"&&xt(e,r+2,"delete"))return!0;if(i){n=!1;continue}if(xt(e,r,"find"))n=!0,r+=3}return!1}function Er(e,t,n){let r=t;while(r<te(e)&&!V(b(e,r))&&!n(b(e,r)))r++;return r}function id(e,t,n,r){if(!K(e,t,n))return-1;let o=t+n.length;for(let i=0;i<r.length&&b(e,o)===r[i];i++)o++;return Rt(e,o)?o:-1}function Nn(e,t,n,r){return id(e,t,n,r)>=0}function $e(e,t){vr(t,e,2);let n=e.toLowerCase(),r=n.trimStart(),o=r.startsWith("echo ")||r.startsWith("rg "),i=[{scan:"rm",label:"rm -rf"},{scan:"reset-hard",label:"git reset --hard"},{scan:"reset-merge",label:"git reset --merge"},{scan:"clean",label:"git clean -f"},{scan:"checkout",label:"git checkout --force"},{scan:"push-force",label:"git push --force"},{scan:"push-refspec",label:"git push --force"},{scan:"push-delete",label:"git push delete"},{scan:"branch",label:"git branch -D",caseSensitive:!0},{scan:"tag",label:"git tag -d"},{regex:/\bgit\s+stash\s+(drop|clear)\b/,label:"git stash drop/clear"},{regex:/\bgit\s+checkout\s+--\s/,label:"git checkout --"},{scan:"restore",label:"git restore without --staged"},{scan:"find",label:"find -delete",skipForEchoRg:!0},{regex:/\bdd\b[^\n|;&]*\bof=\/dev\/\S/,label:"dd of=/dev/",skipForEchoRg:!0},{regex:/\bmkfs(?:\.[a-z0-9_-]+)?\s+\/dev\/\S/,label:"mkfs /dev/",skipForEchoRg:!0},{regex:/\bshred\b\s+\S/,label:"shred",skipForEchoRg:!0},{regex:/\b(?:curl|wget|fetch|aria2c|https?|xhs?|ncat|netcat|nc)\b(?:[^\n|;&]|\\\n)*\|(?:\s|\\\n)*(?:(?:sudo|env|command|builtin)(?:\s+(?:-\S+|\w+=\S*))*\s+)?(?:[^\s|;&]*\/)?(?:ba|da|z|k)?sh(?![^\s;&|])/,label:"download piped to shell",skipForEchoRg:!0}];for(let s of i){if(s.skipForEchoRg&&o)continue;let a=s.caseSensitive?e:n;if(s.regex)Ge(t,a);if((s.regex?.test(a)??!1)||s.scan&&Zo(a,s.scan,t))return v("raw-text.dangerous-command",`Unparseable command text contains a destructive pattern (${s.label}). Rewrite as a plain, parseable command so it can be analyzed.`)}return null}var ZC=/^[A-Za-z_][A-Za-z0-9_]*=/;function ad(e,t,n){let r=e.words[0];if(!t||!r||e.words.length!==1||e.dialect!=="posix")return!1;if(!r.quoted||r.provenance!=="literal")return!1;let o=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r.text)?.[1];if(!o)return!1;vr(n,t.source,2);let i={anchored:new RegExp(`^\\$\\{?${o}(?![A-Za-z0-9_])`),loose:new RegExp(`\\$\\{?${o}(?![A-Za-z0-9_])`)};return ld(t.nodes,r,i)}function ld(e,t,n){return e.every((r)=>{if(r.kind==="connector")return!0;if(r.kind==="group"||r.kind==="function")return ld(r.body.nodes,t,n);if(r.kind==="unknown")return!n.loose.test(r.source);return XC(r,t,n)})}function XC(e,t,n){if(e.nested.some((o)=>n.loose.test(o.source)))return!1;let r=e.words.findIndex((o)=>!ZC.test(o.text));return e.words.every((o,i)=>o===t||sd(o.raw,n.anchored,i!==r))&&e.redirections.every((o)=>(!o.heredoc||o.heredoc.quotedDelimiter||!n.loose.test(o.heredoc.body))&&(!o.target||sd(o.target.raw,n.anchored,!0)))}function sd(e,t,n){let r=!1,o=!1;for(let i=0;i<e.length;i++){let s=e[i];if(s==="\\"&&!r){i++;continue}if(!o&&s==="'"){r=!r;continue}if(!r&&s==='"'){o=!o;continue}if(r||s!=="$")continue;if(!t.test(e.slice(i)))continue;if(!o||!n)return!1}return!0}var Rr=require("node:path");function wr(e,t,n,r){let o=Rr.isAbsolute(e)?Rr.resolve(e):t?Rr.resolve(t,e):void 0;if(!o)return;try{return O(o,n,r)}catch{return o}}function cd(e){return!["/dev","/proc","/sys"].some((t)=>e===t||e.startsWith(`${t}/`))}var Ln="Interpreter code contains a dangerous command. Run the underlying command directly so it can be analyzed, or use the safer alternative for that command.",_r="Interpreter one-liners are blocked by the active safety policy. Write the code to a script file and run it, or run the equivalent shell command directly.",ma=new Map([["python",new Set(["-c"])],["node",new Set(["-e","--eval"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])]]),JC=new Set(["-p","--print"]),QC=new Map([["python",new Set(["c"])],["node",new Set(["e"])],["ruby",new Set(["e"])],["perl",new Set(["e","E"])]]),eb=new Map([["python",new Set(["W","X"])],["node",new Set(["C","r"])],["ruby",new Set(["C","E","F","I","r"])],["perl",new Set(["F","I","M","m"])]]),tb=new Map([["ruby",new Set(["0","K","W","x"])],["perl",new Set(["0","C","D","V","d","i","l","x"])]]),nb=new Map([["python",new Set(["m"])]]),rb=new Map([["node",new Set(["--allow-fs-read","--allow-fs-write","--conditions","--cpu-prof-dir","--cpu-prof-interval","--cpu-prof-name","--debug-port","--diagnostic-dir","--disable-proto","--disable-warning","--dns-result-order","--env-file","--env-file-if-exists","--experimental-package-map","--experimental-test-isolation","--experimental-test-tag-filter","--heap-prof-dir","--heap-prof-interval","--heap-prof-name","--heapsnapshot-near-heap-limit","--heapsnapshot-signal","--icu-data-dir","--input-type","--inspect-port","--inspect-publish-uid","--localstorage-file","--max-http-header-size","--max-old-space-size-percentage","--network-family-autoselection-attempt-timeout","--openssl-config","--redirect-warnings","--report-dir","--report-directory","--report-filename","--report-signal","--secure-heap","--secure-heap-min","--test-concurrency","--test-coverage-branches","--test-coverage-exclude","--test-coverage-functions","--test-coverage-include","--test-coverage-lines","--test-global-setup","--test-isolation","--test-name-pattern","--test-random-seed","--test-reporter","--test-reporter-destination","--test-rerun-failures","--test-shard","--test-skip-pattern","--test-timeout","--title","--tls-cipher-list","--tls-keylog","--trace-event-categories","--trace-event-file-pattern","--trace-require-module","--unhandled-rejections","--use-largepages","--v8-pool-size","--watch-kill-signal"])],["python",new Set(["--check-hash-based-pycs"])],["ruby",new Set(["--backtrace-limit","--crash-report","--disable","--enable","--encoding","--external-encoding","--internal-encoding","--parser"])]]),ob=new Set(["always","default","never"]),ib=new Set(["--backtrace-limit","--crash-report","--disable","--enable"]),sb=/\\\r?\n/g,ab=new Map([["python",[{selector:"-c",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-m",kind:"module-file",valueForm:"attached-or-separate"}]],["node",[{selector:"-e",kind:"inline-code",valueForm:"separate-only"},{selector:"--eval",kind:"inline-code",valueForm:"equals-or-separate"},{selector:"-p",kind:"inline-code",valueForm:"separate-only"},{selector:"--print",kind:"inline-code",valueForm:"separate-only"},{selector:"-r",kind:"module-file",valueForm:"separate-only"},{selector:"--require",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--import",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--loader",kind:"module-file",valueForm:"equals-or-separate"},{selector:"--experimental-loader",kind:"module-file",valueForm:"equals-or-separate"}]],["ruby",[{selector:"-e",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-r",kind:"module-file",valueForm:"attached-or-separate"}]],["perl",[{selector:"-e",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-E",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"-M",kind:"module-file",valueForm:"attached-only"},{selector:"-m",kind:"module-file",valueForm:"attached-only"}]]]);function ud(e){return Qo(e).code}function Jo(e){return Qo(e).sources}function dd(e){return ab.get(pa(e))??[]}function Qo(e){let t=pa(e[0]??"");if(!ma.has(t))return{code:null,sources:[],optionsOpen:!1};let n=[],r=[],o=!0;for(let i=1;i<e.length;i++){let s=e[i];if(s===void 0)break;if(s==="--")return Qe(t,n,r,o,e[i+1]===void 0?void 0:i+1,e[i+1]);if(s===""||s==="-"||!s.startsWith("-"))return Qe(t,n,r,o,i,s);if(t==="node"&&JC.has(s)){let m=e[i+1];if(m===void 0)return Qe(t,n,r,o);if(m.startsWith("-"))continue;n.push({tokenIndex:i+1,value:m}),r.push({tokenIndex:i+1,kind:"inline-code",value:m}),i++;continue}if(cb(t,s)){let m=e[i+1];if(m===void 0)return Qe(t,n,r,o);if(n.push({tokenIndex:i+1,value:m}),r.push({tokenIndex:i+1,kind:"inline-code",value:m}),t==="python")return Qe(t,n,r,o);i++;continue}let a=/^--eval=(.*)$/s.exec(s);if(ub(t)&&a){let m=a[1]??"";n.push({tokenIndex:i,value:m}),r.push({tokenIndex:i,kind:"inline-code",value:m});continue}if(t==="node"){let m=lb(s);if(m){if(m.attached){if(o&&=m.value!=="",m.value!=="")r.push({tokenIndex:i,kind:"module-file",value:m.value});continue}let d=e[i+1];if(d===void 0||d.startsWith("-"))return o=!1,Qe(t,n,r,o);r.push({tokenIndex:i+1,kind:"module-file",value:d}),i++;continue}}if(t==="python"&&s.startsWith("--check-hash-based-pycs=")||t==="node"&&(s==="--conditions="||s==="--diagnostic-dir="||s==="--title=")||t==="ruby"&&(s==="--disable="||s==="--enable="))return Qe(t,n,r,o);if(rb.get(t)?.has(s)){let m=e[i+1];if(m===void 0||m.startsWith("-")&&!(t==="ruby"&&ib.has(s))||t==="python"&&!ob.has(m))return Qe(t,n,r,o);i++;continue}if(s.startsWith("--"))continue;let l,c=!1;for(let m=1;m<s.length;m++){let d=s[m];if(d===void 0)break;if(nb.get(t)?.has(d)){let f=s.slice(m+1),p=f||e[i+1];if(p!==void 0)r.push({tokenIndex:f?i:i+1,kind:"module-file",value:p});return Qe(t,n,r,o)}if(QC.get(t)?.has(d)){l=s.slice(m+1)||e[i+1],c=m+1===s.length;break}if(t==="node"&&d==="r"){if(o&&=s==="-r",s==="-r"){let f=e[i+1];if(o&&=f!==void 0&&!f.startsWith("-"),o&&f!==void 0)r.push({tokenIndex:i+1,kind:"module-file",value:f});i++}break}if(t==="ruby"&&d==="r"){let f=s.slice(m+1),p=f||e[i+1];if(o&&=p!==void 0,p!==void 0)r.push({tokenIndex:f?i:i+1,kind:"module-file",value:p});if(!f)i++;break}if(t==="perl"&&(d==="M"||d==="m")){let f=s.slice(m+1);if(!f){if(o=!1,m+1===s.length)i++;break}r.push({tokenIndex:i,kind:"module-file",value:f});break}if(eb.get(t)?.has(d)){if(m+1===s.length)i++;break}if(tb.get(t)?.has(d)&&m+1<s.length)break}if(l===void 0)continue;let u=c?i+1:i;if(n.push({tokenIndex:u,value:l}),r.push({tokenIndex:u,kind:"inline-code",value:l}),t==="python")return Qe(t,n,r,o);if(c)i++}return Qe(t,n,r,o,void 0,void 0,!0)}function Qe(e,t,n,r,o,i,s=!1){let a=e==="node"?t.slice(-1):t,l=new Set(a.map((u)=>u.tokenIndex)),c=n.filter((u)=>u.kind!=="inline-code"||l.has(u.tokenIndex));if(r&&t.length===0&&o!==void 0&&i!==void 0)c.push({tokenIndex:o,kind:"main-script",value:i});return{code:(e==="node"?a[0]?.value:a.map((u)=>u.value).join(`
|
|
29
|
+
`))||null,sources:r?c:[],optionsOpen:r&&s}}function lb(e){for(let t of["--import","--loader","--experimental-loader","--require"]){if(e===t)return{attached:!1,value:""};if(e.startsWith(`${t}=`))return{attached:!0,value:e.slice(t.length+1)}}return}function fa(e,t){return pa(e)==="node"&&/^\s*console\.(?:log|info|warn|error)\(\s*(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*')\s*\)\s*;?\s*$/.test(t)}function pa(e){let t=k(e).toLowerCase();return vo.test(t)?"python":t}function cb(e,t){return ma.get(e)?.has(t)??!1}function ub(e){return ma.get(e)?.has("--eval")??!1}function Ar(e,t,n=!1){let r=fb(e,t);if(!da(r,t))return!1;Ge(t,r);let o=mb(r);if(da(o,t))return!0;if(Ge(t,o),!md.test(o))return!1;return!n||db(r,t)}function db(e,t){if(/`|%x|\bqx\b/.test(e))return!0;let r=e.split(""),o=[];for(let l=0;l<e.length;l++){let c=e[l];if(c!=="'"&&c!=='"')continue;let u=e.startsWith(c.repeat(3),l)?c.repeat(3):c,m=l+u.length,d=m;while(d<e.length&&!e.startsWith(u,d))d+=e[d]==="\\"?2:1;if(d>=e.length)return!0;o.push({start:m,text:e.slice(m,d)}),r.fill(" ",l,d+u.length),l=d+u.length-1}let i=r.join(""),s=Array.from(i.matchAll(/([\w$]+(?:\s*\.\s*[\w$]+)*)\s*\(/g)).filter((l)=>md.test(l[1]??"")).map((l)=>{let c=l.index+l[0].length;return{start:c,end:ga(i,c)}});if(s.some((l)=>ha(i,l.start)))return!0;return o.some((l)=>{let c=/\b(?:system|exec|spawn|popen)\s*$/.test(i.slice(0,l.start)),u=s.some((m)=>l.start>=m.start&&l.start<m.end);return(c||u)&&da(l.text,t)})}function ga(e,t){let n=1;for(let r=t;r<e.length;r++){if(e[r]==="(")n++;if(e[r]===")")n--;if(n===0)return r}return e.length}function ha(e,t){let n=0;for(let r=t;r<e.length;r++){let o=e[r]??"";if("([{".includes(o))n++;if(")]}".includes(o)&&n--===0)return!1;if(o===","&&n===0)return!1;if(/[A-Za-z_$]/.test(o))return!0}return!1}var md=/`|%x|\b(?:system|exec|spawn|popen|subprocess|child_process|open3|eval|fork|qx)/i;function mb(e){let t=[],n=0,r=0;while(r<e.length){let o=e[r];if(o!=="'"&&o!=='"'){r++;continue}let i=e.startsWith(o.repeat(3),r)?o.repeat(3):o,s=r+i.length;while(s<e.length&&!e.startsWith(i,s))s+=e[s]==="\\"?2:1;if(s>=e.length)break;t.push(e.slice(n,r)," "),r=s+i.length,n=r}return t.push(e.slice(n)),t.join("")}function da(e,t){if(Yo(e,"rm",t))return!0;for(let r of[/\bgit[^\S\n]+checkout[^\S\n]+--[^\S\n]/,/\bgit[^\S\n]+stash[^\S\n]+(drop|clear)\b/])if(Ge(t,e),r.test(e))return!0;if(Yo(e,"dd",t))return!0;for(let r of[/\bmkfs(?:\.[A-Za-z0-9_-]+)?\s+\/dev\/[^\s'"]+/,/\bshred\b\s+/])if(Ge(t,e),r.test(e))return!0;if(Yo(e,"find",t))return!0;let n=e.split(/[\n\r\u2028\u2029]/);return["reset-hard","reset-merge","clean","checkout","push-force","push-refspec","push-delete","branch","tag","restore"].some((r)=>(Ge(t,e),n.some((o)=>Zo(o,r))))}function fb(e,t){return Ge(t,e),e.replace(sb,"")}var di=require("node:fs"),mt=require("node:path");var Tr=require("node:path");var zt=require("node:path");function Ht(e,t,n){if(bt(t))throw Error("Unsupported Windows namespace path");let r=zt.isAbsolute(t)?zt.parse(t).root:"",o=r||e;for(let i of gb(r?t.slice(r.length):t)){if(i===""||i===".")continue;if(i===".."){o=zt.dirname(o);continue}let s=pb(o,i),a=n.entryKind(s),l=a==="symlink"?n.realpath(s):s;if(a==="missing"||l===null)throw Error(`Cannot resolve path component: ${s}`);o=l}return o}function pb(e,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${t}`:`${e}${zt.sep}${t}`}function gb(e){let t=process.platform==="win32"?/[\\/]+/:/\/+/;return e.split(t)}var ya=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"],hb=new Set(ya),yb=1024,fd=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_NOSYSTEM","GIT_CONFIG_SYSTEM","HOME","XDG_CONFIG_HOME"]),pd=new Set(["GIT_SSH_COMMAND","GIT_SSH","GIT_SSH_VARIANT"]),Cb=/^([A-Za-z_][A-Za-z0-9_]*)\+=/;function ei(e){return hb.has(e)}function Ca(e){return ei(e)||fd.has(e)||pd.has(e)||lr(e)}function wt(e,t,n){return n?.has(e)?n.get(e):t.get(e)}function gd(e,t){let n=wt("GIT_CONFIG_COUNT",e,t);if(n===void 0)return{state:"absent"};if(n==="")return{state:"valid",count:0};if(!/^\d+$/.test(n))return{state:"invalid"};let r=Number(n);return Number.isSafeInteger(r)&&r<=yb?{state:"valid",count:r}:{state:"invalid"}}function ti(e,t,n){let o=e.match(Cb)?.[1];if(!o||!Ca(o))return null;let i=e.indexOf("=");return{name:o,value:`${wt(o,t,n)??""}${e.slice(i+1)}`}}function hd(e){return Cd(e,pd)}function yd(e){return Cd(e,fd)}function Cd(e,t){if(!e)return!1;for(let n of e.keys())if(t.has(n))return!0;return!1}var Sd=/^[A-Za-z_][A-Za-z0-9_]*=/;function Ue(e){if(!Sd.test(e))return null;let t=e.indexOf("=");return{name:e.slice(0,t),value:e.slice(t+1)}}function ni(e){let t=new Map,n=0;while(n<e.length){let r=e[n];if(!r)break;let o=Ue(_(r));if(!o)break;t.set(o.name,o.value),n++}return{words:e.slice(n),envAssignments:t}}function vd(e){let t=M(e);return e.includes("=")||t==="sudo"||t==="env"||t==="command"||t==="builtin"}function sn(e,t,n,r){if(!vd(Wn(e)))return{words:e,envAssignments:new Map,cwd:n,rewritten:!1};let o=new Set(e),i=e,s=new Map,a=new Map(r??[]),l=[],c=n;for(let m=0;m<X.wrapperPeelIterations.cap;m++){let d=bd(i),f=ni(i);for(let[g,h]of f.envAssignments)s.set(g,h),a.set(g,h);if(i=f.words,i.length===0)break;while(i.length>0&&Wn(i).includes("=")&&!Sb(i)){let g=vb(Wn(i),a,t.env)??ti(Wn(i),t.env,a);if(g)s.set(g.name,g.value),a.set(g.name,g.value);i=i.slice(1)}if(i.length===0)break;let p=M(Wn(i));if(p!=="sudo"&&p!=="env"&&p!=="command"&&p!=="builtin")break;if(p==="sudo"){let g=xb(i,t.paths,c);if(i=g.words,g.cwd!==void 0)c=g.cwd}if(p==="env"){let g=_b(i,c,a,t);if(l.push(...g.envSplitValues??[]),i=g.words,g.cwd!==void 0)c=g.cwd;for(let[h,y]of g.envAssignments)s.set(h,y),a.set(h,y)}if(p==="command")i=Ab(i);if(p==="builtin")i=i.slice(et(i,1)==="--"?2:1);if(bd(i)===d)break}let u=ni(i);for(let[m,d]of u.envAssignments)s.set(m,d),a.set(m,d);return{words:u.words,envAssignments:s,cwd:c,envSplitValues:l.length>0?l:void 0,rewritten:bb(u.words,o)}}function bb(e,t){return e.some((n)=>!t.has(n))}function bd(e){return e.map(_).join(" ")}function Wn(e){let t=e[0];return t?_(t):""}function et(e,t){let n=e[t];return n?_(n):void 0}function Sb(e){return Sd.test(Wn(e))}function vb(e,t,n){if(!e.startsWith("TMPDIR+="))return null;return{name:"TMPDIR",value:`${t.get("TMPDIR")??n.get("TMPDIR")??""}${e.slice(8)}`}}var Eb=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]);function xb(e,t,n){let r=1,o=n;while(r<e.length){let i=et(e,r);if(!i)break;if(i==="--")return{words:e.slice(r+1),cwd:o};if(!i.startsWith("-"))break;if(i==="-D"||i==="--chdir"){let s=et(e,r+1);o=s?Pr(o,s,t):null,r+=2;continue}if(i.startsWith("--chdir=")){o=Pr(o,i.slice(8),t),r++;continue}if(i.startsWith("-D")&&i.length>2){o=Pr(o,i.slice(2),t),r++;continue}if(i==="-i"||i==="--login"){o=null,r++;continue}if(Eb.has(i)){r+=2;continue}r++}return{words:e.slice(r),cwd:o}}var Rb=new Set(["-i","-0","--null"]),wb=new Set(["-u","--unset","-C","--chdir","-P"]);function _b(e,t,n,r){let o=new Map,i=[],s=t,a=1,l=(c)=>({words:e.slice(c),envAssignments:o,cwd:s,envSplitValues:i.length>0?i:void 0});while(a<e.length){let c=et(e,a);if(!c)break;if(c==="--")return l(a+1);if(c==="-i"||c==="--ignore-environment"||c==="-"){o.clear();for(let m of n.keys())o.set(m,"");o.set("TMPDIR",""),a++;continue}if(Rb.has(c)){a++;continue}if(c==="-u"||c==="--unset"){let m=et(e,a+1);if(m!==void 0)o.set(m,"");a+=2;continue}if(c.startsWith("-u")&&c.length>2&&!c.startsWith("-u=")){o.set(c.slice(2),""),a++;continue}if(c.startsWith("--unset=")){o.set(c.slice(8),""),a++;continue}let u=c==="-S"||c==="--split-string"?{value:et(e,a+1),consumed:2}:c.startsWith("-S")&&c.length>2?{value:c.slice(2),consumed:1}:c.startsWith("--split-string=")?{value:c.slice(15),consumed:1}:null;if(u){if(u.value!==void 0)i.push(u.value);return s=null,l(a+u.consumed)}if(wb.has(c)){if(c==="-C"||c==="--chdir"){let m=et(e,a+1);s=m?Pr(s,m,r.paths):null}a+=2;continue}if(c.startsWith("-u=")){a++;continue}if(c.startsWith("-C")&&c.length>2||c.startsWith("--chdir=")){let m=c.startsWith("--chdir=")?c.slice(8):c.startsWith("-C=")?c.slice(3):c.slice(2);s=Pr(s,m,r.paths),a++;continue}if(c.startsWith("-P")){a++;continue}if(c.startsWith("-")){a++;continue}if(!Ue(c))break;while(a<e.length){let m=Ue(et(e,a)??"");if(!m)break;o.set(m.name,m.value),a++}if(et(e,a)==="--")a++;return l(a)}return l(a)}function Pr(e,t,n){if(t==="")return null;if(!e&&!Tr.isAbsolute(t))return null;let r=Tr.isAbsolute(t)?Tr.parse(t).root:n.realpath(e??"/");if(r===null)return null;try{return Ht(r,t,n)}catch{return null}}function Ab(e){if(et(e,1)==="-v")return[...J(["type"]),...e.slice(2)];let t=1;while(t<e.length){let n=et(e,t);if(!n)break;if(n==="-p"||n==="-v"||n==="-V"){t++;continue}if(n==="--")return e.slice(t+1);if(n.startsWith("-")&&!n.startsWith("--")&&n.length>1){if(!/^[pvV]+$/.test(n.slice(1)))break;t++;continue}break}return e.slice(t)}var Pb=/['"\\$`{}#]/;function ri(e,t){if(e.some((r)=>Pb.test(r)))return null;let n=[...e.flatMap((r)=>r.split(/\s+/).filter((o)=>o.length>0)),...t];return n.length<=64?n:null}function Bt(e,t,n){return oi(e,t,n).tokens}function Tb(e){let t=[],n="",r=0;while(r<e.length){let o=e.charAt(r);if(o==='"'||o==="'"){let i=e.indexOf(o,r+1);if(i===-1)return e.split(/\s+/).map((s)=>s.replace(/["']/g,"")).filter((s)=>s.length>0);n+=e.slice(r+1,i),r=i+1;continue}if(/\s/.test(o)){if(n.length>0)t.push(n);n="",r++;continue}n+=o,r++}if(n.length>0)t.push(n);return t}function $t(e,t,n,r=0){let o=oi(e,t,n),i=(o.envSplitValues??[]).flatMap(Tb);if(i.length===0)return o.tokens;let s=[...i,...o.tokens];if(r>=8)return s;return $t(s,t,n,r+1)}function oi(e,t,n,r){if(!vd(e[0]??""))return{tokens:[...e],envAssignments:new Map,cwd:n};let o=sn(J(e),t,n,r);return{tokens:o.words.map(_),envAssignments:o.envAssignments,cwd:o.cwd,envSplitValues:o.envSplitValues}}var Ea=Symbol("adopt-as-operand"),kb=new Set(["env","sudo","command","builtin"]),Ib=new Set(["&&","||","|&","|","&",";"]),Ob=new Set(["<<","<<<",">|"]),Mb=new Set(["|","|&"]),Db=/[*@#?$!_-]/,Nb=/^\w+(?::\w+)*/,Lb=Object.freeze([]),kr=Object.freeze({kind:"scope",edge:"enter"}),Ir=Object.freeze({kind:"scope",edge:"exit"}),Wb=Object.freeze([]),Gb=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),Or=new Set(["bash","sh","zsh","dash","ksh"]),Fb=256,_d=new WeakMap;function Ad(e,t){let n=t.status==="complete"?new Set(va(t)):new Set,r=Bb(e,n);if(xo(r))return ii("unclosed-quote",r,t);let o={invalid:!1,limited:!1,expansions:0,assignmentFallbacks:[]},i=an(t,{source:r,suppressed:n,flags:o,depth:0,functions:new Map,powershell:t.dialect==="powershell"});if(o.limited)return ii("structural-limit",r,t);if(o.invalid)return ii("invalid",r,t);let s=ii("complete",r,t,o.assignmentFallbacks);return _d.set(s,Object.freeze(i)),s}function ai(e,t,n,r,o){let i=o.word??((m)=>m),s={cwd:t,variables:new Map,previous:null},a=[],l=new Set,c=null,u=[];for(let m of Pd(e)){if(m.kind==="scope"){if(m.edge==="enter"){u.push({state:s,segment:[...a],shellWords:new Set(l),pipeProducer:c});continue}let d=o.segment(a,s,c,null,l);if(d)return d;let f=u.pop();if(f===void 0)throw Error("scope exit without a matching enter");s=f.state,a=f.segment,l=f.shellWords,c=f.pipeProducer;continue}if(m.kind==="operator"){if(!m.boundary)continue;let d=o.segment(a,s,c,m.operator,l);if(d)return d;s=zb(a,s,n,r),c=a.length>0&&Mb.has(m.operator)?a:null,a=[],l=new Set;continue}if(m.kind==="redirection"){if(m.fd!==void 0)l.add(a.length-1);if(m.target===void 0)continue;let d=o.redirection({operator:m.operator,role:m.role,targetOrder:m.targetOrder,target:m.target,...m.body===void 0?{}:{body:m.body,consumer:m.consumer}},s);if(d===Ea){l.add(a.length),a.push(i(m.target));continue}if(d)return d;continue}a.push(i(m.text))}return o.segment(a,s,c,null,l)}function li(e){return Pd(e).flatMap((t)=>{if(t.kind==="word")return[{kind:"word",text:t.text}];if(t.kind==="operator")return[{kind:"operator",boundary:t.boundary}];if(t.kind==="redirection")return[{kind:"redirection",target:t.target}];return[]})}function Ae(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-+])([^}]*)\}/g,(n,r,o,i)=>{let s=t.get(r);if(s===void 0)return n;let a=o.startsWith(":")?s!=="":!0;if(o.endsWith("-"))return a?s:Ae(i,t);return a?Ae(i,t):""}).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(n,r)=>t.get(r)??n).replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(n,r)=>t.get(r)??n)}function Mr(e){return e.length>0&&e.every((t)=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(t))}function zb(e,t,n,r){let o=Mr(e)?new Map([...t.variables,...Hb(e,t.variables)]):t.variables,i=Bt([...e],n),s=k(i[0]??"").toLowerCase()==="cd"?i[1]:void 0;if(!s)return{...t,variables:o};if(s==="-"){if(t.previous===null)return{...t,variables:o};return{cwd:t.previous,variables:o,previous:t.cwd}}return{cwd:he(Ae(s,o),t.cwd,n,r),variables:o,previous:t.cwd}}function Hb(e,t){return e.flatMap((n)=>{let r=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(n),o=r?.[2]?.startsWith("=")?r[2].slice(1):void 0;return r?.[1]!==void 0&&o!==void 0?[[r[1],Ae(o,t)]]:[]})}function Pd(e){return _d.get(e)??Lb}function Bb(e,t){return[...t].reduce((n,r)=>n.slice(0,r.start)+" ".repeat(r.end-r.start)+n.slice(r.end),e)}function ii(e,t,n,r=Wb){return Object.freeze({status:e,source:t,program:n,assignmentFallbacks:Object.freeze(r)})}function an(e,t){return e.nodes.flatMap((n,r)=>$b(n,e,r,t)).sort((n,r)=>n.start-r.start).flatMap((n)=>[...n.events])}function $b(e,t,n,r){if(e.kind==="connector")return[{start:e.span.start,events:[tt(qb(e.operator))]}];if(e.kind==="unknown")return[{start:e.span.start,events:[tt(e.source)]}];if(e.kind==="function")return r.functions.set(e.name,e.body),[];if(e.kind==="group"){let i=e.style!=="subshell",s=r.source[e.span.end-1]===(i?"}":")"),a=i?r:{...r,functions:new Map(r.functions)};return[{start:e.span.start,events:i?[si("{"),...an(e.body,a),...s?[si("}")]:[]]:[kr,tt("("),...an(e.body,a),...s?[tt(")")]:[],Ir]}]}let o=Jb(e,r.functions);if(o){if(r.depth>=Ft.maxDepth||++r.flags.expansions>Fb)return r.flags.limited=!0,[];return[{start:e.span.start,events:[...Ed(e,r),si(";"),...an(o,{...r,depth:r.depth+1}),si(";")]},...xd(e,t,n,r)]}return[{start:e.span.start,events:Ed(e,r)},...xd(e,t,n,r)]}function Ed(e,t){return[...e.words.map((n)=>({start:n.span.start,events:kd(n,e,t,!1)})),...e.redirections.map((n)=>({start:n.span.start,events:Ub(n,e,t)}))].sort((n,r)=>n.start-r.start).flatMap((n)=>n.events)}function Ub(e,t,n){let r=e.operator==="<<-"?"<<":e.operator,o=e.target?kd(e.target,t,n,!0):[],i=o[0],s=i?.kind==="word"?i.text:void 0;return[...e.fd===void 0?[]:[xa(String(e.fd))],Object.freeze({kind:"redirection",operator:r,...e.fd===void 0?{}:{fd:e.fd},role:Yb(r),targetOrder:Ob.has(r)?"legacy-segment":"immediate",...s===void 0?{}:{target:s},...e.heredoc&&n.suppressed.has(e.heredoc.bodySpan)?{body:e.heredoc.body,consumer:Od(t)}:{}}),...s===void 0?o:o.slice(1)]}function xd(e,t,n,r){let o=e.redirections.filter((i)=>i.operator==="<<"||i.operator==="<<-");return[...o.flatMap((i)=>{let s=i.heredoc;if(!s)return[];let a=[xa(s.delimiter),.../[\r\n]/.test(r.source[s.terminatorSpan.end]??"")?[tt(";")]:[]];if(r.suppressed.has(s.bodySpan))return[{start:s.bodySpan.start,events:a}];return[{start:s.bodySpan.start,events:[...Td(r.source.slice(s.bodySpan.start,s.bodySpan.end),r),...a]}]}),...o.some((i)=>!i.heredoc&&i.target)?jb(t,n,r):[]]}function jb(e,t,n){let r=e.nodes.slice(t+1).find((o)=>o.kind==="connector");if(!r||r.span.end>=e.span.end)return[];return[{start:r.span.end,events:Td(n.source.slice(r.span.end,e.span.end),n)}]}function Td(e,t){if(t.depth>=Ft.maxDepth)return t.flags.limited=!0,[];let n=Je(e,"posix");if(n.status==="limited")return t.flags.limited=!0,[];let r={invalid:!1,limited:!1,expansions:t.flags.expansions,assignmentFallbacks:t.flags.assignmentFallbacks},o=an(n,{source:e,suppressed:new Set,flags:r,depth:t.depth+1,functions:new Map,powershell:!1});return t.flags.limited||=r.limited,t.flags.expansions=r.expansions,o}function kd(e,t,n,r){let o=[],i={single:!1,double:!1},s="",a=!1,l=()=>{let c=a&&!r?tt("glob"):s!==""||e.quoted&&o.length===0?xa(s):void 0;if(c)o.push(c);s="",a=!1};for(let c of e.parts){if(c.provenance!=="command-substitution"&&c.provenance!=="arithmetic"){for(let f of ba(c.raw,i,n.flags,n.powershell)){if(typeof f==="string"){l(),o.push(tt(f));continue}s+=f.text,a||=f.glob}continue}let u=t.nested.find((f)=>f.span.start>=c.span.start&&f.span.end<=c.span.end);if(i.double){let f=n.source.slice(c.span.start,c.span.end);s+=ba(f,{single:!1,double:!0},n.flags,n.powershell).map((g)=>typeof g==="string"?g:g.text).join("");let p=u?an(u,n).filter((g)=>g.kind==="redirection"&&g.body!==void 0):[];if(p.length>0)o.push(kr,...p,Ir);continue}let m=u?an(u,n):[];if(c.raw.startsWith("`")){s+="${}",l(),o.push(kr,...m,Ir);continue}if(c.raw.startsWith("<(")||c.raw.startsWith(">(")){l(),o.push(c.raw.startsWith("<(")?tt("<("):Object.freeze({kind:"redirection",operator:">",role:"file-write",targetOrder:"immediate"}),kr,...m,...c.raw.endsWith(")")?[tt(")")]:[],Ir);continue}let d=c.raw.startsWith("$((")?2:1;s+="${}",l(),o.push(...Array.from({length:d},()=>tt("(")),...d===1?[kr]:[],...m,...c.raw.endsWith(")".repeat(d))?Array.from({length:d},()=>tt(")")):[],...d===1?[Ir]:[])}return l(),o}function ba(e,t,n,r){let o=[],i="",s=!1,a=0;while(a<e.length){let l=e[a]??"";if(!t.single&&!t.double&&(l==="("||l===")")){o.push({text:i,glob:s},l),i="",s=!1,a++;continue}if(r&&l==="`"&&!t.single){i+=e[a+1]??"",a+=2;continue}if(t.single&&l==="'"){t.single=!1,a++;continue}if(t.single){i+=l,a++;continue}if(t.double){if(l==='"'){t.double=!1,a++;continue}if(!r&&l==="\\"){let c=e[a+1]??"";i+=['"',"\\","$"].includes(c)?c:`\\${c}`,a+=2;continue}if(l==="$"){let c=Rd(e,a,t,n,r);i+=c.text,a=c.next;continue}i+=l,a++;continue}if(l==="'"||l==='"'){t.single=l==="'",t.double=l==='"',a++;continue}if(!r&&l==="\\"){let c=e[a+1]??"";s||=c==="*"||c==="?",i+=c,a+=2;continue}if(l==="$"){let c=Rd(e,a,t,n,r);i+=c.text,a=c.next;continue}s||=l==="*"||l==="?",i+=l,a++}return[...o,{text:i,glob:s}]}function Rd(e,t,n,r,o){let i=e[t+1];if(i==="{"){let a=Kb(e,t+2);if(a===-1)return r.invalid=!0,{text:"",next:e.length};let l=e.slice(t,a+1);return Vb(l,n,r,o),{text:l,next:a+1}}if(i!==void 0&&Db.test(i))return{text:`\${${i}}`,next:t+2};let s=(o?Nb:/^\w*/).exec(e.slice(t+1))?.[0]??"";return{text:`\${${s}}`,next:t+1+s.length}}function Vb(e,t,n,r){let o=e.slice(2,-1),i=/^[A-Za-z_][A-Za-z0-9_]*/.exec(o)?.[0];if(!i)return;let s=o.slice(i.length),a=[":=","="].find((c)=>s.startsWith(c));if(!a)return;let l=ba(s.slice(a.length),{...t},n,r);n.assignmentFallbacks.push(...l.flatMap((c)=>typeof c==="string"||!c.text?[]:[c.text]))}function Kb(e,t){let n=1,r=t;while(n>0&&r<e.length){if(e[r]==="{"&&e[r-1]==="$")n++;if(e[r]==="}")n--;r++}return n===0?r-1:-1}function qb(e){return/^[\r\n]+$/.test(e)?";":e}function tt(e){return Object.freeze({kind:"operator",operator:e,boundary:Ib.has(e)})}function si(e){return Object.freeze({kind:"operator",operator:e,boundary:!0})}function xa(e){return Object.freeze({kind:"word",text:e})}function Yb(e){if(e==="<<"||e==="<<<")return"here-data";if(e==="<"||e==="<&")return"file-read";return"file-write"}function Dr(e){return Gb.has(e)||/^python\d/.test(e)}var Zb=new Map([["sudo",new Set(["-u","-g","-h","-p","-C","-D","-r","-t","-T","-U","--user","--group","--host","--prompt","--chdir","--role","--type","--other-user"])],["env",new Set(["-u","-C","-P","-S","--unset","--chdir","--split-string"])]]);function Id(e,t){let n=t[0];if(n===void 0||!n.startsWith("-"))return t;let r=Zb.get(e)?.has(n)??!1;return Id(e,t.slice(r?2:1))}function Sa(e){let t=e[0];if(t===void 0)return[];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(t))return Sa(e.slice(1));if(!kb.has(t))return[...e];return Sa(Id(t,e.slice(1)))}function Od(e){let t=Cr(e),n=e.words.findIndex((r)=>r.provenance==="literal"&&r.text===t);return Sa(n<0?[]:e.words.slice(n).map((r)=>r.text))}function Xb(e){let t=Od(e)[0];if(t===void 0)return!1;let n=k(t).toLowerCase();return Dr(n)&&!Or.has(n)}function va(e){return e.nodes.flatMap((t,n)=>{if(t.kind==="group"||t.kind==="function")return va(t.body);if(t.kind!=="command")return[];let r=t.nested.flatMap((a)=>va(a)),o=t.redirections.flatMap((a)=>a.heredoc?.quotedDelimiter?[a.heredoc.bodySpan]:[]);if(Xb(t))return[...r,...o];let i=e.nodes[n+1];if(i?.kind==="connector"&&(i.operator==="|"||i.operator==="|&")||!eS(t))return r;return[...r,...o]})}function Jb(e,t){let n=Cr(e);return n===void 0?void 0:t.get(n)}function Ut(e,t){return e!==void 0&&e.provenance==="literal"&&!e.quoted&&e.raw===e.text&&e.text===t}function Qb(e){if(Ut(e.words[0],"git"))return Ut(e.words[1],"commit");if(!Ut(e.words[0],"gh")||!Ut(e.words[2],"create"))return!1;return Ut(e.words[1],"pr")||Ut(e.words[1],"issue")}function eS(e){return(Ut(e.words[0],"cat")||Ut(e.words[0],"tee")||Qb(e))&&!e.words.some(wd)&&!e.redirections.some((n)=>wd(n.target))}function wd(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}var Md=new Set(["absolutepath","destination","directorypath","directory_path","file","file_path","filepath","include","notebook_path","path","paths","searchdirectory","search_directory","searchpath","targetfile","target_file"]),Dd=new Set([...Md,"glob"]),tS=new Set([...Dd,"pattern"]);class nt extends Error{name="StructuralShellSyntaxLimitError";constructor(){super("Structural command analysis limit exceeded.")}}function Nr(e){let t=nS(),n=Nt(e.input),r=[];if((e.route.kind==="command"||e.route.kind==="unknown")&&n)r.push({usage:"input-candidate",source:n});if(e.route.kind==="command"&&"command"in e&&e.command)r.push({usage:"declared-command",source:e.command});let o=r.reduce((i,s)=>{let a=i.findIndex((u)=>u.source===s.source);if(a!==-1){let u=i[a];if(!u)return i;return i[a]={...u,usages:[...u.usages,s.usage]},i}let l=e.route.kind==="command"?e.route.shell:process.platform==="win32"?"powershell":"posix",c=t.getCommandProgram(s.source,l);return i.push({usages:[s.usage],source:s.source,program:c,shell:t.getShellSyntax(s.source,c)}),i},[]);return{invocation:{toolName:e.toolName,route:e.route,context:e.context},commands:o,paths:rS(e),store:t}}function Pe(e,t){return e.commands.find((n)=>n.usages.includes(t))}function _t(e,t){if(!e.includes("$"))return e;return rs(e,t)}function nS(){let e=new Map,t=new Map,n=new WeakMap,r=(i,s)=>{let a=`${s}\x00${i}`,l=t.get(a);if(l)return l;let c=Je(i,s);return t.set(a,c),c};return{getShellSyntax:(i,s)=>{if(s&&s.source!==i)throw TypeError("Shell syntax source does not match command program source.");let a=s??r(i,"posix");if(a.status==="limited"){let u=n.get(a);if(u)return u;let m={status:"structural-limit",source:i,program:a,assignmentFallbacks:[]};return n.set(a,m),m}let l=e.get(i);if(l)return l;let c=Ad(i,a);return e.set(i,c),c},getCommandProgram:r}}function rS(e){let t=e.route.kind==="grep"?Dd:e.route.kind==="glob"?tS:Md;return[...co(e.input,t),...e.route.kind==="patch"||typeof e.input==="string"?uo(e.input):[]]}var oS=new Set(["-S","--suffix"]);function Gn(e,t,n,r,o){if(e.status==="structural-limit")throw new nt;if(e.status!=="complete")return o.findMalformedTarget(e.source);return ai(e,t,n,r,{segment:(i,s)=>o.findSegmentTarget(i,s),redirection:(i,s)=>i.role==="file-write"&&o.isRedirectionTarget(Ae(i.target,s.variables),s)?i.target:null})}function ci(e){let t=[],n=null,r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i===void 0)break;if(!r&&i==="--"){r=!0;continue}if(!r&&(i==="-t"||i==="--target-directory")){n=e[++o]??null;continue}if(!r&&i.startsWith("--target-directory=")){n=i.slice(19);continue}if(!r&&i.startsWith("-t")&&i.length>2){n=i.slice(2);continue}if(!r&&oS.has(i)){o++;continue}if(!r&&(i.startsWith("--suffix=")||i.startsWith("--backup=")))continue;if(!r&&i.startsWith("-"))continue;t.push(i)}return n?{sources:t,destination:n}:{sources:t.slice(0,-1),destination:t.at(-1)??null}}var je="Git metadata and hooks are protected. Ask the user before modifying them.";function Ld(e,t,n,r){let o=e.invocation.context.executionCwd;if(!t)return null;if(e.invocation.route.kind==="patch"||e.invocation.route.kind==="path"||e.invocation.route.kind==="unknown"){if(lo(e.invocation.toolName))return null;let a=e.paths.find((l)=>Nd(l,o,t,n,r,t.entries));return a?{target:a}:null}if(e.invocation.route.kind!=="command")return null;let i=Pe(e,"input-candidate");if(!i)return null;let s=Gn(i.shell,o,n,r,{findSegmentTarget:(a,l)=>uS(a,l,t,n,r),isRedirectionTarget:(a,l)=>Nd(a,l.cwd,t,n,r,t.markerFiles),findMalformedTarget:()=>null});return s?{target:s}:null}function ln(e,t,n,r,o,i,s=!1){if(!n)return!1;let a=mi(he(e,t,o,i)),l=a.replace(/(\/\.?\*+)+$/,"");if(l!==a&&l!==""){if(Ra(l,n))return!0;let c=s||a.slice(l.length).includes("/."),u=(m)=>c?ui(m,l):iS(m,l);if(n.markerFiles.some(u))return!0;return r&&wa(n).some(u)}if(Ra(a,n))return!0;return r&&wa(n).some((c)=>ui(c,a))}function iS(e,t){let n=mt.relative(t,e);if(n===""||n.startsWith("..")||mt.isAbsolute(n))return!1;return!n.split(/[\\/]/)[0]?.startsWith(".")}function sS(e,t,n,r,o){return ln(e,t,n,!0,r,o)}function aS(e,t,n,r,o){if(!n)return!1;return Ra(mi(he(e,t,r,o)),n)}function Nd(e,t,n,r,o,i){let s=mi(he(e,t,r,o));return i.includes(s)||Gd(s,n)}function Wd(e,t,n,r,o){if(!n)return!1;return n.hooksDirectories.some((i)=>e.some((s)=>ui(i,mi(he(s,t,r,o)))))}function Ra(e,t){return t.entries.includes(e)||t.directories.includes(e)||Gd(e,t)}function Gd(e,t){return t.hooksDirectories.some((n)=>ui(e,n))}var lS=50000;function Fd(e,t){let n=[...new Set(wa(e))];if(n.some((o)=>t(mt.basename(o))))return!0;let r=0;while(n.length>0){let o=n.pop()??"",i=cS(o);if(!i)return!0;if(r+=i.length,r>lS)return!0;if(i.some((s)=>t(s.name)))return!0;n.push(...i.filter((s)=>s.isDirectory()).map((s)=>mt.join(o,s.name)))}return!1}function cS(e){try{let t=di.lstatSync(e,{throwIfNoEntry:!1});if(!t)return[];if(!t.isDirectory())return t.isSymbolicLink()?null:[];return di.readdirSync(e,{withFileTypes:!0,encoding:"utf8"})}catch{return null}}function wa(e){return[...e.entries,...e.directories,...e.hooksDirectories]}function ui(e,t){let n=mt.relative(t,e);return n===""||!/^\.\.(?:[\\/]|$)/.test(n)&&!mt.isAbsolute(n)}function mi(e){return process.platform==="win32"?e.toLowerCase():e}function uS(e,t,n,r,o){if(Mr(e))return null;let i=$t([...e],r);if(k(i[0]??"").toLowerCase()!=="mv")return null;let s=ci(i.slice(1)),a=s.sources.find((l)=>sS(Ae(l,t.variables),t.cwd,n,r,o));if(a)return a;return s.destination&&aS(Ae(s.destination,t.variables),t.cwd,n,r,o)?s.destination:null}var q=require("node:path");var Fe=require("node:path"),dS=["/tmp","/var/tmp","/private/tmp","/private/var/tmp"],mS=`
|
|
30
|
+
`;function Lr(e,t){if(jt(e,t))return!0;if(!e.has("TMPDIR"))return!1;return!_a(e.get("TMPDIR")??"",t)}function cn(e,t){if(e.has("TMPDIR"))return _a(e.get("TMPDIR")??"",t);let n=Aa(e,t);if(n===void 0)return!0;return _a(n,t)}function Aa(e,t){return Bd(e,t,"TMPDIR")}function _a(e,t){if(!e)return!1;if(pS(e))return!1;return Fn(e,t)}function jt(e,t){let n=Bd(e,t,"IFS");return n!==void 0&&n!==""&&n!==mS}function Fn(e,t){let n=fi(e,t.paths);if(n===null)return!1;return Hd(t).some((r)=>zn(n,r))}function gi(e,t){let n=fi(e,t.paths);if(n===null)return!1;return Hd(t).some((r)=>pi(r)===pi(n))}var zd=new WeakMap;function Hd(e){let t=zd.get(e);if(t)return t;let n=fS(e);return zd.set(e,n),n}function fS(e){let t=dS.map((r)=>fi(r,e.paths)??Fe.normalize(r)),n=fi(e.tmpdir,e.paths);if(!n)return t;if(process.platform==="win32")return[...t,n];if(process.platform==="darwin"&&gS(n))return[...t,n];return t}function pS(e){return/[\s$`*?[]/.test(e)||/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(e)||/[+@!]\([^)]*\)/.test(e)}function Bd(e,t,n){return e.has(n)?e.get(n):t.env.get(n)}function gS(e){return/^\/(?:private\/)?var\/folders\/[^/]{2}\/[^/]+\/T$/.test(e)}function fi(e,t){try{let n=Fe.normalize(e);if(!Fe.isAbsolute(n))return n;let r=Fe.parse(n).root,o=n.slice(r.length).split(/[\\/]+/).filter(Boolean),i=r;for(let s=0;s<o.length;s++){let a=Fe.join(i,o[s]??"");if(t.entryKind(a)==="missing")return Fe.join(a,...o.slice(s+1));let l=t.realpath(a);if(l===null)return null;i=l}return i}catch{return null}}function zn(e,t){let n=pi(e),r=pi(t);if(n===r)return!0;let o=r.endsWith(Fe.sep)?r:`${r}${Fe.sep}`;return n.startsWith(o)}function pi(e){return process.platform==="win32"?e.toLowerCase():e}var hS=process.platform==="win32",$d=64,yS=16384;function Wr(e,t,n,r){if(e.kind==="temp_target")return null;let o=r[e.kind];if(e.kind==="dynamic_target"&&!me(n,o.id,t.strict))return null;if(e.kind==="within_anchored_cwd"&&!me(n,o.id,t.paranoid))return null;return v(o.id,o.reason)}function Gr(e){let t=Hu(e,$d,$d,yS);return{expandedTargets:t&&"words"in t?t.words:void 0,unsafeBraceExpansion:t!==void 0&&"limited"in t,targetIsLiteral:t===void 0&&e.provenance==="literal"&&(e.quoted||e.raw!==e.text),tmpdirWordSplittingProtected:CS(e)}}function CS(e){let t=e.parts.filter((n)=>n.provenance==="variable"&&/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(n.raw));return t.length>0&&t.every((n)=>bS(e.raw,n.span.start-e.span.start))}function bS(e,t){let n=null,r=!1;for(let o=0;o<t;o++){let i=e[o];if(r){r=!1;continue}if(i==="\\"&&n!=="'"){r=!0;continue}if(n===i){n=null;continue}if(n===null&&(i==="'"||i==='"'))n=i}return n==='"'}function Vt(e){let t=e.environment.home,n=e.environment.paths,r=e.budget??ue();return{anchoredCwd:e.originalCwd??e.cwd??null,resolvedCwd:e.cwd??null,strict:e.strict??!1,paranoid:e.paranoid??!1,trustTmpdirVar:e.allowTmpdirVar??!0,posixShell:e.posixShell??!1,tmpdirWordSplittingUnsafe:e.tmpdirWordSplittingUnsafe??!1,trustedTmpdirValue:e.trustedTmpdirValue??e.allowTmpdirVar??!0,environment:e.environment,allowRoots:wS(e.allowPaths,t,n,r),protectedGitMetadata:e.protectedGitMetadata,budget:r}}function rt(e,t,n={}){let r=n.targetIsLiteral??!1;if(!r&&t.tmpdirWordSplittingUnsafe&&!n.tmpdirWordSplittingProtected&&AS(e))return{kind:"outside_anchored_cwd"};let o=!r&&jd(e,t.posixShell);if(bt(e))return{kind:"outside_anchored_cwd"};if(Ta(e,r))return{kind:"root_or_home_target"};if(vS(e,t,r))return{kind:"root_or_home_target"};if(t.resolvedCwd&&ln(e,t.resolvedCwd,t.protectedGitMetadata,!0,t.environment,t.budget,!t.posixShell))return{kind:"git_metadata_target"};if(ES(e,t.trustTmpdirVar,t.posixShell,o,r,n.tmpdirWordSplittingProtected??!1,t.trustedTmpdirValue,t.environment))return{kind:"temp_target"};if(o)return{kind:"dynamic_target"};if(_S(e,t,r))return{kind:"temp_target"};let i=t.anchoredCwd;if(i){if(!n.skipHomeCwd&&IS(i,t.environment.home,t.environment.paths,t.budget))return{kind:"home_cwd_target"};if(!n.skipCwdSelf&&[t.resolvedCwd??i,i].some((s)=>OS(e,t.resolvedCwd??i,t.environment.paths,t.budget,s)))return{kind:"cwd_self_target"};if(MS(e,i,t.resolvedCwd??i,o,r,t.environment.paths,t.budget))return{kind:"within_anchored_cwd"}}if(SS(e,t,o))return{kind:"temp_target"};return{kind:"outside_anchored_cwd"}}function SS(e,t,n){let r=e.trim();if(n||!t.resolvedCwd||!t.anchoredCwd||!r)return!1;if(q.isAbsolute(r)||r.startsWith("~"))return!1;if(ka(r))return!1;if(Vd(t.resolvedCwd,t.anchoredCwd,t.environment.paths,t.budget))return!1;return Fn(q.resolve(t.resolvedCwd,r),t.environment)}function Ud(e,t,n={}){let{containmentTarget:r,...o}=n;if(rt(e,t,o).kind!=="temp_target")return!1;let i=e.trim();if(RS(i))return!1;if(gi(i,t.environment))return!1;return![t.anchoredCwd,t.resolvedCwd].some((s)=>Vd(r??i,s,t.environment.paths,t.budget))}function Ta(e,t=!1){let n=e.trim(),r=q.posix.normalize(n),o=n.replace(/\\/g,"/"),i=r==="/"?r:r.replace(/\/+$/,"");if(i==="/"||i.startsWith("/")&&i.slice(1).split("/").every((s)=>/^\*+$/.test(s)))return!0;if(/^[A-Za-z]:\/+\*?$/.test(o)||/^\/\/[^/]+\/+[^/]+(?:\/+\*?)?$/.test(o))return!0;if(!t&&(r==="~"||r==="~/"||r==="~/*"))return!0;if(!t&&(r==="$HOME"||r==="$HOME/"||r==="$HOME/*"))return!0;if(!t&&(r==="${HOME}"||r==="${HOME}/"||r==="${HOME}/*"))return!0;return!1}function vS(e,t,n){let r=e.trim(),o=n?r:r==="*"?".":r.endsWith("/*")?r.slice(0,-2):r;if(!o)return!1;try{let i=q.isAbsolute(o)?o:t.resolvedCwd?q.resolve(t.resolvedCwd,o):null;if(!i)return!1;let s=Te(O(i,t.environment.paths,t.budget));if(s===q.parse(s).root)return!0;return s===Te(O(t.environment.home,t.environment.paths,t.budget))}catch{return!1}}function Te(e){let t=q.normalize(e);if(hS){if(t=t.replace(/\//g,"\\").toLowerCase(),t.length>3&&t.endsWith("\\"))t=t.slice(0,-1);return t}if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);return t}function ES(e,t,n,r,o,i,s,a){let l=e.trim();if(ka(l))return!1;if(!r&&Fn(l,a))return!0;return(t||i&&s)&&n&&!o&&xS(l,n)}function xS(e,t){return["$TMPDIR","${TMPDIR}"].some((n)=>{if(e===n)return!0;if(!e.startsWith(`${n}/`))return!1;return!jd(e.slice(n.length+1),t)})}function RS(e){let t=/^(?:\$TMPDIR|\$\{TMPDIR\})(?:\/(.*))?$/.exec(e);if(!t)return!1;return q.posix.normalize(`/${t[1]??""}`)==="/"}function ka(e){return e.split(/[\\/]+/).includes("..")}function wS(e,t,n,r){if(!e?.length)return[];return e.flatMap((o)=>{let i=gr(o.trim(),t);if(!q.isAbsolute(i))return[];try{let s=O(i,n,r);if(hr(s,O(t,n,r)))return[];return[Te(s)]}catch{return[]}})}function _S(e,t,n){if(t.allowRoots.length===0)return!1;let r=e.trim();if(ka(r))return!1;let o=n?r:gr(r,t.environment.home),i=t.resolvedCwd??t.anchoredCwd,s=q.isAbsolute(o)?o:i?q.resolve(i,o):null;if(!s)return!1;try{let a=Te(O(s,t.environment.paths,t.budget));return t.allowRoots.some((l)=>a===l||a.startsWith(l.endsWith(q.sep)?l:`${l}${q.sep}`))}catch{return!1}}function AS(e){return/\$(?:TMPDIR(?![A-Za-z0-9_])|\{TMPDIR\})/.test(e)}function jd(e,t=!1){return e.includes("$")||e.includes("`")||PS(e)||t&&TS(e)}function PS(e){let t=!1;for(let n of e){if(t){t=!1;continue}if(n==="\\"){t=!0;continue}if(n==="*"||n==="?"||n==="[")return!0}return!1}function TS(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(t){t=!1;continue}if(r==="\\"){t=!0;continue}if(r==="{"&&kS(e,n)||(r==="+"||r==="@"||r==="!")&&e[n+1]==="(")return!0}return!1}function kS(e,t){let n=e.indexOf("}",t+1);if(n===-1)return!1;let r=e.slice(t+1,n);return r.includes(",")||r.includes("..")}function IS(e,t,n,r){try{return Te(O(e,n,r))===Te(O(t,n,r))}catch{try{return Te(e)===Te(t)}catch{return!1}}}function OS(e,t,n,r,o=t){if(o===t&&(e==="."||e==="./"||e===".\\"))return!0;try{return Te(O(q.resolve(t,e),n,r))===Te(O(o,n,r))}catch{try{return Te(q.resolve(t,e))===Te(o)}catch{return!1}}}function MS(e,t,n,r,o,i,s){let a=n??t;if(!o&&(e.startsWith("~")||e.startsWith("$HOME")||e.startsWith("${HOME}")))return!1;if(r)return!1;if(e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e))try{return Pa(e,t,i,s)}catch{return!1}if(e.startsWith("./")||e.startsWith(".\\")||!e.includes("/")&&!e.includes("\\"))try{return Pa(q.resolve(a,e),t,i,s)}catch{return!1}if(e.startsWith("../"))return!1;try{return Pa(q.resolve(a,e),t,i,s)}catch{return!1}}function Pa(e,t,n,r){try{return Kd(O(e,n,r),O(t,n,r))}catch{return!1}}function Vd(e,t,n,r){if(!t)return!1;try{return Kd(O(t,n,r),O(e,n,r))}catch{return!0}}function Kd(e,t){let n=Te(e),r=Te(t);return n.startsWith(`${r}${q.sep}`)||n===r}var DS=new Set(["remove-item","ri","del","erase","rd","rm","rmdir"]),qd="PowerShell Remove-Item -Recurse -Force outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",NS="PowerShell Remove-Item -Recurse -Force for non-temporary paths is blocked by the active safety policy. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",Yd="PowerShell Remove-Item target contains variables or pipeline input that cannot be verified safely. Use literal paths within cwd.",Zd="PowerShell Remove-Item targeting root or home directory is extremely dangerous and always blocked.",LS="PowerShell Remove-Item -Recurse -Force in home directory is dangerous. Change to a project directory first.",WS="PowerShell Remove-Item receives pipeline input that cannot be verified safely. Use explicit literal paths within cwd.",GS={root_or_home_target:{id:"powershell.remove-item-recursive-force-root-or-home",reason:Zd},git_metadata_target:{id:"powershell.remove-item-git-metadata",reason:je},dynamic_target:{id:"powershell.remove-item-recursive-force-dynamic-target",reason:Yd},home_cwd_target:{id:"powershell.remove-item-recursive-force-home-cwd",reason:LS},cwd_self_target:{id:"powershell.remove-item-recursive-force-cwd-self",reason:qd},within_anchored_cwd:{id:"powershell.remove-item-recursive-force-paranoid",reason:NS},outside_anchored_cwd:{id:"powershell.remove-item-recursive-force-outside-cwd",reason:qd}};function Xd(e,t,n,r=Vt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths})){return FS(e.words.map((o)=>({kind:"word",text:o.text,dynamic:o.provenance!=="literal"})),t,r,n.policy)}function FS(e,t,n,r){let o=e.filter((l)=>l.kind==="word"),i=HS(o),s=o[i];if(!s||!DS.has(ZS(s.text)))return null;let a=zS(o.slice(i+1));if(a.whatIfProtected)return null;if(me(r,"powershell.remove-item-pipeline-dynamic-target",n.strict)&&t&&(a.targets.length===0||a.recursive))return v("powershell.remove-item-pipeline-dynamic-target",WS);for(let l of a.targets)if(!bt(l.text)&&Ta(Oa(l.text)))return v(a.recursive&&a.force?"powershell.remove-item-recursive-force-root-or-home":"powershell.remove-item-root-or-home",Zd);for(let l of a.targets)if(n.resolvedCwd&&ln(Oa(l.text),n.resolvedCwd,n.protectedGitMetadata,a.recursive,n.environment,n.budget,!0))return v("powershell.remove-item-git-metadata",je);if(!a.recursive||!a.force)return null;if(me(r,"powershell.remove-item-recursive-force-dynamic-target",n.strict)&&(a.hasDynamicTarget||a.targets.length===0))return v("powershell.remove-item-recursive-force-dynamic-target",Yd);for(let l of a.targets){let c=Wr(rt(Oa(l.text),n),n,r,GS);if(c)return c}return null}function zS(e){let t=[],n=!1,r=!1,o=!1,i=!1,s=!1;for(let a=0;a<e.length;a++){let l=e[a];if(!l||l.kind!=="word")continue;if(BS(l))continue;if(s){t.push(Ia(l)),i=i||l.dynamic;continue}if(l.text==="--"){s=!0;continue}let c=US(l.text);if(!c){t.push(Ia(l)),i=i||l.dynamic;continue}if(jS(c.name)){let u=c.value?$S(c.value,l):e[++a];if(u?.kind==="word"){t.push(Ia(u)),i=i||u.dynamic;continue}i=!0;continue}if(VS(c.name)){n=!0;continue}if(KS(c.name)){r=!0;continue}if(qS(c.name))o=YS(c.value)}return{targets:t,recursive:n,force:r,whatIfProtected:o,hasDynamicTarget:i}}function HS(e){let t=e[0];if(t?.kind==="word"&&t.text==="&"||t?.text===".")return e.length>1?1:0;return 0}function Ia(e){return{text:e.kind==="word"?e.text:"",dynamic:e.kind==="word"&&e.dynamic}}function BS(e){return e.kind==="word"&&e.text===","}function Oa(e){let t=e.replace(/\\/g,"/"),n=/^\$env:(?:userprofile|home)(?=$|\/)/i.exec(t);return n?`$HOME${t.slice(n[0].length)}`:t}function $S(e,t){return{kind:"word",text:e,dynamic:t.kind==="word"&&(t.dynamic||e.includes("$"))}}function US(e){if(!e.startsWith("-")||e==="-")return null;let t=e.slice(1),n=t.indexOf(":");if(n===-1)return{name:t.toLowerCase()};return{name:t.slice(0,n).toLowerCase(),value:t.slice(n+1)}}function jS(e){return"path".startsWith(e)||"literalpath".startsWith(e)}function VS(e){return"recurse".startsWith(e)}function KS(e){return e.length>=2&&"force".startsWith(e)}function qS(e){return e==="wi"||"whatif".startsWith(e)}function YS(e){if(e===void 0||e==="")return!0;let t=e.toLowerCase();return t==="$true"||t==="true"}function ZS(e){return e.toLowerCase()}var Hn="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",hi="Unsupported heredoc syntax",Fr="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.",Jd="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.";var XS=new Set(["--ca-bundle","--cli-binary-format","--cli-connect-timeout","--cli-error-format","--cli-read-timeout","--color","--endpoint-url","--output","--profile","--query","--region"]),JS=new Set(["--access-token-file","--account","--billing-project","--configuration","--flags-file","--flatten","--format","--impersonate-service-account","--project","--trace-token","--verbosity"]),QS=new Set(["-o","--output","--query","--subscription"]),ev=new Set;function Qd(e){if(e==="aws")return XS;if(e==="gcloud")return JS;if(e==="az")return QS;return ev}var tv=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),nv=new Set;function em(e){if(e==="git")return De;if(e==="docker")return tv;return nv}function At(e,t){if(e.length===0||t.length===0)return null;let n=M(e[0]??""),r=we(e);for(let o of t){if(!iv(n,o.command))continue;if(o.match){if(rv(n,e,o.match))return tm(o);continue}if(!sv(n,e,o.subcommand))continue;if(lv(e,new Set(o.block_args),r))return tm(o)}return null}function tm(e){return{id:`custom.${e.name}`,reason:`[${e.name}] ${e.reason}`,intent:e.intent??"manual_only"}}function rv(e,t,n){let r=t.slice(1);if(n.exclude_args?.some((o)=>r.includes(o)))return!1;if(n.any_args&&!n.any_args.some((o)=>r.includes(o)))return!1;return ov(r,n.command_path,Qd(e))}function ov(e,t,n){let r=0,o=!1;for(let i of e){if(r>=t.length)return!0;if(o){o=!1;continue}if(i.startsWith("-")){o=!i.includes("=")&&n.has(i);continue}if(i!==t[r])return!1;r++}return r>=t.length}function iv(e,t){return e===M(t)}function sv(e,t,n){if(!n)return!0;return nm(t,1,n,em(e))}function nm(e,t,n,r){let o=!1;for(let i=t;i<e.length;i++){let s=e[i];if(!s)continue;if(o){o=!1;continue}if(s==="--"){let a=e[i+1];if(a&&!a.startsWith("-"))return a===n;return!1}if(r.has(s)){o=!0;continue}if(s.startsWith("-")){if(!s.includes("=")&&av(e,i,n,r))return!0;continue}return s===n}return!1}function av(e,t,n,r){let o=e[t+1];if(!o||o.startsWith("-"))return!1;return nm(e,t+2,n,r)}function lv(e,t,n){return e.some((r)=>t.has(r))||[...n].some((r)=>t.has(r))}var cv=new Set(["-e","--source"]),uv=new Set(["-F","-v","--assign","--field-separator"]),rm=new Set(["-f","--file"]),dv=new Set(["print","printf","return"]),om=[{selector:"-e",kind:"inline-code",valueForm:"attached-or-separate"},{selector:"--source",kind:"inline-code",valueForm:"equals-or-separate"},{selector:"-f",kind:"program-file",valueForm:"attached-or-separate"},{selector:"--file",kind:"program-file",valueForm:"equals-or-separate"}],mv="Detected awk system(), pipe, or getline command with dynamic command that cannot be safely analyzed. Use a literal command or process the data without system(), pipes, or getline.";function im(e,t,n){let r=!1;for(let o of fv(e)){let i=pv(o,n);if(!i)continue;for(let s of i.commands){let a=t(s);if(a)return a;if(s.includes("{}")||/[$`]/.test(s))r=!0}r||=i.dynamic}return r?v("awk.system-dynamic",mv):null}function Da(e){let t=[],n=!1,r=!1,o=!0,i=!0;for(let s=1;s<e.length;s++){let a=e[s];if(a===void 0)break;if(o&&a==="--"){o=!1;continue}if(o&&cv.has(a)){n=!0;let l=e[s+1];if(i&&=l!==void 0,l!==void 0)t.push({tokenIndex:s+1,kind:"inline-code",value:l});s++;continue}if(o&&a.startsWith("--source=")){n=!0,t.push({tokenIndex:s,kind:"inline-code",value:a.slice(9)});continue}if(o&&a.startsWith("-e")&&a.length>2){n=!0,t.push({tokenIndex:s,kind:"inline-code",value:a.slice(2)});continue}if(o&&(uv.has(a)||rm.has(a))){let l=e[s+1];if(i&&=l!==void 0,rm.has(a)){if(r=!0,l!==void 0)t.push({tokenIndex:s+1,kind:"program-file",value:l})}s++;continue}if(o&&(a.startsWith("-F")||a.startsWith("-v")&&a.slice(2).includes("=")))continue;if(o&&a.startsWith("-f")&&a.length>2){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(2)});continue}if(o&&(a.startsWith("--assign=")||a.startsWith("--field-separator=")))continue;if(o&&a.startsWith("--file=")){r=!0,t.push({tokenIndex:s,kind:"program-file",value:a.slice(7)});continue}if(o&&a.startsWith("-")&&a!=="-")continue;if(!n&&!r)t.push({tokenIndex:s,kind:"main-program",value:a});return{sources:t,optionsOpen:!1}}return{sources:i?t:[],optionsOpen:o&&i}}function Hr(e){return Da(e).sources}function fv(e){return Hr(e).filter((t)=>t.kind!=="program-file").map((t)=>t.value)}function pv(e,t){Ge(t,e);let n=e.includes("system")?Na(e,t):null,r=gv(e,t);if(!n&&!r)return null;return{dynamic:!!n?.dynamic||!!r?.dynamic,commands:[...n?.commands??[],...r?.commands??[]]}}function Na(e,t){Ge(t,e);let n=[],r=!1,o=!1,i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){i=Ci(e,i,s)?.endIndex??i+1;continue}if(s==="#"){i=sm(e,i+1);continue}if(s==="/"&&am(e,i)){i=lm(e,i+1)??i+1;continue}if(!e.startsWith("system",i)){i++;continue}let a=i;if(i+=6,zr(e[a-1])||zr(e[i]))continue;let l=yi(e,i);if(e[l]!=="(")continue;l=yi(e,l+1);let c=e[l];if(c!=='"'&&c!=="'"){r=!0,o=!0;continue}let u=Ci(e,l,c);if(!u){r=!0,o=!0;continue}if(l=yi(e,u.endIndex),r=!0,e[l]!==")"){o=!0,i=u.endIndex;continue}n.push(u.value),i=l+1}if(!r)return null;return{dynamic:o,commands:n}}function gv(e,t){Ge(t,e);let n=[],r=!1,o=!1,i=0,s=0,a=null,l=null,c=0;while(i<e.length){let u=e[i];if(!u)break;if(u==='"'||u==="'"){let f=Ci(e,i,u);if(f&&c===s)l={...f,startIndex:i};c=f?.endIndex??i+1,i=f?.endIndex??i+1;continue}if(u==="#"){i=sm(e,i+1),s=i,a=null,l=null,c=i;continue}if(u==="/"&&am(e,i)){let f=lm(e,i+1);c=f??i+1,i=f??i+1;continue}if(`;
|
|
31
|
+
{}`.includes(u)){i++,s=i,a=null,l=null,c=i;continue}if(a===null&&(Ma(e,i,"print")||Ma(e,i,"printf")))a=i;if(u!=="|"||e[i-1]==="|"||e[i+1]==="|"){if(!/\s/.test(u))c=i+1;i++;continue}let m=e[i+1]==="&"?i+2:i+1,d=yi(e,m);if(Ma(e,d,"getline")){o=!0;let f=Cv(s,l,c);if(r||=f===null,f!==null)n.push(f);c=m,i=m;continue}if(Sv(s,a)){o=!0;let f=yv(e,d);if(!f){r=!0,c=m,i=m;continue}if(!hv(e,f.endIndex)){r=!0,c=f.endIndex,i=f.endIndex;continue}n.push(f.value),c=f.endIndex,i=f.endIndex;continue}c=m,i++}if(!o)return null;return{dynamic:r,commands:n}}function zr(e){return!!e&&/[A-Za-z0-9_]/.test(e)}function yi(e,t){let n=t;while(/\s/.test(e[n]??""))n++;return n}function hv(e,t){let n=t;while(/[\t\f\v\r ]/.test(e[n]??""))n++;let r=e[n];return!r||`;
|
|
32
|
+
}#`.includes(r)}function Ci(e,t,n){let r="",o=!1;for(let i=t+1;i<e.length;i++){let s=e[i];if(!s)break;if(o){let a=bv(e,i);if(!a)return null;r+=a.value,i=a.endIndex,o=!1;continue}if(s==="\\"){o=!0;continue}if(s===n)return{value:r,endIndex:i+1};r+=s}return null}function yv(e,t){let n=e[t];if(n!=='"'&&n!=="'")return null;return Ci(e,t,n)}function Cv(e,t,n){if(!t)return null;return t.startIndex>=e&&t.endIndex===n?t.value:null}function bv(e,t){let n=e[t];if(!n)return null;if(n==="x"){let o=e.slice(t+1,t+3);if(!/^[0-9A-Fa-f]{2}$/.test(o))return null;return{value:String.fromCharCode(Number.parseInt(o,16)),endIndex:t+2}}if(/[0-7]/.test(n)){let o=/^[0-7]{1,3}/.exec(e.slice(t));if(!o)return null;return{value:String.fromCharCode(Number.parseInt(o[0],8)),endIndex:t+o[0].length-1}}return{value:{a:"\x07",b:"\b",f:"\f",n:`
|
|
33
|
+
`,r:"\r",t:"\t",v:"\v"}[n]??n,endIndex:t}}function Ma(e,t,n){return e.startsWith(n,t)&&!zr(e[t-1])&&!zr(e[t+n.length])}function Sv(e,t){return t!==null&&t>=e}function sm(e,t){let n=e.indexOf(`
|
|
34
|
+
`,t);return n===-1?e.length:n+1}function am(e,t){let n=vv(e,t);if(n===-1)return!0;if("{([,;!~=".includes(e[n]??""))return!0;let r=n;while(zr(e[r-1]))r--;return dv.has(e.slice(r,n+1))}function vv(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function lm(e,t){let n=!1;for(let r=t;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="/")return r+1}return null}var Ev=new Set(["sudo","env","command","builtin"]);function bi(e,t){let n=e[0];if(!n||!t.transparentWrappers.includes(k(n)))return null;let r=k(n),o=e[1]==="--"?2:1,i=xv(e,o,r,t),s=i[0];if(s===void 0)return null;return{wrapper:r,tokens:e.slice(s),childIndex:s,alternativeChildIndices:i.slice(1)}}function xv(e,t,n,r){let o=e[1]==="--",i=[];for(let s=t;s<e.length;s++){let a=e[s];if(!a)continue;let l=k(a)!==n&&Rv(a,r);if(l)i.push(s);if(!l&&Eo.has(M(a)))break;if(o)break}return i}function Rv(e,t){let n=k(e),r=M(e);return r==="git"||n==="busybox"||un(e)||xs.has(n)||t.transparentWrappers.includes(n)||Q.has(r)||e==="$SHELL"||Xe(r)||Be.has(r)||t.rules.some((o)=>o.command===n)}function un(e){return Ev.has(e.toLowerCase())}function dn(e,t){return{embedded:!1,cwd:e.cwd,originalCwd:t.originalCwd,effectiveCwd:e.cwd,envAssignments:e.envAssignments,allowTmpdirVar:t.allowTmpdirVar,worktreeMode:t.worktreeMode,wrappedByTransparent:!1}}function ot(e,t){let n=t.policy??{rules:[],transparentWrappers:[]};return Si([...e],t.environment,t.cwd,t.cwd,new Map,new Map(t.envAssignments??[]),n,{iterations:0},!1)}function*Si(e,t,n,r,o,i,s,a,l){let c=oi(e,t,n,i);for(let[f,p]of c.envAssignments)i.set(f,p),o.set(f,p);let{tokens:u,cwd:m}=c;if(c.envSplitValues){let f=ri(c.envSplitValues,u);if(!f)throw new N("derivedCommandShape");La(a),yield*Si(f,t,m,r,o,i,s,a,l);return}if(un(u[0]??""))throw new N("wrapperPeelIterations");let d=bi(u,s);if(d){for(let f of[d.childIndex,...d.alternativeChildIndices])La(a),yield*Si(f===d.childIndex?d.tokens:u.slice(f),t,m,r,new Map(o),new Map(i),s,a,!0);return}if(_v(u)){La(a),yield*Si(u.slice(1),t,m,r,o,i,s,a,l);return}yield wv(u,m,r,o,i,l)}function wv(e,t,n,r,o,i){return{tokens:e,cwd:t===null?void 0:t??n,wrapperCwd:t,wrapperEnvAssignments:r,envAssignments:o,head:k(e[0]??"").toLowerCase(),wrappedByTransparent:i}}function La(e){if(e.iterations>=X.wrapperPeelIterations.cap)throw new N("wrapperPeelIterations");e.iterations++}function _v(e){return k(e[0]??"").toLowerCase()==="busybox"&&e.length>1}function Wa(e,t){let n=[],r=t;while(r<e.length){let o=e[r];if(o===void 0||o===":::")break;n.push(o),r++}return{markerIndex:r<e.length&&e[r]===":::"?r:-1,templateTokens:n}}function it(e){let t=!1,n=!1;for(let r of e){if(r==="--")break;if(r==="-r"||r==="-R"||Ga(r,"recursive")){t=!0;continue}if(r==="-f"||Ga(r,"force")){n=!0;continue}if(r.startsWith("-")&&!r.startsWith("--")){if(r.includes("r")||r.includes("R"))t=!0;if(r.includes("f"))n=!0}}return t&&n}function vi(e){let t=e.indexOf("--");return e.slice(1,t===-1?void 0:t).some((n)=>Ga(n,"recursive")||/^-[A-Za-z]+$/.test(n)&&/[rR]/.test(n.slice(1)))}function Ga(e,t){return e.length>2&&e.startsWith("--")&&t.startsWith(e.slice(2))}var Av=["--init-file","--rcfile"],Pv=new Map([["bash","BASH_ENV"],["dash","ENV"],["ksh","ENV"],["sh","ENV"]]);function st(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n)continue;if(n==="-c")return cm(e,t,!0);if(n.startsWith("-")&&n.includes("c")&&!n.startsWith("--")){let r=cm(e,t,!1);if(r!==null)return r}}return null}function Pt(e){let t=k(e[0]??"").toLowerCase();if(t==="zsh"||t==="ksh")return Ne(e).syntaxCheck;let n=!1;for(let r of e.slice(1)){if(r==="--")return n;if(r.startsWith("+")&&!r.startsWith("++")){if(r.slice(1).includes("n"))n=!1;continue}if(!r.startsWith("-")||r.startsWith("--"))return n;let o=r.slice(1);if(o.includes("n"))n=!0;if(o.includes("c"))return n}return n}function cm(e,t,n){if(e[t+1]==="--")return e[t+2]||null;let r=e[t+1];if(!r||!n&&r.startsWith("-"))return null;return r}function um(e){let t=k(e[0]??"").toLowerCase(),n=Tv(e,t),r=Pv.get(t)??null,o=n.argvSource?.kind!=="absent";return{argvSource:t==="bash"?n.argvSource:null,argvSourceApplies:t==="bash"&&n.interactive&&n.argvSource?.kind==="literal",envName:r,envSourceApplies:o&&(r==="BASH_ENV"?!n.interactive:r==="ENV"&&n.interactive)}}function Tv(e,t){let n=Ne(e),r=n.commandIndex??n.scriptIndex??e.length,o=[],i=!1,s=!0;for(let a=1;a<r;a++){let l=e[a];if(l===void 0||l==="--"||l==="-"||l[0]!=="-"&&l[0]!=="+")break;if(l.startsWith("--")){if(t==="bash"&&s?Av.find((d)=>l===d):void 0){let d=e[a+1];o.push(d===void 0?{kind:"absent"}:{kind:"literal",value:d}),a++;continue}let m=l.split("=",1)[0]??l;if(t==="bash"&&vs.has(m)&&!l.includes("="))a++;continue}if(t==="bash")s=!1;let c=Es(t,l,e[a+1],"startup");if(c.interactive)i=l[0]==="-";a+=c.followingValues}return{argvSource:o.at(-1)??null,interactive:i}}var kv="find -delete permanently removes files. Use -print first to preview.",Iv="find -exec rm -rf is dangerous. Use explicit file list instead.",Ov=new Set(["-exec","-execdir","-ok","-okdir"]),Mv=new Map([...["-Bmin","-Bnewer","-Btime","-amin","-anewer","-atime","-cmin","-cnewer","-context","-ctime","-f","-flags","-fprint","-fprint0","-fls","-fstype","-gid","-group","-ilname","-iname","-inum","-ipath","-iwholename","-iregex","-links","-lname","-maxdepth","-mindepth","-mmin","-mnewer","-mtime","-name","-newer","-newerXY","-newermt","-path","-perm","-printf","-regex","-samefile","-size","-type","-uid","-used","-user","-wholename","-xattrname","-xtype"].map((e)=>[e,1]),["-fprintf",2]]);function dm(e,t){let n=e.map(_),r=Dv(e,n,t);if(r)return r;if(Ei(n,1)&&!zv(e,n,t)){let s=T(v("find.delete",kv),t.policy);if(s)return s}let o=t.budget??ue(),i=0;while(i<n.length){let s=n[i],a=Tt(s??"");if(a>0){i+=a+1;continue}if(!ft(s)){i++;continue}o.charge("derivedTokens",n.length-i-1);let l=Bn(n,i);i=l.nextIndex;let c=Bv(l.tokens,t.environment);if(c){let f=T(c,t.policy);if(f)return f}let u=s==="-execdir"||s==="-okdir",m=t.analyzeTokens?t.analyzeTokens(l.tokens,u?null:t.cwd):t.analyzeNested?t.analyzeNested(l.tokens.join(" "),{effectiveCwd:u?void 0:t.cwd,envAssignments:t.envAssignments}):null,d=m?.id.startsWith("custom.")?m:T(m,t.policy);if(d)return d}return null}function Dv(e,t,n){if(!Ei(t,1)&&!Fa(t,n.environment))return null;let o=Br(e)??J(["."]),i=Vt({...n,allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0});for(let s of o){let a=Gr(s);for(let l of a.expandedTargets??[_(s)]){let c=rt(l,i,{targetIsLiteral:a.expandedTargets!==void 0||a.targetIsLiteral,tmpdirWordSplittingProtected:a.tmpdirWordSplittingProtected});if(c.kind==="root_or_home_target")return v("rm.recursive-force-root-or-home","rm -rf targeting root or home directory is extremely dangerous and always blocked.");if(c.kind==="git_metadata_target"&&!Nv(e,i.protectedGitMetadata,n.environment))return v("find.delete-git-metadata",je)}}if(Fv(t)&&i.resolvedCwd&&Wd(o.map(_),i.resolvedCwd,i.protectedGitMetadata,i.environment,i.budget))return v("find.delete-git-metadata",je);return null}function Nv(e,t,n){if(!t)return!1;let r=e.map(_),o=[],i=!1,s=Br(e)?.at(-1),a=s?e.indexOf(s)+1:1;while(a<r.length){let l=r[a]??"";if(ft(l)){let c=Bn(r,a),u=$t([...c.tokens],n),m=vi(u),d=Q.has(k(u[0]??"").toLowerCase()),f=c.tokens.some((g)=>g!=="{}"&&g.includes("{}")),p=(l==="-execdir"||l==="-okdir")&&u.slice(1).some((g)=>g!=="{}"&&!g.startsWith("-"));if(m||d||f||p)return!1;i=!0,a=c.nextIndex;continue}if(l==="-delete"){i=!0,a++;continue}if(l==="-name"||l==="-iname"){let c=e[a+1];if(!(c?.provenance==="literal"&&!/[[\\]/.test(c.text)))return!1;if(!i)o.push(Wv(c.text,l==="-iname"));a+=2;continue}if(!Lv.has(l))return!1;a+=1+Tt(l)}return o.length>0&&!Fd(t,(l)=>o.every((c)=>c.test(l)))}var Lv=new Set(["-a","-and","-depth","-maxdepth","-mindepth","-mmin","-mtime","-newer","-size","-type"]);function Wv(e,t){let n=e.replace(/[*?]|[.+^${}()|\]/]/g,(r)=>r==="*"?".*":r==="?"?".":`\\${r}`);return new RegExp(`^${n}$`,t?"isu":"su")}var Gv=/(?:^|[\s;&|(`{])\\?(?:\S*\/)?rm(?:dir)?(?=[\s;&|)`}]|$)/;function Fa(e,t){let n=0;while(n<e.length){if(!ft(e[n])){n++;continue}let r=Bn(e,n),o=$t([...r.tokens],t),i=k(o[0]??"").toLowerCase(),s=Q.has(i)&&Gv.test((st(o)??"").replace(/["'\\]/g,""));if((i==="rm"||i==="rmdir"||s)&&o.some((l)=>l.includes("{}")))return!0;n=r.nextIndex}return!1}function Fv(e){return e.some((t,n)=>{if(!["-name","-iname"].includes(t))return!1;return e[n+1]?.toLowerCase()==="hooks"})}function zv(e,t,n){if(t.includes("-L")||t.includes("-f")||t.includes("-follow"))return!1;let r=Br(e);if(!r)return!1;let o=n.envAssignments??new Map,i=Aa(o,n.environment),s=n.trustedTmpdirValue??cn(o,n.environment),a=n.allowTmpdirVar??!Lr(o,n.environment),l={environment:n.environment,protectedGitMetadata:n.protectedGitMetadata,cwd:n.cwd,originalCwd:n.originalCwd,strict:n.strict,allowTmpdirVar:a&&s&&Boolean(i),allowPaths:n.policy?.destructiveCommandAllowPaths,posixShell:!0,tmpdirWordSplittingUnsafe:n.tmpdirWordSplittingUnsafe??jt(o,n.environment),trustedTmpdirValue:s,budget:n.budget},c=Vt(l),u=Vt({...l,cwd:n.originalCwd??n.cwd}),m=n.originalCwd&&n.environment.paths.realpath(n.originalCwd),d=n.cwd&&n.environment.paths.realpath(n.cwd),f=m&&d&&!zn(d,m)?n.cwd:void 0;return r.every((p)=>{let g=Gr(p);if(g.unsafeBraceExpansion)return!1;return(g.expandedTargets??[_(p)]).every((h)=>{let y=/^\.\/*$/.test(h)?f:void 0,S=y??h;return Ud(S,y?u:c,{containmentTarget:Hv(S,i),targetIsLiteral:g.expandedTargets!==void 0||g.targetIsLiteral,tmpdirWordSplittingProtected:g.tmpdirWordSplittingProtected})})})}function Hv(e,t){if(!t)return e;return e.replace(/^(?:\$TMPDIR|\$\{TMPDIR\})/,()=>t)}function Br(e){let t=(o)=>{let i=e[o];return i?_(i):void 0},n=1;while(t(n)==="-H"||t(n)==="-P")n++;if(t(n)==="--")n++;let r=[];while(n<e.length){let o=t(n),i=e[n];if(!o||!i||o.startsWith("-")||["!","(",")"].includes(o))break;r.push(i),n++}return r.length>0?r:null}function Bv(e,t){let n=Bt([...e],t);if(n.length===0)return null;let r=k(n[0]??"");if(r==="busybox"&&n.length>1)n=n.slice(1),r=k(n[0]??"");if(r==="rm"&&it(n))return v("find.exec-rm-recursive-force",Iv);return null}function Bn(e,t){let n=t+1;while(n<e.length&&e[n]!==";"&&!(e[n]==="+"&&e[n-1]==="{}"))n++;return{tokens:e.slice(t+1,n),nextIndex:Math.min(n+1,e.length)}}function Ei(e,t){let n=t;while(n<e.length){let r=e[n];if(!r){n++;continue}if(ft(r)){n=Bn(e,n).nextIndex;continue}let o=Tt(r);if(o>0){n+=o+1;continue}if(r==="-delete")return!0;n++}return!1}function Tt(e){return Mv.get(e)??(/^-newer[A-Za-z]{2}$/.test(e)?1:0)}function ft(e){return e!==void 0&&Ov.has(e)}var Nm=require("node:path");function $r(e){let t=Je(e,"posix");if(t.status!=="complete"||t.nodes.length!==1)return null;let n=t.nodes[0];if(n?.kind!=="command")return null;if(n.redirections.length>0||n.nested.length>0)return null;if(n.words.some((r)=>r.provenance==="command-substitution"))return null;return n.words.map((r)=>r.text)}var $v=5,za="Git aliases supplied through command-line or environment config can hide or execute commands. Run git without Git alias overrides, or ask the user to run it manually.";function pe(e){let t=e.indexOf("--");if(t===-1)return{index:-1,before:e,after:[]};return{index:t,before:e.slice(0,t),after:e.slice(t+1)}}function fm(e,t,n){let r=xi(e,t,n),o=Uv(r.entries);if(o.size===0)return{blockedReason:r.blockedReason,expanded:!1,tokens:e};let i=e,s=!1;for(let a=0;a<$v;a++){let{subcommand:l,rest:c}=ze(i),u=l?.toLowerCase();if(!u||!o.has(u))return{blockedReason:r.blockedReason,expanded:s,tokens:i};let m=o.get(u),d=Yv(m);if(d===null||d.length===0)return{blockedReason:za,expanded:!0,tokens:i};i=["git",...d,...c],s=!0}return{blockedReason:za,expanded:!0,tokens:i}}function pm(e,t,n){return xi(e,t,n).entries.some((r)=>r.key.toLowerCase()==="core.sshcommand")}function ze(e){if(e.length===0)return{subcommand:null,rest:[]};let t=e[0];if((t?k(t).toLowerCase():null)!=="git")return{subcommand:null,rest:[]};let r=1;while(r<e.length){let o=e[r];if(!o)break;if(o==="--"){let i=e[r+1];if(i&&!i.startsWith("-"))return{subcommand:i,rest:e.slice(r+2)};return{subcommand:null,rest:e.slice(r+1)}}if(!o.startsWith("-"))return{subcommand:o,rest:e.slice(r+1)};r+=De.has(o)?2:1}return{subcommand:null,rest:[]}}function Uv(e){let t=new Map;for(let n of e){let r=n.key.toLowerCase();if(!r.startsWith("alias."))continue;let o=r.slice(6);if(o!=="")t.set(o,n.value)}return t}function xi(e,t,n){if(e.length===0)return{blockedReason:null,entries:[]};let r=e[0];if((r?k(r).toLowerCase():null)!=="git")return{blockedReason:null,entries:[]};let i=Vv(t,n);return{blockedReason:i.blockedReason,entries:[...i.entries,...jv(e,t,n)]}}function jv(e,t,n){let r=[],o=1;while(o<e.length){let i=e[o];if(!i||i==="--"||!i.startsWith("-"))return r;if(i==="-c"){let s=Ha(e[o+1]);if(s)r.push(s);o+=2;continue}if(i.startsWith("-c")&&i.length>2){let s=Ha(i.slice(2));if(s)r.push(s);o++;continue}if(i==="--config-env"){let s=mm(e[o+1],t,n);if(s)r.push(s);o+=2;continue}if(i.startsWith("--config-env=")){let s=mm(i.slice(13),t,n);if(s)r.push(s);o++;continue}if(De.has(i)){o+=2;continue}o++}return r}function Vv(e,t){let n=Kv(e,t),r=qv(e,t);return{blockedReason:n===null||r===null?za:null,entries:[...n??[],...r??[]]}}function Kv(e,t){let n=wt("GIT_CONFIG_PARAMETERS",e,t);if(n===void 0)return[];let r=[],o=$r(n);if(!o)return null;for(let i of o){let s=Ha(i);if(!s)return null;r.push(s)}return r}function qv(e,t){let n=gd(e,t);if(n.state==="absent")return[];if(n.state==="invalid")return null;let r=[];for(let o=0;o<n.count;o++){let i=wt(`GIT_CONFIG_KEY_${o}`,e,t)?.trim(),s=wt(`GIT_CONFIG_VALUE_${o}`,e,t);if(!i||s===void 0)return null;r.push({key:i,value:s})}return r}function Ha(e){if(!e)return null;let t=e.indexOf("=");return{key:(t===-1?e:e.slice(0,t)).trim(),value:t===-1?void 0:e.slice(t+1)}}function mm(e,t,n){let r=e?.indexOf("=")??-1;if(!e||r===-1)return null;return{key:e.slice(0,r).trim(),value:wt(e.slice(r+1),t,n)}}function Yv(e){let t=e?.trimStart();if(!t||t.startsWith("!"))return null;return $r(t)}var Zv="git checkout -- discards uncommitted changes permanently. Use 'git stash' first.",Xv="git checkout <path> discards uncommitted changes permanently. Use 'git stash' first, or 'git switch' to change branches.",Jv="git checkout --force discards uncommitted changes. Use 'git stash' first.",Qv="git checkout <ref> -- <path> overwrites working tree with ref version. Use 'git stash' first.",eE="git checkout --pathspec-from-file can overwrite multiple files. Use 'git stash' first.",tE="git checkout with multiple positional args may overwrite files. Use 'git switch' for branches or 'git restore' for files.",nE="git switch --discard-changes discards uncommitted changes. Use 'git stash' first.",rE="git switch --force discards uncommitted changes. Use 'git stash' first.",oE="git restore discards uncommitted changes. Use 'git stash' first, or use --staged to only unstage.",iE="git restore --worktree explicitly discards working tree changes. Use 'git stash' first.",sE="git reset --hard destroys all uncommitted changes permanently. Use 'git stash' first.",aE="git reset --merge can lose uncommitted changes. Use 'git stash' first.",lE="git clean -f removes untracked files permanently. Use 'git clean -n' to preview first.",cE="git rm --force removes tracked files from the working tree. Use 'git rm --cached' to keep the files, or 'git rm --dry-run' to preview first.",uE="git push --force destroys remote history. Use --force-with-lease for safer force push.",dE="git push deletes remote refs. Ask the user to run it manually if deletion is intended.",mE="git push --mirror can force-update and delete remote refs. Ask the user to run it manually if mirror push is intended.",fE="git branch -D force-deletes without merge check. Use -d for safe delete.",pE="git rebase --abort discards rebase conflict resolutions. Use 'git status' first.",gE="git merge --abort discards merge conflict resolutions. Use 'git status' first.",hE="git tag -d permanently deletes tags. Ask the user to run it manually if deletion is intended.",yE="git reflog delete removes recovery history. Ask the user to run it manually if deletion is intended.",CE="git stash drop permanently deletes stashed changes. Consider 'git stash list' first.",bE="git stash clear deletes ALL stashed changes permanently. Use 'git stash list' to review; ask the user to run it manually if intended.",SE="git worktree remove --force can delete uncommitted changes. Remove --force flag.",vE=new Set(["-b","-B","--orphan","--conflict","--inter-hunk-context","--pathspec-from-file","--unified"]),EE=new Set(["--recurse-submodules","--track","-t"]),Ba=new Set(["-b","-B","-U"]),$a=new Set(["-c","-C"]),xE=new Set(["--source","--conflict","--unified","--inter-hunk-context"]);function D(e,t){let n=e.split("=",1)[0]??e;return n.length>=4&&t.startsWith(n)&&n.startsWith("--")&&n.slice(2).length>=2}var $n=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","rm","stash","switch","tag","worktree"]);function hm(e,t){let{subcommand:n,rest:r}=ze(e);if(!n)return null;switch(n.toLowerCase()){case"checkout":return Kt(RE(r,t));case"switch":return Kt(_E(r));case"restore":return Kt(PE(r));case"reset":return kE(r);case"clean":return Kt(OE(r));case"rm":return Kt(ME(r));case"push":return mn(DE(r));case"branch":return mn(WE(r));case"stash":return mn(BE(r));case"worktree":return mn($E(r));case"rebase":return Kt(GE(r));case"merge":return Kt(FE(r));case"tag":return mn(zE(r));case"reflog":return mn(HE(r));default:return null}}function Kt(e){return e?{...e,localDiscard:!0}:null}function mn(e){return e?{...e,localDiscard:!1}:null}function RE(e,t){let{index:n,before:r}=pe(e),o=we(r,{shortOptsWithValue:Ba});if(r.some((a)=>D(a,"--force"))||o.has("-f"))return v("git.checkout-force",Jv);for(let a of e){if(a==="-b"||a==="-B"||a==="--orphan")return null;if(D(a,"--pathspec-from-file"))return v("git.checkout-pathspec-from-file",eE)}if(n!==-1){if(r.some((l)=>!l.startsWith("-")))return v("git.checkout-ref-path",Qv);return v("git.checkout-double-dash",Zv)}let i=AE(e);if(i.length>=2)return v("git.checkout-ambiguous",tE);let s=i[0];if(s===void 0||o.has("-d")||o.has("-t")||e.some((a)=>D(a,"--detach")||D(a,"--track")))return null;if(wE(s)||t(s))return v("git.checkout-double-dash",Xv);return null}function wE(e){return e==="."||e===".."||/^\.\.?[/\\]/.test(e)||/^([/\\]|[A-Za-z]:[/\\])/.test(e)||e.endsWith("/")||e.startsWith(":")||/[*?[]/.test(e)}function _E(e){let{before:t}=pe(e);if(t.some((r)=>D(r,"--discard-changes")))return v("git.switch-discard-changes",nE);let n=we(t,{shortOptsWithValue:$a});if(t.some((r)=>D(r,"--force"))||n.has("-f"))return v("git.switch-force",rE);return null}function AE(e){let t=[],n=0;while(n<e.length){let r=e[n];if(!r)break;if(r==="--")break;if(!r.startsWith("-")){t.push(r),n++;continue}if(vE.has(r)){n+=2;continue}if(EE.has(r)){let o=e[n+1],i=r==="--recurse-submodules"?["checkout","on-demand"]:["direct","inherit"];n+=o&&!o.startsWith("-")&&i.includes(o)?2:1;continue}n++}return t}function PE(e){let t=TE(e);if(t.isTerminal||!t.hasPathspec&&!t.hasPatch||!t.hasWorktree)return null;return t.hasExplicitLocation?v("git.restore-worktree",iE):v("git.restore-unstaged",oE)}function TE(e){let t=!1,n=!1,r=!0,o=!1,i=(s)=>{if(!o)r=!1,o=!0;if(s!==void 0)r=s};for(let s=0;s<e.length;s++){let a=e[s];if(a===void 0)break;if(a==="--"){t||=s+1<e.length;break}if(a==="--pathspec-from-file"){t=!0,s++;continue}if(a.startsWith("--pathspec-from-file=")){t=!0;continue}if(a==="-h"||a==="--help"||a==="--version")return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!0};if(a==="--staged"){i();continue}if(a==="--no-staged"){i();continue}if(a==="--worktree"){i(!0);continue}if(a==="--no-worktree"){i(!1);continue}if(a==="--patch"){n=!0;continue}if(a==="--no-patch"){n=!1;continue}if(xE.has(a)){s++;continue}if(a.startsWith("--"))continue;if(a==="-"){t=!0;continue}if(!a.startsWith("-")){t=!0;continue}for(let l=1;l<a.length;l++){let c=a.charAt(l);if(c==="h")return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!0};if(c==="S"){i();continue}if(c==="W"){i(!0);continue}if(c==="p"){n=!0;continue}if(c==="s"||c==="U"){if(l===a.length-1)s++;break}}}return{hasPathspec:t,hasPatch:n,hasWorktree:r,hasExplicitLocation:o,isTerminal:!1}}function kE(e){let t=null;for(let n of e){if(D(n,"--hard")){t=v("git.reset-hard",sE);break}if(D(n,"--merge")){t=v("git.reset-merge",aE);break}}if(!t)return null;return IE(e)?mn(t):Kt(t)}function IE(e){for(let t of e){if(t==="--")return!1;if(!t.startsWith("-"))return!0}return!1}function OE(e){for(let n of e)if(n==="-n"||D(n,"--dry-run"))return null;let t=we(e.filter((n)=>n!=="--"));if(e.some((n)=>D(n,"--force"))||t.has("-f"))return v("git.clean-force",lE);return null}function ME(e){let t=!1,n=!1,r=!1;for(let o of pe(e).before){if(D(o,"--no-force")){t=!1;continue}if(D(o,"--force")){t=!0;continue}if(D(o,"--no-cached")){n=!1;continue}if(D(o,"--cached")){n=!0;continue}if(D(o,"--no-dry-run")){r=!1;continue}if(D(o,"--dry-run")){r=!0;continue}let i=we([o]);t||=i.has("-f"),r||=i.has("-n")}return t&&!n&&!r?v("git.rm-force",cE):null}function DE(e){let{before:t,after:n}=pe(e),r=we(t);if(t.some((s)=>D(s,"--mirror")))return v("git.push-mirror",mE);if(t.some((s)=>D(s,"--force"))||r.has("-f")||gm(t,n).some(NE))return v("git.push-force",uE);if(t.some((s)=>D(s,"--delete"))||r.has("-d")||gm(t,n).some(LE))return v("git.push-delete",dE);return null}function gm(e,t){return[...e.filter((n)=>n!==""&&!n.startsWith("-")),...t]}function NE(e){return e.startsWith("+")||e.includes(":+")}function LE(e){return e.length>1&&e.startsWith(":")}function WE(e){let{before:t}=pe(e),n=we(t),r=n.has("-D")||n.has("-d")||t.some((i)=>D(i,"--delete")),o=n.has("-D")||n.has("-f")||t.some((i)=>D(i,"--force"));if(r&&o)return v("git.branch-force-delete",fE);return null}function GE(e){let{before:t}=pe(e);return t.some((n)=>D(n,"--abort"))?v("git.rebase-abort",pE):null}function FE(e){let{before:t}=pe(e);return t.some((n)=>D(n,"--abort"))?v("git.merge-abort",gE):null}function zE(e){let{before:t}=pe(e);return we(t).has("-d")||t.some((r)=>D(r,"--delete"))?v("git.tag-delete",hE):null}function HE(e){return e[0]==="delete"?v("git.reflog-delete",yE):null}function BE(e){for(let t of e){if(t==="drop")return v("git.stash-drop",CE);if(t==="clear")return v("git.stash-clear",bE)}return null}function $E(e){let{before:t}=pe(e);if(!t.includes("remove"))return null;let r=we(t);if(t.some((o)=>D(o,"--force"))||r.has("-f"))return v("git.worktree-remove-force",SE);return null}var kt=require("node:path");var ja="TMPDIR",Va="IFS",Cm=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,bm=/^[A-Za-z_][A-Za-z0-9_]*$/,Sm=new Set(["export","typeset","declare","readonly"]),UE=new Set(["builtin","command","time"]),vm=new Set(["do","then","else"]),jE=new Set(["do","then","case"]),ym=new Set(["done","fi","esac"]),VE=/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;function Em(e,t){return e.map((n)=>n.provenance==="variable"&&Tm(n.text)?xm(n.text,t.shellAssignments):_(n))}function xm(e,t){return e.replace(VE,(n,r,o)=>t.get(r??o??"")??n)}function pt(e,t){let n=e.parts.every((o)=>o.provenance!=="literal"||!/[$`]/.test(o.raw));if(e.provenance!=="variable"||!n)return null;let r=xm(e.text,t);return/^[~-]/.test(r)||/[\s$`*?[]/.test(r)?null:r}function Rm(e,t){return{env:e,effectiveEnvAssignments:ZE(e,t),shellAssignments:new Map,bodyDepth:0,bodyAssignments:new Set}}function wm(e){return{env:e.env,effectiveEnvAssignments:e.effectiveEnvAssignments?new Map(e.effectiveEnvAssignments):void 0,shellAssignments:new Map(e.shellAssignments),bodyDepth:e.bodyDepth,bodyAssignments:new Set(e.bodyAssignments)}}function Ka(e,t){let n=Am(e,t),r=e[0]??"";if(jE.has(r))t.bodyDepth+=1;if(r==="elif"||ym.has(r))t.bodyDepth=Math.max(0,t.bodyDepth-1);if(ym.has(r)&&t.bodyDepth===0)t.bodyAssignments.forEach((a)=>{t.shellAssignments.delete(a)}),t.bodyAssignments.clear();n.assignments.filter((a)=>a.persists).forEach((a)=>{if(t.shellAssignments.set(a.name,a.value),t.bodyDepth>0)t.bodyAssignments.add(a.name);qa(t,a)});let o=n.commandIndex;if(o!==-1&&Sm.has(e[o]??""))e.filter((a)=>bm.test(a)&&Ua(a)).forEach((a)=>{XE(t,a)});let i=o===-1?-1:Pm(e,o);if(i===-1||e[i]!=="unset")return;let s=QE(e,i);if(s===null)return;e.slice(s).forEach((a)=>{if(vm.has(r)){t.shellAssignments.set(a,"");return}JE(t,a)})}function _m(e,t){let n=Am(e,t).assignments;if(n.length===0)return t.effectiveEnvAssignments;let r=new Map(t.effectiveEnvAssignments??[]);return n.forEach((o)=>{r.set(o.name,o.value)}),r}function Am(e,t){let n=vm.has(e[0]??"")?1:0,r=e.findIndex((a,l)=>l>=n&&!Tm(a)),o=r!==-1&&Sm.has(e[Pm(e,r)]??""),i=YE(t);return{assignments:e.flatMap((a,l)=>{let c=KE(a,i,t.env);if(!c)return[];if(r!==-1&&l>r&&!o&&!ei(c.name))return[];return i.set(c.name,c.value),[{...c,persists:r===-1||o}]}),commandIndex:r}}function Pm(e,t){let n=t;while(UE.has(e[n]??"")){n+=1;while(e[n]?.startsWith("-")){if(/^-p*[vV][pvV]*$/.test(e[n]??""))return t;n+=1}}return n}function Tm(e){return Ue(e)!==null||Cm.test(e)}function KE(e,t,n){return Ue(e)??qE(e,t,n)}function qE(e,t,n){let r=ti(e,n,t);if(r)return r;let o=e.match(Cm)?.[1];if(!o)return null;let i=e.indexOf("=");return{name:o,value:`${t.has(o)?t.get(o):n.get(o)??""}${e.slice(i+1)}`}}function Ua(e){return e===ja||e===Va||Ca(e)}function YE(e){return new Map([...e.effectiveEnvAssignments??[],...e.shellAssignments])}function ZE(e,t){let n=[ja,Va].map((r)=>{let o=e.get(r);return o===void 0?null:[r,o]}).filter((r)=>r!==null);if(n.length===0)return t;return new Map([...n,...t??[]])}function qa(e,t){let n=new Map(e.effectiveEnvAssignments??[]);n.set(t.name,t.value),e.effectiveEnvAssignments=n}function XE(e,t){qa(e,{name:t,value:e.shellAssignments.get(t)??e.effectiveEnvAssignments?.get(t)??e.env.get(t)??""})}function JE(e,t){if(!Ua(t)&&!bm.test(t))return;if(e.shellAssignments.set(t,""),ei(t)&&e.env.has(t)){let r=new Map(e.env);r.delete(t),e.env=r}if(!Ua(t)||t===ja||t===Va||lr(t)){qa(e,{name:t,value:""});return}if(!e.effectiveEnvAssignments?.has(t))return;let n=new Map(e.effectiveEnvAssignments);n.delete(t),e.effectiveEnvAssignments=n.size===0?void 0:n}function QE(e,t){let n=t+1;while(n<e.length){let r=e[n];if(!r)return null;if(r==="--")return n+1;if(r==="-v"){n++;continue}if(r.startsWith("-"))return null;return n}return n}var Im=require("node:path");function Ri(e,t){return ya.some((n)=>t?.has(n)||e.has(n))}function Un(e,t,n){if(!t)return{gitCwd:null,hasExplicitGitContext:!1};let r=n.realpath(Im.resolve(t));if(r===null||!n.isDirectory(r))return{gitCwd:null,hasExplicitGitContext:!1};let o=r,i=!1,s=1;while(s<e.length){let a=e[s];if(!a)break;if(a==="--")break;if(!a.startsWith("-"))break;if(a==="-C"){let l=e[s+1];if(!l)return{gitCwd:null,hasExplicitGitContext:i};let c=km(o,l,n);if(!c)return{gitCwd:null,hasExplicitGitContext:i};o=c,s+=2;continue}if(a.startsWith("-C")&&a.length>2){let l=km(o,a.slice(2),n);if(!l)return{gitCwd:null,hasExplicitGitContext:i};o=l,s++;continue}if(a==="--git-dir"||a==="--work-tree"){i=!0,s+=2;continue}if(a.startsWith("--git-dir=")||a.startsWith("--work-tree=")){i=!0,s++;continue}s+=De.has(a)?2:1}return{gitCwd:o,hasExplicitGitContext:i}}function km(e,t,n){try{let r=Ht(e,t,n);return n.isDirectory(r)?r:null}catch{return null}}function Om(e,t,n){if(!t.localDiscard||!n.worktreeMode||Ri(n.environment.env,n.envAssignments))return null;let r=Un(e,n.cwd,n.environment.paths);if(!r.gitCwd||r.hasExplicitGitContext)return null;let o=n.environment.worktreeFacts(r.gitCwd);if(!o)return null;if(Ya(e,n,o))return null;return{kind:"worktree",originalReason:t.reason,gitCwd:r.gitCwd}}function Ya(e,t,n){let{subcommand:r,rest:o}=ze(e),i=r?.toLowerCase();if(t.dynamicArguments||ex(o)||ix(e,t.environment.env,t.envAssignments,n)||rx(o)||tx(i,o))return!0;return i==="clean"&&ox(o)>1}function ex(e){return e.some((t)=>/[$*?[]/.test(t))}function tx(e,t){if(e==="checkout"){let{before:n}=pe(t),r=we(n,{shortOptsWithValue:Ba}),o=n.some((s)=>D(s,"--force"))||r.has("-f"),i=r.has("-B")||n.some((s)=>s==="-B"||s.startsWith("-B"));return o&&i}if(e==="switch"){let{before:n}=pe(t),r=we(n,{shortOptsWithValue:$a}),o=n.some((s)=>D(s,"--force"))||n.some((s)=>D(s,"--discard-changes"))||r.has("-f"),i=n.some((s)=>s==="-C"||s.startsWith("-C")||nx(s))||r.has("-C");return o&&i}return!1}function nx(e){let t=e.split("=",1)[0]??e;return t==="--force-create"||t.length>=9&&"--force-create".startsWith(t)}function rx(e){return e.some((t)=>t.startsWith("--recurse-sub"))}function ox(e){let t=0;for(let n of e){if(n==="--force"){t++;continue}if(n.startsWith("-")&&!n.startsWith("--")){for(let r of n.slice(1))if(r==="f")t++}}return t}function ix(e,t,n,r){if(wt("GIT_CONFIG_PARAMETERS",t,n)!==void 0)return!0;let o=xi(e,t,n);if(o.blockedReason!==null)return!0;let i=o.entries.map((a)=>({key:a.key.toLowerCase(),value:a.value}));if(i.some((a)=>ax(a.key)))return!0;let s=i.filter((a)=>a.key==="submodule.recurse").at(-1);if(s)return s.value===void 0||sx(s.value);if(yd(n))return!0;return r.recursiveSubmodules}function sx(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function ax(e){return e==="include.path"||e.startsWith("includeif.")&&e.endsWith(".path")}function Mm(e,t,n){let r=e.map((l)=>pt(l,n.shellAssignments??new Map)??_(l)),o=n.environment.paths,i=Un(r,n.cwd,o),s=n.originalCwd?o.realpath(kt.resolve(n.originalCwd)):null;if(t.id.startsWith("git.push-")||s===null||i.gitCwd===null||i.hasExplicitGitContext||Ri(n.environment.env,n.envAssignments))return null;let a=t.id==="git.worktree-remove-force"?cx(e,n.shellAssignments,o):Dm(i.gitCwd,o);if(a===null||t.id!=="git.worktree-remove-force"&&!lx(a,r,t,n)||!Fn(a,n.environment)||gi(a,n.environment)||zn(s,a)||zn(a,s))return null;return{kind:"temp-root",originalReason:t.reason,gitCwd:i.gitCwd}}function lx(e,t,n,r){let o=r.environment.paths,i=kt.join(e,".git");if(o.entryKind(i)!=="present")return!1;if(o.isDirectory(i))return!0;if(!n.localDiscard)return!1;let a=r.environment.worktreeFacts(e);return a!==null&&!Ya(t,r,a)}function cx(e,t,n){let r=ze(e.map(_)).rest,{before:o,after:i}=pe(r.slice(r.indexOf("remove")+1)),s=[...o.filter((u)=>!u.startsWith("-")),...i],a=s.length===1?s[0]??"":"",l=e.find((u)=>u.text===a),c=(l&&pt(l,t??new Map))??a;if(!kt.isAbsolute(c)||/[\s$`*?[]/.test(c)||n.entryKind(c)!=="present"||!n.isDirectory(c))return null;return n.realpath(c)}function Dm(e,t){if(t.entryKind(kt.join(e,".git"))!=="missing")return e;let n=kt.dirname(e);return n===e?null:Dm(n,t)}var ux="Git SSH environment overrides can execute arbitrary commands during network operations. Run git without GIT_SSH/GIT_SSH_COMMAND overrides, or ask the user to run it manually.",dx=new Set(["clone","fetch","pull","push","ls-remote","submodule"]);function wi(e,t){return Lm(e,t)}function Lm(e,t,n){let r=e.map(_),o=fm(r,t.environment.env,t.envAssignments),i=o.blockedReason?T(v("git.alias-config",o.blockedReason),t.policy):null;if(i)return i;let s=o.tokens;if((hd(t.envAssignments)||pm(r,t.environment.env,t.envAssignments))&&mx(s))return v("git.ssh-env",ux);let a=hm(s,(c)=>{let u=Un(r,t.cwd,t.environment.paths).gitCwd;return u!==null&&t.environment.paths.entryKind(Nm.resolve(u,c))!=="missing"});if(!a)return null;if(o.expanded||o.blockedReason)return a;let l=Om(r,a,t)??Mm(e,a,t);if(!l)return a;return n?.(l),null}function Wm(e,t){let n=null;return{match:Lm(e,t,(o)=>{n=o}),relaxation:n}}function mx(e){let{subcommand:t,rest:n}=ze(e),r=t?.toLowerCase();if(!r)return!1;if(dx.has(r))return!0;if(r==="archive")return pe(n).before.some((o)=>D(o,"--remote"));return r==="remote"&&fx(n)}function fx(e){return e.find((t)=>!px(t))?.toLowerCase()==="update"}function px(e){return e==="-v"||D(e,"--verbose")||D(e,"--no-verbose")}var gf=require("node:path");function Gm(e,t,n,r){let o=e.slice(0,t),i=e.slice(t+n);return r.startsWith(o)&&r.endsWith(i)?r.slice(o.length,r.length-i.length):null}function _i(e,t,n){let r=(i)=>`${i.tokenIndex}\x00${i.kind}\x00${i.value}`,o=new Set(e.map(r));return Array.from(t).some((i)=>n(i).some((s)=>!o.has(r(s))))}var Fm="rm -rf outside cwd is blocked. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",gx="rm -rf for non-temporary paths is blocked by the active safety policy. Retry deleting only explicit paths inside the current directory; escalate for anything outside it.",hx="rm -rf target contains shell variables that cannot be verified safely. Use literal paths within cwd, /tmp, /var/tmp, or $TMPDIR.",Hm="rm -rf targeting root or home directory is extremely dangerous and always blocked.",yx="rm -rf in home directory is dangerous. Change to a project directory first.",zm={root_or_home_target:{id:"rm.recursive-force-root-or-home",reason:Hm},git_metadata_target:{id:"rm.git-metadata",reason:je},dynamic_target:{id:"rm.recursive-force-dynamic-target",reason:hx},home_cwd_target:{id:"rm.recursive-force-home-cwd",reason:yx},cwd_self_target:{id:"rm.recursive-force-cwd-self",reason:Fm},within_anchored_cwd:{id:"rm.recursive-force-paranoid",reason:gx},outside_anchored_cwd:{id:"rm.recursive-force-outside-cwd",reason:Fm}};function Ai(e,t){let n=Vt({...t,allowPaths:t.policy?.destructiveCommandAllowPaths,posixShell:!0}),r=e.map(_),o=it(r),i=vi(r),s=bx(e);for(let a of s){let l=Gr(a.word);if(o&&l.unsafeBraceExpansion){let c=T(Wr({kind:"outside_anchored_cwd"},n,t.policy,zm),t.policy);if(c)return c;continue}for(let c of l.expandedTargets??[a.text]){let u=Me(c),m={targetIsLiteral:l.expandedTargets!==void 0||l.targetIsLiteral,tmpdirWordSplittingProtected:l.tmpdirWordSplittingProtected};if(!i&&n.resolvedCwd&&ln(u,n.resolvedCwd,n.protectedGitMetadata,i,n.environment,n.budget))return v("rm.git-metadata",je);if(i&&!o){let d=rt(u,n,m);if(d.kind==="root_or_home_target")return v("rm.recursive-force-root-or-home",Hm);if(d.kind==="git_metadata_target")return v("rm.git-metadata",je);continue}if(!o)continue;for(let d of Cx(u,n,m)){let f=Wr(d,n,t.policy,zm),p=T(f,t.policy);if(p)return p}}}return null}function Cx(e,t,n){let r=rt(e,t,n);if(r.kind==="cwd_self_target")return[r,rt(e,t,{...n,skipCwdSelf:!0})];if(r.kind!=="home_cwd_target")return[r];let o=rt(e,t,{...n,skipHomeCwd:!0});if(o.kind!=="cwd_self_target")return[r,o];return[r,o,rt(e,t,{...n,skipHomeCwd:!0,skipCwdSelf:!0})]}function bx(e){let t=[],n=!1;for(let r of e.slice(1)){let o=_(r);if(!o)continue;if(o==="--"){n=!0;continue}if(n){t.push({text:o,word:r});continue}if(!o.startsWith("-"))t.push({text:o,word:r})}return t}var qt={kind:"none"},fn={kind:"dynamic"},Sx=new Set(["<","<<","<<-","<<<","<&","<>"]),$m=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*))/g,vx=/^(?:[0-9]+|[@*])$/,Ex=Ft.maxWords,Um=Ft.maxInputLength;function jm(e){if(!e||k(M(e.words[0]?.text??""))!=="printf")return;if(e.words.some((o)=>o.provenance!=="literal"))return;let t=e.words.slice(e.words[1]?.text==="--"?2:1),n=t[0]?.text;if(n===void 0)return"";let r=t.slice(1).map((o)=>o.text);if(n==="%s")return r.join("");if(n==="%s\\n"||n===`%s
|
|
35
35
|
`)return`${r.join(`
|
|
36
36
|
`)}
|
|
37
37
|
`;if(n.includes("%")||/\\(?![\\nrt])/.test(n))return;return n.replaceAll("\\n",`
|
|
38
|
-
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function
|
|
39
|
-
`}}function
|
|
38
|
+
`).replaceAll("\\r","\r").replaceAll("\\t","\t").replaceAll("\\\\","\\")}function Pi(e){let t=jn(e[1])==="--"?2:1;if(e.length<=t)return qt;let n=e.slice(t);if(!n.every(jr))return fn;return{kind:"literal",source:n.map(_).join(" ")}}function Vm(e){let t=jn(e[1])==="--"?2:1,n=e[t],r=jn(n);if(n===void 0||e.length<=t+1||r==="-"||r===""||r==="-l"||r==="-p")return qt;if(!jr(n))return fn;return{kind:"literal",source:r}}function Ti(e,t){let n=Ym(e);if(n===-1)return qt;let r=Rx(t);if(!r)return qt;let o=[],i=r.command?.length??0;for(let s of r.references){let a=_x(s,e,n,r.ifs);if(!a)return fn;if(i+=a.reduce((l,c)=>l+c.length+3,0),o.length+a.length>Ex||i>Um)return fn;o.push(...a)}if(r.command==="eval")return{kind:"literal",source:o.join(" ")};if(o.length===0||/\s/.test(o[0]??""))return{kind:"literal",source:""};return{kind:"literal",source:[r.command,r.command&&r.optionTerminator?"--":null,...o.map(Zm)].filter((s)=>s!==null).join(" ")}}function Km(e,t){let n=Ym(e),r=e.slice(n+1),o=/\bIFS\b/.test(t);if(n===-1||!r.every(jr)||o)return t;let i=r.map(jn),s="",a=null,l=0;while(l<t.length){let c=t[l]??"",u=a==="'"?null:/^\$(?:\{([0-9]+|[@*])\}|([0-9@*]))/.exec(t.slice(l));if(u){let m=u[1]??u[2],d=m==="@"||m==="*"?i.slice(1):[i[Number(m)]??""];if(a!=='"'&&d.some((p)=>/[*?[]/.test(p)))return t;if(s+=a==='"'?d.map((p)=>p.replace(/["$`\\]/g,"\\$&")).join(m==="@"?'" "':" "):d.map((p)=>p.split(/[ \t\n]+/).map((g)=>g?Zm(g):"").join(" ")).join(" "),s.length>Um)return t;l+=u[0].length;continue}if(c==="\\"&&a!=="'"){s+=t.slice(l,l+2),l+=2;continue}if(c==="'"&&a!=='"'||c==='"'&&a!=="'")a=a?null:c;s+=c,l++}return s}function qm(e,t,n,r){if(!Ne(e.map(_)).readsStdinAsCommands)return qt;let o=t.filter((i)=>(i.fd===void 0||i.fd===0)&&Sx.has(i.operator)).at(-1);if(o){if(o.operator==="<<"||o.operator==="<<-")return qt;if(o.operator!=="<<<"||o.target?.provenance!=="literal")return fn;return{kind:"literal",source:o.target.text}}if(!n)return qt;return r===void 0?fn:{kind:"literal",source:r}}function It(e,t=new Map){let n=Ne(e.map(_)).scriptIndex;if(n===null)return qt;let r=e[n],o=jn(r);if(qo(r,o))return{kind:"literal",source:o};let i=r?pt(r,t):null;return i===null?fn:{kind:"literal",source:i}}var xx=new Set(["curl","wget","fetch","aria2c","http","https","xh","xhs","nc","ncat","netcat"]);function Qa(e){if(e.words.length!==2||e.redirections.length!==0||e.nested.length!==1)return!1;let t=e.words[0],n=e.words[1];if(!t||t.provenance!=="literal"||t.quoted||t.raw!==t.text||!n)return!1;if(!(t.text==="eval"&&n.quoted&&n.parts.length===3&&n.parts[0]?.raw==='"'&&n.parts[1]?.provenance==="command-substitution"&&n.parts[1].raw.startsWith("$(")&&n.parts[2]?.raw==='"'||t.text==="eval"&&!n.quoted&&n.parts.length===1&&n.parts[0]?.provenance==="command-substitution"&&n.parts[0].raw.startsWith("$(")||(t.text==="source"||t.text===".")&&!n.quoted&&n.parts.length===1&&n.parts[0]?.provenance==="command-substitution"&&n.parts[0].raw.startsWith("<(")))return!1;let o=e.nested[0];if(o?.status!=="complete"||o.nodes.length!==1)return!1;let i=o.nodes[0];if(i?.kind!=="command"||i.redirections.length!==0||i.nested.length!==0||i.words.some((l)=>l.provenance!=="literal"||l.parts.some((c)=>c.provenance!=="literal")))return!1;let s=i.words[0]?.text;if(s===void 0||Ue(s)!==null)return!1;let a=k(M(s));return!xx.has(a)&&!Q.has(a)&&!un(a)}function Ym(e){return Ne(e.map(_)).commandIndex??-1}function Rx(e){let t=/^IFS=(?:'([^']*)'|"([^"]*)"|([^;\s]*))\s*;\s*(.+)$/.exec(e.trim()),n=t?.[4]??e.trim(),r=/^(\.|bash|command|dash|exec|eval|ksh|sh|source|zsh)(?:\s+(--))?\s+(.+)$/.exec(n),o=(r?.[3]??n).split(/\s+/).map(wx);if(o.length===0||o.some((i)=>i===null))return null;return{command:r?.[1]??null,optionTerminator:r?.[2]!==void 0,references:o.filter((i)=>!!i),ifs:t?t[1]??t[2]??t[3]??"":`
|
|
39
|
+
`}}function wx(e){let t=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec(e),n=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec(e),r=t??n;if(!r)return null;let o=r[1]??r[2];return{parameter:o==="@"||o==="*"?o:Number(o),quoted:t!==null}}function _x(e,t,n,r){let o=t.slice(n+2);if(e.parameter==="@")return e.quoted?Za(o):Ax(o,r);if(e.parameter==="*"){let a=Za(o);if(!a)return;let l=a.join(r[0]??"");return e.quoted?[l]:Xa(l,r)}let i=t[n+1+e.parameter];if(i&&!jr(i))return;let s=jn(i);return e.quoted?[s]:Xa(s,r)}function Za(e){return e.every(jr)?e.map(_):void 0}function Ax(e,t){let n=Za(e);if(!n)return;let r=n.map((o)=>Xa(o,t));return r.some((o)=>o===void 0)?void 0:r.flatMap((o)=>o??[])}function Xa(e,t){if(["*","?","[","]"].some((n)=>e.includes(n)))return;if(t==="")return e===""?[]:[e];if(t===`
|
|
40
40
|
`)return e.trim().split(/\s+/).filter(Boolean);if(t.length!==1)return;return t===" "||t==="\t"||t===`
|
|
41
|
-
`?e.trim().split(/\s+/).filter(Boolean):e.split(t).filter(Boolean)}function Wr(e){if(!e)return!0;return e.provenance==="unknown"?!/[$`]/.test(w(e)):e.provenance==="literal"}function Ln(e){return e?w(e):""}function zm(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Ka(e,t){return ja(Ye(e,"posix"),t)}function Gr(e){return Ka(e,new Set(Array.from(e.matchAll(Mm)).flatMap((t)=>{let n=t[1]??t[2];return n===void 0?[]:[n]})))}function ja(e,t){if(e.status==="invalid"||e.status==="limited")return!1;let n=new Set(t);for(let r of e.nodes){if(r.kind==="group"){if(ja(r.body,n))return!0;continue}if(r.kind!=="command")continue;if(r.nested.some((o)=>ja(o,n))||Hm(r.words,n))return!0;Sx(r,n)}return!1}function Hm(e,t){let n=e.findIndex((s)=>$e(s.text)===null);if(n===-1)return!1;let r=e[n];if(!r)return!1;if(Lr(r,t))return!0;let o=O(r.text);if(o==="source"||o==="."){let s=e[n+1]?.text==="--"?n+2:n+1;return Om(e[s],t)}if(ee.has(o)){let s=e.slice(n),a=De(s.map((c)=>c.text)),l=a.commandIndex??a.scriptIndex;return!a.syntaxCheck&&l!==null&&Om(s[l],t)}let i=hx(e,n,t);if(i===null)return!1;if(i===-1)return!0;return Hm(e.slice(i),t)}function hx(e,t,n){let r=O(e[t]?.text??"");if(r==="command")return yx(e,t+1);if(r==="exec")return Cx(e,t+1);if(r==="env")return bx(e,t+1,n);return null}function yx(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 Cx(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 bx(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 Lr(e[r+1],n)?-1:r+2;if(i.startsWith("-S")||i.startsWith("--split-string="))return Lr(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($e(i))continue;return r}return null}function Sx(e,t){if(!e.words.every((n)=>$e(n.text)!==null))return;for(let n of e.words){let r=$e(n.text);if(!r)continue;if(Lr(n,t))t.add(r.name)}}function Lr(e,t){if(!e)return!1;return e.parts.filter((n)=>n.provenance==="variable").some((n)=>Array.from(n.raw.matchAll(Mm)).some((r)=>{let o=r[1]??r[2];return o!==void 0&&(cx.test(o)||t.has(o))}))}function Om(e,t){return!!e&&(e.parts.some((n)=>n.provenance!=="literal"&&n.provenance!=="variable")||Lr(e,t))}var qa="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",Ya="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",vx="__CC_SAFETY_NET_XARGS_INPUT__",Si="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",vi="rm",Ex=/(?:^|[;&|]\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,xx=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,Rx=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,_x=/^(?:[0-9]+|[@*])$/;function Um(e,t){let n=e.map(w),{childStart:r,replacementToken:o}=an(n),i=n.slice(r),s=S("xargs.shell-dynamic",Ya);if(Ax(i,o,t)&&P(s,t.policy))return P(s,t.policy);for(let a of tt(i,t)){let l=a.tokens,c=o!==null&&l[0]!==i[0]&&(l[0]?.includes(o)??!1)?P(s,t.policy):null;if(c)return c;let u=Zm(l,o,a.wrapperEnvAssignments),m=a.head==="rm"&&o!==null&&qm(l,o),d=t.analyzeChild(l,{...rn(a,t),dynamicInput:u,dynamicSourceInput:m||Vm(l,a.head,o,a.wrapperEnvAssignments,u,t.environment,t.strict?void 0:t.analyzeNested),dynamicRmInput:m,shellDynamicMatch:s,dynamicSourceMatch:s,rmDynamicMatch:S("xargs.rm-recursive-force-dynamic",qa)});if(d)return d;let f=wx(l,o,t.policy?.rules??[],P(s,t.policy));if(f)return f;if(a.head==="git"){let g=o===null?[...l,vx]:l,h=o!==null&&(l.some((b)=>b.includes(o))||Array.from(a.envAssignments.values()).some((b)=>b.includes(o))),y=t.analyzeChild(g,{...rn(a,t),worktreeMode:o===null||h?!1:t.worktreeMode});if(y)return y}let p=Et(l,t.policy?.rules??[]);if(p)return p}return null}function wx(e,t,n,r){if(n.length===0)return null;if(t===null){for(let i of n){let s=Et([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],n);if(s)return s}return null}let o=O(e[0]??"");if(!n.some((i)=>O(i.command)===o))return null;return e.slice(1).some((i)=>i.includes(t))?r:null}function jm(e,t,n){let r=e.indexOf(t);if(r===-1||e.indexOf(t,r+t.length)!==-1)return[];let o=Pm(e,r,t.length,n);return o===null?[]:[o]}function Vm(e,t,n,r,o,i,s){if(ee.has(t)){if(xt(e))return!1;if(n!==null&&Px(e,n,s))return!0;let a=rt(e);if(!a){let l=wt(J(e));if(l.kind==="literal")return n!==null&&l.source.includes(n);return l.kind==="none"&&o}if(n!==null&&a.includes(n)&&!Km(a,n,s))return!0;if(Be(a))return!0;return Tx(a,n,r)}if(qe(t))return Bm(e,n,Bo,nd(t));if(He.has(t))return Bm(e,n,Aa,Yd);if(t==="eval"){let a=Ci(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 Ix(e,n,i);if(t==="git"){let a=Fe(e);return n===null?a.subcommand===null:(a.subcommand?.includes(n)??!1)||a.subcommand!==null&&Dn.has(a.subcommand.toLowerCase())&&Ym(a.rest,n).some((l)=>l.includes(n))}return!1}function Km(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 Be(i)===null&&n(i)===null}function Bm(e,t,n,r){let o=n(e);if(t===null)return o.optionsOpen||n([...e,Si]).sources.some((a)=>a.value===Si);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}${Si}`]:[],...a.valueForm==="equals-or-separate"?[`${a.selector}=${Si}`]:[]]),s=new Set(i.flatMap((a)=>e.flatMap((l)=>jm(l,t,a))));return hi(o.sources,s,(a)=>n(e.map((l)=>l.replaceAll(t,a))).sources)}function Ax(e,t,n){if(e.length===0||(e[0]??"").toLowerCase()==="command")return!1;let r=new Set(Array.from(tt(e,n),(i)=>i.head)),o=t===null?[...e,vi]:e.map((i,s)=>s===0?i:i.replaceAll(t,vi));return Array.from(tt(o,n)).some((i)=>i.head===vi&&!r.has(vi))}function qm(e,t){return Ym(e.slice(1),t).some((n)=>n.includes(t)&&(n.startsWith("-")||n.startsWith(t)))}function Ym(e,t){let n=e.findIndex((r)=>r==="--"&&!r.includes(t));return n===-1?e:e.slice(0,n)}function Zm(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 Px(e,t,n){let r=De(e),o=r.commandIndex===null?"":e[r.commandIndex]??"";if(o.includes(t)&&!Km(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 jm(a,t,s).some((u)=>{let m=e.map((f,p)=>p===l?f.replaceAll(t,u):f),d=De(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 Tx(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(Ex))if($m(o,r))return!0;for(let o of e.matchAll(xx))for(let i of(o[1]??"").matchAll(Rx))if($m(i,r))return!0;return Ka(e,r)}function $m(e,t){let n=e[1]??e[2];return n!==void 0&&(_x.test(n)||t.has(n))}function Ix(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(ut(s)){let l=Mn(e,i);i=l.nextIndex-1;for(let c of tt(l.tokens,{environment:n,cwd:void 0})){let u=Zm(c.tokens,t,c.wrapperEnvAssignments);if(c.head==="rm"&&qm(c.tokens,t)||Vm(c.tokens,c.head,t,c.wrapperEnvAssignments,u,n))return!0}continue}let a=Rt(s);if(a>0){if(o=a,s.includes(t))return!0;continue}if(s.includes(t))return!0}return!1}function an(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 Fr="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",zr="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",kx="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",Ox="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",xi=/\{[^{}\s]*\}/g,Xm=/\{\}|\{-?\d+\}/g,Mx=["e","f","source","file","-e","-f","--source","--file"],Dx=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],Nx=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),Lx=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),Jm=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),Wx=new Set(["--workdir","--wd"]),Qm="__CC_SAFETY_NET_PARALLEL_SOURCE__";function je(e,t){for(let n of e){let r=t(n);if(r)return r}return null}function sf(e){return je([...e],(t)=>Be(t))}function af(e,t){let n=e.map(w);if((t.envAssignments?.has("PARALLEL")?t.envAssignments.get("PARALLEL"):t.environment.env.get("PARALLEL"))?.trim()){let p=Wn(t);if(p)return p}if(n.length===2&&(n[1]==="--version"||n[1]==="--help"))return null;let o=hf(n),{template:i,jobs:s,runsRemotely:a,readsCommandsFromInput:l,unsupported:c,workdir:u,dryRun:m}=o;if(c){let p=Wn(t);if(p)return p;let g=sf(t.envAssignments?.values()??[]);if(g)return g}if(l){let p=$x(t);if(p)return p}if(u!==void 0&&a){let p=Wn(t);if(p)return p}let d=Ux(u,t.cwd,t.environment.paths);if(d===null){let p=Wn(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([...tt(i,f)].flatMap((g)=>[...g.envAssignments.values()]).some(Ja)){let g=Wn(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=df(f.envAssignments,f.cwd,a);return je(p,(h)=>t.analyzeNested(h,g))}return je(tt(i,f),(p)=>Gx(p,o,t,f))}function Gx(e,t,n,r){let{jobs:o,templateHasPlaceholder:i,runsRemotely:s,usesStdin:a}=t,l=e.tokens,c=[...e.envAssignments.values()];if(c.some(pf)){let h=Wn(n);if(h)return h}let u=sf(c);if(u)return u;let m=c.some(B),d=i||m,f=a&&d,p=df(e.envAssignments,e.wrapperCwd,s||f);if(ee.has(e.head)){let h=()=>{if(!i||o.length===0)return null;return je(o,(E)=>n.analyzeChild(Ei(l,E,n.budget),rn(e,r)))};if(xt(l))return h();let y=rt(l);if(y){if(gf(y)){let x=$t(n);if(x)return x;if(o.length===0)return null;return je(o,(A)=>n.analyzeNested(nf(y,A,n.budget),p))}if(B(y)){if(o.length>0)return je(o,(Q)=>n.analyzeNested(nf(y,Q,n.budget),p));let x=Dr(y);if(x?.[0]&&O(x[0])==="rm"&&nt(x)){let Q=tf(n);if(Q)return Q}let A=x?n.analyzeChild(x,{...rn(e,r),dynamicInput:a,shellDynamicMatch:S("parallel.shell-dynamic",zr),rmDynamicMatch:S("parallel.rm-recursive-force-dynamic",Fr)}):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)=>bi(J(x===void 0?l:i?l.map((A)=>mf(A,x)):[...l,...x]),y)):[];if(E.some((x)=>x.kind==="dynamic")){let x=$t(n);if(x)return x}let v=E.flatMap((x)=>x.kind==="literal"?[x.source]:[]);if(v.length>0)return n.budget.charge("derivedTokens",v.length),je(v,(x)=>n.analyzeNested(x,p));if(Gr(y)){let x=$t(n);if(x)return x}let T=n.analyzeNested(y,p);if(T)return T;if(d)return $t(n);return null}let b=wt(J(l));if(b.kind==="dynamic"||b.kind==="literal"&&B(b.source))return $t(n)??h();if(b.kind==="literal")return h();if(o.length>0){let E=$t(n);if(E)return E;let v=h();if(v)return v;if(i)return null;let T=o.flatMap((x)=>x[0]===void 0?[]:[x[0]]);return n.budget.charge("derivedTokens",T.length),je(T,(x)=>n.analyzeNested(x,p))}if(d||a)return $t(n)??h();return null}if(e.head==="rm"&&nt(l)){if(i&&o.length>0)return je(o,(y)=>Za(Ei(l,y,n.budget,Xm),e.cwd,r));if(o.length>0)return je(o,(y)=>Za(rf(l,y,n.budget),e.cwd,r));let h=Za(l.flatMap((y,b)=>{if(b===0||!B(y))return[y];return y.startsWith("-")?[y.replace(Xm,"")]:[]}),e.cwd,r);if(h)return h;return tf(n)}let g=o.length>0?o:[void 0];return je(g,(h)=>{let y=h===void 0?l:i?Ei(l,h,n.budget):rf(l,h,n.budget),b=S("parallel.shell-dynamic",zr),E=a&&e.head==="find"?Bx(y,r):null,v=cf(y,a,n)??E?.customResult??null,T=O(e.head),x=a&&(T==="rm"&&Xa(y)||T==="xargs"&&uf(y)||E?.rmOptions===!0),A=a&&(x||E?.executedSource===!0||E===null&&lf(y,T)),Q=n.analyzeChild(y,{...rn(e,r),worktreeMode:s||a||d?!1:n.worktreeMode,dynamicInput:a||d,dynamicRmInput:x,dynamicSourceInput:v!==null||A,shellDynamicMatch:b,dynamicSourceMatch:b,rmDynamicMatch:S("parallel.rm-recursive-force-dynamic",Fr)});if(A){let oe=P(b,n.policy);if(oe)return oe}return Q??v??Et(y,n.policy?.rules??[])})}function lf(e,t){if(B(e[0]??""))return!0;if(t==="eval"||t==="source"||t===".")return!0;if(t==="parallel"||t==="xargs")return!0;if(ee.has(t))return Hx(e);if(t==="git")return Fx(e);if(t==="find")return!0;if(He.has(t))return ef(e,Mx,Or);if(qe(t))return ef(e,Dx,Ho);return!1}function Xa(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("-")||gf(o)))}function Fx(e){if(zx(e))return!0;let t=Fe(e);if(t.subcommand===null||B(t.subcommand))return!0;if(!Dn.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 Hx(e){if(xt(e))return!1;let t=rt(e);if(t!==null)return B(t);let n=wt(J(e));if(n.kind==="literal")return B(n.source);if(n.kind==="dynamic")return!0;return!e.some(B)}function ef(e,t,n){let r=n(e);if(r.some((o)=>B(o.value)))return!0;if(!e.some(B))return n([...e,Qm]).some((o)=>o.value===Qm);return hi(r,t,(o)=>n(e.map((i)=>mf(i,[o]))))}function cf(e,t,n){let r=n.policy?.rules??[];if(!t||r.length===0)return null;let o=r.filter((i)=>O(i.command)===O(e[0]??""));if(o.length===0)return null;if(e.slice(1).some(B))return $t(n);return je(o,(i)=>Et([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],[i]))}function Bx(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 tt(i,t))n.executedSource||=lf(a.tokens,a.head),n.rmOptions||=a.head==="rm"&&Xa(a.tokens)||a.head==="xargs"&&uf(a.tokens),n.customResult??=cf(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(ut(a)){i=[],n.executedSource||=B(a);continue}let l=Rt(a);if(l>0){o=l,n.executedSource||=B(a);continue}n.executedSource||=B(a)}return s(),n}function uf(e){let t=e.slice(an(e).childStart);return O(t[0]??"")==="rm"&&Xa(t)}function Ri(e,t){return(n)=>P(S(e,t),n.policy)}var $t=Ri("parallel.shell-dynamic",zr),$x=Ri("parallel.command-stream-dynamic",kx),Wn=Ri("parallel.command-stream-dynamic",Ox),tf=Ri("parallel.rm-recursive-force-dynamic",Fr);function Za(e,t,n){return P(yi(J(e),{environment:n.environment,cwd:t,budget:n.budget,originalCwd:n.originalCwd,strict:n.strict,paranoid:n.paranoidRm,allowTmpdirVar:n.allowTmpdirVar,tmpdirWordSplittingUnsafe:zt(n.envAssignments??new Map,n.environment),trustedTmpdirValue:en(n.envAssignments??new Map,n.environment),protectedGitMetadata:n.protectedGitMetadata,policy:n.policy}),n.policy)}function df(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 mf(e,t){return e.replace(xi,(n)=>ff(n,t))}function Ei(e,t,n,r=xi){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=ff(i,t);return n.charge("derivedTokens",Math.max(1,Math.ceil(s.length/64))),s}))}function nf(e,t,n){return Ei([e],t,n)[0]??""}function rf(e,t,n){return n.charge("derivedTokens",e.length+t.length),[...e,...t]}function ff(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(xi)!==-1}function pf(e){if(Ja(e))return!0;for(let t of e.matchAll(xi))if(!/^(?:\{\}|\{\d+\})$/.test(t[0]))return!0;return!1}function Ja(e){let t=e.indexOf("{=");return t!==-1&&e.indexOf("=}",t+2)!==-1}function gf(e){return/^\{[^{}\s]*\}$/.test(e)}function Ux(e,t,n){if(e===void 0)return;if(e==="..."||/^~|[{}$`*?[]/.test(e))return null;if(!t&&!of.isAbsolute(e))return null;try{return Lt(t??e,e,n)}catch{return null}}function hf(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=Ia(e,t+1);n.push(...E.templateTokens),r=t+1,o=E.markerIndex;break}if(!p.startsWith("-")){let E=Ia(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),b=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"?b:p.slice(2);c||=E!==""&&E!=="{}",t++;continue}if(p==="-a"||Lx.has(y)){c=!0,t+=b===void 0?2:1;continue}if(p==="--pipe"||p==="--pipepart"){s=!0,t++;continue}if(y==="--env"){c=!0,t+=b===void 0?2:1;continue}if(Jm.has(y)||p.startsWith("-S")&&p.length>2){i=!0,t+=Jm.has(p)?2:1;continue}if(Wx.has(y)){c=!0;let E=b??g;if(E===void 0||E===":::"||E==="--"){t++;continue}a=E,t+=b===void 0?2:1;continue}if(p.startsWith("-j")&&p.length>2&&/^\d+$/.test(p.slice(2))){t++;continue}if(p.startsWith("--")&&b!==void 0){t++;continue}if(Nx.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?Ja:pf);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=jx(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 jx(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 D("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 D("derivedTokens");o.push([...i,s])}t=o}return t}function yf(e){return hf(e).childStart}var Vx="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",_i="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function el(e){return e?.parts.some((t)=>t.provenance==="command-substitution")??!1}function Qa(e){return e?.parts.some((t)=>t.provenance==="literal"&&t.raw.replace(/^["']/,"").startsWith("-"))??!1}function bf(e,t,n,r,o=!1,i){let a=(lr(e,t)||r&&e!=="powershell"&&t[0]?.provenance==="variable")&&fe(i,"shell.dynamic-executable",o)?S("shell.dynamic-executable",Vx):null;return P(a,i)??Sf(e,t,n,o,i)}function Sf(e,t,n,r,o){if(t.length<2)return null;let i=t.flatMap((a,l)=>el(a)?[l]:[]);if(i.length===0)return null;let s=O(t[0]?.text??"");if(s==="git"){let a=_n(e,t),l=qx(a);if(fe(o,"shell.dynamic-structure",r)&&i.some((m)=>m<=l))return P(S("shell.dynamic-structure",_i),o);if(P(gi(a,{environment:n}),o))return null;let c=t[l]?.text.toLowerCase(),u=a.findIndex((m,d)=>d>l&&w(m)==="--");if(fe(o,"shell.dynamic-structure",r)&&c&&Dn.has(c)&&i.some((m)=>m>l&&(u===-1||m<u)))return P(S("shell.dynamic-structure",_i),o);return null}if(s==="find")return fe(o,"shell.dynamic-structure",r)&&Yx(t)?P(S("shell.dynamic-structure",_i),o):null;if(s==="rm"){let a=t.findIndex((c,u)=>u>0&&w(c)==="--"),l=nt(t.map(w));return fe(o,"shell.dynamic-structure",r)&&i.some((c)=>(a===-1||c<a)&&(c<t.length-1||!l))?P(S("shell.dynamic-structure",_i),o):null}if(s==="xargs")return Cf(e,t.slice(an(t.map(w)).childStart),"xargs",n,r,o);if(s==="parallel")return Cf(e,t.slice(yf(t.map(w))),"parallel",n,r,o);return null}function Cf(e,t,n,r,o,i){if(t.length===0)return null;let s=Kx(t,r);if(lr(e,s)){let l=P(S(`${n}.shell-dynamic`,n==="xargs"?Ya:zr),i);if(l)return l}let a=Sf(e,s,r,o,i);if(a)return a;if(s[0]?.text==="rm"&&s.slice(1).some((l)=>el(l)&&Qa(l)))return P(S(`${n}.rm-recursive-force-dynamic`,n==="xargs"?qa:Fr),i);return null}function Kx(e,t){let n=Xt(e,t),r=n.rewritten?J(n.words.map(w)):n.words,o=r[0];return o&&w(o)==="busybox"?r.slice(1):r}function qx(e){let t=1;while(t<e.length){let n=e[t],r=n?w(n):"";if(Me.has(r)){t+=2;continue}if(r.startsWith("-")){t++;continue}return t}return t}function Yx(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=el(s);if(n>0){n--;continue}if(o){if(s.text===";"||s.text==="+"){o=!1,t=!0,r=!1;continue}if(a&&(r||Qa(s)))return!0;r=!1;continue}if(!t&&!s.text.startsWith("-")){if(a&&(i>1||Qa(s)))return!0;continue}if(t=!0,a)return!0;let l=Rt(s.text);if(l>0){n=l;continue}if(ut(s.text))o=!0,r=!0}return!1}function tl(e,t){return e.some((n)=>{if(n.value==="-"&&(n.kind==="main-script"||n.kind==="program-file"))return!0;return!Wo(t[n.tokenIndex],n.value)})}var Zx="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",Xx="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",Jx="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function vf(e,t){let n=t.slice(1);if(e==="dd"&&n.some((r)=>/^of=\/dev\/.+/.test(r)))return S("dd.device-write",Zx);if((e==="mkfs"||e.startsWith("mkfs."))&&n.some((r)=>r.startsWith("/dev/")))return S("mkfs.device",Xx);if(e==="shred"&&n.length>0)return S("shred.target",Jx);return null}var xf=[{heads:new Set(["rm","rmdir"]),analyze:(e)=>yi(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoid:e.options.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:zt(e.envAssignments,e.options.environment),trustedTmpdirValue:en(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,policy:e.options.policy,budget:e.options.budget})},{heads:new Set(["git"]),analyze:(e)=>gi(e.words,nl(e))},{heads:new Set(["find"]),analyze:(e)=>nm(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:zt(e.envAssignments,e.options.environment),trustedTmpdirValue:en(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)=>ln(e.options.analyzeNested(t,n))})},{heads:new Set(["xargs"]),analyze:(e)=>Um(e.words,{...Ef(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>ln(e.options.analyzeNested(t,n))})},{heads:new Set(["parallel"]),analyze:(e)=>af(e.words,{...Ef(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>ln(e.options.analyzeNested(t,n))})}];function Ef(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 ln(e){return e?{id:e.ruleId??"",reason:e.reason,intent:e.intent??"manual_only"}:null}function nl(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 Af(e){return xf.find((t)=>t.heads.has(e))?.analyze}function Fn(e,t,n){let r=n.trace;if(e.length===0)return null;let o=n.commandView?.dialect??"posix",i=(R)=>R.map((k)=>o==="posix"?w(k):k.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=jo(e);if(d.envAssignments.size>0)r?.recordSegment({type:"env-strip",input:i(e),envVars:[...d.envAssignments.keys()],output:i(d.words)});let f=Xt(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(" "),k=Be(R);if(k)return r?.recordSegment({type:"dangerous-text",token:R,matched:!0,reason:k.reason}),Ee(k);if(n.strict)return Ie(r);let F=Vo(p,i(f.words));if(F){n.budget.charge("derivedTokens",F.length);let ue=n.analyzeNested(F.join(" "),{effectiveCwd:f.cwd===void 0?n.effectiveCwd:f.cwd,envAssignments:new Map([...n.envAssignments??[],...d.envAssignments,...f.envAssignments])});if(ue)return ue}}let g=f.rewritten?J(i(f.words)):_n(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 b=new Map([...n.envAssignments??[],...d.envAssignments,...f.envAssignments]),E=h[0];if(!E)return null;if(nn(E))throw new D("wrapperPeelIterations");let v=O(E),T=f.cwd===null?void 0:f.cwd??u,x=f.cwd===null?void 0:m,A=f.cwd===void 0?n.effectiveCwd:f.cwd,Q=s?s.allowTmpdirVar:!Ar(b,n.environment),oe=bf(o,f.words,n.environment,t===0,n.strict,n.policy);if(oe)return r?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:oe.reason}),Ee(oe);let ce=ci(h,n.policy);if(ce){for(let R of[ce.childIndex,...ce.alternativeChildIndices]){Rf(y.wrapperNormalizationBudget);let k=g.slice(R);r?.recordSegment({type:"transparent-wrapper",wrapper:ce.wrapper,output:i(k)});let F=Fn(k,t,{...y,effectiveCwd:A,envAssignments:b});if(F)return F}return null}let ie=l?void 0:v==="eval"?Ci(g):v==="trap"&&!a?Lm(g):void 0;if(a&&s&&v==="eval"){if(ie?.kind==="dynamic")return Gn(s,n.policy);if(ie?.kind==="literal"){let R=n.analyzeNested(ie.source,{effectiveCwd:A,envAssignments:b});if(R)return R}return zn(s,n.policy)}if(ie?.kind==="dynamic"&&(n.strict||!n.commandView||!Va(n.commandView)))return Ie(r);if(ie?.kind==="literal"){r?.recordSegment({type:"recurse",reason:v==="eval"?"shell-eval":"shell-trap",innerCommand:ie.source,depth:t+1});let R=n.analyzeNested(ie.source,{effectiveCwd:A,envAssignments:b,functionDefinitions:n.functionDefinitions});if(R)return R}if(a?ee.has(v):Tf(E,v)){if(xt(h))return null;if(a&&s){let R=rt(h);if(R){if(s.dynamicSourceInput??s.dynamicInput){let F=Gn(s,n.policy);if(F)return F}if(Gr(R)){let F=Gn(s,n.policy);if(F)return F}return n.analyzeNested(R,{effectiveCwd:A,envAssignments:b})}let k=wt(g);if(k.kind==="dynamic")return Gn(s,n.policy);if(k.kind==="literal")return s.dynamicSourceInput?Gn(s,n.policy):null;return s.dynamicSourceInput??s.dynamicInput?Gn(s,n.policy):null}if(l){let R=rt(h),k=R?n.analyzeNested(R,{effectiveCwd:A,envAssignments:b}):wt(g).kind==="dynamic"?Ie(r):null;if(k)return k}if(s===void 0){let R=nR(h,b,A,n,r,t);if(R)return R;let k=rt(h);if(k){let pn=bi(g,k);if(pn.kind==="dynamic")return Ie(r);let Bi=pn.kind==="literal"?pn.source:Wm(g,k),Il=rR(Bi);r?.recordSegment({type:"shell-wrapper",wrapper:v,innerCommand:Il}),r?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:Il,depth:t+1});let kl=n.analyzeNested(Bi,{effectiveCwd:A,envAssignments:b});if(kl)return kl;return Gr(Bi)?Ie(r):null}let F=wt(g);if(F.kind==="dynamic")return Ie(r);if(F.kind==="literal")return wi(F.source,A,b,n,r,t);let ue=Gm(g,n.commandView?.redirections??[],n.hasPipelineInput??!1,n.literalShellInput);if(ue.kind==="dynamic")return Ie(r);if(ue.kind==="literal")return r?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:ue.source,depth:t+1}),n.analyzeNested(ue.source,{effectiveCwd:A,envAssignments:b})}}if(!s&&(v==="source"||v===".")){let R=h[1]==="-p"?2:null;if(R!==null){let pn=n.commandView?g[R]:void 0;if(!pn)return null;if(pn.provenance!=="literal")return Ie(r)}let k=R===null?1:3,F=h[k]==="--"?k+1:k,ue=n.commandView?g[F]:void 0;if(!ue)return null;if(ue.provenance==="literal")return wi(ue.text,A,b,n,r,t);if(n.strict||!n.commandView||!Va(n.commandView))return Ie(r)}if(He.has(v)&&!l){if(!s&&n.strict&&tl(Or(h),g))return Ie(r);let R=Zd(h,(F)=>ln(n.analyzeNested(F,{effectiveCwd:A,envAssignments:b}))),k=P(R,n.policy);if(k)return r?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:k.reason}),Ee(k)}if(qe(v)&&!l){if(!s&&n.strict&&tl(Ho(h),g))return Ie(r);let R=td(h);if(a&&s)return eR(v,R,A,b,n,s);if(R){let k=fe(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(r?.recordSegment({type:"interpreter",interpreter:v,codeArg:R,paranoidBlocked:k}),k){let ue=P(S("interpreter.one-liner-paranoid",yr),n.policy);if(ue)return Ee(ue)}if(sa(v,R))return null;r?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:R,depth:t+1});let F=n.analyzeNested(R,{effectiveCwd:A,envAssignments:b});if(F&&!Pf(F,R))return F;if(Cr(R,void 0,!n.strict)){let ue=P(S("interpreter.dangerous-command",Pn),n.policy);if(ue)return r?.recordSegment({type:"dangerous-text",token:R,matched:!0,reason:Pn}),Ee(ue)}r=void 0}}if(v==="busybox"&&h.length>1)return Rf(y.wrapperNormalizationBudget),r?.recordSegment({type:"busybox",subcommand:h[1]??"unknown"}),r?.recordSegment({type:"recurse",reason:"busybox",innerCommand:h.slice(1).join(" "),depth:t+1}),Fn(g.slice(1),t,{...y,effectiveCwd:A,envAssignments:b});let G=s?null:P(vf(v,h),n.policy);if(G)return r?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:G.reason}),Ee(G);let Se=r===y.trace?y:{...y,trace:r},ze={words:g,head:v,cwd:T,originalCwd:x,envAssignments:b,allowTmpdirVar:Q,dynamicArguments:f.words.some((R)=>R.provenance==="command-substitution"),depth:t,effectiveCwd:A,options:Se,analyzeChildTokens:(R,k)=>a&&s?rl(R,t,Se,{...s,cwd:k??void 0,effectiveCwd:k??void 0}):ln(Fn(J(R),t+1,{...Se,child:void 0,commandView:void 0,effectiveCwd:k,envAssignments:b}))??Et(R,Se.policy.rules),analyzeChild:(R,k)=>rl(R,t,Se,k)},pt=s&&(v==="xargs"||v==="parallel")?void 0:Af(v);if(v==="rm"||v==="xargs"||v==="parallel")r?.recordSegment({type:"tmpdir-check",tmpdirValue:b.has("TMPDIR")||n.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:Q});let Ve=r&&v==="git"?Am(ze.words,nl(ze)):void 0,zi=_f(Ve?Ve.match:pt?.(ze)??null,n.policy);if(r)oR(ze,zi,Ve?.relaxation??null);if(zi)return Ee(zi);if(a&&s&&(v==="rm"||v==="rmdir")){if(!(v==="rm"&&(nt(h)||s.dynamicRmInput)))return null;return(s.dynamicRmInput?zn(s,n.policy):null)??tR(s,n.policy)}let Tl=!s&&pt===void 0&&!uo.has(v),Hi=r&&Tl?[]:void 0;if(Tl)for(let R=1;R<h.length;R++){let k=h[R];if(!k)continue;Hi?.push(k);let F=_f(Qx(h,R,t,Se,T,x,A,b),n.policy);if(F)return r?.recordSegment({type:"fallback-scan",tokensScanned:Hi??[],embeddedCommandFound:O(k)}),Ee(F)}if(r?.recordSegment({type:"fallback-scan",tokensScanned:Hi??[]}),l&&s&&!s.wrappedByTransparent)return null;let qr=Et(h,n.policy.rules);if(r?.recordSegment({type:"custom-rules-check",rulesChecked:n.policy.rules.length>0,matched:!!qr,reason:qr?.reason}),qr)return Ee(qr);return a&&s?zn(s,n.policy):null}function rl(e,t,n,r){return ln(Fn(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 Qx(e,t,n,r,o,i,s,a){for(let l of tt(e.slice(t),{environment:r.environment,cwd:o,envAssignments:a,policy:r.policy})){let c=l.tokens[0];if(!c)continue;let u=O(c);if(Tf(c,u)||Af(u)!==void 0&&u!=="xargs"&&u!=="parallel"||l.wrappedByTransparent&&r.policy.rules.length>0)r.budget.charge("derivedTokens",e.length-t);let d=rl(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:!Ar(l.envAssignments,r.environment),worktreeMode:!1,wrappedByTransparent:l.wrappedByTransparent});if(d)return d}return null}function eR(e,t,n,r,o,i){if(!t)return zn(i,o.policy);if(fe(o.policy,"interpreter.one-liner-paranoid",!!o.paranoidInterpreters)){let a=P(S("interpreter.one-liner-paranoid",yr),o.policy);if(a)return Ee(a)}if(sa(e,t))return zn(i,o.policy);let s=o.analyzeNested(t,{effectiveCwd:n,envAssignments:r});if(s&&!Pf(s,t))return s;if(Cr(t,void 0,!o.strict)){let a=P(S("interpreter.dangerous-command",Pn),o.policy);if(a)return Ee(a)}return zn(i,o.policy)}function Pf(e,t){if(e.ruleId==="raw-text.dangerous-command")return!0;return(e.reason.startsWith(si)||e.reason===On)&&!mo(t)}function Gn(e,t){let n=e.shellDynamicMatch?P(e.shellDynamicMatch,t):null;return n?Ee(n):null}function zn(e,t){let n=e.dynamicSourceInput&&e.dynamicSourceMatch?P(e.dynamicSourceMatch,t):null;return n?Ee(n):null}function tR(e,t){let n=e.dynamicInput&&e.rmDynamicMatch?P(e.rmDynamicMatch,t):null;return n?Ee(n):null}function nR(e,t,n,r,o,i){let s=tm(e);if(s.argvSource?.kind==="absent")return Ie(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 Ie(o);let a=hr(e,t,r.environment.paths,r.budget),l=a?r.literalHeredocFiles?.get(a):void 0;if(l===void 0)return s?Ie(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 rR(e){let t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.at(-1)===t?e.slice(1,-1):e}function oR(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 Rf(e){if(e.iterations>=X.wrapperPeelIterations.cap)throw new D("wrapperPeelIterations");e.iterations++}function Ee(e){return{reason:e.reason,ruleId:e.id||void 0,intent:e.intent}}function Ie(e){return e?.recordSegment({type:"error",message:Ir}),Ee(iR())}function iR(){return{id:"",reason:Ir,intent:"stop_and_explain"}}function Tf(e,t){return ee.has(t)||e==="$SHELL"||e==="${SHELL}"||ee.has(I(t))}function _f(e,t){return e?.id.startsWith("custom.")||e?.id==="raw-text.dangerous-command"?e:P(e,t)}var sR=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,aR=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function lR(e,t){let n=Of(e,t);if(n.length===0)return!1;let r=n[kf(n)];if(r==="cd"||r==="pushd"||r==="popd")return!0;return sR.test(e.join(" "))}function If(e,t,n,r,o){if(e.dialect==="powershell"){let h=uR(e.words,o);if(h.kind==="none")return;if(!t||h.kind==="unknown")return null;return wf(pR(h.target),t,n.paths)}let i=e.words.map(w),s=i.some((h)=>/^CDPATH\+?=/.test(h));if(!lR(i,n))return s?null:void 0;if(!t)return null;let a=Of(i,n,t),l=kf(a);if(l===-1||a[l]!=="cd")return null;let c=a.slice(l+1),u=c.findIndex((h)=>h.length<=1||!h.startsWith("-")||h==="--");if((u===-1?c:c.slice(0,u)).some((h)=>!/^-[LP]+$/.test(h)))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.some((h)=>h.provenance==="variable"&&h.text===p)?cR(p,r):p;if(g===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(g)&&(s||n.env.has("CDPATH")))return null;return wf(g,t,n.paths)}function cR(e,t){let n=Nr(e,t);return n.startsWith("~")||/[\s$`*?[]/.test(n)?null:n}function wf(e,t,n){if(!e||e==="-"||e.includes("$")||e.includes("`"))return null;try{return Lt(t,e,n)}catch{return null}}function uR(e,t){let n=dR(e[0])?1:0,r=e[n];if(!mR(r,n===1))return{kind:"none"};let o=r.text.toLowerCase(),i=o.split(/[\\/]/).pop()??o;if(!aR.has(i))return{kind:"none"};if(o!==i||i==="pop-location"||i==="popd")return{kind:"unknown"};return fR(e.slice(n+1),t)}function dR(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&(e.text==="&"||e.text===".")}function mR(e,t){return e?.provenance==="literal"&&(t||!e.quoted&&e.raw===e.text)}function fR(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 pR(e){return e.includes("::")?void 0:e.replaceAll("\\","/")}function kf(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 Of(e,t,n){let r=gR(e);return Wt([...r],t,n)}function gR(e){let t=0;while(t<e.length){let n=e[t];if(n!=="{"&&n!=="("&&n!=="$(")break;t++}return e.slice(t)}var hR="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",cn="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 ll(e,t,n,r){if(t>=X.recursionDepth.cap)return n.trace?.recordSegment({type:"error",message:st}),{reason:st,segment:e,intent:"stop_and_explain"};let o=r??n.factStore?.getCommandProgram(e,n.shell??"auto")??Ye(e,n.shell);if(o.status==="limited")return n.trace?.recordSegment({type:"error",message:st}),{reason:st,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 al(e,n);let u=`${si}: ${c.message}`;return n.trace?.recordGlobal({type:"error",message:u}),{reason:u,segment:e,intent:"stop_and_explain"}}return Gf(e,n),{reason:On,segment:e,intent:"stop_and_explain"}}if(n.strict&&o.status==="partial")return Gf(e,n),{reason:On,segment:e,intent:"stop_and_explain"};if(o.issues.some((c)=>c.code.includes("quote")))return al(e,n);let s=n.cwd,a=n.effectiveCwd!==void 0?n.effectiveCwd:n.cwd,l=pm(n.environment.env,n.envAssignments);return Ti(o,t,{...n,rootProgram:o},s,[{effectiveCwd:a,shellGitContextState:l,literalHeredocFiles:new Map(n.literalHeredocFiles),functionDefinitions:new Map(n.functionDefinitions)}]).result}function Ti(e,t,n,r,o){let i=[...o],s,a;for(let[l,c]of e.nodes.entries()){if(c.kind==="connector"){a=c.operator;continue}let u=e.nodes[l+1],m=u?.kind==="connector"?u.operator:void 0,d=yR(e,l,c,a,m),f=a==="&&"||a==="||",p=f?s:void 0,g=a==="&&"?p?.success??i:a==="||"?p?.failure??i:i,h=a==="||"?p?.success??[]:[],y=a==="&&"?p?.failure??[]:[],b=f||Bn(m);if(c.kind==="function"){let oe=g.flatMap((ie)=>{let K=$n(ie);return K.functionDefinitions.set(c.name,c.body),ol(ie,[K],d,m==="&",Bn(m))}),ce=il(oe,[],h,y,a,m);i=ce.states,s=ce.conditionalStates,a=void 0;continue}if(c.kind==="group"){let oe=[],ce=[];for(let K of g){let G=Ti(c.body,t,n,r,[$n(K)]);if(G.result)return G;if(oe.push(...ol(K,G.states,d,m==="&",Bn(m))),b)ce.push(K,...d?G.states.map((Se)=>Ai(K,Se)):G.states)}let ie=il(oe,ce,h,y,a,m);i=ie.states,s=ie.conditionalStates,a=void 0;continue}if(c.kind!=="command")continue;let E=n.trace?.flattenNested?n.trace.currentSegmentIndex:n.trace?.allocateSegment(),v=e.nodes[l-2],T=Ii(a)&&v?.kind==="command"?Nm(v)??bR(v):void 0,x=[],A=[];for(let oe of g){let ce=SR(c,t,n,r,[$n(oe)]);if(ce.result)return{result:ce.result,states:i};let ie=e.dialect==="powershell"?ce.states:ce.states.map((K)=>Ai(oe,K));for(let K of ie){let G=$n(K),Se=xR(c,t,n.trace?{...n,trace:Ff(n.trace,E)}:n,r,G,Ii(a),T);if(Se)return{result:Se,states:i};let ze=FR(c,G.functionDefinitions);if(ze)n.budget.charge("derivedTokens",ki(ze));let pt=ze?t+1>=X.recursionDepth.cap?sl(c.displayText,n,[G]):Ti(ze,t+1,n,r,[G]):{result:null,states:WR(c,G)};if(pt.result)return pt;if(x.push(...ol(oe,pt.states,d,m==="&",Bn(m))),b)A.push(oe),A.push(...pt.states.map((Ve)=>d?Ai(oe,Ve):Ve))}}let Q=il(x,A,h,y,a,m);i=Q.states,s=Q.conditionalStates,a=void 0}return{result:null,states:i}}function yR(e,t,n,r,o){if(n.kind==="group"&&n.style==="subshell")return!0;if(e.dialect==="posix"&&(Ii(r)||Ii(o)))return!0;if(o==="&")return!0;return e.dialect==="powershell"&&n.kind==="group"&&n.style==="brace"&&CR(e,t)}function ol(e,t,n,r,o){let i=n?t.map((a)=>Ai(e,a)):[...t],s=o?i.flatMap((a)=>Hn(e.literalHeredocFiles,a.literalHeredocFiles)?[a]:[{...a,literalHeredocFiles:new Map(e.literalHeredocFiles)},a]):i;return r?[e,...s]:s}function Ai(e,t){return{...e,literalHeredocFiles:new Map(t.literalHeredocFiles)}}function CR(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(vR(n))return!0;return n.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function Ii(e){return e==="|"||e==="|&"}function bR(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 Bn(e){return e==="&&"||e==="||"}function il(e,t,n,r,o,i){let s={success:Pi([...n,...e]),failure:Pi([...r,...t])},a=Bn(i)?s:void 0;return{states:Bn(o)||a?Pi([...s.success,...s.failure]):s.success,conditionalStates:a}}function Ff(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 SR(e,t,n,r,o){let i=e.nested.map((s)=>({program:s,depth:t}));if(e.dialect==="powershell"){let s=ER(e);if(s){if(t+1>=X.recursionDepth.cap)return sl(s,n,o);let a=Ye(s,"powershell");if(a.status==="limited")return sl(s,n,o);if(a.status!=="complete")return Mf(i,n,r,o);n.budget.charge("derivedTokens",ki(a)),i.push({program:a,depth:t+1})}}return Mf(i,n,r,o)}function vR(e){let t=e.words[0];return t?.provenance==="variable"&&e.words.at(-1)?.text==="="?t.text.toLowerCase():void 0}function Mf(e,t,n,r){let o=[...r];for(let i of e){let s=[];for(let a of o){let l=Ti(i.program,i.depth,t,n,[$n(a)]);if(l.result)return l;s.push(...l.states)}o=Pi(s)}return{result:null,states:o}}function ER(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 ki(e){return e.nodes.reduce((t,n)=>t+(n.kind==="command"?n.words.length+n.nested.reduce((r,o)=>r+ki(o),0):n.kind==="group"||n.kind==="function"?ki(n.body):0),0)}function sl(e,t,n){return t.trace?.recordSegment({type:"error",message:st}),{result:{reason:st,segment:e,intent:"stop_and_explain"},states:[...n]}}function xR(e,t,n,r,o,i,s){let a={...n,environment:{...n.environment,env:o.shellGitContextState.env}},l=IR(e,!a.strict);if(l&&a.strict)return a.trace?.recordSegment({type:"error",message:l}),{reason:l,segment:e.source,intent:"stop_and_explain"};zf(e,o,"before-consumer",a.environment.paths,a.budget);let c=_n(e.dialect,e.words),u=c.map(w),m=e.displayText,d=fm(c,o.shellGitContextState),f=hm(d,o.shellGitContextState);if(e.dialect==="powershell"){let h=P(Bd(e,i,HR(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 zR(m,h)}if(u.length===1&&u[0]?.includes(" ")&&!lr(e.dialect,e.words)){let h=P(Be(u[0]),a.policy),y=h!==null&&!a.strict&&Ju(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 b=Df(e,l,o,f,s,a);if(b)return b;return za(d,o.shellGitContextState),null}let p=Fn(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 b=y&&Object.hasOwn(y,"effectiveCwd")?y.effectiveCwd:o.effectiveCwd,E=ll(h,t+1,{...a,effectiveCwd:b,envAssignments:y?.envAssignments??f,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:y?.functionDefinitions,worktreeMode:y?.worktreeMode??a.worktreeMode,trace:a.trace?Ff(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=Df(e,l,o,f,s,a);if(g)return g;return za(d,o.shellGitContextState),null}function Df(e,t,n,r,o,i){let s=kR(e,t,n,r??new Map,i);if(s)return s;return zf(e,n,"after-consumer",i.environment.paths,i.budget),n.literalHeredocFiles.clear(),wR(e,t,n,i.environment.paths,i.budget),DR(e,n,o,i.environment,i.trace),null}var RR=new Set([">>","<>"]);function zf(e,t,n,r,o){for(let s of e.redirections){if(!(n==="before-consumer"?_R(s):RR.has(s.operator)))continue;Nf(s.target,t,r,o)}if(n!=="before-consumer"||!Ce(e.words[0],"tee"))return;let i=Hf(e.words.slice(1));if(!i)return;for(let s of i.operands)Nf(s,t,r,o)}function _R(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 Nf(e,t,n,r){let o=e?.provenance==="literal"?hr(e.text,t.effectiveCwd,n,r):void 0;if(!o)return;t.literalHeredocFiles.delete(o)}function wR(e,t,n,r,o){if(t)return;let i=e.redirections.find((s)=>s.operator==="<<"||s.operator==="<<-")?.heredoc;if(!i)return;for(let s of AR(e)){let a=hr(s.text,n.effectiveCwd,r,o);if(!a||!ed(a))continue;if(!n.literalHeredocFiles.has(a)&&n.literalHeredocFiles.size>=X.trackedHeredocFiles.cap)throw new D("trackedHeredocFiles");n.literalHeredocFiles.set(a,i.body)}}function AR(e){let t=TR(e.redirections)?.target,n=Lf(t)?[t]:[];if(Ce(e.words[0],"cat"))return PR(e.words)?n:[];if(!Ce(e.words[0],"tee"))return[];let r=Hf(e.words.slice(1));if(!r||r.append||r.hasUnsupportedOptions||!r.operands.every(Lf))return[];return[...r.operands,...n]}function PR(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 TR(e){let t=e.findLast((n)=>(n.fd??([">",">|",">>",">&"].includes(n.operator)?1:0))===1);return t?.operator===">"||t?.operator===">|"?t:void 0}function Hf(e){let t=[],n=!0,r=!1,o=!1;for(let i of e){if(i.provenance!=="literal")return;if(n&&Ce(i,"--")){n=!1;continue}if(n&&!i.quoted&&i.raw===i.text&&/^-[^-]/.test(i.text)){r||=i.text.slice(1).includes("a"),o||=Array.from(i.text.slice(1)).some((s)=>s!=="a"&&s!=="i");continue}if(n&&!i.quoted&&i.raw===i.text&&i.text.startsWith("--")){r||=i.text==="--append",o||=i.text!=="--append"&&i.text!=="--ignore-interrupts";continue}t.push(i)}return{operands:t,append:r,hasUnsupportedOptions:o}}function Lf(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 Ce(e,t){return e?.text===t&&e.raw===t&&e.provenance==="literal"&&!e.quoted}function cl(e){return e.quotedDelimiter||!/[$`\\]/.test(e.body)}function IR(e,t){let n=e.redirections.filter((a)=>a.operator==="<<"||a.operator==="<<-");if(n.length===0)return;if(n.length!==1)return cn;let r=n[0];if(!r?.heredoc)return cn;if(!cl(r.heredoc)&&!(t&&!/\$\(|`/.test(r.heredoc.body)))return hR;if(r.fd!==void 0&&r.fd!==0)return cn;if(e.redirections.some((a)=>a!==r&&["<","<<","<<-","<<<","<&","<>"].includes(a.operator)))return cn;let o=e.redirections.some((a)=>a!==r&&Wf(a.target));if(Ce(e.words[0],"cat"))return o?cn:void 0;if(Ce(e.words[0],"tee"))return o||e.words.slice(1).some(Wf)?cn:void 0;let i=e.words[0],s=e.words[1];if(Ce(i,"git")&&(Ce(s,"apply")||Ce(s,"commit")))return;if(Ce(i,"gh")&&(Ce(s,"pr")||Ce(s,"issue"))&&Ce(e.words[2],"create"))return;return cn}function Wf(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(MR(e,i,n,r,o))return null;let a=OR(e,i,o);if(a!==void 0)return a?{reason:a.reason,segment:e.displayText,ruleId:a.id,intent:a.intent}:null;let l=al(s.length===i.length?s.join(`
|
|
42
|
-
`):e.source,o);return l?{...l,segment:e.displayText}:null}function OR(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=Ce(e.words[0],"uv")&&Ce(e.words[1],"run")?e.words.slice(2):e.words,i=o[0];if(i?.provenance!=="literal"||!qe(i.text))return;let s=o.findIndex((m)=>Ce(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=fe(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(n.trace?.recordSegment({type:"interpreter",interpreter:i.text,codeArg:l,paranoidBlocked:c}),c){let m=P(S("interpreter.one-liner-paranoid",yr),n.policy);if(m)return m}if(!Cr(l,void 0,!n.strict))return null;let u=P(S("interpreter.dangerous-command",Pn),n.policy);if(!u)return null;return n.trace?.recordSegment({type:"dangerous-text",token:l,matched:!0,reason:u.reason}),u}function MR(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=Xt(e.words,o.environment,n.effectiveCwd,r),a=s.words.map(w),l=O(a[0]??"");if((s.envSplitValues?.length??0)>0||!ee.has(l)&&!ee.has(I(l)))return!1;return xt(a)}function DR(e,t,n,r,o){let i=If(e,t.effectiveCwd,r,t.shellGitContextState.shellAssignments,n);if(i===null)o?.recordSegment({type:"cwd-change",segment:e.words.map(w).join(" "),effectiveCwdNowUnknown:!0});if(i!==void 0)t.effectiveCwd=i}var NR=/^[A-Za-z_][A-Za-z0-9_]*$/,LR=8;function WR(e,t){let n=e.words[1]?.text;if(e.dialect!=="posix"||e.words[0]?.text!=="for"||n===void 0||!NR.test(n))return[t];let r=e.words.slice(3);if(!(e.words[2]?.text==="in"&&r.length>=1&&r.length<=LR&&r.every((i)=>i.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(i.text))))return t.shellGitContextState.shellAssignments.delete(n),[t];return r.map((i)=>{let s=$n(t);return s.shellGitContextState.shellAssignments.set(n,i.text),s})}function $n(e){return{effectiveCwd:e.effectiveCwd,shellGitContextState:gm(e.shellGitContextState),literalHeredocFiles:new Map(e.literalHeredocFiles),functionDefinitions:new Map(e.functionDefinitions)}}function Pi(e){let t=[];for(let n of e){if(!t.some((r)=>GR(r,n)))t.push(n);if(t.length>X.controlFlowStates.cap)throw new D("controlFlowStates")}return t}function GR(e,t){return e.effectiveCwd===t.effectiveCwd&&Hn(e.shellGitContextState.env,t.shellGitContextState.env)&&Hn(e.literalHeredocFiles,t.literalHeredocFiles)&&Hn(e.functionDefinitions,t.functionDefinitions)&&Hn(e.shellGitContextState.effectiveEnvAssignments,t.shellGitContextState.effectiveEnvAssignments)&&Hn(e.shellGitContextState.shellAssignments,t.shellGitContextState.shellAssignments)&&e.shellGitContextState.bodyDepth===t.shellGitContextState.bodyDepth&&e.shellGitContextState.bodyAssignments.size===t.shellGitContextState.bodyAssignments.size&&[...e.shellGitContextState.bodyAssignments].every((n)=>t.shellGitContextState.bodyAssignments.has(n))}function Hn(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 FR(e,t){let n=cr(e);return n===void 0?void 0:t.get(n)}function zR(e,t){if(!t)return null;return{reason:t.reason,segment:e,ruleId:t.id,intent:t.intent}}function HR(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 al(e,t){let n=P(Be(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 Gf(e,t){let n={type:"strict-unparseable",rawCommand:e,reason:On},r=t.trace?.currentSegmentIndex;if(r===void 0)t.trace?.recordGlobal(n);if(r!==void 0)t.trace?.recordSegment(n)}var BR=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function Bf(e,t,n,r){let o=ll(e,0,{...t,...Su(t),budget:t.budget??de(),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 $f(e,t,n){try{return{decision:e()}}catch(r){let o=$R(r,t,n);if(!o)throw r;return o}}function $R(e,t,n){if(!(e instanceof D)||!BR.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 UR=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),dl=new Set(["cc-safety-net","ccsn"]),jR=new Set(["bunx","npx","pnpx"]),VR=new Set(["pnpm","yarn"]),KR=new Set(["npm","pnpm","yarn"]),qR=new Set(["bun","node"]);function Mi(e,t,n={}){if(dl.has(e))return 0;if(jR.has(e)){if(n.broad)return ul(t);let o=t[0]==="-y"||t[0]==="--yes"?1:0;return Oi(t[o])?o+1:null}let r=n.broad?t.findIndex((o)=>!o.startsWith("-")):0;if(r!==-1&&KR.has(e)&&n.broad&&t[r]==="exec"){let o=ul(t.slice(r+1));return o===null?null:r+1+o}if(VR.has(e)){if(e==="yarn"&&!n.broad)return null;if(!n.broad)return t[0]==="dlx"&&Oi(t[1])?2:null;if(r===-1||t[r]!=="dlx")return null;let o=ul(t.slice(r+1));return o===null?null:r+1+o}if(qR.has(e)){let o=n.broad&&r!==-1?r:0;if(Uf(t[o]))return o+1;if(e==="bun"&&t[o]==="run"&&Uf(t[o+1]))return o+2}return null}function ul(e){let t=e.findIndex((r)=>Oi(r));if(t===-1)return null;let n=t;while(n<e.length){let r=e[n]??"";if(!r.startsWith("-")&&!Oi(r))break;n++}return n}function Oi(e){if(!e)return!1;let t=e.indexOf("@");if(t===-1)return dl.has(e);if(t===0)return!1;let n=e.slice(t+1);if(n===""||n.includes("/")||n.includes(":"))return!1;return dl.has(e.slice(0,t))}function Uf(e){let t=e?.replaceAll("\\","/");return[...UR].some((n)=>t===n||t?.endsWith(`/${n}`))}var jf="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 Vf(e,t,n){let r=Pe(e,"input-candidate");if(!r)return null;let o=In(r.shell,e.invocation.context.executionCwd,t,n,{findSegmentTarget:(i)=>YR(i,t),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return o?{target:o}:null}function YR(e,t){let n=Wt([...e],t),r=n.slice(1),o=Mi(I(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 Hr=require("node:path");var Zf="This path contains the protected policy config and you must not modify or delete it.",ZR=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function Xf(e,t,n){let r=n_(e.invocation.context,t,n);if(e.invocation.route.kind==="patch")return Kf(e.paths,!1,e.invocation.context.executionCwd,r,t,n);let o=Pe(e,"input-candidate");if(e.invocation.route.kind==="command")return o?qf(o.shell,e.invocation.context.executionCwd,r,t,n):null;if(e.invocation.route.kind==="unknown"&&o){let i=qf(o.shell,e.invocation.context.executionCwd,r,t,n);if(i)return i}return Kf(e.paths,e.invocation.route.kind==="grep"||e.invocation.route.kind==="glob"||Jr(e.invocation.toolName),e.invocation.context.executionCwd,r,t,n)}function Kf(e,t,n,r,o,i){if(t)return null;let s=e.find((a)=>Br(a,n,r,o,i));return s?{target:s}:null}function qf(e,t,n,r,o){let i=In(e,t,r,o,{findSegmentTarget:(s,a)=>XR(s,a,n,r,o)?.target??null,isRedirectionTarget:(s,a)=>Br(s,a.cwd,n,r,o),findMalformedTarget:(s)=>t_(s,t,n,r,o)?.target??null});return i?{target:i}:null}function XR(e,t,n,r,o){if(Rr(e))return null;let i=Gt([...e],r),s=I(i[0]??"").toLowerCase(),a=i.slice(1);if(s==="rm"&&JR(a)){let l=QR(a).find((c)=>Yf(Ae(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(s==="find"){if(mi(i,1)||Oa(i,r)){let c=(Mr(J(i))??J(["."])).find((u)=>{let m=Ae(u.text,t.variables);return Br(m,t.cwd,n,r,o)||Yf(m,t.cwd,n,r,o)})?.text;if(c)return{target:c}}}if(s==="mv"){let l=Jo(a).sources.find((c)=>r_(Ae(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(e_(i,s))return null;for(let l of[...e,...i])for(let c of Jf(l))if(Br(Ae(c,t.variables),t.cwd,n,r,o))return{target:c};return null}function JR(e){return e.some((t)=>t==="--recursive"||t.startsWith("-")&&!t.startsWith("--")&&/[rR]/.test(t.slice(1)))}function QR(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 e_(e,t){if(!ZR.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 t_(e,t,n,r,o){for(let i of e.split(/\s+/))for(let s of Jf(i))if(Br(s,t,n,r,o))return{target:s};return null}function Jf(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.indexOf("=");return n===-1||n===t.length-1?[t]:[t,t.slice(n+1)]}function n_(e,t,n){let r=(a)=>$r(he(a,e.executionCwd,t,n)),o=r(bn(t)),i=[r(nr(e.executionCwd)),r(nr(e.configCwd))],s=new Set(i.map((a)=>Hr.dirname(a)));for(let a=Hr.dirname(o);;a=Hr.dirname(a))if(s.add(a),Hr.dirname(a)===a)break;return{files:new Set([o,...i]),directoriesAndAncestors:s}}function Br(e,t,n,r,o){let i=Gl(e,t,r,o,(s)=>$r(s)===lo);return i!==null&&n.files.has($r(i))}function Yf(e,t,n,r,o){return n.directoriesAndAncestors.has($r(he(e,t,r,o)))}function r_(e,t,n,r,o){let i=$r(he(e,t,r,o));return n.files.has(i)||n.directoriesAndAncestors.has(i)}function $r(e){return process.platform==="win32"?e.toLowerCase():e}var xe=require("node:path"),up=require("node:url");var dp="Access to a sensitive path is not allowed.",mp=new Set(["echo","printf"]),o_=new Set(["find"]),i_=new Set(["!","do","elif","else","if","then","until","while"]),s_=new Set(["-exec","-execdir"]),a_=new Set([";","+"]),l_=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),c_=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),fp=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),u_=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),d_=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"]),pp=new Set(["-c","-e","-r","-E","--eval","--exec"]),m_=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"])]]),f_=new Set(["grep","rg"]),p_=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),g_=new Set(["commit","merge","notes","stash","tag"]),h_=new Set(["-m","--message"]),y_=new Set(["--grep"]),Qf=new Set(["jq","gojq","jaq"]),ep="f",tp="file",C_="files",b_=new Set(["e","f"]),S_=new Set(["regexp","file"]),v_=new Set(["e","f","A","B","C","m"]),E_=new Set(["regexp","file","after-context","before-context","context","max-count"]),ml="__CC_SAFETY_NET_PIPE_INPUT__",pl=/[\w./~@+-]*[./~][\w./~@+-]*/g,x_=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,R_=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,__=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,np=/\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,rp=/\b(?:system|exec|spawn|popen)\s*$/,w_=/\b(?:eval|exec)\s*\(/g,A_=/\b(?:eval|exec)\s*$/,P_=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 op(e,t,n,r,o,i){for(let s of e){let a=s.target;if(_w(a,s.cwd,t?.denyPaths??[],n,r,o))return{target:a,ruleId:"secret.deny-path"};if(i&&!i.has(a))continue;let l=xw(a,s.cwd,t,r,o);if(l){let c=!l.startsWith("secret.home.")&&!l.startsWith("secret.cli.");if(i&&(c&&r.paths.isDirectory(vp(a,s.cwd,r,o))||c&&s.written===!0&&!a.includes("$")&&!hl(a,s.cwd,r,o)||c&&/\s/.test(a)&&!a.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(a)&&!hl(a,s.cwd,r,o)))continue;if(!l.startsWith("secret.cli.")&&ww(a,s.cwd,t?.allowPaths??[],n,r,o))continue;return{target:a,ruleId:l}}}return null}function gp(e,t,n,r,o={}){let i=ip(e,n,r),s=op(i,t,e.invocation.context.configCwd,n,r);if(s===null||s.ruleId==="secret.deny-path"||o.strict!==!1)return s;let a=op(i,t,e.invocation.context.configCwd,n,r,new Set(ip(e,n,r,{standard:!0}).map((l)=>l.target)));return a?.ruleId!=="secret.deny-path"&&T_(e,n)?null:a}function T_(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 Xo(n.shell)){if(s.kind==="operator"&&s.boundary)return!1;if(s.kind==="redirection")return!1;if(s.kind==="operator")continue;r.push(vt(s.text,t))}let o=Pt(r);if(o.length===0)return!1;let i=it(o[0]??"").toLowerCase();if(e.invocation.route.kind==="unknown")return n.program.dialect==="powershell"&&(i==="ls"||i==="stat");return yl(i,o.slice(1))}function yl(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)=>l_.has(n))}function ip(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?Un(s.shell,e.store,r,t,o,n,I_(s)):[],...i==="unknown"?e.paths.map((a)=>({target:a,cwd:o})):[]]}function I_(e){return e.program.dialect==="powershell"}function Un(e,t,n,r,o,i,s=!1){if(e.status==="structural-limit")throw new Qe;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})),...sw(vt(e.source,r),t,n,r,o,i)],l=(c)=>vt(H_(c,s),r);return Zo(e,o,r,i,{word:l,segment:(c,u,m,d,f)=>{if(c.length===0)return null;if(a.push(...Ni(c,t,n,r,u.cwd,i,f)),m!==null)a.push(...O_(m,c,t,n,r,u.cwd,i));return null},redirection:(c,u)=>{if(c.body!==void 0&&c.consumer!==void 0)a.push(...hp(c.consumer,[c.body],t,n,r,u.cwd,i,(m)=>M_(c.consumer??[],m,t,n,r,u.cwd,i)));if(c.targetOrder==="legacy-segment")return ga;return a.push({target:l(c.target),cwd:u.cwd,...c.role==="file-write"?{written:!0}:{}}),null}}),a}function Cl(e,t,n,r,o,i){let s=t.getShellSyntax(e);if(s.status==="structural-limit")throw new Qe;return s.status==="complete"?Un(s,t,n,r,o,i):null}function Ni(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(Qf.has(it(Pt(g)[0]??"").toLowerCase()))return[...e.filter((h,y)=>s.has(y)).map(a),...Ni(g,t,n,r,o,i)]}let l=z_(e).map(a),c=Pt(e);if(c.length===0)return l;let u=c[0]??"",m=it(u).toLowerCase(),d=c.slice(1),f=c.findIndex((g)=>!i_.has(g));if(n.standard===!0&&f!==-1&&yl(it(c[f]??"").toLowerCase(),c.slice(f+1)))return l;let p=k_(u,m,d);if(p)return[...l,...p.map(a)];if(mp.has(m))return n.capturedOutput===!0?[...l,...yp(e).map(a)]:l;if(m==="eval")return[...l,...Cl(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)]:mt(m,g)).map(a)];if(m==="git")return[...l,...$_(d).map(a)];if(m==="gh")return[...l,...gl(m,d,p_).map(a)];if(Qf.has(m))return[...l,...B_(d).map(a)];if(f_.has(m))return[...l,...pw(d).map(a)];if(o_.has(m))return[...l,...K_(d,t,n,r,o,i).map(a)];if(He.has(m))return[...l,...d.flatMap((g)=>mt("awk",g)).map(a),...d.flatMap((g)=>Y_(g,t,n,r,o,i)),...d.flatMap(Z_).map(a)];if(m==="curl")return[...l,...d.flatMap((g)=>mt(m,g)).map(a),...U_(d).map(a)];if(_r(m)){let g=xr.has(m)?De([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 Qe;if(h.status==="complete")return[...l,...Un(h,t,n,r,o,i),...d.slice(g.commandIndex).filter((y)=>!y.startsWith("-")).map(a)]}return[...l,...q_(m,d,t,n,r,o,i)]}return[...l,...d.flatMap((g)=>mt(m,g)).map(a)]}function k_(e,t,n){let r=Mi(t,n);if(r===null||n[r]!=="explain")return null;let o=[e,...n.slice(0,r)],i=n.slice(r+1);for(let s=0;s<i.length;s++){let a=i[s];if(a==="--json"||a==="--help"||a==="-h")continue;if(a==="--cwd"){let l=i[s+1];if(l&&!l.startsWith("--"))o.push(l);s++;continue}return o}return o}function O_(e,t,n,r,o,i,s){if(W_(t,n,r,o,i,s)){let a=Pt(e),l=yl(it(a[0]??"").toLowerCase(),a.slice(1))?a.slice(1).filter((c)=>!c.startsWith("-")):[];return[...yp(e),...l].map((c)=>({target:c,cwd:i}))}return hp(t,D_(e),n,r,o,i,s,()=>[])}function M_(e,t,n,r,o,i,s){let a=Pt(e);if(!_r(it(a[0]??"").toLowerCase()))return[];return Cl(t,n,r,o,i,s)??[{target:t,cwd:i}]}function hp(e,t,n,r,o,i,s,a){let l=G_(e);if(l===null)return t.flatMap(a);return t.flatMap((c)=>xr.has(l)?Un(n.getShellSyntax(c),n,r,o,i,s):Di(l,c,n,r,o,i,s))}function yp(e){let t=Pt(e);if(t.length===0)return[];let n=it(t[0]??"").toLowerCase();if(!mp.has(n))return[];let r=t[t[1]==="--"?2:1];if(n==="printf"&&r!==void 0&&!r.startsWith("-")&&!r.replaceAll("%%","").includes("%"))return[bl(r.replaceAll("%%","%"))];return t.slice(1)}function D_(e){let t=Pt(e);if(t.length===0)return[];let n=it(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 N_(r);return[]}function N_(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[bl(t)];let r=e.slice(1);return Array.from({length:Math.ceil(r.length/n)},(o,i)=>L_(t,r.slice(i*n,(i+1)*n)))}function L_(e,t){let n=0;return bl(e.replace(/%%|%[bqs]/g,(r)=>{if(r==="%%")return"%";let o=t[n]??"";return n++,o}))}function bl(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 nw(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 rw(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(u_.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)=>d_.has(i)))continue;if(o.length>1)return!0;if(ow(e,r)===".")return!0;if(iw(e,r+n.length)==="(")return!0}return!1}function ow(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function iw(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function sw(e,t,n,r,o,i){return dw(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...Un(a,t,{...n,capturedOutput:!0},r,o,i),...aw(a,r)?lw(a,r).map((l)=>({target:l,cwd:o})):[]]})}function aw(e,t){let n=Xo(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||it(vt(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=vt(s.text,t);if(a==="--decode"||!a.startsWith("--")&&a.startsWith("-")&&/[dD]/.test(a))return!0}}return!1}function lw(e,t){return Xo(e).flatMap((n)=>n.kind==="word"?[vt(n.text,t)]:n.kind==="redirection"&&n.target?[vt(n.target,t)]:[]).flatMap(vl)}function vl(e){let t=uw(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||cw(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function cw(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function uw(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 dw(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(rr(o,n))continue;if(bp(e,r,n)){let i=mw(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=fw(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function mw(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(rr(i,n))continue;if(bp(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 fw(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 bp(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function pw(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===C_)o=!0;if(S_.has(m))r=!0;if(d!==void 0){if(m===tp)t.push(d);continue}if(E_.has(m)){let f=e[l+1];if(m===tp&&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(b_.has(h))r=!0;if(v_.has(h)){d=h,f=m.slice(g+1);break}}if(d==="")continue;if(f.length>0){if(d===ep)t.push(f);continue}let p=e[l+1];if(d===ep&&p!==void 0)t.push(p);l++;continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function Pt(e){let t=e.findIndex((n)=>!Sp(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:e.slice(t)}function Sp(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var gw=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),hw=".env.",yw=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),Cw=[".env.example.",".env.sample."];function bw(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function Sw(e){return e.length>0&&!/\s/.test(e)}function hl(e,t,n,r){let o=vp(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function vp(e,t,n,r){try{return Vr(e,t,n,r)}catch(o){if(o instanceof D)throw o;return""}}var vw=new Set(["node_modules","__pycache__"]),Ew=[["vendor","bundle"],["vendor","cache"]];function xw(e,t,n,r,o){if(bw(e))return null;let i=dt(e,t,r,o);if(!i)return null;let s=U(i.split("/").pop()??""),a=U(i),l=()=>Sw(s)||hl(e,t,r,o);if(yw.has(s)||Cw.some((d)=>s.startsWith(d)))return null;let c=U(Tw(e,t,r,o));for(let d of Rs){let f=`~/${d.suffixParts.join("/")}`;if((cp(a,f)||cp(c,f))&&At(d.id,n))return d.id}let u=Rw(i,t,n,r,o);if(u)return u;if(gw.has(s))return null;for(let d of xs)if(s===d.basename&&At(d.id,n))return d.id;if(s.startsWith(hw)&&At(go.id,n)&&l())return go.id;for(let d of _s)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){let f=s.slice(d.prefix.length)[0];if((f==="-"||f==="_")&&At(d.id,n)&&l())return d.id}for(let d of ws)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){if(s.slice(d.prefix.length)===d.suffix&&At(d.id,n))return d.id}if(Aw(a))return null;if(!s.includes(".")&&ir.pattern.test(s)&&At(ir.id,n))return ir.id;let m=Pw(s,n);if(m)return m;return null}function Rw(e,t,n,r,o){return ho.find((i)=>{if(!At(i.id,n))return!1;switch(i.id){case"secret.cli.claude-code":return H(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 H(e,V(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),["settings.json","settings.local.json"])||jr(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 H(e,dt("~/.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 H(e,s,["auth.json",".credentials.json"])||Ur(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 H(e,s,["config.toml"])||a.endsWith(".config.toml")&&H(e,s,[a])}case"secret.cli.gemini":return H(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 H(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()?jr(e,a,t,r,o):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...l].some((c)=>H(e,dt(c,t,r,o),["settings.json"]))}case"secret.cli.copilot-cli":{let s=V(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o);return H(e,s,["config.json"])||Ur(e,s,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return H(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 H(e,s,["server.token"])||Ur(e,s,["credentials"])||Ur(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"||H(e,V(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),s)||H(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 H(e,s,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(a)&&H(e,s,[a])||c.some((u)=>jr(e,u,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)??"")||H(e,s,l)||(c?.trim()?jr(e,c,t,r,o):!1)||["/Library/Application Support/opencode","/etc/opencode",...a].some((u)=>H(e,dt(u,t,r,o),l))}case"secret.cli.pi":return H(e,V(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["auth.json"]);case"secret.cli.pi.config":return H(e,V(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["models.json"]);case"secret.cli.amp":{let s=dt("~",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)=>H(e,l,["secrets.json"]))||Ur(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(dt("~",t,r,o),".config","amp")],l=U(e).split("/"),c=r.env.get("AMP_SETTINGS_FILE");return a.some((u)=>H(e,u,s))||l.at(-2)===".amp"&&s.includes(l.at(-1)??"")||(c?.trim()?jr(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 H(e,dt("~/.cursor",t,r,o),["auth.json"])||H(e,s,["auth.json"])||U(e).split("/").at(-1)==="mcp-auth.json"&&un(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 H(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"||H(e,V(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["config.toml","managed_config.toml","requirements.toml"])||H(e,dt("/etc/grok",t,r,o),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var lp=new WeakMap;function V(e,t,n,r,o){let i=lp.get(o)??new Map;lp.set(o,i);let s=`${n}\x00${e??""}\x00${t}`,a=i.get(s);if(a!==void 0)return a;let l=dt(e?.trim()?e:t,n,r,o);return i.set(s,l),l}function H(e,t,n){return n.some((r)=>Ep(e,be(t,r)))}function Ur(e,t,n){return n.some((r)=>un(U(e),U(be(t,r))))}function jr(e,t,n,r,o){return Ep(e,dt(t,n,r,o))}function Ep(e,t){return U(e)===U(t)}function be(e,...t){return ot([e,...t].filter(Boolean).join("/"))}function _w(e,t,n,r,o,i){if(n.length===0)return!1;let s=U(Vr(e,t,o,i));return n.some((a)=>un(s,U(Vr(a,r,o,i))))}function ww(e,t,n,r,o,i){if(n.length===0)return!1;let s=U(Vr(e,t,o,i));if(!s)return!1;let a=o.env.get("HOME")??o.home,l=a?ot(N(Oe(a),o.paths,i)):"",c=U(l),u=o.env.get("CC_SAFETY_NET_HOME"),m=U(u?ot(N(xe.resolve(Oe(u)),o.paths,i)):l&&ot(N(`${l}/.cc-safety-net`,o.paths,i)));if(m&&un(s,m))return!1;return n.some((d)=>{let f=Is(d);if(f&&xe.posix.basename(s)!==U(f.name))return!1;let p=U(Vr(f?.root??d,r,o,i));if(!p)return!1;if(c&&(c===p||c.startsWith(p.endsWith("/")?p:`${p}/`)))return!1;return un(s,p)&&!(f&&s===p)})}function Aw(e){let t=e.split("/");return t.some((n)=>vw.has(n))||Ew.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function Pw(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 As)if(r===o.extension&&At(o.id,t))return o.id;for(let o of Ps)if(o.pattern.test(r)&&At(o.id,t))return o.id;return null}function U(e){return e.toLowerCase()}function At(e,t){return!t?.disabledRules?.includes(e)}function dt(e,t,n,r){let{home:o,normalized:i}=El(e,n,r);if(!i)return"";if(!o)return i;let s=xl(i,o),a=xe.isAbsolute(s)?s:ot(xe.resolve(t,s)),l=ot(N(a,n.paths,r));if(!un(l,o)){if(xe.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 Tw(e,t,n,r){let{home:o,normalized:i}=El(e,n,r);if(!i||!o)return"";let s=xl(i,o),a=xe.posix.normalize(xe.isAbsolute(s)?s:ot(xe.resolve(t,s))),l=ot(Oe(n.env.get("HOME")??n.home)),c=(d)=>process.platform==="win32"?d.toLowerCase():d,u=[o,l].find((d)=>d!==""&&un(c(a),c(d)));if(u===void 0)return"";let m=a.slice(u.length);return m?`~${m}`:"~"}function Vr(e,t,n,r){let{home:o,normalized:i}=El(e,n,r);if(!i)return"";let s=o?xl(i,o):i;return ot(N(xe.isAbsolute(s)?s:xe.resolve(t,s),n.paths,r))}function El(e,t,n){let r=t.env.get("HOME")??t.home,o=r?ot(N(Oe(r),t.paths,n)):"",i=ot(Oe(Iw(vt(e,t))));return{home:o,normalized:i}}function Iw(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return up.fileURLToPath(e)}catch{return e}}function xl(e,t){if(e==="~")return t;if(e.startsWith("~/"))return be(t,e.slice(2));return e}function kw(e){if(process.platform==="win32")return!0;return xe.win32.parse(e).root.length>1}function ot(e){let t=e.trim(),n=(t.includes("\\")&&kw(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function un(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function it(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class dn 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 Ow={findPolicyMutation:Xf,findGitMetadataMutation:Ad,resolveGitMetadata:Mw,loadPolicySnapshot:bu,findSensitiveTarget:gp,analyzeCommand:Bf,getModes:is};function xp(e,t){let n={...Ow,...t.dependencies},r=Lw(e),o=Kr(e)?e.command:r,i=Ut("policy-protection",o,()=>wr(e)),s=Pe(i,"input-candidate"),a=Pe(i,"declared-command");if(Kr(e)&&e.command?.trim()&&a?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:st,intent:"stop_and_explain",evidence:{command:e.command,segment:e.command}}};if(s?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:$d,intent:"stop_and_explain"}};let l=de(),c=Ut("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd],t.environment)),u=Ut("policy-protection",o,()=>n.findPolicyMutation(i,t.environment,l));if(u){let E=o??u.target;return{stage:"policy-protection",decision:{kind:"deny",reason:Zf,intent:"hard_stop",evidence:{command:E,segment:u.target}}}}let m=Ut("policy-protection",o,()=>Vf(i,t.environment,l));if(m){let E=o??m.target;return{stage:"policy-protection",decision:{kind:"deny",reason:jf,intent:"hard_stop",evidence:{command:E,segment:m.target}}}}let d=Ut("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:Ue,intent:"hard_stop",evidence:{command:E,segment:d.target}}}}let f=Ut("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,...Dw(f)},y=p.secretProtection.enabled===!1?null:Ut("secret-protection",o,()=>n.findSensitiveTarget(i,p.secretProtection,t.environment,l,{strict:Kr(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:dp,intent:"hard_stop",ruleId:y.ruleId,evidence:{command:E,segment:y.target}}}}if(!Kr(e))return{stage:"non-command",...h,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...Rl("command-validation",o),...h};let b=Ut("command-analysis",o,()=>$f(()=>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}:{}},Nw(i),i.store),e.command,t.trace));if(b.decision){let E=!g.strict&&b.decision.kind==="deny"&&(b.decision.ruleId==="raw-text.dangerous-command"||b.decision.reason===Ir&&!/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/.test(b.decision.evidence?.segment??"")&&Be(e.command)===null);return{stage:"command-analysis",...h,..."errorCode"in b?{errorCode:b.errorCode}:{},decision:E?{...b.decision,ask:!0}:b.decision}}return{stage:"command-analysis",...h,decision:{kind:"allow"}}}function Mw(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 Dw(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function Nw(e){return Pe(e,"declared-command")?.program}function Lw(e){try{return It(e.input)}catch(t){let n=Kr(e)?e.command:void 0;throw new dn("policy-protection",Rl("policy-protection",t instanceof ve?void 0:n,t),t)}}function Ut(e,t,n){try{return n()}catch(r){throw new dn(e,Rl(e,r instanceof ve?void 0:t,r),r)}}function Rl(e,t,n){let r=n instanceof D||n instanceof Qe;return{stage:e,decision:{kind:"deny",reason:r?Ui:Zn,intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function Kr(e){return e.route.kind==="command"}var Wi=require("node:fs"),Vn=require("node:path");var le=require("node:fs"),jn=require("node:path");function Rp(e,t={}){return _o(bn(e,t),e.home).policy.audit.retention_days}var wl=86400000,Ww=".last-prune",Gw=/^\d{4}-\d{2}$/,Fw=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,_p=(e)=>Math.floor(e/wl);function Ap(e,t,n=()=>new Date){try{let r=n().getTime();if(!le.statSync(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=jn.join(t,Ww),i=le.statSync(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&_p(i)===_p(r))return;let s=r-Rp(e)*wl,a=new Date(r).toISOString().slice(0,7);for(let l of _l(t)){if(l.isDirectory()){zw(jn.join(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))Hw(jn.join(t,l.name),s)}le.writeFileSync(o,"",{mode:384}),le.utimesSync(o,r/1000,r/1000)}catch{}}function zw(e,t,n){for(let r of _l(e)){if(!r.isDirectory()||!Gw.test(r.name))continue;let o=jn.join(e,r.name);for(let i of _l(o)){if(!i.isFile())continue;let s=Fw.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+wl;if(!Number.isFinite(a)||a>=t)continue;Pp(jn.join(o,i.name))}if(r.name!==n)wp(o)}wp(e)}function Hw(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}),Ap(e,l,s.now)}catch{}}function Li(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function Zw(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&&Vn.isAbsolute(n)?n:null}function Xw(e){let t=Zw(e);return t?Vn.join(t,".cc-safety-net","logs"):null}function Ip(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=Tp(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?Tp(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 Tp(e){return"command"in e?e.command??"":""}function kp(e,t,n,r){if(!t)return;let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Al(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 Op(e,t,n,r){let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Al(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 Dp(e,t,n){try{let r=xp(t,{environment:e,...n.guard});return Mp(e,t,r,n),r}catch(r){if(!(r instanceof dn))throw r;throw Mp(e,t,r.evaluation,n,!(r.cause instanceof ve),{stage:r.stage,errorCode:Jw(r.cause)}),r}}function Mp(e,t,n,r,o=!0,i){kp(e,Ip(t,n,r.guard?.auditAllowed??!1,o,i),r.audit.getSessionId,{agent:r.audit.agent,shape:r.audit.shape})}function Jw(e){if(e instanceof D)return X[e.kind].errorCode;if(e instanceof ve)return"tool-input-limit";if(e instanceof Qe)return"structural-shell-syntax-limit";return"unexpected-error"}var ft=(e,t,n,r,o)=>nc(e.cwd,t,n,r,o.paths,process.cwd());function Qw(e,t){console.log(JSON.stringify(e(Ml(t))))}async function eA(e){let t;try{t=(await tc(process.stdin)).trim()}catch{e({reason:"Failed to parse hook input JSON."});return}if(!t){e({reason:"Missing hook input JSON."});return}return to(t,e,"Failed to parse hook input JSON.")}async function tA(e){let t=mc(),n=await eA(e.outputDeny);if(n===void 0)return;if(!n||typeof n!=="object"||Array.isArray(n)){te(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=iA(n),s=(p,g)=>{Op(t,p,()=>e.getSessionId(n),{agent:r,shape:o,toolName:g,cwd:i}),e.outputDeny(p)},a=e.getToolName(n);if(typeof a!=="string"||a.trim()===""){te((p)=>s(p),oA(n));return}let l=a,c=(p)=>s(p,l),u;try{u=e.getToolInput(n,l,c,t)}catch(p){if(!(p instanceof ve))throw p;te(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=It(u.input)}catch(p){if(!(p instanceof ve))throw p;te(c,void 0,l);return}let f=er(l,u.input,u.route,m,d??null);try{let p=Dp(t,f,{guard:{auditAllowed:fc(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.ask&&e.outputAsk?.(n,g))return;e.outputDeny(g);return}e.outputAllow?.()}catch(p){if(!(p instanceof dn))throw p;nA(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 nA(e,t){if(!Vt(ae.debug,t))return;console.error(`CC Safety Net debug: ${rA(e.stage)}: ${Nl(e.cause)}`)}function rA(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 oA(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 iA(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 ke(e){let t=(s)=>Qw(e.createDenyOutput,s),n=e.createAskOutput,r=n?(s,a)=>{let l=n(s,Dl(a));if(l===null)return!1;return console.log(JSON.stringify(l)),!0}:void 0,o=e.createAllowOutput,i=o?()=>console.log(JSON.stringify(o())):void 0;try{await tA({...e,outputDeny:t,outputAsk:r,outputAllow:i})}catch(s){console.error("CC Safety Net error:",s),t(gn())}}var sA=new Map([["run_command","auto"]]),aA=new Set(["absolutepath","directorypath","file_path","filepath","path","searchdirectory","searchpath","target_file","targetfile"]);function Np(e){return se(e,sA)}async function Lp(){await ke({agent:"antigravity-cli",createDenyOutput:(e)=>({decision:"deny",reason:e}),isSupported:()=>!0,getToolName:(e)=>e.toolCall?.name,getToolInput:(e,t)=>({ok:!0,input:mA(e.toolCall?.args,t),route:Np(t)}),getContext:lA,getSessionId:(e)=>e.conversationId})}function lA(e,t,n,r,o){let s=dA(e,o.paths).flatMap((u)=>{let m=lt([u],o.paths);return m?[m]:[]});if(!s[0])return mn(r,t,n),null;if(n!=="run_command"){let u;try{u=cA(t,n,s,o.paths)}catch(m){if(m instanceof ve)return mn(r,void 0,n),null;if(!(m instanceof D))throw m;return mn(r,t,n),null}if(!u)return mn(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 mn(r,t,n),null;let c=yt(l,s,o.paths);if(c){let u=Wp(c,s);if(!u)return mn(r,t,n,l),null;return{configCwd:u,executionCwd:c}}return mn(r,t,n,l),null}function cA(e,t,n,r){let o=Np(t),i=[...Qr(e,aA),...o.kind==="patch"?eo(e):[]].filter(Kn.isAbsolute),s=de(),a=new Set(i.flatMap((l)=>{let c=Wp(N(l,r,s),n);return c?[c]:[]}));if(a.size>1)return null;return[...a][0]??n[0]??null}function Wp(e,t){return t.filter((n)=>uA(e,n)).reduce((n,r)=>r.length>n.length?r:n,"")||null}function uA(e,t){let n=Kn.relative(t,e);return n===""||!n.startsWith("..")&&!Kn.isAbsolute(n)}function mn(e,t,n,r){let o=t&&typeof t==="object"?t.command:void 0;e(gn({command:typeof o==="string"?o:void 0,segment:r,toolName:n}))}function dA(e,t){if(e.workspacePaths===void 0)return[process.cwd()];let n=Array.isArray(e.workspacePaths)?e.workspacePaths.filter((r)=>typeof r==="string"&&r.trim()!==""):[];return lt(n,t)?n:[]}function mA(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 Gi=[{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"]}}],fL=Gi.slice().sort((e,t)=>e.doctorOrder-t.doctorOrder).map((e)=>e.id),Gp=Gi.filter((e)=>("runtime"in e)).slice().sort((e,t)=>e.runtime.order-t.runtime.order).map((e)=>({id:e.id,displayName:"displayName"in e.runtime?e.runtime.displayName:e.displayName,flags:e.runtime.flags,legacyFlags:"legacyFlags"in e.runtime?e.runtime.legacyFlags:[],description:e.runtime.description,legacyTopLevelFlags:e.runtime.legacyTopLevelFlags})),pL=Gi.slice().sort((e,t)=>e.install.order-t.install.order).map((e)=>({id:e.id,...e.install})).map(({order:e,...t})=>t),gL=Object.fromEntries(Gi.map((e)=>[e.id,e.displayName]));var fn=require("node:path");function Fp(e,t){if(e!==void 0&&e!==null&&typeof e!=="string")return"unknown";if(typeof e==="string"&&!fn.isAbsolute(e))return"unknown";try{let n=de(),r=typeof e==="string"&&e?N(e,t.paths,n):void 0,o=t.home,i=[["codex",t.env.get("CODEX_HOME")||fn.join(o,".codex")],["copilot-cli",t.env.get("COPILOT_HOME")||fn.join(o,".copilot")],["claude-code",t.env.get("CLAUDE_CONFIG_DIR")||fn.join(o,".claude")]],s=r?i.flatMap(([a,l])=>{if(!fn.isAbsolute(l))return[];return es(r,N(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 Fi="PreToolUse",zp="BeforeTool",Hp="pre_tool_call";async function qn(e){await ke({agent:e.agent,...e.getAgent?{getAgent:e.getAgent}:{},createDenyOutput:(t)=>({hookSpecificOutput:{hookEventName:Fi,permissionDecision:"deny",permissionDecisionReason:t}}),...e.canAsk?{createAskOutput:(t,n)=>e.canAsk?.(t)?{hookSpecificOutput:{hookEventName:Fi,permissionDecision:"ask",permissionDecisionReason:n}}:null}:{},isSupported:(t)=>t.hook_event_name===Fi,getToolName:(t)=>t.tool_name,getToolInput:(t,n)=>({ok:!0,input:t.tool_input,route:e.getToolRoute(n)}),getContext:e.getContext??ft,getSessionId:(t)=>t.session_id})}var fA=new Map([["Bash","posix"],["PowerShell","powershell"]]);function pA(e){return se(e,fA)}async function Bp(){await qn({agent:"claude-code",getAgent:(e,t)=>Fp(e.transcript_path,t),canAsk:(e)=>["default","acceptEdits","plan"].includes(e.permission_mode??""),getToolRoute:pA})}var gA=new Map([["Bash","auto"]]);async function $p(){await qn({agent:"codex",getToolRoute:(e)=>se(e,gA)})}var hA=new Map([["bash","auto"],["Bash","auto"],["powershell","powershell"],["PowerShell","powershell"]]);function yA(e){return se(e,hA)}async function Up(){await ke({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=to(e.toolArgs,n,"Failed to parse toolArgs JSON.");if(r===void 0)return{ok:!1};return{ok:!0,input:r,route:yA(t)}},getContext:ft,getSessionId:(e)=>typeof e.sessionId==="string"&&e.sessionId.trim()?e.sessionId:void 0})}var CA=new Map([["Shell","auto"]]);function bA(e){return se(e,CA)}async function jp(){await ke({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:bA(t)}),getContext:SA,getSessionId:(e)=>e.conversation_id})}function SA(e,t,n,r,o){let i=vA(e,o.paths);if(!i[0])return te(r,t,n),null;let s=yt(xA(e.cwd),i,o.paths);if(!s)return te(r,t,n,typeof e.cwd==="string"?e.cwd:void 0),null;if(t===null||typeof t!=="object"||Array.isArray(t))return{configCwd:s,executionCwd:s};if(!Object.hasOwn(t,"working_directory"))return{configCwd:s,executionCwd:s};let a=t.working_directory;if(typeof a!=="string"||a.trim()==="")return te(r,t,n),null;let l=yt(a,i,o.paths);if(!l)return te(r,t,n,a),null;return{configCwd:s,executionCwd:l}}function vA(e,t){return EA(e).flatMap((n)=>{let r=lt([n],t);return r?[r]:[]})}function EA(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 xA(e){return typeof e==="string"&&e.trim()!==""?e:"."}var RA=new Map([["run_shell_command","auto"]]);function _A(e){return se(e,RA)}async function Vp(){await ke({agent:"gemini-cli",createDenyOutput:(e)=>({decision:"deny",reason:e,systemMessage:e}),isSupported:(e)=>e.hook_event_name===zp,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:_A(t)}),getContext:ft,getSessionId:(e)=>e.session_id})}var wA=new Map([["run_terminal_command","auto"]]);function AA(e){return se(e,wA)}async function Kp(){await ke({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 te(n,e.toolInput,t),{ok:!1};return{ok:!0,input:e.toolInput,route:AA(t)}},getContext:PA,getSessionId:(e)=>e.sessionId})}function PA(e,t,n,r,o){let i=lt(TA(e),o.paths);if(!i)return te(r,t,n),null;let s=yt(IA(e.cwd),[i],o.paths);if(!s)return te(r,t,n,typeof e.cwd==="string"?e.cwd:void 0),null;return{configCwd:s,executionCwd:s}}function TA(e){let t=e.workspaceRoot===void 0?e.cwd:e.workspaceRoot;return typeof t==="string"&&t.trim()!==""?[t]:[]}function IA(e){return typeof e==="string"&&e.trim()!==""?e:"."}var qp=require("node:path");var kA=new Map([["terminal","posix"]]);async function Yp(){await ke({agent:"hermes-agent",createDenyOutput:(e)=>({action:"block",message:e}),isSupported:(e)=>e.hook_event_name===Hp,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:se(t,kA)}),getContext:OA,getSessionId:(e)=>e.session_id})}function OA(e,t,n,r,o){let i=ft(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 te(r,t,n),null;let a=lt([qp.resolve(i.configCwd,s)],o.paths);if(!a)return te(r,t,n,s),null;return{...i,executionCwd:a}}var Zp=new Map([["Bash","posix"]]);function MA(e){return se(e,Zp)}async function Xp(){await qn({agent:"kimi-code",getToolRoute:MA,getContext:(e,t,n,r,o)=>{let i=ft(e,t,n,r,o);if(!i)return null;let s=e.tool_input;if(!Zp.has(n)||!s||!Object.hasOwn(s,"cwd"))return i;let a=s.cwd;if(typeof a!=="string"||a.trim()==="")return te(r,t,n),null;let l=yt(a,[i.configCwd],o.paths);if(!l)return te(r,t,n,a),null;return{configCwd:i.configCwd,executionCwd:l}}})}var DA={"antigravity-cli":Lp,"claude-code":Bp,codex:$p,"copilot-cli":Up,cursor:jp,"gemini-cli":Vp,"grok-build":Kp,"hermes-agent":Yp,"kimi-code":Xp},Pl=Gp.map((e)=>({...e,run:DA[e.id]}));function Jp(e){let t=Yr({label:"hook",booleans:Object.fromEntries(Pl.map((r)=>[r.id,[...r.flags,...r.legacyFlags]]))},e);if(t.errors.length>0)return;let n=Pl.filter((r)=>t.flags[r.id]);return n.length===1?n[0]:void 0}function Qp(e){return Pl.find((t)=>t.legacyTopLevelFlags.some((n)=>n===e))}async function NA(){let e=process.argv.slice(2),t=e[0],n=Yr({label:"cc-safety-net",booleans:{version:["-V","--version"]},positionals:"list"},e);if(!n.help&&!n.flags.version){if(t?.toLowerCase()==="hook"){let i=Jp(e.slice(1));if(i){await i.run();return}}let o=Qp(t);if(o){await o.run();return}}let r=await import("../cli.js");await r.runCli(e)}NA().catch((e)=>{console.error("CC Safety Net error:",e),process.exit(1)});
|
|
41
|
+
`?e.trim().split(/\s+/).filter(Boolean):e.split(t).filter(Boolean)}function jr(e){if(!e)return!0;return e.provenance==="unknown"?!/[$`]/.test(_(e)):e.provenance==="literal"}function jn(e){return e?_(e):""}function Zm(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function el(e,t){return Ja(Je(e,"posix"),t)}function Vr(e){return el(e,new Set(Array.from(e.matchAll($m)).flatMap((t)=>{let n=t[1]??t[2];return n===void 0?[]:[n]})))}function Ja(e,t){if(e.status==="invalid"||e.status==="limited")return!1;let n=new Set(t);for(let r of e.nodes){if(r.kind==="group"){if(Ja(r.body,n))return!0;continue}if(r.kind!=="command")continue;if(r.nested.some((o)=>Ja(o,n))||Xm(r.words,n))return!0;Ox(r,n)}return!1}function Xm(e,t){let n=e.findIndex((s)=>Ue(s.text)===null);if(n===-1)return!1;let r=e[n];if(!r)return!1;if(Ur(r,t))return!0;let o=M(r.text);if(o==="source"||o==="."){let s=e[n+1]?.text==="--"?n+2:n+1;return Bm(e[s],t)}if(Q.has(o)){let s=e.slice(n),a=Ne(s.map((c)=>c.text)),l=a.commandIndex??a.scriptIndex;return!a.syntaxCheck&&l!==null&&Bm(s[l],t)}let i=Px(e,n,t);if(i===null)return!1;if(i===-1)return!0;return Xm(e.slice(i),t)}function Px(e,t,n){let r=M(e[t]?.text??"");if(r==="command")return Tx(e,t+1);if(r==="exec")return kx(e,t+1);if(r==="env")return Ix(e,t+1,n);return null}function Tx(e,t){for(let n=t;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return e[n+1]?n+1:null;if(/^-[p]*[vV][pvV]*$/.test(r))return null;if(/^-p+$/.test(r))continue;return n}return null}function kx(e,t){for(let n=t;n<e.length;n++){let r=e[n]?.text??"";if(r==="--")return e[n+1]?n+1:null;if(r==="-a"){n++;continue}if(/^-a.+/.test(r)||/^-[cl]+$/.test(r))continue;return n}return null}function Ix(e,t,n){for(let r=t;r<e.length;r++){let o=e[r],i=o?.text??"";if(i==="--")return e[r+1]?r+1:null;if(i==="-S"||i==="--split-string")return Ur(e[r+1],n)?-1:r+2;if(i.startsWith("-S")||i.startsWith("--split-string="))return Ur(o,n)?-1:r+1;if(i==="-u"||i==="--unset"||i==="-C"||i==="--chdir"||i==="-P"){r++;continue}if(i==="-i"||i==="-0"||i==="--null"||i.startsWith("-u=")||i.startsWith("--unset=")||i.startsWith("-C")||i.startsWith("--chdir=")||i.startsWith("-P"))continue;if(i.startsWith("-"))continue;if(Ue(i))continue;return r}return null}function Ox(e,t){if(!e.words.every((n)=>Ue(n.text)!==null))return;for(let n of e.words){let r=Ue(n.text);if(!r)continue;if(Ur(n,t))t.add(r.name)}}function Ur(e,t){if(!e)return!1;return e.parts.filter((n)=>n.provenance==="variable").some((n)=>Array.from(n.raw.matchAll($m)).some((r)=>{let o=r[1]??r[2];return o!==void 0&&(vx.test(o)||t.has(o))}))}function Bm(e,t){return!!e&&(e.parts.some((n)=>n.provenance!=="literal"&&n.provenance!=="variable")||Ur(e,t))}var tl="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",nl="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",Mx="__CC_SAFETY_NET_XARGS_INPUT__",ki="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",Ii="rm",Dx=/(?:^|[;&|]\s*|\b(?:eval|source)\s+|\b(?:ba|da|z|k)?sh\s+-c\s+)\s*["']?\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,Nx=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,Lx=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,Wx=/^(?:[0-9]+|[@*])$/;function ef(e,t){let n=e.map(_),{childStart:r,replacementToken:o}=pn(n),i=n.slice(r),s=v("xargs.shell-dynamic",nl);if(Fx(i,o,t)&&T(s,t.policy))return T(s,t.policy);for(let a of ot(i,t)){let l=a.tokens,c=o!==null&&l[0]!==i[0]&&(l[0]?.includes(o)??!1)?T(s,t.policy):null;if(c)return c;let u=af(l,o,a.wrapperEnvAssignments),m=a.head==="rm"&&o!==null&&of(l,o),d=t.analyzeChild(l,{...dn(a,t),dynamicInput:u,dynamicSourceInput:m||nf(l,a.head,o,a.wrapperEnvAssignments,u,t.environment,t.strict?void 0:t.analyzeNested),dynamicRmInput:m,shellDynamicMatch:s,dynamicSourceMatch:s,rmDynamicMatch:v("xargs.rm-recursive-force-dynamic",tl)});if(d)return d;let f=Gx(l,o,t.policy?.rules??[],T(s,t.policy));if(f)return f;if(a.head==="git"){let g=o===null?[...l,Mx]:l,h=o!==null&&(l.some((S)=>S.includes(o))||Array.from(a.envAssignments.values()).some((S)=>S.includes(o))),y=t.analyzeChild(g,{...dn(a,t),worktreeMode:o===null||h?!1:t.worktreeMode});if(y)return y}let p=At(l,t.policy?.rules??[]);if(p)return p}return null}function Gx(e,t,n,r){if(n.length===0)return null;if(t===null){for(let i of n){let s=At([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],n);if(s)return s}return null}let o=M(e[0]??"");if(!n.some((i)=>M(i.command)===o))return null;return e.slice(1).some((i)=>i.includes(t))?r:null}function tf(e,t,n){let r=e.indexOf(t);if(r===-1||e.indexOf(t,r+t.length)!==-1)return[];let o=Gm(e,r,t.length,n);return o===null?[]:[o]}function nf(e,t,n,r,o,i,s){if(Q.has(t)){if(Pt(e))return!1;if(n!==null&&zx(e,n,s))return!0;let a=st(e);if(!a){let l=It(J(e));if(l.kind==="literal")return n!==null&&l.source.includes(n);return l.kind==="none"&&o}if(n!==null&&a.includes(n)&&!rf(a,n,s))return!0;if($e(a))return!0;return Hx(a,n,r)}if(Xe(t))return Jm(e,n,Qo,dd(t));if(Be.has(t))return Jm(e,n,Da,om);if(t==="eval"){let a=Pi(J(e));if(a.kind==="dynamic")return!0;if(n!==null)return a.kind==="literal"&&a.source.includes(n);return o}if(t==="find")return Bx(e,n,i);if(t==="git"){let a=ze(e);return n===null?a.subcommand===null:(a.subcommand?.includes(n)??!1)||a.subcommand!==null&&$n.has(a.subcommand.toLowerCase())&&sf(a.rest,n).some((l)=>l.includes(n))}return!1}function rf(e,t,n){if(n===void 0)return!1;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`(?:^|[;&|({!\`\\n]|\\b(?:then|do|else|elif|if|while|until|time|command|builtin|nohup|eval|exec|source))\\s*(?:[A-Za-z_][A-Za-z0-9_]*=\\S*\\s+)*["']?${r}`).test(e)||/\bcase\b/.test(e))return!1;let i=e.replaceAll(t,"/");return $e(i)===null&&n(i)===null}function Jm(e,t,n,r){let o=n(e);if(t===null)return o.optionsOpen||n([...e,ki]).sources.some((a)=>a.value===ki);if(o.sources.some((a)=>a.value.includes(t)))return!0;let i=r.flatMap((a)=>[a.selector,...a.valueForm==="attached-only"||a.valueForm==="attached-or-separate"?[`${a.selector}${ki}`]:[],...a.valueForm==="equals-or-separate"?[`${a.selector}=${ki}`]:[]]),s=new Set(i.flatMap((a)=>e.flatMap((l)=>tf(l,t,a))));return _i(o.sources,s,(a)=>n(e.map((l)=>l.replaceAll(t,a))).sources)}function Fx(e,t,n){if(e.length===0||(e[0]??"").toLowerCase()==="command")return!1;let r=new Set(Array.from(ot(e,n),(i)=>i.head)),o=t===null?[...e,Ii]:e.map((i,s)=>s===0?i:i.replaceAll(t,Ii));return Array.from(ot(o,n)).some((i)=>i.head===Ii&&!r.has(Ii))}function of(e,t){return sf(e.slice(1),t).some((n)=>n.includes(t)&&(n.startsWith("-")||n.startsWith(t)))}function sf(e,t){let n=e.findIndex((r)=>r==="--"&&!r.includes(t));return n===-1?e:e.slice(0,n)}function af(e,t,n){if(t===null)return!0;return e.some((r)=>r.includes(t))||Array.from(n.values()).some((r)=>r.includes(t))}function zx(e,t,n){let r=Ne(e),o=r.commandIndex===null?"":e[r.commandIndex]??"";if(o.includes(t)&&!rf(o,t,n)||r.scriptIndex!==null&&(e[r.scriptIndex]??"").includes(t))return!0;return["-c","-nc","-cn",`--${t}`,t].some((s)=>e.some((a,l)=>{if(l===0||!a.includes(t))return!1;return tf(a,t,s).some((u)=>{let m=e.map((f,p)=>p===l?f.replaceAll(t,u):f),d=Ne(m);if(d.commandIndex===null&&d.scriptIndex===null)return!1;if(r.commandIndex===null&&d.commandIndex!==null)return!0;if(r.scriptIndex===null&&d.scriptIndex!==null)return!0;if(d.commandIndex!==null&&(m[d.commandIndex]??"").includes(u))return!0;return d.scriptIndex!==null&&(m[d.scriptIndex]??"").includes(u)})}))}function Hx(e,t,n){let r=new Set(t===null?[]:Array.from(n).filter(([,o])=>o.includes(t)).map(([o])=>o));for(let o of e.matchAll(Dx))if(Qm(o,r))return!0;for(let o of e.matchAll(Nx))for(let i of(o[1]??"").matchAll(Lx))if(Qm(i,r))return!0;return el(e,r)}function Qm(e,t){let n=e[1]??e[2];return n!==void 0&&(Wx.test(n)||t.has(n))}function Bx(e,t,n){if(t===null)return!0;let r=!1,o=0;for(let i=1;i<e.length;i++){let s=e[i]??"";if(!r&&!s.startsWith("-")&&s!=="!"&&s!=="("){if(s.indexOf(t)===0)return!0;continue}if(r=!0,o>0){o--;continue}if(ft(s)){let l=Bn(e,i);i=l.nextIndex-1;for(let c of ot(l.tokens,{environment:n,cwd:void 0})){let u=af(c.tokens,t,c.wrapperEnvAssignments);if(c.head==="rm"&&of(c.tokens,t)||nf(c.tokens,c.head,t,c.wrapperEnvAssignments,u,n))return!0}continue}let a=Tt(s);if(a>0){if(o=a,s.includes(t))return!0;continue}if(s.includes(t))return!0}return!1}function pn(e){let t=new Set(["-L","-n","-P","-s","-a","-E","-R","-S","-e","-d","-J","--max-args","--max-procs","--max-chars","--arg-file","--eof","--delimiter","--max-lines","--process-slot-var"]),n=null,r=1;while(r<e.length){let o=e[r];if(!o)break;if(o==="--")return{childStart:r+1,replacementToken:n};if(!o.startsWith("-"))return{childStart:r,replacementToken:n};if(o==="-I"){n=e[r+1]??"{}",r+=2;continue}if(o.startsWith("-I")&&o.length>2){n=o.slice(2),r++;continue}if(o==="--replace"){n="{}",r++;continue}if(o.startsWith("--replace=")){let i=o.slice(10);n=i===""?"{}":i,r++;continue}if(o==="-J"){n=e[r+1]??"{}",r+=2;continue}r+=t.has(o)?2:1}return{childStart:e.length,replacementToken:n}}var Kr="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",qr="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",$x="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",Ux="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",Mi=/\{[^{}\s]*\}/g,lf=/\{\}|\{-?\d+\}/g,jx=["e","f","source","file","-e","-f","--source","--file"],Vx=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],Kx=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),qx=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),cf=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),Yx=new Set(["--workdir","--wd"]),uf="__CC_SAFETY_NET_PARALLEL_SOURCE__";function Ve(e,t){for(let n of e){let r=t(n);if(r)return r}return null}function hf(e){return Ve([...e],(t)=>$e(t))}function yf(e,t){let n=e.map(_);if((t.envAssignments?.has("PARALLEL")?t.envAssignments.get("PARALLEL"):t.environment.env.get("PARALLEL"))?.trim()){let p=Vn(t);if(p)return p}if(n.length===2&&(n[1]==="--version"||n[1]==="--help"))return null;let o=_f(n),{template:i,jobs:s,runsRemotely:a,readsCommandsFromInput:l,unsupported:c,workdir:u,dryRun:m}=o;if(c){let p=Vn(t);if(p)return p;let g=hf(t.envAssignments?.values()??[]);if(g)return g}if(l){let p=tR(t);if(p)return p}if(u!==void 0&&a){let p=Vn(t);if(p)return p}let d=nR(u,t.cwd,t.environment.paths);if(d===null){let p=Vn(t);if(p)return p}let f=a?{...t,cwd:void 0,originalCwd:void 0}:d===null||d===void 0||d===t.cwd?t:{...t,cwd:d};if(m){if([...ot(i,f)].flatMap((g)=>[...g.envAssignments.values()]).some(il)){let g=Vn(t);if(g)return g}return null}if(i.length===0){let p=s.map((h)=>h[0]??"");t.budget.charge("derivedTokens",p.length);let g=vf(f.envAssignments,f.cwd,a);return Ve(p,(h)=>t.analyzeNested(h,g))}return Ve(ot(i,f),(p)=>Zx(p,o,t,f))}function Zx(e,t,n,r){let{jobs:o,templateHasPlaceholder:i,runsRemotely:s,usesStdin:a}=t,l=e.tokens,c=[...e.envAssignments.values()];if(c.some(Rf)){let h=Vn(n);if(h)return h}let u=hf(c);if(u)return u;let m=c.some(B),d=i||m,f=a&&d,p=vf(e.envAssignments,e.wrapperCwd,s||f);if(Q.has(e.head)){let h=()=>{if(!i||o.length===0)return null;return Ve(o,(E)=>n.analyzeChild(Oi(l,E,n.budget),dn(e,r)))};if(Pt(l))return h();let y=st(l);if(y){if(wf(y)){let x=Yt(n);if(x)return x;if(o.length===0)return null;return Ve(o,(A)=>n.analyzeNested(ff(y,A,n.budget),p))}if(B(y)){if(o.length>0)return Ve(o,(ee)=>n.analyzeNested(ff(y,ee,n.budget),p));let x=$r(y);if(x?.[0]&&M(x[0])==="rm"&&it(x)){let ee=mf(n);if(ee)return ee}let A=x?n.analyzeChild(x,{...dn(e,r),dynamicInput:a,shellDynamicMatch:v("parallel.shell-dynamic",qr),rmDynamicMatch:v("parallel.rm-recursive-force-dynamic",Kr)}):null;if(A)return A;return n.analyzeNested(y,p)}let E=!m&&(!i||o.length>0)?(o.length>0?o:[void 0]).map((x)=>Ti(J(x===void 0?l:i?l.map((A)=>Ef(A,x)):[...l,...x]),y)):[];if(E.some((x)=>x.kind==="dynamic")){let x=Yt(n);if(x)return x}let C=E.flatMap((x)=>x.kind==="literal"?[x.source]:[]);if(C.length>0)return n.budget.charge("derivedTokens",C.length),Ve(C,(x)=>n.analyzeNested(x,p));if(Vr(y)){let x=Yt(n);if(x)return x}let P=n.analyzeNested(y,p);if(P)return P;if(d)return Yt(n);return null}let S=It(J(l));if(S.kind==="dynamic"||S.kind==="literal"&&B(S.source))return Yt(n)??h();if(S.kind==="literal")return h();if(o.length>0){let E=Yt(n);if(E)return E;let C=h();if(C)return C;if(i)return null;let P=o.flatMap((x)=>x[0]===void 0?[]:[x[0]]);return n.budget.charge("derivedTokens",P.length),Ve(P,(x)=>n.analyzeNested(x,p))}if(d||a)return Yt(n)??h();return null}if(e.head==="rm"&&it(l)){if(i&&o.length>0)return Ve(o,(y)=>rl(Oi(l,y,n.budget,lf),e.cwd,r));if(o.length>0)return Ve(o,(y)=>rl(pf(l,y,n.budget),e.cwd,r));let h=rl(l.flatMap((y,S)=>{if(S===0||!B(y))return[y];return y.startsWith("-")?[y.replace(lf,"")]:[]}),e.cwd,r);if(h)return h;return mf(n)}let g=o.length>0?o:[void 0];return Ve(g,(h)=>{let y=h===void 0?l:i?Oi(l,h,n.budget):pf(l,h,n.budget),S=v("parallel.shell-dynamic",qr),E=a&&e.head==="find"?eR(y,r):null,C=bf(y,a,n)??E?.customResult??null,P=M(e.head),x=a&&(P==="rm"&&ol(y)||P==="xargs"&&Sf(y)||E?.rmOptions===!0),A=a&&(x||E?.executedSource===!0||E===null&&Cf(y,P)),ee=n.analyzeChild(y,{...dn(e,r),worktreeMode:s||a||d?!1:n.worktreeMode,dynamicInput:a||d,dynamicRmInput:x,dynamicSourceInput:C!==null||A,shellDynamicMatch:S,dynamicSourceMatch:S,rmDynamicMatch:v("parallel.rm-recursive-force-dynamic",Kr)});if(A){let qe=T(S,n.policy);if(qe)return qe}return ee??C??At(y,n.policy?.rules??[])})}function Cf(e,t){if(B(e[0]??""))return!0;if(t==="eval"||t==="source"||t===".")return!0;if(t==="parallel"||t==="xargs")return!0;if(Q.has(t))return Qx(e);if(t==="git")return Xx(e);if(t==="find")return!0;if(Be.has(t))return df(e,jx,Hr);if(Xe(t))return df(e,Vx,Jo);return!1}function ol(e){let t=e.indexOf("--"),n=e.slice(1,t===-1?void 0:t);if(!e.some(B))return t===-1;return n.some((o)=>B(o)&&(o.startsWith("-")||wf(o)))}function Xx(e){if(Jx(e))return!0;let t=ze(e);if(t.subcommand===null||B(t.subcommand))return!0;if(!$n.has(t.subcommand.toLowerCase()))return!1;let n=t.rest.indexOf("--"),r=t.rest.slice(0,n===-1?void 0:n);if(!e.some(B))return n===-1;return r.some(B)}function Jx(e){for(let t=1;t<e.length;t++){let n=e[t];if(!n||n==="--"||!n.startsWith("-"))return!1;if(n==="-c"||n==="--config-env"){if(B(e[t+1]??""))return!0;t++;continue}if(n.startsWith("-c")&&n.length>2||n.startsWith("--config-env=")){if(B(n))return!0;continue}if(B(n))return!0}return!1}function Qx(e){if(Pt(e))return!1;let t=st(e);if(t!==null)return B(t);let n=It(J(e));if(n.kind==="literal")return B(n.source);if(n.kind==="dynamic")return!0;return!e.some(B)}function df(e,t,n){let r=n(e);if(r.some((o)=>B(o.value)))return!0;if(!e.some(B))return n([...e,uf]).some((o)=>o.value===uf);return _i(r,t,(o)=>n(e.map((i)=>Ef(i,[o]))))}function bf(e,t,n){let r=n.policy?.rules??[];if(!t||r.length===0)return null;let o=r.filter((i)=>M(i.command)===M(e[0]??""));if(o.length===0)return null;if(e.slice(1).some(B))return Yt(n);return Ve(o,(i)=>At([...e,...i.subcommand?[i.subcommand]:[],...i.block_args],[i]))}function eR(e,t){let n={customResult:null,executedSource:!e.some(B),rmOptions:!1},r=!1,o=0,i=null,s=()=>{if(!i?.some(B))return;for(let a of ot(i,t))n.executedSource||=Cf(a.tokens,a.head),n.rmOptions||=a.head==="rm"&&ol(a.tokens)||a.head==="xargs"&&Sf(a.tokens),n.customResult??=bf(a.tokens,!0,t)};for(let a of e.slice(1)){if(!r&&!a.startsWith("-")&&a!=="!"&&a!=="("){n.executedSource||=B(a);continue}if(r=!0,i){if(a===";"||a==="+"){s(),i=null;continue}i.push(a);continue}if(o>0){o--;continue}if(ft(a)){i=[],n.executedSource||=B(a);continue}let l=Tt(a);if(l>0){o=l,n.executedSource||=B(a);continue}n.executedSource||=B(a)}return s(),n}function Sf(e){let t=e.slice(pn(e).childStart);return M(t[0]??"")==="rm"&&ol(t)}function Di(e,t){return(n)=>T(v(e,t),n.policy)}var Yt=Di("parallel.shell-dynamic",qr),tR=Di("parallel.command-stream-dynamic",$x),Vn=Di("parallel.command-stream-dynamic",Ux),mf=Di("parallel.rm-recursive-force-dynamic",Kr);function rl(e,t,n){return T(Ai(J(e),{environment:n.environment,cwd:t,budget:n.budget,originalCwd:n.originalCwd,strict:n.strict,paranoid:n.paranoidRm,allowTmpdirVar:n.allowTmpdirVar,tmpdirWordSplittingUnsafe:jt(n.envAssignments??new Map,n.environment),trustedTmpdirValue:cn(n.envAssignments??new Map,n.environment),protectedGitMetadata:n.protectedGitMetadata,policy:n.policy}),n.policy)}function vf(e,t,n){let r={};if(e)r.envAssignments=e;if(n)return r.effectiveCwd=null,r.worktreeMode=!1,r;if(t!==void 0)r.effectiveCwd=t;return Object.keys(r).length>0?r:void 0}function Ef(e,t){return e.replace(Mi,(n)=>xf(n,t))}function Oi(e,t,n,r=Mi){return n.charge("derivedTokens",e.reduce((o,i)=>o+1+Math.floor(i.length/64),0)),e.map((o)=>o.replace(r,(i)=>{let s=xf(i,t);return n.charge("derivedTokens",Math.max(1,Math.ceil(s.length/64))),s}))}function ff(e,t,n){return Oi([e],t,n)[0]??""}function pf(e,t,n){return n.charge("derivedTokens",e.length+t.length),[...e,...t]}function xf(e,t){let n=/^\{(-?\d+)[^{}\s]*\}$/.exec(e)?.[1];if(n===void 0)return t[0]??"";let r=Number(n);return t[r>0?r-1:t.length+r]??""}function B(e){return e.search(Mi)!==-1}function Rf(e){if(il(e))return!0;for(let t of e.matchAll(Mi))if(!/^(?:\{\}|\{\d+\})$/.test(t[0]))return!0;return!1}function il(e){let t=e.indexOf("{=");return t!==-1&&e.indexOf("=}",t+2)!==-1}function wf(e){return/^\{[^{}\s]*\}$/.test(e)}function nR(e,t,n){if(e===void 0)return;if(e==="..."||/^~|[{}$`*?[]/.test(e))return null;if(!t&&!gf.isAbsolute(e))return null;try{return Ht(t??e,e,n)}catch{return null}}function _f(e){let t=1,n=[],r=e.length,o=-1,i=!1,s=!1,a,l=!1,c=e.some((p)=>p==="::::"||p==="::::+"||p===":::+");while(t<e.length){let p=e[t];if(p===void 0)break;if(p===":::"){o=t;break}if(p==="--"){let E=Wa(e,t+1);n.push(...E.templateTokens),r=t+1,o=E.markerIndex;break}if(!p.startsWith("-")){let E=Wa(e,t);n.push(...E.templateTokens),r=t,o=E.markerIndex;break}let g=e[t+1],h=p.indexOf("="),y=h===-1?p:p.slice(0,h),S=h===-1?void 0:p.slice(h+1);if(p==="--dry-run"){l=!0,t++;continue}if(p==="-I"||p.startsWith("-I")&&p.length>2){c||=(p==="-I"?g:p.slice(2))!=="{}",t+=p==="-I"?2:1;continue}if(p==="--replace"||p==="-i"){c=!0,t+=2;continue}if(y==="--replace"||p.startsWith("-i")&&p.length>2){let E=y==="--replace"?S:p.slice(2);c||=E!==""&&E!=="{}",t++;continue}if(p==="-a"||qx.has(y)){c=!0,t+=S===void 0?2:1;continue}if(p==="--pipe"||p==="--pipepart"){s=!0,t++;continue}if(y==="--env"){c=!0,t+=S===void 0?2:1;continue}if(cf.has(y)||p.startsWith("-S")&&p.length>2){i=!0,t+=cf.has(p)?2:1;continue}if(Yx.has(y)){c=!0;let E=S??g;if(E===void 0||E===":::"||E==="--"){t++;continue}a=E,t+=S===void 0?2:1;continue}if(p.startsWith("-j")&&p.length>2&&/^\d+$/.test(p.slice(2))){t++;continue}if(p.startsWith("--")&&S!==void 0){t++;continue}if(Kx.has(p)){if(g===void 0||g===":::"||g==="--"){c=!0,t++;continue}t+=2;continue}t+=p==="-j"||p==="--jobs"?2:1}c||=n.some(l?il:Rf);let u=[];if(o!==-1){let p=[];for(let g=o+1;g<e.length;g++){let h=e[g];if(h===":::"){u.push(p),p=[];continue}if(h!==void 0)p.push(h)}u.push(p)}c||=u.length>1;let m=rR(u),d=n.some(B),f=n.length===0&&o===-1;return{template:n,jobs:m,childStart:r,templateHasPlaceholder:d,runsRemotely:i,usesStdin:s||o===-1,readsCommandsFromInput:f,unsupported:c,workdir:a,dryRun:l}}function rR(e){if(e.length===0||e.some((n)=>n.length===0))return[];let t=[[]];for(let[n,r]of e.entries()){if(r.length===1){let i=r[0];if(i===void 0)return[];for(let s of t)s.push(i);if(t.length*(n+1)>X.derivedTokens.cap)throw new N("derivedTokens");continue}let o=[];for(let i of t)for(let s of r){if((o.length+1)*(n+1)>X.derivedTokens.cap)throw new N("derivedTokens");o.push([...i,s])}t=o}return t}function Af(e){return _f(e).childStart}var oR="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",Ni="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.";function al(e){return e?.parts.some((t)=>t.provenance==="command-substitution")??!1}function sl(e){return e?.parts.some((t)=>t.provenance==="literal"&&t.raw.replace(/^["']/,"").startsWith("-"))??!1}function Tf(e,t,n,r,o=!1,i){let a=(yr(e,t)||r&&e!=="powershell"&&t[0]?.provenance==="variable")&&me(i,"shell.dynamic-executable",o)?v("shell.dynamic-executable",oR):null;return T(a,i)??kf(e,t,n,o,i)}function kf(e,t,n,r,o){if(t.length<2)return null;let i=t.flatMap((a,l)=>al(a)?[l]:[]);if(i.length===0)return null;let s=M(t[0]?.text??"");if(s==="git"){let a=Mn(e,t),l=sR(a);if(me(o,"shell.dynamic-structure",r)&&i.some((m)=>m<=l))return T(v("shell.dynamic-structure",Ni),o);if(T(wi(a,{environment:n}),o))return null;let c=t[l]?.text.toLowerCase(),u=a.findIndex((m,d)=>d>l&&_(m)==="--");if(me(o,"shell.dynamic-structure",r)&&c&&$n.has(c)&&i.some((m)=>m>l&&(u===-1||m<u)))return T(v("shell.dynamic-structure",Ni),o);return null}if(s==="find")return me(o,"shell.dynamic-structure",r)&&aR(t)?T(v("shell.dynamic-structure",Ni),o):null;if(s==="rm"){let a=t.findIndex((c,u)=>u>0&&_(c)==="--"),l=it(t.map(_));return me(o,"shell.dynamic-structure",r)&&i.some((c)=>(a===-1||c<a)&&(c<t.length-1||!l))?T(v("shell.dynamic-structure",Ni),o):null}if(s==="xargs")return Pf(e,t.slice(pn(t.map(_)).childStart),"xargs",n,r,o);if(s==="parallel")return Pf(e,t.slice(Af(t.map(_))),"parallel",n,r,o);return null}function Pf(e,t,n,r,o,i){if(t.length===0)return null;let s=iR(t,r);if(yr(e,s)){let l=T(v(`${n}.shell-dynamic`,n==="xargs"?nl:qr),i);if(l)return l}let a=kf(e,s,r,o,i);if(a)return a;if(s[0]?.text==="rm"&&s.slice(1).some((l)=>al(l)&&sl(l)))return T(v(`${n}.rm-recursive-force-dynamic`,n==="xargs"?tl:Kr),i);return null}function iR(e,t){let n=sn(e,t),r=n.rewritten?J(n.words.map(_)):n.words,o=r[0];return o&&_(o)==="busybox"?r.slice(1):r}function sR(e){let t=1;while(t<e.length){let n=e[t],r=n?_(n):"";if(De.has(r)){t+=2;continue}if(r.startsWith("-")){t++;continue}return t}return t}function aR(e){let t=!1,n=0,r=!1,o=!1;for(let i=1;i<e.length;i++){let s=e[i];if(!s)continue;let a=al(s);if(n>0){n--;continue}if(o){if(s.text===";"||s.text==="+"){o=!1,t=!0,r=!1;continue}if(a&&(r||sl(s)))return!0;r=!1;continue}if(!t&&!s.text.startsWith("-")){if(a&&(i>1||sl(s)))return!0;continue}if(t=!0,a)return!0;let l=Tt(s.text);if(l>0){n=l;continue}if(ft(s.text))o=!0,r=!0}return!1}function ll(e,t){return e.some((n)=>{if(n.value==="-"&&(n.kind==="main-script"||n.kind==="program-file"))return!0;return!qo(t[n.tokenIndex],n.value)})}var lR="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",cR="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",uR="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function If(e,t){let n=t.slice(1);if(e==="dd"&&n.some((r)=>/^of=\/dev\/.+/.test(r)))return v("dd.device-write",lR);if((e==="mkfs"||e.startsWith("mkfs."))&&n.some((r)=>r.startsWith("/dev/")))return v("mkfs.device",cR);if(e==="shred"&&n.length>0)return v("shred.target",uR);return null}var Mf=[{heads:new Set(["rm","rmdir"]),analyze:(e)=>Ai(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoid:e.options.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:jt(e.envAssignments,e.options.environment),trustedTmpdirValue:cn(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,policy:e.options.policy,budget:e.options.budget})},{heads:new Set(["git"]),analyze:(e)=>wi(e.words,cl(e))},{heads:new Set(["find"]),analyze:(e)=>dm(e.words,{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,allowTmpdirVar:e.allowTmpdirVar,tmpdirWordSplittingUnsafe:jt(e.envAssignments,e.options.environment),trustedTmpdirValue:cn(e.envAssignments,e.options.environment),protectedGitMetadata:e.options.protectedGitMetadata,budget:e.options.budget,envAssignments:e.envAssignments,policy:e.options.policy,analyzeTokens:e.analyzeChildTokens,analyzeNested:(t,n)=>gn(e.options.analyzeNested(t,n))})},{heads:new Set(["xargs"]),analyze:(e)=>ef(e.words,{...Of(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>gn(e.options.analyzeNested(t,n))})},{heads:new Set(["parallel"]),analyze:(e)=>yf(e.words,{...Of(e),analyzeChild:e.analyzeChild,analyzeNested:(t,n)=>gn(e.options.analyzeNested(t,n))})}];function Of(e){return{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,strict:e.options.strict,paranoidRm:e.options.paranoidRm,paranoidInterpreters:e.options.paranoidInterpreters,allowTmpdirVar:e.allowTmpdirVar,protectedGitMetadata:e.options.protectedGitMetadata,budget:e.options.budget,envAssignments:e.envAssignments,worktreeMode:e.options.worktreeMode,policy:e.options.policy}}function gn(e){return e?{id:e.ruleId??"",reason:e.reason,intent:e.intent??"manual_only"}:null}function cl(e){return{environment:e.options.environment,cwd:e.cwd,originalCwd:e.originalCwd,dynamicArguments:e.dynamicArguments,envAssignments:e.envAssignments,shellAssignments:e.options.shellAssignments,policy:e.options.policy,worktreeMode:e.options.worktreeMode}}function Wf(e){return Mf.find((t)=>t.heads.has(e))?.analyze}function qn(e,t,n){let r=n.trace;if(e.length===0)return null;let o=n.commandView?.dialect??"posix",i=(R)=>R.map((I)=>o==="posix"?_(I):I.text),s=n.child,a=s!==void 0&&!s.embedded,l=s?.embedded===!0,c=n.effectiveCwd===null,u=s?s.cwd:c?void 0:n.effectiveCwd??n.cwd,m=s?s.originalCwd:c?void 0:n.cwd,d=ni(e);if(d.envAssignments.size>0)r?.recordSegment({type:"env-strip",input:i(e),envVars:[...d.envAssignments.keys()],output:i(d.words)});let f=sn(d.words,n.environment,u,new Map([...n.envAssignments??[],...d.envAssignments])),p=f.envSplitValues??[];if(p.length>0){let R=[...p,...i(f.words)].join(" "),I=$e(R);if(I)return r?.recordSegment({type:"dangerous-text",token:R,matched:!0,reason:I.reason}),ve(I);if(n.strict)return ke(r);let G=ri(p,i(f.words));if(G){n.budget.charge("derivedTokens",G.length);let ce=n.analyzeNested(G.join(" "),{effectiveCwd:f.cwd===void 0?n.effectiveCwd:f.cwd,envAssignments:new Map([...n.envAssignments??[],...d.envAssignments,...f.envAssignments])});if(ce)return ce}}let g=f.rewritten?J(i(f.words)):Mn(o,f.words),h=i(g),y={...n,wrapperNormalizationBudget:n.wrapperNormalizationBudget??{iterations:0}};if(r&&d.words.length>g.length){let R=i(d.words);r.recordSegment({type:"leading-tokens-stripped",input:R,removed:R.slice(0,R.length-g.length),output:h})}let S=new Map([...n.envAssignments??[],...d.envAssignments,...f.envAssignments]),E=h[0];if(!E)return null;if(un(E))throw new N("wrapperPeelIterations");let C=M(E),P=f.cwd===null?void 0:f.cwd??u,x=f.cwd===null?void 0:m,A=f.cwd===void 0?n.effectiveCwd:f.cwd,ee=s?s.allowTmpdirVar:!Lr(S,n.environment),qe=Tf(o,f.words,n.environment,t===0,n.strict,n.policy);if(qe)return r?.recordSegment({type:"rule-check",rule:"analyzer/segment.ts:analyzeDynamicCommandStructure",matched:!0,reason:qe.reason}),ve(qe);let ct=bi(h,n.policy);if(ct){for(let R of[ct.childIndex,...ct.alternativeChildIndices]){Df(y.wrapperNormalizationBudget);let I=g.slice(R);r?.recordSegment({type:"transparent-wrapper",wrapper:ct.wrapper,output:i(I)});let G=qn(I,t,{...y,effectiveCwd:A,envAssignments:S});if(G)return G}return null}let xe=l?void 0:C==="eval"?Pi(g):C==="trap"&&!a?Vm(g):void 0;if(a&&s&&C==="eval"){if(xe?.kind==="dynamic")return Kn(s,n.policy);if(xe?.kind==="literal"){let R=n.analyzeNested(xe.source,{effectiveCwd:A,envAssignments:S});if(R)return R}return Yn(s,n.policy)}if(xe?.kind==="dynamic"&&(n.strict||!n.commandView||!Qa(n.commandView)))return ke(r);if(xe?.kind==="literal"){r?.recordSegment({type:"recurse",reason:C==="eval"?"shell-eval":"shell-trap",innerCommand:xe.source,depth:t+1});let R=n.analyzeNested(xe.source,{effectiveCwd:A,envAssignments:S,functionDefinitions:n.functionDefinitions});if(R)return R}if(a?Q.has(C):Ff(E,C)){if(Pt(h))return null;if(a&&s){let R=st(h);if(R){if(s.dynamicSourceInput??s.dynamicInput){let G=Kn(s,n.policy);if(G)return G}if(Vr(R)){let G=Kn(s,n.policy);if(G)return G}return n.analyzeNested(R,{effectiveCwd:A,envAssignments:S})}let I=It(g);if(I.kind==="dynamic")return Kn(s,n.policy);if(I.kind==="literal")return s.dynamicSourceInput?Kn(s,n.policy):null;return s.dynamicSourceInput??s.dynamicInput?Kn(s,n.policy):null}if(l){let R=st(h),I=R?n.analyzeNested(R,{effectiveCwd:A,envAssignments:S}):It(g).kind==="dynamic"?ke(r):null;if(I)return I}if(s===void 0){let R=pR(h,S,A,n,r,t);if(R)return R;let I=st(h);if(I){let En=Ti(g,I);if(En.kind==="dynamic")return ke(r);let Zi=En.kind==="literal"?En.source:Km(g,I),Gl=gR(Zi);r?.recordSegment({type:"shell-wrapper",wrapper:C,innerCommand:Gl}),r?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:Gl,depth:t+1});let Fl=n.analyzeNested(Zi,{effectiveCwd:A,envAssignments:S});if(Fl)return Fl;return Vr(Zi)?ke(r):null}let G=It(g,n.strict?void 0:n.shellAssignments);if(G.kind==="dynamic")return ke(r);if(G.kind==="literal")return Li(G.source,A,S,n,r,t);let ce=qm(g,n.commandView?.redirections??[],n.hasPipelineInput??!1,n.literalShellInput);if(ce.kind==="dynamic")return ke(r);if(ce.kind==="literal")return r?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:ce.source,depth:t+1}),n.analyzeNested(ce.source,{effectiveCwd:A,envAssignments:S})}}if(!s&&(C==="source"||C===".")){let R=h[1]==="-p"?2:null;if(R!==null){let En=n.commandView?g[R]:void 0;if(!En)return null;if(En.provenance!=="literal")return ke(r)}let I=R===null?1:3,G=h[I]==="--"?I+1:I,ce=n.commandView?g[G]:void 0;if(!ce)return null;if(ce.provenance==="literal")return Li(ce.text,A,S,n,r,t);if(n.strict||!n.commandView||!Qa(n.commandView))return ke(r)}if(Be.has(C)&&!l){if(!s&&n.strict&&ll(Hr(h),g))return ke(r);let R=im(h,(G)=>gn(n.analyzeNested(G,{effectiveCwd:A,envAssignments:S}))),I=T(R,n.policy);if(I)return r?.recordSegment({type:"rule-check",rule:"awk:analyzeAwkSystemCallMatch",matched:!0,reason:I.reason}),ve(I)}if(Xe(C)&&!l){if(!s&&n.strict&&ll(Jo(h),g))return ke(r);let R=ud(h);if(a&&s)return mR(C,R,A,S,n,s);if(R){let I=me(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(r?.recordSegment({type:"interpreter",interpreter:C,codeArg:R,paranoidBlocked:I}),I){let ce=T(v("interpreter.one-liner-paranoid",_r),n.policy);if(ce)return ve(ce)}if(fa(C,R))return null;r?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:R,depth:t+1});let G=n.analyzeNested(R,{effectiveCwd:A,envAssignments:S});if(G&&!Gf(G,R))return G;if(Ar(R,void 0,!n.strict)){let ce=T(v("interpreter.dangerous-command",Ln),n.policy);if(ce)return r?.recordSegment({type:"dangerous-text",token:R,matched:!0,reason:Ln}),ve(ce)}r=void 0}}if(C==="busybox"&&h.length>1)return Df(y.wrapperNormalizationBudget),r?.recordSegment({type:"busybox",subcommand:h[1]??"unknown"}),r?.recordSegment({type:"recurse",reason:"busybox",innerCommand:h.slice(1).join(" "),depth:t+1}),qn(g.slice(1),t,{...y,effectiveCwd:A,envAssignments:S});let H=s?null:T(If(C,h),n.policy);if(H)return r?.recordSegment({type:"rule-check",rule:"analyzer/device.ts:analyzeDeviceCommandMatch",matched:!0,reason:H.reason}),ve(H);let ie=r===y.trace?y:{...y,trace:r},ne={words:g,head:C,cwd:P,originalCwd:x,envAssignments:S,allowTmpdirVar:ee,dynamicArguments:f.words.some((R)=>R.provenance==="command-substitution"),depth:t,effectiveCwd:A,options:ie,analyzeChildTokens:(R,I)=>a&&s?ul(R,t,ie,{...s,cwd:I??void 0,effectiveCwd:I??void 0}):gn(qn(J(R),t+1,{...ie,child:void 0,commandView:void 0,effectiveCwd:I,envAssignments:S}))??At(R,ie.policy.rules),analyzeChild:(R,I)=>ul(R,t,ie,I)},se=s&&(C==="xargs"||C==="parallel")?void 0:Wf(C);if(C==="rm"||C==="xargs"||C==="parallel")r?.recordSegment({type:"tmpdir-check",tmpdirValue:S.has("TMPDIR")||n.environment.env.has("TMPDIR")?"<redacted>":null,allowTmpdirVar:ee});let Oe=r&&C==="git"?Wm(ne.words,cl(ne)):void 0,Dt=Nf(Oe?Oe.match:se?.(ne)??null,n.policy);if(r)hR(ne,Dt,Oe?.relaxation??null);if(Dt)return ve(Dt);if(a&&s&&(C==="rm"||C==="rmdir")){if(!(C==="rm"&&(it(h)||s.dynamicRmInput)))return null;return(s.dynamicRmInput?Yn(s,n.policy):null)??fR(s,n.policy)}let no=!s&&se===void 0&&!Eo.has(C),yt=r&&no?[]:void 0;if(no)for(let R=1;R<h.length;R++){let I=h[R];if(!I)continue;yt?.push(I);let G=Nf(dR(h,R,t,ie,P,x,A,S),n.policy);if(G)return r?.recordSegment({type:"fallback-scan",tokensScanned:yt??[],embeddedCommandFound:M(I)}),ve(G)}if(r?.recordSegment({type:"fallback-scan",tokensScanned:yt??[]}),l&&s&&!s.wrappedByTransparent)return null;let ro=At(h,n.policy.rules);if(r?.recordSegment({type:"custom-rules-check",rulesChecked:n.policy.rules.length>0,matched:!!ro,reason:ro?.reason}),ro)return ve(ro);return a&&s?Yn(s,n.policy):null}function ul(e,t,n,r){return gn(qn(J(e),t+1,{...n,trace:void 0,commandView:void 0,hasPipelineInput:void 0,literalShellInput:void 0,functionDefinitions:void 0,cwd:r.originalCwd,effectiveCwd:r.effectiveCwd,envAssignments:r.envAssignments,worktreeMode:r.dynamicInput?!1:r.worktreeMode,wrapperNormalizationBudget:{iterations:0},child:r}))}function dR(e,t,n,r,o,i,s,a){for(let l of ot(e.slice(t),{environment:r.environment,cwd:o,envAssignments:a,policy:r.policy})){let c=l.tokens[0];if(!c)continue;let u=M(c);if(Ff(c,u)||Wf(u)!==void 0&&u!=="xargs"&&u!=="parallel"||l.wrappedByTransparent&&r.policy.rules.length>0)r.budget.charge("derivedTokens",e.length-t);let d=ul(l.tokens,n,r,{embedded:!0,cwd:l.cwd,originalCwd:l.wrapperCwd===null?void 0:i,effectiveCwd:l.wrapperCwd===void 0?s:l.wrapperCwd,envAssignments:l.envAssignments,allowTmpdirVar:!Lr(l.envAssignments,r.environment),worktreeMode:!1,wrappedByTransparent:l.wrappedByTransparent});if(d)return d}return null}function mR(e,t,n,r,o,i){if(!t)return Yn(i,o.policy);if(me(o.policy,"interpreter.one-liner-paranoid",!!o.paranoidInterpreters)){let a=T(v("interpreter.one-liner-paranoid",_r),o.policy);if(a)return ve(a)}if(fa(e,t))return Yn(i,o.policy);let s=o.analyzeNested(t,{effectiveCwd:n,envAssignments:r});if(s&&!Gf(s,t))return s;if(Ar(t,void 0,!o.strict)){let a=T(v("interpreter.dangerous-command",Ln),o.policy);if(a)return ve(a)}return Yn(i,o.policy)}function Gf(e,t){let n=e.ruleId==="raw-text.dangerous-command",r=(e.reason.startsWith(hi)||e.reason===Hn)&&!xo(t);return n||r}function Kn(e,t){let n=e.shellDynamicMatch?T(e.shellDynamicMatch,t):null;return n?ve(n):null}function Yn(e,t){let n=e.dynamicSourceInput&&e.dynamicSourceMatch?T(e.dynamicSourceMatch,t):null;return n?ve(n):null}function fR(e,t){let n=e.dynamicInput&&e.rmDynamicMatch?T(e.rmDynamicMatch,t):null;return n?ve(n):null}function pR(e,t,n,r,o,i){let s=um(e);if(s.argvSource?.kind==="absent")return ke(o);if(s.argvSourceApplies&&s.argvSource){let l=Li(s.argvSource.value,n,t,r,o,i,!0);if(l)return l}if(!s.envSourceApplies||!s.envName)return null;let a=t.get(s.envName);if(!a)return null;return Li(a,n,t,r,o,i,!0)}function Li(e,t,n,r,o,i,s=!1){if(s&&/[$`*?[\]]/.test(e))return ke(o);let a=wr(e,t,r.environment.paths,r.budget),l=a?r.literalHeredocFiles?.get(a):void 0;if(l===void 0)return s?ke(o):null;return r.budget.charge("derivedTokens",1),o?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:l,depth:i+1}),r.analyzeNested(l,{effectiveCwd:t,envAssignments:n})}function gR(e){let t=e[0];return e.length>=2&&(t==='"'||t==="'")&&e.at(-1)===t?e.slice(1,-1):e}function hR(e,t,n){let r={git:"git:analyzeGitMatch",rm:"analyzer/rm.ts:analyzeRmMatch",find:"analyzer/find.ts:analyzeFindMatch",xargs:"analyzer/xargs.ts:analyzeXargs",parallel:"analyzer/parallel.ts:analyzeParallel"}[e.head];if(!r)return;if(e.options.trace?.recordSegment({type:"rule-check",rule:r,matched:!!t||!!n,reason:t?.reason??n?.originalReason}),n)e.options.trace?.recordSegment({type:n.kind==="worktree"?"worktree-relaxation":"temp-root-relaxation",originalReason:n.originalReason,gitCwd:n.gitCwd})}function Df(e){if(e.iterations>=X.wrapperPeelIterations.cap)throw new N("wrapperPeelIterations");e.iterations++}function ve(e){return{reason:e.reason,ruleId:e.id||void 0,intent:e.intent}}function ke(e){return e?.recordSegment({type:"error",message:Fr}),ve(yR())}function yR(){return{id:"",reason:Fr,intent:"stop_and_explain"}}function Ff(e,t){return Q.has(t)||e==="$SHELL"||e==="${SHELL}"||Q.has(k(t))}function Nf(e,t){return e?.id.startsWith("custom.")||e?.id==="raw-text.dangerous-command"?e:T(e,t)}var CR=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,bR=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function SR(e,t){let n=Bf(e,t);if(n.length===0)return!1;let r=n[Hf(n)];if(r==="cd"||r==="pushd"||r==="popd")return!0;return CR.test(e.join(" "))}function zf(e,t,n,r,o){if(e.dialect==="powershell"){let y=vR(e.words,o);if(y.kind==="none")return;if(!t||y.kind==="unknown")return null;return Lf(wR(y.target),t,n.paths)}let i=e.words.map(_),s=i.some((y)=>/^CDPATH\+?=/.test(y));if(!SR(i,n))return s?null:void 0;if(!t)return null;let a=Bf(i,n,t),l=Hf(a);if(l===-1||a[l]!=="cd")return null;let c=a.slice(l+1),u=c.findIndex((y)=>y.length<=1||!y.startsWith("-")||y==="--");if((u===-1?c:c.slice(0,u)).some((y)=>!/^-[LP]+$/.test(y)))return null;let d=u===-1?[]:c.slice(u),f=d[0]==="--"?d.slice(1):d;if(f.length!==1)return null;let p=f[0]??"",g=e.words.find((y)=>y.provenance==="variable"&&y.text===p),h=g?pt(g,r):p;if(h===null)return null;if(!/^(?:[./]|[A-Za-z]:[\\/])/.test(h)&&(s||n.env.has("CDPATH")))return null;return Lf(h,t,n.paths)}function Lf(e,t,n){if(!e||e==="-"||e.startsWith("~")||e.includes("$")||e.includes("`"))return null;try{let r=Ht(t,e,n);return n.isDirectory(r)?r:null}catch{return null}}function vR(e,t){let n=ER(e[0])?1:0,r=e[n];if(!xR(r,n===1))return{kind:"none"};let o=r.text.toLowerCase(),i=o.split(/[\\/]/).pop()??o;if(!bR.has(i))return{kind:"none"};if(o!==i||i==="pop-location"||i==="popd")return{kind:"unknown"};return RR(e.slice(n+1),t)}function ER(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&(e.text==="&"||e.text===".")}function xR(e,t){return e?.provenance==="literal"&&(t||!e.quoted&&e.raw===e.text)}function RR(e,t){let n;for(let r of e){if(r.provenance!=="literal"||n!==void 0)return{kind:"unknown"};n=r.text}if(n!==void 0)return{kind:"target",target:n};return t===void 0?{kind:"unknown"}:{kind:"target",target:t}}function wR(e){return e.includes("::")?void 0:e.replaceAll("\\","/")}function Hf(e){let t=0;if(e[0]==="builtin"&&e.length>1)t=1;if(e[t]!=="time")return t;let n=t+1;while(e[n]?.startsWith("-"))n++;return n}function Bf(e,t,n){let r=_R(e);return Bt([...r],t,n)}function _R(e){let t=0;while(t<e.length){let n=e[t];if(n!=="{"&&n!=="("&&n!=="$(")break;t++}return e.slice(t)}var AR="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",hn="This heredoc form or stdin consumer is not supported safely. Use a quoted heredoc with a supported consumer (cat, tee, git apply, git commit, gh pr create, gh issue create), or ask the user to verify.";function hl(e,t,n,r){if(t>=X.recursionDepth.cap)return n.trace?.recordSegment({type:"error",message:ut}),{reason:ut,segment:e,intent:"stop_and_explain"};let o=r??n.factStore?.getCommandProgram(e,n.shell??"auto")??Je(e,n.shell);if(o.status==="limited")return n.trace?.recordSegment({type:"error",message:ut}),{reason:ut,segment:e,intent:"stop_and_explain"};if(o.status==="invalid"){let c=o.issues.find((u)=>u.code.includes("heredoc"));if(c){if(!n.strict)return gl(e,n);let u=`${hi}: ${c.message}`;return n.trace?.recordGlobal({type:"error",message:u}),{reason:u,segment:e,intent:"stop_and_explain"}}return qf(e,n),{reason:Hn,segment:e,intent:"stop_and_explain"}}if(n.strict&&o.status==="partial")return qf(e,n),{reason:Hn,segment:e,intent:"stop_and_explain"};if(o.issues.some((c)=>c.code.includes("quote")))return gl(e,n);let s=n.cwd,a=n.effectiveCwd!==void 0?n.effectiveCwd:n.cwd,l=Rm(n.environment.env,n.envAssignments);return Fi(o,t,{...n,rootProgram:o},s,[{effectiveCwd:a,shellGitContextState:l,literalHeredocFiles:new Map(n.literalHeredocFiles),functionDefinitions:new Map(n.functionDefinitions),createdDirectories:new Set}]).result}function Fi(e,t,n,r,o){let i=[...o],s,a,l;for(let[c,u]of e.nodes.entries()){if(u.kind==="connector"){a=u.operator;continue}let m=e.nodes[c+1],d=m?.kind==="connector"?m.operator:void 0,f=PR(e,c,u,a,d),g=a==="&&"||a==="||"?s:void 0,h=a==="&&"?g?.success??i:a==="||"?g?.failure??i:i,y=a==="||"?g?.success??[]:[],S=a==="&&"?g?.failure??[]:[],E={connector:a,skippedSuccessStates:y,skippedFailureStates:S};if(Zt(d)&&!Zt(a))l=E;let C=Zt(d)?{connector:void 0,skippedSuccessStates:[],skippedFailureStates:[]}:Zt(a)?l??E:E,P=yn(C.connector)||yn(d);if(u.kind==="function"){let Z=h.flatMap((ie)=>{let ne=Xn(ie);return ne.functionDefinitions.set(u.name,u.body),dl(ie,[ne],f,d==="&",yn(d))}),H=ml(Z,[],C.skippedSuccessStates,C.skippedFailureStates,C.connector,d);i=H.states,s=H.conditionalStates,a=void 0;continue}if(u.kind==="group"){let Z=[],H=[];for(let ne of h){let se=Fi(u.body,t,n,r,[Xn(ne)]);if(se.result)return se;if(Z.push(...dl(ne,se.states,f,d==="&",yn(d))),P)H.push(ne,...f?se.states.map((Oe)=>Wi(ne,Oe)):se.states)}let ie=ml(Z,H,C.skippedSuccessStates,C.skippedFailureStates,C.connector,d);i=ie.states,s=ie.conditionalStates,a=void 0;continue}if(u.kind!=="command")continue;let x=n.trace?.flattenNested?n.trace.currentSegmentIndex:n.trace?.allocateSegment(),A=e.nodes[c-2],ee=Zt(a)&&A?.kind==="command"?jm(A)??kR(A):void 0,qe=[],ct=[];for(let Z of h){let H=IR(u,t,n,r,[Xn(Z)]);if(H.result)return{result:H.result,states:i};let ie=e.dialect==="powershell"?H.states:H.states.map((ne)=>Wi(Z,ne));for(let ne of ie){let se=Xn(ne),Oe=DR(u,t,n.trace?{...n,trace:Yf(n.trace,x)}:n,r,se,Zt(a),ee);if(Oe)return{result:Oe,states:i};let Dt=ew(u,se.functionDefinitions);if(Dt)n.budget.charge("derivedTokens",zi(Dt));let nr=Dt?t+1>=X.recursionDepth.cap?fl(u.displayText,n,[se]):Fi(Dt,t+1,n,r,[se]):{result:null,states:JR(u,se)};if(nr.result)return nr;qe.push(...dl(Z,nr.states,f,d==="&",yn(d)));let no=typeof se.effectiveCwd==="string"&&se.effectiveCwd!==ne.effectiveCwd&&u.redirections.every((yt)=>["<",">",">>",">|"].includes(yt.operator)&&yt.target?.text==="/dev/null");if(P&&!no)ct.push(Z),ct.push(...nr.states.map((yt)=>f?Wi(Z,yt):yt))}}let xe=ml(qe,ct,C.skippedSuccessStates,C.skippedFailureStates,C.connector,d);i=xe.states,s=xe.conditionalStates,a=void 0}return{result:null,states:i}}function PR(e,t,n,r,o){if(n.kind==="group"&&n.style==="subshell")return!0;if(e.dialect==="posix"&&(Zt(r)||Zt(o)))return!0;if(o==="&")return!0;return e.dialect==="powershell"&&n.kind==="group"&&n.style==="brace"&&TR(e,t)}function dl(e,t,n,r,o){let i=n?t.map((a)=>Wi(e,a)):[...t],s=o?i.flatMap((a)=>Zn(e.literalHeredocFiles,a.literalHeredocFiles)?[a]:[{...a,literalHeredocFiles:new Map(e.literalHeredocFiles)},a]):i;return r?[e,...s]:s}function Wi(e,t){return{...e,literalHeredocFiles:new Map(t.literalHeredocFiles),createdDirectories:new Set(t.createdDirectories)}}function TR(e,t){let n=e.nodes.slice(0,t).reverse().find((o)=>o.kind==="command"||o.kind==="connector");if(!n||n.kind!=="command")return!0;let r=n.words[0]?.text.toLowerCase();if(r==="&"||r===".")return!1;if(r==="write-output"||r==="function"||r==="start-job")return!0;if(OR(n))return!0;return n.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function Zt(e){return e==="|"||e==="|&"}function kR(e){if(e?.dialect!=="powershell")return;if(e.words.length===1&&e.words[0]?.quoted&&e.words[0].provenance==="literal")return e.words[0].text;if(e.words[0]?.text.toLowerCase()==="write-output"&&e.words.length===2&&e.words[1]?.provenance==="literal")return e.words[1].text;return}function yn(e){return e==="&&"||e==="||"}function ml(e,t,n,r,o,i){let s={success:Gi([...n,...e]),failure:Gi([...r,...t])},a=yn(i)?s:void 0;return{states:yn(o)||a?Gi([...s.success,...s.failure]):s.success,conditionalStates:a}}function Yf(e,t,n=e.flattenNested){return{currentSegmentIndex:t,flattenNested:n,allocateSegment:e.allocateSegment,getNextSegmentIndex:e.getNextSegmentIndex,recordGlobal:e.recordGlobal,recordSegment:(r,o=t)=>e.recordSegment(r,o)}}function IR(e,t,n,r,o){let i=e.nested.map((s)=>({program:s,depth:t}));if(e.dialect==="powershell"){let s=MR(e);if(s){if(t+1>=X.recursionDepth.cap)return fl(s,n,o);let a=Je(s,"powershell");if(a.status==="limited")return fl(s,n,o);if(a.status!=="complete")return $f(i,n,r,o);n.budget.charge("derivedTokens",zi(a)),i.push({program:a,depth:t+1})}}return $f(i,n,r,o)}function OR(e){let t=e.words[0];return t?.provenance==="variable"&&e.words.at(-1)?.text==="="?t.text.toLowerCase():void 0}function $f(e,t,n,r){let o=[...r];for(let i of e){let s=[];for(let a of o){let l=Fi(i.program,i.depth,t,n,[Xn(a)]);if(l.result)return l;s.push(...l.states)}o=Gi(s)}return{result:null,states:o}}function MR(e){let t=e.words[0]?.provenance==="literal"&&!e.words[0].quoted&&e.words[0].raw===e.words[0].text&&(e.words[0].text==="&"||e.words[0].text==="."),n=t?1:0,r=e.words[n];if(r?.provenance!=="literal"||!t&&(r.quoted||r.raw!==r.text)||!["iex","invoke-expression"].includes(r.text.toLowerCase()))return;let o=e.words.slice(n+1),i=o[0]&&!o[0].quoted&&o[0].raw===o[0].text&&["-c","-command"].includes(o[0].text.toLowerCase())?1:0,s=o[i];return o.length===i+1&&s?.quoted&&s.provenance==="literal"?s.text:void 0}function zi(e){return e.nodes.reduce((t,n)=>t+(n.kind==="command"?n.words.length+n.nested.reduce((r,o)=>r+zi(o),0):n.kind==="group"||n.kind==="function"?zi(n.body):0),0)}function fl(e,t,n){return t.trace?.recordSegment({type:"error",message:ut}),{result:{reason:ut,segment:e,intent:"stop_and_explain"},states:[...n]}}function DR(e,t,n,r,o,i,s){let a={...n,environment:{...n.environment,env:o.shellGitContextState.env,paths:FR(n.environment.paths,o.createdDirectories,n.budget)}},l=jR(e,!a.strict);if(l&&a.strict)return a.trace?.recordSegment({type:"error",message:l}),{reason:l,segment:e.source,intent:"stop_and_explain"};Zf(e,o,"before-consumer",a.environment.paths,a.budget);let c=Mn(e.dialect,e.words),u=c.map(_),m=e.displayText,d=Em(c,o.shellGitContextState),f=_m(d,o.shellGitContextState);if(e.dialect==="powershell"){let h=T(Xd(e,i,nw(a,o.effectiveCwd)),a.policy);if(a.trace?.recordSegment({type:"rule-check",rule:"analyzer/powershell/remove-item.ts:analyzePowerShellCommandViewMatch",matched:!!h,reason:h?.reason}),h)return tw(m,h)}if(u.length===1&&u[0]?.includes(" ")&&!yr(e.dialect,e.words)){let h=T($e(u[0]),a.policy),y=h!==null&&!a.strict&&ad(e,a.rootProgram);if(h&&!y)return a.trace?.recordSegment({type:"dangerous-text",token:u[0],matched:!0,reason:h.reason}),{reason:h.reason,segment:m,ruleId:h.id,intent:h.intent};a.trace?.recordSegment({type:"dangerous-text",token:u[0],matched:!1});let S=Uf(e,l,o,f,s,a);if(S)return S;return Ka(d,o.shellGitContextState),null}let p=qn(e.words,t,{...a,commandView:e,cwd:r,effectiveCwd:o.effectiveCwd,envAssignments:f,shellAssignments:o.shellGitContextState.shellAssignments,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:o.functionDefinitions,hasPipelineInput:i,literalShellInput:s,analyzeNested:(h,y)=>{let S=y&&Object.hasOwn(y,"effectiveCwd")?y.effectiveCwd:o.effectiveCwd,E=hl(h,t+1,{...a,effectiveCwd:S,envAssignments:y?.envAssignments??f,literalHeredocFiles:o.literalHeredocFiles,functionDefinitions:y?.functionDefinitions,worktreeMode:y?.worktreeMode??a.worktreeMode,trace:a.trace?Yf(a.trace,a.trace.currentSegmentIndex,!0):void 0});return E?{reason:E.reason,ruleId:E.ruleId,intent:E.intent}:null}});if(p)return{...p,segment:m};let g=Uf(e,l,o,f,s,a);if(g)return g;return Ka(d,o.shellGitContextState),null}function Uf(e,t,n,r,o,i){let s=VR(e,t,n,r??new Map,i);if(s)return s;return Zf(e,n,"after-consumer",i.environment.paths,i.budget),n.literalHeredocFiles.clear(),WR(e,t,n,i.environment.paths,i.budget),zR(e,n,i.environment.paths,i.budget),YR(e,n,o,i.environment,i.trace),null}var NR=new Set([">>","<>"]);function Zf(e,t,n,r,o){for(let s of e.redirections){if(!(n==="before-consumer"?LR(s):NR.has(s.operator)))continue;jf(s.target,t,r,o)}if(n!=="before-consumer"||!ge(e.words[0],"tee"))return;let i=Jf(e.words.slice(1));if(!i)return;for(let s of i.operands)jf(s,t,r,o)}function LR(e){if(e.operator===">"||e.operator===">|")return!0;return e.operator===">&"&&e.fd===void 0&&e.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test(e.target.text)}function jf(e,t,n,r){let o=e?.provenance==="literal"?wr(e.text,t.effectiveCwd,n,r):void 0;if(!o)return;t.literalHeredocFiles.delete(o)}function WR(e,t,n,r,o){if(t)return;let i=e.redirections.find((s)=>s.operator==="<<"||s.operator==="<<-")?.heredoc;if(!i)return;for(let s of GR(e,n.shellGitContextState.shellAssignments)){let a=wr(s,n.effectiveCwd,r,o);if(!a||!cd(a))continue;if(!n.literalHeredocFiles.has(a)&&n.literalHeredocFiles.size>=X.trackedHeredocFiles.cap)throw new N("trackedHeredocFiles");n.literalHeredocFiles.set(a,i.body)}}function GR(e,t){let n=pl($R(e.redirections)?.target,t),r=n===void 0?[]:[n];if(ge(e.words[0],"cat"))return BR(e.words)?r:[];if(!ge(e.words[0],"tee"))return[];let o=Jf(e.words.slice(1),t);if(!o||o.append||o.hasUnsupportedOptions)return[];let i=o.operands.map((s)=>pl(s,t));if(!i.every((s)=>s!==void 0))return[];return[...i,...r]}function pl(e,t){if(UR(e))return e.text;return(e&&pt(e,t))??void 0}function FR(e,t,n){if(t.size===0)return e;let r=(o)=>{let i=O(o,e,n);return[...t].some((s)=>s===i||s.startsWith(`${i}${Ke.sep}`))};return{realpath:(o)=>e.realpath(o)??(r(o)?O(o,e,n):null),entryKind:(o)=>{let i=e.entryKind(o);return i==="missing"&&r(o)?"present":i},isDirectory:(o)=>e.isDirectory(o)||r(o)}}function zR(e,t,n,r){if(t.shellGitContextState.bodyDepth>0||!ge(e.words[0],"mkdir"))return;let o=e.words.slice(1).map((c)=>pl(c,t.shellGitContextState.shellAssignments));if(!o.every((c)=>c!==void 0))return;let i=o.findIndex((c)=>c==="--"||c==="-"||!c.startsWith("-")),s=o.slice(0,i);if(i===-1||!s.every((c)=>/^(?:-[pv]+|--parents|--verbose)$/.test(c)))return;let a=s.some((c)=>c==="--parents"||/^-v*p/.test(c)),l=t.effectiveCwd;for(let c of o.slice(o[i]==="--"?i+1:i)){if(c.split(/[\\/]/).includes("..")||!Ke.isAbsolute(c)&&!l)continue;let u=O(Ke.resolve(l??"",c),n,r);if(a?HR(u,n):n.isDirectory(Ke.dirname(u))&&Xf(u,n))t.createdDirectories.add(u)}}function HR(e,t){let n=Ke.parse(e).root,r=e.slice(n.length).split(/[\\/]+/).filter(Boolean),o=(s)=>Ke.join(n,...r.slice(0,s+1)),i=r.findIndex((s,a)=>!t.isDirectory(o(a)));return i===-1||Xf(o(i),t)}function Xf(e,t){try{return t.entryKind(e)==="missing"}catch{return!1}}function BR(e){let t=!1;for(let n of e.slice(1)){if(t||n.provenance!=="literal")return!1;if(n.text==="--"){t=!0;continue}if(!/^-u+$/.test(n.text))return!1}return!0}function $R(e){let t=e.findLast((n)=>(n.fd??([">",">|",">>",">&"].includes(n.operator)?1:0))===1);return t?.operator===">"||t?.operator===">|"?t:void 0}function Jf(e,t=new Map){let n=[],r=!0,o=!1,i=!1;for(let s of e){if(s.provenance!=="literal"&&pt(s,t)===null)return;if(r&&ge(s,"--")){r=!1;continue}if(r&&!s.quoted&&s.raw===s.text&&/^-[^-]/.test(s.text)){o||=s.text.slice(1).includes("a"),i||=Array.from(s.text.slice(1)).some((a)=>a!=="a"&&a!=="i");continue}if(r&&!s.quoted&&s.raw===s.text&&s.text.startsWith("--")){o||=s.text==="--append",i||=s.text!=="--append"&&s.text!=="--ignore-interrupts";continue}n.push(s)}return{operands:n,append:o,hasUnsupportedOptions:i}}function UR(e){if(!e||e.provenance!=="literal"||e.text.length===0)return!1;if(e.quoted||e.raw!==e.text)return!0;return!e.raw.startsWith("~")&&!/[{}]/.test(e.raw)}function ge(e,t){return e?.text===t&&e.raw===t&&e.provenance==="literal"&&!e.quoted}function yl(e){return e.quotedDelimiter||!/[$`\\]/.test(e.body)}function jR(e,t){let n=e.redirections.filter((l)=>l.operator==="<<"||l.operator==="<<-");if(n.length===0)return;if(n.length!==1)return hn;let r=n[0];if(!r?.heredoc)return hn;let o=/\$\(|`/.test(r.heredoc.body);if(!yl(r.heredoc)&&(!t||o))return AR;if(r.fd!==void 0&&r.fd!==0)return hn;if(e.redirections.some((l)=>l!==r&&["<","<<","<<-","<<<","<&","<>"].includes(l.operator)))return hn;let i=e.redirections.some((l)=>l!==r&&Vf(l.target));if(ge(e.words[0],"cat"))return i?hn:void 0;if(ge(e.words[0],"tee"))return i||e.words.slice(1).some(Vf)?hn:void 0;let s=e.words[0],a=e.words[1];if(ge(s,"git")&&(ge(a,"apply")||ge(a,"commit")))return;if(ge(s,"gh")&&(ge(a,"pr")||ge(a,"issue"))&&ge(e.words[2],"create"))return;return hn}function Vf(e){return e?.parts.some((t)=>t.provenance==="command-substitution"&&t.raw.startsWith(">("))??!1}function VR(e,t,n,r,o){if(!t)return null;let i=e.redirections.filter((c)=>c.operator==="<<"||c.operator==="<<-"),s=i.flatMap((c)=>c.heredoc?[c.heredoc.body]:[]);if(qR(e,i,n,r,o))return null;let a=KR(e,i,o);if(a!==void 0)return a?{reason:a.reason,segment:e.displayText,ruleId:a.id,intent:a.intent}:null;let l=gl(s.length===i.length?s.join(`
|
|
42
|
+
`):e.source,o);return l?{...l,segment:e.displayText}:null}function KR(e,t,n){let r=t.length===1?t[0]:void 0;if(!r?.heredoc||!yl(r.heredoc)||r.fd!==void 0&&r.fd!==0)return;let o=ge(e.words[0],"uv")&&ge(e.words[1],"run")?e.words.slice(2):e.words,i=o[0];if(i?.provenance!=="literal"||!Xe(i.text))return;let s=o.findIndex((m)=>ge(m,"-"));if(!o.slice(1,s===-1?void 0:s).every((m)=>m.provenance==="literal"&&m.text.startsWith("-")))return;let l=r.heredoc.body,c=me(n.policy,"interpreter.one-liner-paranoid",!!n.paranoidInterpreters);if(n.trace?.recordSegment({type:"interpreter",interpreter:i.text,codeArg:l,paranoidBlocked:c}),c){let m=T(v("interpreter.one-liner-paranoid",_r),n.policy);if(m)return m}if(!Ar(l,void 0,!n.strict))return null;let u=T(v("interpreter.dangerous-command",Ln),n.policy);if(!u)return null;return n.trace?.recordSegment({type:"dangerous-text",token:l,matched:!0,reason:u.reason}),u}function qR(e,t,n,r,o){let i=t.length===1?t[0]:void 0;if(!i?.heredoc||!yl(i.heredoc)||i.fd!==void 0&&i.fd!==0)return!1;let s=sn(e.words,o.environment,n.effectiveCwd,r),a=s.words.map(_),l=M(a[0]??"");if((s.envSplitValues?.length??0)>0||!Q.has(l)&&!Q.has(k(l)))return!1;return Pt(a)}function YR(e,t,n,r,o){let i=zf(e,t.effectiveCwd,r,t.shellGitContextState.shellAssignments,n);if(i===null)o?.recordSegment({type:"cwd-change",segment:e.words.map(_).join(" "),effectiveCwdNowUnknown:!0});if(i!==void 0)t.effectiveCwd=i}var ZR=/^[A-Za-z_][A-Za-z0-9_]*$/,XR=8;function JR(e,t){let n=e.words[1]?.text;if(e.dialect!=="posix"||e.words[0]?.text!=="for"||n===void 0||!ZR.test(n))return[t];let r=e.words.slice(3);if(!(e.words[2]?.text==="in"&&r.length>=1&&r.length<=XR&&r.every((i)=>i.provenance==="literal"&&!/[\s$`*?[{}~'"\\]/.test(i.text))))return t.shellGitContextState.shellAssignments.delete(n),[t];return r.map((i)=>{let s=Xn(t);return s.shellGitContextState.shellAssignments.set(n,i.text),s})}function Xn(e){return{effectiveCwd:e.effectiveCwd,shellGitContextState:wm(e.shellGitContextState),literalHeredocFiles:new Map(e.literalHeredocFiles),functionDefinitions:new Map(e.functionDefinitions),createdDirectories:new Set(e.createdDirectories)}}function Gi(e){let t=[];for(let n of e){if(!t.some((r)=>QR(r,n)))t.push(n);if(t.length>X.controlFlowStates.cap)throw new N("controlFlowStates")}return t}function QR(e,t){return e.effectiveCwd===t.effectiveCwd&&Zn(e.shellGitContextState.env,t.shellGitContextState.env)&&Zn(e.literalHeredocFiles,t.literalHeredocFiles)&&Zn(e.functionDefinitions,t.functionDefinitions)&&Zn(e.shellGitContextState.effectiveEnvAssignments,t.shellGitContextState.effectiveEnvAssignments)&&Zn(e.shellGitContextState.shellAssignments,t.shellGitContextState.shellAssignments)&&e.shellGitContextState.bodyDepth===t.shellGitContextState.bodyDepth&&Kf(e.shellGitContextState.bodyAssignments,t.shellGitContextState.bodyAssignments)&&Kf(e.createdDirectories,t.createdDirectories)}function Kf(e,t){return e.size===t.size&&[...e].every((n)=>t.has(n))}function Zn(e,t){if(e===t)return!0;if(!e||!t||e.size!==t.size)return!1;return[...e].every(([n,r])=>t.get(n)===r&&t.has(n))}function ew(e,t){let n=Cr(e);return n===void 0?void 0:t.get(n)}function tw(e,t){if(!t)return null;return{reason:t.reason,segment:e,ruleId:t.id,intent:t.intent}}function nw(e,t=e.effectiveCwd){let n=t===null;return{environment:e.environment,cwd:n?void 0:t??e.cwd,originalCwd:n?void 0:e.cwd,strict:e.strict,paranoid:e.paranoidRm,allowTmpdirVar:e.allowTmpdirVar,protectedGitMetadata:e.protectedGitMetadata,policy:e.policy,budget:e.budget}}function gl(e,t){let n=T($e(e),t.policy),r=t.trace?.currentSegmentIndex??t.trace?.allocateSegment(),o={type:"dangerous-text",token:e,matched:!!n,reason:n?.reason};if(t.trace?.recordSegment(o,r),!n&&/^(?:cd|pushd)\s/.test(e))t.trace?.recordSegment({type:"cwd-change",segment:e,effectiveCwdNowUnknown:!0},r);return n?{reason:n.reason,segment:e,ruleId:n.id,intent:n.intent}:null}function qf(e,t){let n={type:"strict-unparseable",rawCommand:e,reason:Hn},r=t.trace?.currentSegmentIndex;if(r===void 0)t.trace?.recordGlobal(n);if(r!==void 0)t.trace?.recordSegment(n)}var rw=new Set(["derivedTokens","trackedHeredocFiles","controlFlowStates","wrapperPeelIterations","derivedCommandShape"]);function Qf(e,t,n,r){let o=hl(e,0,{...t,...Tu(t),budget:t.budget??ue(),factStore:r},n);if(!o)return null;return{kind:"deny",reason:o.reason,intent:o.intent??"manual_only",...o.ruleId?{ruleId:o.ruleId}:{},evidence:{command:e,segment:o.segment}}}function ep(e,t,n){try{return{decision:e()}}catch(r){let o=ow(r,t,n);if(!o)throw r;return o}}function ow(e,t,n){if(!(e instanceof N)||!rw.has(e.kind))return null;let r=X[e.kind];if(n?.currentSegmentIndex!==void 0)n.recordSegment({type:"error",message:r.reason});if(n?.currentSegmentIndex===void 0)n?.recordGlobal({type:"error",message:r.reason});return{decision:{kind:"deny",reason:r.reason,intent:"stop_and_explain",evidence:{command:t,segment:t}},errorCode:r.errorCode}}var iw=new Set(["src/entries/bin.ts","src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js","dist/bin/hook.js"]),bl=new Set(["cc-safety-net","ccsn"]),sw=new Set(["bunx","npx","pnpx"]),aw=new Set(["pnpm","yarn"]),lw=new Set(["npm","pnpm","yarn"]),cw=new Set(["bun","node"]);function Bi(e,t,n={}){if(bl.has(e))return 0;if(sw.has(e)){if(n.broad)return Cl(t);let o=t[0]==="-y"||t[0]==="--yes"?1:0;return Hi(t[o])?o+1:null}let r=n.broad?t.findIndex((o)=>!o.startsWith("-")):0;if(r!==-1&&lw.has(e)&&n.broad&&t[r]==="exec"){let o=Cl(t.slice(r+1));return o===null?null:r+1+o}if(aw.has(e)){if(e==="yarn"&&!n.broad)return null;if(!n.broad)return t[0]==="dlx"&&Hi(t[1])?2:null;if(r===-1||t[r]!=="dlx")return null;let o=Cl(t.slice(r+1));return o===null?null:r+1+o}if(cw.has(e)){let o=n.broad&&r!==-1?r:0;if(tp(t[o]))return o+1;if(e==="bun"&&t[o]==="run"&&tp(t[o+1]))return o+2}return null}function Cl(e){let t=e.findIndex((r)=>Hi(r));if(t===-1)return null;let n=t;while(n<e.length){let r=e[n]??"";if(!r.startsWith("-")&&!Hi(r))break;n++}return n}function Hi(e){if(!e)return!1;let t=e.indexOf("@");if(t===-1)return bl.has(e);if(t===0)return!1;let n=e.slice(t+1);if(n===""||n.includes("/")||n.includes(":"))return!1;return bl.has(e.slice(0,t))}function tp(e){let t=e?.replaceAll("\\","/");return[...iw].some((n)=>t===n||t?.endsWith(`/${n}`))}var np="Only the user may apply a policy proposal, because it rewrites the configuration CC Safety Net enforces. Ask them to run `cc-safety-net policy apply <file>` themselves in a terminal; you can run `cc-safety-net policy check <file>` to show them what it would change.";function rp(e,t,n){let r=Pe(e,"input-candidate");if(!r)return null;let o=Gn(r.shell,e.invocation.context.executionCwd,t,n,{findSegmentTarget:(i)=>uw(i,t),isRedirectionTarget:()=>!1,findMalformedTarget:()=>null});return o?{target:o}:null}function uw(e,t){let n=Bt([...e],t),r=n.slice(1),o=Bi(k(n[0]??"").toLowerCase(),r,{broad:!0});if(o===null)return null;let i=r.slice(o).filter((s)=>s!=="-g"&&s!=="--global");return i[0]==="policy"&&i[1]==="apply"?n.join(" "):null}var Yr=require("node:path");var ap="This path contains the protected policy config and you must not modify or delete it.",dw=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function lp(e,t,n){let r=yw(e.invocation.context,t,n);if(e.invocation.route.kind==="patch")return op(e.paths,!1,e.invocation.context.executionCwd,r,t,n);let o=Pe(e,"input-candidate");if(e.invocation.route.kind==="command")return o?ip(o.shell,e.invocation.context.executionCwd,r,t,n):null;if(e.invocation.route.kind==="unknown"&&o){let i=ip(o.shell,e.invocation.context.executionCwd,r,t,n);if(i)return i}return op(e.paths,e.invocation.route.kind==="grep"||e.invocation.route.kind==="glob"||lo(e.invocation.toolName),e.invocation.context.executionCwd,r,t,n)}function op(e,t,n,r,o,i){if(t)return null;let s=e.find((a)=>Zr(a,n,r,o,i));return s?{target:s}:null}function ip(e,t,n,r,o){let i=Gn(e,t,r,o,{findSegmentTarget:(s,a)=>mw(s,a,n,r,o)?.target??null,isRedirectionTarget:(s,a)=>Zr(s,a.cwd,n,r,o),findMalformedTarget:(s)=>hw(s,t,n,r,o)?.target??null});return i?{target:i}:null}function mw(e,t,n,r,o){if(Mr(e))return null;let i=$t([...e],r),s=k(i[0]??"").toLowerCase(),a=i.slice(1);if(s==="rm"&&fw(a)){let l=pw(a).find((c)=>sp(Ae(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(s==="find"){if(Ei(i,1)||Fa(i,r)){let c=(Br(J(i))??J(["."])).find((u)=>{let m=Ae(u.text,t.variables);return Zr(m,t.cwd,n,r,o)||sp(m,t.cwd,n,r,o)})?.text;if(c)return{target:c}}}if(s==="mv"){let l=ci(a).sources.find((c)=>Cw(Ae(c,t.variables),t.cwd,n,r,o));if(l)return{target:l}}if(gw(i,s))return null;for(let l of[...e,...i])for(let c of cp(l))if(Zr(Ae(c,t.variables),t.cwd,n,r,o))return{target:c};return null}function fw(e){return e.some((t)=>t==="--recursive"||t.startsWith("-")&&!t.startsWith("--")&&/[rR]/.test(t.slice(1)))}function pw(e){let t=e.indexOf("--");if(t!==-1)return[...e.slice(0,t).filter((n)=>!n.startsWith("-")),...e.slice(t+1)];return e.filter((n)=>!n.startsWith("-"))}function gw(e,t){if(!dw.has(t))return!1;if(t!=="sed")return!0;return!e.slice(1).some((n)=>n.startsWith("-i")||n==="--in-place"||n.startsWith("--in-place="))}function hw(e,t,n,r,o){for(let i of e.split(/\s+/))for(let s of cp(i))if(Zr(s,t,n,r,o))return{target:s};return null}function cp(e){let t=e.trim().replace(/^['"]|['"]$/g,""),n=t.indexOf("=");return n===-1||n===t.length-1?[t]:[t,t.slice(n+1)]}function yw(e,t,n){let r=(a)=>Xr(he(a,e.executionCwd,t,n)),o=r(An(t)),i=[r(dr(e.executionCwd)),r(dr(e.configCwd))],s=new Set(i.map((a)=>Yr.dirname(a)));for(let a=Yr.dirname(o);;a=Yr.dirname(a))if(s.add(a),Yr.dirname(a)===a)break;return{files:new Set([o,...i]),directoriesAndAncestors:s}}function Zr(e,t,n,r,o){let i=Vl(e,t,r,o,(s)=>Xr(s)===So);return i!==null&&n.files.has(Xr(i))}function sp(e,t,n,r,o){return n.directoriesAndAncestors.has(Xr(he(e,t,r,o)))}function Cw(e,t,n,r,o){let i=Xr(he(e,t,r,o));return n.files.has(i)||n.directoriesAndAncestors.has(i)}function Xr(e){return process.platform==="win32"?e.toLowerCase():e}var Ee=require("node:path"),vp=require("node:url");var Ep="Access to a sensitive path is not allowed.",xp=new Set(["echo","printf"]),bw=new Set(["find"]),Sw=new Set(["!","do","elif","else","if","then","until","while"]),vw=new Set(["-exec","-execdir"]),Ew=new Set([";","+"]),xw=new Set(["-delete","-files0-from","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),Rw=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),Rp=new Set(["-d","--data","--data-ascii","--data-binary","--data-urlencode","-F","--form"]),ww=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),_w=new Set(["append","awk","base64","cat","chmod","chown","connect","copy","cp","database","dd","eval","exec","fetch","file","function","grep","head","include","load","move","mv","open","fopen","popen","read","readfile","remove","rename","require","rg","rm","sed","shell","source","spawn","strings","system","tail","tar","truncate","unlink","write","xxd","zip"]),wp=new Set(["-c","-e","-r","-E","--eval","--exec"]),Aw=new Map([["c",new Set(["bash","sh","zsh","dash","ksh","python"])],["e",new Set(["node","deno","bun","ruby","perl","rscript","osascript"])],["E",new Set(["perl"])],["r",new Set(["php"])]]),Pw=new Set(["grep","rg"]),Tw=new Set(["--search","-S","--title","-t","--body","-b","--jq","-q"]),kw=new Set(["commit","merge","notes","stash","tag"]),Iw=new Set(["-m","--message"]),Ow=new Set(["--grep"]),up=new Set(["jq","gojq","jaq"]),dp="f",mp="file",Mw="files",Dw=new Set(["e","f"]),Nw=new Set(["regexp","file"]),Lw=new Set(["e","f","A","B","C","m"]),Ww=new Set(["regexp","file","after-context","before-context","context","max-count"]),Sl="__CC_SAFETY_NET_PIPE_INPUT__",El=/[\w./~@+-]*[./~][\w./~@+-]*/g,Gw=/(?:^|[^\w])([rRbBuUfF]{1,2})$/,Fw=/^(?:`|%[qQwWiIxX]?[([{<|!/]|<<<?[~-]?['"]?[A-Za-z_])/,zw=/#\{|\$\{|\{\$|[$@][A-Za-z_]/,fp=/\b(?:subprocess\s*\.\s*(?:run|call|Popen|check_output|check_call|getoutput|getstatusoutput)|(?:[\w$]+\s*\.\s*)*(?:exec(?:File)?(?:Sync)?|spawn(?:File)?(?:Sync)?|system|popen|shell_exec|passthru|child_process|eval))\s*\(/g,pp=/\b(?:system|exec|spawn|popen)\s*$/,Hw=/\b(?:eval|exec)\s*\(/g,Bw=/\b(?:eval|exec)\s*$/,$w=new Map([["bash",new Set(["-O"])],["sh",new Set(["-O"])],["zsh",new Set(["-o"])],["dash",new Set(["-o"])],["ksh",new Set(["-o"])],["python",new Set(["-W","-X"])],["node",new Set(["-r","--require","--loader","--import","--input-type"])]]);function gp(e,t,n,r,o,i){for(let s of e){let a=s.target;if(z_(a,s.cwd,t?.denyPaths??[],n,r,o))return{target:a,ruleId:"secret.deny-path"};if(i&&!i.has(a))continue;let l=G_(a,s.cwd,t,r,o);if(l){let c=i!==void 0&&!l.startsWith("secret.home.")&&!l.startsWith("secret.cli.");if(c&&r.paths.isDirectory(Op(a,s.cwd,r,o)))continue;if(c&&s.isRedirectionWriteTarget===!0&&!a.includes("$")&&!Rl(a,s.cwd,r,o))continue;if(c&&/\s/.test(a)&&!a.includes("$")&&!/^(?:[~./]|[A-Za-z]:[\\/])/.test(a)&&!Rl(a,s.cwd,r,o))continue;if(!l.startsWith("secret.cli.")&&H_(a,s.cwd,t?.allowPaths??[],n,r,o))continue;return{target:a,ruleId:l}}}return null}function _p(e,t,n,r,o={}){let i=hp(e,n,r),s=gp(i,t,e.invocation.context.configCwd,n,r);if(s===null||s.ruleId==="secret.deny-path"||o.strict!==!1)return s;let a=gp(i,t,e.invocation.context.configCwd,n,r,new Set(hp(e,n,r,{skipMetadataOnlySegments:!0,inlineLiteralsPresumedData:!0}).map((l)=>l.target)));return a?.ruleId!=="secret.deny-path"&&Uw(e,n)?null:a}function Uw(e,t){let n=Pe(e,"input-candidate")??Pe(e,"declared-command");if(!n)return!1;if(n.program.nodes.some((s)=>s.kind==="command"&&s.nested.length>0))return!1;let r=[];for(let s of li(n.shell)){if(s.kind==="operator"&&s.boundary)return!1;if(s.kind==="redirection")return!1;if(s.kind==="operator")continue;r.push(_t(s.text,t))}let o=Mt(r);if(o.length===0)return!1;let i=lt(o[0]??"").toLowerCase();if(e.invocation.route.kind==="unknown")return n.program.dialect==="powershell"&&(i==="ls"||i==="stat");return wl(i,o.slice(1))}function wl(e,t){if(e==="ls"||e==="stat")return!0;if(e==="test")return t.length===2&&(t[0]==="-e"||t[0]==="-f");if(e==="[")return t.length===3&&(t[0]==="-e"||t[0]==="-f")&&t[2]==="]";if(e==="git")return t[0]==="check-ignore";if(e!=="find")return!1;return!t.some((n)=>xw.has(n))}function hp(e,t,n,r={}){let o=e.invocation.context.executionCwd,i=e.invocation.route.kind;if(i!=="command"&&i!=="unknown")return e.paths.map((a)=>({target:a,cwd:o}));let s=Pe(e,"input-candidate");return[...s?Jn(s.shell,e.store,r,t,o,n,jw(s)):[],...i==="unknown"?e.paths.map((a)=>({target:a,cwd:o})):[]]}function jw(e){return e.program.dialect==="powershell"}function Jn(e,t,n,r,o,i,s=!1){if(e.status==="structural-limit")throw new nt;if(e.status==="unclosed-quote")return[];if(e.status==="invalid")throw Error("Unable to parse command for secret protection");let a=[...e.assignmentFallbacks.map((c)=>({target:c,cwd:o})),...v_(_t(e.source,r),t,n,r,o,i)],l=(c)=>_t(n_(c,s),r);return ai(e,o,r,i,{word:l,segment:(c,u,m,d,f)=>{if(c.length===0)return null;if(a.push(...Ui(c,t,n,r,u.cwd,i,f)),m!==null)a.push(...Kw(m,c,t,n,r,u.cwd,i));return null},redirection:(c,u)=>{if(c.body!==void 0&&c.consumer!==void 0)a.push(...Ap(c.consumer,[c.body],t,n,r,u.cwd,i,(m)=>qw(c.consumer??[],m,t,n,r,u.cwd,i)));if(c.targetOrder==="legacy-segment")return Ea;return a.push({target:l(c.target),cwd:u.cwd,...c.role==="file-write"?{isRedirectionWriteTarget:!0}:{}}),null}}),a}function _l(e,t,n,r,o,i){let s=t.getShellSyntax(e);if(s.status==="structural-limit")throw new nt;return s.status==="complete"?Jn(s,t,n,r,o,i):null}function Ui(e,t,n,r,o,i,s){let a=(g)=>({target:g,cwd:o});if(s?.size){let g=e.filter((h,y)=>!s.has(y));if(up.has(lt(Mt(g)[0]??"").toLowerCase()))return[...e.filter((h,y)=>s.has(y)).map(a),...Ui(g,t,n,r,o,i)]}let l=t_(e).map(a),c=Mt(e);if(c.length===0)return l;let u=c[0]??"",m=lt(u).toLowerCase(),d=c.slice(1),f=c.findIndex((g)=>!Sw.has(g));if(n.skipMetadataOnlySegments===!0&&f!==-1&&wl(lt(c[f]??"").toLowerCase(),c.slice(f+1)))return l;let p=Vw(u,m,d);if(p)return[...l,...p.map(a)];if(xp.has(m))return n.displayOperandsAreCapturedOutput===!0?[...l,...Pp(e).map(a)]:l;if(m==="eval")return[...l,..._l(d.join(" "),t,n,r,o,i)??d.map(a)];if(m==="export")return[...l,...d.flatMap((g)=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(g)?[g.slice(g.indexOf("=")+1)]:ht(m,g)).map(a)];if(m==="git")return[...l,...o_(d).map(a)];if(m==="gh")return[...l,...xl(m,d,Tw).map(a)];if(up.has(m))return[...l,...r_(d).map(a)];if(Pw.has(m))return[...l,...T_(d).map(a)];if(bw.has(m))return[...l,...l_(d,t,n,r,o,i).map(a)];if(Be.has(m))return[...l,...d.flatMap((g)=>ht("awk",g)).map(a),...d.flatMap((g)=>u_(g,t,n,r,o,i)),...d.flatMap(d_).map(a)];if(m==="curl")return[...l,...d.flatMap((g)=>ht(m,g)).map(a),...i_(d).map(a)];if(Dr(m)){let g=Or.has(m)?Ne([m,...d]):null;if(g!==null&&g.command!==null&&g.commandIndex!==null){let h=t.getShellSyntax(g.command);if(h.status==="structural-limit")throw new nt;if(h.status==="complete")return[...l,...Jn(h,t,n,r,o,i),...d.slice(g.commandIndex).filter((y)=>!y.startsWith("-")).map(a)]}return[...l,...c_(m,d,t,n,r,o,i)]}return[...l,...d.flatMap((g)=>ht(m,g)).map(a)]}function Vw(e,t,n){let r=Bi(t,n);if(r===null||n[r]!=="explain")return null;let o=[e,...n.slice(0,r)],i=n.slice(r+1);for(let s=0;s<i.length;s++){let a=i[s];if(a==="--json"||a==="--help"||a==="-h")continue;if(a==="--cwd"){let l=i[s+1];if(l&&!l.startsWith("--"))o.push(l);s++;continue}return o}return o}function Kw(e,t,n,r,o,i,s){if(Jw(t,n,r,o,i,s)){let a=Mt(e),l=wl(lt(a[0]??"").toLowerCase(),a.slice(1))?a.slice(1).filter((c)=>!c.startsWith("-")):[];return[...Pp(e),...l].map((c)=>({target:c,cwd:i}))}return Ap(t,Yw(e),n,r,o,i,s,()=>[])}function qw(e,t,n,r,o,i,s){let a=Mt(e);if(!Dr(lt(a[0]??"").toLowerCase()))return[];return _l(t,n,r,o,i,s)??[{target:t,cwd:i}]}function Ap(e,t,n,r,o,i,s,a){let l=Qw(e);if(l===null)return t.flatMap(a);return t.flatMap((c)=>Or.has(l)?Jn(n.getShellSyntax(c),n,r,o,i,s):$i(l,c,n,r,o,i,s))}function Pp(e){let t=Mt(e);if(t.length===0)return[];let n=lt(t[0]??"").toLowerCase();if(!xp.has(n))return[];let r=t[t[1]==="--"?2:1];if(n==="printf"&&r!==void 0&&!r.startsWith("-")&&!r.replaceAll("%%","").includes("%"))return[Al(r.replaceAll("%%","%"))];return t.slice(1)}function Yw(e){let t=Mt(e);if(t.length===0)return[];let n=lt(t[0]??"").toLowerCase(),r=t.slice(1);if(n==="echo"){let o=r.findIndex((i)=>!/^-[neE]+$/.test(i));return[(o===-1?[]:r.slice(o)).join(" ")]}if(n==="printf")return Zw(r);return[]}function Zw(e){let t=e[0];if(t===void 0)return[];let n=(t.match(/%%|%[bqs]/g)??[]).filter((o)=>o!=="%%").length;if(n===0||e.length===1)return[Al(t)];let r=e.slice(1);return Array.from({length:Math.ceil(r.length/n)},(o,i)=>Xw(t,r.slice(i*n,(i+1)*n)))}function Xw(e,t){let n=0;return Al(e.replace(/%%|%[bqs]/g,(r)=>{if(r==="%%")return"%";let o=t[n]??"";return n++,o}))}function Al(e){return e.replace(/\\n/g,`
|
|
43
|
+
`).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function Jw(e,t,n,r,o,i){let s=Mt(e);if(s.length===0||lt(s[0]??"").toLowerCase()!=="xargs")return!1;let a=pn(s),l=s.slice(a.childStart);if(l.length===0)return!1;if(a.replacementToken==="")return!1;let c=a.replacementToken,u=c===null?[...l,Sl]:l.map((m)=>m.split(c).join(Sl));return Ui(u,t,n,r,o,i).some((m)=>m.target.includes(Sl))}function Qw(e){let t=Mt(e);if(t.length===0)return null;let n=lt(t[0]??"").toLowerCase();if(!Dr(n))return null;return e_(n,t.slice(1))?n:null}function e_(e,t){let n=Pl(e);for(let r=0;r<t.length;r++){let o=t[r];if(o===void 0)break;if(wp.has(o)||Tp(e,o)||/^--(?:eval|exec)=/.test(o))return!1;if(o==="-")return!0;if(o.startsWith("-")){if(n==="python"&&o==="-m")return!1;if($w.get(n)?.has(o))r++;continue}return!1}return!0}function Pl(e){return/^python\d/.test(e)?"python":e}function t_(e){let t=[];for(let n of e){if(Ip(n))continue;let r=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(n);if(r===null)break;if(r[1]!==void 0&&r[1]!=="")t.push(r[1])}return t}var yp=/^(?:\$\{home\}|\$\{env:(?:userprofile|home)\}|~)(?=[\\/])/i;function n_(e,t){if(!t||!yp.test(e))return e;return`~${e.replace(yp,"").replace(/\\/g,"/")}`}function ht(e,t){if(t==="--")return[];let n=[],r=t.indexOf("=");if(r>0&&r<t.length-1)n.push(t.slice(r+1));if(t.startsWith("-"))return n;if(e==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(t))return n;if(e==="zip"&&/\.zip$/i.test(t))return n;return n.push(t),n}function r_(e){let t=-1,n=!1;for(let r=0;r<e.length;r++){let o=e[r]??"";if(!n&&o==="--"){n=!0;continue}if(n||!/^-(?:[A-Za-z]|-)/.test(o)){if(t===-1)t=r;continue}if(/^--(?:arg|argjson|argfile|rawfile|slurpfile)$/.test(o)){r+=2;continue}if(o==="--indent"||o==="-L"){r++;continue}if(o.startsWith("-L"))continue;if(/^-[srjcCMaSRnbehV]+$/.test(o)||/^--(?:slurp|raw-output0?|join-output|compact-output|color-output|monochrome-output|ascii-output|unbuffered|sort-keys|raw-input|null-input|binary|tab|seq|stream|stream-errors|exit-status|args|jsonargs|help|version|build-configuration)$/.test(o))continue;return e.flatMap((i)=>ht("jq",i))}return e.flatMap((r,o)=>o===t?[]:ht("jq",r))}function o_(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n]??"";if(r==="--"||!r.startsWith("-"))return[...t,...kw.has(r)?xl("git",e.slice(n).map((i)=>/^-[aeinopqsv]+m$/.test(i)?"-m":i),Iw):xl("git",e.slice(n),Ow)];if(t.push(...ht("git",r)),!De.has(r))continue;let o=e[n+1];if(o===void 0)break;t.push(...r==="-c"&&o.includes("=")?[o.slice(o.indexOf("=")+1)]:ht("git",o)),n++}return t}function xl(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o]??"";if(i==="--")return[...r,...t.slice(o).flatMap((s)=>ht(e,s))];if(n.has(i)){o++;continue}if(i.includes("=")&&n.has(i.slice(0,i.indexOf("="))))continue;r.push(...ht(e,i))}return r}function i_(e){return e.flatMap((t,n)=>{let r=a_(t);if(r!==null)return Cp(r.flag,r.value);let o=s_(e[n-1]);return o===null?[]:Cp(o,t)})}function Cp(e,t){if(e==="-F"||e==="--form"){let n=t.indexOf("="),r=n===-1?t:t.slice(n+1);if(!r.startsWith("@")&&!r.startsWith("<"))return[];return vl(r.slice(1).split(";")[0]??"")}if(e==="--data-urlencode"){let n=t.indexOf("@"),r=t.indexOf("=");if(n===-1||r!==-1&&r<n)return[];return vl(t.slice(n+1))}return t.startsWith("@")?vl(t.slice(1)):[]}function s_(e){if(e===void 0)return null;if(Rp.has(e))return e;return/^-[A-Za-z]+[dF]$/.test(e)?`-${e.slice(-1)}`:null}function a_(e){let t=e.slice(0,2);if(e.length>2&&(t==="-d"||t==="-F"))return{flag:t,value:e.slice(2)};let n=e.indexOf("=");if(n===-1)return null;let r=e.slice(0,n);return Rp.has(r)?{flag:r,value:e.slice(n+1)}:null}function vl(e){return e===""||e==="-"?[]:[e]}function l_(e,t,n,r,o,i){let s=e.findIndex((l)=>l.startsWith("-")||l==="("||l==="!"||l===";"),a=[...e.slice(0,s===-1?e.length:s),...e.flatMap((l,c)=>l==="-files0-from"&&e[c+1]!==void 0?[e[c+1]??""]:[])];for(let l=0;l<e.length;l++){if(!vw.has(e[l]??""))continue;let c=e.slice(l+1),u=c.findIndex((f)=>Ew.has(f)),m=u===-1?c:c.slice(0,u),d=Ui(m,t,n,r,o,i).map((f)=>f.target);if(a.push(...d.filter((f)=>f!=="{}")),!d.includes("{}"))continue;a.push(...e.slice(0,l).flatMap((f,p,g)=>{if(!Rw.has(f))return[];let h=g[p+1];return h===void 0?[]:[h,h.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return a}function c_(e,t,n,r,o,i,s){let a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c===void 0)break;if(wp.has(c)||Tp(e,c)){let m=t[l+1];if(m!==void 0)a.push(...$i(e,m,n,r,o,i,s)),l++;continue}let u=/^--(?:eval|exec)=(.*)$/.exec(c);if(u!==null&&u[1]!==void 0){a.push(...$i(e,u[1],n,r,o,i,s));continue}if(!c.startsWith("-"))a.push({target:c,cwd:i})}return a}function Tp(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<=2)return!1;return Aw.get(t[t.length-1]??"")?.has(Pl(e))??!1}function u_(e,t,n,r,o,i){if(!e.includes("system"))return[];return Na(e)?.commands.flatMap((s)=>Jn(t.getShellSyntax(s),t,n,r,o,i))??[]}function d_(e){return Array.from(e.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((t)=>t[1]).filter((t)=>t!==void 0&&t!=="")}function m_(e){let t=Array.from(e.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((n)=>n[2]).filter((n)=>n!==void 0&&n!=="");return[...t,...t.flatMap(Tl),...e.match(El)??[]]}function $i(e,t,n,r,o,i,s){let a=(g)=>({target:g,cwd:i}),l=p_(t,f_(e));if(l.kind==="unmaskable")return m_(t).map(a);let c=l.masked.match(fp)!==null||l.literals.some((g)=>pp.test(l.masked.slice(0,g.start))),u=l.masked.match(Hw)!==null||l.literals.some((g)=>Bw.test(l.masked.slice(0,g.start))),m=r.inlineLiteralsPresumedData===!0&&!Or.has(e),d=m&&!(C_(l.masked)||c||u)?[]:l.literals,f=m?Array.from(l.masked.matchAll(fp),(g)=>{let h=g.index+g[0].length;return{start:h,end:ga(l.masked,h)}}):[],p=!m||f.some((g)=>ha(l.masked,g.start))?l.literals:l.literals.filter((g)=>pp.test(l.masked.slice(0,g.start))||f.some((h)=>g.start>=h.start&&g.start<h.end));return[...d.map((g)=>g.text).filter((g)=>g!=="").map(a),...d.flatMap((g)=>Tl(g.text)).map(a),...m?[]:l.literals.flatMap((g)=>g.text.match(El)??[]).map(a),...c?p.flatMap((g)=>_l(g.text,n,r,o,i,s)??[a(g.text)]):[],...u?l.literals.flatMap((g)=>$i(e,g.text.replace(/\\(.)/g,(h,y)=>y==="n"?`
|
|
44
|
+
`:y),n,r,o,i,s)):[],...(l.masked.match(El)??[]).map(a)]}function f_(e){let t=Pl(e);if(t==="python")return"python";if(t==="osascript")return"opaque";return t==="node"||t==="bun"||t==="deno"?"javascript":"simple"}function p_(e,t){if(t==="opaque")return{kind:"unmaskable"};let n=e.split(""),r=[];for(let o=0;o<e.length;o++){let i=e[o]??"";if(t==="simple"&&(i==="`"||i==="%"||i==="<")){if(Fw.test(e.slice(o)))return{kind:"unmaskable"}}let s=i==="'"||i==='"'||t==="javascript"&&i==="`"?i:null;if(s===null)continue;if(s==="`"&&y_(e,o))return{kind:"unmaskable"};let a=t==="python"?g_(e,o):"",l=t==="python"&&e.startsWith(s.repeat(3),o)?s.repeat(3):s,c=o+l.length,u=h_(e,c,l);if(u===null)return{kind:"unmaskable"};let m=e.slice(c,u);if(/[fF]/.test(a)&&m.includes("{"))return{kind:"unmaskable"};if(t==="simple"&&s==='"'&&zw.test(m))return{kind:"unmaskable"};r.push({start:c,text:m});for(let d=o;d<u+l.length;d++)n[d]=" ";o=u+l.length-1}return{kind:"masked",masked:n.join(""),literals:r}}function g_(e,t){return Gw.exec(e.slice(Math.max(0,t-3),t))?.[1]??""}function h_(e,t,n){let r=n==="`",o=r||n.length===3;for(let i=t;i<e.length;i++){let s=e[i];if(s==="\\"){i++;continue}if(r&&s==="$"&&e[i+1]==="{")return null;if(!o&&(s===`
|
|
45
|
+
`||s==="\r"))return null;if(e.startsWith(n,i))return i}return null}function y_(e,t){for(let n=t-1;n>=0;n--){let r=e[n];if(!r||/\s/.test(r))continue;return/[\w$\])]/.test(r)}return!1}function C_(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(ww.has(n.toLowerCase()))return!0;let o=n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((i)=>i.toLowerCase());if(!o.some((i)=>_w.has(i)))continue;if(o.length>1)return!0;if(b_(e,r)===".")return!0;if(S_(e,r+n.length)==="(")return!0}return!1}function b_(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return e[n];return}function S_(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return e[n];return}function v_(e,t,n,r,o,i){return __(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...Jn(a,t,{...n,displayOperandsAreCapturedOutput:!0},r,o,i),...E_(a,r)?x_(a,r).map((l)=>({target:l,cwd:o})):[]]})}function E_(e,t){let n=li(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||lt(_t(o.text,t)).toLowerCase()!=="base64")continue;for(let i=r+1;i<n.length;i++){let s=n[i];if(s?.kind==="operator")break;if(s?.kind!=="word")continue;let a=_t(s.text,t);if(a==="--decode"||!a.startsWith("--")&&a.startsWith("-")&&/[dD]/.test(a))return!0}}return!1}function x_(e,t){return li(e).flatMap((n)=>n.kind==="word"?[_t(n.text,t)]:n.kind==="redirection"&&n.target?[_t(n.target,t)]:[]).flatMap(Tl)}function Tl(e){let t=w_(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||R_(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function R_(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function w_(e){if(e.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(e))return null;if(/=/.test(e.replace(/=+$/g,"")))return null;let t=e.replace(/=+$/g,"");if(t.length%4===1)return null;return`${t.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-t.length%4)%4)}`}function __(e){let t=[],n={inSingle:!1,inDouble:!1,escaped:!1};for(let r=0;r<e.length;r++){let o=e[r];if(!o)break;if(mr(o,n))continue;if(kp(e,r,n)){let i=A_(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=P_(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function A_(e,t){let n={inSingle:!1,inDouble:!1,escaped:!1},r=1;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i)break;if(mr(i,n))continue;if(kp(e,o,n)){r++,o++;continue}if(!n.inSingle&&!n.inDouble&&i===")"){if(r--,r===0)return{body:e.slice(t+1,o),endIndex:o}}}return null}function P_(e,t){let n=!1;for(let r=t+1;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="`")return{body:e.slice(t+1,r),endIndex:r}}return null}function kp(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function T_(e){let t=[],n=[],r=!1,o=!1,i=!1;for(let l=0;l<e.length;l++){let c=e[l];if(c===void 0)break;if(!i&&c==="--"){i=!0;continue}if(i){n.push(c);continue}let u=/^--([^=]+)(?:=(.*))?$/.exec(c);if(u!==null){let m=u[1]??"",d=u[2];if(m===Mw)o=!0;if(Nw.has(m))r=!0;if(d!==void 0){if(m===mp)t.push(d);continue}if(Ww.has(m)){let f=e[l+1];if(m===mp&&f!==void 0)t.push(f);l++}continue}if(c.startsWith("-")&&c.length>1){let m=c.slice(1),d="",f="";for(let g=0;g<m.length;g++){let h=m[g]??"";if(Dw.has(h))r=!0;if(Lw.has(h)){d=h,f=m.slice(g+1);break}}if(d==="")continue;if(f.length>0){if(d===dp)t.push(f);continue}let p=e[l+1];if(d===dp&&p!==void 0)t.push(p);l++;continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function Mt(e){let t=e.findIndex((n)=>!Ip(n)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(n));return t===-1?[]:e.slice(t)}function Ip(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var k_=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),I_=".env.",O_=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),M_=[".env.example.",".env.sample."];function D_(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function N_(e){return e.length>0&&!/\s/.test(e)}function Rl(e,t,n,r){let o=Op(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function Op(e,t,n,r){try{return eo(e,t,n,r)}catch(o){if(o instanceof N)throw o;return""}}var L_=new Set(["node_modules","__pycache__"]),W_=[["vendor","bundle"],["vendor","cache"]];function G_(e,t,n,r,o){if(D_(e))return null;let i=gt(e,t,r,o);if(!i)return null;let s=U(i.split("/").pop()??""),a=U(i),l=()=>N_(s)||Rl(e,t,r,o);if(O_.has(s)||M_.some((d)=>s.startsWith(d)))return null;let c=U(U_(e,t,r,o));for(let d of Is){let f=`~/${d.suffixParts.join("/")}`;if((Sp(a,f)||Sp(c,f))&&Ot(d.id,n))return d.id}let u=F_(i,t,n,r,o);if(u)return u;if(k_.has(s))return null;for(let d of ks)if(s===d.basename&&Ot(d.id,n))return d.id;if(s.startsWith(I_)&&Ot(_o.id,n)&&l())return _o.id;for(let d of Os)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){let f=s.slice(d.prefix.length)[0];if((f==="-"||f==="_")&&Ot(d.id,n)&&l())return d.id}for(let d of Ms)if(s.length>d.prefix.length&&s.startsWith(d.prefix)){if(s.slice(d.prefix.length)===d.suffix&&Ot(d.id,n))return d.id}if(B_(a))return null;if(!s.includes(".")&&pr.pattern.test(s)&&Ot(pr.id,n))return pr.id;let m=$_(s,n);if(m)return m;return null}function F_(e,t,n,r,o){return Ao.find((i)=>{if(!Ot(i.id,n))return!1;switch(i.id){case"secret.cli.claude-code":return z(e,Y(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),[".credentials.json"]);case"secret.cli.claude-code.config":{let s=U(e).split("/");return z(e,Y(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),["settings.json","settings.local.json"])||Qr(e,"~/.claude.json",t,r,o)||s.at(-1)==="settings.local.json"&&s.at(-2)===".claude"||s.at(-1)===".mcp.json"}case"secret.cli.antigravity":return z(e,gt("~/.gemini/config",t,r,o),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let s=Y(r.env.get("CODEX_HOME"),"~/.codex",t,r,o);return z(e,s,["auth.json",".credentials.json"])||Jr(e,s,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let s=Y(r.env.get("CODEX_HOME"),"~/.codex",t,r,o),a=U(e).split("/").at(-1)??"";return z(e,s,["config.toml"])||a.endsWith(".config.toml")&&z(e,s,[a])}case"secret.cli.gemini":return z(e,Ce(Y(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let s=U(e).split("/"),a=r.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),l=r.env.get("ProgramData")?[Ce(Y(r.env.get("ProgramData"),"",t,r,o),"gemini-cli")]:[];return z(e,Ce(Y(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["settings.json","google_accounts.json"])||s.at(-1)==="settings.json"&&s.at(-2)===".gemini"||(a?.trim()?Qr(e,a,t,r,o):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...l].some((c)=>z(e,gt(c,t,r,o),["settings.json"]))}case"secret.cli.copilot-cli":{let s=Y(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o);return z(e,s,["config.json"])||Jr(e,s,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return z(e,Y(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o),["mcp-config.json"]);case"secret.cli.kimi-code":{let s=Y(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),a=Y(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o);return z(e,s,["server.token"])||Jr(e,s,["credentials"])||Jr(e,a,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let s=["config.toml","mcp.json"],a=U(e).split("/");return a.at(-1)==="mcp.json"&&a.at(-2)===".kimi-code"||z(e,Y(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),s)||z(e,Y(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o),[...s,"config.json","config.json.bak"])}case"secret.cli.opencode":{let s=Ce(Y(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"opencode"),a=U(e).split("/").at(-1)??"",l=r.env.get("OPENCODE_DB")?.trim(),c=l&&l!==":memory:"?[l,`${l}-wal`,`${l}-shm`]:[];return z(e,s,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(a)&&z(e,s,[a])||c.some((u)=>Qr(e,u,t,r,o))}case"secret.cli.opencode.config":{let s=Ce(Y(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"opencode"),a=r.env.get("ProgramData")?[Ce(Y(r.env.get("ProgramData"),"",t,r,o),"opencode")]:[],l=["opencode.json","opencode.jsonc"],c=r.env.get("OPENCODE_CONFIG");return l.includes(U(e).split("/").at(-1)??"")||z(e,s,["config.json"])||(c?.trim()?Qr(e,c,t,r,o):!1)||["/Library/Application Support/opencode","/etc/opencode",...a].some((u)=>z(e,gt(u,t,r,o),l))}case"secret.cli.pi":return z(e,Y(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["auth.json"]);case"secret.cli.pi.config":return z(e,Y(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["models.json"]);case"secret.cli.amp":{let s=gt("~",t,r,o);return[Ce(Y(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"amp"),Ce(s,".local","share","amp")].some((l)=>z(e,l,["secrets.json"]))||Jr(e,Ce(s,".amp"),["oauth"])}case"secret.cli.amp.config":{let s=["settings.json","settings.jsonc"],a=[Ce(Y(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"amp"),Ce(gt("~",t,r,o),".config","amp")],l=U(e).split("/"),c=r.env.get("AMP_SETTINGS_FILE");return a.some((u)=>z(e,u,s))||l.at(-2)===".amp"&&s.includes(l.at(-1)??"")||(c?.trim()?Qr(e,c,t,r,o):!1)}case"secret.cli.cursor":{let s=Ce(Y(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"cursor"),a=Ce(Y(r.env.get("CURSOR_DATA_DIR"),"~/.cursor",t,r,o),"projects");return z(e,gt("~/.cursor",t,r,o),["auth.json"])||z(e,s,["auth.json"])||U(e).split("/").at(-1)==="mcp-auth.json"&&Cn(U(e),U(a))}case"secret.cli.cursor.config":{let s=U(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".cursor"}case"secret.cli.grok-build":return z(e,Y(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let s=U(e).split("/");return s.at(-1)==="config.toml"&&s.at(-2)===".grok"||z(e,Y(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["config.toml","managed_config.toml","requirements.toml"])||z(e,gt("/etc/grok",t,r,o),["managed_config.toml","requirements.toml"])}default:return!1}})?.id??null}var bp=new WeakMap;function Y(e,t,n,r,o){let i=bp.get(o)??new Map;bp.set(o,i);let s=`${n}\x00${e??""}\x00${t}`,a=i.get(s);if(a!==void 0)return a;let l=gt(e?.trim()?e:t,n,r,o);return i.set(s,l),l}function z(e,t,n){return n.some((r)=>Mp(e,Ce(t,r)))}function Jr(e,t,n){return n.some((r)=>Cn(U(e),U(Ce(t,r))))}function Qr(e,t,n,r,o){return Mp(e,gt(t,n,r,o))}function Mp(e,t){return U(e)===U(t)}function Ce(e,...t){return at([e,...t].filter(Boolean).join("/"))}function z_(e,t,n,r,o,i){if(n.length===0)return!1;let s=U(eo(e,t,o,i));return n.some((a)=>Cn(s,U(eo(a,r,o,i))))}function H_(e,t,n,r,o,i){if(n.length===0)return!1;let s=U(eo(e,t,o,i));if(!s)return!1;let a=o.env.get("HOME")??o.home,l=a?at(O(Me(a),o.paths,i)):"",c=U(l),u=o.env.get("CC_SAFETY_NET_HOME"),m=U(u?at(O(Ee.resolve(Me(u)),o.paths,i)):l&&at(O(`${l}/.cc-safety-net`,o.paths,i)));if(m&&Cn(s,m))return!1;return n.some((d)=>{let f=Ws(d);if(f&&Ee.posix.basename(s)!==U(f.name))return!1;let p=U(eo(f?.root??d,r,o,i));if(!p)return!1;if(c&&(c===p||c.startsWith(p.endsWith("/")?p:`${p}/`)))return!1;return Cn(s,p)&&!(f&&s===p)})}function B_(e){let t=e.split("/");return t.some((n)=>L_.has(n))||W_.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function $_(e,t){let n=e.lastIndexOf("."),r=n>0&&n<e.length-1?e.slice(n+1):"";if(r==="")return null;for(let o of Ds)if(r===o.extension&&Ot(o.id,t))return o.id;for(let o of Ns)if(o.pattern.test(r)&&Ot(o.id,t))return o.id;return null}function U(e){return e.toLowerCase()}function Ot(e,t){return!t?.disabledRules?.includes(e)}function gt(e,t,n,r){let{home:o,normalized:i}=kl(e,n,r);if(!i)return"";if(!o)return i;let s=Il(i,o),a=Ee.isAbsolute(s)?s:at(Ee.resolve(t,s)),l=at(O(a,n.paths,r));if(!Cn(l,o)){if(Ee.isAbsolute(s))return l;return l===a?i:l}let c=l.slice(o.length);return c?`~${c}`:"~"}function Sp(e,t){return e===t||e.startsWith(`${t}/`)}function U_(e,t,n,r){let{home:o,normalized:i}=kl(e,n,r);if(!i||!o)return"";let s=Il(i,o),a=Ee.posix.normalize(Ee.isAbsolute(s)?s:at(Ee.resolve(t,s))),l=at(Me(n.env.get("HOME")??n.home)),c=(d)=>process.platform==="win32"?d.toLowerCase():d,u=[o,l].find((d)=>d!==""&&Cn(c(a),c(d)));if(u===void 0)return"";let m=a.slice(u.length);return m?`~${m}`:"~"}function eo(e,t,n,r){let{home:o,normalized:i}=kl(e,n,r);if(!i)return"";let s=o?Il(i,o):i;return at(O(Ee.isAbsolute(s)?s:Ee.resolve(t,s),n.paths,r))}function kl(e,t,n){let r=t.env.get("HOME")??t.home,o=r?at(O(Me(r),t.paths,n)):"",i=at(Me(j_(_t(e,t))));return{home:o,normalized:i}}function j_(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return vp.fileURLToPath(e)}catch{return e}}function Il(e,t){if(e==="~")return t;if(e.startsWith("~/"))return Ce(t,e.slice(2));return e}function V_(e){if(process.platform==="win32")return!0;return Ee.win32.parse(e).root.length>1}function at(e){let t=e.trim(),n=(t.includes("\\")&&V_(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function Cn(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function lt(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class bn extends Error{stage;evaluation;name="GuardEvaluationError";constructor(e,t,n){super(`CC Safety Net ${e} dependency failed`,{cause:n});this.stage=e;this.evaluation=t}}var K_={findPolicyMutation:lp,findGitMetadataMutation:Ld,resolveGitMetadata:Y_,loadPolicySnapshot:Pu,findSensitiveTarget:_p,analyzeCommand:Qf,getModes:ms},q_=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/;function Dp(e,t){let n={...K_,...t.dependencies},r=J_(e),o=to(e)?e.command:r,i=Xt("policy-protection",o,()=>Nr(e)),s=Pe(i,"input-candidate"),a=Pe(i,"declared-command");if(to(e)&&e.command?.trim()&&a?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:ut,intent:"stop_and_explain",evidence:{command:e.command,segment:e.command}}};if(s?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:Jd,intent:"stop_and_explain"}};let l=ue(),c=Xt("policy-protection",o,()=>n.resolveGitMetadata([e.context.executionCwd,e.context.configCwd],t.environment)),u=Xt("policy-protection",o,()=>n.findPolicyMutation(i,t.environment,l));if(u){let E=o??u.target;return{stage:"policy-protection",decision:{kind:"deny",reason:ap,intent:"hard_stop",evidence:{command:E,segment:u.target}}}}let m=Xt("policy-protection",o,()=>rp(i,t.environment,l));if(m){let E=o??m.target;return{stage:"policy-protection",decision:{kind:"deny",reason:np,intent:"hard_stop",evidence:{command:E,segment:m.target}}}}let d=Xt("policy-protection",o,()=>n.findGitMetadataMutation(i,c,t.environment,l));if(d){let E=o??d.target;return{stage:"policy-protection",decision:{kind:"deny",reason:je,intent:"hard_stop",evidence:{command:E,segment:d.target}}}}let f=Xt("config-load",o,()=>n.loadPolicySnapshot(t.environment,{...t.policyOptions,cwd:e.context.configCwd})),p=f.policy,g=n.getModes(p,t.environment.env),h={level:g.effectiveLevel,...Z_(f)},y=p.secretProtection.enabled===!1?null:Xt("secret-protection",o,()=>n.findSensitiveTarget(i,p.secretProtection,t.environment,l,{strict:to(e)||s?.program.dialect==="powershell"?g.strict:void 0}));if(y){let E=o??y.target;return{stage:"secret-protection",...h,decision:{kind:"deny",reason:Ep,intent:"hard_stop",ruleId:y.ruleId,evidence:{command:E,segment:y.target}}}}if(!to(e))return{stage:"non-command",...h,decision:{kind:"allow"}};if(!e.command||e.command.trim()==="")return{...Ol("command-validation",o),...h};let S=Xt("command-analysis",o,()=>ep(()=>n.analyzeCommand(e.command,{cwd:e.context.executionCwd,shell:e.route.shell,policySnapshot:f,environment:t.environment,protectedGitMetadata:c,effectiveCapabilities:g.capabilities,strict:g.strict,paranoidRm:g.paranoidRm,paranoidInterpreters:g.paranoidInterpreters,worktreeMode:g.worktreeMode,budget:l,...t.trace?{trace:t.trace}:{}},X_(i),i.store),e.command,t.trace));if(S.decision){let E=!g.strict&&(S.decision.ruleId==="raw-text.dangerous-command"||S.decision.reason===Fr&&!q_.test(S.decision.evidence?.segment??"")&&$e(e.command)===null);return{stage:"command-analysis",...h,..."errorCode"in S?{errorCode:S.errorCode}:{},decision:E?{...S.decision,unverifiedByStandardMode:!0}:S.decision}}return{stage:"command-analysis",...h,decision:{kind:"allow"}}}function Y_(e,t){let n=[...new Set(e.filter((r)=>typeof r==="string"&&r!==""))].flatMap((r)=>t.gitMetadata(r)??[]);if(n.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(n.flatMap((r)=>r.entries))]),markerFiles:Object.freeze([...new Set(n.flatMap((r)=>r.markerFiles))]),directories:Object.freeze([...new Set(n.flatMap((r)=>r.directories))]),hooksDirectories:Object.freeze([...new Set(n.flatMap((r)=>r.hooksDirectories))])})}function Z_(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function X_(e){return Pe(e,"declared-command")?.program}function J_(e){try{return Nt(e.input)}catch(t){let n=to(e)?e.command:void 0;throw new bn("policy-protection",Ol("policy-protection",t instanceof be?void 0:n,t),t)}}function Xt(e,t,n){try{return n()}catch(r){throw new bn(e,Ol(e,r instanceof be?void 0:t,r),r)}}function Ol(e,t,n){let r=n instanceof N||n instanceof nt;return{stage:e,decision:{kind:"deny",reason:r?Ji:or,intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function to(e){return e.route.kind==="command"}var Vi=require("node:fs"),er=require("node:path");var le=require("node:fs"),Qn=require("node:path");function Np(e,t={}){return Lo(An(e,t),e.home).policy.audit.retention_days}var Dl=86400000,Q_=".last-prune",eA=/^\d{4}-\d{2}$/,tA=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Lp=(e)=>Math.floor(e/Dl);function Gp(e,t,n=()=>new Date){try{let r=n().getTime();if(!le.statSync(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=Qn.join(t,Q_),i=le.statSync(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&Lp(i)===Lp(r))return;let s=r-Np(e)*Dl,a=new Date(r).toISOString().slice(0,7);for(let l of Ml(t)){if(l.isDirectory()){nA(Qn.join(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))rA(Qn.join(t,l.name),s)}le.writeFileSync(o,"",{mode:384}),le.utimesSync(o,r/1000,r/1000)}catch{}}function nA(e,t,n){for(let r of Ml(e)){if(!r.isDirectory()||!eA.test(r.name))continue;let o=Qn.join(e,r.name);for(let i of Ml(o)){if(!i.isFile())continue;let s=tA.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+Dl;if(!Number.isFinite(a)||a>=t)continue;Fp(Qn.join(o,i.name))}if(r.name!==n)Wp(o)}Wp(e)}function rA(e,t){try{let n=le.lstatSync(e);if(n.mtimeMs>=t)return;let r=le.readFileSync(e,"utf-8").split(`
|
|
46
|
+
`).filter((o)=>o.trim()).map(oA);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(le.lstatSync(e).mtimeMs!==n.mtimeMs)return;Fp(e)}catch{}}function oA(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function Ml(e){try{return le.readdirSync(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Fp(e){try{le.unlinkSync(e)}catch{}}function Wp(e){try{le.rmdirSync(e)}catch{}}var iA="2.4.13",sA=1e4,aA=2000,lA=256,cA=32768;function uA(e){let t=e.trim();if(!t)return null;let n=t.replace(/[^A-Za-z0-9_.-]+/g,"_");if(n=n.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!n||n==="."||n==="..")return null;return n}function dA(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function Nl(e,t,n,r,o,i,s={}){let a=uA(t);if(!a)return;let l=fA(e);if(!l)return;try{let c=(s.now??(()=>new Date))().toISOString(),u=ji(Ct(n),s.failureStage?Number.POSITIVE_INFINITY:sA),m=ji(Ct(r),aA),d=s.toolName?ji(Ct(s.toolName),lA):void 0,f=i===null?void 0:ji(Ct(i),cA),p=er.join(l,dA(f?.value??null),c.slice(0,7));Vi.mkdirSync(p,{recursive:!0,mode:448});let g=er.join(p,`${c.slice(0,10)}-${a}.jsonl`),h={ts:c,id:(s.createId??ps)(),v:iA,sessionId:a,decision:s.decision??"deny",agent:s.agent,shape:s.shape,level:s.level,configFallback:s.configFallback,toolName:d?.value,command:u.value,segment:m.value,...u.truncated||m.truncated||d?.truncated||f?.truncated?{truncated:!0}:{},reason:o,ruleId:s.ruleId,intent:s.intent,failureStage:s.failureStage,errorCode:s.errorCode,cwd:f?.value??null};Vi.appendFileSync(g,`${JSON.stringify(h)}
|
|
47
|
+
`,{encoding:"utf-8",mode:384}),Gp(e,l,s.now)}catch{}}function ji(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function mA(e){let t=e.env.get("CC_SAFETY_NET_AUDIT_HOME");if(e.env.get("NODE_ENV")==="test"&&!t)return null;let n=t||e.home;return n&&er.isAbsolute(n)?n:null}function fA(e){let t=mA(e);return t?er.join(t,".cc-safety-net","logs"):null}function Hp(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=zp(e);return{decision:"allow",command:a,segment:a,reason:"allowed",cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{}}}let i=t.decision.evidence,s=i?.command??(r?zp(e):"");return{decision:"deny",command:s,segment:i?.segment??s,reason:t.decision.reason,cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{},ruleId:t.decision.ruleId,intent:t.decision.intent,failureStage:o?.stage,errorCode:o?.errorCode}}function zp(e){return"command"in e?e.command??"":""}function Bp(e,t,n,r){if(!t)return;let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Nl(e,o,t.command,t.segment,t.reason,t.cwd,{decision:t.decision,agent:r.agent,shape:r.shape,level:t.level,configFallback:t.configFallback,toolName:t.toolName,ruleId:t.ruleId,intent:t.intent,failureStage:t.failureStage,errorCode:t.errorCode})}function $p(e,t,n,r){let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;Nl(e,o,t.command??"",t.segment??t.command??"",t.reason,r.cwd??null,{decision:"deny",agent:r.agent,shape:r.shape,toolName:r.toolName??t.toolName,ruleId:t.ruleId,intent:t.intent})}function jp(e,t,n){try{let r=Dp(t,{environment:e,...n.guard});return Up(e,t,r,n),r}catch(r){if(!(r instanceof bn))throw r;throw Up(e,t,r.evaluation,n,!(r.cause instanceof be),{stage:r.stage,errorCode:pA(r.cause)}),r}}function Up(e,t,n,r,o=!0,i){Bp(e,Hp(t,n,r.guard?.auditAllowed??!1,o,i),r.audit.getSessionId,{agent:r.audit.agent,shape:r.audit.shape})}function pA(e){if(e instanceof N)return X[e.kind].errorCode;if(e instanceof be)return"tool-input-limit";if(e instanceof nt)return"structural-shell-syntax-limit";return"unexpected-error"}var Sn=(e,t,n,r,o)=>uc(e.cwd,t,n,r,o.paths,process.cwd()),Ki=(e,t,n)=>(r,o,i,s,a)=>{let l=Sn(r,o,i,s,a);if(!l)return null;let c=r.tool_input;if(!t.has(i)||!c||!Object.hasOwn(c,e))return l;let u=c[e];if(n?.emptyMeansSessionCwd&&u==="")return l;if(typeof u!=="string"||u.trim()==="")return Se(s,o,i),null;let m=n?.allowOutsideSessionCwd?as(u,l.configCwd,a.paths):St(u,[l.configCwd],a.paths);if(m)return{configCwd:l.configCwd,executionCwd:m};return He(s,o,i,{directory:"requested",problem:Et(u,l.configCwd,a.paths),cwd:u}),null};function gA(e,t){console.log(JSON.stringify(e(Hl(t))))}async function hA(e){let t;try{t=(await cc(process.stdin)).trim()}catch{e({reason:"Failed to parse hook input JSON."});return}if(!t){e({reason:"Missing hook input JSON."});return}return fo(t,e,"Failed to parse hook input JSON.")}async function yA(e){let t=vc(),n=await hA(e.outputDeny);if(n===void 0)return;if(!n||typeof n!=="object"||Array.isArray(n)){Se(e.outputDeny);return}if(!e.isSupported(n))return;let r=e.getAgent?.(n,t)??e.agent,o=e.agent===r?void 0:e.agent,i=vA(n),s=(p,g)=>{$p(t,p,()=>e.getSessionId(n),{agent:r,shape:o,toolName:g,cwd:p.cwd??i}),e.outputDeny(p)},a=e.getToolName(n);if(typeof a!=="string"||a.trim()===""){Se((p)=>s(p),SA(n));return}let l=a,c=(p)=>s(p,l),u;try{u=e.getToolInput(n,l,c,t)}catch(p){if(!(p instanceof be))throw p;Se(c,void 0,l);return}if(!u.ok)return;let m=e.getContext(n,u.input,l,c,t);if(!m)return;let d;try{d=Nt(u.input)}catch(p){if(!(p instanceof be))throw p;Se(c,void 0,l);return}let f=cr(l,u.input,u.route,m,d??null);try{let p=jp(t,f,{guard:{auditAllowed:Ec(t.env),dependencies:e.guardDependencies},audit:{agent:r,shape:o,getSessionId:()=>e.getSessionId(n)}}),g=Qi(p,{includeEvidence:!0,toolName:p.stage==="command-analysis"?void 0:l});if(g){if(g.unverifiedByStandardMode&&e.outputAsk&&e.canPromptPerson?.(n)){e.outputAsk(g);return}e.outputDeny(g);return}e.outputAllow?.()}catch(p){if(!(p instanceof bn))throw p;CA(p,t.env);let g=Qi(p.evaluation,{includeEvidence:!0,toolName:p.evaluation.stage==="command-analysis"?void 0:l});if(g)e.outputDeny(g);return}}function CA(e,t){if(!en(ae.debug,t))return;console.error(`CC Safety Net debug: ${bA(e.stage)}: ${$l(e.cause)}`)}function bA(e){if(e==="policy-protection")return"hook policy protection failed";if(e==="config-load")return"hook config loading failed";if(e==="secret-protection")return"hook secret protection failed";return"hook analysis failed"}function SA(e){if(!e||typeof e!=="object"||Array.isArray(e))return;if(Object.hasOwn(e,"tool_input"))return e.tool_input;let t=e.toolCall;if(t&&typeof t==="object"&&!Array.isArray(t))return t.args;return}function vA(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let t=e.cwd;if(typeof t==="string")return t;let n=e.toolCall;if(!n||typeof n!=="object"||Array.isArray(n))return null;let r=n.args;if(!r||typeof r!=="object"||Array.isArray(r))return null;let o=r.Cwd;return typeof o==="string"?o:null}async function Ie(e){let t=(s)=>gA(e.createDenyOutput,s),n=e.createAskOutput,r=n?(s)=>console.log(JSON.stringify(n(Bl(s)))):void 0,o=e.createAllowOutput,i=o?()=>console.log(JSON.stringify(o())):void 0;try{await yA({...e,outputDeny:t,outputAsk:r,outputAllow:i})}catch(s){console.error("CC Safety Net error:",s),t(xn())}}var EA=new Map([["run_command","auto"]]),xA=new Set(["absolutepath","directorypath","file_path","filepath","path","searchdirectory","searchpath","target_file","targetfile"]);function Vp(e){return oe(e,EA)}async function Kp(){await Ie({agent:"antigravity-cli",createDenyOutput:(e)=>({decision:"deny",reason:e}),isSupported:()=>!0,getToolName:(e)=>e.toolCall?.name,getToolInput:(e,t)=>({ok:!0,input:AA(e.toolCall?.args,t),route:Vp(t)}),getContext:RA,getSessionId:(e)=>e.conversationId})}function RA(e,t,n,r,o){let i=_A(e);if(!i[0])return Jt(r,t,n),null;let s=i.flatMap((u)=>{let m=vt([u],o.paths);return m?[m]:[]});if(!s[0])return Jt(r,t,n,{directory:"session",problem:"unusable",cwd:i[0]}),null;if(n!=="run_command"){let u;try{u=wA(t,n,s,o.paths)}catch(m){if(m instanceof be)return Jt(r,void 0,n),null;if(!(m instanceof N))throw m;return Jt(r,t,n),null}if(!u)return Jt(r,t,n),null;return{configCwd:u,executionCwd:u}}let a=e.toolCall?.args;if(!a||!Object.hasOwn(a,"Cwd"))return{configCwd:s[0],executionCwd:s[0]};let l=a.Cwd;if(typeof l!=="string"||l.trim()==="")return Jt(r,t,n),null;let c=St(l,s,o.paths);if(c){let u=qp(c,s);if(!u)return Jt(r,t,n),null;return{configCwd:u,executionCwd:c}}return Jt(r,t,n,{directory:"requested",problem:Et(l,s[0],o.paths),cwd:l}),null}function wA(e,t,n,r){let o=Vp(t),i=[...co(e,xA),...o.kind==="patch"?uo(e):[]].filter(Ll.isAbsolute),s=ue(),a=new Set(i.flatMap((l)=>{let c=qp(O(l,r,s),n);return c?[c]:[]}));if(a.size>1)return null;return[...a][0]??n[0]??null}function qp(e,t){return t.filter((n)=>ar(e,n)).reduce((n,r)=>r.length>n.length?r:n,"")||null}function Jt(e,t,n,r){let o=t&&typeof t==="object"?t.command:void 0,i={command:typeof o==="string"?o:void 0,toolName:n};e(r?io(r,i):xn(i))}function _A(e){if(e.workspacePaths===void 0)return[process.cwd()];return Array.isArray(e.workspacePaths)?e.workspacePaths.filter((t)=>typeof t==="string"&&t.trim()!==""):[]}function AA(e,t){if(!e)return;if(t!=="run_command")return e;return{...e,command:typeof e.CommandLine==="string"&&e.CommandLine!==""?e.CommandLine:void 0}}var qi=[{id:"antigravity-cli",displayName:"Antigravity CLI",doctorOrder:3,runtime:{order:1,flags:["-ac","--agy-cli"],description:"Run as Antigravity CLI PreToolUse hook",legacyTopLevelFlags:[]},install:{order:2,flag:"--agy-cli",artifactKind:"hook config",probeCommand:["agy","--version"]}},{id:"claude-code",displayName:"Claude Code",doctorOrder:1,runtime:{order:2,displayName:"Coding CLI",flags:["-cc","--coding-cli"],legacyFlags:["--claude-code"],description:"Run as Coding CLI PreToolUse hook",legacyTopLevelFlags:["-cc","--claude-code"]},install:{order:3,flag:"--claude-code",artifactKind:"plugin",probeCommand:["claude","--version"]}},{id:"codex",displayName:"Codex",doctorOrder:4,runtime:{order:3,flags:["-cx","--codex"],description:"Run as a Codex PreToolUse hook",legacyTopLevelFlags:[]},install:{order:4,flag:"--codex",artifactKind:"plugin",probeCommand:["codex","--version"]}},{id:"copilot-cli",displayName:"GitHub Copilot CLI",doctorOrder:7,runtime:{order:6,flags:["-cp","--copilot-cli"],description:"Run as GitHub Copilot CLI PreToolUse hook",legacyTopLevelFlags:["-cp","--copilot-cli"]},install:{order:7,flag:"--copilot-cli",artifactKind:"plugin",probeCommand:["copilot","--binary-version"]}},{id:"gemini-cli",displayName:"Gemini CLI",doctorOrder:6,runtime:{order:5,flags:["-gc","--gemini-cli"],description:"Run as Gemini CLI BeforeTool hook",legacyTopLevelFlags:["-gc","--gemini-cli"]},install:{order:6,flag:"--gemini-cli",artifactKind:"extension",probeCommand:["gemini","--version"]}},{id:"grok-build",displayName:"Grok Build",doctorOrder:8,runtime:{order:7,flags:["-gb","--grok-build"],description:"Run as Grok Build PreToolUse hook",legacyTopLevelFlags:[]},install:{order:8,flag:"--grok-build",artifactKind:"hook config",probeCommand:["grok","--version"]}},{id:"hermes-agent",displayName:"Hermes Agent",doctorOrder:9,runtime:{order:8,flags:["-ha","--hermes-agent"],description:"Run as Hermes Agent pre_tool_call hook",legacyTopLevelFlags:[]},install:{order:9,flag:"--hermes-agent",artifactKind:"plugin",probeCommand:["hermes","--version"]}},{id:"kimi-code",displayName:"Kimi Code",doctorOrder:10,runtime:{order:9,flags:["-kc","--kimi-code"],description:"Run as Kimi Code PreToolUse hook",legacyTopLevelFlags:[]},install:{order:10,flag:"--kimi-code",artifactKind:"hook config",probeCommand:["kimi","--version"]}},{id:"openclaw",displayName:"OpenClaw",doctorOrder:11,install:{order:11,flag:"--openclaw",artifactKind:"plugin",probeCommand:["openclaw","--version"]}},{id:"opencode",displayName:"OpenCode",doctorOrder:12,install:{order:12,flag:"--opencode",artifactKind:"plugin",probeCommand:["opencode","--version"]}},{id:"pi",displayName:"Pi",doctorOrder:13,install:{order:13,flag:"--pi",artifactKind:"package",probeCommand:["pi","--version"]}},{id:"cursor",displayName:"Cursor",doctorOrder:5,runtime:{order:4,flags:["-cu","--cursor"],description:"Run as Cursor preToolUse hook",legacyTopLevelFlags:[]},install:{order:5,flag:"--cursor",artifactKind:"hook config",probeCommand:["cursor","--version"]}},{id:"amp",displayName:"Amp Code",doctorOrder:2,install:{order:1,flag:"--amp",artifactKind:"plugin",probeCommand:["amp","--version"]}}],AL=qi.slice().sort((e,t)=>e.doctorOrder-t.doctorOrder).map((e)=>e.id),Yp=qi.filter((e)=>("runtime"in e)).slice().sort((e,t)=>e.runtime.order-t.runtime.order).map((e)=>({id:e.id,displayName:"displayName"in e.runtime?e.runtime.displayName:e.displayName,flags:e.runtime.flags,legacyFlags:"legacyFlags"in e.runtime?e.runtime.legacyFlags:[],description:e.runtime.description,legacyTopLevelFlags:e.runtime.legacyTopLevelFlags})),PL=qi.slice().sort((e,t)=>e.install.order-t.install.order).map((e)=>({id:e.id,...e.install})).map(({order:e,...t})=>t),TL=Object.fromEntries(qi.map((e)=>[e.id,e.displayName]));var vn=require("node:path");function Zp(e,t){if(e!==void 0&&e!==null&&typeof e!=="string")return"unknown";if(typeof e==="string"&&!vn.isAbsolute(e))return"unknown";try{let n=ue(),r=typeof e==="string"&&e?O(e,t.paths,n):void 0,o=t.home,i=[["codex",t.env.get("CODEX_HOME")||vn.join(o,".codex")],["copilot-cli",t.env.get("COPILOT_HOME")||vn.join(o,".copilot")],["claude-code",t.env.get("CLAUDE_CONFIG_DIR")||vn.join(o,".claude")]],s=r?i.flatMap(([a,l])=>{if(!vn.isAbsolute(l))return[];return ar(r,O(l,t.paths,n))?[a]:[]}):[];if(s.length===1)return s[0]??"unknown";if(s.length>1)return"unknown"}catch{return"unknown"}if(t.env.get("COPILOT_CLI")==="1")return"copilot-cli";if(t.env.get("CLAUDECODE")==="1"||Boolean(t.env.get("CLAUDE_CODE_ENTRYPOINT")))return"claude-code";return"unknown"}var Yi="PreToolUse",Xp="BeforeTool",Jp="pre_tool_call";async function tr(e){await Ie({agent:e.agent,...e.getAgent?{getAgent:e.getAgent}:{},createDenyOutput:(t)=>({hookSpecificOutput:{hookEventName:Yi,permissionDecision:"deny",permissionDecisionReason:t}}),...e.canPromptPerson?{canPromptPerson:e.canPromptPerson,createAskOutput:(t)=>({hookSpecificOutput:{hookEventName:Yi,permissionDecision:"ask",permissionDecisionReason:t}})}:{},isSupported:(t)=>t.hook_event_name===Yi,getToolName:(t)=>t.tool_name,getToolInput:(t,n,r,o)=>({ok:!0,input:t.tool_input,route:e.getToolRoute(n,t.tool_input,o)}),getContext:e.getContext??Sn,getSessionId:(t)=>t.session_id})}var PA=new Map([["Bash","posix"],["PowerShell","powershell"],["Monitor","posix"]]);function TA(e,t,n){if(e==="Bash"&&n.env.get("COPILOT_CLI")==="1")return{kind:"command",shell:"auto"};return e==="Monitor"&&t?.command===void 0?oe(e,new Map):oe(e,PA)}async function Qp(){await tr({agent:"claude-code",getAgent:(e,t)=>Zp(e.transcript_path,t),canPromptPerson:(e)=>["default","acceptEdits","plan"].includes(e.permission_mode??""),getToolRoute:TA})}var kA=new Map([["Bash","auto"]]);async function eg(){await tr({agent:"codex",getToolRoute:(e)=>oe(e,kA)})}var IA=new Map([["bash","auto"],["Bash","auto"],["powershell","powershell"],["PowerShell","powershell"]]);function OA(e){return oe(e,IA)}async function tg(){await Ie({agent:"copilot-cli",createDenyOutput:(e)=>({permissionDecision:"deny",permissionDecisionReason:e}),isSupported:()=>!0,getToolName:(e)=>e.toolName,getToolInput:(e,t,n)=>{let r=OA(t);if(typeof e.toolArgs==="object"&&e.toolArgs!==null)return{ok:!0,input:e.toolArgs,route:r};if(typeof e.toolArgs!=="string")return n({reason:"Failed to parse toolArgs JSON."}),{ok:!1};if(r.kind==="patch"&&e.toolArgs.trimStart().startsWith("*** Begin Patch"))return{ok:!0,input:e.toolArgs,route:r};let i=fo(e.toolArgs,n,"Failed to parse toolArgs JSON.");if(i===void 0)return{ok:!1};return{ok:!0,input:i,route:r}},getContext:Sn,getSessionId:(e)=>typeof e.sessionId==="string"&&e.sessionId.trim()?e.sessionId:void 0})}var MA=new Map([["Shell","auto"]]);function DA(e){return oe(e,MA)}async function ng(){await Ie({agent:"cursor",createDenyOutput:(e)=>({permission:"deny",user_message:e,agent_message:e}),createAllowOutput:()=>({permission:"allow"}),isSupported:()=>!0,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:DA(t)}),getContext:NA,getSessionId:(e)=>e.conversation_id})}function NA(e,t,n,r,o){let i=LA(e);if(!i[0])return Se(r,t,n),null;let s=i.flatMap((m)=>{let d=vt([m],o.paths);return d?[d]:[]});if(!s[0])return He(r,t,n,{directory:"session",problem:"unusable",cwd:i[0]}),null;let a=WA(e.cwd),l=St(a,s,o.paths);if(!l)return He(r,t,n,{directory:"session",problem:Et(a,s[0],o.paths),cwd:a}),null;if(t===null||typeof t!=="object"||Array.isArray(t))return{configCwd:l,executionCwd:l};if(!Object.hasOwn(t,"working_directory"))return{configCwd:l,executionCwd:l};let c=t.working_directory;if(typeof c!=="string"||c.trim()==="")return Se(r,t,n),null;let u=St(c,s,o.paths);if(!u)return He(r,t,n,{directory:"requested",problem:Et(c,s[0],o.paths),cwd:c}),null;return{configCwd:l,executionCwd:u}}function LA(e){if(e.workspace_roots===void 0)return typeof e.cwd==="string"&&e.cwd.trim()!==""?[e.cwd]:[];if(!Array.isArray(e.workspace_roots))return[];return e.workspace_roots.filter((t)=>typeof t==="string"&&t.trim()!=="")}function WA(e){return typeof e==="string"&&e.trim()!==""?e:"."}var rg=new Map([["run_shell_command","auto"]]);function GA(e){return oe(e,rg)}async function og(){await Ie({agent:"gemini-cli",createDenyOutput:(e)=>({decision:"deny",reason:e,systemMessage:e}),isSupported:(e)=>e.hook_event_name===Xp,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:GA(t)}),getContext:Ki("dir_path",rg,{emptyMeansSessionCwd:!0,allowOutsideSessionCwd:!0}),getSessionId:(e)=>e.session_id})}var FA=new Map([["run_terminal_command","auto"],["monitor","auto"]]);function zA(e){return oe(e,FA)}async function ig(){await Ie({agent:"grok-build",createDenyOutput:(e)=>({decision:"deny",reason:e}),createAllowOutput:()=>({decision:"allow"}),isSupported:()=>!0,getToolName:(e)=>e.toolName,getToolInput:(e,t,n)=>{if(e.toolInputTruncated===!0)return Se(n,e.toolInput,t),{ok:!1};return{ok:!0,input:e.toolInput,route:zA(t)}},getContext:HA,getSessionId:(e)=>e.sessionId})}function HA(e,t,n,r,o){let i=BA(e);if(!i)return Se(r,t,n),null;let s=vt([i],o.paths);if(!s)return He(r,t,n,{directory:"session",problem:"unusable",cwd:i}),null;let a=$A(e.cwd),l=St(a,[s],o.paths);if(!l)return He(r,t,n,{directory:"session",problem:Et(a,s,o.paths),cwd:a}),null;return{configCwd:l,executionCwd:l}}function BA(e){let t=e.workspaceRoot===void 0?e.cwd:e.workspaceRoot;return typeof t==="string"&&t.trim()!==""?t:void 0}function $A(e){return typeof e==="string"&&e.trim()!==""?e:"."}var sg=require("node:path");var UA=new Map([["terminal","posix"]]);async function ag(){await Ie({agent:"hermes-agent",createDenyOutput:(e)=>({action:"block",message:e}),isSupported:(e)=>e.hook_event_name===Jp,getToolName:(e)=>e.tool_name,getToolInput:(e,t)=>({ok:!0,input:e.tool_input,route:oe(t,UA)}),getContext:jA,getSessionId:(e)=>e.session_id})}function jA(e,t,n,r,o){let i=Sn(e,t,n,r,o);if(!i)return null;if(!t||typeof t!=="object"||Array.isArray(t))return i;if(!Object.hasOwn(t,"workdir"))return i;let s=t.workdir;if(typeof s!=="string"||s.trim()==="")return Se(r,t,n),null;let a=vt([sg.resolve(i.configCwd,s)],o.paths);if(!a)return He(r,t,n,{directory:"requested",problem:"unusable",cwd:s}),null;return{...i,executionCwd:a}}var lg=new Map([["Bash","posix"]]);function VA(e){return oe(e,lg)}async function cg(){await tr({agent:"kimi-code",getToolRoute:VA,getContext:Ki("cwd",lg)})}var KA={"antigravity-cli":Kp,"claude-code":Qp,codex:eg,"copilot-cli":tg,cursor:ng,"gemini-cli":og,"grok-build":ig,"hermes-agent":ag,"kimi-code":cg},Wl=Yp.map((e)=>({...e,run:KA[e.id]}));function ug(e){let t=oo({label:"hook",booleans:Object.fromEntries(Wl.map((r)=>[r.id,[...r.flags,...r.legacyFlags]]))},e);if(t.errors.length>0)return;let n=Wl.filter((r)=>t.flags[r.id]);return n.length===1?n[0]:void 0}function dg(e){return Wl.find((t)=>t.legacyTopLevelFlags.some((n)=>n===e))}async function qA(){let e=process.argv.slice(2),t=e[0],n=oo({label:"cc-safety-net",booleans:{version:["-V","--version"]},positionals:"list"},e);if(!n.help&&!n.flags.version){if(t?.toLowerCase()==="hook"){let i=ug(e.slice(1));if(i){await i.run();return}}let o=dg(t);if(o){await o.run();return}}let r=await import("../cli.js");await r.runCli(e)}qA().catch((e)=>{console.error("CC Safety Net error:",e),process.exit(1)});
|